pyneuroml.utils package#

The utils package contains various utility functions to aid users working with PyNeuroML. Many of these methods are meant for internal use in the package and so may change in the future: the API here is not considered stable.

Copyright 2024 NeuroML Contributors

pyneuroml.utils.extract_lems_definition_files(path: str | None | 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 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.

Parameters:

path (str or None) – path of directory relative to current working directory to extract to, or None

Returns:

directory path

pyneuroml.utils.extract_position_info(nml_model: NeuroMLDocument, verbose: bool = False) tuple#

Extract position information from a NeuroML model

Returns a tuple of dictionaries:

  • cell_id_vs_cell: dict(cell id, cell object)

  • pop_id_vs_cell: dict(pop id, cell object)

  • positions: dict(pop id, dict(cell id, position in x, y, z))

  • pop_id_vs_color: dict(pop id, colour property)

  • pop_id_vs_radii: dict(pop id, radius property)

Parameters:
  • nml_model (NeuroMLDocument) – NeuroML2 model to extract position information from

  • verbose (bool) – toggle function verbosity

Returns:

[cell id vs cell dict, pop id vs cell dict, positions dict, pop id vs colour dict, pop id vs radii dict]

Return type:

tuple of dicts

pyneuroml.utils.get_colour_hex(fract: float, min_colour: Tuple[int, int, int] = (255, 255, 0), max_colour: Tuple[int, int, int] = (255, 0, 0)) str#

Get colour hex at fraction between min_colour and max_colour.

Parameters:
  • fract (float between (0, 1)) – fraction between min_colour and max_colour

  • min_colour (tuple) – lower colour tuple (R, G, B)

  • max_colour (tuple) – upper colour tuple (R, G, B)

Returns:

colour in hex representation

Return type:

str

pyneuroml.utils.get_files_generated_after(timestamp: float = 1714067441.780833, directory: str = '.', ignore_suffixes: List[str] = ['xml', 'nml'], include_suffixes: List[str] = []) List[str]#

Get files modified after provided time stamp in directory, excluding provided suffixes.

Currently ignores directories.

Added in version 1.0.9.

Parameters:
  • timestamp (float) – time stamp to compare to

  • directory (str) – directory to list files of

  • ignore_suffixes (str) – file suffixes to ignore (none if empty)

  • include_suffixes (str) – file suffixes to include (all if empty)

Returns:

list of file names

Return type:

list(str)

pyneuroml.utils.get_ion_color(ion: str) str#

Get colours for ions in hex format.

Hard codes for na, k, ca, h. All others get a grey.

Parameters:

ion (str) – name of ion

Returns:

colour in hex

Return type:

str

pyneuroml.utils.get_model_file_list(rootfile: str, filelist: List[str], rootdir: str = '.', lems_def_dir: str | None = None) str | None#

Get the list of files to archive.

This method will take the rootfile, and recursively resolve all the files it uses.

Parameters:
  • rootfile (str) – main NeuroML/LEMS/SED-ML file to resolve

  • filelist (list of strings) – list of file paths to append to

  • rootdir (str) – directory holding the root file

  • lems_def_dir (str) – path to directory holding lems definition files

Returns:

value of lems_def_dir so that the temporary directory can be cleaned up. strings are immuatable in Python so the variable cannot be modified in the function.

Raises:

ValueError – if a file that does not have “.xml” or “.nml” as extension is encountered

pyneuroml.utils.get_pyneuroml_tempdir(rootdir: str = '.', prefix: str = 'pyneuroml')#

Generate a pyneuroml directory name that can be used for various purposes.

Default format: {rootdir}/{prefix}_{timestamp}_{6 random characters}

Parameters:
  • rootdir (str) – root directory where to create the new directory

  • prefix (str) – prefix for directory name

Returns:

generated directory name

Return type:

str

pyneuroml.utils.get_state_color(s: str) str#

Get colours for state variables.

Hard codes for m, k, r, h, l, n, a, b, c, q, e, f, p, s, u.

Parameters:

state (str) – name of state

Returns:

colour in hex format

Return type:

str

pyneuroml.utils.rotate_cell(cell: Cell, x: float = 0, y: float = 0, z: float = 0, order: str = 'xyz', relative_to_soma: bool = False) Cell#

Return a new cell object rotated in the provided order along the provided angles (in radians) relative to the soma position.

Parameters:
  • cell (neuroml.Cell) – cell object to rotate

  • x (float) – angle to rotate around x axis, in radians

  • y (float) – angle to rotate around y axis, in radians

  • z (float) – angle to rotate around z axis, in radians

  • order (str) – rotation order in terms of x, y, and z

  • relative_to_soma (bool) – whether rotation is relative to soma

Returns:

new neuroml.Cell object

Return type:

neuroml.Cell

Derived from LFPy’s implementation: LFPy/LFPy

pyneuroml.utils.info module#

Utilities for getting information from NeuroML models

File: pyneuroml/utils/info.py

Copyright 2024 NeuroML contributors

pyneuroml.utils.info.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

Parameters:

cell (Cell) – cell object to investigate

Returns:

string of cell information

pyneuroml.utils.info.cells_info(nml_file_name: str) str#

Provide information about the cells in a NeuroML file.

Parameters:

nml_file_name (str) – name of NeuroML v2 file

Returns:

information on cells (str)

pyneuroml.utils.info.quick_summary(nml2_doc: NeuroMLDocument) str#

Get a quick summary of the NeuroML2 document

NOTE: You should prefer nml2_doc.summary(show_includes=False)

Parameters:

nml2_doc (NeuroMLDocument) – NeuroMLDocument to fetch summary for

Returns:

summary string

pyneuroml.utils.info.summary(nml2_doc: NeuroMLDocument | None = None, verbose: bool = False) None#

Wrapper around nml_doc.summary() to generate the pynml-summary command line tool.

Parameters:
  • nml2_doc (NeuroMLDocument) – NeuroMLDocument object or name of NeuroML v2 file to get summary for.

  • verbose (bool) – toggle verbosity

pyneuroml.utils.plot module#

Common utils to help with plotting

File: pyneuroml/utils/plot.py

Copyright 2023 NeuroML contributors

class pyneuroml.utils.plot.LineDataUnits(*args, **kwargs)#

Bases: Line2D

New Line class for making lines with specific widthS

Reference:

https://stackoverflow.com/questions/19394505/expand-the-line-with-specified-width-in-data-unit

set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, dash_capstyle=<UNSET>, dash_joinstyle=<UNSET>, dashes=<UNSET>, data=<UNSET>, drawstyle=<UNSET>, fillstyle=<UNSET>, gapcolor=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, marker=<UNSET>, markeredgecolor=<UNSET>, markeredgewidth=<UNSET>, markerfacecolor=<UNSET>, markerfacecoloralt=<UNSET>, markersize=<UNSET>, markevery=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, solid_capstyle=<UNSET>, solid_joinstyle=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, xdata=<UNSET>, ydata=<UNSET>, zorder=<UNSET>)#

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: scalar or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: ~matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

pyneuroml.utils.plot.add_box_to_matplotlib_2D_plot(ax, xy, height, width, color)#

Add a box to a matplotlib plot, at xy of height, width and color.

Parameters:
  • ax (matplotlob.axes.Axis) – matplotlib.axes.Axes object

  • xy (List[float]) – bottom left corner of box

  • height (float) – height of box

  • width (float) – width of box

  • color (str) – color of box for edge, face, fill

Returns:

None

pyneuroml.utils.plot.add_line_to_matplotlib_2D_plot(ax, xv, yv, width, color, axis_min_max)#

Add a line to a matplotlib plot

Parameters:
  • ax (matplotlib.axes.Axes) – matplotlib.axes.Axes object

  • xv ([float, float]) – x values

  • yv ([float, float]) – y values

  • width (float) – width of line

  • color (str) – color of line

  • axis_min_max ([float, float]) – min, max value of axis

pyneuroml.utils.plot.add_scalebar_to_matplotlib_plot(axis_min_max, ax)#

Add a scalebar to matplotlib plots.

The scalebar is of magnitude 50 by default, but if the difference between max and min vals is less than 100, it’s reduced to 5, and if the difference is less than 10, it’s reduced to 1.

Parameters:
  • axis_min_max ([float, float]) – minimum, maximum value in plot

  • ax (matplotlib.axes.Axes) – axis to plot scalebar at

Returns:

None

pyneuroml.utils.plot.add_text_to_matplotlib_2D_plot(ax: Axes, xv: List[float], yv: List[float], color: str, text: str, horizontal: str = 'center', vertical: str = 'bottom', clip_on: bool = True)#

Add text to a matplotlib plot between two points

Wrapper around matplotlib.axes.Axes.text.

Rotates the text label to ensure it is at the same angle as the line.

Parameters:
  • ax (Axes) – matplotlib axis object

  • xv (list[x1, x2]) – start and end coordinates in one axis

  • yv (list[y1, y2]) – start and end coordinates in second axix

  • color (str) – color of text

  • text (str) – text to write

  • clip_on (bool) – toggle clip_on (if False, text will also be shown outside plot)

pyneuroml.utils.plot.autoscale_matplotlib_plot(verbose: bool = False, square: bool = True) None#

Autoscale the current matplotlib plot

Parameters:
  • verbose (bool) – toggle verbosity

  • square (bool) – toggle squaring of plot

Returns:

None

pyneuroml.utils.plot.get_cell_bound_box(cell: Cell)#

Get a boundary box for a cell

Parameters:

cell (neuroml.Cell) – cell to get boundary box for

Returns:

tuple (min view, max view)

pyneuroml.utils.plot.get_new_matplotlib_morph_plot(title: str = '', plane2d: str = 'xy') Tuple[Figure, Axes]#

Get a new 2D matplotlib plot for morphology related plots.

Parameters:
  • title (str) – title of plot

  • plane2d – plane to use

Returns:

new [matplotlib.figure.Figure, matplotlib.axes.Axes]

Return type:

[matplotlib.figure.Figure, matplotlib.axes.Axes]

pyneuroml.utils.plot.get_next_hex_color(my_random: Random | None = None) str#

Get a new randomly generated HEX colour code.

You may pass a random.Random instance that you may be used. Otherwise the default Python random generator will be used.

Parameters:

my_random (random.Random) – a random.Random object

Returns:

HEX colour code

pyneuroml.utils.plot.load_minimal_morphplottable__model(nml_model: NeuroMLDocument, nml_file_path: str = '')#

Take a model that has been loaded without recursively including all bits, and load only information that is needed to plot it.

Parameters:
  • nml_model (neuroml.NeuroMLDocument) – partially loaded model

  • nml_file_path (str) – path of file corresponding to the model

pyneuroml.utils.misc module#

Miscellaneous utils

File: pyneuroml/utils/misc.py

Copyright 2024 NeuroML contributors

pyneuroml.utils.misc.get_path_to_jnml_jar() str#

Get the path to the jNeuroML jar included with PyNeuroML.

Returns:

path of jar file

pyneuroml.utils.cli module#

Utilities use in writing console scripts.

File: pyneuroml/utils/cli.py

Copyright 2023 NeuroML contributors

pyneuroml.utils.units module#

Methods related to units.

File: pyneuroml/utils/units.py

Copyright 2024 NeuroML contributors

pyneuroml.utils.units.convert_to_units(nml2_quantity: str, unit: str) float#

Convert a NeuroML2 quantity to provided unit.

Parameters:
  • nml2_quantity (str) – NeuroML2 quantity to convert

  • unit (str) – unit to convert to

Returns:

converted value (float)

pyneuroml.utils.units.get_lems_model_with_units() Model#

Get a LEMS model with NeuroML core dimensions and units.

Returns:

a lems.model.model.Model that includes NeuroML dimensions and units.

pyneuroml.utils.units.get_value_in_si(nml2_quantity: str) float | None#

Get value of a NeuroML2 quantity in SI units

Parameters:

nml2_quantity (str) – NeuroML2 quantity to convert

Returns:

value in SI units (float)

pyneuroml.utils.units.split_nml2_quantity(nml2_quantity: str) Tuple[float, str]#

Split a NeuroML 2 quantity into its magnitude and units

Parameters:

nml2_quantity – NeuroML2 quantity to split

Returns:

a tuple (magnitude, unit)

pyneuroml.utils.xml module#

Utility methods related to xml processing

File: pyneuroml/utils/xml.py

Copyright 2024 NeuroML contributors