crantpy.queries package#
Submodules#
- crantpy.queries.connections module
- crantpy.queries.nested_connectivity_matrices module
DirectedNestedMatrixDirectedNestedMatrix.by()DirectedNestedMatrix.from_connectivity()DirectedNestedMatrix.from_synapses()DirectedNestedMatrix.from_synapses_by_neuropil()DirectedNestedMatrix.get_relative_weights()DirectedNestedMatrix.matrixDirectedNestedMatrix.mean_type_matrixDirectedNestedMatrix.order()DirectedNestedMatrix.plot()DirectedNestedMatrix.source_neuron_to_typeDirectedNestedMatrix.source_neuronsDirectedNestedMatrix.source_type_boundariesDirectedNestedMatrix.source_typed_neuronsDirectedNestedMatrix.source_untyped_neuronsDirectedNestedMatrix.sum_type_matrixDirectedNestedMatrix.target_neuron_to_typeDirectedNestedMatrix.target_neuronsDirectedNestedMatrix.target_type_boundariesDirectedNestedMatrix.target_typed_neuronsDirectedNestedMatrix.target_untyped_neurons
NestedMatrixNestedMatrix.matrixNestedMatrix.type_boundariesNestedMatrix.ordered_neuronsNestedMatrix.neuron_to_typeNestedMatrix.by()NestedMatrix.from_connectivity()NestedMatrix.from_synapses()NestedMatrix.from_synapses_by_neuropil()NestedMatrix.get_relative_weights()NestedMatrix.matrixNestedMatrix.mean_type_matrixNestedMatrix.neuron_to_typeNestedMatrix.order()NestedMatrix.ordered_neuronsNestedMatrix.plot()NestedMatrix.sum_type_matrixNestedMatrix.type_boundariesNestedMatrix.typed_neuronsNestedMatrix.untyped_neurons
NeuropilCollection
- crantpy.queries.neurons module
- crantpy.queries.neuropils module
Module contents#
- class crantpy.queries.DirectedNestedMatrix(matrix, source_neurons, target_neurons, source_type_boundaries=None, target_type_boundaries=None, source_neuron_to_type=None, target_neuron_to_type=None)[source]#
Bases:
objectA rectangular nested connectivity matrix with independent axes.
Rows are presynaptic/source neurons, columns postsynaptic/target. Unlike
NestedMatrixthe matrix may be rectangular and the two cell type sets may differ.Constructors take
source_types/source_ids(and thetarget_pair) to select an axis; the resolved order is read back from.source_neurons/.target_neurons. Type and ID selectors on one axis are unioned; leaving both of themNonekeeps every available neuron on that axis.Per axis,
<axis>_neuronsis<axis>_typed_neurons + <axis>_untyped_neurons, and only the typed part is covered by<axis>_type_boundariesand<axis>_neuron_to_type.- Parameters:
matrix (pd.DataFrame)
source_neurons (Iterable[Any])
target_neurons (Iterable[Any])
source_type_boundaries (Mapping[Any, tuple[int, int]] | None)
target_type_boundaries (Mapping[Any, tuple[int, int]] | None)
source_neuron_to_type (Mapping[Any, Any] | None)
target_neuron_to_type (Mapping[Any, Any] | None)
- by(*, rank=None, extract=None, key=None, na='last')#
Sort a cell type’s neurons by annotation column(s).
A string at the order layer is only a named rule (
"id","annotation","label","size"). Column names live here.- Parameters:
columns (str) – Annotation columns to read, in priority order. The first column that yields a usable value wins.
rank (sequence of str, optional) – Explicit label order. Without extract, the leftmost rank label that appears in the cell is used, so
"EPG/PEG_R1"and"Δ7_L8R1R9"both rank without a regex.extract (str or compiled pattern, optional) – Regex whose first group is the label. A plain string is compiled.
key (callable, optional) –
value -> sort keywhen rank is omitted. Defaults to a natural sort, so"ER_g2"precedes"ER_g10".na ({"last", "first", "raise"}, default "last") – What an unrankable or null value costs.
"raise"errors; the others put those neurons after or before the ranked ones, keeping annotation row order inside that group.
- Return type:
Examples
>>> NestedMatrix.by("cell_instance") >>> NestedMatrix.by("cell_instance", "cell_subtype", rank=EB_RING) >>> NestedMatrix.by("cell_instance", extract=r"([LR]\d+)", rank=PB)
- classmethod from_connectivity(connections_df, neuron_annotations, source_types=None, target_types=None, source_ids=None, target_ids=None, cell_type_column='cell_type', neuron_id_column='root_id', order=None, source_order=None, target_order=None, annotation_scope='annotated_only')[source]#
Create a rectangular directed nested matrix from connectivity data.
- Parameters:
connections_df (pd.DataFrame) – Any format accepted by
NestedMatrix.from_connectivity().neuron_annotations (pd.DataFrame) – Neuron ID and cell type columns.
source_types (selector, optional) – Keep only these cell types on the row / column axis.
target_types (selector, optional) – Keep only these cell types on the row / column axis.
source_ids (selector, optional) – Keep only these neuron IDs, unioned with the same axis’ type selector. Leaving both selectors for an axis
Nonekeeps every available neuron on it.target_ids (selector, optional) – Keep only these neuron IDs, unioned with the same axis’ type selector. Leaving both selectors for an axis
Nonekeeps every available neuron on it.cell_type_column (str) – Annotation column names.
neuron_id_column (str) – Annotation column names.
order (NestedMatrix.order, sequence or None, optional) – Shared axis order; a bare sequence is types-only shorthand.
source_order (optional) – Per-axis override of
order.target_order (optional) – Per-axis override of
order.annotation_scope ({"annotated_only", "all"}, default "annotated_only") – Which neurons to retain before axis selection.
- Return type:
- classmethod from_synapses(synapses_df, neuron_annotations, source_types=None, target_types=None, source_ids=None, target_ids=None, pre_col='pre_pt_root_id', post_col='post_pt_root_id', weight_mode='relative_outgoing', weight_column=None, normalization_scope='selected', cell_type_column='cell_type', neuron_id_column='root_id', order=None, source_order=None, target_order=None, annotation_scope='annotated_only')[source]#
Create a rectangular directed nested matrix from synapse rows.
Axis selection and ordering work as in
from_connectivity().normalization_scope="selected"(the default) normalizes relative weights after axis filtering;"all"normalizes by every partner first, then restricts to the selected axes.- Parameters:
synapses_df (pandas.DataFrame)
neuron_annotations (pandas.DataFrame)
source_types (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
target_types (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
source_ids (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
target_ids (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
pre_col (str)
post_col (str)
weight_mode (Literal['relative_outgoing', 'relative_incoming', 'count', 'column'])
weight_column (str | None)
normalization_scope (Literal['selected', 'all'])
cell_type_column (str)
neuron_id_column (str)
order (MatrixOrder | Iterable[Any] | None)
source_order (MatrixOrder | Iterable[Any] | None)
target_order (MatrixOrder | Iterable[Any] | None)
annotation_scope (Literal['annotated_only', 'all'])
- Return type:
- classmethod from_synapses_by_neuropil(synapses_df, neuron_annotations, neuropil_names=None, coordinates='nm', position_column='ctr_pt_position', source_types=None, target_types=None, source_ids=None, target_ids=None, pre_col='pre_pt_root_id', post_col='post_pt_root_id', weight_mode='relative_outgoing', weight_column=None, normalization_scope='selected', cell_type_column='cell_type', neuron_id_column='root_id', order=None, source_order=None, target_order=None, annotation_scope='annotated_only', include_other=True, voxel_offset=None)[source]#
Create one DirectedNestedMatrix per neuropil, by mesh containment.
Arguments match
from_synapses()and apply independently inside each ROI. ROIs empty on either axis are skipped.- Parameters:
synapses_df (pandas.DataFrame)
neuron_annotations (pandas.DataFrame)
coordinates (str)
position_column (str)
source_types (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
target_types (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
source_ids (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
target_ids (str | bytes | int | float | bool | integer | floating | bool | Iterable[Any] | None)
pre_col (str)
post_col (str)
weight_mode (Literal['relative_outgoing', 'relative_incoming', 'count', 'column'])
weight_column (str | None)
normalization_scope (Literal['selected', 'all'])
cell_type_column (str)
neuron_id_column (str)
order (MatrixOrder | Iterable[Any] | None)
source_order (MatrixOrder | Iterable[Any] | None)
target_order (MatrixOrder | Iterable[Any] | None)
annotation_scope (Literal['annotated_only', 'all'])
include_other (bool)
- Return type:
- get_relative_weights(by_type=False)[source]#
Calculate row-normalized source-to-target weights.
- Parameters:
by_type (bool)
- Return type:
- property matrix: pandas.DataFrame#
Read-only source-to-target neuron connectivity matrix.
- property mean_type_matrix: pandas.DataFrame#
Mean source-to-target connectivity by source and target cell type.
- order(default=None, within=None)#
Build a reusable neuron order for a nested matrix axis.
Nested call:
NestedMatrix.order( types=["ER2", "EPG/PEG", "delta7"], default="id", within={"EPG/PEG": NestedMatrix.by("cell_instance", rank=EB_RING)}, )
Builder:
NestedMatrix.order().types(["ER2", "EPG/PEG"]).default("id").within( "EPG/PEG", NestedMatrix.by("cell_instance", rank=EB_RING) )
A bare sequence passed as
order=to a matrix constructor is still types-only shorthand forNestedMatrix.order(types=...).- Parameters:
- Return type:
- plot(output_path=None, level='neuron', figsize=(16, 14), show_neuron_labels=False, vmin_percentile=0.0, vmax_percentile=100.0, min_neurons_for_plot=1, linewidth_scale=1.0)[source]#
Plot the rectangular directed connectivity matrix as a heatmap.
- property source_neuron_to_type: Mapping[str, Any]#
Read-only mapping from source neuron ID to cell type.
- property source_neurons: tuple[str, ...]#
Resolved row order (not a filter – select with
source_types/source_ids).
- property source_type_boundaries: Mapping[str, tuple[int, int]]#
Read-only mapping from source cell type to its row slice.
- property source_untyped_neurons: tuple[str, ...]#
Row neurons with no cell type, appended after the blocks.
- property sum_type_matrix: pandas.DataFrame#
Sum source-to-target connectivity by source and target cell type.
- property target_neuron_to_type: Mapping[str, Any]#
Read-only mapping from target neuron ID to cell type.
- property target_neurons: tuple[str, ...]#
Resolved column order (not a filter – select with
target_types/target_ids).
- class crantpy.queries.NestedMatrix(matrix, type_boundaries, ordered_neurons, neuron_to_type)[source]#
Bases:
objectA square connectivity matrix with neurons grouped into cell type blocks.
ordered_neuronsistyped_neurons + untyped_neurons, and only the typed prefix is covered bytype_boundariesandneuron_to_type.- Parameters:
- matrix#
Neuron-by-neuron connectivity, ordered by type.
- Type:
pd.DataFrame
- type_boundaries#
Cell type -> half-open
(start, end)slice intoordered_neurons. Contiguous from 0, coveringtyped_neuronsonly.
- typed_neurons, untyped_neurons
The typed prefix and the untyped tail of
ordered_neurons.
Examples
>>> matrix = NestedMatrix.from_connectivity( ... connections_df=adjacency_df, ... neuron_annotations=annotations_df ... ) >>> type_matrix = matrix.sum_type_matrix >>> matrix.plot(level="type_mean")
- static by(*columns, rank=None, extract=None, key=None, na='last')#
Sort a cell type’s neurons by annotation column(s).
A string at the order layer is only a named rule (
"id","annotation","label","size"). Column names live here.- Parameters:
columns (str) – Annotation columns to read, in priority order. The first column that yields a usable value wins.
rank (sequence of str, optional) – Explicit label order. Without extract, the leftmost rank label that appears in the cell is used, so
"EPG/PEG_R1"and"Δ7_L8R1R9"both rank without a regex.extract (str or compiled pattern, optional) – Regex whose first group is the label. A plain string is compiled.
key (callable, optional) –
value -> sort keywhen rank is omitted. Defaults to a natural sort, so"ER_g2"precedes"ER_g10".na ({"last", "first", "raise"}, default "last") – What an unrankable or null value costs.
"raise"errors; the others put those neurons after or before the ranked ones, keeping annotation row order inside that group.
- Return type:
Examples
>>> NestedMatrix.by("cell_instance") >>> NestedMatrix.by("cell_instance", "cell_subtype", rank=EB_RING) >>> NestedMatrix.by("cell_instance", extract=r"([LR]\d+)", rank=PB)
- classmethod from_connectivity(connections_df, neuron_annotations, cell_type_column='cell_type', neuron_id_column='root_id', order=None, annotation_scope='annotated_only')[source]#
Create a NestedMatrix from an adjacency matrix or edge list.
Accepts the output of
cp.get_connectivity().- Parameters:
connections_df (pd.DataFrame) –
Connectivity data in one of the following formats: - Adjacency matrix (index and columns are neuron IDs) - Edge list with columns [‘type.from’, ‘type.to’, ‘weight’] - Edge list with columns [‘pre’, ‘post’, ‘weight’] - Edge list with columns [‘source’, ‘target’, ‘weight’] or [‘source’, ‘target’, ‘n_syn’]
where each row is already aggregated to a unique source-target pair, such as the output of
cp.get_connectivity()neuron_annotations (pd.DataFrame) – Neuron annotations; needs at least the ID and cell type columns.
cell_type_column (str) – Annotation column names.
neuron_id_column (str) – Annotation column names.
order (NestedMatrix.order, sequence or None, optional) – How to order cell type blocks and the neurons inside them. Build one with
NestedMatrix.order(...)or the chained builder; a bare sequence is types-only shorthand.annotation_scope ({"annotated_only", "all"}, default "annotated_only") –
"annotated_only"keeps only annotated neurons;"all"keeps every neuron, appending the untyped ones after the typed blocks.
- Return type:
Examples
>>> adjacency = pd.DataFrame({ ... 1: [0, 10, 0], 2: [5, 0, 15], 3: [0, 20, 0] ... }, index=[1, 2, 3]) >>> annotations = pd.DataFrame({ ... 'root_id': [1, 2, 3], ... 'cell_type': ['ER', 'ER', 'Pbt'] ... }) >>> matrix = NestedMatrix.from_connectivity(adjacency, annotations)
- classmethod from_synapses(synapses_df, neuron_annotations, pre_col='pre_pt_root_id', post_col='post_pt_root_id', weight_mode='relative_outgoing', weight_column=None, cell_type_column='cell_type', neuron_id_column='root_id', order=None, annotation_scope='annotated_only')[source]#
Create a NestedMatrix from a synapse dataframe.
Returns one matrix over all supplied synapses. For ROI-specific output, pre-filter
synapses_dfor usefrom_synapses_by_neuropil().- Parameters:
synapses_df (pd.DataFrame) – Synapse rows, with pre- and postsynaptic ID columns.
neuron_annotations (pd.DataFrame) – Neuron annotations; needs at least the ID and cell type columns.
pre_col (str) – Pre- and postsynaptic ID columns in
synapses_df.post_col (str) – Pre- and postsynaptic ID columns in
synapses_df.weight_mode ({"relative_outgoing", "relative_incoming", "count", "column"}, default "relative_outgoing") – Edge weights per pre/post pair: raw synapse
"count", that count normalized so each row ("relative_outgoing") or column ("relative_incoming") sums to 1, or the sum ofweight_column("column").weight_column (str | None, optional) – Column to sum. Required for
weight_mode="column", rejected otherwise.cell_type_column (str) – Annotation column names.
neuron_id_column (str) – Annotation column names.
order (NestedMatrix.order, sequence or None, optional) – How to order cell type blocks and the neurons inside them. Build one with
NestedMatrix.order(...)or the chained builder; a bare sequence is types-only shorthand.annotation_scope ({"annotated_only", "all"}, default "annotated_only") –
"annotated_only"keeps only rows whose pre and post neurons are both annotated;"all"keeps every row and appends the untyped neurons after the typed blocks.
- Return type:
Examples
>>> synapses = pd.DataFrame({ ... 'pre_pt_root_id': [1, 1, 2], ... 'post_pt_root_id': [3, 4, 3], ... 'Weight': [10, 20, 15] ... }) >>> annotations = pd.DataFrame({ ... 'root_id': [1, 2, 3, 4], ... 'cell_type': ['KC', 'KC', 'MB', 'MB'] ... }) >>> matrix = NestedMatrix.from_synapses( ... synapses, ... annotations, ... weight_mode="column", ... weight_column="Weight", ... ) >>> relative = NestedMatrix.from_synapses( ... synapses, ... annotations, ... weight_mode="relative_outgoing", ... ) >>> # For neuropil ROI-specific matrices, use: >>> # NestedMatrix.from_synapses_by_neuropil(...)
- classmethod from_synapses_by_neuropil(synapses_df, neuron_annotations, neuropil_names=None, coordinates='nm', position_column='ctr_pt_position', pre_col='pre_pt_root_id', post_col='post_pt_root_id', weight_mode='relative_outgoing', weight_column=None, cell_type_column='cell_type', neuron_id_column='root_id', order=None, annotation_scope='annotated_only', include_other=True, voxel_offset=None)[source]#
Create NestedMatrix instances per neuropil using mesh containment.
Assigns each synapse to ROIs by testing its coordinates against the neuropil meshes, then builds one matrix per ROI that holds synapses. All other arguments match
from_synapses()and apply independently inside each ROI.- Parameters:
synapses_df (pd.DataFrame) – Synapse rows, with the position and pre/post ID columns.
neuron_annotations (pd.DataFrame) – Neuron annotations; needs at least the ID and cell type columns.
neuropil_names (list[str] | None, optional) – Mesh names from
NEUROPIL_MESH_DICT;Noneuses all of them.coordinates ({"nm", "pixels"}, default "nm") – Units of
position_column. Meshes are in nm;"pixels"is converted using the configured scale factors.position_column (str, default "ctr_pt_position") – Column holding
[x, y, z]coordinates.pre_col (str) – Pre- and postsynaptic ID columns in
synapses_df.post_col (str) – Pre- and postsynaptic ID columns in
synapses_df.weight_mode (Literal['relative_outgoing', 'relative_incoming', 'count', 'column']) – As in
from_synapses(), applied within each ROI subset.weight_column (str | None) – As in
from_synapses(), applied within each ROI subset.cell_type_column (str) – Annotation column names.
neuron_id_column (str) – Annotation column names.
order (NestedMatrix.order, sequence or None, optional) – How to order cell type blocks and the neurons inside them. Build one with
NestedMatrix.order(...)or the chained builder; a bare sequence is types-only shorthand.annotation_scope ({"annotated_only", "all"}, default "annotated_only") – As in
from_synapses(), applied before ROI assignment.include_other (bool, default True) – Collect synapses outside every mesh under an
"other"key.voxel_offset (tuple[float, float, float] | None, optional) – Added to pixel coordinates before nm conversion, to align them with the meshes. Only used when
coordinates="pixels".
- Returns:
Dict-like, mapping ROI name (plus
"other") to a NestedMatrix. Supportscollection.plot(name, ...)and attribute access.- Return type:
- Raises:
ValueError – On an unknown neuropil name or
coordinatesvalue.
Examples
>>> matrices = NestedMatrix.from_synapses_by_neuropil( ... synapses_df=synapses, ... neuron_annotations=annotations, ... neuropil_names=["antennal_lobe_left", "mushroom_body_pedunculus_and_lobes_left"], ... coordinates="nm", ... ) >>> for name, mat in matrices.items(): ... print(name, mat.sum_type_matrix.shape)
- get_relative_weights(by_type=False)[source]#
Row-normalized weights: each source’s share of output per target.
Each row is divided by its own sum, so rows sum to 1.0 – except a row whose weights sum to zero, which is left unchanged. That covers rows with no output, and also rows whose positive and negative weights cancel. Set by_type to compute this at the cell type level instead of the neuron level.
- Parameters:
by_type (bool)
- Return type:
- property matrix: pandas.DataFrame#
Read-only neuron-to-neuron connectivity matrix.
- property mean_type_matrix: pandas.DataFrame#
Mean weight across each type-pair block (read-only view).
Zero entries count towards the mean, so large cell types don’t dominate just by having more neurons.
- property neuron_to_type: Mapping[str, Any]#
Read-only neuron ID -> cell type, for
typed_neuronsonly.
- static order(types='label', default=None, within=None)#
Build a reusable neuron order for a nested matrix axis.
Nested call:
NestedMatrix.order( types=["ER2", "EPG/PEG", "delta7"], default="id", within={"EPG/PEG": NestedMatrix.by("cell_instance", rank=EB_RING)}, )
Builder:
NestedMatrix.order().types(["ER2", "EPG/PEG"]).default("id").within( "EPG/PEG", NestedMatrix.by("cell_instance", rank=EB_RING) )
A bare sequence passed as
order=to a matrix constructor is still types-only shorthand forNestedMatrix.order(types=...).- Parameters:
- Return type:
- property ordered_neurons: tuple[str, ...]#
typed_neurons + untyped_neurons.- Type:
Neuron order for both axes
- plot(output_path=None, level='neuron', figsize=(16, 14), show_neuron_labels=False, vmin_percentile=0.0, vmax_percentile=100.0, min_neurons_for_plot=1, linewidth_scale=1.0)[source]#
Plot the connectivity matrix as a heatmap.
- Parameters:
output_path (str | None, optional) – Save the figure here, creating the directory if needed.
level ({"neuron", "type_mean", "type_sum"}, default "neuron") – Plot the neuron-level matrix with nested type boundaries, or
mean_type_matrix/sum_type_matrix.figsize (tuple[int, int], default (16, 14)) – Figure size in inches.
show_neuron_labels (bool, default False) – Label axes with neuron IDs instead of type names.
level="neuron"only.vmin_percentile (float, default 0.0 and 100.0) – Color scale range, as percentiles over the strictly positive values – so zeros always map to the bottom, and any negative weights are excluded from the range and clipped. (Negatives reach the matrix through
from_connectivity(), which passes weights through unchanged, or throughweight_mode="column".) A vmax below 100 clips the strongest connections, making mid-range weights visible.vmax_percentile (float, default 0.0 and 100.0) – Color scale range, as percentiles over the strictly positive values – so zeros always map to the bottom, and any negative weights are excluded from the range and clipped. (Negatives reach the matrix through
from_connectivity(), which passes weights through unchanged, or throughweight_mode="column".) A vmax below 100 clips the strongest connections, making mid-range weights visible.min_neurons_for_plot (int, default 1) – Drop types with fewer neurons than this.
level="neuron"only; the type-level matrices are plotted whole.linewidth_scale (float, default 1.0) – Multiplier on the default boundary line widths.
- Return type:
tuple[plt.Figure, plt.Axes]
Examples
>>> fig, ax = matrix.plot(level="type_mean", output_path='conn.png')
- property sum_type_matrix: pandas.DataFrame#
Total weight between each pair of cell types (read-only view).
>>> matrix.sum_type_matrix.loc['KC', 'MB']
- property type_boundaries: Mapping[str, tuple[int, int]]#
Read-only mapping from cell type to its matrix slice.
- property typed_neurons: tuple[str, ...]#
Neurons carrying a cell type – exactly those inside
type_boundaries.
- property untyped_neurons: tuple[str, ...]#
Neurons with no cell type, appended after every block.
Present in
matrixbut excluded from type-level aggregation. Ordered as neurons whose annotation row has a null cell type – which survive the defaultannotation_scope="annotated_only"– then, underannotation_scope="all", neurons with no annotation row at all, each group sorted by neuron ID as a string (so"30"precedes"7").
- class crantpy.queries.NeuropilCollection[source]#
Bases:
dictDict subclass mapping neuropil names to nested matrix instances.
Provides convenience methods for accessing and plotting individual neuropil/ROI matrices with cleaner syntax.
Examples
>>> matrices = NestedMatrix.from_synapses_by_neuropil(...) >>> matrices.plot("protocerebral_bridge", level="neuron") >>> matrices.plot(All) >>> matrices.plot(All.minus("fan_shaped_body")) >>> matrices.protocerebral_bridge.sum_type_matrix
- plot(name, **kwargs)[source]#
Plot connectivity matrix/matrices.
- Parameters:
name (str or All selector) – A single neuropil name, or
All/All.minus(...)to plot multiple neuropils at once.**kwargs – Forwarded to the contained matrix object’s
plot()method.
- Returns:
tuple[Figure, Axes] – When name is a single neuropil string.
dict[str, tuple[Figure, Axes]] – When name is an
Allselector.
- Return type:
- crantpy.queries.attach_synapses(neurons, pre=True, post=True, threshold=1, min_size=None, materialization='latest', clean=True, max_distance=10000.0, update_ids=True, dataset=None)[source]#
Attach synapses as connectors to skeleton neurons.
This function fetches synapses for the given neuron(s) and maps them to the closest node on each skeleton using a KD-tree. The synapses are attached as a .connectors table with columns for connector_id, x, y, z, type (pre/post), partner_id, and node_id.
Adapted from fafbseg-py (Philipp Schlegel) to work with CRANTb data.
- Parameters:
neurons (navis.TreeNeuron or navis.NeuronList) – Skeleton neuron(s) to attach synapses to. Must be TreeNeuron objects with node coordinates.
pre (bool, default True) – Whether to fetch and attach presynapses (outputs) for the given neurons.
post (bool, default True) – Whether to fetch and attach postsynapses (inputs) for the given neurons.
threshold (int, default 1) – Minimum number of synapses required between neuron pairs to be included.
min_size (int, optional) – Minimum synapse size for filtering.
materialization (str, default 'latest') – Materialization version to use. Either ‘latest’ or ‘live’.
clean (bool, default True) – Whether to perform cleanup of synapse data: - Remove autapses (self-connections) - Remove connections involving neuron ID 0 (background) - Remove synapses that are too far from skeleton nodes (see max_distance)
max_distance (float, default 10000.0) – Maximum distance (in nanometers) between a synapse and its nearest skeleton node. Synapses further than this are removed if clean=True. The default of 10um helps filter out spurious synapse annotations far from the actual neuron.
update_ids (bool, default True) – Whether to automatically update outdated root IDs to their latest versions before querying. This ensures accurate results even after segmentation edits. Uses efficient per-ID caching to minimize overhead for repeated queries. Set to False only if you’re certain all IDs are current (faster but risky).
dataset (str, optional) – Dataset to use for queries.
- Returns:
The same neuron(s) with .connectors table attached. The connectors table includes columns: - connector_id: Unique ID for each synapse (sequential) - x, y, z: Synapse coordinates in nanometers - type: ‘pre’ for presynapses, ‘post’ for postsynapses - partner_id: Root ID of the partner neuron - node_id: ID of the skeleton node closest to this synapse
Note: The input neurons are modified in place and also returned.
- Return type:
navis.TreeNeuron or navis.NeuronList
- Raises:
TypeError – If neurons is not a TreeNeuron or NeuronList of TreeNeurons.
ValueError – If both pre and post are False.
Examples
>>> import crantpy as cp >>> # Get a skeleton neuron >>> skeleton = cp.get_l2_skeleton(576460752664524086) >>> >>> # Attach synapses to it >>> skeleton = cp.attach_synapses(skeleton) >>> >>> # View the connectors table >>> print(skeleton.connectors.head()) >>> >>> # Get only presynapses >>> skeleton = cp.attach_synapses(skeleton, post=False) >>> >>> # Filter distant synapses more aggressively >>> skeleton = cp.attach_synapses(skeleton, max_distance=5000) >>> >>> # Skip ID updates for faster queries (use only if IDs are known to be current) >>> skeleton = cp.attach_synapses(skeleton, update_ids=False)
See also
get_synapsesFetch synapse data without attaching to neurons.
Notes
This function modifies the input neurons in place by adding/updating the .connectors attribute.
Synapses are mapped to skeleton nodes using scipy’s KDTree for efficient nearest neighbor search.
The connector_id is a sequential integer starting from 0, not the original synapse ID from the database.
If a neuron already has a .connectors table, it will be overwritten.
Synapse coordinates are automatically converted from pixels to nanometers to match skeleton coordinate system (using SCALE_X=8, SCALE_Y=8, SCALE_Z=42).
When update_ids=True (default), IDs are automatically updated with efficient caching
- crantpy.queries.get_adjacency(pre_ids=None, post_ids=None, threshold=1, min_size=None, materialization='latest', symmetric=False, clean=True, update_ids=True, dataset=None)[source]#
Construct an adjacency matrix from synaptic connections between neurons.
This function queries the synapses table to get connections between specified pre- and post-synaptic neurons, then constructs an adjacency matrix showing the number of synapses between each pair.
- Parameters:
pre_ids (int, str, list, NeuronCriteria, optional) – Pre-synaptic neuron root IDs or criteria. If None, all pre-synaptic neurons in the dataset will be included.
post_ids (int, str, list, NeuronCriteria, optional) – Post-synaptic neuron root IDs or criteria. If None, all post-synaptic neurons in the dataset will be included.
threshold (int, default 1) – Minimum number of synapses required between a pair to be included in the adjacency matrix.
min_size (int, optional) – Minimum size for filtering synapses before constructing adjacency matrix.
materialization (str, default 'latest') – Materialization version to use. ‘latest’ (default) or ‘live’ for live table.
symmetric (bool, default False) – If True, return a symmetric adjacency matrix with the same set of IDs on both rows and columns. The neuron set includes all neurons that appear in the filtered synapses data (union of all pre- and post-synaptic neurons). This provides a complete view of connectivity among all neurons involved in the queried connections. If False (default), rows represent pre-synaptic neurons and columns represent post-synaptic neurons from the actual synapses data.
clean (bool, default True) – Whether to perform cleanup of the underlying synapse data: - Remove autapses (self-connections) - Remove connections involving neuron ID 0 (background) This parameter is passed to get_synapses().
update_ids (bool, default True) – Whether to automatically update outdated root IDs to their latest versions before querying. This ensures accurate results even after segmentation edits. Uses efficient per-ID caching to minimize overhead for repeated queries. Set to False only if you’re certain all IDs are current (faster but risky).
dataset (str, optional) – Dataset to use for the query.
- Returns:
An adjacency matrix where each entry [i, j] represents the number of synapses from neuron i (pre-synaptic) to neuron j (post-synaptic). Rows are pre-synaptic neurons, columns are post-synaptic neurons.
- Return type:
pd.DataFrame
Examples
>>> import crantpy as cp >>> # Get adjacency between specific neurons >>> adj = cp.get_adjacency(pre_ids=[576460752641833774], post_ids=[576460752777916050]) >>> >>> # Get adjacency with minimum threshold >>> adj = cp.get_adjacency(pre_ids=[576460752641833774], post_ids=[576460752777916050], threshold=3) >>> >>> # Get symmetric adjacency matrix >>> adj = cp.get_adjacency(pre_ids=[576460752641833774], post_ids=[576460752777916050], symmetric=True) >>> >>> # Get adjacency matrix with autapses included >>> adj = cp.get_adjacency(pre_ids=[576460752641833774], post_ids=[576460752777916050], clean=False) >>> >>> # Skip ID updates for faster queries (use only if IDs are known to be current) >>> adj = cp.get_adjacency(pre_ids=[576460752641833774], post_ids=[576460752777916050], update_ids=False)
Notes
This function uses get_synapses() internally to retrieve synaptic connections
If both pre_ids and post_ids are None, this will query all synapses in the dataset
The threshold parameter filters connection pairs, not individual synapses
When symmetric=True, the resulting matrix includes all neurons that appear in the filtered synapses data, ensuring complete connectivity visualization
When symmetric=False, the matrix may be rectangular with different neuron sets for rows (pre-synaptic) and columns (post-synaptic)
When clean=True (default), autapses and background connections are removed
When update_ids=True (default), IDs are automatically updated with efficient caching
- crantpy.queries.get_connectivity(neuron_ids, upstream=True, downstream=True, threshold=1, min_size=None, materialization='latest', clean=True, update_ids=True, dataset=None)[source]#
Fetch connectivity information for given neuron(s) in CRANTb.
This function retrieves synaptic connections for the specified neurons, returning a table of connections with pre-synaptic neurons, post-synaptic neurons, and synapse counts.
- Parameters:
neuron_ids (int, str, list, NeuronCriteria) – Neuron root ID(s) to query connectivity for. Can be a single ID, list of IDs, or NeuronCriteria object.
upstream (bool, default True) – Whether to fetch upstream (incoming) connectivity to the query neurons.
downstream (bool, default True) – Whether to fetch downstream (outgoing) connectivity from the query neurons.
threshold (int, default 1) – Minimum number of synapses required between a pair to be included in the results.
min_size (int, optional) – Minimum size for filtering synapses before aggregating connections.
materialization (str, default 'latest') – Materialization version to use. ‘latest’ (default) or ‘live’ for live table.
clean (bool, default True) – Whether to perform cleanup of the underlying synapse data: - Remove autapses (self-connections) - Remove connections involving neuron ID 0 (background) This parameter is passed to get_synapses().
update_ids (bool, default True) – Whether to automatically update outdated root IDs to their latest versions before querying. This ensures accurate results even after segmentation edits. Uses efficient per-ID caching to minimize overhead for repeated queries. Set to False only if you’re certain all IDs are current (faster but risky).
dataset (str, optional) – Dataset to use for the query.
- Returns:
Connectivity table with columns: - ‘pre’: pre-synaptic neuron ID - ‘post’: post-synaptic neuron ID - ‘weight’: number of synapses between the pair
- Return type:
pd.DataFrame
- Raises:
ValueError – If both upstream and downstream are False.
Examples
>>> import crantpy as cp >>> # Get all connections for a neuron >>> conn = cp.get_connectivity(576460752641833774) >>> >>> # Get only downstream connections with threshold >>> conn = cp.get_connectivity(576460752641833774, upstream=False, threshold=3) >>> >>> # Get connectivity for multiple neurons >>> conn = cp.get_connectivity([576460752641833774, 576460752777916050]) >>> >>> # Skip ID updates for faster queries (use only if IDs are known to be current) >>> conn = cp.get_connectivity(576460752641833774, update_ids=False)
Notes
This function uses get_synapses() internally to retrieve synaptic connections
Results are aggregated by pre-post neuron pairs and sorted by synapse count
When clean=True, autapses and background connections are removed
When update_ids=True (default), IDs are automatically updated with efficient caching
- crantpy.queries.get_synapse_counts(neuron_ids, threshold=1, min_size=None, materialization='latest', clean=True, update_ids=True, dataset=None)[source]#
Get synapse counts (pre and post) for given neuron IDs in CRANTb.
This function returns the total number of presynaptic and postsynaptic connections for each specified neuron, aggregated across all their partners.
- Parameters:
neuron_ids (int, str, list, NeuronCriteria) – Neuron root ID(s) to get synapse counts for. Can be a single ID, list of IDs, or NeuronCriteria object.
threshold (int, default 1) – Minimum number of synapses required between a pair to be counted towards the total. Pairs with fewer synapses are excluded.
min_size (int, optional) – Minimum size for filtering individual synapses before counting.
materialization (str, default 'latest') – Materialization version to use. ‘latest’ (default) or ‘live’ for live table.
clean (bool, default True) – Whether to perform cleanup of the underlying synapse data: - Remove autapses (self-connections) - Remove connections involving neuron ID 0 (background) This parameter is passed to get_connectivity().
update_ids (bool, default True) – Whether to automatically update outdated root IDs to their latest versions before querying. This ensures accurate results even after segmentation edits. Uses efficient per-ID caching to minimize overhead for repeated queries. Set to False only if you’re certain all IDs are current (faster but risky).
dataset (str, optional) – Dataset to use for the query.
- Returns:
DataFrame with columns: - index: neuron IDs - ‘pre’: number of presynaptic connections (outgoing) - ‘post’: number of postsynaptic connections (incoming)
- Return type:
pd.DataFrame
Examples
>>> import crantpy as cp >>> # Get synapse counts for a single neuron >>> counts = cp.get_synapse_counts(576460752641833774) >>> >>> # Get counts for multiple neurons with threshold >>> counts = cp.get_synapse_counts([576460752641833774, 576460752777916050], threshold=3) >>> >>> # Skip ID updates for faster queries (use only if IDs are known to be current) >>> counts = cp.get_synapse_counts(576460752641833774, update_ids=False)
Notes
This function uses get_connectivity() internally to get connection data
Counts represent the number of distinct synaptic partners, not individual synapses
The threshold is applied at the connection level (pairs of neurons)
When update_ids=True (default), IDs are automatically updated with efficient caching
- crantpy.queries.get_synapses(pre_ids=None, post_ids=None, threshold=1, min_size=None, materialization='latest', return_pixels=True, clean=True, update_ids=True, dataset=None)[source]#
Fetch synapses for a given set of pre- and/or post-synaptic neuron IDs in CRANTb.
- Parameters:
pre_ids (int, str, list of int/str, NeuronCriteria, optional) – Pre-synaptic neuron root ID(s) to include. Can be a single ID, list of IDs, or NeuronCriteria object.
post_ids (int, str, list of int/str, NeuronCriteria, optional) – Post-synaptic neuron root ID(s) to include. Can be a single ID, list of IDs, or NeuronCriteria object.
threshold (int, default 1) – Minimum number of synapses required for a partner to be retained. Currently we don’t know what a good threshold is.
min_size (int, optional) – Minimum size for filtering synapses. Currently we don’t know what a good size is.
materialization (str, default 'latest') – Materialization version to use. ‘latest’ (default) or ‘live’ for live table.
return_pixels (bool, default True) – Whether to convert coordinate columns from nanometers to pixels. If True (default), coordinates in ctr_pt_position, pre_pt_position, and post_pt_position are converted using dataset scale factors. If False, coordinates remain in nanometer units.
clean (bool, default True) – Whether to perform cleanup of the synapse data: - Remove autapses (self-connections) - Remove connections involving neuron ID 0 (background)
update_ids (bool, default True) – Whether to automatically update outdated root IDs to their latest versions before querying. This ensures accurate results even after segmentation edits. Uses efficient per-ID caching to minimize overhead for repeated queries. Set to False only if you’re certain all IDs are current (faster but risky).
dataset (str, optional) – Dataset to use for the query.
- Returns:
DataFrame of synaptic connections.
- Return type:
pd.DataFrame
- Raises:
ValueError – If neither pre_ids nor post_ids are provided.
Notes
When update_ids=True (default), outdated root IDs are automatically updated using supervoxel IDs from annotations when available for fast, reliable updates
ID updates are cached per-ID, so repeated queries with overlapping IDs are efficient
Updated IDs are used for the query, but the original IDs are not modified in place
See also
update_idsManually update root IDs to their latest versions