Slices and synapse slots#
Python module dendra.models.slice.
The user-facing semantics, including indexing, mutation, labels, batching, rebuilds, and repeated-index behavior, are defined in The Slice contract.
Slice#
- class Slice(model, index_spec, base_shape=None, parent_slice=None, *, root_model=None, module_path=(), relative_index_spec=None)[source]#
Bases:
objectIndexed view onto a subset of a
dendra.models.core.Population.Overview#
A
Populationrepresents a collection of neuronal compartments arranged in a tensorshape(e.g.(n_cells, n_compartments)). Indexing a population with any valid NumPy / PyTorch key (integers, slices, ellipses, boolean masks, integer arrays, or tuples thereof) returns aSlicerather than a raw tensor:pop = Population(...) # Basic indexing soma = pop[:, 0] # first compartment of every cell first_ten = pop[:10] # first 10 cells distal = pop[:, 5:] # distal compartments # Advanced / fancy indexing subset = pop[[0, 3, 7]] # pick specific cells masked = pop[cell_mask] # boolean-mask selection
The
Sliceobject is a lightweight, logical view that:Stores an owned
IndexSpecdescribing the selection.Provides methods for reading and writing model and mechanism state restricted to that selection.
Supports targeted intracellular current injections via
inject().Restricts mechanism insertion and removal to that subset via
insert(),delete(), anddelete_all().Can itself be sliced again; see Nested slices below.
Importantly, a
Slicedoes not own any numerical state. All tensors and parameters remain stored on the underlying population or mechanisms.Slicemerely routes reads and writes through the correct indices.Creating slices#
Slices are created by indexing any
Sliceableobject, typically andendra.models.core.Population:# Standard Python / NumPy semantics pop = Population(...) soma = pop[:, 0] # select soma compartment dend = pop[:, 1:] # all dendritic compartments middle = pop[:, 2:4] # compartments 2 and 3 # Explicit tuples of indices are also supported band = pop[(slice(None), slice(2, 6))]
Advanced indexing mixes are handled by delegating to PyTorch’s indexing rules.
Nested slices (slices of slices)#
Applying further indexing to an existing
Slicereturns anotherSlicecorresponding to the composition of the two selections:distal = pop[:, 5:] distal_mid = distal[:, 2:4] # Equivalent direct selection on the population direct = pop[:, 7:9] assert torch.allclose(distal_mid.v, direct.v)
Internally,
compose_indices()is used to compute an equivalent index into the original population. It materialises an integer coordinate map, but never materialises or copies the population state itself.Reading state:
inspect()andget()#Use
inspect()(or its aliasget()) to read variables restricted to the slice:# Read a model-level buffer/parameter v_soma = pop[:, 0].get("v") # membrane voltage in the soma # Read a mechanism field m_gate = pop[:, 0].get("m", mechanism="NaTs2t")
When the target is stored sparsely (e.g. keyed mechanisms), the slice will internally materialise a dense tensor, index it, and return the selected subset.
Attribute-style access#
For common cases, you can also rely on attribute access instead of calling
get()explicitly. TheSliceintercepts attribute access and returns a sliced snapshot of buffers and parameters, or a retained Slice wrapper for submodules:# Sliced buffer access v_soma = pop[:, 0].v # Equivalent to: # v_soma = pop[:, 0].get("v") # Sliced mechanism access through the mechanism submodule m_gate = pop[:, 0].mech.NaTs2t.m # Equivalent to: # m_gate = pop[:, 0].get("m", mechanism="NaTs2t")
This attribute-style syntax is often the most concise way to work with subsets of state.
Writing state:
set()and attribute assignment#To modify state only on the selected compartments, use
set():soma = pop[:, 0] soma.set("v", torch.full(soma.shape, -65.0, device=pop.device()))
If the target is registered as a buffer on the underlying PyTorch module, you can also write via attribute assignment on the
Slice:# Assuming ``v`` is a registered buffer on ``pop`` soma.v = torch.full(soma.shape, -65.0, device=pop.device())
Both pathways validate the complete update first, then copy it under
torch.no_grad(). Registered tensor identity, dtype, device and unrelated entries are preserved.Current injection:
inject()#inject()registers an intracellular current waveform that should be applied only to the compartments in this slice during simulation:soma = pop[:, 0] soma.inject(step_current)
Here
step_currentis anyWaveformobject understood by the population’s injection machinery. The slice records both the waveform and theIndexSpecso that the solver can apply the current to the correct subset at run time.Mechanism insertion:
insert()#Mechanisms (ion channels, synapses, etc.) can be inserted only on a selected subset of compartments by calling
insert()on a slice:soma = pop[:, 0] soma.insert("NaTs2t", alias="Na_soma")
Only the compartments included in the slice will host the mechanism. All other compartments in the population are unaffected. Any additional keyword arguments are forwarded to the underlying
Population.insertcall.Labelling slices:
label()#Often it is convenient to name a particular subset once and reuse it throughout a model or experiment.
label()attaches a name to a slice and exposes it as an attribute on the owning population (or on the parent slice, if labelling a nested view):# Define labels pop[:, 0].label("soma") pop[:, 1:].label("dendrites") # Later, possibly in a different module: pop.soma.inject(step_current) pop.dendrites.set( "g", torch.full(pop.dendrites.shape, 1e-4), # S/cm² mechanism="pas", )
Labels are also stored in
population._labels(a simpledict), allowing programmatic access viapopulation._labels["soma"].- index_spec#
Canonicalised description of the selection (index, shape, scalar flag).
- Type:
IndexSpec
Notes
A
Sliceowns no simulation state. Read operations deliberately return non-aliasing tensor snapshots, while writes mutate the registered state on the owning model through the explicit Slice mutation contract.- property model#
Live population or submodule wrapped by this Slice.
- property base_shape#
Current logical shape of the owning population.
- property index: Tuple[int | bool | slice | ndarray | Tensor | list | tuple | EllipsisType | None, ...]#
Stable tuple index describing this slice in the current model layout.
- property flat_index: LongTensor#
Return selected locations as population-flat integer indices.
The result is always a one-dimensional
torch.longtensor on the population’s device. Its order and multiplicity match the flattened Slice result, so scalar selections contain one index, empty selections contain none, and repeated selections retain their repeats. A fresh tensor is materialized on every access and may be sampled, permuted, or otherwise modified without changing this Slice. Access materializes an integer grid with one entry per location in the logical population.
- property is_scalar: bool#
Whether the selection is scalar-valued (no remaining dimensions).
- property name: str#
Name of the underlying population (delegated from
model.name).
- property is_empty: bool#
Return
Trueif this slice selects no elements.
- inspect(var, mechanism=None)[source]#
Return a non-aliasing snapshot of
varconstrained to the slice.This is the main low-level accessor for reading model or mechanism state. It honours any sparse/keyed storage used by mechanisms and returns a value whose leading dimensions correspond to this slice.
- Parameters:
var (str) – Attribute name to inspect. This may refer to a model-level buffer or parameter (e.g.
"v"), or to a mechanism field such as a gating variable.mechanism (str or None, optional) – Mechanism identifier when querying mechanism state. If
None,varis looked up directly on the wrappedmodel.
- Returns:
Snapshot of the requested spatial tensor with shape
shape. Global and non-spatial tensors raiseValueError.- Return type:
Any
Examples
Read membrane voltage in the soma:
soma = pop[:, 0] v_soma = soma.inspect("v") # shape == soma.shape
Read a mechanism state variable:
m_gate = soma.inspect("m", mechanism="NaTs2t")
- get(var, mechanism=None)[source]#
Convenience alias for
inspect()returning a tensor snapshot.This method simply forwards to
inspect()and is provided for readability in user code that predominantly deals with tensor-valued variables.- Parameters:
var (str) – Attribute name to read.
mechanism (str or None, optional) – Mechanism identifier when querying mechanism state.
- Returns:
Non-aliasing tensor snapshot restricted to the slice.
- Return type:
torch.Tensor
Examples
v_soma = pop[:, 0].get("v") m_gate = pop[:, 0].get("m", mechanism="NaTs2t")
- set(var, value, mechanism=None)[source]#
Write
valueintovarconstrained to the slice.This is the main low-level mutator for updating state on a subset of compartments. The complete update is validated before an in-place copy under
torch.no_grad(). Registered buffer or Parameter identity, dtype, device and unrelated entries are preserved.- Parameters:
var (str) – Attribute name to mutate. May refer to a model-level buffer or parameter, or to a mechanism field.
value (torch.Tensor) – Tensor data to assign. Its shape must be broadcastable to the slice’s
shape.mechanism (str or None, optional) – Mechanism identifier when writing mechanism state. If provided, the appropriate mechanism’s storage is updated; otherwise the attribute is looked up on the wrapped
model.
Examples
Set the soma voltage to a constant:
soma = pop[:, 0] target = torch.full(soma.shape, -65.0, device=pop.device()) soma.set("v", target)
Modify a mechanism gating variable:
soma.set("m", new_m_values, mechanism="NaTs2t")
- inject(waveform)[source]#
Register an intracellular current waveform targeting this slice.
The waveform is not applied immediately. Instead, this method records the tuple
(waveform, index_spec.shape, index_spec.index)on the underlying population’sinjectionslist and, when available, on the population’s mechanism-level injection registry. The solver path applies the current to the selected compartments in the usual way, while mechanisms that implementinject(...)can consume the waveform directly.- Parameters:
waveform (Any) –
Waveformobject understood by the population’s injection infrastructure.
Notes
Calling
inject()on an empty slice is a no-op.Examples
soma = pop[:, 0] soma.inject(step_current) # step_current defined elsewhere
- slots(synapse, slot_index=None, *, local_index=None)[source]#
Return synapse-local slots for
synapsethat lie in this slice.Sliceselects physical compartments. For banked point-process mechanisms, multiple independent slots may live on each selected compartment; this method exposes those slots explicitly for network connectivity.
- insert(mechanism, alias=None, ic=None, preserve_duplicate_indices=False, preserve_multiplicity=None, copies=1, **kwargs)[source]#
Insert a mechanism restricted to this slice.
Only the selected compartments will host the inserted mechanism. This method forwards to
model.insertwhile passing along the slice’sIndexSpec, so the underlying population can allocate and wire the mechanism appropriately.- Parameters:
mechanism (Any) – Mechanism class.
alias (str or None, optional) – Optional alias with which the mechanism should be registered on the model. If
None, the default aliasing behaviour ofmodel.insertis used.ic (Any, optional) – Optional initial-condition mapping. It is class-wide because all regions of one mechanism class compile into one mechanism instance.
preserve_duplicate_indices (bool, optional) – If True, duplicate selected compartments are retained as independent mechanism slots. This is useful for colocated point-process banks that should keep separate state while scattering current to the same compartment.
preserve_multiplicity (bool, optional) – User-facing synonym for
preserve_duplicate_indices.copies (int, optional) – Number of independent copies of this insertion region to allocate.
copies > 1implies duplicate preservation.**kwargs – Mechanism parameters forwarded to
model.insert. RANGE/BATCH values apply to this Slice; GLOBAL values are class-wide and must agree across insertion records for the same mechanism class.
Notes
Calling
insert()on an empty slice is a no-op.Examples
soma = pop[:, 0] soma.insert(NaTs2t, alias="Na_soma") # Insert a passive mechanism only in dendrites pop[:, 1:].insert(pas, alias="pas_dend", g=1e-4) # S/cm²
- delete(mechanism, *, strict=False)[source]#
Delete a mechanism class where it intersects this Slice.
- Parameters:
mechanism (type) – Exact mechanism class to remove.
strict (bool, default False) – If True, require every selected physical compartment to host the mechanism and fail atomically otherwise. If False, remove the mechanism only where it is present.
Notes
Overlapping insertion aliases are all cropped, and every copied/duplicate mechanism slot at a selected physical compartment is removed. On a batched population, the Slice is projected onto the shared structural core, so the deletion applies to every batch replica. Calling this method on an empty Slice is a no-op. Reinitialize the population after a successful deletion.
Examples
# Remove pas from dendrites while retaining it in the soma. pop.dendrites.delete(pas) # Remove the class from all remaining compartments. pop.delete(pas)
- delete_all()[source]#
Delete every mechanism class present anywhere in this Slice.
The operation uses physical support-intersection semantics for each exact configured class and is transactional across classes. On a batched Population the structural selection applies to every replica. An empty Slice is a no-op. Reinitialize after a successful deletion.
- parametrize(name, value, alias=None)[source]#
Add or update an alias-specific parameter override on this slice.
This method forwards to
model.parametrizewhile passing along the slice’sIndexSpec, so that only the selected compartments receive the parameter override.- Parameters:
name (str) – Parameter name to override.
value (float, torch.Tensor, torch.nn.Parameter, or torch.nn.Module) – New parameter value.
alias (str or None, optional) – Optional mechanism alias to which the parameter applies. If
None, the parameter is assumed to be a model-level parameter.
Examples
# Override a model-level parameter in the soma pop[:, 0].parametrize("rhoa", 150.0) # Override a mechanism parameter in dendrites # Passive conductance density is expressed in S/cm². pop[:, 1:].mech.pas.parametrize("g", 1e-4, alias="dend")
- label(name, *, replace=False)[source]#
Attach a label to the slice for convenient, reusable access.
This method exposes the slice under the given
nameas an attribute on the owning population (for top-level slices) or on the parent slice (for nested slices). For populations, it also adds an entry to the_labelsdictionary.- Parameters:
name (str) – Non-private Python identifier to use as the label. Existing model attributes and Slice API names are reserved.
replace (bool, optional) – Replace an existing Slice label with the same owner and name. This never permits replacement of a non-label attribute. Defaults to
False.
- Returns:
This Slice, allowing
region = pop[key].label("region").- Return type:
Examples
Label soma and dendrites on a population:
pop[:, 0].label("soma") pop[:, 1:].label("dendrites") # Later, reuse the labels pop.soma.inject(step_current) pop.dendrites.set( "g", torch.full(pop.dendrites.shape, 1e-4), # S/cm² mechanism="pas", )
Labels on nested slices attach to the outer slice:
distal = pop[:, 5:] distal[:, :2].label("distal_proximal") # stored on ``distal`` distal.distal_proximal.set("gNa", 0.0)
- intersect(other)[source]#
Return the physical intersection with another population Slice.
Intersection is deliberately an explicit operation because its shape contract differs from ordinary Slice indexing. At creation, the result is a canonical one-dimensional Slice. It preserves the traversal order and duplicate occurrences of
selfwhile treatingotheras a set of physical compartments. Consequently it never widensselfand duplicates inotherdo not multiply the result. As with any retained Slice, later batching prepends batch axes.Both operands must be population-backed Slices of the same root model. Mechanism-local and cross-population intersections are rejected rather than guessing how their coordinate systems relate.
SynapseSlots#
- class SynapseSlots(model, synapse, local_index, slot_to_flat_index, name=None)[source]#
Explicit selection of local slots inside a point-process mechanism.
A regular
Sliceidentifies physical compartments. That is enough for distributed mechanisms, but a banked point-process mechanism can have several independent local slots attached to the same compartment. ASynapseSlotsobject addresses those local slots directly while retaining their mapping back to parent-population compartments.- classmethod from_region(model, synapse, *, region_index=None, slot_index=None, name=None)[source]#
Create a slot selection from a population region and/or slot index.
slot_indexaddresses the mechanism’s absolute local slot axis. Ifregion_indexis also provided, the selected absolute slots are validated against that population region. Relative selection within an already-created slot view is available throughSynapseSlots.__getitem__.
- property index#
Slot-local indices, provided for endpoint-like introspection.
- property flat_index: LongTensor#
Population-flat compartment index for each selected local slot.
Helpers#
- concat_slices(slices, dim=-1)[source]#
Concatenate multiple
Sliceobjects into a single slice.- Parameters:
slices (Sequence[Slice]) – Slices to concatenate. All slices must wrap the same underlying model and be compatible for concatenation along
dim.dim (int, optional) – Dimension along which to concatenate. If None, concatenates flattened slices. Defaults to
-1.
- Returns:
New
Slicerepresenting the concatenation of the inputs.- Return type:
- Raises:
ValueError – If the input slices wrap different models or are incompatible for concatenation.