Skip to content

Commit 63cf16a

Browse files
committed
fix(annotations): ensure rdf tags are single line
Needs etree to do this. We're working around jLEMS not being able to manage multi-line tags: LEMS/jLEMS#127
1 parent cb65fa0 commit 63cf16a

File tree

1 file changed

+41
-11
lines changed

1 file changed

+41
-11
lines changed

pyneuroml/annotations.py

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -227,10 +227,14 @@ def create_annotation(
227227
228228
See: https://rdflib.readthedocs.io/en/stable/plugin_serializers.html
229229
230+
Note that for xml formats, the xml is finally parsed through
231+
lxml.etree to ensure compatibility with the rest of the
232+
NeuroML/LEMS tool chain.
233+
230234
:type serialization_format: str
231235
:param xml_header: toggle inclusion of xml header if serializing in xml format
232236
:type xml_header: bool
233-
:param indent: number of spaces to use to indent the annotation block
237+
:param indent: number of spaces to use to indent the annotation block for xml
234238
:type indent: int
235239
:param description: a longer description
236240
:type description: str
@@ -371,10 +375,6 @@ def create_annotation(
371375

372376
annotation = self.doc.serialize(format=serialization_format)
373377

374-
# indent
375-
if indent > 0:
376-
annotation = textwrap.indent(annotation, " " * indent)
377-
378378
# xml issues
379379
if "xml" in serialization_format:
380380
# replace rdf:_1 etc with rdf:li
@@ -388,14 +388,44 @@ def create_annotation(
388388
annotation = rdfbnode_pattern.sub("", annotation)
389389

390390
# remove xml header, not used when embedding into other NeuroML files
391-
if xml_header is False:
392-
annotation = annotation[annotation.find(">") + 1 :]
391+
# etree doesn't like it either for unicode strings
392+
annotation = annotation[annotation.find(">") + 1 :]
393+
394+
# put all the namespaces on one line
395+
# jlems doesn't like multi-line tags
396+
# https://github.com/LEMS/jLEMS/issues/127
397+
annotation_etree = etree.fromstring(annotation)
398+
399+
annotation_str = etree.tostring(
400+
annotation_etree,
401+
pretty_print=True,
402+
encoding="unicode",
403+
xml_declaration=xml_header,
404+
)
405+
406+
if write_to_file:
407+
with open(write_to_file, "w") as f:
408+
annotation_etree.write(
409+
f,
410+
encoding="unicode",
411+
xml_declaration=xml_header,
412+
pretty_print=True,
413+
)
414+
415+
# indent
416+
if indent > 0:
417+
annotation_str = textwrap.indent(annotation_str, " " * indent)
418+
419+
return annotation_str
420+
421+
else:
422+
annotation = self.doc.serialize(format=serialization_format)
393423

394-
if write_to_file:
395-
with open(write_to_file, "w") as f:
396-
print(annotation, file=f)
424+
if write_to_file:
425+
with open(write_to_file, "w") as f:
426+
print(annotation, file=f)
397427

398-
return annotation
428+
return annotation
399429

400430
def _add_element(
401431
self,

0 commit comments

Comments
 (0)