-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathutils.py
More file actions
698 lines (667 loc) · 19.7 KB
/
utils.py
File metadata and controls
698 lines (667 loc) · 19.7 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
import os
import shutil
import subprocess
from bionetgen.core.exc import BNGPerlError
from bionetgen.core.utils.logging import BNGLogger
class ActionList:
"""
Class to store everything related to BioNetGen actions.
This class stores information about the list of BNG actions, their
arguments as well as their syntax information. The class also provides
an argument parser using pyparsing.
Usage: ActionList()
Attributes
----------
normal_types : list
no_setter_syntax : list
actions without => syntax
square_braces : list
actions that use [] syntax in them
before_model : list
actions that are supposed to come before the model
possible_types : list
the list of all possible actions
arg_dict : dict
dictionary that contains every argument of every action
irregular_args : dict
actions that have arguments that aren't simply arg=>val
Methods
---------
is_before_model : bool
checks if a given action is supposed to come before `begin model`
define_parser : None
sets ActionList.action_parser to a pyparsing parser that's capable of
splitting up any BNG action into parts
"""
def __init__(self):
# these are all the action types, categorized
# by their argument syntax
self.normal_types = [
"generate_network",
"generate_hybrid_model",
"simulate",
"simulate_ode",
"simulate_ssa",
"simulate_pla",
"simulate_nf",
"parameter_scan",
"bifurcate",
"readFile",
"writeFile",
"writeModel",
"writeNetwork",
"writeXML",
"writeSBML",
"writeMfile",
"writeCPYfile",
"writeMexfile",
"writeMDL",
"visualize",
]
self.no_setter_syntax = [
"setConcentration",
"addConcentration",
"setParameter",
"quit",
"setModelName",
"substanceUnits",
"version",
"setOption",
]
self.square_braces = [
"saveConcentrations",
"resetConcentrations",
"resetParameters",
"saveParameters",
]
# remember what's written before models
self.before_model = [
"setModelName",
"substanceUnits",
"version",
"setOption",
]
self.possible_types = (
self.normal_types + self.no_setter_syntax + self.square_braces
)
# Use dictionary to keep track of all possible args (and types?) for each action
self.arg_dict = {}
# arg_dict["action"] = ["arg1", "arg2", "etc."]
# normal_types
self.arg_dict["generate_network"] = [
"prefix",
"suffix",
"verbose",
"overwrite",
"print_iter",
"max_agg",
"max_iter",
"max_stoich",
"TextReaction",
"TextSpecies",
]
self.arg_dict["generate_hybrid_model"] = [
"prefix",
"suffix",
"verbose",
"overwrite",
"actions",
"execute",
"safe",
]
self.arg_dict["simulate"] = [
"prefix",
"suffix",
"verbose",
"method",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
# TODO: arguments for a method called "psa" that is not documented in
# https://docs.google.com/spreadsheets/d/1Co0bPgMmOyAFxbYnGCmwKzoEsY2aUCMtJXQNpQCEUag/
"poplevel",
"check_product_scale",
]
self.arg_dict["simulate_ode"] = [
"prefix",
"suffix",
"verbose",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
"atol",
"rtol",
"sparse",
"steady_state",
]
self.arg_dict["simulate_ssa"] = [
"prefix",
"suffix",
"verbose",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
]
self.arg_dict["simulate_pla"] = [
"prefix",
"suffix",
"verbose",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
"pla_config",
"pla_output",
]
self.arg_dict["simulate_nf"] = [
"prefix",
"suffix",
"verbose",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
"complex",
"nocslf",
"notf",
"binary_output",
"gml",
"equil",
"get_final_state",
"utl",
"param",
]
self.arg_dict["simulate"] = list(
set(
self.arg_dict["simulate"]
+ self.arg_dict["simulate_ode"]
+ self.arg_dict["simulate_ssa"]
+ self.arg_dict["simulate_pla"]
+ self.arg_dict["simulate_nf"]
)
)
self.arg_dict["parameter_scan"] = [
"prefix",
"suffix",
"verbose",
"method",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
"parameter",
"par_min",
"par_max",
"n_scan_pts",
"log_scale",
"par_scan_vals",
"reset_conc",
]
self.arg_dict["parameter_scan"] = list(
set(self.arg_dict["parameter_scan"] + self.arg_dict["simulate"])
)
self.arg_dict["bifurcate"] = [
"prefix",
"suffix",
"verbose",
"method",
"argfile",
"continue",
"t_start",
"t_end",
"n_steps",
"n_output_steps",
"sample_times",
"output_step_interval",
"max_sim_steps",
"stop_if",
"print_on_stop",
"print_end",
"print_net",
"save_progress",
"print_CDAT",
"print_functions",
"netfile",
"seed",
"parameter",
"par_min",
"par_max",
"n_scan_pts",
"log_scale",
"par_scan_vals",
]
self.arg_dict["bifurcate"] = list(
set(self.arg_dict["bifurcate"] + self.arg_dict["parameter_scan"])
)
self.arg_dict["bifurcate"].remove("reset_conc")
self.arg_dict["readFile"] = ["file", "blocks", "atomize", "skip_actions"]
self.arg_dict["writeFile"] = [
"format",
"prefix",
"suffix",
"evaluate_expressions",
"include_model",
"include_network",
"overwrite",
"pretty_formatting",
"TextReaction",
"TextSpecies",
]
self.arg_dict["writeModel"] = [
"format",
"prefix",
"suffix",
"evaluate_expressions",
"include_model",
"include_network",
"overwrite",
"pretty_formatting",
"TextReaction",
"TextSpecies",
]
self.arg_dict["writeNetwork"] = [
"format",
"prefix",
"suffix",
"evaluate_expressions",
"include_model",
"include_network",
"overwrite",
"pretty_formatting",
"TextReaction",
"TextSpecies",
]
self.arg_dict["writeXML"] = [
"format",
"prefix",
"suffix",
"evaluate_expressions",
"include_model",
"include_network",
"overwrite",
"pretty_formatting",
"TextReaction",
"TextSpecies",
]
self.arg_dict["writeSBML"] = ["prefix", "suffix"]
self.arg_dict["writeMfile"] = [
"prefix",
"suffix",
"t_start",
"t_end",
"n_steps",
"atol",
"rtol",
"max_step",
"bdf",
"maxOrder",
"stats",
]
self.arg_dict["writeCPYfile"] = [
"prefix",
"suffix",
"t_start",
"t_end",
"n_steps",
"atol",
"rtol",
"max_step",
"bdf",
"maxOrder",
"stats",
]
self.arg_dict["writeMexfile"] = [
"prefix",
"suffix",
"t_start",
"t_end",
"n_steps",
"atol",
"rtol",
"max_step",
"max_num_steps",
"max_err_test_fails",
"max_conv_fails",
"stiff",
"sparse",
]
self.arg_dict["writeMDL"] = ["prefix", "suffix"]
self.arg_dict["visualize"] = [
"type",
"help",
"suffix",
"each",
"background",
"groups",
"collapse",
"filter",
"level",
"textonly",
"opts",
"ruleNames",
]
# no_setter_syntax
self.arg_dict["setConcentration"] = []
self.arg_dict["addConcentration"] = []
self.arg_dict["setParameter"] = []
self.arg_dict["saveParameters"] = []
self.arg_dict["quit"] = None
self.arg_dict["setModelName"] = []
self.arg_dict["substanceUnits"] = []
self.arg_dict["version"] = []
self.arg_dict["setOption"] = []
# square_braces
self.arg_dict["saveConcentrations"] = []
self.arg_dict["resetConcentrations"] = []
self.arg_dict["resetParameters"] = []
# irregular arg types
self.irregular_args = {}
self.irregular_args["max_stoich"] = "dict"
self.irregular_args["actions"] = "list"
self.irregular_args["sample_times"] = "list"
self.irregular_args["par_scan_vals"] = "list"
self.irregular_args["blocks"] = "list"
self.irregular_args["opts"] = "list"
def is_before_model(self, action_name):
if action_name in self.before_model:
return True
return False
def define_parser(self):
## Define action grammar
import pyparsing as pp
#
base_name = pp.Word(pp.alphas, pp.alphanums + "_")
action_name = base_name
#
dquote_word = pp.dblQuotedString
squote_word = pp.sglQuotedString
quote_word = dquote_word ^ squote_word
# all action argument types
# TODO: deal w/ zero argument list
list_arg = "[" + pp.delimitedList(quote_word) + "]"
#
arg_type_bool = pp.Word("0") ^ pp.Word("1")
arg_type_int = pp.Word(pp.nums)
arg_type_float = pp.Word(pp.nums + ".")
arg_type_expr = pp.Word(
pp.nums + "." + "+" + "-" + "e" + "E" + "(" + ")" + "/" + "*" + "^"
)
arg_type_list = "[" + pp.delimitedList((quote_word ^ arg_type_float)) + "]"
arg_type_string = quote_word
#
curly_arg_token = quote_word + "=>" + arg_type_int
# TODO: handle 0 case
arg_type_curly = "{" + pp.delimitedList(curly_arg_token) + "}"
arg_types = (
arg_type_bool
^ arg_type_int
^ arg_type_float
^ arg_type_list
^ arg_type_list
^ arg_type_string
^ arg_type_curly
^ arg_type_expr
)
#
one_arg = quote_word
two_arg = quote_word + "," + (arg_type_expr ^ quote_word)
#
single_arg = base_name + "=>" + arg_types
#
reg_arg_full = "{" + pp.Optional(pp.delimitedList(single_arg)) + "}"
#
reg_action_tk = (
action_name + "(" + reg_arg_full + ")" + pp.Optional(";") + pp.stringEnd
)
two_arg_action_tk = (
action_name
+ "("
+ quote_word
+ ","
+ pp.SkipTo(")" + pp.Optional(";") + pp.stringEnd)
+ ")"
+ pp.Optional(";")
+ pp.stringEnd
)
one_arg_action_tk = (
action_name
+ "("
+ pp.Optional(one_arg)
+ ")"
+ pp.Optional(";")
+ pp.stringEnd
)
list_arg_action_tk = (
action_name + "(" + list_arg + ")" + pp.Optional(";") + pp.stringEnd
)
full_action_tk = (
reg_action_tk ^ list_arg_action_tk ^ two_arg_action_tk ^ one_arg_action_tk
)
## Action grammar done
self.action_parser = full_action_tk
def find_BNG_path(BNGPATH=None):
"""
A simple function finds the path to BNG2.pl from
* Environment variable
* Assuming it's under PATH
* Given optional path as argument
Usage: test_bngexec(path)
test_bngexec()
Arguments
---------
BNGPATH : str
(optional) path to the folder that contains BNG2.pl
"""
# TODO: Figure out how to use the BNG2.pl if it's set
# in the PATH variable. Solution: set os.environ BNGPATH
# and make everything use that route
def _try_path(candidate_path):
if candidate_path is None:
return None
# candidate can be either a directory or a direct path to BNG2.pl
if os.path.basename(candidate_path).lower() == "bng2.pl":
candidate_dir = os.path.dirname(candidate_path)
candidate_exec = candidate_path
else:
candidate_dir = candidate_path
candidate_exec = os.path.join(candidate_path, "BNG2.pl")
if test_bngexec(candidate_exec):
return candidate_dir, candidate_exec
return None
# 1) Prefer explicit argument
tried = []
if BNGPATH is not None:
tried.append(BNGPATH)
hit = _try_path(BNGPATH)
if hit is not None:
return hit
# 2) Environment variable
env_path = os.environ.get("BNGPATH")
if env_path:
tried.append(env_path)
hit = _try_path(env_path)
if hit is not None:
return hit
# 3) On PATH
bng_on_path = shutil.which("BNG2.pl")
if bng_on_path:
tried.append(bng_on_path)
hit = _try_path(bng_on_path)
if hit is not None:
return hit
# If we get here, BNG2.pl is not available. Some users may only need
# basic BNGL parsing behavior and may not have BioNetGen installed.
# Return (None, None) so callers can either raise a clearer error or
# fall back to a minimal in-Python parse.
return None, None
def test_perl(app=None, perl_path=None):
"""
Test if perl is working
Arguments
---------
perl_path : str
(optional) path to the folder that contains perl
"""
logger = BNGLogger(app=app)
logger.debug("Checking if perl is installed.", loc=f"{__file__} : test_perl()")
# find path to perl binary
if perl_path is None:
perl_path = shutil.which("perl")
if perl_path is None:
raise BNGPerlError
# check if perl is actually working
command = [perl_path, "-v"]
rc, _ = run_command(command)
if rc != 0:
raise BNGPerlError
def test_bngexec(bngexec):
"""
A simple function that test if BNG2.pl given runs
Usage: test_bngexec(path)
Arguments
---------
bngexec : str
path to BNG2.pl to test
"""
command = ["perl", bngexec]
rc, _ = run_command(command)
if rc == 0:
return True
else:
return False
def run_command(command, suppress=True, timeout=None, cwd=None):
"""
A convenience function to run a given command. The command should be
given as a list of values e.g. ['command', 'arg1', 'arg2'] etc.
Suppress kwarg suppresses all output from the command and timeout kwarg
allows you to set a time period in seconds after which the command will
be killed.
"""
if timeout is not None:
if suppress:
# I am unsure how to do both timeout and the live polling of stdo
rc = subprocess.run(
command,
timeout=timeout,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
cwd=cwd,
)
return rc.returncode, rc
else:
# I am unsure how to do both timeout and the live polling of stdo
rc = subprocess.run(command, timeout=timeout, capture_output=True, cwd=cwd)
return rc.returncode, rc
else:
if suppress:
process = subprocess.Popen(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
bufsize=-1,
cwd=cwd,
)
rc = process.wait()
return rc, process
else:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, encoding="utf8", cwd=cwd
)
out = []
while True:
output = process.stdout.readline()
if output == "" and process.poll() is not None:
break
if output:
o = output.strip()
out.append(o)
# print(o) # Removed to avoid bottleneck in tests
rc = process.wait()
return rc, out