Morphology and compartment geometry#
Python module dendra.models.morphology.
Declare sections and their connections with
dn.Morphology. Build a branched
model with dn.Tree.from_morphology
or an unbranched model with
dn.Cable.from_morphology.
Follow the native morphology tutorial for a
complete simulation.
Native morphology declaration#
- class Morphology(*, rhoa=100.0, cm=1.0)[source]#
Mutable section-tree declaration compiled into a
CompartmentGraph.- Parameters:
rhoa (float, optional) – Default intracellular resistivity in Ω·cm.
cm (float, optional) – Default specific membrane capacitance in µF/cm².
- property rhoa: float#
Validated default axial resistivity for subsequently declared Sections.
- property cm: float#
Validated specific-capacitance default for later Sections.
- property swc_section_types: Mapping[str, int]#
Read-only imported SWC type provenance keyed by generated Section.
Manually authored Sections and non-SWC imports have no entry. Pass this mapping explicitly to
to_swc()orwrite_swc()to retain raw type IDs; export never guesses types from names or labels.
- delete_section(section, *, recursive=False)[source]#
Delete one Section or an explicitly requested descendant subtree.
- Parameters:
section (str or Section) – Exact name or canonical Section owned by this Morphology.
recursive (bool, optional) – If false (default), a Section with children is rejected. If true, delete the Section and every descendant connected below it.
- Returns:
Deleted Section names in their original declaration order.
- Return type:
tuple of str
Notes
The complete deletion set is validated before mutation. Deleting the sole root, or recursively deleting a complete tree, is allowed and leaves an empty Morphology that cannot be compiled until a new tree is declared. Surviving Sections retain their identity, declaration order, and connections. Imported SWC type provenance associated with deleted Sections is removed as part of the same transaction.
Deleted Section and SectionLocation objects become stale and are rejected by later authoring operations, even if a new Section reuses a deleted name. Previously compiled graphs and instantiated models are independent snapshots and are not changed.
- update_section(section, *, L=None, diam=None, points=None, nseg=None, rhoa=None, cm=None, labels=None)[source]#
Transactionally update a named Section while preserving its identity.
Parameters use the same units and validation as
section().rhoa,cm, andnsegapply to the complete Section. Stylized Sections may updateLanddiam. A complete pt3d centerline or diameter-profile replacement usespoints; useSectionLocation.update()for one local diameter control point. Passingpointsfor a stylized Section promotes it to pt3d; the reverse pt3d-to-stylized conversion is unsupported by this update API.labelsreplaces the explicit labels, while the Section name remains automatic.Nonemeans unchanged for every optional argument.The canonical Section object and all existing
SectionLocationreferences remain valid. Connections and declaration order are preserved. Previously compiled graphs and instantiated models are immutable snapshots and are not changed by this authoring edit.- Returns:
The same canonical Section object after a successful update.
- Return type:
- apply_d_lambda(*, d_lambda=0.1, freq_hz=100.0)[source]#
Select and apply NEURON-compatible d-lambda compartment counts.
- Parameters:
d_lambda (float, optional) – Positive dimensionless maximum compartment length as a fraction of the AC space constant. Default is
0.1.freq_hz (float, optional) – Positive raw frequency in hertz at which the space constant is evaluated. This is deliberately named
freq_hzbecause Dendra’s ordinary simulation-frequency coordinate is kHz. Default is100.0.
- Returns:
Selected odd
nsegvalues keyed by Section name in original declaration order.- Return type:
dict of str to int
Notes
Every wavelength and compartment count is validated before any Section is modified. The method then updates
nsegin place while preserving Section identity, connections, labels, and declaration order. Existing compiled graphs and instantiated models remain independent snapshots; compile or construct a new model to use the new discretization.The calculation uses the standard AC space-constant estimate and odd-count rounding rule on native stylized or pt3d geometry. It requires no NEURON objects.
- section(name, *, L=None, diam=None, points=None, nseg=1, rhoa=None, cm=None, labels=())[source]#
Declare a stylized cylinder or a pt3d tapered section.
A stylized section requires
Land scalardiam. A pt3d section requires at least two(x, y, z, diameter)points and derives its length from the centerline. The two geometry forms cannot be mixed.- Parameters:
name (str) – Unique, non-empty authored Section identity. The exact name is used for connection bookkeeping and compiled
section_nameprovenance, and is automatically included among the Section’s labels. Section names are reserved: an explicit label on another Section cannot use the same string.L (float, optional) – Stylized-cylinder length in µm. Required with
diamand mutually exclusive withpoints.diam (float, optional) – Stylized-cylinder diameter in µm. Required with
Land mutually exclusive withpoints.points (sequence of (x, y, z, diameter), optional) – At least two pt3d samples in µm. Length is derived from centerline arclength. Consecutive samples may share coordinates only when their diameters differ; this represents an abrupt, zero-arclength diameter step with an annular membrane surface but no length, volume, or axial resistance. The complete Section must retain positive centerline length.
nseg (int, optional) – Positive number of computational compartments. Default is 1.
rhoa (float, optional) – Section intracellular resistivity in Ω·cm. Defaults to the owning Morphology’s value.
cm (float, optional) – Section specific membrane capacitance in µF/cm². Defaults to the owning Morphology’s value.
labels (str or iterable of str, optional) – Reusable structural region tags applied to every material compartment compiled from this Section. Labels may be shared by multiple Sections to form union selections. The Section
nameis added automatically and need not be supplied here.
- Returns:
The declaration owned by this Morphology. Its fields are read-only; use
Section.update()for validated authoring edits.- Return type:
Notes
After constructing a
TreeorCable, collision-free labels that are safe Python identifiers become population-owned Slice attributes. All labels remain available in the compiled graph’s metadata even when an attribute cannot be installed.
- connect(parent, child, *, child_end=None)[source]#
Connect a child endpoint to a parent location.
parentmust be produced byparent_section.at(x).childmay be a Section plus an explicitchild_end, orchild.at(0/1). Interior child locations are rejected because they do not define a section-tree orientation.
- compile()[source]#
Validate and discretize the declared Section tree in binary64.
Pt3d compartments retain exact tapered-frustum membrane area, volume, and axial inverse-area integrals. An abrupt repeated-coordinate diameter step contributes its NEURON-compatible annular membrane area but no centerline length, volume, or axial resistance; a step exactly on a compartment boundary belongs to the lower-x compartment. Material
diameter_ummetadata is the arclength mean over the compartment, not a point sample used to reconstruct these exact integrals.
- classmethod from_swc(file_path, *, rhoa=100.0, cm=1.0, nseg=1, single_point_soma='sphere', type_labels=None)[source]#
Load a classic SWC node tree as a native Morphology declaration.
The pure-Python loader preserves finite xyz samples, radii, rooted connectivity, and raw structure type IDs without applying NEURON’s d-lambda discretization or repair heuristics. Maximal root-away paths of one downstream SWC type become pt3d Sections; branches and type changes start a new Section at the shared parent sample.
- Parameters:
file_path (path-like) – UTF-8 SWC file containing the seven classic columns
id type x y z radius parent. Blank lines, full-line comments, and inline#comments are accepted. Rows may appear in any order.rhoa (float, optional) – Positive default axial resistivity in Ω·cm. SWC does not carry this electrical property. Default is
100.cm (float, optional) – Positive default specific capacitance in µF/cm². SWC does not carry this electrical property. Default is
1.nseg (int, optional) – Positive compartment count assigned independently to every generated Section. SWC samples describe geometry, not numerical compartments. Default is
1.single_point_soma ({'sphere', 'error'}, optional) – A common type-1 root has no positive-length cable of its own.
"sphere"creates the NEURON-compatible three-point x-axis cable surrogate centered on the sample with length and diameter2r; its lateral area equals a sphere’s surface area, though its volume remains cylindrical."error"rejects this ambiguity. Default is"sphere".type_labels (mapping, optional) – Additional shared labels for selected integer SWC type IDs. Every imported Section always receives
swc_type_<id>plus Dendra’s conventional semantic labels where defined.
- Returns:
Native, editable pt3d Sections with deterministic collision-free names such as
soma_0andbasal_dendrite_0.- Return type:
Notes
Exactly one root is required. Duplicate IDs, unknown parents, cycles, non-positive radii, non-finite values, and zero-length edges are rejected rather than repaired silently. Structural integer IDs are parsed exactly rather than through binary64. A non-soma root must have a same-type child so its type can belong to a positive-length Section; an isolated root-type discontinuity is rejected instead of being silently retyped. SWC cannot preserve original Section names/boundaries, labels,
nseg,rhoa, orcm.swc_section_typesretains raw type provenance for an explicit re-export viasection_types=morphology.swc_section_types.
- classmethod from_asc(file_path, *, root=None, rhoa=100.0, cm=1.0, nseg=1)[source]#
Load NEURON’s normalized interpretation of a Neurolucida ASC file.
Neurolucida V3 text includes contours, nested cable trees, spines, markers, colors, arbitrary properties, and repair conventions. Dendra therefore delegates this compatibility grammar to NEURON’s mature
Import3d_Neurolucida3reader, then immediately snapshots the chosen cable tree into editable native pt3d Sections. The returned object holds no NEURON references.- Parameters:
file_path (path-like) – Neurolucida V3 ASCII morphology.
root (str, optional) – Exact generated root Section name, such as
"soma[0]". A file with several disconnected cable trees is rejected unless one root is selected explicitly; candidates are listed in the error.rhoa (float, optional) – Positive axial resistivity in Ω·cm for every imported Section. ASC does not define this electrical value. Default is
100.cm (float, optional) – Positive specific capacitance in µF/cm² for every imported Section. ASC does not define this electrical value. Default is
1.nseg (int, optional) – Positive compartment count assigned to every imported Section. No d-lambda policy is inferred from geometry. Default is
1.
- Returns:
A native snapshot with NEURON-generated names such as
soma[0],axon[3],dend[8], andapic[1]and corresponding shared structural labels.- Return type:
Notes
Centerlines, diameters, topology, logical attachment locations, and the selected cable component are preserved after NEURON normalization. Exact duplicate pt3d samples are coalesced. Consecutive samples at the same coordinate with different diameters are preserved as abrupt zero-length diameter steps, including their annular membrane area. A Section with no positive centerline length after coalescing is rejected. Source formatting, comments, colors, markers, properties, spines, original trace identifiers, and soma contour boundaries are not retained. NEURON may repair or approximate source geometry and stores pt3d values at its own precision. When NEURON makes its recoverable logical connection from an outlying main branch to the nearest soma, Dendra emits one
RuntimeWarningcontaining NEURON’s repair diagnostics before snapshotting that topology. This method intentionally complements the pure-Python, sample-preservingfrom_swc()loader.
- to_swc(*, section_types=None, default_type=0, connection_tolerance_um=1e-09)[source]#
Serialize the authored centerline tree in SWC format.
- Parameters:
section_types (mapping of str to int, optional) – SWC structure type for each exactly named Section. Unlisted Sections use
default_type. No type is inferred from Section names or labels.default_type (int, optional) – Non-negative SWC structure type for unlisted Sections. The default is
0(undefined).connection_tolerance_um (float, optional) – Maximum spatial separation, in micrometers, allowed between a parent attachment and its connected child endpoint. SWC combines topology and geometry, so larger discrepancies are rejected. The default is
1e-9.
- Returns:
Deterministic SWC text ending in a newline.
- Return type:
str
Notes
SWC export describes the authored Section centerlines, not the compartment graph produced by
compile(). It therefore does not encodenseg,rhoa,cm, Section names, or labels. Importing the result may choose a different electrical discretization.A shared connection is represented by one SWC sample carrying the parent’s type and radius. Classic SWC cannot retain distinct radii on the two sides of that single junction. It also cannot represent the annular membrane surface of a repeated-coordinate diameter step, so export rejects a Morphology containing such a discontinuity rather than silently discarding geometry or writing a zero-length SWC edge.
- write_swc(file_path, *, section_types=None, default_type=0, connection_tolerance_um=1e-09)[source]#
Validate and write the authored centerline tree as UTF-8 SWC.
The complete document is serialized before the destination is opened, so a morphology validation error cannot truncate an existing file. See
to_swc()for the export contract and keyword arguments.
- plot(*, view='y', color_by='section', highlight=None, show_points=True, show_connections=True, show_compartments=False, show_orientation=True, annotate_sections=False, annotate_connections=False, connection_tolerance_um=1e-09, diameter_scale=0.35, min_linewidth=0.75, legend=True, cmap='viridis', ax=None, figsize=(8, 8), dpi=150, title=None)[source]#
Plot an orthographic view of the authored morphology.
The plot is a read-only view of the current
Sectiondeclarations. It shows authored centerlines and optional authoring diagnostics without compiling aCompartmentGraphor constructing a simulation model.- Parameters:
view ({"x", "y", "z"}, optional) – Coordinate axis to look along (and therefore omit from the plot). For example,
view="y"displays x against z. Default is"y".color_by (str, optional) – Attribute used to color Section paths.
"section"assigns a deterministic categorical color to each exact Section identity. Scalar morphology fields such as"length","diameter","nseg","rhoa", and"cm"use a continuous color scale. Default is"section".highlight (str or iterable of str, optional) – Exact Section name or shared structural label, or several of either. Matching Sections remain prominent and other Sections are muted.
Nonehighlights the complete morphology.show_points (bool, optional) – Show authored pt3d control points. Stylized Sections expose their two canonical local endpoints. Default is
True.show_connections (bool, optional) – Show electrical attachment markers and spatial-gap diagnostics. These glyphs describe connectivity; a line between spatially separated endpoints is not an authored physical cable. Default is
True.show_compartments (bool, optional) – Overlay the compartment centers implied by each Section’s
nsegdeclaration. This is an authoring preview and does not compile the solver graph. Default isFalse.show_orientation (bool, optional) – Draw increasing authored Section x along a local authored span and mark the
0or1child endpoint facing each parent. A child attached throughchild_end=1retains its authored x direction. Default isTrue.annotate_sections (bool, optional) – Annotate paths with exact Section names. Default is
False.annotate_connections (bool, optional) – Annotate attachments with parent x and child endpoint values. Default is
False.connection_tolerance_um (float, optional) – Spatial separation, in µm, at or below which connected attachment points are classified as within visualization tolerance rather than as a true spatial gap. Nonzero separation remains visible. This neither changes electrical connectivity nor applies the stricter SWC export contract. Default is
1e-9.diameter_scale (float, optional) – Scale converting authored diameter in µm to relative screen-space line width. Rendered thickness is an expressive encoding, not a geometrically to-scale tube radius. Default is
0.35.min_linewidth (float, optional) – Minimum visible centerline width in display points. Default is
0.75.legend (bool, optional) – Show a categorical legend or numeric color key as appropriate. Default is
True.cmap (str, optional) – Matplotlib colormap name used for continuous coloring. Default is
"viridis".ax (object, optional) – Existing Matplotlib axes to draw into. A new figure and axes are created when omitted.
figsize (tuple of float, optional) – Width and height in inches for a newly created figure. Ignored when
axis supplied. Default is(8, 8).dpi (int, optional) – Resolution of a newly created figure. Ignored when
axis supplied. Default is150.title (str, optional) – Figure title.
Noneuses the renderer’s descriptive default.
- Returns:
The Matplotlib
(Figure, Axes)pair returned by the renderer.- Return type:
object
Notes
Relative geometry is displayed exactly as authored. In particular,
connect()does not translate or rotate a child, and stylized Sections use local canonical coordinates, so electrically connected paths may overlap or remain spatially separated. At extreme binary64 magnitudes, a numerical origin or scale may be applied to the display coordinates; every such transform is printed on the axes. Tapered authored spans may be subdivided visually to interpolate width/color, but this does not alter the Morphology. A repeated-coordinate diameter step is retained in the scene data, but a centerline drawing cannot display its annular surface; useplot_shape()orplot_shape_3d()to see that shoulder. The method never callsshow; display, save, or further customize the returned figure explicitly.
- plot_3d(*, color_by='section', highlight=None, show_points=True, show_connections=True, show_compartments=False, show_orientation=True, annotate_sections=False, annotate_connections=False, connection_tolerance_um=1e-09, diameter_scale=0.35, min_linewidth=0.75, legend=True, cmap='viridis', ax=None, figsize=(9, 8), dpi=150, title=None)[source]#
Plot the authored morphology in three spatial dimensions.
This method has the same authoring-layer semantics as
plot(), but preserves x, y, and z. It is useful for checking pt3d placement, taper, orientation, and whether electrically attached points are also spatially coherent.- Parameters:
color_by (str, optional) – Attribute used to color Section paths.
"section"is categorical;"length","diameter","nseg","rhoa", and"cm"provide continuous encodings. Default is"section".highlight (str or iterable of str, optional) – Exact Section name or shared label, or several of either, to keep prominent while muting non-matches. Default is
None.show_points (bool, optional) – Show authored pt3d controls or stylized canonical endpoints. Default is
True.show_connections (bool, optional) – Show electrical attachment markers and spatial-gap diagnostics. Diagnostic connectors are not physical centerline segments. Default is
True.show_compartments (bool, optional) – Overlay centers implied by authored
nsegvalues without compiling a solver graph. Default isFalse.show_orientation (bool, optional) – Draw increasing authored Section x on a local span and mark each connected child endpoint as
0or1. Default isTrue.annotate_sections (bool, optional) – Annotate paths with exact Section names. Default is
False.annotate_connections (bool, optional) – Annotate electrical attachments with their normalized locations. Default is
False.connection_tolerance_um (float, optional) – Visual coincidence tolerance for connected coordinates, in µm. It does not alter connectivity, compilation, or SWC validation. Default is
1e-9.diameter_scale (float, optional) – Conversion from diameter in µm to relative display width. The result is not a metrically exact solid tube. Default is
0.35.min_linewidth (float, optional) – Minimum centerline width in display points. Default is
0.75.legend (bool, optional) – Show the Section legend or numeric color key. Default is
True.cmap (str, optional) – Matplotlib colormap name for numeric coloring. Default is
"viridis".ax (object, optional) – Existing three-dimensional Matplotlib axes. A new 3D axes is created when omitted.
figsize (tuple of float, optional) – New figure size in inches. Ignored when
axis supplied. Default is(9, 8).dpi (int, optional) – New figure resolution. Ignored when
axis supplied. Default is150.title (str, optional) – Figure title.
Noneuses the renderer’s descriptive default.
- Returns:
The Matplotlib
(Figure, 3D Axes)pair from the renderer.- Return type:
object
Notes
The current declaration is read without mutation or compilation. Existing
CompartmentGraph,Tree, andCablesnapshots are not consulted. Extreme-coordinate display origins/scales and extreme color-value divisors are disclosed on the figure. As inplot(), a diagnostic centerline cannot show the annular surface of a zero-length diameter step; the shape views render it as a shoulder. No display call is made implicitly.
- plot_shape(*, view='y', diameter_scale=1.0, radial_segments=8, connection_tolerance_um=1e-09, legend='auto', show_axes=False, ax=None, figsize=(8, 8), dpi=150, title=None)[source]#
Draw a quiet orthographic view of the physical cable envelope.
Unlike
plot(), this renderer uses authored diameters as radii in morphology coordinate units rather than as screen-space line widths. It constructs closed, linearly tapered tubes around the authored pt3d centerlines, colors them by structural morphology family, and omits diagnostic points, arrows, connection glyphs, annotations, and titles by default. Indexed Sections such asdend[0]anddend[1]share the canonicaldendcolor used byvis_2d().- Parameters:
view ({'x', 'y', 'z'}, optional) – Axis viewed along.
"y"produces an x-z projection. Default is"y".diameter_scale (float, optional) – Positive multiplier for every physical diameter.
1preserves authored proportions; larger values intentionally exaggerate thin cables for display. Default is1.radial_segments (int, optional) – Number of sides in each circular tube ring. Larger values make a smoother surface at greater rendering cost. Must be at least 3; default is
8.connection_tolerance_um (float, optional) – Spatial-gap threshold in µm. A single warning is emitted when an electrical connection exceeds it; no artificial bridge is drawn. Default is
1e-9.legend (bool or {'auto'}, optional) – Show structural color families.
"auto"shows the legend for at most 16 families, avoiding an unusable key while retaining a compact legend for large imported cells. Default is"auto".show_axes (bool, optional) – Show physical coordinate axes. Default is
False.ax (object, optional) – Existing two-dimensional Matplotlib axes. A new figure and axes are created when omitted.
figsize (tuple of float, optional) – New figure size in inches. Ignored when
axis supplied.dpi (int, optional) – New figure resolution. Ignored when
axis supplied.title (str, optional) – Optional explicit title. The default adds no title.
- Returns:
The Matplotlib
(Figure, Axes)pair.- Return type:
object
Notes
The surface is a faithful tapered-cable envelope of the authored Section data, not a histological reconstruction or a boolean union at branches. It does not use
nsegor compile the Morphology. Connected stylized Sections retain their canonical local z-axis and may overlap; use coherent pt3d coordinates for a meaningful whole-cell shape. Two coincident controls with different diameters are rendered as concentric rings and the corresponding annular shoulder, without inventing cable length. Exact Section provenance remains available on the rendered collection even when several Sections share one family color. The method never mutates the declaration or callsshow.
- plot_shape_3d(*, diameter_scale=1.0, radial_segments=8, connection_tolerance_um=1e-09, legend='auto', show_axes=False, show_axis_indicator=True, interactive=False, ax=None, figsize=(9, 8), dpi=150, title=None)[source]#
Draw the authored physical cable envelope as a quiet 3-D surface.
This is the rotatable three-dimensional counterpart of
plot_shape(). Diameters remain in morphology coordinate units; its structural family colors and compact legend are identical to the 2-D view. Diagnostic metadata and connection glyphs belong toplot_3d()andinspect()instead.Parameters are the same as
plot_shape(), except that no projectionviewis required andfigsizedefaults to(9, 8).show_axis_indicator=Trueadds a compact, screen-fixed x/y/z triad in the lower left even while the full coordinate axes remain hidden. The triad follows camera rotation without changing the morphology’s limits.Set
interactive=Trueto explicitly request event-driven Matplotlib navigation. Left drag rotates, middle drag pans, right drag zooms, and the scroll wheel zooms around the current view. An event-capable backend must be selected before creating the figure—for example,%matplotlib widgetwith the optionalipymplpackage in Jupyter, or a desktop GUI backend. A static backend emits an actionable warning; this method never changes the backend or callsshow. Matplotlib 3-D axes may already expose their native drag navigation on a live backend wheninteractiveis left false; the flag requests and validates that capability and adds Dendra’s scroll-wheel zoom.A supplied axes must be a Matplotlib 3-D axes. The method returns
(Figure, Axes)and does not mutate the Morphology.
- plot_topology(*, highlight=None, interactive=False, node_scale=8.0, min_node_size=12.0, max_node_size=240.0, branchpoint_scale=1.35, min_branchpoint_size=24.0, max_branchpoint_size=300.0, junction_size=52.0, edge_scale=0.12, min_edge_width=0.35, max_edge_width=3.0, node_size=None, branchpoint_size=None, edge_width=None, legend=True, ax=None, figsize=(10, 7), dpi=150, title=None)[source]#
Draw the flat, coordinate-independent compartment connectivity graph.
Every material compartment is a node colored by its exact authored Section name. Retained zero-area algebraic junctions are separate neutral nodes. Edges are the canonical axial connections after endpoint removal, degree-two junction collapse, and interior-attachment resolution. The graph contains no per-node text; optional hover cards expose the underlying node metadata. Layout depth and spacing are schematic rather than morphological distances.
- Parameters:
highlight (str or iterable of str, optional) – Exact Section name or shared label, or several of either, to keep prominent while muting non-matching material compartments. Unlabelled algebraic junctions remain neutral structural context. Default is
None.interactive (bool, optional) – Enable Matplotlib motion-event hover cards without adding a Dendra runtime dependency. Hovering over a material node reports its generated name, Section, segment, x, labels, length, arclength-mean diameter, integrated area/volume,
rhoa,cm, and spatial center. Select an event-capable backend before creating the figure: for example, a GUI backend or%matplotlib widgetwith the optionalipymplpackage (available throughdendra[jupyter]). Restart the complete Jupyter server after installation, not only its kernel. A separately installed kernel and server both need compatible ipympl components. Static inline and saved raster output cannot react to pointer motion; an inline notebook call emits an actionable warning. Default isFalse.node_scale (float, optional) – Scale from material-compartment arclength-mean diameter in µm to marker area in display points². Default is
8.min_node_size (float or None, optional) – Visible bounds for material-compartment marker areas. The default bounds are
12and240points²;Noneremoves the upper bound.max_node_size (float or None, optional) – Visible bounds for material-compartment marker areas. The default bounds are
12and240points²;Noneremoves the upper bound.branchpoint_scale (float, optional) – Additional marker-area factor for a material forking compartment. Default is
1.35.min_branchpoint_size (float or None, optional) – Visible bounds for material-fork marker areas after scaling. The defaults are
24and300points²;Noneremoves the upper bound.max_branchpoint_size (float or None, optional) – Visible bounds for material-fork marker areas after scaling. The defaults are
24and300points²;Noneremoves the upper bound.junction_size (float, optional) – Fixed marker area for a zero-area algebraic junction. Junctions have no physical diameter to encode. Default is
52points².edge_scale (float, optional) – Scale from the mean of the material endpoints’ arclength-mean diameters in µm to edge width in display points. A junction endpoint is excluded because its stored geometry is not material. Default is
0.12.min_edge_width (float or None, optional) – Visible bounds for scaled edge widths. The defaults are
0.35and3points;Noneremoves the upper bound.max_edge_width (float or None, optional) – Visible bounds for scaled edge widths. The defaults are
0.35and3points;Noneremoves the upper bound.node_size (float or None, optional) – Explicit fixed-size compatibility overrides.
node_sizefixes ordinary material markers;branchpoint_sizefixes both material-fork and algebraic-junction markers;edge_widthfixes every edge.None(the default) uses diameter scaling.branchpoint_size (float or None, optional) – Explicit fixed-size compatibility overrides.
node_sizefixes ordinary material markers;branchpoint_sizefixes both material-fork and algebraic-junction markers;edge_widthfixes every edge.None(the default) uses diameter scaling.edge_width (float or None, optional) – Explicit fixed-size compatibility overrides.
node_sizefixes ordinary material markers;branchpoint_sizefixes both material-fork and algebraic-junction markers;edge_widthfixes every edge.None(the default) uses diameter scaling.legend (bool, optional) – Show exact Section-name colors and structural glyphs. Default is
True.ax (object, optional) – Existing Matplotlib axes. A new figure and axes are created when omitted.
figsize (tuple of float, optional) – New figure size in inches. Ignored when
axis supplied. Default is(10, 7).dpi (int, optional) – New figure resolution. Ignored when
axis supplied. Default is150.title (str, optional) – Figure title.
Noneuses the renderer’s descriptive default.
- Returns:
The Matplotlib
(Figure, Axes)pair from the renderer.- Return type:
object
Notes
A complete Morphology uses the exact topology produced by
compile(). A partially authored forest is compiled one connected component at a time, retaining exact per-component compartment semantics without requiring a single root.Any node with at least three neighbors in the undirected compartment graph is a graph branchpoint. A Section-colored diamond distinguishes a material forking compartment; a neutral
Xdistinguishes a retained zero-area algebraic junction. This invariant definition does not misclassify an arbitrary degree-two solver root. Junction hover cards deliberately omit copied storage fields that are not material properties; their marker size and incident-edge scaling likewise never use those copied fields. Scaling changes display geometry only, while highlighting changes alpha only. The title’s branchpoint count includes both glyph classes. The method does not mutate the declaration or callshow.
- plot_section_topology(*, color_by='section', highlight=None, show_parameters=True, show_labels=True, show_compartments=True, annotate_connections=True, connection_tolerance_um=1e-09, legend=True, cmap='viridis', ax=None, figsize=(10, 7), dpi=150, title=None)[source]#
Draw the authored Section tree/forest as a labelled schematic.
This authoring-level companion to
plot_topology()uses one box per Section and can display authoring parameters, structural labels,nsegrulers, connection locations, and spatial-gap diagnostics. It does not compile the compartment graph and therefore describes the declaration rather than solver-node connectivity.- Parameters:
color_by (str, optional) –
"section","length","diameter","nseg","rhoa", or"cm". Default is"section".highlight (str or iterable of str, optional) – Exact Section name or shared label, or several of either, to keep prominent while muting non-matches. Default is
None.show_parameters (bool, optional) – Include geometry, length,
rhoa, andcmin each Section box. Default isTrue.show_labels (bool, optional) – Include shared structural labels in each Section box. Default is
True.show_compartments (bool, optional) – Draw the declared
nsegruler and count. This is an authoring preview, not the compiled graph. Default isTrue.annotate_connections (bool, optional) – Include attachment locations, child endpoints, and spatial-gap status on graph edges. Default is
True.connection_tolerance_um (float, optional) – Non-negative visual tolerance in µm for classifying connection coordinates as coincident. Default is
1e-9.legend (bool, optional) – Show the Section-name legend or numeric color scale. Default is
True.cmap (str, optional) – Matplotlib colormap for numeric
color_bymodes. Default is"viridis".ax (object, optional) – Existing two-dimensional Matplotlib axes. A new figure and axes are created when omitted.
figsize (tuple of float, optional) – New figure size in inches. Ignored when
axis supplied. Default is(10, 7).dpi (int, optional) – New figure resolution. Ignored when
axis supplied. Default is150.title (str, optional) – Figure title.
Noneuses the renderer’s descriptive default.
- Returns:
The Matplotlib
(Figure, Axes)pair. The method never callsshow.- Return type:
object
- plot_diameter_profile(*, sections=None, highlight=None, x_axis='normalized', show_points=True, show_compartments=True, show_connections=True, legend=True, ax=None, figsize=(9, 5), dpi=150, title=None)[source]#
Plot authored diameter as a function of position along Sections.
Stylized cylinders appear as constant profiles. Pt3d Sections use their piecewise-linear diameter controls, making this view especially useful after
SectionLocation.update()inserts or edits a local control point. Repeated-coordinate controls have the same horizontal position and draw an abrupt diameter step as a vertical segment.- Parameters:
sections (Section, str, or iterable, optional) – Exact Section object or name, or several of either, to include.
Noneincludes all Sections in declaration order.highlight (str or iterable of str, optional) – Exact Section name or shared structural label, or several of either, to emphasize while muting non-matches. It does not filter the selected
sections. Default isNone.x_axis ({"normalized", "distance"}, optional) – Horizontal coordinate.
"normalized"uses each Section’s authored x in[0, 1];"distance"uses centerline distance in µm from authored x=0. Default is"normalized".show_points (bool, optional) – Mark authored diameter control points. Default is
True.show_compartments (bool, optional) – Mark centers or intervals implied by authored
nsegvalues, without compiling a solver graph. Default isTrue.show_connections (bool, optional) – Mark normalized parent attachment positions and child endpoints on included profiles. These marks describe electrical connectivity, not a continuous global path-distance coordinate. Default is
True.legend (bool, optional) – Show the Section legend. Default is
True.ax (object, optional) – Existing Matplotlib axes. A new figure and axes are created when omitted.
figsize (tuple of float, optional) – New figure size in inches. Ignored when
axis supplied. Default is(9, 5).dpi (int, optional) – New figure resolution. Ignored when
axis supplied. Default is150.title (str, optional) – Figure title.
Noneuses the renderer’s descriptive default.
- Returns:
The Matplotlib
(Figure, Axes)pair from the renderer.- Return type:
object
Notes
Each Section retains its own authored coordinate and orientation; connected profiles are not concatenated into a global cable axis. The current declaration is read without mutation or compilation, and no display call is made implicitly.
- inspect(*, highlight=None, show_points=True, show_compartments=True, show_orientation=True, annotate_sections=False, annotate_connections=True, connection_tolerance_um=1e-09, figsize=(16, 9), dpi=150, title=None)[source]#
Build a coordinated dashboard for human morphology validation.
The dashboard combines complementary spatial projections with exact compartment topology and diameter/discretization diagnostics. All panels describe one read-only snapshot of the current authored declaration.
- Parameters:
highlight (str or iterable of str, optional) – Exact Section name or shared structural label, or several of either, to emphasize consistently across panels. Default is
None.show_points (bool, optional) – Show authored pt3d controls and stylized endpoints. Default is
True.show_compartments (bool, optional) – Show centers or counts implied by authored
nsegdeclarations in the spatial and diameter-profile panels. These are authoring previews; the topology panel always shows the canonical compiled graph regardless of this option. Default isTrue.show_orientation (bool, optional) – Mark increasing authored x and the connected child endpoint. Default is
True.annotate_sections (bool, optional) – Label spatial paths with exact Section names. Default is
False.annotate_connections (bool, optional) – Label electrical attachments with parent x and child endpoint values once, on the z-projection panel. Default is
True.connection_tolerance_um (float, optional) – Visual threshold, in µm, for distinguishing coincident attachment coordinates from spatial gaps. It does not change electrical connectivity or validate SWC export. Default is
1e-9.figsize (tuple of float, optional) – Dashboard width and height in inches. Default is
(16, 9).dpi (int, optional) – Dashboard resolution. Default is
150.title (str, optional) – Dashboard title.
Noneuses the renderer’s descriptive default.
- Returns:
The Matplotlib figure and coordinated axes returned by the dashboard renderer.
- Return type:
object
Notes
Authored centerline coordinates and electrical connection semantics are deliberately shown as distinct information. Connected stylized Sections may overlap because
connect()does not place them in a shared coordinate frame. The topology panel canonically compiles each connected component of the detached declaration snapshot; this gives a complete Morphology the same graph ascompile()while keeping an incomplete forest inspectable. The dashboard does not mutate the Morphology, consult an existing model snapshot, or display itself implicitly.
- class Section[source]#
One named cable section in a native
Morphology.Obtain sections through
Morphology.section(). Each section is a handle owned by its Morphology; users do not construct Section objects directly.nameis the Section’s unique authored identity.labelsis its read-only set of structural region tags and always includesname. Attribute assignment is disabled;update()performs a validated, transactional edit through the owning Morphology while preserving this object’s identity.- lambda_f(*, freq_hz=100.0)[source]#
Return this Section’s AC space constant in µm.
The calculation is the native equivalent of NEURON’s
lambda_fdiscretization helper. Stylized Sections use their uniform diameter; pt3d Sections evaluate the compiler-representable authored profile with NEURON’s control-interval approximation along centerline arclength.freq_hzis a raw frequency in hertz, not Dendra’s usual kHz simulation-frequency coordinate. The calculation uses the same binary64-representable spans asMorphology.compile().This method performs analysis only and does not change
nseg. UseMorphology.apply_d_lambda()to select and apply compartment counts across the owning Morphology.
- update(*, L=None, diam=None, points=None, nseg=None, rhoa=None, cm=None, labels=None)[source]#
Transactionally update this authored Section and return it.
rhoa,cm, andnsegare whole-Section properties. Stylized Sections may updateLanddiam; pt3d Sections replace geometry throughpointsbecause their length and diameter profile are derived. Usesection.at(x).update(diam=...)for one pt3d diameter control point. Supplyingpointscan promote a stylized Section to pt3d.labelsreplaces the explicit set, withnamere-added.Existing compiled graphs and instantiated models are independent snapshots. Compile or construct a new model to observe an update.
Nonemeans unchanged for every argument.
- delete(*, recursive=False)[source]#
Delete this Section from its owning Morphology.
A leaf Section can be deleted directly. A Section with children is rejected unless
recursive=True, in which case the complete descendant subtree is deleted. The returned names follow the original Section declaration order.Deletion invalidates this Section and any saved locations on it for future authoring operations. Existing compiled graphs and instantiated models remain independent snapshots.
- class SectionLocation(section, x)[source]#
An immutable normalized selector on a native Section’s current geometry.
- connect(parent)[source]#
Connect this child endpoint to a parent location and return its Section.
Only authored endpoints
0and1can be child locations. Parent locations may lie anywhere on their Section.
- update(*, diam)[source]#
Edit or insert a pt3d diameter control point at this location.
Diameter remains linearly interpolated between neighboring authored samples. The centerline path,
nseg, and electrical properties are unchanged; an inserted point may re-express the same path length within binary64 roundoff. If coordinate precision cannot represent a distinct control point, the update is rejected. A location containing an abrupt diameter discontinuity has two authored diameter limits and is therefore ambiguous; replace the complete Sectionpointsto edit either side. Location-scopedrhoaandcmare not defined by the current whole-Section electrical contract.- Returns:
The canonical owning Section after a successful update.
- Return type:
Morphology composition#
- connect_morphologies(parent, child, *, child_prefix='')[source]#
Connect two complete Morphologies and return an independent declaration.
parentmay select any location on its owning Morphology.childmust select endpoint 0 or 1 of the root Section in a different Morphology. The parent Morphology is copied first, the complete child Morphology is copied after it, and one new Section connection joins the two trees. Neither input is mutated, and every Section in the result has fresh identity.Section names remain exact by default.
child_prefixis prepended to every child-Morphology Section name when the two declarations would otherwise collide. The corresponding automatic name label and imported SWC type key are renamed with it; reusable structural labels are unchanged. Any remaining Section-name or name-versus-label conflict is rejected.Spatial coordinates are preserved exactly. As with
Morphology.connect(), this operation establishes electrical topology but does not translate or rotate the child geometry.- Parameters:
parent (SectionLocation) – Attachment location in the Morphology that will provide the result’s defaults and root tree.
child (SectionLocation) – Endpoint of the other Morphology’s unique root Section.
child_prefix (str, optional) – Prefix for every Section name copied from the child Morphology. Default is the empty string.
- Returns:
A fresh, connected Morphology containing independent copies of both source declarations, in parent-then-child Section declaration order.
- Return type:
Canonical scalar compartment graph#
Morphology.compile()
validates the sections and returns a snapshot of compartment geometry and
electrical connections. Inspect it before constructing a model if you need
to check the compartment count or the geometry.
- class CompartmentGraph(topology, geometry, metadata, schema_version=1)[source]#
Immutable canonical scalar compartment resistor tree.
- path_ordered()[source]#
Return an equivalent graph ordered from one cable end to the other.
The generic unbranched
dendra.Cablebackend requires its final tensor dimension to follow physical path order. A canonical rooted tree need not already have that ordering: a valid unbranched morphology can have its rooted node in the middle of the physical cable. This method validates the stronger material-only path contract and returns a new immutable snapshot whose parent array is(-1, 0, 1, ...).Orientation is deterministic. If the original root is a physical end it remains the first node; otherwise the lower-numbered end is first. Provenance, authored Section coordinates, labels, and exact edge geometry are retained while node IDs are remapped to storage order.
- Raises:
ValueError – If any node is an algebraic junction or the underlying undirected graph is not one simple path.
- class CompartmentTopology(parent_index)[source]#
Immutable rooted-tree topology using child-indexed parent IDs.
- class CompartmentGeometry(length_um, diameter_um, area_um2, volume_um3, volume_i_um3, volume_o_um3, x_um, y_um, z_um, rhoa_ohm_cm, cm_uF_cm2, edge_length_um, edge_resistance_ohm, edge_diff_geom_um)[source]#
Immutable binary64 node geometry and child-indexed axial edge data.
For geometry produced by
Morphology.compile(),diameter_umis the arclength-mean diameter of each material compartment, matching NEURON’s segment-diameter convention. It is descriptive metadata rather than a cylindrical approximation:area_um2,volume_um3, and the axial edge fields retain the exact compiled tapered-cable integrals.
- class CompartmentMetadata(name, kind, section_name, segment_index, section_x, labels)[source]#
Immutable provenance and structural labels for graph nodes.
nameis the generated per-node display/search name, for example"soma(0.5)".section_nameis the unique authoredSectionidentity from which a material compartment was compiled.labelscontains reusable structural region tags; for native Sections it also includes that Section’s name. Retained junction nodes have no source Section and therefore useNoneprovenance and an empty label set.
Plot a compartment graph#
plot_shape() draws the section
declaration. Use vis_2d to plot the compartment graph of a constructed
Population.
- vis_2d(cell, idx=0, view='y', node_scale=8, dpi=200, *, fig=None, ax=None, show_nodes=True, show_edges=True, show_legend=True, edge_alpha=0.85, node_alpha=0.7, edge_scale=0.12, min_edge_width=0.35, max_edge_width=None, edge_color='k', scalebar=False, scalebar_length=None, scalebar_loc='lower right', scalebar_color='black', scalebar_linewidth=2.5, scalebar_fontsize=10)[source]#
Project a 3-D morphology graph to 2-D and plot it with matplotlib.
- Parameters:
cell (Dendra Population) – The cell object containing the graph, labels, and
findmethod.idx (int, optional) – Population instance index to visualize.
view ({'x', 'y', 'z'}, optional) – Axis to project along. Default
'y'(drop y -> plot x-z).node_scale (float, optional) – Factor converting compartment diameter (µm) to marker area.
dpi (int, optional) – Figure resolution in dots per inch.
fig (matplotlib objects, optional) – Existing figure/axes to draw into. If omitted, a new figure is created.
ax (matplotlib objects, optional) – Existing figure/axes to draw into. If omitted, a new figure is created.
show_nodes (bool, optional) – Toggle display of node markers, graph edges, and legend.
show_edges (bool, optional) – Toggle display of node markers, graph edges, and legend.
show_legend (bool, optional) – Toggle display of node markers, graph edges, and legend.
edge_alpha (float, optional) – Transparency for edges and node markers.
node_alpha (float, optional) – Transparency for edges and node markers.
edge_scale (float, optional) – Scale factor converting local diameter (µm) to line width.
min_edge_width (float, optional) – Minimum visible line width for edges.
max_edge_width (float or None, optional) – Optional cap on edge line width.
edge_color (matplotlib color, optional) – Fallback color for edges.
scalebar (bool, optional) – If True, hide axes and draw a 2D scalebar instead.
scalebar_length (float or None, optional) – Scalebar length in µm. If omitted, a visually sensible value is chosen.
scalebar_loc ({'lower right', 'lower left'}, optional) – Placement of the scalebar.
- Returns:
The matplotlib figure and axes.
- Return type:
(fig, ax)