graph_gt#
Graph class and utilities built on the graph-tool library.
Graph is the central data structure for vasculature and network
analyses in ClearMap. It wraps a graph_tool.Graph backend and adds:
Spatial embedding — vertex coordinates in voxels (
coordinates), physical units (coordinates_units), and atlas space (coordinates_atlas).Edge geometry — variable-length arrays stored along each edge that capture intermediate vertex positions, radii, and labels between branch points. Two storage modes are supported:
'graph'(a single flat array at graph level, indexed by per-edge start/end pairs) and'edge'(variable-length vectors stored in each edge property). Convert between them withGraph.set_edge_geometry_type().Vessel typing — properties for artery/vein binary labels, signal intensity, radii in voxels and µm, distance to surface, and atlas annotation.
Subgraph extraction —
Graph.sub_graph()(vertex/edge masks),Graph.sub_slice()(axis-aligned spatial window),Graph.largest_component().Atlas annotation —
Graph.annotate_properties()andGraph.transform_properties()apply arbitrary callables to vertex or edge properties in one pass.Morphological graph operations — binary dilation, erosion, opening, and closing on vertex and edge label arrays, propagating along graph topology.
Persistence —
Graph.save()/Graph.load()via the graph-tool.gtformat.
Typical usage#
Graphs are produced by
graph_from_skeleton()
and then simplified by cleaning and reduction
See also
ClearMap.Analysis.graphs.graph_processingGraph construction, cleaning, reduction, and label tracing.
VesselGraphProcessorPipeline orchestrator that builds and annotates vasculature graphs.
- class Graph(name=None, n_vertices=None, edges=None, directed=None, vertex_coordinates=None, vertex_radii=None, edge_coordinates=None, edge_radii=None, edge_geometries=None, shape=None, vertex_labels=None, edge_labels=None, annotation=None, base=None, edge_geometry_type='graph')[source]#
Bases:
AnnotatedGraphGraph class to handle graph construction and analysis.
Note
This is an interface from ClearMap graphs to graph_tool.
- classmethod partial_load(filename: str, *, exclude_edge_geometry_properties: bool = False, include_dict: Dict[str, Iterable[str]] | None = None, exclude_dict: Dict[str, Iterable[str]] | None = None, include: Iterable[str] | None = None, exclude: Iterable[str] | None = None)[source]#
Partially load a graph from a file, allowing for selective property inclusion/exclusion.
Five options are available, in order of precedence:
exclude_edge_geometry_properties: ifTrue, all edge geometry properties (those starting with'edge_geometry_') are excluded.include_dict: a dictionary specifying which properties to include for each scope ('vertex','edge','graph').exclude_dict: a dictionary specifying which properties to exclude for each scope.include: a list of property names to include across all scopes.exclude: a list of property names to exclude across all scopes.
Note
To inspect which properties are available in the file, use
Graph.scan_gt_properties(filename, as_dict=True).
- static scan_gt_properties(filename: str, as_dict: bool = False)[source]#
Scan the graph-tool file for its properties without loading the entire graph.
- Parameters:
filename (str) – The path to the graph-tool file.
as_dict (bool) – If True, return a dictionary of property names. If False, return a list of tuples (scope, name, dtype).
- annotate_properties(annotation, vertex_properties=None, edge_properties=None, edge_geometry_properties=None)[source]#
- edge_geometry(name='coordinates', edge=None, as_list=True, return_indices=False, reshape=True, ndim=None)[source]#
- edge_radii(edge=None) ndarray[source]#
Deprecated since version Use:
edge_radii_voxels()oredge_radii_um()explicitly.
- edge_radii_um(edge=None) ndarray[source]#
Edge radii in physical units (µm).
- Raises:
KeyError – If radius_units have not been propagated to edges yet.
- edge_radii_voxels(edge=None) ndarray[source]#
Edge radii in voxels (aggregated from vertex radii during reduce_graph).
- Raises:
KeyError – If radii have not been propagated to edges yet.
- export_vertex_properties(output_path: str | Path, v_props: list[str] | None = None)[source]#
Export vertex properties as a pandas DataFrame. The export format will be determined by the file extension.
- Parameters:
v_props (list of str) – The vertex properties to export.
output_path (str | Path) – The output file path.
- prune_edge_geometry()[source]#
Remove the unused edge geometries from the graph. This computes the new indices and remaps the edge geometry properties to the new indices.
- remap_edge_geometry_properties(new_indices)[source]#
- Remap all properties in self.edge_geometry_properties (edge_geometry_<>) to the new indices i.e.,
copy every edge-geometry_<> array so old ranges → new ranges
- Parameters:
new_indices (np.ndarray) – The new indices to remap the edge geometry properties to.
- set_edge_geometry(name, values, indices=None, edge=None)[source]#
Set the given edge geometry property for the graph.
Warning
edgeis not supported for'graph'edge geometry type.- Parameters:
name (str) – The name of the original vertex or edge property to set as edge geometry. As an edge geometry property, the name will be prefixed with
'edge_geometry_*'(e.g.'edge_geometry_coordinates').values (list or np.ndarray) – The values to set as edge geometry.
indices (np.ndarray or None) – How to slice the values to map to edges.
edge (gt.Edge or int, optional) – The edge to set the geometry for. If
None, the geometry is set for all edges. Not supported whenedge_geometry_typeis'graph'.
- set_edge_geometry_edge_properties(original_graph, edge_geometry_edge_properties, indices, edge_to_edge_map)[source]#
- set_edge_geometry_vertex_properties(original_graph, edge_geometry_vertex_properties, branch_indices, indices)[source]#
Set the edge geometry properties from the vertex properties of the original graph.
Note
The property is processed only if it exists in the original graph and is not already set as an edge geometry property in the current graph.
- Parameters:
original_graph
edge_geometry_vertex_properties
branch_indices
indices
Returns
- sub_graph(vertex_filter=None, edge_filter=None, view=False)[source]#
Construct a subgraph using graph-tool filtering, returning either a view or a pruned copy.
- Parameters:
vertex_filter (None or array-like or gt.PropertyMap) – Vertex selection mask or property map. Commonly a 1-D boolean numpy array of length
n_vertices.Truemeans the vertex is retained in the view.edge_filter (None or array-like or gt.PropertyMap) – Edge selection mask or property map. Commonly a 1-D boolean numpy array of length
n_edges.Truemeans the edge is retained in the view.view (bool) – If
True, return aGraphwrapping agt.GraphView(no pruning/copy). IfFalse, materialise a pruned copy viagt.Graph(gv, prune=True).
Returns
- Graph
A graph restricted by the provided filters.
Notes
Edge geometry handling:
If the resulting graph has edges and the source graph has edge geometry,
prune_edge_geometry()is called to compact edge-geometry arrays to the retained edge set.If the resulting graph has no edges, edge geometry is removed (
remove_edge_geometry()).
- sub_slice(slicing, view=False, coordinates=None, cut_edges='exclusive')[source]#
Slice the graph by an axis-aligned spatial selection, with optional boundary-edge policy.
The slice is defined by applying
slicingto per-vertex coordinates (by default the'coordinates'vertex property). This produces an initial vertex maskV0.Two boundary policies are supported via
cut_edges:'exclusive'(default): return the induced subgraph onV0(retain an edge only if both endpoints are inV0).'inclusive': retain an edge if at least one endpoint is inV0, then expand the vertex set to include both endpoints of every retained edge.
- Parameters:
slicing (tuple of slice or int) – A slicing spec accepted by
ClearMap.IO.IO.slc.unpack_slicing(slices/ints per axis).view (bool) – If
True, return a lightweightgt.GraphView-backed wrapper. IfFalse, return a pruned copy (seesub_graph()).coordinates (None or str or np.ndarray) –
Coordinate source to slice against:
None: usesself.vertex_coordinates().str: name of a vertex property to use.np.ndarray: explicit(N, ndim)coordinates array.
cut_edges (str) – Boundary edge policy:
'exclusive'or'inclusive'.
Returns
- Graph
The sliced graph (view or pruned copy). If edge geometry exists and edges are retained, geometry is compacted via
prune_edge_geometry()insub_graph().
- transform_properties(transformation, vertex_properties=None, edge_properties=None, edge_geometry_properties=None, verbose=False)[source]#
- vertex_property(name, vertex=None, as_array=True)[source]#
Warning
This risks creating a copy of the vertex property map if as_array is True.
- Parameters:
name
vertex
as_array
Returns
- vertex_radii(vertex=None) ndarray[source]#
Deprecated since version Use:
vertex_radii_voxels()orvertex_radii_units()explicitly. This method returns voxel radii and will be removed in a future version.
- vertex_radii_units(vertex=None) ndarray[source]#
Vertex radii in physical units (µm).
- Raises:
KeyError – If radius_units have not been measured yet. Call _measure_radii() with a valid spacing array first. For voxel units use
vertex_radii_voxels().
- vertex_radii_voxels(vertex=None) ndarray[source]#
Vertex radii in voxels.
- Raises:
KeyError – If radii have not been measured yet. Call _measure_radii() first. For physical units use
vertex_radii_units().
- DEFAULT_N_DIMS = 3#
- SCOPES = ('vertex', 'edge', 'graph')#
- property base#
- property directed#
- property edge_geometry_properties#
- property edge_geometry_property_names#
- property edge_geometry_type#
Type for storing edge properties
Returns
- type‘graph’ or ‘edge’
- ‘graph’Stores edge coordinates in a graph property array and
start end indices in edges.
- ‘edge’Stores the edge coordinates in variable length vectors in
each edge.
- property edge_properties#
- property edges#
- property graph_properties#
- property has_edge_coordinates#
- property has_edge_radii#
- property has_edge_radii_um: bool#
True if µm radii have been propagated to edges.
- property has_vertex_coordinates#
- property has_vertex_radii#
- property is_view#
- property n_edges#
Number of edges in the graph.
- property n_vertices#
Number of vertices in the graph.
- property ndim#
- property shape#
The shape of the space in which the graph is embedded.
Returns
- shapetuple of int
The shape of the graph space.
- property vertex_properties#
- property vertices#