-
Notifications
You must be signed in to change notification settings - Fork 0
/
createMatlabFile.py
1164 lines (928 loc) · 41.8 KB
/
createMatlabFile.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
import sys, re, io, os, textwrap, math, csv
from collections import defaultdict
###############################
# Error and Usage Information #
###############################
# Check if the correct number of arguments is provided
if len(sys.argv) < 2:
print(textwrap.dedent("""
Python code that generates a Matlab Code for Law of Mass action Reactions
Use: python3 createMatlabFile.py StaticCoag.txt
StaticCoag.txt:
- Can contain comments that are proceeded with "#" (will be ignored)
- On any line, anything after a "#" will be ignored
- Can contain whitespace (will be ignored)
- Two types of structure are allowed for biochemical reactions: Forward, Reversible
- Can set kinetic rate values when defining biochemical reactions.
SINGLE_REACTION , RATE_VARIABLE
ex:
A + 2 * B -> C , k_1
In the case of reversible reactions, two rates must be specified, the forward reaction
is always FIRST, eg:
A + 2 * B <-> C , k_1 , k_2
**Warning: Any invalid reactions will be skipped (and output to the screen).
Output File: StaticCoagMatlab.m (assumes prefix).
Requirements:
1) Only the operators '*', '+', '<->', and '->' are allowed
2) Reactions should be pre-simplified, this code will NOT reduce algebra
3) Species names can only contain [0-9a-zA-Z_:]
4) Species names MUST begin with a letter - no leading numbers allowed
New Features (11/07/2024):
1) Allows for specifying the value of the kinetic rates in the reacitons:
Allowable:
A + B -> C, k1=0.1
A + B <-> C, kon, koff=100
2) Can set initial conditions within the equations file.
MIGHT NOT BE VALIE
New Features (08/19/2024):
1) Allows for pure synthesis or pure degradation. ( -> A, B ->)
2) Handles comments/white space in the biochemical equation file.
3) Handles duplicate kinetic rates (i.e., p vector is consolidated)
4) Handles A + B -> A + C reactions (splits stochiometric matrix)
5) Checks for (and removes) duplicate reactions. (i.e., identical reaction)
-> Even if the reaction is 1 side of a bi-directional reaction.
6) Checks that the dimension of reactions rates is the SAME (?).
Coag Specific Changes:
1) Creates variables to track active and in-active bound lipid sites (s and _st)
-> Counts the number of "s" and "st" in each species name.
2) Separately creates outputs for initial conditions, parameters and code.
-> Could do a --coag flag = false to do the original mode.
Other Features to Consider:
1) Keep the species/rates in the same order the StaticCoag.txt file was in <-Helpful
-> Currently sorting species alphabetically, rates are not in any particular order.
2) Set the rates of reactions and initial conditions based on a file. <- Helpful
-> Could have a user input values (separate file) and use 1 for missing values.
3) Original version allowed "=" operator. Not sure what this was for.
4) Text wrap for the long lines in Matlab. (Currently half-implemented)
Based on previous Python Code by:
Michael Stobb (Originally written on 8/4/2023)
Current Version:
Suzanne Sindi
11/07/2024
"""))
sys.exit("Usage: python3 createMatlabFile.py StaticCoag.txt")
########################
# Supporting Functions #
########################
#Matlab can not handle ":"'s in variable names!
def transform_string(s):
#return s.replace(':', '_')
return s.replace(':', 'b')
#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))
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 parseReactions(reactions):
parsed_reactions = []
for reaction in reactions:
# Split the reaction line by commas
parts = [part.strip() for part in reaction.split(',')]
# Check if we have at least the equation and one rate constant
if len(parts) < 2:
print(f"\tError: Invalid format {reaction} (not enough parts)")
continue
# Separate the equation and rate constants
equation = parts[0]
rate_constants = parts[1:]
# Sanity check for number of rate constants based on the reaction direction
if '<->' in equation:
# For uni-directional reactions, we expect exactly 1 rate constant
if len(rate_constants) != 2:
print(f"\tError: Bi-directional reaction '{reaction}' must have exactly 2 rate constants.")
continue
elif '->' in equation:
# For bi-directional reactions, we expect exactly 2 rate constants
if len(rate_constants) != 1:
print(f"\tError: Uni-directional reaction '{reaction}' must have exactly 1 rate constant.")
continue
else:
print(f"\tError: Invalid reaction format (must include '->' or '<->'): {reaction}")
continue
# Parse the equation
result = parseEquation(equation)
if result is None:
print(f"\tError: Invalid equation format in reaction: {reaction}")
continue
reactionCount, reactants, reactantCoeffs, products, productCoeffs = result
# Parse the rate constants;
names = []
values = []
for rateString in rate_constants:
# Check if there's an '=' symbol, which indicates a rate constant with a value
if '=' in rateString:
name, value = rateString.split('=')
names.append(name.strip())
values.append(float(value.strip())) # Convert the value to a float
else:
# If no '=' symbol, it's just a symbolic rate constant (e.g., "kon")
names.append(rateString.strip())
values.append(-1) # Unrealistic value so we know this wasn't set to a number
if reactionCount == 1: # We add only 1 case, easy
# Create a Reaction object and add to the list
reaction_obj = Reaction(
equation=equation,
rateName=names[0],
rateValue=values[0],
reactants=reactants,
reactant_coeffs=reactantCoeffs,
products=products,
product_coeffs=productCoeffs
)
parsed_reactions.append(reaction_obj)
elif reactionCount == 2: # We add 2 objects for bi-directional reactions
reaction_fwd = Reaction(
equation=formatFwdReaction(reactants, reactantCoeffs, products, productCoeffs),
rateName=names[0],
rateValue=values[0],
reactants=reactants,
reactant_coeffs=reactantCoeffs,
products=products,
product_coeffs=productCoeffs
)
reaction_rev = Reaction(
equation=formatFwdReaction(products, productCoeffs, reactants, reactantCoeffs),
rateName=names[1],
rateValue=values[1],
reactants=products,
reactant_coeffs=productCoeffs,
products=reactants,
product_coeffs=reactantCoeffs
)
parsed_reactions.append(reaction_fwd)
parsed_reactions.append(reaction_rev)
else:
print(f"\tError: Invalid equation format in reaction: {reaction}")
continue
return parsed_reactions
# Adjusted parseEquation to handle None case
def parseEquation(equation):
# Determine if the equation has <-> or ->
if '<->' in equation:
reactionCount = 2
lhs, rhs = equation.split('<->')
elif '->' in equation:
reactionCount = 1
lhs, rhs = equation.split('->')
else:
print(f"Error: Equation must contain '->' or '<->': {equation}")
return None, None, None, None, None
# Split LHS and RHS on "+" and ignore white space
reactants = [r.strip() for r in lhs.split('+')]
products = [p.strip() for p in rhs.split('+')]
# Call extract_coefficients to process reactants and products
reactantCoeffs, reactants = extract_coefficients(reactants)
productCoeffs, products = extract_coefficients(products)
return reactionCount, reactants, reactantCoeffs, products, productCoeffs
# Extract the Coefficients for a Set of Reactants
def extract_coefficients(terms):
# Check if the input contains only an empty string
if len(terms) == 1 and terms[0] == '':
return [], []
coeffs = []
species = []
for term in terms:
# Match terms with coefficients followed by '*'
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
coeffs.append(coeff)
species.append(species_name.strip())
else:
# Match terms with optional coefficients without '*'
match = re.match(r'(\d*)\s*(.*)', term)
if match:
coeff_str, species_name = match.groups()
coeff = int(coeff_str) if coeff_str else 1
coeffs.append(coeff)
species.append(species_name.strip())
else:
# Handle unexpected formats
print(f"Error: Invalid term format: {term}")
coeffs.append(1)
species.append(term.strip())
return coeffs, species
def parseInitialConditions(initialConditions):
parsed_ICs = []
for ic_str in initialConditions:
# Split the string at the '=' character and strip any leading/trailing whitespace
try:
name, value_str = ic_str.split("=")
name = name.strip()
value = float(value_str.strip()) # Convert value to float (could be int or float)
# Create InitialCondition object and append to the result list
parsed_ICs.append(InitialCondition(name, value))
except ValueError:
print(f"Error: The string '{ic_str}' could not be parsed.")
except Exception as e:
print(f"Unexpected error while parsing '{ic_str}': {e}")
return parsed_ICs
#################
# Class Objects #
#################
class InitialCondition:
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return f"InitialCondition(name={self.name}, value={self.value})"
def __eq__(self, other):
if isinstance(other, InitialCondition):
# Two InitialCondition objects are equal if they have the same name
return self.name == other.name and self.value == other.value
return False
def __hash__(self):
# We want the hash based on the 'name' and 'value' attributes.
return hash((self.name, self.value))
#class Reaction:
# def __init__(self, equation, rateName, rateValue, reactants, reactant_coeffs, products, product_coeffs):
# self.equation = equation
# self.rateName = rateName
# self.rateValue = rateValue
# self.reactants = reactants
# self.reactant_coeffs = reactant_coeffs
# self.products = products
# self.product_coeffs = product_coeffs
# def __repr__(self):
# return (f"Reaction(equation={self.equation}, rateName={self.rateName}, "
# f"rateValue={self.rateValue}, "
# f"reactants={self.reactants}, "
# f"reactant_coeffs={self.reactant_coeffs}, products={self.products}, "
# f"product_coeffs={self.product_coeffs})")
# def __eq__(self, other):
# if isinstance(other, Reaction):
# sorted_self_reactants = sorted(zip(self.reactants, self.reactant_coeffs))
# sorted_other_reactants = sorted(zip(other.reactants, other.reactant_coeffs))
# sorted_self_products = sorted(zip(self.products, self.product_coeffs))
# sorted_other_products = sorted(zip(other.products, other.product_coeffs))
# return (self.rateName == other.rateName and
# self.rateValue == other.rateValue and
# sorted_self_reactants == sorted_other_reactants and
# sorted_self_products == sorted_other_products)
# return False
# def __hash__(self):
# sorted_reactants = tuple(sorted(zip(self.reactants, self.reactant_coeffs)))
# sorted_products = tuple(sorted(zip(self.products, self.product_coeffs)))
# return hash((self.rateName, self.rateValue, sorted_reactants, sorted_products))
class Reaction:
index_counter = 0 # Class variable to keep track of the index
def __init__(self, equation, rateName, rateValue, reactants, reactant_coeffs, products, product_coeffs):
self.equation = equation
self.rateName = rateName
self.rateValue = rateValue
self.reactants = reactants
self.reactant_coeffs = reactant_coeffs
self.products = products
self.product_coeffs = product_coeffs
self.index = Reaction.index_counter # Assign the current index
Reaction.index_counter += 1 # Increment the index for the next reaction
def __repr__(self):
return (f"Reaction(index={self.index}, equation={self.equation}, rateName={self.rateName}, "
f"rateValue={self.rateValue}, reactants={self.reactants}, "
f"reactant_coeffs={self.reactant_coeffs}, products={self.products}, "
f"product_coeffs={self.product_coeffs})")
def __eq__(self, other):
if isinstance(other, Reaction):
sorted_self_reactants = sorted(zip(self.reactants, self.reactant_coeffs))
sorted_other_reactants = sorted(zip(other.reactants, other.reactant_coeffs))
sorted_self_products = sorted(zip(self.products, self.product_coeffs))
sorted_other_products = sorted(zip(other.products, other.product_coeffs))
# Compare only the content (ignoring index)
return (self.rateName == other.rateName and
self.rateValue == other.rateValue and
sorted_self_reactants == sorted_other_reactants and
sorted_self_products == sorted_other_products)
return False
def __hash__(self):
sorted_reactants = tuple(sorted(zip(self.reactants, self.reactant_coeffs)))
sorted_products = tuple(sorted(zip(self.products, self.product_coeffs)))
# Hash based on content (ignoring index)
return hash((self.rateName, self.rateValue, sorted_reactants, sorted_products))
class Stoich:
def __init__(self, uniqueSpecies: list, parsedReactions: list) -> None:
self.species = dict()
c = 0
for s in uniqueSpecies:
if s not in self.species:
self.species[s] = c
c += 1
self.rates = []
for r in parsedReactions:
self.rates.append(r.rateName)
self.N = len(self.species)
self.M = len(self.rates)
self.stoich = [[math.nan for i in range(self.M)] for j in range(self.N)]
self.reactants = [[math.nan for i in range(self.M)] for j in range(self.N)]
self.products = [[math.nan for i in range(self.M)] for j in range(self.N)]
for r, reaction in enumerate(parsedReactions):
#Process Reactants
for i,spec in enumerate(reaction.reactants):
spec_ind = self.species[spec]
# Subtract species multiplicities from stoich matrix
if math.isnan(self.stoich[spec_ind][r]): self.stoich[spec_ind][r] = 0
self.stoich[spec_ind][r] += - reaction.reactant_coeffs[i]
if math.isnan(self.reactants[spec_ind][r]): self.reactants[spec_ind][r] = 0
self.reactants[spec_ind][r] += - reaction.reactant_coeffs[i]
# Process Products
for i, spec in enumerate(reaction.products):
spec_ind = self.species[spec]
# Add species multiplicities from stoich matrix
if math.isnan(self.stoich[spec_ind][r]): self.stoich[spec_ind][r] = 0
self.stoich[spec_ind][r] += reaction.product_coeffs[i]
if math.isnan(self.products[spec_ind][r]): self.products[spec_ind][r] = 0
self.products[spec_ind][r] += reaction.product_coeffs[i]
# Define how to print stoich objects
def __str__(self):
return f"Stoich Info:\nSpecies: {list(self.species)}\nRates: {list(self.rates)}\nMatrix: {self.stoich}\nMatrix: {self.reactants}\nMatrix: {self.products}"
def __repr__(self):
return self.__str__()
def check_rates(self):
# Create a dictionary to map rates to their corresponding columns
rate_to_columns = defaultdict(list)
for i, rate in enumerate(self.rates):
rate_to_columns[rate].append(i)
# Calculate sum for each column where rates are the same
column_sums = {}
for rate, columns in rate_to_columns.items():
# Initialize a list for storing sums, with length equal to the number of rows
column_sum = [0] * len(columns)
# Iterate over each column index for the current rate
for j,col in enumerate(columns):
for row in range(self.N):
# Sum the values in the column only if they are not NaN
if not math.isnan(self.reactants[row][col]):
column_sum[j] += self.reactants[row][col]
# Store the sum for the current rate
column_sums[rate] = column_sum
# Identify bad rates
bad_rates = {}
for rate, column_sum in column_sums.items():
unique_sums = set(column_sum)
if len(unique_sums) > 1:
bad_rates[rate] = column_sum
return bad_rates
def to_csv(self, filename: str, option: str):
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow([''] + list(self.rates)) # Header with rate names
if option == "S":
# Write each row for species
for i, species in enumerate(self.species):
row = [species] + [self.stoich[i][j] if not math.isnan(self.stoich[i][j]) else '' for j in range(self.M)]
writer.writerow(row)
elif option == "R":
# Write each row for species
for i, species in enumerate(self.species):
row = [species] + [self.reactants[i][j] if not math.isnan(self.reactants[i][j]) else '' for j in range(self.M)]
writer.writerow(row)
elif option == "P":
# Write each row for species
for i, species in enumerate(self.species):
row = [species] + [self.products[i][j] if not math.isnan(self.products[i][j]) else '' for j in range(self.M)]
writer.writerow(row)
else:
print(f"Error: Invalid Option Given: {option}")
#######################
# Create Output Files #
#######################
def create_matlab_multipleFileOutput(input_file: str, outputPrefix: str, s: Stoich, species: list, rates: list, uniqueRates: list, v: bool = False):
Ns = len(s.species)
Nr = len(s.rates)
#species = [i.name for i in s.species.keys()]
#rates = [i for i in s.rates.keys()]
#if v: print('\nOutput File: \n', output_file)
#if v: print("\n")
matlabFilePrefix = outputPrefix + "Matlab"
ICFilePrefix = outputPrefix + "IC"
ParamPrefix = outputPrefix + "Params"
RenamePrefix = outputPrefix + "Rename"
fIC = open(ICFilePrefix + ".m", 'w')
fParam = open(ParamPrefix + ".m", 'w')
fRename = open(RenamePrefix + ".m", 'w')
f = open(matlabFilePrefix + ".m", 'w')
#if v: print('\nOutput File: \n', output_file)
#if v: print("\n")
f.write("function [time,y] = ")
f.write(matlabFilePrefix)
f.write("(t_final,t_start)\n")
f.write("% Solves a system of ODEs from t=t_start to t=t_final \n")
f.write("% If no start time is given, then t_start = 0 \n")
f.write("% If no start or final time is given, then t_start = 0, t_final = 1 \n")
f.write("%\n")
f.write("%\n")
f.write("% This file was created by issuing command: \n")
f.write("% python createMatlabFile.py ")
f.write(input_file)
f.write("\n")
f.write("%\n")
f.write("\n")
f.write("\nif nargin == 1\n")
f.write(" t_start = 0; % Default start time is 0 \n")
f.write("elseif nargin == 0\n")
f.write(" t_start = 0; % Default start time is 0\n")
f.write(" t_final = 1; % Default final time is 1\n")
f.write("end\n\n\n")
fParam.write("% Kinetic Parameters \n")
for i in range(len(uniqueRates)):
fParam.write(uniqueRates[i])
fParam.write(" = 1; \n")
fParam.write("\np = [ ")
fParam.write(uniqueRates[0])
for i in range(1, len(uniqueRates)):
fParam.write(", ")
fParam.write(uniqueRates[i])
fParam.write(" ];\n\n\n")
f.write("% Set the Kinetic Parameters\n")
f.write(f"{ParamPrefix}\n\n")
fIC.write("% Initial Conditions \n")
for i in range(Ns):
fIC.write(transform_string(species[i]))
fIC.write("_IC")
fIC.write(" = 0; \n")
##Line that's too long;
fIC.write("\ninit_cond = [ ")
fIC.write(transform_string(species[0]))
fIC.write("_IC")
for i in range(1,Ns):
fIC.write(", ")
fIC.write(transform_string(species[i]))
fIC.write("_IC")
fIC.write(" ];\n\n\n")
f.write("% Set the Initial Conditions\n")
f.write(f"{ICFilePrefix}\n\n")
f.write("options = odeset('RelTol',1e-12,'AbsTol',1e-23);\n\n\n")
f.write("%------------------------- Main Solve ----------------------%\n")
f.write("[time,y] = ode15s(@(t,y)RHS(t,y,p), [t_start t_final], init_cond, options);\n")
f.write("%-----------------------------------------------------------%\n\n\n")
fRename.write("% Rename solution components\n") ##Modify
for i in range(Ns):
fRename.write(transform_string(species[i]))
fRename.write(" = y(:,")
fRename.write(str(i+1))
fRename.write("); \n")
f.write("% Rename solution components\n") ##Modify
f.write(f"{RenamePrefix}\n") ##Modify
f.write("% \n")
f.write("% Place plots or other calculations here\n")
f.write("% \n")
f.write("% Example: \n")
f.write("% plot(time, ")
f.write(str(transform_string(species[0])))
f.write(", 'k-o', 'LineWidth', 4, 'MarkerSize', 4); legend('")
f.write(str(species[0]))
f.write("');\n\n\n")
f.write("end\n\n\n\n")
f.write("%-----------------------------------------------------%\n")
f.write("%-------------------- RHS Function -------------------%\n")
f.write("%-----------------------------------------------------%\n\n")
f.write("function dy = RHS(t,y,p)\n\n")
f.write("dy = zeros(")
f.write(str(Ns))
f.write(",1);\n")
f.write("\n\n")
f.write("% Rename Variables \n\n") ## Modify
for i in range(Ns):
f.write(str(transform_string(species[i])))
f.write(" = y(")
f.write(str(i+1))
f.write("); \n")
f.write("\n\n")
f.write("% Rename Kinetic Parameters \n")
for i in range(len(uniqueRates)):
f.write(str(uniqueRates[i]))
f.write(" = p(")
f.write(str(i+1))
f.write("); \n")
f.write("\n\n")
f.write("% ODEs from reaction equations \n\n")
if v: print("Writing ODEs now....\n")
for i in range(Ns):
f.write("% ")
f.write(str(transform_string(species[i])))
f.write("\n dy(")
f.write(str(i+1))
f.write(") =")
for j in range(Nr):
#If the reaction j reduces the amount of species i;
if (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) < 0):
f.write(" - ")
f.write(str(rates[j]))
for k in range(Ns):
if (not math.isnan(s.reactants[k][j])) and (int(s.reactants[k][j]) <= 0):
f.write(" * ")
f.write(transform_string(species[k]))
if (abs(int(s.reactants[k][j])) != 1) and (s.reactants[k][j] != 0):
f.write("^")
f.write(str(abs(int(s.reactants[k][j]))))
#If the reaction j increases the amount of species i
elif (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) > 0):
f.write(" + ")
f.write(str(rates[j]))
for k in range(Ns):
##Double check that this makes sense; perhaps should be reactants.
if (not math.isnan(s.stoich[k][j])) and (int(s.stoich[k][j]) <= 0):
f.write(" * ")
if (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) > 1):
f.write(str(int(s.stoich[i][j])))
f.write(" * ")
f.write(transform_string(species[k]))
if (abs(int(s.reactants[k][j])) != 1) and (s.reactants[k][j] != 0):
f.write("^")
f.write(str(abs(int(s.reactants[k][j]))))
#If the reaction j leaves species i untouched.
elif (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) == 0):
f.write(" + ")
f.write(" 0 ")
if v: print(species[i]," complete")
f.write(";\n\n")
f.write("\n\n\n\n")
f.write("end")
def create_matlab_output(input_file: str, output_file: str, s: Stoich, species: list, rates: list, uniqueRates: list, v: bool = False):
Ns = len(s.species)
Nr = len(s.rates)
#species = [i.name for i in s.species.keys()]
#rates = [i for i in s.rates.keys()]
if v: print('\nOutput File: \n', output_file)
if v: print("\n")
#f = open(output_file,'w')
f = io.StringIO() #Let's us format the code to wrap after 80 characters;
f.write("function [time,y] = ")
f.write(output_file.strip(".m"))
f.write("(t_start,t_final)\n")
f.write("% Solves a system of ODEs from t=t_start to t=t_final \n")
f.write("% If no start time is given, then t_start = 0 \n")
f.write("% If no start or final time is given, then t_start = 0, t_final = 1 \n")
f.write("%\n")
f.write("%\n")
f.write("% This file was created by issuing command: \n")
f.write("% python createMatlabFile.py ")
f.write(input_file)
f.write("\n")
f.write("%\n")
f.write("\n")
f.write("\nif nargin == 1\n")
f.write(" t_start = 0; % Default start time is 0 \n")
f.write("elseif nargin == 0\n")
f.write(" t_start = 0; % Default start time is 0\n")
f.write(" t_final = 1; % Default final time is 1\n")
f.write("end\n\n\n")
f.write("% Kinetic Parameters \n")
for i in range(len(uniqueRates)):
f.write(uniqueRates[i])
f.write(" = 1; \n")
f.write("\np = [ ")
f.write(uniqueRates[0])
for i in range(1, len(uniqueRates)):
f.write(", ")
f.write(uniqueRates[i])
f.write(" ];\n\n\n")
f.write("% Initial Conditions \n")
for i in range(Ns):
f.write(transform_string(species[i]))
f.write("_IC")
f.write(" = 0; \n")
##Line that's too long;
f.write("\ninit_cond = [ ")
f.write(transform_string(species[0]))
f.write("_IC")
for i in range(1,Ns):
f.write(", ")
f.write(transform_string(species[i]))
f.write("_IC")
f.write(" ];\n\n\n")
f.write("options = odeset('RelTol',1e-12,'AbsTol',1e-23);\n\n\n")
f.write("%-------------------------------- Main Solve -----------------------------%\n")
f.write("[time,y] = ode15s(@(t,y)RHS(t,y,p), [t_start t_final], init_cond, options);\n")
f.write("%-------------------------------------------------------------------------%")
f.write("\n\n\n")
f.write("% Rename solution components\n") ##Modify
for i in range(Ns):
f.write(transform_string(species[i]))
f.write(" = y(:,")
f.write(str(i+1))
f.write("); \n")
f.write("\n\n\n")
f.write("% \n")
f.write("% Place plots or other calculations here\n")
f.write("% \n")
f.write("% Example: \n")
f.write("% plot(time, ")
f.write(str(transform_string(species[0])))
f.write(", 'k-o', 'LineWidth', 4, 'MarkerSize', 4); legend('")
f.write(str(species[0]))
f.write("');\n\n\n")
f.write("end\n\n\n\n")
f.write("%-----------------------------------------------------%\n")
f.write("%-------------------- RHS Function -------------------%\n")
f.write("%-----------------------------------------------------%\n\n")
f.write("function dy = RHS(t,y,p)\n\n")
f.write("dy = zeros(")
f.write(str(Ns))
f.write(",1);\n")
f.write("\n\n")
f.write("% Rename Variables \n\n") ## Modify
for i in range(Ns):
f.write(str(transform_string(species[i])))
f.write(" = y(")
f.write(str(i+1))
f.write("); \n")
f.write("\n\n")
f.write("% Rename Kinetic Parameters \n")
for i in range(len(uniqueRates)):
f.write(str(uniqueRates[i]))
f.write(" = p(")
f.write(str(i+1))
f.write("); \n")
f.write("\n\n")
f.write("\n\n")
f.write("% ODEs from reaction equations \n\n")
if v: print("Writing ODEs now....\n")
for i in range(Ns):
f.write("% ")
f.write(str(transform_string(species[i])))
f.write("\n dy(")
f.write(str(i+1))
f.write(") =")
for j in range(Nr):
if (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) < 0):
f.write(" - ")
f.write(str(rates[j]))
for k in range(Ns):
if (not math.isnan(s.stoich[k][j])) and (int(s.stoich[k][j]) <= 0):
f.write(" * ")
f.write(transform_string(species[k]))
if (abs(int(s.stoich[k][j])) != 1) and (s.stoich[k][j] != 0):
f.write("^")
f.write(str(abs(int(s.stoich[k][j]))))
elif (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) > 0):
f.write(" + ")
f.write(str(rates[j]))
for k in range(Ns):
if (not math.isnan(s.stoich[k][j])) and (int(s.stoich[k][j]) <= 0):
f.write(" * ")
if (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) > 1):
f.write(str(int(s.stoich[i][j])))
f.write(" * ")
f.write(transform_string(species[k]))
if (abs(int(s.stoich[k][j])) != 1) and (s.stoich[k][j] != 0):
f.write("^")
f.write(str(abs(int(s.stoich[k][j]))))
elif (not math.isnan(s.stoich[i][j])) and (int(s.stoich[i][j]) == 0):
f.write(" + ")
f.write(" 0 ")
if v: print(species[i]," complete")
f.write(";\n\n")
f.write("\n\n\n\n")
f.write("end")
formatted_code = f.getvalue()
f.close()
formatted_code_with_continuations = add_line_continuations(formatted_code)
# Write the formatted code to the file
with open(output_file, 'w') as file:
file.write(formatted_code_with_continuations)
def add_line_continuations(code: str, max_line_length: int = 80) -> str:
lines = code.split('\n')
new_lines = []
for line in lines:
while len(line) > max_line_length:
split_index = line.rfind(' ', 0, max_line_length)
if split_index == -1:
split_index = max_line_length
new_lines.append(line[:split_index] + ' ...')
line = line[split_index:].strip()
new_lines.append(line)
return '\n'.join(new_lines)
#############
# Main Code #
#############
verbose = True
specialVerbose = True
previewVal = 10
######################################
# Step 0: Preprocessing #
# - Read in Txt File #
# - Remove white space #
# - Store the biochemicalReactions #
######################################
if verbose:
print('-' * 50)
print(f"Step 0: Preprocessing")
# Initialize the initial biochemical arrays and counters
biochemicalReactions = []
initialConditions = []
numReactionsReadIn = 0
numInitialConditionsReadIn = 0
try:
with open(sys.argv[1], 'r') as file:
for line in file:
line = line.rstrip() # Remove trailing newline characters
# Ignore blank lines or lines starting with '#'
if not line or line.startswith('#'):
continue
# Remove everything after the first '#' (if any)
line = line.split('#')[0].rstrip() # Keep part before '#', remove trailing spaces
# Split the line by commas
fields = line.split(',')
# Process as biochemical reaction if there are multiple comma-separated values
if len(fields) > 1:
biochemicalReactions.append(line)
numReactionsReadIn += 1
else:
# Handle single-field lines (initial conditions)
initialConditions.append(line)
numInitialConditionsReadIn += 1
print(f"\t\tInitial Condition:{line}")
except IOError:
sys.exit(f"Couldn't open {sys.argv[1]}")
# Get the input file name
input_file = sys.argv[1]
# Extract the PREFIX from the input file name
prefix, _ = os.path.splitext(input_file)
# Output the counts to the screen
if verbose:
print(f"\t\tNumber of Biochemical Equations: {numReactionsReadIn}")
print(f"\t\tNumber of Species with Initial Conditions: {numInitialConditionsReadIn}")
print(f"DONE: Step 0 Preprocessing of {sys.argv[1]}")
print('-' * 50)
#########################################
# Step 1: Parse the Initial Conditions #
#########################################
if verbose:
print(f"Step 1: Parse the Intial Conditions")
# Parse the reactions
parsed_ICs = parseInitialConditions(initialConditions)
if verbose:
# Print parsed objects
for ic in parsed_ICs:
print(f"\t{ic}")
print(f"DONE: Step 1 Parsed ")
print('-' * 50)
# Define the output file names
stoich_output_file = f"{prefix}Stoich.csv"
reactant_output_file = f"{prefix}Reactants.csv"
product_output_file = f"{prefix}Products.csv"
#matlab_output_file = f"{prefix}Matlab.m"
#IC_output_file = f"{prefix}ICs.m"
#param_output_file = f"{prefix}Params.m"
#rename_output_file = f"{prefix}Rename.m"
if verbose:
print(f"\tNumber of biochemical reactions: {len(biochemicalReactions)}")
print(f"\tSome of the Biochemical Reactions:")
num_reactions_to_print = min(previewVal, len(biochemicalReactions))
for i in range(num_reactions_to_print):
print(f"\t\t" + biochemicalReactions[i])
print('-' * 50)
###########################################
# Step 2: Parse the Biochemical Reactions #
###########################################
if verbose:
print(f"Step 2: Parsing the Biochemical Reacitons")