Alignment¶
Audio--motion (and stream-to-stream) alignment tools.
Lead/lag estimation by cross-correlation, per-cycle motion-onset deltas, anchor-and-match relative event alignment with offset statistics, sliding-window coupling, and N-source envelope agreement.
These functions are independent of the MgVideo/MgAudio classes and operate on plain numpy arrays (envelopes, onset/event time lists).
Sources: ro study, cymbal-comparison study and Westney-comparisons study (Jensenius).
xcorr_lag ¶
xcorr_lag(x, y, fs, max_lag=1.5)
Canonical lead/lag estimate between two signals by vectorized
cross-correlation: the lag of y relative to x that maximizes their
correlation, searched within +/- max_lag seconds. Positive lag means
y happens after x.
Both signals are mean-removed and the correlation is normalized to a Pearson-like coefficient over the full window. Among near-tied maxima (common for periodic envelopes, where peaks recur at +/- one period), the smallest-magnitude lag is returned rather than an arbitrary aliased one.
Since 1.11.3 this delegates to micromotion.xcorr_lag, which owns lag
estimation for the toolbox family, so the two packages cannot return
different numbers for one pair of signals. The convention here is the one
that was kept: micromotion returned the opposite sign until its 1.13.0,
against its own documentation, and this function's agreement with its
docstring is what exposed that. micromotion also gained the tie-breaking
rule described above, which originated here.
difference=False is passed, preserving this function's behaviour.
micromotion differences by default, which guards against the spurious
correlation of two drifting series; for envelopes, which do not drift, the
undifferenced correlation is the more sensitive of the two. Call
micromotion.xcorr_lag directly if the inputs may drift.
Source: Westney-comparisons study (Jensenius) -- camera/audio residual
sync by onset-envelope cross-correlation; unified with the ro study's
envelope_lag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Reference 1-D signal. |
required |
y
|
ndarray
|
Comparison 1-D signal (same sampling rate). |
required |
fs
|
float
|
Sampling rate of both signals (Hz). |
required |
max_lag
|
float
|
Maximum absolute lag to search (s). Defaults to 1.5. |
1.5
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Source code in musicalgestures/_alignment.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
envelope_lag ¶
envelope_lag(x, y, rate, max_lag_s=1.5)
Lag (s) of y relative to x maximizing their correlation. Positive
lag = y happens after x. Thin wrapper around xcorr_lag, kept as
the ro study's interface for envelope-to-envelope lags (e.g. voice
envelope vs motion envelope).
Source: ro study (Jensenius).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Reference envelope. |
required |
y
|
ndarray
|
Comparison envelope (same sampling rate). |
required |
rate
|
float
|
Sampling rate of both envelopes (Hz). |
required |
max_lag_s
|
float
|
Maximum absolute lag to search (s). Defaults to 1.5. |
1.5
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Source code in musicalgestures/_alignment.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
per_cycle_motion_delta ¶
per_cycle_motion_delta(cycle_starts, motion_times, lookback=0.3)
For each cycle, the time of its assigned motion onset minus the cycle start (NaN if none). Each cycle's natural window is [start-lookback, next_start): the lookback lets a motion onset that anticipates this cycle's stroke be credited to it, while the unshifted upper bound at next_start lets genuine post-onset motion (motion after the cycle's own stroke) be credited too.
Because windows overlap by up to lookback, a single motion onset
can fall in two consecutive cycles' windows. To avoid double-
counting (and to stop a slow cycle from "stealing" a fast cycle's
only motion onset when IOI < lookback), cycles are processed in
DESCENDING time order and each claims the unclaimed motion onset
still inside its window that is NEAREST to its own cycle start
(ties broken toward the earlier onset), marking it claimed.
A cyclic gesture can plausibly produce two motion peaks per slow
cycle: a forward-stroke peak close to the sound onset and a later
return-stroke peak near the tail of the cycle's window. The
forward-stroke response to the sound is the one of interest, so
nearest-to-start assignment credits that one to the cycle instead
of the return-stroke peak that a latest-wins rule would grab.
Processing cycles in descending order still ensures a fast climax
cycle can secure its own motion onset before an earlier, slower
cycle's wider (lookback-only) window claims it instead.
Source: ro study (Jensenius) -- rowing-gesture onsets vs drum cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle_starts
|
ndarray
|
Cycle start times (s), ascending. |
required |
motion_times
|
ndarray
|
Motion onset times (s), any order. |
required |
lookback
|
float
|
How far before its start a cycle may claim a motion onset (s). Defaults to 0.3. |
0.3
|
Returns:
| Type | Description |
|---|---|
|
np.ndarray: One delta (s) per cycle: assigned motion onset time minus cycle start, NaN where no onset was assigned. |
Source code in musicalgestures/_alignment.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
anchor_and_match ¶
anchor_and_match(times_a, times_b, anchor_a=None, anchor_b=None, weights_a=None, weights_b=None, window=0.15)
Per-take relative event alignment between two streams with independent
clocks: both streams are shifted so that their anchor events -- by
default the strongest event of each stream, physically the same moment
(e.g. the hardest strike) -- sit at t = 0; then non-anchor events of
stream a are matched to non-anchor events of stream b within
+/- window seconds, and the signed offset (b minus a; positive =
b later) is recorded. The anchor pair contributes an offset of 0 by
construction and is excluded from BOTH streams -- b's anchor is
dropped from the match pool symmetrically with a's, so a non-anchor
a event near t = 0 cannot spuriously match b's anchor. Matching is
one-to-one: every candidate pair within the window is considered in
order of increasing |offset| and greedily claimed, each a and b
event usable in at most one match (consistent with
per_cycle_motion_delta's claim semantics), so a single b event
cannot be double-counted against multiple a events. No absolute
cross-stream synchronisation is claimed: the result measures whether
the two streams agree on the RELATIVE timing of the remaining events.
The default matching window of 0.15 s is a PROVISIONAL default, reimplemented from the cymbal-comparison paper's method description.
Source: cymbal-comparison study (Jensenius) -- audio-onset vs kinematic- impact (and video/pose) timing agreement without a common clock.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times_a
|
ndarray
|
Event times (s) of stream a (e.g. kinematic impacts). |
required |
times_b
|
ndarray
|
Event times (s) of stream b (e.g. audio onsets). |
required |
anchor_a
|
float
|
Anchor time in stream a. Defaults to None. |
None
|
anchor_b
|
float
|
Anchor time in stream b. Defaults to None. |
None
|
weights_a
|
ndarray
|
Event strengths for stream a, used to
pick the anchor (argmax) when |
None
|
weights_b
|
ndarray
|
Event strengths for stream b, used to
pick the anchor (argmax) when |
None
|
window
|
float
|
Maximum absolute offset (s) for a match. Defaults to 0.15. |
0.15
|
Returns:
| Type | Description |
|---|---|
|
np.ndarray: Signed offsets (s), one per matched non-anchor event of
stream a ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an anchor can be determined for neither stream (no anchor time and no weights given). |
Source code in musicalgestures/_alignment.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
offset_stats ¶
offset_stats(offsets)
Summary statistics of a signed-offset distribution (s), as reported for anchor-and-match timing agreement.
Source: cymbal-comparison study (Jensenius).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offsets
|
ndarray
|
Signed offsets (s), e.g. from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
|
Source code in musicalgestures/_alignment.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | |
sliding_correlation ¶
sliding_correlation(x, y, fs, window=10.0, step=2.0, min_std=1e-06)
Local (windowed) Pearson correlation profile between two signals:
correlation within sliding windows of window seconds, hopped by
step seconds. Windows where either signal is (near-)constant yield
NaN. Useful for testing whether two streams that are uncorrelated
globally correlate locally (e.g. a motion envelope vs an audio level
envelope).
Source: Westney-comparisons study (Jensenius) -- local motion-loudness correlation in 10 s windows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
First 1-D signal. |
required |
y
|
ndarray
|
Second 1-D signal (same sampling rate). |
required |
fs
|
float
|
Sampling rate of both signals (Hz). |
required |
window
|
float
|
Window length (s). Defaults to 10.0. |
10.0
|
step
|
float
|
Hop between windows (s). Defaults to 2.0. |
2.0
|
min_std
|
float
|
Minimum in-window standard deviation for a valid correlation. Defaults to 1e-6. |
1e-06
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Source code in musicalgestures/_alignment.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
envelope_agreement ¶
envelope_agreement(signals, fs, smooth=1.0)
Agreement among N parallel envelopes (e.g. per-camera-angle quantity-of-
motion curves of the same performance): the signals are truncated to
their common length, smoothed and z-scored (see
musicalgestures.envelope), and their Pearson correlation matrix is
computed. The mean off-diagonal correlation summarises how well the
sources agree.
Source: Westney-comparisons study (Jensenius) -- cross-view agreement of five camera angles' motion envelopes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signals
|
sequence
|
Sequence of N 1-D arrays (possibly of different lengths), or a 2-D array of shape (N, T). |
required |
fs
|
float
|
Sampling rate of the signals (Hz). |
required |
smooth
|
float
|
Envelope smoothing window (s); None or 0 disables smoothing. Defaults to 1.0. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Source code in musicalgestures/_alignment.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
envelope_from_audio ¶
envelope_from_audio(samples, sr, hop_s=0.05)
An amplitude envelope: peak absolute amplitude per hop.
Peak rather than mean, because a brief transient is exactly what makes two recordings of one event recognisable to each other, and a mean removes it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Audio, one dimension. Stereo is mixed to mono by the caller. |
required | |
sr
|
float
|
Sample rate of |
required |
hop_s
|
float
|
Hop length in seconds. Defaults to 0.05, a 20 Hz envelope. |
0.05
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
The envelope, and its sampling rate in frames per second. |
Source code in musicalgestures/_alignment.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
locate_probe ¶
locate_probe(probe, reference)
Where probe best matches inside reference, and how well.
The correlation is normalised over the actual overlap at every position, so a position where only a few samples overlap cannot score better than one where they all do --- an unnormalised correlation picks exactly such a position and reports a perfect match.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
The shorter series to locate. |
required | |
reference
|
The longer series to search. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Index of the best position and its Pearson r, or |
|
|
probe has no variance to match with or is longer than the reference. |
Source code in musicalgestures/_alignment.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
align_by_audio ¶
align_by_audio(cut, reference, fs, n_probes=12, probe_s=30.0, min_r=0.45, tolerance_s=0.5)
The offset at which cut sits inside reference, from several probes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cut
|
Envelope of the shorter recording. |
required | |
reference
|
Envelope of the longer one. |
required | |
fs
|
float
|
Sampling rate of both envelopes, in frames per second. |
required |
n_probes
|
int
|
How many windows to locate independently. Defaults to 12. |
12
|
probe_s
|
float
|
Length of each window in seconds. Defaults to 30.0. |
30.0
|
min_r
|
float
|
Correlation below which a probe is treated as no match rather than as a weak one. Defaults to 0.45. |
0.45
|
tolerance_s
|
float
|
How close two probe offsets must be to count as the same. Defaults to 0.5. |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
|
|
cluster of probes agrees, which is the correct answer for two recordings that |
||
|
have nothing in common. Add |
||
|
|
Source code in musicalgestures/_alignment.py
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | |