Alignment¶
Setup: install HyperTools (run this cell first on Colab)
[ ]:
# HyperTools setup: use 1.1 or newer; retain a current local checkout.
import importlib.util
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from pathlib import Path
try:
_hypertools_version = Version(version('hypertools'))
except PackageNotFoundError:
_hypertools_version = Version('0')
if _hypertools_version < Version('1.1.0'):
_spec = importlib.util.find_spec('hypertools')
if _spec and _spec.origin and (Path(_spec.origin).resolve().parents[1] / '.git').exists():
raise RuntimeError('Select a HyperTools 1.1 checkout/kernel before running this tutorial; the installer will not replace your checkout.')
%pip install -q "hypertools[interactive]>=1.1.0"
else:
print('Keeping HyperTools', _hypertools_version, 'in this kernel. Optional extras are loaded when requested.')
The align function projects 2 or more datasets with different coordinate systems into a common space. By default it uses the hyperalignment algorithm (Haxby et al., 2011), but also provides the Shared Response Model (SRM; Chen et al., 2015) and a plain Procrustes rotation.
Alignment can be particularly useful in exploring statistical properties and/or similarities of datasets that are not in the same coordinate system (such as fMRI data from visual areas of participants watching a movie, and the movie data itself).
Alignment algorithms use linear transformations to rotate and scale your datasets so they match as best as possible. For example, take the three datasets on the left below. Each has a similar shape (an S), but they are scaled and rotated differently. Aligning them finds the transformation that minimizes the distance between them, giving the overlapping copies on the right.

This tutorial covers the three algorithms, using align= inside hyp.plot and hyp.analyze, and reusing a fitted aligner on held-out data with return_model=True.
Import Hypertools¶
[1]:
import hypertools as hyp
import numpy as np
%matplotlib inline
What alignment does¶
Take three copies of the same trajectory, each rotated and scaled differently. Each has the same shape, but their coordinate systems disagree. Aligning them finds the rotation (and scale) that minimizes the distance between them. Below, the left panel shows the three copies as given; the right panel shows them after align='HyperAlign', drawn into a second axes with ax=. The two panels differ in align=, not in which dataset each shows, so panels= (one shared fit, one dataset per
panel) does not apply here; we use hyp.subplots (a thin wrapper over plt.subplots that pre-sets the 3-D projection) instead. The three linestyles make the aligned copies visible even though they now lie on top of one another. The trajectory is the first of the weights_avg datasets (average fMRI activity of 18 subjects listening to a story), reduced to three dimensions so the rotations are easy to see.
[2]:
base = hyp.reduce(hyp.load('weights_avg')[0], ndims=3)
rng = np.random.default_rng(1)
copies = []
for scale in (1.0, 0.5, 2.0):
rotation, _ = np.linalg.qr(rng.standard_normal((3, 3))) # a random 3-D rotation
copies.append(scale * base @ rotation)
fig, axes = hyp.subplots(1, 2, size=[11, 4.5], backend='matplotlib')
# backend='matplotlib' on the grid and on each call: fig.tight_layout() is matplotlib's,
# and on Colab the default backend would be plotly
hyp.plot(copies, ['-', '--', ':'], reduce=None, ax=axes[0], linewidth=2, backend='matplotlib',
names=['copy 1', 'copy 2', 'copy 3'], title='three rotated, scaled copies', show=False)
hyp.plot(copies, ['-', '--', ':'], reduce=None, ax=axes[1], linewidth=2, align='HyperAlign',
backend='matplotlib',
names=['copy 1', 'copy 2', 'copy 3'], title='after hyperalignment', show=False)
fig.tight_layout()
Load your data¶
Next, we’ll load one of the sample datasets. This dataset is a list of 36 numpy arrays, each containing brain activity (fMRI) from one subject listening to the same story, fit using Hierarchical Topographic Factor Analysis (HTFA) with 100 nodes. Each array has 300 rows (timepoints) and 100 columns (fMRI components).
See the full dataset or the HTFA article for more info on the data and HTFA, respectively.
[3]:
data = hyp.load('weights')
print(f'{len(data)} subjects, each {data[0].shape[0]} timepoints x {data[0].shape[1]} components')
36 subjects, each 300 timepoints x 100 components
Visualize unaligned data¶
First, we’ll average the 36 subjects into two groups of 18 subjects each, and see how the first hundred timepoints of the two group averages look when plotted together.
hyp.plot reduces the 100 components down to the top 3 principal components before drawing, so each trajectory below is a 3D summary of one group average.
[4]:
def group_averages(subjects):
"""Average the first and second halves of a list of subjects."""
half = len(subjects) // 2
return [np.mean(subjects[:half], 0), np.mean(subjects[half:], 0)]
group1, group2 = group_averages(data)
fig = hyp.plot([group1[:100], group2[:100]], names=['group 1', 'group 2'],
title='unaligned group averages')
Aligning data with Hyperalignment¶
Next, we can align the two datasets (using hyperalignment) and visualize the aligned data. Note that the two datasets are now much more similar to each other.
hyp.align(data) defaults to model='HyperAlign', which iteratively Procrustes-rotates every subject onto a common template and returns arrays of the same shape (300 x 100) in that shared space. Note that we align all 36 subjects and only then average them into two groups: the rotations are estimated per subject, which is exactly what averaging the unaligned subjects cannot do.
[5]:
aligned = hyp.align(data)
group1, group2 = group_averages(aligned)
fig = hyp.plot([group1[:100], group2[:100]], names=['group 1', 'group 2'],
title='hyperaligned group averages')
Procrustes: one rotation onto a reference¶
model='Procrustes' is the building block the other two are made of: every dataset is rotated (and scaled) onto one reference dataset in a single step, with no iteration and no shared template. index picks the reference (default 0). It is the right choice when one dataset is the reference – a canonical template, or the coordinates you want everything expressed in. Here we rotate subject 2 onto subject 1 and compare their first hundred timepoints; each panel already overlays two
datasets (subject 1 and subject 2) rather than showing one dataset per panel, so we keep the explicit-axes form via hyp.subplots rather than panels=.
[7]:
pair = [data[0], data[1]]
pair_aligned = hyp.align(pair, model='Procrustes', index=0)
fig, axes = hyp.subplots(1, 2, size=[11, 4.5], backend='matplotlib')
hyp.plot([d[:100] for d in pair], ax=axes[0], names=['subject 1', 'subject 2'], backend='matplotlib',
title='two subjects, unaligned', show=False)
hyp.plot([d[:100] for d in pair_aligned], ax=axes[1], names=['subject 1', 'subject 2'], backend='matplotlib',
title="Procrustes: subject 2 rotated onto subject 1", show=False)
fig.tight_layout()
Alignment inside plot and analyze¶
You rarely need to call hyp.align yourself: hyp.plot and hyp.analyze both accept the same align= argument (a model name, or a dict with model and kwargs), applied after normalization and reduction. Below hyp.plot hyperaligns the 36 subjects’ first hundred timepoints and draws them all; the per-dataset fade (alpha) keeps the cloud readable.
[8]:
fig = hyp.plot([d[:100] for d in data], align='HyperAlign', alpha=0.4, linewidth=1,
title='36 subjects, hyperaligned inside hyp.plot')
hyp.analyze runs the same pipeline and returns the transformed arrays instead of a figure – here normalized, reduced to 3 dimensions, then SRM-aligned – which we hand straight back to hyp.plot(..., reduce=None). The analyze tutorial covers the pipeline in full.
[9]:
analyzed = hyp.analyze(data, normalize='within', reduce='PCA', ndims=3,
align={'model': 'SRM', 'kwargs': {'features': 3}})
print('analyze returned', len(analyzed), 'arrays of shape', analyzed[0].shape)
group1, group2 = group_averages(analyzed)
fig = hyp.plot([group1[:100], group2[:100]], reduce=None, names=['group 1', 'group 2'],
title='normalize -> reduce -> SRM via hyp.analyze')
analyze returned 36 arrays of shape (300, 3)
Reusing a fitted aligner on held-out data¶
return_model=True also returns the fitted aligner. A fitted aligner is a one-way street: it stores one rotation per subject, so it can transform new timepoints from those same subjects (the same number of datasets, each with the same number of columns) but not a subject it never saw – a new subject needs its own fit. That makes the natural held-out set a block of timepoints.
Below we fit hyperalignment on the first 150 timepoints of the first 18 subjects, then pass the fitted aligner back as model= to align the last 150 timepoints, which it has never seen – no refitting, the stored rotations are applied as-is. The two panels compare the held-out group averages unaligned and aligned; each panel again overlays two datasets (group 1 and group 2), so we keep the explicit-axes form via hyp.subplots.
[10]:
subjects = data[:18]
fit_block = [s[:150] for s in subjects] # timepoints the aligner is fit on
held_out = [s[150:] for s in subjects] # timepoints it never sees during fitting
_, aligner = hyp.align(fit_block, return_model=True)
print(f'fitted: {type(aligner).__name__}, is_fitted={aligner.is_fitted}')
held_out_aligned = hyp.align(held_out, model=aligner) # reuse: transform only, no refit
fig, axes = hyp.subplots(1, 2, size=[11, 4.5], backend='matplotlib')
hyp.plot(group_averages(held_out), ax=axes[0], names=['group 1', 'group 2'], backend='matplotlib',
title='held-out timepoints, unaligned', show=False)
hyp.plot(group_averages(held_out_aligned), ax=axes[1], names=['group 1', 'group 2'], backend='matplotlib',
title='held-out timepoints, fitted aligner reused', show=False)
fig.tight_layout()
fitted: HyperAlign, is_fitted=True
Passing a dataset count the aligner was not fit on raises a ValueError naming the fit-time shape, so a mistaken reuse fails loudly rather than silently mis-rotating the data.
[11]:
try:
hyp.align([data[20][150:]], model=aligner)
except ValueError as e:
fitted, got = str(e).split('; ') # the fit-time shape, then what was passed
print('ValueError:', fitted.split(' with ')[0] + ';', got.split(' (fit-time')[0])
ValueError: aligner was fit on 18 dataset(s); got 1 dataset(s) with [100] column(s)
Next steps¶
The analyze tutorial chains
manip,normalize,reduce,alignandclusterin one call.The
plot_aligngallery example is the one-figure version of this tutorial.The market-sectors tutorial hyperaligns its sector trajectories with
hyp.alignbefore animating them.