Welcome to CeDNe’s documentation!#
CeDNe: Connectome-embedded Dynamical Networks A composable framework for building, analyzing, and visualizing nervous systems.
This top-level module exports the core components (e.g., Worm, Fly, 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:
CitableThis is a full animal class
- save(file_path, file_format='cedne')[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]#
-
Models a biological neuron
- property is_merged: bool#
True iff this neuron was produced by contracting other neurons.
Backed by
self.constituents: a non-empty dict ⇒ merged. Set byNervousSystem.contract_neurons; round-trips through graph cloning via the networkx node attribute mirror.
- property constituent_types#
Sorted list of distinct source types across this neuron’s constituents, derived on-demand from
self.constituents.Single source of truth: changing
constituentsautomatically updates this list — no parallel field to keep in sync. Returns[]for un-merged neurons.
- property constituent_categories#
Sorted list of distinct source categories across this neuron’s constituents.
[]for un-merged neurons or for merged neurons whose constituents had no category set.
- property constituent_modalities#
Sorted list of distinct source modalities across this neuron’s constituents.
[]for un-merged neurons or for merged neurons whose constituents had no modality set.
- to_dict() Dict[str, Any][source]#
Serialize neuron to a plain Python dictionary.
Returns a dict with guaranteed keys:
id,type,group_id,degree,has_recordings. Optionally includesposition,scalars(auto-discovered numeric attributes), andloadings(dimensionality-reduction weights).- Returns:
Dict[str, Any]: A JSON-compatible dictionary representation.
- 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.
- load_recording(data, trial_num=0, sampling_rate=None, metadata=None)[source]#
Attach a 1D time-series recording to this neuron as a new Trial.
Thin convenience over add_trial() + setting trial.recording; use it when you already have a per-neuron trace in memory (ndarray, list, pandas Series) and don’t want to manage Trial objects by hand.
- Args:
data: 1D array-like of samples (calcium trace, voltage, etc.). trial_num: Trial index (default 0). Overwrites any existing trial
at this index for this neuron.
- sampling_rate: Sampling rate in Hz; written to
trial.metadata. Leave as None to keep the module default (F_SAMPLE).
metadata: Extra metadata dict merged into
trial.metadata.- sampling_rate: Sampling rate in Hz; written to
- Returns:
Trial: The trial object holding the recording.
- 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:
CitableThis 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.
- get_neurons_by_type(type: str) List[Neuron][source]#
Get all neurons of a specific type.
- Args:
type: Neuron type to filter by.
- Returns:
List of neurons of the specified type.
- get_neurons_by_property(key: str, value: Any) List[Neuron][source]#
Get neurons with a specific property value.
- Args:
key: Property name. value: Property value to match.
- Returns:
List of neurons with matching property value.
- union(other: NeuronGroup, group_name: str = None) NeuronGroup[source]#
Return a new NeuronGroup containing neurons from both groups.
- Args:
other: Another NeuronGroup to union with. group_name: Optional name for the resulting group.
- Returns:
A new NeuronGroup with the combined members.
- intersection(other: NeuronGroup, group_name: str = None) NeuronGroup[source]#
Return a new NeuronGroup containing only neurons present in both groups.
- Args:
other: Another NeuronGroup to intersect with. group_name: Optional name for the resulting group.
- Returns:
A new NeuronGroup with the shared members.
- difference(other: NeuronGroup, group_name: str = None) NeuronGroup[source]#
Return a new NeuronGroup containing neurons in self but not in other.
- Args:
other: Another NeuronGroup to subtract. group_name: Optional name for the resulting group.
- Returns:
A new NeuronGroup with the difference members.
- class cedne.NervousSystem(*args, backend=None, **kwargs)[source]#
Bases:
MultiDiGraph,Citable- 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, legacy=False, fold_policy=None)[source]#
Fold the network based on a partition.
- Args:
- fold_by (dict[str, list[str]]):
Mapping from each merged-neuron name to the list of original neuron names that should collapse into it. Singleton lists are treated as renames.
- name (str, optional):
Name for the resulting NervousSystem.
- data (str, optional): One of:
‘collect’: Preserve every original edge as a separate parallel in the folded view (default).
‘clean’: Sum weights of parallel edges per
(folded_pre, folded_post, connection_type)and union list-valued edge metadata (ligands, neurotransmitters, putative receptors, receptor dicts).
- exceptions (list[str], optional):
Neuron names that should NOT be folded into their class — they pass through to the folded view under their original names.
- self_loops (bool, optional):
If False, intra-class edges (i.e. edges whose endpoints both belong to the same merged class) are dropped from the result. Defaults to True.
- legacy (bool, optional):
Selects between two implementations that should be behaviourally equivalent. Default
Falseuses the batch path which builds the folded view directly from the partition map in O(V + E). SetTrueto use the pre-batch implementation that does N-1 pair-wisecontract_neuronscalls per class (O(class_size × growing_supernode_degree) per class — unusable at scale). Preserved during the rollout so callers can bisect parity issues, and scheduled for removal once the fast path has soaked.- fold_policy (FoldPolicySet, optional):
Per-attribute aggregation policy applied when merging parallel edges in
data='clean'mode.None(default) → useDEFAULT_CONNECTION_FOLD_POLICY, which encodes the historical contract (weights sum, list-valued metadata set-union, receptor dicts merge with first-observed-value semantics). Both the batch and legacy fold paths honor the policy (Phase 2.1); strict parity tests pin behavior on identical inputs across both. The applied policy is stamped onto the result asfolded.fold_policyfor provenance.
- Returns:
NervousSystem: The folded graph. Each merged neuron carries
constituents,is_merged,constituent_subgraphand the merge-policy-resolvedMERGE_TRACK_ATTRS. Both code paths produce structurally equivalent NervousSystem objects; see_fold_network_batchfor the precise preservation contract.
- adjacency(order=None, weighted=False, connection_type=None)[source]#
Output the adjacency matrix for the network ordered by neurons.
- Args:
- order:
Optional ordered list of neuron names or neuron objects. When omitted, neurons are ordered deterministically by name.
- weighted (bool):
If
True, matrix entries are summed edge weights. Otherwise returns a binary adjacency matrix.- connection_type:
Optional string or list of strings selecting which connection types to include. Supports convenience aliases such as
"chemical","gap-junction", and"bulk"in addition to exact connection type names.
- 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, fold_policy=None)[source]#
Contract
targetintosource, redirecting target’s edges to source and renaming source tocontracted_name.- Args:
- pair (tuple[str, str]):
(source_name, target_name). Source survives (renamed tocontracted_name); target is removed and its edges are redirected onto source.- contracted_name (str):
New name for the surviving neuron.
- data (str, optional):
No-op at the core layer — accepted for backwards compatibility with callers that use it as a hint for post-merge cleanup. The cedne_web backend uses
data='clean'to indicate thatcontract_connectionsshould be called after a chain of contractions to collapse parallel edges.- copy_graph (bool, optional):
If True, work on a deep copy and return it; the original is untouched. If False (default), mutate in place and return None.
- self_loops (bool, optional):
Forwarded to
nx.contracted_nodes. If False, drops any self-loop produced by edges between the merged pair.
- Returns:
- NervousSystem | None:
The new graph if
copy_graph=True;Noneotherwise (mutates in place).
- Notes:
Tracks merge provenance on the surviving neuron via three new Neuron API surfaces:
Neuron.constituents: dict mapping each pre-merge name to a snapshot{'name', 'type'}. Transitive — merging A+B then merging the result with C yields constituents{A, B, C}.Neuron.is_merged: bool, True iffconstituentsis non-empty.Neuron.constituent_types: sorted list of distinct constituent types, derived fromconstituentsso the two cannot drift out of sync.
Type-merge policy:
If all constituents share a single type → that type is preserved on the surviving neuron.
If types differ →
Neuron.typeis set to the sentinelMERGED_TYPE('merged') so analyses that switch on type can branch on the merged case explicitly rather than silently inheriting one constituent’s type.
- contract_connections(contraction_dict, fold_policy=None)[source]#
Contract parallel connections into one supernode-edge per group.
- Args:
- contraction_dict: Mapping of
(neuron_a, neuron_b, conn_type) tuples to the list of constituent
Connectionobjects that should be folded into a single supernode-edge.- fold_policy (FoldPolicySet, optional):
Per-attribute aggregation policy. When
None(default) the historical contract is used (weights sum; ligands / neurotransmitters / putative pairs set-union; receptors dict-union with first-observed-value semantics). Pass a customFoldPolicySetto override aggregators or add new dataset shapes.
- contraction_dict: Mapping of
- Returns:
NervousSystem: The folded graph. The applied policy is attached as
result.fold_policyso consumers (and re-fold operations) can read back exactly how the merge decisions were made.
- 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
- shortest_path(source, target, weight=None, method='dijkstra')[source]#
Finds a single shortest path between two neurons in the network.
- shortest_paths(source, target, weight=None, method='dijkstra')[source]#
Finds all shortest paths between two neurons in the network.
- 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
- to_dict() dict[source]#
Serialize the full network to a plain Python dictionary.
Composes
Neuron.to_dict()andConnection.to_dict()for each node and edge, then attaches group membership, group summaries, network-level metadata, and visualization hints.- Returns:
- dict: A JSON-compatible dictionary with keys:
name: Network name.organism: Organism name (from worm), if available.nodes: List of neuron dicts.links: List of connection dicts.groups: List of group summary dicts.visualization_metadata: Arbitrary viz hints.
- 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 (Iterable[Union[Neuron, str]]):
The members of the group. Each entry may be a
Neuroninstance or a neuron name (string); strings are resolved againstself.neurons.- group_name (str, optional):
The name of the neuron group. Auto-generated if omitted.
- 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 (Iterable[Connection]):
The members of the group. Each entry must be a
Connectioninstance — connection identity is the(pre, post, uid)triple, not a string name.- group_name (str, optional):
The name of the connection group. Auto-generated if omitted.
- Returns:
ConnectionGroup: The created connection group.
- class cedne.Connection(pre: Neuron, post: Neuron, uid=None, connection_type='chemical-synapse', **kwargs)[source]#
Bases:
CitableThis 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:
CitableThis 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.
- get_statistics()[source]#
Returns statistics about the connections in the group.
- Returns:
dict: A dictionary containing statistics about the connections.
- union(other: ConnectionGroup, group_name: str = None) ConnectionGroup[source]#
Return a new ConnectionGroup containing connections from both groups.
- Args:
other: Another ConnectionGroup to union with. group_name: Optional name for the resulting group.
- Returns:
A new ConnectionGroup with the combined members.
- intersection(other: ConnectionGroup, group_name: str = None) ConnectionGroup[source]#
Return a new ConnectionGroup containing only connections present in both groups.
- Args:
other: Another ConnectionGroup to intersect with. group_name: Optional name for the resulting group.
- Returns:
A new ConnectionGroup with the shared members.
- difference(other: ConnectionGroup, group_name: str = None) ConnectionGroup[source]#
Return a new ConnectionGroup containing connections in self but not in other.
- Args:
other: Another ConnectionGroup to subtract. group_name: Optional name for the resulting group.
- Returns:
A new ConnectionGroup with the difference members.
- 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.Citation(key: str, title: str | None = None, authors: List[str] | None = None, year: int | None = None, doi: str | None = None, url: str | None = None, notes: str | None = None)[source]#
Bases:
objectA bibliographic reference: paper, dataset, or other evidence source.
The
keyis the canonical identifier (BibTeX-style, e.g."White1986"). All other fields are optional; populate as much metadata as is available.- key: str#
- title: str | None = None#
- authors: List[str] | None = None#
- year: int | None = None#
- doi: str | None = None#
- url: str | None = None#
- notes: str | None = None#
- class cedne.Citable[source]#
Bases:
objectBase class adding a citations container and hierarchical resolution.
Subclasses should call
Citable.__init__(self)somewhere in their own__init__(the call is idempotent, so order with other base classes doesn’t matter). Subclasses may override_parent_citablesto define which container objectseffective_citationsshould walk into.The
citationsattribute is a plain dict. Values may beCitationinstances OR arbitrary user data (legacy loaders attach plain dicts). The hierarchical resolution treats both uniformly.- add_citation(citation: Citation, key: str | None = None) None[source]#
Attach a structured Citation. Defaults the dict key to citation.key.
- citations_to_dict() Dict[str, Any][source]#
Serialize the local citations dict to JSON-friendly form.
Citation instances are flattened via
Citation.to_dict; any other value (e.g. legacy loader dicts) is passed through as-is.
- effective_citations(_visited: set | None = None) List[Tuple[str, str, Any]][source]#
Walk up the containment hierarchy and return all applicable citations.
- Returns:
A list of
(provenance_label, citation_key, citation_value)tuples. The label identifies which object in the hierarchy carried the citation (most-specific first). Duplicate citation_keys are dropped, keeping the most-specific attribution.citation_valuemay be aCitationinstance or any other value the caller stored under that key.
- cedne.serialize_citations(citations: Dict[str, Any]) Dict[str, Any][source]#
Convert a citations dict to JSON-friendly form.
Citation instances are flattened via
Citation.to_dict; any other value (e.g. legacy loader dicts, strings) is passed through unchanged. Lists are walked recursively so a list ofCitationobjects inside the dict serializes properly.
- class cedne.FoldPolicy(name: str, kind: Literal['scalar', 'timeseries', 'list', 'dict', 'categorical'], aggregator: str = 'drop')[source]#
Bases:
objectHow to aggregate one named attribute across constituents.
- Attributes:
- name: The attribute key (e.g.
"recording"for time series,
"type"for categorical,"ligands"for list-valued connection metadata). Used by callers as the lookup key against the live attribute on each constituent.- kind: The shape of the attribute. Determines which
aggregators are valid;
apply_policyraises if a kind/aggregator combination doesn’t make sense.- aggregator: How to combine N constituent values into one.
Default
"drop"means the attribute isn’t copied to the supernode (safe default — no silent merge).
- name: The attribute key (e.g.
- name: str#
- kind: Literal['scalar', 'timeseries', 'list', 'dict', 'categorical']#
- aggregator: str = 'drop'#
- classmethod from_dict(d: Dict[str, str]) FoldPolicy[source]#
- class cedne.FoldPolicySet(policies: ~typing.Dict[str, ~cedne.core.fold_policy.FoldPolicy] = <factory>, default_aggregator: str = 'drop')[source]#
Bases:
objectA bundle of per-attribute policies + a default for unregistered attrs.
Attached to the resulting network after a fold so the choices that produced it are part of the provenance record (alongside the constituent subgraphs already captured by
fold_network).- policies: Dict[str, FoldPolicy]#
- default_aggregator: str = 'drop'#
- add(policy: FoldPolicy) FoldPolicySet[source]#
- get(name: str, kind: str) FoldPolicy[source]#
Return the policy for
nameor a drop policy of the given kind.
- classmethod from_dict(d: Dict[str, Any]) FoldPolicySet[source]#
- cedne.apply_policy(policy: FoldPolicy, values: List[Any]) Any[source]#
Apply a policy to a list of constituent values.
Returns the merged value, or
Nonefor the drop sentinel / empty input. Never raises on empty/missing data — that’s the caller’s cue to skip copying the attribute to the supernode.
- 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:
objectBehavioral data container for an organism.
Stores named behavioral time series (e.g., speed, heading, body curvature) with timestamps and metadata. Can be linked to Session and Trial objects for alignment between behavioral and neural data.
- Attributes:
worm: The worm object associated with this behavior. variables: Dict mapping variable names to 1-D numpy arrays. timestamps: Array of time points for the behavioral data. metadata: Dict of metadata (sampling_rate, units, source, etc.). session: Optional link to the experimental Session. trials: List of Trial objects linked to this behavior.
- add_variable(name: str, data: ndarray[Any, dtype[_ScalarType_co]], timestamps: ndarray[Any, dtype[_ScalarType_co]] | None = None, unit: str | None = None) None[source]#
Add a named behavioral variable (1-D time series).
- Args:
name: Variable name (e.g., “speed”, “heading”). data: 1-D array of values. timestamps: Optional array of time points. If provided on the
first call, it sets the global timestamps for this Behavior. Subsequent calls verify length consistency.
unit: Optional unit string (e.g., “mm/s”).
- Raises:
ValueError: If data is not 1-D or length doesn’t match timestamps.
- get_variable(name: str) ndarray[Any, dtype[_ScalarType_co]][source]#
Get a behavioral variable by name.
- Args:
name: Variable name.
- Returns:
The 1-D array for the named variable.
- Raises:
KeyError: If variable doesn’t exist.
- property variable_names: List[str]#
List of available behavioral variable names.
- property n_timepoints: int#
Number of time points (0 if no data loaded).
- align_to_neural(trial: Trial, method: str = 'interpolate') Dict[str, ndarray[Any, dtype[_ScalarType_co]]][source]#
Align behavioral data to a neural recording’s time base.
Resamples all behavioral variables to match the neural trial’s timestamps.
- Args:
trial: A Trial object with recording data. method: Alignment method.
“interpolate”: Linear interpolation to neural time points.
“nearest”: Nearest-neighbor matching.
- Returns:
Dict mapping variable names to resampled arrays matching the neural trial’s time points.
- Raises:
ValueError: If behavioral timestamps are not set or trial has no data.
- link_trial(trial: Trial) None[source]#
Link a Trial to this Behavior for cross-referencing.
Also sets the trial’s behavior back-reference.
- Args:
trial: The Trial object to link.
- link_session(session: Session) None[source]#
Link a Session to this Behavior.
- Args:
session: The Session object to link.
- to_dict() Dict[str, Any][source]#
Serialize behavior data to a dictionary.
- Returns:
Dict with variables, timestamps, and metadata.
- classmethod from_dict(data: Dict[str, Any], worm: Worm = None, network: str = 'Neutral') Behavior[source]#
Create a Behavior from a dictionary.
- Args:
data: Dict with ‘variables’, optional ‘timestamps’, and ‘metadata’. worm: Optional Worm object. network: Network context name.
- Returns:
New Behavior instance.
- class cedne.GraphMap(mapping_dict, graph_1, graph_2, map_type='node', **kwargs)[source]#
Bases:
MapThis class represents a map between two graphs.
- cedne.load_worm(file_path)[source]#
Load a Worm object from a pickle file.
- Args:
file_path (str): The path to the pickle file.
- Returns:
Worm: The loaded Worm object.