RCVSIM: A Cardiovascular Simulator for Research (PhysioNet): sample notebook
A worked notebook for RCVSIM: A Cardiovascular Simulator for Research (PhysioNet), with 6 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.
- Provider
- Ramakrishna Mukkamala (MIT); distributed by PhysioNet
- License
- ODC-By-1.0
- Stored at
- Amazon S3, s3://physionet-open/rcvsim (us-east-1)
- Access
- Free and public. No account with the data provider is needed.
The notebook
Start here. Click the grey cell below and press Shift+Enter. It reads the simulator's parameter file from the archive and prints the values named in SHOW. Then put other names in SHOW (for example "Rpa" or "Cv") and run it again.
import math, os, re
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
SHOW = ["F", "Qtot", "Ra", "Cls", "Cld"]
ROOT = Path(os.environ.get("SCIGANTIC_MOUNT_PATH", "/mnt/archive")) / "1.0.0"
PARAMETER_FILE = ROOT / "bin" / "parameters.def"
def read_parameters(path):
"""Parse RCVSIM's 'name: value' parameter file. The comment above each value is kept as its description."""
values, notes, comment = {}, {}, []
for line in open(path):
line = line.strip()
if line.startswith("%"):
comment.append(line.lstrip("% ").strip())
continue
m = re.match(r"^([A-Za-z]\w*):\s*(.+)$", line)
if m:
nums = [float(v) for v in m.group(2).split()]
values[m.group(1)] = nums[0] if len(nums) == 1 else nums
notes[m.group(1)] = " ".join(c for c in comment if c)
comment = []
return values, notes
par, notes = read_parameters(PARAMETER_FILE)
print(f"{len(par)} parameters in {PARAMETER_FILE.name}")
for name in SHOW:
print(f" {name:5} = {par[name]:<6g} {notes[name]}")
RCVSIM: a cardiovascular simulator for research
RCVSIM (Research CardioVascular SIMulator) is a model of the human heart and circulation written by Ramakrishna Mukkamala at MIT and distributed by PhysioNet. It was made to generate realistic blood pressure, flow and volume waveforms, so that methods for analyzing real recordings can be tested on a system whose true parameters are known.
This archive is software, not recordings. It holds the MATLAB source, a parameter file, the user manual, and a Linux binary compiled in 2002. The cell below lists what is there.
rows = []
for folder in sorted(p for p in ROOT.iterdir() if p.is_dir()):
files = [f for f in folder.rglob("*") if f.is_file()]
biggest = sorted(files, key=lambda f: -f.stat().st_size)[:3]
rows.append((folder.name + "/", len(files), sum(f.stat().st_size for f in files) / 1e6, ", ".join(f.name for f in biggest)))
for name, n, mb, biggest in rows:
print(f"{name:6} {n:4} files {mb:7.1f} MB largest: {biggest}")
print()
with open(ROOT / "src" / "rcvsim", "rb") as fh:
head = fh.read(20)
print("src/rcvsim starts with", head[:4], "and is a", {1: "32-bit", 2: "64-bit"}[head[4]], "executable for machine type", head[18])
Output:
bin/ 5 files 0.0 MB largest: check_wfdb, check_redhat, header_def.m doc/ 190 files 99.5 MB largest: manual.ps, updateQfrs.eps, updateQtot.eps lib/ 9 files 8.3 MB largest: wfdb-10.1.6.tar.gz, libc-5.3.12-31.i386.rpm, libc.so.5 src/ 55 files 5.9 MB largest: rcvsim.c, simulate.c, rcvsim src/rcvsim starts with b'\x7fELF' and is a 32-bit executable for machine type 3
src/rcvsim is a 32-bit Intel (machine type 3) executable linked against the libc5 libraries in lib/, which current Linux systems no longer load, so it cannot be run in this notebook. The MATLAB source in src/ is complete and readable, though, and that is what the rest of this notebook uses.
The model
The "intact circulation" is six compartments in a loop: left ventricle, systemic arteries, systemic veins, right ventricle, pulmonary arteries, pulmonary veins. Each compartment has a compliance and an unstressed volume, and neighboring compartments are joined by a resistance. The two ventricles have a compliance that changes during the beat (stiff in systole, slack in diastole) and one-way valves on each side. The pulmonary bed and the vena cava can collapse when the pressure outside them is higher than the pressure inside.
The cell below is a Python version of that model. It follows src/intact_eval_deriv.m (the differential equations), intact_init_cond.m (the starting state), var_cap.m (ventricular elastance through the beat), vent_vol.m (the ventricular pressure-volume curve) and rk4.m with the main loop of simulate.m (fourth-order Runge-Kutta at the file's sampling rate). The reflexes, breathing and random disturbances that RCVSIM can add are left off, which is also the default in parameters.def. This Python version was checked against the original source run in GNU Octave.
K = 50.0 # sharpness of the knee in the ventricular pressure-volume curve (vent_vol.m)
def elastance(Cs, Cd, Tp, tc):
"""var_cap.m: normalized ventricular elastance and its time derivative, tc seconds into the beat."""
if Cd <= Cs:
return 1.0 / Cd, 0.0
Ts = 0.3 * math.sqrt(Tp); Tir = Ts / 2.0 # systole lasts 0.3*sqrt(beat length), relaxation half of that
amp = (1.0 / Cs - 1.0 / Cd) / 2.0
if tc < Ts:
return amp * (1 - math.cos(math.pi / Ts * tc)) + 1 / Cd, math.pi / Ts * amp * math.sin(math.pi / Ts * tc)
if tc >= Ts + Tir:
return 1.0 / Cd, 0.0
return amp * (1 + math.cos(math.pi / Tir * (tc - Ts))) + 1 / Cd, -math.pi / Tir * amp * math.sin(math.pi / Tir * (tc - Ts))
def _pv(x, E):
"""Normalized ventricular pressure for normalized volume x, and its slope."""
x0 = 1.0 / (E + 1.0)
d = 1 + math.exp(K * x0)
b = (1 - E) / (1 + (1 / K) * math.log((1 + math.exp(-K * (1 - x0))) / d))
e = math.exp(-K * (x - x0))
return E * x + b * (x + (1 / K) * math.log((1 + e) / d)), E + b * (1 - e / (1 + e))
def vent_vol(x, y, E, tol=1e-5):
"""vent_vol.m: Newton's method for the normalized volume that gives normalized pressure y."""
while True:
f, df = _pv(x, E)
xn = x - (f - y) / df
if abs(xn - x) <= tol:
return xn
x = xn
class Intact:
"""RCVSIM intact circulation (preparation 0) with reflexes, breathing and disturbances off."""
NAMES = ["left ventricle", "systemic arteries", "systemic veins", "right ventricle", "pulmonary arteries", "pulmonary veins"]
def __init__(self, par):
g = par.__getitem__
self.F, self.Qtot, self.Pvc, self.Palv = g("F"), g("Qtot"), g("Pvc"), g("Pvc")
self.Pth = g("Pvc") - (g("Qfr") - g("Qluo")) / g("Clu") # pressure in the chest at resting lung volume
self.Plmax, self.Prmax = g("Plmax"), g("Prmax")
self.Vl, self.Vr = g("Qlmax") - g("Qlo"), g("Qrmax") - g("Qro")
# ventricular compliances are stored normalized, as read_param.m does
self.Cls, self.Cld = g("Cls") * self.Plmax / self.Vl, g("Cld") * self.Plmax / self.Vl
self.Crs, self.Crd = g("Crs") * self.Prmax / self.Vr, g("Crd") * self.Prmax / self.Vr
self.C = np.array([np.nan, g("Ca"), g("Cv"), np.nan, g("Cpa"), g("Cpv")])
self.Q0 = np.array([g("Qlo"), g("Qao"), g("Qvo"), g("Qro"), g("Qpao"), g("Qpvo")])
self.Rl, self.Ra, self.Rv, self.Rr, self.Rpa, self.Rpv = (g(k) for k in ("Rl", "Ra", "Rv", "Rr", "Rpa", "Rpv"))
self.inchest = np.array([1, 0, 0, 1, 1, 1])
def pulmonary_flow(self, Ppa, Ppv):
"""Flow through lung vessels stacked over the height of the lung, each one collapsible."""
c = 1330 / (1.06 * 980)
h1 = min(20.0, max(-10.0, c * (Ppv - self.Palv)))
h2 = min(20.0, max(-10.0, c * (Ppa - self.Palv)))
R = 30 * self.Rpa
return (Ppa - Ppv) / R * (h1 + 10) + (Ppa - self.Palv) / R * (h2 - h1) - (1.06 * 980) / (2660 * R) * (h2 ** 2 - h1 ** 2)
def flows(self, P, strict=False):
"""Flow into the left ventricle, out of it, through the body, into the right ventricle, out of it, through the lungs."""
Pl, Pa, Pv, Pr, Ppa, Ppv = P
is_open = (lambda a, b: a > b) if strict else (lambda a, b: a >= b)
qli = (Ppv - Pl) / self.Rpv if is_open(Ppv, Pl) else 0.0
qlo = (Pl - Pa) / self.Rl if is_open(Pl, Pa) else 0.0
qa = (Pa - Pv) / self.Ra
if Pv > Pr and Pr >= self.Pvc:
qri = (Pv - Pr) / self.Rv
elif Pv > self.Pvc > Pr: # the vein collapses and limits the flow
qri = (Pv - self.Pvc) / self.Rv
else:
qri = 0.0
qro = (Pr - Ppa) / self.Rr if is_open(Pr, Ppa) else 0.0
return qli, qlo, qa, qri, qro, self.pulmonary_flow(Ppa, Ppv)
def _dP_ventricle(self, P, x_prev, Cs, Cd, Pmax, V, Q0, q_in, q_out, Tp, tc):
E, dE = elastance(Cs, Cd, Tp, tc)
if P < self.Pth:
g = (P - self.Pth) / (E * Q0 * (2 / math.pi))
return E * (q_in - q_out) * (1 + g * g) + (P - self.Pth) * (dE / E)
x = vent_vol(x_prev, (P - self.Pth) / Pmax, E)
x0 = 1 / (E + 1)
# ... 83 more lines in the notebook
Output:
model defined: left ventricle, systemic arteries, systemic veins, right ventricle, pulmonary arteries, pulmonary veins
A normal resting circulation
Run 30 seconds with the parameters exactly as they are in the file, and summarize the last 10 seconds, after the starting transient has settled.
def summarize(t, P, Q, q, last=10.0):
s = t >= t[-1] - last
return {
"arterial systolic (mmHg)": P[s, 1].max(),
"arterial diastolic (mmHg)": P[s, 1].min(),
"arterial mean (mmHg)": P[s, 1].mean(),
"pulmonary artery sys/dia (mmHg)": f"{P[s, 4].max():.0f}/{P[s, 4].min():.0f}",
"central venous mean (mmHg)": P[s, 2].mean(),
"LV end-diastolic volume (ml)": Q[s, 0].max(),
"LV end-systolic volume (ml)": Q[s, 0].min(),
"stroke volume (ml)": Q[s, 0].max() - Q[s, 0].min(),
"ejection fraction (%)": 100 * (Q[s, 0].max() - Q[s, 0].min()) / Q[s, 0].max(),
"cardiac output (L/min)": q[s, 2].mean() * 60 / 1000,
}
model = Intact(par)
t, P, Q, q, beats = model.run(30, fs=int(par["Fs"]))
base = summarize(t, P, Q, q)
print(f"heart rate {60 * par['F']:.0f} beats/min, {len(beats)} beats, {len(t):,} samples at {par['Fs']:.0f} Hz\n")
for k, v in base.items():
print(f" {k:34} {v if isinstance(v, str) else format(v, '.1f')}")
print(f"\n blood volume at the end: {Q[-1].sum():.1f} ml (parameter Qtot = {par['Qtot']:.0f})")
Output:
heart rate 72 beats/min, 36 beats, 3,750 samples at 125 Hz arterial systolic (mmHg) 110.8 arterial diastolic (mmHg) 74.9 arterial mean (mmHg) 93.4 pulmonary artery sys/dia (mmHg) 24/12 central venous mean (mmHg) 5.6 LV end-diastolic volume (ml) 134.0 LV end-systolic volume (ml) 60.3 stroke volume (ml) 73.7 ejection fraction (%) 55.0 cardiac output (L/min) 5.3 blood volume at the end: 5000.0 ml (parameter Qtot = 5000)
s = t >= t[-1] - 3
fig, ax = plt.subplots(1, 2, figsize=(11, 3.8), dpi=85, gridspec_kw={"width_ratios": [1.6, 1]})
ax[0].plot(t[s], P[s, 0], color="#b91c1c", lw=1.4, label="left ventricle")
ax[0].plot(t[s], P[s, 1], color="#1d4ed8", lw=1.4, label="systemic arteries")
ax[0].plot(t[s], P[s, 4], color="#15803d", lw=1.2, label="pulmonary arteries")
ax[0].plot(t[s], P[s, 2], color="#6b7280", lw=1.0, label="systemic veins")
ax[0].set_xlabel("time (s)"); ax[0].set_ylabel("pressure (mmHg)"); ax[0].set_title("Pressures over three seconds")
ax[0].legend(frameon=False, fontsize=8, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.2))
one = (t >= beats[-3]) & (t <= beats[-2])
ax[1].plot(Q[one, 0], P[one, 0], color="#b91c1c", lw=1.6)
ax[1].set_xlabel("left ventricular volume (ml)"); ax[1].set_ylabel("left ventricular pressure (mmHg)")
ax[1].set_title("One beat as a pressure-volume loop")
for a in ax:
a.spines[["top", "right"]].set_visible(False)
plt.tight_layout(); plt.show()
The left panel shows the usual pattern: left ventricular pressure rises until it exceeds arterial pressure, the aortic valve opens and the two move together, then the ventricle relaxes and arterial pressure decays through the body's resistance until the next beat. The right panel is the same beat drawn as volume against pressure. The loop runs counterclockwise: filling along the bottom, contraction up the right side, ejection across the top, relaxation down the left. Its width is the stroke volume.
Changing the physiology
Because every parameter has a physical meaning, a change in the patient is a change in one number. The cell below runs four cases. Reflexes are off in all of them, so these show the direct mechanical effect with no compensation from the nervous system. Turning the baroreflex on (baro in the parameter file) is what the full RCVSIM does and is not part of this Python version.
cases = {
"baseline": {},
"blood loss, 500 ml": {"Qtot": par["Qtot"] - 500},
"weak left ventricle (Cls x 2.5)": {"Cls": par["Cls"] * 2.5},
"high arterial resistance (Ra x 1.5)": {"Ra": par["Ra"] * 1.5},
}
keys = ["arterial systolic (mmHg)", "arterial diastolic (mmHg)", "LV end-diastolic volume (ml)", "stroke volume (ml)",
"ejection fraction (%)", "cardiac output (L/min)"]
loops = {}
lines = [f"{'':38}" + "".join(f"{h:>10}" for h in ["sys", "dia", "EDV", "SV", "EF %", "CO"])]
for name, change in cases.items():
m = Intact({**par, **change})
tt, PP, QQ, qq, bb = m.run(40, fs=int(par["Fs"]))
r = summarize(tt, PP, QQ, qq)
one = (tt >= bb[-3]) & (tt <= bb[-2])
loops[name] = (QQ[one, 0], PP[one, 0])
lines.append(f"{name:38}" + "".join(f"{r[k]:10.1f}" for k in keys))
print("\n".join(lines))
fig, ax = plt.subplots(figsize=(6.4, 4.4), dpi=85)
for (name, (vol, prs)), color in zip(loops.items(), ["#111827", "#1d4ed8", "#b91c1c", "#15803d"]):
ax.plot(vol, prs, lw=1.6, color=color, label=name)
ax.set_xlabel("left ventricular volume (ml)"); ax.set_ylabel("left ventricular pressure (mmHg)")
ax.legend(frameon=False, fontsize=8, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.16))
ax.spines[["top", "right"]].set_visible(False)
plt.tight_layout(); plt.show()
Output:
sys dia EDV SV EF % CO baseline 110.8 74.9 133.9 73.7 55.0 5.3 blood loss, 500 ml 69.0 46.3 90.4 46.7 51.6 3.3 weak left ventricle (Cls x 2.5) 96.2 64.8 178.6 63.6 35.6 4.5 high arterial resistance (Ra x 1.5) 142.2 108.3 140.8 67.7 48.0 4.8
Read the table against the loops. Losing blood lowers filling, so the loop shifts left and gets narrower, and pressure falls. A weak ventricle (a higher end-systolic compliance means it cannot squeeze as hard) ejects less at a larger volume: the loop moves right and the ejection fraction drops. A higher arterial resistance raises pressure and makes the loop taller and narrower, because the ventricle is ejecting against a higher load.
Going further
- doc/manual.pdf in the archive is the user's manual. It describes the baroreflex, breathing and disturbance models that this notebook leaves off, and the other "preparations" (heart-lung unit, systemic circulation alone) used to draw cardiac function and venous return curves.
- The source for those is in src/: abreflex.m and cpreflex.m for the reflexes, resp_act.m for breathing, hlu_eval_deriv.m and sc_eval_deriv.m for the other preparations.
- The original writes its output in WFDB format, the same format as PhysioNet's recorded waveforms, so simulated and measured signals can be analyzed with the same tools.
Source: Mukkamala R. A Forward Model-Based Analysis of Cardiovascular System Identification Methods. PhD thesis, Massachusetts Institute of Technology, 2000, and the RCVSIM user's manual in doc/. Distributed by PhysioNet, whose page gives the current citation, under the Open Data Commons Attribution License v1.0.
Run it
Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.