-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautomaticR0.py
2593 lines (2146 loc) · 80.1 KB
/
automaticR0.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
import numpy as np
from dataclasses import dataclass
import math
from math import *
import matplotlib.pyplot as plt
import time
import json
from tqdm import tqdm
import os
from scipy.signal import argrelextrema
PLUM = '#8E4585'
# Use GPU if wanted
useTorch = False
if useTorch:
from torchdiffeq import odeint
import torch
device = torch.device(
'cuda:' + str(0) if torch.cuda.is_available() else 'cpu')
print(
f'Using device {device} with name {torch.cuda.get_device_name(device)}')
else:
from scipy.integrate import odeint
@dataclass
class Delta:
flux: list
@dataclass
class Flux:
coef_indices: tuple([int, int])
rate_index: list
contact_index: list
types = [Flux]
functions = {}
derivatives = None
def storeFunctions(model: dict):
"""
Stores all functions from model into dictionary.
Inputs:
model: dictionary
Model for which we store the functions.
Outputs:
None.
"""
global functions
modelName = model['name']
functions[modelName] = {}
flows = model['flows']
for flowType_index, flowType in enumerate(flows):
for flow_index, flow in enumerate(flows[flowType]):
functions[modelName][f"{flowType_index, flow_index}"] \
= eval('lambda t: ' + str(flow['parameter']))
def removeDuplicates(liste: list) -> list:
"""
Removes duplicates from list.
Inputs:
liste: list
List to modify.
Outputs:
newList: list
List without duplicates.
"""
newList = list(dict.fromkeys(liste))
return newList
def rreplace(s, old, new, n):
"""
Replaces last n occurences in string.
Inputs:
s: string
Original string to modify.
old: string
What to replace in string.
new: string
What to replace with.
n: int
Number of instances to replace.
Outputs:
newString: string
Modified string.
"""
li = s.rsplit(old, n)
newString = new.join(li)
return newString
def plotCurves(xPoints: np.ndarray or list, curves: np.ndarray or list,
toPlot: list, labels: list,
title: str = 'Infection curves', style: list = None,
xlabel: str = 'Temps (jours)', ylabel: str = 'Nb. d\'individus',
scales: list = ['linear', 'linear'],
axes=plt, legendLoc: str = 'best',
colors: list = None, ycolor: str = 'black') -> None:
"""
Plots given curves. If xPoints are the same for all curves, give only np.ndarray.
Otherwise, a list of np.ndarrays works, in which case it has to be given for every curve.
Other options (title, labels, scales, etc.) are the same as for matplotlib.pyplot.plot function.
Inputs:
xPoints: np.ndarray or list
Points to use for x axis.
curves: np.ndarray or list
Points to use for y axis.
toPlot: list
Curves to plot in given curves.
labels: list
Labels to use for given curves.
title: string
Title for graph.
style: list
Styles to use for each curve.
xLabel: str
Label of x axis.
yLabel: str
Label of y axis.
scales: list
Scales to use for each axis.
axes: figure or axes
Where to draw the curves.
legendLoc: str
Where to place legend.
colors: list
Colors to use for each curve.
ycolor: str
Color to use for y axis.
Ouputs:
None.
"""
# Create missing lists if given None.
liste = list(range(max(toPlot) + 1))
if style == None:
style = ['-' for _ in liste]
if type(style) == type(''):
style = [style for _ in liste]
if colors == None:
colors = [f'C{x}' for x in liste]
k = 0
# TODO rewrite using try except
if type(xPoints) is np.ndarray: # Only one set of x coordinates
for curve in toPlot:
if labels == None:
axes.plot(xPoints,
curves[curve],
style[curve],
c=colors[curve])
k += 1
else:
axes.plot(xPoints,
curves[curve],
style[curve],
label=labels[curve],
c=colors[curve])
k += 1
else: # Different time scales
for curve in toPlot:
if labels == None:
axes.plot(xPoints[curve],
curves[curve],
style[curve],
c=colors[curve])
k += 1
else:
axes.plot(xPoints[curve],
curves[curve],
style[curve],
label=labels[curve],
c=colors[curve])
k += 1
if labels != None:
axes.legend(loc=legendLoc)
try:
axes.title(title)
axes.xlabel(xlabel)
axes.ylabel(ylabel, color=ycolor)
axes.xscale(scales[0])
axes.yscale(scales[1])
except:
axes.set_title(title)
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel, color=ycolor)
axes.set_xscale(scales[0])
axes.set_yscale(scales[1])
def verifyModel(model: dict, modelName: str, printText: bool = True) -> None:
"""
Verifies if model has the right properties. Might not be complete.
Inputs:
model: dict
Model to verify.
modelFile: str
Name to compare model with.
printText: bool
Whether or not to print debug text.
Ouputs:
None.
"""
# Try fixing the model if there are problems with nulls.
missingNulln = False
missingNullm = False
if 'Null_n' not in model['compartments']:
missingNulln = True
if 'Null_m' not in model['compartments']:
missingNullm = True
if missingNulln or missingNullm or 'Null' in getCompartments(model):
if printText:
print('Fixing missing empty nodes.')
flows = model['flows']
model['compartments']['Null_n'] = 0
model['compartments']['Null_m'] = 0
# We don't need Null anymore
if 'Null' in model['compartments']:
del model['compartments']['Null']
print('Model should be fixed...')
# Solve Null nodes in edges. Replace Null with their right instances.
flows = model['flows']
problem = False
for _, flowType in enumerate(flows):
for _, flow in enumerate(flows[flowType]):
for i, arg in enumerate(['to', 'from', 'rate', 'contact']):
if flow[arg].lower() == 'null' and arg in ['to', 'from', 'rate', 'contact']:
problem = True
# i even: change null to null_n
# i odd: change null to null_m
flow[arg] = 'Null' + ('_n' if not i % 2 else '_m')
if problem and printText:
print('Les noeuds vides sont réglés dans les arrêtes')
if model['name'] != modelName:
raise Exception(f"Model doesn\'t have right name in file.\n"
+ f"Name in file: {model['name']}. Wanted name: {modelName}.")
missing = []
flows = model['flows']
for flowType in flows:
for flow in flows[flowType]:
# Check for missing keys in flows
keys = list(flow.keys())
for p in ['from', 'to', 'rate', 'contact', 'parameter']:
if p not in keys and p not in missing:
missing.append(p)
# if p in keys and flow[p] == 'Null':
# if p in ['from', 'rate']:
# flow[p] = 'Null_n'
# print(flow)
# TODO check for flow informations to respect the structure defined
if missing != []:
missingStr = ', '.join(list(map(lambda x: f'"{x}"', missing)))
missingStr = rreplace(missingStr, ', ', ' and ', 1)
raise Exception(
f'Some flows are missing parameters {missingStr} in model {modelName}.')
if printText:
print('Model verified.')
return model
def loadModel(name: str, overWrite=True, printText: bool = True) -> dict:
"""
Loads model from file.
Inputs:
name: str
Name of model to load. Function will load model [name].json.
overWrite: bool
Whether or not to overwrite file after loading model.
printText: bool
Whether or not to print debug text.
Outputs:
model: dict
Model loaded.
"""
try:
with open(f'models/{name}.json', 'r') as file:
model = json.load(file)
except:
time.sleep(1)
try:
with open(f'models/{name}.json', 'r') as file:
model = json.load(file)
except:
raise Exception(f'Could not open file {name}.json.')
# Verify
model = verifyModel(model, name, printText=printText)
# Write to file
writeModel(model, overWrite=overWrite, printText=printText)
# Store functions in dictionary
storeFunctions(model)
return model
def initialize(model: dict, y0: dict, t: float, originalModel:
dict = None, r0: bool = True, printText: bool = True,
whereToAdd: str = 'to', scaled=False) -> None:
"""
This modifies model variable, but doesn't modify the file it comes from.
Inputs:
model: dict
Model which needs to be modified.
y0: dict
New values to initialize with.
t: float
Time at which we are initializing.
scaled: bool
Whether or not to rescale infected when initializing.
originalModel: dict
Dictionary to use as template for modified model. None if no modified model.
printText: bool
Whether or not to print debug text.
whereToAdd: str
Where to add new infections.
Outputs:
None.
"""
if originalModel != None:
# If we are initializing using another model
if printText and r0:
print(f'Initializing with values {roundDict(y0, 0)} at time {t}.')
weWant = getCompartments(originalModel)
if sorted(list(y0.keys())) != sorted(weWant):
raise Exception("Initialization vector doesn't have right entries.\n"
+ f" Entries wanted: {weWant}.\n"
+ f" Entries obtained: {list(y0.keys())}.")
if scaled:
infectious = infsScaled(originalModel, y0, t, whereToAdd)
else:
infectious = infs(originalModel, y0, t, whereToAdd)
toDuplicate = isolated(originalModel)
for compartment in y0:
try:
if compartment in toDuplicate:
model['compartments'][addI(
compartment, 0)] = infectious[compartment]
model['compartments'][addI(
compartment, 1)] = y0[compartment] \
- infectious[compartment]
except:
model['compartments'][addI(
compartment, 1)] = y0[compartment]
else:
# No need for any ajustments. Simply write the values.
for compartment in list(y0.keys()):
model['compartments'][compartment] \
= y0[compartment]
def getCompartments(model: dict) -> list:
"""
List of compartments in model file.
Inputs:
model: dict
Model of interest.
Ouputs:
compartments: list
List of compartments in model.
"""
compartments = list(model['compartments'].keys())
return compartments
def getFlowsByCompartments(model: dict) -> list:
"""
Get all inflows and outflows for model.
Inputs:
model: dict
Model of interest.
Ouputs:
FBC: list
Flows by compartments.
"""
compartments = getCompartments(model)
flows = model['flows']
# FlowByCompartment
FBC = [([], []) for _ in compartments]
for flowType_index, flowType in enumerate(flows):
for flow_index, flow in enumerate(flows[flowType]):
to_i = compartments.index(
flow['to'])
from_i = compartments.index(
flow['from'])
rate_i = list(map(compartments.index,
[x for x in flow['rate'].split('+') if not x.startswith('Null')]))
contact_i = list(map(compartments.index,
[x for x in flow['contact'].split('+') if not x.startswith('Null')]))
term = Flux((flowType_index, flow_index), rate_i, contact_i)
try:
# Inflow
FBC[to_i][0].append(term)
except:
pass
try:
# Outflow
FBC[from_i][1].append(term)
except:
pass
# Create delta (list of flows) with each flux
FBC = [[Delta(*[[f for f in flows if isinstance(f, T)] for T in types])
for flows in compartment] for compartment in FBC]
return FBC
def getPopNodes(model: dict) -> list:
"""
Return compartments that are in the population only.
Inputs:
model: dict
Model of interest.
Outputs:
weWant: list
List of compartments in population.
"""
compartments = getCompartments(model)
weWant = [x for x in compartments if not x.startswith(('Rt', 'Null'))]
return weWant
def getSusceptibleNodes(model: dict) -> list:
"""
Return all susceptible nodes, from definition 1.2.3 in thesis.
Inputs:
model: dict
Model of interest.
Outputs:
weWant: list
list of susceptible nodes in population.
"""
population = getPopNodes(model)
flows = model['flows']
weWant = []
for category in flows:
for flow in flows[category]:
# On veut des noeuds vides pour considérer les entrées et sorties
# Puisque les noeuds prennent de la place on les crée seulement lorsque nécessaire
_, _, v_r, _ = flow['from'], flow['to'], flow['rate'], flow['contact']
flowType = getFlowType(flow)
if flowType == 'contact': # we know v_r != Null
rates = v_r.split('+')
weWant += [node for node in rates if node not in weWant]
problems = [x for x in weWant if x not in population]
if problems != []:
print(f'Found a susceptible not in population. Excluding {problems}.')
return [x for x in population if x in weWant]
def getOtherNodes(model: dict) -> list:
"""
Return compartments that are not in the population.
Inputs:
model: dict
Model of interest.
Outputs:
weWant: list
List of compartments not in population.
"""
compartments = getCompartments(model)
weWant = [x for x in compartments if x.startswith(('Rt', 'Null'))]
return weWant
def getRtNodes(model: dict) -> list:
"""
Return compartments that are used for computing Rt's.
Inputs:
model: dict
Model of interest.
Outputs:
weWant: list
List of compartments for Rt's.
"""
compartments = getCompartments(model)
weWant = [x for x in compartments if x.startswith(('Rt'))]
return weWant
def getNodeValues(model: dict, state: np.ndarray or list, weWant: list) -> dict:
"""
Get every value for nodes in weWant, as dictionary.
Inputs:
model: dict
Model of interest.
state: np.ndarray or list
Value of each node in the model.
weWant: list
List of compartments of interest.
Ouputs:
dictNb: dict
Value of each node in weWant.
"""
if len(state.shape) != 1:
# Prevent complete solutions from being given as input.
# This is to be used on a single state.
raise Exception('2nd argument should be a vector, not matrix.')
dictNb = {}
compartments = getCompartments(model)
indexes = list(map(compartments.index, weWant))
for i in indexes:
dictNb[compartments[i]] = state[i]
dictNb['Sum'] = sum(state[i] for i in indexes)
return dictNb
def getPopulation(model: dict, state: np.ndarray or list) -> dict:
"""
Get every value for nodes in population as dictionary.
Inputs:
model: dict
Model of interest.
state: np.ndarray or list
Value of each node in the model.
Ouputs:
dictNb: dict
Value of each node in population.
"""
dictNb = getNodeValues(model, state, getPopNodes(model))
return dictNb
def getPopChange(model: dict, solution: np.ndarray) -> float:
"""
Get change in population from start to finish.
Inputs:
model: dict
Model of interest.
solution: np.ndarray
Solution given by solve function.
Outputs:
popChange: float
Change in population over solution given.
"""
popChange = getPopulation(
model, solution[-1])['Sum'] - getPopulation(model, solution[0])['Sum']
return popChange
def getOthers(model: dict, state: np.ndarray or list) -> dict:
"""
Get every value for nodes not in population as dictionary.
Inputs:
model: dict
Model of interest.
state: np.ndarray or list
Value of each node in the model.
Ouputs:
dictNb: dict
Value of each node not in population.
"""
dictNb = getNodeValues(model, state, getOtherNodes(model))
return dictNb
def getOtherChange(model: dict, solution: np.ndarray) -> float:
"""
Get change in other nodes from start to finish.
Inputs:
model: dict
Model of interest.
solution: np.ndarray
Solution given by solve function.
Outputs:
otherChange: float
Change in other nodes over solution given.
"""
otherChange = getOthers(
model, solution[-1])['Sum'] - getOthers(model, solution[0])['Sum']
return otherChange
def getCoefForFlux(model: dict, flux: Flux, t: float) -> float:
"""
Gets the coefficient for flux from the config file.
Inputs:
model: dict
Model of interest.
flux: Flux
Flux for which we need coefficient.
t: float
Time at which we compute coefficient.
Outputs:
value: float
Value of coefficient at given time.
"""
# Information read from stored functions.
coef = functions[model['name']
][f"{flux.coef_indices[0], flux.coef_indices[1]}"]
value = coef(t)
return value
def getCoefForFlow(flow: dict, t: float) -> float:
"""
Gets the coefficient for flow given from the config file.
Inputs:
flow: dict
Flow for which we need coefficient.
t: float
Time at which we compute coefficient.
Outputs:
value: float
Value of coefficient at given time.
"""
# Information read directly from flow dictionary.
string = str(flow['parameter'])
fonc = eval('lambda t: ' + string)
value = fonc(t)
return value
def evalDelta(model: dict, delta: Delta, state: np.ndarray or list,
t: float, t0: float) -> float:
"""
Computes the actual derivative for a delta (dataclass defined earlier).
Inputs:
model: dict
Model of interest
delta: Delta
List of Flows.
state: np.ndarray or list
Value of each node in the model.
t: float
Time at which we compute the derivative.
Outputs:
somme: float
Sum of all flux in delta.
"""
compartments = getCompartments(model)
N = sum(state[i] for i, comp in enumerate(compartments)
if not comp.startswith(('Null', 'Rt')))
rateInfluence = [sum(state[x] for x in flux.rate_index)
if len(flux.rate_index) > 1
else (state[flux.rate_index[0]]
if len(flux.rate_index) == 1
else 1)
for flux in delta.flux]
contactInfluence = [sum(state[x] for x in flux.contact_index) / N
if len(flux.contact_index) > 1
else (state[flux.contact_index[0]] / N
if len(flux.contact_index) == 1
else 1)
for flux in delta.flux]
coefsInfluence = [getCoefForFlux(model, flux, t if t0 is None else t0)
for flux in delta.flux]
somme = np.einsum('i,i,i', rateInfluence, contactInfluence, coefsInfluence)
return somme
def derivativeFor(model: dict, compartment: str):
"""
Get the derivative for a compartment as a function of state and time.
Inputs:
model: dict
Model of interest.
compartments: str
Compartment for which we want to get the derivative.
Outputs:
derivativeForThis: function
Function for derivative according to state and time.
"""
compartments = getCompartments(model)
i = compartments.index(compartment)
FBC = getFlowsByCompartments(model)
def derivativeForThis(state, t, t0):
# evalDelta takes care of getting the right coefficient for the derivative
inflows = evalDelta(model, FBC[i][0], state, t, t0)
outflows = evalDelta(model, FBC[i][1], state, t, t0)
return inflows - outflows
return derivativeForThis
def model_derivative(t: float, state: list or torch.Tensor or np.ndarray, t0: float) -> list:
"""
Gets the derivative functions for every compartments evaluated at given state.
Inputs:
state: list or torch.Tensor or np.ndarray
Value of each node in the model.
t: float
Time at which we are evaluating.
derivatives: list
List of functions containing the derivative of each compartment.
Outputs:
dstate_dt: float
Evaluation of the derivative of each compartment.
"""
# state = [x if x > 0 else 0 for x in state]
global derivatives
if useTorch:
dstate_dt = torch.FloatTensor(
[derivatives[i](state, t, t0) for i in range(len(state))])
else:
[t, state] = [state, t]
dstate_dt = np.array(
[derivatives[i](state, t, t0) for i in range(len(state))])
return dstate_dt
def solve(model: dict, tRange: tuple, refine: int = 100, printText=False, t0=None) -> tuple:
"""
Model solver, uses odeint from scipy.integrate.
Inputs:
model: dict
Model of interest.
tRange: tuple
Time range considered.
refine: int
Precision used for integration.
printText: bool
Whether or not to print debug text.
Outputs:
solution: np.ndarray
Solver solution for each compartment.
t_span: np.ndarray
All time values for the generated solution.
"""
ti = time.time()
global derivatives
compartments = getCompartments(model)
steps = (tRange[1] - tRange[0]) * refine + 1
t_span = np.linspace(tRange[0], tRange[1], num=math.ceil(steps))
derivatives = [derivativeFor(model, c)
for c in compartments]
y0 = np.array([model['compartments'][comp]
for comp in compartments])
if useTorch:
solution = odeint(model_derivative, torch.FloatTensor(y0),
torch.FloatTensor(t_span), args=(t0,))
else:
solution = odeint(model_derivative, y0, t_span, args=(t0,))
if printText:
print(f'Model took {time.time() - ti:.1e} seconds to solve.')
return solution, t_span
def getFlowType(flow: dict) -> str:
"""
Returns the type of a given flow.
Inputs:
flow: dict
Flow for which we want the type.
Outputs:
type: str
Type of the flow.
"""
if flow['rate'].startswith('Null'):
if flow['contact'].startswith('Null'):
return 'batch'
else:
raise Exception(f'Invalid flow type: {flow}.')
else:
if flow['contact'].startswith('Null'):
return 'rate'
else:
return 'contact'
def addI(node: str, i: int) -> str:
"""
Adds layer number to a given node.
Inputs:
node: str
Node name to modify.
i: int
Number to add.
Outputs:
newNode: str
Modified node name.
"""
if node.startswith(('Null', 'Rt')):
newNode = node
else:
newNode = (node + f'^{i}')
return newNode
def removeI(node: str) -> str:
"""
Get base node for a numbered one.
Inputs:
node: str
Node of interest.
Outputs:
newNode: str
Base node name.
"""
if len(node) > 1:
newNode = node[:-2] if node[-2] == '^' else node
else:
newNode = node
return newNode
def getI(node: str) -> str:
"""
Get layer number for node.
Inputs:
node: str
Node of interest.
Outputs:
i: int
Layer containing node.
"""
remove = len(removeI(node))
if remove == len(node):
return -1
else:
return int(node[remove + 1:])
def joinNodeSum(nodes: list) -> str:
"""
Joins a node list with a sum.
Inputs:
nodes: list
List of nodes to join.
Outputs:
sum: string
Sum of nodes as a string.
"""
return '+'.join(removeDuplicates(nodes))
def addIList(nodes: list, i: int) -> str:
"""
Adds i to all nodes in list "nodes".
Inputs:
nodes: list
List of nodes to update.
i: int
Superior index to add.
Outputs:
newNodes: list
Modified nodes.
"""
newNodes = joinNodeSum(list(map(
lambda x: addI(x, i),
nodes
)))
return newNodes
def splitVrVc(nodes, newCompartments) -> str:
"""
Splits vr or vc node if there is something to split to.
Inputs:
nodes: list
List of nodes to split.
newCompartments: list
List of compartments in the new model.
Outputs:
newVrVc: str
String containing split nodes.
"""
def splitIfExists(x):
if addI(x, 0) in newCompartments:
return joinNodeSum([addI(x, j) for j in range(2)])
else:
return addI(x, 1)
newVrVc = joinNodeSum(list(map(splitIfExists,
nodes)))
return newVrVc
def subSet(model, start: str, end: str):
"""
Gets all edges in graph as a dictionary.
Inputs:
model: dict
Model of interest.
u: str
Start point for search.
d: str
Destination for search
Outputs:
edges: dict
All edges in model.
"""