connectivitytools module

class clabtoolkit.connectivitytools.Connectome(data=None, name=None, region_coords=None, region_names=None, region_index=None, region_colors=None, connectivity_type='structural', affine=None)[source]

Bases: object

A class to represent and visualize brain connectivity data.

Attributes:

namestr

Name identifier for the connectome

matrixnp.ndarray

Connectivity matrix (n_regions x n_regions)

region_coordsnp.ndarray

3D region_coords for each region (n_regions x 3)

region_colorsnp.ndarray

RGB color values for each region (n_regions x 3)

region_namesList[str]

Names/labels for each brain region

region_indexnp.ndarray

Index codes for each region

connectivity_typestr

Type of connectivity (‘structural’, ‘functional’, ‘effective’, etc.)

affinenp.ndarray

4x4 affine transformation matrix

n_regionsint

Number of brain regions

__init__(data=None, name=None, region_coords=None, region_names=None, region_index=None, region_colors=None, connectivity_type='structural', affine=None)[source]

Initialize a Connectome object.

Parameters:

datanp.ndarray, str, Path, or None

Can be: - np.ndarray: Connectivity matrix (n_regions x n_regions) - str or Path: Path to HDF5 file to load - None: Create empty Connectome

namestr, optional

Name for the connectome. If loading from file and None, uses filename stem.

region_coordsnp.ndarray, optional

3D region_coords for each region (n_regions x 3)

region_namesList[str], optional

Names/labels for each brain region

region_indexnp.ndarray, optional

Index codes for each region

region_colorsnp.ndarray or List, optional

RGB color values or hex strings for each region

connectivity_typestr, optional

Type of connectivity (default: ‘structural’)

affinenp.ndarray, optional

4x4 affine transformation matrix

Examples:

>>> # From matrix
>>> matrix = np.random.rand(10, 10)
>>> conn = Connectome(matrix)
>>> # From file
>>> conn = Connectome('/path/to/connectome.h5')
>>> # Empty connectome
>>> conn = Connectome(name='my_network')
classmethod from_h5(filename, name=None)[source]

Create a Connectome object from an HDF5 file.

Parameters:

filenamestr or Path

Path to the HDF5 file containing connectivity data

namestr, optional

Name for the connectome. If None, uses filename stem.

Returns:

Connectome : New Connectome object with loaded data

load_h5(filename)[source]

Load connectivity data from HDF5 file.

Parameters:

filenamestr or Path

Path to the HDF5 file

save_h5(filename, compression=True)[source]

Save Connectome to HDF5 file.

Parameters:

filenamestr or Path

Output HDF5 filename

compressionbool, optional

Whether to use gzip compression (default: True)

get_region_names()[source]

Get region of interest (ROI) names. If not available, generate default names.

Returns:

List[str] : List of ROI names

get_region_colors()[source]

Get region of interest (ROI) colors. If not available, generate default colors.

Returns:

np.ndarray : Array of ROI colors

get_region_coordinates()[source]

Get region of interest (ROI) coordinates.

Returns:

Optional[np.ndarray] : Array of ROI coordinates or None

set_region_coordinates(coordinates)[source]

Set 3D coordinates for brain regions.

Parameters:

coordinatesnp.ndarray

Array of shape (n_regions, 3) with x, y, z coordinates

set_region_colors(colors)[source]

Set colors for brain regions.

Parameters:

colorsnp.ndarray or List

Array of shape (n_regions, 3) with RGB values [0-1] or [0-255], or list of hex colors

set_region_names(names)[source]

Set names for brain regions.

Parameters:

namesList[str]

List of region names

get_default_region_colors()[source]

Generate default colors for regions if not available.

Returns:

np.ndarray : RGB colors for each region

get_default_region_names()[source]

Generate default region names if not available.

Returns:

List[str] : Default region names

get_density()[source]

Calculate the density of the connectivity matrix.

Returns:

float

Proportion of non-zero connections (excluding diagonal)

get_connectivity_stats()[source]

Calculate basic connectivity statistics.

Returns:

dict : Dictionary with connectivity statistics

threshold(method='value', threshold=0.0, absolute=True, binarize=False, copy=True)[source]

Threshold the connectivity matrix.

Parameters:

method{‘value’, ‘sparsity’}

Thresholding method: - ‘value’: Keep connections above threshold value - ‘sparsity’: Keep top connections to achieve target sparsity

thresholdfloat
  • For ‘value’: minimum connection strength to keep

  • For ‘sparsity’: target sparsity level (0-1), proportion of connections to keep

absolutebool, optional

Use absolute values for thresholding (default: True)

binarizebool, optional

Convert to binary matrix after thresholding (default: False)

copybool, optional

If True, return new Connectome object; if False, modify in place (default: True)

Returns:

Connectome

Thresholded Connectome object (new if copy=True, self if copy=False)

get_subnetwork(region_indices, copy=True)[source]

Extract a subnetwork with selected regions.

Parameters:

region_indicesnp.ndarray or List[int]

Indices of regions to include

copybool, optional

If True, return new Connectome object; if False, modify in place (default: True)

Returns:

Connectome

Subnetwork Connectome object

copy()[source]

Create a deep copy of the Connectome.

Returns:

Connectome

Deep copy of the Connectome

print_info()[source]

Print comprehensive information about the connectome.

plot_matrix(figsize=(12, 10), log_scale=False, show_labels=True, cmap='RdBu_r', threshold=None, threshold_mode='absolute')[source]

Plot the connectivity matrix as a heatmap.

Parameters:

figsizetuple

Figure size (width, height)

show_labelsbool

Whether to show region names on axes

cmapstr

Colormap for the heatmap

thresholdfloat, optional

Threshold value for displaying connections. Values below threshold will be set to 0.

threshold_modestr

How to apply threshold: ‘absolute’ (abs(value) > threshold) or ‘raw’ (value > threshold)

plot_circular_graph(figsize=(12, 12), threshold=None, node_size_property='strength', node_size_scale=1000, edge_width_scale=5, show_labels=True, label_distance=1.1, edge_alpha=0.6, node_alpha=0.8, edge_cmap='plasma', layout_seed=42)[source]

Plot the connectivity matrix as a circular graph.

Parameters:

figsizetuple

Figure size (width, height)

thresholdfloat, optional

Minimum connection strength to display edges

node_size_propertystr

Property to scale node sizes by: ‘strength’, ‘degree’, ‘uniform’

node_size_scalefloat

Scale factor for node sizes

edge_width_scalefloat

Scale factor for edge widths

show_labelsbool

Whether to show region labels

label_distancefloat

Distance of labels from nodes (1.0 = at node border)

edge_alphafloat

Transparency of edges (0-1)

node_alphafloat

Transparency of nodes (0-1)

edge_cmapstr

Colormap for edges based on connection strength

layout_seedint, optional

Random seed for consistent layout

visualize_3d(connectivity_threshold=0.1, node_size_scale=1.0, edge_width_scale=1.0, show_edges=True, show_labels=False, background_color='black', window_size=(1200, 800), node_size_property='strength', base_node_size=0.5)[source]

Create a 3D visualization of the connectome using PyVista.

Parameters:

connectivity_thresholdfloat

Minimum connection strength to display edges

node_size_scalefloat

Scale factor for node sizes

edge_width_scalefloat

Scale factor for edge widths

show_edgesbool

Whether to show connectivity edges

show_labelsbool

Whether to show region labels

background_colorstr

Background color for the plot

window_sizetuple

Window size (width, height)

node_size_propertystr

Property to scale node sizes by: - ‘strength’: Total connectivity strength (sum of absolute connections) - ‘degree’: Number of connections above threshold - ‘uniform’: All nodes same size (base_node_size) - ‘betweenness’: Betweenness centrality (requires networkx) - ‘eigenvector’: Eigenvector centrality (requires networkx)

base_node_sizefloat

Base size for nodes when using ‘uniform’ or as minimum size for other properties

Returns:

pv.Plotter : PyVista plotter object

save_visualization(filename, **kwargs)[source]

Save a 3D visualization to file.

Parameters:

filenamestr

Output filename for the visualization

**kwargsdict

Additional arguments passed to visualize_3d()

get_info()[source]

Display comprehensive information about the connectome.

Provides a formatted overview including region count, connectivity type, matrix statistics, coordinate ranges, and availability of optional data (colors, names, index). Useful for quick inspection and validation.

The method displays:
  • Basic identification (name, type, number of regions)

  • Matrix statistics (min, max, mean ± SD, density)

  • Coordinate ranges per axis (if available)

  • Availability and shape of optional attributes

Returns:

Prints formatted information to stdout.

Return type:

None

Examples

>>> conn = Connectome('/path/to/connectome.h5')
>>> conn.get_info()
╔════════════════════════════════════════════════════════════════╗
║                     CONNECTOME OVERVIEW                        ║
╠════════════════════════════════════════════════════════════════╣
║ Name: my_connectome                                            ║
║ Type: structural                                               ║
║ Regions: 84                                                    ║
╠════════════════════════════════════════════════════════════════╣
║ MATRIX STATISTICS                                              ║
║   Shape:      84 × 84                                          ║
║   Range:      [0.000, 1.000]                                   ║
║   Mean ± SD:  0.123 ± 0.045                                    ║
║   Density:    0.312                                            ║
╠════════════════════════════════════════════════════════════════╣
║ COORDINATE RANGES                                              ║
║   X:  [-72.10,  68.40]                                         ║
║   Y:  [-98.50,  76.20]                                         ║
║   Z:  [-32.10,  78.90]                                         ║
╠════════════════════════════════════════════════════════════════╣
║ OPTIONAL DATA                                                  ║
║   Region names:   ✔  (84 entries)                              ║
║   Region colors:  ✔  (84 × 3)                                  ║
║   Region index:   ✔  (84 entries)                              ║
╚════════════════════════════════════════════════════════════════╝

The connectivitytools module is currently empty and serves as a placeholder for future connectivity analysis functionality.

Key Features

  • Module is currently under development

  • Intended for brain connectivity analysis capabilities

  • Will provide structural and functional connectivity processing

  • Future integration with network analysis workflows

Main Functions

Currently no functions are implemented in this module.

Common Usage Examples

This module is currently empty. Future implementations will include connectivity matrix processing and network analysis tools.