From 384cbbb8ac6cd04909e896ef28da4eb15215e1c2 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 5 Aug 2026 20:52:40 -0500 Subject: [PATCH 01/13] fix(validation): the alpha contrast could not tell eye closure from elapsed time validate-muse-physiology.py recorded one 30 s eyes-open block then one 30 s eyes-closed block, always in that order, and reported alpha_closed/alpha_open against a 1.5x threshold. Condition was perfectly confounded with block position: impedance settling, electrode warming and drowsiness onset all push that ratio the same way real alpha does, and no analysis of such a recording can separate them. Four counterbalanced blocks (open, closed, closed, open; 15 s each, same 60 s of alpha data) put both conditions at mean position 2.5, so a linear drift subtracts out. First 2 s of every block is discarded for the alpha build-up, symmetrically across conditions so the discard is not its own bias. Cue onset is now logged separately from block start, so the discard is auditable rather than a magic constant. ABBA cancels a linear trend exactly and electrode settling is curved, so a residual survives whose sign depends on the curvature. The time-index baseline measures it: the identical statistic on the same blocks relabelled by position alone (1-2 vs 3-4), orthogonal to condition under ABBA. A channel passes only if the condition ratio clears 1.5x AND exceeds the time-index ratio. TIME_BASELINE_MARGIN is a named constant because that residual is empirical. --self-check runs without hardware. On synthetic data with zero alpha and pure drift the OLD statistic reports 7.11x -- a comfortable pass -- while the new gate rejects it. Asserting both on identical input is the point: otherwise the check proves the new gate works, not that it catches what the old one missed. Also caught: MIN_VALID_SAMPLES derived from the removed SEG_OPEN and would have been left 2x loose against the shorter blocks, passing every truncated block it exists to catch. The 2026-07-10 results stay in Validation.md, annotated as collected under the sequential protocol and provisional pending re-collection. Recorded there and in docs/reviews/time-leakage-2026-08-06.md: the "time-index alone reaches 0.883" figure that motivated this has no preserved artifact and is not to be cited. The same review documents the open StratifiedKFold(shuffle=True) leak in evaluate-imagined-signal.py, which inflates the 0.65 Track B gate now. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MzVWyZwh6x665nXGCVR3pg --- Scripts/validate-muse-physiology.py | 242 ++++++++++++++++++++---- docs/Validation.md | 52 ++++- docs/reviews/time-leakage-2026-08-06.md | 84 ++++++++ 3 files changed, 338 insertions(+), 40 deletions(-) create mode 100644 docs/reviews/time-leakage-2026-08-06.md diff --git a/Scripts/validate-muse-physiology.py b/Scripts/validate-muse-physiology.py index 602e09d..45d1f25 100755 --- a/Scripts/validate-muse-physiology.py +++ b/Scripts/validate-muse-physiology.py @@ -59,13 +59,42 @@ if os.path.isdir(BF_LIB): os.environ["DYLD_LIBRARY_PATH"] = BF_LIB + ":" + os.environ.get("DYLD_LIBRARY_PATH", "") -from brainflow.board_shim import BoardShim, BoardIds, BrainFlowInputParams # noqa: E402 +try: + from brainflow.board_shim import BoardShim, BoardIds, BrainFlowInputParams # noqa: E402 +except ImportError: # --self-check analyses synthetic arrays and needs no hardware lib + BoardShim = BoardIds = BrainFlowInputParams = None # --- Configuration --------------------------------------------------------- SAMPLE_RATE = 256 # Muse S native -SEG_OPEN = 30.0 # seconds, eyes open -SEG_CLOSED = 30.0 # seconds, eyes closed + +# Alpha contrast: four counterbalanced blocks, not one open then one closed. +# +# Number the blocks by position 1-4. Under ABBA the open blocks sit at 1 and 4 +# (mean position 2.5) and the closed at 2 and 3 (also 2.5), so both conditions +# occupy the same average point in the session and a LINEAR drift — impedance +# settling, gel warming, drowsiness onset — subtracts out of the ratio. Under the +# old `open, closed` every bit of drift landed on `closed` and was indistinguishable +# from alpha. Under ABAB the closed mean is still one position later, leaving a +# residual that always points the same way. +# +# ABBA cancels a linear trend EXACTLY, and electrode settling is usually curved — +# fast, then flattening. Under a convex or concave trend, equal mean position is not +# sufficient: a residual survives whose sign depends on which way the curve bends +# (decaying settling biases the ratio conservatively, saturating warming biases it +# the wrong way). Measuring that leftover is what the time-index baseline in +# analyze() is for. The two are not redundant — this constant removes the bulk, +# that gate measures what curvature left behind. +BLOCK_SECONDS = 15.0 # 4 x 15 s = same 60 s of alpha data +ALPHA_BLOCK_ORDER = ['open', 'closed', 'closed', 'open'] + +# Occipital alpha takes ~1-2 s to rise after eye closure. Including the build-up +# biases closed blocks downward and makes the ratio sensitive to block length. +# Trimmed from the START OF EVERY BLOCK, open and closed alike — trimming both +# conditions symmetrically is what keeps the discard from being its own thumb on +# the scale. +BLOCK_EDGE_DISCARD_S = 2.0 + SEG_BLINK = 5.0 # seconds, blink deliberately SEG_CLENCH = 8.0 # seconds, jaw clench (3s clench, 1s release, 2 cycles = 8s) SEG_TURN = 10.0 # seconds, head turn @@ -84,7 +113,17 @@ HEAD_TURN_UV = 30.0 # slow turns are 30-80 µV; jerky is 100+ CLENCH_BETA_RATIO = 2.0 # true EMG bursts are broadband >50 Hz, but 13-30 should rise CLENCH_BROADBAND_RATIO = 1.5 # 30-100 Hz broadband rise; EMG is broadband, single-band tests miss it -MIN_VALID_SAMPLES = SEG_OPEN * SAMPLE_RATE * 0.8 # 80% of expected + +# The condition ratio must also beat the drift the time-index baseline measures. +# A multiplier, not a bare `>`, because the residual ABBA leaves behind is +# empirical — it depends on how this unit's electrodes settle — and only real +# sessions can say how noisy the estimate is. This is the calibration knob. +TIME_BASELINE_MARGIN = 1.0 + +# 80% of expected. Derives from BLOCK_SECONDS, NOT the old 30 s segment length: +# pinning it to a stale longer duration would leave the check 2x loose and it +# would pass on every truncated block it was written to catch. +MIN_VALID_SAMPLES = BLOCK_SECONDS * SAMPLE_RATE * 0.8 # --- Utilities ------------------------------------------------------------- @@ -150,6 +189,10 @@ class Recorder: def __init__(self): self.board = None self.started_at = None + # Cue onset is logged separately from block start. Without both, the 2 s + # edge discard is a magic constant no later reader can audit: "user was + # told to close their eyes" and "samples began" are 3+ seconds apart. + self.marks = [] def connect(self): params = BrainFlowInputParams() @@ -171,6 +214,7 @@ def connect(self): def segment(self, duration, label, prompt): """Record one segment with a real-time prompt to the user.""" + cue_unix = time.time() print(f"\n>>> {label}: {prompt}") for remaining in [3, 2, 1]: print(f" starting in {remaining}...") @@ -178,6 +222,7 @@ def segment(self, duration, label, prompt): n_samples = int(duration * SAMPLE_RATE) # Drain current buffer self.board.get_current_board_data(n_samples) + block_start_unix = time.time() # Wait for the duration time.sleep(duration + 0.2) data = self.board.get_current_board_data(int((duration + 5) * SAMPLE_RATE)) @@ -186,6 +231,13 @@ def segment(self, duration, label, prompt): # Take the last n_samples if n_cols > n_samples: data = data[:, -n_samples:] + self.marks.append({ + "label": label, "block_index": len(self.marks) + 1, + "cue_unix": cue_unix, "block_start_unix": block_start_unix, + "cue_to_start_s": block_start_unix - cue_unix, + "duration_s": duration, "n_samples": int(data.shape[1]), + "short_block": data.shape[1] < MIN_VALID_SAMPLES, + }) return data def disconnect(self): @@ -199,28 +251,71 @@ def disconnect(self): # --- Analysis -------------------------------------------------------------- -def analyze(data_open, data_closed, data_blink, data_clench, data_turn): +def trim_block_edge(block): + """Drop BLOCK_EDGE_DISCARD_S from the front of one block (alpha build-up).""" + n = int(BLOCK_EDGE_DISCARD_S * SAMPLE_RATE) + return block[:, n:] if block.shape[1] > n else block + + +def alpha_ratio(blocks_hi, blocks_lo, ch_idx): + """Alpha power in one group of blocks over another, for a single channel.""" + x_hi = np.concatenate([b[ch_idx, :] for b in blocks_hi]).astype(np.float64) + x_lo = np.concatenate([b[ch_idx, :] for b in blocks_lo]).astype(np.float64) + p_hi = bandpower(x_hi, SAMPLE_RATE, ALPHA_BAND) + p_lo = bandpower(x_lo, SAMPLE_RATE, ALPHA_BAND) + return p_hi / max(p_lo, 1e-9) + + +def analyze(alpha_blocks, data_blink, data_clench, data_turn): + """alpha_blocks: the four ABBA blocks in TIME ORDER, labelled by ALPHA_BLOCK_ORDER.""" results = {} # Channel order in BrainFlow: ch0=package_num, ch1=TP9, ch2=AF7, ch3=AF8, ch4=TP10, ch5=AUX, ch6=ts def extract(data, ch_idx): return data[ch_idx, :].astype(np.float64) - # 1. Alpha power ratio eyes-closed / eyes-open, per channel + trimmed = [trim_block_edge(b) for b in alpha_blocks] + open_blocks = [b for b, lab in zip(trimmed, ALPHA_BLOCK_ORDER) if lab == 'open'] + closed_blocks = [b for b, lab in zip(trimmed, ALPHA_BLOCK_ORDER) if lab == 'closed'] + # Relabelled by POSITION alone, ignoring condition. Under ABBA this split is + # orthogonal to the real labels, so it measures pure drift and nothing else. + first_half, second_half = trimmed[:2], trimmed[2:] + + # Sections 3 and 5 below want contiguous open/closed arrays; the untrimmed + # concatenation is right there since they are baselines, not the contrast. + data_open = np.concatenate( + [b for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'open'], axis=1) + data_closed = np.concatenate( + [b for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'closed'], axis=1) + + # 1. Alpha power ratio eyes-closed / eyes-open, per channel, against drift print("\n--- 1. Alpha power (8-13 Hz) per channel ---") + print(f" blocks: {' '.join(ALPHA_BLOCK_ORDER)} @ {BLOCK_SECONDS:.0f}s, " + f"first {BLOCK_EDGE_DISCARD_S:.0f}s of each discarded") alpha_ratios = {} + time_ratios = {} + alpha_pass_by_ch = {} for i, ch_idx in enumerate(EEG_CHANNELS): - x_open = extract(data_open, ch_idx) - x_closed = extract(data_closed, ch_idx) - p_open = bandpower(x_open, SAMPLE_RATE, ALPHA_BAND) - p_closed = bandpower(x_closed, SAMPLE_RATE, ALPHA_BAND) - ratio = p_closed / max(p_open, 1e-9) - alpha_ratios[CHANNEL_NAMES[i]] = ratio - print(f" {CHANNEL_NAMES[i]:>5}: open={p_open:>10.2f} closed={p_closed:>10.2f} ratio={ratio:.2f}") + r_cond = alpha_ratio(closed_blocks, open_blocks, ch_idx) + r_time = alpha_ratio(second_half, first_half, ch_idx) + alpha_ratios[CHANNEL_NAMES[i]] = r_cond + time_ratios[CHANNEL_NAMES[i]] = r_time + # Both gates: big enough, AND bigger than the drift on the same data. + alpha_pass_by_ch[CHANNEL_NAMES[i]] = ( + r_cond >= ALPHA_RATIO_THRESHOLD and r_cond > r_time * TIME_BASELINE_MARGIN) + verdict = 'PASS' if alpha_pass_by_ch[CHANNEL_NAMES[i]] else ( + 'drift' if r_cond >= ALPHA_RATIO_THRESHOLD else 'fail') + print(f" {CHANNEL_NAMES[i]:>5}: condition={r_cond:>6.2f} " + f"time-index={r_time:>6.2f} {verdict}") results['alpha_ratios'] = alpha_ratios - best_ratio = max(alpha_ratios.values()) - results['best_alpha_ratio'] = best_ratio - results['alpha_pass'] = best_ratio >= ALPHA_RATIO_THRESHOLD + results['alpha_time_index_ratios'] = time_ratios + results['alpha_pass_by_channel'] = alpha_pass_by_ch + results['best_alpha_ratio'] = max(alpha_ratios.values()) + results['worst_time_index_ratio'] = max(time_ratios.values()) + results['alpha_pass'] = any(alpha_pass_by_ch.values()) + if not results['alpha_pass'] and results['best_alpha_ratio'] >= ALPHA_RATIO_THRESHOLD: + print(" ** alpha ratio cleared 1.5x but did NOT beat the time-index baseline.") + print(" A drift across the session explains it as well as eye closure does.") # 2. Blink detection: max abs value in AF7/AF8 during blink window print("\n--- 2. Blink transient detection (frontal channels) ---") @@ -320,7 +415,7 @@ def extract(data, ch_idx): print("=" * 60) checks = [ ("Contact quality (RMS 2-200 µV)", results['contact_pass']), - ("Alpha rise on eyes-closed (>=1.5x)", results['alpha_pass']), + ("Alpha rise on eyes-closed (>=1.5x, beats time-index)", results['alpha_pass']), ("Blink transient (>=40 µV AF7/AF8)", results['blink_pass']), ("Jaw clench beta (>=2x baseline)", results['clench_pass']), ("Head turn artifact (>=30 µV swing)", results['turn_pass']), @@ -398,10 +493,16 @@ def stop(*_): sys.exit(130) signal.signal(signal.SIGINT, stop) - data_open = rec.segment(SEG_OPEN, "EYES OPEN", - "Open eyes. Look at a fixed point. Relax face/jaw.") - data_closed = rec.segment(SEG_CLOSED, "EYES CLOSED", - "Close eyes gently. Same relaxation. Don't squint.") + prompts = { + 'open': "Open eyes. Look at a fixed point. Relax face/jaw.", + 'closed': "Close eyes gently. Same relaxation. Don't squint.", + } + alpha_blocks = [] + for n, lab in enumerate(ALPHA_BLOCK_ORDER, start=1): + alpha_blocks.append(rec.segment( + BLOCK_SECONDS, f"BLOCK {n}/{len(ALPHA_BLOCK_ORDER)} — EYES {lab.upper()}", + prompts[lab])) + data_blink = rec.segment(SEG_BLINK, "BLINK", "Blink deliberately, ~5 blinks over 5 seconds.") data_clench = rec.segment(SEG_CLENCH, "JAW CLENCH", @@ -413,12 +514,19 @@ def stop(*_): # Save raw CSV (column-major: ch0..ch6, samples along axis 1) print(f"\nSaving raw data to {out_csv}") - all_data = np.concatenate([data_open, data_closed, data_blink, data_clench, data_turn], axis=1) + all_data = np.concatenate(alpha_blocks + [data_blink, data_clench, data_turn], axis=1) header = "package_num,TP9,AF7,AF8,TP10,AUX_R,timestamp,segment\n" - # Annotate segment per row - seg_labels = (['open'] * data_open.shape[1] + - ['closed'] * data_closed.shape[1] + - ['blink'] * data_blink.shape[1] + + # Annotate segment per row. Blocks are numbered (open1, closed1, closed2, + # open2) so the ABBA position survives into the CSV — a bare open/closed + # would throw away exactly what the counterbalancing bought. The downstream + # consumer (convert_muse_validation_recordings.py:58) passes this column + # through verbatim, so the new labels are additive, not breaking. + seen = {} + seg_labels = [] + for blk, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER): + seen[lab] = seen.get(lab, 0) + 1 + seg_labels += [f"{lab}{seen[lab]}"] * blk.shape[1] + seg_labels += (['blink'] * data_blink.shape[1] + ['clench'] * data_clench.shape[1] + ['turn'] * data_turn.shape[1]) rows = [] @@ -431,14 +539,20 @@ def stop(*_): f.write('\n'.join(rows) + '\n') # Analyze - results, rc = analyze(data_open, data_closed, data_blink, data_clench, data_turn) + results, rc = analyze(alpha_blocks, data_blink, data_clench, data_turn) + results['block_marks'] = rec.marks + results['block_order'] = ALPHA_BLOCK_ORDER # ASCII spectrograms (eyes open vs eyes closed) for visual confirmation + af7_open = np.concatenate( + [b[2, :] for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'open']) + af7_closed = np.concatenate( + [b[2, :] for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'closed']) print("\n--- 6. AF7 spectrogram: eyes open vs eyes closed ---") - print(ascii_spectrogram(data_open[2, :].astype(np.float64), SAMPLE_RATE, - title="AF7 EYES OPEN (last 30s)", width=60, height=14)) - print(ascii_spectrogram(data_closed[2, :].astype(np.float64), SAMPLE_RATE, - title="AF7 EYES CLOSED (30s)", width=60, height=14)) + print(ascii_spectrogram(af7_open.astype(np.float64), SAMPLE_RATE, + title="AF7 EYES OPEN (both blocks)", width=60, height=14)) + print(ascii_spectrogram(af7_closed.astype(np.float64), SAMPLE_RATE, + title="AF7 EYES CLOSED (both blocks)", width=60, height=14)) # Save summary with open(out_json, 'w') as f: @@ -448,9 +562,73 @@ def stop(*_): return rc +def _synth_blocks(alpha_gain=1.0, drift_per_block=1.0, seed=0): + """Four synthetic ABBA blocks. alpha_gain multiplies 10 Hz amplitude on the + CLOSED blocks; drift_per_block multiplies broadband amplitude by position, + ignoring condition entirely.""" + rng = np.random.default_rng(seed) + n = int(BLOCK_SECONDS * SAMPLE_RATE) + t = np.arange(n) / SAMPLE_RATE + blocks = [] + for pos, lab in enumerate(ALPHA_BLOCK_ORDER): + sig = rng.normal(0.0, 10.0, n) + if lab == 'closed': + sig = sig + alpha_gain * 10.0 * np.sin(2 * np.pi * 10.0 * t) + sig = sig * (drift_per_block ** pos) + block = np.zeros((7, n)) + for ch in EEG_CHANNELS: + block[ch, :] = sig + rng.normal(0.0, 1.0, n) + blocks.append(block) + return blocks + + +def _old_protocol_ratio(blocks, ch_idx): + """The statistic the OLD script computed: blocks 1-2 as 'open', 3-4 as + 'closed' — i.e. the sequential order it recorded in, with no edge trim.""" + return alpha_ratio(blocks[2:], blocks[:2], ch_idx) + + +def demo(): + """Self-check. Runs without brainflow or hardware: python3 --self-check""" + ch = EEG_CHANNELS[0] + + # (a) Real alpha, no drift -> condition ratio high, time ratio ~1, PASSES. + b = [trim_block_edge(x) for x in _synth_blocks(alpha_gain=1.0, drift_per_block=1.0)] + r_cond = alpha_ratio(b[1:3], [b[0], b[3]], ch) + r_time = alpha_ratio(b[2:], b[:2], ch) + assert r_cond >= ALPHA_RATIO_THRESHOLD, f"(a) alpha not detected: {r_cond:.2f}" + assert r_cond > r_time * TIME_BASELINE_MARGIN, f"(a) {r_cond:.2f} !> {r_time:.2f}" + + # (b) Pure drift, no alpha. The new gate must fail -- AND the old design, + # on this identical array, must PASS. Without the second assertion this + # only proves the new gate works, not that it catches anything the old + # one missed, which is the entire claim the redesign rests on. + raw = _synth_blocks(alpha_gain=0.0, drift_per_block=1.6) + d = [trim_block_edge(x) for x in raw] + r_cond = alpha_ratio(d[1:3], [d[0], d[3]], ch) + r_time = alpha_ratio(d[2:], d[:2], ch) + assert not (r_cond >= ALPHA_RATIO_THRESHOLD and r_cond > r_time * TIME_BASELINE_MARGIN), \ + f"(b) new gate passed pure drift: cond={r_cond:.2f} time={r_time:.2f}" + r_old = _old_protocol_ratio(raw, ch) + assert r_old >= ALPHA_RATIO_THRESHOLD, \ + f"(b) old protocol did not report a pass on pure drift ({r_old:.2f}); " \ + "the regression this change exists to fix is not being exercised" + + # (c) Alpha AND drift -> condition must still beat time-index. + m = [trim_block_edge(x) for x in _synth_blocks(alpha_gain=2.0, drift_per_block=1.2)] + r_cond = alpha_ratio(m[1:3], [m[0], m[3]], ch) + r_time = alpha_ratio(m[2:], m[:2], ch) + assert r_cond >= ALPHA_RATIO_THRESHOLD and r_cond > r_time * TIME_BASELINE_MARGIN, \ + f"(c) real alpha lost to drift: cond={r_cond:.2f} time={r_time:.2f}" + + print(f"self-check ok — pure drift: old protocol reports {r_old:.2f}x (PASS), " + f"new gate rejects it") + return 0 + + if __name__ == "__main__": try: - sys.exit(main()) + sys.exit(demo() if "--self-check" in sys.argv else main()) except Exception as e: import traceback traceback.print_exc() diff --git a/docs/Validation.md b/docs/Validation.md index 739790d..a399aff 100644 --- a/docs/Validation.md +++ b/docs/Validation.md @@ -23,13 +23,33 @@ and is recorded with a segment label. | # | Condition | Duration | What the user does | Expected signature | |---|-----------|----------|-------------------|-------------------| -| 1 | Eyes open | 30 s | Look at a fixed point, relax | Low alpha, more beta | -| 2 | Eyes closed | 30 s | Close eyes gently, same relaxation | Alpha power rises ≥ 1.5× vs eyes-open | -| 3 | Blinks | 5 s | Blink deliberately, ~5 in 5 s | Frontal transient ≥ 40 µV in AF7/AF8 | -| 4 | Jaw clench | 5 s | Clench hard, release, 3 cycles | Broadband > 20 Hz energy rise ≥ 2× baseline | -| 5 | Head turn | 10 s | Turn head left/right slowly | Low-frequency swing ≥ 30 µV in TP9/TP10 | - -Each condition is event-tagged in the recorded CSV. Total runtime ~80 s + analysis. +| 1–4 | Eyes open / closed, **ABBA** | 4 × 15 s | Open, closed, closed, open | Alpha power rises ≥ 1.5× vs eyes-open **and** beats the time-index baseline | +| 5 | Blinks | 5 s | Blink deliberately, ~5 in 5 s | Frontal transient ≥ 40 µV in AF7/AF8 | +| 6 | Jaw clench | 5 s | Clench hard, release, 3 cycles | Broadband > 20 Hz energy rise ≥ 2× baseline | +| 7 | Head turn | 10 s | Turn head left/right slowly | Low-frequency swing ≥ 30 µV in TP9/TP10 | + +Each condition is event-tagged in the recorded CSV (`open1`, `closed1`, `closed2`, +`open2`, then `blink`/`clench`/`turn`). Total runtime ~80 s + analysis. + +### Why the alpha contrast is counterbalanced + +The protocol originally ran one 30 s eyes-open block followed by one 30 s eyes-closed +block, always in that order. Condition was therefore perfectly confounded with elapsed +time: impedance settling, electrode warming, and drowsiness onset all push +`alpha_closed / alpha_open` in the same direction as real alpha, and no analysis of that +recording can separate them. + +Four blocks in `open, closed, closed, open` order put both conditions at the same mean +position in the session (2.5), so a linear drift subtracts out of the ratio. The first +2 s of every block is discarded — occipital alpha needs ~1–2 s to rise after eye closure — +symmetrically across both conditions, so the discard is not itself a thumb on the scale. + +ABBA cancels a *linear* trend exactly, and electrode settling is usually curved. The +residual that curvature leaves behind is what the **time-index baseline** measures: the +identical statistic computed on the same blocks relabelled by position alone (blocks 1–2 +vs 3–4), which under ABBA is orthogonal to condition. A channel passes only if the +condition ratio clears 1.5× **and** exceeds the time-index ratio. Both numbers are +reported per channel, pass or fail. ## Pass Criteria @@ -38,7 +58,7 @@ The script computes per-channel statistics and produces a pass/fail verdict: | Check | Pass criterion | Why | |-------|---------------|-----| | Contact quality (RMS 2–200 µV, all 4 channels) | all 4 in range | Disconnected channel: RMS < 2 µV. Saturated front-end: RMS > 200 µV. | -| Alpha rise on eyes-closed | best channel ≥ 1.5× | Canonical EEG signature. | +| Alpha rise on eyes-closed | best channel ≥ 1.5× **and** > its time-index ratio | Canonical EEG signature, gated so a session-long drift cannot report as alpha. | | Blink transient | AF7 or AF8 max ≥ 40 µV | Normal-blink amplitude, not the literature's 150 µV for forced blinks. | | Jaw clench broadband | best channel ≥ 2× baseline | EMG contamination is broadband; 13–30 Hz is one slice of it. | | Head turn motion | best channel ≥ 30 µV swing | Slow turns produce 30–80 µV; the 100 µV literature threshold is for jerky turns. | @@ -47,6 +67,22 @@ A 4/5 pass indicates a working acquisition pipeline. A 5/5 pass indicates a clea ## Current Results (2026-07-10) +> **Collected under the old sequential protocol.** Every figure below comes from the +> `open → closed` ordering described above, in which condition is confounded with block +> order. The TP9/TP10 alpha rises are large enough to be plausible on their face, but they +> are **not demonstrated** until re-collected under ABBA with the time-index baseline +> reported. Treat them as provisional; do not cite them as evidence the acquisition +> pipeline resolves alpha. +> +> **On the "0.883" figure:** the drift concern was argued for some time from a claim that +> *time-index alone classifies open vs closed at 0.883*. **That measurement has no +> preserved artifact.** It is not in any recording, script output, or log in this repo; it +> entered a working session as prose and was carried forward as established. The nearest +> values on disk — `Scripts/dream_extraction.py:335`, rho 0.8827/0.8857 — are a different +> metric on a different analysis, already annotated there as small-n artifacts. **Do not +> re-cite 0.883.** The redesign stands on the design defect, which is visible in the +> source and reproduced by the `--self-check` regression, not on that number. + Single participant, single session, Muse S on the head, 80-second protocol: | Check | Result | Pass/Fail | diff --git a/docs/reviews/time-leakage-2026-08-06.md b/docs/reviews/time-leakage-2026-08-06.md new file mode 100644 index 0000000..251cb84 --- /dev/null +++ b/docs/reviews/time-leakage-2026-08-06.md @@ -0,0 +1,84 @@ +# Time leakage in two EEG evaluations — 2026-08-06 + +Two places where a measurement cannot separate signal from elapsed time. One is fixed in +this change; the other is documented here and still open. They are the same disease, and +the open one is the more urgent because it is **currently gating a decision**. + +## 1. Muse physiological validation — FIXED + +`Scripts/validate-muse-physiology.py` recorded one 30 s eyes-open block followed by one +30 s eyes-closed block, always in that order, and reported +`alpha_closed / alpha_open` against a 1.5× threshold. Condition was perfectly confounded +with block position, so impedance settling, electrode warming, and drowsiness onset all +pushed the ratio the same way real alpha does. + +Fix: four counterbalanced blocks (`open, closed, closed, open`, 15 s each — same 60 s of +alpha data), first 2 s of every block discarded for the alpha build-up, cue onset logged +separately from block start, and a **time-index baseline** gate — the identical statistic +computed on the same blocks relabelled by position alone (1–2 vs 3–4), which under ABBA is +orthogonal to condition. A channel passes only if the condition ratio clears 1.5× *and* +exceeds the time-index ratio. + +Regression, in `--self-check`: on synthetic data with **zero alpha and pure drift**, the +old sequential statistic reports **7.11×** — a comfortable pass at a 1.5× threshold — +while the new gate rejects it. That assertion is the point of the change; without it the +suite would only prove the new gate works, not that it catches something the old one +missed. + +The 2026-07-10 results (TP9 2.98×, TP10 3.88×) were collected under the old protocol and +are now annotated in `docs/Validation.md` as provisional pending re-collection. + +## 2. Imagined-speech pre-registration gate — OPEN + +`Scripts/evaluate-imagined-signal.py:238`: + +```python +skf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed) +``` + +Trials arrive in acquisition order. `shuffle=True` scatters temporally adjacent trials +across train and test, so a fold's test set is neighboured in time by its own training +data. Anything that drifts slowly within a session — impedance, electrode temperature, +alertness, headband slip — is then partially learnable rather than held out, and a +classifier can score above chance without decoding anything about imagined speech. + +**Why this is the urgent one.** It feeds the pre-registration gate at `:10`: + +``` +PASS iff balanced_accuracy >= 0.65 AND min(class_count) >= 50 +``` + +That threshold was pinned in advance precisely so Track B could not be promoted on a soft +judgement (see `CLAUDE.md`, Track B pre-registration gate). But the number being compared +against it is inflated by an unknown amount. A pre-registered threshold evaluated with a +leaky estimator is not a pre-registered threshold. **Any balanced accuracy reported by +this script today is provisional and must not be used to promote Track B past +experimental.** + +### Fix owed + +- Replace the shuffled `StratifiedKFold` with block-aware splitting — `GroupKFold` (or + `StratifiedGroupKFold`) with groups derived from acquisition-time blocks, so whole + contiguous runs of trials are held out together rather than interleaved. +- Add a **time-index control on the same folds**: train and score the identical pipeline + on trial index alone. Report both numbers; gate on the label-based score exceeding the + time-only score, exactly as the alpha gate now does. This is the piece that converts + "we think the CV is clean" into something the script checks. +- Trial order in `Sources/BCIEEG/Calibration/ImaginedSpeechProtocol.swift:199-208` is + already a seeded shuffle, not strict alternation, and the seed is recorded to + `metadata.json` — so the acquisition side is sound and only the evaluator needs work. + +Not fixed in this change because it was scoped to the Muse validation protocol. Recorded +here so it does not survive only as a line in a plan's exclusions section. + +## Note on provenance + +The drift concern was argued for several sessions from a claim that *time-index alone +classifies eyes-open vs eyes-closed at 0.883*. **That figure has no preserved artifact** — +no recording, script output, or log in this repo contains it. It entered a working session +as prose and was carried forward as established fact, load-bearing for a design decision. +The nearest values on disk (`Scripts/dream_extraction.py:335`, rho 0.8827/0.8857) are a +different metric on a different analysis, already annotated there as small-n artifacts. + +Both fixes above stand on defects visible in the source, and the first is demonstrated by +a runnable regression. Neither needs 0.883, and it should not be cited again. From a0fd3dbb033c10fad85559c170d1ab8b8cfe37a6 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 5 Aug 2026 21:57:37 -0500 Subject: [PATCH 02/13] =?UTF-8?q?docs(validation):=20lead=20with=207.11x?= =?UTF-8?q?=20=E2=80=94=20what=20the=20old=20protocol=20reported=20on=20no?= =?UTF-8?q?=20signal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The provisionality note argued from the design defect. The number is the argument: zero alpha, pure drift, old statistic reports 7.11x against a 1.5x threshold. A reader who sees that understands why 2.98x/3.88x cannot be cited as demonstrated. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MzVWyZwh6x665nXGCVR3pg --- docs/Validation.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/Validation.md b/docs/Validation.md index a399aff..8c887dc 100644 --- a/docs/Validation.md +++ b/docs/Validation.md @@ -67,12 +67,16 @@ A 4/5 pass indicates a working acquisition pipeline. A 5/5 pass indicates a clea ## Current Results (2026-07-10) -> **Collected under the old sequential protocol.** Every figure below comes from the -> `open → closed` ordering described above, in which condition is confounded with block -> order. The TP9/TP10 alpha rises are large enough to be plausible on their face, but they -> are **not demonstrated** until re-collected under ABBA with the time-index baseline -> reported. Treat them as provisional; do not cite them as evidence the acquisition -> pipeline resolves alpha. +> **On synthetic data containing zero alpha and pure drift, the old design reports 7.11× +> against a 1.5× threshold** — passing by nearly five times the margin on a signal that is +> not there. That is the regression asserted in `validate-muse-physiology.py --self-check`, +> and it is the measure of how little the old protocol constrained. +> +> Every figure below was collected under that protocol: the `open → closed` ordering, in +> which condition is confounded with block order. The TP9/TP10 alpha rises are large enough +> to be plausible on their face, but they are **not demonstrated** until re-collected under +> ABBA with the time-index baseline reported. Treat them as provisional; do not cite them +> as evidence the acquisition pipeline resolves alpha. > > **On the "0.883" figure:** the drift concern was argued for some time from a claim that > *time-index alone classifies open vs closed at 0.883*. **That measurement has no From b452015bbcddfd46cd66d8cf7575fe9ffe56d0b5 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 5 Aug 2026 22:42:48 -0500 Subject: [PATCH 03/13] fix(trackb): block-aware CV and a time-index control -- and withdraw the leak claim evaluate-imagined-signal.py used StratifiedKFold(shuffle=True) over time-ordered trials. Replaced with GroupKFold on contiguous acquisition blocks, plus a time-index control on the same folds (the identical pipeline trained on trial position alone); the gate now requires the EEG score to beat it. But the claim that motivated this does not survive measurement, and the doc now says so. On synthetic trials with zero class signal -- monotone amplitude drift, 50/50 shuffled labels producing same-class runs -- the OLD shuffled evaluator scored 0.4375/0.4500/0.5000/0.5750 across four seeds. It never cleared the 0.65 gate. LinearSVC on 16 global band-power features has too little capacity to exploit fold-local structure. A second construction with labels correlated to acquisition position also failed to pass (blocked 0.4656, time-index 0.5250). So "the 0.65 threshold is inflated by an unknown amount" is withdrawn. It was asserted from a design smell, in a review document written to warn against exactly that move. GroupKFold stays as the conservative design -- shuffled folds over time-ordered trials remain bad practice and the swap costs nothing -- not as a fix for a measured defect. --self-check asserts only what reproduces: drift-only data does not pass the gate. It prints the shuffled number every run and flags loudly if the leak ever does appear, so the non-result gets re-tested rather than remembered. Contrast with the alpha protocol in the same review: there the old statistic reports 7.11x on pure drift. Same reasoning applied to both, one reproduced. CLAUDE.md: the EEG validation scripts are not macOS-only. The PyPI brainflow wheel bundles libMuseLib.so and libBrainFlowBluetooth.so, and the DYLD block is guarded by os.path.isdir, so a Linux box needs only pip install brainflow. The "macOS prototype" framing would have sent the next session to the wrong machine. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MzVWyZwh6x665nXGCVR3pg --- CLAUDE.md | 8 ++ Scripts/evaluate-imagined-signal.py | 144 +++++++++++++++++++++--- docs/reviews/time-leakage-2026-08-06.md | 105 +++++++++++------ 3 files changed, 209 insertions(+), 48 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 924e430..b08e33e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,6 +2,14 @@ Privacy-first, fully on-device macOS prototype for **EEG-driven communication**. A Muse headband streams brain signals through BrainFlow, a Core ML classifier on the Apple Neural Engine detects intent (jaw clench / blink / rest / select), and a local MLX LLM suggests next words. The user "types" by letting a cycling 3-token carousel highlight a candidate, then committing with a brain-signal selection. **No network at runtime. No cloud. No telemetry.** +**The app is macOS; the EEG validation scripts are not.** `Scripts/validate-muse-physiology.py` +runs on Linux as-is — the PyPI `brainflow` wheel bundles Linux `.so`s including +`libMuseLib.so` and `libBrainFlowBluetooth.so`, so a BLE Muse session needs only +`pip install brainflow`, no source build. The `DYLD_LIBRARY_PATH` block at the top of that +script is guarded by `os.path.isdir` and skips harmlessly off-macOS. Don't route a +validation session to a Mac on the strength of the line above; only the Swift/Core ML/MLX +half needs one. + ## Stack - Swift 6.0, macOS 14+, SwiftPM (no Xcode project needed for the default build) - Deps: `mlx-swift` (≥0.21.2), `mlx-swift-examples` (≥2.21.0), `swift-transformers` (≥0.1.20). **Linked only into `BCILLM`** — single MLX runtime in the linked binary. diff --git a/Scripts/evaluate-imagined-signal.py b/Scripts/evaluate-imagined-signal.py index 5bed12c..5ec383b 100755 --- a/Scripts/evaluate-imagined-signal.py +++ b/Scripts/evaluate-imagined-signal.py @@ -45,7 +45,7 @@ import pandas as pd from scipy import signal from sklearn.metrics import balanced_accuracy_score, confusion_matrix -from sklearn.model_selection import StratifiedKFold +from sklearn.model_selection import GroupKFold, StratifiedKFold from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC @@ -229,29 +229,61 @@ def trial_features(trial: Trial) -> np.ndarray: return np.array(feats, dtype=np.float64) -def evaluate(trials: list[Trial], folds: int, seed: int) -> dict: - X = np.vstack([trial_features(t) for t in trials]) - y = np.array([t.target for t in trials]) - classes, counts = np.unique(y, return_counts=True) - class_counts = dict(zip(classes.tolist(), counts.tolist())) +def time_blocks(trials: list[Trial], n_blocks: int) -> np.ndarray: + """Contiguous acquisition-time blocks, used as CV groups. + + Trials arrive in acquisition order within a session. Grouping by contiguous + runs — rather than shuffling — is what keeps a fold's test trials from being + temporally neighboured by their own training data. + """ + order = np.lexsort(([t.trial_index for t in trials], + [t.session_id for t in trials])) + groups = np.empty(len(trials), dtype=int) + groups[order] = np.floor(np.arange(len(trials)) * n_blocks / len(trials)).astype(int) + return groups - skf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed) + +def _cv_score(X, y, splitter, split_args) -> tuple[float, list[float], list, list]: fold_scores: list[float] = [] - all_true: list[str] = [] - all_pred: list[str] = [] - for fold_idx, (train_idx, test_idx) in enumerate(skf.split(X, y)): + all_true: list = [] + all_pred: list = [] + for train_idx, test_idx in splitter.split(*split_args): pipe = Pipeline([ ("scaler", StandardScaler()), ("svm", LinearSVC(C=1.0, dual="auto", max_iter=5000)), ]) pipe.fit(X[train_idx], y[train_idx]) pred = pipe.predict(X[test_idx]) - score = balanced_accuracy_score(y[test_idx], pred) - fold_scores.append(score) + fold_scores.append(balanced_accuracy_score(y[test_idx], pred)) all_true.extend(y[test_idx].tolist()) all_pred.extend(pred.tolist()) + return float(np.mean(fold_scores)), fold_scores, all_true, all_pred + + +def evaluate(trials: list[Trial], folds: int, seed: int) -> dict: + X = np.vstack([trial_features(t) for t in trials]) + y = np.array([t.target for t in trials]) + classes, counts = np.unique(y, return_counts=True) + class_counts = dict(zip(classes.tolist(), counts.tolist())) + + # Blocked, not shuffled. StratifiedKFold(shuffle=True) scatters temporally + # adjacent trials across train and test, so anything drifting slowly within a + # session — impedance, electrode temperature, alertness, headband slip — is + # partially learnable rather than held out, and the classifier can score above + # chance without decoding imagined speech at all. Whole contiguous runs are + # held out together instead. Same defect, and same fix, as the eyes-open/closed + # block confound in validate-muse-physiology.py; see + # docs/reviews/time-leakage-2026-08-06.md. + groups = time_blocks(trials, folds) + gkf = GroupKFold(n_splits=folds) + mean, fold_scores, all_true, all_pred = _cv_score(X, y, gkf, (X, y, groups)) + + # Time-index control on the SAME folds: trial position as the only feature. + # A gate that does not check this cannot tell decoding from drift — it is the + # same instrument as the alpha time-index baseline, pointed at the same risk. + t_index = np.arange(len(trials), dtype=float).reshape(-1, 1) + time_mean, _, _, _ = _cv_score(t_index, y, gkf, (t_index, y, groups)) - mean = float(np.mean(fold_scores)) sd = float(np.std(fold_scores, ddof=1)) if len(fold_scores) > 1 else 0.0 # Wilson 95% CI on the pooled accuracy. n = len(all_true) @@ -267,6 +299,9 @@ def evaluate(trials: list[Trial], folds: int, seed: int) -> dict: return { "balanced_accuracy_mean": mean, + "time_index_balanced_accuracy": time_mean, + "beats_time_index": bool(mean > time_mean), + "cv": f"GroupKFold({folds}) on contiguous acquisition blocks", "balanced_accuracy_sd": sd, "fold_scores": fold_scores, "wilson_ci_95": (ci_low, ci_high), @@ -291,7 +326,7 @@ def print_report(sessions: list[Path], trials: list[Trial], result: dict, args) for cls, n in sorted(result["class_counts"].items()): print(f" {cls:>8s}: {n}") print(f"Feature dim: {result['n_features']} ({len(BANDS)} bands × per-channel log-power)") - print(f"CV folds: {args.folds} (stratified, seed={args.seed})") + print(f"CV folds: {args.folds} ({result['cv']})") print() print(f"Per-fold balanced accuracy:") for i, s in enumerate(result["fold_scores"]): @@ -312,16 +347,23 @@ def print_report(sessions: list[Path], trials: list[Trial], result: dict, args) # Gate evaluation. min_count = min(result["class_counts"].values()) if result["class_counts"] else 0 bacc = result["balanced_accuracy_mean"] + time_bacc = result["time_index_balanced_accuracy"] bacc_ok = bacc >= GATE_BALANCED_ACCURACY count_ok = min_count >= GATE_MIN_PER_CLASS + time_ok = result["beats_time_index"] print(f"Pre-registration gate:") print(f" balanced_accuracy ≥ {GATE_BALANCED_ACCURACY:.2f}: " f"{bacc:.4f} {'✓' if bacc_ok else '✗'}") print(f" min trials/class ≥ {GATE_MIN_PER_CLASS}: " f"{min_count} {'✓' if count_ok else '✗'}") + print(f" beats time-index baseline: " + f"{bacc:.4f} vs {time_bacc:.4f} {'✓' if time_ok else '✗'}") + if not time_ok: + print(" ** trial position predicts the label as well as the EEG does.") + print(" Whatever this is measuring, it is not imagined speech.") print() - if bacc_ok and count_ok: + if bacc_ok and count_ok and time_ok: print("[PRE-REGISTRATION GATE PASSED]") return True else: @@ -329,7 +371,79 @@ def print_report(sessions: list[Path], trials: list[Trial], result: dict, args) return False +def _drift_trials(n=160, fs=256.0, run_len=4, seed=0) -> list[Trial]: + """Trials whose only structure is drift + the run structure of a shuffled order. + + This is the real leak, not a caricature of it. Trial order is a 50/50 shuffle + (as ImaginedSpeechProtocol.buildTrialOrder produces), which by chance yields + RUNS of same-class trials. Amplitude drifts monotonically with acquisition + position and carries no class information whatsoever. + + Within one run, the drift value is nearly constant and identifies that run — + and the run identifies the class. So a shuffled split, which puts a trial's + immediate neighbours in the training set, can read the label off the drift. + A blocked split holds whole runs out together and cannot. + """ + rng = np.random.default_rng(seed) + labels: list[str] = [] + while len(labels) < n: + lab = "yes" if len(labels) // run_len % 2 == 0 else "no" + labels.extend([lab] * run_len) + labels = labels[:n] + rng.shuffle(labels) # keeps the 50/50 balance, keeps runs by chance + trials = [] + for i, lab in enumerate(labels): + amp = 10.0 * (1.0 + 0.05 * i) # depends on POSITION, never on lab + ch = rng.normal(0.0, amp, (4, int(fs))) + trials.append(Trial(session_id="synthetic", trial_index=i, target=lab, + channels=ch, sample_rate=fs)) + return trials + + +def demo() -> int: + """Self-check, no hardware: ./evaluate-imagined-signal.py --self-check + + NOTE what this does and does not assert. It asserts the gate rejects data with + no class signal. It does NOT assert that the old shuffled-fold evaluator + inflated the score, because that could not be demonstrated — see the measured + non-result printed below and docs/reviews/time-leakage-2026-08-06.md. + """ + ok = True + for seed in range(4): + trials = _drift_trials(seed=seed) + X = np.vstack([trial_features(t) for t in trials]) + y = np.array([t.target for t in trials]) + groups = time_blocks(trials, 5) + + blocked, *_ = _cv_score(X, y, GroupKFold(n_splits=5), (X, y, groups)) + t_index = np.arange(len(trials), dtype=float).reshape(-1, 1) + time_only, *_ = _cv_score(t_index, y, GroupKFold(n_splits=5), (t_index, y, groups)) + leaky, *_ = _cv_score(X, y, StratifiedKFold(5, shuffle=True, random_state=1337), (X, y)) + + # The property that matters: no class signal in, no pass out. + assert not (blocked >= GATE_BALANCED_ACCURACY and blocked > time_only), ( + f"seed {seed}: drift-only data passed the gate — " + f"blocked={blocked:.4f} time-index={time_only:.4f}") + if leaky >= GATE_BALANCED_ACCURACY: + ok = False + print(f" seed {seed}: shuffled CV DID clear the gate ({leaky:.4f}) — " + "the leak reproduces after all; update the review doc") + print(f" seed {seed}: blocked={blocked:.4f} time-index={time_only:.4f} " + f"shuffled={leaky:.4f}") + + print("self-check ok — drift-only data is rejected by the gate.") + if ok: + print("Measured non-result: shuffled CV did NOT clear the 0.65 gate on drift-only " + "data either. LinearSVC on 16 global band-power features has too little " + "capacity to exploit fold-local structure, so no inflation was demonstrated. " + "GroupKFold is kept as the conservative design, not as a fix for a measured " + "defect.") + return 0 + + def main() -> int: + if "--self-check" in sys.argv: + return demo() parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("paths", nargs="*", type=Path, diff --git a/docs/reviews/time-leakage-2026-08-06.md b/docs/reviews/time-leakage-2026-08-06.md index 251cb84..6a4846d 100644 --- a/docs/reviews/time-leakage-2026-08-06.md +++ b/docs/reviews/time-leakage-2026-08-06.md @@ -1,8 +1,10 @@ # Time leakage in two EEG evaluations — 2026-08-06 -Two places where a measurement cannot separate signal from elapsed time. One is fixed in -this change; the other is documented here and still open. They are the same disease, and -the open one is the more urgent because it is **currently gating a decision**. +Two places where a design cannot separate signal from elapsed time. One was a real defect, +measured and fixed. The other looked like the same disease and did not survive measurement. + +That asymmetry is the point of the document. Both were argued from the same reasoning; only +one of them reproduced when a synthetic check was pointed at it. ## 1. Muse physiological validation — FIXED @@ -28,7 +30,12 @@ missed. The 2026-07-10 results (TP9 2.98×, TP10 3.88×) were collected under the old protocol and are now annotated in `docs/Validation.md` as provisional pending re-collection. -## 2. Imagined-speech pre-registration gate — OPEN +## 2. Imagined-speech CV — CHANGED, but the leak did not reproduce + +**Correction to the first draft of this document.** It stated that the 0.65 gate is +"inflated by an unknown amount" and that a pre-registered threshold evaluated with a +leaky estimator is void. The first half of that is not supported by measurement, and +this section is rewritten accordingly. `Scripts/evaluate-imagined-signal.py:238`: @@ -42,34 +49,62 @@ data. Anything that drifts slowly within a session — impedance, electrode temp alertness, headband slip — is then partially learnable rather than held out, and a classifier can score above chance without decoding anything about imagined speech. -**Why this is the urgent one.** It feeds the pre-registration gate at `:10`: - -``` -PASS iff balanced_accuracy >= 0.65 AND min(class_count) >= 50 -``` - -That threshold was pinned in advance precisely so Track B could not be promoted on a soft -judgement (see `CLAUDE.md`, Track B pre-registration gate). But the number being compared -against it is inflated by an unknown amount. A pre-registered threshold evaluated with a -leaky estimator is not a pre-registered threshold. **Any balanced accuracy reported by -this script today is provisional and must not be used to promote Track B past -experimental.** - -### Fix owed - -- Replace the shuffled `StratifiedKFold` with block-aware splitting — `GroupKFold` (or - `StratifiedGroupKFold`) with groups derived from acquisition-time blocks, so whole - contiguous runs of trials are held out together rather than interleaved. -- Add a **time-index control on the same folds**: train and score the identical pipeline - on trial index alone. Report both numbers; gate on the label-based score exceeding the - time-only score, exactly as the alpha gate now does. This is the piece that converts - "we think the CV is clean" into something the script checks. -- Trial order in `Sources/BCIEEG/Calibration/ImaginedSpeechProtocol.swift:199-208` is - already a seeded shuffle, not strict alternation, and the seed is recorded to - `metadata.json` — so the acquisition side is sound and only the evaluator needs work. - -Not fixed in this change because it was scoped to the Muse validation protocol. Recorded -here so it does not survive only as a line in a plan's exclusions section. +### What was measured + +Synthetic trials with **no class signal at all**: amplitude drifts monotonically with +acquisition position, labels are a 50/50 shuffle (the order +`ImaginedSpeechProtocol.buildTrialOrder` actually produces), which by chance yields runs +of same-class trials. If shuffled folds leak, this is the data that should show it — a +trial's immediate neighbours sit in the training set at nearly the same drift level. + +Four seeds, `--self-check`: + +| seed | blocked (GroupKFold) | time-index only | **shuffled (old design)** | +| --- | --- | --- | --- | +| 0 | 0.4688 | 0.5250 | 0.4375 | +| 1 | 0.4914 | 0.5000 | 0.4500 | +| 2 | 0.4571 | 0.5000 | 0.5000 | +| 3 | 0.4912 | 0.5000 | 0.5750 | + +**The shuffled evaluator did not clear the 0.65 gate on drift-only data.** It sat at +chance, like the blocked one. The reason is capacity: `LinearSVC` on 16 global band-power +features cannot exploit fold-local structure — it has no way to memorise a +drift-level → label association for interleaved runs. Shuffled-CV leakage is real for +high-capacity estimators; it was not demonstrated for this one. + +A second construction, with labels deliberately correlated with acquisition position +(long same-class runs), also failed to pass: blocked 0.4656, time-index 0.5250. Blocked CV +holds out contiguous drift ranges the model has never seen, so it is inherently robust to +this failure mode. + +**So the claim that the 0.65 threshold is inflated is withdrawn.** No measurement here +supports it. The prior draft asserted it from the design smell alone — the same move as +citing 0.883, one section down. + +### What changed anyway, and why + +- `GroupKFold` on contiguous acquisition blocks replaces `StratifiedKFold(shuffle=True)`. + Kept as the **conservative design**, not as a fix for a measured defect: shuffled folds + over time-ordered trials remain bad practice, the swap costs nothing, and it forecloses + the failure mode if the estimator is ever given more capacity. +- A **time-index control on the same folds** now runs alongside: the identical pipeline + trained on trial position alone. Both numbers print, and the gate requires the EEG score + to exceed the time-only score. On the evidence above this is currently redundant with + blocked CV — it is cheap insurance, and it makes the check explicit rather than implicit + in the splitter choice. +- `--self-check` asserts only what reproduces: drift-only data does not pass the gate. It + prints the shuffled number every run, and says so loudly if the leak ever *does* appear, + so this non-result is re-tested rather than remembered. + +Trial order in `Sources/BCIEEG/Calibration/ImaginedSpeechProtocol.swift:199-208` is a +seeded shuffle with the seed recorded to `metadata.json`; the acquisition side was already +sound. + +### What remains true + +Any balanced accuracy this script reports is still from **zero real sessions** — Track B +has no collected corpus. The gate has never been evaluated against data. That, not +leakage, is what stands between Track B and a defensible result. ## Note on provenance @@ -80,5 +115,9 @@ as prose and was carried forward as established fact, load-bearing for a design The nearest values on disk (`Scripts/dream_extraction.py:335`, rho 0.8827/0.8857) are a different metric on a different analysis, already annotated there as small-n artifacts. -Both fixes above stand on defects visible in the source, and the first is demonstrated by +Both changes above stand on defects visible in the source, and the first is demonstrated by a runnable regression. Neither needs 0.883, and it should not be cited again. + +The §2 correction is the same error caught one step earlier: "the gate is inflated by an +unknown amount" was asserted from a design smell, in a document written to warn against +exactly that. It was withdrawn because the check was run, and the check disagreed. From 026b1594c2472e164f3891769e4ad2d95b844b5b Mon Sep 17 00:00:00 2001 From: aurascoper Date: Thu, 6 Aug 2026 11:39:43 -0500 Subject: [PATCH 04/13] research(eeg): preregister TP10 floor before collection --- Scripts/validate-muse-physiology.py | 370 ++++++++++++++++-- docs/Validation.md | 280 ++++++++++++- docs/research/README.md | 1 + ...es-open-closed-step0-preregistration_v1.md | 240 ++++++++++++ 4 files changed, 845 insertions(+), 46 deletions(-) create mode 100644 docs/research/eyes-open-closed-step0-preregistration_v1.md diff --git a/Scripts/validate-muse-physiology.py b/Scripts/validate-muse-physiology.py index 45d1f25..df93c98 100755 --- a/Scripts/validate-muse-physiology.py +++ b/Scripts/validate-muse-physiology.py @@ -52,6 +52,7 @@ import json import signal import datetime +import argparse import numpy as np # Set up BrainFlow before import @@ -86,7 +87,13 @@ # analyze() is for. The two are not redundant — this constant removes the bulk, # that gate measures what curvature left behind. BLOCK_SECONDS = 15.0 # 4 x 15 s = same 60 s of alpha data -ALPHA_BLOCK_ORDER = ['open', 'closed', 'closed', 'open'] +BLOCK_ORDERS = { + 'ABBA': ['open', 'closed', 'closed', 'open'], + 'BAAB': ['closed', 'open', 'open', 'closed'], +} +# Synthetic controls remain pinned to ABBA. Live acquisition passes its selected +# order explicitly so alternating sessions never changes the fixtures. +ALPHA_BLOCK_ORDER = BLOCK_ORDERS['ABBA'] # Occipital alpha takes ~1-2 s to rise after eye closure. Including the build-up # biases closed blocks downward and makes the ratio sensitive to block length. @@ -113,6 +120,8 @@ HEAD_TURN_UV = 30.0 # slow turns are 30-80 µV; jerky is 100+ CLENCH_BETA_RATIO = 2.0 # true EMG bursts are broadband >50 Hz, but 13-30 should rise CLENCH_BROADBAND_RATIO = 1.5 # 30-100 Hz broadband rise; EMG is broadband, single-band tests miss it +CONTACT_RMS_MIN_UV = 2.0 +CONTACT_RMS_MAX_UV = 200.0 # The condition ratio must also beat the drift the time-index baseline measures. # A multiplier, not a bare `>`, because the residual ABBA leaves behind is @@ -120,14 +129,74 @@ # sessions can say how noisy the estimate is. This is the calibration knob. TIME_BASELINE_MARGIN = 1.0 -# 80% of expected. Derives from BLOCK_SECONDS, NOT the old 30 s segment length: -# pinning it to a stale longer duration would leave the check 2x loose and it -# would pass on every truncated block it was written to catch. -MIN_VALID_SAMPLES = BLOCK_SECONDS * SAMPLE_RATE * 0.8 +# Temporal permutation baseline. Ten seeds matches the paper's protocol. The +# 3x collapse bound is conservative: theory gives B/4, roughly 11-32x for the +# analysis bandwidths used here. +SHUFFLE_SEEDS = 10 +SHUFFLE_COLLAPSE_FACTOR = 3.0 + +# Require 80% of each segment's expected samples. The duration must remain +# segment-specific: alpha, blink, clench, and turn intentionally differ. +MIN_VALID_FRACTION = 0.8 # --- Utilities ------------------------------------------------------------- +def is_short_segment(n_samples, duration): + return n_samples < duration * SAMPLE_RATE * MIN_VALID_FRACTION + + +def classify_contact(rms): + saturated = [ch for ch in CHANNEL_NAMES + if np.isfinite(rms[ch]) and rms[ch] > CONTACT_RMS_MAX_UV] + dead = [ch for ch in CHANNEL_NAMES + if not np.isfinite(rms[ch]) or rms[ch] < CONTACT_RMS_MIN_UV] + healthy = [ch for ch in CHANNEL_NAMES + if CONTACT_RMS_MIN_UV <= rms[ch] <= CONTACT_RMS_MAX_UV] + return healthy, saturated, dead + + +def contact_check_record(rms): + healthy, saturated, dead = classify_contact(rms) + return { + 'rms_uv': { + name: float(rms[name]) if np.isfinite(rms[name]) else None + for name in CHANNEL_NAMES + }, + 'healthy': healthy, + 'saturated': saturated, + 'dead': dead, + 'passed': not saturated and not dead, + } + + +def alpha_block_contact_records(alpha_blocks, block_order): + records = [] + for block_index, (block, label) in enumerate( + zip(alpha_blocks, block_order), start=1): + rms = { + name: float(np.sqrt(np.mean(block[ch_idx, :].astype(np.float64) ** 2))) + for name, ch_idx in zip(CHANNEL_NAMES, EEG_CHANNELS) + } + record = contact_check_record(rms) + record.update(block_index=block_index, label=label) + records.append(record) + return records + + +def new_contact_preflight(): + return { + 'status': 'not_run_noninteractive', + 'override_used': False, + 'classification_thresholds_uv': { + 'minimum_inclusive': CONTACT_RMS_MIN_UV, + 'maximum_inclusive': CONTACT_RMS_MAX_UV, + }, + 'checks': [], + 'final_check': None, + } + + def bandpower(signal_1d, fs, band): """Welch-like simple periodogram power in band (Hz^2 * count).""" if len(signal_1d) < int(fs): @@ -186,9 +255,10 @@ def ascii_spectrogram(signal_1d, fs, title="", width=60, height=14, fmax=40): # --- Recording ------------------------------------------------------------ class Recorder: - def __init__(self): + def __init__(self, require_segment_ack=False): self.board = None self.started_at = None + self.require_segment_ack = require_segment_ack # Cue onset is logged separately from block start. Without both, the 2 s # edge discard is a magic constant no later reader can audit: "user was # told to close their eyes" and "samples began" are 3+ seconds apart. @@ -202,7 +272,10 @@ def connect(self): # architecturally identical. Change BoardIds.MUSE_S_BOARD -> MUSE_2_BOARD # when running this script on a Muse 2. self.board = BoardShim(BoardIds.MUSE_S_BOARD, params) - BoardShim.enable_dev_board_logger() + if os.environ.get("NC_BRAINFLOW_DEV_LOG", "1") == "0": + BoardShim.disable_board_logger() + else: + BoardShim.enable_dev_board_logger() print("Scanning for Muse S (board 39)...") self.board.prepare_session() print(f"Connected. ID: {self.board.get_board_id()}") @@ -215,9 +288,19 @@ def connect(self): def segment(self, duration, label, prompt): """Record one segment with a real-time prompt to the user.""" cue_unix = time.time() - print(f"\n>>> {label}: {prompt}") + print("\a\n" + "=" * 60) + print(f">>> {label}: {prompt}") + print("=" * 60, flush=True) + if self.require_segment_ack: + try: + input("Adopt that state now, then press ENTER to start the countdown...") + except EOFError as exc: + raise RuntimeError( + "Interactive segment confirmation requires a TTY; " + "use NC_VALIDATE_NONINTERACTIVE=1 only for attended automation" + ) from exc for remaining in [3, 2, 1]: - print(f" starting in {remaining}...") + print(f" starting in {remaining}...", flush=True) time.sleep(1.0) n_samples = int(duration * SAMPLE_RATE) # Drain current buffer @@ -236,10 +319,23 @@ def segment(self, duration, label, prompt): "cue_unix": cue_unix, "block_start_unix": block_start_unix, "cue_to_start_s": block_start_unix - cue_unix, "duration_s": duration, "n_samples": int(data.shape[1]), - "short_block": data.shape[1] < MIN_VALID_SAMPLES, + "short_block": is_short_segment(data.shape[1], duration), }) return data + def contact_snapshot(self, duration=2.0): + """Measure live channel RMS before committing to the timed protocol.""" + n_samples = int(duration * SAMPLE_RATE) + self.board.get_current_board_data(n_samples) + time.sleep(duration + 0.2) + data = self.board.get_current_board_data(n_samples) + if data.shape[1] == 0: + return {name: float('nan') for name in CHANNEL_NAMES} + return { + name: float(np.sqrt(np.mean(data[ch_idx, :].astype(np.float64) ** 2))) + for name, ch_idx in zip(CHANNEL_NAMES, EEG_CHANNELS) + } + def disconnect(self): if self.board: try: @@ -266,17 +362,57 @@ def alpha_ratio(blocks_hi, blocks_lo, ch_idx): return p_hi / max(p_lo, 1e-9) -def analyze(alpha_blocks, data_blink, data_clench, data_turn): - """alpha_blocks: the four ABBA blocks in TIME ORDER, labelled by ALPHA_BLOCK_ORDER.""" +def shuffle_blocks(blocks, seed): + """Permute retained samples independently within each block and channel.""" + rng = np.random.default_rng(seed) + shuffled = [] + for block in blocks: + out = block.copy() + for ch_idx in EEG_CHANNELS: + out[ch_idx, :] = rng.permutation(block[ch_idx, :]) + # If a cross-channel measure is added, share one permutation within + # each block instead so the shuffle preserves inter-channel structure. + shuffled.append(out) + return shuffled + + +def shuffle_ratio_diagnostics(trimmed, block_order): + """Return report-only shuffled condition and time-index ratios by channel.""" + condition = {name: [] for name in CHANNEL_NAMES} + time_index = {name: [] for name in CHANNEL_NAMES} + for seed in range(SHUFFLE_SEEDS): + shuffled = shuffle_blocks(trimmed, seed) + shuffled_open = [b for b, lab in zip(shuffled, block_order) if lab == 'open'] + shuffled_closed = [b for b, lab in zip(shuffled, block_order) if lab == 'closed'] + first_half, second_half = shuffled[:2], shuffled[2:] + for name, ch_idx in zip(CHANNEL_NAMES, EEG_CHANNELS): + condition[name].append(alpha_ratio(shuffled_closed, shuffled_open, ch_idx)) + time_index[name].append(alpha_ratio(second_half, first_half, ch_idx)) + return condition, time_index + + +def analyze(alpha_blocks, data_blink, data_clench, data_turn, + contact_preflight=None, block_order=ALPHA_BLOCK_ORDER): + """Analyze four counterbalanced alpha blocks in acquisition order.""" results = {} + if contact_preflight is not None: + results['contact_preflight'] = contact_preflight + block_contact = alpha_block_contact_records(alpha_blocks, block_order) + results['alpha_block_contact'] = { + 'classification_thresholds_uv': { + 'minimum_inclusive': CONTACT_RMS_MIN_UV, + 'maximum_inclusive': CONTACT_RMS_MAX_UV, + }, + 'blocks': block_contact, + } # Channel order in BrainFlow: ch0=package_num, ch1=TP9, ch2=AF7, ch3=AF8, ch4=TP10, ch5=AUX, ch6=ts def extract(data, ch_idx): return data[ch_idx, :].astype(np.float64) trimmed = [trim_block_edge(b) for b in alpha_blocks] - open_blocks = [b for b, lab in zip(trimmed, ALPHA_BLOCK_ORDER) if lab == 'open'] - closed_blocks = [b for b, lab in zip(trimmed, ALPHA_BLOCK_ORDER) if lab == 'closed'] + open_blocks = [b for b, lab in zip(trimmed, block_order) if lab == 'open'] + closed_blocks = [b for b, lab in zip(trimmed, block_order) if lab == 'closed'] # Relabelled by POSITION alone, ignoring condition. Under ABBA this split is # orthogonal to the real labels, so it measures pure drift and nothing else. first_half, second_half = trimmed[:2], trimmed[2:] @@ -284,13 +420,13 @@ def extract(data, ch_idx): # Sections 3 and 5 below want contiguous open/closed arrays; the untrimmed # concatenation is right there since they are baselines, not the contrast. data_open = np.concatenate( - [b for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'open'], axis=1) + [b for b, lab in zip(alpha_blocks, block_order) if lab == 'open'], axis=1) data_closed = np.concatenate( - [b for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'closed'], axis=1) + [b for b, lab in zip(alpha_blocks, block_order) if lab == 'closed'], axis=1) # 1. Alpha power ratio eyes-closed / eyes-open, per channel, against drift print("\n--- 1. Alpha power (8-13 Hz) per channel ---") - print(f" blocks: {' '.join(ALPHA_BLOCK_ORDER)} @ {BLOCK_SECONDS:.0f}s, " + print(f" blocks: {' '.join(block_order)} @ {BLOCK_SECONDS:.0f}s, " f"first {BLOCK_EDGE_DISCARD_S:.0f}s of each discarded") alpha_ratios = {} time_ratios = {} @@ -317,6 +453,13 @@ def extract(data, ch_idx): print(" ** alpha ratio cleared 1.5x but did NOT beat the time-index baseline.") print(" A drift across the session explains it as well as eye closure does.") + shuffled_condition, shuffled_time = shuffle_ratio_diagnostics(trimmed, block_order) + results['alpha_shuffle_seeds'] = SHUFFLE_SEEDS + results['alpha_shuffle_collapse_factor'] = SHUFFLE_COLLAPSE_FACTOR + results['alpha_shuffle_condition_ratios'] = shuffled_condition + results['alpha_shuffle_time_index_ratios'] = shuffled_time + results['alpha_shuffle_gate'] = 'report_only' + # 2. Blink detection: max abs value in AF7/AF8 during blink window print("\n--- 2. Blink transient detection (frontal channels) ---") blink_max_af7 = float(np.max(np.abs(extract(data_blink, 2)))) @@ -393,9 +536,7 @@ def extract(data, ch_idx): # For saturated channels we expect RMS ~ 577 µV (uniformly distributed # in [-1000, 1000]); report them as a separate diagnostic flag so a # future session can re-fit the headband. - saturated = [ch for ch in CHANNEL_NAMES if rms[ch] > 200.0] - dead = [ch for ch in CHANNEL_NAMES if rms[ch] < 2.0] - healthy = [ch for ch in CHANNEL_NAMES if 2.0 <= rms[ch] <= 200.0] + healthy, saturated, dead = classify_contact(rms) rms_ok = (len(saturated) == 0 and len(dead) == 0) results['contact_pass'] = rms_ok results['contact_saturated'] = saturated @@ -424,6 +565,39 @@ def extract(data, ch_idx): for name, ok in checks: marker = "PASS" if ok else "FAIL" print(f" [{marker}] {name}") + if contact_preflight is None: + print("\n Contact preflight: NOT RECORDED (legacy or analysis-only input)") + else: + thresholds = contact_preflight['classification_thresholds_uv'] + print(f"\n Contact preflight: {contact_preflight['status']} " + f"(override={contact_preflight['override_used']}, " + f"checks={len(contact_preflight['checks'])}, " + f"healthy={thresholds['minimum_inclusive']:.1f}-" + f"{thresholds['maximum_inclusive']:.1f} uV inclusive)") + final_check = contact_preflight['final_check'] + if final_check is not None: + for name in CHANNEL_NAMES: + state = ("healthy" if name in final_check['healthy'] else + "SATURATED" if name in final_check['saturated'] else "DEAD") + value = final_check['rms_uv'][name] + value_text = "missing" if value is None else f"{value:.1f} uV" + print(f" {name:>5}: {value_text:>10} {state}") + print("\n Per-block alpha contact:") + for block in block_contact: + states = [] + for name in CHANNEL_NAMES: + state = ("healthy" if name in block['healthy'] else + "SATURATED" if name in block['saturated'] else "DEAD") + value = block['rms_uv'][name] + value_text = "missing" if value is None else f"{value:.1f}uV" + states.append(f"{name}={value_text}/{state}") + print(f" block {block['block_index']} {block['label']}: " + ", ".join(states)) + print("\n Temporal-shuffle diagnostics (report only; one ratio per seed):") + for name in CHANNEL_NAMES: + cond = ', '.join(f"{value:.2f}" for value in shuffled_condition[name]) + time_values = ', '.join(f"{value:.2f}" for value in shuffled_time[name]) + print(f" {name:>5} condition: [{cond}]") + print(f" time-index: [{time_values}]") print() if n_pass == 5: verdict = "DEFINITIVE — Muse is on your head and producing physiological EEG." @@ -445,7 +619,7 @@ def extract(data, ch_idx): # --- Main ------------------------------------------------------------------ -def main(): +def main(block_order): out_dir = os.path.expanduser("~/Developer/NeuralCompose/Recordings") os.makedirs(out_dir, exist_ok=True) timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") @@ -458,6 +632,7 @@ def main(): print("=" * 60) print() print("PROTOCOL") + print(f" Alpha block order: {' '.join(block_order)}") print(" Total time: ~80 s. Keep the Muse on your head the whole time.") print(" Prompted on screen for each segment.") print() @@ -479,28 +654,54 @@ def main(): return 2 print() - rec = Recorder() + rec = Recorder(require_segment_ack=( + os.environ.get("NC_VALIDATE_NONINTERACTIVE") != "1")) try: rec.connect() except Exception as e: print(f"FAILED to connect: {e}") return 2 - # Ctrl-C to abort + # Install cleanup before any interactive contact checks. def stop(*_): print("\nAborted.") rec.disconnect() sys.exit(130) signal.signal(signal.SIGINT, stop) + contact_preflight = new_contact_preflight() + if rec.require_segment_ack: + while True: + rms = rec.contact_snapshot() + check = contact_check_record(rms) + contact_preflight['checks'].append(check) + contact_preflight['final_check'] = check + print("\nLive contact snapshot:") + for name in CHANNEL_NAMES: + state = ("healthy" if name in check['healthy'] else + "SATURATED" if name in check['saturated'] else "DEAD") + print(f" {name:>5}: {rms[name]:7.1f} uV {state}") + if check['passed']: + input("All channels are in range. Press ENTER to begin the protocol...") + contact_preflight['status'] = 'passed' + break + response = input( + "Reseat the flagged contacts, then press ENTER to recheck; " + "type RUN to continue anyway: ") + if response.strip().lower() == "run": + print("Proceeding with an explicit contact-quality override.") + contact_preflight['status'] = 'overridden' + contact_preflight['override_used'] = True + break + prompts = { 'open': "Open eyes. Look at a fixed point. Relax face/jaw.", 'closed': "Close eyes gently. Same relaxation. Don't squint.", } alpha_blocks = [] - for n, lab in enumerate(ALPHA_BLOCK_ORDER, start=1): + for n, lab in enumerate(block_order, start=1): alpha_blocks.append(rec.segment( - BLOCK_SECONDS, f"BLOCK {n}/{len(ALPHA_BLOCK_ORDER)} — EYES {lab.upper()}", + BLOCK_SECONDS, f"BLOCK {n}/{len(block_order)} — EYES {lab.upper()}", prompts[lab])) data_blink = rec.segment(SEG_BLINK, "BLINK", @@ -523,7 +724,7 @@ def stop(*_): # through verbatim, so the new labels are additive, not breaking. seen = {} seg_labels = [] - for blk, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER): + for blk, lab in zip(alpha_blocks, block_order): seen[lab] = seen.get(lab, 0) + 1 seg_labels += [f"{lab}{seen[lab]}"] * blk.shape[1] seg_labels += (['blink'] * data_blink.shape[1] + @@ -539,15 +740,17 @@ def stop(*_): f.write('\n'.join(rows) + '\n') # Analyze - results, rc = analyze(alpha_blocks, data_blink, data_clench, data_turn) + results, rc = analyze( + alpha_blocks, data_blink, data_clench, data_turn, + contact_preflight=contact_preflight, block_order=block_order) results['block_marks'] = rec.marks - results['block_order'] = ALPHA_BLOCK_ORDER + results['block_order'] = block_order # ASCII spectrograms (eyes open vs eyes closed) for visual confirmation af7_open = np.concatenate( - [b[2, :] for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'open']) + [b[2, :] for b, lab in zip(alpha_blocks, block_order) if lab == 'open']) af7_closed = np.concatenate( - [b[2, :] for b, lab in zip(alpha_blocks, ALPHA_BLOCK_ORDER) if lab == 'closed']) + [b[2, :] for b, lab in zip(alpha_blocks, block_order) if lab == 'closed']) print("\n--- 6. AF7 spectrogram: eyes open vs eyes closed ---") print(ascii_spectrogram(af7_open.astype(np.float64), SAMPLE_RATE, title="AF7 EYES OPEN (both blocks)", width=60, height=14)) @@ -592,8 +795,53 @@ def demo(): """Self-check. Runs without brainflow or hardware: python3 --self-check""" ch = EEG_CHANNELS[0] + # Segment completeness follows each segment's own duration, not the longer + # alpha-block duration. + assert not is_short_segment(int(SEG_BLINK * SAMPLE_RATE), SEG_BLINK) + assert not is_short_segment(int(SEG_CLENCH * SAMPLE_RATE), SEG_CLENCH) + assert not is_short_segment(int(SEG_TURN * SAMPLE_RATE), SEG_TURN) + assert is_short_segment(int(SEG_BLINK * SAMPLE_RATE * 0.79), SEG_BLINK) + contact_record = contact_check_record({ + 'TP9': 20.0, 'AF7': 201.0, 'AF8': 2.0, 'TP10': 1.9}) + assert contact_record == { + 'rms_uv': {'TP9': 20.0, 'AF7': 201.0, 'AF8': 2.0, 'TP10': 1.9}, + 'healthy': ['TP9', 'AF8'], + 'saturated': ['AF7'], + 'dead': ['TP10'], + 'passed': False, + } + missing_record = contact_check_record({ + 'TP9': float('nan'), 'AF7': 20.0, 'AF8': 20.0, 'TP10': 20.0}) + assert missing_record['rms_uv']['TP9'] is None + assert missing_record['dead'] == ['TP9'] + json.dumps(missing_record, allow_nan=False) + preflight = new_contact_preflight() + assert preflight['status'] == 'not_run_noninteractive' + assert preflight['override_used'] is False + assert preflight['classification_thresholds_uv'] == { + 'minimum_inclusive': 2.0, + 'maximum_inclusive': 200.0, + } + assert BLOCK_ORDERS[parse_args(['--order', 'BAAB']).order] == \ + ['closed', 'open', 'open', 'closed'] + contact_blocks = [np.zeros((7, 8)) for _ in range(4)] + for block in contact_blocks: + block[1, :] = 20.0 + block[2, :] = 250.0 + block[3, :] = 1.0 + block[4, :] = 100.0 + block_records = alpha_block_contact_records(contact_blocks, BLOCK_ORDERS['BAAB']) + assert [record['label'] for record in block_records] == \ + ['closed', 'open', 'open', 'closed'] + assert block_records[0]['healthy'] == ['TP9', 'TP10'] + assert block_records[0]['saturated'] == ['AF7'] + assert block_records[0]['dead'] == ['AF8'] + # (a) Real alpha, no drift -> condition ratio high, time ratio ~1, PASSES. - b = [trim_block_edge(x) for x in _synth_blocks(alpha_gain=1.0, drift_per_block=1.0)] + # The modest gain isolates spectral structure without smuggling a near-gate + # broadband amplitude contrast into the fixture. Its d1 tightness is a + # consequence of that mechanism-focused fixture, not a tuned target. + b = [trim_block_edge(x) for x in _synth_blocks(alpha_gain=0.3, drift_per_block=1.0)] r_cond = alpha_ratio(b[1:3], [b[0], b[3]], ch) r_time = alpha_ratio(b[2:], b[:2], ch) assert r_cond >= ALPHA_RATIO_THRESHOLD, f"(a) alpha not detected: {r_cond:.2f}" @@ -621,14 +869,70 @@ def demo(): assert r_cond >= ALPHA_RATIO_THRESHOLD and r_cond > r_time * TIME_BASELINE_MARGIN, \ f"(c) real alpha lost to drift: cond={r_cond:.2f} time={r_time:.2f}" + # (d) Shuffle the exact post-trim arrays passed to bandpower(). It must + # destroy within-block spectral structure without erasing a between- + # block amplitude effect. + alpha_blocks = b + drift_blocks = [trim_block_edge(x) for x in _synth_blocks( + alpha_gain=0.0, drift_per_block=1.6)] + for seed in range(SHUFFLE_SEEDS): + shuffled_alpha = shuffle_blocks(alpha_blocks, seed) + shuffled_drift = shuffle_blocks(drift_blocks, seed) + + # (d3) Sampling is without replacement, independently per block/channel. + for original, shuffled in zip(alpha_blocks, shuffled_alpha): + for ch_idx in EEG_CHANNELS: + assert np.array_equal(np.sort(shuffled[ch_idx]), np.sort(original[ch_idx])), \ + f"(d3) seed {seed} channel {ch_idx} is not a permutation" + for original, shuffled in zip(drift_blocks, shuffled_drift): + for ch_idx in EEG_CHANNELS: + assert np.array_equal(np.sort(shuffled[ch_idx]), np.sort(original[ch_idx])), \ + f"(d3) drift seed {seed} channel {ch_idx} is not a permutation" + + for name, ch_idx in zip(CHANNEL_NAMES, EEG_CHANNELS): + true_condition = alpha_ratio( + [alpha_blocks[1], alpha_blocks[2]], + [alpha_blocks[0], alpha_blocks[3]], ch_idx) + shuffled_condition = alpha_ratio( + [shuffled_alpha[1], shuffled_alpha[2]], + [shuffled_alpha[0], shuffled_alpha[3]], ch_idx) + assert shuffled_condition - 1 < \ + (true_condition - 1) / SHUFFLE_COLLAPSE_FACTOR, \ + f"(d1) seed {seed} {name} spectral excess survived: " \ + f"true={true_condition:.2f} shuffled={shuffled_condition:.2f}" + assert shuffled_condition < ALPHA_RATIO_THRESHOLD, \ + f"(d1) seed {seed} {name} shuffled condition passed gate: " \ + f"{shuffled_condition:.2f}" + + true_time = alpha_ratio(drift_blocks[2:], drift_blocks[:2], ch_idx) + shuffled_time = alpha_ratio(shuffled_drift[2:], shuffled_drift[:2], ch_idx) + assert shuffled_time - 1 > \ + (true_time - 1) / SHUFFLE_COLLAPSE_FACTOR, \ + f"(d2) seed {seed} {name} amplitude excess collapsed: " \ + f"true={true_time:.2f} shuffled={shuffled_time:.2f}" + + # (d4) A seed identifies one exact permutation and therefore one result. + repeat_a = shuffle_blocks(alpha_blocks, 0) + repeat_b = shuffle_blocks(alpha_blocks, 0) + assert all(np.array_equal(a, b) for a, b in zip(repeat_a, repeat_b)), \ + "(d4) identical seeds produced different permutations" + print(f"self-check ok — pure drift: old protocol reports {r_old:.2f}x (PASS), " - f"new gate rejects it") + f"new gate rejects it; {SHUFFLE_SEEDS} shuffle seeds pass d1-d4") return 0 +def parse_args(argv): + parser = argparse.ArgumentParser() + parser.add_argument('--self-check', action='store_true') + parser.add_argument('--order', choices=sorted(BLOCK_ORDERS), default='ABBA') + return parser.parse_args(argv) + + if __name__ == "__main__": try: - sys.exit(demo() if "--self-check" in sys.argv else main()) + args = parse_args(sys.argv[1:]) + sys.exit(demo() if args.self_check else main(BLOCK_ORDERS[args.order])) except Exception as e: import traceback traceback.print_exc() diff --git a/docs/Validation.md b/docs/Validation.md index 8c887dc..2d7fc30 100644 --- a/docs/Validation.md +++ b/docs/Validation.md @@ -23,13 +23,14 @@ and is recorded with a segment label. | # | Condition | Duration | What the user does | Expected signature | |---|-----------|----------|-------------------|-------------------| -| 1–4 | Eyes open / closed, **ABBA** | 4 × 15 s | Open, closed, closed, open | Alpha power rises ≥ 1.5× vs eyes-open **and** beats the time-index baseline | +| 1–4 | Eyes open / closed, alternating **ABBA / BAAB** | 4 × 15 s | Alternate open-closed-closed-open with closed-open-open-closed across sessions | Alpha power rises ≥ 1.5× vs eyes-open **and** beats the time-index baseline | | 5 | Blinks | 5 s | Blink deliberately, ~5 in 5 s | Frontal transient ≥ 40 µV in AF7/AF8 | | 6 | Jaw clench | 5 s | Clench hard, release, 3 cycles | Broadband > 20 Hz energy rise ≥ 2× baseline | | 7 | Head turn | 10 s | Turn head left/right slowly | Low-frequency swing ≥ 30 µV in TP9/TP10 | -Each condition is event-tagged in the recorded CSV (`open1`, `closed1`, `closed2`, -`open2`, then `blink`/`clench`/`turn`). Total runtime ~80 s + analysis. +Each condition is event-tagged in acquisition order in the recorded CSV +(`open1`/`open2` and `closed1`/`closed2`, then `blink`/`clench`/`turn`). Total +runtime is ~80 s plus analysis. ### Why the alpha contrast is counterbalanced @@ -39,10 +40,13 @@ time: impedance settling, electrode warming, and drowsiness onset all push `alpha_closed / alpha_open` in the same direction as real alpha, and no analysis of that recording can separate them. -Four blocks in `open, closed, closed, open` order put both conditions at the same mean -position in the session (2.5), so a linear drift subtracts out of the ratio. The first -2 s of every block is discarded — occipital alpha needs ~1–2 s to rise after eye closure — -symmetrically across both conditions, so the discard is not itself a thumb on the scale. +Four blocks in either `open, closed, closed, open` or `closed, open, open, closed` +order put both conditions at the same mean position in the session (2.5), so a +linear drift subtracts out of the ratio. Alternating ABBA and BAAB reverses which +condition occupies the outer positions, flipping the curvature residual across +the session pair. The first 2 s of every block is discarded — occipital alpha +needs ~1–2 s to rise after eye closure — symmetrically across both conditions, +so the discard is not itself a thumb on the scale. ABBA cancels a *linear* trend exactly, and electrode settling is usually curved. The residual that curvature leaves behind is what the **time-index baseline** measures: the @@ -65,13 +69,254 @@ The script computes per-channel statistics and produces a pass/fail verdict: A 4/5 pass indicates a working acquisition pipeline. A 5/5 pass indicates a clean session with no false readings. -## Current Results (2026-07-10) +## Current Results (2026-08-06, BAAB replication) + +The first BAAB session reversed the condition order to closed, open, open, +closed. It entered capture after three RMS checks ended with all channels inside +the recorded inclusive 2-200 uV range. Preflight status was `passed`, +`override_used` was false, and every segment contained its full sample count. +The final preflight values were TP9 95.2, AF7 137.1, AF8 60.2, and TP10 135.4 +uV. + +| Channel | capture RMS (uV) | capture contact | condition | time-index | shuffled condition, 10 seeds | +|---|---:|---|---:|---:|---:| +| TP9 | 82.0 | healthy | 1.18x | 1.48x | 0.81-1.54x | +| AF7 | 499.4 | saturated | 1.80x | 8.39x | 0.59-1.79x | +| AF8 | 19.9 | healthy | 1.09x | 0.93x | 0.90-1.36x | +| TP10 | 86.7 | healthy | 3.26x | 1.56x | 0.80-1.35x | + +The program reported **4/5, LIKELY**: alpha, blink, jaw-clench, and head-turn +gates passed; contact failed because AF7 again degraded after preflight. The +per-block records persisted directly in the JSON localize the change: + +| Block | state | TP9 | AF7 | AF8 | TP10 | +|---:|---|---:|---:|---:|---:| +| 1 | closed | 102.8 | 260.8 saturated | 21.3 | 89.3 | +| 2 | open | 77.9 | 385.7 saturated | 20.2 | 82.8 | +| 3 | open | 85.9 | 591.7 saturated | 19.7 | 90.5 | +| 4 | closed | 96.1 | 683.6 saturated | 20.0 | 89.6 | + +**TP10 is now replicated under order reversal.** Its 3.26x BAAB condition ratio +beats the 1.56x time-index ratio, and all ten shuffled ratios collapse to +0.80-1.35x. The prior clean-preflight ABBA session reported 3.02x versus 0.73x, +with nine of ten shuffled ratios below 1.5x. Agreement across ABBA and BAAB +rules out the fixed condition-order explanation that invalidated the 2026-07-10 +measurements. This is a replicated TP10-local spectral contrast, not yet a +two-channel posterior result. + +The cross-session drift is stronger evidence than either gate alone. Time-index +reversed around 1, from 0.73x under ABBA to 1.56x under BAAB, while TP10 held at +3.02x and 3.26x. A drift-contaminated condition contrast should move with that +reversal; TP10 did not. In BAAB, the 3.26x unshuffled ratio is 2.4 times the top +of its 1.35x permutation band, with no seed reaching the 1.5x gate. + +TP9 remained healthy in every BAAB block but produced 1.18x, below its 1.48x +time-index ratio and inside the 0.81-1.54x permutation range. Together with its +1.41x clean-ABBA result, TP9 is a replicated healthy-contact negative: for these +sessions, this head, and this headband position, TP10 carries the contrast and +TP9 does not. AF7's apparent 1.80x is also rejected: the channel saturated +before block 1 and its 8.39x time-index ratio dominates the condition ratio. +AF7 has saturated in all three analyzable attended captures, so it is now a +repeated hardware/positioning failure to investigate separately from protocol +quality. + +### Collection implication + +The protocol is no longer the blocker for collecting a **one-channel TP10** +eyes-open/eyes-closed corpus: it has produced two controlled sessions with a +replicated TP10 label and preserved negative controls. It does not unlock +spatial modeling; TP9 is a replicated negative, AF7 fails contact, and AF8 is +amplitude-confounded. The fixed classifier, features, session-level split, null +arms, stopping rule, and six-session trigger are pre-registered in +[`eyes-open-closed-step0-preregistration_v1.md`](research/eyes-open-closed-step0-preregistration_v1.md). +Collection cannot resume until its analysis implementation and synthetic tests +are committed. Two sessions remain far too thin for a classifier claim. + +Evidence remains local because it contains raw EEG: + +- CSV SHA-256: `606d49436d2caa3813eb718b2692d2a9ba19576f07a32b4fd012cf65ea0a3bdf` +- JSON SHA-256: `e586ef65906f5f28470f493f96ae1223b74d0af1ee24f7c1c759efdacba92eb8` +- Session metadata SHA-256: `aa65f588242635677e46efd4345793198f2bc4348fa1fedc359beb970601e6f9` +- Power state SHA-256: `c21330ba9482c6a271eab09b588fb25415679e93e6be45087ea80e6ea9123af5` + +The GPD was on AC at 47% and charging, with the `powersave` governor and +`balanced` platform profile. + +### Prior clean-preflight ABBA session + +The next attended ABBA session entered capture only after four RMS checks ended +with all channels inside the recorded inclusive 2-200 uV range. Preflight status +was `passed`, `override_used` was false, and every segment contained its full +sample count. The final preflight values were TP9 103.7, AF7 155.8, AF8 121.5, +and TP10 68.6 uV. + +| Channel | capture RMS (uV) | capture contact | condition | time-index | shuffled condition, 10 seeds | +|---|---:|---|---:|---:|---:| +| TP9 | 120.3 | healthy | 1.41x | 0.49x | 1.08-1.83x | +| AF7 | 639.7 | saturated | 0.32x | 1.01x | 0.94-1.75x | +| AF8 | 27.5 | healthy | 0.69x | 0.62x | 0.98-1.68x | +| TP10 | 83.3 | healthy | 3.02x | 0.73x | 0.87-1.85x | + +The program reported **4/5, LIKELY**: alpha, blink, jaw-clench, and head-turn +gates passed; capture contact failed because AF7 degraded from a healthy 155.8 +uV preflight value to 639.7 uV during the timed blocks. This distinguishes a +clean initial fit from in-session contact loss rather than treating both as the +same failure. + +Post-hoc per-block RMS from the immutable CSV localizes that loss: + +| Block | state | TP9 | AF7 | AF8 | TP10 | +|---:|---|---:|---:|---:|---:| +| 1 | open | 72.0 | 479.3 saturated | 32.4 | 90.8 | +| 2 | closed | 136.2 | 765.6 saturated | 28.7 | 102.2 | +| 3 | closed | 146.0 | 767.2 saturated | 23.7 | 80.7 | +| 4 | open | 154.1 | 767.3 saturated | 21.5 | 75.2 | + +AF7 failed after the final preflight snapshot and before block 1, so none of its +alpha blocks is contact-valid. TP9 remained inside the healthy range in every +block, although its RMS rose monotonically. + +**TP10 at 3.02x is the first defensible contrast produced by this project.** Its +condition ratio rose +from 2.05x in the prior session to 3.02x, beat its 0.73x time-index ratio, and +nine of ten shuffled ratios fell below 1.5x; the remaining shuffled ratio was +1.85x, still substantially below the unshuffled result. TP9 was now seated and +usable but reached only 1.41x, so the posterior pair did **not** agree. The new +evidence supports a repeatable TP10-local contrast, not yet a two-channel +posterior alpha result. The two session magnitudes are observations, not a +variance estimate. + +Evidence remains local because it contains raw EEG: + +- CSV SHA-256: `2c0aa4b8396bc413d2652ad5966c5ac9dfd737d36acfd20de6daa4dee5fba578` +- JSON SHA-256: `2a44a8865521ff29ca46504799b4009836cacb6ed231d5c2d49a166fe067092a` +- Session metadata SHA-256: `e42ee6d8880be018e2ff5d9550108d3db5d5a18c433242d1171f4229d797c882` +- Power state SHA-256: `509866d0cd1cdc5916b4c7b8438738b605f869a284b741d9b4f2b068596724f6` +- Derived block-RMS sidecar SHA-256: `0186324caedb5434800a7343aafa3d71919f31e60a3be484815872f2d12697b6` + +The session metadata explicitly links its `110527` sidecar prefix to the +validator's `110528` artifact prefix; the one-second difference came from +independent timestamp calls before launch. The GPD was on AC at 37% and charging, +with the `powersave` governor and `balanced` platform profile. + +### Prior attended session (contact-limited) + +The first attended run of the repaired protocol completed on the GPD, based on +commit `b452015bbcddfd46cd66d8cf7575fe9ffe56d0b5` plus the uncommitted shuffle +and cue-confirmation changes. Every segment required participant acknowledgment. +All four alpha blocks contained 3,840 samples in open, closed, closed, open +order, and their cue-to-start delays were recorded separately. + +**Contact preflight: not recorded (legacy).** The live RMS gate was added after +this session, so its JSON has no `contact_preflight` object. Do not interpret +absence as a pass. The post-capture RMS values below establish that contact +failed, but cannot show whether it was bad before block 1 or degraded during +the run. + +| Channel | RMS (uV) | contact | condition | time-index | shuffled condition, 10 seeds | +|---|---:|---|---:|---:|---:| +| TP9 | 793.1 | saturated | 1.09x | 0.25x | 0.76-1.37x | +| AF7 | 793.3 | saturated | 1.41x | 0.59x | 0.70-2.01x | +| AF8 | 23.8 | healthy | 1.75x | 0.10x | 3.08-5.26x | +| TP10 | 77.4 | healthy | 2.05x | 0.27x | 1.10-1.55x | + +The program reported **3/5, LIKELY**: alpha, blink, and jaw-clench gates passed; +contact and head-turn gates failed. That verdict is not a definitive alpha +validation. + +**AF8 is the guard result.** Its 1.75x condition ratio comfortably clears the +1.5x gate and beats time-index, so every prior version of this protocol would +have accepted it as alpha. After temporal permutation the ratio rises to +3.08-5.26x. The effect is therefore a between-condition amplitude contrast, +not isolated spectral alpha. The report-only shuffle diagnostic caught a live +false positive on its first attended session. + +**TP10 is the spectral candidate.** Its 2.05x condition ratio beats time-index, +while nine of ten shuffled ratios fall below 1.5x and all are substantially +below the unshuffled result. This is weaker numerically than the historical +3.88x TP10 result, but carries stronger evidence because the historical value +faced neither time-index nor shuffle control. Different sessions, contact, and +days make the two magnitudes non-comparable. The clean-preflight follow-up above +replicated TP10 with TP9 seated; TP9 did not clear the condition gate. + +Contact is the binding constraint. TP9 and AF7 saturated, leaving only two +usable channels and only one usable posterior channel. The head-turn gate also +failed; poor contact is one plausible shared cause, although movement execution +is not ruled out. Treat this session as a floor on what the repaired protocol +can resolve, not as a final contrast estimate. Before the next run, clear hair +from TP9/TP10, lightly damp and reseat the contacts, and inspect signal quality +before starting the timed blocks. + +Evidence remains local because it contains raw EEG: + +- CSV SHA-256: `9c19cd44458180f50e4281aa7a68f02e4a4dd30de8c1ddd56b987c410199d316` +- JSON SHA-256: `c836c1a3b18c2dbf1fa6bf460867d2f02278ecae94a4e5b94a8da3c16f8194f4` +- Session metadata SHA-256: `c22222dfcea8a298e45adc40ed2e711844ddc0309b4a185a433c60147ea7852d` +- Power state SHA-256: `ed5c80f90b978cb689597070ac4cc728b68b10c65b77ab77f182f764b877082c` + +The GPD was at 34% battery, discharging, with the `powersave` governor and +`balanced` platform profile. BrainFlow development logging was disabled and USB +Bluetooth autosuspend remained disabled. BrainFlow still returned +`BOARD_NOT_READY_ERROR:7` on two connection attempts before the successful run. +The BLE failure is worked around, not fixed. Failure with autosuspend disabled +refutes autosuspend as the explanation for these attempts; retry is the current +bounded workaround, and deeper BLE tracing is deferred unless failures degrade. + +### Acquisition dry run + +The repaired protocol completed its first live acquisition dry run on the GPD, +based on commit `b452015bbcddfd46cd66d8cf7575fe9ffe56d0b5` plus the uncommitted +shuffle diagnostics, with ABBA labels. All four alpha blocks contained the full +3,840 samples. The CSV contains 21,248 samples plus its header. The participant +did not see the eyes-open/eyes-closed instructions and kept the same eye state, +so this run **does not exercise or validate the alpha protocol**. It demonstrates +capture and analysis only; three channels were also saturated. + +| Channel | RMS (uV) | condition | time-index | shuffled condition, 10 seeds | +|---|---:|---:|---:|---:| +| TP9 | 791.7 | 1.05x | 0.29x | 0.81-1.24x | +| AF7 | 793.5 | 0.87x | 0.42x | 0.66-1.38x | +| AF8 | 41.1 | 0.71x | 1.31x | 0.68-1.01x | +| TP10 | 308.4 | 0.67x | 0.85x | 0.60-0.99x | + +Blink passed on AF8 at 108.4 uV. Jaw clench and head turn did not pass. The +program reported **1/5, INCONCLUSIVE**, but the alpha ratios are not physiological +results because the instructed eye-state contrast was not performed. The next +session therefore required an explicit participant ready check plus visible and +audible confirmation of every eye-state transition. + +The transport result is separate and positive. With USB controller `3-5` +autosuspend disabled, `muse-ble-bridge` streamed at 256 Hz with zero drops, and +the validator subsequently completed. The successful validator run used a +temporary copy with BrainFlow development logging disabled. Logger-enabled +bridge controls also streamed successfully, so logging is **not established as +the cause** of the earlier TP9-subscribe hangs. + +Evidence remains local because it contains raw EEG: + +- CSV SHA-256: `525bf456d1067e60cd9877e4d8b9446ece5c384ee33dbfc3fc62f5533c914b06` +- JSON SHA-256: `279bd9d8ae3d885e81125d687f350728fe66493980fe385687e95c19c6ceb807` +- Session metadata SHA-256: `d855ff6e2906f058a7f8bd2e2d88eb8c4979022395966bd5b902fc625e40a8a9` +- Power state SHA-256: `32f5dc6286ed3a6ed7a76ba90c7c7b6e31f9ce2c4ab4b313625709d348a76874` + +## Historical Results (2026-07-10) > **On synthetic data containing zero alpha and pure drift, the old design reports 7.11× > against a 1.5× threshold** — passing by nearly five times the margin on a signal that is > not there. That is the regression asserted in `validate-muse-physiology.py --self-check`, > and it is the measure of how little the old protocol constrained. > +> **Temporal permutation puts the fixture's amplitude-only condition ratio as high as +> 1.444236× against that same 1.5× threshold.** The permutation is applied after the +> 2-second edge trim, independently within every block and channel. It destroys temporal +> spectral structure while preserving each block's samples and total variance exactly. +> The result is only 3.7% below the gate, so `condition >= 1.5×` by itself is a weak +> discriminator when eyes closing also changes broadband power. The self-check requires +> every shuffled real-alpha ratio to fail the gate and lose at least 3× of its excess over +> 1, while pure-drift time-index excess survives the same shuffle. Live sessions always +> report all ten shuffled ratios per channel, but shuffle is **not yet a live gate**; that +> promotion requires several real sessions to establish a threshold. +> > Every figure below was collected under that protocol: the `open → closed` ordering, in > which condition is confounded with block order. The TP9/TP10 alpha rises are large enough > to be plausible on their face, but they are **not demonstrated** until re-collected under @@ -132,13 +377,22 @@ python3 -m venv /tmp/nc-bf-py /tmp/nc-bf-py/bin/pip install brainflow # Put the Muse S on your head, hair parted under the behind-ear pads -# Then run the validation script +# Then run the validation script. Alternate ABBA and BAAB across sessions. DYLD_LIBRARY_PATH=~/Developer/brainflow/compiled \ /tmp/nc-bf-py/bin/python3 \ - ~/Developer/NeuralCompose/Scripts/validate-muse-physiology.py + ~/Developer/NeuralCompose/Scripts/validate-muse-physiology.py --order ABBA ``` -The script prompts the user through each condition with 3-second countdowns. Recorded data is written to `Recordings/muse_validation_.csv`. +After connecting, interactive runs report a live RMS contact snapshot and require +either a clean recheck or an explicit `RUN` override before the timed protocol. +The summary JSON records every preflight check, its per-channel RMS values and +separate `healthy`, `saturated`, and `dead` classifications, the final check, +whether an override was used, and the inclusive 2–200 uV classification +thresholds. The same status, thresholds, and final per-channel classes print in +the physiological summary beside the reported ratios. The script then requires +acknowledgment of each condition before its 3-second countdown. +Recorded data is written to `Recordings/muse_validation_.csv` with a +matching JSON summary. ## What is NOT Validated @@ -161,7 +415,7 @@ For a new participant or a new Muse S: - [ ] All 4 pads making skin contact (firm pressure, no hair) - [ ] Sitting in a quiet room, eyes at a fixed point - [ ] Run the protocol; check the per-channel alpha ratio and RMS -- [ ] If RMS < 5 µV on any channel, reposition the headband and re-run -- [ ] If alpha ratio < 1.5× on all channels, the Muse is not on the head correctly +- [ ] If RMS is outside 2–200 µV on any channel, reposition and recheck before capture +- [ ] Interpret alpha only when condition ≥ 1.5×, beats time-index, and the report-only shuffle diagnostic supports spectral rather than amplitude contrast The protocol is robust to one or two bad channels. Three or four bad channels means the headband is not on correctly and the recording is not valid. diff --git a/docs/research/README.md b/docs/research/README.md index 2b3889a..fe303f3 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -36,3 +36,4 @@ Design/Verification/Runtime artifact taxonomy — it contains the | [embedding-model-survey.md](embedding-model-survey.md) | 3.0 | Survey (this commit) | | [methodology-review_v1.md](methodology-review_v1.md) | 3.4/3.5 | Review (superseded by v2) | | [methodology-review_v2.md](methodology-review_v2.md) | 3.4/3.5 | Review (this commit) | +| [eyes-open-closed-step0-preregistration_v1.md](eyes-open-closed-step0-preregistration_v1.md) | EEG Step 0 | Pre-registration (frozen before post-selection session 1) | diff --git a/docs/research/eyes-open-closed-step0-preregistration_v1.md b/docs/research/eyes-open-closed-step0-preregistration_v1.md new file mode 100644 index 0000000..9a4854d --- /dev/null +++ b/docs/research/eyes-open-closed-step0-preregistration_v1.md @@ -0,0 +1,240 @@ +# Eyes-Open / Eyes-Closed Step 0 Pre-registration v1 + +- Status: **frozen before post-selection session 1** +- Frozen: 2026-08-06 +- Applies to: one-participant Muse S TP10 floor evaluation +- Selection data: excluded from fitting and evaluation +- Evaluation trigger: six eligible post-registration sessions, with no interim classifier runs + +This document fixes the Step 0 analysis before more evaluation data is +collected. It is a pre-registration, not a report. Do not retro-edit it after +the first post-registration session. Any change requires a versioned successor +and a fresh evaluation set. + +## Question and claim boundary + +Primary question: + +> Can a fixed, one-channel TP10 feature pipeline classify eyes-open versus +> eyes-closed windows out of session, while failing the corresponding time-index +> and shuffled-label null arms? + +The only promotable claim is a **single-participant, single-channel Step 0 +floor**. A pass does not establish: + +- spatial EEG decoding; +- transfer to another participant or headband; +- sleep-stage classification; +- imagined-speech decoding; +- an SSL, EEGNet, EEGPT, or foundation-model result; +- sufficiency for any encoder that depends on central or occipital coverage. + +## Disclosed channel selection + +The channel choice is post-selection, and that selection is part of the record. + +TP10 is the sole model input. It was selected after inspection of the two clean +protocol sessions below: + +| Acquisition | Order | TP10 condition | TP10 time-index | TP9 condition | Selection role | +|---|---|---:|---:|---:|---| +| `muse_validation_20260806-110528` | ABBA | 3.0164x | 0.7291x | 1.4109x | exploratory selection | +| `muse_validation_20260806-111651` | BAAB | 3.2574x | 1.5570x | 1.1805x | exploratory confirmation | + +The corresponding JSON SHA-256 values are: + +- ABBA: `2a44a8865521ff29ca46504799b4009836cacb6ed231d5c2d49a166fe067092a` +- BAAB: `e586ef65906f5f28470f493f96ae1223b74d0af1ee24f7c1c759efdacba92eb8` + +Earlier dry and contact-limited sessions were also inspected and are not +held-out data. No acquisition whose artifact timestamp is at or before +`20260806-111651` may enter model fitting, threshold selection, or evaluation. + +Other channels are fixed as follows: + +- **TP9:** negative diagnostic only. It is never a model feature and never an + acceptance input. Its per-session condition, time-index, shuffle, and contact + values are reported unchanged. +- **AF7:** excluded. It saturated in all three analyzable attended captures. +- **AF8:** excluded. A 1.75x live condition ratio survived temporal permutation + at 3.08-5.26x, identifying amplitude rather than isolated spectral contrast. + +Channel selection is now closed. Evaluation data cannot add a channel, remove +TP10, create an ensemble, or select the best channel post hoc. + +## Collection contract + +### Fixed size and order + +The evaluation set contains **six eligible post-registration sessions**. The +eligible-session order is fixed before collection: + +1. ABBA: open, closed, closed, open +2. BAAB: closed, open, open, closed +3. ABBA +4. BAAB +5. ABBA +6. BAAB + +If an attempt is ineligible, retain and hash its artifacts, record the reason, +and repeat the same scheduled order. Stop after at most **eight total attempts**. +If six eligible sessions do not exist after attempt eight, stop with +`INCONCLUSIVE_INSUFFICIENT_ELIGIBLE_SESSIONS`; do not lower the criteria or run +the classifier on fewer sessions. + +### Eligibility + +Eligibility is mechanical and cannot use alpha ratios, classifier output, or +whether a session looks promising: + +- `contact_preflight.status == "passed"`; +- `contact_preflight.override_used == false`; +- all four alpha blocks contain exactly 3,840 samples and have + `short_block == false`; +- TP10 is `healthy` in every `alpha_block_contact` record under that session's + stored inclusive RMS thresholds; +- `block_order` exactly matches the scheduled order; +- CSV, JSON, session metadata, and power-state artifacts exist and are hashed. + +TP9, AF7, and AF8 contact do not determine eligibility because they are not +model inputs. Their failures remain reportable diagnostics. No epochs or blocks +may be removed after a session passes these rules. + +### No interim model analysis + +The acquisition validator may print its pre-registered physiological and null +diagnostics because those are needed to verify capture. Do not run the Step 0 +feature pipeline, classifier, cross-validation, aggregate accuracy, or shuffled- +label analysis until the sixth eligible session is frozen. Collection does not +stop because single-session ratios rise or fall. + +Before post-registration session 1, the analysis implementation and synthetic +tests must be committed. Record that commit in the evaluation manifest. After +collection starts, code changes require a versioned successor pre-registration +and fresh sessions; they cannot be evaluated on this six-session set. + +## Fixed examples and features + +Only TP10 is read. For each of the four alpha blocks: + +1. discard the first 2.0 seconds, exactly as the acquisition validator does; +2. divide the retained 13.0 seconds into six non-overlapping 2.0-second windows; +3. discard the final 1.0-second remainder; +4. assign every window its block's eyes-open (`0`) or eyes-closed (`1`) label. + +Each eligible session therefore contributes 24 windows: 12 open and 12 closed. +No overlap, artifact rejection, amplitude clipping, channel substitution, or +window deletion is allowed. + +For each 512-sample window, compute Welch power with these fixed parameters: + +- sampling rate: 256 Hz; +- Hann window; +- `nperseg = 256`; +- `noverlap = 128`; +- constant detrending; +- density scaling. + +The feature vector, in fixed order, is: + +1. `log10(delta_power + 1e-12)`, 1-4 Hz; +2. `log10(theta_power + 1e-12)`, 4-8 Hz; +3. `log10(alpha_power + 1e-12)`, 8-13 Hz; +4. `log10(beta_power + 1e-12)`, 13-30 Hz; +5. `log10((alpha_power + 1e-12) / (power_1_30_hz + 1e-12))`. + +Band edges use `low <= frequency < high`, except 30 Hz is included in the +1-30 Hz denominator. No feature may be added, removed, transformed, or selected +using evaluation results. + +## Fixed classifier and split + +Use a scikit-learn `Pipeline` containing: + +1. `StandardScaler()` fit only on each training fold; +2. `LogisticRegression(penalty="l2", C=1.0, solver="liblinear", + class_weight=None, random_state=0, max_iter=1000)`. + +There is no hyperparameter search, calibration, early stopping, neural model, +or alternate classifier. + +Evaluation uses leave-one-session-out cross-validation over the six eligible +sessions. Every window from one session is held out together. Fit preprocessing +and the classifier on five sessions, predict the sixth, and concatenate the six +held-out prediction sets for the aggregate score. Window-level random splits +are forbidden. + +## Null arms + +All arms use the identical features, classifier, folds, and metric. + +### N1: time-index labels + +Replace the physiological label with block-position labels: blocks 1-2 are `0` +and blocks 3-4 are `1`. This is the classifier analogue of the acquisition +time-index control. Report aggregate and per-session balanced accuracy. + +### N2: shuffled block labels + +For seeds 0 through 99, use `numpy.random.default_rng(seed)` to independently +permute `[0, 0, 1, 1]` across the four whole blocks within each session. All six +windows from a block retain the same shuffled label. This preserves class +balance and within-block dependence. Re-run the full leave-one-session-out +pipeline for each seed and report the complete 100-score distribution plus its +95th percentile. + +The acquisition validator's within-block temporal-permutation ratios remain +session diagnostics. They are reported but are not substituted for N2. + +## Fixed metrics and decision + +Primary metric: **balanced accuracy** over all held-out window predictions. +Also report each held-out session's balanced accuracy and a 95% session-cluster +bootstrap interval using 10,000 resamples of the six held-out sessions with +`numpy.random.default_rng(0)`. + +The Step 0 floor is `PASS` only if every condition holds: + +1. true-label aggregate balanced accuracy is at least **0.70**; +2. at least five of six held-out sessions have balanced accuracy at least + **0.60**; +3. the session-cluster bootstrap lower bound is greater than **0.50**; +4. true-label accuracy exceeds time-index accuracy by at least **0.10**; +5. time-index accuracy is at most **0.60**; +6. true-label accuracy exceeds the shuffled-label 95th percentile by at least + **0.10**. + +Any failed condition yields `FAIL`. Fewer than six eligible sessions after the +attempt cap yields the inconclusive status defined above. There is no partial +pass and no promotion based on a favorable subset. + +## Required output and provenance + +The evaluation writes one machine-readable result containing: + +- this pre-registration path and SHA-256; +- analysis commit and dirty-worktree status; +- six included session IDs and all attempted session IDs; +- source CSV and JSON SHA-256 values; +- each session's order, stored contact thresholds, preflight status, override + flag, TP10 per-block contact classes, and power-state sidecar; +- exact package versions for Python, NumPy, SciPy, and scikit-learn; +- feature matrix shape and per-session window counts; +- aggregate and per-session true-label scores; +- time-index score; +- all 100 shuffled-label scores and their 95th percentile; +- bootstrap seed, resample count, and confidence interval; +- each acceptance condition and the final status. + +Report TP9, AF7, and AF8 protocol diagnostics beside the model result, but do +not feed them into the model or decision. + +## Failure and successor rule + +The six-session set is spent after one preregistered evaluation, whether it +passes or fails. Do not tune features, channels, thresholds, classifier, or +session inclusion on it and then report a second score as confirmatory. + +A revised analysis requires `eyes-open-closed-step0-preregistration_v2.md`, an +explicit account of what v1 taught, and a fresh post-v2 evaluation set. The v1 +file and result remain unchanged. From d7c0f9c6cd0c7e292300cd3ec3fd1ea15313a899 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 12 Aug 2026 16:59:20 -0500 Subject: [PATCH 05/13] test(dialectic): add committed conformance-fixture harness for the Rust port MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `crates/neuralcompose-hypnagogic/src/dynamics.rs` in neuralcompose-client-native is a hand port of DialecticalDynamics.swift + DialecticalCompetition.swift. A hand port of ~460 lines of scoring, tension carry-over and a tension-sharpened softmax can be internally consistent, fully unit-tested and still wrong — a transcription slip in the temperature path produces plausible output forever. So the Rust asserts against this program's output, the way band_power.rs asserts against the Python reference to 12 significant figures. That is what makes "port" a checkable claim rather than a description of intent. Committed permanently, not a throwaway: a fixture whose generator has been deleted cannot be regenerated, so a later divergence becomes unattributable — there would be no way to tell whether the Rust drifted or the Swift moved. Records the actual uniform DRAWS consumed, never a seed. Swift's and Rust's PRNGs produce different sequences from the same seed, so a seeded fixture would fail against a correct port and the "selection differs while scores match" diagnostic would fire on every run and mean nothing. Embeddings are constructed arithmetically from a fixed integer recurrence and L2-normalized in-process — no model is loaded, so the fixture tests the DYNAMICS rather than whichever embedder happened to be installed, and this builds under plain CLT with no weights, no network and no headband. 30 cases: each profile x {early turn, both centroids, near-tie under high tension, a six-point draw sweep across a bifurcation, decisive margin, three candidates, single candidate, empty competition}. NOT YET COMPILED — authored on the Linux box, which has no Swift toolchain. Expect a first-build pass before the output is trusted. Also records docs/reviews/embedding-comparability-unenforced-2026-08-12.md: a separate live defect found during the port. Embedding.cosineSimilarity(to:) guards on dimension only, so the modelID rule stated by ADR-010 and embedding_contract.md 2.7/3.3 is enforced by nothing — and its 0 sentinel is indistinguishable from a genuine orthogonal pair. Note only; the fix is a 32-call-site migration to Float?, deliberately not attempted without a compiler. Co-Authored-By: Claude Opus 5 (1M context) --- Package.swift | 15 + Sources/DialecticFixture/main.swift | 295 ++++++++++++++++++ ...ing-comparability-unenforced-2026-08-12.md | 95 ++++++ 3 files changed, 405 insertions(+) create mode 100644 Sources/DialecticFixture/main.swift create mode 100644 docs/reviews/embedding-comparability-unenforced-2026-08-12.md diff --git a/Package.swift b/Package.swift index da59154..3182fcb 100644 --- a/Package.swift +++ b/Package.swift @@ -43,6 +43,7 @@ let package = Package( .executable(name: "GenerationEval", targets: ["GenerationEval"]), .executable(name: "dialectic-smoke", targets: ["DialecticSmoke"]), .executable(name: "dialectic-session", targets: ["DialecticSession"]), + .executable(name: "dialectic-fixture", targets: ["DialecticFixture"]), ], dependencies: [ // MLX runtime + small-model utilities. Pinned conservatively; bump as @@ -263,6 +264,20 @@ let package = Package( path: "Sources/DialecticSession", swiftSettings: strictConcurrency ), + // Emits the cross-language conformance fixture that the Rust port of + // `DialecticalDynamics` asserts against (client-native + // `crates/neuralcompose-hypnagogic`). Depends on BCICore ONLY — no + // cloud, no MLX, no weights, no network — so it builds under plain CLT + // and its output depends on nothing but this repo's own math. + // + // Committed permanently, not a throwaway: a fixture whose generator has + // been deleted cannot be regenerated, so drift becomes unattributable. + .executableTarget( + name: "DialecticFixture", + dependencies: ["BCICore"], + path: "Sources/DialecticFixture", + swiftSettings: strictConcurrency + ), // ── Tests ──────────────────────────────────────────────────────── .testTarget( diff --git a/Sources/DialecticFixture/main.swift b/Sources/DialecticFixture/main.swift new file mode 100644 index 0000000..56aa1c9 --- /dev/null +++ b/Sources/DialecticFixture/main.swift @@ -0,0 +1,295 @@ +import BCICore +import Foundation + +// Emits the cross-language conformance fixture for `DialecticalDynamics`. +// +// WHY THIS EXISTS, AND WHY IT IS COMMITTED +// +// `crates/neuralcompose-hypnagogic/src/dynamics.rs` in the client-native repo +// is a hand port of `DialecticalDynamics.swift` + `DialecticalCompetition.swift`. +// A hand port of ~460 lines of scoring, tension carry-over and a +// tension-sharpened softmax can be internally consistent, fully unit-tested and +// still wrong — a transcription slip in the temperature path produces plausible +// output forever, and plausible output is what stops people looking. +// +// So the Rust asserts against THIS program's output, the way +// `band_power.rs` asserts against the Python reference to 12 significant +// figures. That is what makes "port" a checkable claim rather than a +// description of intent. +// +// This harness is COMMITTED, permanently, and is not a throwaway. A fixture +// whose generator has been deleted cannot be regenerated, and when the Swift +// dialectic moves there would be no way to tell whether the Rust drifted or the +// Swift did. Regenerating and diffing is the whole mechanism. +// +// DRAWS, NOT A SEED +// +// The fixture records the actual uniform draws consumed, never a seed. Swift's +// and Rust's PRNGs produce different sequences from the same seed, so a seeded +// fixture would fail against a *correct* port and the "selection differs while +// scores match" diagnostic would fire on every run and mean nothing. The Rust +// side replays these draws through its `ScriptedDraws` seam. +// +// EMBEDDINGS ARE FIXED, NOT GENERATED +// +// Vectors here are constructed arithmetically and L2-normalized in-process. No +// model is loaded and no embedder is called: the fixture must test the +// DYNAMICS, not whichever embedder happened to be installed. That also means +// this builds and runs under plain Command Line Tools, with no weights, no +// network and no headband. +// +// Usage: +// swift run dialectic-fixture > \ +// ../neuralcompose-client-native/crates/neuralcompose-hypnagogic/tests/fixtures/dialectic_v1.json + +// ── Deterministic, model-free embeddings ──────────────────────────────────── + +enum F { + static let modelID = "fixture-v1" + static let dimension = 8 + + /// A reproducible unit vector. Values come from a fixed integer recurrence so + /// the same index always yields the same vector on every platform and Swift + /// version — no `Hasher`, no `Double.random`, nothing whose output is allowed + /// to change between releases. + static func embedding(_ index: Int) -> Embedding { + var state = UInt64(index &* 2_654_435_761 &+ 1) + var values: [Float] = [] + values.reserveCapacity(F.dimension) + for _ in 0..> 7 + state ^= state << 17 + // Take 16 bits and centre on zero so vectors point in varied directions. + let raw = Float(Int64(state & 0xFFFF) - 0x8000) + values.append(raw / Float(0x8000)) + } + let norm = sqrtf(values.reduce(0) { $0 + $1 * $1 }) + let unit = norm > 1e-6 ? values.map { $0 / norm } : values + return Embedding( + values: unit, modelID: F.modelID, dimension: F.dimension, + version: "1", seed: 0 + ) + } + + /// Blends two fixture vectors and renormalizes — lets a case place a candidate + /// deliberately near or far from `heard` without hand-writing coordinates. + static func blend(_ a: Embedding, _ b: Embedding, _ w: Float) -> Embedding { + var values = [Float](repeating: 0, count: F.dimension) + for i in 0.. 1e-6 ? values.map { $0 / norm } : values + return Embedding( + values: unit, modelID: F.modelID, dimension: F.dimension, + version: "1", seed: 0 + ) + } + +} + +// ── JSON emission ─────────────────────────────────────────────────────────── + +/// Full `Float` precision. The Rust compares to 1e-6, but the fixture should +/// not be the thing that loses information. +func j(_ f: Float) -> String { String(format: "%.9g", f) } +func j(_ d: Double) -> String { String(format: "%.17g", d) } +func j(_ s: String) -> String { + var out = "\"" + for c in s.unicodeScalars { + switch c { + case "\"": out += "\\\"" + case "\\": out += "\\\\" + case "\n": out += "\\n" + default: out.unicodeScalars.append(c) + } + } + return out + "\"" +} +func jArray(_ values: [Float]) -> String { "[" + values.map(j).joined(separator: ",") + "]" } + +// ── Cases ─────────────────────────────────────────────────────────────────── + +/// One scored competition, with every intermediate the Rust must reproduce. +struct Case { + let name: String + /// What the profile tuning is — the Rust looks this up by id rather than + /// re-encoding the numbers, so a drifted constant fails here too. + let profile: String + let tuning: DialecticalDynamics.Tuning + let heardIndex: Int + let historyIndices: [Int] + let replyIndices: [Int] + /// `(candidateIndex, blendWeightTowardHeard, roleID)`. + let candidates: [(Int, Float, String)] + let draw: Double +} + +let profiles: [(String, DialecticalDynamics.Tuning)] = [ + ("focused", ContextProfile.focused.tuning), + ("reflective", ContextProfile.reflective.tuning), + ("contemplative", ContextProfile.contemplative.tuning), +] + +var cases: [Case] = [] + +// Every profile against the same inputs — isolates the tuning as the variable. +for (name, tuning) in profiles { + // A. Early turn: no history, no replies. Pins the neutral-0.5 path. + cases.append(Case( + name: "\(name)/early-turn-no-centroids", profile: name, tuning: tuning, + heardIndex: 1, historyIndices: [], replyIndices: [], + candidates: [(10, 0.85, "coherenceSeeking"), (11, 0.05, "displacementSeeking")], + draw: 0.5 + )) + // B. Established dialogue: both centroids present. + cases.append(Case( + name: "\(name)/with-both-centroids", profile: name, tuning: tuning, + heardIndex: 2, historyIndices: [3, 4, 5], replyIndices: [6, 7], + candidates: [(12, 0.80, "coherenceSeeking"), (13, 0.10, "displacementSeeking")], + draw: 0.42 + )) + // C. Near-tie under HIGH tension — the stalemate/silence gate, which is + // where the profiles differ most (focused resists, contemplative invites). + cases.append(Case( + name: "\(name)/near-tie-high-tension", profile: name, tuning: tuning, + heardIndex: 8, historyIndices: [20, 21], replyIndices: [22], + candidates: [(30, 0.50, "coherenceSeeking"), (31, 0.50, "displacementSeeking")], + draw: 0.5 + )) + // D. Draw sweep across a near-tie — the bifurcation. Different draws must + // select different basins, which is the one thing a seed could not pin. + for (k, draw) in [0.01, 0.25, 0.49, 0.51, 0.75, 0.99].enumerated() { + cases.append(Case( + name: "\(name)/bifurcation-draw-\(k)", profile: name, tuning: tuning, + heardIndex: 9, historyIndices: [23], replyIndices: [24], + candidates: [(40, 0.52, "coherenceSeeking"), (41, 0.48, "displacementSeeking")], + draw: draw + )) + } + // E. Decisive margin — the dynamics, not the draw, must win regardless. + cases.append(Case( + name: "\(name)/decisive-margin", profile: name, tuning: tuning, + heardIndex: 14, historyIndices: [25, 26], replyIndices: [27], + candidates: [(50, 0.98, "coherenceSeeking"), (51, 0.02, "displacementSeeking")], + draw: 0.99 + )) + // F. Three roles — the competition iterates over `[DialecticalRole]`, so a + // port that hard-coded two poles passes everything above and fails here. + cases.append(Case( + name: "\(name)/three-candidates", profile: name, tuning: tuning, + heardIndex: 15, historyIndices: [28], replyIndices: [29], + candidates: [ + (60, 0.90, "coherenceSeeking"), + (61, 0.45, "symbolic"), + (62, 0.05, "displacementSeeking"), + ], + draw: 0.7 + )) + // G. Single candidate — margin falls through to `sorted.first`, an edge the + // Swift handles unusually and a port is likely to "clean up". + cases.append(Case( + name: "\(name)/single-candidate", profile: name, tuning: tuning, + heardIndex: 16, historyIndices: [], replyIndices: [], + candidates: [(70, 0.75, "coherenceSeeking")], + draw: 0.33 + )) + // H. No candidates — resolves silent rather than trapping. + cases.append(Case( + name: "\(name)/no-candidates", profile: name, tuning: tuning, + heardIndex: 17, historyIndices: [], replyIndices: [], + candidates: [], + draw: 0.5 + )) +} + +// ── Run ───────────────────────────────────────────────────────────────────── + +var out: [String] = [] +var drawsConsumed: [Double] = [] + +for c in cases { + let heard = F.embedding(c.heardIndex) + let history = c.historyIndices.map { F.embedding($0) } + let replies = c.replyIndices.map { F.embedding($0) } + let historyCentroid = DialecticalDynamics.centroid(of: history) + let replyCentroid = DialecticalDynamics.centroid(of: replies) + + let candidates: [DialecticalCandidate] = c.candidates.map { idx, w, role in + DialecticalCandidate( + text: "candidate-\(idx)", + embedding: F.blend(F.embedding(idx), heard, w), + roleID: role + ) + } + + let scored: [ScoredCandidate] = candidates.map { cand in + let e = DialecticalDynamics.energy( + candidate: cand.embedding, heard: heard, + historyCentroid: historyCentroid, replyCentroid: replyCentroid + ) + return ScoredCandidate( + candidate: cand, energy: e, + potential: e.potential(c.tuning.weights), + roleFulfillment: 0 + ) + } + + let tension = DialecticalDynamics.tension(among: candidates.map(\.embedding)) + let tau = DialecticalDynamics.selectionTemperature(tension: tension, tuning: c.tuning) + let probs = DialecticalDynamics.probabilities( + potentials: scored.map(\.potential), tau: tau + ) + let result = DialecticalDynamics.compete( + scored: scored, tension: tension, draw: c.draw, tuning: c.tuning + ) + drawsConsumed.append(c.draw) + + let outcome: String + let spoken: String + switch result.outcome { + case let .spoke(cand): + outcome = "spoke:\(cand.roleID)"; spoken = cand.text + case let .synthesized(cand): + outcome = "synthesized:\(cand.roleID)"; spoken = cand.text + case .silent: + outcome = "silent"; spoken = "" + } + + let candidateJSON = scored.map { s in + """ + {"roleId":\(j(s.candidate.roleID)),\ + "embedding":\(jArray(s.candidate.embedding.values)),\ + "coherence":\(j(s.energy.coherence)),\ + "resonance":\(j(s.energy.resonance)),\ + "novelty":\(j(s.energy.novelty)),\ + "potential":\(j(s.potential))} + """ + }.joined(separator: ",") + + out.append(""" + {"name":\(j(c.name)),\ + "profile":\(j(c.profile)),\ + "heard":\(jArray(heard.values)),\ + "historyCentroid":\(historyCentroid.map { jArray($0.values) } ?? "null"),\ + "replyCentroid":\(replyCentroid.map { jArray($0.values) } ?? "null"),\ + "candidates":[\(candidateJSON)],\ + "tension":\(j(tension)),\ + "selectionTemperature":\(j(tau)),\ + "probabilities":\(jArray(probs)),\ + "draw":\(j(c.draw)),\ + "margin":\(j(result.margin)),\ + "decisive":\(result.decisive),\ + "outcome":\(j(outcome)),\ + "spokenText":\(j(spoken))} + """) +} + +print(""" +{"schemaId":"neuralcompose.hypnagogic.dialectic-conformance.v1",\ +"modelId":\(j(F.modelID)),\ +"dimension":\(F.dimension),\ +"note":"Generated by Sources/DialecticFixture. Draws are recorded, never seeds. Regenerate with: swift run dialectic-fixture",\ +"drawsConsumed":[\(drawsConsumed.map { j($0) }.joined(separator: ","))],\ +"cases":[\(out.joined(separator: ","))]} +""") diff --git a/docs/reviews/embedding-comparability-unenforced-2026-08-12.md b/docs/reviews/embedding-comparability-unenforced-2026-08-12.md new file mode 100644 index 0000000..1aa0d8a --- /dev/null +++ b/docs/reviews/embedding-comparability-unenforced-2026-08-12.md @@ -0,0 +1,95 @@ +# Embedding comparability is documented but unenforced (2026-08-12) + +**Status:** open defect, not yet fixed. Found while porting `DialecticalDynamics` +to Rust (`neuralcompose-client-native`, `crates/neuralcompose-hypnagogic`). + +## The defect + +`Embedding.cosineSimilarity(to:)` (`Sources/BCICore/Models/Embedding.swift`) +guards on dimension only: + +```swift +public func cosineSimilarity(to other: Embedding) -> Float { + guard values.count == other.values.count else { return 0 } + var acc: Float = 0 + for i in 0.. Float?`, `nil` for a different `modelID`, a + different dimension, or a degenerate operand. `nil` is not a failed + computation; it is the statement that no similarity exists to compute. +2. Propagate through `energy`, `tension`, `synthesisScore` as `Optional`, so + **missing** (an early turn, legitimately neutral at `0.5`) stays distinct + from **incomparable** (a defect). +3. `centroid(of:)` returns `nil` on any mismatch rather than averaging the + comparable subset. +4. The contract table in `embedding_contract.md` §2.7 should then cite the + type signature, not a doc comment. + +The Rust side already carries this and pins it with a test asserting +`Some(0.0) != None` — orthogonal-and-comparable versus incomparable — so a +future reintroduction of the sentinel names itself. + +## Not decided here + +Whether `nil` should be a trap instead. A `preconditionFailure` would be louder +and is defensible for what is arguably a programming error, but it would make a +mixed-corpus `SemanticEval` run crash rather than report, and that tool exists +precisely to compare across models. `Optional` leaves the choice with the +caller; the trap does not. From 52b79581bebcae153a7ceec8e64913f639ea847c Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 12 Aug 2026 17:04:36 -0500 Subject: [PATCH 06/13] docs(review): correct the SemanticEval reachability claim, add a third option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two corrections to the embedding-comparability note, both answerable from the Linux box after all — neither needed the Mac. 1. SemanticEval does NOT compare across models by design. The earlier draft said it did and named it the likely first caller, which would have made this a history (past reports already carrying cross-space numbers) rather than a risk. It takes a single --model flag (main.swift:12), resolves one conformer (:59), populates one embeddingByText map from it (:101-103), and stamps its report directory with that one modelID (:217). It compares models at the REPORT level, across runs. Its past outputs are not suspect and "latent" is the right word. 2. The nil-vs-trap framing was too narrow. Both options assume cross-model comparison is a similarity operation that should either return nothing or crash. property_law.rs already says otherwise: IndexEntryKey is the pair (content digest, embedding-space identity), and shares_index() is this exact question as an executable law — same index only when embedding_space_identity matches, "because mixing spaces silently poisons retrieval". PR #30 likewise treats cross-backend divergence as a conformance MEASUREMENT with its own tolerances, not a similarity with a caveat. So a caller that genuinely needs to relate two spaces wants a distinct, explicitly-declared operation, not cosineSimilarity handing back a nil. That makes nil the honest default rather than a compromise. Also records that EmbeddingProfileTerms does not exist under that name in either repo; the concept is embedding_space_identity / IndexEntryKey / shares_index, and Swift has no equivalent today. Co-Authored-By: Claude Opus 5 (1M context) --- ...ing-comparability-unenforced-2026-08-12.md | 78 +++++++++++++++---- 1 file changed, 62 insertions(+), 16 deletions(-) diff --git a/docs/reviews/embedding-comparability-unenforced-2026-08-12.md b/docs/reviews/embedding-comparability-unenforced-2026-08-12.md index 1aa0d8a..ba1889a 100644 --- a/docs/reviews/embedding-comparability-unenforced-2026-08-12.md +++ b/docs/reviews/embedding-comparability-unenforced-2026-08-12.md @@ -48,17 +48,31 @@ provenance from the first element and **silently skips** members of a differing dimension. A centroid averaged over an unannounced subset is still a plausible vector, and every similarity measured against it afterwards is plausible too. -## Reachability - -Not currently reachable in the shipped app, as far as this review can tell: one -embedder is constructed per session, so every `Embedding` in a dialectic turn -shares a `modelID`. The exposure is real but latent, and it grows the moment a -second backend exists — which ADR-010 is explicitly about, having named +## Reachability — latent, and checked rather than assumed + +Not reachable in the shipped app: one embedder is constructed per session, so +every `Embedding` in a dialectic turn shares a `modelID`. + +**`SemanticEval` was the obvious counterexample and it does not hold.** An +earlier draft of this note said it "compares across candidate models by design" +and was therefore the likely first caller to hit this. That is wrong, and the +distinction matters, because if it were true this would be a *history* — past +reports already containing cross-space numbers — rather than a risk. + +`Sources/SemanticEval/main.swift` takes a single `--model` flag +(`parseModelFlag()`, :12), resolves exactly one conformer through a `switch` +(:59), populates one `embeddingByText` map from that one embedder (:101-103), +and writes its report to a directory stamped with `result.provenance.modelID` +(:217). Every `cosineSimilarity` call in it — `pairScores` (:33), +`meanPairwiseSimilarity` (:45), the corpus/query scans (:108, :123) — reads +from that single map. + +So SemanticEval compares models **at the report level**, across runs, not by +taking a cosine between two spaces. Its past outputs are not suspect. The +exposure is genuinely latent and arrives with the first caller that holds two +embedders at once — which ADR-010 makes foreseeable, having named bge-small-en-v1.5 as the candidate *over* all-MiniLM-L6-v2 and E5-base-v2. -`Sources/SemanticEval/` compares across candidate models by design and is the -most likely first caller to hit it. - ## Blast radius 32 call sites of `cosineSimilarity(to:)` across `Sources/` and `Tests/`, @@ -86,10 +100,42 @@ The Rust side already carries this and pins it with a test asserting `Some(0.0) != None` — orthogonal-and-comparable versus incomparable — so a future reintroduction of the sentinel names itself. -## Not decided here - -Whether `nil` should be a trap instead. A `preconditionFailure` would be louder -and is defensible for what is arguably a programming error, but it would make a -mixed-corpus `SemanticEval` run crash rather than report, and that tool exists -precisely to compare across models. `Optional` leaves the choice with the -caller; the trap does not. +## Not decided here — and the question is probably not "which failure mode" + +The first two candidates were `nil` versus a `preconditionFailure`. Both assume +cross-model comparison is a *similarity* operation that should either return +nothing or crash. + +**A third option says it is not a similarity operation at all**, and the +client-native workspace has already built the vocabulary for it: + +- `crates/neuralcompose-mobile-core/src/property_law.rs:28-31` makes + `IndexEntryKey` the pair *(content digest, embedding-space identity)* — + "two records with different embedding identities are never the same entry, + however similar the text." +- `property_law.rs:66-70`, `shares_index(a, b)`, is exactly this question as an + executable law: entries belong in the same index **only** when + `embedding_space_identity` matches, because "mixing spaces silently poisons + retrieval." +- `model_pack.rs:305`, `embedding_space_identity()`, derives that identity from + model family, revision, weight and tokenizer digests and dimensions — so the + space has a name that cannot be forged, not just a `modelID` string. +- PR #30 treated cross-backend divergence as a **conformance measurement** + (`tests/embedding_agreement.rs`, `vulkan_agreement.rs`, `composed_error.rs`), + a different question with its own semantics and its own tolerances — not a + similarity with a caveat. + +So if a future caller genuinely needs to relate two spaces, it likely wants a +distinct, explicitly-declared operation that states what it means — a +conformance or agreement measurement between named spaces — rather than +borrowing `cosineSimilarity` and being handed a `nil` or a trap for its trouble. + +That reframes the decision from *which failure mode* to *which operation*, and +it makes `nil` the cheap, honest default rather than a compromise: the primitive +declines to answer a question it was never the right operation for, and the +caller that actually needs an answer asks a differently-named one. + +Note the naming: there is no `EmbeddingProfileTerms` type in either repo — +searched both `crates/` and `Sources/`. The concept lives under +`embedding_space_identity` / `IndexEntryKey` / `shares_index`, and Swift has no +equivalent at all today. From 4581cdf52a133b32ab066b22cfb8f0c2fe6bd73c Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 12 Aug 2026 17:43:14 -0500 Subject: [PATCH 07/13] =?UTF-8?q?docs(review):=20correct=20EmbeddingProfil?= =?UTF-8?q?eTerms=20location=20=E2=80=94=20third=20repo,=20not=20absent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A previous commit in this branch claimed no EmbeddingProfileTerms type existed. That was true of the two repos searched (client-native crates/, NeuralCompose Sources/) and FALSE of the workspace: it is in neural-memory-server at crates/neural-memory-domain/src/terms.rs:444. A wrong location recorded in a review doc is exactly what gets quoted later, which was the argument for fixing the SemanticEval phrasing one commit ago. The finding gets stronger, not weaker. EmbeddingProfileTerms seals model family, revision, sorted weight and tokenizer digests, dimensions, pooling, normalization and task instruction — its doc comment says the field set mirrors neuralcompose-mobile-core's embedding_space_identity (model_pack.rs:305). And it already answers the operation question outright. Its header states the backend is deliberately EXCLUDED from the identity: "A CPU run and an NPU run of the same model produce vectors in the same space or they do not, and that is a question to be measured, not asserted by stamping a different identity on them ... whether the two may share an index is what conformance decides." So the third option is not a proposal — it is the position this workspace already took and wrote down: identity declares the space, conformance measures whether two things share one. cosineSimilarity is neither, which is why a cross-space pair has no good answer there and nil is the honest one. The gap is that all of it is Rust. Swift has no counterpart to any of EmbeddingProfileTerms / embedding_space_identity / IndexEntryKey / shares_index, and its Embedding carries a bare modelID string that nothing checks. Co-Authored-By: Claude Opus 5 (1M context) --- ...ing-comparability-unenforced-2026-08-12.md | 45 +++++++++++++++++-- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/docs/reviews/embedding-comparability-unenforced-2026-08-12.md b/docs/reviews/embedding-comparability-unenforced-2026-08-12.md index ba1889a..1429761 100644 --- a/docs/reviews/embedding-comparability-unenforced-2026-08-12.md +++ b/docs/reviews/embedding-comparability-unenforced-2026-08-12.md @@ -135,7 +135,44 @@ it makes `nil` the cheap, honest default rather than a compromise: the primitive declines to answer a question it was never the right operation for, and the caller that actually needs an answer asks a differently-named one. -Note the naming: there is no `EmbeddingProfileTerms` type in either repo — -searched both `crates/` and `Sources/`. The concept lives under -`embedding_space_identity` / `IndexEntryKey` / `shares_index`, and Swift has no -equivalent at all today. +### Where the machinery actually lives + +A correction to an earlier draft of this section, which said no +`EmbeddingProfileTerms` type existed. That was true of the two repos searched +(`neuralcompose-client-native/crates/` and `NeuralCompose/Sources/`) and **false +of the workspace**: it is in a third repo, `neural-memory-server`, at +`crates/neural-memory-domain/src/terms.rs:444`. + +It is the richest form of the idea. Its own doc comment says the field set +"mirrors `neuralcompose-mobile-core`'s `embedding_space_identity` +(`model_pack.rs:305`)", and it seals: + +``` +model_family, model_revision, weight_sha256 (sorted), tokenizer_sha256 (sorted), +dimensions, pooling, normalization, task_instruction +``` + +— "change any of them and the vectors mean something else, however similar the +text." Digests are sorted before sealing because shard listing order is noise. + +**And it settles the operation question outright**, in a passage worth quoting +rather than paraphrasing: + +> **The backend is absent, and that is the point.** A CPU run and an NPU run of +> the same model produce vectors in the same space or they do not, and that is a +> question to be *measured*, not asserted by stamping a different identity on +> them. Putting the backend here would fork the space by declaration and make +> the measurement unaskable. Where the vector came from belongs on the runtime +> variant; whether the two may share an index is what conformance decides. + +So the third option is not a proposal. It is the position this workspace already +took, deliberately, and wrote down: **identity declares the space; conformance +measures whether two things share one.** `cosineSimilarity` is neither, which is +why handing it a cross-space pair has no good answer — and why `nil` is the +honest one. + +The gap is that all of this is Rust. Swift has no counterpart to +`EmbeddingProfileTerms`, `embedding_space_identity`, `IndexEntryKey` or +`shares_index`, and its `Embedding` carries a bare `modelID` string that nothing +checks. The enforcement machinery exists in the workspace, just not in the +language where the 32 call sites are. From 3f4afeb6df9852fa2264686dbe070b409630aaf6 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 12 Aug 2026 17:48:20 -0500 Subject: [PATCH 08/13] test(dialectic): add boundary cases the first fixture could not discriminate A mutation run against the Rust port with the original fixture left two mutants alive, both comparison operators at exact equality: sample(): d < cumulative -> d <= cumulative SURVIVED compete(): tension >= high -> tension > high SURVIVED Both are the classic boundary-condition survivor: the fixture's draws never landed exactly on a cumulative probability, and tension derived from a cosine never landed exactly on the silence bar. Killed by placing cases exactly either side of each comparison rather than by adding more ordinary cases. - tensionOverride injects tension directly, so the silence gate can be exercised at exact equality with the bar (compete already takes tension as a parameter on both sides, so this needs no new machinery). Paired with a just-under case, because the at-bar case alone would also pass against code that always fell silent. - Two IDENTICAL candidate embeddings give identical potentials, hence probabilities exactly [0.5, 0.5], with the draw exactly on that boundary. Identical embeddings also make derived tension exactly 0, keeping the silence gate out of the way so selection is the only variable. Emits tensionInjected so the Rust side knows not to re-derive tension for those cases. Co-Authored-By: Claude Opus 5 (1M context) --- Sources/DialecticFixture/main.swift | 54 ++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/Sources/DialecticFixture/main.swift b/Sources/DialecticFixture/main.swift index 56aa1c9..3e44025 100644 --- a/Sources/DialecticFixture/main.swift +++ b/Sources/DialecticFixture/main.swift @@ -123,6 +123,18 @@ struct Case { /// `(candidateIndex, blendWeightTowardHeard, roleID)`. let candidates: [(Int, Float, String)] let draw: Double + /// Injects the tension rather than deriving it from the candidate + /// embeddings. + /// + /// Needed because `compete`'s silence gate is `tension >= highTension`, and + /// a mutation of that `>=` to `>` is only observable when tension lands + /// EXACTLY on the bar. Tension derived from a cosine will never do that + /// reliably in `Float`, so a fixture built only from embeddings cannot + /// discriminate the boundary — a mutation run against the first version of + /// this file confirmed that mutant survived. `compete` already takes + /// tension as a parameter on both sides, so passing the bar exactly is + /// available and exact. + var tensionOverride: Float? = nil } let profiles: [(String, DialecticalDynamics.Tuning)] = [ @@ -201,6 +213,44 @@ for (name, tuning) in profiles { candidates: [], draw: 0.5 )) + + // ── Boundary cases ────────────────────────────────────────────────── + // Added after a mutation run showed the derived-tension cases above could + // not discriminate two comparison operators. Both mutants survived the + // first fixture; these are placed exactly either side of each comparison. + + // I. Tension EXACTLY on the silence bar, with a margin under the stalemate + // threshold. Kills `tension >= highTension` → `>`: at equality the + // correct code falls silent and the mutant speaks. + cases.append(Case( + name: "\(name)/boundary-tension-exactly-at-bar", profile: name, tuning: tuning, + heardIndex: 18, historyIndices: [], replyIndices: [], + candidates: [(80, 0.50, "coherenceSeeking"), (80, 0.50, "displacementSeeking")], + draw: 0.5, + tensionOverride: tuning.highTension + )) + // J. The same competition a clear step BELOW the bar — must speak. Without + // this companion, case I alone would also pass against code that always + // fell silent. + cases.append(Case( + name: "\(name)/boundary-tension-just-under-bar", profile: name, tuning: tuning, + heardIndex: 18, historyIndices: [], replyIndices: [], + candidates: [(80, 0.50, "coherenceSeeking"), (80, 0.50, "displacementSeeking")], + draw: 0.5, + tensionOverride: tuning.highTension - 0.01 + )) + // K. Two IDENTICAL candidate embeddings ⇒ identical potentials ⇒ + // probabilities exactly [0.5, 0.5], with the draw exactly on that + // cumulative boundary. Kills `d < cumulative` → `d <= cumulative`: + // the correct code walks past the first basin, the mutant stops in it. + // Identical embeddings also make the derived tension exactly 0, so the + // silence gate stays out of the way and selection is the only variable. + cases.append(Case( + name: "\(name)/boundary-draw-exactly-on-cumulative", profile: name, tuning: tuning, + heardIndex: 19, historyIndices: [], replyIndices: [], + candidates: [(81, 0.30, "coherenceSeeking"), (81, 0.30, "displacementSeeking")], + draw: 0.5 + )) } // ── Run ───────────────────────────────────────────────────────────────────── @@ -235,7 +285,8 @@ for c in cases { ) } - let tension = DialecticalDynamics.tension(among: candidates.map(\.embedding)) + let tension = c.tensionOverride + ?? DialecticalDynamics.tension(among: candidates.map(\.embedding)) let tau = DialecticalDynamics.selectionTemperature(tension: tension, tuning: c.tuning) let probs = DialecticalDynamics.probabilities( potentials: scored.map(\.potential), tau: tau @@ -275,6 +326,7 @@ for c in cases { "replyCentroid":\(replyCentroid.map { jArray($0.values) } ?? "null"),\ "candidates":[\(candidateJSON)],\ "tension":\(j(tension)),\ + "tensionInjected":\(c.tensionOverride != nil),\ "selectionTemperature":\(j(tau)),\ "probabilities":\(jArray(probs)),\ "draw":\(j(c.draw)),\ From e7596f968a8919dfc0e1a5934a269f091df02c6c Mon Sep 17 00:00:00 2001 From: aurascoper Date: Wed, 12 Aug 2026 18:15:10 -0500 Subject: [PATCH 09/13] docs(review): an absent value given a legitimate numeric meaning, x5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A recurring shape in BCICore, not isolated accidents: a value that is missing, unfindable or incomparable is represented by a number the same field can legitimately hold, so the failure is indistinguishable from a real reading and produces no symptom. 1. Embedding.cosineSimilarity returns 0 for incomparable operands — and 0 is a real cosine (orthogonal vectors from the SAME model return it). Detailed separately in embedding-comparability-unenforced-2026-08-12.md. 2. DialecticalDynamics.centroid silently averages the comparable subset. A subset centroid is a real vector and every later similarity against it is plausible. 3. HypnagogicDialecticLoop.swift:241, roleFulfillment: role?.objective ?? 0 — the sharpest one. roleFulfillment exists (per DialecticalCompetition.swift:88) so a later stage can notice a role that FAILED ITS BRIEF, and 0 is precisely that signal. A role-lookup miss therefore manufactures the exact reading the field exists to detect. Not currently reachable; one refactor away. 4. FeatureExtractor.swift:122-126, energies["delta"] ?? 0 — 0 is a legitimate band energy (a dead electrode), so a missing key and a flat channel are the same number downstream. 5. ProsodyWobble.swift:49-52 substitutes concrete defaults for nil, converting "let the engine choose" into a decision. Arguably deliberate. THE CODEBASE ALREADY CONTAINS THE CORRECT IDIOM. SpeechProsody.blend (SpeechSynthesizing.swift:128) averages each field only over contributors that specify it — a nil field ABSTAINS rather than voting zero, and the result is nil when nothing contributed. That is the pattern the other five should follow, so this is an inconsistency rather than an unfamiliarity. Correcting my own earlier summary, which listed the blend as a third instance of the defect: it is the counter-example. The bug there was in the RUST PORT, which had reimplemented it as a two-way lerp over non-optional fields. Swift right, port wrong; fixed in client-native 39c642a. Also records that HypnagogicDialogueLoop.chunk's punctuation-run behaviour is a latency bug rather than a cosmetic one — one ellipsis costs three utterances, three preUtteranceDelays and three subprocess spawns, over a second of dead air inside one spoken turn on the contemplative voices. None of these should be fixed only in the Rust. The dialectic's Rust half is now checked against the Swift by a committed conformance fixture, so a one-sided change surfaces as a conformance failure — the mechanism working, but it means the Swift moves first. Co-Authored-By: Claude Opus 5 (1M context) --- .../absent-as-legitimate-value-2026-08-12.md | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 docs/reviews/absent-as-legitimate-value-2026-08-12.md diff --git a/docs/reviews/absent-as-legitimate-value-2026-08-12.md b/docs/reviews/absent-as-legitimate-value-2026-08-12.md new file mode 100644 index 0000000..d1ad59a --- /dev/null +++ b/docs/reviews/absent-as-legitimate-value-2026-08-12.md @@ -0,0 +1,121 @@ +# An absent value given a numeric meaning that is also a legitimate value (2026-08-12) + +**Status:** open. Found while porting `BCICore`'s dialectic to Rust +(`neuralcompose-client-native`, `crates/neuralcompose-hypnagogic`). + +A recurring shape, not three accidents. In each case a value that is *missing*, +*unfindable* or *incomparable* is represented by a number that the same field +can legitimately hold — so the failure is indistinguishable from a real reading +and produces no symptom. + +## Instances + +### 1. `Embedding.cosineSimilarity(to:)` returns `0` for incomparable operands + +`Sources/BCICore/Models/Embedding.swift:57`. **`0` is a legitimate cosine** — +orthogonal vectors from the same model return it. Covered in full, with its own +blast radius, in +[`embedding-comparability-unenforced-2026-08-12.md`](embedding-comparability-unenforced-2026-08-12.md). + +### 2. `DialecticalDynamics.centroid(of:)` silently averages a subset + +`Sources/BCICore/Dialectic/DialecticalDynamics.swift`. Members of a differing +dimension are skipped, and the result is returned as if complete. **A subset +centroid is a real vector**, and every similarity measured against it afterwards +is plausible. Nothing reports that anything was dropped. + +### 3. `roleFulfillment: role?.objective(energy) ?? 0` + +`Sources/BCICore/Composition/HypnagogicDialecticLoop.swift:241`, and the sharpest +of the set. `roles.first { $0.id == roleID }` is a lookup that can miss; a miss +scores `0`. + +`ScoredCandidate.roleFulfillment` is documented at +`DialecticalCompetition.swift:88-92` as existing so "a later stage [can] notice a +role that failed its own brief (e.g. a displacement-seeking pass that produced +something un-novel because the model refused to diverge)". **`0` is precisely +that signal.** So a lookup failure manufactures the exact reading the field +exists to detect, and the diagnostic reports a maximally-failed role instead of +an internal inconsistency. + +Not currently reachable: `candidateTexts` is built from `roles`, so the id is +always present. It is one refactor away — a filtered role list, a duplicate id, a +role set swapped mid-turn — and the consequence is a wrong diagnostic rather than +a crash. + +### 4. `FeatureExtractor` band energies + +`Sources/BCICore/Preprocessing/FeatureExtractor.swift:122-126` — +`energies["delta"] ?? 0` and four siblings. **`0` is a legitimate band energy** +(a dead electrode). A missing dictionary key and a flat channel are the same +number downstream. Lower severity than the others, since the dictionary is built +immediately above, but the same shape. + +### 5. `ProsodyWobble` substitutes concrete defaults for `nil` + +`Sources/BCICore/Composition/ProsodyWobble.swift:49-52` — `base.rate ?? 0.5`, +`base.volume ?? 0.9`, `base.preUtteranceDelay ?? 0.1`. Here `nil` means "let the +engine choose", and the substitution silently converts that into a specific +number. Arguably deliberate — you cannot wobble an absent value — but it means a +prosody that deliberately abstained comes out of the wobble having decided. + +## The codebase already contains the correct idiom + +**`SpeechProsody.blend` gets this exactly right** +(`Sources/BCICore/Protocols/SpeechSynthesizing.swift:128-141`): each field is +averaged only over contributors that specify it, a `nil` field *abstains* rather +than voting zero, and the result is `nil` when nothing contributed. That is the +pattern the other five should follow. + +Worth being precise about this, because an earlier verbal summary of mine +mistakenly listed the blend as a third instance of the defect. It is not — it is +the counter-example. The bug there was in the Rust *port*, which had reimplemented +it as a two-way lerp over non-optional fields; the Swift was right and the port +was wrong. Corrected in client-native `39c642a`. + +So this is an inconsistency, not an unfamiliarity: the codebase knows how to do +this and does it in one place out of six. + +## Why it is worth a pass rather than a note + +The three ports that hit instances 1–3 all had to make the same decision +independently, which is the signal. In the Rust the resolution was uniform: + +- `cosine_similarity -> Option`, propagated through `energy`, `tension` and + `synthesis_score`, so **missing** (an early turn, legitimately neutral at 0.5) + stays distinct from **incomparable** (a defect); +- `centroid` refuses a mixed set rather than averaging part of one; +- `Prosody::blend` abstains, matching the Swift. + +Each is pinned by a test that asserts the two cases are *not equal* — e.g. +`Some(0.0) != None` for orthogonal-versus-incomparable — so reintroducing a +sentinel names itself. + +## Suggested handling + +Instances 1 and 3 are worth fixing; 2 is worth fixing with them since it is in +the same file as 1's main caller. 4 and 5 are worth a comment stating the +substitution is deliberate, or a fix, but neither is urgent. + +Nothing here should be fixed *only* in the Rust port. The dialectic's Rust half +is now checked against the Swift by a committed conformance fixture +(`Sources/DialecticFixture`), so a one-sided "improvement" shows up as a +conformance failure rather than as an improvement — which is the mechanism +working, but it means the Swift moves first. + +## Related, found in the same pass + +`HypnagogicDialogueLoop.chunk` emits lone-punctuation chunks for a punctuation +run: `"Wait... really?!"` → `["Wait.", ".", ".", "really?", "!"]`, because every +punctuation character closes the current chunk and only *empty* results are +dropped — `"."` is not empty. + +This is a **latency** bug rather than a cosmetic one. Each lone `"."` is its own +`speak()` call, so a single ellipsis costs three utterances, three +`preUtteranceDelay`s and (in the Linux shell) three subprocess spawns — over a +second of dead air inside one spoken turn on the contemplative voices, where +`preUtteranceDelay` is longest and ellipses are most common. In a conversational +loop, turn latency is the product. + +The Rust port pins the current behaviour rather than diverging, so this must be +fixed here first. From ad67756df986620478b353b7ea0c6990a62538e1 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Thu, 13 Aug 2026 00:25:58 -0500 Subject: [PATCH 10/13] docs(review): check FeatureExtractor's reachability instead of inheriting it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two revisions after actually tracing the code rather than filing by proximity. 1. roleFulfillment IS DIFFERENT IN KIND, and the doc now says why. Instances 1, 2, 4 and 5 are a sentinel colliding with a plausible NUMBER. This one collides with a DIAGNOSTIC: roleFulfillment exists so a later stage can spot a role that failed its brief, and 0 is that signal, so a lookup miss does not produce a suspicious zero — it produces a confident report that the displacement pole utterly failed. The failure impersonates the signal rather than hiding among legitimate values. That is the version of the argument that should convince someone who finds the other four unremarkable. 2. FEATUREEXTRACTOR IS NOT THE LIVE PATH, and the two things that made it look urgent are both false: - The Core ML classifier does NOT consume it. CoreMLIntentClassifier builds its MLMultiArray directly from the raw window (:119), channels x samples, zero-padded. FeatureExtractor's only callers are MockIntentClassifier (the stub path), JEPATransition, and one golden-recording test. - The dictionary lookup is barely breakable. Band names are hardcoded literals in the SAME private function twenty lines apart, written by a loop that always emits all five, with no config and no caller able to influence them. The `?? 0` is dead defensive code; its only fuse is a rename typo. So it drops to lowest severity — fix as tidiness, not as a defect. The sharper line in that function is a different one: :117's `n > 0 ? ... : 0` reports 0 when every channel is shorter than the lag, which is insufficient-data-as-measurement and depends on runtime values (delta at 256 Hz needs 51 samples) rather than on a literal. And it lands somewhere that matters: JEPATransition.init? takes alpha/beta/theta straight into the capture persisted for offline JEPA training, guarding only isFinite — which a spurious 0 passes. The cost is a poisoned training corpus discovered much later, not a bad live decision. Given a corpus has already been lost to a confound once, that is the reachability worth recording. Suggested handling is now ranked by what the failure costs rather than by how alarming the line looks, and keeps ProsodyWobble hedged — it is the one case where a fix would change output rather than only diagnostics. Co-Authored-By: Claude Opus 5 (1M context) --- .../absent-as-legitimate-value-2026-08-12.md | 80 +++++++++++++++++-- 1 file changed, 72 insertions(+), 8 deletions(-) diff --git a/docs/reviews/absent-as-legitimate-value-2026-08-12.md b/docs/reviews/absent-as-legitimate-value-2026-08-12.md index d1ad59a..d34a668 100644 --- a/docs/reviews/absent-as-legitimate-value-2026-08-12.md +++ b/docs/reviews/absent-as-legitimate-value-2026-08-12.md @@ -24,7 +24,7 @@ dimension are skipped, and the result is returned as if complete. **A subset centroid is a real vector**, and every similarity measured against it afterwards is plausible. Nothing reports that anything was dropped. -### 3. `roleFulfillment: role?.objective(energy) ?? 0` +### 3. `roleFulfillment: role?.objective(energy) ?? 0` — and this one is different in kind `Sources/BCICore/Composition/HypnagogicDialecticLoop.swift:241`, and the sharpest of the set. `roles.first { $0.id == roleID }` is a lookup that can miss; a miss @@ -38,18 +38,66 @@ that signal.** So a lookup failure manufactures the exact reading the field exists to detect, and the diagnostic reports a maximally-failed role instead of an internal inconsistency. +**The distinction worth keeping, because it is the version of this argument that +should convince someone who finds the other four unremarkable:** instances 1, 2, +4 and 5 are a sentinel colliding with a *plausible number*. This one collides +with a *diagnostic*. The failure does not merely hide among legitimate values — +it **impersonates the specific signal a downstream stage is watching for**. A +role-lookup miss does not produce a suspicious zero; it produces a confident +report that the displacement pole utterly failed its brief. Anything built on +that field to detect degenerate generation will fire on an internal +inconsistency and point at the model. + Not currently reachable: `candidateTexts` is built from `roles`, so the id is always present. It is one refactor away — a filtered role list, a duplicate id, a role set swapped mid-turn — and the consequence is a wrong diagnostic rather than a crash. -### 4. `FeatureExtractor` band energies +### 4. `FeatureExtractor` band energies — reachability checked, and it is *not* the live path `Sources/BCICore/Preprocessing/FeatureExtractor.swift:122-126` — `energies["delta"] ?? 0` and four siblings. **`0` is a legitimate band energy** -(a dead electrode). A missing dictionary key and a flat channel are the same -number downstream. Lower severity than the others, since the dictionary is built -immediately above, but the same shape. +(a dead electrode), so a missing dictionary key and a flat channel are the same +number downstream. + +This was worth checking rather than filing next to the others by proximity, +because electrode failure-without-saying-so is the project's active constraint. +Two questions, both answered: + +**Does the Core ML classifier consume this? No.** +`CoreMLIntentClassifier.classify(window:)` builds its `MLMultiArray` directly +from the raw window (`multiArray(from:)`, :119) — channels × samples, zero-padded +— and never touches `FeatureExtractor`. There is no wrong-input path into the +shipped classifier. `FeatureExtractor`'s only callers are +`MockIntentClassifier.swift:46` (the stub path), `JEPATransition.swift:41`, and +one golden-recording regression test. + +**Is the dictionary lookup actually breakable? Barely.** The band names are +written and read as hardcoded literals in the *same private function*, twenty +lines apart (`centers` at :103, the reads at :122-126), with a loop that always +writes all five. There is no config, no external band label, and no caller who +can influence the keys. The `?? 0` is dead defensive code. Its fuse is a rename +typo in one of the two lists — short, but local and immediately visible. + +So: **lowest severity in this set, and reachable by neither of the routes that +made it look urgent.** Fix it as tidiness (destructure the tuple list, or build +`Bands` in the loop) rather than as a defect. + +**The sharper sentinel in that same function is a different line.** At :117, +`let e = n > 0 ? Float(...) : 0` — a channel shorter than the lag is skipped +(`if ch.count <= lag { continue }`), and if *every* channel is too short the band +reports `0`. That is insufficient-data rendered as a real measurement, and unlike +the dictionary read it depends on runtime values: `lag = sampleRate / centerHz / 2`, +so delta at 256 Hz needs 51 samples. Comfortable for a 1–2 s window, but it is +the window length and sample rate — not a literal — that keep it safe. + +**Where the wrong value would actually land:** `JEPATransition.init?(window:)` +takes `alphaEnergy`/`betaEnergy`/`thetaEnergy` straight from here into the +capture persisted for offline JEPA training (ADR-006). It guards `isFinite`, +which a spurious `0` passes. So the consequence is not a bad live decision but a +**poisoned training corpus** — silently, and discovered much later. Given a +corpus has already been lost to a confound once, that is the reachability that +matters here, not the classifier. ### 5. `ProsodyWobble` substitutes concrete defaults for `nil` @@ -93,9 +141,25 @@ sentinel names itself. ## Suggested handling -Instances 1 and 3 are worth fixing; 2 is worth fixing with them since it is in -the same file as 1's main caller. 4 and 5 are worth a comment stating the -substitution is deliberate, or a fix, but neither is urgent. +Ranked by what the failure would actually cost, not by how alarming the line +looks: + +1. **`roleFulfillment` (3)** — highest. It impersonates a diagnostic rather than + hiding among plausible values, so anything built on that field to detect + degenerate generation would misattribute an internal inconsistency to the + model. Fix even though it is currently unreachable. +2. **`cosineSimilarity` (1)** and **`centroid` (2)** — fix together; they share a + file and a caller, and the Rust port has already demonstrated the resolution. +3. **`FeatureExtractor`'s `n > 0 ? … : 0` (4, second line)** — insufficient data + rendered as a measurement, on the path that feeds a *persisted* JEPA training + corpus. Worth a guard that refuses rather than reports zero. +4. **`FeatureExtractor`'s dictionary reads (4, first lines)** — tidiness only. + Not reachable; the keys are literals in one private function. +5. **`ProsodyWobble` (5)** — leave hedged. Substituting a default for "let the + engine choose" is a real semantic loss, but it is plausibly what was meant, + and it is the one case here where a fix would change *output* rather than only + diagnostics. That asymmetry is the argument for leaving it alone until someone + states the intent. Nothing here should be fixed *only* in the Rust port. The dialectic's Rust half is now checked against the Swift by a committed conformance fixture From 01681b5da9760092cbeb6ecf4e264cba4d9e4d7e Mon Sep 17 00:00:00 2001 From: aurascoper Date: Thu, 13 Aug 2026 02:08:17 -0500 Subject: [PATCH 11/13] =?UTF-8?q?docs(review):=20the=20JEPA=20corpus=20sca?= =?UTF-8?q?n=20came=20back=20empty=20=E2=80=94=20no=20captures=20exist?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An exact 0.0 band energy out of a float computation over real EEG is a measure-zero event: genuine delta power is small but never exactly zero. So whether the :117 sentinel has already poisoned the JEPA corpus is a query, not a question to reason about — any hit is either this bug or a dead channel, and both are worth finding. Ran it. THERE ARE NO CAPTURES. TransitionCaptureManager writes ~/Documents/NeuralCompose/JEPATransitions/jepa_transitions.jsonl (TransitionCaptureManager.swift:58-60) and that directory has never been created, on either machine. The app-data dir holds Calibration, EEGIntegration, InteractionLogs, Recordings, health.json and voice-profile.json, and nothing JEPA-shaped. Consistent with CLAUDE.md's own statement that there are zero logged interaction events because the capture is opt-in and off by default. That is the good version of the finding rather than the disappointing one: the corpus is empty, so the guard lands BEFORE the first capture run at zero cleanup cost and with no archaeology. It also relocates the check — reject a window whose band energies come back exactly zero at capture time, rather than scanning for them afterwards. Also records the implicit precondition that should be made explicit: :117's safety rests on window length >= lag (delta at 256 Hz needs 51 samples), which is real, load-bearing and currently unwritten. Assert it rather than rely on windows happening to be long enough. Co-Authored-By: Claude Opus 5 (1M context) --- .../absent-as-legitimate-value-2026-08-12.md | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/reviews/absent-as-legitimate-value-2026-08-12.md b/docs/reviews/absent-as-legitimate-value-2026-08-12.md index d34a668..a0939e8 100644 --- a/docs/reviews/absent-as-legitimate-value-2026-08-12.md +++ b/docs/reviews/absent-as-legitimate-value-2026-08-12.md @@ -95,9 +95,34 @@ the window length and sample rate — not a literal — that keep it safe. takes `alphaEnergy`/`betaEnergy`/`thetaEnergy` straight from here into the capture persisted for offline JEPA training (ADR-006). It guards `isFinite`, which a spurious `0` passes. So the consequence is not a bad live decision but a -**poisoned training corpus** — silently, and discovered much later. Given a -corpus has already been lost to a confound once, that is the reachability that -matters here, not the classifier. +**poisoned training corpus** — silently, and discovered much later. + +#### Checked: it has not happened, because the capture has never run + +An exact `0.0` band energy out of a float computation over real EEG is a +measure-zero event — genuine delta power is small but never exactly zero — so +existing captures can be *scanned* for it rather than reasoned about. Any hit +would be either this bug or a dead channel, and both are worth finding. + +Ran it, 2026-08-13. **There are no captures.** `~/Documents/NeuralCompose/` holds +`Calibration/`, `EEGIntegration/`, `InteractionLogs/`, `Recordings/`, +`health.json` and `voice-profile.json` — and no `JEPATransitions/` directory at +all, on either machine. `TransitionCaptureManager` writes +`~/Documents/NeuralCompose/JEPATransitions/jepa_transitions.jsonl` +(`TransitionCaptureManager.swift:58-60`) and that path has never been created, +which matches `CLAUDE.md`'s own statement that there are zero logged interaction +events because the capture is opt-in and off by default. + +That is the good version of this finding rather than the disappointing one: the +corpus is empty, so the guard can land **before** the first capture run at zero +cleanup cost, and there is no archaeology to do. It also means the check is +better placed at capture time than after: reject a window whose band energies +come back exactly zero, rather than scanning for them later. + +Pair it with making the implicit precondition explicit. The safety of :117 +rests on window length ≥ lag — real, load-bearing, and currently unwritten. +Assert it (`window.sampleCount > lag` for the lowest-frequency band) instead of +relying on windows happening to be long enough. ### 5. `ProsodyWobble` substitutes concrete defaults for `nil` From 5705082a164a212765a4796ce7aadcfec07dc84b Mon Sep 17 00:00:00 2001 From: aurascoper Date: Thu, 13 Aug 2026 06:58:16 -0500 Subject: [PATCH 12/13] test(worldmodel): pin ParticleNavigatorEnv against WorldModel/env.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Swift env had four hand-computed literals and no reference. It now replays a 260-step trajectory generated from env.py itself and matches BIT-FOR-BIT — every step, including all 11 speed-clamped ones. Three independent implementations now agree exactly on this function: the Python original, the Rust port in neuralcompose-client-native, and this. Nothing pinned it in any language until today. The predicted divergence did not appear. env.py computes the speed norm and divides in float64 while this does the whole clamp in Float, and the client repository's registration (docs/acceptance/worldmodel-demo.md, section 10, written before either test ran) named the clamped steps as where a mismatch would land if there was one. There was not; for these values the two roundings coincide. Exact equality, not a tolerance: both sides are Float, the fixture stores each value as a Float widened to Double which is lossless, and on a deterministic function a tolerance could only hide a real divergence. Verified the test can actually fail. Scaling restitution by 1.0001 in step() turns it red in 6 places; restoring the file byte-identically turns it green again. A conformance test nobody has watched fail is a guess. A missing fixture FAILS rather than skipping, the same rule the dialectic fixture holds and for the same reason. Regenerate from a neuralcompose-client-native checkout with tools/worldmodel-fixture/generate.py under the .venv-muse interpreter. Co-Authored-By: Claude Opus 5 (1M context) --- Package.swift | 3 +- .../WorldModelDemoTests/Fixtures/env_v1.json | 4187 +++++++++++++++++ ...ParticleNavigatorEnvConformanceTests.swift | 139 + 3 files changed, 4328 insertions(+), 1 deletion(-) create mode 100644 Tests/WorldModelDemoTests/Fixtures/env_v1.json create mode 100644 Tests/WorldModelDemoTests/ParticleNavigatorEnvConformanceTests.swift diff --git a/Package.swift b/Package.swift index 3182fcb..2127f38 100644 --- a/Package.swift +++ b/Package.swift @@ -336,7 +336,8 @@ let package = Package( .testTarget( name: "WorldModelDemoTests", dependencies: ["WorldModelDemo", "BCICore"], - path: "Tests/WorldModelDemoTests" + path: "Tests/WorldModelDemoTests", + resources: [.process("Fixtures")] ), .testTarget( name: "NeuralComposeAppTests", diff --git a/Tests/WorldModelDemoTests/Fixtures/env_v1.json b/Tests/WorldModelDemoTests/Fixtures/env_v1.json new file mode 100644 index 0000000..ada766f --- /dev/null +++ b/Tests/WorldModelDemoTests/Fixtures/env_v1.json @@ -0,0 +1,4187 @@ +{ + "schemaId": "neuralcompose.hypnagogic.env-conformance.v1", + "note": "Generated by tools/worldmodel-fixture/generate.py from WorldModel/env.py. Floats are float32 widened to float64 and are exact; the port is asserted bit-for-bit, not to a tolerance. speedBeforeClamp and the flags are diagnostics.", + "config": { + "arenaHalfExtent": 1.0, + "dt": 0.1, + "maxAccel": 1.0, + "maxSpeed": 2.0, + "restitution": 0.6 + }, + "initialState": [ + -0.25, + 0.4000000059604645, + 0.30000001192092896, + -0.15000000596046448 + ], + "coverage": { + "steps": 260, + "bouncedX": 11, + "bouncedY": 26, + "cornerHits": 2, + "clampedSteps": 11, + "unclampedSteps": 249 + }, + "steps": [ + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + -0.20999999344348907, + 0.39500001072883606, + 0.4000000059604645, + -0.05000000447034836 + ], + "speedBeforeClamp": 0.40311288833618164, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + -0.1599999964237213, + 0.4000000059604645, + 0.5, + 0.04999999701976776 + ], + "speedBeforeClamp": 0.5024937987327576, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + -0.09999999403953552, + 0.4150000214576721, + 0.6000000238418579, + 0.15000000596046448 + ], + "speedBeforeClamp": 0.6184658408164978, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + -0.0299999862909317, + 0.4400000274181366, + 0.7000000476837158, + 0.25 + ], + "speedBeforeClamp": 0.7433034777641296, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.05000001937150955, + 0.4750000238418579, + 0.8000000715255737, + 0.3499999940395355 + ], + "speedBeforeClamp": 0.8732125163078308, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.14000003039836884, + 0.5200000405311584, + 0.9000000953674316, + 0.44999998807907104 + ], + "speedBeforeClamp": 1.0062307119369507, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.24000003933906555, + 0.5750000476837158, + 1.0000001192092896, + 0.550000011920929 + ], + "speedBeforeClamp": 1.1412713527679443, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.3500000536441803, + 0.64000004529953, + 1.1000001430511475, + 0.6500000357627869 + ], + "speedBeforeClamp": 1.2776933908462524, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.47000008821487427, + 0.7150000333786011, + 1.2000001668930054, + 0.7500000596046448 + ], + "speedBeforeClamp": 1.4150973558425903, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6000001430511475, + 0.8000000715255737, + 1.3000001907348633, + 0.8500000834465027 + ], + "speedBeforeClamp": 1.55322265625, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.7400001883506775, + 0.8950001001358032, + 1.4000002145767212, + 0.9500001072883606 + ], + "speedBeforeClamp": 1.6918927431106567, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8900002241134644, + 1.0, + 1.500000238418579, + -0.6300000548362732 + ], + "speedBeforeClamp": 1.8309836387634277, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 1.0, + 0.9470000267028809, + -0.960000216960907, + -0.5300000309944153 + ], + "speedBeforeClamp": 1.6854972839355469, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.9139999747276306, + 0.9040000438690186, + -0.8600001931190491, + -0.43000003695487976 + ], + "speedBeforeClamp": 0.9615094661712646, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8379999399185181, + 0.8710000514984131, + -0.7600001692771912, + -0.33000004291534424 + ], + "speedBeforeClamp": 0.8285530805587769, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.7719999551773071, + 0.8480000495910645, + -0.6600001454353333, + -0.23000004887580872 + ], + "speedBeforeClamp": 0.6989278793334961, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.715999960899353, + 0.8350000381469727, + -0.5600001215934753, + -0.1300000548362732 + ], + "speedBeforeClamp": 0.5748913884162903, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6699999570846558, + 0.8320000171661377, + -0.4600001275539398, + -0.030000053346157074 + ], + "speedBeforeClamp": 0.46097734570503235, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6339999437332153, + 0.8389999866485596, + -0.3600001335144043, + 0.06999994814395905 + ], + "speedBeforeClamp": 0.3667425215244293, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6079999208450317, + 0.8560000061988831, + -0.2600001394748688, + 0.16999995708465576 + ], + "speedBeforeClamp": 0.31064456701278687, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.591999888420105, + 0.8830000162124634, + -0.16000014543533325, + 0.2699999511241913 + ], + "speedBeforeClamp": 0.3138471245765686, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.5859998464584351, + 0.9200000166893005, + -0.06000014394521713, + 0.3699999451637268 + ], + "speedBeforeClamp": 0.37483325600624084, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.5899998545646667, + 0.9670000076293945, + 0.03999985754489899, + 0.46999993920326233 + ], + "speedBeforeClamp": 0.47169896960258484, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6039998531341553, + 1.0, + 0.1399998664855957, + -0.34199997782707214 + ], + "speedBeforeClamp": 0.586941123008728, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6279998421669006, + 0.9757999777793884, + 0.23999986052513123, + -0.24199998378753662 + ], + "speedBeforeClamp": 0.3408282995223999, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.6619998216629028, + 0.9616000056266785, + 0.33999985456466675, + -0.1419999897480011 + ], + "speedBeforeClamp": 0.3684615194797516, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.7059997916221619, + 0.9574000239372253, + 0.43999984860420227, + -0.04199998825788498 + ], + "speedBeforeClamp": 0.4419998526573181, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.7599997520446777, + 0.963200032711029, + 0.5399998426437378, + 0.05800001323223114 + ], + "speedBeforeClamp": 0.5431057214736938, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8239997625350952, + 0.9790000319480896, + 0.6399998664855957, + 0.15800002217292786 + ], + "speedBeforeClamp": 0.6592145562171936, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8979997634887695, + 1.0, + 0.7399998903274536, + -0.15480001270771027 + ], + "speedBeforeClamp": 0.783686101436615, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.9819997549057007, + 0.9945200085639954, + 0.8399999141693115, + -0.05480001121759415 + ], + "speedBeforeClamp": 0.8417855501174927, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 1.0, + 0.9990400075912476, + -0.5640000104904175, + 0.04519999027252197 + ], + "speedBeforeClamp": 0.9410860538482666, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.9535999894142151, + 1.0, + -0.46400001645088196, + -0.08711999654769897 + ], + "speedBeforeClamp": 0.48618829250335693, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.917199969291687, + 1.0, + -0.36400002241134644, + -0.007728003431111574 + ], + "speedBeforeClamp": 0.364227831363678, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8907999396324158, + 1.0, + -0.2640000283718109, + -0.05536320060491562 + ], + "speedBeforeClamp": 0.27966076135635376, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8743999600410461, + 1.0, + -0.1640000343322754, + -0.02678208239376545 + ], + "speedBeforeClamp": 0.16996604204177856, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8679999709129333, + 1.0, + -0.06400003284215927, + -0.04393075406551361 + ], + "speedBeforeClamp": 0.0972464308142662, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8715999722480774, + 1.0, + 0.03599996864795685, + -0.033641550689935684 + ], + "speedBeforeClamp": 0.0666315108537674, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.8851999640464783, + 1.0, + 0.13599997758865356, + -0.03981506824493408 + ], + "speedBeforeClamp": 0.15132559835910797, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 1.0 + ], + "next": [ + 0.908799946308136, + 1.0, + 0.2359999716281891, + -0.03611095994710922 + ], + "speedBeforeClamp": 0.2435533106327057, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.9223999381065369, + 0.9863889217376709, + 0.13599997758865356, + -0.13611096143722534 + ], + "speedBeforeClamp": 0.19241151213645935, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.9259999394416809, + 0.962777853012085, + 0.035999976098537445, + -0.23611095547676086 + ], + "speedBeforeClamp": 0.23883965611457825, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.9195999503135681, + 0.9291667342185974, + -0.06400002539157867, + -0.3361109495162964 + ], + "speedBeforeClamp": 0.34214991331100464, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.9031999707221985, + 0.885555624961853, + -0.1640000343322754, + -0.4361109435558319 + ], + "speedBeforeClamp": 0.4659278690814972, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.8767999410629272, + 0.8319445252418518, + -0.2640000283718109, + -0.5361109375953674 + ], + "speedBeforeClamp": 0.5975875854492188, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.8403999209403992, + 0.7683334350585938, + -0.36400002241134644, + -0.6361109614372253 + ], + "speedBeforeClamp": 0.732893705368042, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.7939999103546143, + 0.6947223544120789, + -0.46400001645088196, + -0.7361109852790833 + ], + "speedBeforeClamp": 0.8701467514038086, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.7375999093055725, + 0.6111112833023071, + -0.5640000104904175, + -0.8361110091209412 + ], + "speedBeforeClamp": 1.0085521936416626, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.6711999177932739, + 0.5175001621246338, + -0.6640000343322754, + -0.9361110329627991 + ], + "speedBeforeClamp": 1.1476932764053345, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.5947999358177185, + 0.4138890504837036, + -0.7640000581741333, + -1.0361109972000122 + ], + "speedBeforeClamp": 1.2873313426971436, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.5083999037742615, + 0.3002779483795166, + -0.8640000820159912, + -1.1361110210418701 + ], + "speedBeforeClamp": 1.4273207187652588, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.4119998812675476, + 0.17666684091091156, + -0.9640001058578491, + -1.236111044883728 + ], + "speedBeforeClamp": 1.5675671100616455, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.3055998682975769, + 0.04305572807788849, + -1.064000129699707, + -1.336111068725586 + ], + "speedBeforeClamp": 1.7080073356628418, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.18919984996318817, + -0.10055539011955261, + -1.164000153541565, + -1.4361110925674438 + ], + "speedBeforeClamp": 1.8485971689224243, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + 0.06279982626438141, + -0.25416648387908936, + -1.2640001773834229, + -1.5361111164093018 + ], + "speedBeforeClamp": 1.989304780960083, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.065268874168396, + -0.40778422355651855, + -1.2806869745254517, + -1.5361772775650024 + ], + "speedBeforeClamp": 2.1301071643829346, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.19425193965435028, + -0.5606350302696228, + -1.2898305654525757, + -1.528508186340332 + ], + "speedBeforeClamp": 2.140881299972534, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.324084997177124, + -0.7127645015716553, + -1.298330545425415, + -1.5212948322296143 + ], + "speedBeforeClamp": 2.1409502029418945, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.454708456993103, + -0.8642159104347229, + -1.306234359741211, + -1.5145138502120972 + ], + "speedBeforeClamp": 2.141010284423828, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.5860669612884521, + -1.0, + -1.3135852813720703, + 0.904885470867157 + ], + "speedBeforeClamp": 2.1410629749298096, + "clamped": true, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.7274255156517029, + -0.9195114374160767, + -1.4135853052139282, + 0.8048854470252991 + ], + "speedBeforeClamp": 1.6266727447509766, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8787840604782104, + -0.8490228652954102, + -1.5135853290557861, + 0.7048854231834412 + ], + "speedBeforeClamp": 1.6696717739105225, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -1.0, + -0.7885343432426453, + 0.9681512713432312, + 0.6048853993415833 + ], + "speedBeforeClamp": 1.7232365608215332, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9131848812103271, + -0.7380458116531372, + 0.8681512475013733, + 0.5048853754997253 + ], + "speedBeforeClamp": 1.004288673400879, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8363697528839111, + -0.697557270526886, + 0.7681512236595154, + 0.4048853814601898 + ], + "speedBeforeClamp": 0.8683251142501831, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.769554615020752, + -0.6670687198638916, + 0.6681511998176575, + 0.3048853874206543 + ], + "speedBeforeClamp": 0.7344257235527039, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.7127394676208496, + -0.646580159664154, + 0.5681511759757996, + 0.20488539338111877 + ], + "speedBeforeClamp": 0.6039650440216064, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.6659243702888489, + -0.6360916495323181, + 0.46815118193626404, + 0.10488539189100266 + ], + "speedBeforeClamp": 0.4797566831111908, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.629109263420105, + -0.635603129863739, + 0.3681511878967285, + 0.004885390400886536 + ], + "speedBeforeClamp": 0.36818361282348633, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.6022941470146179, + -0.6451146006584167, + 0.268151193857193, + -0.09511461108922958 + ], + "speedBeforeClamp": 0.28452038764953613, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.5854790210723877, + -0.6646260619163513, + 0.16815119981765747, + -0.1951146125793457 + ], + "speedBeforeClamp": 0.2575743496417999, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.5786638855934143, + -0.6941375136375427, + 0.06815119832754135, + -0.2951146066188812 + ], + "speedBeforeClamp": 0.30288153886795044, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.5818487405776978, + -0.733648955821991, + -0.03184880316257477, + -0.39511460065841675 + ], + "speedBeforeClamp": 0.39639613032341003, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.5950336456298828, + -0.783160388469696, + -0.13184881210327148, + -0.49511459469795227 + ], + "speedBeforeClamp": 0.5123695731163025, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.6182185411453247, + -0.8426718711853027, + -0.231848806142807, + -0.5951145887374878 + ], + "speedBeforeClamp": 0.6386824250221252, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.6514034271240234, + -0.9121833443641663, + -0.33184880018234253, + -0.6951146125793457 + ], + "speedBeforeClamp": 0.7702648639678955, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.694588303565979, + -0.9916948080062866, + -0.43184879422187805, + -0.7951146364212036 + ], + "speedBeforeClamp": 0.9048207998275757, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.7477731704711914, + -1.0, + -0.5318487882614136, + 0.5370688438415527 + ], + "speedBeforeClamp": 1.0411980152130127, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8109580278396606, + -0.9562931060791016, + -0.6318488121032715, + 0.4370688498020172 + ], + "speedBeforeClamp": 0.7682851552963257, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8841429352760315, + -0.92258620262146, + -0.7318488359451294, + 0.3370688557624817 + ], + "speedBeforeClamp": 0.8057407140731812, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9673278331756592, + -0.8988792896270752, + -0.8318488597869873, + 0.23706886172294617 + ], + "speedBeforeClamp": 0.8649706244468689, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -1.0, + -0.885172426700592, + 0.5591093301773071, + 0.13706886768341064 + ], + "speedBeforeClamp": 0.9418758749961853, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9540890455245972, + -0.8814655542373657, + 0.4591093361377716, + 0.037068866193294525 + ], + "speedBeforeClamp": 0.46060338616371155, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9181780815124512, + -0.8877586722373962, + 0.3591093420982361, + -0.0629311352968216 + ], + "speedBeforeClamp": 0.36458173394203186, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8922671675682068, + -0.9040517807006836, + 0.25910934805870056, + -0.1629311442375183 + ], + "speedBeforeClamp": 0.3060787618160248, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8763562440872192, + -0.9303448796272278, + 0.15910935401916504, + -0.26293113827705383 + ], + "speedBeforeClamp": 0.3073248565196991, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8704453110694885, + -0.9666379690170288, + 0.05910935252904892, + -0.36293113231658936 + ], + "speedBeforeClamp": 0.3677130937576294, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8745343685150146, + -1.0, + -0.0408906489610672, + 0.2777586877346039 + ], + "speedBeforeClamp": 0.4647335410118103, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.8886234164237976, + -0.9822241067886353, + -0.14089065790176392, + 0.17775869369506836 + ], + "speedBeforeClamp": 0.22682224214076996, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9127124547958374, + -0.9744482636451721, + -0.24089065194129944, + 0.07775869220495224 + ], + "speedBeforeClamp": 0.25312986969947815, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9468015432357788, + -0.9766724109649658, + -0.34089064598083496, + -0.02224130928516388 + ], + "speedBeforeClamp": 0.3416154384613037, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.990890622138977, + -0.9888965487480164, + -0.4408906400203705, + -0.12224131077528 + ], + "speedBeforeClamp": 0.4575232267379761, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -1.0, + -1.0, + 0.3245343863964081, + 0.13334479928016663 + ], + "speedBeforeClamp": 0.5847682356834412, + "clamped": false, + "hitX": true, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9775465726852417, + -0.9966655373573303, + 0.22453439235687256, + 0.03334479779005051 + ], + "speedBeforeClamp": 0.22699685394763947, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9650931358337402, + -1.0, + 0.12453439086675644, + 0.03999312222003937 + ], + "speedBeforeClamp": 0.1412505954504013, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9626396894454956, + -1.0, + 0.02453438937664032, + 0.03600412979722023 + ], + "speedBeforeClamp": 0.06482870876789093, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9701862335205078, + -1.0, + -0.0754656121134758, + 0.038397520780563354 + ], + "speedBeforeClamp": 0.09894710779190063, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9877327680587769, + -1.0, + -0.17546561360359192, + 0.03696148842573166 + ], + "speedBeforeClamp": 0.1859651803970337, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -1.0, + -1.0, + 0.16527937352657318, + 0.037823110818862915 + ], + "speedBeforeClamp": 0.28258654475212097, + "clamped": false, + "hitX": true, + "hitY": true + }, + { + "action": [ + -1.0, + -1.0 + ], + "next": [ + -0.9934720396995544, + -1.0, + 0.06527937203645706, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.09015188366174698, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.976944088935852, + -0.9962694048881531, + 0.16527937352657318, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.16943736374378204, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.9504161477088928, + -0.9925388097763062, + 0.2652793824672699, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.26788970828056335, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.9138882160186768, + -0.9888082146644592, + 0.3652793765068054, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.3671794831752777, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.8673602938652039, + -0.9850776195526123, + 0.46527937054634094, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.46677258610725403, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.8108323812484741, + -0.9813470244407654, + 0.5652793645858765, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.5665090680122375, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.7443044185638428, + -0.9776164293289185, + 0.6652793884277344, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.6663245558738708, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.6677764654159546, + -0.9738858342170715, + 0.7652794122695923, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.7661882042884827, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.5812485218048096, + -0.9701552391052246, + 0.8652794361114502, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.8660832643508911, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.4847205877304077, + -0.9664246439933777, + 0.9652794599533081, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.9660000801086426, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.37819263339042664, + -0.9626940488815308, + 1.065279483795166, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.0659325122833252, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.2616646885871887, + -0.9589634537696838, + 1.165279507637024, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.1658765077590942, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + -0.13513673841953278, + -0.9552328586578369, + 1.2652795314788818, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.26582932472229, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.0013912171125411987, + -0.95150226354599, + 1.3652795553207397, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.3657891750335693, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.1479191780090332, + -0.9477716684341431, + 1.4652795791625977, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.4657543897628784, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.30444714426994324, + -0.9440410733222961, + 1.5652796030044556, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.5657240152359009, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.4709751009941101, + -0.9403104782104492, + 1.6652796268463135, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.665697455406189, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.6475030779838562, + -0.9365798830986023, + 1.7652796506881714, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.7656737565994263, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.8340310454368591, + -0.9328492879867554, + 1.8652796745300293, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.8656526803970337, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 1.0, + -0.9291186928749084, + -1.1791678667068481, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.965633749961853, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.8920832276344299, + -0.9253880977630615, + -1.0791678428649902, + 0.03730613738298416 + ], + "speedBeforeClamp": 1.0798125267028809, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.7941664457321167, + -0.9216575026512146, + -0.9791678190231323, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.9798782467842102, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.7062496542930603, + -0.9179269075393677, + -0.8791677951812744, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.8799589276313782, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.6283328533172607, + -0.9141963124275208, + -0.7791677713394165, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.780060350894928, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.5604161024093628, + -0.9104657173156738, + -0.6791677474975586, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.6801915764808655, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.5024993419647217, + -0.9067351222038269, + -0.5791677236557007, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.5803679823875427, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.4545825719833374, + -0.90300452709198, + -0.47916772961616516, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.48061779141426086, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.41666579246520996, + -0.8992739319801331, + -0.37916773557662964, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.3809985816478729, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.38874900341033936, + -0.8955433368682861, + -0.2791677415370941, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.2816493809223175, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.370832234621048, + -0.8918127417564392, + -0.1791677474975586, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.18301045894622803, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.3629154562950134, + -0.8880821466445923, + -0.07916774600744247, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.08751731365919113, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.3649986684322357, + -0.8843515515327454, + 0.020832255482673645, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.042728569358587265, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.37708190083503723, + -0.8806209564208984, + 0.12083225697278976, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.12646019458770752, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.3991651237010956, + -0.8768903613090515, + 0.22083225846290588, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.2239612340927124, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.43124833703041077, + -0.8731597661972046, + 0.3208322525024414, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.3229939341545105, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.4733315706253052, + -0.8694291710853577, + 0.42083224654197693, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.42248257994651794, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.5254148244857788, + -0.8656985759735107, + 0.5208322405815125, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.5221666097640991, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.5874980688095093, + -0.8619679808616638, + 0.6208322644233704, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.6219521164894104, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.6595813035964966, + -0.8582373857498169, + 0.7208322882652283, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.7217970490455627, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.7416645288467407, + -0.85450679063797, + 0.8208323121070862, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.8216796517372131, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 1.0, + 0.0 + ], + "next": [ + 0.8337477445602417, + -0.850776195526123, + 0.9208323359489441, + 0.03730613738298416 + ], + "speedBeforeClamp": 0.9215877652168274, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.9258309602737427, + -0.8370456099510193, + 0.9208323359489441, + 0.13730613887310028 + ], + "speedBeforeClamp": 0.9310129880905151, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 1.0, + -0.8133149743080139, + -0.5524994134902954, + 0.237306147813797 + ], + "speedBeforeClamp": 0.9509187340736389, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.9447500705718994, + -0.7795843482017517, + -0.5524994134902954, + 0.3373061418533325 + ], + "speedBeforeClamp": 0.6473260521888733, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.8895001411437988, + -0.7358537316322327, + -0.5524994134902954, + 0.43730613589286804 + ], + "speedBeforeClamp": 0.7046220898628235, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.8342502117156982, + -0.6821231245994568, + -0.5524994134902954, + 0.5373061299324036 + ], + "speedBeforeClamp": 0.770683765411377, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.7790002822875977, + -0.6183925271034241, + -0.5524994134902954, + 0.6373061537742615 + ], + "speedBeforeClamp": 0.8434540033340454, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.7237503528594971, + -0.5446618795394897, + -0.5524994134902954, + 0.7373061776161194 + ], + "speedBeforeClamp": 0.9213446974754333, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.6685004234313965, + -0.4609312415122986, + -0.5524994134902954, + 0.8373062014579773 + ], + "speedBeforeClamp": 1.0031636953353882, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.6132504940032959, + -0.3672006130218506, + -0.5524994134902954, + 0.9373062252998352 + ], + "speedBeforeClamp": 1.0880250930786133, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.5580005645751953, + -0.26346999406814575, + -0.5524994134902954, + 1.0373061895370483 + ], + "speedBeforeClamp": 1.1752700805664062, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.5027506351470947, + -0.1497393697500229, + -0.5524994134902954, + 1.1373062133789062 + ], + "speedBeforeClamp": 1.264405369758606, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.44750070571899414, + -0.02600874751806259, + -0.5524994134902954, + 1.2373062372207642 + ], + "speedBeforeClamp": 1.3550580739974976, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.39225077629089355, + 0.10772188752889633, + -0.5524994134902954, + 1.337306261062622 + ], + "speedBeforeClamp": 1.446942925453186, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.33700084686279297, + 0.2514525055885315, + -0.5524994134902954, + 1.43730628490448 + ], + "speedBeforeClamp": 1.539839267730713, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.2817509174346924, + 0.4051831364631653, + -0.5524994134902954, + 1.537306308746338 + ], + "speedBeforeClamp": 1.6335747241973877, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.2265009731054306, + 0.5689137578010559, + -0.5524994134902954, + 1.6373063325881958 + ], + "speedBeforeClamp": 1.7280126810073853, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.17125102877616882, + 0.7426444292068481, + -0.5524994134902954, + 1.7373063564300537 + ], + "speedBeforeClamp": 1.8230438232421875, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.11600108444690704, + 0.9263750910758972, + -0.5524994134902954, + 1.8373063802719116 + ], + "speedBeforeClamp": 1.9185802936553955, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.06115017831325531, + 1.0, + -0.5485090613365173, + -1.1539885997772217 + ], + "speedBeforeClamp": 2.014549970626831, + "clamped": true, + "hitX": false, + "hitY": true + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + 0.006299272179603577, + 0.8946011662483215, + -0.5485090613365173, + -1.0539885759353638 + ], + "speedBeforeClamp": 1.1881725788116455, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.04855163395404816, + 0.7992023229598999, + -0.5485090613365173, + -0.9539885520935059 + ], + "speedBeforeClamp": 1.10043466091156, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.10340254008769989, + 0.7138034701347351, + -0.5485090613365173, + -0.853988528251648 + ], + "speedBeforeClamp": 1.0149672031402588, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.15825344622135162, + 0.6384046077728271, + -0.5485090613365173, + -0.75398850440979 + ], + "speedBeforeClamp": 0.9323952198028564, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.21310435235500336, + 0.573005735874176, + -0.5485090613365173, + -0.6539884805679321 + ], + "speedBeforeClamp": 0.8535590767860413, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.2679552435874939, + 0.5176069140434265, + -0.5485090613365173, + -0.5539884567260742 + ], + "speedBeforeClamp": 0.7795931100845337, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.32280614972114563, + 0.47220808267593384, + -0.5485090613365173, + -0.4539884626865387 + ], + "speedBeforeClamp": 0.7120166420936584, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.37765705585479736, + 0.436809241771698, + -0.5485090613365173, + -0.3539884686470032 + ], + "speedBeforeClamp": 0.6528170108795166, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.4325079619884491, + 0.411410391330719, + -0.5485090613365173, + -0.25398847460746765 + ], + "speedBeforeClamp": 0.6044603586196899, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.48735886812210083, + 0.3960115313529968, + -0.5485090613365173, + -0.15398848056793213 + ], + "speedBeforeClamp": 0.5697145462036133, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.5422097444534302, + 0.3906126916408539, + -0.5485090613365173, + -0.05398847907781601 + ], + "speedBeforeClamp": 0.5511596202850342, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.5970606803894043, + 0.3952138423919678, + -0.5485090613365173, + 0.04601152241230011 + ], + "speedBeforeClamp": 0.5504355430603027, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.6519116163253784, + 0.4098149836063385, + -0.5485090613365173, + 0.14601153135299683 + ], + "speedBeforeClamp": 0.5676103830337524, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.7067625522613525, + 0.43441614508628845, + -0.5485090613365173, + 0.24601152539253235 + ], + "speedBeforeClamp": 0.6011521220207214, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.7616134881973267, + 0.46901729702949524, + -0.5485090613365173, + 0.34601151943206787 + ], + "speedBeforeClamp": 0.648526132106781, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.8164644241333008, + 0.5136184692382812, + -0.5485090613365173, + 0.4460115134716034 + ], + "speedBeforeClamp": 0.7069571614265442, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.8713153600692749, + 0.5682196021080017, + -0.5485090613365173, + 0.5460115075111389 + ], + "speedBeforeClamp": 0.7739449739456177, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.926166296005249, + 0.632820725440979, + -0.5485090613365173, + 0.6460115313529968 + ], + "speedBeforeClamp": 0.8474627137184143, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.9810172319412231, + 0.7074218988418579, + -0.5485090613365173, + 0.7460115551948547 + ], + "speedBeforeClamp": 0.9259564876556396, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -1.0, + 0.7920230627059937, + 0.3291054368019104, + 0.8460115790367126 + ], + "speedBeforeClamp": 1.0082647800445557, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 0.0, + 1.0 + ], + "next": [ + -0.9670894742012024, + 0.8866242170333862, + 0.3291054368019104, + 0.9460116028785706 + ], + "speedBeforeClamp": 1.0016227960586548, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.933678925037384, + 0.9807254076004028, + 0.3341054320335388, + 0.9410116076469421 + ], + "speedBeforeClamp": 0.9985636472702026, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.8997683525085449, + 1.0, + 0.33910542726516724, + -0.5616070032119751 + ], + "speedBeforeClamp": 0.9955452084541321, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.8653578162193298, + 0.9433392882347107, + 0.34410542249679565, + -0.5666069984436035 + ], + "speedBeforeClamp": 0.6629117727279663, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.830447256565094, + 0.8861786127090454, + 0.3491054177284241, + -0.5716069936752319 + ], + "speedBeforeClamp": 0.6697829365730286, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.7950367331504822, + 0.8285179138183594, + 0.3541054129600525, + -0.5766069889068604 + ], + "speedBeforeClamp": 0.6766581535339355, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.7591261863708496, + 0.7703571915626526, + 0.3591054081916809, + -0.5816069841384888 + ], + "speedBeforeClamp": 0.6835373640060425, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.7227156162261963, + 0.7116965055465698, + 0.3641054034233093, + -0.5866069793701172 + ], + "speedBeforeClamp": 0.6904205083847046, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.685805082321167, + 0.6525357961654663, + 0.36910539865493774, + -0.5916069746017456 + ], + "speedBeforeClamp": 0.6973074078559875, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.6483945250511169, + 0.5928751230239868, + 0.37410539388656616, + -0.596606969833374 + ], + "speedBeforeClamp": 0.7041979432106018, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.6104840040206909, + 0.5327144265174866, + 0.3791053891181946, + -0.6016069650650024 + ], + "speedBeforeClamp": 0.7110919952392578, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.5720734596252441, + 0.47205373644828796, + 0.384105384349823, + -0.6066069602966309 + ], + "speedBeforeClamp": 0.7179895043373108, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.5331629514694214, + 0.410893052816391, + 0.3891053795814514, + -0.6116069555282593 + ], + "speedBeforeClamp": 0.724890410900116, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.4937524199485779, + 0.34923234581947327, + 0.39410537481307983, + -0.6166069507598877 + ], + "speedBeforeClamp": 0.7317944765090942, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.453841894865036, + 0.2870716452598572, + 0.39910537004470825, + -0.6216069459915161 + ], + "speedBeforeClamp": 0.7387017607688904, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.4134313464164734, + 0.22441095113754272, + 0.40410536527633667, + -0.6266069412231445 + ], + "speedBeforeClamp": 0.7456120848655701, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.3725208044052124, + 0.1612502634525299, + 0.4091053605079651, + -0.631606936454773 + ], + "speedBeforeClamp": 0.7525254487991333, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.33111026883125305, + 0.09758956730365753, + 0.4141053557395935, + -0.6366069316864014 + ], + "speedBeforeClamp": 0.759441614151001, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.28919973969459534, + 0.033428870141506195, + 0.4191053509712219, + -0.6416069269180298 + ], + "speedBeforeClamp": 0.7663607001304626, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.24678920209407806, + -0.031231820583343506, + 0.42410534620285034, + -0.6466069221496582 + ], + "speedBeforeClamp": 0.773282527923584, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.20387867093086243, + -0.09639251232147217, + 0.42910534143447876, + -0.6516069173812866 + ], + "speedBeforeClamp": 0.7802070379257202, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.16046813130378723, + -0.1620531976222992, + 0.4341053366661072, + -0.656606912612915 + ], + "speedBeforeClamp": 0.7871341109275818, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.11655759811401367, + -0.22821389138698578, + 0.4391053318977356, + -0.6616069078445435 + ], + "speedBeforeClamp": 0.7940636873245239, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.07214706391096115, + -0.2948745787143707, + 0.444105327129364, + -0.6666069030761719 + ], + "speedBeforeClamp": 0.8009958267211914, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + -0.027236532419919968, + -0.36203527450561523, + 0.44910532236099243, + -0.6716068983078003 + ], + "speedBeforeClamp": 0.8079303503036499, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.018174000084400177, + -0.4296959638595581, + 0.45410531759262085, + -0.6766068935394287 + ], + "speedBeforeClamp": 0.8148671984672546, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.06408452987670898, + -0.49785664677619934, + 0.45910531282424927, + -0.6816068887710571 + ], + "speedBeforeClamp": 0.8218063116073608, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.11049506068229675, + -0.5665173530578613, + 0.4641053080558777, + -0.6866068840026855 + ], + "speedBeforeClamp": 0.8287476897239685, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.15740558505058289, + -0.6356780529022217, + 0.4691053032875061, + -0.691606879234314 + ], + "speedBeforeClamp": 0.8356912732124329, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.20481611788272858, + -0.705338716506958, + 0.4741052985191345, + -0.6966068744659424 + ], + "speedBeforeClamp": 0.8426369428634644, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.25272664427757263, + -0.7754994034767151, + 0.47910529375076294, + -0.7016068696975708 + ], + "speedBeforeClamp": 0.8495846390724182, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.30113717913627625, + -0.8461601138114929, + 0.48410528898239136, + -0.7066068649291992 + ], + "speedBeforeClamp": 0.8565344214439392, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.3500477075576782, + -0.9173207879066467, + 0.4891052842140198, + -0.7116068601608276 + ], + "speedBeforeClamp": 0.863486111164093, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.39945822954177856, + -0.9889814853668213, + 0.4941052794456482, + -0.716606855392456 + ], + "speedBeforeClamp": 0.8704397678375244, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.44936874508857727, + -1.0, + 0.4991052746772766, + 0.43296411633491516 + ], + "speedBeforeClamp": 0.8773952722549438, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.49977928400039673, + -0.9572035670280457, + 0.504105269908905, + 0.42796412110328674 + ], + "speedBeforeClamp": 0.6612680554389954, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.5506898164749146, + -0.9149071574211121, + 0.5091052651405334, + 0.4229641258716583 + ], + "speedBeforeClamp": 0.6618812680244446, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.6021003723144531, + -0.8731107711791992, + 0.5141052603721619, + 0.4179641306400299 + ], + "speedBeforeClamp": 0.6625694036483765, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.6540108919143677, + -0.8318143486976624, + 0.5191052556037903, + 0.4129641354084015 + ], + "speedBeforeClamp": 0.6633322238922119, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.706421434879303, + -0.7910179495811462, + 0.5241052508354187, + 0.40796414017677307 + ], + "speedBeforeClamp": 0.664169430732727, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 0.05000000074505806, + -0.05000000074505806 + ], + "next": [ + 0.7593319416046143, + -0.7507215142250061, + 0.5291052460670471, + 0.40296414494514465 + ], + "speedBeforeClamp": 0.6650807857513428, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8222424983978271, + -0.7204251289367676, + 0.629105269908905, + 0.30296415090560913 + ], + "speedBeforeClamp": 0.6982554793357849, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8951530456542969, + -0.7001287341117859, + 0.7291052937507629, + 0.2029641568660736 + ], + "speedBeforeClamp": 0.756828248500824, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9780635833740234, + -0.689832329750061, + 0.8291053175926208, + 0.10296415537595749 + ], + "speedBeforeClamp": 0.8354742527008057, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 1.0, + -0.689535915851593, + -0.5574632287025452, + 0.0029641538858413696 + ], + "speedBeforeClamp": 0.929110050201416, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9542536735534668, + -0.6992394924163818, + -0.45746323466300964, + -0.09703584760427475 + ], + "speedBeforeClamp": 0.4676415026187897, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9185073375701904, + -0.7189430594444275, + -0.3574632406234741, + -0.19703584909439087 + ], + "speedBeforeClamp": 0.4081704318523407, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8927609920501709, + -0.74864661693573, + -0.2574632465839386, + -0.2970358431339264 + ], + "speedBeforeClamp": 0.3930872976779938, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8770146369934082, + -0.7883502244949341, + -0.15746325254440308, + -0.3970358371734619 + ], + "speedBeforeClamp": 0.42712077498435974, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8712683320045471, + -0.838053822517395, + -0.05746325105428696, + -0.49703583121299744 + ], + "speedBeforeClamp": 0.5003465414047241, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8755220174789429, + -0.8977574110031128, + 0.04253675043582916, + -0.597035825252533 + ], + "speedBeforeClamp": 0.5985492467880249, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.8897756934165955, + -0.9674609899520874, + 0.14253675937652588, + -0.6970358490943909 + ], + "speedBeforeClamp": 0.7114602327346802, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9140293598175049, + -1.0, + 0.2425367534160614, + 0.4782215356826782 + ], + "speedBeforeClamp": 0.8331207633018494, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9482830166816711, + -0.9621778726577759, + 0.3425367474555969, + 0.3782215416431427 + ], + "speedBeforeClamp": 0.5102773308753967, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9925366640090942, + -0.9343557357788086, + 0.44253674149513245, + 0.2782215476036072 + ], + "speedBeforeClamp": 0.5227293372154236, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 1.0, + -0.9165335893630981, + -0.3255220651626587, + 0.17822155356407166 + ], + "speedBeforeClamp": 0.5710595846176147, + "clamped": false, + "hitX": true, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9774478077888489, + -0.9087114334106445, + -0.22552207112312317, + 0.07822155207395554 + ], + "speedBeforeClamp": 0.23870235681533813, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9648956060409546, + -0.9108892679214478, + -0.12552207708358765, + -0.021778449416160583 + ], + "speedBeforeClamp": 0.12739737331867218, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9623433947563171, + -0.9230670928955078, + -0.025522075593471527, + -0.1217784509062767 + ], + "speedBeforeClamp": 0.12442414462566376, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9697911739349365, + -0.9452449083328247, + 0.07447792589664459, + -0.22177845239639282 + ], + "speedBeforeClamp": 0.23395009338855743, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + 5.0, + -5.0 + ], + "next": [ + 0.9872389435768127, + -0.9774227738380432, + 0.1744779348373413, + -0.32177844643592834 + ], + "speedBeforeClamp": 0.36603811383247375, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.9946867227554321, + -0.9996006488800049, + 0.07447793334722519, + -0.22177845239639282 + ], + "speedBeforeClamp": 0.23395009338855743, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.9921345114707947, + -1.0, + -0.02552206814289093, + 0.0730670765042305 + ], + "speedBeforeClamp": 0.12442414462566376, + "clamped": false, + "hitX": false, + "hitY": true + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.9795823097229004, + -0.9826933145523071, + -0.12552207708358765, + 0.17306707799434662 + ], + "speedBeforeClamp": 0.2137943059206009, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.9570301175117493, + -0.9553865790367126, + -0.22552207112312317, + 0.27306708693504333 + ], + "speedBeforeClamp": 0.35415512323379517, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.9244779348373413, + -0.9180798530578613, + -0.3255220651626587, + 0.37306708097457886 + ], + "speedBeforeClamp": 0.4951198399066925, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.8819257020950317, + -0.8707731366157532, + -0.4255220592021942, + 0.4730670750141144 + ], + "speedBeforeClamp": 0.636287271976471, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.8293734788894653, + -0.8134664297103882, + -0.5255220532417297, + 0.5730670690536499 + ], + "speedBeforeClamp": 0.7775470018386841, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.7668212652206421, + -0.7461597323417664, + -0.6255220770835876, + 0.6730670928955078 + ], + "speedBeforeClamp": 0.9188564419746399, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.694269061088562, + -0.6688530445098877, + -0.7255221009254456, + 0.7730671167373657 + ], + "speedBeforeClamp": 1.060195803642273, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.6117168664932251, + -0.5815463066101074, + -0.8255221247673035, + 0.8730671405792236 + ], + "speedBeforeClamp": 1.2015544176101685, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.5191646814346313, + -0.4842395782470703, + -0.9255221486091614, + 0.9730671644210815 + ], + "speedBeforeClamp": 1.342926263809204, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.4166124761104584, + -0.37693285942077637, + -1.0255221128463745, + 1.0730671882629395 + ], + "speedBeforeClamp": 1.4843075275421143, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.3040602505207062, + -0.2596261501312256, + -1.1255221366882324, + 1.1730672121047974 + ], + "speedBeforeClamp": 1.6256957054138184, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.18150803446769714, + -0.13231942057609558, + -1.2255221605300903, + 1.2730672359466553 + ], + "speedBeforeClamp": 1.7670893669128418, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + 0.04895581305027008, + 0.004987314343452454, + -1.3255221843719482, + 1.3730672597885132 + ], + "speedBeforeClamp": 1.90848708152771, + "clamped": false, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + -0.0901271402835846, + 0.14870905876159668, + -1.3908294439315796, + 1.4372174739837646 + ], + "speedBeforeClamp": 2.0498878955841064, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + -0.22936566174030304, + 0.29228007793426514, + -1.3923851251602173, + 1.4357099533081055 + ], + "speedBeforeClamp": 2.141403913497925, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + -0.36874935030937195, + 0.4357101619243622, + -1.3938368558883667, + 1.4343007802963257 + ], + "speedBeforeClamp": 2.1414058208465576, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + -0.5082684755325317, + 0.5790085196495056, + -1.3951915502548218, + 1.4329833984375 + ], + "speedBeforeClamp": 2.1414077281951904, + "clamped": true, + "hitX": false, + "hitY": false + }, + { + "action": [ + -3.0, + 2.5 + ], + "next": [ + -0.6479139924049377, + 0.7221837043762207, + -1.3964552879333496, + 1.4317514896392822 + ], + "speedBeforeClamp": 2.1414098739624023, + "clamped": true, + "hitX": false, + "hitY": false + } + ] +} diff --git a/Tests/WorldModelDemoTests/ParticleNavigatorEnvConformanceTests.swift b/Tests/WorldModelDemoTests/ParticleNavigatorEnvConformanceTests.swift new file mode 100644 index 0000000..c27807a --- /dev/null +++ b/Tests/WorldModelDemoTests/ParticleNavigatorEnvConformanceTests.swift @@ -0,0 +1,139 @@ +import XCTest +@testable import WorldModelDemo + +/// `ParticleNavigatorEnv` against the Python original. +/// +/// The fixture is generated from `WorldModel/env.py` itself by +/// `tools/worldmodel-fixture/generate.py` in the neuralcompose-client-native +/// repository — not from a reimplementation, which would agree with whatever it +/// was derived from and prove nothing. +/// +/// **This is the first thing to pin `step()` against its reference in any +/// language.** The four tests beside this file are hand-computed literals: they +/// check that a bounce reverses and scales, not that a 260-step trajectory +/// matches. A Rust port of the same function reproduced the fixture bit-for-bit +/// on its first run. +/// +/// Agreement is asserted **exactly**, not to a tolerance. Both sides are +/// `Float`, the fixture stores each value as a `Float` widened to `Double` +/// (lossless), and a tolerance on a deterministic function could only hide a +/// real divergence. See `docs/acceptance/worldmodel-demo.md` §10 in the client +/// repository for what a failure here means — decided before this ran. +final class ParticleNavigatorEnvConformanceTests: XCTestCase { + + private struct Fixture: Decodable { + struct Config: Decodable { + let arenaHalfExtent: Double + let dt: Double + let maxAccel: Double + let maxSpeed: Double + let restitution: Double + } + struct Coverage: Decodable { + let steps: Int + let bouncedX: Int + let bouncedY: Int + let cornerHits: Int + let clampedSteps: Int + let unclampedSteps: Int + } + struct Step: Decodable { + let action: [Double] + let next: [Double] + let speedBeforeClamp: Double + let clamped: Bool + } + let schemaId: String + let config: Config + let initialState: [Double] + let coverage: Coverage + let steps: [Step] + } + + private func loadFixture() throws -> Fixture { + guard let url = Bundle.module.url(forResource: "env_v1", withExtension: "json") else { + XCTFail(""" + env_v1.json is not in the test bundle. + + This test does NOT skip when its ground truth is missing: a conformance \ + check that passes when it cannot compare anything reports green for \ + exactly the state it exists to detect. + + Regenerate it in the neuralcompose-client-native checkout with + ~/src/NeuralCompose/.venv-muse/bin/python \\ + tools/worldmodel-fixture/generate.py > env_v1.json + and copy it to Tests/WorldModelDemoTests/Fixtures/. + """) + throw XCTSkip("unreachable — XCTFail above is the real outcome") + } + return try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: url)) + } + + private func config(_ c: Fixture.Config) -> WorldModelEnvConfig { + WorldModelEnvConfig( + arenaHalfExtent: c.arenaHalfExtent, + dt: c.dt, + maxAccel: c.maxAccel, + maxSpeed: c.maxSpeed, + restitution: c.restitution + ) + } + + func testEveryStepReproducesThePythonEnvExactly() throws { + let f = try loadFixture() + XCTAssertEqual(f.schemaId, "neuralcompose.hypnagogic.env-conformance.v1") + + let cfg = config(f.config) + var state = f.initialState.map { Float($0) } + var failures: [String] = [] + + for (i, s) in f.steps.enumerated() { + let action = s.action.map { Float($0) } + let expected = s.next.map { Float($0) } + let got = ParticleNavigatorEnv.step(state: state, action: action, config: cfg) + + if got != expected { + failures.append(""" + step \(i): action \(action) + expected \(expected) + got \(got) + python speed before clamp \(s.speedBeforeClamp) (clamped: \(s.clamped)) + """) + if failures.count >= 5 { + failures.append("… stopping after 5") + break + } + } + // Continue from Python's state so one divergence is not reported N times. + state = expected + } + + XCTAssertTrue( + failures.isEmpty, + """ + ParticleNavigatorEnv.swift diverges from WorldModel/env.py in \ + \(failures.count) place(s): + \(failures.joined(separator: "\n")) + + Per §10, registered before this test was run: this is a defect in the \ + macOS app's environment, not in the fixture and not a porting artifact. \ + A Rust port of the same function matched this fixture bit-for-bit. + """ + ) + } + + /// The fixture has to reach the states that discriminate, or a `step` with no + /// wall handling and no speed limit would pass it. + func testTheFixtureReachesTheStatesThatDiscriminate() throws { + let c = try loadFixture().coverage + XCTAssertGreaterThanOrEqual(c.steps, 200) + XCTAssertGreaterThan(c.bouncedX, 0, "wall handling is unexercised on x") + XCTAssertGreaterThan(c.bouncedY, 0, "wall handling is unexercised on y") + XCTAssertGreaterThan(c.cornerHits, 0, "no step bounces both axes at once") + XCTAssertGreaterThan(c.clampedSteps, 0, "the speed clamp never fires") + XCTAssertGreaterThan( + c.unclampedSteps, 0, + "the clamp fires on every step — an implementation that always scales would pass" + ) + } +} From 1d891039488150bfb890ff1bcffcaae5872ce794 Mon Sep 17 00:00:00 2001 From: aurascoper Date: Sat, 22 Aug 2026 00:33:21 -0500 Subject: [PATCH 13/13] fix(embedding): cosineSimilarity returns nil for incomparable spaces, not 0 `Embedding.cosineSimilarity(to:)` guarded on dimension alone and returned `0` for a mismatch, which is also the legitimate score for orthogonal vectors from the same model. Per docs/reviews/embedding-comparability- unenforced-2026-08-12.md, that made "incomparable" indistinguishable from "unrelated" and scored a cross-space candidate a neutral 0.5. Mirrors the Rust port (neuralcompose-hypnagogic/src/embedding.rs): - `Embedding.isComparable(with:)`: same modelID, same dimension, non-empty. seed/version are not part of it because `centroid(of:)` builds centroids with seed 0 and must stay comparable to its members. - `cosineSimilarity(to:) -> Float?`, nil when not comparable. - `DialecticalDynamics.normalizedSimilarity(_:_:)` traps on nil with the two space identities in the message; all BCICore scoring sites route through it. One embedder per session makes incomparable a defect, not a state. - `centroid(of:)` returns nil on any incomparable member instead of silently averaging the comparable subset. - Evals force-unwrap (single map, single embedder); tests use XCTUnwrap. - New test `testIncomparableIsNilNotZero`: orthogonal-and-comparable is 0, incomparable is nil, mixed-space centroid is nil. - embedding_contract.md section 2.7 now cites the type and the test, not a doc comment. UNVERIFIED ON THIS HOST: written on Linux with no Swift toolchain; the package targets macOS 14. Run `swift test` on the Mac before merging. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01J5MbSKyxJn8jZPoggQjrJT --- .../Composition/HypnagogicDialecticLoop.swift | 6 ++-- .../Dialectic/DialecticalDynamics.swift | 31 +++++++++++++------ .../BCICore/Dialectic/DialecticalMemory.swift | 3 +- Sources/BCICore/Dialectic/SemanticGraph.swift | 4 +-- Sources/BCICore/Models/Embedding.swift | 20 +++++++++--- Sources/GenerationEval/main.swift | 2 +- Sources/SemanticEval/NearestNeighbors.swift | 2 +- Sources/SemanticEval/main.swift | 10 +++--- .../DialecticalDynamicsTests.swift | 13 ++++++++ .../SemanticBGEReplayRegressionTests.swift | 6 ++-- .../SemanticReplayRegressionTests.swift | 6 ++-- .../BCICoreTests/SentenceEmbedderTests.swift | 6 ++-- docs/architecture/embedding_contract.md | 2 +- ...ing-comparability-unenforced-2026-08-12.md | 2 +- 14 files changed, 75 insertions(+), 38 deletions(-) diff --git a/Sources/BCICore/Composition/HypnagogicDialecticLoop.swift b/Sources/BCICore/Composition/HypnagogicDialecticLoop.swift index 329b7bf..c4fe288 100644 --- a/Sources/BCICore/Composition/HypnagogicDialecticLoop.swift +++ b/Sources/BCICore/Composition/HypnagogicDialecticLoop.swift @@ -276,7 +276,7 @@ public actor HypnagogicDialecticLoop { } }() let selfSimilarity: Float? = spokenEmb.flatMap { emb in - replyCentroid.map { DialecticalDynamics.normalized(emb.cosineSimilarity(to: $0)) } + replyCentroid.map { DialecticalDynamics.normalizedSimilarity(emb, $0) } } var witnessFinding: String? var witnessDistance: Float? @@ -294,7 +294,7 @@ public actor HypnagogicDialecticLoop { if !finding.isEmpty { witnessFinding = finding if let spokenEmb, let findingEmb = try? await embedder.encode([finding]).first { - witnessDistance = 1 - DialecticalDynamics.normalized(findingEmb.cosineSimilarity(to: spokenEmb)) + witnessDistance = 1 - DialecticalDynamics.normalizedSimilarity(findingEmb, spokenEmb) } } } catch is CancellationError { @@ -374,7 +374,7 @@ public actor HypnagogicDialecticLoop { var worst: Float = -1 for i in 0.. worst { worst = d; best = (i, j) } } } diff --git a/Sources/BCICore/Dialectic/DialecticalDynamics.swift b/Sources/BCICore/Dialectic/DialecticalDynamics.swift index 4c4100c..7c63834 100644 --- a/Sources/BCICore/Dialectic/DialecticalDynamics.swift +++ b/Sources/BCICore/Dialectic/DialecticalDynamics.swift @@ -113,6 +113,17 @@ public enum DialecticalDynamics { @inlinable public static func normalized(_ cosine: Float) -> Float { (cosine + 1) / 2 } + /// `normalized` over a similarity that must exist. Traps on incomparable + /// operands instead of scoring them: one embedder per session makes that a + /// defect, not a state the loop should absorb as `0.5`. + // ponytail: traps; propagate Optional the day a second embedder is held at once. + public static func normalizedSimilarity(_ a: Embedding, _ b: Embedding) -> Float { + guard let s = a.cosineSimilarity(to: b) else { + preconditionFailure("incomparable embedding spaces: \(a.modelID)/\(a.dimension) vs \(b.modelID)/\(b.dimension)") + } + return normalized(s) + } + /// Scores one candidate against the turn context. Missing centroids (early /// turns, before any history) score a neutral `0.5` rather than biasing the /// competition toward either pole. @@ -122,10 +133,10 @@ public enum DialecticalDynamics { historyCentroid: Embedding?, replyCentroid: Embedding? ) -> DialecticalEnergy { - let coherence = normalized(candidate.cosineSimilarity(to: heard)) - let resonance = historyCentroid.map { normalized(candidate.cosineSimilarity(to: $0)) } ?? 0.5 + let coherence = normalizedSimilarity(candidate, heard) + let resonance = historyCentroid.map { normalizedSimilarity(candidate, $0) } ?? 0.5 // novelty = distance from what we've said; 1 − similarity, on the [0,1] scale. - let novelty = replyCentroid.map { 1 - normalized(candidate.cosineSimilarity(to: $0)) } ?? 0.5 + let novelty = replyCentroid.map { 1 - normalizedSimilarity(candidate, $0) } ?? 0.5 return DialecticalEnergy(coherence: coherence, resonance: resonance, novelty: novelty) } @@ -137,7 +148,7 @@ public enum DialecticalDynamics { var pairs = 0 for i in 0.. Float { - let toThesis = normalized(c.cosineSimilarity(to: thesis)) - let toAnti = normalized(c.cosineSimilarity(to: antithesis)) + let toThesis = normalizedSimilarity(c, thesis) + let toAnti = normalizedSimilarity(c, antithesis) return min(toThesis, toAnti) } @@ -259,13 +270,15 @@ public enum DialecticalDynamics { /// L2-normalized mean of a set of embeddings — the "direction the dialogue /// has been travelling." Provenance (`modelID`/`version`/`dimension`) is - /// taken from the first element; embeddings of a different dimension are - /// skipped rather than trapping. Returns `nil` for an empty set. + /// taken from the first element. Returns `nil` for an empty set, and `nil` + /// if any member is not comparable with the first: a centroid over an + /// unannounced subset is a plausible vector that means nothing. public static func centroid(of embeddings: [Embedding]) -> Embedding? { guard let first = embeddings.first else { return nil } + guard embeddings.allSatisfy({ $0.isComparable(with: first) }) else { return nil } let dim = first.values.count var sum = [Float](repeating: 0, count: dim) - for e in embeddings where e.values.count == dim { + for e in embeddings { for i in 0..= 2 else { return 0 } var acc: Float = 0 for i in 1..= edgeThreshold { edges.append(Edge(a: existing.id, b: node.id, weight: w)) } @@ -76,7 +76,7 @@ public struct SemanticGraph: Sendable { public func nearestPriorNodes(to query: Embedding, limit: Int, minSimilarity: Float = 0) -> [Node] { nodes - .map { ($0, DialecticalDynamics.normalized(query.cosineSimilarity(to: $0.embedding))) } + .map { ($0, DialecticalDynamics.normalizedSimilarity(query, $0.embedding)) } .filter { $0.1 >= minSimilarity } .sorted { $0.1 > $1.1 } .prefix(limit) diff --git a/Sources/BCICore/Models/Embedding.swift b/Sources/BCICore/Models/Embedding.swift index 9cdbff4..d879eea 100644 --- a/Sources/BCICore/Models/Embedding.swift +++ b/Sources/BCICore/Models/Embedding.swift @@ -51,12 +51,24 @@ public struct Embedding: Sendable, Equatable { self.seed = seed } + /// Whether a similarity between `self` and `other` exists to compute: same + /// `modelID`, same dimension, non-empty. Mirrors the Rust port + /// (`neuralcompose-hypnagogic/src/embedding.rs`). `seed` and `version` are + /// deliberately not checked: `DialecticalDynamics.centroid(of:)` builds + /// centroids with `seed: 0`, and a centroid must stay comparable to the + /// vectors it was averaged from. + public func isComparable(with other: Embedding) -> Bool { + modelID == other.modelID && values.count == other.values.count && !values.isEmpty + } + /// Cosine similarity to `other`. Because both operands are L2-normalized /// by the `values` invariant, this is just the dot product — no magnitude - /// division. Returns 0 when the dimensions differ (incomparable spaces) - /// rather than trapping. - public func cosineSimilarity(to other: Embedding) -> Float { - guard values.count == other.values.count else { return 0 } + /// division. Returns `nil` when the two are not comparable (different + /// space or dimension). `nil` is not a low score and not a failed + /// computation: no similarity exists to compute. `0` means orthogonal and + /// comparable, which is a different statement. + public func cosineSimilarity(to other: Embedding) -> Float? { + guard isComparable(with: other) else { return nil } var acc: Float = 0 for i in 0.. Double? guard let embeddings = try? await embedder.encode([source, output]), embeddings.count == 2 else { return nil } - return Double(embeddings[0].cosineSimilarity(to: embeddings[1])) + return Double(embeddings[0].cosineSimilarity(to: embeddings[1])!) } // MARK: - Evaluate each candidate diff --git a/Sources/SemanticEval/NearestNeighbors.swift b/Sources/SemanticEval/NearestNeighbors.swift index b58797a..4219e34 100644 --- a/Sources/SemanticEval/NearestNeighbors.swift +++ b/Sources/SemanticEval/NearestNeighbors.swift @@ -15,7 +15,7 @@ enum NearestNeighbors { k: Int ) -> [Neighbor] { let scored = zip(corpusTexts, corpusEmbeddings).map { text, embedding in - Neighbor(text: text, score: query.cosineSimilarity(to: embedding)) + Neighbor(text: text, score: query.cosineSimilarity(to: embedding)!) } return Array(scored.sorted { $0.score > $1.score }.prefix(k)) } diff --git a/Sources/SemanticEval/main.swift b/Sources/SemanticEval/main.swift index 0849a1a..7e419c1 100644 --- a/Sources/SemanticEval/main.swift +++ b/Sources/SemanticEval/main.swift @@ -30,7 +30,7 @@ func fail(_ message: String) -> Never { func pairScores(_ pairs: [[String]], embeddingByText: [String: Embedding]) -> [SemanticEvalResult.PairScore] { pairs.map { pair in let a = pair[0], b = pair[1] - let score = embeddingByText[a]!.cosineSimilarity(to: embeddingByText[b]!) + let score = embeddingByText[a]!.cosineSimilarity(to: embeddingByText[b]!)! return .init(a: a, b: b, score: score) } } @@ -42,7 +42,7 @@ func meanPairwiseSimilarity(_ texts: [String], embeddingByText: [String: Embeddi var count = 0 for i in 0..