crantpy.queries package#

Submodules#

Module contents#

class crantpy.queries.NeuronCriteria(*, regex=False, case=False, verbose=False, clear_cache=False, match_all=False, exact=True, dataset=None, **criteria)[source]#

Bases: object

Parses filter queries into root IDs using Seatable.

This class allows filtering neurons based on various criteria defined in the Seatable annotations table.

Filtering for multiple criteria is done using a logical AND, i.e. only neurons that match all criteria will be selected.

Not providing any criteria will return all neurons in the annotations table.

Parameters:
  • regex (bool, default False) – Whether to interpret string criteria as regex.

  • case (bool, default False) – Whether to interpret string criteria as case sensitive (only applies when regex=True).

  • verbose (bool, default False) – Whether to print information about the query process.

  • clear_cache (bool, default False) – Whether to force reloading annotations from Seatable, bypassing the cache.

  • match_all (bool, default False) – When filtering by a list of values on a column that contains lists (e.g., status=[‘DAMAGED’, ‘TRACING_ISSUE’]), setting match_all=True will only return neurons where the column contains all the specified values. If False (default), it returns neurons where the column contains any of the specified values.

  • exact (bool, default True) – Whether to match values exactly. If False, substring matching is enabled.

  • dataset (str, optional) – The dataset to fetch annotations from.

  • **criteria (dict) – Filtering criteria where keys are column names from NeuronCriteria.available_fields() and values are the desired values or lists of values to filter by.

Examples

>>> from crantbseg.crantb.annotations import NeuronCriteria as NC
>>> # Check available fields
>>> NC.available_fields()
['root_id', 'nucleus_id', ...]
>>> # Get all neurons (will print a warning)
>>> all_neurons = NC()
>>> # Get neurons by cell class
>>> ol_neurons = NC(cell_class='olfactory_projection_neuron')
>>> # Get neurons by multiple cell types using regex
>>> pns = NC(cell_type=['PN_.*', 'mPN_.*'], regex=True)
>>> # Get neurons by side and status (any status in the list)
>>> left_proofread = NC(side='L', status=['BACKBONE_PROOFREAD', 'PRELIM_PROOFREAD'])
>>> # Get neurons by side and status (must have BOTH statuses)
>>> left_damaged_and_tracing = NC(side='L', status=['DAMAGED', 'TRACING_ISSUE'], match_all=True)
>>> # Use in functions expecting root IDs
>>> neuron_data = some_function(NC(cell_class='picky_neuron'))
property annotations: pandas.DataFrame#

Return annotations table (DataFrame), loading if necessary.

Returns:

DataFrame containing the annotations from Seatable.

Return type:

pd.DataFrame

classmethod available_fields()[source]#

Return all available fields for selection.

Returns:

List of field names that can be used for filtering.

Return type:

List[str]

get_roots()[source]#

Return all root IDs matching the given criteria.

Returns:

Array of root IDs matching the given criteria.

Return type:

numpy.ndarray

Raises:

NoMatchesError – If no neurons are found matching the given criteria.

property is_empty: bool#

Returns True if no criteria are specified.

Returns:

True if no criteria are specified, False otherwise.

Return type:

bool

to_neuroglancer(**kwargs)[source]#

Create a neuroglancer URL for neurons matching the criteria.

This is a convenience method that generates a neuroglancer visualization URL for all neurons that match the current filter criteria.

Parameters:

**kwargs – Additional arguments passed to encode_url(). Common options: - seg_colors: Color scheme for segments - layout: Layout type (“3d”, “xy-3d”, “xy”, “4panel”) - coords: Center position [x, y, z] - open: Whether to open in browser - to_clipboard: Whether to copy to clipboard - shorten: Whether to create shortened URL

Returns:

Neuroglancer URL for the matching neurons.

Return type:

str

Examples

>>> from crantpy import NeuronCriteria
>>> nc = NeuronCriteria(cell_class='olfactory_projection_neuron')
>>> url = nc.to_neuroglancer(seg_colors=np.arange(len(nc.get_roots())))
>>>
>>> # With custom settings
>>> url = nc.to_neuroglancer(layout='4panel', open=True, shorten=True)

See also

crantpy.utils.neuroglancer.encode_url

Full documentation of available parameters

crantpy.queries.get_adjacency(pre_ids=None, post_ids=None, threshold=1, min_size=None, materialization='latest', symmetric=False, clean=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().

  • 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)

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

crantpy.queries.get_annotations(neurons, dataset=None, clear_cache=False, proofread_only=False)[source]#

Get annotations from Seatable.

Parameters:
  • neurons (int, str, list of int/str, or NeuronCriteria) – Neuron root ID(s) or a NeuronCriteria instance specifying which neurons to fetch. Accepts a single ID, a list/array of IDs, or a NeuronCriteria object.

  • dataset (str, optional) – Dataset to fetch annotations from.

  • clear_cache (bool, default False) – Whether to force reloading annotations from Seatable, bypassing the cache.

  • proofread_only (bool, default False) – Whether to return only annotations marked as proofread.

Returns:

DataFrame containing the annotations for the specified neurons.

Return type:

pd.DataFrame

Raises:
crantpy.queries.get_connectivity(neuron_ids, upstream=True, downstream=True, threshold=1, min_size=None, materialization='latest', clean=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().

  • 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])

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

crantpy.queries.get_synapse_counts(neuron_ids, threshold=1, min_size=None, materialization='latest', clean=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().

  • 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)

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)

crantpy.queries.get_synapses(pre_ids=None, post_ids=None, threshold=1, min_size=None, materialization='latest', return_pixels=True, clean=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)

  • 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.

crantpy.queries.is_proofread(neurons, dataset=None, clear_cache=False)[source]#

Check if the specified neurons are proofread.

Parameters:
  • neurons (Neurons = Neurons = str | int | np.int64 | navis.BaseNeuron | Iterables of previous types | navis.NeuronList | NeuronCriteria) – Neurons to check for proofread status.

  • dataset (str, optional) – Dataset to fetch annotations from.

  • clear_cache (bool, default False) – Whether to force updating annotations from Seatable, bypassing the cache.

Returns:

A boolean array indicating whether each neuron is proofread.

Return type:

np.ndarray

crantpy.queries.parse_neuroncriteria(*args, **kwargs)#

Deprecated: parse_neuroncriteria has moved to crantpy.utils.decorators.

This function will be removed in a future version. Please update your imports:

OLD: from crantpy.queries.neurons import parse_neuroncriteria NEW: from crantpy.utils.decorators import parse_neuroncriteria