Adjacency ¶
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 |
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 |
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 |
matrix_type |
str
|
One of |
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 |
shape |
tuple
|
Logical shape — |
vector_shape |
tuple
|
Shape of the internal vectorized storage ( |
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 |
z_to_r |
Convert each z score back into an r value. |
Attributes¶
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
¶
Return the number of nodes in the adjacency matrix.
Returns:
| Type | Description |
|---|---|
int
|
Number of nodes (n) for an (n, n) matrix. |
shape
property
¶
Return the logical shape of the adjacency matrix.
Returns:
| Type | Description |
|---|---|
tuple
|
|
Note
Use .vector_shape to get the internal vectorized representation shape.
vector_shape
property
¶
Return shape of internal vectorized representation.
Returns:
| Type | Description |
|---|---|
tuple
|
|
Note
This is the raw shape of the internal data storage.
Use .shape for the logical (n_nodes, n_nodes) shape.
Methods:¶
append ¶
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: |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If this Adjacency holds fewer than two matrices. |
Examples:
cluster_summary ¶
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'
|
scope
|
str
|
Summarize |
'within'
|
Returns:
| Type | Description |
|---|---|
dict
|
Per-cluster summaries keyed by cluster label. |
distance ¶
Calculate distance between images within an Adjacency() instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str
|
Distance metric; any metric accepted by
|
'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 |
{}
|
Returns:
| Type | Description |
|---|---|
Adjacency
|
A 2D distance matrix. |
distance_to_similarity ¶
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 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:
mean ¶
median ¶
plot ¶
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 |
{}
|
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 |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[DataFrame, ...]
|
|
plot_label_distance ¶
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 |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame | tuple[DataFrame, dict]
|
The long-format frame with
columns |
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 |
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 |
{}
|
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
|
None
|
figsize
|
tuple
|
Figure size. Default (6, 4). |
(6, 4)
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns |
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; |
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 |
None
|
vmin
|
float | tuple
|
One lower limit for both triangles,
or an |
None
|
vmax
|
float | tuple
|
One upper limit for both triangles,
or an |
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 |
{}
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axis holding both triangles. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
regress ¶
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
|
Returns:
| Type | Description |
|---|---|
dict
|
Keys |
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 |
required |
plot
|
bool
|
Plot the two stacked adjacency matrices being compared. Default False. |
False
|
method
|
str | None
|
Permutation scheme, |
'2d'
|
n_permute
|
int
|
Number of permutations for the p-value. Default 5000. |
5000
|
metric
|
str
|
|
'spearman'
|
include_diag
|
bool
|
Only applies to |
False
|
nan_policy
|
str
|
How to handle NaN values on the 1-D paths
( |
'omit'
|
tail
|
int | str
|
|
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 ¶
Estimate the social relations model from a matrix for a round-robin design.
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 ¶
stats_label_distance ¶
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 ¶
sum ¶
threshold ¶
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 |
None
|
lower
|
float | str
|
Lower cutoff. A string such as |
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 ¶
Convert a single Adjacency matrix into a NetworkX graph.
This currently works only when is_single_matrix is True.
Returns:
| Type | Description |
|---|---|
Graph | DiGraph
|
|
to_square ¶
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 |
False
|
n_permute
|
int
|
Number of permutations, used only when
|
5000
|
tail
|
int | str
|
|
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If this Adjacency holds fewer than two matrices. |
Examples:
write ¶
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 |
required |
method
|
str
|
Layout for CSV output, |
'long'
|