-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCAMpy.py
More file actions
1522 lines (1250 loc) · 56.9 KB
/
TCAMpy.py
File metadata and controls
1522 lines (1250 loc) · 56.9 KB
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
import io
import time
import random
import hashlib
import numpy as np
import pandas as pd
import altair as alt
import streamlit as st
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from sklearn.metrics import r2_score, mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from streamlit_javascript import st_javascript
from scipy.ndimage import gaussian_filter
from scipy.stats import skew, kurtosis
from functools import wraps
from tqdm import tqdm
class TModel:
"""
Class for a cellular automata, modeling tumor growth.
Parameters:
cycles (int): duration of the model given in hours
side (int): the length of the side of field (10um)
pmax (int): maximum proliferation potential of RTC
PA (int): chance for apoptosis of RTC (in percent)
CCT (int): cell cycle time of cells given in hours
Dt (float): time step of the model given in days
PS (int): STC-STC division chance (in percent)
mu (int): migration capacity of cancer cells
I (int): strength of the immune cells (1-5)
M (int): tumor mutation chance (in percent)
"""
def __init__(self, cycles, side, pmax, PA, CCT, Dt, PS, mu, I, M):
# Parameters
self.cycles = cycles
self.side = side
self.pmax = pmax
self.CCT = CCT
self.Dt = Dt
self.mu = mu
self.I = I
self.M = M
# Single model data
self.stc_number = []
self.rtc_number = []
self.wbc_number = []
self.cancer = []
self.immune = []
self.mutate = []
self.mutmap = []
self.images = []
# Multiple models data
self.stats = []
self.runs = []
# Chances
self.PP = 24 * Dt/CCT * 100
self.PM = 100 * mu/24
self.PA = PA
self.PS = PS
# Immune Data
self.it_ratio = []
self.kill_day = []
# ---------------------------------------------------------------------
def init_state(self):
"""
Creates the initial state with one STC in the middle.
Creates the field for immune cells and mutations too.
"""
self.cancer = np.zeros((self.side, self.side))
self.immune = np.zeros((self.side, self.side))
self.mutate = np.zeros((self.side, self.side))
self.mutmap = np.zeros((self.side, self.side))
self.mod_cell(self.side//2, self.side//2, self.pmax+1)
# ---------------------------------------------------------------------
def find_tumor_cells(self):
"""
Saves the coordinates of tumor cells to self.tumor_cells.
"""
# Tumor cell coords randomized
coords = np.argwhere(self.cancer > 0)
np.random.shuffle(coords)
self.tumor_cells = coords
# ---------------------------------------------------------------------
def count_tumor_cells(self):
"""
Saves the number of STCs/RTCs to self.stc_number/self.rtc_number.
"""
# Count RTC and STC
stc_count = np.count_nonzero(self.cancer == self.pmax + 1)
rtc_count = len(self.tumor_cells) - stc_count
# Save the current number
self.stc_number.append(stc_count)
self.rtc_number.append(rtc_count)
# ---------------------------------------------------------------------
def get_neighbours(self, x, y, neighbour_type):
"""
Returns the neighboring coordinates of a given cell in a 2D NumPy matrix.
Parameters:
x, y (int): representing the coordinates of the cell
neighbour_type (int): type of neighboring cells (1-5)
Returns:
list: a list with the coords of the neighbouring cells
"""
r_start = max(1, x - 1)
r_end = min(self.side - 1, x + 2)
c_start = max(1, y - 1)
c_end = min(self.side - 1, y + 2)
# Extract views of the field and immune grids
f_view = self.cancer[r_start:r_end, c_start:c_end]
i_view = self.immune[r_start:r_end, c_start:c_end]
match neighbour_type:
case 1: # Empty
mask = (f_view == 0) & (i_view == 0)
case 2: # Tumor
mask = f_view > 0
case 3: # Immune
mask = i_view > 0
case 4: # Any Cell
mask = (f_view > 0) | (i_view > 0)
case 5: # Not Immune
mask = i_view == 0
matches = np.argwhere(mask)
matches += [r_start, c_start]
is_center = (matches[:, 0] == x) & (matches[:, 1] == y)
return matches[~is_center].tolist()
# ---------------------------------------------------------------------
def cell_step(self, x, y, step_type):
"""
The function that makes a single cell do one of the following actions:
prolif STC - STC, prolif STC - RTC, prolif RTC - RTC, migration (1-4).
New mutations can appear every time a cell proliferates with M chance.
Parameters:
x, y (int): representing the coordinates of the cell
step_type (int): type of division or migration (1-4)
"""
# Choose random target position
free_nb = self.get_neighbours(x, y, 1)
nx, ny = free_nb[random.randint(1,len(free_nb)) - 1]
match step_type:
case 1:
# Proliferation STC -> STC + STC
self.cancer[nx, ny] = self.pmax+1
case 2:
# Proliferation STC -> STC + RTC
self.cancer[nx, ny] = self.pmax
case 3:
# Proliferation RTC -> RTC + RTC
self.cancer[x, y] -= 1
self.cancer[nx, ny] = self.cancer[x, y]
case 4:
# Migration
self.cancer[nx, ny] = self.cancer[x, y]
self.cancer[x, y] = 0
if step_type < 4 and self.cancer[x, y] == 0:
self.mutate[x, y] = 0
elif step_type < 4:
# Inherit mother's mutation
self.mutate[nx, ny] = self.mutate[x, y]
# Chance of a new mutation
if self.M >= random.randint(1, 100):
mut = random.choice([-1,1])
self.mutate[nx, ny] = np.clip(self.mutate[nx, ny]+mut, -3, 3)
# Mutation influences pp value
if step_type != 1:
self.cancer[nx, ny] = np.clip(self.cancer[nx, ny]+mut, 1, self.pmax)
self.mutmap[nx, ny] = self.mutate[nx, ny]
else:
self.mutate[nx, ny] = self.mutate[x, y]
self.mutmap[nx, ny] = self.mutate[x, y]
self.mutate[x, y] = 0
# ---------------------------------------------------------------------
def tumor_action(self):
"""
This is the function that decides what action a cell will do.
Either kills the cell or calls the 'cell_step' function.
This function goes through every single cell in the field.
"""
for cell in self.tumor_cells:
x, y = cell
is_stc = (self.cancer[x, y] == self.pmax + 1)
# Probabilities
probs = np.array([self.PA, self.PP, self.PM, 0], dtype=float)
if is_stc:
probs[0] = 0
if not self.get_neighbours(x, y, 1):
probs[1:3] = 0
probs = self.mutate_probs(probs, x, y)
probs /= probs.sum()
# Choose action
choice = np.random.choice(4, p=probs)
if choice == 0: # apoptosis
self.cancer[x, y] = self.mutate[x, y] = 0
elif choice == 1: # proliferation
if is_stc and np.random.rand() < self.PS/100:
self.cell_step(x, y, 1) # STC-STC division
elif is_stc:
self.cell_step(x, y, 2) # STC-RTC division
else:
self.cell_step(x, y, 3) # RTC-RTC division
elif choice == 2: # migration
self.cell_step(x, y, 4)
# ---------------------------------------------------------------------
def mutate_probs(self, chances, x, y):
"""
The function that changes the cell action chances
based on the current mutation status of the cell.
Parameters:
chances (list of float): the base action chances
x, y (int): representing coordinates of the cell
"""
mut_state = self.mutate[x, y]/2
if mut_state > 0:
mut_state += 1
chances[0] = chances[0]/mut_state # Decreased chance for apoptosis
chances[1] = chances[1]*mut_state # Increased proliferation chance
elif mut_state < 0:
mut_state -= 1
chances[0] = chances[0]*abs(mut_state) # Increased chance for apoptosis
chances[1] = chances[1]/abs(mut_state) # Decreased proliferation chance
if chances.sum() <= 100:
chances[3] = 100 - chances.sum()
return chances
# ---------------------------------------------------------------------
def immune_response(self, offset = 10, alpha = 0.002, it_targ = 0.1, infil = 0.3):
"""
The function that simulates immune cells.
Spawns, moves and activates immune cells.
Parameters:
offset (int): distance of spawnpoints ("frame") from the tumor
alpha (float): controls strength (slope) of immune exhaustion
it_targ (float): desired mean immune/tumor ratio during simulation
infil (float): "searching/infiltrating" threshold for wbcs (0-1)
"""
# Current tumor cell locations
self.find_tumor_cells()
tumor_size = len(self.tumor_cells)
if tumor_size == 0:
self.immune = np.maximum(0, self.immune - 1)
self.wbc_number.append(np.count_nonzero(self.immune))
return
# Immune spawnpoints = "frame" around tumor
min_coords = self.tumor_cells.min(axis=0) - offset
max_coords = self.tumor_cells.max(axis=0) + offset
x1, y1 = np.clip(min_coords, 1, self.side - 2)
x2, y2 = np.clip(max_coords, 1, self.side - 2)
t = np.column_stack((np.full(y2-y1+1, x1), np.arange(y1, y2+1)))
b = np.column_stack((np.full(y2-y1+1, x2), np.arange(y1, y2+1)))
l = np.column_stack((np.arange(x1+1, x2), np.full(x2-x1-1, y1)))
r = np.column_stack((np.arange(x1+1, x2), np.full(x2-x1-1, y2)))
self.spawnpoints = np.concatenate([t, b, l, r])
# Immune exhaustion = time-dependent decline
IE = max(1.0 / (1.0 + alpha * self.cycles), 0.2)
# Saturating spawn (sigmoid-like), delayed onset
spawn = self.I * (tumor_size / (tumor_size + self.I * 100)) * IE
current_wbc_count = np.count_nonzero(self.immune)
it_ratio = current_wbc_count / tumor_size
if it_ratio <= it_targ:
# Choose all spawnpoints
spawn_mask = np.random.random(len(self.spawnpoints)) < (spawn / 50)
potential_spawns = self.spawnpoints[spawn_mask]
if len(potential_spawns) > 0:
# Filter for empty slots
px, py = potential_spawns[:, 0], potential_spawns[:, 1]
valid = (self.cancer[px, py] == 0) & (self.immune[px, py] == 0)
final_coords = potential_spawns[valid]
if len(final_coords) > 0:
min_life, max_life = min(24, (self.I-1)*168), (self.I+1)*168
self.immune[final_coords[:, 0], final_coords[:, 1]] = np.random.randint(
min_life, max_life, size=len(final_coords))
# Chemoattractant map for tumor density
self.chemo = (self.cancer > 0).astype(float)
self.chemo = gaussian_filter(self.chemo, sigma=5)
self.chemo = self.chemo / np.max(self.chemo)
# Immune action
coords = np.argwhere(self.immune > 0)
kills_per_hour = 0
self.immune_cells = coords
# Temporary immune grid
new_immune = np.zeros_like(self.immune)
for (x, y) in self.immune_cells:
strength = self.immune[x, y]
if strength <= 0:
continue
# Kill prob on contact: (0.15 - 0.3, if I=5, IE = 0)
tumor_nb = self.get_neighbours(x, y, 2)
if tumor_nb:
tx, ty = random.choice(tumor_nb)
kill = (0.05*self.I) * np.exp(-0.25*self.mutate[tx,ty]) * IE
kill = min(kill, 0.3)
if np.random.rand() < kill:
self.cancer[tx, ty] = 0
self.mutate[tx, ty] = 0
kills_per_hour += 1
# # Multiple moves/cycle as immune cells are faster
moves = int(1 + self.I * (1 - self.chemo[x, y]))
for _ in range(moves):
free_nb = self.get_neighbours(x, y, 1)
if not free_nb:
strength -= 1
break
# Biased movement towards tumor density (chemotaxis)
t_dens = [self.chemo[i, j] for (i, j) in free_nb]
if sum(t_dens) > 0:
weights = np.array(t_dens) / sum(t_dens)
tx, ty = free_nb[np.random.choice(len(free_nb), p=weights)]
else:
tx, ty = random.choice(free_nb)
x, y = tx, ty
strength -= 1
if strength > 0:
new_immune[x, y] = strength
self.immune = new_immune
# Save number of immune cells
immune_size = len(self.immune_cells)
self.wbc_number.append(immune_size)
self.it_ratio.append(immune_size / tumor_size)
# Infiltrating immune cells
wbc_infil = sum(1 for (x,y) in self.immune_cells if self.chemo[x,y] >= infil)
if immune_size > 0:
self.kill_day.append(kills_per_hour / max(1, wbc_infil) * 24)
# ---------------------------------------------------------------------
def animate(self, mode):
"""
Creates and returns animation of the growth.
Parameters:
mode (int): create figure, save frame or display animation. (1-3)
Returns:
ArtistAnimation: the animation of the growth (optional)
"""
if mode == 1:
# Create the figure
self.fig, self.ax = plt.subplots()
self.ax.imshow(self.cancer)
self.ax.set_title(str(self.cycles)+ " hour cell growth")
self.ax.set_xlabel(str(self.side*10) + " micrometers")
self.ax.set_ylabel(str(self.side*10) + " micrometers")
elif mode == 2:
# Save the current frame
growth = self.ax.imshow(self.cancer, animated=True)
immune_coords = np.argwhere(self.immune > 0)
immune = self.ax.scatter(immune_coords[:,1], immune_coords[:,0], c='blue', s=10)
self.images.append([growth, immune])
elif mode == 3:
# Display the animation
return animation.ArtistAnimation(self.fig, self.images, interval=50, blit=True)
# ---------------------------------------------------------------------
def save_field_to_excel(self, file_name):
"""
Saves the current state of self.cancer to an excel file.
Parameters:
file_name (str): name of the excel file
"""
pd.DataFrame(self.cancer).to_excel(file_name, index=False)
# ---------------------------------------------------------------------
def mod_cell(self, x, y, value):
"""
Modifies cell value. (Create initial state before this!)
Parameters:
x, y (int): representing coordinates of the cell
value (int): the new value at the given position
"""
self.cancer[y][x] = value
# ---------------------------------------------------------------------
def get_prolif_potentials(self):
"""
Returns a dictionary of proliferation potential numbers.
Returns:
dict: a dictionary of the proliferation potentials
"""
nonzero_field = np.array(self.cancer)[np.array(self.cancer) > 0]
unique, counts = np.unique(nonzero_field, return_counts=True)
prolif_potents = {}
for i in range(1, self.pmax + 2):
prolif_potents[i] = 0
for val, count in zip(unique, counts):
prolif_potents[int(val)] = count
return prolif_potents
# ---------------------------------------------------------------------
def get_statistics(self):
"""
Returns various statistical properties of the model.
Returns:
dict: a dictionary of the statistical properties
"""
nonzero_field = self.cancer[self.cancer > 0]
# Statistics
if nonzero_field.size != 0:
stats = {
"Min": nonzero_field.min(),
"Max": nonzero_field.max(),
"Mean": nonzero_field.mean(),
"Std": nonzero_field.std(),
"Median": np.median(nonzero_field),
"Skew": skew(nonzero_field.ravel()),
"Kurtosis": kurtosis(nonzero_field.ravel()),
"Final STC": self.stc_number[self.cycles-1],
"Final RTC": self.rtc_number[self.cycles-1],
"Final WBC": self.wbc_number[self.cycles-1],
"Tumor Size": nonzero_field.size,
"Confluence": nonzero_field.size/self.cancer.size*100,
}
if self.I > 0:
stats.update({
"Mean I/T" : sum(self.it_ratio)/len(self.it_ratio),
"Mean k/d" : sum(self.kill_day)/len(self.kill_day)
})
# Proliferation potentials
stats.update(self.get_prolif_potentials())
# Cell Numbers
checkpoints = np.linspace(0, self.cycles - 1, int(self.cycles/10) + 1, dtype=int)
for idx in checkpoints:
hour = (idx + 1)
stats[f"{hour}h_STC"] = self.stc_number[idx]
stats[f"{hour}h_RTC"] = self.rtc_number[idx]
stats[f"{hour}h_WBC"] = self.wbc_number[idx]
else: stats = {
"Tumor Size": 0,
"Confluence": 0,
"Status": "Extinct"
}
return stats
# ---------------------------------------------------------------------
def save_statistics(self, file_name):
"""
Saves various statistical properties of the model to an excel file.
Parameters:
file_name (str): name of the excel file
"""
stats_dict = self.get_statistics()
df = pd.DataFrame([stats_dict])
df.to_excel(file_name, index=False)
# ---------------------------------------------------------------------
def measure_runtime(func):
# Decorator to measure completion time
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
runtime = end_time - start_time
print("Model completion time (s): " + str(runtime))
return result
return wrapper
# ---------------------------------------------------------------------
@measure_runtime
def run_model(self, plot, animate, stats):
"""
The function that runs a single entire simulation.
For animation matplotlib backend cannot be inline!
Parameters:
plot (bool): set to true to display the plots of the model
animate (bool): set to true to enable matplotlib animation
stats (bool): set to true to print statistics of the model
"""
# Create initial state
if len(self.cancer) == 0: self.init_state()
self.find_tumor_cells()
if len(self.immune) == 0:
self.immune = np.zeros((self.side, self.side))
if len(self.mutate) == 0:
self.mutate = np.zeros((self.side, self.side))
self.mutmap = np.zeros((self.side, self.side))
self.stc_number = []
self.rtc_number = []
self.wbc_number = []
if animate: self.animate(1)
# Growth loop
for c in tqdm(range(self.cycles), desc="Running simulation..."):
self.tumor_action()
self.immune_response()
self.find_tumor_cells()
self.count_tumor_cells()
if animate: self.animate(2)
# Store the results
self.store_model()
# Output settings
if plot: self.plot_run(len(self.runs))
if animate: self.ani = self.animate(3)
if stats:
df = pd.DataFrame(self.stats)
base_cols = self.separate_columns(df)[0]
print(df[base_cols])
# ---------------------------------------------------------------------
@measure_runtime
def run_multimodel(self, count, init_field, plot, stats):
"""
Runs the model multiple times and returns a DataFrame of statistics.
Parameters:
count (int): number of times to run the simulation
init_field (np.array): custom initial state of field/run
plot (bool): set to true to display the plots of the model
stats (bool): set to true to print statistics of the model
Returns:
pd.DataFrame: collected statistics from each run
"""
stats = []
for i in range(count):
self.cancer = init_field.copy()
self.immune = []
self.mutate = []
self.mutmap = []
self.run_model(plot = False, animate = False, stats = False)
stats.append(self.get_statistics())
all_stats = pd.DataFrame(stats)
if plot:
self.plot_averages(all_stats)
if stats:
df = pd.DataFrame(self.stats)
base_cols = self.separate_columns(df)[0]
print(df[base_cols])
return all_stats
# ---------------------------------------------------------------------
def store_model(self):
"""
Stores the results of the previous model executions.
"""
result = {}
result["immune"] = self.immune
result["mutate"] = self.mutate
result["mutmap"] = self.mutmap
result["cancer"] = self.cancer
result["stc"] = self.stc_number
result["rtc"] = self.rtc_number
result["wbc"] = self.wbc_number
result["pp"] = self.get_prolif_potentials().values()
# Stores data for plotting
self.runs.append(result)
# Stores data for statistics
self.stats.append(self.get_statistics())
# ---------------------------------------------------------------------
def separate_columns(self, data):
"""
Separates the statistics DataFrame columns into logical groups:
base stats, STC, RTC, WBC counts, and proliferation potentials.
Parameters:
data (pd.DataFrame): Your data in a pandas dataframe format
Returns:
tuple of list[str]: A tuple containing 5 lists of column names:
- base: Columns with general statistical properties
- stc: Columns with STC counts at each time point
- rtc: Columns with RTC counts at each time point
- wbc: Columns with WBC counts at each time point
- pp: Columns for proliferation potential values
"""
base = [col for col in data.columns if not str(col).isdigit()
and "_STC" not in str(col)
and "_RTC" not in str(col)
and "_WBC" not in str(col)]
stc = sorted([col for col in data.columns if "_STC" in str(col)],
key=lambda x: int(str(x).split("h")[0]))
rtc = sorted([col for col in data.columns if "_RTC" in str(col)],
key=lambda x: int(str(x).split("h")[0]))
wbc = sorted([col for col in data.columns if "_WBC" in str(col)],
key=lambda x: int(str(x).split("h")[0]))
pp = sorted([col for col in data.columns if isinstance(col, int)])
return base, stc, rtc, wbc, pp
# ---------------------------------------------------------------------
def plot_run(self, run):
"""
Creates growth and cell number plots, proliferation potential histograms.
Paramteres:
run (int): which model execution to plot
Returns:
matplotlib.figure.Figure: the generated plots of the specific run
"""
# Create the figue and axis
fig, axs = plt.subplots(2, 2, figsize=(14,14))
tumor = axs[0, 0].imshow(self.runs[run-1]["cancer"], vmin=0, vmax=self.pmax+1)
fig.colorbar(tumor, ax=axs[0, 0])
immune_coords = np.argwhere(self.runs[run-1]["immune"] > 0)
axs[0, 0].scatter(immune_coords[:,1], immune_coords[:,0],
c='blue', marker='v', s=10)
axs[0, 1].plot(self.runs[run-1]["stc"], 'C1', label='STC')
axs[0, 1].plot(self.runs[run-1]["rtc"], 'C2', label='RTC')
axs[0, 1].plot(self.runs[run-1]["wbc"], 'C3', label='WBC')
axs[0, 1].legend()
mutmap = axs[1, 0].imshow(self.runs[run-1]["mutmap"],
cmap="RdBu_r", vmin=-3, vmax=3, interpolation="bicubic")
fig.colorbar(mutmap, ax=axs[1, 0])
axs[1, 1].bar(range(1, self.pmax + 2), self.runs[run-1]["pp"], edgecolor='black')
# Titles/labels of the plots
titles = [str(self.cycles)+ "h cell growth", "Cell count",
"Mutation history", "Final PP values"]
labs_x = [str(self.side*10) + " um", "Time (h)",
str(self.side*10) + " um", "Proliferation potentials"]
labs_y = [str(self.side*10) + " um", "Cell numbers",
str(self.side*10) + " um", "Number of appearance"]
fig.suptitle("Simulation " + str(run) + " Results", fontsize = 16)
for i, ax in enumerate(axs.flat):
ax.set_title(titles[i])
ax.set_xlabel(labs_x[i])
ax.set_ylabel(labs_y[i])
# ---------------------------------------------------------------------
def plot_averages(self, data):
"""
The function that plots the averages of multiple model results.
Works with the results of the 'run_multimodel' function.
Parameters:
data (pd.DataFrame): Your data in a pandas dataframe format
Returns:
matplotlib.figure.Figure: The plots of the averages with SD values
"""
base_cols, stc_cols, rtc_cols, wbc_cols, pp_cols = self.separate_columns(data)
avg_stc = data[stc_cols].mean()
std_stc = data[stc_cols].std()
avg_rtc = data[rtc_cols].mean()
std_rtc = data[rtc_cols].std()
avg_wbc = data[wbc_cols].mean()
std_wbc = data[wbc_cols].std()
avg_pp = data[pp_cols].mean()
std_pp = data[pp_cols].std()
fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(14, 5))
timepoints = np.linspace(0, self.cycles - 1, int(self.cycles/10) + 1)
ax1.plot(timepoints, avg_stc, label='STC', color='C1')
ax1.fill_between(timepoints, avg_stc - std_stc, avg_stc + std_stc,
color='C1', alpha=0.3)
ax1.plot(timepoints, avg_rtc, label='RTC', color='C2')
ax1.fill_between(timepoints, avg_rtc - std_rtc, avg_rtc + std_rtc,
color='C2', alpha=0.3)
ax1.plot(timepoints, avg_wbc, label='WBC', color='C3')
ax1.fill_between(timepoints, avg_wbc - std_wbc, avg_wbc + std_wbc,
color='C3', alpha=0.3)
ax1.set_title("Average Tumor Cell Count")
ax1.set_xlabel("Model Time (hours)")
ax1.set_ylabel("Number of Cells")
ax1.legend()
ax2.bar(pp_cols, avg_pp, yerr=std_pp, capsize=5, edgecolor='black')
ax2.set_title("Average Proliferation Potential Distribution")
ax2.set_xlabel("Proliferation Potential")
ax2.set_ylabel("Average Count")
fig.suptitle("Averages of " + str(len(self.stats)) + " Models", fontsize = 16)
plt.tight_layout()
class TDashboard:
"""
Class for a Streamlit dashboard providing a GUI for the model.
Parameters:
model (TModel): The created model you want a dashboard for
"""
def __init__(self, model):
self.model = model
# ---------------------------------------------------------------------
def run_dashboard(self):
"""
The function that creates the entire streamlit dashboard for the model.
"""
st.set_page_config(layout="wide")
st.markdown("<h1 style='text-align: center;'>TCAMpy</h1>", unsafe_allow_html=True)
self.screen_width = st_javascript("window.innerWidth", key="screen_width")
tab1, tab2 = st.tabs(["SIMULATION", "MACHINE LEARNING"])
with tab1:
self.columns = [4, 1, 12]
self.col1, _, self.col3 = st.columns(self.columns)
with self.col1:
self._initialize()
self._modify_cell()
self._execute_model()
with self.col3:
self._visualize_run("Last Simulation", len(self.model.runs))
self._show_statistics()
self._reset_save_stats()
with tab2:
col1, col2 = st.columns(2)
with col1:
self._simdata_generator()
with col2:
self._train_and_predict()
# ---------------------------------------------------------------------
def print_title(self, title):
"""
The function that prints text as a title on the dashboard.
Parameters:
title (string): The text to print
"""
st.markdown(
f"<h2 style='text-align: center;'>{title}</h2>",
unsafe_allow_html=True
)
# ---------------------------------------------------------------------
def get_plot_height(self, col, scaler):
"""
The function that calculates the height of plots
based on screen width, column width and a scaler.
Parameters:
col (int): main column number
scalar (float): scaler for column width
"""
screen_width = st.session_state.get("screen_width")
col_width_px = screen_width * (self.columns[col-1] / sum(self.columns))
return int(col_width_px * scaler)
# ---------------------------------------------------------------------
def _initialize(self):
"""
The function that sets the parameters and initializes the model.
"""
self.print_title("Model Parameters")
self.model.cycles = st.slider("Model Duration (hours)", 50, 5000, value=self.model.cycles)
self.model.side = st.slider("Field Side Length (10um)", 10, 200, value=self.model.side)
self.model.pmax = st.slider("Max Proliferation Potential", 1, 20, value=self.model.pmax)
self.model.PA = st.slider("Apoptosis Chance (RTC) (%)", 0, 100, value=self.model.PA)
self.model.CCT = st.slider("Cell Cycle Time (hours)", 1, 48, value=self.model.CCT)
self.model.Dt = st.slider("Time Step (days)", 0.01, 1.0, value=self.model.Dt, step=0.01)
self.model.PS = st.slider("STC-STC Division Chance (%)", 0, 100, value=self.model.PS)
self.model.mu = st.slider("Migration Capacity", 0, 10, value=self.model.mu)
self.model.I = st.slider("Immune Strength", 0, 10, value=self.model.I)
self.model.M = st.slider("Mutation Chance", 0, 50, value=self.model.M)
self.model.PP = int(self.model.CCT * self.model.Dt / 24 * 100)
self.model.PM = 100 * self.model.mu / 24
init_config = (
self.model.side, self.model.cycles, self.model.pmax,
self.model.PA, self.model.CCT, self.model.Dt, self.model.PS,
self.model.mu, self.model.I, self.model.M
)
config_hash = hashlib.md5(str(init_config).encode()).hexdigest()
# Storing data for model plotting
if "model_runs" in st.session_state:
self.model.runs = st.session_state.model_runs
# Storing data for model statistics
if "model_stats" in st.session_state:
self.model.stats = st.session_state.model_stats
if (
"initialized" not in st.session_state
or "init_config_hash" not in st.session_state
or st.session_state.init_config_hash != config_hash
):
self.model.init_state()
st.session_state.cancer = self.model.cancer.copy()
st.session_state.immune = self.model.immune.copy()
st.session_state.mutate = self.model.mutate.copy()
st.session_state.mutmap = self.model.mutmap.copy()
st.session_state.initialized = True
st.session_state.init_config_hash = config_hash
# ---------------------------------------------------------------------
def _modify_cell(self):
"""
The function for initial state modification logic.
"""
self.print_title("Initial State")
x_coord = st.number_input("X Coordinate", 0, self.model.side - 1, value=self.model.side // 2)
y_coord = st.number_input("Y Coordinate", 0, self.model.side - 1, value=self.model.side // 2)
cell_value = st.number_input("Cell Value", 0, self.model.pmax + 1, value=self.model.pmax + 1)
plots_height = self.get_plot_height(1, 0.9)
if st.button("Modify Cell"):
self.model.cancer = st.session_state.cancer.copy()
self.model.mod_cell(x_coord, y_coord, cell_value)
st.session_state.cancer = self.model.cancer.copy()
st.success(f"Cell modified at ({x_coord}, {y_coord}) to {cell_value}")
cancer = st.session_state.cancer
heatmap = self._create_heatmap(
plots_height, "Initial state", "viridis",
"PP", 0, self.model.pmax+1, cancer
)
st.altair_chart(heatmap, use_container_width=True)
# ---------------------------------------------------------------------
def _execute_model(self):
"""
The function for model running logic.
"""
self.print_title("Execution")
rep = st.number_input("How many simulations?", 1)
if st.button("Run Model"):
with st.spinner("Running simulations..."):
for i in range(rep):
self.model.cancer = st.session_state.cancer.copy()
self.model.immune = st.session_state.immune.copy()
self.model.mutate = st.session_state.mutate.copy()
self.model.mutmap = st.session_state.mutmap.copy()
self.model.run_model(plot = False, animate=False, stats=False)
st.session_state.model_runs = self.model.runs
st.session_state.model_stats = self.model.stats
# ---------------------------------------------------------------------
def _visualize_run(self, title, run):
"""
The function for the result visualization logic.
Parameters:
title (string): title of the visualization
run (int): which model execution to plot
"""
if "model_runs" not in st.session_state:
st.warning("Simulation results will appear here...")
return
self.print_title(title)
# --- Get latest run ---
latest = self.model.runs[run - 1]
immune = latest["immune"]
mutmap = latest["mutmap"]
cancer = latest["cancer"]
stc = latest["stc"]
rtc = latest["rtc"]
wbc = latest["wbc"]
pp = latest["pp"]
# --- Create charts ---
plots_height = self.get_plot_height(3, 0.4)
tumor_heatmap = self._create_heatmap(
plots_height, "Tumor growth", "viridis",
"PP", 0, self.model.pmax+1, cancer, immune
)
mutation_map = self._create_heatmap(
plots_height, "Mutation history", "redblue",
"M", -3, 3, mutmap
)
bar_chart = self._create_bar_chart(plots_height, list(pp))
line_chart = self._create_line_chart(plots_height, stc, rtc, wbc)
# --- Layout rules ---
col1, col2 = st.columns([4, 5])
with col1:
st.altair_chart(tumor_heatmap, use_container_width=True)
st.altair_chart(mutation_map, use_container_width=True)
with col2:
st.altair_chart(bar_chart, use_container_width=True)
st.altair_chart(line_chart, use_container_width=True)
# ---------------------------------------------------------------------
def _create_heatmap(
self, h, title, cmap, ctitle,