Adjacency¶
Adjacency(data = None, *, Y = None, matrix_type = None, labels = None, spatial_scale: SpatialScale | None = None)Represent adjacency matrices in vectorized form.
Adjacency is a class to represent Adjacency matrices as a vector rather than a 2-dimensional matrix. This makes it easier to perform data manipulation and analyses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | pandas data instance or list of files | None | |
matrix_type | (str) type of matrix. Possible values include: [‘distance’,‘similarity’,‘directed’,‘distance_flat’, ‘similarity_flat’,‘directed_flat’] | None | |
Y | Pandas DataFrame of training labels | None | |
labels | (list) optional node labels | None | |
spatial_scale | SpatialScale | None | (SpatialScale, optional) spatial-scale metadata linking rows/ columns to a brain parcellation, enabling projection back into brain space | None |
Attributes:
| Name | Type | Description |
|---|---|---|
Y | DataFrame | Training labels as a polars DataFrame (possibly empty). |
data | ||
is_empty | bool | Check if Adjacency object is empty. |
is_single_matrix | ||
issymmetric | ||
labels | ||
matrix_type | ||
n_nodes | Return the number of nodes in the adjacency matrix. | |
shape | Return the logical shape of the adjacency matrix. | |
spatial_scale | SpatialScale | None | |
vector_shape | Return shape of internal vectorized representation. |
Methods:
| Name | Description |
|---|---|
append | Append data to an Adjacency instance. |
bootstrap | Bootstrap statistics using efficient online algorithms. |
cluster_summary | Provide summaries of clusters within Adjacency matrices. |
copy | Create a copy of Adjacency object. |
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_label_distance | Create a violin plot of within- and between-label distances. |
plot_mds | Plot multidimensional scaling. |
plot_silhouette | Create a silhouette plot. |
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_brain | Project per-matrix scalars back to voxel-space BrainData. |
to_graph | Convert a single Adjacency matrix into a NetworkX graph. |
to_square | Convert adjacency back to square matrix format. |
ttest | Calculate ttest across samples. |
write | Write out Adjacency object to csv file. |
z_to_r | Convert each z score back into an r value. |
Methods¶
append¶
append(data)Append data to an Adjacency instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | (Adjacency) Adjacency instance to append | required |
Returns:
| Name | Type | Description |
|---|---|---|
out | (Adjacency) new appended Adjacency instance |
bootstrap¶
bootstrap(stat, *, n_samples = 5000, save_boots = False, percentiles = (2.5, 97.5), tail = 2, n_jobs = -1, random_state = None, progress_bar: bool = False)Bootstrap statistics using efficient online algorithms.
Uses memory-efficient bootstrap infrastructure with CPU parallelization. Supports simple aggregation statistics (mean, std, median, sum, min, max).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stat | (str) Statistic to bootstrap. Options: - Simple stats: ‘mean’, ‘median’, ‘std’, ‘sum’, ‘min’, ‘max’ | required | |
n_samples | (int) Number of bootstrap iterations. Default: 5000 | 5000 | |
save_boots | (bool) If True, store all bootstrap samples (memory intensive). Default: False | False | |
percentiles | (tuple) Percentiles for confidence intervals. Default: (2.5, 97.5) | (2.5, 97.5) | |
n_jobs | (int) Number of CPU cores for parallelization. -1 means all CPUs. | -1 | |
random_state | (int, optional) Random seed for reproducibility | None | |
progress_bar | bool | (bool) If True, show a progress bar. Default False. | False |
Returns:
| Name | Type | Description |
|---|---|---|
dict | Dictionary with keys: ‘Z’, ‘p’, ‘mean’, ‘std’, ‘ci_lower’, ‘ci_upper’ (all Adjacency objects). If save_boots=True, also includes ‘samples’. |
Examples:
>>> # Simple aggregation
>>> boot = adj.bootstrap(stat='mean', n_samples=1000)
>>> assert 'mean' in boot
>>> assert isinstance(boot['mean'], 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) list of cluster labels | None | |
summary | (str) central tendency, ‘mean’ or ‘median’. If None then return all r values | ‘mean’ | |
scope | (str) summarize ‘within’ cluster or ‘between’ clusters | ‘within’ |
Returns:
| Name | Type | Description |
|---|---|---|
dict | per-cluster summaries |
copy¶
copy()Create a copy of Adjacency object.
distance¶
distance(metric = 'correlation', include_diag = False, **kwargs)Calculate distance between images within an Adjacency() instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric | (str) type of distance metric (can use any scikit learn or scipy metric) | ‘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 diagonal). | False |
Returns:
| Name | Type | Description |
|---|---|---|
dist | (Adjacency) Outputs a 2D distance matrix. |
distance_to_similarity¶
distance_to_similarity(metric = 'correlation', beta = 1)Convert distance matrix to similarity matrix.
Note: currently only implemented for correlation and euclidean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric | (str) Can only be correlation or euclidean | ‘correlation’ | |
beta | (float) parameter to scale exponential function (default: 1) for euclidean | 1 |
Returns:
| Name | Type | Description |
|---|---|---|
out | (Adjacency) Adjacency object |
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 , seed ) | random seed for reproducibility. | None |
Examples:
>>> for perm in adj.generate_permutations(1000):
>>> out = neural_distance_mat.similarity(perm)
>>> ...Yields:
| Name | Type | Description |
|---|---|---|
Adjacency | permuted version of self |
mean¶
mean(axis = 0)Calculate mean of Adjacency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis | Calculate mean over matrices (0) or upper triangle (1). | 0 |
Returns:
| Type | Description |
|---|---|
| float if single matrix, Adjacency if axis=0, np.array if axis=1. |
median¶
median(axis = 0)Calculate median of Adjacency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis | Calculate median over matrices (0) or upper triangle (1). | 0 |
Returns:
| Type | Description |
|---|---|
| float if single matrix, Adjacency if axis=0, np.array if axis=1. |
plot¶
plot(limit = 3, axes = None, *args, **kwargs)Create a heatmap of an Adjacency matrix.
Can pass in any sns.heatmap argument
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit | (int) number of heatmaps to plot if object contains multiple adjacencies (default: 3) | 3 | |
axes | matplotlib axis handle | None |
plot_label_distance¶
plot_label_distance(labels = None, ax = None)Create a violin plot of within- and between-label distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels | array | numpy array of labels to plot | None |
Returns:
| Type | Description |
|---|---|
| None |
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 (can be 2 or 3) | 2 | |
metric_mds | (bool) Perform metric (True) or non-metric (False) dimensional scaling; default True | True | |
labels | (list) Can override labels stored in Adjacency Class | None | |
labels_color | (str) list of colors for labels, if len(1) then make all same color | None | |
cmap | colormap instance (default: plt.cm.hot_r) | None | |
view | (tuple) view for 3-Dimensional plot; default (30,20) | (30, 20) | |
figsize | (list) figure size; default [12, 8] | None | |
ax | matplotlib axis handle | None | |
n_jobs | (int) Number of parallel jobs | -1 |
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 | Numpy array of cluster/group labels (overrides stored labels). | None | |
ax | Matplotlib axis handle. | 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 | Optional list of RGB triplets, one per cluster (default: seaborn ‘hls’ palette). | None | |
figsize | Figure size tuple. Default (6, 4). | (6, 4) |
r_to_z¶
r_to_z()Apply Fisher’s r-to-z transformation to each data element.
regress¶
regress(X, method = 'ols', tail = 2)Run a regression on an adjacency instance. You can decompose an adjacency instance with another adjacency instance. You can also decompose each pixel by passing a design_matrix instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | Design matrix can be an Adjacency or DesignMatrix instance | required | |
method | type of regression (default: ols) - only ‘ols’ is currently supported | ‘ols’ | |
tail | 2 | ‘two’ (two-tailed, default) or 1 |
Returns:
| Name | Type | Description |
|---|---|---|
stats | (dict) dictionary of stats outputs. |
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, project: bool = False)Calculate similarity between two Adjacency matrices.
The default uses Spearman correlation and a permutation test.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Adjacency or array | Adjacency data, or 1-d array same size as self.data | required |
plot | (bool) plot the two stacked adjacency matrices being compared. Default False | False | |
method | (str) permutation scheme ‘1d’, ‘2d’, or None | ‘2d’ | |
n_permute | (int) number of permutations for the p-value. Default 5000 | 5000 | |
metric | (str) ‘spearman’,‘pearson’,‘kendall’ | ‘spearman’ | |
include_diag | (bool) only applies to ‘directed’ Adjacency types using 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. Options: - ‘omit’: Remove NaN values pairwise before computing correlation (default) - ‘propagate’: Allow NaN to propagate through calculations - ‘raise’: Raise an error if NaN values are present | ‘omit’ | |
tail | (int) Tail of the test (1 or 2). Default 2. | 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, optional) Random seed for reproducibility. | None | |
progress_bar | bool | (bool) If True, show a progress bar. Default False. | False |
project | bool | (bool) If True and this Adjacency has a spatial_scale, project the per-matrix correlations back into brain space. Default False. | False |
Returns:
| Type | Description |
|---|---|
dict or list or BrainData: A correlation result dict with keys ‘correlation’, ‘p’, and ‘device’ for a single matrix, a list of such dicts when this Adjacency holds multiple matrices, or a BrainData when project=True (per-matrix correlations projected via spatial_scale). |
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.
where is the score for person i rating person j, is the group mean, is person i’s actor effect, is person j’s partner effect, is the relationship effect and is the error in measure l for actor i and partner j.
This model is primarily concerned with partioning the variance of the various effects.
Code is based on implementation presented in Chapter 8 of Kenny, Kashy, & Cook (2006). Tests replicate examples presented in the book. Note, that this method assumes that actor scores are rows (lower triangle), while partner scores are columnns (upper triangle). The minimal sample size to estimate these effects is 4.
Model Assumptions
Social interactions are exclusively dyadic
People are randomly sampled from population
No order effects
The effects combine additively and relationships are linear
In the future we might update the formulas and standard errors based on Bond and Lashley, 1996
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
self | (adjacency) can be a single matrix or many matrices for each group | required | |
summarize_results | (bool) will provide a formatted summary of model results | True | |
nan_replace | (bool) will replace nan values with row and column means | True |
Returns:
| Type | Description |
|---|---|
| estimated effects: (pd.Series/pd.DataFrame) All of the effects estimated using SRM |
squareform¶
squareform()Convert adjacency data back to square form.
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 | array | numpy array of labels to plot | None |
n_permute | int | number of permutations to run (default=5000) | 5000 |
Returns:
| Name | Type | Description |
|---|---|---|
dict | dictionary of within and between group differences and p-values |
std¶
std(axis = 0)Calculate standard deviation of Adjacency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis | Calculate std over matrices (0) or upper triangle (1). | 0 |
Returns:
| Type | Description |
|---|---|
| float if single matrix, Adjacency if axis=0, np.array if axis=1. |
sum¶
sum(axis = 0)Calculate sum of Adjacency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis | Calculate sum over matrices (0) or upper triangle (1). | 0 |
Returns:
| Type | Description |
|---|---|
| float if single matrix, Adjacency if axis=0, np.array if 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 or str) Upper cutoff for thresholding. If string will interpret as percentile; can be None for one-sided thresholding. | None | |
lower | (float or str) Lower cutoff for thresholding. If string will interpret as percentile; can be None for one-sided thresholding. | None | |
binarize | bool | return binarized image respecting thresholds if provided, otherwise binarize on every non-zero value; default False | False |
Returns:
| Name | Type | Description |
|---|---|---|
Adjacency | thresholded Adjacency instance |
to_brain¶
to_brain(values, *, fill: float = np.nan)Project per-matrix scalars back to voxel-space BrainData.
Requires spatial_scale to be set (i.e. this stack came from
BrainData.distance or another spatial-scale-aware producer).
Each entry of values is painted onto the voxels assigned to its
corresponding parcel by spatial_scale.atlas /
spatial_scale.roi_labels. Voxels outside the atlas receive
fill.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values | 1-D array of length len(self) — one scalar per matrix in the stack. | required | |
fill | float | Value for voxels not covered by any provided ROI label. Default np.nan. | nan |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | Single image masked to spatial_scale.source_mask. |
Examples:
>>> rdms = brain.distance(metric='correlation',
... spatial_scale='roi', roi_mask=atlas)
>>> sims = rdms.similarity(model_rdm)
>>> brain_map = rdms.to_brain(sims)to_graph¶
to_graph()Convert a single Adjacency matrix into a NetworkX graph.
This currently works only for single_matrix.
to_square¶
to_square()Convert adjacency back to square matrix format.
This is an alias for squareform.
Returns:
| Type | Description |
|---|---|
| np.ndarray or list: Square matrix representation. Returns a list | |
| of matrices if this object contains multiple adjacency matrices. |
ttest¶
ttest(*, permutation = False, n_permute = 5000, tail = 2, return_null = False, n_jobs = -1, random_state = None, progress_bar: bool = False)Calculate ttest across samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permutation | (bool) Run ttest as permutation. Note this can be very slow. | False | |
n_permute | Number of permutations (used only when permutation=True). Default 5000. | 5000 | |
tail | 2 | ‘two’ (two-tailed, default) or 1 | |
return_null | If True, also return the null distribution. Default False. | False | |
n_jobs | Number of parallel jobs. Default -1 (all cores). | -1 | |
random_state | Random seed for reproducibility. | None | |
progress_bar | bool | If True, show a progress bar. Default False. | False |
Returns:
| Name | Type | Description |
|---|---|---|
out | (dict) contains Adjacency instances of t values (or mean if running permutation) and Adjacency instance of p values. |
write¶
write(file_name, method = 'long')Write out Adjacency object to csv file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name | str | name of file name to write | required |
method | str | method to write out data [‘long’,‘square’] | ‘long’ |
z_to_r¶
z_to_r()Convert each z score back into an r value.