phrenic 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- phrenic/__init__.py +45 -0
- phrenic/api.py +467 -0
- phrenic/cli.py +332 -0
- phrenic/drive.py +406 -0
- phrenic/gas.py +141 -0
- phrenic/mechanics.py +226 -0
- phrenic/plot.py +78 -0
- phrenic/presets.py +110 -0
- phrenic/replay.py +385 -0
- phrenic/sensors.py +539 -0
- phrenic-0.1.0.dist-info/METADATA +137 -0
- phrenic-0.1.0.dist-info/RECORD +16 -0
- phrenic-0.1.0.dist-info/WHEEL +5 -0
- phrenic-0.1.0.dist-info/entry_points.txt +2 -0
- phrenic-0.1.0.dist-info/licenses/LICENSE +21 -0
- phrenic-0.1.0.dist-info/top_level.txt +1 -0
phrenic/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Mechanistic lung, chest-wall, and multi-sensor modelling of human breathing."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .api import simulate_respiration, simulate_sensors_from_flow
|
|
6
|
+
from .drive import simulate_mechanics_core
|
|
7
|
+
from .gas import simulate_two_pool_co2
|
|
8
|
+
from .mechanics import solve_lung_mechanics
|
|
9
|
+
from .plot import save_simulation_figure
|
|
10
|
+
from .presets import (
|
|
11
|
+
MECHANICS_PRESETS,
|
|
12
|
+
PRESET_SHARED_DEFAULTS,
|
|
13
|
+
resolve_mechanics_params,
|
|
14
|
+
)
|
|
15
|
+
from .replay import replay_sensor_array
|
|
16
|
+
from .sensors import (
|
|
17
|
+
apply_dc_rip_realism,
|
|
18
|
+
bold_rrf_from_volume,
|
|
19
|
+
capnogram_from_flow,
|
|
20
|
+
meg_head_coils_from_volume,
|
|
21
|
+
motion_artifact_wave,
|
|
22
|
+
thermistor_from_flow,
|
|
23
|
+
thoracic_impedance_from_chest,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"MECHANICS_PRESETS",
|
|
28
|
+
"PRESET_SHARED_DEFAULTS",
|
|
29
|
+
"__version__",
|
|
30
|
+
"apply_dc_rip_realism",
|
|
31
|
+
"bold_rrf_from_volume",
|
|
32
|
+
"capnogram_from_flow",
|
|
33
|
+
"meg_head_coils_from_volume",
|
|
34
|
+
"motion_artifact_wave",
|
|
35
|
+
"replay_sensor_array",
|
|
36
|
+
"resolve_mechanics_params",
|
|
37
|
+
"save_simulation_figure",
|
|
38
|
+
"simulate_mechanics_core",
|
|
39
|
+
"simulate_respiration",
|
|
40
|
+
"simulate_sensors_from_flow",
|
|
41
|
+
"simulate_two_pool_co2",
|
|
42
|
+
"solve_lung_mechanics",
|
|
43
|
+
"thermistor_from_flow",
|
|
44
|
+
"thoracic_impedance_from_chest",
|
|
45
|
+
]
|
phrenic/api.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""High-level public entry points for coupled multi-sensor respiratory simulation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from scipy.integrate import cumulative_trapezoid, trapezoid
|
|
10
|
+
from scipy.signal import butter, sosfiltfilt
|
|
11
|
+
|
|
12
|
+
from .drive import simulate_mechanics_core
|
|
13
|
+
from .mechanics import _split_chest_wall
|
|
14
|
+
from .presets import PRESET_SHARED_DEFAULTS, resolve_mechanics_params
|
|
15
|
+
from .sensors import _clock, _synthesize_sensors
|
|
16
|
+
|
|
17
|
+
_TRUTH_COLUMNS = (
|
|
18
|
+
"start_s", "insp_end_s", "exp_start_s", "exp_end_s", "end_s",
|
|
19
|
+
"duration_s", "ti_s", "te_active_s", "inh_pause_s", "exp_pause_s", "vt_l", "is_sigh",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _windows(intervals, duration, fs, name):
|
|
24
|
+
"""Validate times before merging adjacent windows on the sample grid."""
|
|
25
|
+
tol = 1e-9
|
|
26
|
+
try:
|
|
27
|
+
intervals = sorted(tuple(map(float, pair)) for pair in intervals)
|
|
28
|
+
if any(not np.isfinite([a, d]).all() or a < 0 or d <= 0 or
|
|
29
|
+
a + d > duration + tol for a, d in intervals):
|
|
30
|
+
raise ValueError
|
|
31
|
+
if any(a + d > b + tol for (a, d), (b, _) in itertools.pairwise(intervals)):
|
|
32
|
+
raise ValueError
|
|
33
|
+
except (TypeError, ValueError):
|
|
34
|
+
raise ValueError(f"{name} must contain non-overlapping (start, duration) pairs in the run") from None
|
|
35
|
+
windows = []
|
|
36
|
+
for a, d in intervals:
|
|
37
|
+
start, end = round(a * fs), round((a + d) * fs)
|
|
38
|
+
if end <= start:
|
|
39
|
+
raise ValueError(f"{name} intervals must span at least one sample")
|
|
40
|
+
if windows and start <= windows[-1][1]:
|
|
41
|
+
windows[-1] = (windows[-1][0], end)
|
|
42
|
+
else:
|
|
43
|
+
windows.append((start, end))
|
|
44
|
+
return windows
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _lobe(flow, start, end, depth, fs, skew):
|
|
48
|
+
u = np.linspace(0, 1, end - start + 1)
|
|
49
|
+
shape = np.sin(np.pi * u) ** 2 * (1 + skew * (1 - 2 * u))
|
|
50
|
+
shape[[0, -1]] = 0
|
|
51
|
+
shape *= depth / trapezoid(shape, dx=1 / fs)
|
|
52
|
+
stop = min(end + 1, len(flow))
|
|
53
|
+
if start < stop:
|
|
54
|
+
flow[start:stop] += shape[:stop - start]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def simulate_sensors_from_flow(
|
|
58
|
+
flow_l_s,
|
|
59
|
+
fs,
|
|
60
|
+
*,
|
|
61
|
+
volume_l=None,
|
|
62
|
+
baseline_correct=True,
|
|
63
|
+
rc_fraction=0.40,
|
|
64
|
+
rc_ab_lag_s=0.08,
|
|
65
|
+
ac_highpass_hz=0.05,
|
|
66
|
+
belt_clip_quantile=None,
|
|
67
|
+
loose_intervals_s=(),
|
|
68
|
+
motion_intervals_s=(),
|
|
69
|
+
mri_tr_s=1.5,
|
|
70
|
+
mri_shots_per_tr=8,
|
|
71
|
+
mri_pe_scale_mm_per_l=1.2,
|
|
72
|
+
mri_polarity=1,
|
|
73
|
+
ecg_fs=500.0,
|
|
74
|
+
heart_rate_bpm=68.0,
|
|
75
|
+
rsa_amp_bpm=3.0,
|
|
76
|
+
mayer_amp_bpm=2.5,
|
|
77
|
+
ectopic_rate_per_min=0.0,
|
|
78
|
+
qrs_mod_depth=0.20,
|
|
79
|
+
ppg_pwa_scale=1.0,
|
|
80
|
+
oral_leak_frac=0.0,
|
|
81
|
+
capno_delay_s=2.0,
|
|
82
|
+
dead_space_l=0.15,
|
|
83
|
+
etco2_mmhg=38.0,
|
|
84
|
+
thermistor_tau_s=0.70,
|
|
85
|
+
noise_level=0.01,
|
|
86
|
+
seed=0,
|
|
87
|
+
):
|
|
88
|
+
"""Run any calibrated airflow recording (L/s) through the coupled sensor layer."""
|
|
89
|
+
flow_in = np.asarray(flow_l_s, dtype=float)
|
|
90
|
+
if flow_in.ndim != 1 or len(flow_in) < 4 or not np.isfinite(flow_in).all():
|
|
91
|
+
raise ValueError("flow_l_s must be a finite 1D array with at least 4 samples")
|
|
92
|
+
fs = float(fs)
|
|
93
|
+
if not np.isfinite(fs) or fs <= 0:
|
|
94
|
+
raise ValueError("fs must be finite and positive")
|
|
95
|
+
if not 0 < rc_fraction < 1 or not np.isfinite(rc_ab_lag_s) or abs(rc_ab_lag_s) > 1.0:
|
|
96
|
+
raise ValueError("Expected 0 < rc_fraction < 1 and |rc_ab_lag_s| <= 1.0")
|
|
97
|
+
if not 0 <= ac_highpass_hz < fs / 2:
|
|
98
|
+
raise ValueError("ac_highpass_hz must be nonnegative and below Nyquist")
|
|
99
|
+
if belt_clip_quantile is not None and not 0 < belt_clip_quantile < 1:
|
|
100
|
+
raise ValueError("belt_clip_quantile must lie in (0, 1)")
|
|
101
|
+
if (not isinstance(mri_shots_per_tr, (int, np.integer)) or isinstance(mri_shots_per_tr, bool)
|
|
102
|
+
or mri_shots_per_tr < 1 or mri_polarity not in (-1, 1)):
|
|
103
|
+
raise ValueError("Expected positive integer mri_shots_per_tr and mri_polarity of -1 or 1")
|
|
104
|
+
if (not 0 <= qrs_mod_depth < 1 or rsa_amp_bpm >= heart_rate_bpm
|
|
105
|
+
or not np.isfinite(mayer_amp_bpm) or mayer_amp_bpm < 0 or noise_level < 0):
|
|
106
|
+
raise ValueError("Expected 0 <= qrs_mod_depth < 1, RSA below heart rate, and nonnegative noise")
|
|
107
|
+
if not np.isfinite(ppg_pwa_scale) or ppg_pwa_scale < 0:
|
|
108
|
+
raise ValueError("ppg_pwa_scale must be finite and nonnegative")
|
|
109
|
+
if not np.isfinite(oral_leak_frac) or not 0.0 <= oral_leak_frac <= 1.0:
|
|
110
|
+
raise ValueError("oral_leak_frac must lie in [0, 1]")
|
|
111
|
+
if (not np.isfinite(capno_delay_s) or capno_delay_s < 0
|
|
112
|
+
or not np.isfinite(dead_space_l) or dead_space_l <= 0
|
|
113
|
+
or not np.isfinite(etco2_mmhg) or etco2_mmhg <= 0
|
|
114
|
+
or not np.isfinite(thermistor_tau_s) or thermistor_tau_s < 0):
|
|
115
|
+
raise ValueError("Expected nonnegative capno_delay_s/thermistor_tau_s and positive dead_space_l/etco2_mmhg")
|
|
116
|
+
|
|
117
|
+
n = len(flow_in)
|
|
118
|
+
duration_s = n / fs
|
|
119
|
+
time = np.arange(n, dtype=float) / fs
|
|
120
|
+
latent_time = np.arange(n + 1, dtype=float) / fs
|
|
121
|
+
loose_pairs = tuple(tuple(pair) for pair in loose_intervals_s)
|
|
122
|
+
loose = _windows(loose_pairs, duration_s, fs, "loose_intervals_s")
|
|
123
|
+
motion_pairs = tuple(tuple(pair) for pair in motion_intervals_s)
|
|
124
|
+
motion_windows = _windows(motion_pairs, duration_s, fs, "motion_intervals_s")
|
|
125
|
+
|
|
126
|
+
flow_pad = np.append(flow_in, flow_in[-1])
|
|
127
|
+
if volume_l is not None:
|
|
128
|
+
vol_in = np.asarray(volume_l, dtype=float)
|
|
129
|
+
if vol_in.shape != flow_in.shape or not np.isfinite(vol_in).all():
|
|
130
|
+
raise ValueError("volume_l must be a finite 1D array matching flow_l_s")
|
|
131
|
+
vol_pad = np.append(vol_in, vol_in[-1])
|
|
132
|
+
else:
|
|
133
|
+
raw_vol = cumulative_trapezoid(flow_pad, dx=1.0 / fs, initial=0.0)
|
|
134
|
+
if baseline_correct and duration_s > 25.0 and fs > 0.2:
|
|
135
|
+
sos = butter(2, 0.02, btype="highpass", fs=fs, output="sos")
|
|
136
|
+
detrended = sosfiltfilt(sos, raw_vol)
|
|
137
|
+
vol_pad = detrended - float(np.percentile(detrended, 5))
|
|
138
|
+
elif baseline_correct:
|
|
139
|
+
trend = np.linspace(raw_vol[0], raw_vol[-1], len(raw_vol))
|
|
140
|
+
detrended = raw_vol - trend
|
|
141
|
+
vol_pad = detrended - float(np.percentile(detrended, 5))
|
|
142
|
+
else:
|
|
143
|
+
vol_pad = raw_vol
|
|
144
|
+
|
|
145
|
+
v_rc, v_ab = _split_chest_wall(vol_pad, flow_pad, fs, rc_fraction, rc_ab_lag_s)
|
|
146
|
+
vt_est = float(max(0.1, np.percentile(vol_pad[:n], 95) - np.percentile(vol_pad[:n], 5)))
|
|
147
|
+
rng = np.random.default_rng(seed)
|
|
148
|
+
sensors = _synthesize_sensors(
|
|
149
|
+
time=time, latent_time=latent_time, flow=flow_pad, volume=vol_pad,
|
|
150
|
+
belt_source=v_ab[:n] / (1.0 - rc_fraction),
|
|
151
|
+
fs=fs, duration_s=duration_s, vt_l=vt_est, rate_bpm=14.0, duty_cycle=0.40,
|
|
152
|
+
ac_highpass_hz=ac_highpass_hz, belt_clip_quantile=belt_clip_quantile, loose=loose,
|
|
153
|
+
motion_windows=motion_windows,
|
|
154
|
+
mri_tr_s=mri_tr_s, mri_shots_per_tr=mri_shots_per_tr,
|
|
155
|
+
mri_pe_scale_mm_per_l=mri_pe_scale_mm_per_l, mri_polarity=mri_polarity,
|
|
156
|
+
ecg_fs=ecg_fs, heart_rate_bpm=heart_rate_bpm, rsa_amp_bpm=rsa_amp_bpm,
|
|
157
|
+
mayer_amp_bpm=mayer_amp_bpm, qrs_mod_depth=qrs_mod_depth, ectopic_rate_per_min=ectopic_rate_per_min,
|
|
158
|
+
ppg_pwa_scale=ppg_pwa_scale, oral_leak_frac=oral_leak_frac,
|
|
159
|
+
noise_level=noise_level, include_extended=True, pmus=None,
|
|
160
|
+
rip_chest=v_rc, rip_abdomen=v_ab,
|
|
161
|
+
flow_fast=None, flow_slow=None, heterogeneity=0.0,
|
|
162
|
+
capno_delay_s=capno_delay_s, dead_space_l=dead_space_l, etco2_mmhg=etco2_mmhg,
|
|
163
|
+
thermistor_tau_s=thermistor_tau_s, rng=rng,
|
|
164
|
+
)
|
|
165
|
+
return {"time_s": time, "fs": fs, **sensors}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def simulate_respiration(
|
|
169
|
+
duration_s=180.0, fs=100.0, rate_bpm=None, rate_sd_bpm=None,
|
|
170
|
+
duty_cycle=0.40, inh_pause_s=0.15, exp_pause_s=0.40, vt_l=None, vt_cv=None,
|
|
171
|
+
sigh_times_s=(), sigh_scale=2.2, hold_intervals_s=(), hold_phase="trough",
|
|
172
|
+
ac_highpass_hz=0.05, belt_clip_quantile=None, loose_intervals_s=(),
|
|
173
|
+
mri_tr_s=1.5, mri_shots_per_tr=8, mri_pe_scale_mm_per_l=1.2, mri_polarity=1,
|
|
174
|
+
ecg_fs=500.0, heart_rate_bpm=68.0, rsa_amp_bpm=None, qrs_mod_depth=0.20,
|
|
175
|
+
noise_level=0.01, seed=0,
|
|
176
|
+
*,
|
|
177
|
+
model=None,
|
|
178
|
+
preset=None,
|
|
179
|
+
resistance_cmh2o_s_l=None,
|
|
180
|
+
rohrer_k2=None,
|
|
181
|
+
compliance_l_cmh2o=None,
|
|
182
|
+
exp_resistance_ratio=None,
|
|
183
|
+
volume_resistance_slope=None,
|
|
184
|
+
insp_drive_exp=None,
|
|
185
|
+
braking_tau_s=None,
|
|
186
|
+
ventilation_heterogeneity=None,
|
|
187
|
+
peak_pmus_cmh2o=None,
|
|
188
|
+
rc_fraction=None,
|
|
189
|
+
rc_ab_lag_s=None,
|
|
190
|
+
ar1_phi=None,
|
|
191
|
+
ar1_phi_depth=None,
|
|
192
|
+
drift_amp_frac=None,
|
|
193
|
+
post_sigh_pause_s=None,
|
|
194
|
+
post_sigh_scale=None,
|
|
195
|
+
periodic_cycle_s=None,
|
|
196
|
+
periodic_apnoea_frac=None,
|
|
197
|
+
obstructive_period_s=None,
|
|
198
|
+
obstructive_duration_s=None,
|
|
199
|
+
obstructive_intervals_s=(),
|
|
200
|
+
motion_intervals_s=(),
|
|
201
|
+
mayer_amp_bpm=None,
|
|
202
|
+
ectopic_rate_per_min=0.0,
|
|
203
|
+
ppg_pwa_scale=None,
|
|
204
|
+
oral_leak_frac=0.0,
|
|
205
|
+
capno_delay_s=2.0,
|
|
206
|
+
dead_space_l=0.15,
|
|
207
|
+
etco2_mmhg=38.0,
|
|
208
|
+
thermistor_tau_s=0.70,
|
|
209
|
+
swallow_times_s=(),
|
|
210
|
+
):
|
|
211
|
+
"""Generate coupled multi-sensor respiratory recordings on shared clocks."""
|
|
212
|
+
if model is None:
|
|
213
|
+
model = "mechanics" if preset is not None else "analytic"
|
|
214
|
+
if model not in ("analytic", "mechanics"):
|
|
215
|
+
raise ValueError("model must be 'analytic' or 'mechanics'")
|
|
216
|
+
if model == "analytic" and preset is not None:
|
|
217
|
+
raise ValueError("preset is only supported with model='mechanics'")
|
|
218
|
+
|
|
219
|
+
shared_defaults = {}
|
|
220
|
+
if model == "mechanics":
|
|
221
|
+
preset_key = "quiet_rest" if preset is None else preset
|
|
222
|
+
shared_defaults = PRESET_SHARED_DEFAULTS.get(preset_key, {})
|
|
223
|
+
if rate_bpm is None:
|
|
224
|
+
rate_bpm = shared_defaults.get("rate_bpm", 14.0)
|
|
225
|
+
if rate_sd_bpm is None:
|
|
226
|
+
rate_sd_bpm = shared_defaults.get("rate_sd_bpm", 1.0)
|
|
227
|
+
if vt_l is None:
|
|
228
|
+
vt_l = shared_defaults.get("vt_l", 0.50)
|
|
229
|
+
if vt_cv is None:
|
|
230
|
+
vt_cv = shared_defaults.get("vt_cv", 0.08)
|
|
231
|
+
if rsa_amp_bpm is None:
|
|
232
|
+
rsa_amp_bpm = shared_defaults.get("rsa_amp_bpm", 3.0 if model == "mechanics" else 6.0)
|
|
233
|
+
if mayer_amp_bpm is None:
|
|
234
|
+
mayer_amp_bpm = shared_defaults.get("mayer_amp_bpm", 2.5 if model == "mechanics" else 0.0)
|
|
235
|
+
if ppg_pwa_scale is None:
|
|
236
|
+
ppg_pwa_scale = shared_defaults.get("ppg_pwa_scale", 1.0)
|
|
237
|
+
|
|
238
|
+
params = locals().copy()
|
|
239
|
+
positive = {
|
|
240
|
+
"duration_s": duration_s, "fs": fs, "rate_bpm": rate_bpm, "vt_l": vt_l,
|
|
241
|
+
"mri_tr_s": mri_tr_s, "mri_pe_scale_mm_per_l": mri_pe_scale_mm_per_l,
|
|
242
|
+
"ecg_fs": ecg_fs, "heart_rate_bpm": heart_rate_bpm, "sigh_scale": sigh_scale,
|
|
243
|
+
"dead_space_l": dead_space_l, "etco2_mmhg": etco2_mmhg,
|
|
244
|
+
}
|
|
245
|
+
nonnegative = {
|
|
246
|
+
"rate_sd_bpm": rate_sd_bpm, "inh_pause_s": inh_pause_s, "exp_pause_s": exp_pause_s,
|
|
247
|
+
"vt_cv": vt_cv, "rsa_amp_bpm": rsa_amp_bpm, "mayer_amp_bpm": mayer_amp_bpm,
|
|
248
|
+
"ppg_pwa_scale": ppg_pwa_scale, "oral_leak_frac": oral_leak_frac,
|
|
249
|
+
"capno_delay_s": capno_delay_s, "thermistor_tau_s": thermistor_tau_s,
|
|
250
|
+
"noise_level": noise_level,
|
|
251
|
+
}
|
|
252
|
+
mech_params = None
|
|
253
|
+
if model == "mechanics":
|
|
254
|
+
mech_params = resolve_mechanics_params(preset, {
|
|
255
|
+
"resistance_cmh2o_s_l": resistance_cmh2o_s_l,
|
|
256
|
+
"rohrer_k2": rohrer_k2,
|
|
257
|
+
"compliance_l_cmh2o": compliance_l_cmh2o,
|
|
258
|
+
"exp_resistance_ratio": exp_resistance_ratio,
|
|
259
|
+
"volume_resistance_slope": volume_resistance_slope,
|
|
260
|
+
"insp_drive_exp": insp_drive_exp,
|
|
261
|
+
"braking_tau_s": braking_tau_s,
|
|
262
|
+
"ventilation_heterogeneity": ventilation_heterogeneity,
|
|
263
|
+
"rc_fraction": rc_fraction,
|
|
264
|
+
"rc_ab_lag_s": rc_ab_lag_s,
|
|
265
|
+
"ar1_phi": ar1_phi,
|
|
266
|
+
"ar1_phi_depth": ar1_phi_depth,
|
|
267
|
+
"drift_amp_frac": drift_amp_frac,
|
|
268
|
+
"post_sigh_pause_s": post_sigh_pause_s,
|
|
269
|
+
"post_sigh_scale": post_sigh_scale,
|
|
270
|
+
"periodic_cycle_s": periodic_cycle_s,
|
|
271
|
+
"periodic_apnoea_frac": periodic_apnoea_frac,
|
|
272
|
+
"obstructive_period_s": obstructive_period_s,
|
|
273
|
+
"obstructive_duration_s": obstructive_duration_s,
|
|
274
|
+
})
|
|
275
|
+
params.update(mech_params)
|
|
276
|
+
positive.update(
|
|
277
|
+
resistance_cmh2o_s_l=mech_params["resistance_cmh2o_s_l"],
|
|
278
|
+
compliance_l_cmh2o=mech_params["compliance_l_cmh2o"],
|
|
279
|
+
exp_resistance_ratio=mech_params["exp_resistance_ratio"],
|
|
280
|
+
insp_drive_exp=mech_params["insp_drive_exp"],
|
|
281
|
+
post_sigh_scale=mech_params["post_sigh_scale"],
|
|
282
|
+
)
|
|
283
|
+
nonnegative.update(
|
|
284
|
+
rohrer_k2=mech_params["rohrer_k2"],
|
|
285
|
+
volume_resistance_slope=mech_params["volume_resistance_slope"],
|
|
286
|
+
braking_tau_s=mech_params["braking_tau_s"],
|
|
287
|
+
ventilation_heterogeneity=mech_params["ventilation_heterogeneity"],
|
|
288
|
+
drift_amp_frac=mech_params["drift_amp_frac"],
|
|
289
|
+
post_sigh_pause_s=mech_params["post_sigh_pause_s"],
|
|
290
|
+
periodic_cycle_s=mech_params["periodic_cycle_s"],
|
|
291
|
+
obstructive_period_s=mech_params["obstructive_period_s"],
|
|
292
|
+
obstructive_duration_s=mech_params["obstructive_duration_s"],
|
|
293
|
+
)
|
|
294
|
+
for name, value in (positive | nonnegative).items():
|
|
295
|
+
if not np.isfinite(value) or value < 0 or (name in positive and value == 0):
|
|
296
|
+
raise ValueError(f"{name} must be finite and {'positive' if name in positive else 'nonnegative'}")
|
|
297
|
+
if oral_leak_frac > 1.0:
|
|
298
|
+
raise ValueError("oral_leak_frac must lie in [0, 1]")
|
|
299
|
+
if mech_params is not None:
|
|
300
|
+
if peak_pmus_cmh2o is not None and (not np.isfinite(peak_pmus_cmh2o) or peak_pmus_cmh2o <= 0):
|
|
301
|
+
raise ValueError("peak_pmus_cmh2o must be finite and positive when provided")
|
|
302
|
+
if not 0.15 <= mech_params["insp_drive_exp"] <= 2.5:
|
|
303
|
+
raise ValueError("insp_drive_exp must lie in [0.15, 2.5]")
|
|
304
|
+
if not 0 < mech_params["rc_fraction"] < 1 or not np.isfinite(mech_params["rc_ab_lag_s"]) or abs(mech_params["rc_ab_lag_s"]) > 1.0:
|
|
305
|
+
raise ValueError("Expected 0 < rc_fraction < 1 and |rc_ab_lag_s| <= 1.0")
|
|
306
|
+
for phi_name in ("ar1_phi", "ar1_phi_depth"):
|
|
307
|
+
if not np.isfinite(mech_params[phi_name]) or not 0 <= mech_params[phi_name] < 1:
|
|
308
|
+
raise ValueError(f"{phi_name} must lie in [0, 1)")
|
|
309
|
+
if not 0 <= mech_params["ventilation_heterogeneity"] < 1:
|
|
310
|
+
raise ValueError("ventilation_heterogeneity must lie in [0, 1)")
|
|
311
|
+
if not 0 <= mech_params["periodic_apnoea_frac"] < 0.9:
|
|
312
|
+
raise ValueError("periodic_apnoea_frac must lie in [0, 0.9)")
|
|
313
|
+
if not 0 < duty_cycle < 1 or hold_phase not in ("trough", "peak"):
|
|
314
|
+
raise ValueError("Expected 0 < duty_cycle < 1 and hold_phase of trough or peak")
|
|
315
|
+
if not 0 <= ac_highpass_hz < fs / 2:
|
|
316
|
+
raise ValueError("ac_highpass_hz must be nonnegative and below Nyquist")
|
|
317
|
+
if belt_clip_quantile is not None and not 0 < belt_clip_quantile < 1:
|
|
318
|
+
raise ValueError("belt_clip_quantile must lie in (0, 1)")
|
|
319
|
+
if (not isinstance(mri_shots_per_tr, (int, np.integer)) or isinstance(mri_shots_per_tr, bool)
|
|
320
|
+
or mri_shots_per_tr < 1 or mri_polarity not in (-1, 1)):
|
|
321
|
+
raise ValueError("Expected positive integer mri_shots_per_tr and mri_polarity of -1 or 1")
|
|
322
|
+
if not 0 <= qrs_mod_depth < 1 or rsa_amp_bpm >= heart_rate_bpm:
|
|
323
|
+
raise ValueError("Expected 0 <= qrs_mod_depth < 1 and RSA amplitude below heart rate")
|
|
324
|
+
if sigh_scale < 1 or duration_s * fs < 2 or duration_s * ecg_fs < 2:
|
|
325
|
+
raise ValueError("Expected sigh_scale >= 1 and at least two samples per recording")
|
|
326
|
+
ip, ep = round(inh_pause_s * fs), round(exp_pause_s * fs)
|
|
327
|
+
if model == "analytic":
|
|
328
|
+
minimum = max(ip + ep + 4, 2 / duty_cycle, (ip + ep + 3) / (1 - duty_cycle))
|
|
329
|
+
if 60 * fs / rate_bpm < minimum:
|
|
330
|
+
raise ValueError("Breath period is too short for the duty cycle, pauses and sample rate")
|
|
331
|
+
|
|
332
|
+
for name in ("hold_intervals_s", "loose_intervals_s", "obstructive_intervals_s", "motion_intervals_s"):
|
|
333
|
+
try:
|
|
334
|
+
params[name] = tuple(tuple(pair) for pair in params[name])
|
|
335
|
+
except TypeError:
|
|
336
|
+
raise ValueError(f"{name} must contain (start, duration) pairs") from None
|
|
337
|
+
holds = _windows(params["hold_intervals_s"], duration_s, fs, "hold_intervals_s")
|
|
338
|
+
loose = _windows(params["loose_intervals_s"], duration_s, fs, "loose_intervals_s")
|
|
339
|
+
obstructive_windows = _windows(params["obstructive_intervals_s"], duration_s, fs, "obstructive_intervals_s")
|
|
340
|
+
motion_windows = _windows(params["motion_intervals_s"], duration_s, fs, "motion_intervals_s")
|
|
341
|
+
event_arrays = {}
|
|
342
|
+
for name, raw_times in (("sigh_times_s", sigh_times_s), ("swallow_times_s", swallow_times_s)):
|
|
343
|
+
try:
|
|
344
|
+
arr = np.asarray(tuple(raw_times), dtype=float)
|
|
345
|
+
except (TypeError, ValueError):
|
|
346
|
+
raise ValueError(f"{name} must contain finite times within the run") from None
|
|
347
|
+
params[name] = tuple(arr)
|
|
348
|
+
if arr.ndim != 1 or not np.isfinite(arr).all() or np.any((arr < 0) | (arr >= duration_s)):
|
|
349
|
+
raise ValueError(f"{name} must contain finite times within the run")
|
|
350
|
+
event_arrays[name] = arr
|
|
351
|
+
sighs, swallows = event_arrays["sigh_times_s"], event_arrays["swallow_times_s"]
|
|
352
|
+
|
|
353
|
+
rng = np.random.default_rng(seed)
|
|
354
|
+
time = _clock(duration_s, fs)
|
|
355
|
+
n = len(time)
|
|
356
|
+
latent_time = np.arange(n + 1) / fs
|
|
357
|
+
mech = None
|
|
358
|
+
if model == "mechanics":
|
|
359
|
+
mech = simulate_mechanics_core(
|
|
360
|
+
n=n, fs=fs, duration_s=duration_s, rate_bpm=rate_bpm, rate_sd_bpm=rate_sd_bpm,
|
|
361
|
+
duty_cycle=duty_cycle, vt_l=vt_l, vt_cv=vt_cv, sighs=sighs, sigh_scale=sigh_scale,
|
|
362
|
+
swallows=swallows, holds=holds, hold_phase=hold_phase,
|
|
363
|
+
obstructive_windows=obstructive_windows,
|
|
364
|
+
peak_pmus_cmh2o=peak_pmus_cmh2o, rng=rng, **mech_params,
|
|
365
|
+
)
|
|
366
|
+
flow = mech["flow"]
|
|
367
|
+
volume = mech["volume"]
|
|
368
|
+
sigh_windows = mech["sigh_windows_s"]
|
|
369
|
+
truth_df = mech["truth"]
|
|
370
|
+
belt_source = mech["rip_abdomen"][:n] / (1.0 - mech_params["rc_fraction"])
|
|
371
|
+
else:
|
|
372
|
+
flow = np.zeros(n + 1)
|
|
373
|
+
records = []
|
|
374
|
+
sigh_windows = []
|
|
375
|
+
start = 0
|
|
376
|
+
initial_volume = 0.0
|
|
377
|
+
while start < n:
|
|
378
|
+
rate = np.clip(rng.normal(rate_bpm, rate_sd_bpm), rate_bpm / 4, 60 * fs / minimum)
|
|
379
|
+
period = max(round(minimum), round(60 * fs / rate))
|
|
380
|
+
ti = min(period - ip - ep - 2, max(2, round(period * duty_cycle)))
|
|
381
|
+
te = period - ti - ip - ep
|
|
382
|
+
inh, exp = ip, ep
|
|
383
|
+
if holds:
|
|
384
|
+
anchor, stop = holds[0]
|
|
385
|
+
if anchor < start:
|
|
386
|
+
raise ValueError("Hold intervals are too close to fit the requested breath phase")
|
|
387
|
+
min_ti, min_te = (max(2, round(.25 * phase), min(phase, round(.25 * fs)))
|
|
388
|
+
for phase in (ti, te))
|
|
389
|
+
if hold_phase == "trough" and anchor <= start + 1.5 * period:
|
|
390
|
+
holds.pop(0)
|
|
391
|
+
if anchor == start == 0:
|
|
392
|
+
start = stop
|
|
393
|
+
continue
|
|
394
|
+
available = anchor - start
|
|
395
|
+
spare = available - min_ti - min_te
|
|
396
|
+
if spare < 0:
|
|
397
|
+
raise ValueError("Trough hold is too close to fit inspiration and expiration")
|
|
398
|
+
inh = min(ip, spare)
|
|
399
|
+
exp = min(ep, spare - inh)
|
|
400
|
+
ti = min(available - inh - exp - min_te, max(min_ti, round(available * duty_cycle)))
|
|
401
|
+
te = available - ti - inh - exp
|
|
402
|
+
exp += stop - anchor
|
|
403
|
+
elif hold_phase == "peak" and anchor <= start + period + ti / 2:
|
|
404
|
+
holds.pop(0)
|
|
405
|
+
ti = anchor - start
|
|
406
|
+
if holds:
|
|
407
|
+
room = holds[0][0] - stop - min_ti
|
|
408
|
+
if room < min_te:
|
|
409
|
+
raise ValueError("Peak holds are too close to fit expiration and inspiration")
|
|
410
|
+
inh = min(ip, max(0, room - te))
|
|
411
|
+
te = min(te, room - inh)
|
|
412
|
+
exp = min(ep, room - inh - te)
|
|
413
|
+
if anchor == start == 0:
|
|
414
|
+
initial_volume = vt_l
|
|
415
|
+
_lobe(flow, stop + inh, stop + inh + te, -initial_volume, fs, .45)
|
|
416
|
+
start = stop + inh + te + exp
|
|
417
|
+
continue
|
|
418
|
+
if ti < min_ti:
|
|
419
|
+
raise ValueError("Peak hold is too close to fit inspiration")
|
|
420
|
+
inh += stop - anchor
|
|
421
|
+
insp_end = start + ti
|
|
422
|
+
exp_start = insp_end + inh
|
|
423
|
+
exp_end = exp_start + te
|
|
424
|
+
end = exp_end + exp
|
|
425
|
+
sigh = bool(np.any((sighs >= start / fs) & (sighs < end / fs)))
|
|
426
|
+
if sigh:
|
|
427
|
+
sigh_windows.append((start / fs, min(end / fs, duration_s)))
|
|
428
|
+
sigma = np.sqrt(np.log1p(vt_cv ** 2))
|
|
429
|
+
depth = vt_l * np.exp(rng.normal(-sigma ** 2 / 2, sigma)) * (sigh_scale if sigh else 1)
|
|
430
|
+
_lobe(flow, start, insp_end, depth, fs, -.15)
|
|
431
|
+
_lobe(flow, exp_start, exp_end, -depth, fs, .45)
|
|
432
|
+
if end <= duration_s * fs + 1e-12:
|
|
433
|
+
records.append((*np.array([start, insp_end, exp_start, exp_end, end,
|
|
434
|
+
end - start, ti, te, inh, exp]) / fs, depth, sigh))
|
|
435
|
+
start = end
|
|
436
|
+
|
|
437
|
+
volume = initial_volume + cumulative_trapezoid(flow, dx=1 / fs, initial=0)
|
|
438
|
+
truth_df = pd.DataFrame(records, columns=_TRUTH_COLUMNS)
|
|
439
|
+
belt_source = volume[:n]
|
|
440
|
+
sensors = _synthesize_sensors(
|
|
441
|
+
time=time, latent_time=latent_time, flow=flow, volume=volume, belt_source=belt_source,
|
|
442
|
+
fs=fs, duration_s=duration_s, vt_l=vt_l, rate_bpm=rate_bpm, duty_cycle=duty_cycle,
|
|
443
|
+
ac_highpass_hz=ac_highpass_hz, belt_clip_quantile=belt_clip_quantile, loose=loose,
|
|
444
|
+
motion_windows=motion_windows,
|
|
445
|
+
mri_tr_s=mri_tr_s, mri_shots_per_tr=mri_shots_per_tr,
|
|
446
|
+
mri_pe_scale_mm_per_l=mri_pe_scale_mm_per_l, mri_polarity=mri_polarity,
|
|
447
|
+
ecg_fs=ecg_fs, heart_rate_bpm=heart_rate_bpm, rsa_amp_bpm=rsa_amp_bpm,
|
|
448
|
+
mayer_amp_bpm=mayer_amp_bpm, qrs_mod_depth=qrs_mod_depth, ectopic_rate_per_min=ectopic_rate_per_min,
|
|
449
|
+
ppg_pwa_scale=ppg_pwa_scale, oral_leak_frac=oral_leak_frac,
|
|
450
|
+
noise_level=noise_level, include_extended=(mech is not None),
|
|
451
|
+
pmus=(None if mech is None else mech["pmus"]),
|
|
452
|
+
rip_chest=(None if mech is None else mech["rip_chest"]),
|
|
453
|
+
rip_abdomen=(None if mech is None else mech["rip_abdomen"]),
|
|
454
|
+
flow_fast=(None if mech is None else mech["flow_fast"]),
|
|
455
|
+
flow_slow=(None if mech is None else mech["flow_slow"]),
|
|
456
|
+
heterogeneity=(0.0 if mech_params is None else mech_params["ventilation_heterogeneity"]),
|
|
457
|
+
capno_delay_s=capno_delay_s, dead_space_l=dead_space_l, etco2_mmhg=etco2_mmhg,
|
|
458
|
+
thermistor_tau_s=thermistor_tau_s, rng=rng,
|
|
459
|
+
)
|
|
460
|
+
result = {"time_s": time, "fs": fs, "sigh_windows_s": sigh_windows, "truth": truth_df,
|
|
461
|
+
**sensors, "params": params}
|
|
462
|
+
if mech is not None:
|
|
463
|
+
result.update(
|
|
464
|
+
pmus_cmh2o=mech["pmus"][:n],
|
|
465
|
+
alveolar_pressure_cmh2o=mech["alveolar_pressure"][:n],
|
|
466
|
+
)
|
|
467
|
+
return result
|