SetCon / processing_setcon.py
lschiweck's picture
SetCon weights, inference and evaluation code
0107764 verified
Raw History Blame Contribute Delete
12.7 kB
"""Input preparation for SetCon: body sites, gravity canonicalization and the calibrator input.
Everything here is plain NumPy/SciPy. The file is loaded by `modeling_setcon.py` (Hugging Face remote code) and
can also be imported directly (`import processing_setcon`) by the evaluation package in this repository.
Model input contract
--------------------
A window is 10 s at 20 Hz (200 frames) on a graph of 22 body sites. Every worn site carries nine channels:
channels 0-2 specific force (m/s^2), rotated so that the estimated gravity direction points up (+y)
channels 3-5 angular velocity (rad/s), rotated by the same rotation; zero for a device without gyroscope
channels 6-8 the reference channels: the gravity direction in the segment frame, Q g_hat(t), where Q is the
setup reference of the device (see `SetConModel.estimate_reference`); zero when no reference exists
Sites without a device are all zero. A frame counts as valid when any of its channels is non-zero.
"""
from __future__ import annotations
import numpy as np
SAMPLE_RATE_HZ = 20.0
WINDOW_FRAMES = 200
# The 22 sites of the body graph. Each name is the body segment the site sits on; l_ / r_ / c_ = left, right, center.
SITE_NAMES = ("root", "l_upleg", "l_lowleg", "l_foot", "l_ball", "r_upleg", "r_lowleg", "r_foot", "r_ball",
"c_spine1", "c_spine2", "c_spine3", "c_neck", "c_head", "l_clavicle", "l_uparm", "l_lowarm", "l_wrist",
"r_clavicle", "r_uparm", "r_lowarm", "r_wrist")
SITE_INDEX = {name: i for i, name in enumerate(SITE_NAMES)}
# Parent of every site in the graph (-1 = root): left leg, right leg, spine to head, left arm, right arm.
SITE_PARENTS = (-1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 12, 11, 14, 15, 16, 11, 18, 19, 20)
# Calibrator conditioning: body part (left and right share one) and side (0 center, 1 left, 2 right) of every site.
BODY_PART_OF_SITE = (0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 10, 11, 12, 13)
SIDE_OF_SITE = (0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2)
# Gravity estimation: a complementary (Mahony) filter when a gyroscope in rad/s is present. Some datasets ship
# gyroscopes in other units; a median rate above this threshold falls back to the low-pass estimate.
MAHONY_MAX_MEDIAN_RATE = 10.0
_ANTIPODAL_COS = -1.0 + 1e-12
def unit(x):
"""Rows scaled to unit length (float64 in, float64 out)."""
return x / np.clip(np.linalg.norm(x, axis=-1, keepdims=True), 1e-9, None)
# ---------------------------------------------------------------------------------------------- gravity
def rotation_to_up(ghat):
"""Shortest rotation that turns the unit vectors ghat (..., 3) onto +y; returns (..., 3, 3) with det +1.
For ghat close to -y the rotation by pi about x is used."""
g = np.asarray(ghat, dtype=np.float64)
c = g[..., 1]
w = np.stack([-g[..., 2], np.zeros_like(c), g[..., 0]], axis=-1) # g x y
K = np.zeros(g.shape[:-1] + (3, 3))
K[..., 0, 1], K[..., 0, 2] = -w[..., 2], w[..., 1]
K[..., 1, 0], K[..., 1, 2] = w[..., 2], -w[..., 0]
K[..., 2, 0], K[..., 2, 1] = -w[..., 1], w[..., 0]
denom = np.where(c > _ANTIPODAL_COS, 1.0 + c, 1.0)
eye = np.broadcast_to(np.eye(3), K.shape)
R = eye + K + (K @ K) / denom[..., None, None]
R_pi = np.zeros_like(R)
R_pi[..., 0, 0], R_pi[..., 1, 1], R_pi[..., 2, 2] = 1.0, -1.0, -1.0
antipodal = (c <= _ANTIPODAL_COS)[..., None, None]
return np.where(antipodal, R_pi, R)
def canonicalize(acc, gyro, ghat):
"""acc, gyro, ghat (..., T, 3) -> (..., T, 9) = [R acc, R gyro, ghat], one rotation R per frame for both signals."""
n = np.linalg.norm(ghat, axis=-1, keepdims=True)
g = ghat / np.clip(n, 1e-9, None)
R = rotation_to_up(g)
acc_c = np.einsum("...ab,...b->...a", R, acc)
gyr_c = np.einsum("...ab,...b->...a", R, gyro)
return np.concatenate([acc_c, gyr_c, g], axis=-1)
def gravity_lowpass(acc, fs, cut_hz=0.3, order=2):
"""Gravity direction without a gyroscope: zero-phase Butterworth low-pass of the acceleration (time on axis -2).
Windows too short for filtfilt use their mean."""
from scipy.signal import butter, sosfiltfilt
T = acc.shape[-2]
sos = butter(order, cut_hz, btype="low", fs=fs, output="sos")
padlen = 3 * (2 * len(sos) + 1)
if T <= padlen:
g = np.broadcast_to(acc.mean(axis=-2, keepdims=True), acc.shape).copy()
else:
g = sosfiltfilt(sos, acc, axis=-2)
n = np.linalg.norm(g, axis=-1, keepdims=True)
return g / np.clip(n, 1e-9, None)
def gravity_mahony(acc, gyro, fs, kp=1.0):
"""Gravity direction with a gyroscope: complementary filter (gain kp in 1/s) that propagates the direction with
the angular velocity and pulls it towards the measured acceleration. acc in m/s^2, gyro in rad/s, (..., T, 3).
The start value is the mean acceleration direction of the first second."""
a = np.asarray(acc, dtype=np.float64)
w = np.asarray(gyro, dtype=np.float64)
T = a.shape[-2]
dt = 1.0 / fs
an = a / np.clip(np.linalg.norm(a, axis=-1, keepdims=True), 1e-9, None)
g0 = a[..., : min(T, max(3, int(fs))), :].mean(axis=-2)
g0 = g0 / np.clip(np.linalg.norm(g0, axis=-1, keepdims=True), 1e-9, None)
out = np.empty_like(a)
g = g0
out[..., 0, :] = g
for t in range(1, T):
e = np.cross(g, an[..., t, :]) # pulls g towards the measurement
g = g + dt * (-np.cross(w[..., t, :], g) + kp * np.cross(e, g)) # rotating frame: g_dot = -w x g
g = g / np.clip(np.linalg.norm(g, axis=-1, keepdims=True), 1e-9, None)
out[..., t, :] = g
return out
def estimate_gravity(acc, gyro, fs):
"""-> (ghat, method, median rate). Mahony filter when the gyroscope looks like rad/s, else the low-pass."""
median_rate = None
if gyro is not None:
median_rate = float(np.median(np.linalg.norm(gyro, axis=-1)))
if median_rate < MAHONY_MAX_MEDIAN_RATE:
return gravity_mahony(acc, gyro, fs), "mahony", median_rate
return gravity_lowpass(acc, fs), "lowpass", median_rate
def canonical_device_windows(acc, gyro, fs):
"""Raw windows of one device (N, T, 3) at their own rate -> (N, T, 9) gravity-canonical channels.
A gyroscope that fails the unit check is dropped (channels 3-5 zero), as is a missing one."""
ghat, method, _ = estimate_gravity(acc, gyro, fs)
use_gyro = gyro is not None and method == "mahony"
x9 = canonicalize(acc, gyro if use_gyro else np.zeros_like(acc), ghat)
if not use_gyro:
x9[..., 3:6] = 0.0
return x9, method
def to_model_rate(x, fs):
"""(N, T, S, 9) at fs -> (N, 200, S, 9) float32 at 20 Hz: Fourier resampling to int(T / fs * 20) frames,
gravity channels renormalized (zero where a site is absent), wrap padding to 200 frames, then cut to 200."""
from scipy.signal import resample
N, T, S, C = x.shape
flat = x.reshape(N, T, S * C)
new_len = int(T / fs * SAMPLE_RATE_HZ)
res = np.array([resample(seq, new_len) for seq in flat]).reshape(N, new_len, S, C)
g = res[..., 6:9]
n = np.linalg.norm(g, axis=-1, keepdims=True)
res[..., 6:9] = np.where(n > 0.5, g / np.clip(n, 1e-9, None), 0.0)
res = res.reshape(N, new_len, S * C)
if res.shape[1] < WINDOW_FRAMES:
res = np.pad(res, ((0, 0), (0, WINDOW_FRAMES - res.shape[1]), (0, 0)), "wrap")
return res[:, :WINDOW_FRAMES].reshape(N, WINDOW_FRAMES, S, C).astype(np.float32)
def prepare_device(acc, gyro, fs):
"""Windows of one device -> model windows (N, 200, 9) at 20 Hz with zero reference channels.
acc (N, T, 3) in m/s^2 including gravity, gyro (N, T, 3) in rad/s or None, fs the sampling rate in Hz.
Each window should cover about 10 s; shorter windows are wrap-padded, longer ones cut."""
x9, _ = canonical_device_windows(np.asarray(acc, np.float64),
None if gyro is None else np.asarray(gyro, np.float64), fs)
return to_model_rate(x9[:, :, None, :], fs)[:, :, 0, :]
def place_devices(devices, n_windows=None):
"""{site name: (N, 200, 9) windows} -> (N, 200, 22, 9) encoder input (other sites zero)."""
n = n_windows or len(next(iter(devices.values())))
x = np.zeros((n, WINDOW_FRAMES, len(SITE_NAMES), 9), np.float32)
for site, w in devices.items():
x[:, :, SITE_INDEX[site]] = w
return x
def set_reference(windows, reference):
"""Reference channels of one device: channels 6-8 := Q g_hat(t) on valid frames, 0 elsewhere.
windows (N, 200, 9) with the gravity direction in channels 6-8 as prepared; reference Q (3, 3) or None."""
out = np.array(windows, copy=True)
g = out[..., 6:9].astype(np.float64)
valid = np.abs(g).sum(-1) > 0
if reference is None:
out[..., 6:9] = 0.0
else:
out[..., 6:9] = np.where(valid[..., None], unit(g) @ np.asarray(reference).T, 0.0).astype(out.dtype)
return out
# ---------------------------------------------------------------------------------------------- calibrator input
def device_frame_signals(windows):
"""Undo the canonicalization of one site: (n, T, 9) -> acc, gyro in device axes and the unit up direction."""
g = unit(windows[..., 6:9].astype(np.float64))
R = rotation_to_up(g)
return (np.einsum("ntba,ntb->nta", R, windows[..., 0:3].astype(np.float64)),
np.einsum("ntba,ntb->nta", R, windows[..., 3:6].astype(np.float64)), g)
def calibrator_input(windows, has_gyro, force_scale, rate_scale):
"""Context windows of one device (n, T, 9) with the gravity direction in channels 6-8 -> calibrator input
(n, T, 7) float32 and the valid frames (n, T). The calibrator sees the raw signals in device axes, gravity
included, divided by one scalar each, plus a flag for a missing gyroscope."""
acc, gyr, _ = device_frame_signals(windows)
valid = np.abs(windows[..., 6:9]).sum(-1) > 0
acc = np.where(valid[..., None], acc, 0.0)
gyr = np.where(valid[..., None], gyr, 0.0)
if not has_gyro:
gyr = np.zeros_like(gyr)
flag = np.full(acc.shape[:-1] + (1,), 0.0 if has_gyro else 1.0)
return np.concatenate([acc / force_scale, gyr / rate_scale, flag], -1).astype(np.float32), valid
# ---------------------------------------------------------------------------------------------- context selection
TILT_REF_DEG = 10.0
TILT_SCORE_MIN, TILT_SCORE_MAX = float(np.log(1.0 / 10.0)), float(np.log(90.0 / 10.0))
def tilt_sigma(M, V, s):
"""Spread (radians) of the up axis of a Matrix-Fisher density F = M V diag(s) V^T, from its Gaussian
approximation on the tangent space; inputs (..., 3, 3), (..., 3, 3), (..., 3)."""
M, V, s = (np.asarray(a, np.float64) for a in (M, V, s))
lam = np.stack([s[..., 1] + s[..., 2], s[..., 0] + s[..., 2], s[..., 0] + s[..., 1]], -1)
lam = np.clip(lam, 1e-3, None)
cov = np.einsum("...ab,...b,...cb->...ac", V, 1.0 / lam, V)
up = M[..., 1, :]
along = np.einsum("...a,...ab,...b->...", up, cov, up)
tr = np.trace(cov, axis1=-2, axis2=-1)
return np.sqrt(np.clip(0.5 * (tr - along), 1e-12, None))
def tilt_score(M, V, s, logit):
"""Selection score of the calibrator output (batch of mixtures): log(sigma_up / 10 deg) of the heaviest
component, clipped to [log 0.1, log 9]. Smaller is more certain."""
c = np.asarray(logit).argmax(-1)
i = np.arange(len(c))
sig = tilt_sigma(np.asarray(M)[i, c], np.asarray(V)[i, c], np.asarray(s)[i, c])
return np.clip(np.log(sig) + np.log(180.0 / np.pi / TILT_REF_DEG), TILT_SCORE_MIN, TILT_SCORE_MAX)
def select_by_elimination(pool_sizes, score_fn, keep=6):
"""Greedy backward elimination for many devices at once (paper Sec. 3.5).
pool_sizes {device: n}; score_fn([(device, positions), ...]) -> {(device, positions): score}, called once per
elimination round for all candidate subsets of all devices. Each round drops, per device, the window whose removal
leaves the smallest score (ties: the lowest position). Returns {device: positions of the kept windows}."""
current = {key: tuple(range(n)) for key, n in pool_sizes.items()}
score_fn(list(current.items()))
while True:
active = [key for key in current if len(current[key]) > keep]
if not active:
break
candidates = {key: [tuple(p for p in current[key] if p != r) for r in current[key]] for key in active}
scores = score_fn([(key, c) for key in active for c in candidates[key]])
for key in active:
vals = [scores[(key, c)] for c in candidates[key]]
j = min(range(len(vals)), key=lambda i: (vals[i], i))
current[key] = candidates[key][j]
return current