Manipulating data with hyp.manip, and animating windows and trails¶
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.')
hyp.manip applies per-dataset manipulations – Smooth, Resample, ZScore, Normalize, and Delay (a time-delay embedding, tau=/dims=) – and runs first in the library’s canonical pipeline (manip -> normalize -> reduce -> align -> cluster). They run in native space: Smooth and Resample treat each dataset on its own, while ZScore and Normalize fit one shared set of statistics across a list. The same specs go into hyp.plot(..., manip=). The
second half of this notebook animates the manipulated data with a sliding window (animate='window', sized by focused=) and with the three trail styles.
Import packages and load the data¶
[1]:
import numpy as np
import pandas as pd
import hypertools as hyp
%matplotlib inline
subjects = hyp.load('weights_sample')
subject = subjects[0]
[s.shape for s in subjects]
[1]:
[(300, 100), (300, 100), (300, 100)]
Smooth¶
By default Smooth is a Savitzky-Golay filter along the time axis (kernel='savgol', with order the polynomial degree; kernel='gaussian' and kernel='boxcar' are the other kernels). kernel_width should be odd: an even width is bumped up by one, with a warning. It returns a DataFrame with the same shape. Below, the raw and smoothed versions of one subject are drawn in the same space.
[2]:
smoothed = hyp.manip(subject, model='Smooth', kernel_width=25)
print(type(smoothed).__name__, smoothed.shape)
fig = hyp.plot([subject, smoothed], names=['raw', 'Smooth(kernel_width=25)'], alpha=[0.35, 1.0],
title='one subject, raw and smoothed')
DataFrame (300, 100)
Resample¶
Resample interpolates each dataset to exactly n_samples rows (PCHIP along the time axis), which is how trajectories of different lengths are brought to a common length. hyp.plot(..., resample=N) is sugar for the same manipulator.
[3]:
resampled = hyp.manip(subject, model='Resample', n_samples=100)
print(subject.shape, '->', resampled.shape)
(300, 100) -> (100, 100)
ZScore and Normalize¶
ZScore gives every column zero mean and unit variance; Normalize rescales every column into [min, max] (0 to 1 by default). On a list, both fit one set of statistics across all the datasets, so a column’s mean is zero over the stacked rows, not within each dataset.
A one-dimensional array, Series, or flat numeric list is one column of observations. Direct manipulator classes, hyp.manip, and hyp.Pipeline use the same shape convention. With axis=1, ZScore and min-max Normalize scale each row across its features; a list of datasets is handled separately per dataset, including datasets with different numbers of features. These row-specific statistics cannot be reused on new observations.
[4]:
zscored = hyp.manip(subjects, model='ZScore')
normalized = hyp.manip(subject, model='Normalize')
stacked = pd.concat(zscored)
print('ZScore over the stack: mean', np.round(float(stacked.mean().mean()), 3), 'std', np.round(float(stacked.std().mean()), 3),
'| within subject 1: mean', np.round(float(zscored[0].mean().mean()), 3))
print('Normalize: min', float(normalized.min().min()), 'max', float(normalized.max().max()))
ZScore over the stack: mean 0.0 std 1.0 | within subject 1: mean -0.0
Normalize: min 0.0 max 1.0
Normalize(mode='isotropic')¶
The default mode='minmax' rescales every column on its own, so each feature gets its own offset and scale and the data’s shape is distorted on purpose. mode='isotropic' centers the whole table on its centroid (the per-column mean) and divides every column by the same scalar, the largest absolute deviation from the centroid over all entries, before mapping the result onto [min, max]. All pairwise distances are scaled by one constant, so angles and distance ratios are preserved;
the centroid lands at the midpoint of the range and at least one coordinate touches an end of it. On a list, one shared centroid and one scalar are fit across all the datasets, so every dataset is moved and rescaled identically. Below, the same subject is normalized isotropically into [-1, 1], and the ratio of two between-row distances shows the shape is unchanged.
[5]:
isotropic = hyp.manip(subject, model='Normalize', mode='isotropic', min=-1, max=1)
print('isotropic: min', np.round(float(isotropic.min().min()), 3), 'max', np.round(float(isotropic.max().max()), 3),
'| centroid at', np.round(float(isotropic.mean().mean()), 3))
def distance(a, i, j):
return float(np.linalg.norm(np.asarray(a)[i] - np.asarray(a)[j]))
# one scalar scales every distance, so this ratio is the same for any two pairs of rows
print('distance ratio, rows 0-1:', np.round(distance(isotropic, 0, 1) / distance(subject, 0, 1), 4),
'| rows 5-40:', np.round(distance(isotropic, 5, 40) / distance(subject, 5, 40), 4))
isotropic: min -0.761 max 1.0 | centroid at 0.0
distance ratio, rows 0-1: 0.2263 | rows 5-40: 0.2263
Chaining manipulations¶
A list chains its elements into a hyp.Pipeline and runs it end to end; dict specs carry each step’s keyword arguments. With return_model=True the fitted pipeline comes back, ready to .transform new data.
[6]:
chain = [{'model': 'Smooth', 'kwargs': {'kernel_width': 25}},
{'model': 'Resample', 'kwargs': {'n_samples': 150}},
'ZScore']
manipulated, pipeline = hyp.manip(subjects, model=chain, return_model=True)
print([a.shape for a in manipulated])
pipeline
[(150, 100), (150, 100), (150, 100)]
[6]:
Pipeline([smooth=Smooth(kernel_width=25), resample=Resample(axis=[0, 0, 0], n_samples=[150, 150, 150]), zscore=ZScore()])In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| steps | [('smooth', ...), ('resample', ...), ...] | |
| input_hierarchy | None |
manip= inside plot¶
The same spec – a name or the whole chain – goes into hyp.plot(..., manip=), where it runs before normalize=, reduce= and align=.
[7]:
fig = hyp.plot(subjects, manip=chain, align='HyperAlign',
names=['subject 1', 'subject 2', 'subject 3'],
title='smoothed, resampled to 150, z-scored, then aligned')
A sliding window: animate='window' with focused=¶
animate='window' shows only a moving window of each trajectory: what is inside the window is drawn opaque and everything else is hidden. focused= is the window’s length in seconds of animation time (the same unit as tail_duration); it defaults to tail_duration’s value, so passing it explicitly is what decouples the two. The clip is saved next to this notebook as manip.mp4, and its middle frame is shown in place (backend='matplotlib' keeps the returned animation a
matplotlib one on Colab, where the default backend is plotly: .draw_frame and .figure are matplotlib’s).
[8]:
anim = hyp.plot(subjects, manip='Smooth', animate='window', focused=1.5,
duration=8, frame_rate=15, save_path='manip.mp4', backend='matplotlib',
title='a 1.5-second window sliding along each smoothed trajectory', show=False)
print(f'{anim.n_frames} frames')
_ = anim.draw_frame(anim.n_frames // 2)
display(anim.figure)
# Colab serves output frames separately from kernel files; embed movie bytes.
try:
from google import colab as colab
except ImportError:
pass # Local Jupyter/Sphinx uses the relative video below.
else:
from IPython.display import Video, display
display(Video('manip.mp4', embed=True))
120 frames
Trails: chemtrails, precog and bullettime¶
With animate=True (or 'parallel'/'serial') each dataset can leave a low-opacity trail around its moving window: chemtrails=True draws the path already traversed, precog=True draws the path still to come, and bullettime=True draws both. Each accepts a per-dataset list, so the three styles can be mixed in one animation; focused= sets the opaque window’s length here too. animate='window' is bullettime minus its trail, and 'spin' and 'morph' have no moving
position for a trail to follow, so those modes ignore the trail flags with a warning. The frame below is a third of the way through.
[9]:
trails = hyp.plot(subjects, manip='Smooth', animate=True, focused=1.5,
chemtrails=[True, False, False], precog=[False, True, False], bullettime=[False, False, True],
names=['chemtrails', 'precog', 'bullettime'],
duration=8, frame_rate=15, backend='matplotlib', show=False)
_ = trails.draw_frame(trails.n_frames // 3)
trails.figure
[9]: