|
| 1 | +""" |
| 2 | +Multimodal Synchronization Example |
| 3 | +---------------------------------- |
| 4 | +Aligns Open Ephys EMG data with Hand Tracking landmarks. |
| 5 | +
|
| 6 | +This script demonstrates: |
| 7 | +1. Loading EMG data from an Open Ephys session (or mock data). |
| 8 | +2. Loading Landmark data from a .npz file (captured via udp_landmark_logger.py). |
| 9 | +3. Computing the movement signal from 3D hand landmarks. |
| 10 | +4. Computing the EMG envelope. |
| 11 | +5. Finding the temporal offset to align the two streams. |
| 12 | +
|
| 13 | +Usage: |
| 14 | + python sync_multimodal_data.py --emg <path_to_session> --landmarks landmarks.npz |
| 15 | +""" |
| 16 | + |
| 17 | +import argparse |
| 18 | +import numpy as np |
| 19 | +import matplotlib.pyplot as plt |
| 20 | +from pyoephys.processing import ( |
| 21 | + compute_landmark_movement_signal, |
| 22 | + compute_emg_envelope_signal, |
| 23 | + find_sync_offset |
| 24 | +) |
| 25 | +from pyoephys.io import load_open_ephys_session |
| 26 | + |
| 27 | +def create_mock_data(duration=30.0, emg_fs=2000, landmark_fs=30.0, offset_sec=2.5): |
| 28 | + """Generate aligned mock data if no files provided.""" |
| 29 | + print("Generating mock data...") |
| 30 | + t_emg = np.arange(0, duration, 1/emg_fs) |
| 31 | + t_lm = np.arange(0, duration, 1/landmark_fs) |
| 32 | + |
| 33 | + # Common activity profile (e.g., 3 bursts) |
| 34 | + activity = np.zeros_like(t_emg) |
| 35 | + burst_times = [5.0, 15.0, 25.0] |
| 36 | + for bt in burst_times: |
| 37 | + # gaussian burst |
| 38 | + activity += np.exp(-0.5 * ((t_emg - bt - offset_sec) / 0.5)**2) |
| 39 | + |
| 40 | + # EMG = noise modulated by activity |
| 41 | + emg_data = np.random.randn(8, len(t_emg)) * (1 + 10 * activity) |
| 42 | + |
| 43 | + # Landmarks = velocity matches activity |
| 44 | + # We integrate activity to get position, so derivative (velocity) matches activity |
| 45 | + # Here we just fake the landmarks array directly |
| 46 | + n_frames = len(t_lm) |
| 47 | + landmarks = np.zeros((n_frames, 21, 3)) |
| 48 | + |
| 49 | + # Add movement at burst times (unshifted time for landmarks, shifted for EMG) |
| 50 | + # Effectively EMG is delayed by offset_sec relative to ground truth event, or vice versa |
| 51 | + # Let's say Event happens at t. Landmarks see it at t. EMG sees it at t + offset. |
| 52 | + |
| 53 | + # Re-do: |
| 54 | + # Event times: 5, 15, 25 |
| 55 | + # Landing on landmarks at: 5, 15, 25 |
| 56 | + # Landing on EMG at: 5+offset, 15+offset, 25+offset |
| 57 | + |
| 58 | + # Landmark movement |
| 59 | + for i, t in enumerate(t_lm): |
| 60 | + dist = np.min(np.abs(t - np.array(burst_times))) |
| 61 | + if dist < 1.0: |
| 62 | + # Move index finger |
| 63 | + landmarks[i, 8, 1] = np.sin(20 * t) * 0.1 |
| 64 | + |
| 65 | + return emg_data, t_emg, landmarks, t_lm |
| 66 | + |
| 67 | +def main(): |
| 68 | + parser = argparse.ArgumentParser() |
| 69 | + parser.add_argument("--emg", type=str, help="Path to Open Ephys Session folder") |
| 70 | + parser.add_argument("--landmarks", type=str, help="Path to landmarks.npz") |
| 71 | + args = parser.parse_args() |
| 72 | + |
| 73 | + if args.emg and args.landmarks: |
| 74 | + # Load Real Data |
| 75 | + print(f"Loading EMG from {args.emg}...") |
| 76 | + session = load_open_ephys_session(args.emg) |
| 77 | + emg_data = session['amplifier_data'] |
| 78 | + emg_fs = session['sample_rate'] |
| 79 | + t_emg = np.arange(emg_data.shape[1]) / emg_fs |
| 80 | + |
| 81 | + print(f"Loading Landmarks from {args.landmarks}...") |
| 82 | + lm_data = np.load(args.landmarks) |
| 83 | + # (T, Hands, 21, 3) -> take first hand |
| 84 | + landmarks = lm_data['landmarks'][:, 0, :, :] |
| 85 | + t_lm = lm_data['timestamps'] |
| 86 | + # zero-align timestamps for relative processing if needed, |
| 87 | + # usually we use "system time" for both, so we keep absolute. |
| 88 | + |
| 89 | + else: |
| 90 | + # Use Mock Data |
| 91 | + emg_data, t_emg, landmarks, t_lm = create_mock_data() |
| 92 | + emg_fs = 1.0 / (t_emg[1] - t_emg[0]) |
| 93 | + |
| 94 | + # 1. Process Landmarks -> Movement Signal |
| 95 | + print("Computing landmark movement signal...") |
| 96 | + # landmarks shape: (frames, 21, 3) |
| 97 | + lm_signal, t_lm_clean = compute_landmark_movement_signal(landmarks, t_lm) |
| 98 | + |
| 99 | + # 2. Process EMG -> Envelope |
| 100 | + print("Computing EMG envelope...") |
| 101 | + emg_env, t_emg_env = compute_emg_envelope_signal(emg_data, emg_fs) |
| 102 | + |
| 103 | + # 3. Find Sync |
| 104 | + print("Calculating synchronization offset...") |
| 105 | + # This finds lag such that: emg(t) ~ lm(t + offset) |
| 106 | + # Positive offset => Landmarks are DELAYED relative to EMG? |
| 107 | + # Check docstring: "Positive offset means landmarks are DELAYED relative to EMG." |
| 108 | + sync_result = find_sync_offset(emg_env, t_emg_env, lm_signal, t_lm_clean) |
| 109 | + |
| 110 | + offset = sync_result['offset_sec'] |
| 111 | + conf = sync_result['confidence'] |
| 112 | + print(f"\nFound Offset: {offset:.4f} seconds") |
| 113 | + print(f"Confidence: {conf:.2f}") |
| 114 | + |
| 115 | + # 4. Plot |
| 116 | + plt.figure(figsize=(10, 6)) |
| 117 | + |
| 118 | + # Normalize for plotting |
| 119 | + def norm(x): return (x - np.mean(x)) / np.std(x) |
| 120 | + |
| 121 | + plt.subplot(2, 1, 1) |
| 122 | + plt.title("Original Signals") |
| 123 | + plt.plot(t_emg_env, norm(emg_env), label="EMG Envelope", alpha=0.7) |
| 124 | + plt.plot(t_lm_clean, norm(lm_signal), label="Landmark Movement", alpha=0.7) |
| 125 | + plt.legend() |
| 126 | + plt.grid(True) |
| 127 | + |
| 128 | + plt.subplot(2, 1, 2) |
| 129 | + plt.title(f"Aligned (Landmarks shifted by {-offset:.2f}s)") |
| 130 | + plt.plot(t_emg_env, norm(emg_env), label="EMG Envelope", alpha=0.7) |
| 131 | + plt.plot(t_lm_clean - offset, norm(lm_signal), label="Aligned Landmarks", alpha=0.7) |
| 132 | + plt.legend() |
| 133 | + plt.grid(True) |
| 134 | + |
| 135 | + plt.tight_layout() |
| 136 | + plt.show() |
| 137 | + |
| 138 | +if __name__ == "__main__": |
| 139 | + main() |
0 commit comments