-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBiofilm_CellularAutomata.py
2781 lines (2438 loc) · 129 KB
/
Biofilm_CellularAutomata.py
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
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 17:20:53 2024
@author: Raphaël RUBRICE - AgroParisTech
This is my project for the 2nd year 'Engineering by numerical simulation'
project course at AgroParisTech.
My goals were :
1) To siimulate bacterial biofilm growth using the Cellular Automaton approach
2) To simulate bacterial interactions between strains within the biofilm
To do so I mainly based my work on the following scientific papers :
[1] Sarukhanian, S.; Maslovskaya, A.; Kuttler, C. (2023) -
Three-Dimensional Cellular Automaton for Modeling of Self-Similar
Evolution in Biofilm-Forming Bacterial Populations -
Mathematics 2023, 11, 3346. https://doi.org/10.3390/ math11153346
[2] Irene Guzman-Soto,1 Christopher McTiernan,1 Mayte Gonzalez-Gomez,1
Alex Ross,1,2 Keshav Gupta,1 Erik J. Suuronen,1 Thien-Fah Mah,2
May Griffith,3,4 and Emilio I. Alarcon1,2, (2021) -
Mimicking biofilm formation and development: Recent progress in in vitro
and in vivo biofilm models - iScience 24, 102443, May 21, 2021
For further bibliography, read the project report accessible on github.
You have the possibility to make simulations in both 2D and 3D.
However, note that simulations in 3D takes a lot of time to complete on regular
computers so you should use simpler simulations and small size spaces when
trying 3D mode.
Enjoy :D !
~ Raphaël RUBRICE.
PS : As you may notice, the following code is not at all perfect, so feel free
to make improvements and share them ! :D
"""
# =============================================================================
# IMPORTS
# =============================================================================
# To manipulate files and folders
import shutil
import os
# Set working directory
wd = 'C:/Coding Projects/UP_IngSum'
os.chdir(wd)
# To access time infos
import datetime
import time
# To use deepcopy
from copy import deepcopy
# To save any kind of python object
import pickle as pkl
# To make the simulation
import numpy as np
import random
# For multiprocessing
from joblib import Parallel, delayed
# To make animations and plots
import matplotlib.pyplot as plt
import cellpylib3d as cpl3d
from matplotlib.colors import LogNorm, ListedColormap, BoundaryNorm
import fitz
import io
from PIL import Image
# =============================================================================
# HELPER FUNCTIONS
# =============================================================================
def generate_n_colors(n, mode='strain'):
"""
Generates a list of n colors using matplotlib color maps viridis if n <= 5,
Dark2_r otherwise.
Parameters
----------
n : int
Number of colors to generate.
mode : str, optional
The default is 'strain'.
Returns
-------
colors : list
list of n colors.
"""
if n<=5 and mode == 'strain':
colormap = plt.cm.viridis
else:
colormap = plt.cm.ocean_r
colors = [colormap(i) for i in np.linspace(0, 1, n)]
if mode=='strain':
colors[0] = '#ff0000' # dead cells in red
colors[1] = '#F5F5F5' # medium in white
else:
colors[0] = '#F5F5F5'
return colors
def format_dict(d, indent=0):
"""
Function to format the dictionary into a readable string
Parameters
----------
d : dictionary.
indent : int, optional
The default is 0.
Returns
-------
s : string
String corresponding to the given dictionary.
"""
s = ""
for key, value in d.items():
s += ' ' * indent + f"{key}: "
# if the value is a dictionary
if isinstance(value, dict):
s += "\n" + format_dict(value, indent+4)
else:
s += f"{value}\n"
return s
# =============================================================================
# CELLULAR AUTOMATON
# =============================================================================
# Define Cellular Automaton (Grid class)
class Grid:
def __init__(self, size):
"""
Parameters
----------
size : tuple (height,length) if 2D, else (height,length,depth)
"""
self.height, self.length = size[0], size[1]
if len(size) == 3:
self.dimensionality = 3
self.depth = size[2]
else:
self.dimensionality = 2
self.grid = np.zeros(size) #Biomass Matrix
self.dead = -1 # Value to represent dead cells
self.dead_pos = [] # List of dead cells positions
self.medium = 0 # Value to represent the medium
# =========================================================================
# INITIALIZATION METHODS AND FUNCTIONS
# =========================================================================
def possibles_idx(self, height, length, depth=None, d_min=0, d_max=None,
h_min=0, h_max=None, l_min=0, l_max=None, memory=None):
"""
Generates all possible positions between a set of boundaries.
Parameters
----------
height : int
Maximum height value.
length : int
Maximum length value.
depth : int, optional
Maximum depth value. The default is None.
d_min : int, optional
Minimum depth value. The default is 0.
d_max : int, optional
Maximum depth value. The default is None.
h_min : int, optional
Minimum depth value. The default is 0.
h_max : int, optional
Maximum height value. The default is None.
l_min : int, optional
Minimum length value. The default is 0.
l_max : int, optional
Maxium length value. The default is None.
memory : list, optional
List of indices already used. The default is None.
Returns
-------
L : List
List of all potential indices.
"""
if self.dimensionality == 2: # 2D
L = []
if memory:
if h_max == None and l_max == None:
for i in range(h_min, height):
for j in range(l_min, length):
if (i,j) not in memory:
L.append((i,j))
return L
else :
assert [h_max, l_max]!=[None, None], 'You need to specify both h_max and l_max.'
for i in range(h_min, h_max):
for j in range(l_min, l_max):
if (i,j) not in memory:
L.append((i,j))
else:
if h_max == None and l_max == None:
for i in range(h_min, height):
for j in range(l_min, length):
L.append((i,j))
return L
else :
assert [h_max, l_max]!=[None, None], 'You need to specify both h_max and l_max.'
for i in range(h_min, h_max):
for j in range(l_min, l_max):
L.append((i,j))
else: # 3D
L = []
if memory:
if h_max == None and l_max == None and d_max == None and depth!=None:
for i in range(h_min, height):
for j in range(l_min, length):
for k in range(d_min, depth):
if (i,j,k) not in memory:
L.append((i,j,k))
return L
else :
assert [h_max, l_max, d_max]!=[None, None, None], 'You need to specify both h_max and l_max.'
for i in range(h_min, h_max):
for j in range(l_min, l_max):
for k in range(d_min, d_max):
if (i,j,k) not in memory:
L.append((i,j,k))
else:
if h_max == None and l_max == None and d_max == None and depth!=None:
for i in range(h_min, height):
for j in range(l_min, length):
for k in range(d_min, depth):
L.append((i,j,k))
return L
else :
assert [h_max, l_max, d_max]!=[None, None, None], 'You need to specify both h_max and l_max.'
for i in range(h_min, h_max):
for j in range(l_min, l_max):
for k in range(d_min, d_max):
L.append((i,j,k))
return L
def unique_random(self, size, height, length, depth=None, d_min=0, d_max=None,
h_min=0, h_max=None, l_min=0, l_max=None, memory=None):
"""
Generates the list of indices used for inoculation.
Parameters
----------
size : int
Number of indices to choose, this is the length of the output.
height : int
Maximum height value.
length : int
Maximum length value.
depth : int, optional
Maximum depth value. The default is None.
d_min : int, optional
Minimum depth value. The default is 0.
d_max : int, optional
Maximum depth value. The default is None.
h_min : int, optional
Minimum depth value. The default is 0.
h_max : int, optional
Maximum height value. The default is None.
l_min : int, optional
Minimum length value. The default is 0.
l_max : int, optional
Maxium length value. The default is None.
memory : list, optional
List of indices already used. The default is None.
Returns
-------
indices : List
List of indices used to inoculate the grid.
"""
indices = []
possible_idx = self.possibles_idx(height=height, length=length, depth=depth, d_min=d_min, d_max=d_max,
h_min=h_min, h_max=h_max, l_min=l_min, l_max=l_max,
memory=memory)
# Among posisble indices, randomly choose 'size' indices
for i in range(size):
cell_pos = possible_idx[random.randint(0,len(possible_idx)-1)]
indices.append(cell_pos)
possible_idx.remove(cell_pos)
return indices
def get_grids(self, TOX_dictionary,
O_init=7e-3, O_init_grad=True, scale_O='linear',
N_init=0.7e-3, N_init_grad=True, scale_N='linear',
C_init=25e-3, C_init_grad=True, scale_C='linear',
TOX_init=0, TOX_init_grad=True, scale_TOX='linear',
nportions=5):
"""
Creates a dictionary of nutrients and Toxin matrices. Those are
used in several aspects of the simulation such as molecule diffusion,
cell reproduction, cellular death and cellular movement.
Parameters
----------
TOX_dictionary : dicitonary
{'TOX0':{'+':[0,2], '-':[1], 'DTOX':0.7e-9},
'TOX1':{'+':[1], '-':[2], 'DTOX':0.7e-9},
'TOX2':{'+':[3], '-':[0], 'DTOX':0.7e-9}}.
O_init : int, optional
Maximum amount of Oxygen in space. The default is 1e9.
O_init_grad : boolean, optional
Whether to make a gradient or not (if True, highest values
are at the surface). The default is True.
scale_O : string, optional
The scale to use if init_grad set to True ('log', 'log10',
'log2', 'linear'). The default is 'linear'.
N_init : int, optional
Maximum amount of Nitrogen in space. The default is 1e9.
N_init_grad : boolean, optional
Whether to make a gradient or not (if True, highest values
are at the bottom). The default is True.
scale_N : string, optional
The scale to use if init_grad set to True ('log', 'log10',
'log2', 'linear'). The default is 'linear'.
C_init : int, optional
Maximum amount of Carbon in space. The default is 1e9.
C_init_grad : boolean, optional
Whether to make a gradient or not (if True, highest values
are at the bottom). The default is True.
scale_C : string, optional
The scale to use if init_grad set to True ('log', 'log10',
'log2', 'linear'). The default is 'linear'.
TOX_init : int, optional
Maximum amount of Toxins in space. The default is 0.
TOX_init_grad : boolean, optional
Whether to make a gradient or not (if True, highest values
are at the surface). The default is True.
scale_TOX : string, optional
The scale to use if init_grad set to True ('log', 'log10',
'log2', 'linear'). The default is 'linear'.
nportions : int, optional
How many parts for the gradient to be made of. The default is 5.
Returns
-------
A dictionary of matrices :
{'Biomass_Matrix':self.grid,
'O_Matrix': self.O_Matrix,
'N_Matrix': self.N_Matrix,
'C_Matrix': self.C_Matrix,
'TOX_Matrix': self.TOX_Matrix}
"""
# Helper function to apply gradient scaling
def apply_gradient(matrix, portion, init_value, scale_type, reverse=True):
if scale_type == 'linear':
assert nportions <= self.height, 'When using linear gradient, nportions must be smaller than grid height.'
for k in range(nportions):
factor = (nportions - k) if reverse else (k + 1)
matrix[k * portion:(k + 1) * portion] /= factor
elif scale_type.startswith('log'):
base = {'log': np.e, 'log2': 2, 'log10': 10}[scale_type]
for k in range(nportions):
factor = base**(nportions-k-1) if reverse else base**k
matrix[k * portion:(k + 1) * portion] = init_value * (1 / factor)
return matrix
portion = int(np.ceil(self.height / nportions)) # Used if .._init_grad is set to true
# Oxygen Matrix
self.O_Matrix = self.grid + O_init
if O_init_grad:
self.scale_O = scale_O
self.O_Matrix = apply_gradient(self.O_Matrix, portion, O_init, scale_O, reverse=False)
# Nitrogen Matrix
self.N_Matrix = self.grid + N_init
if N_init_grad:
self.scale_N = scale_N
self.N_Matrix = apply_gradient(self.N_Matrix, portion, N_init, scale_N)
# Carbon Matrix
self.C_Matrix = self.grid + C_init
if C_init_grad:
self.scale_C = scale_C
self.C_Matrix = apply_gradient(self.C_Matrix, portion, C_init, scale_C)
# Toxins Matrix
self.TOX_Matrices = []
for tox in range(len(TOX_dictionary)):
M = self.grid + TOX_init
if TOX_init_grad:
self.scale_TOX = scale_TOX
M = apply_gradient(M, portion, TOX_init, scale_TOX, reverse=True)
self.TOX_Matrices.append(M)
return {'Biomass_Matrix': self.grid,
'O_Matrix': self.O_Matrix,
'N_Matrix': self.N_Matrix,
'C_Matrix': self.C_Matrix,
'TOX_Matrices': self.TOX_Matrices}
def place_cells(self, indices, encoding, ncells, nstrains, biomass_init=10,
place_only=False, strainID=None, start_lists=False):
"""
Inoculates the space by placing cells. Creates the Strain Matrix which
represents where are each cell of each strain, where are empty spaces
and dead cells. Updates the biomass matrix (self.grid).
Parameters
----------
indices : list of tuples
Coordonates of each cell to place.
encoding : list of integers
List containing the values that represent each strain in
the Strains Matrix.
ncells : int
number of cells to place.
nstrains : int
number of strains in the simulation.
biomass_init : int, optional
Biomass quantity for a single cell. The default is 10.
place_only : boolean, optional
Whether to only place one strain or not. The default is False.
strainID : int, optional
ID of the strain to place with place_only. The default is None.
start_lists : boolean, optional
Whether to create self.cells_pos, self.Index_by_strain,
self.INDEX_HISTORY or not. The default is False.
Returns
-------
Strains_Matrix : np.array, dtype = int
Strains Matrix (Matrix of main interest to visualize the simulation).
Index : List of tuples
List of positions of every cell placed.
"""
if place_only:
if start_lists:
Index = [] # To know each living cell's position
Index_by_strain = list([])
INDEX_HISTORY = list([])
self.cells_pos = Index
self.Index_by_strain = Index_by_strain
# To be able to know the strainID of both living and dead cells
self.INDEX_HISTORY = INDEX_HISTORY
if self.dimensionality == 2:
Strains_Matrix = np.zeros((self.height, self.length), dtype=int)
else:
Strains_Matrix = np.zeros((self.height, self.length, self.depth), dtype=int)
else:
Index = deepcopy(self.cells_pos)
Index_by_strain = deepcopy(self.Index_by_strain)
INDEX_HISTORY = deepcopy(self.INDEX_HISTORY)
Strains_Matrix = self.Strains_Matrix.copy()
assert strainID!=None, 'No strainID specified but place_only was set to True.'
Index += indices
Index_by_strain.append(indices)
INDEX_HISTORY.append(indices)
if self.dimensionality == 2:
i_strain, j_strain = zip(*indices)
# Place cell in Strains Matrix
Strains_Matrix[i_strain, j_strain] = strainID
# Place cell in Biomass Matrix
self.grid[i_strain, j_strain] = biomass_init
else: #3D
i_strain, j_strain, k_strain = zip(*indices)
# Place cell in Strains Matrix
Strains_Matrix[i_strain, j_strain, k_strain] = strainID
# Place cell in Biomass Matrix
self.grid[i_strain, j_strain, k_strain] = biomass_init
self.cells_pos = Index #Index of live cells
self.Index_by_strain = Index_by_strain
self.INDEX_HISTORY = INDEX_HISTORY
else:
Index = [] # To know each living cell's position
Index_by_strain = []
# To be able to know the strainID of both living and dead cells
INDEX_HISTORY = []
if self.dimensionality == 2:
Strains_Matrix = np.zeros((self.height, self.length), dtype=int)
else:
Strains_Matrix = np.zeros((self.height, self.length, self.depth), dtype=int)
for strain in encoding:
# Chose a random set of indices for this strain
idx_strain = random.sample(indices, ncells)
# Remove those used
for idx in idx_strain:
indices.remove(idx)
Index += idx_strain
Index_by_strain.append(idx_strain)
INDEX_HISTORY.append(idx_strain)
if self.dimensionality == 2:
i_strain, j_strain = zip(*idx_strain)
# Place cell in Strains Matrix
Strains_Matrix[i_strain, j_strain] = strain
# Place cell in Biomass Matrix
self.grid[i_strain, j_strain] = biomass_init
else: #3D
i_strain, j_strain, k_strain = zip(*idx_strain)
# Place cell in Strains Matrix
Strains_Matrix[i_strain, j_strain, k_strain] = strain
# Place cell in Biomass Matrix
self.grid[i_strain, j_strain, k_strain] = biomass_init
self.cells_pos = Index
self.Index_by_strain = Index_by_strain
self.INDEX_HISTORY = INDEX_HISTORY
self.nstrains = nstrains
self.strain_popsize = ncells
self.strainID = encoding
self.Strains_Matrix = Strains_Matrix
return Strains_Matrix, Index
def on_cluster_inoculation(self, cluster_strain, cluster_height, cluster_width,
max_depth_other, ncells, nstrains, cluster_depth=None, biomass_init=10):
"""
Initialization method that creates a cluster of one strain only and
inoculates the remaining strains above it.
Parameters
----------
cluster_strain : int
Which strain to place (e.g for 3 strains total, put 0 for Strain0).
cluster_height : int
Cluster height.
cluster_width : int
Cluster width.
max_depth_other : int
Maximum height value for the remaining strains (in our simulation,
height 0 is the surface).
ncells : int
Number of cells to place for each strain (all strains start with
the same population size).
nstrains : int
Number of strains in the simulation.
cluster_depth : int, optional
Cluster depth. The default is None.
biomass_init : int, optional
Biomass quantity for a single cell. The default is 10.
Returns
-------
Strains_M : np.array, dtype = int
Strains Matrix (Matrix of main interest to visualize the simulation).
Indx : List of tuples
List of positions of every cell placed.
"""
if self.dimensionality == 2:
assert ncells <= cluster_height*cluster_width, 'Too much cells to place for the indicated cluster size.'
assert ncells <= max_depth_other*self.length, 'Too much cells to place for the indicated inoculation depth.'
assert max_depth_other <= self.height-cluster_height, 'max_depth_other is too deep.'
else:
assert cluster_depth != None, 'You must specify cluster_depth.'
assert ncells <= cluster_height*cluster_width*cluster_depth, 'Too much cells to place for the indicated cluster size.'
assert ncells <= max_depth_other*self.length*self.depth, 'Too much cells to place for the indicated inoculation depth.'
assert max_depth_other <= self.height-cluster_height, 'max_depth_other is too deep.'
encoding = [i*2+3 for i in range((nstrains))] # Strain IDs
self.Biomass_init = biomass_init
memory = []
for i, strain in enumerate(encoding):
if i==0:
start_L = True
else:
start_L = False
if i == cluster_strain:
# Cluster inoculation
if self.dimensionality == 2: # 2D
center = int(self.length/2)
L_min = center-int(cluster_width/2)
cluster = self.unique_random(ncells, height=self.height, length=center+int(cluster_width/2),
h_min=self.height-cluster_height, l_min=L_min)
Strains_M, Indx = self.place_cells(cluster, encoding, ncells, nstrains, biomass_init=biomass_init,
place_only=True, strainID=strain, start_lists=start_L)
else: # 3D
l_center = int(self.length/2)
d_center = int(self.depth/2)
L_min = l_center-int(cluster_width/2)
D_min = d_center - int(cluster_depth/2)
cluster = self.unique_random(ncells, height=self.height, length=l_center+int(cluster_width/2),
depth=d_center+int(cluster_depth/2), d_min=D_min,
h_min=self.height-cluster_height, l_min=L_min)
Strains_M, Indx = self.place_cells(cluster, encoding, ncells, nstrains, biomass_init=biomass_init,
place_only=True, strainID=strain, start_lists=start_L)
else:
#Other strains inoculation
if self.dimensionality == 2: # 2D
colonie = self.unique_random(ncells, height=max_depth_other, length=self.length, memory=memory)
memory.extend(colonie)
Strains_M, Indx = self.place_cells(colonie, encoding, ncells, nstrains, biomass_init=biomass_init,
place_only=True, strainID=strain, start_lists=start_L)
else: # 3D
colonie = self.unique_random(ncells, height=max_depth_other, length=self.length,
depth=self.depth,
memory=memory)
memory.extend(colonie)
Strains_M, Indx = self.place_cells(colonie, encoding, ncells, nstrains, biomass_init=biomass_init,
place_only=True, strainID=strain, start_lists=start_L)
return Strains_M, Indx
def separate_colonies_inoculation(self, col_height, col_width, ncells, nstrains, col_depth=None, biomass_init=10):
"""
Initialization method that creates a cluster for each strain.
Parameters
----------
col_height : int
Height of the colony.
col_width : int
Width of the colony.
ncells : int
Number of cells to place for each strain (all strains start with
the same population size).
nstrains : int
Number of strains in the simulation.
col_depth : int, optional
Depth of the colony. The default is None.
biomass_init : int, optional
Biomass quantity for a single cell. The default is 10.
Returns
-------
Strains_M : np.array, dtype = int
Strains Matrix (Matrix of main interest to visualize the simulation).
Indx : List of tuples
List of positions of every cell placed.
"""
assert col_height <= self.height, 'Colony height is too high to be placed.'
if self.dimensionality == 2:
assert ncells <= col_height*col_width, 'Too much cells to place for the indicated colony size.'
else:
assert col_depth != None, 'You must specify col_depth.'
assert ncells <= col_height*col_width*col_depth, 'Too much cells to place for the indicated colony size.'
encoding = [i*2+3 for i in range((nstrains))] # Strain IDs
self.Biomass_init = biomass_init
H_min = self.height-col_height # Because 0 is the surface
if self.dimensionality == 3:
D_min = int(self.depth/2 - col_depth/2)
assert D_min > 0, 'col_depth is too big to be placed.'
inter_col = int((self.length - nstrains*col_width)/(nstrains + 1))
assert inter_col > 0, 'Colony width is too big for all colonies to be placed.'
start_L =True
end_of_col = 0
for i,strain in enumerate(encoding):
if i>0:
start_L =False
if i==0:
L_min = inter_col
else:
L_min = end_of_col+ inter_col
end_of_col = col_width + L_min
if self.dimensionality == 2: # 2D
if end_of_col < self.length:
colonie = self.unique_random(ncells, height=self.height, length=end_of_col,
h_min=H_min, l_min=L_min)
else:
colonie = self.unique_random(ncells, height=self.height, length=self.length,
h_min=H_min, l_min=L_min)
Strains_M, Indx = self.place_cells(colonie, encoding, ncells, nstrains, biomass_init=biomass_init,
place_only=True, strainID=strain, start_lists=start_L)
else: # 3D
if end_of_col < self.length:
colonie = self.unique_random(ncells, height=self.height, length=end_of_col,
depth=D_min+col_depth,
h_min=H_min, l_min=L_min, d_min=D_min)
else:
colonie = self.unique_random(ncells, height=self.height, length=self.length,
depth=D_min+col_depth,
h_min=H_min, l_min=L_min, d_min=D_min)
Strains_M, Indx = self.place_cells(colonie, encoding, ncells, nstrains, biomass_init=biomass_init,
place_only=True, strainID=strain, start_lists=start_L)
return Strains_M, Indx
def floor_inoculation(self, thickness, ncells, nstrains, biomass_init=10):
"""
Initialization method that creates a cell floor containing all strains.
Parameters
----------
thickness : int
thickness of the floor.
ncells : int
Number of cells to place for each strain (all strains start with
the same population size).
nstrains : int
Number of strains in the simulation.
biomass_init : int, optional
Biomass quantity for a single cell. The default is 10.
Returns
-------
Strains_M : np.array, dtype = int
Strains Matrix (Matrix of main interest to visualize the simulation).
Indx : List of tuples
List of positions of every cell placed.
"""
assert ncells*nstrains <= thickness*self.length, 'Too much cells to place for the indicated thickness.'
encoding = [i*2+3 for i in range((nstrains))] # Strain IDs
self.Biomass_init = biomass_init
if self.dimensionality == 2: # 2D
indices = self.unique_random(ncells*nstrains, height=self.height, length=self.length,
h_min=self.height-thickness)
else: # 3D
indices = self.unique_random(ncells*nstrains, height=self.height, length=self.length,
depth=self.depth,
h_min=self.height-thickness)
Strains_M, Indx = self.place_cells(indices, encoding, ncells, nstrains, biomass_init=biomass_init)
return Strains_M, Indx
def surface_inoculation(self, thickness, ncells, nstrains, biomass_init=10):
"""
Initialization method that places all cells close to the surface.
Parameters
----------
thickness : int
thickness of the floor.
ncells : int
Number of cells to place for each strain (all strains start with
the same population size).
nstrains : int
Number of strains in the simulation.
biomass_init : int, optional
Biomass quantity for a single cell. The default is 10.
Returns
-------
Strains_M : np.array, dtype = int
Strains Matrix (Matrix of main interest to visualize the simulation).
Indx : List of tuples
List of positions of every cell placed.
"""
assert ncells*nstrains <= thickness*self.length, 'Too much cells to place for the indicated thickness.'
encoding = [i*2+3 for i in range((nstrains))] # Strain IDs
self.Biomass_init = biomass_init
if self.dimensionality == 2: # 2D
indices = self.unique_random(ncells*nstrains, height=thickness, length=self.length)
else: # 3D
indices = self.unique_random(ncells*nstrains, height=thickness, length=self.length,
depth=self.depth)
Strains_M, Indx = self.place_cells(indices, encoding, ncells, nstrains, biomass_init=biomass_init)
return Strains_M, Indx
def random_inoculate(self, ncells, nstrains, biomass_init=10):
"""
Initialization method that randomly places all cells across
the entire space.
Parameters
----------
thickness : int
thickness of the floor.
ncells : int
Number of cells to place for each strain (all strains start with
the same population size).
nstrains : int
Number of strains in the simulation.
biomass_init : int, optional
Biomass quantity for a single cell. The default is 10.
Returns
-------
Strains_M : np.array, dtype = int
Strains Matrix (Matrix of main interest to visualize the simulation).
Indx : List of tuples
List of positions of every cell placed.
"""
encoding = [i*2+3 for i in range((nstrains))] # Strain IDs
self.Biomass_init = biomass_init
if self.dimensionality == 2: # 2D
indices = self.unique_random(ncells*nstrains, height=self.height, length=self.length)
else: # 3D
indices = self.unique_random(ncells*nstrains, height=self.height, length=self.length, depth=self.depth)
Strains_M, Indx = self.place_cells(indices, encoding, ncells, nstrains, biomass_init=biomass_init)
return Strains_M, Indx
# =========================================================================
# NEIGHBORHOOD
# =========================================================================
def neighborhood(self, neighborhood='VonNeumman', radius=1, dead_mode=False, all_mode=False):
"""
Generates the list of neighbors positions for each cell.
Parameters
----------
neighborhood : str, optional
Type of neighborhood to use. The default is 'VonNeumman'.
radius : int, optional
Radius of the neighborhood. The default is 1.
dead_mode : boolean, optional
Whether to compute the neighborhood of dead or living cells.
The default is False.
all_mode : boolean, optional
Whether to compute the neighborhood for all cells.
The default is False.
Returns
-------
Near : List of lists
List containing a list of all neighbors positions for each cell.
"""
assert 'cells_pos' in self.__dict__, "Medium not yet inoculated, check the orthograph of 'init_strategy' parameter"
Near = []
if dead_mode:
positions_to_look = self.dead_pos
elif all_mode:
positions_to_look = []
if self.dimensionality == 3:
for i in range(self.height):
for j in range(self.length):
for k in range(self.depth):
positions_to_look.append((i,j,k))
else:
for i in range(self.height):
for j in range(self.length):
positions_to_look.append((i,j))
else:
positions_to_look = self.cells_pos
if neighborhood=='VonNeumman':
for cell in positions_to_look:
if self.dimensionality == 2:
i, j = cell
L = []
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
if abs(di) + abs(dj) <= radius:
ni, nj = i + di, j + dj
if 0 <= ni < self.height and 0 <= nj < self.length:
L.append((ni, nj))
else:
i, j, k = cell
L = []
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
for dk in range(-radius, radius + 1):
if abs(di) + abs(dj) + abs(dk) <= radius:
ni, nj, nk = i + di, j + dj, k + dk
if 0 <= ni < self.height and 0 <= nj < self.length and 0 <= nk < self.depth:
L.append((ni, nj, nk))
Near.append(L)
if neighborhood=='Moore':
for cell in positions_to_look:
if self.dimensionality == 2:
i, j = cell
L = []
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
ni, nj = i + di, j + dj
if 0 <= ni < self.height and 0 <= nj < self.length:
L.append((ni, nj))
else:
i, j, k = cell
L = []
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
for dk in range(-radius, radius + 1):
ni, nj, nk = i + di, j + dj, k + dk
if 0 <= ni < self.height and 0 <= nj < self.length and 0 <= nk < self.depth:
L.append((ni, nj, nk))
Near.append(L)
if neighborhood=='halfVN':
for cell in positions_to_look:
if self.dimensionality == 2:
i, j = cell
L = []
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
if abs(di) + abs(dj) <= radius:
ni, nj = i + di, j + dj
if 0 <= ni < self.height and 0 <= nj < self.length:
L.append((ni, nj))
else:
i, j, k = cell
L = []
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
for dk in range(-radius, radius + 1):
if abs(di) + abs(dj) + abs(dk) <= radius:
ni, nj, nk = i + di, j + dj, k + dk
if 0 <= ni < self.height and 0 <= nj < self.length and 0 <= nk < self.depth:
L.append((ni, nj, nk))
for i in range(int(len(L)/2)):
element = random.sample(L, 1)[0]
L.remove(element)
Near.append(L)
if dead_mode:
return Near
elif all_mode:
return Near, positions_to_look
else:
self.neighbors = deepcopy(Near)
return Near
# =========================================================================
# NUTRIENT and ToxinS EVOLUTION
# =========================================================================
def calculate_diffusion(self, Doxy, Dnitro, Dcar):
"""
Computes the diffusion of nutrients and Toxins.
Based on the equations found in reference [1]
(Approximation of the spatial-temporal distribution of nutrient
concentrations based on Fick's Law).
Parameters
----------
Doxy : float
Diffusion constant for Oxygen.
Dnitro : float
Diffusion constant for Nitrogen.
Dcar : float
Diffusion constant for Carbon.
Returns
-------
diff_O : np.array, dtype = float
New state of the diffusion Matrix.
diff_N : np.array, dtype = float
New state of the diffusion Matrix.
diff_C : np.array, dtype = float
New state of the diffusion Matrix.
diff_TOX : np.array, dtype = float
New state of the diffusion Matrix.
"""
# For the chosen diffusion estimation equation, neighborhood is fixed
All_neighbors, all_pos = self.neighborhood(neighborhood='VonNeumman', radius=1, all_mode=True)
if self.dimensionality == 2:
i, j = zip(*all_pos)
else:
i, j, k = zip(*all_pos)
n_tox = len(self.TOX_Matrices)
diff_O = self.O_Matrix.copy()
diff_N = self.N_Matrix.copy()
diff_C = self.C_Matrix.copy()
diff_TOX = [self.TOX_Matrices[i].copy() for i in range(n_tox)]
# To have a random order of computation we shuffle cell's positions
# Shuffle cells_pos and neighbors in unison
combined = list(zip(all_pos, All_neighbors))
random.shuffle(combined)