pyneuroml.plot package#

pyneuroml.plot.Plot module#

Plotting helper functions.

File: pyneuroml/plot/Plot.py

Copyright 2023 NeuroML contributors

pyneuroml.plot.Plot.generate_interactive_plot(xvalues: List[float], yvalues: List[float], title: str, labels: List[str] | None = None, linestyles: List[str] | None = None, linewidths: List[int] | List[float] | None = None, markers: List[str] | List[int] | None = None, markersizes: List[int] | List[float] | None = None, plot_bgcolor: str | None = None, modes: List[str] | None = None, xaxis: str | None = None, yaxis: str | None = None, legend_title: str | None = None, xaxis_color: str = '#fff', yaxis_color: str = '#fff', xaxis_width: float | int = 1, yaxis_width: float | int = 1, xaxis_mirror: str | bool = False, yaxis_mirror: str | bool = False, xaxis_spikelines: bool = False, yaxis_spikelines: bool = False, grid: bool = True, logx: bool = False, logy: bool = False, layout: dict | None = None, show_interactive: bool = True, save_figure_to: str | None = None) None#

Utility function to generate interactive plots using Plotly.

This function can be used to generate graphs with multiple plot lines. For example, to plot two metrics you can use:

generate_interactive_plot(xvalues=[[ax1, ax2, ax3], [bx1, bx2, bx3]], yvalues=[[ay1, ay2, ay3], [by1, by2, by3]], labels=["metric 1", "metric 2"])

Please note that while plotting multiple plots, you should take care to ensure that the number of x values and y values for each metric correspond. These lists are passed directly to Plotly for plotting without additional sanity checks.

A number of options are provided for convenience to allow plotting of multiple traces in the same plot and modification of common layout options. A layout dict can also be passed instead, which will overwrite any individually set options. If you need more customisation, please look at the source code of this method to write your own.

See the plotly documentation for more information: https://plotly.com/python-api-reference/generated/plotly.graph_objects.scatter.html

Parameters:
pyneuroml.plot.Plot.generate_plot(xvalues: List[List[float]], yvalues: List[List[float]], title: str, labels: List[str] | None = None, colors: List[str] | None = None, linestyles: List[str] | None = None, linewidths: List[str] | None = None, markers: List[str] | None = None, markersizes: List[str] | None = None, xaxis: str | None = None, yaxis: str | None = None, xlim: List[float] | None = None, ylim: List[float] | None = None, show_xticklabels: bool = True, show_yticklabels: bool = True, grid: bool = False, logx: bool = False, logy: bool = False, font_size: int | None = None, bottom_left_spines_only: bool = False, cols_in_legend_box: int = 3, legend_position: str | None = 'best', show_plot_already: bool = True, animate: bool = False, animate_duration: int = 5, animate_writer: Tuple[str, List[str]] = ('pillow', []), save_figure_to: str | None = None, title_above_plot: bool = False, verbose: bool = False, close_plot: bool = False, interactive_legend: bool = True) Axes | None#

Utility function to generate plots using the Matplotlib library.

This function can be used to generate graphs with multiple plot lines. For example, to plot two metrics you can use:

generate_plot(xvalues=[[ax1, ax2, ax3], [bx1, bx2, bx3]], yvalues=[[ay1, ay2, ay3], [by1, by2, by3]], labels=["metric 1", "metric 2"])

Please note that while plotting multiple plots, you should take care to ensure that the number of x values and y values for each metric correspond. These lists are passed directly to Matplotlib for plotting without additional sanity checks.

Please see the Matplotlib documentation for the complete list of available styles and colours: - https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html - https://matplotlib.org/stable/gallery/index.html

Added in version 1.2.15:

  • animate

  • interactive_legend

Parameters:
  • xvalues (list of lists) – X values

  • yvalues (lists of lists) – Y values

  • title (str) – title of plot

  • labels (list of strings) – labels for each plot (default: None)

  • colors (list of strings) – colours for each plot (default: None)

  • linestyles (list strings) – list of line styles (default: None)

  • linewidths (list of floats) – list of line widths (default: None)

  • markers (list strings) – list of markers (default: None)

  • markersizes (list of floats) – list of marker sizes (default: None)

  • xaxis (str) – label of X axis (default: None)

  • yaxis (str) – label of Y axis (default: None)

  • xlim (tuple of (float, float) or individual arguments: (left=float), (right=float)) –

    left and right extents of x axis (default: None)

    See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlim.html

  • ylim (tuple of (float, float) or individual arguments: (top=float), (bottom=float)) –

    top and bottom extents of y axis (default: None)

    See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylim.html

  • show_xticklabels (boolean) – whether labels should be shown on xtics (default: True)

  • show_yticklabels (boolean) – whether labels should be shown on ytics (default: True)

  • grid (boolean) – enable/disable grid (default: False)

  • logx (boolean) – should the x axis be in log scale (default: False)

  • logy (boolean) – should the y ayis be in log scale (default: False)

  • font_size (float) – font size

  • bottom_left_spines_only (boolean) – enable/disable spines on right and top (default: False) (a spine is the line noting the data area boundary)

  • cols_in_legend_box (float) – number of columns to use in legend box (default: 3)

  • legend_position (str) –

    position of legend: See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html

    Extra options:

    • ”outer right” places the legend on the right, but outside the axes box

    • ”bottom center” places the legend on the bottom, below the figure

    Note that if labels is None, a legend is not shown

  • show_plot_already (boolean) – if plot should be shown when created (default: True)

  • animate (boolean) – if plot should be animated (default: False)

  • animate_duration (int) – approx duration (seconds) of the animation. animate should be True (default: 5)

  • animate_writer (tuple) –

    writer for saving animation (default: ("pillow", []))

    See: https://matplotlib.org/stable/users/explain/animations/animations.html#saving-animations

    • format : writer=( "writer name", ["extra args list"])

    • example : writer=( "imagemagick", ["-quality", "100"])

  • save_figure_to (str) – location to save generated figure/animation to (default: None)

  • title_above_plot (boolean) – enable/disable title above the plot (default: False)

  • verbose (boolean) – enable/disable verbose logging (default: False)

  • close_plot (bool) – call pyplot.close() to close plot after plotting, this is always done if using animation

  • interactive_legend (bool) – enable clicking on legend to toggle plot lines when using the matplotlib UI

Returns:

matplotlib.axes.Axes object if plot is not closed, else None

Raises:

ValueError – if the dimensions of xvalues/yvalues and option arguments colors/labels/linestyles/linewidths/markers/markersizes do not match

pyneuroml.plot.PlotTimeSeries module#

Functions related to plotting of time series

File: pyneuroml/plot/PlotTimeSeries.py

Copyright 2024 NeuroML contributors

pyneuroml.plot.PlotTimeSeries.plot_time_series(trace_data: Dict[Any, Any] | List[Dict[Any, Any]], title: str = '', offset: bool = True, show_plot_already: bool = True, scalebar_location: str | None = None, scalebar_length: float | None = None, labels: bool = False, **kwargs_generate_plot: Any) None#

Plot time series data from a dictionary of data

Added in version 1.2.2.

See also

pyneuroml.plot.Plot.generate_plot()

general plotting function

Parameters:
  • trace_data (dict or list(dict)) – a dictionary of trace data, or list of such dictionaries The keys are used as labels in the legend. At least one ‘t’ key must exist in each dict, which holds the time axis data.

  • title (str) – plot title, use “” to leave it blank

  • offset (bool) – whether the time series should be offset from each other along the y axis for clarity. This is often useful when plotting voltage traces for a population of cells where overlapping traces would make it hard to see individual values

  • scalebar_location (str or None) – where a scalebar should be placed If None, no scalebar is shown. See the documentation of matplotlib-scalebar for more information: ppinard/matplotlib-scalebar

  • scalebar_length (float) – length of scalebar in units of data (only valid if scalebar_location is not None)

  • labels (bool) – toggle using labels for legends If labels is None, no legend is shown

  • kwargs_generate_plot – other key word arguments that are passed to the pyneuroml.plot.Plot.generate_plot function

Returns:

None

Raises:

ValueError – if a ‘t’ (time) key is not found in the traces data

pyneuroml.plot.PlotTimeSeries.plot_time_series_from_data_files(data_file_names: str | List[str], **kwargs)#

Plot time series from a data file.

The first column must be the time, the other columns are data.

Added in version 1.2.2.

Parameters:
  • data_file_names (str or list of strings) – name/path to data file(s)

  • kwargs – other key word arguments that are passed to the plot_time_series function

pyneuroml.plot.PlotTimeSeries.plot_time_series_from_lems_file(lems_file_name: str, base_dir: str = '.', title: str = '', **kwargs) None#

Plot time series from a LEMS file.

Wrapper around the plot_time_series function. This reads a LEMS file, loads the data and then passes it to it.

Added in version 1.2.2.

See also

pyneuroml.plot.PlotTimeSeries.plot_time_series()

main plotter function

Parameters:
  • lems_file_name (str) – path to LEMS simulation file

  • base_dir (str) – directory where LEMS file resides

  • kwargs – other arguments passed to plot_time_series

Returns:

None

pyneuroml.plot.PlotSpikes module#

Spike plotting helper functions.

File: pyneuroml/plot/PlotSpikes.py

Copyright 2023 NeuroML contributors

pyneuroml.plot.PlotSpikes.plot_spikes(spike_data: List[Dict[str, List[float] | List[int]]], title: str = '', offset: bool = True, show_plots_already: bool = True, save_spike_plot_to: str | None = None, rates: bool = False, rate_window: int = 50, rate_bins: int = 500, max_image_size: Tuple[int, int] | None = None) None#

Plot spike times from data.

Parameters:
  • spike_data (list of dictionaries) – List of dictionaries containing spike time data. Each dictionary should have the following keys: - “name” (str): Name of the population or file. - “times” (List[float]): List of spike times in seconds. - “ids” (List[int]): List of cell IDs corresponding to each spike time.

  • title (str) – Title of the plot. Defaults to an empty string.

  • offset (bool) – toggle whether different spike_data items should be offset along the y axis for clarity

  • show_plots_already (bool) – Whether to show the plots immediately after they are generated. Defaults to True.

  • save_spike_plot_to (str) – Path to save the spike plot to. If None, the plot will not be saved. Defaults to None.

  • rates (bool) – Whether to plot rates in addition to spike times. Defaults to False.

  • rate_window (int) – Window size for rate calculation in ms. Defaults to 50.

  • rate_bins (int) – Number of bins for rate histogram. Defaults to 500.

Returns:

None

Return type:

None

pyneuroml.plot.PlotSpikes.plot_spikes_from_data_files(spiketime_files: List[str], format_: str, show_plots_already: bool = True, save_spike_plot_to: str | None = None, rates: bool = False, rate_window: int = 50, rate_bins: int = 500, title: str = '') None#

Plot spike times from data files.

Parameters:
  • spiketime_files (List[str]) – List of spike time files to be plotted.

  • title (str) – optional title for plot, empty string disables it

  • format (str) –

    Format of the spike time data in the files.

    Can be one of the following:

    • id_t: Each line contains a cell ID (int) followed by a spike time (float).

    • id_time_nest_dat: Each line contains a cell ID (int) followed by a spike time (float), with NEST-style comments allowed.

    • t_id: Each line contains a spike time (float) followed by a cell ID (int).

    • sonata: SONATA-style HDF5 file.

  • show_plots_already (bool) – Whether to show the plots immediately after they are generated. Defaults to True.

  • save_spike_plot_to (Optional[str]) – Path to save the spike plot to. If None, the plot will not be saved. Defaults to None.

  • rates (bool) – Whether to plot rates in addition to spike times. Defaults to False.

  • rate_window (int) – Window size for rate calculation in ms. Defaults to 50.

  • rate_bins (int) – Number of bins for rate histogram. Defaults to 500.

Returns:

None

Return type:

None

pyneuroml.plot.PlotSpikes.plot_spikes_from_lems_file(lems_file_name: str, base_dir: str = '.', show_plots_already: bool = True, save_spike_plot_to: str | None = None, rates: bool = False, rate_window: int = 50, rate_bins: int = 500) None#

Plot spike times from a LEMS simulation file.

This function reads a LEMS simulation file to figure out the names of the spike data files, and then calls plot_spikes_from_data_files to load and plot the spike data.

Parameters:
  • lems_file_name (str) – Path to the LEMS simulation file.

  • base_dir (str) – Directory where the LEMS file resides. Defaults to the current directory.

  • show_plots_already (bool) – Whether to show the plots immediately after they are generated. Defaults to True.

  • save_spike_plot_to (Optional[str]) – Path to save the spike plot to. If None, the plot will not be saved. Defaults to None.

  • rates (bool) – Whether to plot rates in addition to spike times. Defaults to False.

  • rate_window (int) – Window size for rate calculation in ms. Defaults to 50.

  • rate_bins (int) – Number of bins for rate histogram. Defaults to 500.

Returns:

None

Return type:

None

pyneuroml.plot.PlotSpikes.read_sonata_spikes_hdf5_file(file_name: str) dict#

Read spike times from a SONATA format HDF5 file.

Parameters:

file_name (str) – The name of the HDF5 file.

Returns:

A dictionary where the keys are population names and the values are dictionaries of spike times for each ID in the population.

Return type:

dict

pyneuroml.plot.PlotMorphology module#

Utilities to plot NeuroML2 cell morphologies.

File: pyneuroml/plot/PlotMorphology.py

Copyright 2023 NeuroML contributors

pyneuroml.plot.PlotMorphology.plot_2D(nml_file: str | NeuroMLDocument | Cell, plane2d: str = 'xy', min_width: float = 0.8, verbose: bool = False, nogui: bool = False, save_to_file: str | None = None, square: bool = False, plot_type: str = 'detailed', title: str | None = None, close_plot: bool = False, plot_spec: Dict[str, str | List[int] | float] | None = None, highlight_spec: Dict[Any, Any] | None = None)#

Plot cells in a 2D plane.

If a file with a network containing multiple cells is provided, it will plot all the cells. For detailed neuroml.Cell types, it will plot their complete morphology. For point neurons, we only plot the points (locations) where they are. For single cell SWC files, it will first convert them to NeuroML and then plot them.

This method uses matplotlib.

Added in version 1.1.12: The hightlight_spec parameter

Parameters:
  • nml_file (str or neuroml.NeuroMLDocument or neuroml.Cell or neuroml.Morphology) – path to NeuroML cell file or single cell SWC file or neuroml.NeuroMLDocument or neuroml.Cell or neuroml.Morphology object

  • plane2d (str) – what plane to plot (xy/yx/yz/zy/zx/xz)

  • min_width (float) – minimum width for segments (useful for visualising very thin segments): default 0.8um

  • verbose (bool) – show extra information (default: False)

  • nogui (bool) – do not show matplotlib GUI (default: false)

  • save_to_file (str) – optional filename to save generated morphology to

  • square (bool) – scale axes so that image is approximately square

  • plot_type (str) –

    type of plot, one of:

    • ”detailed”: show detailed morphology taking into account each segment’s width

    • ”constant”: show morphology, but use constant line widths

    • ”schematic”: only plot each unbranched segment group as a straight line, not following each segment

    • ”point”: show all cells as points

    This is only applicable for neuroml.Cell cells (ones with some morphology)

  • title (str) – title of plot

  • close_plot (bool) – call pyplot.close() to close plot after plotting

  • plot_spec (dict) –

    dictionary that allows passing some specifications that control how a plot is generated. This is mostly useful for large network plots where one may want to have a mix of full morphology and schematic, and point representations of cells. Possible keys are:

    • point_fraction: what fraction of each population to plot as point cells: these cells will be randomly selected

    • points_cells: list of cell ids to plot as point cells

    • schematic_cells: list of cell ids to plot as schematics

    • constant_cells: list of cell ids to plot as constant widths

    The last three lists override the point_fraction setting. If a cell id is not included in the spec here, it will follow the plot_type provided before.

  • highlight_spec (dict) –

    dictionary that allows passing some specifications to allow highlighting of particular elements. Only used when plotting multi-compartmental cells for marking segments on them (“plot_type” is either “constant” or “detailed”)

    Each key in the dictionary will be of the cell id and the values will be more dictionaries, with the segment id as key and the following keys in it:

    • marker_color: color of the marker

    • marker_size: width of the marker

    E.g.:

    {
        "cell id1": {
            "seg id1": {
                "marker_color": "blue",
                "marker_size": 10
            }
        }
    }
    

pyneuroml.plot.PlotMorphology.plot_2D_cell_morphology(offset: List[float] = [0, 0], cell: Cell | None = None, plane2d: str = 'xy', color: str | None = None, title: str = '', verbose: bool = False, fig: Figure | None = None, ax: Axes | None = None, min_width: float = 0.8, axis_min_max: List = [inf, -inf], scalebar: bool = False, nogui: bool = True, autoscale: bool = True, square: bool = False, plot_type: str = 'detailed', save_to_file: str | None = None, close_plot: bool = False, overlay_data: Dict[int, float] | None = None, overlay_data_label: str | None = None, datamin: float | None = None, datamax: float | None = None, colormap_name: str = 'viridis', highlight_spec: Dict[Any, Any] | None = None)#

Plot the detailed 2D morphology of a cell in provided plane.

The method can also overlay data onto the morphology.

Added in version 1.0.0.

See also

plot_2D()

general function for plotting

plot_2D_schematic()

for plotting only segmeng groups with their labels

plot_2D_point_cells()

for plotting point cells

Parameters:
  • offset ([float, float]) – offset for cell

  • cell (neuroml.Cell) – cell to plot

  • plane2d (str) – plane to plot on

  • color (str) – color to use for all segments

  • fig (matplotlib.figure.Figure) – a matplotlib.figure.Figure object to use

  • ax (matplotlib.axes.Axes) – a matplotlib.axes.Axes object to use

  • min_width (float) – minimum width for segments (useful for visualising very thin segments): default 0.8um

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

  • title (str) – title of plot

  • verbose (bool) – show extra information (default: False)

  • nogui (bool) – do not show matplotlib GUI (default: false)

  • save_to_file (str) – optional filename to save generated morphology to

  • square (bool) – scale axes so that image is approximately square

  • autoscale (bool) – toggle autoscaling

  • scalebar (bool) – toggle scalebar

  • close_plot (bool) – call pyplot.close() to close plot after plotting

  • overlay_data (dict, keys are segment ids, values are magnitudes to overlay on curtain plots) – data to overlay over the morphology this must be a dictionary with segment ids as keys, the single value to overlay as values

  • overlay_data_label (str) – label of data being overlaid

  • colormap_name (str) – name of matplotlib colourmap to use for data overlay See: https://matplotlib.org/stable/api/matplotlib_configuration_api.html#matplotlib.colormaps Note: random colours are used for each segment if no data is to be overlaid

  • datamin (float) – min limits of data (useful to compare different plots)

  • datamax (float) – max limits of data (useful to compare different plots)

  • highlight_spec (dict) –

    dictionary that allows passing some specifications to allow highlighting of particular elements. Mostly only helpful for marking segments on multi-compartmental cells. In the main dictionary are more dictionaries, one for each segment id (as string or integer) which will be the key:

    • marker_color: color of the marker

    • marker_size: width of the marker

Raises:

ValueError if cell is None

pyneuroml.plot.PlotMorphology.plot_2D_point_cells(offset: List[float] = [0, 0], plane2d: str = 'xy', color: str | None = None, soma_radius: float = 10.0, title: str = '', verbose: bool = False, fig: Figure | None = None, ax: Axes | None = None, axis_min_max: List = [inf, -inf], scalebar: bool = False, nogui: bool = True, autoscale: bool = True, square: bool = False, save_to_file: str | None = None, close_plot: bool = False)#

Plot point cells.

Added in version 1.0.0.

See also

plot_2D()

general function for plotting

plot_2D_schematic()

for plotting only segmeng groups with their labels

plot_2D_cell_morphology()

for plotting cells with detailed morphologies

Parameters:
  • offset ([float, float]) – location of cell

  • plane2d (str) – plane to plot on

  • color (str) – color to use for cell

  • soma_radius (float) – radius of soma

  • fig (matplotlib.figure.Figure) – a matplotlib.figure.Figure object to use

  • ax (matplotlib.axes.Axes) – a matplotlib.axes.Axes object to use

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

  • title (str) – title of plot

  • verbose (bool) – show extra information (default: False)

  • nogui (bool) – do not show matplotlib GUI (default: false)

  • save_to_file (str) – optional filename to save generated morphology to

  • square (bool) – scale axes so that image is approximately square

  • autoscale (bool) – toggle autoscaling

  • scalebar (bool) – toggle scalebar

  • close_plot (bool) – call pyplot.close() to close plot after plotting

pyneuroml.plot.PlotMorphology.plot_2D_schematic(cell: Cell, segment_groups: List[SegmentGroup] | None, offset: List[float] = [0, 0], labels: bool = False, plane2d: str = 'xy', width: float = 2.0, verbose: bool = False, square: bool = False, nogui: bool = False, save_to_file: str | None = None, scalebar: bool = True, autoscale: bool = True, fig: Figure | None = None, ax: Axes | None = None, title: str = '', close_plot: bool = False) None#

Plot a 2D schematic of the provided segment groups.

This plots each segment group as a straight line between its first and last segment.

Added in version 1.0.0.

See also

plot_2D()

general function for plotting

plot_2D_point_cells()

for plotting point cells

plot_2D_cell_morphology()

for plotting cells with detailed morphologies

Parameters:
  • offset ([float, float]) – offset for cell

  • cell (neuroml.Cell) – cell to plot

  • segment_groups (list(SegmentGroup)) – list of unbranched segment groups to plot

  • labels (bool) – toggle labelling of segment groups

  • plane2d (str) – what plane to plot (xy/yx/yz/zy/zx/xz)

  • width (float) – width for lines

  • verbose (bool) – show extra information (default: False)

  • square (bool) – scale axes so that image is approximately square

  • nogui (bool) – do not show matplotlib GUI (default: false)

  • save_to_file (str) – optional filename to save generated morphology to

  • fig (matplotlib.figure.Figure) – a matplotlib.figure.Figure object to use

  • ax (matplotlib.axes.Axes) – a matplotlib.axes.Axes object to use

  • title (str) – title of plot

  • square – scale axes so that image is approximately square

  • autoscale (bool) – toggle autoscaling

  • scalebar (bool) – toggle scalebar

  • close_plot (bool) – call pyplot.close() to close plot after plotting

pyneuroml.plot.PlotMorphology.plot_segment_groups_curtain_plots(cell: Cell, segment_groups: List[str], labels: bool = False, verbose: bool = False, nogui: bool = False, save_to_file: str | None = None, overlay_data: Dict[str, List[Any]] | None = None, overlay_data_label: str = '', width: float | int = 4, colormap_name: str = 'viridis', title: str = 'SegmentGroup', datamin: float | None = None, datamax: float | None = None, close_plot: bool = False) None#

Plot curtain plots of provided segment groups.

Added in version 1.0.0.

Parameters:
  • cell (neuroml.Cell) – cell to plot

  • segment_groups (list(str)) – list of ids of unbranched segment groups to plot

  • labels (bool) – toggle labelling of segment groups

  • verbose (bool) – show extra information (default: False)

  • nogui (bool) – do not show matplotlib GUI (default: false)

  • save_to_file (str) – optional filename to save generated morphology to

  • overlay_data (dict, keys are segment group ids, values are lists of magnitudes to overlay on curtain plots) – data to overlay over the curtain plots; this must be a dictionary with segment group ids as keys, and lists of values to overlay as values. Each list should have a value for every segment in the segment group.

  • overlay_data_label (str) – label of data being overlaid

  • width (float/int) – width of each segment group

  • colormap_name (str) – name of matplotlib colourmap to use for data overlay See: https://matplotlib.org/stable/api/matplotlib_configuration_api.html#matplotlib.colormaps Note: random colours are used for each segment if no data is to be overlaid

  • title (str) – plot title, displayed at bottom

  • datamin (float) – min limits of data (useful to compare different plots)

  • datamax (float) – max limits of data (useful to compare different plots)

  • close_plot (bool) – call pyplot.close() to close plot after plotting

Returns:

None

Raises:
  • ValueError – if keys in overlay_data do not match ids of segment groups of segment_groups

  • ValueError – if number of items for each key in overlay_data does not match the number of segments in the corresponding segment group

pyneuroml.plot.PlotMorphologyVispy module#

Vispy interactive plotting.

Kept in a separate file so that the vispy dependency is not required elsewhere.

File: pyneuroml/plot/PlotMorphologyVispy.py

Copyright 2023 NeuroML contributors

class pyneuroml.plot.PlotMorphologyVispy.PlotSpec#

Bases: dict

constant_cells: List[str]#
detailed_cells: List[str]#
point_cells: List[str]#
point_fraction: float#
schematic_cells: List[str]#
pyneuroml.plot.PlotMorphologyVispy.add_text_to_vispy_3D_plot(current_canvas: SceneCanvas, xv: List[float], yv: List[float], zv: List[float], color: str, text: str)#

Add text to a vispy plot between two points.

Wrapper around vispy.scene.visuals.Text

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

Parameters:
  • scene (scene.SceneCanvas) – vispy scene object

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

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

  • zv (list[z1, z2]) – start and end coordinates in third axix

  • color (str) – color of text

  • text (str) – text to write

pyneuroml.plot.PlotMorphologyVispy.compute_faces_of_cylindrical_mesh(rows: int, cols: int, closed: bool)#

Compute faces for cylindrical meshes

Since we tend to use a constant set of rows and cols, this function should be called repeatedly with the same values, and thus benefits from caching.

Parameters:
  • rows (int) – number of rows in mesh

  • cols (int) – number of cols in mesh

  • closed (bool) – toggle whether mesh is closed or open

Returns:

numpy array with faces (triplets of vertex indices)

pyneuroml.plot.PlotMorphologyVispy.create_cylindrical_mesh(rows: int, cols: int, radius: float | Tuple[float, float] = (1.0, 1.0), length: float = 1.0, closed: bool = True)#

Create a cylinderical mesh, adapted from vispy’s generation method: vispy/vispy

Parameters:
  • rows (int) – number of rows to use for mesh

  • cols (int) – number of columns

  • radius (float or (float, float)) – float or pair of floats for the two radii of the cylinder

  • length (float) – length of cylinder

  • closed (bool) – whether the cylinder should be closed

Returns:

Vertices and faces computed for a cylindrical surface.

Return type:

MeshData

pyneuroml.plot.PlotMorphologyVispy.create_mesh(meshdata: List[Tuple[float, float, float, Point3DWithDiam, Point3DWithDiam, str | Tuple[float, float, float], Tuple[float, float, float] | None]], current_view: ViewBox, save_mesh_to: str | None)#

Internal function to create a mesh from the mesh data

See: https://vispy.org/api/vispy.scene.visuals.html#vispy.scene.visuals.Mesh

Parameters:
  • meshdata – meshdata to plot: list with: [(r1, r2, length, prox, dist, color, offset)]

  • current_view (ViewBox) – vispy viewbox to use

  • save_mesh_to (str or None) – name of file to save mesh object to

pyneuroml.plot.PlotMorphologyVispy.create_new_vispy_canvas(view_min: List[float] | None = None, view_max: List[float] | None = None, title: str = '', axes_pos: Tuple[float, float, float] | Tuple[int, int, int] | str | None = None, axes_length: float = 100, axes_width: int = 2, theme='light', view_center: List[float] | None = None) Tuple[SceneCanvas, ViewBox]#

Create a new vispy scene canvas with a view and optional axes lines

Reference: https://vispy.org/gallery/scene/axes_plot.html

Parameters:
  • view_min ([float, float, float]) – min view co-ordinates

  • view_max ([float, float, float]) – max view co-ordinates

  • view_center ([float, float, float]) – center view co-ordinates, calculated from view max/min if omitted

  • title (str) – title of plot

  • axes_pos ((float, float, float) or (int, int, int) or None or str) –

    add x, y, z axes centered at given position with colours red, green, blue for x, y, z axis respecitvely.

    A few special values are supported:

    • None: disable axes (default)

    • ”origin”: automatically added at origin

    • ”bottom left”: automatically added at bottom left

  • axes_length (float) – length of axes

  • axes_width (float) – width of axes lines

Returns:

scene, view

Raises:

ValueError – if incompatible value of axes_pos is passed

pyneuroml.plot.PlotMorphologyVispy.create_spherical_mesh(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude')#

Wrapper around vispy.geometry.create_sphere to allow the use of a cache

pyneuroml.plot.PlotMorphologyVispy.plot_3D_cell_morphology(offset: Tuple[float, float, float] | None = (0.0, 0.0, 0.0), cell: Cell | None = None, color: str | None = None, title: str = '', verbose: bool = False, current_canvas: SceneCanvas | None = None, current_view: ViewBox | None = None, min_width: float = 0.8, axis_min_max: Tuple = (inf, -inf), axes_pos: Tuple[float, float, float] | Tuple[int, int, int] | str | None = None, nogui: bool = False, plot_type: str = 'detailed', theme: str = 'light', meshdata: List[Any] | None = None, highlight_spec: Dict | frozendict | None = None, upright: bool = False, save_mesh_to: str | None = None) List[Any] | None#

Plot the detailed 3D morphology of a cell using vispy. https://vispy.org/

Added in version 1.0.0.

Added in version 1.1.12: The highlight_spec parameter

See also

plot_interactive_3D()

general function for plotting

plot_3D_schematic()

for plotting only segmeng groups with their labels

Parameters:
  • offset ((float, float, float) or None) – offset for cell Note that this is only used in creating the meshdata. If set to None, this is ommitted from the meshdata, and the mesh creator will set it to origin.

  • cell (neuroml.Cell) – cell to plot

  • color (str) –

    color to use for segments, with some special values:

    • if a color string is given, use that

    • if None, each segment is given a new unique color

    • if “Groups”, each unbranched segment group is given a unique color, and segments that do not belong to an unbranched segment group are in white

    • if “Default Groups”, axonal segments are in red, dendritic in blue, somatic in green, and others in white

  • min_width (float) – minimum width for segments (useful for visualising very

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

  • axes_pos ((float, float, float) or None or str) –

    add x, y, z axes centered at given position with colours red, green, blue for x, y, z axis respecitvely.

    A few special values are supported:

    • None: disable axes (default)

    • ”origin”: automatically added at origin

    • ”bottom left”: automatically added at bottom left

  • title (str) – title of plot

  • verbose (bool) – show extra information (default: False)

  • nogui (bool) – do not show image immediately

  • current_canvas (scene.SceneCanvas) – vispy scene.SceneCanvas to use (a new one is created if it is not provided)

  • current_view (ViewBox) – vispy viewbox to use

  • plot_type (str) –

    type of plot, one of:

    • ”detailed”: show detailed morphology taking into account each segment’s width.

    • ”constant”: show morphology, but use min_width for line widths; the soma is made 5 times thicker to make it easier to see.

    This is only applicable for neuroml.Cell cells (ones with some morphology)

  • theme (str) – theme to use (dark/light)

  • meshdata (list) – list used to store mesh related data for vispy visualisation

  • highlight_spec (dict) –

    dictionary that allows passing some specifications to allow highlighting of particular elements. Mostly only helpful for marking segments on multi-compartmental cells. In the main dictionary are more dictionaries, one for each segment id which will be the key:

    • marker_color: color of the marker

    • marker_size: [diameter 1, diameter 2] (in case of sphere, the first value is used)

    • marker_type: “sphere” (otherwise the default shape of the segment is used, which could either be a sphere or a cylinder)

  • upright (bool) – bool only applicable for single cells: Makes cells “upright” (along Y axis) by calculating its PCA, rotating it so it is along the Y axis, and transforming cell co-ordinates to align along the rotated first principal component. If the rotation around the z axis needed is < 0, then the cell is rotated an additional 180 degrees. This is empirically found to rotate the cell “upwards” instead of “downwards” in most cases. Note that the original cell object is unchanged, this is for visualization purposes only.

  • save_mesh_to (str or None) – name of file to save mesh object to

Returns:

meshdata

Raises:

ValueError if cell is None

pyneuroml.plot.PlotMorphologyVispy.plot_3D_schematic(cell: Cell, segment_groups: List[SegmentGroup] | None = None, offset: Tuple[float, float, float] | None = (0.0, 0.0, 0.0), labels: bool = False, width: float = 1.0, verbose: bool = False, nogui: bool = False, title: str = '', current_canvas: SceneCanvas | None = None, current_view: ViewBox | None = None, axes_pos: Tuple[float, float, float] | Tuple[int, int, int] | str | None = None, theme: str = 'light', color: str | None = 'Cell', meshdata: List[Any] | None = None, upright: bool = False, save_mesh_to: str | None = None) List[Any] | None#

Plot a 3D schematic of the provided segment groups using vispy. layer..

This plots each segment group as a straight line between its first and last segment.

Added in version 1.0.0.

See also

plot_2D_schematic()

general function for plotting

plot_2D()

general function for plotting

plot_2D_point_cells()

for plotting point cells

plot_2D_cell_morphology()

for plotting cells with detailed morphologies

Parameters:
  • offset ((float, float, float) or None) – offset for cell Note that this is only used in creating the meshdata. If set to None, this is ommitted from the meshdata, and the mesh creator will set it to origin.

  • cell (neuroml.Cell) – cell to plot

  • segment_groups (list(SegmentGroup)) – list of unbranched segment groups to plot, all if None

  • labels (bool) – toggle labelling of segment groups

  • width (float) – width for lines for segment groups

  • verbose (bool) – show extra information (default: False)

  • title (str) – title of plot

  • nogui (bool) – toggle if plot should be shown or not

  • current_canvas (scene.SceneCanvas) – vispy scene.SceneCanvas to use (a new one is created if it is not provided)

  • current_view (ViewBox) – vispy viewbox to use

  • axes_pos ((float, float, float) or (int, int, int) or None or str) –

    add x, y, z axes centered at given position with colours red, green, blue for x, y, z axis respecitvely.

    A few special values are supported:

    • None: disable axes (default)

    • ”origin”: automatically added at origin

    • ”bottom left”: automatically added at bottom left

  • theme (str) – theme to use (light/dark)

  • color (str) –

    color to use for segment groups with some special values:

    • if None, each unbranched segment group is given a unique color,

    • if “Cell”, the whole cell is given one color

    • if “Default Groups”, each cell is given unique colors for all axons, dendrites, and soma segments

  • meshdata (dict) – dictionary used to store mesh related data for vispy visualisation

  • upright (bool) – bool only applicable for single cells: Makes cells “upright” (along Y axis) by calculating its PCA, rotating it so it is along the Y axis, and transforming cell co-ordinates to align along the rotated first principal component. If the rotation around the z axis needed is < 0, then the cell is rotated an additional 180 degrees. This is empirically found to rotate the cell “upwards” instead of “downwards” in most cases. Note that the original cell object is unchanged, this is for visualization purposes only.

  • save_mesh_to (str or None) – name of file to save mesh object to

Returns:

meshdata

pyneuroml.plot.PlotMorphologyVispy.plot_interactive_3D(nml_file: str | Cell | Morphology | NeuroMLDocument, min_width: float = 0.8, verbose: bool = False, plot_type: str = 'detailed', axes_pos: Tuple[float, float, float] | Tuple[int, int, int] | str | None = None, title: str | None = None, theme: str = 'light', nogui: bool = False, plot_spec: PlotSpec | None = None, highlight_spec: Dict[Any, Any] | None = None, upright: bool = False, save_mesh_to: str | None = None)#

Plot interactive plots in 3D using Vispy

https://vispy.org

Note that on Linux systems using Wayland, one may need to set the environment variable for PyOpenGL to work correctly:

QT_QPA_PLATFORM=wayland-egl

Added in version 1.1.12: The highlight_spec parameter

If a file with a network containing multiple cells is provided, it will plot all the cells. For detailed neuroml.Cell types, it will plot their complete morphology. For point neurons, we only plot the points (locations) where they are as spheres. For single cell SWC files, it will first convert them to NeuroML and then plot them.

Parameters:
  • nml_file (str or neuroml.NeuroMLDocument or neuroml.Cell or neuroml.Morphology) – path to NeuroML cell file or single cell SWC file or neuroml.NeuroMLDocument or neuroml.Cell or neuroml.Morphology object

  • min_width (float) – minimum width for segments (useful for visualising very thin segments): default 0.8um

  • verbose (bool) – show extra information (default: False)

  • plot_type (str) –

    type of plot, one of:

    • ”detailed”: show detailed morphology taking into account each segment’s width

    • ”constant”: show morphology, but use “min_width” for line widths; the soma is made thicker to make it easy to see

    • ”schematic”: only plot each unbranched segment group as a straight line, not following each segment

    • ”point”: show all cells as points

    This is only applicable for neuroml.Cell cells (ones with some morphology)

  • axes_pos ((float, float, float) or (int, int, int) or None or str) –

    add x, y, z axes centered at given position with colours red, green, blue for x, y, z axis respecitvely.

    A few special values are supported:

    • None: disable axes (default)

    • ”origin”: automatically added at origin

    • ”bottom left”: automatically added at bottom left

  • title (str) – title of plot

  • theme (str) – theme to use (light/dark)

  • nogui (bool) – toggle showing gui (for testing only)

  • plot_spec (dict) –

    dictionary that allows passing some specifications that control how a plot is generated. This is mostly useful for large network plots where one may want to have a mix of full morphology and schematic, and point representations of cells. Possible keys are:

    • point_fraction: what fraction of each population to plot as point cells: these cells will be randomly selected

    • points_cells: list of cell ids to plot as point cells

    • schematic_cells: list of cell ids to plot as schematics

    • constant_cells: list of cell ids to plot as constant widths

    • detailed_cells: list of cell ids to plot in full detail

    The lists override the point_fraction setting. If a cell id is not included in the spec here, it will follow the plot_type provided before.

  • highlight_spec (dict) –

    dictionary that allows passing some specifications to allow highlighting of particular elements. Only used when plotting multi-compartmental cells for marking segments on them (“plot_type” is “detailed”, since for “constant” min_width is always used.)

    Each key in the dictionary will be of the cell id and the values will be a “cell_color” or more dictionaries, with the segment id as key and the following keys in it:

    • marker_color: color of the marker

    • marker_size: [diameter 1, diameter 2] (in case of sphere, the first value is used)

    • marker_type: “sphere” (otherwise the default shape of the segment is used, which could either be a sphere or a cylinder)

    E.g.:

    {
        "cell id1": {
        "cell_color": "red",
            "seg id1": {
                "marker_color": "blue",
                "marker_size": [0.1, 0.1],
                "marker_type": "sphere"
            }
        }
    }
    

    The cell_color can be one of:

    Please see the function docstrings for more information.

  • upright (bool) – bool only applicable for single cells: Makes cells “upright” (along Y axis) by calculating its PCA, rotating it so it is along the Y axis, and transforming cell co-ordinates to align along the rotated first principal component. If the rotation around the z axis needed is < 0, then the cell is rotated an additional 180 degrees. This is empirically found to rotate the cell “upwards” instead of “downwards” in most cases. Note that the original cell object is unchanged, this is for visualization purposes only.

  • save_mesh_to (str or None) – name of file to save mesh object to

Throws ValueError:

if plot_type is not one of “detailed”, “constant”, “schematic”, or “point”

Throws TypeError:

if model is not a NeuroML file path, nor a neuroml.Cell, nor a neuroml.NeuroMLDocument

Throws AttributeError:

if upright=True for non single-cell models

pyneuroml.plot.PlotMorphologyPlotly module#

Methods to plot morphology using Plot.ly

Note: the vispy methods are more performant.

File: pyneuroml/plot/PlotMorphologyPlotly.py

Copyright 2023 NeuroML contributors

pyneuroml.plot.PlotMorphologyPlotly.plot_3D_cell_morphology_plotly(nml_file: str | Cell | NeuroMLDocument, min_width: float = 0.8, verbose: bool = False, nogui: bool = False, save_to_file: str | None = None, plot_type: str = 'detailed')#

Plot NeuroML2 cell morphology interactively using Plot.ly

Please note that the interactive plot uses Plotly, which uses WebGL. So, you need to use a WebGL enabled browser, and performance here may be hardware dependent.

https://plotly.com/python/webgl-vs-svg/ https://en.wikipedia.org/wiki/WebGL

Parameters:
  • nml_file (str or neuroml.NeuroMLDocument or neuroml.Cell) – path to NeuroML cell file, or a neuroml.NeuroMLDocument or neuroml.Cell object

  • min_width (float) – minimum width for segments (useful for visualising very thin segments): default 0.8um

  • verbose (bool) – show extra information (default: False)

  • nogui (bool) – do not show matplotlib GUI (default: false)

  • save_to_file (str) – optional filename to save generated morphology to

  • plot_type (str) –

    type of plot, one of:

    • detailed: show detailed morphology taking into account each segment’s width

    • constant: show morphology, but use constant line widths