-
Notifications
You must be signed in to change notification settings - Fork 1
/
growth_functions.py
1938 lines (1619 loc) · 88 KB
/
growth_functions.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 15:21:05 2020
@author: jolenebritton
"""
import numpy as np
import helper_functions as hf
import nutrient_functions2 as nf
import random
params, config = hf.get_configs('parameters.ini')
# ----------------------------------------------------------------------------
# GENERAL FUNCTIONS
# ----------------------------------------------------------------------------
def michaelis_menten(k, K, s):
"""
Parameters
----------
k : double
Maximum rate achieved by the system, at saturating substrate concentration.
K : double
Michaelis constant.
s : double
Concentration of substrate/nutrient.
Returns
-------
double
Reaction rate.
"""
return (k * s) / (K + s)
# ----------------------------------------------------------------------------
def calc_dist(xy1, xy2):
"""
Parameters
----------
xy1 : double
x- & y-coordinate of starting point.
xy2 : double
x- & y-coordinate of ending point.
Returns
-------
double
The distance between (xy1[0],xy1[1]) and (xy2[0],xy2[1]).
"""
# breakpoint()
return np.sqrt((xy2[1] - xy1[1])**2 + (xy2[0] - xy1[0])**2)
# ----------------------------------------------------------------------------
def check_negative(condition):
"""
Parameters
----------
condition : double
A scalar value to check the sign of.
"""
# if condition < 0:
# breakpoint()
# ----------------------------------------------------------------------------
# EXTENSION & BRANCHING FUNCTIONS
# ----------------------------------------------------------------------------
def map_to_grid(mycelia, idx, num_total_segs, x_vals, y_vals):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
idx : int
Segment index.
num_total_segs : int
Current total number of segments in the mycelium.
x_vals : list/array
The x-values of the external grid.
y_vals : list/array
The y-values of the external grid.
Returns
-------
mycelia : TYdictionaryPE
Updated structural information of mycelia colony for all hyphal segments.
Purpose
-------
Map the starting endpoint of a hyphal segment to the nearest external grid
coordinates. Note if multiples segments are mapped to the same external grid
point.
"""
# Include self in list of shared endpoints
mycelia['share_e'][idx] = [idx]
# Get the index of the external grid point
xy_e = np.array([int(np.argmin(abs(mycelia['xy1'][idx,0]-x_vals))),int(np.argmin(abs(mycelia['xy1'][idx,1]-y_vals)))])
# print(xy_e)
if xy_e is None:
print('None value')
# If another segments also maps to the same location
e_overlap = list(map(lambda x: np.array_equal(x, xy_e), mycelia['xy_e_idx'][:num_total_segs,:]))
# print(e_overlap)
mycelia['xy_e_idx'][idx,:] = xy_e
if any(e_overlap): # If there is overlap, append the segment index
#mycelia['share_e'][np.where(e_overlap)[0][0]].append(idx) # # Append the idx to the shared list for the overlapping indices
#mycelia['share_e'][idx].append(np.where(e_overlap)[0][0]) # Append the overlapping indices to the shared list for index idx
for i, val in enumerate(e_overlap):
if val:
mycelia['share_e'][idx].append(i)
mycelia['share_e'][i].append(idx)
return mycelia
# ----------------------------------------------------------------------------
def cost_of_growth(mycelia, idxs, grow_len):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
idxs : int or array of ints
Segment index or array of segment indicies.
grow_len : double
The amount in which a segment grows/extends.
Returns
-------
grow_len : double
The possibly updated amount in which a segment grows/extends.
cost_grow_gluc : double
The amount of glucose required to grow a length of grow_len.
cost_grow_cw : double
The amount of cell wall materials required to grow a length of grow_len.
Purpose
-------
Calculate the amount of nutrients needed to grow. If the cost is higher
than the amount of nutrient available, adjust the amount of growth downwards.
"""
if any(grow_len > 1e2):
breakpoint()
# Cost to grow predetermined amount
# Here we are testing to see if there is enough material in the
# segment to extend the segment the length of length grow_len.
#cost_grow_cq = grow_len* area * density* (dry mass/wet mass/)(cellwallmass/dry mass) (millimeters/cubic micron) * mw(cw_i)
# gamma is mmoles cw_i/micron
gamma = params['f_dw']* params['f_wall'] * params['f_cw_cellwall']/params['mw_cw']* \
params['hy_density']*params['cross_area']
cost_grow_cw1 = grow_len * gamma # cost in mmoles of cw_i
#cost_grow_cw1 = grow_len * mycelia['cw_i'][idxs]
#cost_grow_cw1 = grow_len* np.pi*(5.0/2)**2 * params['hy_density'] * params['f_dw']* \
# params['f_wall'] * params['f_cw_cellwall']/params['mw_cw']
#cost_grow_cw1 = grow_len* np.pi*(5.0/2)**2 * params['hy_density'] * params['f_dw']* \
# params['f_wall'] * params['f_cw_cellwall']/params['mw_cw']
# Next test to see if the new tip volume will deplete all the material
# from the segment without regard to the amount of material required
# to form the cell wall; That is, scale the length of the new tip so that the
# concentration of the preceding segment
# doesn't become negative.
#cost_grow_cw2 = (mycelia['cw_i'][idxs]/mycelia['seg_length'][idxs]) * (grow_len)
scale = michaelis_menten(1, cost_grow_cw1,
mycelia['cw_i'][idxs])
cost_grow_cw2 = cost_grow_cw1 * scale
#cost_grow_cw = np.maximum(np.max(cost_grow_cw1), np.max(cost_grow_cw2))
#cost_grow_cw = np.maximum((cost_grow_cw1), (cost_grow_cw2))
cost_grow_cw = np.minimum((cost_grow_cw1), (cost_grow_cw2))
#cost_grow_cw = cost_grow_cw2
#Here we are testing to see if the new tip volume will deplete all the material
#from the preceding segment
# Need to make extend_len shorter if cost is too much
cost_grow_gluc = (mycelia['gluc_i'][idxs]/mycelia['seg_length'][idxs]) * (grow_len)
cost_grow_gluc[:] = 0.0
if ((min(mycelia['cw_i'][idxs] - cost_grow_cw) < 0) and (max(grow_len > 0))):
# new_grow_len = 0.5*grow_len * mycelia['cw_i'][idxs]/cost_grow_cw
# if any(new_grow_len > 1e2):
# breakpoint()
# cost_grow_cw = cost_grow_cw * new_grow_len/grow_len
# grow_len = new_grow_len #if we change grow_len do we need to change dt also?
not_enough_cw = np.where(mycelia['cw_i'][idxs] < cost_grow_cw)[0]
try:
grow_len[not_enough_cw] = grow_len[not_enough_cw]*mycelia['cw_i'][idxs[not_enough_cw]]/cost_grow_cw[not_enough_cw] #0.0
except:
breakpoint()
# cost_grow_cw[not_enough_cw] = 0.0
# The alternative is to set the grow_len to zero and wait until enough material
# has been accumulated in the segment.
rand_work = np.random.rand(*cost_grow_cw.shape)*cost_grow_cw
diff_work = rand_work - cost_grow_cw
# scale = np.exp(2*diff_work/cost_grow_cw)
if any(grow_len > 1e2):
breakpoint()
# scale = 0.3
#scale = 1.0
grow_len = grow_len*scale
#cost_grow_cw = cost_grow_cw*scale
#grow_len = grow_len *0.3
#cost_grow_cw = cost_grow_cw *0.35
#cost_grow_gluc = (mycelia['gluc_i'][idxs]/mycelia['seg_length'][idxs]) * (grow_len)
#Here we are testing to see if the new tip volume will deplete all the material
#from the preceding segment
# Need to make extend_len shorter if cost is too much
#if (min(mycelia['gluc_i'][idxs] - cost_grow_gluc) < 0) and (max(grow_len) > 0):
# # breakpoint()
# cost_grow_gluc = 0.9*np.min((cost_grow_gluc, mycelia['gluc_i'][idxs]), axis=0)
# grow_len = (mycelia['seg_length'][idxs]/mycelia['gluc_i'][idxs]) * cost_grow_gluc
# cost_grow_gluc = (mycelia['gluc_i'][idxs]/mycelia['seg_length'][idxs]) * (grow_len)
#if(np.any(cost_grow_gluc > 1.0 )):
# breakpoint()
#cost_grow_cw = (mycelia['cw_i'][idxs]/mycelia['seg_length'][idxs]) * (grow_len)
#Here we are testing to see if the new tip volume will deplete all the material
#from the preceding segment without regard to the amount of material required
# to form the cell wall
#if (min(mycelia['cw_i'][idxs] - cost_grow_cw) < 0) and (max(grow_len) > 0):
# # breakpoint()
# cost_grow_cw = 0.9*np.min((cost_grow_cw, mycelia['cw_i'][idxs]), axis=0)
# grow_len = (mycelia['seg_length'][idxs]/mycelia['cw_i'][idxs]) * cost_grow_cw
# cost_grow_cw = (mycelia['cw_i'][idxs]/mycelia['seg_length'][idxs]) * (grow_len)
if any(grow_len > 1e2):
breakpoint()
return grow_len, cost_grow_gluc, cost_grow_cw
# ----------------------------------------------------------------------------
def update_structure(mycelia, idxs, grow_len, cost_grow_gluc, cost_grow_cw, isCalibration):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
idxs : int or array of ints
Segment index or array of segment indicies.
grow_len : double
The amount in which a segment grows/extends.
cost_grow_gluc : double
The amount of glucose required to grow a length of grow_len.
cost_grow_cw : double
The amount of cell wall materials required to grow a length of grow_len.
Returns
-------
mycelia : dictionary
Updated structural information of mycelia colony for all hyphal segments.
Purpose
-------
Determine updated endpoints of segments, updated length of segment,
updated nutrients in the segment, and distance from nearest septa.
"""
# New endpoint
if (isCalibration == 0):
mycelia['xy2'][idxs,0] += (grow_len*np.cos(mycelia['angle'][idxs])).flatten()
mycelia['xy2'][idxs,1] += (grow_len*np.sin(mycelia['angle'][idxs])).flatten()
else:
mycelia['xy2'][idxs,0] += (grow_len*np.cos(0)).flatten()
mycelia['xy2'][idxs,1] += (grow_len*np.sin(0)).flatten()
# Update length and distance to nearest septa
mycelia['seg_length'][idxs] += grow_len
mycelia['seg_vol'][idxs] = mycelia['seg_length'][idxs] * params['cross_area']
# Update concentration of nutrients due cost of growth
mycelia['gluc_i'][idxs] -= cost_grow_gluc
#if(np.shape(mycelia['cw_i'][idxs]) != np.shape(cost_grow_cw)):
# breakpoint()
mycelia['cw_i'][idxs] -= cost_grow_cw
# Update distance between tip and nearest septa
mycelia['dist_to_septa'][idxs] += grow_len
return mycelia
# ----------------------------------------------------------------------------
# def septa_formation(mycelia, num_total_segs):
# """
# Parameters
# ----------
# mycelia : dictionary
# Stores structural information of mycelia colony for all hyphal segments.
# num_total_segs : int
# CCurrent total number of segments in the mycelium.
# Returns
# -------
# mycelia : dictionary
# Updated structural information of mycelia colony for all hyphal segments.
# Purpose
# -------
# Denotes where a new septa forms.
# """
# print('septa forming')
# # breakpoint()
# # Indicices of segments whose dist_to_septa is long enough to introduce new septa
# septa_need = np.where(mycelia['dist_to_septa']> 3*params['sl']*params['septa_len'])[0]
# if any(mycelia['dist_to_septa'][septa_need] <= 3*params['sl']*params['septa_len']):
# breakpoint()
# #septa_need = np.where(mycelia['dist_to_septa']> params['sl']*params['septa_len'])[0]
# # breakpoint()
# # Find the branches that need new septa
# branch_ids = mycelia['branch_id'][septa_need]
# print('mycelia[dist_to_septa][septa_need] : ' , mycelia['dist_to_septa'][septa_need])
# for idx, branch in enumerate(branch_ids):
# print('branch : ', branch)
# print('idx : ', idx)
# # Find IDs of segments on that branch
# segs_on_branch = np.where(mycelia['branch_id'][:num_total_segs] == branch)[0]
# # If the branch already has a septa
# if any(mycelia['septa_loc'][segs_on_branch]):
# # print('IF')
# # breakpoint()
# # Find which segment the last septa was on
# last_septa = max(np.where(mycelia['septa_loc'][segs_on_branch])[0])
# # New segment septa will have seg index N larger than last septa seg index
# new_septa = last_septa + params['septa_len']
# if new_septa >= len(segs_on_branch):
# breakpoint()
# print('branch = ', branch,'length(segs_on_branch) = ', len(segs_on_branch), ', new_septa = ',new_septa)
# # Indicate location of septa
# mycelia['septa_loc'][segs_on_branch[new_septa]] = True
# # Allow the segment behind it to branch
# mycelia['can_branch'][segs_on_branch[new_septa-1]] = True
# # print('mycelia[dist_to_septa][septa_need] : ' , mycelia['dist_to_septa'][septa_need])
# mycelia['dist_to_septa'][septa_need[idx]] -= params['sl']*params['septa_len']
# if any(mycelia['dist_to_septa'][septa_need] < 0):
# breakpoint()
# else:
# # print('ELSE')
# if len(segs_on_branch) < 2:
# breakpoint()
# print('There is no other segments in this single-segment-branch branch. There is no need to set branching segments.')
# #mycelia['septa_loc'][segs_on_branch[0]] = True
# else:
# print('segs_on_branch[params[septa_len]]:', segs_on_branch[params['septa_len']])
# # Find the index of the segment that is N segments away from the start of the branch
# # if any(mycelia['dist_to_septa'][septa_need] - params['sl']*params['septa_len'] < 2*params['sl']*params['septa_len']):
# # breakpoint()
# mycelia['septa_loc'][segs_on_branch[params['septa_len']]] = True
# # Allow the segment behind it to branch
# mycelia['can_branch'][segs_on_branch[params['septa_len']-1]] = True
# # if any(mycelia['dist_to_septa'][septa_need] - params['sl']*params['septa_len'] < 2*params['sl']*params['septa_len']):
# # breakpoint()
# # print('mycelia[dist_to_septa][septa_need] : ' , mycelia['dist_to_septa'][septa_need])
# mycelia['dist_to_septa'][septa_need[idx]] -= params['sl']*params['septa_len']
# # Update distance between tip and new septa
# #mycelia['dist_to_septa'][septa_need] -= params['sl']*params['septa_len']
# # if min(mycelia['dist_to_septa'][septa_need]) < 0:
# # breakpoint()
# return mycelia
def septa_formation(mycelia, num_total_segs,branch_rate):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
num_total_segs : int
CCurrent total number of segments in the mycelium.
Returns
-------
mycelia : dictionary
Updated structural information of mycelia colony for all hyphal segments.
Purpose
-------
Denotes where a new septa forms.
"""
# print('septa forming')
# breakpoint()
# Indicices of segments whose dist_to_septa is long enough to introduce new septa
nn = 3
septa_need = np.where(mycelia['dist_to_septa'][:num_total_segs] > nn*params['sl']*params['septa_len'])[0]
if any(mycelia['dist_to_septa'][septa_need] <= nn*params['sl']*params['septa_len']):
breakpoint()
#septa_need = np.where(mycelia['dist_to_septa']> params['sl']*params['septa_len'])[0]
# breakpoint()
# Find the branches that need new septa
branch_ids = mycelia['branch_id'][septa_need]
# print('mycelia[dist_to_septa][septa_need] : ' , mycelia['dist_to_septa'][septa_need])
for idx, branch in enumerate(branch_ids):
if (mycelia['is_tip'][septa_need[idx]] == False):
continue
# print('branch : ', branch)
# print('idx : ', idx)
# Find IDs of segments on that branch
segs_on_branch = np.where(mycelia['branch_id'][:num_total_segs] == branch)[0]
# If the branch already has a septa
if any(mycelia['septa_loc'][segs_on_branch]):
# print('IF')
# breakpoint()
# Find which segment the last septa was on
last_septa = max(np.where(mycelia['septa_loc'][segs_on_branch])[0])
# New segment septa will have seg index N larger than last septa seg index
# N = septa_len = 1 currently
new_septa = last_septa + params['septa_len']
if new_septa >= len(segs_on_branch):
breakpoint()
# print('branch = ', branch,'length(segs_on_branch) = ', len(segs_on_branch), ', new_septa = ',new_septa)
# Indicate location of septa
mycelia['septa_loc'][segs_on_branch[new_septa]] = True
# Allow the segment behind it to branch
total_nchoices = segs_on_branch[new_septa-1]
rand_values = np.random.rand(total_nchoices)
rand_values = np.random.rand(1)
is_true = (rand_values < branch_rate)
mycelia['can_branch'][segs_on_branch[new_septa-1]] = is_true
#mycelia['can_branch'][segs_on_branch[new_septa-1]] = True
# print('mycelia[dist_to_septa][septa_need] : ' , mycelia['dist_to_septa'][septa_need])
mycelia['dist_to_septa'][septa_need[idx]] -= params['sl']*params['septa_len']
if (mycelia['dist_to_septa'][septa_need[idx]] < 0):
breakpoint()
else:
# print('ELSE')
if len(segs_on_branch) < 2:
#breakpoint()
print('There is no other segments in this single-segment-branch branch. There is no need to set branching segments.')
#mycelia['septa_loc'][segs_on_branch[0]] = True
else:
# print('segs_on_branch[params[septa_len]]:', segs_on_branch[params['septa_len']])
# Find the index of the segment that is N segments away from the start of the branch
# if any(mycelia['dist_to_septa'][septa_need] - params['sl']*params['septa_len'] < 2*params['sl']*params['septa_len']):
# breakpoint()
mycelia['septa_loc'][segs_on_branch[params['septa_len']]] = True
# Allow the segment behind it to branch
total_nchoices = len([segs_on_branch[params['septa_len']-1]])
rand_values = np.random.rand(total_nchoices)
rand_values = np.random.rand(1)
is_true = (rand_values < branch_rate)
mycelia['can_branch'][segs_on_branch[params['septa_len']-1]] = is_true
#mycelia['can_branch'][segs_on_branch[params['septa_len']-1]] = True
# if any(mycelia['dist_to_septa'][septa_need] - params['sl']*params['septa_len'] < 2*params['sl']*params['septa_len']):
# breakpoint()
# print('mycelia[dist_to_septa][septa_need] : ' , mycelia['dist_to_septa'][septa_need])
mycelia['dist_to_septa'][septa_need[idx]] -= params['sl']*params['septa_len']
# if mycelia['dist_to_septa'][septa_need[idx]] > 60:
# breakpoint()
# Update distance between tip and new septa
#mycelia['dist_to_septa'][septa_need] -= params['sl']*params['septa_len']
# if min(mycelia['dist_to_septa'][septa_need]) < 0:
# breakpoint()
return mycelia
# ----------------------------------------------------------------------------
def split_segment(mycelia, num_total_segs, x_vals, y_vals, isCalibration, dist2Tip_new):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
num_total_segs : int
Current total number of segments in the mycelium.
x_vals : list/array
The x-values of the external grid.
y_vals : list/array
The y-values of the external grid.
Returns
-------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
num_total_segs : int
Current total number of segments in the mycelium.
dtt : array
Contains the distance each segment is away from the nearest tip segment.
Purpose
-------
Splits a segment into twoIf a segment is long enough.
The structural information for each segment is updated.
"""
# Locations of spliting tips
nn = 3
tips_to_split = np.where(mycelia['seg_length'][:num_total_segs] > (nn-1)*params['sl'])[0]
if any(mycelia['seg_length'][tips_to_split] < (nn-1)*params['sl']):
breakpoint()
new_tips = np.arange(len(tips_to_split)) + num_total_segs
# print('segment(s) spliting, new tips', new_tips)
# breakpoint()
# branch_ids = mycelia['branch_id'][tips_to_split]
# print('branch(s) undergoing segment splitting : ', branch_ids)
# Record branch and segment id
if np.shape(mycelia['branch_id'])[0] <= max(new_tips):
mycelia = extend_mycelia(mycelia)
mycelia['branch_id'][new_tips] = mycelia['branch_id'][tips_to_split]
mycelia['seg_id'][new_tips] = mycelia['seg_id'][tips_to_split]+1
# Update neighbor list
for idx, tip in enumerate(tips_to_split):
mycelia['nbr_idxs'][tip].append(new_tips[idx])
mycelia['nbr_idxs'][new_tips[idx]] = [tip]
mycelia['nbr_num'][tips_to_split] += 1
mycelia['nbr_num'][new_tips] += 1
# Increase number of segments on branches that split
num_total_segs += len(tips_to_split)
# Store current lengths of splitting tips
current_lens = mycelia['seg_length'][tips_to_split]
# Redefine endpoint for segment behind the new tip
if (isCalibration == 0):
mycelia['xy2'][tips_to_split,0] = mycelia['xy1'][tips_to_split,0] + (params['sl']*np.cos(mycelia['angle'][tips_to_split])).flatten()
mycelia['xy2'][tips_to_split,1] = mycelia['xy1'][tips_to_split,1] + (params['sl']*np.sin(mycelia['angle'][tips_to_split])).flatten()
else:
mycelia['xy2'][tips_to_split,0] = mycelia['xy1'][tips_to_split,0] + (params['sl']*np.cos(0)).flatten()
mycelia['xy2'][tips_to_split,1] = mycelia['xy1'][tips_to_split,1] + (params['sl']*np.sin(0)).flatten()
# Redefine length of segment behind new tip
mycelia['seg_length'][tips_to_split] = params['sl']
# Starting endpoint for new tip
mycelia['xy1'][new_tips,:] = mycelia['xy2'][tips_to_split,:]
# Ending endpoint for new tip with modified angle
if (isCalibration == 0):
mycelia['angle'][new_tips] = mycelia['angle'][tips_to_split] + np.random.normal(0, params['angle_sd'], np.shape(mycelia['angle'][tips_to_split]))
mycelia['xy2'][new_tips,0] = mycelia['xy1'][new_tips,0] + ((current_lens - params['sl'])*np.cos(mycelia['angle'][new_tips])).flatten()
mycelia['xy2'][new_tips,1] = mycelia['xy1'][new_tips,1] + ((current_lens - params['sl'])*np.sin(mycelia['angle'][new_tips])).flatten()
else:
mycelia['angle'][new_tips] = mycelia['angle'][tips_to_split] + 0#np.random.normal(0, 0, np.shape(mycelia['angle'][tips_to_split]))
mycelia['xy2'][new_tips,0] = mycelia['xy1'][new_tips,0] + ((current_lens - params['sl'])*np.cos(mycelia['angle'][new_tips])).flatten()
mycelia['xy2'][new_tips,1] = mycelia['xy1'][new_tips,1] + ((current_lens - params['sl'])*np.sin(mycelia['angle'][new_tips])).flatten()
# Set length of new tip
mycelia['seg_length'][new_tips] = current_lens - params['sl']
# Designate new tip as a tip
mycelia['is_tip'][tips_to_split] = False
mycelia['is_tip'][new_tips] = True
# Update distance to septa information
mycelia['dist_to_septa'][new_tips] = mycelia['dist_to_septa'][tips_to_split]
mycelia['dist_to_septa'][tips_to_split] = 0
# Map to external grid
for tip_idx in new_tips:
mycelia = map_to_grid(mycelia, tip_idx, num_total_segs, x_vals, y_vals)
# Update nutrient distribution
# Percent of new growth compared to total
perct_new_size = (current_lens - params['sl'])/current_lens
# Store concentrations from originating segments
gluc_new = mycelia['gluc_i'][tips_to_split]
cw_new = mycelia['cw_i'][tips_to_split]
# Update new & originating segments
mycelia['gluc_i'][new_tips] = perct_new_size*gluc_new
mycelia['cw_i'][new_tips] = perct_new_size*cw_new
mycelia['gluc_i'][tips_to_split] = (1-perct_new_size)*gluc_new
mycelia['cw_i'][tips_to_split] = (1-perct_new_size)*cw_new
# Update distance to tip
if dist2Tip_new == 1:
dtt = nf.distance_to_tip_new(mycelia, num_total_segs)
else:
dtt = nf.distance_to_tip(mycelia, num_total_segs)
# breakpoint()
return mycelia, num_total_segs, dtt
# ----------------------------------------------------------------------------
# Extension - Main function for elongation
def extension(mycelia, params, num_total_segs, dtt, x_vals, y_vals,
isCalibration, dist2Tip_new, fungal_fusion,
chance_to_fuse,branch_rate):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
num_total_segs : int
Current total number of segments in the mycelium.
dtt : array
Contains the distance each segment is away from the nearest tip segment.
x_vals : list/array
The x-values of the external grid.
y_vals : list/array
The y-values of the external grid.
Returns
-------
mycelia : dictionary
Updated structural information of mycelia colony for all hyphal segments.
num_total_segs : int
Current total number of segments in the mycelium.
dtt : array
Contains the distance each segment is away from the nearest tip segment.
Purpose
-------
Driver function for elongation - determines which tips elongate, updates
the structural information and checks for septation and segment splitting.
"""
tip_idxs = (np.where(mycelia['is_tip'])[0]).tolist()
# Get the number density of segments around each segment
ndensity = [len(i) for i in mycelia['share_e'][:num_total_segs]]
# The purpose of the code below is apparently to prevent segments from growing in high density regions
# But why? This is not clear.
# This is done by filtering out segments that have a number density per grid greater than a certain threshold
# But this is based on the grid size, not on the actual number of segments per volume
#
# Find those segments that have greater than half of their grid filled by other segments
# But apply density filtering only after initial tips (ie, tip 3) have segmented
if 3 not in tip_idxs:
fidx = np.where(ndensity < np.int64(2)) # This is too sparse if the grid is large
#fidx = np.where(ndensity <= np.int64(params['dy']/params['hy_diam']*0.2))
#grid_area = (params['grid_len']*params['grid_len']*params['grid_height'])
#scale = 1.0e06/grid_area # convert from square microns to square millimeters
#scaled_density = ndensity*scale
#fidx = np.where(scaled_density >= params['max_hyphal_density'])
# Don't allow segments in high density regions to grow
#tip_idxs = list(set(tip_idxs) & set(fidx[0]))
# Check to see if the list is empty, and if so, return
if not tip_idxs:
return mycelia, num_total_segs, dtt
#K = params['Kg2_wall'] * mycelia['hyphal_vol']
dLdt = michaelis_menten(params['kg1_wall'],
params['Kg2_wall'],
mycelia['cw_i'][tip_idxs])
#extend_len = params['dt']*dLdt
extend_len = params['dt_i']*params['kg1_wall']*np.ones(np.shape([tip_idxs])).T
if any(extend_len > 1e2):
breakpoint()
# Cost to grow predetermined amount or shorten if cost is too much
extend_len, cost_grow_gluc, cost_grow_cw = cost_of_growth(mycelia, np.array(tip_idxs), extend_len)
if(np.shape(mycelia['cw_i'][tip_idxs]) != np.shape(cost_grow_cw)):
breakpoint()
if any(extend_len > 1e2):
breakpoint()
# If nutrient to extend, update tip
if max(extend_len) > 0:
# New endpoint update and concentration update
# print(tip_idxs, extend_len, cost_grow_gluc, cost_grow_cw)
mycelia = update_structure(mycelia, tip_idxs, extend_len, cost_grow_gluc, cost_grow_cw, isCalibration)
# if(np.any(np.isnan(mycelia['cw_i']))):
# xx = np.where(np.isnan(mycelia['cw_i']))
# mycelia['cw_i'][xx] = 0.0
##############################################################################
##############################################################################
# Check for fusion
if (fungal_fusion == 1):
for idx in tip_idxs:
mycelia = anastomosis(mycelia, idx, num_total_segs, chance_to_fuse)
if(np.any(np.isnan(mycelia['cw_i']))):
breakpoint()
##############################################################################
##############################################################################
# Check if septa forms (i.e. when tip compartment is 3x length of a compartment)
nn = 3
#if max(mycelia['dist_to_septa']) > 3*params['sl']*params['septa_len']:
if max(mycelia['dist_to_septa']) > nn*params['sl']*params['septa_len']:
mycelia = septa_formation(mycelia, num_total_segs, branch_rate)
# print('Septa formation from 3x length')
# if(np.any(np.isnan(mycelia['cw_i']))):
# breakpoint()
# Check if any tip segment splits
if max(mycelia['seg_length'][tip_idxs] > (nn-1)*params['sl']):
mycelia, num_total_segs, dtt = split_segment(mycelia, num_total_segs, x_vals, y_vals, isCalibration, dist2Tip_new)
# print('Septa formation from 2x length')
# if(np.any(np.isnan(mycelia['cw_i']))):
# breakpoint()
return mycelia, num_total_segs, dtt
# ----------------------------------------------------------------------------
def extend_mycelia(mycelia):
max_total_segs = np.shape(mycelia['cw_i'])[0]
new_max_total_segs = np.int64(max(np.shape(mycelia['cw_i']))*2)
new_array = np.resize(mycelia['branch_id'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['branch_id'] = new_array
new_array = np.resize(mycelia['seg_id'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['seg_id'] = new_array
new_array = np.resize(mycelia['xy1'],(new_max_total_segs,2))
new_array[max_total_segs:,:] = 0
mycelia['xy1'] = new_array
new_array = np.resize(mycelia['xy2'],(new_max_total_segs,2))
new_array[max_total_segs:,:] = 0
mycelia['xy2'] = new_array
new_array = np.resize(mycelia['angle'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['angle'] = new_array
new_array = np.resize(mycelia['seg_length'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['seg_length'] = new_array
new_array = np.resize(mycelia['seg_vol'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['seg_vol'] = new_array
new_array = np.resize(mycelia['dist_to_septa'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['dist_to_septa'] = new_array
new_array = np.resize(mycelia['xy_e_idx'],(new_max_total_segs,2))
new_array[max_total_segs:,:] = 0
mycelia['xy_e_idx'] = new_array
mycelia['share_e'].extend([None]*(new_max_total_segs-max_total_segs))
new_array = np.resize(mycelia['cw_i'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['cw_i'] = new_array
new_array = np.resize(mycelia['gluc_i'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['gluc_i'] = new_array
new_array = np.resize(mycelia['can_branch'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['can_branch'] = new_array
new_array = np.resize(mycelia['is_tip'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['is_tip'] = new_array
new_array = np.resize(mycelia['septa_loc'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['septa_loc'] = new_array
mycelia['nbr_idxs'].extend([None]*(new_max_total_segs-max_total_segs))
new_array = np.resize(mycelia['nbr_num'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['nbr_num'] = new_array
new_array = np.resize(mycelia['bypass'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['bypass'] = new_array
new_array = np.resize(mycelia['treha_i'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['treha_i'] = new_array
new_array = np.resize(mycelia['dist_from_center'],(new_max_total_segs,1))
new_array[max_total_segs:] = 0
mycelia['dist_from_center'] = new_array
return mycelia
# Branching - Main function for new branches
def branching(mycelia, sub_e_gluc, params, num_total_segs, dtt, x_vals, y_vals,
isCalibration, dist2Tip_new, fungal_fusion, restrictBranching,
chance_to_fuse, branch_rate=1.0):
"""
Parameters
----------
mycelia : dictionary
Stores structural information of mycelia colony for all hyphal segments.
num_total_segs : int
Current total number of segments in the mycelium.
dtt : array
Contains the distance each segment is away from the nearest tip segment.
x_vals : list/array
The x-values of the external grid.
y_vals : list/array
The y-values of the external grid.
Returns
-------
mycelia : dictionary
Updated structural information of mycelia colony for all hyphal segments.
num_total_segs : int
Current total number of segments in the mycelium.
dtt : array
Contains the distance each segment is away from the nearest tip segment.
Purpose
-------
Driver function for branching - determines which segments branch, updates
the structural information.
"""
reached_max_branches = False
# Get the number density of segments around each segment
ndensity = [len(i) for i in mycelia['share_e'][:num_total_segs]]
# Find those segments that have greater than half of their grid filled by other segments
#fidx = np.where(ndensity > np.int64(params['sl']/params['hy_diam']*0.2))
fidx = np.where(ndensity[4:] > np.int_(2))
# Don't allow segments in high density regions to branch
# mycelia['can_branch'][fidx] = False
use_original = 0
apical_dominance = 0
if (restrictBranching == 0):
potential_branch_idxs = (np.where(mycelia['can_branch'])[0])
else:
tmp_potential_branch_idxs = np.where(mycelia['can_branch'])[0]
# dtt is the distance - number of segments - to the nearest tip
restricting = np.where(dtt[tmp_potential_branch_idxs]<=restrictBranching)[0]
potential_branch_idxs = (tmp_potential_branch_idxs[restricting])
# if np.max(num_total_segs > 8):
# breakpoint()
# Enforce apical dominance such that if the nutrient concentration is high in the respective tip, branching is less likely
# This is done by reducing the probability of branching by the nutrient concentration
mycelia['branch_id'][potential_branch_idxs]
branch_tip_idx = np.intersect1d(mycelia['branch_id'],mycelia['is_tip'])
tip_idx = np.where(mycelia['is_tip'])[0]
if (apical_dominance == 1):
potential_branch_idxs = np.where(mycelia['gluc_i'][potential_branch_idxs] > mycelia['gluc_i'][tip_idx][potential_branch_idxs])[0]
# Apical dominance is when the tip has more nutrients available than the hyphal segments preciding the tip
tip_xy_e_idx = mycelia['xy_e_idx'][tip_idx][potential_branch_idxs]
branching_xy_e_idx = mycelia['xy_e_idx'][potential_branch_idxs]
# If the tip has more nutrients than the hyphal segments preciding the tip, then branching is less likely
potential_branch_idxs_test = np.where(sub_e_gluc[tip_xy_e_idx] < sub_e_gluc[branching_xy_e_idx])[0]
# Get the
# Reduce the number of branches by the branch rate
#fidx_range = np.arange(1,len(potential_branch_idxs),1, dtype=int)
#adjusted_branch_rate = branch_rate*(params['kg1_wall']/params['sl'])
#fidx = random.choices(fidx_range, k=np.int_(len(potential_branch_idxs)*branch_rate))
#potential_branch_idxs = potential_branch_idxs[fidx]
if not np.any(potential_branch_idxs):
return reached_max_branches, mycelia, num_total_segs, dtt
if(use_original == 1):
rand_vals = np.random.uniform(0, 1, (len(potential_branch_idxs),1))
# print('rand_vals : ', rand_vals)
# print('prob : ', params['branch_rate']*mycelia['cw_i'][potential_branch_idxs])
true_branch_ids = potential_branch_idxs[np.where((rand_vals - params['branch_rate']*mycelia['cw_i'][potential_branch_idxs]) < 0)[0]]
else:
active_trsprt_vel_cw = params['active_trsprt_vel_cw']
K_cw = active_trsprt_vel_cw*params['dt_i']
alpha_cw = michaelis_menten(1, K_cw,
mycelia['cw_i'][:num_total_segs])
nutrient_scaling = 1.0 #rich media
nutrient_scaling = 0.1 #minimal media
prob = alpha_cw * nutrient_scaling
#true_idx = np.where((prob - rand_vals).flatten() > 0)
#print('potential_branch_idxs = ', potential_branch_idxs)
branch_len = params['dt_i']*michaelis_menten(params['kg1_wall'],
params['Kg2_wall'],
mycelia['cw_i'][potential_branch_idxs])
len0 = params['kg1_wall']*params['dt_i']
branch_len0 = np.ones((len(potential_branch_idxs),1))*len0
# Does this ensure that a branch length is only as long as the available nutrients allow? But after ensuring tip growth?
branch_len, cost_branch_gluc, cost_branch_cw = cost_of_growth(mycelia, np.array(potential_branch_idxs), branch_len0)
# prob = 1.0 - np.exp(-(mycelia['cw_i'][potential_branch_idxs] - cost_multiple*cost_branch_cw)/(cost_multiple*cost_branch_cw))
#prob = np.exp((branch_len-1*branch_len0)/branch_len0)
#prob = michaelis_menten(1,params['Kg2_wall'],mycelia['cw_i'][potential_branch_idxs])
rand_vals = np.random.uniform(0, 1, (len(potential_branch_idxs),1))
#rand_vals = np.ones((len(potential_branch_idxs),1))* 0.5
#true_idx = np.where((prob - rand_vals).flatten() > 0)
# Does this ensure branching occurs on the periphery?
true_idx = np.where(mycelia['dist_from_center'][potential_branch_idxs] >= 0.5*max(mycelia['dist_from_center'][:num_total_segs][0]))[0]
# true_idx = np.where((prob - rand_vals).flatten() > 0)
true_branch_ids = potential_branch_idxs[true_idx]
branch_len = branch_len[true_idx]
cost_branch_cw = cost_branch_cw[true_idx]
cost_branch_gluc = cost_branch_gluc[true_idx]
if any(true_branch_ids):
# If nutrient to extend, update tip
if max(branch_len) > 0:
# Locations of new branch tips
new_tips = np.arange(len(true_branch_ids)) + num_total_segs
if np.max(new_tips) > np.shape(mycelia['cw_i'])[0]:
#reached_max_branches = True;
#return reached_max_branches, mycelia, num_total_segs, dtt
mycelia = extend_mycelia(mycelia)
# print('new branch(es):', new_tips)
if(np.shape(mycelia['cw_i'][new_tips]) != np.shape(cost_branch_cw)):
breakpoint()
# Record branch and segment id
num_branches = max(mycelia['branch_id'])+1
mycelia['branch_id'][new_tips] = (np.arange(len(true_branch_ids)) + num_branches).reshape(-1,1)
mycelia['seg_id'][new_tips] = np.zeros((len(true_branch_ids),1))
# Update neighbor list
for idx, tip in enumerate(true_branch_ids):
mycelia['nbr_idxs'][tip].append(new_tips[idx])
mycelia['nbr_idxs'][new_tips[idx]] = [tip]
mycelia['nbr_num'][true_branch_ids] += 1
mycelia['nbr_num'][new_tips] += 1
# Update total number of segments
num_total_segs += len(true_branch_ids)
# Determine position of the new branches
mycelia['xy1'][new_tips,:] = 0.5*(mycelia['xy1'][true_branch_ids,:] + mycelia['xy2'][true_branch_ids,:])
# This will be adjusted in the update_structure function below
mycelia['xy2'][new_tips,:] = mycelia['xy1'][new_tips,:]
# New endpoint
angle_sign = np.sign(np.random.uniform(-1,1,np.shape(mycelia['angle'][true_branch_ids])))
mycelia['angle'][new_tips] = mycelia['angle'][true_branch_ids] + angle_sign*np.random.normal(params['branch_mean'], params['branch_sd'], np.shape(mycelia['angle'][true_branch_ids]))
zero_cost = np.zeros(np.shape(cost_branch_cw))
mycelia = update_structure(mycelia, new_tips, branch_len, zero_cost, zero_cost, isCalibration)
# breakpoint()
# Designate new tip as a tip and set originating banch to can't branch
mycelia['can_branch'][true_branch_ids] = False
mycelia['is_tip'][new_tips] = True
# Map to external grid
for tip_idx in new_tips:
mycelia = map_to_grid(mycelia, tip_idx, num_total_segs, x_vals, y_vals)
# Update nutrient distribution
# Percent of new growth compared to total
perct_new_size = branch_len/(branch_len + mycelia['seg_length'][true_branch_ids])
# Store concentrations from originating segments