neuroml

adapters.neuroml

NeuroML/LEMS adapter for SimulationExperiment.

Renders a self-contained LEMS XML simulation file from any TVBO SimulationExperiment using a Mako template. Every Dynamics model is exported as a custom LEMS ComponentType — no hardcoded mappings to built-in NeuroML cell types.

Validation is done via PyLEMS (lems.Model). Simulation can be run via pyNeuroML (jnml).

Classes

Name Description
NeuroMLAdapter Adapter for exporting a SimulationExperiment (or bare Dynamics) as LEMS XML.

NeuroMLAdapter

adapters.neuroml.NeuroMLAdapter(source=None)

Adapter for exporting a SimulationExperiment (or bare Dynamics) as LEMS XML.

Supports both a single monolithic file and a canonical three-file split:

  • render_dynamics() → standalone ComponentType definitions
  • render_network() → Network component (may include a dynamics file)
  • render_simulation() → LEMS Simulation block (may include a network file)
  • render_code() → monolithic all-in-one LEMS file (default)
  • render_neuroml() → NeuroML v2 document (<neuroml> root)
  • render_lems_wrapper() → LEMS wrapper for a NeuroML file
  • export(dir) → write file(s) to disk, optionally validate

render('lems') produces a self-contained <Lems> file. render('neuroml') produces a <neuroml> document with custom ComponentType definitions — no mapping to native NeuroML cell types.

All render_* methods pass a fully pre-computed context via :func:build_lems_context so templates stay logic-free.

Methods

Name Description
export Export LEMS or NeuroML XML to a directory.
render_code Render a complete, self-contained LEMS simulation file (<Lems> root).
render_dynamics Render a standalone LEMS file with only ComponentType definitions.
render_lems_wrapper Render a LEMS simulation wrapper for a NeuroML file.
render_network Render a LEMS Network document.
render_neuroml Render a NeuroML v2 document (<neuroml> root).
render_simulation Render a LEMS Simulation document.
run Run the LEMS simulation via a downstream simulator.
validate Validate rendered LEMS XML with PyLEMS. Returns True or raises.
export
adapters.neuroml.NeuroMLAdapter.export(
    dir,
    format='lems',
    split=False,
    validate=True,
    **kwargs,
)

Export LEMS or NeuroML XML to a directory.

Parameters

dir : str or Path Output directory (created if needed). format : str 'lems' (default) — LEMS output (monolithic or split). 'neuroml' — NeuroML .nml document + LEMS simulation wrapper. split : bool Only used for format='lems'. False (default) — one monolithic {prefix}_simulation.xml. True — three canonical files:

* ``{prefix}_dynamics.xml``   — ComponentType definitions
* ``{prefix}_network.xml``    — Network (includes dynamics)
* ``{prefix}_simulation.xml`` — Simulation (includes network)

validate : bool Run PyLEMS validation on every written file (default True).

Returns

dict Mapping of role to absolute file paths.

render_code
adapters.neuroml.NeuroMLAdapter.render_code(use_standard_types=False, **kwargs)

Render a complete, self-contained LEMS simulation file (<Lems> root).

Parameters

use_standard_types : bool When True and the dynamics uses NeuroML standard types (iri: neuroml:*), emit standard components with <Include file="Cells.xml"/> etc. These includes are resolved by jNeuroML at runtime but NOT by the Python lems validator, so this should only be True when the output is destined for run().

render_dynamics
adapters.neuroml.NeuroMLAdapter.render_dynamics(**kwargs)

Render a standalone LEMS file with only ComponentType definitions.

The output is a valid LEMS document containing dimensions, units, the dynamics ComponentType, the Coupling ComponentType, and the default Component instances. No Network or Simulation elements are included, making it suitable for inclusion in larger LEMS documents via <Include file="..."/>.

render_lems_wrapper
adapters.neuroml.NeuroMLAdapter.render_lems_wrapper(neuroml_file=None, **kwargs)

Render a LEMS simulation wrapper for a NeuroML file.

The wrapper includes standard NeuroML type files and the given NeuroML document, then defines a <Simulation> targeting the network defined in the .nml file.

Parameters

neuroml_file : str or None Filename of the NeuroML document to include.

render_network
adapters.neuroml.NeuroMLAdapter.render_network(dynamics_file=None, **kwargs)

Render a LEMS Network document.

Parameters

dynamics_file : str or None If given, an <Include file="..."/> referencing that filename is prepended so the document can be used standalone.

render_neuroml
adapters.neuroml.NeuroMLAdapter.render_neuroml(**kwargs)

Render a NeuroML v2 document (<neuroml> root).

Uses custom <ComponentType> definitions for the dynamics model rather than mapping to native NeuroML cell types. The output contains ComponentType definitions, Component instances, and a <network> with populations.

To run the output, pair it with a LEMS simulation wrapper generated by :meth:render_lems_wrapper.

render_simulation
adapters.neuroml.NeuroMLAdapter.render_simulation(network_file=None, **kwargs)

Render a LEMS Simulation document.

Parameters

network_file : str or None If given, an <Include file="..."/> referencing that filename is prepended so the document can be used standalone.

run
adapters.neuroml.NeuroMLAdapter.run(backend='jneuroml', **kwargs)

Run the LEMS simulation via a downstream simulator.

Exports a self-contained monolithic LEMS file and executes it using one of the pyNeuroML runner functions.

Parameters

backend : str Which simulator to use. One of:

* ``'jneuroml'`` (default) — reference LEMS engine (Java)
* ``'neuron'``  — NEURON via jNeuroML
* ``'brian2'``  — Brian2 via jNeuroML
* ``'netpyne'`` — NetPyNE via jNeuroML
* ``'eden'``    — EDEN simulator

**kwargs Passed through to render_code() for template rendering.

Returns

ExperimentResult Simulation results loaded from output files.

Raises

ValueError If backend is not one of the supported names. RuntimeError If the downstream simulator fails.

validate
adapters.neuroml.NeuroMLAdapter.validate(xml_string=None)

Validate rendered LEMS XML with PyLEMS. Returns True or raises.

Standard NeuroML type outputs (<Include file="Cells.xml"/> etc.) cannot be validated by PyLEMS because the type definition files are bundled with jNeuroML, not PyLEMS. For those, validation is skipped here (jNeuroML validates them at runtime).

Functions

Name Description
build_lems_context Build the shared rendering context passed to all LEMS Mako templates.
build_std_lems_context Build a context dict for standard NeuroML-type Mako templates.
compare_traces Compare reference and TVBO traces, print metrics.
get_lems_examples_dir Return the path to the LEMSexamples directory in the NeuroML2 repo.
inline_model_functions Inline model-defined functions into a SymPy expression.
parse_lems_displays Parse Display + Line elements from a LEMS XML file.
parse_lems_output_columns Parse OutputFile → OutputColumn quantities from a LEMS file.
plot_comparison Plot overlaid traces: reference vs TVBO.
plot_lems_comparison Create publication-quality comparison plots mirroring LEMS Display layout.
run_lems_example Run a LEMS XML file via jNeuroML and return {filename: array} for each .dat output.
safe_id Make a string safe for XML id attribute.
sympy_to_lems Convert a TVBO equation RHS string (or SymPy expr) to LEMS syntax.
validate_lems_xml Validate a LEMS XML string using PyLEMS.

build_lems_context

adapters.neuroml.build_lems_context(experiment)

Build the shared rendering context passed to all LEMS Mako templates.

Extracts and pre-computes every variable that LEMS templates need — model objects, name lists for safe SymPy parsing, expression helpers, and integration/network scalars. All templates receive this dict via template.render(**build_lems_context(experiment)).

Parameters

experiment : SimulationExperiment

Returns

dict Keys: dyn, dyn_id, params, svs, dvs, events, coupling_inputs, coupling_meta, coupling_params, coupling_pre_rhs, coupling_post_rhs, coupling_global, sv_names_set, n_nodes, dt, duration, lems_expr (callable), _parse_piecewise (callable), lems_dim (callable), safe_id (callable).

build_std_lems_context

adapters.neuroml.build_std_lems_context(experiment)

Build a context dict for standard NeuroML-type Mako templates.

Inspects the experiment to determine whether it uses standard NeuroML types (iri: neuroml:*). When it does, extracts all data that the Mako templates need — integration parameters, pre-rendered XML fragments for cells/channels/synapses, population lists, connection lists, and simulation metadata.

Returns

dict or None None when the experiment cannot be rendered using standard NeuroML types. Otherwise a dict containing:

* ``'is_network'``  – True for multi-population network template
* ``'is_fhn'``      – True for FitzHugh-Nagumo cell template
* All scalar and list variables that the templates iterate over.

compare_traces

adapters.neuroml.compare_traces(
    ref_data,
    tvbo_data,
    ref_cols,
    tvbo_cols,
    time_col=0,
    rtol=0.05,
    atol=0.0001,
)

Compare reference and TVBO traces, print metrics.

Parameters

ref_data, tvbo_data : (n_time, n_cols) arrays ref_cols, tvbo_cols : column names (index 0 is time) time_col : which column is time (default 0) rtol, atol : tolerances for _np.allclose

get_lems_examples_dir

adapters.neuroml.get_lems_examples_dir()

Return the path to the LEMSexamples directory in the NeuroML2 repo.

inline_model_functions

adapters.neuroml.inline_model_functions(expr, dynamics, all_names)

Inline model-defined functions into a SymPy expression.

LEMS has no user-defined function mechanism, so calls like Sigm(y1 - y2) must be expanded to their body (e.g. 2*e0/(1 + exp(r*(v0 - (y1-y2))))) before the expression is printed.

Parameters

expr : sympy.Basic Already-parsed SymPy expression that may contain calls to model functions. dynamics : Dynamics The model whose functions dict holds body + formal arguments. all_names : list of str All symbol names in scope (parameters, state variables, …) so the body is parsed with the correct local dict.

parse_lems_displays

adapters.neuroml.parse_lems_displays(lems_file)

Parse Display + Line elements from a LEMS XML file.

Parameters

lems_file : str LEMS filename (e.g. ‘LEMS_NML2_Ex9_FN.xml’) resolved relative to the LEMSexamples directory.

Returns

list of _Display objects with their Line children.

parse_lems_output_columns

adapters.neuroml.parse_lems_output_columns(lems_file)

Parse OutputFile → OutputColumn quantities from a LEMS file.

Returns

dict mapping output filename (e.g. ‘ex14.dat’) to list of quantity strings.

plot_comparison

adapters.neuroml.plot_comparison(
    ref_data,
    tvbo_data,
    ref_cols,
    tvbo_cols,
    title='',
    time_scale=1.0,
    time_unit='s',
)

Plot overlaid traces: reference vs TVBO.

Parameters

ref_data, tvbo_data : arrays with time in col 0 ref_cols, tvbo_cols : column names title : plot title time_scale : multiply time by this factor for display time_unit : label for x axis

plot_lems_comparison

adapters.neuroml.plot_lems_comparison(
    lems_file,
    ref_outputs,
    tvbo_result=None,
    title_prefix='',
)

Create publication-quality comparison plots mirroring LEMS Display layout.

For each Display in the LEMS file, creates one subplot panel with: - Reference traces as solid lines (using original colors from LEMS) - TVBO traces as dashed lines (same color, slightly transparent)

Parameters

lems_file : str Reference LEMS filename (e.g. ‘LEMS_NML2_Ex2_Izh.xml’) ref_outputs : dict {filename: array} from run_lems_example() tvbo_result : xarray.DataArray, optional result.integration.data from exp.run("neuroml"). Expects dims (time, quantity). If None, only reference is plotted. title_prefix : str, optional Prefix for figure titles (e.g. ‘Ex2’)

run_lems_example

adapters.neuroml.run_lems_example(lems_file, cwd=None)

Run a LEMS XML file via jNeuroML and return {filename: array} for each .dat output.

Parameters

lems_file : str Name of the LEMS file (e.g., ‘LEMS_NML2_Ex9_FN.xml’). cwd : path, optional Working directory. Defaults to the LEMSexamples directory.

Returns

dict mapping output filename to (n_time, n_cols) numpy arrays.

safe_id

adapters.neuroml.safe_id(s)

Make a string safe for XML id attribute.

sympy_to_lems

adapters.neuroml.sympy_to_lems(expr_str, parameters=None)

Convert a TVBO equation RHS string (or SymPy expr) to LEMS syntax.

Parameters

expr_str : str or sympy.Basic Equation RHS to convert. parameters : list of str, optional Model symbol names (parameters, state variables, etc.) to inject as SymPy Symbols before parsing, overriding any conflicting built-ins (e.g. I, gamma, lambda).

validate_lems_xml

adapters.neuroml.validate_lems_xml(xml_string)

Validate a LEMS XML string using PyLEMS.

Raises if the XML is not valid LEMS.