# Model specification

ECG Studio 0.1 is an organ-scale educational simulation. The implementation is inspectable and separates anatomy, propagation, the forward calculation and rendering. Its passing tests establish specified software properties and reference timing, not diagnostic validity or clinical morphology.

## Anatomy and units

The source is the average adult, end-diastolic model from the [Rodero et al. four-chamber atlas](https://zenodo.org/records/4593739). Only myocardial labels 1–4 are retained; valves, great vessels and auxiliary boundary labels are excluded. Open valve and vessel attachment sites remain visible. No external vessels are drawn. Full attribution and modifications are in [THIRD_PARTY.md](../THIRD_PARTY.md).

Simulation positions use mm, tissue weights use mm³, event times use ms, and velocity in mm/ms is numerically equal to m/s. Tissue weight is the sum of source tetrahedron volumes. It is not cavity volume, wall area or vertex count.

| Label | Tissue | Muscle volume, mL | Display triangles |
| ----- | ------ | ----------------: | ----------------: |
| 1     | LV     |           135.342 |            18,000 |
| 2     | RV     |            52.434 |            14,000 |
| 3     | LA     |            22.513 |             8,000 |
| 4     | RA     |            21.880 |             8,000 |

The graph aggregates tetrahedral centroids by chamber in a 3 mm grid. Neighbouring nodes are connected through shared source tetrahedron faces. Edges crossing the atrioventricular interface are removed. This preserves source myocardial volume, but introduces spatial discretization error: sub-grid structures and propagation within an aggregated cell are unresolved. There is no convergence study for the chosen resolution.

Decimated inner and outer surfaces are for display. Each display vertex interpolates three nearby simulation nodes of its own chamber. Changing surface resolution, visibility, colours, cutaway or camera cannot change the signal. Cutaway caps show a static chamber colour, not a sampled electrical field within the cut face.

The stored transform is `p_model = (p_source − origin) × basis`, using row vectors. A landmark frame is built from chamber centres, then rotated into an illustrative torso pose. Length and volume are preserved by the rigid transform. The displayed orientation labels describe the default view; they are not a tracked anatomical compass during orbiting.

## Conduction

The default right-atrial SA source starts periodic stimuli at `RR = 60000 / heartRate`. Dragging SA snaps the periodic stimulus to the nearest tissue node (`stimulusNode`); placing it outside the RA is an experimental stimulus site, not a validated ectopic rhythm or pacing model. A priority queue propagates activation along graph edges with delay `distance / velocity`. Tissue rejects arriving events while refractory. This is an event-driven approximation, not a monodomain or bidomain PDE solver.

Landmark selection is restricted by chamber and, for ventricular bundle insertions, endocardial depth and apicobasal coordinate. A fast interatrial connection is inserted between septal landmarks. The AV node has directed ventricular gateways; no retrograde AV conduction is implemented. Parameters are educational choices, not measured patient properties.

Default longitudinal myocardial velocity is 0.65 m/s in the ventricles and 1.1 m/s in the atria. Transverse factors are 0.55 and 0.8 respectively. Ventricular edges wholly within the inner 22% of the same chamber use 2.8 m/s. This endocardial layer approximates fast Purkinje distribution; it is not an explicit branching Purkinje network. A bundle block disables its gateway and its chamber's fast layer, allowing activation through slower muscle connections.

The AV delay slider sets gateway delay. **It is not the displayed PR interval**: atrial travel to the AV landmark also contributes. The right ventricular gateway has an additional 8 ms delay by default, adjustable with RV delay (`bundleDelay`).

## Action potential and recovery

Each accepted event stores its activation time and action-potential duration (APD). The normalized potential has a 2 ms upstroke, a slightly declining plateau and smooth recovery. It is not an ionic cell model.

The ventricular base APD is `310 − 42 × rho + 16 × apicobasal` ms; the atrial base is 190 ms. Rate scales APD by `clamp(sqrt(RR / 857.142857), 0.78, 1.12)`. A recovery-dependent restitution factor further shortens APD. The refractory period is 92% of APD. The engine simulates two warm-up cycles and captures the third; two cycles do not prove steady-state convergence for every parameter combination.

The visible activation field uses the same event history and action potential as the forward calculation, including recovery from the preceding beat. Playback speed controls simulated time and the rate at which that time is recorded; each simulated second still contains 500 samples.

## Spatial lesions

Preset lesions affect LV tissue within a selected radius. Subendocardial involvement restricts the affected nodes to `rho < 0.45`. The painting tool instead creates a per-node `tissueOverride` mask: 0 healthy, 1 ischaemic, 2 scar. Its spherical brush uses model-space distance and can affect any chamber with Full wall selected. Depth filters apply only to ventricles: endocardial `rho < 0.45`, mid-wall `0.33 ≤ rho ≤ 0.67`, epicardial `rho ≥ 0.67`. Painting begins with the existing lesion mask and then overrides the preset. Erase restores healthy tissue; Undo restores the previous stroke and configuration.

Scar removes conduction into affected tissue and leaves it electrically silent. Ischaemia halves local conduction speed, multiplies APD by 0.78, and transforms normalized voltage to `0.10 + 0.75 × Vm`. This is a simplified regional perturbation, not a coronary-territory or disease progression model.

All lesion effects pass through the same electrode calculation. No lead-specific ST, QRS or T-wave templates are inserted. A very small lesion or a centre far from tissue can affect few or no nodes at this resolution.

## Forward calculation and ECG

For each tissue node, weighted least squares estimates a voltage gradient from physical graph neighbours. Its source dipole is `−volume × gradient(Vm)`. The conductor uses a softened inverse-distance potential kernel with 15 mm softening and a single fixed `100 / (4π)` factor, corresponding to a 100 mV action-potential excursion and illustrative conductivity ratio of one.

Electrodes start at illustrative positions in the model frame. Dragging a marker moves it in the active camera plane; limb and chest markers retain a minimum distance from the heart centre. During pointer movement, a geometry-only least-squares stencil updates the changed rows of the common electrode operator. Previous samples remain unchanged. Electrode movement changes the field calculation without changing tissue activation. There is no meshed torso, blood pool conductor, lungs, skeletal tissue, electrode impedance or measured conductivity calibration. **Exported mV and plotted amplitudes are model units under these assumptions, not a calibrated clinical voltage prediction.** The same scale is used for every lead, scenario and comparison.

RA, LA and LL potentials supply the limb leads. The Wilson central terminal is `(RA + LA + LL) / 3`; V1–V6 are chest electrode potentials minus this terminal. The implementation preserves `II = I + III` and `aVR + aVL + aVF = 0`. Uniform transmembrane voltage produces zero field.

Traces are sampled at 500 Hz. A constant baseline is subtracted using the sample about 40 ms before the cycle ends. At high rates this point may not be fully diastolic. The moving paper appends live samples to a 120 s ring buffer at a schematic 25 mm/s with 4 CSS pixels per millimetre; resize changes visible duration. Gain defaults to 10 mm/mV, with 5 and 20 mm/mV display options. The calibration pulse represents 1 mV for 200 ms. Display gain does not change export or reference signals. Browser zoom and screen density mean on-screen millimetres are not physical ruler measurements. Every recorded sample is drawn to preserve narrow peaks on small canvases. CSV exports retained history. Pausing stops simulated time; resuming returns to the live edge. Conduction changes switch to a newly computed periodic history when the worker returns; ionic state is not carried between configurations.

## Measurements and interpretation

P, PR, QRS and QT come from tissue activation and recovery bounds, not a clinical ECG delineation algorithm. QTcF uses the Fridericia expression `QT / cbrt(RR_seconds)`. The displayed axis integrates recorded leads I and aVF across the last complete QRS after the latest electrode or conduction change. It stays blank until a qualifying interval is present. QRS boundaries are still activation-derived, in the illustrative frame. It is not independently calibrated to a clinical frontal electrical axis.

The reference parameters were selected to meet declared educational timing ranges. Passing those ranges is an acceptance check of this implementation; it is not independent evidence of physiological accuracy. Changing heart rate, conductivity or delay can create overlapping cycles or refractory loss of activation. Displayed input rate is the SA stimulus rate, which need not equal ventricular rate in such cases.

## Scope and next validation work

The [source study](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008851) explicitly describes imposed wall thickness outside the LV and omission of the LA appendage. The model therefore improves on an arbitrary sculpted shell but cannot be called fully anatomically exact. Its surfaces also lose detail during decimation.

This release does not implement atrial fibrillation, sustained re-entry, an explicit pacemaker, biomechanical contraction, patient-specific anatomy or a migration of old project presets. An exploratory comparison with 20 measured normal-labelled records found 6/12 QRS amplitudes outside that convenience sample’s P5–P95. Normal and disease morphology have not passed clinical validation; see [AUDYT_PL.md](AUDYT_PL.md). No inference should be made from the atlas authors' electromechanical validation to this separate ECG engine.

Further scientific development requires an independently checked anatomical frame, wall and mesh convergence analysis, explicit conduction-system modelling, a more complete conductor, and waveform comparison against reference ECGs with expert review. The separated modules allow those replacements without tying the solver to display vertices.

## Tissue models, editing and illustrative contraction

`simulation.kind: "tissue"` omits cardiac gateways and interval labels for a volume sphere or muscle strip. `simulation.landmarks` supplies explicit node IDs; heart landmarks must belong to their declared chambers. JSON setup includes validated electrical settings and painted tissue, electrode/stimulus positions and contraction strength.

The delayed twitch deforms display vertices only, with reduced shortening in ischaemia and none in scar. Strength ranges from 0 to 12%; 0 leaves rest geometry exact. Painting uses the rest shape. This is not a pressure, force, ejection-fraction or volume-conserving mechanical calculation; electrodes and the field operator use rest geometry. Historical review restores activation/tissue and electrode positions from the recorded timeline, but contraction strength and camera remain current display settings.

Blender export resamples tissue and changes graph connectivity, fibre approximation and layer coordinates. It does not preserve the original ECG. The tested 2 mm heart starter has an activation-derived QRS around 62 ms, versus 104 ms in the shipped atlas. See [BLENDER_PL.md](BLENDER_PL.md) for controls and limits.
