-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreateCoagModel.py
More file actions
2640 lines (2140 loc) · 103 KB
/
Copy pathcreateCoagModel.py
File metadata and controls
2640 lines (2140 loc) · 103 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
#!/usr/bin/env python3
import sys, re, io, os, textwrap, math, csv
import numpy as np
from collections import defaultdict
from collections import Counter
###############################
# Error and Usage Information #
###############################
# Check if the correct number of arguments is provided
if len(sys.argv) < 2:
print(textwrap.dedent("""
Python script to generate MATLAB code for Coagulation Biochemical Reactions.
Usage:
python3 createCoagModel.py StaticCoag.txt
Input File: StaticCoag.txt (List of Biochemical Reactions)
Output File(s): Separates outputs for initial conditions, parameters, and code.
(Assumes prefix based on input file)
- StaticCoagMatlab.m (assumes prefix).
- StaticCoagIC.m
- StaticCoagParams.m
- StaticCoagRename.m
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
Input File Specifications:
----------------------------
There are 3 classes of objects that can be specified:
(1) [OPTIONAL] Variable Specifications: Initial Conditions, Parameter Values, Special Species
(2) [OPTIONAL] Functions (to be used later for dilution/non-mass action biochemical kinetics)
(3) [REQUIRED] Biochemical Reactions
----------------------------
(1) Variable Specification:
----------------------------
- Comments/Whitespace: Anything following "#" is ignored; Whitespace is ignored.
- Parameter/Species names must start with a letter (no leading numbers).
- Parameter/Species names may contain: [0-9a-zA-Z_:]
- Users can define:
* Initial Conditions (must be a non-negative real number; DEFAULT = 0)
Ex:
IIa_IC = 5.0; #mu M
V_IC = 0;
* Parameter Values (real values of Initial Conditions; DEFAULT = 1)
Ex:
IIa_up = IIa_IC #mu M; Let's see if this works!
V_up = V_IC
PL_up = 1.0 #Set to be a random value.
* Special classes of species: LIPID, PLATELET, PLATELET_SITE
Ex:
PL = PLATELET #Platelet in Solution
PL_S = PROCOAG_PLATELET #Platelet in Subendothelium
PL_V = PROCOAG_PLATELET #Platelet in Volume
p2 = PLATELET_SITE
p5 = PLATELET_SITE
---------------
(2) Functions:
---------------
- Functions are defined as a name, list of arguments (comma separated) and body
- Function arguments can be a parameter, species name or a dummy variable (dummy:x)
- Examples:
FUNCTION A(IIa,e2P) = IIa/(e2P + IIa) #1 nM = 0.001 mu M
FUNCTION B(dummy:x, e2P) = x/(e2P + x)
--------------
(3) Dilution:
--------------
- A flag that turns on a dilution equation for every species.
- The dilution function (and any dependent reactions) must already be defined.
Ex:
DILUTION = Dilution(VolP,PL, PL_S, PL_V,IIa,k_pla_act,k_pla_plus,kact_e2,e2P)
FUNCTION Dilution(VolP,PL, PL_S, PL_V,IIa,k_pla_act,k_pla_plus,kact_e2,e2P) = (VolP)/((1-VolP)*(PL_S + PL_V))*dPdt(PL, PL_S, PL_V,IIa,k_pla_act,k_pla_plus,kact_e2,e2P)
FUNCTION dPdt(PL, PL_S, PL_V,IIa,k_pla_act,k_pla_plus,kact_e2,e2P) = + k_pla_act * PL * PL_S + k_pla_act * PL * PL_V + kact_e2 * A(IIa,e2P) * PL + k_pla_plus * PL * P_SUB
----------------------------
(4) Biochemical Equations:
----------------------------
- Assumes biochemical reactions (one per line) of the form:
LHS <-> RHS, Rates, TYPE
- Supports forward and reversible reactions.
- Reaction Operators allowed: '*', '+', '<->', '->'
- 5 Reaction Types:
* MASS_ACTION: Default (if no type given)
* FLOW: species entering or exiting reaction zone.
* LIPID: Binding on/off lipid (competition)
* FUNCTION: Concentration changing due to reaction zone
Example Reactions:
A + 2 * B -> C , k_1 #Forward
A + 2 * B <-> C , k_1 , k_2 #Reversible
Example Initial Conditions/Parameter Setting:
A_IC = 10.0 #\\mu M
B_IC = 1.0 #\\mu M
Lipid Binding Support:
- Allows non-mass action terms for lipid binding:
L_TF + II <-> II_st, kon_ii, koff_ii, nbs_ii, LIPID
- kon_ii units: 1/(concentration * time * binding sites)
Flow Reactant Support:
- Allows specification of flow species in two ways: list, reactions
- Requires that the upstream species for S has the name S_up
Example Flow List:
FLOW, kflow, IIa
Example Flow Reactions:
-> K, kflow, K_up, FLOW #Species Flowing In
K -> , kflow, FLOW #Flowing Flowing Out
Supported Features:
-----------------------------------
- Input file lines can be in any order. (For cases w/ duplicates first entry read is retained)
- Support for non-mass action lipid binding binding.
- Outputs lipid/platelet binding sites as a separate parameter vector (nbs)
- Can handle non-constant coefficients on the RHS for platelet sites and stores.
- Outputs Species and rates output in input order.
- Supports pure synthesis/degradation/in-out flow (e.g., "-> A", "B ->").
- Consolidates duplicate kinetic rates.
- Splits stoichiometric matrix for A + B -> A + C reactions.
- Removes duplicate reactions (even one side of bidirectional ones).
- Checks reaction rate dimensions for consistency.
- Initial conditions can be set in the input file.
In-Progress Features (Still Working On):
-----------------------------------
- Support for inline kinetic rate values:
Example:
A + B -> C, k1=0.1
A + B <-> C, kon, koff=100
Feature to Consider Developing:
-----------------------------------
- Allow setting rates and initial conditions separate external file.
- Improve MATLAB text wrapping for long lines.
- Add back support for Python code.
Current Version:
Suzanne Sindi, 05/06/2025
"""))
sys.exit("Usage: python3 createCoagModel.py StaticCoag.txt")
########################
# Supporting Functions #
########################
def getSubset(species_dict, *types):
"""
Returns a subset of species from species_dict that match one or more specified types.
Parameters:
- species_dict: The dictionary of species (e.g., specialSpecies).
- *types: One or more species types to filter by.
Returns:
- A dictionary containing species matching the specified types.
"""
# Ensure types is a tuple, even if only one type is passed
types_set = set(types)
# Filter the species_dict for entries matching the specified types
subset = {
name: info
for name, info in species_dict.items()
if info["type"] in types_set
}
return subset
def appendToSpecialSpecies(special_species_dict, species_list, species_type):
for species in species_list:
if species in special_species_dict:
existing_type = special_species_dict[species]
print(f"Error: Species '{species}' already assigned as type '{existing_type}', cannot reassign as '{species_type}'.")
else:
special_species_dict[species] = species_type
#Matlab can not handle ":"'s in variable names!
def transform_string(s):
return s.replace(':', 'b')
#Get Args: A(IIa,e2P) ->
def getArgs(function_expr):
match = re.search(r'\((.*?)\)', function_expr)
if match:
args_str = match.group(1) # everything inside the parentheses
return [arg.strip() for arg in args_str.split(',') if arg.strip()]
return []
#Converts List to a String;
def list_to_string(lst):
"""Convert a list into a comma-separated string."""
return ', '.join(map(str, lst))
# Flatten a list of lists into a single list
def flatten_list(lst_of_lists):
"""Flatten a list of lists into a single list."""
return [item for sublist in lst_of_lists for item in sublist]
#Keep only unique entries of a list
def unique_entries_only(lst):
"""Return only unique entries from a list."""
return list(set(lst))
#Keep only unique entries of a list IN ORDER
def unique_entries_in_order(lst):
"""Return only unique entries from a list, preserving their order."""
seen = set()
return [x for x in lst if not (x in seen or seen.add(x))]
def create_reaction(reactants, reactant_coeffs, products, product_coeffs, names, values, reaction_type, reaction_modifiers, reverse=False):
if reverse:
reactants, products = products, reactants
reactant_coeffs, product_coeffs = product_coeffs, reactant_coeffs
name = names[1]
value = values[1]
else:
name = names[0]
value = values[0]
return Reaction(
equation = formatFwdReaction(reactants, reactant_coeffs, products, product_coeffs),
rateName = name,
rateValue = value,
reactants = reactants,
reactant_coeffs = reactant_coeffs,
products = products,
product_coeffs = product_coeffs,
reactionType = reaction_type,
reactionModifiers = reaction_modifiers
)
def formatFwdReaction(reactants, reactant_coeffs, products, product_coeffs):
# Join reactants with their coefficients
reactant_str = " + ".join(
f"{coeff} * {reactant}" if coeff > 1 else reactant
for reactant, coeff in zip(reactants, reactant_coeffs)
)
# Join products with their coefficients
product_str = " + ".join(
f"{coeff} * {product}" if coeff > 1 else product
for product, coeff in zip(products, product_coeffs)
)
# Combine reactants and products into the final reaction string
final_string = f"{reactant_str} -> {product_str}"
return final_string
def parseFlowReactions(flowList, verbose=False):
formattedReactions = []
if verbose:
print(f"\n{'=' * 50}")
print(f"Step 1(d): Convert FLOW reactions to biochemical format")
print(f"{'=' * 50}")
for i, line in enumerate(flowList):
parts = [p.strip() for p in line.split(',')]
if len(parts) < 3:
print(f"\tLine {i+1}: Invalid format (too few parts) -> {line}")
continue
keyword, rate, *species = parts
if keyword != "FLOW":
print(f"\tLine {i+1}: Invalid keyword '{keyword}', expected 'FLOW'")
continue
for sp in species:
# First reaction: species exits the system
outRxn = f"{sp} -> , {rate}, FLOW"
# Second reaction: species appears along with its "up" version
sp_up = f"{sp}_up"
inRxn = f"-> {sp}, {rate}, {sp_up}, FLOW"
formattedReactions.append(outRxn)
formattedReactions.append(inRxn)
if verbose:
print(f"\tLine {i+1}: {sp}")
print(f"\t\tGenerated outRxn: {outRxn}")
print(f"\t\tGenerated inRxn : {inRxn}")
if verbose:
print(f"{'=' * 50}")
return formattedReactions
def parseReactions(reactions, plateletSites, verbose, verboseDetailed):
if verbose:
print(f"Step 2: Parsing the Biochemical Reacitons")
if verbose:
print(f"\tNumber of biochemical reactions: {len(biochemicalReactions)}")
print(f"\tSome of the Biochemical Reactions:")
num_reactions_to_print = min(previewVal, len(reactions))
for i in range(num_reactions_to_print):
print(f"\t\t" + biochemicalReactions[i])
print('-' * 50)
parsed_reactions = []
newRateParameters = []
for reaction in reactions:
if verbose: print(f"Processing Reaction: '{reaction}'")
# Parse the equation
result = parseEquation(reaction,plateletSites,verboseDetailed)
# Ensure result is valid before unpacking
if not result or all(val is None for val in result):
print(f"\tError: Invalid equation format in reaction: {reaction}")
continue # Skip this reaction
(reactants,reactantCoeffs,products,productCoeffs,rates,reaction_type,reaction_modifiers)=result
if verboseDetailed:
print(f"\tReactants = {reactants})")
print(f"\tCoeffs = {reactantCoeffs})")
print(f"\tProducts = {products}")
print(f"\tProducts Coeffs = {productCoeffs}")
print(f"\tRates = {rates}")
print(f"\tReaction Type = {reaction_type}")
print(f"\tReaction Modifiers = {reaction_modifiers}")
print(f"**********")
# Store (if needed) names and values for each rate
names = []
values = []
for key, rate in rates.items():
if '=' in rate:
name, value = rate.split('=')
names.append(name.strip()) # Store the name part
values.append(float(value.strip())) # Convert the value to a float
newRateParameters.append(Parameter(name, value))
else:
names.append(rate.strip()) # Store the rate if no '='
values.append(-1) # Assign -1 as a placeholder for missing values
reactionCount = len(rates);
if reactionCount == 1: # We add only 1 case, easy
parsed_reactions.append(create_reaction(reactants, reactantCoeffs, products, productCoeffs,names,values,reaction_type, reaction_modifiers) )
elif reactionCount == 2: # We add 2 objects for bi-directional reactions
parsed_reactions.append(create_reaction(reactants, reactantCoeffs, products, productCoeffs,names,values,reaction_type, reaction_modifiers,reverse=False) )
parsed_reactions.append(create_reaction(reactants, reactantCoeffs, products, productCoeffs,names,values,reaction_type, reaction_modifiers,reverse=True) )
else:
print(f"\tError: Invalid reaction count in: {reaction}")
continue
return parsed_reactions, newRateParameters
def parse_biochemical_equation(line):
parts = [p.strip() for p in line.split(",")]
if len(parts) < 2:
print(f"Error: Invalid format {line} (must have at least equation and rate)")
return None, None, None, None, None
equation_part = parts[0]
# Determine arrow type and split equation
if '<->' in equation_part:
arrow = '<->'
if len(parts) < 3:
print(f"Error: Bidirectional reaction must include both FWD and REV rates: {line}")
return None, None, None, None, None
lhs, rhs = [s.strip() for s in equation_part.split('<->')]
rates = {
"FWD_RATE": parts[1],
"REV_RATE": parts[2]
}
other = parts[3:]
elif '->' in equation_part:
arrow = '->'
lhs, rhs = [s.strip() for s in equation_part.split('->')]
rates = {
"RATE": parts[1]
}
other = parts[2:]
else:
print(f"Error: Equation must contain '->' or '<->': {line}")
return None, None, None, None, None
return lhs, rhs, arrow, rates, other
def parse_reaction_type(other, reactants, products, coefficients):
known_types = {"LIPID", "FLOW", "MASS_ACTION", "FUNCTION"}
reactionModifiers = {}
if len(other) == 0:
maybe_type = "MASS_ACTION"
else:
maybe_type = other[-1]
if maybe_type not in known_types:
print(f"Error: Unknown reaction type '{maybe_type}'")
return None, None
# Handle based on type
if maybe_type == "LIPID":
if len(other) != 2:
print(f"Error: LIPID reactions must have exactly one modifier before the type — got {other[:-1]}")
return None, None
reactionModifiers["bindingSites"] = other[0]
elif maybe_type == "FLOW":
if len(other) == 2 and len(reactants) == 0: #In: ->K, kflow, Other={K_up, FLOW
reactionModifiers["upstream"] = other[0]
elif len(other) == 1 and len(reactants) == 1: #Out: K->, kflow, Other={FLOW}
reactionModifiers["downstream"] = "outflow"
else:
print(f"Error: FLOW reaction doesn't have expected in/out flow structure")
return None, None
elif maybe_type == "FUNCTION":
if len(other) > 1:
function_expr = ",".join(other[:-1]) # Join all but the last element
reactionModifiers["function"] = function_expr
reactionModifiers["args"] = getArgs(function_expr)
else:
print(f"Error: FUNCTION reactions must include a function expression — got none")
return None, None
# MASS_ACTION doesn't need anything extra
#Add if we have any values in products or coefficients
for key, value in zip(products, coefficients):
reactionModifiers[key] = value
return maybe_type, reactionModifiers
def parseEquation(equationString, plateletSites, verbose=False):
#Remove trailing whitespace
equationString = equationString.split("#")[0].strip()
#Pars into components: lhs arrow rhs, rates, other
lhs, rhs, arrow, rates, other = parse_biochemical_equation(equationString)
if verbose:
print(f"NEW: Equation = {equationString}")
print(f"NEW: LHS = {lhs}")
print(f"NEW: RHS = {rhs}")
print(f"NEW: Arrow = {arrow}")
print(f"NEW: Rates = {rates}")
print(f"NEW: Other = {other}")
#(1) Process the LHS and RHS of the biochemical equation:
reactants = [r.strip() for r in lhs.split('+')] if lhs.strip() else []
products = [p.strip() for p in rhs.split('+')] if rhs.strip() else []
# Extract_coefficients to process reactants and products
# Note: We can only handle non integer coefficients on the RHS. Will throw an error
reactantCoeffs, reactants, plateletSiteReactants, plateletSiteReactantCoeffs = extract_coefficients(reactants,plateletSites,"LHS")
productCoeffs, products, plateletSiteProducts, plateletSiteProductCoeffs = extract_coefficients(products,plateletSites,"RHS")
# Check LHS
if any(x is None for x in [
reactantCoeffs, reactants, plateletSiteReactants, plateletSiteReactantCoeffs
]):
print(f"Error: Malformed equation on LHS - {equation}")
return None, None, None, None, None, None, None
# Check RHS
if any(x is None for x in [
productCoeffs, products, plateletSiteProducts, plateletSiteProductCoeffs
]):
print(f"Error: Malformed equation on RHS - {equation}")
return None, None, None, None, None, None, None
#(2) Parse OTHER:
reactionType, reactionModifiers = parse_reaction_type(other,reactants, plateletSiteProducts, plateletSiteProductCoeffs)
if verbose:
print(f"reactantCoeffs: {reactantCoeffs}")
print(f"reactants: {reactants}")
print(f"plateletSiteReactants: {plateletSiteReactants}")
print(f"plateletSiteReactantCoeffs: {plateletSiteReactantCoeffs}")
print(f"productCoeffs: {productCoeffs}")
print(f"products: {products}")
print(f"plateletSiteProducts: {plateletSiteProducts}")
print(f"plateletSiteProductCoeffs: {plateletSiteProductCoeffs}")
print(f"reactionType: {reactionType}")
print(f"reactionModifiers: {reactionModifiers}")
#(3) Check if we have the right number of rates.
# Rate is a dictionary of either "RATE" or "FWD_RATE" "REV_RATE"
reaction_count = len(rates)
if reaction_count > 1 and reactionType not in {"MASS_ACTION", "LIPID"}:
print(f"Error in Equation = {equation}: Only MASS_ACTION and LIPID reactionTypes can be bidirectional")
return None, None, None, None, None, None, None
if verbose: print(f"**************")
return reactants, reactantCoeffs, products, productCoeffs, rates, reactionType, reactionModifiers
# Extract the Coefficients for a Set of Reactants
# Added: plateletSiteBool to check if there's plateletSites in the equation!
# This should only happen with type PLATELET_ACTIVATION
def extract_coefficients(terms, plateletSites, side=None):
plateletSitesFound = [] # Stores species found in plateletSites
plateletSiteCoeffs = [] # Stores corresponding coefficients
# Check if the input contains only an empty string
if len(terms) == 1 and terms[0] == '':
return [], [], plateletSitesFound, plateletSiteCoeffs
coeffs = []
species = []
for term in terms:
term = term.strip()
found_platelet_species = None
platelet_coeff = "1" # Default coefficient is 1
if '*' in term:
parts = term.split('*')
for part in parts:
stripped_part = part.strip()
if stripped_part in plateletSites:
found_platelet_species = stripped_part
else:
platelet_coeff = stripped_part
else:
if term in plateletSites:
found_platelet_species = term
if found_platelet_species:
# Error check if we're on the LHS
if side == "LHS":
try:
int_val = int(platelet_coeff) # Check if it's numeric
except ValueError:
print(f"Error: Non-numeric coefficient '{platelet_coeff}' for platelet site '{found_platelet_species}' on LHS of equation {terms}.")
return None, None, None, None
else:
coeffs.append(int_val) # Store numeric version
else:
coeffs.append(1) # On RHS or general case, use default 1
species.append(found_platelet_species)
plateletSitesFound.append(found_platelet_species)
plateletSiteCoeffs.append(platelet_coeff) # Store original value as string
else:
# Match terms with coefficients followed by '*'
match = re.match(r'(\d*)\s*\*\s*(\S+)', term)
if match:
coeff_str, species_name = match.groups()
coeff = int(coeff_str) if coeff_str else 1
else:
# Match terms with optional coefficients without '*'
match = re.match(r'(\d*)\s*(\S+)', term)
if match:
coeff_str, species_name = match.groups()
coeff = int(coeff_str) if coeff_str else 1
else:
print(f"Error: Invalid term format: {term}")
coeffs.append(1)
species.append(term.strip())
continue
coeffs.append(coeff)
species.append(species_name.strip())
return coeffs, species, plateletSitesFound, plateletSiteCoeffs
def parseInputFile(verbose=False):
# Initialize biochemical arrays and counters
biochemicalReactions = []
initialConditions = [] # User-specified initial conditions
specialSpecies = [] # Special Species: Lipid, Platelet, Sites, Stores
parameterCondition = [] # User-specified parameters (not in-line)
functionCondition = [] # Dilution and platelet activation
flowList = []
dilutionCondition = [] # Where we store dilution function
numReactionsReadIn = 0
numInitialConditionsReadIn = 0
numLipidSpecies = 0
numPlateletSpecies = 0
numPlateletSites = 0
numPlateletStores = 0
numParametersReadIn = 0
numFunctionsDefined = 0
numFlowListDefined = 0
numDilutionCondition = 0
DILUTION = False #Flag for if we turn on dilution or not.
if verbose:
print(f"{'-' * 50}")
print(f"Step 0 Preprocessing of {sys.argv[1]}")
try:
with open(sys.argv[1], 'r') as file:
for line in file:
line = line.rstrip() # Remove trailing newline characters
# Ignore blank lines or comments
if not line or line.startswith('#'):
continue
# Remove inline comments after '#'
line = line.split('#')[0].rstrip()
# Split the line by commas
fields = line.split(',')
##(Q) Is this a special species?
if "= LIPID" in line:
specialSpecies.append({"type": "LIPID", "line": line.replace("= LIPID", "").strip()})
numLipidSpecies += 1
if verbose: print(f"\t\tLipid Species: {line}")
elif "= PLATELET_SITE" in line:
specialSpecies.append({"type": "PLATELET_SITE", "line": line.replace("= PLATELET_SITE", "").strip()})
numPlateletSites += 1
if verbose: print(f"\t\tPlatelet Site: {line}")
elif "= PLATELET_STORE" in line:
specialSpecies.append({"type": "PLATELET_STORE", "line": line.replace("= PLATELET_STORE", "").strip()})
numPlateletStores += 1
if verbose: print(f"\t\tPlatelet Store: {line}")
elif "= PLATELET" in line:
specialSpecies.append({"type": "PLATELET", "line": line.replace("= PLATELET", "").strip()})
numPlateletSpecies += 1
if verbose: print(f"\t\tPlatelet Species: {line}")
elif "= PROCOAG_PLATELET" in line:
specialSpecies.append({"type": "PROCOAG_PLATELET", "line": line.replace("= PROCOAG_PLATELET", "").strip()})
numPlateletSpecies += 1
if verbose: print(f"\t\tPlatelet Species: {line}")
#(Q2): Do we start with function? Then it's a function!
elif line.lstrip().startswith("FUNCTION"):
functionCondition.append(line)
numFunctionsDefined += 1
if verbose: print(f"\t\tFunctions: {line}")
#(Q3): Do we start the line with FLOW? Then it's a flow LIST!
elif line.lstrip().startswith("FLOW"):
flowList.append(line);
numFlowListDefined += 1
if verbose: print(f"\t\tFlow List: {line}")
#(Q4): Do we start with DIULTION? Then DILUTION = True and we go!
elif line.lstrip().startswith("DILUTION"):
DILUTION = True;
dilutionCondition.append(line)
if verbose: print(f"\t\tDilution is True: {line}")
#(Q5): Is this an intial condition?
elif "_IC" in line.split('=')[0].strip(): # Check if it's an initial condition
initialConditions.append(line)
numInitialConditionsReadIn += 1
if verbose: print(f"\t\tInitial Condition: {line}")
#(Q6): Does it contain a comma? Then Try for biochemical equation
elif len(fields) > 1:
biochemicalReactions.append(line)
numReactionsReadIn += 1
if verbose: print(f"\t\tBiochemical Equation: {line}")
else:
# Assume it's a parameter if it's neither a species nor an initial condition
parameterCondition.append(line)
numParametersReadIn += 1
if verbose: print(f"\t\tParameter: {line}")
except IOError:
sys.exit(f"Couldn't open {sys.argv[1]}")
# Print output summary
if verbose:
print(f"DONE: Step 0 Preprocessing of {sys.argv[1]}")
print(f"{'-' * 50}")
# Define headers
headers = ["Category", "Count"]
data = [
("Biochemical Reactions", numReactionsReadIn),
("Initial Conditions", numInitialConditionsReadIn),
("Lipid Species", numLipidSpecies),
("Platelet Binding Sites",numPlateletSites),
("Platelet Stores", numPlateletStores),
("Platelet Species", numPlateletSpecies),
("Parameters", numParametersReadIn),
("Functions", numFunctionsDefined),
("Flow List", numFlowListDefined),
("Dilution Status", DILUTION )
]
# Print table header
print(f"\n{'=' * 50}")
print(f"{'Step 0: Processed Input File':^30}")
print(f"{'=' * 50}")
print(f"{headers[0]:<30} | {headers[1]:>10}")
print("-" * 50)
# Later, during printing:
for category, count in data:
display_value = str(count) if isinstance(count, bool) else count
if count>0:
print(f"{category:<30} | {display_value:>10}")
# Print done message and finish with a line
print(f"{'=' * 50}\n")
return {
"biochemicalReactions": biochemicalReactions,
"initialConditions": initialConditions,
"specialSpecies": specialSpecies,
"parameterCondition": parameterCondition,
"functionCondition": functionCondition,
"flowList": flowList,
"DILUTION" : DILUTION,
"dilutionCondition": dilutionCondition,
"counts": {
"numReactionsReadIn": numReactionsReadIn,
"numInitialConditionsReadIn": numInitialConditionsReadIn,
"numLipidSpecies": numLipidSpecies,
"numPlateletSpecies": numPlateletSpecies,
"numPlateletSites": numPlateletSites,
"numParametersReadIn": numParametersReadIn,
"numFunctionsDefined": numFunctionsDefined,
"numFlowListDefined": numFlowListDefined,
}
}
def parseSpecies(lines, verbose=False):
allowed_types = { "PLATELET", "PROCOAG_PLATELET", "LIPID",
"PLATELET_SITE", "PLATELET_STORE"}
species_dict = {}
error_flag = False
for entry in lines:
species_type = entry.get('type')
line = entry.get('line', '').strip()
if species_type not in allowed_types:
print(f"Error: Invalid species type '{species_type}' in entry: {entry}")
error_flag = True
continue
parts = [p.strip() for p in line.split(',')]
if not parts or not parts[0]:
print(f"Error: Empty or invalid species name in entry: {entry}")
error_flag = True
continue
name = parts[0]
modifier = parts[1] if len(parts) > 1 else ""
if name in species_dict:
print(f"Error: Duplicate species name '{name}' detected.")
error_flag = True
continue
if species_type in {"PLATELET_STORE", "PLATELET_SITE"} and modifier == "":
print(f"Error: Species '{name}' of type '{species_type}' must have a modifier.")
error_flag = True
continue
species_dict[name] = {
"type": species_type,
"modifier": modifier
}
# Verbose: Print nicely formatted table
if verbose:
print(f"{'=' * 50}")
print(f"{'Step 1(b): Special Species':^30}")
print(f"{'=' * 50}")
print(f"{'Name':<12}| {'Type':<20} | Modifier")
print("-" * 50)
# Sort by type, then by name
sorted_items = sorted(species_dict.items(), key=lambda x: (x[1]["type"], x[0]))
for name, info in sorted_items:
type_str = info["type"]
mod_str = info["modifier"] if info["modifier"] else "[None]"
print(f"{name:<12}| {type_str:<20} | {mod_str}")
print("=" * 50)
return species_dict, error_flag
def parseInitialConditions(initialConditions, verbose=False):
parsed_ICs = []
seen_names = set() # A set to track names that have been parsed
duplicates = [] # List to store any duplicates found
for ic_str in initialConditions:
ic_str = ic_str.strip() # Remove leading/trailing spaces
# Remove comments (anything after #)
ic_str = ic_str.split("#", 1)[0].strip()
if not ic_str:
continue # Skip empty or fully commented-out lines
# Ensure there is exactly one '='
if ic_str.count("=") != 1:
print(f"\t⚠️ Error: Invalid format in '{ic_str}'. Must contain exactly one '='.")
continue
try:
name, value_str = ic_str.split("=") # Guaranteed to have one '=' due to check above
name = name.strip()
value_str = value_str.strip()
# Ensure the name matches the correct format (String_IC)
if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*_IC$", name):
corrected_name = re.sub(r"(_[iI][cC])$", "_IC", name) # Fix capitalization
if corrected_name != name:
print(f"\t🔄 Auto-corrected '{name}' to '{corrected_name}'")
name = corrected_name
else:
print(f"\t⚠️ Error: '{name}' is invalid. Should match 'String_IC'. Did you mean '{name}_IC'?")
continue # Skip invalid entries
# Clean the value string: Remove any extra characters or units (e.g., semicolon)
value_str = ''.join(filter(lambda x: x.isdigit() or x == '.', value_str)) # Keep digits and decimal points
# Convert value to float and check if non-negative
value = float(value_str)
if value < 0:
print(f"\t⚠️ Error: Value for '{name}' must be non-negative. Found {value}.")
continue
# Check for duplicates
if name in seen_names:
duplicates.append(name) # Add to duplicates list
continue # Skip adding this duplicate to the final list
else:
seen_names.add(name) # Add the name to the set of seen names
# Create InitialCondition object and append to the result list
parsed_ICs.append(InitialCondition(name, value))
except ValueError:
print(f"\t⚠️ Error: Could not parse value in '{ic_str}'. Ensure RHS is a non-negative number.")
except Exception as e:
print(f"\t❌ Unexpected error while parsing '{ic_str}': {e}")
# Report duplicates if any
if duplicates:
print(f"\t⚠️ Error: Found duplicates in initial conditions: {', '.join(duplicates)} (retaining only 1st value")
if verbose:
# Define headers for the initial conditions table
ic_headers = ["Initial Condition Name", "Value"]
# Create a data list for parsed initial conditions
ic_data = [(ic.name, ic.value) for ic in parsed_ICs] # Assuming parsed_ICs is a list of InitialCondition objects
# Print table header for initial conditions
print(f"{'=' * 50}")
print(f"Step 1(a): Specified Intial Conditions")
print(f"{'=' * 50}")
print(f"{ic_headers[0]:<30} | {ic_headers[1]:>10}")
print("-" * 50)
# Print each parsed initial condition in the data list
for name, value in ic_data:
print(f"{name:<30} | {value:>10.3f}") # Format value to 2 decimal places
# Print done message and finish with a line
print(f"{'=' * 50}\n")
return parsed_ICs
def parseFunction(functionsDefined,verbose=False):
parsed_functions = []
keyword = "FUNCTION"
function_pattern = re.compile(
rf"^{keyword}\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*=\s*(.+)$"
)
for func in functionsDefined:
match = function_pattern.match(func.strip())
if not match:
if verbose:
print(f"\tInvalid function format: {func}")
continue # Skip invalid functions
name, args, body = match.groups()
# Validate function name (MATLAB/Python compatibility)
if not name.isidentifier():
if verbose:
print(f"\tInvalid function name: {name}")
continue
# Validate arguments (should be valid variable names, comma-separated)
args_list = []
dummy_args = []
for raw_arg in args.split(","):
arg = raw_arg.strip()
if not arg:
continue
if arg.startswith("dummy:"):
arg_name = arg[len("dummy:"):]
dummy_args.append(arg_name)
args_list.append(arg_name)
else:
args_list.append(arg)
# Validate argument names
if not all(arg.isidentifier() for arg in args_list):
if verbose:
print(f"\tInvalid function arguments: {args}")
continue
# Validate expression (basic check: should not be empty)
body = body.strip()
if not body:
if verbose:
print(f"\tInvalid function body: {func}")
continue
# Store valid function details
parsed_functions.append({"name": name, "args": args_list, "dummy_args": dummy_args,"body": body})
#if verbose:
#print(f"\tValid function parsed: {name}({', '.join(args_list)}) = {body}")
if verbose:
# Create a data list for parsed initial conditions
print(f"\n{'=' * 50}")
print(f"Step 1(c): Parsed Functions")
print(f"{'=' * 50}")
for fVal in parsed_functions: # Assuming parsed_ICs is a list of InitialCondition objects
# Print table header for initial conditions
print(f"{fVal}")
return parsed_functions
def parseDilution(dilutionCondition,verbose=False):
#Should look like this:
#DILUTION = FUNCTION Dilution(Vp,PL, PL_S, PL_V,IIa,k_pla_act,k_pla_plus,kact_e2,e2P)
parsed_dilution = []
# Pattern: DILUTION = FunctionName(arg1, arg2, ...)
dilution_pattern = re.compile(
r"^\s*DILUTION\s*=\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*$"
)
for func in dilutionCondition:
match = dilution_pattern.match(func.strip())
if not match:
if verbose:
print(f"\tInvalid dilution format: {func}")
continue # Skip invalid functions
name, args = match.groups()
# Validate function name (MATLAB/Python compatibility)
if not name.isidentifier():
if verbose:
print(f"\tInvalid dilution function name: {name}")
continue
# Validate arguments (should be valid variable names, comma-separated)
args_list = [arg.strip() for arg in args.split(",") if arg.strip()]
if not all(arg.isidentifier() for arg in args_list):
if verbose:
print(f"\tInvalid dilution function arguments: {args}")
continue