-
Notifications
You must be signed in to change notification settings - Fork 30
/
pynml.py
2792 lines (2382 loc) · 91.7 KB
/
pynml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Python wrapper around jnml command.
Also a number of helper functions for
handling/generating/running LEMS/NeuroML2 files
Thanks to Werner van Geit for an initial version of a python wrapper for jnml.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
# py3.7, 3.8 require this to use standard collections as generics
from __future__ import annotations
import warnings
import os
import shutil
import sys
import subprocess
import math
from datetime import datetime
import textwrap
import random
import inspect
import zipfile
import shlex
from lxml import etree
import pprint
import logging
import tempfile
import typing
import traceback
import lems.model.model as lems_model
import lems
from lems.parser.LEMS import LEMSFileParser
from pyneuroml import __version__
from pyneuroml import JNEUROML_VERSION
import neuroml
from neuroml import NeuroMLDocument, Cell
import neuroml.loaders as loaders
import neuroml.writers as writers
# to maintain API compatibility:
# so that existing scripts that use: from pynml import generate_plot
# continue to work
from pyneuroml.plot import generate_plot, generate_interactive_plot # noqa
DEFAULTS = {
"v": False,
"default_java_max_memory": "400M",
"nogui": False,
} # type: dict[str, typing.Any]
lems_model_with_units = None
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
version_string = "pyNeuroML v{} (libNeuroML v{}, jNeuroML v{})".format(
__version__, neuroml.__version__, JNEUROML_VERSION
)
FILE_NOT_FOUND_ERR = 13
ARGUMENT_ERR = 14
UNKNOWN_ERR = 15
def parse_arguments():
"""Parse command line arguments"""
import argparse
try:
from neuromllite.GraphVizHandler import engines
engine_info = "\nAvailable engines: %s\n" % str(engines)
except Exception:
engine_info = ""
parser = argparse.ArgumentParser(
description="Python utilities for NeuroML2",
usage=(
"pynml [-h|--help] [<shared options>] "
"<one of the mutually-exclusive options>"
),
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument("-version", help="Print version and exit", action="store_true")
shared_options = parser.add_argument_group(
title="Shared options",
description=(
"These options can be added to any of the " "mutually-exclusive options"
),
)
shared_options.add_argument(
"-verbose",
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help="Verbose output (default: WARNING)",
)
shared_options.add_argument(
"-java_max_memory",
metavar="MAX",
default=DEFAULTS["default_java_max_memory"],
help=(
"Java memory for jNeuroML, e.g. 400M, 2G (used in\n"
"-Xmx argument to java)"
),
)
shared_options.add_argument(
"-nogui",
action="store_true",
default=DEFAULTS["nogui"],
help=("Suppress GUI,\n" "i.e. show no plots, just save results"),
)
shared_options.add_argument(
"input_files",
type=str,
nargs="*",
metavar="<LEMS/NeuroML 2 file(s)>",
help="LEMS/NeuroML 2 file(s) to process",
)
mut_exc_opts_grp = parser.add_argument_group(
title="Mutually-exclusive options",
description="Only one of these options can be selected",
)
mut_exc_opts = mut_exc_opts_grp.add_mutually_exclusive_group(
required=False
) # noqa: E501
mut_exc_opts.add_argument(
"-sedml",
action="store_true",
help=(
"(Via jNeuroML) Load a LEMS file, and convert\n"
"simulation settings (duration, dt, what to save)\n"
"to SED-ML format"
),
)
mut_exc_opts.add_argument(
"-neuron",
nargs=argparse.REMAINDER,
help=(
"(Via jNeuroML) Load a LEMS file, and convert it to\n"
"NEURON format.\n"
"The full format of the '-neuron' option is:\n"
"-neuron [-nogui] [-run] [-outputdir dir] <LEMS file>\n"
" -nogui\n"
" do not generate gtaphical elements in NEURON,\n"
" just run, save data, and quit\n"
" -run\n"
" compile NMODL files and run the main NEURON\n"
" hoc file (Linux only currently)\n"
" -outputdir <dir>\n"
" generate NEURON files in directory <dir>\n"
" <LEMS file>\n"
" the LEMS file to use"
),
)
mut_exc_opts.add_argument(
"-netpyne",
nargs=argparse.REMAINDER,
help=(
"(Via jNeuroML) Load a LEMS file, and convert it to\n"
"NetPyNE format.\n"
"The full format of the '-netpyne' option is:\n"
"-netpyne [-run] [-outputdir dir] [-np cores] <LEMS file>\n"
" -run\n"
" compile NMODL files and run the NetPyNE\n"
" simulation (Linux only currently)\n"
" -outputdir <dir>\n"
" generate NEURON files in directory <dir>\n"
" -np <cores>\n"
" number of cores to run with (if using MPI)\n"
" -json\n"
" generate network as NetPyNE JSON\n"
" <LEMS file>\n"
" the LEMS file to use"
),
)
mut_exc_opts.add_argument(
"-eden",
nargs=argparse.REMAINDER,
help=(
"Load a LEMS file, and generate a\n"
"Python script to load and execute it in EDEN"
),
)
mut_exc_opts.add_argument(
"-svg",
action="store_true",
help=(
"(Via jNeuroML) Convert NeuroML2 file (network & cells)\n"
"to SVG format view of 3D structure"
),
)
mut_exc_opts.add_argument(
"-png",
action="store_true",
help=(
"(Via jNeuroML) Convert NeuroML2 file (network & cells)\n"
"to PNG format view of 3D structure"
),
)
mut_exc_opts.add_argument(
"-dlems",
action="store_true",
help=(
"(Via jNeuroML) Load a LEMS file, and convert it\n"
"to dLEMS format, a distilled form of LEMS in JSON"
),
)
mut_exc_opts.add_argument(
"-vertex",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to VERTEX format"),
)
mut_exc_opts.add_argument(
"-xpp",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to XPPAUT format"),
)
mut_exc_opts.add_argument(
"-dnsim",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to DNsim format"),
)
mut_exc_opts.add_argument(
"-brian",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to Brian format"),
)
mut_exc_opts.add_argument(
"-brian2",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to Brian2 format"),
)
# TODO: add run_lems_with_jneuroml_moose API function
mut_exc_opts.add_argument(
"-moose",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to Moose format"),
)
mut_exc_opts.add_argument(
"-sbml",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to SBML format"),
)
mut_exc_opts.add_argument(
"-matlab",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to MATLAB format"),
)
mut_exc_opts.add_argument(
"-cvode",
action="store_true",
help=(
"(Via jNeuroML) Load a LEMS file, and convert it\n"
"to C format using CVODE package"
),
)
mut_exc_opts.add_argument(
"-nineml",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to NineML format"),
)
mut_exc_opts.add_argument(
"-spineml",
action="store_true",
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to SpineML format"),
)
mut_exc_opts.add_argument(
"-sbml-import",
metavar=("<SBML file>", "duration", "dt"),
nargs=3,
help=(
"(Via jNeuroML) Load a SBML file, and convert it\n"
"toLEMS format using values for duration & dt\n"
"in ms (ignoring SBML units)"
),
)
mut_exc_opts.add_argument(
"-sbml-import-units",
metavar=("<SBML file>", "duration", "dt"),
nargs=3,
help=(
"(Via jNeuroML) Load a SBML file, and convert it\n"
"to LEMS format using values for duration & dt\n"
"in ms (attempt to extract SBML units; ensure units\n"
"are valid in the SBML!)"
),
)
mut_exc_opts.add_argument(
"-vhdl",
metavar=("neuronid", "<LEMS file>"),
nargs=2,
help=("(Via jNeuroML) Load a LEMS file, and convert it\n" "to VHDL format"),
)
mut_exc_opts.add_argument(
"-graph",
metavar=("level"),
nargs=1,
help=(
"Load a NeuroML file, and convert it to a graph using GraphViz.\n"
"Detail is set by level (min20..0..20, where min implies negative)\n"
"An optional single letter suffix can be used to select engine\n"
"Example: 1d for level 1, using the dot engine" + engine_info
),
)
mut_exc_opts.add_argument(
"-lems-graph",
action="store_true",
help=(
"(Via jNeuroML) Load LEMS file, and convert it to a \n"
"graph using GraphViz."
),
)
mut_exc_opts.add_argument(
"-matrix",
metavar=("level"),
nargs=1,
help=(
"Load a NeuroML file, and convert it to a matrix displaying\n" # noqa: E501
"connectivity. Detail is set by level (1, 2, etc.)"
),
)
mut_exc_opts.add_argument(
"-validate",
action="store_true",
help=("(Via jNeuroML) Validate NeuroML2 file(s) against the\n" "latest Schema"),
)
mut_exc_opts.add_argument(
"-validatev1",
action="store_true",
help=("(Via jNeuroML) Validate NeuroML file(s) against the\n" "v1.8.1 Schema"),
)
return parser.parse_args()
def get_lems_model_with_units() -> lems_model.Model:
"""
Get a LEMS model with NeuroML core dimensions and units.
:returns: a `lems.model.model.Model` that includes NeuroML dimensions and units.
"""
global lems_model_with_units
if lems_model_with_units is None:
jar_path = get_path_to_jnml_jar()
logger.debug(
"Loading standard NeuroML2 dimension/unit definitions from %s" % jar_path
)
jar = zipfile.ZipFile(jar_path, "r")
dims_units = jar.read("NeuroML2CoreTypes/NeuroMLCoreDimensions.xml")
lems_model_with_units = lems_model.Model(include_includes=False)
parser = LEMSFileParser(lems_model_with_units)
parser.parse(dims_units)
return lems_model_with_units
def extract_lems_definition_files(
path: typing.Union[str, None, tempfile.TemporaryDirectory] = None
) -> str:
"""Extract the NeuroML2 LEMS definition files to a directory and return its path.
This function can be used by other LEMS related functions that need to
include the NeuroML2 LEMS definitions.
If a path is provided, the folder is created relative to the current
working directory.
If no path is provided, for repeated usage for example, the files are
extracted to a temporary directory using Python's
`tempfile.mkdtemp
<https://docs.python.org/3/library/tempfile.html>`__ function.
Note: in both cases, it is the user's responsibility to remove the created
directory when it is no longer required, for example using. the
`shutil.rmtree()` Python function.
:param path: path of directory relative to current working directory to extract to, or None
:type path: str or None
:returns: directory path
"""
jar_path = get_path_to_jnml_jar()
logger.debug(
"Loading standard NeuroML2 dimension/unit definitions from %s" % jar_path
)
jar = zipfile.ZipFile(jar_path, "r")
namelist = [x for x in jar.namelist() if ".xml" in x and "NeuroML2CoreTypes" in x]
logger.debug("NeuroML LEMS definition files in jar are: {}".format(namelist))
# If a string is provided, ensure that it is relative to cwd
if path and isinstance(path, str) and len(path) > 0:
path = "./" + path
try:
os.makedirs(path)
except FileExistsError:
logger.warning(
"{} already exists. Any NeuroML LEMS files in it will be overwritten".format(
path
)
)
except OSError as err:
logger.critical(err)
sys.exit(UNKNOWN_ERR)
else:
path = tempfile.mkdtemp()
logger.debug("Created directory: " + path)
jar.extractall(path, namelist)
path = path + "/NeuroML2CoreTypes/"
logger.info("NeuroML LEMS definition files extracted to: {}".format(path))
return path
def list_exposures(
nml_doc_fn: str, substring: str = ""
) -> typing.Union[
dict[lems.model.component.Component, list[lems.model.component.Exposure]],
None,
]:
"""List exposures in a NeuroML model document file.
This wraps around `lems.model.list_exposures` to list the exposures in a
NeuroML2 model. The only difference between the two is that the
`lems.model.list_exposures` function is not aware of the NeuroML2 component
types (since it's for any LEMS models in general), but this one is.
:param nml_doc_fn: NeuroML2 file to list exposures for
:type nml_doc: str
:param substring: substring to match for in component names
:type substring: str
:returns: dictionary of components and their exposures.
The returned dictionary is of the form:
..
{
"component": ["exp1", "exp2"]
}
"""
return get_standalone_lems_model(nml_doc_fn).list_exposures(substring)
def list_recording_paths_for_exposures(
nml_doc_fn: str, substring: str = "", target: str = ""
) -> list[str]:
"""List the recording path strings for exposures.
This wraps around `lems.model.list_recording_paths` to list the recording
paths in the given NeuroML2 model. The only difference between the two is
that the `lems.model.list_recording_paths` function is not aware of the
NeuroML2 component types (since it's for any LEMS models in general), but
this one is.
:param nml_doc_fn: NeuroML2 file to list recording paths for
:type nml_doc: str
:param substring: substring to match component ids against
:type substring: str
:returns: list of recording paths
"""
return get_standalone_lems_model(nml_doc_fn).list_recording_paths_for_exposures(
substring, target
)
def get_standalone_lems_model(nml_doc_fn: str) -> lems_model.Model:
"""Get the complete, expanded LEMS model.
This function takes a NeuroML2 file, includes all the NeuroML2 LEMS
definitions in it and generates the complete, standalone LEMS model.
:param nml_doc_fn: name of NeuroML file to expand
:type nml_doc_fn: str
:returns: complete LEMS model
"""
new_lems_model = lems_model.Model(
include_includes=True, fail_on_missing_includes=True
)
if logger.level < logging.INFO:
new_lems_model.debug = True
else:
new_lems_model.debug = False
neuroml2_defs_dir = extract_lems_definition_files()
filelist = os.listdir(neuroml2_defs_dir)
# Remove the temporary directory
for nml_lems_f in filelist:
new_lems_model.include_file(neuroml2_defs_dir + nml_lems_f, [neuroml2_defs_dir])
new_lems_model.include_file(nml_doc_fn, [""])
shutil.rmtree(neuroml2_defs_dir[: -1 * len("NeuroML2CoreTypes/")])
return new_lems_model
def split_nml2_quantity(nml2_quantity: str) -> tuple[float, str]:
"""Split a NeuroML 2 quantity into its magnitude and units
:param nml2_quantity: NeuroML2 quantity to split
:type nml2_quantity:
:returns: a tuple (magnitude, unit)
"""
magnitude = None
i = len(nml2_quantity)
while magnitude is None:
try:
part = nml2_quantity[0:i]
nn = float(part)
magnitude = nn
unit = nml2_quantity[i:]
except ValueError:
i = i - 1
return magnitude, unit
def get_value_in_si(nml2_quantity: str) -> typing.Union[float, None]:
"""Get value of a NeuroML2 quantity in SI units
:param nml2_quantity: NeuroML2 quantity to convert
:type nml2_quantity: str
:returns: value in SI units (float)
"""
try:
return float(nml2_quantity)
except ValueError:
model = get_lems_model_with_units()
m, u = split_nml2_quantity(nml2_quantity)
si_value = None
for un in model.units:
if un.symbol == u:
si_value = (m + un.offset) * un.scale * pow(10, un.power)
return si_value
def convert_to_units(nml2_quantity: str, unit: str) -> float:
"""Convert a NeuroML2 quantity to provided unit.
:param nml2_quantity: NeuroML2 quantity to convert
:type nml2_quantity: str
:param unit: unit to convert to
:type unit: str
:returns: converted value (float)
"""
model = get_lems_model_with_units()
m, u = split_nml2_quantity(nml2_quantity)
si_value = None
dim = None
for un in model.units:
if un.symbol == u:
si_value = (m + un.offset) * un.scale * pow(10, un.power)
dim = un.dimension
for un in model.units:
if un.symbol == unit:
new_value = si_value / (un.scale * pow(10, un.power)) - un.offset
if not un.dimension == dim:
raise Exception(
"Cannot convert {} to {}. Dimensions of units ({}/{}) do not match!".format(
nml2_quantity, unit, dim, un.dimension
)
)
logger.debug(
"Converting {} {} to {}: {} ({} in SI units)".format(
m, u, unit, new_value, si_value
)
)
return new_value
def generate_nmlgraph(nml2_file_name: str, level: int = 1, engine: str = "dot") -> None:
"""Generate NeuroML graph.
:nml2_file_name (string): NML file to parse
:level (string): level of graph to generate (default: '1')
:engine (string): graph engine to use (default: 'dot')
"""
from neuromllite.GraphVizHandler import GraphVizHandler
from neuroml.hdf5.NeuroMLXMLParser import NeuroMLXMLParser
logger.info(
"Converting %s to graphical form, level %i, engine %s"
% (nml2_file_name, level, engine)
)
handler = GraphVizHandler(level=level, engine=engine, nl_network=None)
currParser = NeuroMLXMLParser(handler)
currParser.parse(nml2_file_name)
handler.finalise_document()
logger.info("Done with GraphViz...")
def generate_lemsgraph(lems_file_name: str, verbose_generate: bool = True) -> bool:
"""Generate LEMS graph using jNeuroML
:param lems_file_name: LEMS file to parse
:type lems_file_name: str
:param verbose_generate: whether or not jnml should be run with verbosity output
:type verbose_generate: bool
:returns bool: True of jnml ran without errors, exits without a return if jnml fails
"""
pre_args = ""
post_args = "-lems-graph"
return run_jneuroml(
pre_args,
lems_file_name,
post_args,
verbose=verbose_generate,
report_jnml_output=verbose_generate,
exit_on_fail=True,
return_string=False,
)
def validate_neuroml1(
nml1_file_name: str, verbose_validate: bool = True, return_string: bool = False
) -> typing.Union[bool, tuple[bool, str]]:
"""Validate a NeuroML v1 file.
NOTE: NeuroML v1 is deprecated. Please use NeuroML v2.
This functionality will be dropped in the future.
:param nml1_file_name: name of NeuroMLv1 file to validate
:type nml1_file_name: str
:param verbose_validate: whether jnml should print verbose information while validating
:type verbose_validate: bool (default: True)
:param return_string: toggle to enable or disable returning the output of the jnml validation
:type return_string: bool
:returns: Either a bool, or a tuple (bool, str): True if jnml ran without errors, false if jnml fails; along with the message returned by jnml
"""
logger.info("NOTE: NeuroMLv1 is deprecated. Please use NeuroMLv2.")
pre_args = "-validatev1"
post_args = ""
warnings.warn(
"Please note that NeuroMLv1 is deprecated. Functions supporting NeuroMLv1 will be removed in the future. Please use NeuroMLv2.",
FutureWarning,
stacklevel=2,
)
return run_jneuroml(
pre_args,
nml1_file_name,
post_args,
verbose=verbose_validate,
report_jnml_output=verbose_validate,
exit_on_fail=False,
return_string=return_string,
)
def validate_neuroml2(
nml2_file_name: str,
verbose_validate: bool = True,
max_memory: typing.Optional[str] = None,
return_string: bool = False,
) -> typing.Union[bool, tuple[bool, str]]:
"""Validate a NeuroML2 file using jnml.
:params nml2_file_name: name of NeuroML 2 file to validate
:type nml2_file_name: str
:param verbose_validate: whether jnml should print verbose information while validating
:type verbose_validate: bool (default: True)
:param max_memory: maximum memory the JVM should use while running jnml
:type max_memory: str
:param return_string: toggle to enable or disable returning the output of the jnml validation
:type return_string: bool
:returns: Either a bool, or a tuple (bool, str): True if jnml ran without errors, false if jnml fails; along with the message returned by jnml
"""
pre_args = "-validate"
post_args = ""
if max_memory is not None:
return run_jneuroml(
pre_args,
nml2_file_name,
post_args,
max_memory=max_memory,
verbose=verbose_validate,
report_jnml_output=verbose_validate,
exit_on_fail=False,
return_string=return_string,
)
else:
return run_jneuroml(
pre_args,
nml2_file_name,
post_args,
verbose=verbose_validate,
report_jnml_output=verbose_validate,
exit_on_fail=False,
return_string=return_string,
)
def validate_neuroml2_lems_file(
nml2_lems_file_name: str, max_memory: str = DEFAULTS["default_java_max_memory"]
) -> bool:
"""Validate a NeuroML 2 LEMS file using jNeuroML.
Note that this uses jNeuroML and so is aware of the standard NeuroML LEMS
definitions.
TODO: allow inclusion of other paths for user-defined LEMS definitions
(does the -norun option allow the use of -I?)
:param nml2_lems_file_name: name of file to validate
:type nml2_lems_file_name: str
:param max_memory: memory to use for the Java virtual machine
:type max_memory: str
:returns: True if valid, False if invalid
"""
post_args = ""
post_args += "-norun"
return run_jneuroml(
"",
nml2_lems_file_name,
post_args,
max_memory=max_memory,
verbose=False,
report_jnml_output=True,
exit_on_fail=True,
)
def read_neuroml2_file(
nml2_file_name: str,
include_includes: bool = False,
verbose: bool = False,
already_included: list = None,
optimized: bool = False,
check_validity_pre_include: bool = False,
) -> NeuroMLDocument:
"""Read a NeuroML2 file into a `nml.NeuroMLDocument`
:param nml2_file_name: file of NeuroML 2 file to read
:type nml2_file_name: str
:param include_includes: toggle whether files included in NML file should also be included/read
:type include_includes: bool
:param verbose: toggle verbosity
:type verbose: bool
:param already_included: list of files already included
:type already_included: list
:param optimized: toggle whether the HDF5 loader should optimise the document
:type optimized: bool
:param check_validity_pre_include: check each file for validity before including
:type check_validity_pre_include: bool
:returns: nml.NeuroMLDocument object containing the read NeuroML file(s)
"""
if already_included is None:
already_included = []
logger.info("Loading NeuroML2 file: %s" % nml2_file_name)
if not os.path.isfile(nml2_file_name):
logger.critical("Unable to find file: %s!" % nml2_file_name)
sys.exit(FILE_NOT_FOUND_ERR)
if nml2_file_name.endswith(".h5") or nml2_file_name.endswith(".hdf5"):
nml2_doc = loaders.NeuroMLHdf5Loader.load(nml2_file_name, optimized=optimized)
else:
nml2_doc = loaders.NeuroMLLoader.load(nml2_file_name)
base_path = os.path.dirname(os.path.realpath(nml2_file_name))
if include_includes:
if verbose:
logger.info(
"Including included files (included already: {})".format(
already_included
)
)
incl_to_remove = []
for include in nml2_doc.includes:
incl_loc = os.path.abspath(os.path.join(base_path, include.href))
if incl_loc not in already_included:
inc = True # type: typing.Union[bool, tuple[bool, str]]
if check_validity_pre_include:
inc = validate_neuroml2(incl_loc, verbose_validate=False)
if inc:
logger.debug(
"Loading included NeuroML2 file: {} (base: {}, resolved: {}, checking {})".format(
include.href,
base_path,
incl_loc,
check_validity_pre_include,
)
)
nml2_sub_doc = read_neuroml2_file(
incl_loc,
True,
verbose=verbose,
already_included=already_included,
check_validity_pre_include=check_validity_pre_include,
)
if incl_loc not in already_included:
already_included.append(incl_loc)
membs = inspect.getmembers(nml2_sub_doc)
for memb in membs:
if (
isinstance(memb[1], list)
and len(memb[1]) > 0
and not memb[0].endswith("_")
):
for entry in memb[1]:
if memb[0] != "includes":
logger.debug(
" Adding {!s} from: {!s} to list: {}".format(
entry, incl_loc, memb[0]
)
)
getattr(nml2_doc, memb[0]).append(entry)
incl_to_remove.append(include)
else:
logger.warning("Not including file as it's not valid...")
for include in incl_to_remove:
nml2_doc.includes.remove(include)
return nml2_doc
def quick_summary(nml2_doc: NeuroMLDocument) -> str:
"""Get a quick summary of the NeuroML2 document
NOTE: You should prefer nml2_doc.summary(show_includes=False)
:param nml2_doc: NeuroMLDocument to fetch summary for
:type nml2_doc: NeuroMLDocument
:returns: summary string
"""
info = "Contents of NeuroML 2 document: {}\n".format(nml2_doc.id)
membs = inspect.getmembers(nml2_doc)
for memb in membs:
if isinstance(memb[1], list) and len(memb[1]) > 0 and not memb[0].endswith("_"):
info += " {}:\n [".format(memb[0])
for entry in memb[1]:
extra = "???"
extra = entry.name if hasattr(entry, "name") else extra
extra = entry.href if hasattr(entry, "href") else extra
extra = entry.id if hasattr(entry, "id") else extra
info += " {} ({}),".format(entry, extra)
info += "]\n"
return info
def summary(
nml2_doc: typing.Optional[NeuroMLDocument] = None, verbose: bool = False
) -> None:
"""Wrapper around nml_doc.summary() to generate the pynml-summary command
line tool.
:param nml2_doc: NeuroMLDocument object or name of NeuroML v2 file to get summary for.
:type nml2_doc: NeuroMLDocument
:param verbose: toggle verbosity
:type verbose: bool
"""
usage = textwrap.dedent(
"""
Usage:
pynml-summary <NeuroML file> [-vh]
Required arguments:
NeuroML file: name of file to summarise
Optional arguments:
-v/--verbose: enable verbose mode
-h/--help: print this help text and exit
"""
)
if len(sys.argv) < 2:
print("Argument required.")
print(usage)
return
if "-h" in sys.argv or "--help" in sys.argv:
print(usage)
return
if "-v" in sys.argv or "--verbose" in sys.argv:
verbose = True
sys.argv.remove("-v")
if nml2_doc is None:
nml2_file_name = sys.argv[1]
nml2_doc = read_neuroml2_file(nml2_file_name, include_includes=verbose)
info = nml2_doc.summary(show_includes=False)
if verbose:
cell_info_str = ""
for cell in nml2_doc.cells:
cell_info_str += cell_info(cell) + "*\n"
lines = info.split("\n")
info = ""
still_to_add = False
for line in lines:
if "Cell: " in line:
still_to_add = True
pass
elif "Network: " in line:
still_to_add = False
if len(cell_info_str) > 0:
info += "%s" % cell_info_str
info += "%s\n" % line
else:
if still_to_add and "******" in line:
if len(cell_info_str) > 0:
info += "%s" % cell_info_str
info += "%s\n" % line
print(info)
def cells_info(nml_file_name: str) -> str:
"""Provide information about the cells in a NeuroML file.
:param nml_file_name: name of NeuroML v2 file
:type nml_file_name: str
:returns: information on cells (str)
"""
from neuroml.loaders import read_neuroml2_file
nml_doc = read_neuroml2_file(
nml_file_name, include_includes=True, verbose=False, optimized=True
)
info = ""
info += "Extracting information on %i cells in %s" % (
len(nml_doc.cells),
nml_file_name,
)
for cell in nml_doc.cells:
info += cell_info(cell)
return info
def cell_info(cell: Cell) -> str:
"""Provide information on a NeuroML Cell instance:
- morphological information:
- Segment information:
- parent segments
- segment location, extents, diameter
- segment length
- segment surface area
- segment volume
- Segment group information:
- included segments
- biophysical properties:
- channel densities
- specific capacitances
:param cell: cell object to investigate
:type cell: Cell
:returns: string of cell information
"""
info = ""
prefix = "* "
info += prefix + "Cell: %s\n" % cell.id
tot_length = 0
tot_area = 0