-
Notifications
You must be signed in to change notification settings - Fork 30
/
runners.py
1472 lines (1269 loc) · 49.9 KB
/
runners.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Util methods related to running models.
File: pyneuroml/utils/runners.py
Copyright 2024 NeuroML contributors
"""
import inspect
import logging
import math
import os
import pathlib
import shlex
import shutil
import subprocess
import sys
import time
import traceback
import typing
from datetime import datetime
from pathlib import Path
from typing import Optional
import ppft as pp
from lxml import etree
import pyneuroml.utils
import pyneuroml.utils.misc
from pyneuroml import DEFAULTS, __version__
from pyneuroml.errors import UNKNOWN_ERR
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def run_lems_with_jneuroml(
lems_file_name: str,
paths_to_include: list = [],
max_memory: str = DEFAULTS["default_java_max_memory"],
skip_run: bool = False,
nogui: bool = False,
load_saved_data: bool = False,
reload_events: bool = False,
plot: bool = False,
show_plot_already: bool = True,
exec_in_dir: str = ".",
verbose: bool = DEFAULTS["v"],
exit_on_fail: bool = True,
cleanup: bool = False,
) -> typing.Union[bool, typing.Union[dict, typing.Tuple[dict, dict]]]:
"""Parse/Run a LEMS file with jnml.
Tip: set `skip_run=True` to only parse the LEMS file but not run the simulation.
:param lems_file_name: name of LEMS file to run
:type lems_file_name: str
:param paths_to_include: additional directory paths to include (for other NML/LEMS files, for example)
:type paths_to_include: list(str)
:param max_memory: maximum memory allowed for use by the JVM
:type max_memory: bool
:param skip_run: toggle whether run should be skipped, if skipped, file will only be parsed
:type skip_run: bool
:param nogui: toggle whether jnml GUI should be shown
:type nogui: bool
:param load_saved_data: toggle whether any saved data should be loaded
:type load_saved_data: bool
:param reload_events: toggle whether events should be reloaded
:type reload_events: bool
:param plot: toggle whether specified plots should be plotted
:type plot: bool
:param show_plot_already: toggle whether prepared plots should be shown
:type show_plot_already: bool
:param exec_in_dir: working directory to execute LEMS simulation in
:type exec_in_dir: str
:param verbose: toggle whether jnml should print verbose information
:type verbose: bool
:param exit_on_fail: toggle whether command should exit if jnml fails
:type exit_on_fail: bool
:param cleanup: toggle whether the directory should be cleaned of generated files after run completion
:type cleanup: bool
"""
logger.info(
"Loading LEMS file: {} and running with jNeuroML".format(lems_file_name)
)
post_args = ""
post_args += _gui_string(nogui)
post_args += _include_string(paths_to_include)
t_run = datetime.now()
if not skip_run:
success = run_jneuroml(
"",
lems_file_name,
post_args,
max_memory=max_memory,
exec_in_dir=exec_in_dir,
verbose=verbose,
report_jnml_output=verbose,
exit_on_fail=exit_on_fail,
)
if not success:
return False
if load_saved_data:
if verbose: logger.info(
"Reloading data generated by: {}, plotting: {}".format(lems_file_name, plot)
)
return reload_saved_data(
lems_file_name,
base_dir=exec_in_dir,
t_run=t_run,
plot=plot,
show_plot_already=show_plot_already,
simulator="jNeuroML",
reload_events=reload_events,
remove_dat_files_after_load=cleanup,
)
else:
return True
def run_multiple_lems_with(
num_parallel: typing.Optional[int], sims_spec: typing.Dict[typing.Any, typing.Any]
):
"""Run multiple LEMS simulation files in a pool.
Uses the `ppft <https://ppft.readthedocs.io/en/latest/>`__ module.
:param num_parallel: number of simulations to run in parallel, if None, ppft
will auto-detect
:type num_parallel: None or int
:param sims_spec: dictionary with simulation specifications
Each key of the dict should be the name of the LEMS file to be
simulated, and the keys will be dictionaries that contain the arguments
and key word arguments to pass to the `run_lems_with` method:
.. code-block:: python
{
"LEMS1.xml": {
"engine": "name of engine",
"args": ("arg1", "arg2"),
"kwargs": {
"kwarg1": value
}
}
Note that since the name of the simulation file and the engine are
already explicitly provided, these should not be included again in the
args/kwargs
:type sims_spec: dict
:returns: dict with results of runs, depending on given arguments:
.. code-block:: python
{
"LEMS1.xml": <results>
}
:rtype: dict
"""
results = {}
if num_parallel is None:
jobserver = pp.Server()
logger.info("Created job server by auto-detecting number of jobs")
else:
logger.info(f"Created job server using {num_parallel} jobs")
jobserver = pp.Server(num_parallel)
function_tuple = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
ctr = 0
for sim, sim_dict in sims_spec.items():
if "engine" not in sim_dict:
raise ValueError("No engine provided")
if "args" not in sim_dict:
sim_dict["args"] = ()
if "kwargs" not in sim_dict:
sim_dict["kwargs"] = {}
# ppft's submit function only takes args, not kwargs, so we need to
# create args from provided kwargs
# In doing so, we end up re-implementing some functionality of the
# `run_lems_with` function, but that cannot be helped
found = False
for fname, function in function_tuple:
if fname.startswith("run_lems_with") and fname.endswith(sim_dict["engine"]):
callfunc = inspect.signature(function)
found = True
bound_arguments = callfunc.bind(sim_dict["args"], **sim_dict["kwargs"])
bound_arguments.apply_defaults()
bound_arguments.arguments["lems_file_name"] = sim
print(f"[{ctr}/{len(sims_spec)}] Submitting {sim} to jobserver")
logger.debug(
f"[{ctr}/{len(sims_spec)}] Submitting {sim} to jobserver with specs: {bound_arguments.arguments}"
)
logger.debug(f"globals are: {globals()}")
results[sim] = jobserver.submit(
function, args=bound_arguments.args, modules=(), globals=globals()
)
jobserver.print_stats()
ctr += 1
break
if found is False:
logger.error(f"No function run_lems_with_{sims_spec['engine']} found")
return {}
logger.info("Waiting for jobs to finish")
jobserver.wait()
jobserver.print_stats()
return results
def run_lems_with(engine: str, *args: typing.Any, **kwargs: typing.Any):
"""Run LEMS with specified engine.
Wrapper around the many `run_lems_with_*` methods.
The engine should be the suffix, for example, to use
`run_lems_with_jneuroml_neuron`, engine will be `jneuroml_neuron`.
All kwargs are passed as is to the function. Please see the individual
function documentations for information on arguments.
:param engine: engine to run with
:type engine: string (valid names are methods)
:param args: postional arguments to pass to run function
:param kwargs: named arguments to pass to run function
:returns: return value of called method
"""
function_tuple = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
found = False
for fname, function in function_tuple:
if fname.startswith("run_lems_with") and fname.endswith(engine):
print(f"Running with {fname}")
found = True
retval = function(*args, **kwargs)
if found is False:
logger.error(f"Could not find engine {engine}. Exiting.")
return False
return retval
def run_lems_with_jneuroml_neuron(
lems_file_name: str,
paths_to_include: typing.List[str] = [],
max_memory: str = DEFAULTS["default_java_max_memory"],
skip_run: bool = False,
nogui: bool = False,
load_saved_data: bool = False,
reload_events: bool = False,
plot: bool = False,
show_plot_already: bool = True,
exec_in_dir: str = ".",
only_generate_scripts: bool = False,
compile_mods: bool = True,
verbose: bool = DEFAULTS["v"],
exit_on_fail: bool = True,
cleanup: bool = False,
realtime_output: bool = False,
) -> typing.Union[bool, typing.Union[dict, typing.Tuple[dict, dict]]]:
# jnml_runs_neuron=True): #jnml_runs_neuron=False is Work in progress!!!
"""Run LEMS file with the NEURON simulator
Tip: set `skip_run=True` to only parse the LEMS file but not run the simulation.
:param lems_file_name: name of LEMS file to run
:type lems_file_name: str
:param paths_to_include: additional directory paths to include (for other NML/LEMS files, for example)
:type paths_to_include: list(str)
:param max_memory: maximum memory allowed for use by the JVM
:type max_memory: bool
:param skip_run: toggle whether run should be skipped, if skipped, file will only be parsed
:type skip_run: bool
:param nogui: toggle whether jnml GUI should be shown
:type nogui: bool
:param load_saved_data: toggle whether any saved data should be loaded
:type load_saved_data: bool
:param reload_events: toggle whether events should be reloaded
:type reload_events: bool
:param plot: toggle whether specified plots should be plotted
:type plot: bool
:param show_plot_already: toggle whether prepared plots should be shown
:type show_plot_already: bool
:param exec_in_dir: working directory to execute LEMS simulation in
:type exec_in_dir: str
:param only_generate_scripts: toggle whether only the runner script should be generated
:type only_generate_scripts: bool
:param compile_mods: toggle whether generated mod files should be compiled
:type compile_mods: bool
:param verbose: toggle whether jnml should print verbose information
:type verbose: bool
:param exit_on_fail: toggle whether command should exit if jnml fails
:type exit_on_fail: bool
:param cleanup: toggle whether the directory should be cleaned of generated files after run completion
:type cleanup: bool
:param realtime_output: toggle whether realtime output should be shown
:type realtime_output: bool
"""
logger.info(
"Loading LEMS file: {} and running with jNeuroML_NEURON".format(lems_file_name)
)
post_args = " -neuron"
if not only_generate_scripts: # and jnml_runs_neuron:
post_args += " -run"
if compile_mods:
post_args += " -compile"
post_args += _gui_string(nogui)
post_args += _include_string(paths_to_include)
t_run = datetime.now()
if skip_run:
success = True
else:
# Fix PYTHONPATH for NEURON: has been an issue on HBP Collaboratory...
if "PYTHONPATH" not in os.environ:
os.environ["PYTHONPATH"] = ""
for path in sys.path:
if path + ":" not in os.environ["PYTHONPATH"]:
os.environ["PYTHONPATH"] = "%s:%s" % (path, os.environ["PYTHONPATH"])
logger.debug("PYTHONPATH for NEURON: {}".format(os.environ["PYTHONPATH"]))
if realtime_output:
success = run_jneuroml_with_realtime_output(
"",
lems_file_name,
post_args,
max_memory=max_memory,
exec_in_dir=exec_in_dir,
verbose=verbose,
exit_on_fail=exit_on_fail,
)
logger.debug("PYTHONPATH for NEURON: {}".format(os.environ["PYTHONPATH"]))
else:
success = run_jneuroml(
"",
lems_file_name,
post_args,
max_memory=max_memory,
exec_in_dir=exec_in_dir,
verbose=verbose,
report_jnml_output=verbose,
exit_on_fail=exit_on_fail,
)
"""
TODO: Work in progress!!!
if not jnml_runs_neuron:
logger.info("Running...")
from LEMS_NML2_Ex5_DetCell_nrn import NeuronSimulation
ns = NeuronSimulation(tstop=300, dt=0.01, seed=123456789)
ns.run()
"""
if not success:
return False
if load_saved_data:
return reload_saved_data(
lems_file_name,
base_dir=exec_in_dir,
t_run=t_run,
plot=plot,
show_plot_already=show_plot_already,
simulator="jNeuroML_NEURON",
reload_events=reload_events,
remove_dat_files_after_load=cleanup,
)
else:
return True
def run_lems_with_jneuroml_netpyne(
lems_file_name: str,
paths_to_include: typing.List[str] = [],
max_memory: str = DEFAULTS["default_java_max_memory"],
skip_run: bool = False,
nogui: bool = False,
num_processors: int = 1,
load_saved_data: bool = False,
reload_events: bool = False,
plot: bool = False,
show_plot_already: bool = True,
exec_in_dir: str = ".",
only_generate_scripts: bool = False,
only_generate_json: bool = False,
verbose: bool = DEFAULTS["v"],
exit_on_fail: bool = True,
return_string: bool = False,
cleanup: bool = False,
) -> typing.Union[
bool, typing.Tuple[bool, str], typing.Union[dict, typing.Tuple[dict, dict]]
]:
"""Run LEMS file with the NEURON simulator
Tip: set `skip_run=True` to only parse the LEMS file but not run the simulation.
:param lems_file_name: name of LEMS file to run
:type lems_file_name: str
:param paths_to_include: additional directory paths to include (for other NML/LEMS files, for example)
:type paths_to_include: list(str)
:param max_memory: maximum memory allowed for use by the JVM
:type max_memory: bool
:param skip_run: toggle whether run should be skipped, if skipped, file will only be parsed
:type skip_run: bool
:param nogui: toggle whether jnml GUI should be shown
:type nogui: bool
:param num_processors: number of processors to use for running NetPyNE
:type num_processors: int
:param load_saved_data: toggle whether any saved data should be loaded
:type load_saved_data: bool
:param reload_events: toggle whether events should be reloaded
:type reload_events: bool
:param plot: toggle whether specified plots should be plotted
:type plot: bool
:param show_plot_already: toggle whether prepared plots should be shown
:type show_plot_already: bool
:param exec_in_dir: working directory to execute LEMS simulation in
:type exec_in_dir: str
:param only_generate_scripts: toggle whether only the runner script should be generated
:type only_generate_scripts: bool
:param verbose: toggle whether jnml should print verbose information
:type verbose: bool
:param exit_on_fail: toggle whether command should exit if jnml fails
:type exit_on_fail: bool
:param return_string: toggle whether command output string should be returned
:type return_string: bool
:param cleanup: toggle whether the directory should be cleaned of generated files after run completion
:type cleanup: bool
:returns: either a bool, or a Tuple (bool, str) depending on the value of
return_string: True of jnml ran successfully, False if not; along with the
output of the command. If load_saved_data is True, it returns a dict
with the data
"""
logger.info(
"Loading LEMS file: {} and running with jNeuroML_NetPyNE".format(lems_file_name)
)
post_args = " -netpyne"
if num_processors != 1:
post_args += " -np %i" % num_processors
if not only_generate_scripts and not only_generate_json:
post_args += " -run"
if only_generate_json:
post_args += " -json"
post_args += _gui_string(nogui)
post_args += _include_string(paths_to_include)
t_run = datetime.now()
if skip_run:
success = True
else:
if return_string is True:
(success, output_string) = run_jneuroml(
"",
lems_file_name,
post_args,
max_memory=max_memory,
exec_in_dir=exec_in_dir,
verbose=verbose,
exit_on_fail=exit_on_fail,
return_string=True,
)
else:
success = run_jneuroml(
"",
lems_file_name,
post_args,
max_memory=max_memory,
exec_in_dir=exec_in_dir,
verbose=verbose,
exit_on_fail=exit_on_fail,
return_string=False,
)
if not success and return_string is True:
return False, output_string
if not success and return_string is False:
return False
if load_saved_data:
return reload_saved_data(
lems_file_name,
base_dir=exec_in_dir,
t_run=t_run,
plot=plot,
show_plot_already=show_plot_already,
simulator="jNeuroML_NetPyNE",
reload_events=reload_events,
remove_dat_files_after_load=cleanup,
)
if return_string is True:
return True, output_string
return True
# TODO: need to enable run with Brian2!
def run_lems_with_jneuroml_brian2(
lems_file_name: str,
paths_to_include: typing.List[str] = [],
max_memory: str = DEFAULTS["default_java_max_memory"],
skip_run: bool = False,
nogui: bool = False,
load_saved_data: bool = False,
reload_events: bool = False,
plot: bool = False,
show_plot_already: bool = True,
exec_in_dir: str = ".",
verbose: bool = DEFAULTS["v"],
exit_on_fail: bool = True,
cleanup: bool = False,
) -> typing.Union[bool, typing.Union[dict, typing.Tuple[dict, dict]]]:
"""Run LEMS file with the NEURON simulator
Tip: set `skip_run=True` to only parse the LEMS file but not run the simulation.
:param lems_file_name: name of LEMS file to run
:type lems_file_name: str
:param paths_to_include: additional directory paths to include (for other NML/LEMS files, for example)
:type paths_to_include: list(str)
:param max_memory: maximum memory allowed for use by the JVM
:type max_memory: bool
:param skip_run: toggle whether run should be skipped, if skipped, file will only be parsed
:type skip_run: bool
:param nogui: toggle whether jnml GUI should be shown
:type nogui: bool
:param load_saved_data: toggle whether any saved data should be loaded
:type load_saved_data: bool
:param reload_events: toggle whether events should be reloaded
:type reload_events: bool
:param plot: toggle whether specified plots should be plotted
:type plot: bool
:param show_plot_already: toggle whether prepared plots should be shown
:type show_plot_already: bool
:param exec_in_dir: working directory to execute LEMS simulation in
:type exec_in_dir: str
:param verbose: toggle whether jnml should print verbose information
:type verbose: bool
:param exit_on_fail: toggle whether command should exit if jnml fails
:type exit_on_fail: bool
:param cleanup: toggle whether the directory should be cleaned of generated files after run completion
:type cleanup: bool
"""
logger.info(
"Loading LEMS file: {} and running with jNeuroML_Brian2".format(lems_file_name)
)
post_args = " -brian2"
# post_args += _gui_string(nogui)
# post_args += _include_string(paths_to_include)
t_run = datetime.now()
if skip_run:
success = True
else:
success = run_jneuroml(
"",
lems_file_name,
post_args,
max_memory=max_memory,
exec_in_dir=exec_in_dir,
verbose=verbose,
exit_on_fail=exit_on_fail,
)
old_sys_args = [a for a in sys.argv]
sys.argv[1] = "-nogui" # To supress gui for brian simulation...
logger.info(
"Importing generated Brian2 python file (changed args from {} to {})".format(
old_sys_args, sys.argv
)
)
brian2_py_name = lems_file_name.replace(".xml", "_brian2")
exec("import %s" % brian2_py_name)
sys.argv = old_sys_args
logger.info("Finished Brian2 simulation, back to {}".format(sys.argv))
if not success:
return False
if load_saved_data:
return reload_saved_data(
lems_file_name,
base_dir=exec_in_dir,
t_run=t_run,
plot=plot,
show_plot_already=show_plot_already,
simulator="jNeuroML_Brian2",
reload_events=reload_events,
remove_dat_files_after_load=cleanup,
)
else:
return True
def run_lems_with_eden(
lems_file_name: str,
load_saved_data: bool = False,
reload_events: bool = False,
verbose: bool = DEFAULTS["v"],
) -> typing.Union[bool, typing.Union[dict, typing.Tuple[dict, dict]]]:
"""Run LEMS file with the EDEN simulator
:param lems_file_name: name of LEMS file to run
:type lems_file_name: str
:param load_saved_data: toggle whether any saved data should be loaded
:type load_saved_data: bool
:param reload_events: toggle whether events should be reloaded
:type reload_events: bool
:param verbose: toggle whether to print verbose information
:type verbose: bool
"""
import eden_simulator
logger.info(
"Running a simulation of %s in EDEN v%s"
% (
lems_file_name,
(
eden_simulator.__version__
if hasattr(eden_simulator, "__version__")
else "???"
),
)
)
results = eden_simulator.runEden(lems_file_name)
if verbose:
logger.info(
"Completed simulation in EDEN, saved results: %s" % (results.keys())
)
if load_saved_data:
logger.warning("Event saving is not yet supported in EDEN!!")
return results, {}
elif load_saved_data:
return results
else:
return True
def _gui_string(nogui: bool) -> str:
"""Return the gui string for jnml
:param nogui: toggle whether GUI should be used or not
:type nogui: bool
:returns: gui string or empty string
"""
return " -nogui" if nogui else ""
def _include_string(
paths_to_include: typing.Union[str, typing.Tuple[str], typing.List[str]]
) -> str:
"""Convert a path or list of paths into an include string to be used by jnml.
:param paths_to_include: path or list or tuple of paths to be included
:type paths_to_include: str or list(str) or tuple(str)
:returns: include string to be used with jnml.
"""
if paths_to_include:
if type(paths_to_include) is str:
paths_to_include = [paths_to_include]
if type(paths_to_include) in (tuple, list):
result = " -I '%s'" % ":".join(paths_to_include)
else:
result = ""
return result
def run_jneuroml(
pre_args: str,
target_file: str,
post_args: str,
max_memory: str = DEFAULTS["default_java_max_memory"],
exec_in_dir: str = ".",
verbose: bool = DEFAULTS["v"],
report_jnml_output: bool = True,
exit_on_fail: bool = False,
return_string: bool = False,
) -> typing.Union[typing.Tuple[bool, str], bool]:
"""Run jnml with provided arguments.
:param pre_args: pre-file name arguments
:type pre_args: list of strings
:param target_file: LEMS or NeuroML file to run jnml on
:type target_file: str
:param max_memory: maximum memory allowed for use by the JVM
Note that the default value of this can be overridden using the
JNML_MAX_MEMORY_LOCAL environment variable
:type max_memory: str
:param exec_in_dir: working directory to execute LEMS simulation in
:type exec_in_dir: str
:param verbose: toggle whether jnml should print verbose information
:type verbose: bool
:param report_jnml_output: toggle whether jnml output should be printed
:type report_jnml_output: bool
:param exit_on_fail: toggle whether command should exit if jnml fails
:type exit_on_fail: bool
:param return_string: toggle whether the output string should be returned
:type return_string: bool
:returns: either a bool, or a Tuple (bool, str) depending on the value of
return_string: True of jnml ran successfully, False if not; along with the
output of the command
"""
logger.debug(
"Running jnml on %s with pre args: [%s], post args: [%s], in dir: %s, verbose: %s, report: %s, exit on fail: %s"
% (
target_file,
pre_args,
post_args,
exec_in_dir,
verbose,
report_jnml_output,
exit_on_fail,
)
)
if post_args and "nogui" in post_args and not os.name == "nt":
pre_jar = " -Djava.awt.headless=true"
else:
pre_jar = ""
jar_path = pyneuroml.utils.misc.get_path_to_jnml_jar()
output = ""
retcode = -1
try:
command = f'java -Xmx{max_memory} {pre_jar} -jar "{jar_path}" {pre_args} {target_file} {post_args}'
retcode, output = execute_command_in_dir(
command, exec_in_dir, verbose=verbose, prefix=" jNeuroML >> "
)
if retcode != 0:
if exit_on_fail:
logger.error("execute_command_in_dir returned with output: %s" % output)
sys.exit(retcode)
else:
if return_string:
return (False, output)
else:
return False
if report_jnml_output:
logger.debug(
"Successfully ran the following command using pyNeuroML v%s: \n %s"
% (__version__, command)
)
logger.debug("Output:\n\n%s" % output)
# except KeyboardInterrupt as e:
# raise e
except Exception as e:
logger.error("*** Execution of jnml has failed! ***")
logger.error("Error: %s" % e)
logger.error("*** Command: %s ***" % command)
logger.error("Output: %s" % output)
if exit_on_fail:
sys.exit(UNKNOWN_ERR)
else:
if return_string:
return (False, output)
else:
return False
if return_string:
return (True, output)
else:
return True
# TODO: Refactorinng
def run_jneuroml_with_realtime_output(
pre_args: str,
target_file: str,
post_args: str,
max_memory: str = DEFAULTS["default_java_max_memory"],
exec_in_dir: str = ".",
verbose: bool = DEFAULTS["v"],
exit_on_fail: bool = True,
) -> bool:
# XXX: Only tested with Linux
"""Run jnml with provided arguments with realtime output.
NOTE: this has only been tested on Linux.
:param pre_args: pre-file name arguments
:type pre_args: list of strings
:param target_file: LEMS or NeuroML file to run jnml on
:type target_file: str
:param max_memory: maximum memory allowed for use by the JVM
:type max_memory: bool
:param exec_in_dir: working directory to execute LEMS simulation in
:type exec_in_dir: str
:param verbose: toggle whether jnml should print verbose information
:type verbose: bool
:param exit_on_fail: toggle whether command should exit if jnml fails
:type exit_on_fail: bool
"""
if post_args and "nogui" in post_args and not os.name == "nt":
pre_jar = " -Djava.awt.headless=true"
else:
pre_jar = ""
jar_path = pyneuroml.utils.misc.get_path_to_jnml_jar()
command = ""
command_success = False
try:
command = 'java -Xmx%s %s -jar "%s" %s "%s" %s' % (
max_memory,
pre_jar,
jar_path,
pre_args,
target_file,
post_args,
)
command_success = execute_command_in_dir_with_realtime_output(
command, exec_in_dir, verbose=verbose, prefix=" jNeuroML >> "
)
except KeyboardInterrupt as e:
raise e
except:
logger.error("*** Execution of jnml has failed! ***")
logger.error("*** Command: %s ***" % command)
if exit_on_fail:
sys.exit(UNKNOWN_ERR)
else:
return False
return command_success
def execute_command_in_dir_with_realtime_output(
command: str,
directory: str,
verbose: bool = DEFAULTS["v"],
prefix: str = "Output: ",
env: typing.Optional[str] = None,
) -> bool:
# NOTE: Only tested with Linux
"""Run a command in a given directory with real time output.
NOTE: this has only been tested on Linux.
:param command: command to run
:type command: str
:param directory: directory to run command in
:type directory: str
:param verbose: toggle verbose output
:type verbose: bool
:param prefix: string to prefix output with
:type prefix: str
:param env: environment variables to be used
:type env: str
"""
if os.name == "nt":
directory = os.path.normpath(directory)
print("####################################################################")
print("# pyNeuroML executing: (%s) in directory: %s" % (command, directory))
if env is not None:
print("# Extra env variables %s" % (env))
print("####################################################################")
p = None
try:
p = subprocess.Popen(
shlex.split(command),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
cwd=directory,
env=env,
universal_newlines=True,
)
with p.stdout:
for line in iter(p.stdout.readline, ""):
print("# %s" % line.strip())
p.wait() # wait for the subprocess to exit
print("####################################################################")
except KeyboardInterrupt as e:
logger.error("*** Command interrupted: \n %s" % command)
if p:
p.kill()
raise e
except Exception as e:
print("# Exception occured: %s" % (e))
print("# More...")
print(traceback.format_exc())
print("####################################################################")
raise e
if not p.returncode == 0:
logger.critical(
"*** Problem running command (return code: %s): \n %s"
% (p.returncode, command)
)
return p.returncode == 0
def execute_command_in_dir(
command: str,
directory: str,
verbose: bool = DEFAULTS["v"],
prefix: str = "Output: ",
env: Optional[typing.Mapping] = None,
) -> typing.Tuple[int, str]:
"""Execute a command in specific working directory
:param command: command to run
:type command: str
:param directory: directory to run command in
:type directory: str
:param verbose: toggle verbose output
:type verbose: bool
:param prefix: string to prefix console output with
:type prefix: str
:param env: environment variables to be used
:type env: Mapping
"""
return_string = "" # type: typing.Union[bytes, str]
if os.name == "nt":
directory = os.path.normpath(directory)
logger.info("Executing: (%s) in directory: %s" % (command, directory))
if env is not None:
logger.debug("Extra env variables %s" % (env))
try:
if os.name == "nt":
return_string = subprocess.check_output(
command, cwd=directory, shell=True, env=env, close_fds=False
)
else:
return_string = subprocess.check_output(
command,
cwd=directory,
shell=True,
stderr=subprocess.STDOUT,
env=env,
close_fds=True,
)
return_string = return_string.decode("utf-8") # For Python 3
logger.info("Command completed successfully!")
if verbose:
logger.info(
"Output: \n %s%s"
% (prefix, return_string.replace("\n", "\n " + prefix))
)
return (0, return_string)
except AttributeError:
# For python 2.6...
logger.warning("Assuming Python 2.6...")
return_string = subprocess.Popen(
command, cwd=directory, shell=True, stdout=subprocess.PIPE
).communicate()[0]
return return_string.decode("utf-8")
except subprocess.CalledProcessError as e:
logger.critical("*** Problem running command: \n %s" % e)
logger.critical(
"%s%s" % (prefix, e.output.decode().replace("\n", "\n" + prefix))
)
return (e.returncode, e.output.decode())
except Exception as e:
logger.critical("*** Unknown problem running command: %s" % e)