-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
1658 lines (1379 loc) · 54.3 KB
/
Copy path__init__.py
File metadata and controls
1658 lines (1379 loc) · 54.3 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
import glob
import hashlib
import json
import os
import pickle
import random
import re
import shutil
import sys
import time
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
import docker
import libsbml
import libsedml
import pandas as pd
import requests
import yaml
from pymetadata import omex
from pyneuroml import biosimulations, tellurium
from requests.exceptions import HTTPError
ENGINES = {
"amici": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_AMICI/",
"status": "",
"name": "AMICI",
},
"brian2": {
"formats": [("nml", "sedml"), ("lems", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_pyNeuroML/",
"status": "",
"name": "Brian 2",
},
"bionetgen": {
"formats": [("bngl", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_BioNetGen/",
"status": "",
"name": "BioNetGen",
},
"boolnet": {
"formats": [("sbmlqual", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_BoolNet/",
"status": "",
"name": "BoolNet",
},
"cbmpy": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_CBMPy/",
"status": "",
"name": "CBMPy",
},
"cobrapy": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_COBRApy/",
"status": "Only allows steady state simulations",
"name": "COBRApy",
},
"copasi": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_COPASI/",
"status": "",
"name": "COPASI",
},
"gillespy2": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_GillesPy2/",
"status": "",
"name": "GillesPy2",
},
"ginsim": {
"formats": [("sbmlqual", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_GINsim/",
"status": "",
"name": "GINsim",
},
"libsbmlsim": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_LibSBMLSim/",
"status": "",
"name": "LibSBMLSim",
},
"masspy": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_MASSpy/",
"status": "",
"name": "MASSpy",
},
"netpyne": {
"formats": [("nml", "sedml"), ("lems", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_pyNeuroML/",
"status": "",
"name": "NetPyNE",
},
"neuron": {
"formats": [("nml", "sedml"), ("lems", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_pyNeuroML/",
"status": "",
"name": "NEURON",
},
"opencor": {
"formats": [("cellml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_OpenCOR/",
"status": "",
"name": "OpenCOR",
},
"pyneuroml": {
"formats": [("nml", "sedml"), ("lems", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_pyNeuroML/",
"status": "",
"name": "pyNeuroML",
},
"pysces": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_PySCeS/",
"status": "",
"name": "PySCeS",
},
"rbapy": {
"formats": [("rbapy", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_RBApy/",
"status": "",
"name": "RBApy",
},
"smoldyn": {
"formats": [("smoldyn", "sedml")],
"url": "https://smoldyn.readthedocs.io/en/latest/python/api.html#sed-ml-combine-biosimulators-api",
"status": "",
"name": "Smoldyn",
},
"tellurium": {
"formats": [("sbml", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_tellurium/",
"status": "",
"name": "Tellurium",
},
"vcell": {
"formats": [("sbml", "sedml"), ("bngl", "sedml")],
"url": "https://github.com/virtualcell/vcell",
"status": "",
"name": "VCell",
},
"xpp": {
"formats": [("xpp", "sedml")],
"url": "https://docs.biosimulators.org/Biosimulators_XPP/",
"status": "",
"name": "XPP",
},
}
TYPES = {
"sbml": "SBML",
"sedml": "SED-ML",
"nml": "NeuroML",
"lems": "LEMS",
"sbmlqual": "SBML-qual",
"bngl": "BNGL",
"rbapy": "RBApy",
"xpp": "XPP",
"smoldyn": "Smoldyn",
"cellml": "CellML",
"xml": "XML",
}
# define the column headers for the markdown table
ERROR = "Error"
PASS_FAIL = "pass / FAIL"
TYPE = "Type"
COMPAT = "Compatibility"
D1 = "d1"
ENGINE = "Engine"
# define error categories for detailed error counting per engine
# (currently only tellurium)
# key is the tag/category used to report the category, value is a regex matching the error message
# see MarkdownTable.process_engine_outcomes
# TODO: use error categories in process_log_yml_dict
error_categories = {
"tellurium": {
"algebraic": "^Unable to support algebraic rules.",
"delay": "^Unable to support delay differential equations.",
"ASTNode": "^Unknown ASTNode type of",
"stochiometry": "^Mutable stochiometry for species which appear multiple times in a single reaction",
"float": "^'float' object is not callable",
"SpeciesRef": "is not a named SpeciesReference",
"reset": "reset",
"SEDMLfile": "^failed to validate SEDML file",
"NoSBMLelement": "^No sbml element exists",
"CV_ERR_FAILURE": "CV_ERR_FAILURE",
"CV_TOO_MUCH_WORK": "CV_TOO_MUCH_WORK",
"CV_CONV_FAILURE": "CV_CONV_FAILURE",
"CV_ILL_INPUT": "CV_ILL_INPUT",
"OutOfRange": "list index out of range",
},
}
def get_entry_format(file_path, file_type):
"""
Get the entry format for a file.
Args:
file_path (:obj:`str`): path to the file
file_type (:obj:`str`): type of the file
Returns:
:obj:`str`: entry format
"""
if file_type == "SBML":
file_l = libsbml.readSBML(file_path).getLevel()
file_v = libsbml.readSBML(file_path).getVersion()
elif file_type == "SEDML":
file_l = libsedml.readSedML(file_path).getLevel()
file_v = libsedml.readSedML(file_path).getVersion()
else:
raise ValueError(f"Invalid file type: {file_type}")
file_entry_format = f"{file_type}_L{file_l}V{file_v}"
entry_formats = [f.name for f in omex.EntryFormat]
if file_entry_format not in entry_formats:
file_entry_format = file_type
return file_entry_format
def temp_sedml_file_if_not_empty(sedml_filepath, temp_sedml_filepath):
"""
If the temp_sedml_filepath is not empty, return its content, otherwise return the original content of the sedml file
"""
sedstr = ""
if temp_sedml_filepath:
if os.path.exists(temp_sedml_filepath):
with open(temp_sedml_filepath, "r") as file:
sedstr = file.read()
if sedstr == "":
with open(sedml_filepath, "r") as file:
sedstr = file.read()
return sedstr
def add_xmlns_sbml_attribute(sedml_filepath, sbml_filepath, temp_sedml_filepath=None):
"""
add an xmlns:sbml attribute to the sedml file that matches the sbml file
raise an error if the attribute is already present
output fixed file to output_filepath which defaults to sedml_filepath
If no temp_sedml_filepath is provided, the original sedml file is overwritten.
"""
sed_str = temp_sedml_file_if_not_empty(sedml_filepath, temp_sedml_filepath)
m = re.search(r"<sedML[^>]*>", sed_str)
if m is None:
raise ValueError(
f"Invalid SedML file: main <sedML> tag not found in {sedml_filepath}"
)
if "xmlns:sbml" in m.group():
raise ValueError(
f"xmlns:sbml attribute already present in file {sedml_filepath}"
)
with open(sbml_filepath, "r") as file:
sbml_str = file.read()
sbml_xmlns = re.search(r'xmlns="([^"]*)"', sbml_str).group(1)
missing_sbml_attribute = 'xmlns:sbml="' + sbml_xmlns + '"'
sed_str = re.sub(r"<sedML ", r"<sedML " + missing_sbml_attribute + " ", sed_str)
if temp_sedml_filepath is None:
temp_sedml_filepath = sedml_filepath
with open(temp_sedml_filepath, "w") as fout:
fout.write(sed_str)
def add_xmlns_fbc_attribute(sedml_filepath, sbml_filepath, temp_sedml_filepath=None):
"""
Adds an xmlns:fbc attribute to the SED-ML file.
If a temp_sedml_filepath (which could already contain a xmlns:sbml fix) is provided,
this instead of the original SED-ML file is used.
"""
sedstr = temp_sedml_file_if_not_empty(sedml_filepath, temp_sedml_filepath)
m = re.search(r"<sedML[^>]*>", sedstr)
if m is None:
raise ValueError(
f"Invalid SedML file: main <sedML> tag not found in {sedml_filepath}"
)
location = m.span()[1] - 1
with open(sbml_filepath, "r") as file:
sbml_str = file.read()
fbc_xmlns = re.search(r'xmlns:fbc="([^"]*)"', sbml_str).group(1)
missing_fbc_attribute = 'xmlns:fbc="' + fbc_xmlns + '"'
sedstr = sedstr[:location] + " " + missing_fbc_attribute + sedstr[location:]
if temp_sedml_filepath is None:
temp_sedml_filepath = sedml_filepath
with open(temp_sedml_filepath, "w") as fout:
fout.write(sedstr)
def xmlns_sbml_attribute_missing(sedml_filepath):
"""
True if the xmlns:sbml attribute is missing from the main sedml tag
"""
with open(sedml_filepath, "r") as file:
sedstr = file.read()
m = re.search(r"<sedML[^>]*>", sedstr)
if m is None:
raise ValueError(
f"Invalid SedML file: main <sedML> tag not found in {sedml_filepath}"
)
if "xmlns:sbml" not in m.group():
return True
else:
return False
def xmlns_fbc_attribute_missing(sbml_filepath, sedml_filepath):
"""
True if the xmlns:fbc attribute is missing from the main sedml tag of the SED-ML file but present in the SBML file
"""
with open(sbml_filepath, "r", encoding="utf-8") as file:
sbmlstr = file.read()
with open(sedml_filepath, "r", encoding="utf-8") as file:
sedstr = file.read()
sbmlstr_fbc = re.search(r'xmlns:fbc="([^"]*)"', sbmlstr)
sedstr_fbc = re.search(r'xmlns:fbc="([^"]*)"', sedstr)
if sbmlstr_fbc and not sedstr_fbc:
return True
else:
return False
def get_temp_file():
"""
create a temporary filename in the current working directory
"""
return f"tmp{random.randrange(1000000)}"
def remove_spaces_from_filename(file_path):
"""
create another file with the same content but with filename spaces replaced by underscores
"""
dir_name = os.path.dirname(file_path)
if " " in dir_name:
raise ValueError(f"File directory path should not contain spaces: {dir_name}")
old_filename = os.path.basename(file_path)
if " " not in old_filename:
return file_path
if " " in old_filename:
new_filename = old_filename.replace(" ", "_")
new_file_path = os.path.join(dir_name, new_filename)
shutil.copy(file_path, new_file_path)
return new_file_path
def create_omex(
sedml_filepath,
sbml_filepath,
omex_filepath=None,
silent_overwrite=True,
add_missing_xmlns=True,
):
"""
wrap a sedml and an sbml file in a combine archive omex file
overwrite any existing omex file
"""
# provide an omex filepath if not specified
if not omex_filepath:
if sedml_filepath.endswith(".sedml"):
omex_filepath = Path(sedml_filepath[:-6] + ".omex")
elif sedml_filepath.endswith(".xml"):
omex_filepath = Path(sedml_filepath[:-4] + ".omex")
else:
omex_filepath = Path(sedml_filepath + ".omex")
# suppress pymetadata "file exists" warning by preemptively removing existing omex file
if os.path.exists(omex_filepath) and silent_overwrite:
os.remove(omex_filepath)
tmp_sedml_filepath = get_temp_file()
if add_missing_xmlns:
xmlns_sbml_missing = xmlns_sbml_attribute_missing(sedml_filepath)
xmlns_fbc_missing = xmlns_fbc_attribute_missing(sbml_filepath, sedml_filepath)
if xmlns_sbml_missing:
add_xmlns_sbml_attribute(sedml_filepath, sbml_filepath, tmp_sedml_filepath)
if xmlns_fbc_missing:
add_xmlns_fbc_attribute(sedml_filepath, sbml_filepath, tmp_sedml_filepath)
if xmlns_sbml_missing or xmlns_fbc_missing:
sedml_filepath = tmp_sedml_filepath
sbml_file_entry_format = get_entry_format(sbml_filepath, "SBML")
sedml_file_entry_format = get_entry_format(sedml_filepath, "SEDML")
# wrap sedml+sbml files into an omex combine archive
om = omex.Omex()
om.add_entry(
entry=omex.ManifestEntry(
location=sedml_filepath,
format=getattr(omex.EntryFormat, sedml_file_entry_format),
master=True,
),
entry_path=Path(os.path.basename(sedml_filepath)),
)
om.add_entry(
entry=omex.ManifestEntry(
location=sbml_filepath,
format=getattr(omex.EntryFormat, sbml_file_entry_format),
master=False,
),
entry_path=Path(os.path.basename(sbml_filepath)),
)
om.to_omex(Path(omex_filepath))
if os.path.exists(tmp_sedml_filepath):
os.remove(tmp_sedml_filepath)
return omex_filepath
def read_log_yml(log_filepath):
"""
read the log YAML file if it exists
return the exception message as a string
"""
if not os.path.isfile(log_filepath):
return None
with open(log_filepath) as f:
ym = yaml.safe_load(f)
return ym["exception"]["message"]
def find_files(directory, extension):
files = glob.glob(f"{directory}/**/*{extension}", recursive=True)
return files
def move_d1_files(file_paths, plot_dir="d1_plots"):
for fpath in file_paths:
# find engine.keys() in the file path and asign to engine
engine = next((e for e in ENGINES.keys() if e in fpath), "unknown")
new_file_path = os.path.join(plot_dir, f"{engine}_{os.path.basename(fpath)}")
if not os.path.exists(plot_dir):
os.makedirs(plot_dir, exist_ok=True)
if os.path.exists(new_file_path):
os.remove(new_file_path)
print(f"Moving {fpath} to {new_file_path}")
shutil.move(fpath, new_file_path)
def find_file_in_dir(file_name, directory):
"""
Searches for a specific file in a given directory and its subdirectories.
Parameters:
file_name (str): The name of the file to search for.
directory (str): The directory to search in.
Returns:
str: The path of the found file. If the file is not found, returns None.
"""
list_of_files = []
for root, _, files in os.walk(directory):
for file in files:
if file == file_name:
file_path = os.path.join(root, file)
list_of_files.append(file_path)
return list_of_files
def d1_plots_dict(d1_plots_path="d1_plots"):
"""
Create a dictionary with engine names as keys and d1 plot paths as values.
"""
d1_plots = find_files(d1_plots_path, ".pdf")
# to fix broken links in output table after changing the file structure, remove the first two parts of the path
d1_plots = [os.path.join(*Path(d1_plot).parts[1:]) for d1_plot in d1_plots]
d1_plots_dict = {
e: d1_plot for e in ENGINES.keys() for d1_plot in d1_plots if e in d1_plot
}
return d1_plots_dict
def create_hyperlink(path, title=None):
"""
Create a hyperlink to a file or folder. If the path is None, return None.
Title is the basename of the path.
"""
if path:
if title is None:
title = os.path.basename(path)
return f'<a href="{path}">{title}</a>'
else:
return None
def ansi_to_html(text):
if text is not None:
text_message = re.findall(r'"([^"]*)"', text)
if len(text_message) > 0:
text = text_message
text = bytes(text[0], "utf-8").decode("unicode_escape")
text = text.replace("|", "")
# # for any text with "<*>" remove "<" as well as ">" but leave wildcard text *
text = re.sub(r"<([^>]*)>", r"\1", text)
# replace color codes with html color codes
text = text.replace("\x1b[33m", "")
text = text.replace("\x1b[31m", "")
# # remove .\x1b[0m
text = text.replace("\x1b[0m", "")
# find first "." or ":" after "<span*" and add "</span>"after it
pattern = r'(<span style="[^"]*">[^.:]*)([.:])'
replacement = r"\1\2</span>"
text = re.sub(pattern, replacement, text, count=1)
# bullet points and new lines
text = text.replace("\r\n - ", "</li><li>")
text = text.replace("\r\n", "<br>")
text = text.replace("\n", "<br>")
# BioSimulatorsWarning: two <br> tags after
text = text.replace(
"BioSimulatorsWarning:", "<br><br>BioSimulatorsWarning:<br><br>"
)
text = text.replace(
"warnings.warn(termcolor.colored(message, Colors.warning.value), category)",
"<br>",
)
return text
def check_file_compatibility_test(engine, model_filepath, experiment_filepath):
"""
Check if the file extensions suggest the file types are compatible with the engine.
Only .sedml and .sbml files, and .xml files with 'sedml' and/or 'sbml' in their filename
are considered at this moment. It can be extended to other cases if needed in the future.
"""
file_extensions = get_filetypes(model_filepath, experiment_filepath)
engine_filetypes_tuple_list = ENGINES[engine]["formats"]
engine_name = ENGINES[engine]["name"]
flat_engine_filetypes_tuple_list = [
item
for sublist in engine_filetypes_tuple_list
for item in sublist
if sublist != "unclear"
]
compatible_filetypes = [
TYPES[i] for i in flat_engine_filetypes_tuple_list if i in list(TYPES.keys())
]
unique_compatible_filetpyes = list(set(compatible_filetypes))
unique_compatible_filetpyes_strings = (
", ".join(unique_compatible_filetpyes[:-1])
+ " and "
+ unique_compatible_filetpyes[-1]
if len(unique_compatible_filetpyes) > 1
else unique_compatible_filetpyes[0]
)
file_types = [TYPES[i] for i in file_extensions]
filetypes_strings = (
", ".join(file_types[:-1]) + " and " + file_types[-1]
if len(file_types) > 1
else file_types[0]
)
if (
file_extensions == ("sbml", "sedml")
and file_extensions not in engine_filetypes_tuple_list
):
return "FAIL", (
f"The file extensions {file_extensions} suggest the input file types are {filetypes_strings} which is not compatible with {engine_name}.<br><br>{unique_compatible_filetpyes_strings} are compatible with {engine_name}."
)
if file_extensions in engine_filetypes_tuple_list:
return "pass", (
f"The file extensions {file_extensions} suggest the input file types are {filetypes_strings}.<br><br> {unique_compatible_filetpyes_strings} are compatible with {engine_name}."
)
if "xml" in file_extensions:
model_sbml = "sbml" in model_filepath
model_sedml = "sedml" in model_filepath
experiment_sbml = "sbml" in experiment_filepath
experiment_sedml = "sedml" in experiment_filepath
if model_sbml and experiment_sbml and experiment_sedml and not model_sedml:
file_types_tuple = ("sbml", "sedml")
file_types = [TYPES[i] for i in file_types_tuple]
filetypes_strings = (
", ".join(file_types[:-1]) + " and " + file_types[-1]
if len(file_types) > 1
else file_types[0]
)
if file_types_tuple in engine_filetypes_tuple_list:
return "pass", (
f"The filenames '{model_filepath}' and '{experiment_filepath}' suggest the input files are {filetypes_strings} which is compatible with {engine_name}.<br><br>{unique_compatible_filetpyes_strings} are compatible with {engine_name}."
)
else:
return "FAIL", (
f"The filenames '{model_filepath}' and '{experiment_filepath}' suggest the input files are {filetypes_strings} which is not compatible with {engine_name}.<br><br>{unique_compatible_filetpyes_strings} are compatible with {engine_name}."
)
else:
return "unsure", (
f"The file extensions {file_extensions} suggest the input file types may not be compatibe with {engine_name}.<br><br>{unique_compatible_filetpyes_strings} are compatible with {engine_name}."
)
else:
return "unsure", (
f"The file extensions {file_extensions} suggest the input file types may not be compatibe with {engine_name}.<br><br>{unique_compatible_filetpyes_strings} are compatible with {engine_name}."
)
def collapsible_content(content, title="Details"):
"""
Create a collapsible content section in markdown format
Input: content, title
"""
if content:
return f"<details><summary>{title}</summary>{content}</details>"
else:
return f"{title}"
def get_filetypes(model_filepath, simulation_filepath):
"""
Get the filetypes of the model and simulation files
Input: model_filepath, simulation_filepath
Output: tuple of filetypes
"""
model_ext = os.path.splitext(model_filepath)[-1].lstrip(".")
simulation_ext = os.path.splitext(simulation_filepath)[-1].lstrip(".")
return (model_ext, simulation_ext)
def delete_output_folder(output_dir):
"""
# Delete the output folder and its contents
"""
for file_name in os.listdir(output_dir):
file_path = os.path.join(output_dir, file_name)
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
def run_biosimulators_remote(engine, sedml_filepath, sbml_filepath):
"""
put the sedml and sbml file into an omex archive
run it remotely using biosimulators
"""
# put the sedml and sbml into a combine archive
omex_filepath = create_omex(sedml_filepath, sbml_filepath)
omex_file_name = os.path.basename(omex_filepath)
# get the version of the engine
engine_version = biosimulations.get_simulator_versions(engine)
sim_dict = {
"name": omex_file_name,
"simulator": engine,
"simulatorVersion": engine_version[engine][-1], # get the latest version
"cpus": 1,
"memory": 8,
"maxTime": 20,
"envVars": [],
"purpose": "academic",
"email": "",
}
try:
results_urls = biosimulations.submit_simulation_archive(
archive_file=omex_file_name, sim_dict=sim_dict
)
results_urls["response"] = results_urls["response"].status_code
except Exception as exception_message:
print(
f"There was an error submitting the simulation archive:{exception_message}"
)
results_urls = {
"response": "",
"view": "",
"download": "",
"logs": "",
"exception": exception_message,
}
return results_urls
return results_urls
def get_remote_results(engine, download_link, output_dir="remote_results"):
filepath_results = download_file_from_link(engine, download_link)
extract_dir = os.path.join(os.getcwd(), output_dir, engine)
shutil.unpack_archive(filepath_results, extract_dir=extract_dir)
os.remove(filepath_results)
return extract_dir
def rename_files_in_extract_dir(extract_dir, engine):
log_yml_path = find_file_in_dir("log.yml", extract_dir)[0]
new_file_name = f"{engine}_log.yml"
root = os.path.dirname(log_yml_path)
new_file_path = os.path.join(root, new_file_name)
if os.path.exists(new_file_path):
os.remove(new_file_path)
os.rename(log_yml_path, new_file_path)
return extract_dir
def run_biosimulators_docker(
engine, sedml_filepath, sbml_filepath, output_dir="output", chown_outputs=True
):
"""
put the sedml and sbml file into an omex archive
run it locally using a biosimulators docker
categorise an error message in the log file
"""
# put the sedml and sbml into a combine archive
omex_filepath = create_omex(sedml_filepath, sbml_filepath)
log_yml_path = os.path.join(output_dir, "log.yml")
log_yml_dict = {}
exception_message = ""
try:
biosimulators_core(engine, omex_filepath, output_dir=output_dir)
except Exception as e:
exception_message = str(e)
# ensure outputs are owned by the user
if "getuid" in dir(os) and chown_outputs:
uid = os.getuid()
gid = os.getgid()
os.system(f"sudo chown -R {uid}:{gid} {output_dir}")
if os.path.exists(log_yml_path):
with open(log_yml_path) as f:
log_yml_dict = yaml.safe_load(f)
# to deal with vcell like cases where there is a log_yml with status SUCCEEDED but a detailedErrorLog.txt with "RuntimeError"
detailed_error_log_dict = {}
if os.path.exists(os.path.join(output_dir, "detailedErrorLog.txt")):
with open(os.path.join(output_dir, "detailedErrorLog.txt")) as f:
detailed_error_log = f.read()
if "RuntimeException" in detailed_error_log:
detailed_error_log_dict["status"] = "FAIL"
detailed_error_log_dict["error_message"] = "Runtime Exception"
return {
"exception_message": exception_message,
"log_yml": log_yml_dict,
"detailed_error_log": detailed_error_log_dict,
}
if "RuntimeException" in detailed_error_log:
detailed_error_log_dict["status"] = "FAIL"
detailed_error_log_dict["error_message"] = "Runtime Exception"
return {
"exception_message": exception_message,
"log_yml": log_yml_dict,
"detailed_error_log": detailed_error_log_dict,
}
def biosimulators_core(engine, omex_filepath, output_dir=None):
"""
run the omex file using biosimulators
calls biosimulators via docker locally
assumes local docker is setup
engine can be any string that matches a biosimulators docker "URI":
ghcr.io/biosimulators/{engine}
omex_filepath: the OMEX file to run
output_dir: folder to write the simulation outputs to
"""
omex_filepath_no_spaces = remove_spaces_from_filename(omex_filepath)
# directory containing omex file needs mapping into the container as the input folders
omex_dir = os.path.dirname(os.path.abspath(omex_filepath_no_spaces))
omex_file = os.path.basename(os.path.abspath(omex_filepath_no_spaces))
mount_in = docker.types.Mount("/root/in", omex_dir, type="bind", read_only=True)
# we want the output folder to be different to the input folder
# to avoid the "file already exists" type error
if not output_dir:
output_dir = os.path.join(omex_dir, "output")
os.makedirs(output_dir, exist_ok=True)
mount_out = docker.types.Mount("/root/out", output_dir, type="bind")
client = docker.from_env()
client.containers.run(
f"ghcr.io/biosimulators/{engine}",
mounts=[mount_in, mount_out],
command=f"-i '/root/in/{omex_file}' -o /root/out",
auto_remove=True,
)
client.containers.run(
f"ghcr.io/biosimulators/{engine}",
mounts=[mount_in, mount_out],
command=f"-i '/root/in/{omex_file}' -o /root/out",
auto_remove=True,
)
if os.path.exists(omex_filepath_no_spaces):
os.remove(omex_filepath_no_spaces)
def test_engine(engine, filename, error_categories=error_categories):
"""
test running the file with the given engine
return category tagged error message, or "pass" if no error was raised
"""
unknown_engine = False
try:
if engine == "tellurium":
print(f"Running tellurium natively for {filename}", file=sys.__stdout__)
tellurium.run_from_sedml_file([filename], ["-outputdir", "none"])
return "pass" # no errors
# elif engine == "some_other_engine":
# #run it here
# return "pass"
else:
unknown_engine = True
except Exception as e:
# return error object
error_str = safe_md_string(e)
print(error_str, file=sys.__stdout__)
if unknown_engine:
raise RuntimeError(f"unknown engine {engine}")
for tag in error_categories[engine]:
if re.search(error_categories[engine][tag], error_str):
return [tag, f"```{error_str}```"]
return ["other", f"```{error_str}```"]
@dataclass
class SuppressOutput:
"""
redirect stdout and/or stderr to os.devnull
stdout: whether to suppress stdout
stderr: whether to suppress stderr
"""
stdout: bool = False
stderr: bool = False
def suppress(self):
"begin to suppress output(s)"
if self.stdout:
self.orig_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
if self.stderr:
self.orig_stderr = sys.stderr
sys.stderr = open(os.devnull, "w")
def restore(self):
"restore output(s)"
if self.stdout:
sys.stdout.close()
sys.stdout = self.orig_stdout
if self.stderr:
sys.stderr.close()
sys.stderr = self.orig_stderr
class RequestCache:
"""
caching is used to prevent the need to download the same responses from the remote server multiple times during testing
currently no handling of unexpected cache misses
"""
def __init__(self, mode="off", direc="cache"):
"""
mode:
"off" to disable caching (does not wipe any existing cache data)
"store" to wipe and store fresh results in the cache
"reuse" to only use existing cache files
"auto" to download only if missing
could also implement "auto" mode that only downloads on a cache miss
direc: the directory used to store the cache
"""
self.mode = mode
# store absolute cache dir path to ensure it is found regardless of current directory
self.absolute_dir = os.path.join(os.getcwd(), direc)
if mode == "store":
self.wipe()
def wipe(self):
"wipe any existing cache directory and setup a new empty one"
shutil.rmtree(self.absolute_dir, ignore_errors=True)
os.makedirs(self.absolute_dir, exist_ok=True)
def get_path(self, request=None):
"""
return path to cached request response
or just the cache base directory for a null request
"""
return os.path.join(
f"{self.absolute_dir}", hashlib.sha256(request.encode("UTF-8")).hexdigest()
)
# return f"{self.absolute_dir}/{hashlib.sha256(request.encode('UTF-8')).hexdigest()}"
def get_entry(self, request):
"""
load cached response
note this should only be used in a context where you trust the integrity of the cache files
due to using pickle
note also: no explicit handling of cache misses yet implemented
"""
with open(self.get_path(request), "rb") as f:
return pickle.load(f)
def set_entry(self, request, response):
"""
save a response to the cache
"""
with open(self.get_path(request), "wb") as fout:
pickle.dump(response, fout)
def do_request(self, request):
"""
automatically handle the cache operations for the call_back function
"""
if self.mode == "reuse" or (
self.mode == "auto" and os.path.isfile(self.get_path(request))
):
return self.get_entry(request)
response = requests.get(request)
response.raise_for_status()
if self.mode == "store" or self.mode == "auto":
self.set_entry(request, response)
return response
class MarkdownTable:
"""
helper class to accumulate rows of data with a header and optional summary row
to be written to file as a markdown table
"""
def __init__(
self, labels: str, keys: str, splitter="|", PASS="pass", FAIL="FAIL", NA="NA"
):
"specify column headers and variable names"