-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcomets.py
2263 lines (1973 loc) · 100 KB
/
comets.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 python
'''
The Comets module serves as a Python user interface to COMETS.
For more information see https://comets-manual.readthedocs.io/en/latest/
'''
import re
import math
import subprocess as sp
import pandas as pd
import os
import cobra
import io
import numpy as np
__author__ = "Djordje Bajic, Jean Vila, Jeremy Chacon"
__copyright__ = "Copyright 2019, The COMETS Consortium"
__credits__ = ["Djordje Bajic", "Jean Vila", "Jeremy Chacon"]
__license__ = "MIT"
__version__ = "0.2.1"
__maintainer__ = "Djordje Bajic"
__email__ = "[email protected]"
__status__ = "Beta"
class CorruptLine(Exception):
pass
class OutOfGrid(Exception):
pass
class UnallocatedMetabolite(Exception):
pass
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def read_file(filename):
f = open(filename, 'r')
f_lines = f.read()
f.close()
return f_lines
def readlines_file(filename):
f = open(filename, 'r')
f_lines = f.readlines()
f.close()
return f_lines
def chemostat(models, reservoir_media, dilution_rate):
""" this returns a layout object and a parameters object setup to use the
given models, reservoir_media, and dilution_rate in a chemostat-like
experiment
@argument models: a list of comets models, with initial_pop pre-assigned
@argument reservoir_media: a dictionary where keys are extracellular
metabolite names and the values are their concentration in the media
@argument dilution_rate: a float between zero and 1 specifying the per-hour
dilution rate
returns (layout, parameters)
then one can either do additional edits or use these files to generate
a comets object
"""
mylayout = layout(models)
for key, value in reservoir_media.items():
mylayout.set_specific_metabolite(key, value)
mylayout.set_specific_refresh(key, value * dilution_rate)
parameters = params()
parameters.all_params['metaboliteDilutionRate'] = dilution_rate
parameters.all_params['deathRate'] = dilution_rate
return(mylayout, parameters)
class model:
def __init__(self, model=None):
self.initial_pop = [[0, 0, 0.0]]
self.id = None
self.reactions = pd.DataFrame(columns=['REACTION_NAMES', 'ID',
'LB', 'UB', 'EXCH',
'EXCH_IND', 'V_MAX',
'KM', 'HILL'])
self.smat = pd.DataFrame(columns=['metabolite',
'rxn',
's_coef'])
self.metabolites = pd.DataFrame(columns=['METABOLITE_NAMES'])
self.signals = pd.DataFrame(columns=['REACTION_NUMBER',
'EXCH_IND',
'BOUND',
'FUNCTION',
'PARAMETERS',
'REACTION_NAMES', 'EXCH'],
dtype=object)
self.light = []
self.vmax_flag = False
self.km_flag = False
self.hill_flag = False
self.convection_flag = False
self.light_flag = False
self.nonlinear_diffusion_flag = False
self.neutral_drift_flag = False
self.noise_variance_flag = False
self.default_vmax = 10
self.default_km = 1
self.default_hill = 1
self.default_bounds = [0, 1000]
self.objective = None
self.optimizer = 'GUROBI'
self.obj_style = 'MAXIMIZE_OBJECTIVE_FLUX'
if model is not None:
if isinstance(model, cobra.Model):
self.load_cobra_model(model)
else: # assume it is a path
if model[-3:] == "cmd":
self.read_comets_model(model)
else:
self.read_cobra_model(model)
def get_reaction_names(self):
return(list(self.reactions['REACTION_NAMES']))
def add_signal(self, rxn_num, exch_ind, bound,
function, parms):
if str(rxn_num).lower().strip() == 'death':
rxn_name = 'death'
rxn_num = 'death'
else:
rxn_name = self.reactions.loc[self.reactions.ID == rxn_num+1,
'REACTION_NAMES']
rxn_num = str(rxn_num)
exch_name = list(self.get_exchange_metabolites())[exch_ind-1]
new_row = pd.DataFrame({'REACTION_NUMBER': rxn_num,
'EXCH_IND': exch_ind,
'BOUND': bound,
'FUNCTION': function,
'PARAMETERS': 1,
'REACTION_NAMES': rxn_name,
'EXCH': exch_name},
index=[0],
dtype=object)
new_row.loc[0, 'PARAMETERS'] = parms
self.signals = self.signals.append(new_row, ignore_index=True)
def add_neutral_drift_parameter(self, neutralDriftSigma):
""" toggles neutral drift to on (which is in the model file) and
sets the demographic noise parameter neutralDriftSigma) """
if not isinstance(neutralDriftSigma, float):
raise ValueError("neutralDriftSigma must be a float")
self.neutral_drift_flag = True
self.neutralDriftSigma = neutralDriftSigma
def add_nonlinear_diffusion_parameters(self,
convNonlinDiffZero=1.,
convNonlinDiffN=1.,
convNonlinDiffExponent=1.,
convNonlinDiffHillN=10.,
convNonlinDiffHillK=0.9):
print("Note: for non-linear diffusion parameters to function,\n"
+ "params.all_params['biomassMotionStyle'] = 'ConvNonlin' Diffusion 2D'\n"
+ "must also be set")
for parm in [convNonlinDiffZero, convNonlinDiffN,
convNonlinDiffExponent, convNonlinDiffHillN,
convNonlinDiffHillK]:
if not isinstance(parm, float):
raise ValueError('all nonlinear diffusion terms must be float')
self.nonlinear_diffusion_flag = True
self.nonlinear_diffusion_parameters = {'convNonLinDiffZero': convNonlinDiffZero,
'convNonlinDiffN': convNonlinDiffN,
'convNonlinDiffExponent': convNonlinDiffExponent,
'convNonlinDiffHillN': convNonlinDiffHillN,
'convNonlinDiffHillK': convNonlinDiffHillK}
def add_light(self, reaction, abs_coefficient, abs_base):
if (reaction not in self.reactions['REACTION_NAMES']):
raise ValueError('the reaction is not present in the model')
self.light.append([reaction, abs_coefficient, abs_base])
self.light_flag = True
def add_convection_parameters(self, packedDensity=1.,
elasticModulus=1.,
frictionConstant=1.,
convDiffConstant=1.):
""" running this without named parameters sets default parameters (i.e. 1).
Named parameters are used to specify how convection works """
print("Note: for convection parameters to function,\n"
+ "params.all_params['biomassMotionStyle'] = 'Convection 2D'\n"
+ "must also be set")
if not isinstance(packedDensity, float):
raise ValueError('packed_density must be a float')
if not isinstance(elasticModulus, float):
raise ValueError('elasticModulus must be a float')
if not isinstance(frictionConstant, float):
raise ValueError('frictionConstant must be a float')
if not isinstance(convDiffConstant, float):
raise ValueError('convDiffConstant must be a float')
self.convection_flag = True
self.convection_parameters = {'packedDensity': packedDensity,
'elasticModulus': elasticModulus,
'frictionConstant': frictionConstant,
'convDiffConstant': convDiffConstant}
def add_noise_variance_parameter(self, noiseVariance):
if not isinstance(noiseVariance, float):
raise ValueError('noiseVariance must be a float')
self.noise_variance_flag = True
self.noise_variance = noiseVariance
def get_exchange_metabolites(self):
""" useful for layouts to grab these and get the set of them """
exchmets = pd.merge(self.reactions.loc[self.reactions['EXCH'], 'ID'],
self.smat,
left_on='ID', right_on='rxn',
how='inner')['metabolite']
exchmets = self.metabolites.iloc[exchmets-1]
return(exchmets.METABOLITE_NAMES)
def change_bounds(self, reaction, lower_bound, upper_bound):
if reaction not in self.reactions['REACTION_NAMES'].values:
print('reaction couldnt be found')
return
self.reactions.loc[self.reactions['REACTION_NAMES'] == reaction,
'LB'] = lower_bound
self.reactions.loc[self.reactions['REACTION_NAMES'] == reaction,
'UB'] = upper_bound
def get_bounds(self, reaction):
if reaction not in self.reactions['REACTION_NAMES'].values:
print('reaction couldnt be found')
return
lb = float(self.reactions.loc[self.reactions[
'REACTION_NAMES'] == reaction, 'LB'])
ub = float(self.reactions.loc[self.reactions[
'REACTION_NAMES'] == reaction, 'UB'])
return((lb, ub))
def change_vmax(self, reaction, vmax):
if reaction not in self.reactions['REACTION_NAMES'].values:
print('reaction couldnt be found')
return
self.vmax_flag = True
self.reactions.loc[self.reactions[
'REACTION_NAMES'] == reaction, 'V_MAX'] = vmax
def change_km(self, reaction, km):
if reaction not in self.reactions['REACTION_NAMES'].values:
print('reaction couldnt be found')
return
self.km_flag = True
self.reactions.loc[self.reactions[
'REACTION_NAMES'] == reaction, 'KM'] = km
def change_hill(self, reaction, hill):
if reaction not in self.reactions['REACTION_NAMES'].values:
print('reaction couldnt be found')
return
self.hill_flag = True
self.reactions.loc[self.reactions[
'REACTION_NAMES'] == reaction, 'HILL'] = hill
def read_cobra_model(self, path):
curr_m = cobra.io.read_sbml_model(path)
self.load_cobra_model(curr_m)
def load_cobra_model(self, curr_m):
self.id = curr_m.id
# reactions and their features
reaction_list = curr_m.reactions
self.reactions['REACTION_NAMES'] = [str(x).split(':')[0] for
x in reaction_list]
self.reactions['ID'] = [k for k in
range(1, len(reaction_list)+1)]
self.reactions['LB'] = [x.lower_bound for x in reaction_list]
self.reactions['UB'] = [x.upper_bound for x in reaction_list]
self.reactions['EXCH'] = [True if (len(k.metabolites) == 1) &
(list(k.metabolites.
values())[0] == (-1)) &
('DM_' not in k.id)
else False for k in reaction_list]
exch = self.reactions.loc[self.reactions['EXCH'], 'ID'].tolist()
self.reactions['EXCH_IND'] = [exch.index(x)+1
if x in exch else 0
for x in self.reactions['ID']]
self.reactions['V_MAX'] = [k.Vmax
if hasattr(k, 'Vmax')
else float('NaN')
for k in reaction_list]
if not self.reactions.V_MAX.isnull().all():
self.vmax_flag = True
self.reactions['KM'] = [k.Km
if hasattr(k, 'Km')
else float('NaN')
for k in reaction_list]
if not self.reactions.KM.isnull().all():
self.km_flag = True
self.reactions['HILL'] = [k.Hill
if hasattr(k, 'Hill')
else float('NaN')
for k in reaction_list]
if not self.reactions.HILL.isnull().all():
self.hill_flag = True
if self.vmax_flag:
if hasattr(curr_m, 'default_vmax'):
self.default_vmax = curr_m.default_vmax
if self.km_flag:
if hasattr(curr_m, 'default_km'):
self.default_km = curr_m.default_km
if self.hill_flag:
if hasattr(curr_m, 'default_hill'):
self.default_hill = curr_m.default_hill
# Metabolites
metabolite_list = curr_m.metabolites
self.metabolites['METABOLITE_NAMES'] = [str(x) for
x in metabolite_list]
# S matrix
for index, row in self.reactions.iterrows():
rxn = curr_m.reactions.get_by_id(
row['REACTION_NAMES'])
rxn_num = row['ID']
rxn_mets = [1+list(self.metabolites[
'METABOLITE_NAMES']).index(
x.id) for x in rxn.metabolites]
met_s_coefs = list(rxn.metabolites.values())
cdf = pd.DataFrame({'metabolite': rxn_mets,
'rxn': [rxn_num]*len(rxn_mets),
's_coef': met_s_coefs})
cdf = cdf.sort_values('metabolite')
self.smat = pd.concat([self.smat, cdf])
self.smat = self.smat.sort_values(by=['metabolite', 'rxn'])
# The rest of stuff
if hasattr(curr_m, 'default_bounds'):
self.default_bounds = curr_m.default_bounds
obj = [str(x).split(':')[0]
for x in reaction_list
if x.objective_coefficient != 0][0]
self.objective = int(self.reactions[self.reactions.
REACTION_NAMES == obj]['ID'])
if hasattr(curr_m, 'comets_optimizer'):
self.optimizer = curr_m.comets_optimizer
if hasattr(curr_m, 'comets_obj_style'):
self.obj_style = curr_m.comets_obj_style
def read_comets_model(self, path):
self.id = os.path.splitext(os.path.basename(path))[0]
# in this way, its robust to empty lines:
m_f_lines = [s for s in read_file(path).splitlines() if s]
m_filedata_string = os.linesep.join(m_f_lines)
ends = []
for k in range(0, len(m_f_lines)):
if '//' in m_f_lines[k]:
ends.append(k)
# '''----------- S MATRIX ------------------------------'''
lin_smat = re.split('SMATRIX',
m_filedata_string)[0].count('\n')
lin_smat_end = next(x for x in ends if x > lin_smat)
self.smat = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_smat:lin_smat_end])),
delimiter=r'\s+',
skipinitialspace=True)
self.smat.columns = ['metabolite', 'rxn', 's_coef']
# '''----------- REACTIONS AND BOUNDS-------------------'''
lin_rxns = re.split('REACTION_NAMES',
m_filedata_string)[0].count('\n')
lin_rxns_end = next(x for x in
ends if x > lin_rxns)
rxn = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_rxns:lin_rxns_end])),
delimiter=r'\s+',
skipinitialspace=True)
rxn['ID'] = range(1, len(rxn)+1)
lin_bnds = re.split('BOUNDS',
m_filedata_string)[0].count('\n')
lin_bnds_end = next(x for x in ends if x > lin_bnds)
bnds = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_bnds:lin_bnds_end])),
delimiter=r'\s+',
skipinitialspace=True)
default_bounds = [float(bnds.columns[1]),
float(bnds.columns[2])]
bnds.columns = ['ID', 'LB', 'UB']
reactions = pd.merge(rxn, bnds,
left_on='ID', right_on='ID',
how='left')
reactions.LB.fillna(default_bounds[0], inplace=True)
reactions.UB.fillna(default_bounds[1], inplace=True)
# '''----------- METABOLITES ---------------------------'''
lin_mets = re.split('METABOLITE_NAMES',
m_filedata_string)[0].count('\n')
lin_mets_end = next(x for x in ends if x > lin_mets)
metabolites = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_mets:lin_mets_end])),
delimiter=r'\s+',
skipinitialspace=True)
# '''----------- EXCHANGE RXNS -------------------------'''
lin_exch = re.split('EXCHANGE_REACTIONS',
m_filedata_string)[0].count('\n')+1
exch = [int(k) for k in re.findall(r'\S+',
m_f_lines[lin_exch].
strip())]
reactions['EXCH'] = [True if x in exch else False
for x in reactions['ID']]
reactions['EXCH_IND'] = [exch.index(x)+1
if x in exch else 0
for x in reactions['ID']]
# '''----------- VMAX VALUES --------------------------'''
if 'VMAX_VALUES' in m_filedata_string:
self.vmax_flag = True
lin_vmax = re.split('VMAX_VALUES',
m_filedata_string)[0].count('\n')
lin_vmax_end = next(x for x in ends if x > lin_vmax)
Vmax = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_vmax:lin_vmax_end])),
delimiter=r'\s+',
skipinitialspace=True)
Vmax.columns = ['EXCH_IND', 'V_MAX']
reactions = pd.merge(reactions, Vmax,
left_on='EXCH_IND',
right_on='EXCH_IND',
how='left')
self.default_vmax = float(m_f_lines[lin_vmax-1].split()[1])
else:
reactions['V_MAX'] = np.NaN
# '''----------- VMAX VALUES --------------------------'''
if 'KM_VALUES' in m_filedata_string:
self.km_flag = True
lin_km = re.split('KM_VALUES',
m_filedata_string)[0].count('\n')
lin_km_end = next(x for x in ends if x > lin_km)
Km = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_km:lin_km_end])),
delimiter=r'\s+',
skipinitialspace=True)
Km.columns = ['EXCH_IND', 'KM']
reactions = pd.merge(reactions, Km,
left_on='EXCH_IND',
right_on='EXCH_IND',
how='left')
self.default_km = float(m_f_lines[lin_km-1].split()[1])
else:
reactions['KM'] = np.NaN
# '''----------- VMAX VALUES --------------------------'''
if 'HILL_COEFFICIENTS' in m_filedata_string:
self.hill_flag = True
lin_hill = re.split('HILL_COEFFICIENTS',
m_filedata_string)[0].count('\n')
lin_hill_end = next(x for x in ends if x > lin_hill)
Hill = pd.read_csv(io.StringIO('\n'.join(m_f_lines[
lin_hill:lin_hill_end])),
delimiter=r'\s+',
skipinitialspace=True)
Hill.columns = ['EXCH_IND', 'HILL']
reactions = pd.merge(reactions, Hill,
left_on='EXCH_IND',
right_on='EXCH_IND',
how='left')
self.default_hill = float(m_f_lines[lin_hill-1].split()[1])
else:
reactions['HILL'] = np.NaN
# '''----------- OBJECTIVE -----------------------------'''
lin_obj = re.split('OBJECTIVE',
m_filedata_string)[0].count('\n')+1
self.objective = int(m_f_lines[lin_obj].strip())
# '''----------- OBJECTIVE STYLE -----------------------'''
if 'OBJECTIVE_STYLE' in m_filedata_string:
lin_obj_st = re.split('OBJECTIVE_STYLE',
m_filedata_string)[0].count(
'\n')+1
self.obj_style = m_f_lines[lin_obj_st].strip()
# '''----------- OPTIMIZER -----------------------------'''
if 'OPTIMIZER' in m_filedata_string:
lin_opt = re.split('OPTIMIZER',
m_filedata_string)[0].count('\n')
self.optimizer = m_f_lines[lin_opt].split()[1]
# '''--------------neutral drift------------------------'''
if "neutralDrift" in m_filedata_string:
lin_obj_st = re.split('neutralDrift',
m_filedata_string)[0].count(
'\n')
if "TRUE" == m_f_lines[lin_obj_st].strip().split()[1].upper():
self.neutral_drift_flag = True
self.neutralDriftSigma = 0.
if "neutralDriftsigma" in m_filedata_string:
lin_opt = re.split('neutralDriftsigma',
m_filedata_string)[0].count('\n')
self.neutralDriftSigma = float(m_f_lines[lin_opt].split()[1])
# '''--------------convection---------------------------'''
for parm in ['packedDensity', 'elasticModulus',
'frictionConstant', 'convDiffConstant']:
if parm in m_filedata_string:
lin_obj_st = re.split(parm,
m_filedata_string)[0].count(
'\n')
parm_value = float(m_f_lines[lin_obj_st].strip().split()[1])
try:
self.convection_parameters[parm] = parm_value
except:
self.convection_flag = True
self.convection_parameters = {'packedDensity': 1.,
'elasticModulus': 1.,
'frictionConstant': 1.,
'convDiffConstant': 1.}
self.convection_parameters[parm] = parm_value
# '''--------------non-linear diffusion---------------------------'''
for parm in ['convNonLinDiffZero', 'convNonlinDiffN', 'convNonlinDiffExponent',
'convNonlinDiffHillN', 'convNonlinDiffHillK']:
if parm in m_filedata_string:
lin_obj_st = re.split(parm,
m_filedata_string)[0].count(
'\n')
parm_value = float(m_f_lines[lin_obj_st].strip().split()[1])
try:
self.nonlinear_diffusion_parameters[parm] = parm_value
except:
self.nonlinear_diffusion_flag = True
self.nonlinear_diffusion_parameters = {'convNonLinDiffZero': 1.,
'convNonlinDiffN': 1.,
'convNonlinDiffExponent': 1.,
'convNonlinDiffHillN': 10.,
'convNonlinDiffHillK': .9}
self.nonlinear_diffusion_parameters[parm] = parm_value
# '''-----------noise variance-----------------'''
if 'noiseVariance' in m_filedata_string:
lin_obj_st = re.split('noiseVariance',
m_filedata_string)[0].count(
'\n')
noiseVariance = float(m_f_lines[lin_obj_st].strip().split()[1])
self.noise_variance_flag = True
self.noise_variance = noiseVariance
# assign the dataframes we just built
self.reactions = reactions
self.metabolites = metabolites
def write_comets_model(self, working_dir=None):
path_to_write = ""
if working_dir is not None:
path_to_write = working_dir
path_to_write = path_to_write + self.id + '.cmd'
# format variables for writing comets model
bnd = self.reactions.loc[(self.reactions['LB']
!= self.default_bounds[0]) |
(self.reactions['UB'] !=
self.default_bounds[1]),
['ID', 'LB', 'UB']].astype(
str).apply(lambda x: ' '.join(x),
axis=1)
bnd = ' ' + bnd.astype(str)
rxn_n = ' ' + self.reactions['REACTION_NAMES'].astype(str)
met_n = ' ' + self.metabolites.astype(str)
smat = self.smat.astype(str).apply(lambda x:
' '.join(x), axis=1)
smat = ' ' + smat.astype(str)
exch_r = ' '.join([str(x) for x in
self.reactions.loc[self.reactions.EXCH, 'ID']])
# optional fields (vmax,km, hill)
if self.vmax_flag:
Vmax = self.reactions.loc[self.reactions['V_MAX'].notnull(),
['EXCH_IND', 'V_MAX']]
Vmax = Vmax.astype(str).apply(lambda x:
' '.join(x), axis=1)
Vmax = ' ' + Vmax.astype(str)
if self.km_flag:
Km = self.reactions.loc[self.reactions['KM'].notnull(),
['EXCH_IND', 'KM']]
Km = Km.astype(str).apply(lambda x:
' '.join(x), axis=1)
Km = ' ' + Km.astype(str)
if self.hill_flag:
Hill = self.reactions.loc[self.reactions['HILL'].notnull(),
['EXCH_IND', 'HILL']]
Hill = Hill.astype(str).apply(lambda x:
' '.join(x), axis=1)
Hill = ' ' + Hill.astype(str)
if os.path.isfile(path_to_write):
os.remove(path_to_write)
with open(path_to_write, 'a') as f:
f.write('SMATRIX ' + str(len(self.metabolites)) +
' ' + str(len(self.reactions)) + '\n')
smat.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
f.write('BOUNDS ' +
str(self.default_bounds[0]) + ' ' +
str(self.default_bounds[1]) + '\n')
bnd.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
f.write('OBJECTIVE\n' +
' ' + str(self.objective) + '\n')
f.write(r'//' + '\n')
f.write('METABOLITE_NAMES\n')
met_n.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
f.write('REACTION_NAMES\n')
rxn_n.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
f.write('EXCHANGE_REACTIONS\n')
f.write(' ' + exch_r + '\n')
f.write(r'//' + '\n')
if self.vmax_flag:
f.write('VMAX_VALUES ' +
str(self.default_vmax) + '\n')
Vmax.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
if self.km_flag:
f.write('KM_VALUES ' +
str(self.default_km) + '\n')
Km.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
if self.hill_flag:
f.write('HILL_VALUES ' +
str(self.default_hill) + '\n')
Hill.to_csv(f, mode='a', header=False, index=False)
f.write(r'//' + '\n')
if self.light_flag:
f.write('LIGHT\n')
for lrxn in self.light:
lrxn_ind = str(int(self.reactions.ID[
self.reactions['REACTION_NAMES'] == lrxn[0]]))
f.write(' {} {} {}\n'.format(lrxn_ind,
lrxn[1], lrxn[2]))
f.write(r'//' + '\n')
if self.signals.size > 0:
f.write('MET_REACTION_SIGNAL\n')
sub_signals = self.signals.drop(['REACTION_NAMES', 'EXCH'],
axis='columns')
col_names = list(self.signals.drop(['REACTION_NAMES',
'EXCH', 'PARAMETERS'],
axis='columns').columns)
for idx in sub_signals.index:
row = sub_signals.drop(['PARAMETERS'], axis='columns').iloc[idx, :]
n_parms = len(sub_signals.PARAMETERS[idx])
curr_col_names = col_names + [str(i) for i in range(n_parms)]
temp_df = pd.DataFrame(columns=curr_col_names)
temp_df.loc[0, 'REACTION_NUMBER'] = row.loc['REACTION_NUMBER']
temp_df.loc[0, 'EXCH_IND'] = row.loc['EXCH_IND']
temp_df.loc[0, 'BOUND'] = row.loc['BOUND']
temp_df.loc[0, 'FUNCTION'] = row.loc['FUNCTION']
for i in range(n_parms):
temp_df.loc[0, str(i)] = sub_signals.PARAMETERS[idx][i]
temp_df.to_csv(f, mode='a', sep=' ', header=False, index=False)
f.write(r'//' + '\n')
if self.convection_flag:
for key, value in self.convection_parameters.items():
f.write(key + ' ' + str(value) + '\n')
f.write(r'//' + '\n')
if self.nonlinear_diffusion_flag:
for key, value in self.nonlinear_diffusion_parameters.items():
f.write(key + ' ' + str(value) + '\n')
f.write(r'//' + '\n')
if self.noise_variance_flag:
f.write('noiseVariance' + ' ' +
str(self.noise_variance) + '\n')
f.write(r'//' + '\n')
if self.neutral_drift_flag:
f.write("neutralDrift true\n//\n")
f.write("neutralDriftSigma " + str(self.neutralDriftSigma) + "\n//\n")
f.write('OBJECTIVE_STYLE\n' + self.obj_style + '\n')
f.write(r'//' + '\n')
f.write('OPTIMIZER ' + self.optimizer + '\n')
f.write(r'//' + '\n')
class layout:
'''
Generates a COMETS layout either by reading from a file or by building one
from a list of COBRA models. Or, with no arguments, build an empty layout.
To read a layout from a file, give the path as a string:
layout = comets.layout("./path/to/layout/layoutfile.txt")
To build a layout from a list of models, give the models in a list:
ijo = cobra.test.load
'''
def __init__(self, input_obj=None):
# define an empty layout that can be filled later
self.models = []
self.grid = [1, 1]
self.media = pd.DataFrame(columns=['metabolite',
'init_amount',
'diff_c',
'g_static',
'g_static_val',
'g_refresh'])
# local_media is a dictionary with locations as keys, and as values,
# another dict with metabolite names as keys and amounts as values
# this information sets initial, location-specific media amounts.
self.local_media = {}
self.global_diff = None
self.refresh = []
self.local_refresh = {}
self.local_static = {}
self.initial_pop_type = "custom" # JMC not sure purpose of this
self.initial_pop = []
self.all_exchanged_mets = []
self.default_diff_c = 5.0e-6
self.default_g_static = 0
self.default_g_static_val = 0
self.default_g_refresh = 0
self.barriers = []
self.reactions = []
self.periodic_media = []
self.region_map = None
self.region_parameters = {}
self.__local_media_flag = False
self.__diffusion_flag = False
self.__refresh_flag = False
self.__static_flag = False
self.__barrier_flag = False
self.__region_flag = False
self.__ext_rxns_flag = False
self.__periodic_media_flag = False
if input_obj is None:
print('building empty layout model\nmodels will need to be added' +
' with layout.add_model()')
elif isinstance(input_obj, str):
if not os.path.isfile(input_obj):
raise IOError(' when running comets.layout(), input_obj' +
' is a string, and therefore should be a path' +
' to a layout; however, no file could be found' +
' at that path destionation')
self.read_comets_layout(input_obj)
else:
if not isinstance(input_obj, list):
input_obj = [input_obj] # probably just one cobra model
self.models = input_obj
self.update_models()
def set_region_parameters(self, region, diffusion, friction):
"""
COMETS can have different regions with different substrate diffusivities
and frictions. Here, you set those parameters. For example, if a layout
had three different substrates, and you wanted to define their diffusion
for region 1, you would use:
layout.set_region_parameters(1, [1e-6, 1e-6, 1e-6], 1.0)
This does not affect a simulation unless a region map is also set, using
the layout.set_region_map() function.
"""
if not self.__region_flag:
print("Warning: You are setting region parameters but a region" +
"map has not been set. Use layout.set_region_map() or these" +
"parameters will be unused")
self.region_parameters[region] = [diffusion, friction]
def set_region_map(self, region_map):
"""
COMETS can have different regions with different substrate diffusivities
and frictions. Here, you set the map defining the regions. Specifically,
you provide either:
1) a numpy array whose shape == layout.grid, or
2) a list of lists whose first length is grid[0] and second len is grid[1]
Populating these objects should be integer values, beginning at 1 and
incrementing only, that define the different grid areas. These are
intimately connected to region_parameters, which are set with
layout.set_region_parameters()
"""
if isinstance(region_map, list):
region_map = np.array(region_map)
if not tuple(self.grid) == region_map.shape:
raise ValueError("the shape of your region map must be the " +
"same as the grid size. specifically, \n" +
"tuple(layout.grid) == region_map.shape\n" +
"must be True after region_map = np.array(region_map)")
self.region_map = region_map
self.__region_flag = True
def add_external_reaction(self,
rxnName, metabolites, stoichiometry, **kwargs):
ext_rxn = {'Name': rxnName,
'metabolites': metabolites,
'stoichiometry': stoichiometry}
for key, value in kwargs.items():
if key not in ['Kcat', 'Km', 'K']:
print('Warning: Parameter ' + key + ' i not recognized and ' +
'will be ignored. Please set either Kcat and Km for' +
' enzymatic reactions, or K for non catalyzed ones')
else:
ext_rxn[key] = value
if 'Kcat' in ext_rxn and len([i for i in ext_rxn['stoichiometry']
if i < 0]) > 1:
print('Warning: Enzymatic reactions are only allowed to have'
+ 'one reactant')
self.reactions.append(ext_rxn)
self.__ext_rxns_flag = True
def set_global_periodic_media(self,
metabolite, function,
amplitude, period, phase, offset):
if (metabolite not in self.media['metabolite'].values):
raise ValueError('the metabolite is not present in the media')
if (function not in ['step', 'sin', 'cos', 'half_sin', 'half_cos']):
raise ValueError(function + ': function unknown')
self.periodic_media.append([self.media.index[self.media['metabolite']
== metabolite][0],
function, amplitude, period,
phase, offset])
self.__periodic_media_flag = True
def read_comets_layout(self, input_obj):
# .. load layout file
f_lines = [s for s in read_file(input_obj).splitlines() if s]
filedata_string = os.linesep.join(f_lines)
end_blocks = []
for i in range(0, len(f_lines)):
if '//' in f_lines[i]:
end_blocks.append(i)
# '''----------- GRID ------------------------------------------'''
try:
self.grid = [int(i) for i in f_lines[2].split()[1:]]
if len(self.grid) < 2:
raise CorruptLine
except CorruptLine:
print('\n ERROR CorruptLine: Only ' + str(len(self.grid)) +
' dimension(s) specified for world grid')
# '''----------- MODELS ----------------------------------------'''
'''
Models can be specified in layout as either comets format models
or .xml format (sbml cobra compliant)
'''
# right now, assume all models in layouts are strings leading to
# comets model files
# models need initial pop, so lets grab that first
# '''----------- INITIAL POPULATION ----------------------------'''
lin_initpop = re.split('initial_pop',
filedata_string)[0].count('\n')
lin_initpop_end = next(x for x in end_blocks if x > lin_initpop)
g_initpop = f_lines[lin_initpop].split()[1:]
# TODO: I think we should deprecate these, it makes things difficult
# then, we could just generate these on-the-fly using the py toolbox,
# and have the initial_pop always appear to be 'custom' type to COMETS
# DB totally agree
if (len(g_initpop) > 0 and g_initpop[0] in ['random',
'random_rect',
'filled',
'filled_rect',
'square']):
self.initial_pop_type = g_initpop[0]
self.initial_pop = [float(x) for x in g_initpop[1:]]
else:
self.initial_pop_type = 'custom'
# .. local initial population values
lin_initpop += 1
# list of lists of lists. first level per-model, then per-location
temp_init_pop_for_models = [[] for x in
range(len(f_lines[0].split()[1:]))]
try:
for i in range(lin_initpop, lin_initpop_end):
ipop_spec = [float(x) for x in
f_lines[i].split()]
if len(ipop_spec)-2 != len(temp_init_pop_for_models):
raise CorruptLine
if (ipop_spec[0] >= self.grid[0] or
ipop_spec[1] >= self.grid[1]):
raise OutOfGrid
else:
for j in range(len(ipop_spec)-2):
if ipop_spec[j+2] != 0.0:
if len(temp_init_pop_for_models[j]) == 0:
temp_init_pop_for_models[j] = [[ipop_spec[0],
ipop_spec[1],
ipop_spec[j+2]]]
else:
temp_init_pop_for_models[j].append([ipop_spec[0],
ipop_spec[1],
ipop_spec[j+2]])
except CorruptLine:
print('Problem at some initial population lines')
except OutOfGrid:
print('Some initial population values' +
' fall outside of the defined grid')
models = f_lines[0].split()[1:]