### Install physioKIT with pip Source: https://github.com/ambiqai/physiokit/blob/main/README.md Install physioKIT using pip. Requires Python 3.12 or later. ```console pip install physiokit ``` -------------------------------- ### Install dev dependencies Source: https://github.com/ambiqai/physiokit/blob/main/CONTRIBUTING.md Installs development dependencies using uv. Run after forking and branching to set up the environment. ```bash uv sync --group dev ``` -------------------------------- ### Install physioKIT with uv Source: https://github.com/ambiqai/physiokit/blob/main/README.md Install physioKIT using uv. Requires Python 3.12 or later. ```console uv add physiokit ``` -------------------------------- ### Build and serve docs Source: https://github.com/ambiqai/physiokit/blob/main/CONTRIBUTING.md Installs documentation dependencies and serves the MkDocs site locally for previewing. ```bash uv sync --group docs uv run mkdocs serve ``` -------------------------------- ### ECG quickstart: synthesize, clean, and compute HR/HRV Source: https://github.com/ambiqai/physiokit/blob/main/docs/index.md Synthesizes a 5-second ECG signal at 70 BPM, cleans it, detects peaks, computes RR intervals, filters them, and then derives heart rate and time-domain HRV metrics. Requires numpy and physiokit. ```python import numpy as np import physiokit as pk fs = 500 ecg, segs, fids = pk.ecg.synthesize(signal_length=5*fs, sample_rate=fs, heart_rate=70, leads=1) ecg = ecg.squeeze() ecg_clean = pk.ecg.clean(ecg, sample_rate=fs) peaks = pk.ecg.find_peaks(ecg_clean, sample_rate=fs) rri = pk.ecg.compute_rr_intervals(peaks) mask = pk.ecg.filter_rr_intervals(rri, sample_rate=fs) hr_bpm, _ = pk.ecg.compute_heart_rate(ecg_clean, sample_rate=fs) hrv_td = pk.hrv.compute_hrv_time(rri[mask == 0], sample_rate=fs) ``` -------------------------------- ### PPG quickstart: compute heart rate and SpO₂ Source: https://github.com/ambiqai/physiokit/blob/main/docs/index.md Computes heart rate from a synthetic PPG signal using peak detection and estimates SpO₂ in time. Requires numpy and physiokit. ```python import numpy as np import physiokit as pk fs = 100 t = np.arange(0, 10, 1/fs) ppg = np.sin(2*np.pi*1.1*t) hr_bpm, qos = pk.ppg.compute_heart_rate(ppg, sample_rate=fs, method="peak") spo2 = pk.ppg.compute_spo2_in_time(ppg, ppg, sample_rate=fs) ``` -------------------------------- ### Generate, clean, and analyze synthetic ECG signal Source: https://github.com/ambiqai/physiokit/blob/main/docs/tutorial/quickstart.md This example demonstrates the core workflow of physiokit: generating a synthetic ECG signal, cleaning it, computing heart rate, extracting R-peaks and RR-intervals, and computing time-domain and frequency-domain HRV metrics. It uses a sample rate of 1000 Hz, a heart rate of 64 BPM, and an 8-second signal. The example assumes numpy is imported as np for the nanmean function. ```python import physiokit as pk sample_rate = 1000 # Hz heart_rate = 64 # BPM signal_length = 8*sample_rate # 8 seconds # Generate synthetic ECG signal ecg, segs, fids = pk.ecg.synthesize( signal_length=signal_length, sample_rate=sample_rate, heart_rate=heart_rate, leads=1 ) ecg = ecg.squeeze() # Clean ECG signal ecg_clean = pk.ecg.clean(ecg, sample_rate=sample_rate) # Compute heart rate hr_bpm, _ = pk.ecg.compute_heart_rate(ecg_clean, sample_rate=sample_rate) # Extract R-peaks and RR-intervals peaks = pk.ecg.find_peaks(ecg_clean, sample_rate=sample_rate) rri = pk.ecg.compute_rr_intervals(peaks) mask = pk.ecg.filter_rr_intervals(rri, sample_rate=sample_rate) # Re-compute heart rate hr_bpm = 60 / (np.nanmean(rri[mask == 0]) / sample_rate) # Compute HRV metrics hrv_td = pk.hrv.compute_hrv_time(rri[mask == 0], sample_rate=sample_rate) bands = [(0.04, 0.15), (0.15, 0.4), (0.4, 0.5)] hrv_fd = pk.hrv.compute_hrv_frequency( peaks[mask == 0], rri[mask == 0], bands=bands, sample_rate=sample_rate ) ``` -------------------------------- ### RSP quickstart: compute respiratory rate from peaks Source: https://github.com/ambiqai/physiokit/blob/main/docs/index.md Computes respiratory rate from a synthetic respiratory signal using peak detection. Requires numpy and physiokit. ```python import numpy as np import physiokit as pk fs = 25 t = np.arange(0, 40, 1/fs) rsp = np.sin(2*np.pi*0.2*t) bpm, qos = pk.rsp.compute_respiratory_rate(rsp, sample_rate=fs, method="peak") ``` -------------------------------- ### Compute frequency-domain HRV metrics with pk.hrv.compute_hrv_frequency Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/hrv.md Continues from the previous time-domain example to compute frequency-domain HRV metrics using pk.hrv.compute_hrv_frequency. It defines three frequency bands (VLF, LF, HF) and passes the filtered peaks and RR-intervals along with the sample rate. The ellipsis (...) indicates that the preceding code from the time-domain example is assumed to be present. ```python ... bands = [(0.04, 0.15), (0.15, 0.4), (0.4, 0.5)] hrv_fd = pk.hrv.compute_hrv_frequency( peaks[mask == 0], rri[mask == 0], bands=bands, sample_rate=fs ) ``` -------------------------------- ### Apply bandpass filter to ECG signal with pk.ecg.clean Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ecg.md Uses `pk.ecg.clean` to apply a bandpass filter with lowcut=1, highcut=30, order=5, and the given sample rate. The default filter is 0.5-40 Hz, but this example customizes it. The input `ecg` is a synthetic signal from a previous example. ```python ... # Using ECG signal from above ^ ecg_clean = pk.ecg.clean( data=ecg, lowcut=1, highcut=30, order=5, sample_rate=sample_rate ) ``` -------------------------------- ### Generate synthetic PPG signal with pk.ppg.synthesize Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ppg.md Creates a synthetic PPG signal with specified heart rate, sample rate, and signal length. Returns the signal, segments, and fiducial points. The example uses a heart rate of 64 BPM, 1000 Hz sampling, and 10 seconds duration. ```python import physiokit as pk sample_rate = 1000 # Hz heart_rate = 64 # BPM signal_length = 10*sample_rate # 10 seconds ppg, segs, fids = pk.ppg.synthesize( signal_length=signal_length, sample_rate=sample_rate, heart_rate=heart_rate, frequency_modulation=0.3, ibi_randomness=0.1 ) ``` -------------------------------- ### Compute dual band metrics with synthetic data Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/rsp.md Generates synthetic ribcage (RC) and abdominal (AB) signals using pk.rsp.synthesize, then computes dual band metrics over a sliding window of 10 seconds with 1-second overlap. The example sets sample rate, respiratory rate, amplitudes, and signal duration. Note the plot output is referenced externally and not included here. ```python sample_rate = 1000 respiratory_rate = 12.2 rc_amp = 1.5 ab_amp = 1.0 dur_sec = 60 win_len = 10*sample_rate ovl_len = 1*sample_rate # Synthesize RC and AB band data rc, segs, fids = pk.rsp.synthesize( signal_length=dur_sec*sample_rate, sample_rate=sample_rate, respiratory_rate=respiratory_rate ) rc = rc * rc_amp ab, segs, fids = pk.rsp.synthesize( signal_length=dur_sec*sample_rate, sample_rate=sample_rate, respiratory_rate=respiratory_rate ) ab = ab * ab_amp # Compute metrics over sliding window ts_metrics, dual_metrics = [], [] for i in range(0, rc.size - win_len, ovl_len): rc_win = rc[i:i+win_len] ab_win = ab[i:i+win_len] ts_metrics.append((i+win_len/2)/sample_rate) dual_metrics.append(pk.rsp.compute_dual_band_metrics( rc=rc_win, ab=ab_win, sample_rate=sample_rate, pwr_threshold=0.9 )) ``` -------------------------------- ### Compute time-domain HRV metrics with pk.hrv.compute_hrv_time Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/hrv.md Generates a synthetic ECG signal, extracts R-peaks and RR-intervals, and computes time-domain HRV metrics using pk.hrv.compute_hrv_time. The example sets a target heart rate of 64 BPM, a sample rate of 1000 Hz, and an 8-second signal. It cleans the ECG, finds peaks, filters RR-intervals, and passes the filtered intervals to compute_hrv_time. ```python import numpy as np import physiokit as pk tgt_hr = 64 # BPM fs = 1000 # Hz signal_length = 8 * fs # 8 seconds # Generate synthetic ECG signal ecg, segs, fids = pk.ecg.synthesize( signal_length=signal_length, sample_rate=fs, heart_rate=tgt_hr, leads=1 ) ecg = ecg.squeeze() # Create timestamps ts = np.arange(0, ecg.size) / fs # Clean ECG signal ecg_clean = pk.ecg.clean( data=ecg, lowcut=2, highcut=30, order=5, sample_rate=fs ) # Extract R-peaks and RR-intervals peaks = pk.ecg.find_peaks(ecg_clean, sample_rate=fs) rri = pk.ecg.compute_rr_intervals(peaks) mask = pk.ecg.filter_rr_intervals(rri, sample_rate=fs) # Compute HRV metrics hrv_td = pk.hrv.compute_hrv_time( rr_intervals=rri[mask == 0], sample_rate=fs ) ``` -------------------------------- ### Compute heart rate with ppg.compute_heart_rate using FFT method Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ppg.md Computes heart rate in BPM and a quality-of-signal (QoS) metric between 0 and 1 using the FFT method. The QoS indicates signal quality, with 1 being high quality. The example continues from a prior preprocessing step and expects a cleaned PPG signal and sample rate. ```python # Compute heart rate using FFT hr_bpm, hr_qos = pk.ppg.compute_heart_rate( ppg_clean, method="fft", sample_rate=sample_rate ) ``` -------------------------------- ### Add noise sources to synthetic PPG signal Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/signal.md Generates a synthetic PPG signal and injects baseline wander, powerline noise, and additional noise sources using pk.signal.add_baseline_wander, pk.signal.add_powerline_noise, and pk.signal.add_noise_sources. The example shows how to chain noise injection functions with specified amplitudes and frequencies. ```python import physiokit as pk fs = 1000 # Hz tgt_hr = 64 # BPM ppg = pk.ppg.synthesize( duration=10, # in seconds sample_rate=fs, heart_rate=tgt_hr, ) # Add baseline wander ppg_noise = pk.signal.add_baseline_wander( data=ppg, amplitude=2, frequency=1, sample_rate=fs ) # Add powerline noise ppg_noise = pk.signal.add_powerline_noise( data=ppg_noise, amplitude=0.05, frequency=60, sample_rate=fs ) # Add additional noise sources ppg_noise = pk.signal.add_noise_sources( data=ppg_noise, amplitudes=[0.05, 0.05], frequencies=[10, 20], sample_rate=fs ) ``` -------------------------------- ### Add noise to PPG signal with pk.signal functions Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ppg.md Adds baseline wander, powerline noise, and custom noise sources to an existing PPG signal. The example uses amplitude and frequency parameters for each noise type, and the noise_shapes parameter for custom noise. ```python # Add baseline wander ppg_noise = pk.signal.add_baseline_wander( data=ppg, amplitude=1, frequency=0.5, sample_rate=sample_rate ) # Add powerline noise ppg_noise = pk.signal.add_powerline_noise( data=ppg_noise, amplitude=0.05, frequency=60, sample_rate=sample_rate ) # Add additional noise sources ppg_noise = pk.signal.add_noise_sources( data=ppg_noise, amplitudes=[0.05, 0.05], frequencies=[10, 20], noise_shapes=["laplace", "laplace"], sample_rate=sample_rate ) ``` -------------------------------- ### Create a branch Source: https://github.com/ambiqai/physiokit/blob/main/CONTRIBUTING.md Creates a new branch for your contribution. Replace 'your-name/short-description' with your own naming convention. ```bash git checkout -b your-name/short-description ``` -------------------------------- ### Format code Source: https://github.com/ambiqai/physiokit/blob/main/CONTRIBUTING.md Formats the codebase using ruff. ```bash uv run ruff format ``` -------------------------------- ### Run tests Source: https://github.com/ambiqai/physiokit/blob/main/CONTRIBUTING.md Runs the test suite located in the tests/ directory. ```bash uv run pytest tests/ ``` -------------------------------- ### Compute SpO2 from synthetic PPG signals Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Shows how to compute SpO2 from red and infrared PPG signals using both time-domain (compute_spo2_in_time) and frequency-domain (compute_spo2_in_frequency) methods with MAX8614x coefficients. Both functions take the same parameters: ppg1, ppg2, coefs, lowcut, highcut, and sample_rate. ```python ppg_red = ... ppg_ir = ... max8614x_coefs = [-16.666666, 8.333333, 100] # Compute SpO2 in time domain spo2_td = pk.ppg.compute_spo2_in_time( ppg1=ppg_red, ppg2=ppg_ir, coefs=max8614x_coefs, lowcut=0.5, highcut=4, sample_rate=sample_rate ) # Compute SpO2 in frequency domain spo2_fd = pk.ppg.compute_spo2_in_frequency( ppg1=ppg_red, ppg2=ppg_ir, coefs=max8614x_coefs, lowcut=0.5, highcut=4, sample_rate=sample_rate ) ``` -------------------------------- ### Add baseline wander, powerline noise, and custom noise to ECG signal Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ecg.md Adds baseline wander, powerline noise, and custom noise sources to an existing ECG signal. Uses pk.signal.add_baseline_wander, pk.signal.add_powerline_noise, pk.signal.add_noise_sources, and pk.signal.add_lead_noise. The example assumes a previous synthetic ECG signal and sample_rate variable. ```python # Add baseline wander ecg = pk.signal.add_baseline_wander( data=ecg, amplitude=1, frequency=1, sample_rate=sample_rate ) # Add powerline noise ecg = pk.signal.add_powerline_noise( data=ecg, amplitude=0.05, frequency=60, sample_rate=sample_rate ) # Add additional noise sources ecg = pk.signal.add_noise_sources( data=ecg, amplitudes=[0.05, 0.05], frequencies=[60, 80], noise_shapes=['laplace', 'laplace'], sample_rate=sample_rate ) ecg = pk.signal.add_lead_noise( data=ecg, scale=5e-2 ) ``` -------------------------------- ### Generate and process synthetic PPG signal with HRV metrics Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Sets up a 10-second PPG signal at 1000 Hz with a 64 BPM heart rate, adds baseline wander, powerline noise, additional noise sources, and lead noise. Then cleans the signal, detects peaks, filters RR intervals, computes heart rate (FFT method and from filtered RR intervals), and computes time-domain and frequency-domain HRV metrics. ```python sample_rate = 1000 # Hz heart_rate = 64 # BPM signal_length = 10 * sample_rate # 10 seconds # Generate synthetic PPG signal ppg, ppg_segs, ppg_fids = pk.ppg.synthesize( signal_length=signal_length, sample_rate=sample_rate, heart_rate=heart_rate, frequency_modulation=0.3, ibi_randomness=0.1, ) # Add baseline wander ppg_noise = pk.signal.add_baseline_wander(data=ppg, amplitude=1, frequency=0.5, sample_rate=sample_rate) # Add powerline noise ppg_noise = pk.signal.add_powerline_noise(data=ppg_noise, amplitude=0.05, frequency=60, sample_rate=sample_rate) # Add additional noise sources ppg_noise = pk.signal.add_noise_sources( data=ppg_noise, amplitudes=[0.05, 0.05], frequencies=[10, 20], sample_rate=sample_rate, noise_shapes=["laplace", "laplace"], ) # Add lead noise ppg_noise = pk.signal.add_lead_noise(data=ppg_noise, scale=1e-1) # Create timestamps tod = datetime.datetime(2025, 5, 24, random.randint(12, 23), 00) ts = np.arange(0, ppg.size) / sample_rate # Clean PPG signal ppg_clean = pk.ppg.clean(data=ppg_noise, lowcut=0.5, highcut=4, order=3, sample_rate=sample_rate) # Extract s-peaks and peak-to-peak intervals peaks = pk.ppg.find_peaks(data=ppg_clean, sample_rate=sample_rate) # Compute RR-intervals rri = pk.ppg.compute_rr_intervals(peaks=peaks) # Filter RR-intervals mask = pk.ppg.filter_rr_intervals(rr_ints=rri, sample_rate=sample_rate) # Compute heart rate hr_bpm, _ = pk.ppg.compute_heart_rate(data=ppg_clean, method="fft", sample_rate=sample_rate) # Re-compute heart rate hr_bpm = 60 / (np.nanmean(rri[mask == 0]) / sample_rate) # Compute HRV metrics hrv_td = pk.hrv.compute_hrv_time(rri[mask == 0], sample_rate=sample_rate) bands = [(0.04, 0.15), (0.15, 0.4), (0.4, 0.5)] hrv_fd = pk.hrv.compute_hrv_frequency(peaks[mask == 0], rri[mask == 0], bands=bands, sample_rate=sample_rate) ``` -------------------------------- ### Load accelerometer data from CSV files for different activities Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Sets sample rate to 500 Hz and reads three CSV files containing accelerometer data for sitting, walking, and running activities from the pulse-transit-time-ppg dataset. ```python sample_rate = 500 dfs = pd.read_csv("../data/pulse-transit-time-ppg/s8_sit.csv") dfw = pd.read_csv("../data/pulse-transit-time-ppg/s8_walk.csv") dfr = pd.read_csv("../data/pulse-transit-time-ppg/s8_run.csv") ``` -------------------------------- ### Compute dual-band respiratory metrics over sliding windows Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Iterates over 10-second windows with 1-second stride, computing dual-band metrics (RC and AB) using pk.rsp.compute_dual_band_metrics with a power threshold of 0.9. Collects timestamps and metric results for later plotting. ```python ts_metrics, dual_metrics = [], [] for i in range(0, rc.size - 10 * sample_rate, 1 * sample_rate): rc_win = rc[i : i + 10 * sample_rate] ab_win = ab[i : i + 10 * sample_rate] ts_metrics.append((i + 5 * sample_rate) / sample_rate) dual_metrics.append( pk.rsp.compute_dual_band_metrics(rc=rc_win, ab=ab_win, sample_rate=sample_rate, pwr_threshold=0.9) ) ``` -------------------------------- ### Compute Tilt Angles with pk.imu.compute_tilt_angles Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/imu.md Computes 3-axis tilt angles from accelerometer data. Requires loading accelerometer data into variables ax, ay, az before calling pk.imu.compute_tilt_angles. ```python import physiokit as pk # Load accelerometer data ax, ay, az = ... aax, aay, aaz = pk.imu.compute_tilt_angles(x=ax, y=ay, z=az) ``` -------------------------------- ### pk.ecg.derive_respiratory_rate - Compute respiratory rate using RIFV method Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ecg.md Derives respiratory rate in breaths per minute (BPM) and a QoS metric. Uses the default 'rifv' method, which analyzes frequency modulation of RR intervals. The code continues from a previous example, using peaks and rri arrays with a mask. The output is displayed as 'Respiratory Rate: 16 BPM'. QoS may be low in noisy environments or certain subjects. ```python ... # Compute respiratory rate using RIFV method rr_bpm, rr_qos = pk.ecg.derive_respiratory_rate( peaks=peaks[mask == 0], rri=rri[mask == 0], method="rifv", sample_rate=sample_rate ) ``` -------------------------------- ### Compute SpO2 with ppg.compute_spo2_in_time and ppg.compute_spo2_in_frequency Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ppg.md Computes SpO2 from two PPG signals (red and IR) using physioKIT's time-domain and frequency-domain routines. Requires raw PPG signals and sensor-specific coefficients (e.g., MAX8614x) for the 2nd order polynomial conversion. The output is a SpO2 percentage (e.g., 98%). ```python max8614x_coefs = [-16.666666, 8.333333, 100] # Load PPG signals ppg_red = ... ppg_ir = ... # NOTE: Pass the raw PPG signals as routines need to extract DC component # Compute SpO2 in time domain spo2_td = pk.ppg.compute_spo2_in_time( ppg1=ppg_red, ppg2=ppg_ir, coefs=max8614x_coefs, lowcut=0.5, highcut=4, sample_rate=sample_rate ) # Compute SpO2 in frequency domain spo2_fd = pk.ppg.compute_spo2_in_frequency( ppg1=ppg_red, ppg2=ppg_ir, coefs=max8614x_coefs, lowcut=0.5, highcut=4, sample_rate=sample_rate ) ``` -------------------------------- ### Compute Counts with pk.imu.compute_counts Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/imu.md Computes activity counts based on ActiGraph algorithms. Requires loading accelerometer data into variables ax, ay, az and defining sample rate fs. The result is summed over epochs of length 1 second. ```python import physiokit as pk # Load accelerometer data ax, ay, az = ... counts = np.sum(pk.imu.compute_counts( data=np.vstack((ax, ay, az)).T, sample_rate=fs, epoch_len=1 ), axis=1) ``` -------------------------------- ### Plot IMU acceleration traces with Plotly Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Creates a Plotly figure with three acceleration traces (X, Y, Z) and vertical dashed lines marking activity segments (Sit, Walk, Run). Saves the plot as an HTML file named pk_imu_accel.html using the CDN version of Plotly.js and displays it. ```python fig = go.Figure() fig.add_trace(go.Scatter(x=ts, y=ax, name="X", line_color=primary_color, line_width=2, mode="lines")) fig.add_trace(go.Scatter(x=ts, y=ay, name="Y", line_color=secondary_color, line_width=2, mode="lines")) fig.add_trace(go.Scatter(x=ts, y=az, name="Z", line_color=tertiary_color, line_width=2, mode="lines")) for name, loc in zip(["Sit", "Walk", "Run"], [1, 20, 40]): fig.add_vline( x=loc, line_width=1, line_dash="dash", line_color="white", annotation={"text": name, "textangle": 270} ) # END FOR fig.update_xaxes(title="Time (s)") fig.update_yaxes(title="Acceleration (g)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), title="", template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=60, b=20), height=300, ) fig.write_html(dst_path / "pk_imu_accel.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Configure Plotly MathJax and create new plot Source: https://github.com/ambiqai/physiokit/blob/main/docs/assets/pk-synthetic-ppg-raw.html Sets the PlotlyConfig global to use local MathJax, then checks for the presence of a div with the specified ID and calls Plotly.newPlot to render a plot. ```javascript window.PlotlyConfig = {MathJaxConfig: 'local'}; window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById("ad0948a5-ecb6-4609-a555-32c4b5ff9676")) { Plotly.newPlot( "ad0948a5-ecb6-4609-a555-32c4b5ff9676", ``` -------------------------------- ### Lint code Source: https://github.com/ambiqai/physiokit/blob/main/CONTRIBUTING.md Lints the codebase using ruff. ```bash uv run ruff check ``` -------------------------------- ### Compute ENMO, tilt angles, and activity counts from accelerometer data Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Computes ENMO, tilt angles, and activity counts using pk.imu functions. The counts are computed per 1-second epoch and summed across axes. A commented alternative using ENMO as input is also shown. ```python enmo = pk.imu.compute_enmo(x=ax, y=ay, z=az) aax, aay, aaz = pk.imu.compute_tilt_angles(x=ax, y=ay, z=az) counts = np.sum(pk.imu.compute_counts(data=np.vstack((ax, ay, az)).T, sample_rate=sample_rate, epoch_len=1), axis=1) # counts = np.max(pk.imu.compute_counts(data=enmo.reshape(-1, 1).repeat(3, axis=1), sample_rate=sample_rate, epoch_len=1), axis=1) ``` -------------------------------- ### Signal helpers: filter and compute FFT Source: https://github.com/ambiqai/physiokit/blob/main/docs/index.md Filters a synthetic signal with a bandpass and computes its FFT. Requires numpy and physiokit. ```python import numpy as np import physiokit as pk fs = 100 t = np.arange(0, 5, 1/fs) sig = np.sin(2*np.pi*2*t) + 0.2*np.random.randn(t.size) clean = pk.signal.filter_signal(sig, lowcut=0.5, highcut=20, sample_rate=fs) freqs, sp = pk.signal.compute_fft(clean, sample_rate=fs) ``` -------------------------------- ### Plot RSP with R-Peak Annotations Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Plots the cleaned RSP signal with vertical dashed lines at detected R-peak positions. Saves the plot as an HTML file and displays it. ```python fig = go.Figure() fig.add_trace( go.Scatter( x=ts, y=rsp_clean, line_color=secondary_color, name="RSP", line_width=4, ) ) for peak in peaks: fig.add_vline( x=ts[peak], line_width=1, line_dash="dash", line_color="white", # annotation={"text": "R-Peak", "textangle": -90} ) fig.update_yaxes(title="Amplitude (mV)") fig.update_xaxes(title="Time (s)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=20, b=20), height=300, ) fig.write_html(dst_path / "pk-synthetic-rsp-rpeak.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Define output path and sample rate Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Sets the output directory for HTML plots and the sample rate (1000 Hz) used throughout the ECG processing pipeline. ```python dst_path = Path("../docs/assets") sample_rate = 1000 # Hz ``` -------------------------------- ### IMU ENMO and tilt Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/index.md Computes ENMO and tilt angles from accelerometer data using pk.imu.compute_enmo and pk.imu.compute_tilt_angles. Prints the ENMO value and tilt angles in degrees. ```python import numpy as np import physiokit as pk x = np.array([0, 0.1, 0.2]) y = np.array([0, 0.1, 0.2]) z = np.array([1, 1.0, 1.1]) enmo = pk.imu.compute_enmo(x, y, z) angles = pk.imu.compute_tilt_angles(x, y, z, in_radians=False) print(enmo, angles) ``` -------------------------------- ### Add noise to RSP signal with pk.signal functions Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/rsp.md Adds baseline wander, powerline noise, and custom noise sources to the synthetic RSP signal to generate a more realistic signal. Uses pk.signal.add_baseline_wander, pk.signal.add_powerline_noise, and pk.signal.add_noise_sources. ```python # Add baseline wander rsp_noise = pk.signal.add_baseline_wander( data=rsp, amplitude=2, frequency=.05, sample_rate=sample_rate ) # Add powerline noise rsp_noise = pk.signal.add_powerline_noise( data=rsp_noise, amplitude=0.05, frequency=60, sample_rate=sample_rate ) # Add additional noise sources rsp_noise = pk.signal.add_noise_sources( data=rsp_noise, amplitudes=[0.05, 0.05], frequencies=[10, 20], noise_shapes=["laplace", "laplace"], sample_rate=sample_rate ) ``` -------------------------------- ### Plot Raw vs Clean RSP Signal Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Overlays the raw noisy RSP and the cleaned RSP signal for comparison. Saves the plot as an HTML file and displays it. ```python fig = go.Figure() fig.add_trace(go.Scatter(x=ts, y=rsp_noise, name="Raw RSP", line_color=primary_color, line_width=1, mode="lines")) fig.add_trace( go.Scatter( x=ts, y=rsp_clean, line_color=secondary_color, name="Clean RSP", line_width=4, ) ) fig.update_yaxes(title="Amplitude (mV)") fig.update_xaxes(title="Time (s)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=60, b=20), height=300, ) fig.write_html(dst_path / "pk-synthetic-rsp-clean.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Compute ENMO with pk.imu.compute_enmo Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/imu.md Computes the Euclidean Norm Minus One (ENMO) from 3-axis accelerometer data. Requires loading accelerometer data into variables ax, ay, az before calling pk.imu.compute_enmo. ```python import physiokit as pk # Load accelerometer data ax, ay, az = ... enmo = pk.imu.compute_enmo(x=ax, y=ay, z=az) ``` -------------------------------- ### Plot clean and noisy PPG signals overlay Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Creates a Plotly figure with two traces for raw noisy PPG and clean PPG, uses a horizontal legend at the top, and saves to 'pk-synthetic-ppg-clean.html'. The clean trace has a thicker line width for distinction. ```python fig = go.Figure() fig.add_trace(go.Scatter(x=ts, y=ppg_noise, name="Raw PPG", line_color=primary_color, line_width=2, mode="lines")) fig.add_trace( go.Scatter( x=ts, y=ppg_clean, line_color=secondary_color, name="Clean PPG", line_width=4, ) ) fig.update_yaxes(title="Amplitude (mV)") fig.update_xaxes(title="Time (s)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=60, b=20), height=300, ) fig.write_html(dst_path / "pk-synthetic-ppg-clean.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Create time array for accelerometer data Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Generates a time vector in seconds corresponding to the concatenated accelerometer samples. ```python ts = np.arange(0, ax.size) / sample_rate ``` -------------------------------- ### Import libraries for ECG analysis and plotting Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Imports required libraries for ECG synthesis, signal processing, and plotting. The import of pandas triggers a DeprecationWarning about Pyarrow becoming a required dependency in pandas 3.0. ```python import datetime import random import dataclasses from pathlib import Path from plotly.subplots import make_subplots import plotly.graph_objects as go import plotly.io as pio import pandas as pd import numpy as np import physiokit as pk ``` -------------------------------- ### Plot synthetic PPG signal with noise Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Creates a Plotly figure with a line trace of the noisy PPG signal, sets axis labels and layout with a dark template, and saves the figure as an HTML file named 'pk-synthetic-ppg-noise.html'. The margin and height are customized for a compact display. ```python fig = go.Figure() fig.add_trace(go.Scatter(x=ts, y=ppg_noise, name="PPG", line_color=primary_color, line_width=2, mode="lines")) fig.update_yaxes(title="Amplitude (mV)") fig.update_xaxes(title="Time (s)") fig.update_layout( template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=20, b=20), height=300, ) fig.write_html(dst_path / "pk-synthetic-ppg-noise.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Plot RSP with Inhale/Exhale Segments and Fiducials Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Creates a Plotly figure showing raw RSP signal with filled areas for inhale and exhale segments, plus markers for fiducial points. Saves the plot as an HTML file and displays it. ```python fig = go.Figure() inhale = np.where(rsp_segs == pk.rsp.RspSegment.inhale, rsp, 0) exhale = np.where(rsp_segs == pk.rsp.RspSegment.exhale, rsp, 0) fig.add_trace(go.Scatter(x=ts, y=rsp, name="RSP", line_width=4, line_color=primary_color, mode="lines")) fig.add_trace(go.Scatter(x=ts, y=inhale, line_width=0, line_color=tertiary_alpha_color, fill="tozeroy", name="Inhale")) fig.add_trace(go.Scatter(x=ts, y=exhale, line_width=0, line_color=secondary_alpha_color, fill="tozeroy", name="Exhale")) fid_pts = np.nonzero(rsp_fids) fig.add_trace( go.Scatter( x=ts[fid_pts], y=rsp[fid_pts], marker_size=8, line_color=primary_marker_color, mode="markers", name="Fiducials", showlegend=False, ) ) fig.update_yaxes(title="Amplitude (mV)") fig.update_xaxes(title="Time (s)") fig.update_layout( template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=20, b=20), height=300, ) fig.write_html(dst_path / "pk-synthetic-rsp-raw.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Plot ECG with R-peak annotations Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Creates a Plotly figure showing the clean ECG trace with vertical dashed lines at detected R-peak positions, annotated with 'R-Peak'. Saves to 'pk-synthetic-ecg-rpeak.html'. ```python fig = go.Figure() fig.add_trace( go.Scatter( x=ts, y=ecg_clean, line_color=secondary_color, name="ECG", line_width=4, ) ) for peak in peaks: fig.add_vline( x=ts[peak], line_width=1, line_dash="dash", line_color="white", annotation={"text": "R-Peak", "textangle": -90} ) fig.update_yaxes(title="Amplitude (mV)") fig.update_xaxes(title="Time (s)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=60, b=20), height=300, ) fig.write_html(dst_path / "pk-synthetic-ecg-rpeak.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Derive respiratory rate with ppg.derive_respiratory_rate using RIFV method Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ppg.md Derives respiratory rate in breaths per minute and a QoS metric using the RIFV method. The function relies on RR-intervals and PPG peaks, and the QoS is low when respiratory rate estimation is unreliable (e.g., in noisy environments). The snippet includes a placeholder '...' for preceding code. ```python ... # Compute respiratory rate using RIFV method rr_bpm, rr_qos = pk.ppg.derive_respiratory_rate( ppg=peaks[mask == 0], peaks=peaks[mask == 0], rri=rri[mask == 0], method="rifv", sample_rate=sample_rate ) ``` -------------------------------- ### Find PPG peaks and estimate SpO₂ Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/index.md Finds peaks in a synthetic PPG signal and estimates SpO₂ using pk.ppg.find_peaks and pk.ppg.compute_spo2_in_time. Prints the number of peaks and the SpO₂ value. ```python import numpy as np import physiokit as pk fs = 100 t = np.arange(0, 8, 1 / fs) ppg = np.sin(2 * np.pi * 1.1 * t) peaks = pk.ppg.find_peaks(ppg, sample_rate=fs) spo2 = pk.ppg.compute_spo2_in_time(ppg, ppg, sample_rate=fs) print(len(peaks), spo2) ``` -------------------------------- ### Plot tilt angles with Plotly Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Plots tilt angles (X, Y, Z) in degrees with activity segment markers. Saves the figure as pk_imu_tilts.html and displays it. ```python fig = go.Figure() fig.add_trace(go.Scatter(x=ts, y=aax, name="X", line_color=primary_color, line_width=2, mode="lines")) fig.add_trace(go.Scatter(x=ts, y=aay, name="Y", line_color=secondary_color, line_width=2, mode="lines")) fig.add_trace(go.Scatter(x=ts, y=aaz, name="Z", line_color=tertiary_color, line_width=2, mode="lines")) fig.update_xaxes(title="Time (s)") fig.update_yaxes(title="Angle (deg)") for name, loc in zip(["Sit", "Walk", "Run"], [1, 20, 40]): fig.add_vline( x=loc, line_width=1, line_dash="dash", line_color="white", annotation={"text": name, "textangle": 270} ) # END FOR fig.update_xaxes(title="Time (s)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), title="", template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=60, b=20), height=300, ) fig.write_html(dst_path / "pk_imu_tilts.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Generate synthetic ECG signal with pk.ecg.synthesize Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/ecg.md Generates a synthetic ECG signal with a heart rate of 64 BPM sampled at 1000 Hz for 8 seconds. Returns the ECG signal, segmentation, and fiducial mask of landmark features (e.g., P-wave). Uses the EcgPreset.SR preset and a noise multiplier of 0.1. ```python import numpy as np import physiokit as pk sample_rate = 1000 # Hz heart_rate = 64 # BPM signal_length = 8*sample_rate # 8 seconds ecg, segs, fids = pk.ecg.synthesize( signal_length=signal_length, sample_rate=sample_rate, heart_rate=heart_rate, leads=1, preset=pk.ecg.EcgPreset.SR, noise_multiplier=0.1 ) ``` -------------------------------- ### Plot ENMO signal with Plotly Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Plots the ENMO (Euclidean Norm Minus One) signal from IMU data with activity segment markers. Saves the figure as pk_imu_enmo.html and displays it. ```python fig = go.Figure() fig.add_trace(go.Scatter(x=ts, y=enmo, name="ENMO", line_color=primary_color, line_width=2, mode="lines")) for name, loc in zip(["Sit", "Walk", "Run"], [1, 20, 40]): fig.add_vline( x=loc, line_width=1, line_dash="dash", line_color="white", annotation={"text": name, "textangle": 270} ) # END FOR fig.update_xaxes(title="Time (s)") fig.update_layout( legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), title="", template="plotly_dark", plot_bgcolor=bg_color, paper_bgcolor=bg_color, margin=dict(l=10, r=5, t=40, b=20), height=300, ) fig.write_html(dst_path / "pk_imu_enmo.html", include_plotlyjs="cdn", full_html=False) fig.show() ``` -------------------------------- ### Clean RSP signal with pk.rsp.clean Source: https://github.com/ambiqai/physiokit/blob/main/docs/reference/rsp.md Use pk.rsp.clean to apply a bandpass filter with cutoff frequencies of 0.05 Hz and 3 Hz. Set the filter order with the 'order' parameter and specify the sampling rate in Hz with 'sample_rate'. The function returns a numpy array of the cleaned RSP signal. ```python # Clean RSP signal rsp_clean = pk.rsp.clean( data=rsp_noise, lowcut=0.05, highcut=3, order=3, sample_rate=sample_rate ) ``` -------------------------------- ### Convert HRV Metrics to Dictionary Source: https://github.com/ambiqai/physiokit/blob/main/notebooks/docs.ipynb Converts the HRV time-domain metrics dataclass to a dictionary using dataclasses.asdict. ```python dataclasses.asdict(hrv_td) ```