refactoredCPPNeuronMesher
NeuronGraph Class Reference

Class for representing and processing neuron morphology graphs. More...

#include <neurongraph.h>

Public Member Functions

 NeuronGraph ()
 Default constructor. More...
 
 NeuronGraph (std::string filename)
 Constructor that loads a neuron from file. More...
 
 NeuronGraph (const std::map< int, SWCNode > &nodeSet)
 Constructs a NeuronGraph from an existing set of nodes. More...
 
void addNode (const SWCNode &node)
 Adds a single node to the graph. More...
 
void setNodes (const std::map< int, SWCNode > &nodeSet)
 Replaces the current set of nodes in the graph. More...
 
bool isTopologicallySorted (const std::map< int, SWCNode > &nodeSet) const
 Checks if a set of nodes is topologically sorted. More...
 
bool isTopologicallySorted () const
 
std::map< int, SWCNodetopologicalSort (const std::map< int, SWCNode > &nodeSet) const
 Sorts nodes topologically using Kahn's algorithm. More...
 
std::map< int, SWCNodetopologicalSort () const
 
bool hasSomaSegment (const std::map< int, SWCNode > &nodeSet) const
 Checks if the node set contains a soma segment. More...
 
bool hasSomaSegment () const
 
bool isSomaMissing (const std::map< int, SWCNode > &nodeSet) const
 Checks if the node set is missing a soma. More...
 
bool isSomaMissing () const
 
std::map< int, SWCNoderemoveSomaSegment (const std::map< int, SWCNode > &inputNodes) const
 Removes the soma segment from a set of nodes. More...
 
std::map< int, SWCNoderemoveSomaSegment () const
 
std::map< int, SWCNodesetSoma (const std::map< int, SWCNode > &nodeSet) const
 Adds a soma node if none exists. More...
 
std::map< int, SWCNodesetSoma () const
 
std::map< int, SWCNodepreprocess (const std::map< int, SWCNode > &nodeSet) const
 Applies standard preprocessing steps to a set of nodes. More...
 
void readFromFile (const std::string &filename)
 Reads neuron data from an SWC file. More...
 
void writeToFile (const std::map< int, SWCNode > &nodeSet, const std::string &filename)
 Writes a set of nodes to an SWC file. More...
 
void writeToFile (const std::string &filename)
 
void readFromFileUGX (const std::string &filename)
 Reads neuron data from a UGX file. More...
 
void readFromFileUGXorSWC (const std::string &filename)
 Reads a neuron file, automatically detecting the format. More...
 
void writeToFileUGX (const std::map< int, SWCNode > &nodeSet, const std::string &filename)
 Writes a set of nodes to a UGX file. More...
 
void writeToFileUGX (const std::string &filename)
 
void swc2ugx (const std::string &inputfile, const std::string &outputfile)
 Converts an SWC file to UGX format. More...
 
void ugx2swc (const std::string &inputfile, const std::string &outputfile)
 Converts a UGX file to SWC format. More...
 
int numberOfNodes ()
 Returns the number of nodes in the graph. More...
 
int numberOfEdges ()
 Returns the number of edges in the graph. More...
 
auto getNodes ()
 Returns a copy of all nodes in the graph. More...
 
std::map< int, SWCNodesplitEdges (const std::map< int, SWCNode > &nodeSet) const
 Splits all edges in the graph by inserting midpoint nodes. More...
 
std::map< int, SWCNodesplitEdges () const
 
std::vector< std::map< int, SWCNode > > splitEdgesN (const std::map< int, SWCNode > &nodeSet, int N) const
 Applies edge splitting N times recursively. More...
 
std::vector< std::map< int, SWCNode > > splitEdgesN (int N) const
 
std::map< int, std::map< int, SWCNode > > getTrunks (const std::map< int, SWCNode > &nodeSet, bool resetIndex=false) const
 Extracts trunk segments from a neuron morphology. More...
 
std::map< int, std::map< int, SWCNode > > getTrunks (bool resetIndex=false) const
 
std::map< int, int > getTrunkParentMap (const std::map< int, SWCNode > &nodeSet, const std::map< int, std::map< int, SWCNode >> &trunkNodeSets) const
 Creates a mapping from trunk IDs to their parent trunk IDs. More...
 
std::map< int, SWCNodeassembleTrunks (const std::map< int, std::map< int, SWCNode >> &trunkNodeSets) const
 Combines multiple trunks into a single node set. More...
 
std::map< int, SWCNodeassembleTrunks (const std::map< int, std::map< int, SWCNode >> &resampledTrunks, const std::map< int, int > &trunkParentMap)
 Combines resampled trunks using a parent-child relationship map. More...
 
std::map< int, SWCNodelinearSplineResampleTrunk (const std::map< int, SWCNode > &trunk, double &delta) const
 Resamples a single trunk using linear interpolation. More...
 
std::map< int, std::map< int, SWCNode > > allLinearSplineResampledTrunks (std::map< int, std::map< int, SWCNode >> &trunks, double &delta) const
 Resamples all trunks using linear interpolation. More...
 
std::map< int, SWCNodecubicSplineResampleTrunk (const std::map< int, SWCNode > &trunk, double &delta) const
 Resamples a single trunk using cubic spline interpolation. More...
 
std::map< int, std::map< int, SWCNode > > allCubicSplineResampledTrunks (std::map< int, std::map< int, SWCNode >> &trunks, double &delta) const
 Resamples all trunks using cubic spline interpolation. More...
 
std::map< int, std::map< int, SWCNode > > generateRefinements (const std::map< int, SWCNode > &nodeSet, double &delta, int &N, std::string &method)
 Generates multiple levels of refined neuron morphologies. More...
 
std::map< int, std::map< int, SWCNode > > generateRefinements (double &delta, int &N, std::string &method)
 

Private Member Functions

std::map< int, std::vector< int > > getNeighborMap (const std::map< int, SWCNode > &nodeSet) const
 Builds a neighbor map from a set of nodes. More...
 

Private Attributes

std::map< int, SWCNodenodes
 Map of node IDs to SWCNode objects. More...
 
std::map< int, std::vector< int > > edges
 Adjacency list representation of the neuron graph. More...
 

Detailed Description

Class for representing and processing neuron morphology graphs.

The NeuronGraph class provides comprehensive functionality for working with neuron morphology data, including file I/O, topological analysis, and geometric processing. It supports both SWC and UGX file formats and includes methods for manipulating and analyzing neuron structures.

Key features:

  • Reading and writing SWC/UGX files
  • Topological sorting and validation
  • Soma detection and processing
  • Edge splitting and resampling
  • Trunk extraction and manipulation

Constructor & Destructor Documentation

◆ NeuronGraph() [1/3]

NeuronGraph::NeuronGraph ( )
inline

Default constructor.

Creates an empty NeuronGraph with no nodes or edges.

◆ NeuronGraph() [2/3]

NeuronGraph::NeuronGraph ( std::string  filename)
inline

Constructor that loads a neuron from file.

Parameters
[in]filenamePath to the SWC or UGX file to load
See also
readFromFileUGXorSWC()
Here is the call graph for this function:

◆ NeuronGraph() [3/3]

NeuronGraph::NeuronGraph ( const std::map< int, SWCNode > &  nodeSet)

Constructs a NeuronGraph from an existing set of nodes.

Constructor that initializes a NeuronGraph from a set of SWC nodes.

Parameters
[in]nodeSetMap of node IDs to SWCNode objects
nodeSetA map containing SWC nodes indexed by their IDs

This constructor creates a new NeuronGraph instance by clearing any existing data and populating the graph with the provided nodes. It automatically builds the parent-child relationships between nodes.

Note
The nodeSet parameter uses structured binding, so the key is ignored (_)
See also
addNode(const SWCNode& node)

Member Function Documentation

◆ addNode()

void NeuronGraph::addNode ( const SWCNode node)

Adds a single node to the graph.

Adds a single node to the graph and updates edge relationships.

Parameters
[in]nodeThe SWCNode to add
Note
This method is typically used internally by other methods that read or generate node data.
Parameters
nodeThe SWCNode to be added to the graph

This method adds a node to the internal nodes map and automatically creates the parent-child edge relationship if the node has a valid parent (pid != -1). Root nodes (pid == -1) are added without creating edges.

Note
This method assumes node IDs are unique and will overwrite existing nodes
See also
SWCNode structure for node data format
Here is the caller graph for this function:

◆ allCubicSplineResampledTrunks()

std::map< int, std::map< int, SWCNode > > NeuronGraph::allCubicSplineResampledTrunks ( std::map< int, std::map< int, SWCNode >> &  trunks,
double &  delta 
) const

Resamples all trunks using cubic spline interpolation.

Applies cubic spline resampling to all trunk segments in a neuron morphology.

Parameters
[in,out]trunksMap of trunk IDs to their nodes
[in,out]deltaTarget spacing between resampled points (may be adjusted)
Returns
A new map of resampled trunks
Parameters
trunksMap of trunk segments where each key is a trunk ID and value is a map of node IDs to SWCNodes
deltaTarget distance between consecutive nodes in the resampled trunks (in microns)
Returns
std::map<int, std::map<int, SWCNode>> Map of resampled trunks with the same structure as input

This method processes each trunk segment in the input map and applies cubic spline resampling to achieve a smooth and uniform node distribution. The resampling is performed independently on each trunk.

Key features:

  • Fits a smooth cubic spline through the original nodes of each trunk
  • Samples points at approximately 'delta' intervals along the spline
  • Preserves the start and end points of each trunk exactly
  • Maintains the original topology while improving smoothness
  • Handles each trunk segment independently

The resampling process involves:

  1. Fitting natural cubic splines to the x, y, and z coordinates separately
  2. Parameterizing the spline by arc length
  3. Sampling new points at approximately 'delta' intervals along the curve
Note
This method produces smoother results than linear interpolation but is more computationally intensive
The actual spacing may vary slightly to ensure the curve is sampled properly
See also
cubicSplineResampleTrunk() for the single-trunk implementation
allLinearSplineResampledTrunks() for a faster but less smooth alternative
Here is the call graph for this function:
Here is the caller graph for this function:

◆ allLinearSplineResampledTrunks()

std::map< int, std::map< int, SWCNode > > NeuronGraph::allLinearSplineResampledTrunks ( std::map< int, std::map< int, SWCNode >> &  trunks,
double &  delta 
) const

Resamples all trunks using linear interpolation.

Applies linear spline resampling to all trunk segments in a neuron morphology.

Parameters
[in,out]trunksMap of trunk IDs to their nodes
[in,out]deltaTarget spacing between resampled points (may be adjusted)
Returns
A new map of resampled trunks
Parameters
trunksMap of trunk segments where each key is a trunk ID and value is a map of node IDs to SWCNodes
deltaTarget distance between consecutive nodes in the resampled trunks (in microns)
Returns
std::map<int, std::map<int, SWCNode>> Map of resampled trunks with the same structure as input

This method processes each trunk segment in the input map and applies linear spline resampling to achieve a more uniform node distribution. The resampling is performed independently on each trunk.

Key features:

  • Preserves the start and end points of each trunk exactly
  • Inserts new nodes to achieve approximately 'delta' spacing between points
  • Maintains the original topology and branching structure
  • Handles each trunk segment independently

The resampling process involves:

  1. Calculating the total length of each trunk
  2. Determining the number of segments needed based on 'delta'
  3. Linearly interpolating new points along each segment
Note
The actual spacing may vary slightly to ensure the start and end points are preserved exactly
This method is typically used as a preprocessing step before mesh generation
See also
linearSplineResampleTrunk() for the single-trunk implementation
allCubicSplineResampledTrunks() for a smoother but more computationally intensive alternative
Here is the call graph for this function:
Here is the caller graph for this function:

◆ assembleTrunks() [1/2]

std::map< int, SWCNode > NeuronGraph::assembleTrunks ( const std::map< int, std::map< int, SWCNode >> &  resampledTrunks,
const std::map< int, int > &  trunkParentMap 
)

Combines resampled trunks using a parent-child relationship map.

Parameters
[in]resampledTrunksMap of trunk IDs to their resampled nodes
[in]trunkParentMapMap of trunk IDs to their parent trunk IDs
Returns
A single map containing all nodes from all trunks with updated parent references

This version is used when trunk nodes have been resampled and need to be reconnected based on the original topology.

◆ assembleTrunks() [2/2]

std::map< int, SWCNode > NeuronGraph::assembleTrunks ( const std::map< int, std::map< int, SWCNode >> &  trunkNodeSets) const

Combines multiple trunks into a single node set.

Combines multiple trunk segments into a single neuron representation with sequential node IDs.

Parameters
[in]trunkNodeSetsMap of trunk IDs to their nodes
Returns
A single map containing all nodes from all trunks
Note
This version preserves the original node IDs
Parameters
trunkNodeSetsMap of trunk segments where each key is a trunk ID and value is a map of node IDs to SWCNodes
Returns
std::map<int, SWCNode> A single map of SWC nodes with sequential IDs representing the assembled neuron

This method takes multiple trunk segments and combines them into a single neuron representation while ensuring all node IDs are unique and sequential. It handles the remapping of parent-child relationships to maintain the neuron's topological structure.

Key features:

  • Renumbers all node IDs sequentially starting from 1
  • Maintains parent-child relationships between nodes
  • Handles duplicate nodes across different trunks (uses first occurrence)
  • Ensures the root node has pid = -1

The method performs two main passes:

  1. First pass: Creates a mapping from old node IDs to new sequential IDs
  2. Second pass: Updates all parent IDs using the new mapping
Note
This method assumes that node IDs within each trunk have NOT been reset to start at 1. If the trunks have already been renumbered, use the other overload that takes a trunkParentMap.
The resulting node IDs will be sequential and unique across all trunks.
See also
assembleTrunks(const std::map<int, std::map<int, SWCNode>>&, const std::map<int,int>&) for the version that handles parent-child relationships between trunks
Here is the caller graph for this function:

◆ cubicSplineResampleTrunk()

std::map< int, SWCNode > NeuronGraph::cubicSplineResampleTrunk ( const std::map< int, SWCNode > &  trunk,
double &  delta 
) const

Resamples a single trunk using cubic spline interpolation.

Resamples a single trunk segment using cubic spline interpolation.

Parameters
[in]trunkThe trunk to resample (map of node IDs to SWCNodes)
[in,out]deltaTarget spacing between resampled points (may be adjusted)
Returns
A new set of nodes representing the resampled trunk

Cubic spline interpolation generally produces smoother curves than linear interpolation, especially for coarsely sampled data.

Parameters
trunkMap of node IDs to SWCNode objects representing the trunk to be resampled
deltaTarget distance between consecutive nodes in the resampled trunk (in microns)
Returns
std::map<int, SWCNode> A new map of resampled nodes with sequential IDs

This method performs cubic spline resampling of a neuron trunk to achieve a smooth and uniform distribution of nodes along its length. It creates a smooth curve that passes through all original nodes and samples new points along this curve.

Key features:

  • Preserves the first and last nodes of the original trunk exactly
  • Fits natural cubic splines to x, y, and z coordinates separately
  • Parameterizes the spline by arc length for uniform sampling
  • Maintains the dominant node type throughout the resampled trunk
  • Handles 3D coordinates and radii with appropriate interpolation
  • Adjusts node IDs and parent IDs to maintain a valid tree structure

The algorithm works as follows:

  1. Converts the input trunk to an ordered vector of nodes
  2. Determines the dominant node type in the trunk
  3. Fits natural cubic splines to x, y, and z coordinates
  4. Parameterizes the spline by arc length
  5. Samples new points at approximately 'delta' intervals along the curve
  6. Ensures the first and last nodes match the original exactly
Note
This method produces smoother results than linear interpolation but is more computationally intensive
The actual spacing may vary slightly to ensure the curve is sampled properly
If the input trunk has fewer than 4 nodes, falls back to linear interpolation
See also
allCubicSplineResampledTrunks() for resampling multiple trunks
linearSplineResampleTrunk() for a faster but less smooth alternative
Here is the caller graph for this function:

◆ generateRefinements() [1/2]

std::map< int, std::map< int, SWCNode > > NeuronGraph::generateRefinements ( const std::map< int, SWCNode > &  nodeSet,
double &  delta,
int &  N,
std::string &  method 
)

Generates multiple levels of refined neuron morphologies.

Generates multiple levels of mesh refinements for a neuron morphology.

Parameters
[in]nodeSetThe set of nodes to refine
[in,out]deltaInitial spacing parameter for refinement
[in,out]NNumber of refinement levels to generate
[in,out]methodRefinement method ("linear" or "cubic")
Returns
A map where keys are refinement levels and values are the refined node sets

This method generates a series of increasingly refined versions of the input neuron morphology by repeatedly applying the specified interpolation method.

Parameters
nodeSetMap of SWC nodes representing the input neuron morphology
deltaInitial target spacing between nodes (in microns). This value is halved in each refinement level.
NNumber of refinement levels to generate
methodInterpolation method to use ("linear" or "cubic")
Returns
std::map<int, std::map<int, SWCNode>> Map where each key is the refinement level (0 to N-1) and the value is the resampled neuron at that refinement level

This method creates a series of increasingly refined versions of the input neuron morphology. Each refinement level approximately halves the spacing between nodes, providing a multi-resolution representation of the neuron that can be used for progressive rendering or adaptive meshing.

Key features:

  • Supports both linear and cubic spline interpolation methods
  • Progressively refines the mesh by halving 'delta' at each level
  • Maintains topological relationships between nodes
  • Preserves branch points and overall neuron structure
  • Returns all refinement levels for comparison or progressive loading

The refinement process works as follows:

  1. Extracts trunk segments from the input neuron
  2. Determines parent-child relationships between trunks
  3. For each refinement level i (0 to N-1): a. Resamples all trunks using the specified method with spacing delta/(2^i) b. Reassembles the neuron from the resampled trunks c. Stores the result in the output map
Note
The input 'delta' parameter will be modified during execution (halved at each level)
If an unsupported method is provided, falls back to linear interpolation
The first refinement level (i=0) uses the initial delta value
See also
allLinearSplineResampledTrunks() for the linear interpolation implementation
allCubicSplineResampledTrunks() for the cubic spline implementation
Here is the call graph for this function:
Here is the caller graph for this function:

◆ generateRefinements() [2/2]

std::map<int, std::map<int,SWCNode> > NeuronGraph::generateRefinements ( double &  delta,
int &  N,
std::string &  method 
)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Generates refinements for the current graph's nodes

Here is the call graph for this function:

◆ getNeighborMap()

std::map< int, std::vector< int > > NeuronGraph::getNeighborMap ( const std::map< int, SWCNode > &  nodeSet) const
private

Builds a neighbor map from a set of nodes.

Builds an adjacency list representing the connectivity between nodes in a neuron morphology.

Parameters
[in]nodeSetSet of nodes to process
Returns
Map where each key is a node ID and the value is a list of neighbor node IDs

This helper function constructs an adjacency list representation of the graph from a set of nodes by establishing parent-child relationships.

Parameters
nodeSetMap of SWC nodes where key is node ID and value is the SWCNode object
Returns
std::map<int, std::vector<int>> where each key is a node ID and value is a vector of its neighbor node IDs

This method constructs an undirected graph representation of the neuron morphology by creating neighbor relationships between connected nodes. For each node in the input set, it establishes bidirectional connections between the node and its parent (if the parent exists in the nodeSet).

The resulting neighbor map allows efficient traversal of the neuron's topology in any direction, which is essential for various analysis and processing tasks such as trunk extraction and topological sorting.

Note
Only nodes present in the input nodeSet are included in the neighbor map
The method creates bidirectional edges (A→B and B→A) for each parent-child relationship
See also
getTrunks() for the primary use of this method
topologicalSort() for another application of the neighbor map
Here is the caller graph for this function:

◆ getNodes()

auto NeuronGraph::getNodes ( )
inline

Returns a copy of all nodes in the graph.

Returns
A map of node IDs to SWCNode objects
Here is the caller graph for this function:

◆ getTrunkParentMap()

std::map< int, int > NeuronGraph::getTrunkParentMap ( const std::map< int, SWCNode > &  nodeSet,
const std::map< int, std::map< int, SWCNode >> &  trunkNodeSets 
) const

Creates a mapping from trunk IDs to their parent trunk IDs.

Determines the parent-child relationships between trunk segments in a neuron morphology.

Parameters
[in]nodeSetThe original set of nodes
[in]trunkNodeSetsMap of trunk IDs to their nodes
Returns
A map where keys are trunk IDs and values are parent trunk IDs (-1 for root trunks)
Parameters
nodeSetOriginal map of all SWC nodes in the neuron
trunkNodeSetsMap of trunk segments where each key is a trunk ID and value is a map of node IDs to SWCNodes
Returns
std::map<int, int> Map where each key is a trunk ID and value is its parent trunk ID (-1 for root trunks)

This method analyzes the connectivity between trunk segments to establish a hierarchical parent-child relationship between them. It determines which trunk connects to which by examining the parent-child relationships of the nodes at the connection points between trunks.

The algorithm works in two main phases:

  1. Builds a reverse lookup (node ID → trunk ID) to quickly find which trunk a node belongs to
  2. For each trunk, examines the parent of its first node to determine its parent trunk

Key assumptions:

  • The first node in each trunk's node map is the rootward (proximal) end of the trunk
  • Trunks are topologically sorted with parent nodes appearing before their children
  • The input trunks have already been extracted and may have been processed (e.g., resampled)
Note
A return value of -1 indicates a root trunk (no parent)
If a trunk's first node has no parent or its parent is not in any trunk, it's considered a root trunk
See also
getTrunks() for how trunks are initially extracted
assembleTrunks() for how this parent information is used in reconstruction
Here is the caller graph for this function:

◆ getTrunks() [1/2]

std::map<int,std::map<int,SWCNode> > NeuronGraph::getTrunks ( bool  resetIndex = false) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Extracts trunk segments from the current graph

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getTrunks() [2/2]

std::map< int, std::map< int, SWCNode > > NeuronGraph::getTrunks ( const std::map< int, SWCNode > &  nodeSet,
bool  resetIndex = false 
) const

Extracts trunk segments from a neuron morphology.

Parameters
[in]nodeSetThe set of nodes to process
[in]resetIndexIf true, renumbers node IDs sequentially
Returns
A map where each key is a trunk ID and the value is a map of node IDs to SWCNodes

A trunk is defined as a linear segment between branch points or between a branch point and a leaf node.

Parameters
nodeSetMap of SWC nodes where key is node ID and value is the SWCNode object
resetIndexIf true, renumbers node IDs sequentially within each trunk (default: false)
Returns
std::map<int, std::map<int, SWCNode>> where each key is a trunk ID and value is a map of node IDs to SWCNodes in that trunk

This method identifies and extracts linear segments (trunks) from a neuron morphology. A trunk is defined as a path between:

  • Two branch points (nodes with degree > 2)
  • A branch point and an endpoint (node with degree 1)
  • The root node and the first branch point

The algorithm works as follows:

  1. Builds a neighbor map to represent the neuron's connectivity
  2. Identifies branch points (nodes with >2 neighbors)
  3. For each branch point, traverses to connected nodes to extract linear segments
  4. Uses canonical representation to avoid duplicate trunks
  5. Optionally renumbers node IDs sequentially within each trunk

The method handles both directed and undirected traversal of the neuron morphology.

Note
When resetIndex is true, node IDs within each trunk will be renumbered sequentially starting from 1, with parent IDs adjusted accordingly. The first node in each trunk will have pid = -1.
The method uses a canonical representation to ensure each trunk is only included once, regardless of traversal direction.
See also
getNeighborMap() for the graph representation used internally
getTrunkParentMap() for establishing relationships between trunks
Here is the call graph for this function:
Here is the caller graph for this function:

◆ hasSomaSegment() [1/2]

bool NeuronGraph::hasSomaSegment ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Checks if the current graph contains a soma segment

Here is the call graph for this function:
Here is the caller graph for this function:

◆ hasSomaSegment() [2/2]

bool NeuronGraph::hasSomaSegment ( const std::map< int, SWCNode > &  nodeSet) const

Checks if the node set contains a soma segment.

Checks if the neuron has multiple soma nodes (soma segment)

Parameters
[in]nodeSetThe set of nodes to check
Returns
true if a soma segment is found, false otherwise

A soma segment is defined as multiple connected nodes of type 1 (soma).

Parameters
nodeSetMap of SWC nodes to check
Returns
true if multiple soma nodes exist, false otherwise

This method detects the presence of soma segments, which occur when multiple nodes have type 1 (soma). In proper neuron morphology, there should be exactly one soma node. Multiple soma nodes can cause issues in analysis and mesh generation.

The method uses early exit optimization - it returns true as soon as a second soma node is found, avoiding unnecessary iterations.

Note
Soma nodes are identified by type == 1 in SWC format
This is used in preprocessing to clean up neuron data
See also
preprocess() for automatic soma segment removal
removeSomaSegment() for soma segment correction

◆ isSomaMissing() [1/2]

bool NeuronGraph::isSomaMissing ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Checks if the current graph is missing a soma

Here is the call graph for this function:
Here is the caller graph for this function:

◆ isSomaMissing() [2/2]

bool NeuronGraph::isSomaMissing ( const std::map< int, SWCNode > &  nodeSet) const

Checks if the node set is missing a soma.

Checks if the neuron is missing a soma node.

Parameters
[in]nodeSetThe set of nodes to check
Returns
true if no soma is present, false otherwise

This is the inverse of hasSomaSegment() and is provided for readability.

Parameters
nodeSetMap of SWC nodes to check
Returns
true if no soma node exists, false if soma is present

This method determines whether the neuron morphology lacks a soma (cell body). Every valid neuron should have exactly one soma node of type 1. Missing somas can occur in incomplete reconstructions or when dealing with neuron fragments.

The method uses early exit - it returns false as soon as any soma node is found, making it efficient for large neuron datasets.

Note
Soma nodes are identified by type == 1 in SWC format
This is used in preprocessing to add missing somas
See also
preprocess() for automatic soma addition
setSoma() for adding missing soma nodes

◆ isTopologicallySorted() [1/2]

bool NeuronGraph::isTopologicallySorted ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Checks if the current graph's nodes are topologically sorted

Here is the call graph for this function:
Here is the caller graph for this function:

◆ isTopologicallySorted() [2/2]

bool NeuronGraph::isTopologicallySorted ( const std::map< int, SWCNode > &  nodeSet) const

Checks if a set of nodes is topologically sorted.

Checks if the neuron nodes are topologically sorted.

Parameters
[in]nodeSetThe set of nodes to check
Returns
true if the nodes are topologically sorted, false otherwise

A set of nodes is considered topologically sorted if for every node, its parent ID is less than its own ID (i.e., parent nodes come before their children in the sequence).

Parameters
nodeSetMap of SWC nodes to check
Returns
true if nodes are topologically sorted, false otherwise

This method verifies that all parent nodes have IDs smaller than their children nodes (parent_id < child_id). This property is important for many neuron analysis algorithms and ensures proper tree traversal.

A topologically sorted neuron means that when nodes are processed in ID order, all parent nodes are encountered before their children.

Note
Root nodes (pid == -1) are always considered valid
The commented debug output can be uncommented for troubleshooting
See also
SWCNode structure for node ID and parent ID fields

◆ linearSplineResampleTrunk()

std::map< int, SWCNode > NeuronGraph::linearSplineResampleTrunk ( const std::map< int, SWCNode > &  trunk,
double &  delta 
) const

Resamples a single trunk using linear interpolation.

Resamples a single trunk segment using linear interpolation.

Parameters
[in]trunkThe trunk to resample (map of node IDs to SWCNodes)
[in,out]deltaTarget spacing between resampled points (may be adjusted)
Returns
A new set of nodes representing the resampled trunk
Parameters
trunkMap of node IDs to SWCNode objects representing the trunk to be resampled
deltaTarget distance between consecutive nodes in the resampled trunk (in microns)
Returns
std::map<int, SWCNode> A new map of resampled nodes with sequential IDs

This method performs linear resampling of a neuron trunk to achieve a more uniform distribution of nodes along its length. It creates a piecewise linear approximation of the original trunk with nodes spaced approximately 'delta' units apart.

Key features:

  • Preserves the first and last nodes of the original trunk exactly
  • Uses linear interpolation between existing nodes
  • Maintains the dominant node type throughout the resampled trunk
  • Adjusts node IDs and parent IDs to maintain a valid tree structure
  • Handles 3D coordinates and radii

The algorithm works as follows:

  1. Converts the input trunk to an ordered vector of nodes
  2. Determines the dominant node type in the trunk
  3. Calculates the total arc length of the trunk
  4. Determines the number of segments needed based on 'delta'
  5. Performs linear interpolation between existing nodes to create new points
  6. Ensures the first and last nodes match the original exactly
Note
The actual spacing may vary slightly to ensure the first and last nodes are preserved exactly
If the input trunk has fewer than 2 nodes, returns an empty map
The minimum number of points in the resampled trunk is 4 to ensure reasonable shape representation
See also
allLinearSplineResampledTrunks() for resampling multiple trunks
cubicSplineResampleTrunk() for a smoother but more computationally intensive alternative
Here is the caller graph for this function:

◆ numberOfEdges()

int NeuronGraph::numberOfEdges ( )
inline

Returns the number of edges in the graph.

Returns
The total number of edges
Here is the caller graph for this function:

◆ numberOfNodes()

int NeuronGraph::numberOfNodes ( )
inline

Returns the number of nodes in the graph.

Returns
The total number of nodes
Here is the caller graph for this function:

◆ preprocess()

std::map< int, SWCNode > NeuronGraph::preprocess ( const std::map< int, SWCNode > &  nodeSet) const

Applies standard preprocessing steps to a set of nodes.

Preprocesses a node set to ensure proper soma properties.

Parameters
[in]nodeSetThe set of nodes to preprocess
Returns
A new set of preprocessed nodes

Preprocessing includes:

  1. Topological sorting
  2. Soma segment handling
  3. Soma addition if missing
Parameters
nodeSetThe input map of SWC nodes to preprocess
Returns
A preprocessed map of SWC nodes with corrected soma properties

This method performs essential preprocessing steps on neuron data:

  1. Checks if soma is missing and adds one if necessary
  2. Removes soma segments if multiple soma nodes exist

The preprocessing ensures that the neuron has exactly one soma node, which is critical for proper neuron analysis and mesh generation.

See also
isSomaMissing(const std::map<int, SWCNode>& nodeSet)
hasSomaSegment(const std::map<int, SWCNode>& nodeSet)
setSoma(const std::map<int, SWCNode>& nodeSet)
removeSomaSegment(const std::map<int, SWCNode>& nodeSet)
Here is the caller graph for this function:

◆ readFromFile()

void NeuronGraph::readFromFile ( const std::string &  filename)

Reads neuron data from an SWC file.

Reads neuron morphology data from an SWC format file.

Parameters
[in]filenamePath to the SWC file to read
Exceptions
std::runtime_errorIf the file cannot be opened or parsed
See also
http://www.neuronland.org/NLMorphologyConverter/MorphologyFormats/SWC/Spec.html
Parameters
filenamePath to the SWC file to read

This method parses an SWC (Standardized Morphology Format) file and populates the graph with neuron nodes. The SWC format contains one node per line with the following columns: ID, type, x, y, z, radius, parent_ID.

The parser handles:

  • Comment lines (starting with #)
  • Inline comments
  • Whitespace normalization
  • Tab-to-space conversion
  • Error reporting for malformed lines
Note
Clears existing graph data before loading new data
Prints summary information upon successful completion
Warning
If file cannot be opened, an error message is printed and method returns
See also
addNode(const SWCNode& node) for individual node processing
Here is the caller graph for this function:

◆ readFromFileUGX()

void NeuronGraph::readFromFileUGX ( const std::string &  filename)

Reads neuron data from a UGX file.

Reads neuron morphology data from a UGX file.

Parameters
[in]filenamePath to the UGX file to read
Exceptions
std::runtime_errorIf the file cannot be opened or parsed
Note
UGX is an XML-based format used by the UG4 simulation framework
Parameters
filenamePath to the input UGX file to read

This method imports neuron morphology data from a UGX file and populates the internal data structures of the NeuronGraph class. It handles the conversion from the UGX format to the internal SWC-based representation.

The method processes the following UGX elements:

  • Vertex coordinates (3D positions)
  • Edge connectivity between nodes
  • Vertex attributes (diameters, types, etc.)
  • Subset information for different neuron components

The import process includes:

  1. Parsing the XML structure of the UGX file
  2. Extracting vertex coordinates and creating SWC nodes
  3. Reconstructing parent-child relationships from edges
  4. Loading additional attributes like diameters and node types
  5. Validating the imported morphology
Note
The method clears any existing neuron data before importing
If the file cannot be read or is malformed, error messages are printed to stderr
The method attempts to map UGX subsets back to SWC node types when possible
See also
writeToFileUGX() for the corresponding export functionality
https://github.com/UG4/ug4 for more information about the UGX format
Here is the caller graph for this function:

◆ readFromFileUGXorSWC()

void NeuronGraph::readFromFileUGXorSWC ( const std::string &  filename)

Reads a neuron file, automatically detecting the format.

Automatically detects file format and reads neuron data.

Parameters
[in]filenamePath to the neuron file (SWC or UGX)

This method examines the file extension to determine whether to use readFromFile() or readFromFileUGX().

Exceptions
std::runtime_errorIf the file format is not supported
Parameters
filenamePath to the input file (SWC or UGX format)

This method automatically determines the file format based on the file extension and calls the appropriate reader method:

This provides a convenient unified interface for loading neuron data regardless of the input format.

Warning
Prints error message for unsupported file extensions
See also
readFromFile(const std::string& filename) for SWC format
readFromFileUGX(const std::string& filename) for UGX format
Here is the caller graph for this function:

◆ removeSomaSegment() [1/2]

std::map<int, SWCNode> NeuronGraph::removeSomaSegment ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Removes the soma segment from the current graph

Here is the call graph for this function:
Here is the caller graph for this function:

◆ removeSomaSegment() [2/2]

std::map< int, SWCNode > NeuronGraph::removeSomaSegment ( const std::map< int, SWCNode > &  inputNodes) const

Removes the soma segment from a set of nodes.

Removes multiple soma nodes and replaces them with a single averaged soma.

Parameters
[in]inputNodesThe set of nodes to process
Returns
A new set of nodes with the soma segment removed

This method identifies and removes the soma segment (multiple connected type 1 nodes) and replaces it with a single representative soma node at the average position.

Parameters
inputNodesThe input map of SWC nodes containing multiple soma nodes
Returns
A new map of SWC nodes with a single soma node at ID 1

This method processes neuron morphologies that have multiple soma nodes (soma segments) and consolidates them into a single soma node. The process involves:

  1. Identifying all soma nodes (type == 1)
  2. Computing the average position and radius of all soma nodes
  3. Creating a new soma node with ID 1 at the averaged location
  4. Reassigning all non-soma nodes with new sequential IDs starting from 2
  5. Updating parent-child relationships to connect to the new soma
  6. Ensuring topological sorting of the result
Note
If no soma nodes are found, returns the input unchanged
The resulting soma always has ID 1 and parent ID -1 (root)
All nodes originally connected to any soma will be connected to the new soma
See also
hasSomaSegment() to detect if soma segments exist
topologicalSort() for ensuring proper node ordering
Here is the call graph for this function:
Here is the caller graph for this function:

◆ setNodes()

void NeuronGraph::setNodes ( const std::map< int, SWCNode > &  nodeSet)

Replaces the current set of nodes in the graph.

Sets the nodes of the graph, replacing any existing nodes.

Parameters
[in]nodeSetNew set of nodes to use

This method clears the current graph and rebuilds it using the provided nodes. It automatically updates the internal adjacency list.

Parameters
nodeSetA map containing SWC nodes indexed by their IDs

This method clears the current graph data and repopulates it with the provided node set. It rebuilds all parent-child relationships from scratch.

Note
This is equivalent to reconstructing the graph with new data
See also
addNode(const SWCNode& node)
Here is the caller graph for this function:

◆ setSoma() [1/2]

std::map<int, SWCNode> NeuronGraph::setSoma ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Adds a soma node to the current graph if none exists

Here is the call graph for this function:
Here is the caller graph for this function:

◆ setSoma() [2/2]

std::map< int, SWCNode > NeuronGraph::setSoma ( const std::map< int, SWCNode > &  nodeSet) const

Adds a soma node if none exists.

Assigns a soma node to a neuron morphology that lacks one.

Parameters
[in]nodeSetThe set of nodes to process
Returns
A new set of nodes with a soma node added if needed

If no soma (type 1) node is present, this method adds one at the root position of the neuron tree.

Parameters
nodeSetThe input map of SWC nodes missing a soma
Returns
A new map of SWC nodes with a soma node assigned

This method addresses neuron morphologies that are missing a soma (cell body) by converting the first root node found (pid == -1) into a soma node (type = 1).

The method follows this logic:

  1. First checks if a soma already exists using isSomaMissing()
  2. If soma is present, returns the input unchanged
  3. If soma is missing, searches for the first root node (pid == -1)
  4. Converts the root node's type to 1 (soma type)
  5. Prints a confirmation message with the assigned node ID

This operation is essential for:

  • Ensuring every neuron has exactly one soma for proper analysis
  • Correcting incomplete neuron reconstructions
  • Preparing neuron data for mesh generation algorithms
  • Maintaining consistency with neuron morphology standards
Note
If no root node is found, prints a warning and returns input unchanged
Only the first root node encountered is converted to soma
The node's position and other properties remain unchanged
Warning
If multiple root nodes exist, only the first one becomes the soma
See also
isSomaMissing() to detect if soma assignment is needed
preprocess() which automatically calls this method when needed
Here is the call graph for this function:

◆ splitEdges() [1/2]

std::map<int, SWCNode> NeuronGraph::splitEdges ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Splits all edges in the current graph

Here is the call graph for this function:
Here is the caller graph for this function:

◆ splitEdges() [2/2]

std::map< int, SWCNode > NeuronGraph::splitEdges ( const std::map< int, SWCNode > &  nodeSet) const

Splits all edges in the graph by inserting midpoint nodes.

Splits all edges in the neuron by inserting midpoint nodes.

Parameters
[in]nodeSetThe set of nodes to process
Returns
A new set of nodes with edges split

This method inserts a new node at the midpoint of each edge, effectively doubling the number of edges while preserving the overall shape of the neuron.

Parameters
nodeSetThe input map of SWC nodes to process
Returns
A new map of SWC nodes with midpoint nodes inserted on all edges

This method performs edge subdivision by inserting a new node at the midpoint of every parent-child edge in the neuron morphology. The process involves:

  1. Creating a midpoint node for each parent-child relationship
  2. Positioning the midpoint at the average coordinates of parent and child
  3. Setting the midpoint radius as the average of parent and child radii
  4. Updating the topology so child nodes connect through their midpoints
  5. Ensuring topological sorting of the final result

This operation effectively doubles the resolution of the neuron morphology, which is useful for:

  • Mesh refinement operations
  • Improved geometric accuracy in simulations
  • Smoother interpolation between neuron segments
Note
New node IDs are assigned sequentially starting from the highest existing ID + 1
Midpoint nodes inherit the type of their child node
Root nodes (pid == -1) are not affected by this operation
See also
splitEdgesN() for performing multiple iterations of edge splitting
topologicalSort() for ensuring proper node ordering
Here is the call graph for this function:
Here is the caller graph for this function:

◆ splitEdgesN() [1/2]

std::vector< std::map< int, SWCNode > > NeuronGraph::splitEdgesN ( const std::map< int, SWCNode > &  nodeSet,
int  N 
) const

Applies edge splitting N times recursively.

Performs N iterations of edge splitting on the neuron morphology.

Parameters
[in]nodeSetThe set of nodes to process
[in]NNumber of times to split the edges
Returns
A vector of node sets, where each element represents the result of i+1 splits (i = 0 to N-1)
Parameters
nodeSetThe input map of SWC nodes to process
NThe number of edge splitting iterations to perform
Returns
A vector containing the node sets after each iteration of splitting

This method applies the splitEdges() operation N times in sequence, where each iteration uses the result of the previous iteration as input. This creates progressively finer subdivisions of the neuron morphology.

The returned vector contains N maps, where:

  • splits[0] contains the result after 1 iteration
  • splits[1] contains the result after 2 iterations
  • splits[N-1] contains the result after N iterations

After N iterations, the number of nodes grows exponentially, with each iteration approximately doubling the number of edges (and thus nodes).

Use cases:

  • Progressive mesh refinement for adaptive simulations
  • Creating multiple levels of detail for the same neuron
  • Analyzing convergence properties of numerical methods
Note
Each iteration significantly increases the number of nodes
Memory usage grows exponentially with N
Consider memory constraints when choosing large values of N
See also
splitEdges() for single iteration edge splitting
Here is the call graph for this function:
Here is the caller graph for this function:

◆ splitEdgesN() [2/2]

std::vector<std::map<int, SWCNode> > NeuronGraph::splitEdgesN ( int  N) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Applies edge splitting N times to the current graph

Here is the call graph for this function:
Here is the caller graph for this function:

◆ swc2ugx()

void NeuronGraph::swc2ugx ( const std::string &  inputfile,
const std::string &  outputfile 
)

Converts an SWC file to UGX format.

Parameters
[in]inputfilePath to the input SWC file
[in]outputfilePath for the output UGX file

This is a convenience method that combines readFromFile() and writeToFileUGX().

Parameters
inputfilePath to the input SWC file
outputfilePath to the output UGX file

This static utility method provides convenient SWC to UGX format conversion. It creates a temporary NeuronGraph instance, loads the SWC data, and exports it in UGX format suitable for mesh generation and finite element analysis.

Note
This is a static method that can be called without a NeuronGraph instance
See also
ugx2swc(const std::string& inputfile, const std::string& outputfile) for reverse conversion
writeToFileUGX() for UGX output functionality
Here is the caller graph for this function:

◆ topologicalSort() [1/2]

std::map<int, SWCNode> NeuronGraph::topologicalSort ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Sorts the current graph's nodes topologically

Here is the call graph for this function:
Here is the caller graph for this function:

◆ topologicalSort() [2/2]

std::map< int, SWCNode > NeuronGraph::topologicalSort ( const std::map< int, SWCNode > &  nodeSet) const

Sorts nodes topologically using Kahn's algorithm.

Performs topological sorting of neuron nodes to ensure proper parent-child ordering.

Parameters
[in]nodeSetThe set of nodes to sort
Returns
A new map of nodes sorted in topological order

This method ensures that parent nodes always appear before their children in the resulting sequence, which is important for many processing steps.

Note
If the graph contains cycles, the behavior is undefined.
See also
https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
Parameters
nodeSetThe input map of SWC nodes to sort
Returns
A new map of SWC nodes with reassigned IDs in topological order

This method implements Kahn's algorithm for topological sorting to ensure that all parent nodes have smaller IDs than their children. The algorithm:

  1. Builds an adjacency list and calculates in-degrees for all nodes
  2. Starts with nodes having zero in-degree (root nodes)
  3. Processes nodes in breadth-first order, updating in-degrees
  4. Reassigns node IDs sequentially (1, 2, 3, ...) based on topological order
  5. Updates parent IDs to maintain correct relationships

Topological sorting is essential for:

  • Ensuring proper tree traversal algorithms work correctly
  • Maintaining consistency in neuron analysis operations
  • Enabling efficient parent-to-child processing
  • Supporting mesh generation algorithms that rely on ordered traversal

The resulting neuron will have:

  • Root nodes (soma) with the smallest IDs
  • All parent nodes having IDs smaller than their children
  • Sequential ID numbering starting from 1
Note
This method creates entirely new node IDs while preserving topology
The original node IDs are completely replaced
Parent-child relationships are preserved but with new ID mappings
See also
isTopologicallySorted() to check if sorting is needed

◆ ugx2swc()

void NeuronGraph::ugx2swc ( const std::string &  inputfile,
const std::string &  outputfile 
)

Converts a UGX file to SWC format.

Parameters
[in]inputfilePath to the input UGX file
[in]outputfilePath for the output SWC file

This is a convenience method that combines readFromFileUGX() and writeToFile().

Parameters
inputfilePath to the input UGX file
outputfilePath to the output SWC file

This static utility method provides convenient UGX to SWC format conversion. It creates a temporary NeuronGraph instance, loads the UGX data, and exports it in standard SWC format for compatibility with neuron analysis tools.

Note
This is a static method that can be called without a NeuronGraph instance
See also
swc2ugx(const std::string& inputfile, const std::string& outputfile) for reverse conversion
writeToFile() for SWC output functionality
Here is the caller graph for this function:

◆ writeToFile() [1/2]

void NeuronGraph::writeToFile ( const std::map< int, SWCNode > &  nodeSet,
const std::string &  filename 
)

Writes a set of nodes to an SWC file.

Writes neuron morphology data to an SWC format file.

Parameters
[in]nodeSetThe nodes to write
[in]filenamePath to the output file
Note
The file will be overwritten if it already exists
Parameters
nodeSetMap of SWC nodes to write to file
filenameOutput file path for the SWC data

This method exports neuron morphology data in the standard SWC format. Nodes are written in sorted order by ID to ensure consistent output. Each line contains: ID, type, x, y, z, radius, parent_ID.

The output format is compatible with standard neuron analysis tools and can be read back using readFromFile().

Note
If output file cannot be opened, an error message is printed and method returns
Prints confirmation message upon successful completion
See also
readFromFile(const std::string& filename) for reading SWC files
Here is the caller graph for this function:

◆ writeToFile() [2/2]

void NeuronGraph::writeToFile ( const std::string &  filename)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Writes the current graph's nodes to an SWC file

Here is the call graph for this function:
Here is the caller graph for this function:

◆ writeToFileUGX() [1/2]

void NeuronGraph::writeToFileUGX ( const std::map< int, SWCNode > &  nodeSet,
const std::string &  filename 
)

Writes a set of nodes to a UGX file.

Writes neuron morphology data to a UGX file format.

Parameters
[in]nodeSetThe nodes to write
[in]filenamePath to the output file
Note
The file will be overwritten if it already exists
Parameters
nodeSetMap of SWC nodes to be written, where key is node ID and value is SWCNode object
filenamePath to the output UGX file

This method converts the internal neuron representation into the UGX file format, which is compatible with the UG4 simulation framework. The UGX format is an XML-based format that can represent complex graph structures with additional attributes.

The output UGX file includes:

  • 3D vertex coordinates for each node
  • Edge connectivity based on parent-child relationships
  • Node diameters as vertex attributes
  • Subset definitions for different neuron components (soma, axon, dendrites, etc.)

The method performs the following steps:

  1. Extracts node positions, diameters, and connectivity from the input node set
  2. Creates a mapping between node IDs and internal indices
  3. Organizes nodes into subsets based on their type (soma, axon, dendrites, etc.)
  4. Constructs the UGX XML structure with proper formatting
  5. Writes the XML data to the specified file
Note
The method preserves the 3D structure and topological relationships of the neuron
If the file cannot be written, an error message is printed to stderr
The method automatically handles different SWC node types (soma=1, axon=2, etc.)
See also
readFromFileUGX() for the corresponding import functionality
https://github.com/UG4/ug4 for more information about the UGX format
Here is the caller graph for this function:

◆ writeToFileUGX() [2/2]

void NeuronGraph::writeToFileUGX ( const std::string &  filename)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Writes the current graph's nodes to a UGX file

Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ edges

std::map<int, std::vector<int> > NeuronGraph::edges
private

Adjacency list representation of the neuron graph.

◆ nodes

std::map<int,SWCNode> NeuronGraph::nodes
private

Map of node IDs to SWCNode objects.


The documentation for this class was generated from the following files: