forked from RuleWorld/PyBioNetGen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibsbml2bngl.py
More file actions
2015 lines (1819 loc) · 66.9 KB
/
libsbml2bngl.py
File metadata and controls
2015 lines (1819 loc) · 66.9 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
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 16:14:42 2013
@author: proto
"""
#!/usr/bin/env python
from collections import OrderedDict
import time
import libsbml
import bionetgen.atomizer.writer.bnglWriter as writer
from optparse import OptionParser
import bionetgen.atomizer.atomizer.moleculeCreation as mc
import sys
from os import listdir
import re
import pickle
import copy
log = {"species": [], "reactions": []}
from collections import Counter, namedtuple
import bionetgen.atomizer.utils.structures as structures
from bionetgen.atomizer.utils.util import (
logMess,
TranslationException,
)
from bionetgen.atomizer.utils import consoleCommands
from bionetgen.atomizer.sbml2bngl import SBML2BNGL
# from biogrid import loadBioGridDict as loadBioGrid
import logging
from bionetgen.atomizer.rulifier import postAnalysis
import pprint
import fnmatch
from collections import defaultdict
import sympy
from sympy.printing.str import StrPrinter
from sympy.core.sympify import SympifyError
# returntype for the sbml analyzer translator and helper functions
AnalysisResults = namedtuple(
"AnalysisResults",
[
"rlength",
"slength",
"reval",
"reval2",
"clength",
"rdf",
"finalString",
"speciesDict",
"database",
"annotation",
"model",
],
)
def loadBioGrid():
pass
def handler(signum, frame):
print("Forever is over!")
raise Exception("end of time")
def getFiles(directory, extension):
"""
Gets a list of bngl files that could be correctly translated in a given 'directory'
Keyword arguments:
directory -- The directory we will recurseviley get files from
extension -- A file extension filter
"""
matches = []
for root, dirnames, filenames in os.walk(directory):
for filename in fnmatch.filter(filenames, "*.{0}".format(extension)):
filepath = os.path.abspath(os.path.join(root, filename))
matches.append([filepath, os.path.getsize(os.path.join(root, filename))])
# sort by size
# matches.sort(key=lambda filename: filename[1], reverse=False)
matches = [x[0] for x in matches]
return matches
import os.path
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def evaluation(numMolecules, translator):
originalElements = numMolecules
nonStructuredElements = len([1 for x in translator if "()" in str(translator[x])])
if originalElements > 0:
ruleElements = (
(len(translator) - nonStructuredElements) * 1.0 / originalElements
)
if ruleElements > 1:
ruleElements = (
(len(translator) - nonStructuredElements) * 1.0 / len(translator.keys())
)
else:
ruleElements = 0
return ruleElements
def selectReactionDefinitions(bioNumber):
"""
This method rrough the stats-biomodels database looking for the
best reactionDefinitions definition available
"""
# with open('stats4.npy') as f:
# db = pickle.load(f)
fileName = resource_path("config/reactionDefinitions.json")
useID = True
naming = resource_path("config/namingConventions.json")
"""
for element in db:
if element[0] == bioNumber and element[1] != '0':
fileName = 'reactionDefinitions/reactionDefinition' + element[1] + '.json'
useID = element[5]
elif element[0] > bioNumber:
break
"""
return fileName, useID, naming
def resolveDependencies(dictionary, key, idx):
counter = 0
for element in dictionary[key]:
if idx < 20:
counter += resolveDependencies(dictionary, element, idx + 1)
else:
counter += 1
return len(dictionary[key]) + counter
def validateReactionUsage(reactant, reactions):
for element in reactions:
if reactant in element:
return element
return None
def readFromString(
inputString,
reactionDefinitions,
useID,
speciesEquivalence=None,
atomize=False,
loggingStream=None,
replaceLocParams=True,
obs_map_file=None,
):
"""
one of the library's main entry methods. Process data from a string
"""
# console = None
# if loggingStream:
# console = logging.StreamHandler(loggingStream)
# console.setLevel(logging.DEBUG)
# # setupStreamLog(console)
reader = libsbml.SBMLReader()
document = reader.readSBMLFromString(inputString)
parser = SBML2BNGL(
document.getModel(),
useID,
replaceLocParams=replaceLocParams,
obs_map_file=obs_map_file,
)
bioGrid = False
pathwaycommons = True
if bioGrid:
loadBioGrid()
database = structures.Databases()
database.assumptions = defaultdict(set)
database.document = document
database.forceModificationFlag = True
database.reactionDefinitions = reactionDefinitions
database.useID = useID
database.atomize = atomize
database.speciesEquivalence = speciesEquivalence
database.pathwaycommons = True
database.isConversion = True
# if pathwaycommons:
# database.pathwaycommons = True
namingConventions = resource_path("config/namingConventions.json")
if atomize:
translator, onlySynDec = mc.transformMolecules(
parser,
database,
reactionDefinitions,
namingConventions,
speciesEquivalence,
bioGrid,
)
database.species = translator.keys()
else:
translator = {}
# logging.getLogger().flush()
# if loggingStream:
# finishStreamLog(console)
returnArray = analyzeHelper(
document,
reactionDefinitions,
useID,
"",
speciesEquivalence,
atomize,
translator,
database,
replaceLocParams=replaceLocParams,
obs_map_file=obs_map_file,
)
if atomize and onlySynDec:
returnArray = list(returnArray)
returnArray = AnalysisResults(
*(
list(returnArray[0:-3])
+ [database]
+ [returnArray[-1]]
+ [returnArray.model]
)
)
return returnArray
def processFunctions(functions, sbmlfunctions, artificialObservables, tfunc):
"""
this method goes through the list of functions and removes all
sbml elements that are extraneous to bngl
"""
# reformat time function
for idx in range(0, len(functions)):
"""
remove calls to functions inside functions
"""
modificationFlag = True
recursionIndex = 0
# remove calls to other sbml functions
while modificationFlag and recursionIndex < 20:
modificationFlag = False
for sbml in sbmlfunctions:
if sbml in functions[idx]:
temp = writer.extendFunction(
functions[idx], sbml, sbmlfunctions[sbml]
)
if temp != functions[idx]:
functions[idx] = temp
modificationFlag = True
recursionIndex += 1
break
functions[idx] = re.sub(r"(\W|^)(time)(\W|$)", r"\1time()\3", functions[idx])
functions[idx] = re.sub(r"(\W|^)(Time)(\W|$)", r"\1time()\3", functions[idx])
functions[idx] = re.sub(r"(\W|^)(t)(\W|$)", r"\1time()\3", functions[idx])
# remove true and false
functions[idx] = re.sub(r"(\W|^)(true)(\W|$)", r"\1 1\3", functions[idx])
functions[idx] = re.sub(r"(\W|^)(false)(\W|$)", r"\1 0\3", functions[idx])
# functions.extend(sbmlfunctions)
dependencies2 = {}
for idx in range(0, len(functions)):
dependencies2[functions[idx].split(" = ")[0].split("(")[0].strip()] = []
for key in artificialObservables:
oldfunc = functions[idx]
functions[idx] = re.sub(
r"(\W|^)({0})([^\w(]|$)".format(key), r"\1\2()\3", functions[idx]
)
if oldfunc != functions[idx]:
dependencies2[functions[idx].split(" = ")[0].split("(")[0]].append(key)
for element in sbmlfunctions:
oldfunc = functions[idx]
key = element.split(" = ")[0].split("(")[0]
if (
re.search("(\W|^){0}(\W|$)".format(key), functions[idx].split(" = ")[1])
!= None
):
dependencies2[functions[idx].split(" = ")[0].split("(")[0]].append(key)
for element in tfunc:
key = element.split(" = ")[0].split("(")[0]
if key in functions[idx].split(" = ")[1]:
dependencies2[functions[idx].split(" = ")[0].split("(")[0]].append(key)
"""
for counter in range(0, 3):
for element in dependencies2:
if len(dependencies2[element]) > counter:
dependencies2[element].extend(dependencies2[dependencies2[element][counter]])
"""
fd = []
for function in functions:
# print(function, '---', dependencies2[function.split(' = ' )[0].split('(')[0]], '---', function.split(' = ' )[0].split('(')[0], 0)
fd.append(
[
function,
resolveDependencies(
dependencies2, function.split(" = ")[0].split("(")[0], 0
),
]
)
fd = sorted(fd, key=lambda rule: rule[1])
functions = [x[0] for x in fd]
return functions
def extractAtoms(species):
"""
given a list of structures, returns a list
of individual molecules/compartment pairs
appends a number for
"""
listOfAtoms = set()
for molecule in species.molecules:
for component in molecule.components:
listOfAtoms.add(tuple([molecule.name, component.name]))
return listOfAtoms
def bondPartners(species, bondNumber):
relevantComponents = []
for molecule in species.molecules:
for component in molecule.components:
if bondNumber in component.bonds:
relevantComponents.append(tuple([molecule.name, component.name]))
return relevantComponents
def getMoleculeByName(species, atom):
"""
returns the state of molecule-component contained in atom
"""
stateVectorVector = []
for molecule in species.molecules:
if molecule.name == atom[0]:
stateVector = []
for component in molecule.components:
if component.name == atom[1]:
# get whatever species this atom is bound to
if len(component.bonds) > 0:
comp = bondPartners(species, component.bonds[0])
comp.remove(atom)
if len(comp) > 0:
stateVector.append(comp[0])
else:
stateVector.append("")
else:
stateVector.append("")
if len(component.states) > 0:
stateVector.append(component.activeState)
else:
stateVector.append("")
stateVectorVector.append(stateVector)
return tuple(stateVectorVector[0])
def extractCompartmentCoIncidence(species):
atomPairDictionary = {}
if [x.name for x in species.molecules] == ["EGF", "EGF", "EGFR", "EGFR"]:
pass
for molecule in species.molecules:
for component in molecule.components:
for component2 in molecule.components:
if component == component2:
continue
atom = tuple([molecule.name, component.name])
atom2 = tuple([molecule.name, component2.name])
molId1 = getMoleculeByName(species, atom)
molId2 = getMoleculeByName(species, atom2)
key = tuple([atom, atom2])
# print(key, (molId1, molId2))
if key not in atomPairDictionary:
atomPairDictionary[key] = Counter()
atomPairDictionary[key].update([tuple([molId1, molId2])])
return atomPairDictionary
def extractCompartmentStatistics(
bioNumber, useID, reactionDefinitions, speciesEquivalence
):
"""
Iterate over the translated species and check which compartments
are used together, and how.
"""
reader = libsbml.SBMLReader()
document = reader.readSBMLFromFile(bioNumber)
parser = SBML2BNGL(document.getModel(), useID)
database = structures.Databases()
database.pathwaycommons = False
# call the atomizer (or not)
# if atomize:
translator, onlySynDec = mc.transformMolecules(
parser, database, reactionDefinitions, speciesEquivalence
)
# else:
# translator={}
compartmentPairs = {}
for element in translator:
temp = extractCompartmentCoIncidence(translator[element])
for element in temp:
if element not in compartmentPairs:
compartmentPairs[element] = temp[element]
else:
compartmentPairs[element].update(temp[element])
finalCompartmentPairs = {}
print("-----")
for element in compartmentPairs:
if element[0][0] not in finalCompartmentPairs:
finalCompartmentPairs[element[0][0]] = {}
finalCompartmentPairs[element[0][0]][tuple([element[0][1], element[1][1]])] = (
compartmentPairs[element]
)
return finalCompartmentPairs
def recursiveSearch(dictionary, element, visitedFunctions=[]):
tmp = 0
for item in dictionary[element]:
if dictionary[item] == []:
tmp += 1
else:
if item in visitedFunctions:
raise Exception(
"Recursive function search landed twice in the same function"
)
tmp += 1
tmp += recursiveSearch(dictionary, item, [item] + visitedFunctions)
return tmp
def reorder_and_replace_arules(functions, parser):
# TODO: Check if we need full_prec, make it optional
prnter = StrPrinter({"full_prec": False})
func_names = []
# get full func names and initialize dependency graph
dep_dict = {}
for func in functions:
splt = func.split("=")
n = splt[0]
f = "=".join(splt[1:])
name = n.rstrip().replace("()", "")
func_names.append(name)
if "fRate" not in name:
dep_dict[name] = []
# make dependency graph between funcs only
func_dict = {}
new_funcs = []
# Let's replace and build dependency map
frates = []
for func in functions:
splt = func.split("=")
# TODO: turn this into warning
n = splt[0]
f = "=".join(splt[1:])
fname = n.rstrip().replace("()", "")
try:
fs = sympy.sympify(f, locals=parser.all_syms)
except:
# Can't parse this func
if fname.startswith("fRate"):
frates.append((fname.strip(), f))
else:
func_dict[fname] = f
continue
# replace here since it affects dependency
for item in parser.only_assignment_dict.items():
oname, nname = item
osym, ns = sympy.symbols(oname + "," + nname)
fs = fs.subs(osym, ns)
func_dict[fname] = fs
# need to build a dependency graph to figure out what to
# write first
# We can skip this if it's a functionRate
if "fRate" not in n:
list_of_deps = list(map(str, fs.atoms(sympy.Symbol)))
for dep in list_of_deps:
if dep in func_names:
dep_dict[fname].append(dep)
else:
frates.append((n.strip(), fs))
# Now reorder accordingly
ordered_funcs = []
# this ensures we write the independendent functions first
stck = sorted(dep_dict.keys(), key=lambda x: len(dep_dict[x]))
# FIXME: This algorithm works but likely inefficient
while len(stck) > 0:
k = stck.pop()
deps = dep_dict[k]
if len(deps) == 0:
if k not in ordered_funcs:
ordered_funcs.append(k)
else:
stck.append(k)
for dep in deps:
if dep not in ordered_funcs:
stck.append(dep)
dep_dict[k].remove(dep)
# print ordered functions and return
for fname in ordered_funcs:
fs = func_dict[fname]
# clean up some whitespace here
try:
func_str = prnter.doprint(fs)
func_str = func_str.replace("**", "^")
new_funcs.append(fname + "() = " + func_str)
except:
new_funcs.append(fname + "() = " + fs)
# now write the functionRates
for fitem in frates:
n, fs = fitem
func_str = prnter.doprint(fs)
func_str = func_str.replace("**", "^")
new_funcs.append(n + " = " + func_str)
return new_funcs
def reorderFunctions(functions):
"""
Analyze a list of sbml functions and make sure there are no forward dependencies.
Reorder if necessary
"""
functionNames = []
tmp = []
for function in functions:
m = re.split("(?<=\()[\w)]", function)
functionName = m[0]
if "=" in functionName:
functionName = functionName.split("=")[0].strip() + "("
functionNames.append(functionName)
functionNamesDict = {x: [] for x in functionNames}
for idx, function in enumerate(functions):
tmp = [
x
for x in functionNames
if x in function.split("=")[1] and x != functionNames[idx]
]
functionNamesDict[functionNames[idx]].extend(tmp)
newFunctionNamesDict = {}
for name in functionNamesDict:
try:
newFunctionNamesDict[name] = recursiveSearch(functionNamesDict, name, [])
# there is a circular dependency
except:
newFunctionNamesDict[name] = 99999
functionWeightsDict = {x: newFunctionNamesDict[x] for x in newFunctionNamesDict}
functionWeights = []
for name in functionNames:
functionWeights.append(functionWeightsDict[name])
tmp = zip(functions, functionWeights)
idx = sorted(tmp, key=lambda x: x[1])
return [x[0] for x in idx]
def postAnalysisHelper(outputFile, bngLocation, database):
consoleCommands.setBngExecutable(bngLocation)
outputDir = os.sep.join(outputFile.split(os.sep)[:-1])
if outputDir != "":
retval = os.getcwd()
os.chdir(outputDir)
consoleCommands.bngl2xml(outputFile.split(os.sep)[-1])
if outputDir != "":
os.chdir(retval)
bngxmlFile = ".".join(outputFile.split(".")[:-1]) + "_bngxml.xml"
# print('Sending BNG-XML file to context analysis engine')
contextAnalysis = postAnalysis.ModelLearning(bngxmlFile)
# analysis of redundant bonds
deleteBonds = contextAnalysis.analyzeRedundantBonds(
database.assumptions["redundantBonds"]
)
for molecule in database.assumptions["redundantBondsMolecules"]:
if molecule[0] in deleteBonds:
for bond in deleteBonds[molecule[0]]:
database.translator[molecule[1]].deleteBond(bond)
logMess(
"INFO:CTX002",
"Used context information to determine that the bond {0} in species {1} is not likely".format(
bond, molecule[1]
),
)
def postAnalyzeFile(
outputFile, bngLocation, database, replaceLocParams=True, obs_map_file=None
):
"""
Performs a postcreation file analysis based on context information
"""
# print('Transforming generated BNG file to BNG-XML representation for analysis')
postAnalysisHelper(outputFile, bngLocation, database)
# recreate file using information from the post analysis
returnArray = analyzeHelper(
database.document,
database.reactionDefinitions,
database.useID,
outputFile,
database.speciesEquivalence,
database.atomize,
database.translator,
database,
replaceLocParams=replaceLocParams,
obs_map_file=obs_map_file,
)
with open(outputFile, "w", encoding="UTF-8") as f:
f.write(returnArray.finalString)
# recompute bng-xml file
consoleCommands.bngl2xml(outputFile)
bngxmlFile = ".".join(outputFile.split(".")[:-1]) + "_bngxml.xml"
# recompute context information
contextAnalysis = postAnalysis.ModelLearning(bngxmlFile)
# get those species patterns that follow uncommon motifs
motifSpecies, motifDefinitions = contextAnalysis.processContextMotifInformation(
database.assumptions["lexicalVsstoch"], database
)
# motifSpecies, motifDefinitions = contextAnalysis.processAllContextInformation()
if len(motifDefinitions) > 0:
logMess(
"INFO:CTX003",
"Species with suspect context information were found. Information is being dumped to {0}_context.log".format(
outputFile
),
)
with open("{0}_context.log".format(outputFile), "w") as f:
pprint.pprint(dict(motifSpecies), stream=f)
pprint.pprint(motifDefinitions, stream=f)
# score hypothetical bonds
# contextAnalysis.scoreHypotheticalBonds(assumptions['unknownBond'])
def postAnalyzeString(outputFile, bngLocation, database):
postAnalysisHelper(outputFile, bngLocation, database)
# recreate file using information from the post analysis
returnArray = analyzeHelper(
database.document,
database.reactionDefinitions,
database.useID,
outputFile,
database.speciesEquivalence,
database.atomize,
database.translator,
database,
).finalString
return returnArray
def analyzeFile(
bioNumber,
reactionDefinitions,
useID,
namingConventions,
outputFile,
speciesEquivalence=None,
atomize=False,
bioGrid=False,
pathwaycommons=False,
ignore=False,
noConversion=False,
memoizedResolver=True,
replaceLocParams=True,
quietMode=False,
logLevel="WARNING",
obs_map_file=None,
app=None,
):
"""
one of the library's main entry methods. Process data from a file
"""
"""
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
"""
# TODO: replace this setup log with our own logging system
# setupLog(
# outputFile + ".log", getattr(logging, logLevel.upper()), quietMode=quietMode
# )
logMess.log = []
logMess.counter = -1
reader = libsbml.SBMLReader()
document = reader.readSBMLFromFile(bioNumber)
if document.getModel() == None:
print(
"l714 - File {0} could not be recognized as a valid SBML file".format(
bioNumber
)
)
return
parser = SBML2BNGL(
document.getModel(),
useID,
replaceLocParams=replaceLocParams,
obs_map_file=obs_map_file,
)
parser.setConversion(not noConversion)
database = structures.Databases()
database.assumptions = defaultdict(set)
database.forceModificationFlag = True
database.pathwaycommons = pathwaycommons
database.ignore = ignore
database.assumptions = defaultdict(set)
bioGridDict = {}
if bioGrid:
bioGridDict = loadBioGrid()
# call the atomizer (or not). structured molecules are contained in translator
# onlysyndec is a boolean saying if a model is just synthesis of decay reactions
# ASS2019 - With this try/except the translator was not being initialized and led to an undefined error in certain models
translator = {}
try:
if atomize:
translator, onlySynDec = mc.transformMolecules(
parser,
database,
reactionDefinitions,
namingConventions,
speciesEquivalence,
bioGrid,
memoizedResolver,
)
except TranslationException as e:
print(
"Found an error in {0}. Check log for more details. Use -I to ignore translation errors".format(
e.value
)
)
if len(logMess.log) > 0:
with open(outputFile + ".log", "w") as f:
for element in logMess.log:
f.write(element + "\n")
return
# process other sections of the sbml file (functions reactions etc.)
"""
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats(10)
print(s.getvalue())
"""
database.document = document
database.reactionDefinitions = reactionDefinitions
database.useID = useID
database.speciesEquivalence = speciesEquivalence
database.atomize = atomize
database.isConversion = not noConversion
returnArray = analyzeHelper(
document,
reactionDefinitions,
useID,
outputFile,
speciesEquivalence,
atomize,
translator,
database,
replaceLocParams=replaceLocParams,
obs_map_file=obs_map_file,
)
with open(outputFile, "w", encoding="UTF-8") as f:
f.write(returnArray.finalString)
# with open('{0}.dict'.format(outputFile), 'wb') as f:
# pickle.dump(returnArray[-1], f)
model = returnArray.model
if atomize and onlySynDec:
returnArray = list(returnArray)
# returnArray.translator = -1
returnArray = AnalysisResults(
*(list(returnArray[0:-3]) + [database] + [returnArray[-1]] + [model])
)
return returnArray
def correctRulesWithParenthesis(rules, parameters):
"""
helper function. Goes through a list of rules and adds a parenthesis
to the reaction rates of those functions whose rate is in list
'parameters'.
"""
for idx in range(len(rules)):
tmp = [x for x in parameters if x + " " in rules[idx]]
# for tmpparameter in tmp:
# re.sub(r'(\W|^){0}(\W|$)'.format(tmpparameter), r'\1{0}\2'.format(dictionary[key]), tmp[1])
if len(tmp) > 0:
rules[idx].strip()
rules[idx] += "()"
def changeNames(functions, dictionary):
"""
changes instances of keys in dictionary appeareing in functions to their corresponding
alternatives
"""
tmpArray = []
for function in functions:
tmp = function.split(" = ")
# hack to avoid problems with less than equal or more than equal
# in equations
# ASS2019 - There are cases where we have more than one equal sign e.g. "= = 0&&"
# in an if statement, I _think_ we need to re-add the '=' we removed by doing
# split
tmp = [tmp[0], "=".join(tmp[1:])]
for key in [x for x in dictionary if x in tmp[1]]:
# ASS - if the key is equal to the value, this goes for an infinite loop
if key == dictionary[key]:
continue
while re.search(r"([\W, ]|^){0}([\W, ]|$)".format(key), tmp[1]):
tmp[1] = re.sub(
r"([\W, ]|^){0}([\W, ]|$)".format(key),
r"\1{0}\2".format(dictionary[key]),
tmp[1],
)
tmpArray.append("{0} = {1}".format(tmp[0], tmp[1]))
return tmpArray
# ASS - We need to rename the functions if they are the same as obs
def changeDefs(functions, dictionary):
"""
changes the names of the functions (RHS) instead of the LHS
"""
tmpArray = []
for function in functions:
tmp = function.split(" = ")
# hack to avoid problems with less than equal or more than equal
# in equations
tmp = [tmp[0], "".join(tmp[1:])]
for key in [x for x in dictionary if x in tmp[0]]:
# ASS - if the key is equal to the value, this goes for an infinite loop
if key == dictionary[key]:
continue
while re.search(r"([\W, ]|^){0}([\W, ]|$)".format(key), tmp[0]):
tmp[0] = re.sub(
r"([\W, ]|^){0}([\W, ]|$)".format(key),
r"\1{0}\2".format(dictionary[key]),
tmp[0],
)
tmpArray.append("{0} = {1}".format(tmp[0], tmp[1]))
return tmpArray
def changeRates(reactions, dictionary):
"""
changes instances of keys in dictionary appeareing in reaction rules to their corresponding
alternatives
"""
tmpArray = []
tmp = None
for reaction in reactions:
cmt = None
tmp = reaction.strip().split(" ")
for ielem, elem in enumerate(tmp):
if elem.startswith("#"):
cmt = tmp[ielem:]
tmp = tmp[:ielem]
break
for key in [x for x in dictionary if x in tmp[-1]]:
tmp[-1] = re.sub(
r"(\W|^){0}(\W|$)".format(key),
r"\1{0}\2".format(dictionary[key]),
tmp[-1],
)
if cmt is not None:
tmp += cmt
tmpArray.append(" ".join(tmp))
# if tmp:
# if cmt is not None:
# tmp += cmt
# tmpArray.append(' '.join(tmp))
return tmpArray
def unrollFunctions(functions):
flag = True
# bngl doesnt accept nested function calling
while flag:
dictionary = OrderedDict()
flag = False
for function in functions:
tmp = function.split(" = ")
for key in dictionary:
if key in tmp[1]:
tmp[1] = re.sub(
r"(\W|^){0}\(\)(\W|$)".format(key),
r"\1({0})\2".format(dictionary[key]),
tmp[1],
)
flag = False
dictionary[tmp[0].split("()")[0]] = tmp[1]
tmp = []
for key in dictionary:
tmp.append("{0}() = {1}".format(key, dictionary[key]))
functions = tmp
return functions
def analyzeHelper(
document,
reactionDefinitions,
useID,
outputFile,
speciesEquivalence,
atomize,
translator,
database,
bioGrid=False,
replaceLocParams=True,
obs_map_file=None,
):
"""
taking the atomized dictionary and a series of data structure, this method
does the actual string output.
"""
useArtificialRules = False
parser = SBML2BNGL(
document.getModel(),
useID,
replaceLocParams=replaceLocParams,
obs_map_file=obs_map_file,
)
# ASS: Port over other parsers? used_molecules list
if hasattr(database, "parser"):
parser.used_molecules.extend(database.parser.used_molecules)
parser.setConversion(database.isConversion)
#
param, zparam = parser.getParameters()
rawSpecies = {}
for species in parser.model.getListOfSpecies():
rawtemp = parser.getRawSpecies(species, [x.split(" ")[0] for x in param])
rawSpecies[rawtemp["identifier"]] = rawtemp
parser.reset()
# parser.bngModel.translator = copy.deepcopy(translator)
parser.bngModel.translator = translator
(
molecules,
initialConditions,
observables,
speciesDict,
observablesDict,
annotationInfo,
) = parser.getSpecies(translator, [x.split(" ")[0] for x in param])
# finally, adjust parameters and initial concentrations according to whatever initialassignments say
param, zparam, initialConditions, initCondMap = parser.getInitialAssignments(
translator, param, zparam, molecules, initialConditions
)
# FIXME: this method is a mess, improve handling of assignmentrules since we can actually handle those
(
aParameters,
aRules,
nonzparam,
artificialRules,
removeParams,
artificialObservables,
) = parser.getAssignmentRules(
zparam, param, rawSpecies, observablesDict, translator
)
compartments = parser.getCompartments()