Skip to content
StevenLShaferPublic

About

A simulated TCI system that calls stanpumpR

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

17 Commits

Folders and files

Repository files navigation

FauxTCI

FauxTCI is a simulated target-controlled infusion (TCI) syringe pump and its controller, running entirely in the browser as a static page: no server, no framework, no build step, no dependencies. You set the pump's maximum rate and its other limits, pick propofol, remifentanil, sufentanil or remimazolam, enter an effect-site (or plasma) target, and watch the pump run in real time or faster: the loading infusion, the pause until the effect site peaks, the hand-off to a slowly falling maintenance rate, and what happens on a hand bolus, a pause, a lost response or a wrong syringe. The right-hand panel is a running transcript of every request the pump sends to the controller and every response it gets back, because the point of FauxTCI is to show how a pump talks to the stanpumpR TCI API.

What the controller is, and is not

The controller inside the page is a JavaScript reimplementation of the stanpumpR TCI API (R/tci-api.R, R/tci.R): the same request body in, the same response body out, the same algorithm (Shafer and Gregg 1992, as in tciRate()), the same four drug models (Eleveld 2018 for propofol; Kim 2017 at a BMI of 30 or more in adults and Eleveld 2017 otherwise for remifentanil; Gepts 1995 for sufentanil; Eleveld 2025 for remimazolam, whose ke0 is the published one and whose time to peak effect is solved from it; sufentanil and remimazolam scaled to fat-free mass as stanpumpR scales them, with options.adjustToFFM false giving their published scaling), the same validation, error codes and warnings. It is validated against fixtures generated by the R package (see How it was validated), and the page says so. It is not the R service. Nothing in this repository runs R.

The page can also talk to a real stanpumpR::run_tci_api() server. In Setup, set Controller to "HTTP: a stanpumpR server" and enter the server's URL; the page then POSTs each request to <URL>/tci/v1/drugs/<drug>/rate and applies the response under the same safety contract. Two things to know:

  • CORS. A browser only lets the page call a server that allows the page's origin. run_tci_api() sends no CORS headers (the API's deployment guidance, section 7.1 of the contract, is CORS disabled on a controller path), so for a teaching demonstration put a reverse proxy in front of the server that adds Access-Control-Allow-Origin for the page's origin and answers the OPTIONS preflight (Access-Control-Allow-Methods: POST, GET, OPTIONS, Access-Control-Allow-Headers: Content-Type), or add an equivalent Plumber filter to tciApiRouter() in a development session. Never on a production ingress.
  • Clocks. The server reports CLOCK_SKEW when its own clock and the request's now differ by more than 30 s. The page's simulated clock starts at the wall clock, so at 1x the two agree; at 5x, 10x or 60x the simulated clock runs ahead and every response from a real server carries the warning (the computation is unaffected: the server uses the request's clock).

Open it

The page is published with GitHub Pages at https://stevenlshafer.github.io/FauxTCI/ once Pages is enabled for the repository (Settings, Pages, Source: "GitHub Actions"; the .github/workflows/pages.yml workflow then deploys index.html, css/, js/, the licence and this file on every push to main).

Screenshot: none is committed yet (this line is the placeholder). Running the browser smoke test (see below) writes one at 1400 px to test-results/smoke.png and one at phone width to test-results/smoke-375.png; test-results/ is ignored by git, so neither is in the repository or on the Pages site.

Run it locally

The page is plain HTML, CSS and ES modules, so any static file server will do; opening index.html from file:// does not work, because browsers refuse to load ES modules from file: origins.

git clone https://github.com/StevenLShafer/FauxTCI.git
cd FauxTCI
npx http-server . -p 8080 -c-1      # or: python3 -m http.server 8080

then open http://localhost:8080/ . There is nothing to install and nothing to build.

The page

On a wide screen (1100 px and up) the page is two columns. The left two thirds are the setup above the pump screen; the right third is the API conversation. On a window 950 px or taller the two boxes are of equal height and fill the window below the header (the pump screen is never shorter than what it holds, so on a window too short for both the setup scrolls inside its box). On a shorter window, a laptop's, the setup takes its natural height and the pump screen is a window tall beneath it, and Start scrolls the pump screen into view. Either way the user first sees the pump set up, presses Start in the pump screen, and from then on sees what a TCI pump shows: the target, the rate, the concentrations and their time course, with nothing to scroll between the target and the charts. The teaching controls, the delivery record, the wire details and the about text are below the two boxes. On a narrow screen everything stacks in that order.

  • Setup: drug, patient (weight, height, age, sex), syringe concentration (propofol 10 or 20 mg/mL; remifentanil 20, 50 or 100 mcg/mL; sufentanil 1, 5 or 50 mcg/mL; remimazolam 1 or 2.5 mg/mL), the pump's maximum rate (1200 mL/hr), minimum rate (0.1), resolution (0.1), syringe volume (50 mL), the declared latency (1.5 s), the actual latency (1.5 s), the interval (10 s), the clock multiplier (1x, real time, the default; 5x, 10x or 60x to run faster) and the controller (in page, or HTTP with a URL). Start locks these for the case.
  • Pump screen: the target (effect site or plasma, in the drug's units, with the typical range; a target of 0 stops the infusion) and the Start button, which disappears once pressed; while the case runs, Set target, Target 0 and Stop (which sets the target to 0, ends the case and halts the clock; Start then returns for the next case). Beneath them the pump face: the rate in mL/hr with the mass rate beneath, the status lamp and phase (loading, waiting for peak, maintenance, above target, stopped, paused, ALARM), the target, the true and predicted effect-site concentrations, the true plasma concentration, the case clock, the next-request countdown, the syringe volume remaining and the time to empty, and the segment's hold countdown with its fallback rate. Then the charts: effect-site concentration, true (solid) and as predicted by the controller (dashed), the target, and the true plasma concentration (lighter); beneath, the pump rate as a step line with the maximum rate dotted. Minutes of case time; each drug in its stanpumpR colour (propofol yellow, remifentanil dark blue, sufentanil light blue, remimazolam orange).
  • Delivery record: the pump's record as a table, with "Copy as JSON" and "Download as stanpumpR dose table (CSV)" (Drug, Time in minutes, Dose, Units: mg or mcg boluses, rate rows in mg/hr or mcg/min), which the stanpumpR app can load to plot the same case.
  • Wire details: the last request and response as JSON, with the status, the transport in use and a one-line log of every exchange.
  • API conversation (the right third of a wide screen, below the pump screen on a narrow one): one card per exchange with the request and response bodies, a one-line reading of each response, its warnings or errors, and when it was sent, received and applied to the pump. "Summaries only / Full JSON", "Copy conversation", "Clear" and a Follow toggle.

What the teaching controls demonstrate

  • Hand bolus: drug given outside the pump. The record gets a bolus event, the controller answers with the pump off (phase "above target") and gives nothing until the effect site has fallen back to the target.
  • Pause / Resume: a paused pump reports pump.state: paused and rate 0; the server still plans (warning PUMP_NOT_RUNNING), projecting the latency at rate 0, and the pump decides not to run the plan. Resume asks at once and the next response restarts the infusion.
  • Drop next response: the next response is lost in transit. The pump runs its segment to holdUntil, then the response's fallback rate; had no later command been accepted it would have stopped and alarmed (section 7, rule 4 of the contract). A response dropped during loading shows that the fallback is itself a safe plan: under a cap it is another capped partial interval (504.1 mL/hr for the default propofol case), and once loading is complete it is 0 (off until the peak); either way the peak never exceeds the target.
  • Change syringe: the controller is told one concentration while the syringe really holds another. The true and predicted curves diverge and DELIVERY_MISMATCH appears; the controller can only be as right as its record.
  • Actual latency: how long the simulated pump really takes to acknowledge a command, against the declared timing.latency. Slower than declared, the loading rate runs too long and the effect site overshoots (section 5.5: about 10% for 3.0 s against a declared 1.5 s under a 1200 mL/hr cap); longer than the interval, no response is ever applied in time, the fallback expires and the pump alarms.
  • A hidden tab: the controller sleeps while the tab is in the background. On return the pump has done what the contract says a pump does without its controller: it ran its segment to holdUntil, the fallback for maxSeconds, then stopped and alarmed. A new target restarts it.
  • Clock: 1x is a real case; 60x shows a 30-minute case in 30 s. The request bodies carry the simulated clock, which is why they stay consistent at any speed.

Where a real pump plugs in: the pump driver

Everything the controller knows about the hardware comes through one object, the pump driver (js/driver.js). It is STANPUMP's infuse() loop made explicit: every interval, and on every local event, the controller tells the pump the rate and reads back what the pump has actually done. The interface has three methods, each called with the controller's clock time in seconds since the epoch:

Method What it does
infuse(time, rate) Run rate mL/hr from time; rate null changes nothing and just reads the pump. Returns a reading.
loadSyringe(time, { volume, concentration, units, drug }) A new syringe: volume in mL, concentration what is really in it, in the drug's base mass unit per mL, units that unit ("mg" or "mcg"), drug the drug's name. Called once at start() for the syringe the case begins with and again on every change. Returns a reading.
horizon(time) When the pump will next change state by itself (a syringe about to run out, a command about to take effect): a time strictly later than time, or null if it cannot predict. Optional; a time at or before time is ignored.

The calling convention: the three methods are synchronous. Each returns at once, from the driver's own cached status, and never throws. A real driver talks to its pump in the background (a serial port, Bluetooth, a socket), keeps the last status it received, issues each command when infuse() asks for it, and answers infuse() from what it has. Within a case the controller never calls the driver with a time earlier than a previous call's; across cases it may, since the page's clock restarts at each Start (see the hook below). A method that throws, or returns a Promise or anything but a reading, is a driver fault: the controller raises the alarm driverFault, stops asking the server, records nothing it has not seen, and keeps its own clock running; the first reading that arrives normally clears the fault (the alarm stays, as every alarm does, until the user clears it). horizon() is the exception: a throw, or anything but a number, reads as null.

A reading is the pump's own account of itself as of time:

time              s, the instant the reading describes (the time asked)
rate              mL/hr actually running, 0 when stopped
acknowledgedAt    s, when the rate running took effect
commanded         { rate, at } a command not yet running, or null
volumeInfused     mL, the pump's own volume totaliser (see below)
massInfused       the drug totaliser in massUnits, or null if the pump has none
massUnits         "mg" or "mcg" (converted to the drug's unit), or null for the drug's unit
syringeRemaining  mL left, or null if the pump cannot tell (then derived)
state             "running" | "stopped" | "paused"
alarms            [{ kind, message, at }]: conditions that stopped the pump
notices           [{ kind, message, at }]: conditions that did not (optional)

What the controller does with it:

  • The truth follows the totaliser. The controller never integrates the commanded rate itself: the true patient model is advanced with the mass the reading says was delivered (the drug totaliser, converted by massUnits; or the volume at the syringe's true concentration when there is none). The totaliser need not be 0 at the first call and may reset: the controller counts from the first reading and takes a decrease as a reset, so the request's pump.volumeInfused is always the volume since the case started. A pump that cannot tell its syringe volume has it derived: the loaded volume less the volume totalised since the load.
  • The record follows the acknowledgement. A rate change goes into the delivery record only when a reading shows it running, at the reading's acknowledgedAt (a pump that acknowledges late is recorded late, which is the truth the server needs), never earlier than an event already recorded. A running rate within the pump's rate resolution of the command answers it and is recorded with the command's source and the pump's own value; a rate the controller did not command is recorded with source pump.
  • An alarm stops the pump, for real. An alarm means the pump has stopped, or must: on the first reading that shows one the controller commands rate 0, records the stop (at the alarm's own time when the pump had stopped itself, at the stop command when it was still running), drops its command segment and raises the alarm on the face. Two alarms at once are raised once each. The pump must keep reporting the alarm until the condition is cleared on the pump; if the user clears it first it comes back at the next reading, so the controller cannot run a pump that will not. syringeEmpty and occlusion are the kinds the API's pump.state names, and the controller's own state for them (it does not ask the server while in alarm; once the user clears the alarm, a pump still stopped is reported as standby); any other kind (doorOpen, whatever the pump calls it) is raised as it comes. A condition that does not stop the pump (low battery, near end of infusion) belongs in notices: shown on the face while the pump reports it, noted once in the controller's log, never acted on.
  • The pump's state is honoured. A pump paused from its own panel pauses the controller (the plan is noted, not run, and the request says paused); when the pump runs again the controller resumes and asks at once. A pump that is stopped with no alarm is reported as standby. The face shows the pump's own word next to the rate when it differs from the controller's: a command not yet acknowledged, or a state other than running.

SimulatedPump, in the same file, is the pump FauxTCI runs: it delivers exactly the commanded rate, keeps a syringe of known volume and true concentration (the teaching control that tells the controller one concentration while the syringe holds another lives there), stops and alarms at the instant the syringe runs out (decided by time, so that it empties at any clock and any rate), refuses to run until a new one is loaded, and can be given an acknowledgement delay. The page constructs it from the setup; the pump and closed-loop tests that pre-date the driver pass unchanged against it.

To drive a real pump, subclass PumpDriver, speak the pump's protocol inside those three methods, and hand it to the page as window.FauxTCI.driver before pressing Start: an instance, or a function of the case settings that returns one, called once per Start. A driver reused for a second case will be called with a time behind its own when the earlier case ran faster than real time (the clock restarts at each Start), which it must tolerate, as SimulatedPump does; the controller notes a reading ahead of its clock. In code, pass the driver to FauxPump as the driver option. test/driver.test.js shows the controller's side with small drivers: one that acknowledges two seconds late, one that delivers half of what it is told, one that occludes, one that changes its own rate, one that refuses a command, one whose totaliser resets, one that pauses itself, one that echoes rates at float32 precision, and one that throws. What a real driver must get right: times are seconds since the epoch on the controller's clock; rates are mL/hr; volumeInfused is the pump's own totaliser, never a re-integration of the command; an alarm carries the time it began and is reported until the condition is cleared on the pump; a stopped pump reports rate 0; and the three methods answer at once and never throw.

How it was validated

The fixtures in test/fixtures/ were generated from stanpumpR at commit d99231c6aebf09d8a6d0352e188f32d4dc4ed6bc (the master of 2026-11-18 plus remimazolam's target units, StevenLShafer/stanpumpR#768; R 4.3.3) by test/fixtures/generate.R; test/fixtures/README.md describes each file and the tolerances a port should aim for. The suite (node --test 'test/*.js', Node 22, about 20 seconds with the browser smoke test) replays them; the figures below are the worst cases the tests print as TAP diagnostics:

Fixture What is checked Tolerance Achieved (worst case)
models.json (48 entries: 8 patients; propofol and remifentanil once, sufentanil and remimazolam at both adjustToFFM positions) PK parameters, eigenvalues, every bolus and infusion coefficient, with R's ke0 injected; pkSizeFactors() 1e-10 relative 4.1e-14 (parameters and eigenvalues), 5.4e-13 (coefficients)
ke0-solve.json ke0 from tPeak as ke0FromTPeakBolus() finds it (the bracket, then uniroot() at tol sqrt(eps) on effectSitePeakTime(), an optimize() at tol 2^-13), or remimazolam's tPeak from its ke0 bracket exact; ke0 1e-9 relative; peak times 1e-8 min bracket exact; ke0 2.5e-11 from the covariates, 2.9e-11 from the fixture's own inputs; remimazolam's tPeak within 1.1e-11 min; effectSitePeakTime() within 3.3e-10 min; the effect site after a unit bolus peaks within 3.7e-9 min of tPeak
rate-cases.json (99 success cases) every numeric field of the response with R's ke0 injected 1e-8 relative 2.6e-11 (rate.ideal); every other field at or below 8.3e-12
rate-cases.json, the port's own ke0 the same, with ke0 solved in JavaScript 1e-8 relative 1.4e-7 relative on rate.ideal (7.5e-9 mL/hr absolute, at a pump-off step where the ideal rate is a residual of the effect-site search; the commanded rates match exactly); state.now.e[] 1.1e-10; the state and prediction concentrations at or below 9e-12
rate-cases.json, strings rate.value after rounding, limitedBy, controller, every timing string, peakAt, targetReachedAt, warning codes and pointers exact exact
rate-cases.json (13 error cases) status, code and pointer exact 12 exact; DUPLICATE_KEY is skipped with a note (JSON.parse() keeps only the last copy of a duplicated key, so the body cannot be refused after parsing)
model.hash MD5 of the parameters rounded to ten significant digits, in jsonlite's spelling the spelling of R's parameters gives R's hash in every model block exact; the port's own hash equals R's in 122 of 147 blocks, the rest differing only where its ke0, equal to R's to about 1e-11, rounds differently in the tenth digit
closed-loop.json (8 traces x 181 steps: six of propofol and remifentanil, sufentanil at 0.1 ng/mL, remimazolam stepped from 0.5 to 1 mcg/mL) the commanded rate, fallback rate, plan, phase, every timing string, warning codes, the server's state at now, the true Cp and Ce at every step, the recorded history and the trace's maximum true Ce rates 1e-8, concentrations 1e-6 relative; strings exact rate.value and fallback.rate exact, state.now.ce 9.1e-12, prediction.peakCe 4.3e-12, true Ce 1.0e-11, maximum true Ce 4.3e-12, recorded rates exact; the pump's own running maximum, sampled at its tick instants rather than on the fixture's 1 s grid, is within 5.8e-6 of the fixture's (trace 5, the 300 mL/hr cap)

Beyond the fixtures, test/pk.test.js checks advance() against a Runge-Kutta integration of the compartment equations (1.5e-13 relative), test/tci.test.js exercises every error and warning code and the section 7 rules, and test/pump.test.js drives the pump through a dropped response, a pause, a lowered target, a wrong syringe, a background gap, a late or crossed response, a three-hour compaction and the dose-table export. test/smoke.playwright.js opens the page in Chromium (when Playwright is installed), checks the wide layout at 1400x1000 (the API panel on the right at about a third of the width, the setup and the pump screen at equal height with the target and the charts in the same box, neither box scrolling inside), checks that a Start with an invalid setup is reported and leaves Start in place, runs a propofol case at 60x to maintenance, gives a hand bolus, stops the case and starts and stops a second one, checks the laptop layout at 1366x768 (Start on screen before a case, the target and both charts on screen while it runs), checks for console and page errors and for horizontal overflow at 375 px, and writes test-results/smoke.png; without Playwright it skips.

Run the suite with Node 22:

npm test                    # = node test/run.js
node --test "test/*.js"     # the same files, through node --test directly

test/run.js names the files itself through node:test's run(), so npm test needs no shell glob. (Node 22 takes glob patterns, not directories, so node --test test/ does not work; the quotes keep the pattern from the shell.) Playwright for the smoke test: npm install -g playwright && npx playwright install chromium.

Regenerating the fixtures

From a stanpumpR checkout at the commit above:

cd /path/to/stanpumpR
LC_ALL=C.UTF-8 NOT_CRAN=true RENV_CONFIG_AUTOLOADER_ENABLED=FALSE \
  Rscript /path/to/FauxTCI/test/fixtures/generate.R /path/to/FauxTCI/test/fixtures

The run takes about 20 s, ends with a validation pass that replays every request through tciNextRate(), and writes manifest.json. tciNextRate() is deterministic, so a regeneration differs only in generatedAt and the server.* blocks, which the tests do not compare.

Layout of the repository

index.html              the page (markup only)
css/fauxtci.css         styles, light and dark
js/pk.js                the drug models, eigenvalues, coefficients, ke0, closed-form advance
js/tci.js               the API port: tciNextRate(request) -> response, tciApiDrugs(), tciApiModel()
js/pump.js              the pump's controller (the section 7 safety contract), driving a pump through the driver
js/driver.js            the pump driver interface, and SimulatedPump, the pump the page runs
js/transport.js         in-page or HTTP transport
js/app.js               the page: wiring, charts, tables, the API conversation panel, the clock
js/md5.js               MD5 for model.hash
test/run.js             the runner behind npm test (node:test's run() over the files below)
test/*.test.js          node:test conformance and behavioural tests
test/smoke.playwright.js   the browser smoke test
test/fixtures/          the stanpumpR golden fixtures and their generator
.github/workflows/      test.yml (push, pull request) and pages.yml (deploy to Pages)

Clinical disclaimer

FauxTCI is a teaching simulation. It is not a medical device, it has not been evaluated by any regulator, and nothing in it is to be used for patient care, for programming a real pump, or for any clinical decision. The drug models are population models from the literature; an individual patient's concentrations differ from them.

Licence

MIT; see LICENSE. Drafted by Claude Code, 2026-10-12, at the request of Steven L. Shafer.

About

A simulated TCI system that calls stanpumpR

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages