Welcome to CeDNe’s documentation!#
CeDNe: C. elegans Dynamic Network A composable framework for building, analyzing, and visualizing nervous systems.
This top-level module exports the core components (e.g., Worm, Neuron, NervousSystem) and utility functions (e.g., graph motifs, loaders, visualization) from its submodules.
Modules: - core: Core neuroscience data structures (neurons, networks, trials) - utils: High-level tools for graph analysis, data loading, and visualization
- class cedne.Animal(species='', name='', stage='', sex='', genotype='', **kwargs)[source]#
Bases:
objectThis is a full animal class
- save(file_path, file_format='pickle')[source]#
Saves the Organism object to a pickle file at the specified file path.
- Args:
file_path (str): The path to the pickle file.
- set_property(key, value)[source]#
Set a property of the organism.
- Args:
key (str): The name of the property. value: The value of the property.
- add_context(name, data=None)[source]#
Adds a context to the organism.
- Args:
name (str): The name of the context. data: Optional data to associate with the context.
- remove_context(name)[source]#
Removes a context from the organism and clears active_context if it was active.
- Args:
name (str): The name of the context to remove.
- get_context(name)[source]#
Get a context by name.
- Args:
name (str): The name of the context.
- Returns:
The context data, or None if not found.
- class cedne.Worm(name='', stage='Day-1 Adult', sex='Hermaphrodite', genotype='N2', **kwargs)[source]#
Bases:
AnimalThis is an explicit Worm class, a container for network(s).
- class cedne.Fly(name='', stage='Day-7 Adult', sex='Female', genotype='w1118 x Canton-S G1', **kwargs)[source]#
Bases:
AnimalThis is an explicit Fly class, a container for network(s).
- class cedne.Neuron(name: str, network: NervousSystem, **kwargs)[source]#
Bases:
CellModels a biological neuron
- add_trial(trial_num=0)[source]#
Adds a new trial to the trial dictionary of the current object with the given trial_num. If trial_num is not provided, it defaults to 0.
- Returns:
Trial: The newly added trial object.
- get_connections(paired_neuron=None, direction='both', connection_type='all')[source]#
Returns all connections that the neuron is involved in.
- Returns:
A list of connections where the neuron is present.
- Return type:
list
- get_connected_neurons(direction='both', weight_filter=1, connection_type='all')[source]#
Returns all connected neurons for this neuron.
- update_connections()[source]#
Updates the in_connections and out_connections dictionaries of the current object.
- outgoing(paired_neuron=None)[source]#
Returns a list of all outgoing connections from the current object.
- Returns:
A list of connections from the current object to other objects.
- Return type:
list
- incoming(paired_neuron=None)[source]#
Returns a list of all incoming connections to the current object.
- set_property(property_name, property_value)[source]#
Sets a new property attribute for the class.
- Args:
property_name (str): The name of the property. property_value: The value of the property.
- class cedne.NeuronGroup(network, members=None, group_name=None)[source]#
Bases:
objectThis contains a group of neurons in the network
- set_property(property_name, property_value)[source]#
Sets a new property attribute for all neurons in the group.
- get_property(property_name)[source]#
Returns the value of the specified property for all neurons in the group.
- remove_neuron(neuron: Neuron) None[source]#
Remove a neuron from the group.
- Args:
neuron: Neuron to remove.
- class cedne.NervousSystem(worm: Worm = None, network: str = 'Neutral', **kwargs)[source]#
Bases:
MultiDiGraph- This is the Nervous System class. This inherits from networkx.MultiDiGraph
and is the main high level class for the nervous system.
- property num_groups#
Returns the current number of Neuron Groups for the Nervous System.
- set_property(key, value)[source]#
Set a property of the nervous system.
- Args:
key (str): The name of the property. value: The value of the property.
- Returns:
None
- build_network(neuron_data, adj, label)[source]#
Make a network with the neurons.
- Args:
- neurons:
The file containing neuron information
- adj:
The adjacency matrix
- label:
The label for the network
- create_neurons(labels, **kwargs)[source]#
- Creates a set of Neuron objects based on the given labels,
types, categories, modalities, and positions.
- Args:
- labels (list):
A list of labels for the neurons.
- neuron_types (list, optional):
A list of types for the neurons. Defaults to None.
- categories (list, optional):
A list of categories for the neurons. Defaults to None.
- modalities (list, optional):
A list of modalities for the neurons. Defaults to None.
- positions (dict, optional):
A dictionary mapping labels to positions. Defaults to None.
- Returns:
None
- create_neurons_from(network, data=False)[source]#
Creates a set of Neuron objects based on the given network.
- Args:
- network (Network):
A Network object.
- data (bool, optional):
A flag indicating whether to include data in the Neuron objects. Defaults to False.
- create_connections(connection_dict)[source]#
Creates a set of connections from a dictinary of connections with pre-post pairs as keys and data as values.
- create_connections_from(network, data=False)[source]#
Creates a set of Connection objects based on the given network.
- Args:
- network (Network):
A Network object.
- data (bool, optional):
A flag indicating whether to include data in the Connection objects. Defaults to False.
- update_neurons()[source]#
Synchronizes the neurons dictionary with the network’s nodes. This should only be needed if the network’s nodes are modified directly.
- update_network()[source]#
Update the network by setting the network attribute of all connections to self.
- setup_connections(adjacency, connection_type, input_type='adjacency', **kwargs)[source]#
Set up connections between neurons based on the adjacency matrix and edge type.
- setup_chemical_connections(chemical_adjacency, **kwargs)[source]#
Set up chemical connections in the network based on the given adjacency dictionary.
- Parameters:
- chemical_adjacency (dict): A dictionary representing the adjacency of chemical synapses.
The keys are source neurons and the values are dictionaries where the keys are target neurons and the values are dictionaries containing the connection data.
- Returns:
None
This function iterates over the chemical_adjacency dictionary and adds chemical synapse edges between source neurons and target neurons if the connection weight is greater than 0. It uses the add_edge method to add the edge to the network and creates a Connection object to store the connection details. The created connection is added to the connections dictionary using a tuple of the source neuron, target neuron, and edge key as the key.
- setup_gap_junctions(gap_junction_adjacency)[source]#
Set up gap junctions in the network based on the given adjacency dictionary.
- Parameters:
- gap_junction_adjacency (dict): A dictionary representing the adjacency of gap junctions.
The keys are source neurons and the values are dictionaries where the keys are target neurons and the values are dictionaries containing the connection data.
- Returns:
None
This function iterates over the gap_junction_adjacency dictionary and adds gap junction edges between source neurons and target neurons if the connection weight is greater than 0. It uses the add_edge method to add the edge to the network and creates a Connection object to store the connection details. The created connection is added to the connections dictionary using a tuple of the source neuron, target neuron, and edge key as the key.
- Note:
The add_edge method is assumed to be defined in the class.
The Connection class is assumed to be defined in the class.
The neurons dictionary is assumed to be defined in the class.
- load_neuron_data(file, file_format='summary-xlsx')[source]#
Standard formats to load data into the network
- load_connection_data(file, file_format='summary-xlsx')[source]#
Standard formats to load data into the network
- subnetwork(neuron_names=None, name=None, connections=None, as_view=False, data=True)[source]#
Generates a subgraph of the network based on the given list of neuron names.
- Args:
neuron_names (List[str]): List of neuron names to include in the subgraph. connections (List[tuple]): List of connections to include in the subgraph.
- Returns:
NervousSystem: A deep copy of the subgraph generated from the neuron_names or connections. The subgraph contains a dictionary of neurons with their names as keys.
- join_networks(networks, mode='consensus')[source]#
Goes through the list of networks and joins them to the current graph.
- fold_network(fold_by, name=None, data='collect', exceptions=None, self_loops=True)[source]#
Fold the network based on a filter.
<TODO>
!!! The fold_by can also take Neuron Group objects as input.
</TODO>
- Args:
- fold_by (tuple): A tuple of length 2 specifying the neurons to fold.
The first element is the neurons to fold, and the second element is the neurons that are exempt from folding. The tuple can contain any neuron name as a string.
- data (str, optional): The data to use for folding. Defaults to ‘collect’.
- Available options are:
- ‘collect’: Collect the data together from all neurons in the fold_by
tuple, but keep them separate.
‘union’ : Union the data from all neurons in the fold_by tuple.
‘intersect’: Intersect the data from all neurons in the fold_by tuple.
- Returns:
None
- Raises:
AssertionError: If the length of fold_by is not 2.
- Notes:
This function folds the network by contracting the specified neurons. The neurons specified in exceptions will not be folded.
- reassign_connections()[source]#
Reassign connections after folding based on the folding _ids and correcting connection names.
- contract_neurons(pair, contracted_name, data='collect', copy_graph=False, self_loops=True)[source]#
Contract two neurons together. Currently, data from other nodes is stored in the contraction attribute on each contracted node. Attributes are currently carried on from the source neuron to the contraction.
- Args:
- pair (tuple):
Pair of neuron names to contract.
- copy_graph (bool):
If True, returns a new graph with the contraction. Otherwise, modifies the current graph.
- Returns:
- NervousSystem:
A deep copy of the subgraph generated from the neuron_names. The subgraph contains a dictionary of neurons with their names as keys. Only returned if copy_graph is True.
- contract_connections(contraction_dict)[source]#
Contracts the connections into a single connection and modifies the graph accordingly.
- copy_data_from(nervous_system)[source]#
Copies data from another nervous system to this one.
- Args:
- nervous_system (NervousSystem):
The nervous system to copy data from.
- Returns:
None
- connections_between(neuron1, neuron2, directed=True)[source]#
Returns connections between neurons in neuron list.
- return_network_where(neurons_have=None, connections_have=None, condition='AND')[source]#
Returns a subgraph view of the current network based on the specified conditions.
- Parameters:
- neurons_have (dict):
A dictionary of neuron attributes and their corresponding values. The subgraph will only include neurons that have all the specified attributes and values. Defaults to an empty dictionary.
- connections_have (dict):
A dictionary of connection attributes and their corresponding values. The subgraph will only include connections that have all the specified attributes and values. Defaults to an empty dictionary.
- condition (str):
The condition to apply when filtering neurons and connections. Can be ‘AND’ or ‘OR’. Default is ‘AND’.
- Returns:
networkx.classes.Graph: A subgraph view of the current network that satisfies the specified conditions.
- copy(name=None, copy_type='deep')[source]#
Returns a deep copy of the Nervous System object.
- Parameters:
- as_view (bool):
If True, the copy will be a view of the original graph. Default is False.
- Returns:
- object:
a deep copy of the Nervous System object.
- copy_neurons(name=None, data=False)[source]#
Copies the neurons from the network and creates a new network with them
- subgraph_view(filter_neurons=None, filter_connections=None)[source]#
Creates a read only view of a subgraph
- export_graph(path, fmt='dot')[source]#
Exports the graph to the specified path.
- Parameters:
- path (str):
The path to save the exported graph.
- Returns:
None
- remove_unconnected_neurons()[source]#
Removes neurons that are not connected to any other neurons.
- Returns:
None
- make_neuron_group(members, group_name=None)[source]#
Creates a neuron group with the specified members.
- Parameters:
- members (List[str]):
The list of members in the neuron group.
- groupname (str):
The name of the neuron group. Defaults to None.
- group_id (int, optional):
The ID of the neuron group. Defaults to 0.
- Returns:
NeuronGroup: The created neuron group.
- delete_neuron_group(groupname)[source]#
Deletes a neuron group with the specified name.
- Parameters:
groupname (str): The name of the neuron group to be deleted.
- Returns:
None
- make_connection_group(members, group_name=None)[source]#
Creates a connection group with the specified members.
- Parameters:
- members (List[str]):
The list of members in the connection group.
- groupname (str):
The name of the connection group. Defaults to None.
- group_id (int, optional):
The ID of the connection group. Defaults to 0.
- Returns:
ConnectionGroup: The created connection group.
- class cedne.Connection(pre: Neuron, post: Neuron, uid=None, connection_type='chemical-synapse', **kwargs)[source]#
Bases:
objectThis class represents a connection between two cells.
- property by_name#
Returns the connecting neuron names (Pre,Post)
- class cedne.ChemicalSynapse(pre, post, uid=0, connection_type='chemical-synapse', weight=1, **kwargs)[source]#
Bases:
ConnectionThis is a convenience class that represents connections of type chemical synapses.
- class cedne.GapJunction(pre, post, uid=1, connection_type='gap-junction', weight=1, **kwargs)[source]#
Bases:
ConnectionThis is a convenience class that represents connections of type gap junctions.
- class cedne.BulkConnection(pre, post, uid, connection_type, weight=1, **kwargs)[source]#
Bases:
ConnectionThis is a convenience class that represents connections of type neuropeptide-receptors.
- class cedne.ConnectionGroup(network, members=None, group_name=None)[source]#
Bases:
objectThis is a group of connections in the network
- set_property(property_name, property_value)[source]#
Sets a new property attribute for all connections in the group.
- update_weights(weight, delta=False)[source]#
Updates weights for all connections in the group.
- Args:
weight (float): The new weight value or weight delta. delta (bool, optional): If True, weight is added to current weights. If False, weight replaces current weights.
- Raises:
ValueError: If weight is not a numeric value.
- update_weights_by_function(weight_function)[source]#
Updates weights for all connections using a custom function.
- Args:
- weight_function (callable): A function that takes a Connection object
and returns a new weight value.
- Raises:
ValueError: If weight_function is not callable or returns non-numeric values.
- filter_by_type(connection_type)[source]#
Returns a new ConnectionGroup containing only connections of the specified type.
- Args:
connection_type (str): The type of connections to filter for.
- Returns:
ConnectionGroup: A new group containing only the filtered connections.
- filter_by_property(property_name, property_value)[source]#
Returns a new ConnectionGroup containing only connections with the specified property value.
- Args:
property_name (str): The name of the property to filter by. property_value: The value to match.
- Returns:
ConnectionGroup: A new group containing only the filtered connections.
- filter_by_function(filter_function)[source]#
Returns a new ConnectionGroup containing only connections that pass the filter function.
- Args:
- filter_function (callable): A function that takes a Connection object
and returns True if the connection should be included.
- Returns:
ConnectionGroup: A new group containing only the filtered connections.
- class cedne.Path(network, members=None, group_name=None)[source]#
Bases:
ConnectionGroupThis is a sequence of Connections in the network.
- get_length()[source]#
Returns the number of connections in the path.
- Returns:
int: The number of connections in the path.
- get_total_weight()[source]#
Returns the sum of weights of all connections in the path.
- Returns:
float: The sum of connection weights.
- get_average_weight()[source]#
Returns the average weight of connections in the path.
- Returns:
float: The average connection weight.
- get_min_weight()[source]#
Returns the minimum weight among all connections in the path.
- Returns:
float: The minimum connection weight.
- get_max_weight()[source]#
Returns the maximum weight among all connections in the path.
- Returns:
float: The maximum connection weight.
- reverse()[source]#
Creates a new path with connections in reverse order.
- Returns:
Path: A new path with reversed connections.
- concatenate(other_path)[source]#
Creates a new path by concatenating this path with another path.
- Args:
other_path (Path): The path to concatenate with.
- Returns:
Path: A new path containing all connections from both paths.
- Raises:
- AssertionError: If the paths cannot be concatenated (target of first path
must match source of second path).
- is_valid()[source]#
Checks if the path is valid (all connections are continuous).
- Returns:
bool: True if the path is valid, False otherwise.
- class cedne.Trial(neuron: Neuron, trialnum: int)[source]#
Bases:
objectA class representing a single experimental recording for a neuron.
This class handles the storage and basic processing of time series data recorded from a neuron during an experimental trial. It supports operations like data storage, bleaching correction, and basic signal processing.
- Attributes:
neuron: The neuron object associated with this trial. i (int): The trial number. discard (List[int]): Points to be discarded due to bleaching or artifacts. _data (NDArray): The actual recording data. metadata (Dict): Dictionary containing trial metadata.
- property recording: ndarray[Any, dtype[_ScalarType_co]]#
Get the recording data for the trial.
- Returns:
NDArray: The recording time series data.
- Raises:
ValueError: If no recording data has been set.
- get_duration() float[source]#
Get the duration of the recording in seconds.
- Returns:
float: Duration of the recording in seconds.
- Raises:
ValueError: If no recording data has been set.
- get_timestamps() ndarray[Any, dtype[_ScalarType_co]][source]#
Get the timestamps for each sample in the recording.
- Returns:
NDArray: Array of timestamps in seconds.
- Raises:
ValueError: If no recording data has been set.
- filter_signal(filter_type: str = 'lowpass', cutoff_freq: float = 10.0, order: int = 4) ndarray[Any, dtype[_ScalarType_co]][source]#
Apply a Butterworth filter to the recording data.
- Args:
filter_type: Type of filter (‘lowpass’, ‘highpass’, or ‘bandpass’). cutoff_freq: Cutoff frequency in Hz. For bandpass, provide tuple (low, high). order: Order of the Butterworth filter.
- Returns:
NDArray: Filtered signal.
- Raises:
ValueError: If filter_type is invalid or if no recording data has been set.
- smooth_signal(window_size: int = 5, method: str = 'moving') ndarray[Any, dtype[_ScalarType_co]][source]#
Smooth the recording signal using various methods.
- Args:
window_size: Size of the smoothing window in samples. method: Smoothing method (‘moving’, ‘gaussian’, or ‘median’).
- Returns:
NDArray: Smoothed signal.
- Raises:
ValueError: If method is invalid or if no recording data has been set.
- normalize_signal(method: str = 'minmax', baseline_window: tuple | None = None) ndarray[Any, dtype[_ScalarType_co]][source]#
Normalize the recording signal using various methods.
- Args:
method: Normalization method (‘minmax’, ‘zscore’, or ‘baseline’). baseline_window: Tuple of (start, end) indices for baseline normalization.
- Returns:
NDArray: Normalized signal.
- Raises:
ValueError: If method is invalid or if no recording data has been set.
- detect_peaks(height: float | None = None, distance: int | None = None) tuple[ndarray[Any, dtype[_ScalarType_co]], ndarray[Any, dtype[_ScalarType_co]]][source]#
Detect peaks in the recording signal.
- Args:
height: Minimum height of peaks. distance: Minimum distance between peaks in samples.
- Returns:
tuple: (peak_indices, peak_heights)
- Raises:
ValueError: If no recording data has been set.
- get_statistics() dict[source]#
Calculate basic statistics of the recording.
- Returns:
- dict: Dictionary containing various statistical measures:
mean: Mean of the signal
std: Standard deviation
median: Median value
min: Minimum value
max: Maximum value
skewness: Skewness of the distribution
kurtosis: Kurtosis of the distribution
rms: Root mean square value
- Raises:
ValueError: If no recording data has been set.
- compute_power_spectrum(window: str = 'hann') tuple[ndarray[Any, dtype[_ScalarType_co]], ndarray[Any, dtype[_ScalarType_co]]][source]#
Compute the power spectrum of the recording.
- Args:
window: Window function to use (‘hann’, ‘hamming’, ‘blackman’, etc.).
- Returns:
tuple: Arrays of frequencies and corresponding power spectrum.
- Raises:
ValueError: If no recording data has been set.
- compute_snr(signal_window: tuple, noise_window: tuple) float[source]#
Compute the signal-to-noise ratio.
- Args:
signal_window: Tuple of (start, end) indices for signal region. noise_window: Tuple of (start, end) indices for noise region.
- Returns:
float: Signal-to-noise ratio in dB.
- Raises:
ValueError: If windows are invalid or if no recording data has been set.
- segment_signal(threshold: float, min_duration: int = 10) List[tuple[int, int]][source]#
Segment the signal into regions above threshold.
- Args:
threshold: Amplitude threshold for segmentation. min_duration: Minimum duration (in samples) for a valid segment.
- Returns:
List[tuple]: List of (start, end) indices for each segment.
- Raises:
ValueError: If no recording data has been set.
- add_metadata(key: str, value: Any) None[source]#
Add metadata to the trial.
- Args:
key: Metadata key. value: Metadata value.
- get_metadata(key: str) Any[source]#
Get metadata value.
- Args:
key: Metadata key.
- Returns:
The metadata value.
- Raises:
KeyError: If the key doesn’t exist in metadata.
- log_processing(operation: str, parameters: Dict[str, Any]) None[source]#
Log a processing operation in the trial’s history.
- Args:
operation: Name of the processing operation. parameters: Dictionary of parameters used in the operation.
- validate_data() bool[source]#
Validate the recording data.
- Returns:
bool: True if data is valid, False otherwise.
This method checks: - Data is not None - Data is a numpy array - Data is 1-dimensional - Data contains no NaN or infinite values - Data length is reasonable (> 0)
- get_quality_metrics() Dict[str, float][source]#
Calculate quality metrics for the recording.
- Returns:
- dict: Dictionary containing quality metrics:
snr: Signal-to-noise ratio
noise_level: Estimated noise level
signal_stability: Measure of signal stability
artifact_count: Number of potential artifacts
- Raises:
ValueError: If no recording data has been set.
- class cedne.StimResponse(trial: Trial, stimulus: ndarray[Any, dtype[_ScalarType_co]], response: ndarray[Any, dtype[_ScalarType_co]], baseline_samples: int)[source]#
Bases:
objectA class representing a stimulus-response pair in a neural recording.
This class handles the analysis of neural responses to specific stimuli, extracting various features from the response signal and providing methods for response characterization.
- Attributes:
stim (NDArray): The stimulus signal. response (NDArray): The response signal. feature (Dict[int, Any]): Dictionary of extracted features. neuron: The neuron object associated with this response. f_sample (float): Sampling frequency in Hz. sampling_time (float): Time between samples in seconds. baseline (NDArray): Baseline signal before stimulus.
- Features extracted include:
0: Maximum response amplitude 1: Area under the curve 2: Mean response 3: Time to peak 4: Area under the curve to peak 5: Minimum response 6: Response onset time 7: Positive response area 8: Absolute area under the curve
- extract_feature(feature_index: int) float | tuple[float, float][source]#
Extract a specific feature from the stimulus-response pair.
- Args:
- feature_index: Index of the feature to extract:
0: Maximum value 1: Area under the curve 2: Time to peak 3: Mean value 4: Area under the curve to peak 5: Minimum value 6: Onset time 7: Positive area 8: Absolute area under the curve
- Returns:
The extracted feature value or tuple of values.
- Raises:
ValueError: If feature_index is invalid.
- get_response_characteristics() Dict[str, float][source]#
Calculate comprehensive response characteristics.
- Returns:
- dict: Dictionary containing various response metrics:
amplitude: Peak response amplitude (relative to baseline)
duration: Response duration
latency: Response latency
integral: Total response integral
baseline_mean: Mean baseline activity
baseline_std: Baseline standard deviation
signal_to_noise: Signal-to-noise ratio
- class cedne.Behavior(worm: Worm = None, network: str = 'Neutral')[source]#
Bases:
objectThis is a behavior class for the organism
- class cedne.GraphMap(mapping_dict, graph_1, graph_2, map_type='node', **kwargs)[source]#
Bases:
MapThis class represents a map between two graphs.