-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDoiBoxModule.f90
3079 lines (2592 loc) · 133 KB
/
DoiBoxModule.f90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
! Note: Reservoirs are not really working at present, only periodic BCs are working
module DoiBoxModule
use MinHeapModule
use BoxLibRNGs ! Random number generation
implicit none
save
! Change for different reaction schemes and recompile:
!integer, parameter :: nSpecies = 3, nReactions = 7 ! BPM model
!integer, parameter :: nSpecies = 3, nReactions = 2 ! A<->B+C test in IRDME
!integer, parameter :: nSpecies = 2, nReactions = 2 ! A+B->B, 0->A equilibrium (from Radek Erban)
!integer, parameter :: nSpecies = 2, nReactions = 2 ! A+B->0, A+A->0, rate test in IRDME
!integer, parameter :: nSpecies = 3, nReactions = 4 ! 0->A, A->0, A+B->0, A+A->0, test if selection is uniform for each cell/particle/pair
integer, parameter :: nSpecies = 3, nReactions = 2 ! 0->A+B, C->A+B
!integer, parameter :: nSpecies = 1, nReactions = 2 ! A+A->A, 0->A
!--------------------------------------
! Supported reaction types as recorded in reactionTable and reactionType
!--------------------------------------
!
! 1, Birth: products are created at randomly-sampled positions:
! (1) 0 --> A (2) 0 --> A + B (3) 0 --> A + A
! For RDME, the products are placed uniformly inside the cell
! For IRDME, the products are placed within a reactive distance of each other:
! one of the particles is uniformly distributed inside the cell, and the other, if there exists one, is within a reactive sphere
! 2, Annihilation: no product is created:
! (1) A --> 0 (2) A + A --> 0 (3) A + B --> 0
! 3, Replacement: one particle gets replaced by one or two particles:
! (1) A --> B (2) A --> B + C
! The particle A is replaced by another species, and an extra particle, if required, is randomly placed
! For RDME, the second particle is placed uniformly inside the cell
! For IRDME, the second particle is placed within a reactive radius of the original A
! 4, Catalitic Birth: one particle remains unchanged in the reaction and creates a new particle, inverse of catalitic annihilation
! (1) A -> A + A (2) A -> A + B
! We simply create a new particle in this reaction near an existing one of species A
! For RDME, the new particle is created randomly inside the same cell.
! For IRDME, the new particle is created within a reactive sphere of the A.
! 5, Merge: one particle disappears and the species of the other particle changes:
! (1) A + A --> B (2) A + B --> C
! We randomly choose one of the reagents to disappear and let the other one be replaced by a new particle with
! the same species as the product
! 6, Catalitic Annihilation (and also Coagulation): one particle disappears when there is another particle nearby:
! (1) A + B --> A (2) A + A --> A
! For type (1), we keep the A where it is and make the B disappear
! For type (2), we randomly choose one of the two reagents to disappear and the other one remains unchanged.
! 7, Transform: the species of two particles change (randomly choose which one of the two becomes which):
! (1) A + A --> B + C (2) A + B --> C + D (3) A + A --> A + B (4) A + B --> A + A
! We randomly let one of the reagent be replaced by one of the product and the other reagent be replaced by the other product.
! 8, Catalyst: a particle changes species when another one is nearby: A + B --> A + C
! We keep the catylist A unchanged and turn the B into a C
integer, parameter :: nMaxDimensions = 3 ! Up to 3 dimensions
! Constants that require recompilation
!---------------------
! The way this works is that you comment one of these two lines out (just as above) -- *don't* change the actual lines
! If you want something different add a new line with a comment
integer, parameter :: dp=kind(0.0d0), sp=kind(0.0)
! The precision is now chosen in MinHeapModule.f90
!integer, parameter :: wp = dp ! Double precision
!integer, parameter :: wp = sp ! Single precision
! Choose dimensionality:
integer, parameter :: nDimensions = 2 ! 1D, 2D and 3D work but remember to change lines below also
!integer, dimension (0:nMaxDimensions), parameter :: neighborhoodSize = (/3, 1, 0, 0/) ! 1D
integer, dimension (0:nMaxDimensions), parameter :: neighborhoodSize = (/9, 1, 1, 0/) ! 2D
!integer, dimension (0:nMaxDimensions), parameter :: neighborhoodSize = (/27, 1, 1, 1/) ! 3D
! IMPORTANT: Turn off assertions and tracing/testing for getting optimized code!
!logical, parameter :: isAssertsOn =.true., printDebug=.true. ! Debug
!logical, parameter :: isAssertsOn =.true., printDebug=.false. ! Test but not print too much stuff (slow!)
logical, parameter :: isAssertsOn =.false., printDebug=.false. ! Optimized for production runs
! For testing the code we do fake reactions and just count to compute the rate in the absence of spatial correlations
! Tracing is used to confirm that each pair of overlapping particles is selected with the same probability
! IRDME_trace distinguishes two kinds of testing: full history trace and just counting:
!logical, parameter :: IRDME_test=.true., IRDME_trace=.true. ! Trace the number of times each pair is selected
!logical, parameter :: IRDME_test=.true., IRDME_trace=.false. ! Count number of reactions only
logical, parameter :: IRDME_test=.false., IRDME_trace=.false. ! For production runs after testing is complete
integer :: nMaxTestPairs = 1000000 ! How much space to allocate to keep a history of reacting pairs
integer :: MaxReactionsPerParticle = 10000 ! How many reactions are allowed for each particle in fake run
! Enumerators:
!---------------------
integer, parameter :: PERIODIC = 1, FREE = 0, RESERVOIR = -1 ! Types of boundaries. Only PERIODIC works at present
! Different types of chemical reactions:
integer, parameter :: R_NONE=0, R_BIRTH = 1, R_ANNIHILATION=2, R_REPLACEMENT = 3, &
R_CATA_BIRTH = 4, R_MERGE = 5, R_CATA_ANNIHILATION = 6, R_TRANSFORM = 7, R_CATALYST = 8
integer, parameter :: RDME = 0, IRDME = 1 ! Type of reaction scheme
! Constants
real (wp), parameter :: PI = 3.14159265358979_wp
! Derived types:
!----------------
type ParticleType
real (wp) :: position (nMaxDimensions) ! We keep here three positions even for 2D to simplify indexing
integer :: species = 0
end type ParticleType
type WallType ! Boundary condition for one side of the Doi box
integer :: wallType = PERIODIC ! What kind of wall this is
real (wp) :: number_density (1:nSpecies) = -1.0_wp ! For reservoirs, the target number density
end type WallType
type DoiBox
integer*8 :: nTimesteps = 0 ! More accurate to count integers than just elapsed time
real(wp) :: globalTime=0.0_wp ! Keep track of elapsed time
real(wp) :: elapsedTime=0.0_wp ! In IRDME, used to track elapsed time in each timestep
! BCs for this specific box (will be different from the global BCs below if running in parallel)
integer, dimension (2,nDimensions) :: boundaryType ! Type of boundary for each side of the Doi box
real (wp), dimension (2, nDimensions) :: boundaryLocation
! IRDME neighrboring cells
integer, allocatable :: neighboringCells (:,:)
! IRDME heap
type (MinHeap) :: heap
! Particle data
integer :: nMaxParticles ! Computed later
type (ParticleType), allocatable :: particle (:)
integer, allocatable, dimension(:) :: nextParticle, particlesSortedByCell
!integer, allocatable, dimension(:) :: previousParticle ! We no longer use a doubly-linked list, we use a singly-linked list
! Species data
integer, dimension(0:nSpecies) :: speciesSum
integer :: nParticles (0:nSpecies) = 0 ! Number of particles of each species
! Reaction cells:
integer, dimension (nMaxDimensions) :: lb, ub ! Lower and upper bounds for Doi collision cell arrays
integer, dimension (0:nMaxDimensions) :: extent ! Extent of grid in each dimension (0 for total number of cells)
integer, allocatable, dimension(:, :, :, :) :: speciesPointers ! Used in RDME for sorting in cells
integer, pointer, dimension(:,:) :: speciesPointersList ! Alias to above of dimension (0:nSpecies,nCells)
integer, allocatable, dimension(:, :) :: numberPerCellList, firstParticleList ! Of dimension (0:nSpecies,nCells)
! Aliased pointers to numberPerCellList, firstParticleList of dimension (0:nSpecies,nCells(1),..,nCells(nDimensions))
integer, pointer, dimension(:, :, :, :) :: numberPerCell, firstParticle
integer :: freeParticle = 1 ! Used to find new particles for insertion
! Number densities are calculated for each species on a hydro sampling grid
! Use index 0 for the total over all species
integer, dimension (nMaxDimensions) :: lbSample, ubSample
integer :: nHydroCells(0:nMaxDimensions)
! This next one needs to be double precision since HydroGrid expects that
real (dp), allocatable :: numberDensity (:, :, :, :) ! Particles per unit volume in each species
! Some counters for various statistics
integer*8, dimension(0:2*nReactions) :: reactionCount=0 ! Counts the number of reactions that happened for each reaction
! For testing:
! QY: The following records the number of particles of each species at the beginning. It is used for debugging only.
integer, dimension(0:nSpecies):: initialParticleCount
! QY: temporary testing, for recording the participating particles in each reaction
integer, allocatable :: IRDME_test_number_1(:) ! reactions in each cell
integer, allocatable :: IRDME_test_number_2(:) ! reactions in each particle
integer :: IRDME_test_number(4) ! QY: number of each fake reaction in test (1=birth, 2=unary death, 3=A+B->0, 4=A+A->0)
integer, dimension(:,:), allocatable :: reactionParticle_AA, reactionParticle_AB ! History log of particles in each reaction, AB for A+B->0,
!AA for A+A->0
real (wp), allocatable :: timeOfReactions_AA (:), timeOfReactions_AB (:) ! History of the time of each pairwise reaction recorded in reactionParticle
! AA for A+A->0, AB for A+B->0
integer, dimension(:), allocatable :: count
end type DoiBox
! Global Doi box parameters:
!----------------
! Species:
real (wp) :: speciesDiameter (nSpecies) = 1.0_wp
real (wp) :: speciesDiffusivity (nSpecies) = 1.0_wp ! In units of length^2 / unit_time
! Global reference or default equilibrium values:
real (wp) :: numberDensity (nSpecies) = 0.0_wp ! Initial/default number density for each species
! Reactions:
! Reaction network (see routine classifyReactionNetwork below)
! We need to multiply by 2 for use in IRDME
integer, dimension(2*nReactions,4) :: reactionTable=0 ! Records the type of reagent and product particles of each reaction
! For example, let the third reaction be 'iSpecies + 0 --> jSpecies + kSpecies', then we set:
! reactionType(3)=R_REPLACEMENT
! reactionTable(3) to be (i,0,j,k).
! For IRME we duplicate A+B->? also as B+A->? with half the rate and schedule them independently
integer, dimension(nReactions*2) :: reactionType = 0 ! Classification of all reactions
! We assume here a classical law of mass action and the rates are the rates appearing in the LMA
! The LMA is expressed here in *number* densities
! Note that the units of the number densities are always 1/m^3 even in 1D and 2D
! For IRDME we assume here that the system is well-mixed
! and later we convert these to Poisson rates (per unit time) for binary reactions
real (wp) :: reactionRate(nReactions) = 0.0_wp
real (wp) :: IRDME_reactionRate(2*nReactions) = 0.0_wp ! Duplicate copy of above for binary reactions to distinguish A+B-> from B+A->
integer :: totalReactions = nReactions ! Total number of reactions including duplicates for IRDME
! Stochiometric coefficients for products and reactants separately (nu_plus and nu_minus):
integer, dimension(nSpecies,2,nReactions) :: reactionNetwork = 0
integer :: reactionScheme = IRDME ! 0 for RDME, 1 for IRDME
! Doi parameters:
real (wp) :: DoiCellLength (nMaxDimensions) = 1.0_wp
real (wp) :: DoiCellVolume
real (wp) :: fractionExtraParticles = 0.1_wp ! Add 10% more particles
integer :: nMaxParticlesPerCell=0 ! This will be recomputed later if less than or equal to zero
real (wp) :: inputTimestep = 0.0_wp
real (wp), dimension(nSpecies) :: diffusiveCLF = 0.0_wp
integer :: problem_type=0 ! 0=uniform, 1=half A's, half B's (interface), 2=stripe
logical :: usePoisson = .true. ! Use Poisson or Gaussian RNGs
logical :: addDensityFluctuations = .true. ! Initialize and fill reservoir cells with fluctuations or without?
logical :: strangSplitting = .true. ! It is more accurate to use Strang splitting here
logical :: randomShift = .true. ! Randomly shift the collision grid each time step
integer :: diffuseByHopping = 0 ! If 0, diffusion is done by continuous random walk
! If 1, diffusion is done by random hopping but positions are not on lattice (RDME or IRDME)
! If 2, positions remain strictly on a lattice at the center of the cells for RDME only!
logical :: writeOutput = .true. ! Is this an I/O process?
! For sampling the number densities on a coarser grid:
! Note: nBlockingSample/nBlockingCollisions = DoiCellLength / sampleCellLength
! That is, nBlockingSample sampling/hydro cells equal nBlockingCollisions collision cells
! Sampling/hydrodynamic cell parameters:
integer, dimension (nMaxDimensions) :: nSampleCells = 1
real (wp), dimension (nMaxDimensions) :: sampleCellLength =1.0_wp
real (wp) :: sampleCellVolume
! Global system dimensions:
real (wp), dimension (1:nMaxDimensions) :: domainLength=1.0_wp
integer, dimension(nMaxDimensions) :: nBlockingSample=1, nBlockingCollision=1
real (wp) :: domainVolume
integer, dimension (0:nMaxDimensions) :: nDoiCells = 1
! Global boundary conditions on the whole system
type (WallType) :: wallBCs (2, nDimensions) ! BCs for non-periodic boundaries
integer :: reservoirThickness = 1 ! Number of reservoir hydro cells to use
contains
!--------------------------------------
! Initialization routines for the whole Doi domain (global)
! These need to be called once per processor per Doi domain (level)
subroutine readDoiParameters (fileUnit) ! Read parameters from a NAMELIST file
integer, intent(in) :: fileUnit ! If positive, the unit to read the namelist from
integer :: nameListFile = 15
namelist / DoiBoxOptions / reactionRate, reactionNetwork, reactionScheme, numberDensity, &
speciesDiffusivity, speciesDiameter, sampleCellLength, nSampleCells, &
nBlockingSample, nBlockingCollision, fractionExtraParticles, &
usePoisson, wallBCs, addDensityFluctuations, reservoirThickness, &
inputTimestep, strangSplitting, randomShift, &
nMaxParticlesPerCell, diffuseByHopping, problem_type
if (fileUnit<=0) then ! Default
if(writeOutput) write(*,*) "Reading Doi parameters from namelist file"
open (nameListFile, file= "DoiBoxOptions.nml", status="old", action="read")
else
nameListFile=fileUnit
end if
read (nameListFile, nml=DoiBoxOptions)
if (fileUnit<=0) close (nameListFile)
if(any(nSampleCells(nDimensions+1:nMaxDimensions)/=1)) stop "Must have only one sampling cell in all trivial dimensions"
end subroutine readDoiParameters
! Prepare all the required values for the whole Doi domain (once per processor)
subroutine initializeDoiParameters (writeToOutput)
logical, intent(in), optional :: writeToOutput
! Before calling this, one must set sampleCellLength, nSampleCells(1:nMaxDimensions), the blocking widths
if(present(writeToOutput)) writeOutput=writeToOutput
domainLength = nSampleCells * sampleCellLength
domainVolume = product(domainLength)
sampleCellVolume = product (sampleCellLength)
DoiCellLength = real(nBlockingSample,wp) / real(nBlockingCollision,wp) * sampleCellLength
DoiCellVolume = product(DoiCellLength)
nDoiCells(1:nMaxDimensions) = nint (domainLength / DoiCellLength)
if(any(nDoiCells(nDimensions+1:nMaxDimensions)/=1)) stop "Must have a single particle cell in trivial dimensions"
nDoiCells(0) = product (nDoiCells(1:nMaxDimensions))
! CFL is only meaningful for the non-trivial dimensions
diffusiveCLF = speciesDiffusivity * inputTimestep / (minval(DoiCellLength(1:nDimensions)**2))
if(writeOutput) write(*,*) 'The diffusive CLF number for each species is ', diffusiveCLF, " max=", maxval(diffusiveCLF)
if(writeOutput) write(*,*) 'Domain covered by ', nDoiCells(1:nDimensions), ' or a total of ', nDoiCells(0), &
' collision cells of length ', DoiCellLength
if(writeOutput) write(*,*) 'The domain has volume', domainVolume, 'and each cell has volume', DoiCellVolume
if(writeOutPUT) write(*,*) 'Sample cell length:', sampleCellLength
if(writeOutput) write(*,*) 'Doi timestep = ', inputTimestep
end subroutine initializeDoiParameters
!--------------------------------------
!--------------------------------------
! Initialization routines for a Doi box (local)
! These are called after the Doi domain is initialized, once per computational box
! Allocate arrays associated with one box
subroutine createDoiBox (box, boundaryType, lbSample, ubSample)
type (DoiBox), target, intent (inout) :: box
integer, intent(in) :: boundaryType (2,nDimensions) ! These must be set externally
integer, intent(in), dimension(nMaxDimensions) :: lbSample, ubSample ! Bounds of this box
! Local variables:
logical :: periodicOnly = .true.
integer :: i, j, k, index, nCells, iDimension, iSpecies
integer :: cellLocation(1:nMaxDimensions), cellIndex
! Copy the inputs:
box%boundaryType = boundaryType
if (any(box%boundaryType /= PERIODIC)) periodicOnly = .false.
if (.not. periodicOnly) randomShift = .false.
if (reactionScheme == IRDME) randomShift = .false.
! Initialize reaction types.
call classifyReactionNetwork(box)
write (*,*) 'Reactions are'
select case (reactionScheme)
case(RDME)
do i = 1, nReactions
write (*,*) 'Reaction No.', i, 'is', reactionTable(i,1), '+', reactionTable(i,2), '-->', &
reactionTable(i,3), '+', reactionTable(i,4), 'reaction type is', reactionType(i), 'reaction rate is', reactionRate(i)
end do
case(IRDME)
do i = 1, totalReactions
write (*,*) 'Reaction No.', i, 'is', reactionTable(i,1), '+', reactionTable(i,2), '-->', &
reactionTable(i,3), '+', reactionTable(i,4), 'reaction type is', reactionType(i), &
'reaction rate is', IRDME_reactionRate(i)
end do
case default
stop 'Wrong Reaction Scheme'
end select
! count reaction numbers
box%reactionCount = 0
box%lb = nint ( (lbSample - 1) * sampleCellLength / DoiCellLength + 1 )
box%ub = nint ( ubSample * sampleCellLength / DoiCellLength )
box%lb(nDimensions+1:nMaxDimensions) = 1
box%ub(nDimensions+1:nMaxDimensions) = 1
box%extent(1:nMaxDimensions) = box%ub - box%lb + 1
box%extent(0) = product(box%extent(1:nDimensions))
if(printDebug) then
write(*,*) "---------------------------------"
write(*,*) "lbSample = ", lbSample
write(*,*) "lbCollision = ", box%lb
write(*,*) "ubSample = ", ubSample
write(*,*) "ubCollision = ", box%ub
end if
! Calculate boundary locations
box%boundaryLocation(1,:) = (lbSample(1:nDimensions) - 1) * sampleCellLength(1:nDimensions)
box%boundaryLocation(2,:) = ubSample(1:nDimensions) * sampleCellLength(1:nDimensions)
box%lbSample = lbSample
box%ubSample = ubSample
box%nHydroCells(1:nMaxDimensions)=(box%ubSample-box%lbSample+1)
box%nHydroCells(0)=product(box%nHydroCells(1:))
if(writeOutput) write(*,*) "Creating box with lb=", box%lb, " ub=", box%ub, &
" lbSample=", box%lbSample, " ubSample=", box%ubSample, &
" BC=", box%boundaryType
! Allocate reaction cell data:
allocate (box%numberPerCell(0:nSpecies, box%lb(1) :box%ub(1), box%lb(2) :box%ub(2), box%lb(3) :box%ub(3)))
select case(reactionScheme)
case(RDME)
allocate (box%speciesPointers(nSpecies, box%lb(1) :box%ub(1), box%lb(2) :box%ub(2), box%lb(3) :box%ub(3)))
box%speciesPointersList(1:nSpecies,1:box%extent(0)) => box%speciesPointers
case(IRDME)
nCells = box%extent(0)
call initializeHeap(box%heap,nCells)
allocate (box%numberPerCellList(0:nSpecies,1:box%extent(0)))
allocate (box%firstParticleList(nSpecies, nCells)) ! For LLCs
! This will be used to pre-compute and store the list of neighbors
allocate (box%neighboringCells(neighborhoodSize(0),box%extent(0)))
! Alias a pointer to the same storage using Fortran 2003 pointer rank-remapping facility:
box%firstParticle(1:nSpecies, box%lb(1) :box%ub(1), box%lb(2) :box%ub(2), box%lb(3) :box%ub(3)) => box%firstParticleList
box%numberPerCell(0:nSpecies, box%lb(1) :box%ub(1), box%lb(2) :box%ub(2), box%lb(3) :box%ub(3)) => box%numberPerCellList
case default
stop "reactionScheme can only be one of 0 (RDME) or 1 (IRDME)"
end select
! We calculate these for each species, and use index 0 for the total:
allocate (box%numberDensity(box%lbSample(1) :box%ubSample(1), box%lbSample(2) :box%ubSample(2), &
box%lbSample(3) :box%ubSample(3), 0:nSpecies))
end subroutine createDoiBox
subroutine initializeDoiBox (box) ! Initialize with uniform equilibrium values
type (DoiBox), target, intent (inout) :: box
integer, dimension(nMaxDimensions) :: iCell
integer :: nParticles, specie,i,j,k,nCells, particle, iParticle
real(wp), dimension(nSpecies) :: numberDensityCopy
real(wp) :: stripe_width
! Estimate the average number of particles in each species:
do specie=1, nSpecies
if(problem_type==3) then
box%nParticles (specie) = nint (numberDensity(specie)*sampleCellVolume)
else
box%nParticles (specie) = nint (numberDensity(specie)*domainVolume)
end if
if(writeOutput) write (*,*) "Estimated number of particles of species ", specie, " is ", box%nParticles(specie)
end do
box%nParticles(0) = sum(box%nParticles(1:nSpecies)) ! Total number of particles
nParticles = ceiling ((1+fractionExtraParticles)*box%nParticles (0))
if(writeOutput) write(*,*) "Estimated total number of particles = ", box%nParticles(0), " allocated=", nParticles
box%nMaxParticles = nParticles
if(nMaxParticlesPerCell<=0) then
nMaxParticlesPerCell = ceiling ( (7.0_wp * nParticles) / nDoiCells(0) )
write(*,*) "Setting nMaxParticlesPerCell=", nMaxParticlesPerCell
end if
allocate ( box%particle(nParticles) )
if (reactionScheme==RDME) then
allocate ( box%particlesSortedByCell(nParticles) )
box%freeParticle=1
else ! We use an LLC data structure
!allocate ( box%previousParticle(nParticles) )
allocate ( box%nextParticle(nParticles) )
box%freeParticle=1 ! Start of list of free particles
do particle=1, box%nMaxParticles-1
box%nextParticle(particle)=particle+1
end do
box%nextParticle(box%nMaxParticles)=0 ! End of list of free particles
end if
! Now actually initialize the domain with particles
do iParticle = 1, nParticles
box%particle(iParticle)%position = 0.0_wp
end do
write(*,*) "Starting to fill domain with particles"
! PARALLEL: Potential to parallelize this loop as operation is purely local
! However, this is only done once for initialization so benefit is minor
! We fill cell by cell:
box%nParticles=0
do k = box%lbSample(3), box%ubSample(3)
do j = box%lbSample(2), box%ubSample(2)
do i = box%lbSample(1), box%ubSample(1)
iCell = (/ i, j, k/)
select case(problem_type)
case(1) ! Generate a biased configuration where all A's are in half the domain and B in the other half
! Donev: Warning, this assumes sampling cells
numberDensityCopy=numberDensity
if( (i-box%lbSample(1) <= box%nHydroCells(1)/3) .or. (i-box%lbSample(1) >= 2*box%nHydroCells(1)/3) ) then
numberDensityCopy(2)=0.0_wp
else
numberDensityCopy(1)=0.0_wp
end if
call fillSamplingCell(box, iCell, numberDensityCopy)
case(2) ! Generate a biased configuration where all particles are in a narrow stripe
stripe_width = 1.0d0/16.0d0 ! Adjust this to match needs
if( (i-box%lbSample(1) < (1-stripe_width)*box%nHydroCells(1)/2) .or. &
(i-box%lbSample(1) >= (1+stripe_width)*box%nHydroCells(1)/2) ) then
numberDensityCopy=0.0_wp
else
numberDensityCopy=numberDensity
end if
call fillSamplingCell(box, iCell, numberDensityCopy)
case(3) ! Only put particles in the center cell -- for detailed testing and comparison to FHD
if(all(iCell==1+(box%nHydroCells(1:nMaxDimensions)-1)/2)) then
numberDensityCopy=numberDensity
else
numberDensityCopy=0.0_wp
end if
call fillSamplingCell(box, iCell, numberDensityCopy)
case default
call fillSamplingCell(box, iCell, numberDensity)
end select
end do
end do
end do
if (reactionScheme==IRDME) then
call initializeIRDME(box)
else
call sorter(box)
end if
write (*,*) "Total number of particles at the beginning is ", box%nParticles(0), "=", box%nParticles(1:nSpecies)
if (isAssertsOn) then
box%initialParticleCount = box%nParticles
end if
end subroutine initializeDoiBox
subroutine classifyReactionNetwork(box)
type (DoiBox), target, intent(inout) :: box
integer :: iReaction, iSpecies, reagentCount, productCount, &
firstReagent, secondReagent, firstProduct, secondProduct, indexReaction, IRDME_index
real (wp) :: thickness, effectiveArea, factor, reactiveRadius
logical :: catalyst
IRDME_index = 0
IRDME_reactionRate = 0
indexReaction = 0
do iReaction = 1, nReactions
reagentCount = 0
productCount = 0
do iSpecies = 1, nSpecies
if (reactionNetwork(iSpecies,1,iReaction)>0) then
reagentCount = reagentCount + reactionNetwork(iSpecies,1,iReaction)
end if
if (reactionNetwork(iSpecies,2,iReaction)>0) then
productCount = productCount + reactionNetwork(iSpecies,2,iReaction)
end if
end do
if (reagentCount <0 .or. reagentCount >2) stop 'Unsupported Reagent Number'
if (productCount <0 .or. productCount >2) stop 'Unsupported Product Number'
firstReagent = 0; secondReagent= 0
firstProduct = 0; secondProduct= 0
do iSpecies = 1, nSpecies
if (reactionNetwork(iSpecies,1,iReaction) > 0) then
if (reactionNetwork(iSpecies,1,iReaction)==2) then
firstReagent = iSpecies
secondReagent= iSpecies
cycle
else if (firstReagent == 0) then
firstReagent = iSpecies
else
secondReagent = iSpecies
end if
end if
end do
do iSpecies = 1, nSpecies
if (reactionNetwork(iSpecies,2,iReaction) > 0) then
if (reactionNetwork(iSpecies,2,iReaction)==2) then
firstProduct = iSpecies
secondProduct= iSpecies
cycle
else if (firstProduct == 0) then
firstProduct = iSpecies
else
secondProduct = iSpecies
end if
end if
end do
indexReaction = indexReaction + 1
reactionTable(indexReaction,1)=firstReagent
reactionTable(indexReaction,2)=secondReagent
reactionTable(indexReaction,3)=firstProduct
reactionTable(indexReaction,4)=secondProduct
call classifyReaction()
if (reactionScheme == IRDME) then
! We convert the input rates here to have units of inverse time (Poisson rates)
! This assumes a well-mixed system and is only an approximation
! But it ensures that we can use the same input files for RDME and IRDME
if (secondReagent/=0) then
reactiveRadius = (speciesDiameter(firstReagent)+speciesDiameter(secondReagent))/2
if (nDimensions==3) then
thickness = 1.0_wp
effectiveArea = 4.0_wp/3.0_wp*PI*(reactiveRadius**3)
else if (nDimensions==2) then
thickness = domainLength(3)
effectiveArea = PI*(reactiveRadius**2)
else if (nDimensions==1) then
thickness = domainLength(2)*domainLength(3)
effectiveArea = 2.0_wp*reactiveRadius
end if
factor = 1.0_wp/(thickness*effectiveArea)
write(*,*) "IRDME: Multiplying input reactionRate for reaction ", iReaction, " by factor=", factor
else
factor = 1.0_wp
end if
! For binary reactions in IRDME with different species, we need to split into A+B-> and B+A->
! For A+B we have k = lambda * n_A*n_B * reactive_volume
! But for A+A we have k = lambda/2 * n_A^2 * reactive_volume since pairs are counted twice
! -- this is why we multiply the rate below by 2
! What we compute below is the microscopic rate "lambda" in the Doi model
! Since each pair of particles can be selected twice for both for A+A-> and A+B->,
! regardless of whether the two reacting particles are in the same cell or in different cells,
! we multiply the rate by 1/2 later in calculatePropensity_IRDME
if ((reagentCount==2) .and. (firstReagent/=secondReagent)) then ! A+B->?
IRDME_reactionRate(indexReaction) = reactionRate(iReaction)*factor
! Now also duplicate as the reverse reaction
indexReaction = indexReaction + 1
reactionTable(indexReaction,1)=secondReagent
reactionTable(indexReaction,2)=firstReagent
reactionTable(indexReaction,3)=firstProduct
reactionTable(indexReaction,4)=secondProduct
call classifyReaction()
IRDME_reactionRate(indexReaction) = reactionRate(iReaction)*factor
else if(reagentCount==2) then ! A+A->?
IRDME_reactionRate(indexReaction) = 2*reactionRate(iReaction)*factor
else ! Here factor=1 but let us leave it in for future use
IRDME_reactionRate(indexReaction) = reactionRate(iReaction)*factor
end if
end if
end do
totalReactions = indexReaction
contains
subroutine classifyReaction()
select case(reagentCount)
case(0)
reactionType(indexReaction)=R_BIRTH
case(1)
if (productCount==0) then
reactionType(indexReaction)=R_ANNIHILATION
else if (productCount==1) then
reactionType(indexReaction)=R_REPLACEMENT
else if (productCount==2) then
if ((firstReagent==firstProduct).or.(firstReagent==secondProduct)) then
reactionType(indexReaction) = R_CATA_BIRTH
else
reactionType(indexReaction)=R_REPLACEMENT
end if
else
stop 'Wrong reaction type.'
end if
case(2)
catalyst = .false.
if ((firstReagent == firstProduct) .or. (firstReagent == secondProduct) &
.or. (secondReagent == firstProduct) .or. (secondReagent == secondProduct)) catalyst = .true.
if (productCount==0) then
reactionType(indexReaction)=R_ANNIHILATION
else if (productCount==1) then
if (catalyst) then
reactionType(indexReaction) = R_CATA_ANNIHILATION
else
reactionType(indexReaction) = R_MERGE
end if
else if (productCount==2) then
! Even though the reaction A+A->A+B is catalytic, we treat it as one with type TRANSFORM since
! they share the same way of position changing.
if ((.not. catalyst) .or. ((firstReagent==secondReagent) .or. (firstProduct==secondProduct))) then
reactionType(indexReaction) = R_TRANSFORM
else
reactionType(indexReaction) = R_CATALYST
end if
else
stop 'Unsupported reaction type'
end if
case default
stop 'Wrong reaction type: wrong reagent number'
end select
end subroutine classifyReaction
end subroutine classifyReactionNetwork
! This is the subroutine that calls mover, sorter, and reactor.
! It distinguishes between the case where we need to do strang splitting and the other case.
subroutine updateDoiBox(box,timestep)
type (DoiBox), target :: box
real (wp), intent(in) :: timestep
real (wp), dimension(nDimensions) :: randomShiftDist
integer :: consumed, produced, temp, difference, iSpecies, iReaction, iParticle, nParticles(0:nSpecies)
integer, dimension(nMaxDimensions) :: cellIndices
call fillReservoirCells(box) ! Donev: This is a no-op at present since only periodic BCs work
! In general we want to do strang splitting even for IRDME since it is more accurate than
! move by dt, react by dt
! which is called Lie splitting
! http://www.staff.science.uu.nl/~frank011/Classes/numwisk/ch13.pdf
if(randomShift.and.(reactionScheme == RDME)) then
! Randomly displace all particles by up to half a grid cell each time step to minimize spatial artifacts
call UniformRNGVec(randomShiftDist,nDimensions)
randomShiftDist = randomShiftDist - 0.5_wp
else
randomShiftDist = 0.0_wp
end if
if (strangSplitting) then
call mover(box,0.5_wp*timestep,randomShiftDist)
! call cleanParticles(box) ! Do this now even if not necessary
if (nReactions>0) call reactor(box,timestep)
call mover(box,0.5_wp*timestep,-randomShiftDist)
call cleanParticles(box) ! Remove empty spaces
else ! No strang splitting below
call mover(box,timestep,randomShiftDist)
!call cleanParticles(box) ! Do this now even if not necessary
if (nReactions>0) call reactor(box,timestep)
call mover(box,0.0_wp,-randomShiftDist)
call cleanParticles(box) ! Remove empty spaces
end if
!box%globalTime = box%globalTime + timestep ! Looses accuracy in single precision
box%nTimesteps = box%nTimesteps + 1
box%globalTime = box%nTimesteps * timestep
! Checks if the number of particle change matches with reaction count.
if(isAssertsOn) then
nParticles=box%nParticles
box%nParticles=0
do iParticle = lbound(box%particle,1), ubound(box%particle,1)
iSpecies = box%particle(iParticle)%species
if (iSpecies <= 0) cycle
box%nParticles(0) = box%nParticles(0) + 1
box%nParticles(iSpecies) = box%nParticles(iSpecies) + 1
end do
if(any(box%nParticles/=nParticles)) stop "Wrong count of particles at end of time step"
end if
if (isAssertsOn.and.(.not.IRDME_test)) then
call testPositionInFakeDimension(box)
do iSpecies = 1, nSpecies
difference = box%nParticles(iSpecies)-box%initialParticleCount(iSpecies)
temp = 0
do iReaction = 1, totalReactions
consumed = 0
produced = 0
if (reactionTable(iReaction,1)==iSpecies) consumed = consumed + 1
if (reactionTable(iReaction,2)==iSpecies) consumed = consumed + 1
if (reactionTable(iReaction,3)==iSpecies) produced = produced + 1
if (reactionTable(iReaction,4)==iSpecies) produced = produced + 1
temp = temp - box%reactionCount(iReaction)*consumed + box%reactionCount(iReaction)*produced
end do
if ((all(wallBCs%wallType==PERIODIC)).and.(temp /= difference)) then
write (*,*) 'Difference is ', difference, 'Temp is ', temp
write (*,*) box%reactionCount
stop 'Reaction count does not match particle count'
end if
end do
!if (all(wallBCs%wallType==PERIODIC)) write (*,*) 'Particle count matches reaction count.'
end if
end subroutine updateDoiBox
!--------------------------------------
! Computational Doi routines (advection, diffusion, collisions, etc.)
!--------------------------------------
! Fill a given sampling (hydrodynamic) cell with particles
subroutine fillSamplingCell(box, iCell, cellNumberDensity)
type (DoiBox), target, intent (inout) :: box
integer, intent (in) :: iCell(nMaxDimensions) ! The position of the sampling cell in the grid
real (wp), intent (in) :: cellNumberDensity(nSpecies) ! Desired values of number densities
real (wp), dimension (nDimensions) :: random ! Donev: I changed this to nDimensions
real (wp) :: rng, mean
integer :: nParticlesInCell, iSpecies, iParticle, iteration
logical :: isReservoirCell
do iSpecies = 1, nSpecies
! Decide how many particles to generate:
if(addDensityFluctuations) then ! Generate a Poisson number of particles for each species
mean = sampleCellVolume * cellNumberDensity(iSpecies)
if(usePoisson) then
call PoissonRNG (nParticlesInCell, mean)
else ! Approximate with a Gaussian
call NormalRNG(rng)
nParticlesInCell = nint(mean + sqrt(mean)*rng)
end if
else if(all(nSampleCells==1)) then ! Fix the density at a constant (nearest integer)
nParticlesInCell = nint( sampleCellVolume * cellNumberDensity(iSpecies))
else ! Smart rounding to get desired density on average but with minimal fluctuations
call UniformRNG(random(1))
nParticlesInCell = floor( sampleCellVolume * cellNumberDensity(iSpecies) + random(1) )
end if
isReservoirCell = ( any(iCell < 1) .or. any(iCell(1:nDimensions) > nSampleCells(1:nDimensions)) )
if(.false.) write(*,*) "Inserting ", nParticlesInCell, " particles of species ", iSpecies, &
" in cell ", iCell, " isR=", isReservoirCell
do iteration = 1, nParticlesInCell
iParticle = box%freeParticle
if(diffuseByHopping>1) then ! Remain strictly on a lattice
random=0.5_wp
else
call UniformRNGVec (random, size(random))
end if
box%particle(iParticle)%position(1:nDimensions) = ( iCell(1:nDimensions) - 1 + random ) * sampleCellLength(1:nDimensions)
box%particle(iParticle)%position(nDimensions+1:nMaxDimensions) = 0.0_wp
if (isReservoirCell) then ! Negative species for particles in reservoir cells
box%particle(iParticle)%species = -iSpecies
else
box%particle(iParticle)%species = iSpecies
end if
box%nParticles(0) = box%nParticles(0) + 1
box%nParticles(iSpecies) = box%nParticles(iSpecies) + 1
call updateFreeParticle(box)
end do
end do
end subroutine fillSamplingCell
! Deletes and repacks particles
subroutine cleanParticles (box)
type (DoiBox), target :: box
integer :: p, lastParticle
if(reactionScheme==IRDME) return
!write(*,*) "Starting search from ", box%freeParticle, count(box%particle(:)%species/=0)
lastParticle = box%freeParticle - 1
p = lbound(box%particle,1)
PackParticles: do
if (box%particle(p)%species > 0) then
if(p>=lastParticle) exit ! The array has been packed
else
! Find the last particle with a positive species
do
if(lastParticle<lbound(box%particle,1)) exit PackParticles ! No particles left
if(box%particle(lastParticle)%species > 0) exit ! Found a particle
box%particle(lastParticle)%species = 0 ! Delete any reservoir particles
lastParticle = lastParticle - 1
end do
if(p>=lastParticle) exit ! The array has been packed
box%particle(p) = box%particle(lastParticle)
box%particle(lastParticle)%species = 0
lastParticle = lastParticle - 1
end if
p = p + 1
end do PackParticles
box%freeParticle = lastParticle + 1
end subroutine cleanParticles
subroutine fillReservoirCells (box) ! Donev: Not really used at present since only periodic BCs work
type (DoiBox), target :: box
integer :: i, j, k, iCell(nMaxDimensions)
if (any(box%boundaryType == RESERVOIR)) then
if (reactionScheme == IRDME) stop "Reservoir cells not supported for IRDME"
do k = box%lbSample(3), box%ubSample(3)
do j = box%lbSample(2), box%ubSample(2)
do i = box%lbSample(1), box%ubSample(1)
iCell = (/ i, j, k/)
if ( any(iCell < 1) .or. any(iCell(1:nDimensions) > nSampleCells(1:nDimensions)) ) then
call fillSamplingCell(box, iCell, numberDensity)
end if
end do
end do
end do
end if
end subroutine fillReservoirCells
! Move all particles by dt, taking into account boundary conditions
subroutine mover (box,timestep,randomShift)
type (DoiBox), target :: box
real (wp), intent(in) :: timestep
real (wp), optional, intent(in) :: randomShift(nDimensions)
integer :: iDimension, p, iSpecies
integer :: initialSpecies
real (wp) :: dtime
real (wp), dimension (nDimensions) :: initialPosition
!integer :: nLeaving, nEntering ! Donev: These are not really useful
if (IRDME_trace) return
if(.false.) then ! Debug the reservoir boundaries
write(*,*) "Initial n_particles: real=", count(box%particle(:)%species>0), &
" reservoir=", count(box%particle(:)%species<0)
end if
dtime = timestep
! QY: If the timestep is 0, then we are actually just doing the second half of random shift in the case in the
! case where there is no strang splitting. Hence, we don't need to call brownianMover at all.
if (timestep>0.0_wp) call brownianMover(box,dtime) ! Move according to simple Brownian motion
! PARALLEL: This is a loop that can benefit from parallelization
! It is a loop over particles, some of which can be no-ops
! So it is important here to use cyclic distribution over threads
!nLeaving=0; nEntering=0
do p = lbound(box%particle,1), ubound(box%particle,1)
iSpecies = abs(box%particle(p)%species)
if (iSpecies == 0) cycle
! QY: Here we do the random shift. The second way of doing random shift, i.e., by shifting the boundaries, is harder to do
if (present(randomShift)) box%particle(p)%position(1:nDimensions) = &
box%particle(p)%position(1:nDimensions) + randomShift * DoiCellLength(1:nDimensions)
initialSpecies = box%particle(p)%species
! Note that due to roundoff error it is possible for a particle to end exactly on the boundary after the position is flushed to memory
! This is particularly true for single precision
do iDimension = 1, nDimensions
if (box%particle(p)%position(iDimension) < box%boundaryLocation(1,iDimension)) then
select case(box%boundarytype(1,iDimension))
case(PERIODIC)
do while (box%particle(p)%position(iDimension) < box%boundaryLocation(1,iDimension))
box%particle(p)%position(iDimension) = box%particle(p)%position(iDimension)+domainLength(iDimension)
end do
case(RESERVOIR)
if (initialSpecies > 0) then
!nLeaving = nLeaving + 1
box%particle(p)%species = -abs(box%particle(p)%species)
end if
case default
stop 'Boundary condition not implemented yet'
end select
else if (box%particle(p)%position(iDimension) >= box%boundaryLocation(2,iDimension)) then
select case(box%boundarytype(2,iDimension))
case(PERIODIC)
do while ((box%particle(p)%position(iDimension) >= box%boundaryLocation(2,iDimension)))
box%particle(p)%position(iDimension) = box%particle(p)%position(iDimension)-domainLength(iDimension)
end do
case(RESERVOIR)
if (initialSpecies > 0) then
!nLeaving = nLeaving + 1
box%particle(p)%species = -abs(box%particle(p)%species)
end if
case default
stop 'Boundary condition not implemented yet'
end select
end if
! Reservoir particle entering box.
if (initialSpecies<0) then
if (all(box%particle(p)%position(1:nDimensions) > box%boundaryLocation(1,:)) .and. &
all(box%particle(p)%position(1:nDimensions) < box%boundaryLocation(2,:))) then
box%particle(p)%species = abs(box%particle(p)%species)
end if
end if
end do
if (isAssertsOn) then
iSpecies=box%particle(p)%species
if(iSpecies>0) then ! Positive species must be inside the box
if ( .not. all( (box%particle(p)%position(1:nDimensions) >= box%boundaryLocation(1,:)) .and. &
( box%particle(p)%position(1:nDimensions) <= box%boundaryLocation(2,:)) )) then
write (0,*) p, box%particle(p)%species, " Particle outside of box! New r=", &
box%particle(p)%species, box%particle(p)%position(1:nDimensions), &
" prior r=", initialSpecies, initialPosition, " box low=", box%boundaryLocation(1,:), &
" box high=", box%boundaryLocation(2,:)
stop
end if
else if(iSpecies<0) then ! Negative species must be outside of the box
if ( all( (box%particle(p)%position(1:nDimensions) >= box%boundaryLocation(1,:)) .and. &
( box%particle(p)%position(1:nDimensions) <= box%boundaryLocation(2,:)) )) then
write (0,*) p, iSpecies," Particle inside of box!", &
" New r=", box%particle(p)%species, box%particle(p)%position, &
" Old r=", initialSpecies, initialPosition, " box low=", box%boundaryLocation(1,:), &
" box high=", box%boundaryLocation(2,:)
stop
end if
end if
end if
end do
if(.false.) then ! Debug the reservoir boundaries
write(*,*) "Final n_particles: real=", count(box%particle(:)%species>0), &
" reservoir=", count(box%particle(:)%species<0)
end if
contains
subroutine brownianMover(box,dtime)
type (DoiBox), target :: box
real (wp), intent(in) :: dtime