-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper_module.py
More file actions
3340 lines (2982 loc) · 141 KB
/
helper_module.py
File metadata and controls
3340 lines (2982 loc) · 141 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 math
import os
import pickle
import time
import numpy as np
import matplotlib.pyplot as plt
def compute_expected_boundary_pos_from_corners(
BOUNDARY_COORDS,
BOUNDARY_DISP_RATES,
BOUNDARY_DISP_RATES_PARALLEL,
STEPS,
TIME_STEP):
"""
Compute MIN_EXPECTED_BOUNDARY_POS and MAX_EXPECTED_BOUNDARY_POS as the global min/max
across (x,y,z) of the 8 corners after applying boundary motion.
"""
x_max0, x_min0, y_max0, y_min0, z_max0, z_min0 = BOUNDARY_COORDS
R = BOUNDARY_DISP_RATES
P = BOUNDARY_DISP_RATES_PARALLEL
T = STEPS * TIME_STEP
# Face displacement vectors (vx, vy, vz)
# +X: normal -> x, parallel -> y,z
v_plusX = (R[0], P[0], P[1])
v_minusX = (R[1], P[2], P[3])
# +Y: normal -> y, parallel -> x,z
v_plusY = (P[4], R[2], P[5])
v_minusY = (P[6], R[3], P[7])
# +Z: normal -> z, parallel -> x,y
v_plusZ = (P[8], P[9], R[4])
v_minusZ = (P[10], P[11], R[5])
# Helper: sum three face vectors
def add3(a, b, c):
return (a[0] + b[0] + c[0],
a[1] + b[1] + c[1],
a[2] + b[2] + c[2])
# 8 corners: (x choice, y choice, z choice) and their 3 contributing faces
corners = [
# x_max, y_max, z_max affected by +X, +Y, +Z
((x_max0, y_max0, z_max0), add3(v_plusX, v_plusY, v_plusZ)),
((x_max0, y_max0, z_min0), add3(v_plusX, v_plusY, v_minusZ)),
((x_max0, y_min0, z_max0), add3(v_plusX, v_minusY, v_plusZ)),
((x_max0, y_min0, z_min0), add3(v_plusX, v_minusY, v_minusZ)),
((x_min0, y_max0, z_max0), add3(v_minusX, v_plusY, v_plusZ)),
((x_min0, y_max0, z_min0), add3(v_minusX, v_plusY, v_minusZ)),
((x_min0, y_min0, z_max0), add3(v_minusX, v_minusY, v_plusZ)),
((x_min0, y_min0, z_min0), add3(v_minusX, v_minusY, v_minusZ)),
]
moved_corners = []
for (x0, y0, z0), (vx, vy, vz) in corners:
moved_corners.append((x0 + vx * T, y0 + vy * T, z0 + vz * T))
# global min/max across all coordinates of all moved corners
flat = [c for pt in moved_corners for c in pt]
min_expected_pos = min(flat)
max_expected_pos = max(flat)
return min_expected_pos, max_expected_pos, moved_corners
def load_fibre_network(
file_name,
boundary_coords,
epsilon,
fibre_segment_equilibrium_distance,
allow_warning_on_mismatch=False, # for special cases like single-fibre network tests
):
critical_error = False
nodes = None
connectivity = None
n_fiber = None
if os.path.exists(file_name):
# print(f'Loading network from {file_name}')
with open(file_name, 'rb') as f:
data = pickle.load(f)
nodes = data['node_coords']
connectivity = data['connectivity']
network_parameters = data.get('network_parameters')
if network_parameters:
# print('Loaded network parameters:')
for key, value in network_parameters.items():
print(f' {key}: {value}')
domain_lx = abs(boundary_coords[1] - boundary_coords[0])
domain_ly = abs(boundary_coords[3] - boundary_coords[2])
domain_lz = abs(boundary_coords[5] - boundary_coords[4])
#print(f'Computed domain size from boundary coords: LX={domain_lx}, LY={domain_ly}, LZ={domain_lz}')
expected_lx = network_parameters.get('LX')
expected_ly = network_parameters.get('LY')
expected_lz = network_parameters.get('LZ')
expected_edge_length = network_parameters.get('EDGE_LENGTH')
#print(f'Expected network parameters for compatibility checks: LX={expected_lx}, LY={expected_ly}, LZ={expected_lz}, EDGE_LENGTH={expected_edge_length}')
n_fiber = network_parameters.get('N_FIBER')
if expected_lx is not None and not math.isclose(domain_lx, expected_lx, rel_tol=0.0, abs_tol=epsilon):
print('ERROR: Network LX does not match domain size.')
critical_error = True
if expected_ly is not None and not math.isclose(domain_ly, expected_ly, rel_tol=0.0, abs_tol=epsilon):
print('ERROR: Network LY does not match domain size.')
critical_error = True
if expected_lz is not None and not math.isclose(domain_lz, expected_lz, rel_tol=0.0, abs_tol=epsilon):
print('ERROR: Network LZ does not match domain size.')
critical_error = True
if expected_edge_length is not None and not math.isclose(
fibre_segment_equilibrium_distance,
expected_edge_length,
rel_tol=0.0,
abs_tol=epsilon,
):
print(
'WARNING: FIBRE_SEGMENT_EQUILIBRIUM_DISTANCE does not match EDGE_LENGTH from network file. '
f'Updating FIBRE_SEGMENT_EQUILIBRIUM_DISTANCE to match EDGE_LENGTH {expected_edge_length}.'
)
fibre_segment_equilibrium_distance = expected_edge_length
else:
print('WARNING: network_parameters not found in network_3d.pkl. Skipping compatibility checks.')
# print(f'Network loaded: {nodes.shape[0]} nodes, {len(connectivity)} fibers')
else:
print(f"ERROR: file {file_name} containing network nodes and connectivity was not found")
critical_error = True
return nodes, connectivity, n_fiber, fibre_segment_equilibrium_distance, critical_error
msg_wrong_network_dimensions = (
"WARNING: Fibre network nodes do not coincide with boundary faces on at least two axes. "
"Check NODE_COORDS vs BOUNDARY_COORDS or regenerate the network."
)
x_max, x_min, y_max, y_min, z_max, z_min = boundary_coords
axes_with_both_faces = 0
has_x_pos = np.any(np.isclose(nodes[:, 0], x_max, atol=epsilon))
has_x_neg = np.any(np.isclose(nodes[:, 0], x_min, atol=epsilon))
if has_x_pos and has_x_neg:
axes_with_both_faces += 1
has_y_pos = np.any(np.isclose(nodes[:, 1], y_max, atol=epsilon))
has_y_neg = np.any(np.isclose(nodes[:, 1], y_min, atol=epsilon))
if has_y_pos and has_y_neg:
axes_with_both_faces += 1
has_z_pos = np.any(np.isclose(nodes[:, 2], z_max, atol=epsilon))
has_z_neg = np.any(np.isclose(nodes[:, 2], z_min, atol=epsilon))
if has_z_pos and has_z_neg:
axes_with_both_faces += 1
if axes_with_both_faces < 2 and not allow_warning_on_mismatch:
print(msg_wrong_network_dimensions)
critical_error = True
return nodes, connectivity, n_fiber, fibre_segment_equilibrium_distance, critical_error
import math
def print_fibre_calibration_summary(
fibre_segment_k_elast,
fibre_segment_d_dumping,
fibre_segment_equilibrium_distance,
dt,
reference_modulus_mpa=(1.5, 100.0, 700.0),
reference_diameter_nm=(20.0, 60.0, 120.0),
tau_multipliers=(10.0, 50.0, 100.0),
):
"""
FNODE-FNODE Kelvin-Voigt link:
F = k_pair * (d - d0) + d_pair * d_dot
Model structure:
- Two identical springs in series:
k_pair = k_node / 2
- One dashpot in parallel at link level:
d_pair = fibre_segment_d_dumping
Relaxation time:
tau = d_pair / k_pair
Units:
k in nN/um
d in nN*s/um
L in um
dt in s
1 MPa = 1000 nN/um^2
"""
eps = 1e-20
k_node = float(fibre_segment_k_elast) # per spring
d_pair = float(fibre_segment_d_dumping) # dashpot at link level
L = float(fibre_segment_equilibrium_distance)
dt = float(dt)
# Two springs in series
k_pair = 0.5 * k_node
# Kelvin-Voigt relaxation time
tau = d_pair / max(k_pair, eps)
tau_steps = tau / max(dt, eps)
print("\n--- Fibre calibration summary ---")
print(f"k_node = {k_node:.4g} nN/um")
print(f"k_pair = {k_pair:.4g} nN/um (2 springs in series)")
print(f"d_dumping = {d_pair:.4g} nN*s/um (dashpot in parallel)")
print(f"L0 = {L:.4g} um, dt = {dt:.4g} s")
print(f"Relaxation time tau = d_pair/k_pair = {tau:.4g} s")
print(f"That is about {tau_steps:.3g} timesteps if dt = {dt:.4g} s")
# Suggested damping values for stable explicit integration
print("\nSuggested stabilization targets (tau ~ 10-100 timesteps):")
for m in tau_multipliers:
tau_target = m * dt
d_suggest = tau_target * k_pair
print(f" tau = {m:.0f}*dt = {tau_target:.4g} s -> d_dumping ~= {d_suggest:.4g} nN*s/um")
print("\nTuning guideline:")
print(" - Too jittery or oscillatory: increase tau (increase d_dumping)")
print(" - Too sluggish / takes forever to settle: decrease tau (decrease d_dumping)")
# Forward mapping: modulus -> implied diameter
print("\nForward mapping (given E -> implied fibre diameter):")
for E_mpa in reference_modulus_mpa:
E = E_mpa * 1000.0 # MPa -> nN/um^2
area = (k_pair * L) / max(E, eps)
r = math.sqrt(max(area, 0.0) / math.pi)
d_nm = 2.0 * r * 1000.0
print(f" E = {E_mpa:.4g} MPa -> diameter ~= {d_nm:.3f} nm")
# Inverse mapping: target diameter -> required stiffness and damping
print("\nInverse mapping (target E, diameter -> required k_node and d_dumping):")
for E_mpa in reference_modulus_mpa:
E = E_mpa * 1000.0
for diam_nm in reference_diameter_nm:
diam_um = diam_nm / 1000.0
r = 0.5 * diam_um
area = math.pi * r * r
k_pair_req = E * area / max(L, eps)
k_node_req = 2.0 * k_pair_req
# keep same relaxation time tau
d_req = tau * k_pair_req
tau_req_steps = tau / max(dt, eps)
print(
f" E={E_mpa:.4g} MPa, d={diam_nm:.4g} nm -> "
f"k_node~={k_node_req:.4g} nN/um, "
f"d_dumping~={d_req:.4g} nN*s/um "
f"(tau~={tau:.4g} s ~= {tau_req_steps:.3g} steps)"
)
print()
return {
"k_node": k_node,
"k_pair": k_pair,
"d_pair": d_pair,
"tau_s": tau,
"tau_steps": tau_steps,
}
def print_focad_birth_calibration_summary(
*,
dt,
init_n_focad_per_cell,
n_min,
n_max,
k0,
kmax,
refractory_s,
k_sigma,
hill_sigma,
k_c,
hill_conc,
species_index,
):
"""
Print a compact calibration summary for CELL-driven FOCAD birth dynamics.
Birth model in cell_focad_update:
h_sigma = sigma_+^m_sigma / (k_sigma^m_sigma + sigma_+^m_sigma)
h_c = C^n_conc / (k_c^n_conc + C^n_conc)
h_birth = h_sigma * h_c
k_birth = k0 + kmax * h_birth
p_step = 1 - exp(-k_birth * dt)
Notes:
- Single-birth-attempt per CELL per step (agent_out semantics)
- Additional refractory timer further caps effective birth frequency
"""
eps = 1e-20
dt = float(dt)
k0 = float(k0)
kmax = float(kmax)
refractory_s = float(refractory_s)
n_min = int(n_min)
n_max = int(n_max)
init_n = int(init_n_focad_per_cell)
k_birth_min = max(0.0, k0)
k_birth_max = max(0.0, k0 + kmax)
p_step_min = 1.0 - math.exp(-k_birth_min * dt)
p_step_max = 1.0 - math.exp(-k_birth_max * dt)
births_per_min_min = 60.0 * k_birth_min
births_per_min_max = 60.0 * k_birth_max
delta_to_max = max(0, n_max - init_n)
if delta_to_max == 0:
est_fill_time_s = 0.0
else:
effective_births_per_s = k_birth_max
if refractory_s > eps:
effective_births_per_s = min(effective_births_per_s, 1.0 / refractory_s)
if effective_births_per_s > eps:
est_fill_time_s = delta_to_max / effective_births_per_s
else:
est_fill_time_s = float("inf")
if refractory_s > eps:
refractory_steps = refractory_s / max(dt, eps)
max_births_per_min_refractory = 60.0 / refractory_s
else:
refractory_steps = 0.0
max_births_per_min_refractory = float("inf")
print("\n--- FOCAD birth calibration summary ---")
print(f"dt = {dt:.4g} s")
print(f"species index for biochemical gate = {species_index}")
print(f"target count bounds: n_min = {n_min}, n_max = {n_max} (init = {init_n})")
print(f"kinetic rates: k0 = {k0:.4g} 1/s, kmax = {kmax:.4g} 1/s")
print(
f"gate half-saturation: k_sigma = {k_sigma:.4g} kPa (hill_sigma = {hill_sigma:.4g}), "
f"k_c = {k_c:.4g} (hill_conc = {hill_conc:.4g})"
)
print(f"k_birth range = [{k_birth_min:.4g}, {k_birth_max:.4g}] 1/s")
print(f"p_step range = [{p_step_min:.4g}, {p_step_max:.4g}] per step")
print(f"expected births per cell per minute (rate-only) = [{births_per_min_min:.4g}, {births_per_min_max:.4g}]")
if math.isfinite(max_births_per_min_refractory):
print(
f"refractory = {refractory_s:.4g} s (~{refractory_steps:.3g} steps), "
f"absolute cap ~= {max_births_per_min_refractory:.4g} births/cell/min"
)
else:
print("refractory disabled (<=0): no refractory cap")
if math.isfinite(est_fill_time_s):
print(
f"estimated time to go from init ({init_n}) to n_max ({n_max}) at max drive (ignoring deaths) "
f"~= {est_fill_time_s:.4g} s ({est_fill_time_s/60.0:.4g} min)"
)
else:
print(
f"estimated time to go from init ({init_n}) to n_max ({n_max}) at max drive (ignoring deaths): infinite "
f"(effective birth rate <= 0)"
)
print("tuning guideline:")
print(" - Too many births: decrease kmax, increase refractory, or increase k_sigma/k_c")
print(" - Too few births: increase kmax or decrease k_sigma/k_c")
print(" - Bursty births: increase refractory (and/or lower k0)")
print()
return {
"k_birth_min": k_birth_min,
"k_birth_max": k_birth_max,
"p_step_min": p_step_min,
"p_step_max": p_step_max,
"births_per_min_min": births_per_min_min,
"births_per_min_max": births_per_min_max,
"refractory_steps": refractory_steps,
"max_births_per_min_refractory": max_births_per_min_refractory,
"delta_to_max": float(delta_to_max),
"est_fill_time_s": est_fill_time_s,
}
#Helper functions for agent initialization
# +--------------------------------------------------------------------+
def getRandomCoords3D(n, minx, maxx, miny, maxy, minz, maxz):
"""
Generates an array (nx3 matrix) of random numbers with specific ranges for each column.
Args:
n (int): Number of rows in the array.
minx, maxx (float): Range for the values in the first column [minx, maxx].
miny, maxy (float): Range for the values in the second column [miny, maxy].
minz, maxz (float): Range for the values in the third column [minz, maxz].
Returns:
numpy.ndarray: Array of random numbers with shape (n, 3).
"""
return np.random.uniform(low=[minx, miny, minz], high=[maxx, maxy, maxz], size=(n, 3))
def randomVector3D():
"""
Generates a random 3D unit vector (direction) with a uniform spherical distribution
Returns
-------
(x,y,z) : tuple
Coordinates of the vector.
"""
np.random.seed()
phi = np.random.uniform(0.0, np.pi * 2.0)
costheta = np.random.uniform(-1.0, 1.0)
theta = np.arccos(costheta)
x = np.sin(theta) * np.cos(phi)
y = np.sin(theta) * np.sin(phi)
z = np.cos(theta)
return (x, y, z)
def getRandomVectors3D(n_vectors: int):
"""
Generates an array of random 3D unit vectors (directions) with a uniform spherical distribution
Parameters
----------
n_vectors : int
Number of vectors to be generated
Returns
-------
v_array : Numpy array
Coordinates of the vectors. Shape: [n_vectors, 3].
"""
phi = np.random.uniform(0.0, 2.0 * np.pi, size=n_vectors)
costheta = np.random.uniform(-1.0, 1.0, size=n_vectors)
sintheta = np.sqrt(np.maximum(0.0, 1.0 - costheta * costheta))
v_array = np.empty((n_vectors, 3), dtype=float)
v_array[:, 0] = sintheta * np.cos(phi)
v_array[:, 1] = sintheta * np.sin(phi)
v_array[:, 2] = costheta
return v_array
def getCellInitCachePath(cache_dir, n_cells: int):
cache_dir = os.fspath(cache_dir)
return os.path.join(cache_dir, f"cell_pos_ori_{n_cells}.pkl")
def generateCellInitializationData(n_cells: int, boundary_coords):
boundary_coords = np.asarray(boundary_coords, dtype=float)
cell_pos = getRandomCoords3D(
n_cells,
boundary_coords[0], boundary_coords[1],
boundary_coords[2], boundary_coords[3],
boundary_coords[4], boundary_coords[5],
)
cell_orientations = getRandomVectors3D(n_cells)
return cell_pos, cell_orientations
def saveCellInitializationCache(n_cells: int, boundary_coords, cache_dir, extra_data=None):
os.makedirs(cache_dir, exist_ok=True)
boundary_coords = np.asarray(boundary_coords, dtype=float)
pos_start = time.perf_counter()
cell_pos = getRandomCoords3D(
n_cells,
boundary_coords[0], boundary_coords[1],
boundary_coords[2], boundary_coords[3],
boundary_coords[4], boundary_coords[5],
)
pos_seconds = time.perf_counter() - pos_start
ori_start = time.perf_counter()
cell_orientations = getRandomVectors3D(n_cells)
ori_seconds = time.perf_counter() - ori_start
cache_data = {
"n_cells": int(n_cells),
"boundary_coords": boundary_coords,
"domain_size": boundary_coords.copy(),
"cell_pos": np.asarray(cell_pos, dtype=float),
"cell_orientations": np.asarray(cell_orientations, dtype=float),
"generation_time_seconds": {
"positions": pos_seconds,
"orientations": ori_seconds,
"total": pos_seconds + ori_seconds,
},
}
if extra_data:
cache_data.update(extra_data)
output_path = getCellInitCachePath(cache_dir, n_cells)
with open(output_path, 'wb') as fh:
pickle.dump(cache_data, fh, protocol=pickle.HIGHEST_PROTOCOL)
return output_path, cache_data
def loadCachedCellInitialization(n_cells: int, boundary_coords, cache_dir, atol=1.0e-10):
cache_path = getCellInitCachePath(cache_dir, n_cells)
if not os.path.exists(cache_path):
return None
try:
with open(cache_path, 'rb') as fh:
cache_data = pickle.load(fh)
except Exception as exc:
print(f"WARNING: Could not read cached cell initialization from {cache_path}: {exc}")
return None
cached_boundary = cache_data.get('boundary_coords', cache_data.get('domain_size'))
if cached_boundary is None:
print(f"WARNING: Cached cell initialization file {cache_path} does not contain boundary coordinates.")
return None
cached_boundary = np.asarray(cached_boundary, dtype=float)
current_boundary = np.asarray(boundary_coords, dtype=float)
if cached_boundary.shape != (6,) or current_boundary.shape != (6,):
print(f"WARNING: Cached cell initialization file {cache_path} has invalid boundary shape.")
return None
if not np.allclose(cached_boundary, current_boundary, rtol=0.0, atol=atol):
print(
f"WARNING: Cached cell initialization file {cache_path} was generated for a different domain. "
"Falling back to on-the-fly generation."
)
return None
cell_pos = np.asarray(cache_data.get('cell_pos'), dtype=float)
cell_orientations = np.asarray(cache_data.get('cell_orientations'), dtype=float)
expected_shape = (n_cells, 3)
if cell_pos.shape != expected_shape or cell_orientations.shape != expected_shape:
print(
f"WARNING: Cached cell initialization file {cache_path} has unexpected array shapes "
f"(positions={cell_pos.shape}, orientations={cell_orientations.shape}, expected={expected_shape})."
)
return None
return cell_pos, cell_orientations, cache_path, cache_data
def getFixedVectors3D(n_vectors: int, v_dir: np.array):
"""
Generates an array of 3D unit vectors (directions) in the specified direction
Parameters
----------
n_vectors : int
Number of vectors to be generated
v_dir : Numpy array
Direction of the vectors
Returns
-------
v_array : Numpy array
Coordinates of the vectors. Shape: [n_vectors, 3].
"""
v_array = np.tile(v_dir, (n_vectors, 1))
return v_array
def getRandomCoordsAroundPoint(n, px, py, pz, radius, on_surface=False):
"""
Generates N random 3D coordinates within a sphere of a specific radius around a central point.
Parameters
----------
n : int
The number of random coordinates to generate.
px : float
The x-coordinate of the central point.
py : float
The y-coordinate of the central point.
pz : float
The z-coordinate of the central point.
radius : float
The radius of the sphere.
on_surface : bool
If True, points lie on the sphere surface; otherwise, points are within the sphere.
Returns
-------
coords
A numpy array of randomly generated 3D coordinates with shape (n, 3).
"""
central_point = np.asarray([px, py, pz], dtype=float)
rand_dirs = getRandomVectors3D(n)
if on_surface:
radii = np.full((n, 1), radius, dtype=float)
else:
radii = np.random.uniform(0.0, 1.0, size=(n, 1)) * radius
return central_point + rand_dirs * radii
def getRadialOrientations(
positions: np.ndarray,
center: np.ndarray = None,
noise_sigma: float = 0.0,
rng: np.random.Generator = None,
) -> np.ndarray:
"""
Compute unit orientation vectors pointing radially outward from *center*
through each agent position. An optional Gaussian angular perturbation
breaks the perfect radial symmetry to produce more natural-looking initial
configurations.
Parameters
----------
positions : (N, 3) np.ndarray
Agent positions in world coordinates.
center : (3,) array-like, optional
Reference center from which radial directions are measured.
Defaults to the origin [0, 0, 0].
noise_sigma : float, optional
Standard deviation of the angular perturbation in **radians**.
0 → perfectly radial (no noise).
~0.3 → moderate randomisation (~17° RMS deviation).
~1.0 → strongly randomised orientations.
Angles are clipped to [-π, π] to avoid excessive rotation.
rng : np.random.Generator, optional
NumPy random generator for reproducibility. If *None* a fresh
default generator is created internally.
Returns
-------
orientations : (N, 3) np.ndarray
Unit vectors, one per agent, pointing roughly radially outward.
"""
positions = np.asarray(positions, dtype=np.float64)
if positions.ndim == 1:
positions = positions[None, :]
if positions.ndim != 2 or positions.shape[1] != 3:
raise ValueError(f"positions must have shape (N, 3), got {positions.shape}")
if center is None:
center = np.zeros(3, dtype=np.float64)
center = np.asarray(center, dtype=np.float64).reshape(3)
if rng is None:
rng = np.random.default_rng()
N = len(positions)
directions = positions - center[None, :] # (N, 3) radial vectors
# Normalize; fall back to a random unit vector for agents at the center
norms = np.linalg.norm(directions, axis=1, keepdims=True) # (N, 1)
near_zero = (norms[:, 0] < 1e-10)
if near_zero.any():
# Replace near-zero rows with random unit vectors
rand_dirs = getRandomVectors3D(int(near_zero.sum()))
directions[near_zero] = rand_dirs
norms[near_zero] = np.linalg.norm(directions[near_zero], axis=1, keepdims=True)
orientations = directions / norms # (N, 3) unit vectors
if noise_sigma > 0.0:
# --- Rodrigues rotation by a random angle around a random perpendicular axis ---
# 1. Draw rotation angles from a zero-mean Gaussian, clipped to [-pi, pi]
angles = rng.normal(0.0, float(noise_sigma), size=N)
angles = np.clip(angles, -np.pi, np.pi)
# 2. Build a random perpendicular axis for each orientation vector
# Use a random vector and project out the radial component.
rand_vecs = rng.standard_normal((N, 3))
# Subtract the component parallel to orientations
dot = np.einsum("ij,ij->i", rand_vecs, orientations) # (N,)
perp = rand_vecs - dot[:, None] * orientations # (N, 3)
perp_norms = np.linalg.norm(perp, axis=1, keepdims=True)
# Handle degenerate case (rand_vec accidentally parallel to orientation)
degenerate = (perp_norms[:, 0] < 1e-10)
if degenerate.any():
# Swap the first and second components to guarantee non-parallel
fallback = np.zeros_like(orientations[degenerate])
fallback[:, 0] = -orientations[degenerate, 1]
fallback[:, 1] = orientations[degenerate, 0]
fallback[:, 2] = 0.0
fallback_norms = np.linalg.norm(fallback, axis=1, keepdims=True)
fallback_norms = np.maximum(fallback_norms, 1e-10)
perp[degenerate] = fallback / fallback_norms
perp_norms[degenerate] = 1.0
axes = perp / perp_norms # (N, 3) unit rotation axes ⊥ to orientations
# 3. Rodrigues' rotation formula (k·v == 0 here so last term vanishes)
# v_rot = v * cos(θ) + (k × v) * sin(θ)
cos_a = np.cos(angles)[:, None] # (N, 1)
sin_a = np.sin(angles)[:, None] # (N, 1)
cross = np.cross(axes, orientations) # (N, 3)
orientations = orientations * cos_a + cross * sin_a
# Re-normalise to absorb any floating-point drift
final_norms = np.linalg.norm(orientations, axis=1, keepdims=True)
final_norms = np.maximum(final_norms, 1e-12)
orientations = orientations / final_norms
return orientations.astype(float) # float64, matching pyflamegpu setVariableFloat expectations
def compute_u_ref_from_anchor_pos(anchor_pos: np.ndarray,
cell_center: np.ndarray,
eps: float = 1e-12) -> np.ndarray:
"""
Compute reference unit vectors u_ref for nucleus anchors.
Parameters
----------
anchor_pos : (N, 3) np.ndarray
Anchor positions in world coordinates.
cell_center : (3,) np.ndarray
Nucleus center in world coordinates (cell_pos[i, :]).
eps : float
Small value to avoid division by zero.
Returns
-------
u_ref : (N, 3) np.ndarray
Unit vectors pointing from nucleus center to each anchor.
"""
anchor_pos = np.asarray(anchor_pos, dtype=np.float64)
cell_center = np.asarray(cell_center, dtype=np.float64).reshape(3,)
if anchor_pos.ndim != 2 or anchor_pos.shape[1] != 3:
raise ValueError(f"anchor_pos must have shape (N, 3), got {anchor_pos.shape}")
if cell_center.shape != (3,):
raise ValueError(f"cell_center must have shape (3,), got {cell_center.shape}")
# Vectors from center to anchors
u = anchor_pos - cell_center[None, :] # (N, 3)
# Normalize safely
norm = np.linalg.norm(u, axis=1) # (N,)
norm = np.maximum(norm, eps) # avoid divide by zero
u_ref = u / norm[:, None]
return u_ref
def build_save_data_context(ecm_agents_per_dir, include_fibre_network, n_nodes):
context = {}
context["header"] = [
"# vtk DataFile Version 3.0",
"ECM data",
"ASCII",
"DATASET POLYDATA",
"POINTS {} float".format(8 + ecm_agents_per_dir[0] * ecm_agents_per_dir[1] * ecm_agents_per_dir[2]),
]
domaindata = ["POLYGONS 6 30"]
cube_conn = [
[4, 0, 3, 7, 4],
[4, 1, 2, 6, 5],
[4, 1, 0, 4, 5],
[4, 2, 3, 7, 6],
[4, 0, 1, 2, 3],
[4, 4, 5, 6, 7],
]
for i in range(len(cube_conn)):
for j in range(len(cube_conn[i])):
if j > 0:
cube_conn[i][j] = cube_conn[i][j] + ecm_agents_per_dir[0] * ecm_agents_per_dir[1] * ecm_agents_per_dir[2]
domaindata.append(' '.join(str(x) for x in cube_conn[i]))
context["domaindata"] = domaindata
if include_fibre_network:
domaindata_network = []
cube_conn_network = [
[4, 0, 3, 7, 4],
[4, 1, 2, 6, 5],
[4, 1, 0, 4, 5],
[4, 2, 3, 7, 6],
[4, 0, 1, 2, 3],
[4, 4, 5, 6, 7],
]
for i in range(len(cube_conn_network)):
for j in range(len(cube_conn_network[i])):
if j > 0:
cube_conn_network[i][j] = cube_conn_network[i][j] + n_nodes
domaindata_network.append(' '.join(str(x) for x in cube_conn_network[i]))
context["domaindata_network"] = domaindata_network
context["domaindata"] += [
"CELL_DATA 6",
"SCALARS boundary_index int 1",
"LOOKUP_TABLE default",
"0",
"1",
"2",
"3",
"4",
"5",
"NORMALS boundary_normals float",
"1 0 0",
"-1 0 0",
"0 1 0",
"0 -1 0",
"0 0 1",
"0 0 -1",
]
context["vascularizationdata"] = [
"# vtk DataFile Version 3.0",
"Vascularization points",
"ASCII",
"DATASET UNSTRUCTURED_GRID",
]
context["fibrenodedata"] = [
"# vtk DataFile Version 3.0",
"Fibre node agents",
"ASCII",
"DATASET UNSTRUCTURED_GRID",
]
context["celldata"] = [
"# vtk DataFile Version 3.0",
"Cell agents",
"ASCII",
"DATASET UNSTRUCTURED_GRID",
]
context["nucleusdata"] = [
"# vtk DataFile Version 3.0",
"Cell agents - nucleus data",
"ASCII",
"DATASET UNSTRUCTURED_GRID",
]
context["focaladhesionsdata"] = [
"# vtk DataFile Version 3.0",
"Focal adhesions",
"ASCII",
"DATASET UNSTRUCTURED_GRID",
]
context["lumendata"] = [
"# vtk DataFile Version 3.0",
"Lumen agents",
"ASCII",
"DATASET UNSTRUCTURED_GRID",
]
return context
def save_data_to_file_step(FLAMEGPU, save_context, config):
save_data_to_file = config["SAVE_DATA_TO_FILE"]
save_every_n_steps = config["SAVE_EVERY_N_STEPS"]
n_species = config["N_SPECIES"]
res_path = config["RES_PATH"]
include_fibre_network = config["INCLUDE_FIBRE_NETWORK"]
heterogeneous_diffusion = config["HETEROGENEOUS_DIFFUSION"]
initial_network_connectivity = config["INITIAL_NETWORK_CONNECTIVITY"]
n_nodes = config["N_NODES"]
include_cells = config["INCLUDE_CELLS"]
ecm_population_size = config["ECM_POPULATION_SIZE"]
include_focal_adhesions = config["INCLUDE_FOCAL_ADHESIONS"]
include_network_remodeling = config["INCLUDE_NETWORK_REMODELING"]
include_lumen = config["INCLUDE_LUMEN"]
pyflamegpu = config["pyflamegpu"]
stepCounter = FLAMEGPU.getStepCounter() + 1
coord_boundary = list(FLAMEGPU.environment.getPropertyArrayFloat("COORDS_BOUNDARIES"))
if not save_data_to_file:
return
if stepCounter % save_every_n_steps != 0 and stepCounter != 1:
return
if include_fibre_network:
file_name = 'fibre_network_data_t{:04d}.vtk'.format(stepCounter)
file_path = res_path / file_name
agent = FLAMEGPU.agent("FNODE")
sum_bx_pos = -agent.sumFloat("f_bx_pos")
sum_bx_neg = -agent.sumFloat("f_bx_neg")
sum_by_pos = -agent.sumFloat("f_by_pos")
sum_by_neg = -agent.sumFloat("f_by_neg")
sum_bz_pos = -agent.sumFloat("f_bz_pos")
sum_bz_neg = -agent.sumFloat("f_bz_neg")
sum_bx_pos_y = -agent.sumFloat("f_bx_pos_y")
sum_bx_pos_z = -agent.sumFloat("f_bx_pos_z")
sum_bx_neg_y = -agent.sumFloat("f_bx_neg_y")
sum_bx_neg_z = -agent.sumFloat("f_bx_neg_z")
sum_by_pos_x = -agent.sumFloat("f_by_pos_x")
sum_by_pos_z = -agent.sumFloat("f_by_pos_z")
sum_by_neg_x = -agent.sumFloat("f_by_neg_x")
sum_by_neg_z = -agent.sumFloat("f_by_neg_z")
sum_bz_pos_x = -agent.sumFloat("f_bz_pos_x")
sum_bz_pos_y = -agent.sumFloat("f_bz_pos_y")
sum_bz_neg_x = -agent.sumFloat("f_bz_neg_x")
sum_bz_neg_y = -agent.sumFloat("f_bz_neg_y")
ids = list()
coords = list()
velocity = list()
force = list()
elastic_energy = list()
degradation = list()
reinforcement = list()
secreted = list()
linked_nodes_all = list()
k_elast = list()
orig_ids = list()
focad_attached = list()
focad_id = list()
av = agent.getPopulationData()
for ai in av:
id_ai = ai.getVariableInt("id")
coords_ai = (ai.getVariableFloat("x"), ai.getVariableFloat("y"), ai.getVariableFloat("z"))
velocity_ai = (ai.getVariableFloat("vx"), ai.getVariableFloat("vy"), ai.getVariableFloat("vz"))
force_ai = (ai.getVariableFloat("fx"), ai.getVariableFloat("fy"), ai.getVariableFloat("fz"))
ids.append(id_ai)
coords.append(coords_ai)
velocity.append(velocity_ai)
force.append(force_ai)
elastic_energy.append(ai.getVariableFloat("elastic_energy"))
degradation.append(ai.getVariableFloat("degradation"))
reinforcement.append(ai.getVariableFloat("reinforcement"))
secreted.append(ai.getVariableInt("secreted"))
linked_nodes_all.append(ai.getVariableArrayFloat("linked_nodes"))
k_elast.append(ai.getVariableFloat("k_elast"))
focad_attached.append(ai.getVariableInt("focad_attached"))
focad_id.append(ai.getVariableInt("focad_id"))
if len(ids) > 0:
orig_ids = ids.copy()
min_id = min(ids)
ids = [fid - min_id for fid in ids if fid > 0]
for i in range(len(linked_nodes_all)):
linked_nodes_all[i] = [linked_id - min_id for linked_id in linked_nodes_all[i] if linked_id > 0] + [linked_id for linked_id in linked_nodes_all[i] if linked_id <= 0]
sorted_indices = np.argsort(ids)
ids = [ids[i] for i in sorted_indices]
orig_ids = [orig_ids[i] for i in sorted_indices]
coords = [coords[i] for i in sorted_indices]
velocity = [velocity[i] for i in sorted_indices]
force = [force[i] for i in sorted_indices]
elastic_energy = [elastic_energy[i] for i in sorted_indices]
degradation = [degradation[i] for i in sorted_indices]
reinforcement = [reinforcement[i] for i in sorted_indices]
secreted = [secreted[i] for i in sorted_indices]
linked_nodes_all = [linked_nodes_all[i] for i in sorted_indices]
focad_attached = [focad_attached[i] for i in sorted_indices]
focad_id = [focad_id[i] for i in sorted_indices]
n_fnodes = len(ids)
id_to_point_idx = {fid: i for i, fid in enumerate(ids)}
added_lines = set()
cell_connectivity = []
for i, fid in enumerate(ids):
links = linked_nodes_all[i]
for linked_id_raw in links:
linked_id = int(round(linked_id_raw))
if linked_id < 0 or linked_id == fid:
continue
if linked_id in id_to_point_idx:
line = tuple(sorted((id_to_point_idx[fid], id_to_point_idx[linked_id])))
if line not in added_lines:
added_lines.add(line)
cell_connectivity.append(line)
num_cells = len(cell_connectivity) # WARNING: Vtk cells, nothing to do with cell agents
with open(str(file_path), 'w') as file:
for line in save_context["fibrenodedata"]:
file.write(line + '\n')
file.write("POINTS {} float \n".format(8 + n_fnodes))
for coords_ai in coords:
file.write("{} {} {} \n".format(coords_ai[0], coords_ai[1], coords_ai[2]))
file.write("{} {} {} \n".format(coord_boundary[0], coord_boundary[2], coord_boundary[4]))
file.write("{} {} {} \n".format(coord_boundary[1], coord_boundary[2], coord_boundary[4]))
file.write("{} {} {} \n".format(coord_boundary[1], coord_boundary[3], coord_boundary[4]))
file.write("{} {} {} \n".format(coord_boundary[0], coord_boundary[3], coord_boundary[4]))
file.write("{} {} {} \n".format(coord_boundary[0], coord_boundary[2], coord_boundary[5]))
file.write("{} {} {} \n".format(coord_boundary[1], coord_boundary[2], coord_boundary[5]))
file.write("{} {} {} \n".format(coord_boundary[1], coord_boundary[3], coord_boundary[5]))
file.write("{} {} {} \n".format(coord_boundary[0], coord_boundary[3], coord_boundary[5]))
file.write(f"CELLS {num_cells + 6} {num_cells * 3 + 6 * 5}\n")
for conn in cell_connectivity:
file.write(f"2 {conn[0]} {conn[1]}\n")
if include_network_remodeling:
domaindata_network = []
cube_conn_network = [
[4, 0, 3, 7, 4],
[4, 1, 2, 6, 5],
[4, 1, 0, 4, 5],
[4, 2, 3, 7, 6],
[4, 0, 1, 2, 3],