crantpy.utils.helpers module#
This module contains helper functions for crantpy.
- crantpy.utils.helpers.create_sql_query(table_name, fields, condition=None, limit=None, start=None)[source]#
Creates a SQL query to get the specified fields from the specified table.
- Parameters:
table_name (str) β The name of the table to query.
fields (List[str]) β The list of field names to include in the query.
condition (str, optional) β The WHERE clause of the query.
limit (int, optional) β The maximum number of rows to return.
start (int, optional) β The number of rows to skip (OFFSET).
- Returns:
The constructed SQL query string.
- Return type:
- crantpy.utils.helpers.filter_df(df, column, value, regex=False, case=False, match_all=False, exact=True)[source]#
This function filters a df based on a column and a value. It can handle string, numeric, and list-containing columns.
- Parameters:
(pd.DataFrame) (df)
(str) (column)
(Any) (value)
(bool) (exact)
(bool)
(bool) β if True, requires all filter values to be present in the cellβs list. If False, requires at least one filter value to be present. Defaults to False.
(bool)
df (pandas.DataFrame)
column (str)
value (Any)
regex (bool)
case (bool)
match_all (bool)
exact (bool)
- Returns:
pd.DataFrame
- Return type:
The filtered df.
- crantpy.utils.helpers.make_iterable(x, force_type=None)[source]#
Convert input to an numpy array.
- Parameters:
x (Any) β The input to convert.
force_type (Optional[type]) β If specified, the input will be cast to this type.
- Returns:
The converted numpy array.
- Return type:
np.ndarray
- crantpy.utils.helpers.map_position_to_node(neuron, position, return_distance=False)[source]#
Map a spatial position to the nearest node in a skeleton.
This utility function finds the closest node in a skeleton to a given position using a KDTree for efficient spatial lookup. Useful for soma detection, synapse attachment, and other spatial queries.
- Parameters:
neuron (navis.TreeNeuron) β The skeleton neuron to search.
position (list or np.ndarray) β The [x, y, z] coordinates to map. Should be in the same coordinate system as the neuron (typically nanometers).
return_distance (bool, optional) β If True, also return the Euclidean distance to the nearest node. Default is False.
- Returns:
node_id (int) β The node_id of the nearest node.
distance (float (optional)) β The Euclidean distance to the nearest node in nanometers. Only returned if return_distance=True.
- Return type:
Examples
>>> import crantpy as cp >>> import numpy as np >>> skel = cp.get_l2_skeleton(576460752664524086) >>> # Map a position to nearest node >>> node_id = cp.map_position_to_node(skel, [240000, 85000, 96000]) >>> print(f"Nearest node: {node_id}") >>> # Get distance too >>> node_id, dist = cp.map_position_to_node(skel, [240000, 85000, 96000], return_distance=True) >>> print(f"Nearest node: {node_id} at distance {dist:.2f} nm")
See also
reroot_at_somaReroot a skeleton at its soma location.
detect_somaDetect soma location in a neuron.
- crantpy.utils.helpers.match_dtype(value, dtype)[source]#
Match the dtype of a value to a given dtype.
- Parameters:
- Returns:
The converted value.
- Return type:
Any
- Raises:
ValueError β If the dtype is not supported.
- crantpy.utils.helpers.parse_root_ids(neurons)[source]#
Parse various neuron input types to a list of root ID strings. :param neurons: The neuron(s) to parse. Can be a single root ID (int or str),
a list of root IDs, or a NeuronCriteria object.
- crantpy.utils.helpers.parse_timestamp(x)[source]#
Parse a timestamp string to Unix timestamp.
- Parameters:
x (Timestamp) β The timestamp string to parse. Int must be unix timestamp. String must be ISO 8601 - e.g. β2021-11-15β. datetime, np.datetime64, pd.Timestamp are also accepted.
- Returns:
The Unix timestamp.
- Return type:
- crantpy.utils.helpers.plot_em_image(x, y, z, size=1000)[source]#
Fetch and return an EM image slice from the precomputed CloudVolume. Currently only supports slices through the Z axis (i.e. XY plane).
- Parameters:
- Returns:
The EM image slice as a numpy array.
- Return type:
np.ndarray
- crantpy.utils.helpers.reroot_at_soma(neurons, soma_coords=None, detect_soma_kwargs=None, inplace=True, progress=False)[source]#
Reroot skeleton(s) at their soma location.
This convenience function combines soma detection and rerooting. If soma coordinates are not provided, they will be automatically detected using detect_soma(). The skeleton is then rerooted at the node nearest to the soma location.
- Parameters:
neurons (TreeNeuron | NeuronList) β Single neuron or list of neurons to reroot.
soma_coords (np.ndarray or list of np.ndarray, optional) β Soma coordinates in pixels [x, y, z]. If not provided, soma will be automatically detected using detect_soma(). For multiple neurons, provide a list of coordinates in the same order as neurons.
detect_soma_kwargs (dict, optional) β Additional keyword arguments to pass to detect_soma() if soma coordinates are not provided.
inplace (bool, optional) β If True, reroot neurons in place. If False, return rerooted copies. Default is True.
progress (bool, optional) β If True, show progress bar when processing multiple neurons or detecting somas. Default is False.
- Returns:
Rerooted neuron(s). Same as input if inplace=True, otherwise copies.
- Return type:
TreeNeuron | NeuronList
Examples
>>> import crantpy as cp >>> # Get skeleton >>> skel = cp.get_l2_skeleton(576460752664524086) >>> # Reroot at automatically detected soma >>> skel_rerooted = cp.reroot_at_soma(skel) >>> print(f"Root node: {skel_rerooted.root}") >>> # Reroot with provided soma coordinates >>> soma = [28000, 9000, 2200] # in pixels >>> skel_rerooted = cp.reroot_at_soma(skel, soma_coords=soma) >>> # Process multiple neurons >>> skels = cp.get_l2_skeleton([576460752664524086, 576460752590602315]) >>> skels_rerooted = cp.reroot_at_soma(skels, progress=True)
See also
map_position_to_nodeMap a position to the nearest node.
detect_somaDetect soma location in a neuron.