Cell#

class braincell.Cell(morpho, *, pop_size=(), cv_policy=None, V_th=Quantity(0, 'mV'), V_init=None, spk_fun=ReluGrad(alpha=0.3, width=1.0), solver='staggered', cache_ion_total_current=True, ion_channel_update_order='family', name=None)#

Multi-compartment cell with explicit declaration / initialization phases.

Parameters:
  • morpho (Morphology) – Morphology tree.

  • cv_policy (CVPolicy | None) – Control-volume splitting policy; defaults to CVPerBranch.

  • V_th (Quantity) – Spike-detection threshold (default 0. mV).

  • V_init (Array | ndarray | bool | number | bool | int | float | complex | Quantity | Callable | None) – Initial voltage. None means “use per-CV resting potential”.

  • spk_fun (Callable) – Surrogate-gradient spike function.

  • solver (str | Callable) – Integrator name (registry lookup) or callable step function.

  • ion_channel_update_order (str) – Post-voltage ion/channel scheduling. "family" updates all ions before all channels; "integration" preserves the previous IndependentIntegration-grouped scheduling.

  • name (str | None) – Cell name.

bind_synapse_input(synapse, source, *, weight=1.0, transform=None)[source]#

Bind an external presynaptic drive source to a runtime synapse.

Parameters:
  • synapse (str) – Synapse instance name, matching braincell.mech.Synapse(name=...) or its default instance name.

  • source (array-like or callable) – Presynaptic drive source. Callables are evaluated every step; this supports bindings such as lambda: pre_cell.spike.value.

  • weight (array-like, optional) – Multiplicative weight applied to source.

  • transform (callable, optional) – Optional mapping called as transform(source_value) before weighting, useful when the source shape does not directly broadcast to the target synapse shape.

Return type:

Cell

cache_ion_total_currents(V=None)[source]#

Cache ion source currents before voltage advances in staggered mode.

Return type:

None

clear_ion_total_current_cache()[source]#

Remove per-step ion source-current caches.

Return type:

None

compute_derivative()[source]#

Compute the derivative of the state variables for the ion channel.

This method calculates the rate of change of the state variables associated with the ion channel. It is an abstract method that must be implemented by subclasses to provide specific behavior for each type of ion channel.

Parameters:
  • *args – Variable length argument list. Specific arguments should be defined in the subclass implementation.

  • **kwargs – Arbitrary keyword arguments. Specific keyword arguments should be defined in the subclass implementation.

Raises:

NotImplementedError – This method must be implemented by subclasses.

Notes

Subclasses should override this method to implement the specific equations governing the dynamics of the ion channel. The implementation should calculate how the state variables change over time based on the current state and any input parameters.

init_state(batch_size=None)[source]#

Lower the declaration into runtime state and allocate V / spike.

Raises:

RuntimeError – If the cell is already initialized. Call reset() first.

Return type:

None

property n_compartment: int#

Get the number of compartments in the neuron group.

This property represents the number of distinct compartments within each neuron in the group. Compartments are typically used to model different sections of a neuron, such as the soma, dendrites, and axon.

Returns:

The number of compartments in each neuron of the group.

Return type:

int

Raises:

NotImplementedError – This method is not implemented in the base class and must be implemented by subclasses.

property name: str | None#

Name of the model.

paint(region, *mechanisms)[source]#

Paint mechanisms onto region. Returns self for chaining.

Return type:

Cell

place(locset, *mechanisms)[source]#

Place point mechanisms at locset. Returns self for chaining.

Return type:

Cell

property pop_size: tuple[int, ...]#

Get the population size of the neuron group.

This property returns the size of the neuron population, which represents the number of neurons in each dimension of the group.

Returns:

A tuple of integers representing the population size in each dimension. For example, (100, 50) would represent a 2D population with 100 neurons in the first dimension and 50 in the second.

Return type:

Tuple[int, …]

Raises:

NotImplementedError – This method is not implemented in the base class and must be implemented by subclasses.

post_integral()[source]#

Perform any necessary operations after the integral step in the simulation.

This method is called after the integration of the differential equations in each time step. For the neuron model, this typically corresponds to the update() function, where state variables are updated based on the results of the integration.

Parameters:
  • *args – Variable length argument list. Specific arguments should be defined in the subclass implementation.

  • **kwargs – Arbitrary keyword arguments. Specific keyword arguments should be defined in the subclass implementation.

Notes

Subclasses should override this method to implement any necessary operations that need to be performed after the integration step, such as updating membrane potentials, ion concentrations, or other state variables of the neuron model.

pre_integral()[source]#

Perform any necessary operations before the integral step in the simulation.

This method is called before the integration of the differential equations in each time step. It allows for any preprocessing or setup required before the actual integration occurs.

Parameters:
  • *args – Variable length argument list. Specific arguments should be defined in the subclass implementation.

  • **kwargs – Arbitrary keyword arguments. Specific keyword arguments should be defined in the subclass implementation.

Raises:

NotImplementedError – This method must be implemented by subclasses to provide specific pre-integration behavior.

Notes

Subclasses should override this method to implement any necessary operations that need to be performed before the integration step. This could include updating certain variables, checking conditions, or preparing data for the integration process.

reset()[source]#

Drop runtime and per-step state; return to DECLARING.

Raises:

RuntimeError – If the cell is not initialized.

Return type:

None

Notes

reset() is distinct from reset_state(). reset_state reseeds V / spike / current_time in place and stays in the INITIALIZED phase. reset() fully tears down the runtime and returns to DECLARING so paint / place can run again.

reset_state(batch_size=None)[source]#

Reseed V / spike / current_time without leaving INITIALIZED.

Distinct from reset(): reset_state is the in-phase brainstate lifecycle hook; reset tears down the runtime entirely and returns the cell to DECLARING.

Return type:

None

run(*, dt, duration)[source]#

Run the cell for duration at dt and return probe traces.

If init_state() has not been called yet, run calls it automatically. Once initialized the cell will not be re-initialized on subsequent run invocations.

runtime_objects(*args, **kwargs)[source]#

Return runtime graph objects from the inherited container API.

update()[source]#

Advance the cell by one simulation step.

This method is the standalone cell-level step wrapper. It applies already-prepared synaptic events, advances continuous membrane and mechanism dynamics by one dt, computes the spike output, and prepares synaptic input for the next standalone step.

Returns:

Spike value produced by the transition from the previous membrane voltage to the updated membrane voltage.

Return type:

object

Notes

The standalone update order is:

  1. Apply prepared runtime synapse events.

  2. Advance voltage and mechanism dynamics through self.solver.

  3. Detect and store the current spike.

  4. Prepare pre_spike inputs for the next step.

In network execution, delayed event delivery is scheduled outside the cell. Network.run(...) writes arrivals into runtime state buffers before calling the corresponding internal cell phases.

property varshape: tuple[int, ...]#

Get the shape of variables in the neuron group.

This property provides access to the geometry (shape) of the neuron population, which determines how variables and states are structured.

Returns:

A tuple representing the dimensional shape of the neuron group, matching the in_size parameter provided during initialization.

Return type:

tuple

See also

in_size

The input geometry specification for the neuron group

vis_branch(*, preset='dendrotweaks', layout=None, layout_scale=1.0, region=None, coverage_mode='fraction', highlight_color='#ef4444', node_color=None, edge_color=None, root_color=None, ax=None, show=True)[source]#

Visualize the cell at the branch topology level.

Cell.vis_branch(...) renders one node per morphology branch. This view is intended for topology and region coverage inspection rather than runtime-value inspection.

Parameters:
  • preset (str) – Name of the built-in topology preset.

  • layout (str | None) – Explicit layout algorithm override.

  • layout_scale (float) – Global spacing multiplier for the resolved layout.

  • region (RegionExpr | RegionMask | None) – Region used to compute per-branch coverage.

  • coverage_mode (str) – Coverage display rule. "fraction" blends by overlap fraction, "any" highlights any overlap fully, and "all" only highlights fully covered branches.

  • highlight_color (str) – Highlight colour used in coverage mode.

  • node_color (str | None) – Base style colour overrides.

  • edge_color (str | None) – Base style colour overrides.

  • root_color (str | None) – Base style colour overrides.

  • ax (matplotlib.axes.Axes or None, optional) – Destination axes. When None, a fresh figure and axes are created.

  • show (bool) – If True (default), call matplotlib.pyplot.show() after rendering.

Returns:

The rendered Matplotlib axes.

Return type:

object

Raises:

ValueError – If an invalid coverage configuration is supplied by the low-level renderer.

Notes

This view is topology-only and does not support value-based colormaps. Each branch is represented by one node.

See also

vis_node

Render the full runtime node topology.

vis_cv

Render one node per control volume.

vis_topology

Thin dispatcher over the available topology levels.

Examples

Render partial branch coverage:

>>> ax = cell.vis_branch(region=some_region, show=False)
vis_cv(*, preset='dendrotweaks', layout=None, layout_scale=1.0, region=None, locset=None, coverage_mode='fraction', highlight_color='#ef4444', value=None, cmap=None, vmin=None, vmax=None, norm=None, value_label=None, show_colorbar=True, node_color=None, edge_color=None, root_color=None, ax=None, show=True)[source]#

Visualize the cell at the control-volume topology level.

Cell.vis_cv(...) renders one node per control volume. It shares the same high-level selector model as vis_node(), but collapses the view to CV granularity.

Parameters:
  • preset (str) – Name of the built-in topology preset.

  • layout (str | None) – Explicit layout algorithm override.

  • layout_scale (float) – Global spacing multiplier for the resolved layout.

  • region (RegionExpr | RegionMask | None) – Region used to compute per-CV coverage.

  • locset (LocsetExpr | LocsetMask | None) – Discrete morphology locations to highlight. Each location is mapped to its owning CV.

  • coverage_mode (str) – Coverage display rule. "fraction" blends by overlap fraction, "any" highlights any overlap fully, and "all" only highlights fully covered CVs.

  • highlight_color (str) – Highlight colour used in coverage mode.

  • value (object, optional) – CV colouring source. Supports the same high-level selector forms as vis_node().

  • cmap (str | None) – Matplotlib colormap name used in value mode.

  • vmin (float | None) – Explicit lower and upper bounds for the value colormap.

  • vmax (float | None) – Explicit lower and upper bounds for the value colormap.

  • norm (matplotlib.colors.Normalize or None, optional) – Explicit normalization object for value mode.

  • value_label (str | None) – Colorbar label override.

  • show_colorbar (bool) – If True (default), draw a colorbar in value mode.

  • node_color (str | None) – Base style colour overrides.

  • edge_color (str | None) – Base style colour overrides.

  • root_color (str | None) – Base style colour overrides.

  • ax (matplotlib.axes.Axes or None, optional) – Destination axes. When None, a fresh figure and axes are created.

  • show (bool) – If True (default), call matplotlib.pyplot.show() after rendering.

Returns:

The rendered Matplotlib axes.

Return type:

object

Raises:

ValueError – If the cell has no unique root CV, or if value is combined with region / locset.

Notes

Each CV is represented by one node. region / locset and value remain mutually exclusive in v1.

See also

vis_node

Render the lower-level runtime node topology.

vis_branch

Render the higher-level morphology branch topology.

vis_topology

Thin dispatcher over the available topology levels.

Examples

Highlight a region at CV level:

>>> ax = cell.vis_cv(region=some_region, show=False)

Colour CVs by voltage:

>>> ax = cell.vis_cv(value="V", cmap="viridis", show=False)
vis_node(*, preset='dendrotweaks', layout=None, layout_scale=1.0, region=None, locset=None, coverage_mode='fraction', highlight_color='#ef4444', value=None, cmap=None, vmin=None, vmax=None, norm=None, value_label=None, show_colorbar=True, node_color=None, edge_color=None, root_color=None, ax=None, show=True)[source]#

Visualize the runtime node tree with cell-aware inputs.

Cell.vis_node(...) is the high-level node-tree entry point. It resolves region / locset selections against the cell’s morphology and CVs, maps those selections to runtime midpoint points, and can also colour points by runtime state such as voltage or mechanism parameters.

Parameters:
  • preset (str) – Name of the built-in point-topology preset.

  • layout (str | None) – Explicit layout algorithm override.

  • layout_scale (float) – Global spacing multiplier for the resolved layout.

  • region (RegionExpr | RegionMask | None) – Continuous morphology selection to highlight. In v1, selected CVs are mapped to their midpoint point ids only.

  • locset (LocsetExpr | LocsetMask | None) – Discrete morphology locations to highlight. In v1, each location is mapped to the CV midpoint point that owns the location.

  • coverage_mode (str) – Coverage display rule for region. Locset-backed highlights are always treated as full intensity.

  • highlight_color (str) – Colour used for highlighted points.

  • value (object, optional) –

    Point colouring source. Supported forms are:

    • point-space array of length n_point

    • CV-space array of length n_cv (scattered to point space)

    • "V" or "voltage"

    • ("ion", ion_name, field)

    • ("channel", class_name, field)

    • ("layout_id", layout_id, field)

    value is mutually exclusive with region / locset in v1.

  • cmap (str | None) – Matplotlib colormap name used in value mode.

  • vmin (float | None) – Explicit lower and upper bounds for the value colormap.

  • vmax (float | None) – Explicit lower and upper bounds for the value colormap.

  • norm (matplotlib.colors.Normalize or None, optional) – Explicit normalization object for value mode.

  • value_label (str | None) – Colorbar label override. When None, certain named value selectors infer a label automatically.

  • show_colorbar (bool) – If True (default), draw a colorbar in value mode.

  • node_color (str | None) – Base style colour overrides.

  • edge_color (str | None) – Base style colour overrides.

  • root_color (str | None) – Base style colour overrides.

  • ax (matplotlib.axes.Axes or None, optional) – Destination axes. When None, a fresh figure and axes are created.

  • show (bool) – If True (default), call matplotlib.pyplot.show() after rendering.

Returns:

The rendered Matplotlib axes.

Return type:

object

Raises:
  • RuntimeError – If the cell is not initialized.

  • ValueError – If value is combined with region or locset, or if a supplied value source cannot be mapped into point space.

Notes

Highlight mode and value mode are mutually exclusive in v1. Region and locset mappings use CV midpoint semantics to stay consistent with the current runtime lowering model.

Examples

Highlight a region:

>>> ax = cell.vis_node(region=some_region, show=False)

Colour nodes by voltage:

>>> ax = cell.vis_node(value="V", cmap="viridis", show=False)

Colour nodes by a channel parameter:

>>> ax = cell.vis_node(value=("channel", "IL", "g_max"), show=False)
vis_topology(*, level='node', preset='dendrotweaks', layout=None, layout_scale=1.0, region=None, locset=None, coverage_mode='fraction', highlight_color='#ef4444', value=None, cmap=None, vmin=None, vmax=None, norm=None, value_label=None, show_colorbar=True, node_color=None, edge_color=None, root_color=None, ax=None, show=True)[source]#

Dispatch to one of the topology visualization levels.

This is a thin wrapper around vis_node(), vis_cv(), and vis_branch(). It lets callers select

a topology level dynamically while keeping one stable entry point.

Parameters:
  • level (str) – Topology abstraction level to render.

  • preset (str) – Name of the built-in topology preset.

  • layout (str | None) – Explicit layout algorithm override.

  • layout_scale (float) – Global spacing multiplier for the resolved layout.

  • region (RegionExpr | RegionMask | None) – Region selection used for highlighting / coverage.

  • locset (LocsetExpr | LocsetMask | None) – Discrete location selection. Supported by level="node" and level="cv" only.

  • coverage_mode (str) – Coverage display rule for region-based highlighting.

  • highlight_color (str) – Highlight colour used for selected nodes.

  • value (object, optional) – Runtime value selector. Supported by level="node" and level="cv" only.

  • cmap (str | None) – Matplotlib colormap name used in value mode.

  • vmin (float | None) – Explicit lower and upper bounds for the value colormap.

  • vmax (float | None) – Explicit lower and upper bounds for the value colormap.

  • norm (matplotlib.colors.Normalize or None, optional) – Explicit normalization object for value mode.

  • value_label (str | None) – Colorbar label override for value mode.

  • show_colorbar (bool) – If True (default), draw a colorbar in value mode.

  • node_color (str | None) – Base style colour overrides.

  • edge_color (str | None) – Base style colour overrides.

  • root_color (str | None) – Base style colour overrides.

  • ax (matplotlib.axes.Axes or None, optional) – Destination axes. When None, a fresh figure and axes are created.

  • show (bool) – If True (default), call matplotlib.pyplot.show() after rendering.

Returns:

The rendered Matplotlib axes.

Return type:

object

Raises:

ValueError – If level is invalid, or if branch-level rendering is given parameters that are only supported by node/CV value modes.

See also

vis_node

Render the full runtime node topology.

vis_cv

Render one node per control volume.

vis_branch

Render one node per morphology branch.

Examples

Render node topology:

>>> ax = cell.vis_topology(level="node", show=False)

Render CV topology:

>>> ax = cell.vis_topology(level="cv", show=False)

Render branch topology:

>>> ax = cell.vis_topology(level="branch", show=False)