Skip to content

Adjacency

Adjacency(
    data=None, *, Y=None, matrix_type=None, labels=None
)

Represent adjacency matrices in vectorized form.

Store distance/similarity matrices as strict upper triangles and directed matrices as full row-major vectors. Symmetric reconstruction fills the diagonal from the matrix type — 0 for a distance, 1 for a similarity — and input diagonals are discarded. Flat rectangular stacks require an explicit *_flat matrix type. A list or 2-D flat array retains stack rank, including one matrix. A zero-length symmetric vector represents one node. Construction and result methods return independently owned mutable state.

Parameters:

Name Type Description Default
data Adjacency | ndarray | DataFrame | DataFrame | str | Path | list

A square matrix, a flattened vector, a .csv/.h5 path, or a list of matrices/Adjacency instances/.csv paths to stack.

None
Y DataFrame | DataFrame

Matrix metadata, one row per matrix. None inherits metadata during copy construction.

None
matrix_type str

Type of matrix. One of 'distance', 'similarity', 'directed', 'distance_flat', 'similarity_flat', 'directed_flat'. For copy construction, this confirms the existing kind without reinterpreting it.

None
labels list

Shared node labels, or a nested matrix-by-node label grid for a stack. None inherits labels during copy construction.

None

Attributes:

Name Type Description
data ndarray

Vectorized matrix values. Shape (vector_length,) for a single matrix or (n_matrices, vector_length) for a stack; symmetric matrices store only the upper triangle without the diagonal.

matrix_type str

One of 'distance', 'similarity', 'directed', or 'empty' (the '_flat' input variants are normalized to their base type).

is_single_matrix bool

True for single storage; a one-row stack is False.

issymmetric bool

True for distance/similarity matrices, False for directed.

labels list

Node labels (empty list when none were given).

Y DataFrame

Training labels as a polars DataFrame (possibly empty).

is_empty bool

True if the instance holds no matrices.

n_nodes int

Number of nodes n for an (n, n) matrix.

shape tuple

Logical shape — (n_nodes, n_nodes) for a single matrix, (n_matrices, n_nodes, n_nodes) for a stack, including typed empty stacks; (0, 0) for an untyped empty constructor.

vector_shape tuple

Shape of the internal vectorized storage (data.shape).

Methods:

Name Description
append

Append data to an Adjacency instance.

bootstrap

Bootstrap an aggregate statistic across a stack of matrices.

cluster_summary

Provide summaries of clusters within Adjacency matrices.

copy

Return an independently owned copy, preserving internal aliases and cycles.

distance

Calculate distance between images within an Adjacency() instance.

distance_to_similarity

Convert distance matrix to similarity matrix.

generate_permutations

Generate permuted versions of an Adjacency instance lazily.

mean

Calculate mean of Adjacency.

median

Calculate median of Adjacency.

plot

Create a heatmap of an Adjacency matrix.

plot_between_label_distance

Create a heatmap of the average distance between every pair of labels.

plot_label_distance

Create a violin plot of within- and between-label distances.

plot_mds

Plot multidimensional scaling.

plot_silhouette

Create a silhouette plot.

plot_stacked

Draw this matrix and another as complementary triangles of one square.

r_to_z

Apply Fisher's r-to-z transformation to each data element.

regress

Run a regression on an adjacency instance.

similarity

Calculate similarity between two Adjacency matrices.

social_relations_model

Estimate the social relations model from a matrix for a round-robin design.

squareform

Convert adjacency data back to square form.

stats_label_distance

Calculate permutation tests on within and between label distance.

std

Calculate standard deviation of Adjacency.

sum

Calculate sum of Adjacency.

threshold

Threshold an Adjacency instance.

to_graph

Convert a single Adjacency matrix into a NetworkX graph.

to_square

Convert adjacency back to square matrix format.

ttest

Run a one-sample t-test across stacked matrices.

write

Write the Adjacency to a .csv or .h5 file.

z_to_r

Convert each z score back into an r value.

Attributes

Y property writable

Y: DataFrame

Training labels as a polars DataFrame (possibly empty).

is_empty property

is_empty: bool

Check if Adjacency object is empty.

Returns:

Type Description
bool

True if the adjacency matrix is empty, False otherwise.

n_nodes property

n_nodes

Return the number of nodes in the adjacency matrix.

Returns:

Type Description
int

Number of nodes (n) for an (n, n) matrix.

shape property

shape

Return the logical shape of the adjacency matrix.

Returns:

Type Description
tuple

(n_nodes, n_nodes) for a single matrix, (n_matrices, n_nodes, n_nodes) for stacked matrices, including typed empty stacks; (0, 0) for an untyped empty constructor.

Note

Use .vector_shape to get the internal vectorized representation shape.

vector_shape property

vector_shape

Return shape of internal vectorized representation.

Returns:

Type Description
tuple

(vector_length,) for a single matrix, (n_matrices, vector_length) for stacked matrices.

Note

This is the raw shape of the internal data storage. Use .shape for the logical (n_nodes, n_nodes) shape.

Methods:

append

append(data)

Append data to an Adjacency instance.

Parameters:

Name Type Description Default
data Adjacency

Adjacency instance to append.

required

Returns:

Type Description
Adjacency

New appended Adjacency instance.

bootstrap

bootstrap(
    statistic,
    *,
    n_samples=5000,
    confidence_level=0.95,
    return_samples=False,
    n_jobs=-1,
    random_state=None,
    progress_bar: bool = False,
)

Bootstrap an aggregate statistic across a stack of matrices.

Resamples matrices with replacement and aggregates the replicates as they complete, so what the run holds is the retained tail — about (1 - confidence_level) of the replicates per edge — plus one dispatch window, rather than all n_samples matrices.

Parameters:

Name Type Description Default
statistic str

Statistic to bootstrap: 'mean', 'median', 'std', 'sum', 'min', or 'max' — each the corresponding NumPy reduction over matrices, with 'std' at ddof=0.

required
n_samples int

Number of bootstrap replicates, at least two. Default 5000.

5000
confidence_level float

Confidence level of the reported interval, strictly between zero and one. Default 0.95. The bounds are the central percentile interval, elementwise marginal per edge.

0.95
return_samples bool

Retain and return every replicate. Default False.

False
n_jobs int

CPU worker ceiling. -1 (default) means all cores.

-1
random_state int | None

Random seed for reproducibility.

None
progress_bar bool

If True, show a progress bar. Default False.

False

Returns:

Type Description
BootstrapResult

estimate (the statistic on the unresampled stack), standard_error, ci_lower and ci_upper as single-matrix Adjacency objects, plus samples as a NumPy array with the bootstrap axis first when return_samples=True.

Raises:

Type Description
ValueError

If this Adjacency holds fewer than two matrices.

Examples:

boot = adj.bootstrap("mean", n_samples=1000)
boot.estimate  # → Adjacency

cluster_summary

cluster_summary(
    *, clusters=None, summary="mean", scope="within"
)

Provide summaries of clusters within Adjacency matrices.

Computes mean/median of within and between cluster values. Requires a list of cluster ids indicating the row/column of each cluster.

Parameters:

Name Type Description Default
clusters list

Cluster label for each row/column.

None
summary str | None

Central tendency, 'mean' or 'median'. If None, return all values instead of a summary.

'mean'
scope str

Summarize 'within' cluster or 'between' clusters.

'within'

Returns:

Type Description
dict

Per-cluster summaries keyed by cluster label.

copy

copy()

Return an independently owned copy, preserving internal aliases and cycles.

distance

distance(
    metric="correlation", *, include_diag=False, **kwargs
)

Calculate distance between images within an Adjacency() instance.

Parameters:

Name Type Description Default
metric str

Distance metric; any metric accepted by sklearn.metrics.pairwise_distances (scikit-learn or scipy).

'correlation'
include_diag bool

Whether to include the main diagonal when computing distances between adjacency matrices. Only applies to symmetric matrices. Default False (consistent with how symmetric matrices are stored without the diagonal).

False
**kwargs dict

Forwarded to sklearn.metrics.pairwise_distances.

{}

Returns:

Type Description
Adjacency

A 2D distance matrix.

distance_to_similarity

distance_to_similarity(metric='correlation', beta=1)

Convert distance matrix to similarity matrix.

Currently only implemented for the 'correlation' and 'euclidean' metrics.

Parameters:

Name Type Description Default
metric str

Either 'correlation' or 'euclidean'.

'correlation'
beta float

Scale parameter of the exponential used for 'euclidean' (default: 1).

1

Returns:

Type Description
Adjacency

The converted similarity matrix.

generate_permutations

generate_permutations(n_permute, random_state=None)

Generate permuted versions of an Adjacency instance lazily.

Parameters:

Name Type Description Default
n_permute int

Number of permutations.

required
random_state int | RandomState

Random seed for reproducibility.

None

Yields:

Type Description
Adjacency

Permuted version of self.

Examples:

for perm in adj.generate_permutations(1000):
    out = neural_distance_mat.similarity(perm)

mean

mean(axis=0)

Calculate mean of Adjacency.

Parameters:

Name Type Description Default
axis int

Calculate mean over matrices (0) or upper triangle (1).

0

Returns:

Type Description
float | Adjacency | ndarray

A float for a single matrix; an Adjacency when axis=0; an array when axis=1.

median

median(axis=0)

Calculate median of Adjacency.

Parameters:

Name Type Description Default
axis int

Calculate median over matrices (0) or upper triangle (1).

0

Returns:

Type Description
float | Adjacency | ndarray

A float for a single matrix; an Adjacency when axis=0; an array when axis=1.

plot

plot(*, limit=3, ax=None, **kwargs)

Create a heatmap of an Adjacency matrix.

Matrices whose off-diagonal values cross zero are drawn on "RdBu_r", centered at 0 with symmetric limits; one-signed matrices keep seaborn's sequential default. cmap, center, vmin and vmax override this.

Parameters:

Name Type Description Default
limit int

Number of heatmaps to plot if the object contains multiple matrices. Default 3.

3
ax Axes

Axis to draw on (single matrix only).

None
**kwargs dict

Forwarded to seaborn.heatmap.

{}

plot_between_label_distance

plot_between_label_distance(
    *,
    labels=None,
    ax=None,
    permutation_test=True,
    n_permute=5000,
    **kwargs,
)

Create a heatmap of the average distance between every pair of labels.

Parameters:

Name Type Description Default
labels ndarray

Group label per node; defaults to the stored labels.

None
ax Axes

Axis to draw on.

None
permutation_test bool

Also compute the mean-difference and p-value matrices from a two-sample permutation test comparing each group's within-label distances against its distances to each other group. Default True.

True
n_permute int

Number of permutations for the test. Default 5000.

5000
**kwargs dict

Forwarded to seaborn.heatmap.

{}

Returns:

Type Description
tuple[DataFrame, ...]

(long_df, within_mean_df) without the permutation test, or (long_df, within_mean_df, mean_diff_df, p_df) with it. long_df holds every pairwise distance with its Group and Comparison labels; the others are long-format label-pair frames.

plot_label_distance

plot_label_distance(
    labels=None,
    ax=None,
    *,
    permutation_test=False,
    n_permute=5000,
    **kwargs,
)

Create a violin plot of within- and between-label distances.

Parameters:

Name Type Description Default
labels ndarray

Group label per node; defaults to the stored labels.

None
ax Axes

Axis to draw on.

None
permutation_test bool

Run a two-sample permutation test of within against between distance for each group. Default False.

False
n_permute int

Number of permutations for the test. Default 5000.

5000
**kwargs dict

Forwarded to seaborn.violinplot, plus fontsize for the axis label and title (default 18).

{}

Returns:

Type Description
DataFrame | tuple[DataFrame, dict]

The long-format frame with columns Distance, Type, Group, or (long_df, stats) when permutation_test=True, where stats maps each group label to its permutation-test result.

plot_mds

plot_mds(
    *,
    n_components=2,
    metric_mds=True,
    labels=None,
    labels_color=None,
    cmap=None,
    view=(30, 20),
    figsize=None,
    ax=None,
    n_jobs=-1,
    **kwargs,
)

Plot multidimensional scaling.

Parameters:

Name Type Description Default
n_components int

Number of dimensions to project (2 or 3).

2
metric_mds bool

Perform metric (True) or non-metric (False) scaling. Default True.

True
labels list

Overrides the labels stored on the instance.

None
labels_color list

One color per label.

None
cmap Colormap

Colormap. Default plt.cm.hot_r.

None
view tuple

Elevation/azimuth for a 3-D plot. Default (30, 20).

(30, 20)
figsize list

Figure size. Default [12, 8].

None
ax Axes

Axis to draw on.

None
n_jobs int

Number of parallel jobs.

-1
**kwargs dict

Forwarded to sklearn.manifold.MDS.

{}

plot_silhouette

plot_silhouette(
    *,
    labels=None,
    ax=None,
    permutation_test=True,
    n_permute=5000,
    colors=None,
    figsize=(6, 4),
)

Create a silhouette plot.

Parameters:

Name Type Description Default
labels ndarray

Cluster/group label per node (overrides stored labels).

None
ax Axes

Axis to draw on.

None
permutation_test bool

Whether to run a permutation test. Default True.

True
n_permute int

Number of permutations for the test. Default 5000.

5000
colors list

RGB triplets, one per cluster. Default: seaborn 'hls' palette.

None
figsize tuple

Figure size. Default (6, 4).

(6, 4)

Returns:

Type Description
DataFrame

Columns label and mean_silhouette, plus p when permutation_test=True.

plot_stacked

plot_stacked(
    data,
    *,
    labels=None,
    upper_title=None,
    lower_title=None,
    cmap=None,
    vmin=None,
    vmax=None,
    colorbar=True,
    ax=None,
    **kwargs,
)

Draw this matrix and another as complementary triangles of one square.

This matrix fills the upper-right triangle and data the lower-left, with the diagonal hidden in both so a one-cell white gap runs between them — the intersubject RSA figure that compares a neural similarity structure against a behavioural one. Each triangle keeps its own colormap and limits, so the two matrices need not share units: signed matrices are anchored at zero on "RdBu_r" like plot, one-signed ones keep seaborn's sequential default.

Parameters:

Name Type Description Default
data Adjacency

Single matrix over the same nodes, drawn in the lower triangle.

required
labels list

Node tick labels. Defaults to the stored labels, or no ticks when there are none; False suppresses them.

None
upper_title str

Title drawn above the square.

None
lower_title str

Title drawn below the square.

None
cmap str | Colormap | tuple

One colormap for both triangles, or an (upper, lower) tuple.

None
vmin float | tuple

One lower limit for both triangles, or an (upper, lower) tuple.

None
vmax float | tuple

One upper limit for both triangles, or an (upper, lower) tuple.

None
colorbar bool

Draw colorbars. One bar when both triangles share a colormap and limits, two when they do not. Default True.

True
ax Axes

Axis to draw on.

None
**kwargs dict

Forwarded to seaborn.heatmap for both triangles.

{}

Returns:

Type Description
Axes

The axis holding both triangles.

Raises:

Type Description
ValueError

If data is not an Adjacency, either object holds more than one matrix, or the two cover different numbers of nodes.

Examples:

brain_rdm.plot_stacked(
    behavior_rdm,
    upper_title="PCC ROI similarity",
    lower_title="Self-control similarity",
)

r_to_z

r_to_z()

Apply Fisher's r-to-z transformation to each data element.

regress

regress(X, *, tail=2)

Run a regression on an adjacency instance.

Pass an Adjacency as X to decompose this matrix with other matrices, or a DesignMatrix to regress each cell across a stack of matrices.

Parameters:

Name Type Description Default
X Adjacency | DesignMatrix

Design matrix.

required
tail int | str

2/'two' (two-tailed, default) or 1/'one' (one-tailed: beta > 0; negate a regressor for the other direction).

2

Returns:

Type Description
dict

Keys beta, sigma (coefficient standard error), t, p, df, and residual. With DesignMatrix predictors, coefficient fields are Adjacency maps per predictor (single for one predictor). With Adjacency predictors, a single response is required and coefficient fields are native predictor arrays or scalars. df is a scalar; residual retains response shape and metadata.

similarity

similarity(
    data,
    *,
    plot=False,
    method="2d",
    n_permute=5000,
    metric="spearman",
    include_diag=False,
    nan_policy="omit",
    tail=2,
    return_null=False,
    n_jobs=-1,
    random_state=None,
    progress_bar: bool = False,
)

Calculate similarity between two Adjacency matrices.

The default uses Spearman correlation and a permutation test.

Parameters:

Name Type Description Default
data Adjacency | ndarray

Adjacency to compare against, or a 1-D array the same size as self.data, read as the same kind of matrix as this one.

required
plot bool

Plot the two stacked adjacency matrices being compared. Default False.

False
method str | None

Permutation scheme, '1d', '2d', or None (no permutation test).

'2d'
n_permute int

Number of permutations for the p-value. Default 5000.

5000
metric str

'spearman', 'pearson', or 'kendall'.

'spearman'
include_diag bool

Only applies to 'directed' matrices with method=None or method='1d'. Default False (self-similarity is uninformative). Symmetric matrices never store the diagonal, so this flag is a no-op for them.

False
nan_policy str

How to handle NaN values on the 1-D paths (method='1d' or method=None): 'omit' removes NaN pairwise before computing the correlation (default), 'propagate' lets NaN flow through, 'raise' errors if any NaN is present. method='2d' raises on any NaN whatever the policy.

'omit'
tail int | str

2/'two' (two-tailed, default) or 1/'one' (one-tailed, positive direction).

2
return_null bool

If True, also return the null distribution. Default False.

False
n_jobs int

Number of parallel jobs. Default -1 (all cores).

-1
random_state int

Random seed for reproducibility.

None
progress_bar bool

If True, show a progress bar. Default False.

False

Returns:

Type Description
dict | list[dict]

A correlation result dict with keys 'correlation' and 'p' for a single matrix, or a list of these dicts for a stack.

Note

metric and method are easy to mix up. metric is the correlation used to compare the two matrices. method is the permutation scheme: '2d' shuffles rows and columns together (the Mantel test, the right null for a symmetric RDM), '1d' shuffles the vectorized entries, and None skips the test entirely.

social_relations_model

social_relations_model(
    summarize_results=True, nan_replace=True
)

Estimate the social relations model from a matrix for a round-robin design.

\[X_{ij} = m + \alpha_i + \beta_j + g_{ij} + \epsilon_{ijl}\]

where \(X_{ij}\) is the score for person i rating person j, \(m\) is the group mean, \(\alpha_i\) is person i's actor effect, \(\beta_j\) is person j's partner effect, \(g_{ij}\) is the relationship effect and \(\epsilon_{ijl}\) is the error in measure l for actor i and partner j.

This model is primarily concerned with partitioning the variance of the various effects. The implementation follows Chapter 8 of Kenny, Kashy, & Cook (2006) and the tests replicate the book's examples. Actor scores are rows (lower triangle) and partner scores are columns (upper triangle). The minimal sample size to estimate these effects is 4.

Model assumptions: social interactions are exclusively dyadic; people are randomly sampled from the population; there are no order effects; the effects combine additively and relationships are linear.

Parameters:

Name Type Description Default
summarize_results bool

If True, print a formatted summary of model results.

True
nan_replace bool

If True, replace NaN values with row and column means.

True

Returns:

Type Description
Series | DataFrame

All of the effects estimated using SRM, as a Series (single matrix) or DataFrame (one row per matrix).

References

Kenny, D. A., Kashy, D. A., & Cook, W. L. (2006). Dyadic data analysis. Guilford Press.

squareform

squareform()

Convert adjacency data back to square form.

Returns:

Type Description
ndarray | list[ndarray]

Detached square matrix, or a list of detached matrices for a stack. A symmetric diagonal is filled from the matrix type: 0 for a distance, 1 for a similarity.

stats_label_distance

stats_label_distance(
    *, labels=None, n_permute=5000, n_jobs=-1
)

Calculate permutation tests on within and between label distance.

Parameters:

Name Type Description Default
labels ndarray

Group label per node; defaults to the stored labels.

None
n_permute int

Number of permutations to run. Default 5000.

5000
n_jobs int

Number of parallel jobs. Default -1 (all cores).

-1

Returns:

Type Description
dict

Per-group within-vs-between distance differences and p-values, keyed by group label.

std

std(axis=0)

Calculate standard deviation of Adjacency.

Parameters:

Name Type Description Default
axis int

Calculate std over matrices (0) or upper triangle (1).

0

Returns:

Type Description
float | Adjacency | ndarray

A float for a single matrix; an Adjacency when axis=0; an array when axis=1.

sum

sum(axis=0)

Calculate sum of Adjacency.

Parameters:

Name Type Description Default
axis int

Calculate sum over matrices (0) or upper triangle (1).

0

Returns:

Type Description
float | Adjacency | ndarray

A float for a single matrix; an Adjacency when axis=0; an array when axis=1.

threshold

threshold(*, upper=None, lower=None, binarize=False)

Threshold an Adjacency instance.

Provide upper and lower values or percentages to perform two-sided thresholding. Binarize will return a mask image respecting thresholds if provided, otherwise respecting every non-zero value.

Parameters:

Name Type Description Default
upper float | str

Upper cutoff. A string such as '95%' is interpreted as a percentile; None for one-sided thresholding.

None
lower float | str

Lower cutoff. A string such as '5%' is interpreted as a percentile; None for one-sided thresholding.

None
binarize bool

Return a binarized matrix respecting the thresholds if provided, otherwise binarize on every non-zero value. Default False.

False

Returns:

Type Description
Adjacency

Thresholded Adjacency instance.

to_graph

to_graph()

Convert a single Adjacency matrix into a NetworkX graph.

This currently works only when is_single_matrix is True.

Returns:

Type Description
Graph | DiGraph

DiGraph for directed matrices, Graph otherwise; nodes are relabeled with labels when set.

to_square

to_square()

Convert adjacency back to square matrix format.

This is an alias for squareform.

Returns:

Type Description
ndarray | list[ndarray]

Square matrix representation, or a list of them if this object contains multiple adjacency matrices.

ttest

ttest(
    *,
    popmean=0.0,
    permutation=False,
    n_permute=5000,
    tail=2,
    return_null=False,
    n_jobs=-1,
    random_state=None,
    progress_bar: bool = False,
)

Run a one-sample t-test across stacked matrices.

Tests every stored edge against popmean across the matrices in the stack.

Parameters:

Name Type Description Default
popmean float

Population mean to test against. Default 0.0.

0.0
permutation bool

If True, take p from a sign-flip permutation test on matrices - popmean. The reported t stays the observed parametric statistic. Default False.

False
n_permute int

Number of permutations, used only when permutation=True. Default 5000.

5000
tail int | str

2/'two' (two-tailed, default) or 1/'one' (one-tailed: mean > popmean). Applies to both paths.

2
return_null bool

If True, also return the permutation null. Has no effect on the parametric path, which computes no null. Default False.

False
n_jobs int

Number of parallel jobs. Default -1 (all cores).

-1
random_state int

Random seed for reproducibility.

None
progress_bar bool

If True, show a progress bar. Default False.

False

Returns:

Type Description
dict

'mean', 't', 'z' and 'p' as independent single-matrix Adjacency results that retain the node count, storage kind (including directed) and shared node labels, with matrix metadata cleared. 'mean' is the edgewise mean minus popmean; 't' is the observed one-sample t-statistic on both paths; 'p' is parametric, or the empirical sign-flip p-value when permutation=True; 'z' is the tail-aware normal score of p. With permutation=True and return_null=True the dict also holds 'null_dist', an owned (n_permute, n_edges) array of centered means in flat storage order and in the units of 'mean'. Maps are unthresholded. Apply a cutoff or a multiple-comparison correction afterwards.

Raises:

Type Description
ValueError

If this Adjacency holds fewer than two matrices.

Examples:

result = stacked.ttest()
result["mean"]  # effect size per edge
result["t"].squareform()  # back to a node-by-node matrix

# Threshold after testing, never inside it
import numpy as np

significant = result["t"].copy()
significant.data = np.where(result["p"].data < 0.05, result["t"].data, 0.0)

write

write(file_name, method='long')

Write the Adjacency to a .csv or .h5 file.

HDF5 is the round-trip format: values, matrix kind, node labels, and Y. CSV stores values only, so a CSV read back loses the labels, Y, and the matrix kind, and needs an explicit matrix_type wherever the flat layout is ambiguous. Square CSV output is single-matrix only.

Parameters:

Name Type Description Default
file_name str | Path

Output path; an .h5/.hdf5 suffix writes HDF5.

required
method str

Layout for CSV output, 'long' (vectorized rows) or 'square' (single matrix only).

'long'

z_to_r

z_to_r()

Convert each z score back into an r value.