-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulation.cpp
3197 lines (2478 loc) · 117 KB
/
Simulation.cpp
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
#include "Simulation.hpp"
#include <omp.h>
using namespace std;
using namespace arma;
// Constructers /////////////////////////////////////////////////////////////////////////
// Direct constructer
Simulation::Simulation(int N_0) {
// Store the number of cells in the simulation
this->N_0 = N_0;
// Set some default parameters (initlize some default objects)
P_0 = 0; // [1/µm^2] The density of invading phages in the simulation initially
N_max = 65536; // Maximum number of cells in simulation (Unsigned short int)
M_max = 1e6; // Maximum number of phages in simulation
M_tot = 0; // Accumulated number of phages
dt = 1e-6; // [hour] Default time step size
dT_c = dt; // [hour] Size of the time step which updates the phages
dT = dt; // [hour] Size of the time step which updates everything else
dR = 3.5; // Depth of the infected layer (for spawning)
nSamp = 10; // Number of samples to save per simulation hour
dGrid = 2; // Spacing of grid (in units of critical radius R)
dShell = HUGE_VAL; // [µm] Thickness of agent layer (for biomass)
n_0 = 0.1; // [1/µm^3] Initial concentration of nutrient
g_max = 10.0/6.0; // [1/hour] Maximal growth rate for the cells
R = 0.782; // [µm] The length scale for division (Typical volume 1.3 µm^3)
k = 1e3; // [N*m] Parameter for repulsive potential
K = 0.0; // Michaels-Menten FACTOR for Monod growth (K = 0.0 disables Monod behavior)
gamma = 1/dT; // Probability to infect cell
alpha = 0.00; // Probability for phage to go lysogenic
beta = 400; // Multiplication factor phage
delta = 0.003; // [1/hour] Rate of phage decay
epsilon = 0; // Probability for offspring to turn resistant
r = 10.0*2/3; // Constant used in the time-delay mechanism
T_i = -1; // [hours] Time when the phage infections begins (less than 0 disables phage infection)
L_box = 50; // [µm] Length of boundary condition box
numB = 0; // Current tally of suceptible cells
numL = 0; // Current tally of lysogenic cells
numI = 0; // Current tally of infected cells
numD = 0; // Current tally of dead cells
numR = 0; // Current tally of resistant cells
eta = 0.1; // Amount of division noise (width of gaussian)
nu = R/4; // Amount of displacement noise during division. x = x0 + rand(nu) etc.
D_B = 0.0; // [µm^2/hour] Diffusion constant for the cells
D_P = 13000; // [µm^2/hour] Diffusion constant for the phage
D_n = 4e5; // [µm^2/hour] Diffusion constant for the nutrient
h_agar = 250; // [µm] Total height of the soft agar layers
h_cell = 125; // [µm] Distance of the cell colony to the hard agar
p = 0; // Helper variable to control phage spawning
Time = 0; // Counter for how many timesteps have passed
maxStep = 1; // Maximum time-step used in adaptive algorithm
sigma = HUGE_VAL; // Maximum number of standard deviations to move in diffusions term
nSkips = 0; // Counts the number of time-steps skipped with adaptive algorithm
posibleStep = 1; // Largest possible "step" at current time
debug = 1; // The amount of information to print to terminal
debugBool = false;
exit = false; // Boolean to control early exit
firstRun = true; // Bool to indicate if this run is the first
nutrientField = false; // Boolean to toggle between nutrient field and just nutrients
exportAny = false; //
exportCellData = false; //
exportColonySize = false; // Booleans to control the export output
exportPhageData = false; //
exportNutrient = false; //
singleInfectedCell = false; // Boolean to enable phages via a single infected cell
planarPhageInvasion = false; // Boolean to enable phages invading in a plane
uniformPhageInvasion= false; // Boolean to enable phages invading uniformly from entire space
manyInfectedCells = false; // Boolean to enable surface infection and uniformly from entire space
forcedThickness = 0; // "Boolean" to force an infected surface of a given number
invasionType = 0; // Number to remember the invasion type
reflectingBoundary = false; // Boolean to enable the simple box boundary condition with reflective sides
absorbingBoundary = true; // Boolean to enable the simple box boundary condition with absorbing sides
experimentBoundary = false; // Boolean to enable the advanced petri dish boundary conditions
phageType = "default"; // Contains the type of phage chosen (sets parameters according to De Paepe)
rngSeed = -1; // Random number seed ( set to -1 if unused )
// Initilize the benchmarking vector
for (int j = 0; j < 20; j ++) {
benchMark[j] = 0.0;
}
// Set the resolution of the grid to match Lbox
res = ceil(L_box/(2*dGrid*R)-1/2);
// Set the number of threads to use
omp_set_num_threads(1);
};
// Copy constructor
Simulation::Simulation(const Simulation& other) {
N_0 = other.N_0; // Store the initial number of cells in the simulation
P_0 = other.P_0; // [1/µm^2] The density of invading phages in the simulation initially
N_max = other.N_max; // Maximum number of cells in simulation
M_max = other.M_max; // Maximum number of phages in simulation
M_tot = other.M_tot; // Accumulated number of phages
dt = other.dt; // [hour] Default time step size
dT_c = other.dT_c; // [hour] Size of the time step which updates the cells
dT = other.dT; // [hour] Size of the time step which updates everything else
dR = other.dR; // Depth of the infected layer (for spawning)
nSamp = other.nSamp; // Number of samples to save
dGrid = other.dGrid; // Spacing of grid (in units of critical radius R)
dShell = other.dShell; // [µm] Thickness of agent layer (for biomass)
n_0 = other.n_0; // [1/µm^3] Initial concentration of nutrient
g_max = other.g_max; // [1/hour] Maximal growth rate for the cells
R = other.R; // [µm] The length scale for division (Typical volume 1.3 µm^3)
k = other.k; // [N*m] Parameter for repulsive potential
K = other.K; // Michaels-Menten FACTOR for Monod growth
gamma = other.gamma; // Probability to infect cell
alpha = other.alpha; // Probability for phage to go lysogenic
beta = other.beta; // Multiplication factor phage
delta = other.delta; // [1/hour] Rate of phage decay
epsilon = other.epsilon; // Probability for offspring to turn resistant
r = other.r; // Constant used in the time-delay mechanism
T_i = other.T_i; // [hours] Time when the phage infections begins (less than 0 disables phage infection)
L_box = other.L_box; // [µm] Length of boundary condition box
numB = other.numB; // Current tally of suceptible cells
numL = other.numL; // Current tally of lysogenic cells
numI = other.numI; // Current tally of infected cells
numD = other.numD; // Current tally of dead cells
numR = other.numR; // Current tally of resistant cells
eta = other.eta; // Amount of division noise (width of gaussian)
nu = other.nu; // Amount of displacement noise during division. x = x0 + rand(nu) etc.
D_B = other.D_B; // [µm^2/hour] Diffusion constant for the cells
D_P = other.D_P; // [µm^2/hour] Diffusion constant for the phage
D_n = other.D_n; // [µm^2/hour] Diffusion constant for the nutrient
h_agar = other.h_agar; // [µm] Total height of the soft agar layers
h_cell = other.h_cell; // [µm] Distance of the cell colony to the hard agar
p = other.p; // Helper variable to control phage spawning
debug = other.debug; // The amount of information to print to terminal
debugBool = other.debugBool;
exit = other.exit; // Boolean to control early exit
Time = other.Time; // Counter for how many timesteps have passed
maxStep = other.maxStep; // Maximum time-step used in adaptive algorithm
sigma = other.sigma; // Maximum number of standard deviations to move in diffusions term
posibleStep = other.posibleStep; // Largest possible timestep at current time
nutrientField = other.nutrientField; // Boolean to toggle between nutrient field and just nutrients
exportAny = other.exportAny; //
exportCellData = other.exportCellData; //
exportColonySize = other.exportColonySize; // Booleans to control the export output
exportPhageData = other.exportPhageData; //
exportNutrient = other.exportNutrient; //
singleInfectedCell = other.singleInfectedCell; // Boolean to enable phages via a single infected cell
planarPhageInvasion = other.planarPhageInvasion; // Boolean to enable phages invading in a plane
uniformPhageInvasion= other.uniformPhageInvasion; // Boolean to enable phages invading uniformly from entire space
manyInfectedCells = other.manyInfectedCells; // Boolean to enable surface infection and uniformly from entire spacefalse
forcedThickness = other.forcedThickness; // "Boolean" to force an infected surface of a given number
invasionType = other.invasionType; // Number to remember the invasion type
reflectingBoundary = other.reflectingBoundary; // Boolean to enable the simple box boundary condition with reflective sides
absorbingBoundary = other.absorbingBoundary; // Boolean to enable the simple box boundary condition with absorbing sides
experimentBoundary = other.experimentBoundary; // Boolean to enable the advanced petri dish boundary conditions
phageType = other.phageType; // Contains the type of phage chosen (sets parameters according to De Paepe)
rngSeed = other.rngSeed; // The seed for the random number generator
// Initilize the benchmarking vector
for (int j = 0; j < 20; j ++) {
benchMark[j] = other.benchMark[j];
}
res = other.res;
// Copy random number generator
rng = other.rng;
// Copy cells, phages, nutrients and nutrient grid.
cells = other.cells;
biomass = other.biomass;
phages = other.phages;
center = other.center;
nutrient = other.nutrient;
nutrient_grid = other.nutrient_grid;
CN = other.CN;
B = other.B;
}
// Controls the evaluation of the simulation
int Simulation::Run(double T) {
// Check for invalid runs
if (exit) { return 1; }
if (T < dT) { return 1; }
// Get start time
time_t tic;
time(&tic);
// Things to run only when simulation is initialized
if (Time == 0) {
// Initilize the simulation matrices
Initialize();
}
// Check if export has been enabled, and if so, generate a path
if (exportAny) {
path = GeneratePath();
// Write the reproducable command to log.txt
WriteLog(T);
}
// Determine the number of timesteps between samplings
int nStepsPerSample = (int)round(1/(nSamp*dt));
// Determine the number of timesteps between cell updates
int nStepsPerCellUpdate = (int)round(dT_c/dt);
// Determine the number of samples to take during this run
int nSamplings = nSamp*T;
// Run steps which should not be sampled
if ((Time < (int)round(T_i/dt)) or (nSamplings == 0)) {
// If no samplings are to be made. Compute the number of time-steps to take:
if (nSamplings == 0) {
nStepsPerSample = (int)round(T/dt);
} else { // If simulation should run up until T_i, and then start sampling:
// Compute number of steps between now and T_i
nStepsPerSample = (int)round(T_i/dt) - Time - 1;
}
int t = 0;
while (t < nStepsPerSample) {
// Check for exit flag
if (exit) { break; }
// Update cells
CellUpdate();
// Use adaptive timesteps to update phages
int tp = 0;
while (tp < nStepsPerCellUpdate) {
// Adaptive timesteps
int step = posibleStep;
// Ensure the step is less than maxStep
if (step > maxStep) {
step = maxStep;
}
// Ensure the step fits with next saving point
if (step > nStepsPerCellUpdate-tp) {
step = nStepsPerCellUpdate-tp;
}
// Ensure the step is positive
if (step < 1) {
step = 1;
}
dT = step*dt;
PhageUpdate();
// Increase Time counter and t if steps were stepped (t and Time are measured in units of dtF)
Time += step;
tp += step;
t += step;
nSkips += step-1;
}
// if (numB == 0) {
// cerr << "\t>>No more uninfected cells! Exiting..<<" << endl;
// f_log << ">>No more uninfected cells! Exiting..<<" << endl;
// exit = true;
// }
// if (phages.size() == 0) {
// cerr << "\t>>No more phages! Exiting..<<" << endl;
// f_log << ">>No more phages! Exiting..<<" << endl;
// exit = true;
// }
if ((numB == 0) and (numI == 0) and (numL == 0)) {
cerr << "\t>>All cells are dead! Exiting..<<" << endl;
f_log << ">>All cells are dead! Exiting..<<" << endl;
exit = true;
}
}
// Reset the sampling frequency
nStepsPerSample = (int)round(1/(nSamp*dt));
}
// Export the start configuration
if (firstRun) {
if ( exportCellData and (debug > 0)) {cout << "\tExporting Cell Position Data" << endl;}
if ( exportColonySize and (debug > 0)) {cout << "\tExporting Colony Size" << endl;}
if ( exportPhageData and (debug > 0)) {cout << "\tExporting Phage Position Data" << endl;}
if ( exportNutrient and (debug > 0)) {cout << "\tExporting Nutrient" << endl;}
// Export data
if (exportAny) ExportData(Time*dt);
}
// Run the time evolution
time_t timer;
time(&timer);
// Loop over samplings
for (int n = 0; n < nSamplings; n++) {
// Determine the number of samplings during run is compatible with timestep
// cout << nSamplings << endl;
// cout << nStepsPerSample << endl;
// cout << dt << endl;
// cout << T << endl;
// cout << fabs(nSamplings*nStepsPerSample*dt-T) << endl;
if (fabs(nSamplings*nStepsPerSample*dt-T) > dt/2) {
cerr << "\t>>Time-step too large for sampling frequency! Exiting..<<" << endl;
f_log << ">>Time-step too large for sampling frequency! Exiting..<<" << endl;
exit = true;
}
// Check for exit flag
if (exit) { break; }
int t = 0;
while (t < nStepsPerSample) {
// Check for exit flag
if (exit) { break; }
// Update cells
CellUpdate();
// Use adaptive timesteps to update phages
int tp = 0;
while (tp < nStepsPerCellUpdate) {
// Adaptive timesteps
int step = posibleStep;
// Ensure the step is less than maxStep
if (step > maxStep) {
step = maxStep;
}
// Ensure the step fits with next saving point
if (step > nStepsPerCellUpdate-tp) {
step = nStepsPerCellUpdate-tp;
}
// Ensure the step is positive
if (step < 1) {
step = 1;
}
dT = step*dt;
PhageUpdate();
// Increase Time counter and t if steps were stepped (t and Time are measured in units of dtF)
Time += step;
tp += step;
t += step;
nSkips += step-1;
}
// if (numB == 0) {
// cerr << "\t>>No more uninfected cells! Exiting..<<" << endl;
// f_log << ">>No more uninfected cells! Exiting..<<" << endl;
// exit = true;
// }
// if (phages.size() == 0) {
// cerr << "\t>>No more phages! Exiting..<<" << endl;
// f_log << ">>No more phages! Exiting..<<" << endl;
// exit = true;
// }
if ((numB == 0) and (numI == 0) and (numL == 0)) {
cerr << "\t>>All cells are dead! Exiting..<<" << endl;
f_log << ">>All cells are dead! Exiting..<<" << endl;
exit = true;
}
}
// Export the data
time(&timer);
if (exportAny) ExportData(Time*dt);
benchMark[6] += difftime(time(NULL),timer);
// Show progress bar
if ((n > 0) and (debug > 0)) {
cout << "\t[";
int pos = 60 * static_cast<float>(n)/static_cast<float>(nSamplings);;
for (int i = 0; i < 60; ++i) {
if (i <= pos) cout << ".";
else cout << " ";
}
cout << "] " << "\r";
cout.flush();
}
// Store the state to file
time(&timer);
if (exportAny) {
SaveState();
}
benchMark[6] += difftime(time(NULL),timer);
}
// Get stop time
time_t toc;
time(&toc);
// Calculate time difference
float seconds = difftime(toc, tic);
float hours = floor(seconds/3600);
float minutes = floor(seconds/60);
minutes -= hours*60;
seconds -= minutes*60 + hours*3600;
if (debug > 0) {
cout << endl;
cout << "\tSimulation complete after ";
if (hours > 0.0) cout << hours << " hours and ";
if (minutes > 0.0) cout << minutes << " minutes and ";
cout << seconds << " seconds." << endl;
}
// Report benchmarking results
if (debug > 0) {
cout << endl;
cout << "\tBenchmarking results:" << endl;
cout << "\t" << setw(3) << difftime(toc, tic) << " s of total time" << endl;
cout << "\t" << setw(3) << benchMark[0] << " s spent on computing movement" << endl;
cout << "\t\t" << setw(3) << benchMark[7] << " s spent on computing cell bursting" << endl;
cout << "\t\t" << setw(3) << benchMark[8] << " s spent on computing cell movement" << endl;
cout << "\t\t" << setw(3) << benchMark[9] << " s spent on computing phage movement" << endl;
cout << "\t\t\t" << setw(3) << benchMark[12] << " s spent on phage-cell overlap and diffusion" << endl;
cout << "\t\t\t\t" << setw(3) << benchMark[18] << " s spent on phage-cell overlap" << endl;
cout << "\t\t\t\t" << setw(3) << benchMark[19] << " s spent on phage diffusion" << endl;
cout << "\t\t\t" << setw(3) << benchMark[13] << " s spent on phage-boundary reflections" << endl;
cout << "\t" << setw(3) << benchMark[1] << " s spent on executing movement" << endl;
cout << "\t" << setw(3) << benchMark[2] << " s spent on cell growth" << endl;
cout << "\t" << setw(3) << benchMark[3] << " s spent on nutrient" << endl;
cout << "\t" << setw(3) << benchMark[4] << " s spent on infections" << endl;
cout << "\t" << setw(3) << benchMark[5] << " s spent on CN, B and P grids" << endl;
cout << "\t\t" << setw(3) << benchMark[10] << " s spent on armadillo data structures" << endl;
cout << "\t\t\t" << setw(3) << benchMark[14] << " s spent on clearing arrays" << endl;
cout << "\t\t\t" << setw(3) << benchMark[15] << " s spent on updating arrays" << endl;
cout << "\t\t" << setw(3) << benchMark[11] << " s spent on std vector data structures" << endl;
cout << "\t\t\t" << setw(3) << benchMark[16] << " s spent on clearing arrays" << endl;
cout << "\t\t\t" << setw(3) << benchMark[17] << " s spent on updating arrays" << endl;
cout << "\t" << setw(3) << benchMark[6] << " s spent on filesaving" << endl;
cout << "\t----------------------------------------------------"<< endl << endl << endl;
}
// Write sucess to log
if (exit) {
f_log << "Adaptive algorithm reduced time-steps by: " << nSkips << endl;
f_log << ">>Simulation completed with exit flag<<" << endl;
} else {
f_log << "Adaptive algorithm reduced time-steps by: " << nSkips << endl;
f_log << ">>Simulation completed without exit flag<<" << endl;
}
if (exit) {
return 1;
} else {
return 0;
}
}
// Initialize the simulation
void Simulation::Initialize() {
// Set the random number generator seed
if (rngSeed >= 0.0) {
rng.seed( rngSeed );
} else {
static std::random_device rd;
rng.seed(rd());
}
// Initilize unit nutrient throughout the simulation
if (debug > 1) {
cout << endl;
cout << "\tInitlizing the nutrient grid, cell density grid, phage density grid, clever neighbour grid, and laplace operator" << endl;
}
// Resize armadillo data types
if (nutrientField) {
nutrient_grid.set_size(2*res+1,2*res+1,2*res+1);
}
B.set_size(2*res+1,2*res+1,2*res+1);
lap.set_size(2*res+1,2*res+1);
// Fill nutrient and cell density
if (nutrientField) nutrient_grid.fill(n_0*pow(dGrid*R,3)); // Nutrient per unit cell
else nutrient = n_0*pow(dGrid*R,3); // Average nutrient per unit cell
B.zeros();
// Compute the proper value for the Michaels-Menten
K *= n_0*pow(dGrid*R,3);
// Reinterpret dGrid
dGrid = dGrid*R;
// Adjust the maxStep
// maxStep = min(maxStep,(int)floor(pow(dGrid*R,2)/(pow(1,2)*6*D_P*dT)));
// Boundary conditions for laplace operator
lap(0,0) = -1;
lap(0,1) = 1;
lap(2*res,2*res) = -1;
lap(2*res,2*res-1) = 1;
// Fill the laplace operator, and resize the clever neighbour grid
CN.resize(2*res+1);
for (int x = 0; x < 2*res+1; x++ ) {
if ((x > 0) and (x < 2*res)) {
lap(x,x) = -2;
lap(x,x+1) = 1;
lap(x,x-1) = 1;
}
CN[x].resize(2*res+1);
for (int y = 0; y < 2*res+1; y++ ) {
CN[x][y].resize(2*res+1);
}
}
// Initilize the cells at (0,0,0) + random offset, with radius r = 0.677+random offset, and in the 0 state
if (debug > 1) {cout << "\tInitlizing the cells" << endl;}
cells.reserve(N_max);
cells.resize(N_0);
for (int n = 0; n < N_0; n++) {
// Generate location
double x = (2*rand(rng)-1)*N_0*R;
double y = (2*rand(rng)-1)*N_0*R;
double z = (2*rand(rng)-1)*N_0*R;
// Generate radius
double rad = 0.0;
if (n == 0) {
rad = 0.677;
} else {
rad = 0.677*(1 + (Rand(0.2)-0.1));
}
// Detect which grid point cell belongs to
int i = round(x / (dGrid)) + res;
int j = round(y / (dGrid)) + res;
int k = round(z / (dGrid)) + res;
// Add cell to system
cells[n] = vector<double> { x, y, z, rad, 0, (double)i, (double)j, (double)k, 0};
// Add information to clever neighbour grid
CN[i][j][k].push_back(n);
// Update tally
numB++;
}
// Add center of colony
center = vector<double> { 0, 0, 0, -1 };
r_max = 0;
I_max = -1;
// Do some checks for input parameters
if ( (not exit) and (nutrientField) and (2*D_n *dT_c/pow(dGrid,2) > 1) ) {
cerr << "\t>>Unstable resolution sizes [ 2*D_n dT/(dGrid)^2 = " << 2*D_n*dT_c/pow(dGrid,2) << " > 1 ]! Exiting..<<" << endl;
f_log << ">>Unstable resolution sizes [ 2*D_n dT/(dGrid)^2 = " << 2*D_n*dT_c/pow(dGrid,2) << " > 1 ]! Exiting..<<" << endl;
exit = true;
}
}
// Updates the cells
void Simulation::CellUpdate() {
// Check for exit flag
if (exit) { return; }
// Time objects for benchmarking
time_t timer;
// Reset tally of uninfected
numB = 0;
if (debugBool) {deb(11);}
time(&timer);
// Increase the state of infections, and spawn new phages.
bool bursting = false;
int N = cells.size();
for (int n = N-1; n >= 0 ; n--) {
if (GrowInfection(n)) {
// Remove bursted cell
cells.erase(cells.begin() + n);
// Set bursting variable to true
bursting = true;
// Update tally
numI--;
numD++;
}
}
benchMark[7] += difftime(time(NULL),timer);
benchMark[0] += difftime(time(NULL),timer);
// Check if all cells are bursted
if (cells.size() == 0) {
cerr << "\t>>All cells have bursted! Exiting..<<" << endl;
f_log << ">>All cells have bursted! Exiting..<<" << endl;
exit = true;
return;
}
// Check for exit flag
if (exit) { return; }
if (debugBool) {deb(12);}
time(&timer);
// Grow the cells
N = cells.size();
for (int n = 0; n < N; n++) {
if (cells[n][4] > 0) { // Lytic cells
continue;
} else if (cells[n][4] == 0) { // Uninfected cells
numB++;
GrowCell(n);
} else if (cells[n][4] == -1) { // Lysogenic cells
GrowCell(n);
} else if (cells[n][4] == -2) { // Dead cells
continue;
} else if (cells[n][4] == -3) { // Resistant cells
GrowCell(n);
}
}
if (debugBool) {deb(13);}
// Grow the biomass
if (not biomass.empty()) {
if (GrowBiomass()) {
// If biomass absorbed a cell, update CN grid
bursting = true;
}
// Update the number of uninfected cells
numB += (int)floor(pow(biomass[3],3)/pow(0.677,3));
}
benchMark[2] += difftime(time(NULL),timer);
if (debugBool) {deb(14);}
// Update the CN grid if cells have been removed
if (bursting) {
UpdateNearestNeighbourGrid();
}
if (debugBool) {deb(15);}
if (cells.size() >= 100) {
if (omp_get_num_threads() == 1) {
omp_set_num_threads(omp_get_max_threads());
}
}
if (debugBool) {deb(16);}
time(&timer);
// Run the over cells to get movement for the cells
N = cells.size();
double** C_movement = new double*[N];
#pragma omp parallel for
for (int n = 0; n < N; n++) {
C_movement[n] = new double[3];
CellMovement(n,C_movement[n]);
}
benchMark[8] += difftime(time(NULL),timer);
if (debugBool) {deb(17);}
// Center the biomass
if (not biomass.empty()) {
int counter = 0;
double ucenter[3] = {0.0, 0.0, 0.0}; // Center of uninfected cells
for (int n = 0; n < N; n++) {
if (cells[n][4] == 0) {
for (int j = 0; j < 3; j ++) {
ucenter[j] += cells[n][j];
counter++;
}
}
}
// Move the biomass
for (int j = 0; j < 3; j ++) {
biomass[j] = 0.25*ucenter[j]/counter + (1-0.25)*biomass[j];
}
// Detect which grid point center belongs to
biomass[5] = round( biomass[0] / (dGrid) ) + res;
biomass[6] = round( biomass[1] / (dGrid) ) + res;
biomass[7] = round( biomass[2] / (dGrid) ) + res;
}
if (debugBool) {deb(18);}
time(&timer);
// Update the nutrient
if (K > 0.0) {
if (nutrientField) {
NutrientGridUpdate();
if (accu(nutrient_grid)/(pow(2*res+1,3)*pow(dGrid,3)) < 1e-9) {
cerr << "\t>>Nutrients are depleted! (Time = " << Time*dt << "); Exiting..<<" << endl;
f_log << ">>Nutrients are depleted! (Time = " << Time*dt << "); Exiting..<<" << endl;
exit = true;
}
} else {
nutrient -= g_max*nutrient/(nutrient+K)*(numB+numL)/pow(2*res+1,3)*dT;
nutrient = fmax(0.0,nutrient); // Ensure that negative numbers does not occur.
if (nutrient/pow(dGrid,3) < 1e-9) {
cerr << "\t>>Nutrients are depleted! (Time = " << Time*dt << "); Exiting..<<" << endl;
f_log << ">>Nutrients are depleted! (Time = " << Time*dt << "); Exiting..<<" << endl;
exit = true;
}
}
}
benchMark[3] += difftime(time(NULL),timer);
if (debugBool) {deb(19);}
time(&timer);
// Reset the cell density grid and phage grid
if (nutrientField) {
B.fill(0);
}
benchMark[14] += difftime(time(NULL),timer);
benchMark[10] += difftime(time(NULL),timer);
benchMark[5] += difftime(time(NULL),timer);
if (debugBool) {deb(20);}
// Run the over cells to apply the movement step
for (int n = 0; n < N; n++) {
time(&timer);
for (int j = 0; j < 3; j++) {
cells[n][j] += C_movement[n][j];
}
benchMark[1] += difftime(time(NULL),timer);
// Detect which grid point cell belongs to now
int i = (int)round(cells[n][0] / (dGrid)) + res;
int j = (int)round(cells[n][1] / (dGrid)) + res;
int k = (int)round(cells[n][2] / (dGrid)) + res;
// Check if outer bondary is reached
if ( (i < 0) or (i >= 2*res+1) or (j < 0) or (j >= 2*res+1) or (k < 0) or (k >= 2*res+1) ) {
cerr << "\t>>Colony extends simulation grid size! Exiting...<<" << endl;
f_log << ">>Colony extends simulation grid size! Exiting...<<" << endl;
exit = true;
return;
}
// Get the old gridpoint
int io = (int)cells[n][5];
int jo = (int)cells[n][6];
int ko = (int)cells[n][7];
// Check if cell moved to new point
if ( (not ( io == i)) or (not ( jo == j)) or (not ( ko == k))) {
// Erase from old grid point
CN[io][jo][ko].erase(std::remove(CN[io][jo][ko].begin(), CN[io][jo][ko].end(), n), CN[io][jo][ko].end());
// Update location information
cells[n][5] = (double)i;
cells[n][6] = (double)j;
cells[n][7] = (double)k;
// Add cell to new CN grid point
CN[i][j][k].push_back(n);
}
// Add cell to cell density grid
if (nutrientField) {
if ((cells[n][4] == 0) or (cells[n][4] == -1)) {
B(i,j,k)++;
}
}
benchMark[15] += difftime(time(NULL),timer);
benchMark[10] += difftime(time(NULL),timer);
benchMark[17] += difftime(time(NULL),timer);
benchMark[11] += difftime(time(NULL),timer);
}
if (debugBool) {deb(21);}
// Replaces the most central bacteria with a central biomass if the colony is too large
if (not exit) {
if (biomass.empty()) {
CreateCentralBiomass();
}
}
if (debugBool) {deb(22);}
// Update the colony extent
ComputeColonyExtent();
// Clean up
if (debugBool) {deb(23);}
time(&timer);
for (int n = 0; n < N; n++) {
delete[] C_movement[n];
}
delete[] C_movement;
if (debugBool) {deb(24);}
}
// Updates the phages
void Simulation::PhageUpdate() {
// Check for exit flag
if (exit) { return; }
// Time objects for benchmarking
time_t timer;
if (debugBool) {deb(1);}
time(&timer);
// Run the over phages to infect the cells
int M = phages.size();
for (int m = M-1; m >= 0; m--) {
// Remove the phage if it sucessfully infects the cell
if (PhageInfection(m) == 1) {
phages.erase(phages.begin() + m);
}
}
benchMark[4] += difftime(time(NULL),timer);
if (debugBool) {deb(2);}
time(&timer);
// Run the over phages to get movement for the phage
M = phages.size();
double** P_movement = new double*[M];
#pragma omp parallel for
for (int m = 0; m < M; m++) {
P_movement[m] = new double[3];
PhageMovement(m,P_movement[m]);
}
benchMark[9] += difftime(time(NULL),timer);
benchMark[0] += difftime(time(NULL),timer);
if (debugBool) {deb(3);}
time(&timer);
// Run the over phages to apply the movement step
for (int m = M-1; m >= 0; m--) {
time(&timer);
// Kill phages according to the decay rate
if (rand(rng) < delta*dT) {
phages.erase(phages.begin() + m);
continue;
}
// Apply the movement step
for (int j = 0; j < 3; j++) {
phages[m][j] += P_movement[m][j];
}
benchMark[1] += difftime(time(NULL),timer);
time(&timer);
// Apply boundary conditions to the phage
ApplyBoundaryConditions(m);
benchMark[13] += difftime(time(NULL),timer);
benchMark[9] += difftime(time(NULL),timer);
benchMark[0] += difftime(time(NULL),timer);
}
if (debugBool) {deb(4);}
// Spawns phages, if the infection time has been passed
if (not exit) {
SpawnPhages();
}
// Clean up
for (int m = 0; m < M; m++) {
delete[] P_movement[m];
}
delete[] P_movement;
if (debugBool) {deb(5);}
}
// Simulation functions /////////////////////////////////////////////////////////////////
// Get movement vector for cell I
void Simulation::CellMovement(int I, double *B) {
// Prepare the output vector
std::fill(B,B+3,0);
// Get the cell gridpoint
int i = cells[I][5];
int j = cells[I][6];
int k = cells[I][7];
// Find nearest neighbours
vector<int> NN = NearestNeighbours(i,j,k);
for (int i = 0; i < NN.size(); i++) {
// Neighbour to test overlap with
int n = NN[i];
// Skip the current cell ( cell I )
if ( n == I ) continue;
// Calculate distance between cells
double d = 0.0;
for (int j = 0; j < 3; j++) {
d += pow(cells[n][j]-cells[I][j],2);
}
d = sqrt(d); // Distance between center of mass
// Check for overlap
if ( d < cells[n][3]+cells[I][3] ) {
// Calculate the displacement of the cell
// See notes p. 12
double F = - PotentialGradient(d,cells[n][3],cells[I][3]) * dT_c;
// Use the difference in position vectors to determine the direction of the force