-
Notifications
You must be signed in to change notification settings - Fork 30
/
io.py
268 lines (223 loc) · 9.25 KB
/
io.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
#!/usr/bin/env python3
"""
Methods related to IO.
File: pyneuroml/io.py
Copyright 2024 NeuroML contributors
"""
import inspect
import logging
import os
import sys
import textwrap
import typing
from typing import Optional
import neuroml.loaders as loaders
import neuroml.writers as writers
from neuroml import NeuroMLDocument
import lems.model.model as lems_model
from pyneuroml.errors import FILE_NOT_FOUND_ERR
from pyneuroml.validators import validate_neuroml2
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def read_neuroml2_file(
nml2_file_name: str,
include_includes: bool = False,
verbose: bool = False,
already_included: Optional[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, typing.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 write_neuroml2_file(
nml2_doc: NeuroMLDocument,
nml2_file_name: str,
validate: bool = True,
verbose_validate: bool = False,
hdf5: bool = False,
) -> typing.Optional[typing.Union[bool, typing.Tuple[bool, str]]]:
"""Write a NeuroMLDocument object to a file using libNeuroML.
:param nml2_doc: NeuroMLDocument object to write to file
:type nml2_doc: NeuroMLDocument
:param nml2_file_name: name of file to write to
:type nml2_file_name: str
:param validate: toggle whether the written file should be validated
:type validate: bool
:param verbose_validate: toggle whether the validation should be verbose
:type verbose_validate: bool
:param hdf5: write to HDF5 file
:type hdf5: bool
"""
if hdf5 is True:
writers.NeuroMLHdf5Writer.write(nml2_doc, nml2_file_name)
else:
writers.NeuroMLWriter.write(nml2_doc, nml2_file_name)
if validate:
return validate_neuroml2(nml2_file_name, verbose_validate)
return None
def read_lems_file(
lems_file_name: str,
include_includes: bool = False,
fail_on_missing_includes: bool = False,
debug: bool = False,
) -> lems_model.Model:
"""Read LEMS file using PyLEMS. See WARNING below.
WARNING: this is a general function that uses PyLEMS to read any files that
are valid LEMS *even if they are not valid NeuroML*. Therefore, this
function is not aware of the standard NeuroML LEMS definitions.
To validate NeuroML LEMS files which need to be aware of the NeuroML
standard LEMS definitions, please use the `validate_neuroml2_lems_file`
function instead.
"""
if not os.path.isfile(lems_file_name):
logger.critical("Unable to find file: %s!" % lems_file_name)
sys.exit(FILE_NOT_FOUND_ERR)
model = lems_model.Model(
include_includes=include_includes,
fail_on_missing_includes=fail_on_missing_includes,
)
model.debug = debug
model.import_from_file(lems_file_name)
return model
def write_lems_file(
lems_model: lems_model.Model, lems_file_name: str, validate: bool = False
) -> None:
"""Write a lems_model.Model to file using pyLEMS.
:param lems_model: LEMS model to write to file
:type lems_model: lems_model.Model
:param lems_file_name: name of file to write to
:type lems_file_name: str
:param validate: toggle whether written file should be validated
:type validate: bool
"""
lems_model.export_to_file(lems_file_name)
if validate:
from lems.base.util import validate_lems
validate_lems(lems_file_name)
def confirm_file_exists(filename: str) -> None:
"""Check if a file exists, exit if it does not.
:param filename: the filename to check
:type filename: str
"""
if not os.path.isfile(filename):
logger.critical("Unable to find file: %s!" % filename)
sys.exit(FILE_NOT_FOUND_ERR)
def confirm_neuroml_file(filename: str) -> None:
"""Confirm that file exists and is a NeuroML file before proceeding with
processing.
:param filename: Names of files to check
:type filename: str
"""
# print('Checking file: %s'%filename)
# Some conditions to check if a LEMS file was entered
# TODO: Ideally we'd like to check the root node: checking file extensions is brittle
confirm_file_exists(filename)
if filename.startswith("LEMS_"):
logger.warning(
textwrap.dedent(
"""
*************************************************************************************
** Warning, you may be trying to use a LEMS XML file (containing <Simulation> etc.)
** for a pyNeuroML option when a NeuroML2 file is required...
*************************************************************************************
"""
)
)
def confirm_lems_file(filename: str) -> None:
"""Confirm that file exists and is a LEMS file before proceeding with
processing.
:param filename: Names of files to check
:type filename: list of strings
"""
# print('Checking file: %s'%filename)
# Some conditions to check if a LEMS file was entered
# TODO: Ideally we'd like to check the root node: checking file extensions is brittle
confirm_file_exists(filename)
if filename.endswith("nml"):
logger.warning(
textwrap.dedent(
"""
*************************************************************************************
** Warning, you may be trying to use a NeuroML2 file for a pyNeuroML option
** when a LEMS XML file (containing <Simulation> etc.) is required...
*************************************************************************************
"""
)
)