Skip to content

Biosensors and Physiological Signals

Every heartbeat, breath, muscle twitch, and rising tide of blood sugar writes a continuous physical story across the human body, yet neural networks can read none of it until a transducer turns wet biology into clean numbers. This file explores the four major biosensor physics families, the messy real-world artefacts and skin-tone biases that corrupt wearable recordings, the deep learning and foundation models that turn noisy waveforms into clinical warnings, and the closed-loop, milliwatt edge systems bringing continuous physiology to everyday life.

  • Place two fingers gently against your wrist and feel your pulse. Your brain effortlessly interprets that tiny throb as rhythm, speed, and strength. A silicon chip has no fingertips, no sense of taste for glucose, and no ear for heart murmurs. To let an algorithm understand living physiology, engineers build biosensors, tiny physical bridges that translate chemical concentrations, shifting light absorption, mechanical pressure waves, and cellular ionic currents into voltage or current time series.

  • Once a living process becomes an electrical ripple, an Analogue Front End (AFE) amplifies microvolt or microampere whispers, removes mains power interference, applies an anti-aliasing filter respecting the Nyquist limit from Chapter 09, and feeds a 16-to-24-bit analogue-to-digital converter (ADC). From that moment on, living biology enters the exact same world of discrete sequences, spectra, and neural encoders that powers speech, vision, and clinical AI.

The Four Major Biosensor Transduction Mechanisms

  • Nearly every hospital bedside monitor and consumer smartwatch rests on four physical mechanisms for turning biology into electricity. Understanding the physics of each sensor explains immediately why its signals look the way they do and exactly how they fail in the wild.

Optical Biosensors, PPG, and Pulse Oximetry

  • Hold a bright torch directly against your fingertip in a dark room and your finger glows ruby red. Look closely and that glow pulses almost imperceptibly in time with your heartbeat, because each cardiac contraction pushes a fresh wave of oxygen-rich blood into the tiny capillaries under your skin, briefly absorbing slightly more light before relaxing again.

  • Photoplethysmography (PPG) automates that exact trick by placing a miniature LED next to a photodiode on a finger clip, earlobe, or smartwatch back. Light travelling through tissue obeys the Beer-Lambert law, where transmitted intensity \(I(\lambda, t)\) decays exponentially with the wavelength-dependent molar extinction coefficient \(\varepsilon(\lambda)\), absorber concentration \(c\), and optical path length \(l\).

\[I(\lambda, t) = I_0(\lambda) \exp\!\left(-\varepsilon(\lambda)\, c\, l(t)\right)\]
  • In living skin, light absorption splits cleanly into two parts. A large, nearly constant DC component comes from bone, static tissue, skin pigment, and non-pulsatile venous blood, while a tiny oscillating AC component (often just \(0.5\%\) to \(2\%\) of the total signal) comes from expanding and relaxing arterial blood on every heartbeat. Tracking the peaks of that AC wave yields Heart Rate (HR) and Heart-Rate Variability (HRV), the beat-to-beat timing fluctuations that reveal autonomic nervous system balance, stress, and recovery.

  • To measure blood oxygen saturation (\(\text{SpO}_2\)) non-invasively, a pulse oximeter shines two alternating wavelengths, typically red (\(660\,\text{nm}\)) and infrared (\(940\,\text{nm}\)). Oxygenated haemoglobin (\(\text{HbO}_2\)) looks bright red because it lets red light pass while absorbing more infrared light, whereas deoxygenated haemoglobin (\(\text{Hb}\)) looks dark bluish-purple because it strongly absorbs red light at \(660\,\text{nm}\) and transmits more infrared light.

  • Dividing each wavelength's pulsatile AC amplitude by its static DC baseline cancels out LED brightness and steady tissue thickness, producing the dimensionless ratio of ratios \(R\).

\[R = \frac{\text{AC}_{660} / \text{DC}_{660}}{\text{AC}_{940} / \text{DC}_{940}} \approx \frac{\varepsilon_{\text{art}}(660, \text{SpO}_2)}{\varepsilon_{\text{art}}(940, \text{SpO}_2)}\]
  • A healthy person with \(\text{SpO}_2 \approx 98\%\) has a ratio near \(R \approx 0.5\), whereas falling oxygen levels raise red absorption and push \(R\) past \(1.0\). Because real tissue scatters light rather than acting like a tidy glass cuvette, medical oximeters map \(R\) to \(\text{SpO}_2\) through an empirically calibrated curve validated against arterial blood-gas laboratory draws.

Biopotential Sensors Across Heart, Muscle, Brain, and Skin

  • Inside living cells, electrical messages do not travel as free electrons along copper wire. They travel as charged ions (sodium \(\text{Na}^+\), potassium \(\text{K}^+\), calcium \(\text{Ca}^{2+}\), and chloride \(\text{Cl}^-\)) rushing across cell membranes. A biopotential electrode, most famously silver coated in silver chloride (\(\text{Ag/AgCl}\)), acts like a diplomatic translator at the skin boundary, converting ionic currents inside the body into tiny electronic currents entering an amplifier via reversible surface redox chemistry.

  • Different organs broadcast electrical signatures across vastly different voltage scales and frequency bands.

  • Electrocardiography (ECG) records millivolt-scale (\(0.5\text{ to }3\,\text{mV}\)) cardiac waves tracing each beat's electrical choreography, namely the P wave (atrial depolarisation), the sharp QRS complex (ventricular contraction), and the T wave (ventricular repolarisation). Smartwatches capture a single-lead ECG between the wrist back and a finger on the crown, while hospitals record twelve spatial angles to pinpoint localised heart attacks.
  • Surface Electromyography (sEMG) captures noisy microvolt-to-millivolt bursts (\(20\text{ to }500\,\text{Hz}\)) whenever skeletal muscle fibres fire, powering prosthetic limb control, ergonomic fatigue tracking, and silent wrist-band gesture interfaces.
  • Wearable EEG and Electrodermal Activity (EDA) bridge directly into Chapter 12 (NeuroAI). Scalp EEG measures faint microvolt cortical rhythms (\(5\text{ to }100\,\mu\text{V}\)) for sleep and seizure monitoring, while EDA applies a tiny constant voltage across two fingers or wrist pads to track subtle rises in sweat-gland skin conductance driven by sympathetic nervous system arousal.

  • Because the human body behaves like a walking antenna picking up \(50\,\text{Hz}\) or \(60\,\text{Hz}\) mains hum thousands of times stronger than an ECG or EEG signal, biopotential front ends rely on differential instrumentation amplifiers with a high Common-Mode Rejection Ratio (CMRR), subtracting identical room noise present on both electrodes while preserving the genuine voltage difference across the heart or cortex.

Electrochemical Biosensors, CGMs, and Microfluidic Sweat Patches

  • Measuring blood sugar without pricking a finger every ten minutes sounds like magic until you picture a miniature biochemical factory perched on a hair-thin filament under the skin. A Continuous Glucose Monitor (CGM) inserts a flexible sensor a few millimetres into the subcutaneous interstitial fluid bathing tissue cells and coats its tip with the enzyme glucose oxidase.

  • Whenever glucose molecules diffuse to the filament, the enzyme catalyses a selective reaction turning glucose and oxygen into gluconic acid and hydrogen peroxide (\(\text{H}_2\text{O}_2\)). A modest bias voltage (around \(0.6\,\text{V}\)) oxidises that hydrogen peroxide at a platinum electrode, releasing two electrons per glucose molecule and generating a clean nanoampere-to-microampere current proportional to local glucose concentration.

  • However, there is a crucial physiological catch that every diabetes algorithm must respect. Glucose leaves capillaries and diffuses slowly into interstitial fluid, creating a 5 to 15 minute physiological lag between true arterial blood glucose \(G_{\text{blood}}(t)\) and interstitial glucose \(G_{\text{int}}(t)\). Engineers commonly approximate this compartment delay with a first-order diffusion equation governed by a time constant \(\tau\) (typically \(8\text{ to }15\,\text{minutes}\)).

\[\tau \frac{dG_{\text{int}}(t)}{dt} = G_{\text{blood}}(t) - G_{\text{int}}(t)\]
  • When blood sugar sits steady overnight, the lag barely matters. During intense exercise or after an oversized insulin dose, blood sugar can plunge by \(3\,\text{mg/dL}\) every minute, meaning the CGM screen may still show a reassuring \(85\,\text{mg/dL}\) at the exact moment true blood glucose crosses into dangerous hypoglycaemia below \(70\,\text{mg/dL}\). Beyond glucose, next-generation microfluidic epidermal patches channel tiny droplets of sweat across multiplexed enzymatic and aptamer electrodes to track lactate (athletic exertion and sepsis), electrolytes (dehydration), and cortisol (stress physiology) without breaking the skin.

Mechanical and Acoustic Sensors

  • Not every biological clue is optical, electrical, or chemical. A great deal of health reveals itself through pure physical motion and sound waves.
  • MEMS accelerometers and Inertial Measurement Units (IMUs) pack microscopic silicon proof-masses suspended on springs inside a millimetre chip, capturing three-axis acceleration and angular velocity to quantify gait symmetry, fall detection, sleep restlessness, and the characteristic \(4\text{ to }6\,\text{Hz}\) resting hand tremor of Parkinson's disease.
  • Piezoelectric and capacitive pressure sensors generate voltage whenever stretched or compressed, reading radial artery pulse-wave velocity (a proxy for arterial stiffness and cuffless blood pressure trends) and ballistocardiography (the microscopic mechanical recoil of the body on every heartbeat, detectable even through a bed mattress).
  • Digital stethoscopes pair acoustic diaphragms with MEMS microphones to record cardiac valves closing and air whistling through narrowed bronchioles, feeding directly into time-frequency spectrogram classifiers shared with Chapter 10 (Audio and Speech).

Pipeline showing four major biosensor transduction families passing through an analogue front end and digital signal conditioning into clean physiological streams

Real-World Signal Challenges, Artefacts, and Fairness

  • Physiological waveforms look textbook-clean when a volunteer lies motionless in a quiet laboratory. Put that same sensor onto a runner sweating in cold rain or a restless patient turning in bed, and the signal quickly drowns in real-world physics.

Motion Artefacts and Adaptive LMS Filtering

  • Imagine trying to listen to a soft violin melody while standing right next to a pneumatic road drill. On a smartwatch during a brisk jog, every footstrike shakes the watch casing against the wrist and sloshes venous blood under the LEDs, injecting huge optical ripples right at the runner's step cadence (\(2.5\text{ to }3.0\,\text{Hz}\), or \(150\text{ to }180\) steps per minute). That noise sits smack inside the exact frequency band of a runner's heart rate, so a plain bandpass filter from Chapter 09 cannot separate them!

  • The breakthrough is sensor fusion with an adaptive noise canceller. Because the watch already carries a tri-axial accelerometer measuring the exact wrist movement \(x[n]\) without sensing the heartbeat, an Adaptive Least Mean Squares (LMS) filter (introduced in Chapter 09) continuously learns an \(M\)-tap finite impulse response vector \(\mathbf{w}[n]\) that mimics how physical motion leaks into the optical channel, subtracting the estimated motion interference \(\hat{m}[n]\) sample by sample from the corrupted PPG \(d[n]\).

\[\hat{m}[n] = \mathbf{w}[n]^T \mathbf{x}[n], \qquad e[n] = d[n] - \hat{m}[n], \qquad \mathbf{w}[n+1] = \mathbf{w}[n] + \mu\, e[n]\, \mathbf{x}[n]\]
  • Because the cardiac pulse is uncorrelated with the accelerometer reference \(\mathbf{x}[n]\), minimising the residual energy \(e[n]^2\) forces \(\hat{m}[n]\) to track the shifting motion coupling while leaving the clean heartbeat standing clearly in the residual \(e[n]\).

Baseline Wander, Skin-Tone Optical Bias, and Sensor Drift

  • Motion is only the first hurdle in building trustworthy biosensing systems. Three quieter failure modes routinely sabotage clinical reliability unless engineers address them head-on.
  • Baseline wander is a slow undulating drift below \(0.5\,\text{Hz}\) in ECG and PPG caused by chest-wall expansion during breathing, posture changes, and changing perspiration under electrodes. High-pass zero-phase filters, cubic spline interpolation, or wavelet detrending flatten the baseline without distorting delicate ECG ST-segment shifts that signal heart attacks.
  • Skin-tone optical bias is one of the most consequential fairness lessons in biomedical engineering. Epidermal melanin absorbs shorter green (\(525\,\text{nm}\)) and red (\(660\,\text{nm}\)) light far more strongly than infrared (\(940\,\text{nm}\)) light. On darker skin tones, raw optical reflectance drops sharply, shrinking signal-to-noise ratio in wrist PPG and introducing systematic overestimation of \(\text{SpO}_2\) in poorly calibrated pulse oximeters (a dangerous clinical phenomenon called occult hypoxaemia, where low blood oxygen looks falsely normal). Modern equitable designs combine adaptive LED drive currents, multi-wavelength optical modelling, and mandatory calibration trials across the full Monk and Fitzpatrick skin-tone spectrum.
  • Sensor drift and biofouling erode accuracy over days of wear. An implanted CGM filament gradually accumulates a microscopic blanket of immune proteins that slows glucose diffusion and drops sensitivity, requiring factory drift models, periodic blood-fingerstick recalibration, or on-device anomaly detectors that flag loose skin contact via a Signal Quality Index (SQI) before noisy segments ever reach a classifier.

AI Pipelines for Physiological Waveforms

  • Early wearable algorithms hunted for hand-crafted rules such as R-peak thresholds and spectral ratios. Those heuristics break quickly during irregular rhythms or everyday noise. Modern physiological AI combines signal-processing discipline with deep sequence modelling.

  • 1D Convolutional Neural Networks (1D CNNs) slide learned temporal filters directly across raw multi-lead ECG or PPG waveforms, acting like data-driven matched filters that detect subtle P-wave loss, ectopic beats, or QRS widening even amid noise. Transformers and State-Space Models extend that view across hours of continuous sleep or ICU telemetry, linking slow heart-rate trends, respiratory patterns, and sudden arousal bursts separated by tens of minutes.

  • Because labelled medical waveforms are expensive while unlabelled wearable recordings span billions of hours, self-supervised physiological foundation models have transformed the field. Using masked waveform reconstruction (hiding random 2-second chunks of PPG or ECG and predicting them from context) and cross-modal contrastive learning (aligning simultaneous ECG, PPG, and accelerometer views of the same heartbeat), a single pretrained physiological encoder adapts with very few labels to diverse clinical tasks.

  • Arrhythmia detection flags atrial fibrillation (AFib) from irregular beat-to-beat intervals and absent P waves, allowing quiet opportunistic screening on millions of wrists to prevent strokes.
  • Sleep staging fuses PPG heart-rate variability, respiratory oscillations, wrist actigraphy, and compact headband EEG to separate Wake, REM, Light, and Deep sleep without wiring patients up inside a sleep clinic.
  • Sepsis early warning watches subtle multi-vital trajectories inside hospital wards, spotting creeping tachycardia, narrowing HRV, rising respiratory rate, and dropping blood pressure hours before overt shock sets in.
  • Hypoglycaemia forecasting pairs recent CGM trajectories and their velocity with logged meals and active insulin-on-board (IOB) to warn patients 30 minutes ahead, effectively erasing the physiological interstitial lag before blood sugar hits dangerous levels.

Multimodal wearable fusion diagram connecting optical, IMU, and CGM sensors through adaptive denoising, physiological AI encoders, and closed-loop insulin actuation with physiological feedback

Closed-Loop Bio-Sensing and Ultra-Low-Power Edge Inference

  • Monitoring a signal passively is valuable, yet the ultimate ambition of BioAI is closing the loop so continuous sensing smoothly guides safe real-world therapy.

  • The flagship clinical triumph of closed-loop bio-sensing is Automated Insulin Delivery (AID), often called an artificial pancreas. Every five minutes, a wearable CGM sends interstitial glucose readings to a control algorithm driving a wearable insulin pump. Because subcutaneous rapid-acting insulin takes 15 minutes to start acting and peaks roughly an hour later, naive reactive dosing causes wild roller-coaster swings between high sugar and dangerous hypoglycaemia.

  • Modern AID controllers therefore rely on Model Predictive Control (MPC) or safety-constrained Reinforcement Learning (RL) paired with pharmacokinetic models of insulin-on-board and meal carbohydrate absorption. At every step, the controller simulates multiple future glucose trajectories over the next two to four hours, solving a constrained optimisation problem that nudges basal insulin gently up during post-meal rises and suspends delivery early whenever forecast glucose bends downward.

  • Running continuous physiological AI on a ring, watch, or skin patch imposes brutal energy limits. A typical smartwatch battery holds roughly one watt-hour of energy and must last days, leaving only a few milliwatts for continuous sensing and inference. Streaming raw \(250\,\text{Hz}\) waveforms continuously over Bluetooth or cellular radios both drains the battery in hours and exposes deeply intimate health data.

  • Solving that constraint draws directly on Chapter 20 (AI Inference) and Chapter 26 (Neuromorphic Computing). Wearables run cascaded early-exit pipelines, where an ultra-cheap tiny threshold or INT8-quantised 1D CNN running in microwatts watches continuously for suspicious rhythm shifts and wakes a heavier Transformer or requests a clinical confirmation only when an anomaly appears. Looking further ahead, event-driven neuromorphic front ends process spikes only when a waveform changes significantly rather than clocking dense multiply-accumulate loops during steady silence, cutting continuous edge power by orders of magnitude while keeping raw physiological traces private on the wearer's own wrist.

Take-Home

  • Biosensors turn wet living physiology into electrical time series across four physical families covering optical absorption (PPG and \(\text{SpO}_2\)), ionic biopotentials (ECG, EMG, EEG, EDA), enzyme-catalysed electrochemistry (CGMs and sweat patches), and mechanical or acoustic waves (IMUs and digital stethoscopes).
  • Real-world physics shapes every engineering challenge, from running motion overlapping heart-rate frequencies and slow respiratory baseline wander to 5-to-15-minute interstitial CGM diffusion lags and biofouling drift.
  • Sensor fusion and fairness are non-negotiable in wearable AI, pairing accelerometers with adaptive LMS filtering to strip away motion artefacts while designing multi-wavelength optical calibration across all skin tones to prevent occult hypoxaemia bias.
  • Physiological foundation models and temporal encoders unify raw 1D waveforms with multi-vital context to detect atrial fibrillation, stage sleep, warn early of sepsis, and forecast hypoglycaemia well ahead of danger.
  • Closed-loop bio-sensing and milliwatt edge inference turn passive health tracking into active therapy such as automated insulin delivery, relying on quantised cascaded models and event-driven neuromorphic front ends to stay safe, private, and multi-day battery efficient.

Coding Tasks (use CoLab or notebook)

  1. Build an Adaptive LMS Motion-Artefact Canceller that recovers a clean wrist PPG heart-rate waveform from a signal buried in running step-cadence motion noise using a synchronised accelerometer reference. Verify in both the time domain and BPM spectrum that adaptive filtering removes the false step-cadence peak and restores the true heart rate.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    k1, k2 = jax.random.split(jax.random.PRNGKey(42))
    fs, N = 50.0, 800
    t = jnp.arange(N) / fs
    
    # True cardiac PPG pulse at 78 BPM (1.30 Hz) with systolic peak and dicrotic notch
    f_hr = 78.0 / 60.0
    clean_ppg = (
        0.85 * jnp.sin(2.0 * jnp.pi * f_hr * t)
        + 0.35 * jnp.sin(4.0 * jnp.pi * f_hr * t - 0.7)
        + 0.12 * jnp.sin(6.0 * jnp.pi * f_hr * t - 1.2)
    )
    
    # Running wrist accelerometer reference (159 steps/min = 2.65 Hz) leaking through unknown tissue path
    phase_step = 2.0 * jnp.pi * (2.65 * t + 0.08 * jnp.sin(2.0 * jnp.pi * 0.12 * t))
    acc_ref = 1.1 * jnp.sin(phase_step) + 0.55 * jnp.sin(2.0 * phase_step + 0.5) + 0.45 * jax.random.normal(k1, (N,))
    h_true = jnp.array([2.1, -0.95, 0.50, -0.22])
    acc_pad = jnp.concatenate([jnp.zeros(len(h_true) - 1), acc_ref])
    motion_leak = sum(h_true[k] * acc_pad[len(h_true) - 1 - k : len(h_true) - 1 - k + N] for k in range(len(h_true)))
    corrupted_ppg = clean_ppg + motion_leak + 0.06 * jax.random.normal(k2, (N,))
    
    # Online normalised LMS adaptive filter (M = 6 taps)
    M, mu = 6, 0.09
    w = jnp.zeros(M)
    acc_lms = jnp.concatenate([jnp.zeros(M - 1), acc_ref])
    cleaned_list = []
    for n in range(N):
        x_vec = acc_lms[n : n + M][::-1]
        err = corrupted_ppg[n] - jnp.dot(w, x_vec)
        w = w + mu * err * x_vec / (jnp.dot(x_vec, x_vec) + 1.0)
        cleaned_list.append(err)
    cleaned_ppg = jnp.array(cleaned_list)
    
    sl = slice(N // 2, N)
    snr_before = 10.0 * jnp.log10(jnp.var(clean_ppg[sl]) / jnp.var(corrupted_ppg[sl] - clean_ppg[sl]))
    snr_after = 10.0 * jnp.log10(jnp.var(clean_ppg[sl]) / jnp.var(cleaned_ppg[sl] - clean_ppg[sl]))
    freqs_bpm = jnp.fft.rfftfreq(N // 2, d=1.0 / fs) * 60.0
    spec_raw, spec_lms = jnp.abs(jnp.fft.rfft(corrupted_ppg[sl])), jnp.abs(jnp.fft.rfft(cleaned_ppg[sl]))
    band = (freqs_bpm >= 45.0) & (freqs_bpm <= 200.0)
    print(f"Raw PPG peak: {float(freqs_bpm[band][jnp.argmax(spec_raw[band])]):.1f} BPM | LMS peak: {float(freqs_bpm[band][jnp.argmax(spec_lms[band])]):.1f} BPM (True 78.0)")
    print(f"PPG SNR -> Before LMS: {float(snr_before):.1f} dB | After LMS: {float(snr_after):.1f} dB")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.8, 3.6))
    axes[0].plot(t[-200:], corrupted_ppg[-200:], color="#e74c3c", alpha=0.45, lw=1.2, label="Corrupted PPG")
    axes[0].plot(t[-200:], clean_ppg[-200:], color="#27ae60", lw=2.2, linestyle="--", label="True Clean PPG")
    axes[0].plot(t[-200:], cleaned_ppg[-200:], color="#3498db", lw=1.8, label="LMS Recovered")
    axes[0].set_xlabel("Time (s)"); axes[0].set_ylabel("Amplitude"); axes[0].set_title("Time Domain Recovery")
    axes[0].legend(fontsize=8); axes[0].grid(alpha=0.3)
    
    axes[1].plot(freqs_bpm[band], spec_raw[band], color="#e74c3c", alpha=0.65, lw=1.8, label="Corrupted")
    axes[1].plot(freqs_bpm[band], spec_lms[band], color="#3498db", lw=2.2, label="LMS Cleaned")
    axes[1].axvline(78.0, color="#27ae60", linestyle="--", lw=1.5, label="True HR (78 BPM)")
    axes[1].set_xlabel("Frequency (BPM)"); axes[1].set_ylabel("Magnitude"); axes[1].set_title("BPM Spectrum")
    axes[1].legend(fontsize=8); axes[1].grid(alpha=0.3); plt.tight_layout(); plt.show()
    

  2. Simulate Beer-Lambert Dual-Wavelength Pulse Oximetry (\(\text{SpO}_2\)) at red (\(660\,\text{nm}\)) and infrared (\(940\,\text{nm}\)) wavelengths, computing the ratio of ratios \(R\) from \(75\%\) to \(100\%\) saturation. Then sweep epidermal melanin absorption across skin tones to observe how stronger red-light attenuation degrades SNR and increases \(\text{SpO}_2\) error at fixed LED power.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    eps_hbo2_r, eps_hb_r = 0.08, 0.80
    eps_hbo2_ir, eps_hb_ir = 0.29, 0.18
    t = jnp.linspace(0.0, 4.0, 400)
    delta_l = 0.08 * 0.5 * (1.0 + jnp.sin(2.0 * jnp.pi * 1.2 * t) + 0.3 * jnp.sin(4.0 * jnp.pi * 1.2 * t - 0.8))
    
    def simulate_oximetry(spo2_frac, melanin=0.0, noise_std=0.0, rng_key=None):
        eps_r = spo2_frac * eps_hbo2_r + (1.0 - spo2_frac) * eps_hb_r
        eps_ir = spo2_frac * eps_hbo2_ir + (1.0 - spo2_frac) * eps_hb_ir
        # Melanin attenuates 660 nm red light roughly 3x more strongly than 940 nm IR
        I_r = jnp.exp(-(0.90 + 1.15 * melanin + eps_r * delta_l))
        I_ir = jnp.exp(-(0.80 + 0.38 * melanin + eps_ir * delta_l))
        if noise_std > 0.0 and rng_key is not None:
            k1, k2 = jax.random.split(rng_key)
            I_r = I_r + noise_std * jax.random.normal(k1, I_r.shape)
            I_ir = I_ir + noise_std * jax.random.normal(k2, I_ir.shape)
        R = (jnp.std(I_r) / jnp.mean(I_r)) / (jnp.std(I_ir) / jnp.mean(I_ir) + 1e-8)
        spo2_est = (eps_hb_r - R * eps_hb_ir) / ((eps_hb_r - eps_hbo2_r) + R * (eps_hbo2_ir - eps_hb_ir))
        return R, spo2_est, jnp.std(I_r)
    
    spo2_grid = jnp.linspace(0.75, 1.00, 35)
    R_curve = jnp.array([simulate_oximetry(float(s))[0] for s in spo2_grid])
    
    melanin_levels = jnp.linspace(0.0, 2.2, 12)
    det_noise = 0.00022
    snr_red_db, spo2_rmse = [], []
    for idx, m in enumerate(melanin_levels):
        _, _, ac_clean = simulate_oximetry(0.92, melanin=float(m))
        subkeys = jax.random.split(jax.random.PRNGKey(100 + idx), 40)
        errs = jnp.array([(simulate_oximetry(0.92, float(m), det_noise, sk)[1] - 0.92) * 100.0 for sk in subkeys])
        snr_red_db.append(float(20.0 * jnp.log10(ac_clean / det_noise)))
        spo2_rmse.append(float(jnp.sqrt(jnp.mean(errs ** 2))))
    
    print(f"Clean R -> 98% SpO2: {float(simulate_oximetry(0.98)[0]):.2f} | 85% SpO2: {float(simulate_oximetry(0.85)[0]):.2f}")
    print(f"Light skin -> Red SNR: {snr_red_db[0]:.1f} dB, RMSE: {spo2_rmse[0]:.2f}% | Dark skin -> Red SNR: {snr_red_db[-1]:.1f} dB, RMSE: {spo2_rmse[-1]:.2f}%")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.8, 3.6))
    axes[0].plot(R_curve, spo2_grid * 100.0, color="#e74c3c", lw=2.4)
    axes[0].set_xlabel("Ratio of Ratios R"); axes[0].set_ylabel("True SpO2 (%)")
    axes[0].set_title("Beer-Lambert Calibration Curve"); axes[0].grid(alpha=0.3)
    
    ax_r = axes[1].twinx()
    l1 = axes[1].plot(melanin_levels, snr_red_db, color="#3498db", lw=2.2, marker="o", label="660 nm Red SNR (dB)")
    l2 = ax_r.plot(melanin_levels, spo2_rmse, color="#9b59b6", lw=2.2, linestyle="--", marker="s", label="SpO2 RMSE (%)")
    axes[1].set_xlabel("Epidermal Melanin Optical Depth"); axes[1].set_ylabel("Red SNR (dB)", color="#3498db")
    ax_r.set_ylabel("SpO2 RMSE (%)", color="#9b59b6"); axes[1].set_title("Fixed-Gain Skin-Tone Optical Bias")
    axes[1].legend(l1 + l2, [l.get_label() for l in l1 + l2], loc="center left", fontsize=8)
    axes[1].grid(alpha=0.3); plt.tight_layout(); plt.show()
    

  3. Simulate interstitial CGM physiological lag (\(\tau = 12\,\text{min}\)) across multi-day glucose, meal, and insulin traces, then train a 30-minute ahead hypoglycaemia forecaster using jax.grad. Compare the early-warning lead time before blood glucose crosses \(70\,\text{mg/dL}\) against waiting for the lagged CGM sensor to cross the alarm threshold.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    dt, tau, horizon = 5.0, 12.0, 6  # 5-min samples, 12-min lag, 30-min forecast horizon
    
    def simulate_day(rng_key):
        N = 144
        k1, k2, k3, k4 = jax.random.split(rng_key, 4)
        t_min = jnp.arange(N) * dt
        meal_t = jnp.array([90.0, 330.0]) + jax.random.uniform(k1, (2,), minval=-20.0, maxval=20.0)
        meal_s = jax.random.uniform(k2, (2,), minval=45.0, maxval=70.0)
        bolus_s = meal_s * jnp.array([0.68, 1.42])  # Oversized second bolus creates hypoglycaemia risk
    
        carb_r = ins_r = iob = cob = jnp.zeros(N)
        for mt, ms, bs in zip(meal_t, meal_s, bolus_s):
            d = jnp.maximum(t_min - mt, 0.0)
            on = (t_min >= mt).astype(jnp.float32)
            carb_r = carb_r + on * (ms / 28.0) * (d / 30.0) * jnp.exp(-d / 30.0)
            cob = cob + on * ms * jnp.exp(-d / 50.0)
            ins_r = ins_r + on * (bs / 30.0) * (d / 55.0) * jnp.exp(-d / 55.0)
            iob = iob + on * bs * jnp.exp(-d / 80.0)
    
        noise_bg = 0.5 * jax.random.normal(k3, (N,))
        gb, gint, gb_list, gint_list = 115.0, 115.0, [], []
        for i in range(N):
            gb = max(45.0, min(260.0, gb + dt * (0.005 * (110.0 - gb) + 1.85 * float(carb_r[i]) - 1.90 * float(ins_r[i])) + float(noise_bg[i])))
            gint = gint + (dt / tau) * (gb - gint)
            gb_list.append(gb); gint_list.append(gint)
        cgm = jnp.array(gint_list) + 1.8 * jax.random.normal(k4, (N,))
        return t_min, jnp.array(gb_list), cgm, iob, cob
    
    def build_dataset(day_keys):
        X_rows, y_rows = [], []
        for dk in day_keys:
            _, gb, cgm, iob, cob = simulate_day(dk)
            for i in range(2, len(gb) - horizon):
                vel = (cgm[i] - cgm[i - 2]) / (2.0 * dt)
                acc = (cgm[i] - 2.0 * cgm[i - 1] + cgm[i - 2]) / (dt ** 2)
                X_rows.append(jnp.array([cgm[i] / 100.0, cgm[i - 1] / 100.0, vel / 2.0, acc * 2.0, iob[i] / 50.0, cob[i] / 50.0, 1.0]))
                y_rows.append(gb[i + horizon] / 100.0)
        return jnp.stack(X_rows), jnp.array(y_rows)
    
    keys = jax.random.split(jax.random.PRNGKey(2026), 19)
    X_tr, y_tr = build_dataset(keys[:18])
    t_te, gb_te, cgm_te, _, _ = simulate_day(keys[18])
    X_te, y_te = build_dataset([keys[18]])
    
    w = jnp.zeros(X_tr.shape[1])
    g_fn = jax.grad(lambda w_: jnp.mean((X_tr @ w_ - y_tr) ** 2) + 1e-3 * jnp.sum(w_[:-1] ** 2))
    for _ in range(600):
        w = w - 0.05 * g_fn(w)
    
    pred_30, true_30 = (X_te @ w) * 100.0, y_te * 100.0
    t_fc = t_te[2 : len(gb_te) - horizon]
    print(f"30-Min RMSE -> Naive CGM: {float(jnp.sqrt(jnp.mean((cgm_te[2:-horizon] - true_30) ** 2))):.1f} mg/dL | AI: {float(jnp.sqrt(jnp.mean((pred_30 - true_30) ** 2))):.1f} mg/dL")
    
    t_true = float(t_te[int(jnp.where(gb_te < 70.0)[0][0])]) if jnp.any(gb_te < 70.0) else -1.0
    t_cgm = float(t_te[int(jnp.where(cgm_te < 70.0)[0][0])]) if jnp.any(cgm_te < 70.0) else -1.0
    t_ai = float(t_fc[int(jnp.where(pred_30 < 72.0)[0][0])]) if jnp.any(pred_30 < 72.0) else -1.0
    if t_true > 0 and t_ai > 0:
        print(f"True Hypo at t={t_true:.0f} min | AI warned {t_true - t_ai:.0f} min EARLY | Lagged CGM alarmed {max(0.0, t_cgm - t_true):.0f} min LATE")
    
    plt.figure(figsize=(10.2, 3.8))
    plt.plot(t_te, gb_te, color="#27ae60", lw=2.3, label="True Blood Glucose")
    plt.plot(t_te, cgm_te, color="#f39c12", lw=1.8, linestyle="--", label="Lagged Noisy CGM")
    plt.plot(t_fc, pred_30, color="#3498db", lw=2.2, label="AI 30-Min Ahead Forecast (at alert time)")
    plt.axhline(70.0, color="#e74c3c", linestyle=":", lw=1.8, label="Hypoglycaemia Threshold (70 mg/dL)")
    plt.xlabel("Time (minutes)"); plt.ylabel("Glucose (mg/dL)")
    plt.title("Overcoming Interstitial CGM Lag with 30-Minute Hypoglycaemia Forecasting")
    plt.legend(fontsize=8.5); plt.grid(alpha=0.3); plt.tight_layout(); plt.show()