Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Adjacency

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:

NameTypeDescriptionDefault
datapandas data instance or list of filesNone
matrix_type(str) type of matrix. Possible values include: [‘distance’,‘similarity’,‘directed’,‘distance_flat’, ‘similarity_flat’,‘directed_flat’]None
YPandas DataFrame of training labelsNone
labels(list) optional node labelsNone
spatial_scaleSpatialScale | None(SpatialScale, optional) spatial-scale metadata linking rows/ columns to a brain parcellation, enabling projection back into brain spaceNone

Attributes:

NameTypeDescription
YDataFrameTraining labels as a polars DataFrame (possibly empty).
data
is_emptyboolCheck if Adjacency object is empty.
is_single_matrix
issymmetric
labels
matrix_type
n_nodesReturn the number of nodes in the adjacency matrix.
shapeReturn the logical shape of the adjacency matrix.
spatial_scaleSpatialScale | None
vector_shapeReturn shape of internal vectorized representation.

Methods:

NameDescription
appendAppend data to an Adjacency instance.
bootstrapBootstrap statistics using efficient online algorithms.
cluster_summaryProvide summaries of clusters within Adjacency matrices.
copyCreate a copy of Adjacency object.
distanceCalculate distance between images within an Adjacency() instance.
distance_to_similarityConvert distance matrix to similarity matrix.
generate_permutationsGenerate permuted versions of an Adjacency instance lazily.
meanCalculate mean of Adjacency.
medianCalculate median of Adjacency.
plotCreate a heatmap of an Adjacency matrix.
plot_label_distanceCreate a violin plot of within- and between-label distances.
plot_mdsPlot multidimensional scaling.
plot_silhouetteCreate a silhouette plot.
r_to_zApply Fisher’s r-to-z transformation to each data element.
regressRun a regression on an adjacency instance.
similarityCalculate similarity between two Adjacency matrices.
social_relations_modelEstimate the social relations model from a matrix for a round-robin design.
squareformConvert adjacency data back to square form.
stats_label_distanceCalculate permutation tests on within and between label distance.
stdCalculate standard deviation of Adjacency.
sumCalculate sum of Adjacency.
thresholdThreshold an Adjacency instance.
to_brainProject per-matrix scalars back to voxel-space BrainData.
to_graphConvert a single Adjacency matrix into a NetworkX graph.
to_squareConvert adjacency back to square matrix format.
ttestCalculate ttest across samples.
writeWrite out Adjacency object to csv file.
z_to_rConvert each z score back into an r value.

Methods

append

append(data)

Append data to an Adjacency instance.

Parameters:

NameTypeDescriptionDefault
data(Adjacency) Adjacency instance to appendrequired

Returns:

NameTypeDescription
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:

NameTypeDescriptionDefault
stat(str) Statistic to bootstrap. Options: - Simple stats: ‘mean’, ‘median’, ‘std’, ‘sum’, ‘min’, ‘max’required
n_samples(int) Number of bootstrap iterations. Default: 50005000
save_boots(bool) If True, store all bootstrap samples (memory intensive). Default: FalseFalse
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 reproducibilityNone
progress_barbool(bool) If True, show a progress bar. Default False.False

Returns:

NameTypeDescription
dictDictionary 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:

NameTypeDescriptionDefault
clusters(list) list of cluster labelsNone
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:

NameTypeDescription
dictper-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:

NameTypeDescriptionDefault
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:

NameTypeDescription
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:

NameTypeDescriptionDefault
metric(str) Can only be correlation or euclidean‘correlation’
beta(float) parameter to scale exponential function (default: 1) for euclidean1

Returns:

NameTypeDescription
out(Adjacency) Adjacency object

generate_permutations

generate_permutations(n_permute, random_state = None)

Generate permuted versions of an Adjacency instance lazily.

Parameters:

NameTypeDescriptionDefault
n_permuteintnumber of permutationsrequired
random_state( int , seed )random seed for reproducibility.None

Examples:

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

Yields:

NameTypeDescription
Adjacencypermuted version of self

mean

mean(axis = 0)

Calculate mean of Adjacency.

Parameters:

NameTypeDescriptionDefault
axisCalculate mean over matrices (0) or upper triangle (1).0

Returns:

TypeDescription
float if single matrix, Adjacency if axis=0, np.array if axis=1.

median

median(axis = 0)

Calculate median of Adjacency.

Parameters:

NameTypeDescriptionDefault
axisCalculate median over matrices (0) or upper triangle (1).0

Returns:

TypeDescription
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:

NameTypeDescriptionDefault
limit(int) number of heatmaps to plot if object contains multiple adjacencies (default: 3)3
axesmatplotlib axis handleNone

plot_label_distance

plot_label_distance(labels = None, ax = None)

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

Parameters:

NameTypeDescriptionDefault
labelsarraynumpy array of labels to plotNone

Returns:

TypeDescription
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:

NameTypeDescriptionDefault
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 TrueTrue
labels(list) Can override labels stored in Adjacency ClassNone
labels_color(str) list of colors for labels, if len(1) then make all same colorNone
cmapcolormap 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
axmatplotlib axis handleNone
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:

NameTypeDescriptionDefault
labelsNumpy array of cluster/group labels (overrides stored labels).None
axMatplotlib 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
colorsOptional list of RGB triplets, one per cluster (default: seaborn ‘hls’ palette).None
figsizeFigure 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:

NameTypeDescriptionDefault
XDesign matrix can be an Adjacency or DesignMatrix instancerequired
methodtype of regression (default: ols) - only ‘ols’ is currently supported‘ols’
tail2‘two’ (two-tailed, default) or 1

Returns:

NameTypeDescription
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:

NameTypeDescriptionDefault
dataAdjacency or arrayAdjacency data, or 1-d array same size as self.datarequired
plot(bool) plot the two stacked adjacency matrices being compared. Default FalseFalse
method(str) permutation scheme ‘1d’, ‘2d’, or None‘2d’
n_permute(int) number of permutations for the p-value. Default 50005000
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_barbool(bool) If True, show a progress bar. Default False.False
projectbool(bool) If True and this Adjacency has a spatial_scale, project the per-matrix correlations back into brain space. Default False.False

Returns:

TypeDescription
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.

Xij=m+αi+βj+gij+ϵijlX_{ij} = m + \alpha_i + \beta_j + g_{ij} + \epsilon_{ijl}

where XijX_{ij} is the score for person i rating person j, mm is the group mean, αi\alpha_i is person i’s actor effect, βj\beta_j is person j’s partner effect, gijg_{ij} is the relationship effect and ϵijl\epsilon_{ijl} 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:

NameTypeDescriptionDefault
self(adjacency) can be a single matrix or many matrices for each grouprequired
summarize_results(bool) will provide a formatted summary of model resultsTrue
nan_replace(bool) will replace nan values with row and column meansTrue

Returns:

TypeDescription
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:

NameTypeDescriptionDefault
labelsarraynumpy array of labels to plotNone
n_permuteintnumber of permutations to run (default=5000)5000

Returns:

NameTypeDescription
dictdictionary of within and between group differences and p-values

std

std(axis = 0)

Calculate standard deviation of Adjacency.

Parameters:

NameTypeDescriptionDefault
axisCalculate std over matrices (0) or upper triangle (1).0

Returns:

TypeDescription
float if single matrix, Adjacency if axis=0, np.array if axis=1.

sum

sum(axis = 0)

Calculate sum of Adjacency.

Parameters:

NameTypeDescriptionDefault
axisCalculate sum over matrices (0) or upper triangle (1).0

Returns:

TypeDescription
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:

NameTypeDescriptionDefault
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
binarizeboolreturn binarized image respecting thresholds if provided, otherwise binarize on every non-zero value; default FalseFalse

Returns:

NameTypeDescription
Adjacencythresholded 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:

NameTypeDescriptionDefault
values1-D array of length len(self) — one scalar per matrix in the stack.required
fillfloatValue for voxels not covered by any provided ROI label. Default np.nan.nan

Returns:

NameTypeDescription
BrainDataSingle 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:

TypeDescription
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:

NameTypeDescriptionDefault
permutation(bool) Run ttest as permutation. Note this can be very slow.False
n_permuteNumber of permutations (used only when permutation=True). Default 5000.5000
tail2‘two’ (two-tailed, default) or 1
return_nullIf True, also return the null distribution. Default False.False
n_jobsNumber of parallel jobs. Default -1 (all cores).-1
random_stateRandom seed for reproducibility.None
progress_barboolIf True, show a progress bar. Default False.False

Returns:

NameTypeDescription
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:

NameTypeDescriptionDefault
file_namestrname of file name to writerequired
methodstrmethod to write out data [‘long’,‘square’]‘long’

z_to_r

z_to_r()

Convert each z score back into an r value.