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:

str

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:

int | tuple[int, float]

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_soma

Reroot a skeleton at its soma location.

detect_soma

Detect soma location in a neuron.

crantpy.utils.helpers.match_dtype(value, dtype)[source]#

Match the dtype of a value to a given dtype.

Parameters:
  • value (Any) – The value to convert.

  • dtype (str or type) – The target dtype to convert to.

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.

Returns:

A list of root ID strings.

Return type:

List[str]

Parameters:

neurons (Union[int, str, List[Union[int, str]], NeuronCriteria])

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:

str

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:
  • x (int) – The x coordinate of the center of the image slice.

  • y (int) – The y coordinate of the center of the image slice.

  • z (int) – The z coordinate of the image slice.

  • size (int, optional) – The size of the image slice (default is 1000).

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_node

Map a position to the nearest node.

detect_soma

Detect soma location in a neuron.

crantpy.utils.helpers.retry(func, retries=5, cooldown=2)[source]#

Retry function on HTTPError.

This also suppresses UserWarnings (commonly raised by l2 cache requests)

Parameters:
  • cooldown (int | float) – Cooldown period in seconds between attempts.

  • retries (int) – Number of retries before we give up. Every subsequent retry will delay by an additional retry.

crantpy.utils.helpers.set_logging_level(level)[source]#

Sets the logging level for the logger.

Parameters:

level (str) – The logging level to set. Options are β€˜DEBUG’, β€˜INFO’, β€˜WARNING’, β€˜ERROR’, β€˜CRITICAL’.

Return type:

None