FEniCSx-Beat

Contents

FEniCSx-Beat#

class beat.BaseMonitor[source]#
class beat.BidomainModel(time: Constant, mesh: Mesh, M_i: Coefficient | float, M_e: Coefficient | float, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, params: dict[str, Any] | None = None, C_m: float = 1.0, dx: Measure | None = None, **kwargs)[source]#

Solve the bidomain model

\[\begin{split}C_m \frac{\partial v}{\partial t} - \nabla \cdot (M_i \nabla v) - \nabla \cdot (M_i \nabla u_e) - I_{\mathrm{stim}} &= 0 \\ \nabla \cdot (M_i \nabla v) + \nabla \cdot ((M_i + M_e) \nabla u_e) &= 0\end{split}\]

for the transmembrane potential \(v\) and the extracellular potential \(u_e\), with insulating boundary conditions on both.

The two fields live in separate Lagrange spaces and the system is assembled blocked and solved monolithically. Keeping v in a space of its own – rather than making the pair one mixed element – is what lets the ODE solvers consume it unchanged.

\(u_e\) is only determined up to a constant. By default it is normalised to zero mean with a Lagrange multiplier in a real-valued space; supplying bcs that constrain \(u_e\) grounds it instead and the multiplier is dropped, since the two together would over-determine the problem.

The parameter lump_mass (default False) lumps the mass term of the parabolic row, as in beat.MonodomainModel; see there for the trade-off.

Parameters:
property state: BidomainState#

Both solved-for fields, in the order the blocked system holds them.

step(interval) → None[source]#

Perform a single time step.

Parameters:

interval (tuple[float, float]) – The time interval (T0, T)

property u_e: Function#

The extracellular potential.

property v: Function#

The transmembrane potential.

variational_forms(dt: Expr | float) → tuple[Form | Sequence[Sequence[Form | None]], Form | Sequence[Form]][source]#

Blocked theta-rule forms for the coupled system.

Both rows are written in terms of the midpoint pair. The elliptic row carries no time derivative, but it is linear and homogeneous, so imposing it on the midpoint is equivalent to imposing it at the new time given that it held at the old one – and it is the only choice under which the collapse to the monodomain model at equal anisotropy ratio stays exact away from theta = 1.

Parameters:

dt (Expr | float) – The time step

Returns:

The blocked bilinear and linear forms

Return type:

tuple[_BilinearForm, _LinearForm]

class beat.ECGRecovery(v: dolfinx.fem.function.Function, sigma_b: float | dolfinx.fem.function.Constant = 1.0, C_m: float | dolfinx.fem.function.Constant = 1.0, dx: ufl.measure.Measure | None = None, M: float = 1.0, petsc_options: dict[str, typing.Any] = <factory>)[source]#
class beat.ExternalOperatorMultiODESolver(v_ode: Function, v_pde: Function, markers: Function, fun: dict[int, Callable], init_states: dict[int, ndarray], num_states: dict[int, int], v_index: dict[int, int], parameters: dict[int, ndarray] | None = None, monitor: BaseMonitor | None = None)[source]#

Multi-region counterpart to ExternalOperatorODESolver, analogous to how beat.odesolver.DolfinMultiODESolver extends beat.odesolver.DolfinODESolver and beat.irksome_odesolver. IrksomeMultiODESolver extends ExternalOperatorODESolver’s Irksome sibling: a different cell model (fun, init_states, parameters, num_states) can be used in each region of the mesh, as identified by an integer-valued markers function.

As in beat.irksome_odesolver.IrksomeMultiODESolver, one full-mesh external operator is built per marker, and only the degrees of freedom that actually belong to that marker are read back out; the cost of a step therefore scales with the number of regions. Prefer beat.odesolver.DolfinMultiODESolver for problems with many regions or very large meshes.

class beat.ExternalOperatorODESolver(v_ode: Function, v_pde: Function, fun: Callable, init_states: ndarray, num_states: int, v_index: int = 0, parameters: ndarray | None = None, monitor: BaseMonitor | None = None)[source]#

An ODE solver that steps a cell model via dolfinx-external-operator’s FEMExternalOperator, instead of the plain-numpy loop used by beat.odesolver.DolfinODESolver.

Unlike beat.irksome_odesolver.IrksomeODESolver, fun keeps the exact same signature already used by beat.odesolver.DolfinODESolver, fun(states, t, parameters, dt) -> new_states (plain NumPy or Numba-jitted arrays) — no UFL-returning variant of the cell model is needed. All num_states state variables are stored in a single vector-valued (blocked) dolfinx.fem.Function, rather than a mixed-element one, since FEMExternalOperator operates on raw (num_cells, num_quadrature_points, num_states) arrays rather than UFL expressions.

class beat.IrksomeMonodomainModel(time: Constant, mesh: Mesh, M: Coefficient | float, butcher_tableau, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, params=None, C_m: float = 1.0, dx: Measure | None = None, **kwargs)[source]#

The monodomain model advanced by an Irksome Runge-Kutta stepper.

Built like beat.MonodomainModel (same parameters, monitor, bcs factory and restart support); the theta-rule linear problem is replaced by an Irksome StageDerivativeTimeStepper for the given butcher_tableau.

The bcs factory must return Irksome-compatible conditions, built with irksome.backends.dolfinx.dirichletbc (plain dolfinx.fem.dirichletbc objects are rejected by Irksome). A restart reproduces the run to round-off rather than bit for bit: the stepper starts each solve from the previous step’s stages, which a checkpoint does not hold.

The parameter lump_mass is not supported and raises NotImplementedError.

assign_previous() → None[source]#

Nothing to do: Irksome keeps its own history within advance().

step(interval) → None[source]#

Perform a single time step.

Parameters:

interval (tuple[float, float]) – The time interval (T0, T)

class beat.IrksomeMultiODESolver(v_ode: Function, v_pde: Function, markers: Function, fun: dict[int, Callable], init_states: dict[int, ndarray], butcher_tableau, time: Constant, num_states: dict[int, int], v_index: dict[int, int], parameters: dict[int, ndarray] | None = None, monitor: BaseMonitor | None = None)[source]#

Multi-region counterpart to IrksomeODESolver, analogous to how beat.odesolver.DolfinMultiODESolver extends beat.odesolver.DolfinODESolver: a different cell model (fun, init_states, parameters, num_states) can be used in each region of the mesh, as identified by an integer-valued markers function.

All regions share the same butcher_tableau and time/dt stepping. Internally, one full-mesh mixed-element Irksome stepper is built per marker (as in IrksomeODESolver), and only the degrees of freedom that actually belong to that marker are read back out; the values computed at the other degrees of freedom are discarded. This keeps the implementation simple and correct, but means the cost of a step scales with the number of regions (each region’s stepper solves over the whole mesh), unlike beat.odesolver.DolfinMultiODESolver, whose plain-numpy ODE systems are only ever sized to the points that need them. Prefer beat.odesolver.DolfinMultiODESolver for problems with many regions or very large meshes.

class beat.IrksomeODESolver(v_ode: Function, v_pde: Function, fun: Callable, init_states: ndarray, butcher_tableau, time: Constant, num_states: int, v_index: int = 0, parameters: dict | None = None, monitor: BaseMonitor | None = None)[source]#

An ODE Solver mapping the DolfinODESolver interface to an Irksome stepper.

class beat.MonodomainModel(time: Constant, mesh: Mesh, M: Coefficient | float, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, params=None, C_m: float = 1.0, dx: Measure | None = None, **kwargs)[source]#

Solve

\[\frac{\partial V}{\partial t} - \nabla \cdot \left( M \nabla V \right) - I_{\mathrm{stim}} = 0\]

The right-hand side is affine in the previous potential, \(L = B v_{n} + L_0\), where \(B\) holds the mass and the explicit part of the diffusion and \(L_0\) the stimulus. With the parameter rhs_matrix (default True), \(B\) is assembled together with the system matrix, i.e. only when the time step changes, and every step assembles only \(L_0\) and adds the product \(B v_{n}\). This assumes, like the system matrix already does, that the conductivity and the capacitance do not change in time; at theta 0 (explicit diffusion) they enter only \(B\), which is then still used. Set rhs_matrix to False to assemble the whole right-hand side every step; this is also done, with a warning, when the right-hand side is not affine in \(v_{n}\) or \(B\) depends on data the system matrix does not, other than the conductivity, the capacitance and the time step (e.g. a stimulus linear in \(v_{n}\) that varies in time).

With the parameter lump_mass (default False) the mass term uses the lumped mass matrix, the diagonal matrix of the consistent one’s row sums, as openCARP and CARPentry do by default; diffusion and stimulus are integrated as before. The mass term is lumped the same way in the system matrix and on the right-hand side, with or without rhs_matrix. With theta > 0 the system matrix keeps the sparsity of the diffusion operator, so lumping barely changes the cost per step; its use there is to reproduce lumped-mass setups like for like. With theta = 0 (explicit diffusion) the system matrix is the lumped mass matrix, diagonal, so a Jacobi solve (ksp_type “preonly”, pc_type “jacobi”) is exact, and the time step limit of explicit diffusion is about five times larger than with the consistent mass matrix. The default, the consistent mass matrix, is more accurate on coarse meshes: with lumping, activation is later there (Niederer et al. 2011, “Verification of cardiac tissue electrophysiology simulators using an N-version benchmark”, Phil. Trans. R. Soc. A 369:4331-4351, doi:10.1098/rsta.2011.0139, Section 6). Only P1 Lagrange is supported, on straight or curved cells; other elements raise a ValueError.

property state: Function#

The transmembrane potential.

Kept for compatibility; v says the same thing by name and is preferred.

property v: Function#

The transmembrane potential.

variational_forms(dt: Expr | float) → tuple[Form, Form][source]#

Create the variational forms corresponding to the given discretization of the given system of equations.

Parameters:

dt (float) – Time step size

Returns:

The variational form and the precondition

Return type:

tuple[ufl.Form, ufl.Form]

class beat.MonodomainSplittingSolver(pde: ~beat.monodomain_solver.PDEModel | None, ode: ~beat.monodomain_solver.ODESolver, theta: float | None = None, monitor: ~beat.telemetry.BaseMonitor = <factory>, splitting: ~typing.Literal['godunov', 'strang'] | None = None, merge_half_steps: bool = False)[source]#

Deprecated name of SplittingSolver (same arguments and behaviour).

class beat.NullMonitor[source]#
class beat.PerformanceMonitor(log_frequency: int = 1, comm: ~mpi4py.MPI.Intracomm = <mpi4py.MPI.Intracomm object>)[source]#

A monitor that accumulates timings and KSP stats, logging them periodically, and can save/display a final summary.

display_summary() → None[source]#

Logs a nicely formatted summary of the accumulated timings and metrics.

save_summary(filepath: str | Path) → None[source]#

Saves the performance metrics to a JSON file.

class beat.SplittingSolver(pde: ~beat.monodomain_solver.PDEModel | None, ode: ~beat.monodomain_solver.ODESolver, theta: float | None = None, monitor: ~beat.telemetry.BaseMonitor = <factory>, splitting: ~typing.Literal['godunov', 'strang'] | None = None, merge_half_steps: bool = False)[source]#

Advance a PDE model and an ODE solver by operator splitting.

splitting="strang" (the default) takes half an ODE step, a full PDE step and another half ODE step: second order in time, provided both sub-steps are second order themselves (PDE params["theta"] = 0.5 and a second-order cell scheme such as gotranx’s rush_larsen_2). splitting="godunov" takes a full ODE step and then a full PDE step: first order in time. theta is the deprecated way of choosing the splitting (the fraction of the step the first ODE sub-step covers: 1.0 Godunov, 0.5 Strang); after construction it always holds that fraction.

With pde=None only the cell model is advanced and the splitting is ignored. Wrapping the ODE solver in beat.reaction_eikonal.FootCurrentODESolver gives the R-E+ model (with a PDE) or the R-E- model (pde=None). monitor=None (or leaving it out) records nothing (a beat.telemetry.NullMonitor).

merge_half_steps=True (Strang only) merges each step’s closing ODE half-step with the next step’s opening one: still second order, at Godunov’s cost of one ODE step per step, but with a larger error than plain Strang at the same dt. Between steps the state then lacks the closing half-step, so call synchronize() before reading v or the ODE states; solve() and restart_functions() do it automatically. A parameter or stimulus change made between steps also affects the pending half-step of the previous step. Anything that reads v after every step (probes, beat.activation.ActivationTracker, conduction-velocity estimates) sees it lagging its closing half-step, so threshold activation times come out late by up to about half a time step; synchronizing every step to avoid this costs as much as plain Strang splitting.

load_restart(functions: Sequence[tuple[str, Function]], metadata: Mapping[str, Any] | None = None) → None[source]#

Restore the solver from functions as returned by restart_functions().

Overwrites pde.v and every ODE state, restores the PDE’s metadata if given (as returned by restart_metadata()), then sets the PDE’s previous value, exactly as construction does.

Without a PDE, v is one of the ODE states, so the states are authoritative: the checkpoint’s "v" is overwritten by the loaded states (ode.to_dolfin()).

Raises ValueError, before anything is modified and on every rank, if the checkpoint was saved by a solver with a PDE and this one has none or the reverse (metadata’s "has_pde"; checkpoints without it are not checked), or if its "v" does not fit this solver’s v.

restart_functions(state_names: Sequence[str]) → list[tuple[str, Function]][source]#

The Functions that hold everything the splitting scheme carries between steps.

These are ("v", pde.v) followed by ("state_<name>", f) for each ODE state, named by state_names (one per state). Write them to save a checkpoint. On a fresh solver, read into them and pass them to load_restart(). Without a PDE, "v" is ode.v_ode. Synchronizes first (see synchronize()), so a checkpoint is never taken mid-step. This means calling it mid-run (e.g. to checkpoint) changes the rest of a merged run at truncation-error level, compared with a run that never checkpoints.

restart_metadata() → dict[str, Any][source]#

State beyond the Functions, to be stored with a checkpoint (JSON-serializable).

Pass it back to load_restart(). "has_pde" records whether this solver has a PDE model, so a checkpoint is not loaded into the other kind; "pde" holds the PDE model’s own metadata, if it has any.

solve(interval: tuple[float, float], dt: float | None) → None[source]#

Step over interval with time step dt (see beat.utils.time_steps()).

Synchronizes at the end (see synchronize()).

step(interval)[source]#

Advance the coupled system over interval = (t0, t1).

Godunov: a full ODE step, then a full PDE step. Strang: half an ODE step, a PDE step and a closing half ODE step. Merged Strang: the closing half-step is left pending and merged into the next step’s opening ODE step (see synchronize()). If a pending half-step is left over after merging was turned off, it is synchronized first.

synchronize() → None[source]#

Run the pending closing ODE half-step of merged Strang splitting, if there is one.

With merge_half_steps=True each step leaves its closing half-step pending, to be merged with the next step’s opening half-step. Until then v and the ODE states lack that half-step (v is only first-order accurate), so call this before saving or post-processing them. Does nothing when nothing is pending (Godunov, no merging, no PDE, or already synchronized).

property synchronized: bool#

False while merged Strang splitting owes the last step’s closing ODE half-step.

property v: Function#

pde.v, or ode.v_ode without a PDE.

Type:

The transmembrane potential

class beat.base_model.BaseModel(time: Constant, mesh: Mesh, dx: Measure | None = None, params: dict[str, Any] | None = None, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, bcs: Callable[[BaseModel], Sequence[DirichletBC]] | None = None, monitor: BaseMonitor | None = None, **kwargs: Any)[source]#

Base class for models.

Parameters:
  • time (dolfinx.fem.Constant) – The current time

  • mesh (dolfinx.mesh.Mesh) – The mesh

  • dx (ufl.Measure, optional) – The measure for the spatial domain, by default None

  • params (dict, optional) – Parameters for the model, by default None

  • I_s (Stimulus | Sequence[Stimulus] | ufl.core.expr.Expr, optional) – The stimulus, by default None

  • bcs (Callable[[BaseModel], Sequence[dolfinx.fem.DirichletBC]], optional) – Factory returning the Dirichlet boundary conditions, by default None (natural boundary conditions). It is called once the state space exists and is handed the model, because a boundary condition is only honoured on the very function space object the model built – one constructed separately on the same mesh and element is silently ignored during assembly.

  • jit_options (dict, optional) – JIT options, by default None

  • form_compiler_options (dict, optional) – Form compiler options, by default None

  • petsc_options (dict, optional) – PETSc options, by default None

load_restart_metadata(data: Mapping[str, Any]) → None[source]#

Restore what restart_metadata() returned, re-assembling the matrix.

property mesh: Mesh#

The mesh the model is discretized on.

restart_metadata() → dict[str, float][source]#

The model’s own state beyond its fields: the time step its matrix was assembled for.

The matrix is kept while dt stays within 1e-12 of this, so a restarted run only reproduces the uninterrupted one bit for bit if it assembles at the same time step.

solve(interval: tuple[float, float], dt: float | None = None) → Results[source]#

Solve on the given time interval.

Parameters:
  • interval (tuple[float, float]) – The time interval (T0, T)

  • dt (float, optional) – The time step, by default None

Returns:

The results of the solution

Return type:

Results

Raises:

ValueError – If dt is not positive or is longer than the interval.

step(interval)[source]#

Perform a single time step.

Parameters:

interval (tuple[float, float]) – The time interval (T0, T)

abstract variational_forms(dt: Expr | float) → tuple[Form | Sequence[Sequence[Form | None]], Form | Sequence[Form]][source]#

Create the variational forms corresponding to the given discretization of the given system of equations.

Parameters:

dt (Expr | float) – The time step

Returns:

The bilinear and linear form. A model with several coupled fields returns these blocked, as a nested list of forms and a list of forms respectively.

Return type:

tuple[_BilinearForm, _LinearForm]

class beat.base_model.Results(state, status)[source]#
state: Function | Sequence[Function]#

Alias for field number 0

status: Status#

Alias for field number 1

class beat.base_model.Status(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
class beat.monodomain_model.MonodomainModel(time: Constant, mesh: Mesh, M: Coefficient | float, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, params=None, C_m: float = 1.0, dx: Measure | None = None, **kwargs)[source]#

Solve

\[\frac{\partial V}{\partial t} - \nabla \cdot \left( M \nabla V \right) - I_{\mathrm{stim}} = 0\]

The right-hand side is affine in the previous potential, \(L = B v_{n} + L_0\), where \(B\) holds the mass and the explicit part of the diffusion and \(L_0\) the stimulus. With the parameter rhs_matrix (default True), \(B\) is assembled together with the system matrix, i.e. only when the time step changes, and every step assembles only \(L_0\) and adds the product \(B v_{n}\). This assumes, like the system matrix already does, that the conductivity and the capacitance do not change in time; at theta 0 (explicit diffusion) they enter only \(B\), which is then still used. Set rhs_matrix to False to assemble the whole right-hand side every step; this is also done, with a warning, when the right-hand side is not affine in \(v_{n}\) or \(B\) depends on data the system matrix does not, other than the conductivity, the capacitance and the time step (e.g. a stimulus linear in \(v_{n}\) that varies in time).

With the parameter lump_mass (default False) the mass term uses the lumped mass matrix, the diagonal matrix of the consistent one’s row sums, as openCARP and CARPentry do by default; diffusion and stimulus are integrated as before. The mass term is lumped the same way in the system matrix and on the right-hand side, with or without rhs_matrix. With theta > 0 the system matrix keeps the sparsity of the diffusion operator, so lumping barely changes the cost per step; its use there is to reproduce lumped-mass setups like for like. With theta = 0 (explicit diffusion) the system matrix is the lumped mass matrix, diagonal, so a Jacobi solve (ksp_type “preonly”, pc_type “jacobi”) is exact, and the time step limit of explicit diffusion is about five times larger than with the consistent mass matrix. The default, the consistent mass matrix, is more accurate on coarse meshes: with lumping, activation is later there (Niederer et al. 2011, “Verification of cardiac tissue electrophysiology simulators using an N-version benchmark”, Phil. Trans. R. Soc. A 369:4331-4351, doi:10.1098/rsta.2011.0139, Section 6). Only P1 Lagrange is supported, on straight or curved cells; other elements raise a ValueError.

property state: Function#

The transmembrane potential.

Kept for compatibility; v says the same thing by name and is preferred.

property v: Function#

The transmembrane potential.

variational_forms(dt: Expr | float) → tuple[Form, Form][source]#

Create the variational forms corresponding to the given discretization of the given system of equations.

Parameters:

dt (float) – Time step size

Returns:

The variational form and the precondition

Return type:

tuple[ufl.Form, ufl.Form]

class beat.monodomain_solver.MonodomainSplittingSolver(pde: ~beat.monodomain_solver.PDEModel | None, ode: ~beat.monodomain_solver.ODESolver, theta: float | None = None, monitor: ~beat.telemetry.BaseMonitor = <factory>, splitting: ~typing.Literal['godunov', 'strang'] | None = None, merge_half_steps: bool = False)[source]#

Deprecated name of SplittingSolver (same arguments and behaviour).

class beat.monodomain_solver.ODESolver(*args, **kwargs)[source]#

What the splitting driver asks of an ODE (cell model) solver.

The solver keeps the cell states at its own points (the degrees of freedom of v_ode’s space) and moves the potential between them and the PDE’s space. SplittingSolver never copies between v_pde and the PDE model’s v: they must be the same Function (pass v_pde=pde.state). Without a PDE model (pde=None) v_pde is not used.

Implemented by every beat.odesolver.BaseDolfinODESolver subclass and by beat.reaction_eikonal.FootCurrentODESolver.

from_dolfin() → None[source]#

Copy v_ode back into the cell states.

load_all_states(functions: list[Function]) → None[source]#

Set every state from functions (as returned by states_to_dolfin()).

ode_to_pde() → None[source]#

Project v_ode into v_pde.

pde_to_ode() → None[source]#

Project v_pde into v_ode.

states_to_dolfin(names: list[str] | None = None) → list[Function][source]#

New Functions on v_ode’s space holding every state, named names.

step(t0: float, dt: float) → None[source]#

Advance the cell states from t0 by dt.

to_dolfin() → None[source]#

Copy the potential from the cell states into v_ode.

property v_ode: Function#

The transmembrane potential at the ODE points.

property v_pde: Function#

the PDE model’s v.

Type:

The transmembrane potential in the PDE space

class beat.monodomain_solver.PDEModel(*args, **kwargs)[source]#

What the splitting driver asks of a PDE model.

It only ever advances the model and asks it to keep its history; the transmembrane potential is shared with the ODE solver directly. So any model offering these is drivable here, whatever else it solves for alongside.

property v: Function#

The transmembrane potential.

class beat.monodomain_solver.SplittingSolver(pde: ~beat.monodomain_solver.PDEModel | None, ode: ~beat.monodomain_solver.ODESolver, theta: float | None = None, monitor: ~beat.telemetry.BaseMonitor = <factory>, splitting: ~typing.Literal['godunov', 'strang'] | None = None, merge_half_steps: bool = False)[source]#

Advance a PDE model and an ODE solver by operator splitting.

splitting="strang" (the default) takes half an ODE step, a full PDE step and another half ODE step: second order in time, provided both sub-steps are second order themselves (PDE params["theta"] = 0.5 and a second-order cell scheme such as gotranx’s rush_larsen_2). splitting="godunov" takes a full ODE step and then a full PDE step: first order in time. theta is the deprecated way of choosing the splitting (the fraction of the step the first ODE sub-step covers: 1.0 Godunov, 0.5 Strang); after construction it always holds that fraction.

With pde=None only the cell model is advanced and the splitting is ignored. Wrapping the ODE solver in beat.reaction_eikonal.FootCurrentODESolver gives the R-E+ model (with a PDE) or the R-E- model (pde=None). monitor=None (or leaving it out) records nothing (a beat.telemetry.NullMonitor).

merge_half_steps=True (Strang only) merges each step’s closing ODE half-step with the next step’s opening one: still second order, at Godunov’s cost of one ODE step per step, but with a larger error than plain Strang at the same dt. Between steps the state then lacks the closing half-step, so call synchronize() before reading v or the ODE states; solve() and restart_functions() do it automatically. A parameter or stimulus change made between steps also affects the pending half-step of the previous step. Anything that reads v after every step (probes, beat.activation.ActivationTracker, conduction-velocity estimates) sees it lagging its closing half-step, so threshold activation times come out late by up to about half a time step; synchronizing every step to avoid this costs as much as plain Strang splitting.

load_restart(functions: Sequence[tuple[str, Function]], metadata: Mapping[str, Any] | None = None) → None[source]#

Restore the solver from functions as returned by restart_functions().

Overwrites pde.v and every ODE state, restores the PDE’s metadata if given (as returned by restart_metadata()), then sets the PDE’s previous value, exactly as construction does.

Without a PDE, v is one of the ODE states, so the states are authoritative: the checkpoint’s "v" is overwritten by the loaded states (ode.to_dolfin()).

Raises ValueError, before anything is modified and on every rank, if the checkpoint was saved by a solver with a PDE and this one has none or the reverse (metadata’s "has_pde"; checkpoints without it are not checked), or if its "v" does not fit this solver’s v.

restart_functions(state_names: Sequence[str]) → list[tuple[str, Function]][source]#

The Functions that hold everything the splitting scheme carries between steps.

These are ("v", pde.v) followed by ("state_<name>", f) for each ODE state, named by state_names (one per state). Write them to save a checkpoint. On a fresh solver, read into them and pass them to load_restart(). Without a PDE, "v" is ode.v_ode. Synchronizes first (see synchronize()), so a checkpoint is never taken mid-step. This means calling it mid-run (e.g. to checkpoint) changes the rest of a merged run at truncation-error level, compared with a run that never checkpoints.

restart_metadata() → dict[str, Any][source]#

State beyond the Functions, to be stored with a checkpoint (JSON-serializable).

Pass it back to load_restart(). "has_pde" records whether this solver has a PDE model, so a checkpoint is not loaded into the other kind; "pde" holds the PDE model’s own metadata, if it has any.

solve(interval: tuple[float, float], dt: float | None) → None[source]#

Step over interval with time step dt (see beat.utils.time_steps()).

Synchronizes at the end (see synchronize()).

step(interval)[source]#

Advance the coupled system over interval = (t0, t1).

Godunov: a full ODE step, then a full PDE step. Strang: half an ODE step, a PDE step and a closing half ODE step. Merged Strang: the closing half-step is left pending and merged into the next step’s opening ODE step (see synchronize()). If a pending half-step is left over after merging was turned off, it is synchronized first.

synchronize() → None[source]#

Run the pending closing ODE half-step of merged Strang splitting, if there is one.

With merge_half_steps=True each step leaves its closing half-step pending, to be merged with the next step’s opening half-step. Until then v and the ODE states lack that half-step (v is only first-order accurate), so call this before saving or post-processing them. Does nothing when nothing is pending (Godunov, no merging, no PDE, or already synchronized).

property synchronized: bool#

False while merged Strang splitting owes the last step’s closing ODE half-step.

property v: Function#

pde.v, or ode.v_ode without a PDE.

Type:

The transmembrane potential

class beat.odesolver.BaseDolfinMultiODESolver[source]#

Base class of the ODE solvers with one cell model per region

Regions are the values of markers (a Function on v_ode’s space); num_states, v_index and parameters are dicts keyed by region. A backend implements step() and the per-region storage primitives _get_region_state() and _set_region_state(), and calls _setup_regions() in its constructor. Dofs that belong to no region are left alone.

assign_all_states(functions: list[Function]) → None[source]#

Copy state i into functions[i] (one per state, on v_ode’s space).

from_dolfin() → None[source]#

Copy v_ode back into each region’s potential.

property full_values: ndarray[tuple[Any, ...], dtype[_ScalarT]]#

Every state at every point of v_ode’s space, shape (num_states, n).

load_all_states(functions: list[Function]) → None[source]#

Inverse of assign_all_states(): overwrite every ODE state from functions (one per state, on v_ode’s function space), e.g. when restarting from a checkpoint. Ends with to_dolfin().

to_dolfin() → None[source]#

Copy each region’s potential into v_ode.

values(marker: int) → ndarray[tuple[Any, ...], dtype[_ScalarT]][source]#

Region marker’s states, shape (num_states[marker], num_points(marker)).

class beat.odesolver.BaseDolfinODESolver[source]#

Base class of the ODE solvers that keep the cell states on a dolfinx function space

v_ode is the potential on the ODE space (P1, DG, quadrature, …) and v_pde the PDE model’s potential; ode_to_pde() and pde_to_ode() project between them. Implements beat.monodomain_solver.ODESolver.

A backend stores its states however it likes and implements step() and the two storage primitives _get_state() and _set_state(); everything that moves states between that storage and dolfinx Functions is built from them here. Multi-region backends derive from BaseDolfinMultiODESolver instead.

assign_all_states(functions: list[Function]) → None[source]#

Copy state i into functions[i] (one per state, on v_ode’s space).

from_dolfin() → None[source]#

Copy v_ode back into the cell states.

property full_values: ndarray[tuple[Any, ...], dtype[_ScalarT]]#

Every state at every point of v_ode’s space, shape (num_states, n).

load_all_states(functions: list[Function]) → None[source]#

Inverse of assign_all_states(): overwrite every ODE state from functions (one per state, on v_ode’s function space), e.g. when restarting from a checkpoint. Ends with to_dolfin().

ode_to_pde() → None[source]#

Projects v_ode (DG0, quadrature space, …) into v_pde (CG1)

pde_to_ode() → None[source]#

Projects v_pde (CG1) into v_ode (DG0, quadrature space, …)

states_to_dolfin(names: list[str] | None = None) → list[Function][source]#

New Functions on v_ode’s space holding every state, named names (default state_<i>).

to_dolfin() → None[source]#

Copy the potential from the cell states into v_ode.

class beat.odesolver.DolfinMultiODESolver(v_ode: 'dolfinx.fem.Function', v_pde: 'dolfinx.fem.Function', markers: 'dolfinx.fem.Function', init_states: 'dict[int, npt.NDArray]', parameters: 'dict[int, npt.NDArray]', fun: 'dict[int, Callable]', num_states: 'dict[int, int]', v_index: 'dict[int, int]', monitor: 'BaseMonitor' = <factory>)[source]#
values(marker: int) → ndarray[tuple[Any, ...], dtype[_ScalarT]][source]#

Region marker’s states: the live array the cell model steps.

class beat.odesolver.DolfinODESolver(v_ode: 'dolfinx.fem.Function', v_pde: 'dolfinx.fem.Function', init_states: 'npt.NDArray', parameters: 'npt.NDArray', fun: 'Callable', num_states: 'int', v_index: 'int' = 0, missing_variables: 'npt.NDArray | None' = None, num_missing_variables: 'int' = 0, monitor: 'BaseMonitor' = <factory>)[source]#
property full_values#

The live state array, shape (num_states, num_points).

class beat.odesolver.ODESystemSolver(fun: 'Callable', states: 'npt.NDArray', parameters: 'npt.NDArray', missing_variables: 'npt.NDArray | None' = None, _kwargs: 'dict[str, npt.NDArray]' = <factory>, monitor: 'BaseMonitor' = <factory>)[source]#

Compiled C backend for cell models generated by gotranx

beat advances the cell model through a function fun(states, t, parameters, dt) that acts on a (num_states, num_points) array (fun(states, t, parameters, dt, missing_variables=...) for the half of a split model that reads missing variables from the other half). This module compiles the C code that gotranx generates for one cell (gotranx ode2c, or gotranx.codegen.CCodeGenerator) together with a small driver that loops over the points, and wraps the library in a CScheme with that signature, so that it can be passed as fun to beat.odesolver.DolfinODESolver and beat.odesolver.DolfinMultiODESolver.

Rank 0 compiles the library into a cache directory, keyed by a hash of the source, the compiler and the flags, and the other ranks load it from there. The cache directory must therefore be on a file system that all ranks can see.

class beat.c_backend.CScheme(library_path: Path, scheme: str, *, num_states: int | None = None, num_parameters: int | None = None, num_missing_variables: int = 0, openmp: bool = False, num_threads: int | None = None)[source]#

A compiled cell-model scheme, callable as fun(states, t, parameters, dt)

A scheme with missing variables is called as fun(states, t, parameters, dt, missing_variables=...).

Parameters:
  • library_path (Path) – The shared library built by compile_scheme()

  • scheme (str) – The name of the per-cell C function

  • num_states (int | None, optional) – The number of states of the model; if given, states is checked against it

  • num_parameters (int | None, optional) – The number of parameters of the model; if given, parameters is checked against it

  • num_missing_variables (int, optional) – The number of missing variables that the scheme takes (those of a split model that the other half supplies), by default 0. missing_variables must be given exactly when it is positive.

  • openmp (bool, optional) – Whether the library was compiled with OpenMP

  • num_threads (int | None, optional) – The number of OpenMP threads, by default the OpenMP default

init_parameter_values() → ndarray[tuple[Any, ...], dtype[float64]][source]#

The default parameters of the model

init_state_values() → ndarray[tuple[Any, ...], dtype[float64]][source]#

The default initial states of the model

max_threads() → int[source]#

The number of threads that one call uses (1 without OpenMP)

missing_index(name: str) → int[source]#

The index of the missing variable name, as the scheme reads it

parameter_index(name: str) → int[source]#

The index of the parameter name

state_index(name: str) → int[source]#

The index of the state name

beat.c_backend.build_library(source: str, *, cc: str, cflags: tuple[str, ...], cache_dir: Path, comm: Comm, library_name: str = 'libbeat_scheme.so', source_name: str = 'scheme.c', description: str = 'C scheme') → Path[source]#

Compile source on rank 0 (unless it is cached) and return the library on all ranks

library_name and source_name are the file names inside the cache entry, and description names the library in log and error messages.

beat.c_backend.cache_key(source: str, cc: str, cc_version: str, flags: Sequence[str]) → str[source]#

Hash of everything that changes the compiled library

beat.c_backend.compile_scheme(c_code: str, scheme: str = 'rush_larsen_2', *, num_states: int | None = None, num_parameters: int | None = None, num_missing_variables: int = 0, cache_dir: str | ~pathlib.Path | None = None, cc: str | None = None, cflags: ~collections.abc.Sequence[str] = ('-O3', '-march=native'), openmp: bool = False, num_threads: int | None = None, comm: ~mpi4py.MPI.Intracomm = <mpi4py.MPI.Intracomm object>) → CScheme[source]#

Compile gotranx-generated C code into a fun(states, t, parameters, dt)

Parameters:
  • c_code (str) – C code with the per-cell function scheme, as generated by gotranx

  • scheme (str, optional) – The name of the per-cell function, by default “rush_larsen_2”

  • num_states (int | None, optional) – The number of states, used to check the arrays that the scheme is called with. The generated C code has no state or parameter counts, so without num_states and num_parameters the arrays are not checked against the model, and arrays that are too small make the C code read out of bounds. from_ode() fills them in.

  • num_parameters (int | None, optional) – The number of parameters, used to check the arrays that the scheme is called with (see num_states)

  • num_missing_variables (int, optional) – The number of missing variables, by default 0. If positive, the C function must take them as its last argument (const double *missing_variables), as gotranx generates it for an ODE with missing variables, and the scheme is called with missing_variables=....

  • cache_dir (str | Path | None, optional) – Where to put the library, by default default_cache_dir(). Must be visible to all ranks

  • cc (str | None, optional) – The C compiler, by default default_compiler()

  • cflags (Sequence[str], optional) – The compiler flags, by default ("-O3", "-march=native")

  • openmp (bool, optional) – Compile with -fopenmp and run the point loop in parallel, by default False

  • num_threads (int | None, optional) – The number of OpenMP threads, by default OMP_NUM_THREADS or the OpenMP default

  • comm (MPI.Intracomm, optional) – The communicator; rank 0 compiles, by default MPI.COMM_WORLD

Returns:

The compiled scheme

Return type:

CScheme

beat.c_backend.compiler_version(cc: str) → str[source]#

The first line of cc --version

beat.c_backend.default_cache_dir() → Path[source]#

$BEAT_C_CACHE if it is set, else ~/.cache/beat/c_backend

beat.c_backend.default_compiler() → str[source]#

$CC if it is set, else cc

beat.c_backend.from_ode(ode: ~typing.Any, scheme: str = 'rush_larsen_2', *, codegen_kwargs: dict[str, ~typing.Any] | None = None, comm: ~mpi4py.MPI.Intracomm = <mpi4py.MPI.Intracomm object>, **compile_kwargs: ~typing.Any) → CScheme[source]#

Generate C for a gotranx ODE and compile it with compile_scheme()

The code is generated on rank 0 only. compile_kwargs are passed on to compile_scheme() (cache_dir, cc, cflags, …). An ODE with missing variables (a split model) gives a scheme that takes missing_variables.

Parameters:
  • ode (gotranx.ode.ODE) – The cell model

  • scheme (str, optional) – The name of a gotranx scheme, by default “rush_larsen_2”

  • codegen_kwargs (dict[str, Any] | None, optional) – Extra keyword arguments for gotranx.codegen.CCodeGenerator.scheme()

  • comm (MPI.Intracomm, optional) – The communicator, by default MPI.COMM_WORLD

beat.c_backend.full_source(c_code: str, scheme: str, missing: bool = False) → str[source]#

The generated C code followed by the driver that loops over the points

With missing the driver passes the missing variables to the scheme (BEAT_MISSING).

beat.c_backend.generate_c_code(ode: Any, scheme: str = 'rush_larsen_2', codegen_kwargs: dict[str, Any] | None = None) → str[source]#

The C code for one cell, with index and initial value helpers and scheme

An ODE with missing variables (a split model) gives a scheme that takes them, and a missing_index helper.

Parameters:
  • ode (gotranx.ode.ODE) – The cell model

  • scheme (str, optional) – The name of a gotranx scheme, by default “rush_larsen_2”

  • codegen_kwargs (dict[str, Any] | None, optional) – Extra keyword arguments for gotranx.codegen.CCodeGenerator.scheme()

beat.c_backend.openmp_available(cc: str | None = None) → bool[source]#

Whether the C compiler can build an OpenMP shared library

beat.c_backend.target_signature(cc: str, flags: Sequence[str]) → str[source]#

The compiler’s predefined macros for flags if they target the native CPU, else “”

With -march=native (or -mcpu=native) the library depends on the features of the CPU it is compiled on, which platform.machine() does not tell apart (e.g. with and without AVX-512), so the macros that the compiler defines for these flags go into the cache key.

class beat.irksome_model.IrksomeMonodomainModel(time: Constant, mesh: Mesh, M: Coefficient | float, butcher_tableau, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, params=None, C_m: float = 1.0, dx: Measure | None = None, **kwargs)[source]#

The monodomain model advanced by an Irksome Runge-Kutta stepper.

Built like beat.MonodomainModel (same parameters, monitor, bcs factory and restart support); the theta-rule linear problem is replaced by an Irksome StageDerivativeTimeStepper for the given butcher_tableau.

The bcs factory must return Irksome-compatible conditions, built with irksome.backends.dolfinx.dirichletbc (plain dolfinx.fem.dirichletbc objects are rejected by Irksome). A restart reproduces the run to round-off rather than bit for bit: the stepper starts each solve from the previous step’s stages, which a checkpoint does not hold.

The parameter lump_mass is not supported and raises NotImplementedError.

assign_previous() → None[source]#

Nothing to do: Irksome keeps its own history within advance().

step(interval) → None[source]#

Perform a single time step.

Parameters:

interval (tuple[float, float]) – The time interval (T0, T)

class beat.irksome_odesolver.IrksomeMultiODESolver(v_ode: Function, v_pde: Function, markers: Function, fun: dict[int, Callable], init_states: dict[int, ndarray], butcher_tableau, time: Constant, num_states: dict[int, int], v_index: dict[int, int], parameters: dict[int, ndarray] | None = None, monitor: BaseMonitor | None = None)[source]#

Multi-region counterpart to IrksomeODESolver, analogous to how beat.odesolver.DolfinMultiODESolver extends beat.odesolver.DolfinODESolver: a different cell model (fun, init_states, parameters, num_states) can be used in each region of the mesh, as identified by an integer-valued markers function.

All regions share the same butcher_tableau and time/dt stepping. Internally, one full-mesh mixed-element Irksome stepper is built per marker (as in IrksomeODESolver), and only the degrees of freedom that actually belong to that marker are read back out; the values computed at the other degrees of freedom are discarded. This keeps the implementation simple and correct, but means the cost of a step scales with the number of regions (each region’s stepper solves over the whole mesh), unlike beat.odesolver.DolfinMultiODESolver, whose plain-numpy ODE systems are only ever sized to the points that need them. Prefer beat.odesolver.DolfinMultiODESolver for problems with many regions or very large meshes.

class beat.irksome_odesolver.IrksomeODESolver(v_ode: Function, v_pde: Function, fun: Callable, init_states: ndarray, butcher_tableau, time: Constant, num_states: int, v_index: int = 0, parameters: dict | None = None, monitor: BaseMonitor | None = None)[source]#

An ODE Solver mapping the DolfinODESolver interface to an Irksome stepper.

class beat.external_operator_odesolver.ExternalOperatorMultiODESolver(v_ode: Function, v_pde: Function, markers: Function, fun: dict[int, Callable], init_states: dict[int, ndarray], num_states: dict[int, int], v_index: dict[int, int], parameters: dict[int, ndarray] | None = None, monitor: BaseMonitor | None = None)[source]#

Multi-region counterpart to ExternalOperatorODESolver, analogous to how beat.odesolver.DolfinMultiODESolver extends beat.odesolver.DolfinODESolver and beat.irksome_odesolver. IrksomeMultiODESolver extends ExternalOperatorODESolver’s Irksome sibling: a different cell model (fun, init_states, parameters, num_states) can be used in each region of the mesh, as identified by an integer-valued markers function.

As in beat.irksome_odesolver.IrksomeMultiODESolver, one full-mesh external operator is built per marker, and only the degrees of freedom that actually belong to that marker are read back out; the cost of a step therefore scales with the number of regions. Prefer beat.odesolver.DolfinMultiODESolver for problems with many regions or very large meshes.

class beat.external_operator_odesolver.ExternalOperatorODESolver(v_ode: Function, v_pde: Function, fun: Callable, init_states: ndarray, num_states: int, v_index: int = 0, parameters: ndarray | None = None, monitor: BaseMonitor | None = None)[source]#

An ODE solver that steps a cell model via dolfinx-external-operator’s FEMExternalOperator, instead of the plain-numpy loop used by beat.odesolver.DolfinODESolver.

Unlike beat.irksome_odesolver.IrksomeODESolver, fun keeps the exact same signature already used by beat.odesolver.DolfinODESolver, fun(states, t, parameters, dt) -> new_states (plain NumPy or Numba-jitted arrays) — no UFL-returning variant of the cell model is needed. All num_states state variables are stored in a single vector-valued (blocked) dolfinx.fem.Function, rather than a mixed-element one, since FEMExternalOperator operates on raw (num_cells, num_quadrature_points, num_states) arrays rather than UFL expressions.

class beat.utils.PointEvaluator(mesh: Mesh, points: ndarray)[source]#

Evaluate a Function at fixed points; the point location is done once

points has shape (N, 3) (pad 2D points with a zero) and must be the same on every rank. Calling the evaluator returns the values at all points on every rank, NaN where a point is outside the mesh. Unlike scifem.evaluate_function the collision search is not repeated on every call. Each point takes its value from one rank, the lowest one that finds it, so NaN values come back as NaN and every rank gets the same result.

beat.utils.cpp_function_space(V)[source]#

The C++ function space behind V, whichever wrapper V arrives in.

Some dolfinx APIs return the Python FunctionSpace and others the C++ space it wraps; DirichletBC.function_space has returned each of them in different releases. Comparisons such as contains are only defined between two C++ spaces, so bring both sides down to that one shape rather than assuming either.

Parameters:

V (dolfinx.fem.FunctionSpace | dolfinx.cpp.fem.FunctionSpace) – The function space, in either wrapper

Returns:

The C++ function space

Return type:

dolfinx.cpp.fem.FunctionSpace

beat.utils.expand_layer(V: FunctionSpace, ft: MeshTags, endo_marker: int, epi_marker: int, endo_size: float, epi_size: float, output_mid_marker: int = 0, output_endo_marker: int = 1, output_epi_marker: int = 2) → Function[source]#

Expand the endo and epi markers to the rest of the mesh with a given size

Parameters:
  • V (dolfinx.fem.FunctionSpace) – The function space for your return function

  • ft (dolfinx.mesh.MeshTags) – The facet tags

  • endo_marker (int) – The endocardium marker

  • epi_marker (int) – The epicardium marker

  • endo_size (float) – The endocardium size

  • epi_size (float) – The epicardium size

  • output_mid_marker (int, optional) – The marker to be set for the midwall, by default 0

  • output_endo_marker (int, optional) – The marker to be set for the endocardium, by default 1

  • output_epi_marker (int, optional) – The marker to be set for the epicardium, by default 2

Returns:

The expanded markers as a function in V

Return type:

dolfinx.fem.Function

beat.utils.expand_layer_biv(V: FunctionSpace, ft: MeshTags, endo_lv_marker: int, endo_rv_marker: int, epi_marker: int, endo_size: float, epi_size: float, output_mid_marker: int = 0, output_endo_marker: int = 1, output_epi_marker: int = 2) → Function[source]#

Expand the endo and epi markers to the rest of the mesh with a given size

Parameters:
  • V (dolfinx.fem.FunctionSpace) – The function space for your return function

  • ft (dolfinx.mesh.MeshTags) – The facet tags

  • endo_lv_marker (int) – The LV endocardium marker

  • endo_rv_marker (int) – The LV endocardium marker

  • epi_marker (int) – The epicardium marker

  • endo_size (float) – The endocardium size

  • epi_size (float) – The epicardium size

  • output_mid_marker (int, optional) – The marker to be set for the midwall, by default 0

  • output_endo_marker (int, optional) – The marker to be set for the endocardium, by default 1

  • output_epi_marker (int, optional) – The marker to be set for the epicardium, by default 2

Returns:

The expanded markers as a function in V

Return type:

dolfinx.fem.Function

beat.utils.local_project(v: Function, V: FunctionSpace, u: Function | None = None) → Function | None[source]#

Element-wise projection using LocalSolver

Parameters:
Returns:

The projected function

Return type:

dolfinx.fem.Function | None

beat.utils.parse_element(space_string: str, mesh: Mesh, dim: int) → _ElementBase[source]#

Parse a string representation of a basix element family

beat.utils.real_function_space(mesh: Mesh) → FunctionSpace[source]#

A scalar space holding a single global degree of freedom.

dolfinx supports real spaces natively from 0.11; before that, basix.ufl.real_element exists but cannot be compiled into a function space, so fall back to scifem’s implementation.

Parameters:

mesh (dolfinx.mesh.Mesh) – The mesh the space is defined on

Returns:

The real function space

Return type:

dolfinx.fem.FunctionSpace

beat.utils.space_from_string(space_string: str, mesh: Mesh, dim: int = 1) → FunctionSpace[source]#

Constructed a finite elements space from a string representation of the space

Parameters:
  • space_string (str) – A string on the form {family}_{degree} which determines the space. Example ‘Lagrange_1’.

  • mesh (df.Mesh) – The mesh

  • dim (int) – 1 for scalar space, 3 for vector space.

Returns:

The function space

Return type:

df.FunctionSpace

beat.utils.time_steps(interval: tuple[float, float], dt: float | None) → Iterator[tuple[float, float]][source]#

The steps (t0, t1) of length dt that cover interval = (T0, T)

The number of steps is floor((T - T0) / dt), up to round-off in that one division, so a dt that does not divide the interval leaves the remainder out. The times accumulate (t1 = t0 + dt), as the time loops have always done. dt=None is one step over the whole interval.

Raises:

ValueError – If dt is not positive or is longer than the interval.

Activation times from the anisotropic eikonal equation

\[\sqrt{\nabla t_a^T V \nabla t_a} = 1, \qquad t_a = t_0 \text{ on the sources},\]

with the velocity tensor \(V = v_l^2 f f^T + v_t^2 s s^T + v_n^2 n n^T\), solved at the vertices of the mesh with the Fast Iterative Method (FIM) of Jeong & Whitaker (2008) and Fu, Kirby & Whitaker (2013), in the Jacobi form. The FIM kernel is C, compiled ahead of time with beat.c_backend.build_library() (rank 0 compiles into the hash-keyed cache, every rank loads it), optionally with OpenMP.

class beat.eikonal.EikonalSolver(mesh: Mesh, velocities: Sequence[Any], fibers: Sequence[Any], *, mesh_unit: str = 'mm', openmp: bool = False, num_threads: int | None = None, cc: str | None = None, cflags: Sequence[str] = ('-O3', '-march=native'), cache_dir: str | Path | None = None)[source]#

Solve the eikonal equation for activation times on mesh

The mesh, the metric \(V^{-1}\) and the connectivity are set up once, so solve() can be called for many source sets.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – The mesh (triangles, tetrahedra, quadrilaterals or hexahedra; any geometry degree). Only its vertices are used: the result is a P1 Function.

  • velocities (Sequence) – Conduction velocities along fibers (mesh units per ms): floats, pint quantities, Constants or (DG0/P1/…) Functions, evaluated at cell midpoints

  • fibers (Sequence) – The directions (e.g. (f0, s0, n0)), normalised at the cell midpoints

  • mesh_unit (str, optional) – Unit of the mesh coordinates, used to convert pint velocities, by default “mm”

  • openmp – Compilation of the C kernel: openmp runs its update phases with OpenMP (num_threads threads, by default OMP_NUM_THREADS or the OpenMP default); cc, cflags and cache_dir as in beat.c_backend.compile_scheme()

  • num_threads – Compilation of the C kernel: openmp runs its update phases with OpenMP (num_threads threads, by default OMP_NUM_THREADS or the OpenMP default); cc, cflags and cache_dir as in beat.c_backend.compile_scheme()

  • cc – Compilation of the C kernel: openmp runs its update phases with OpenMP (num_threads threads, by default OMP_NUM_THREADS or the OpenMP default); cc, cflags and cache_dir as in beat.c_backend.compile_scheme()

  • cflags – Compilation of the C kernel: openmp runs its update phases with OpenMP (num_threads threads, by default OMP_NUM_THREADS or the OpenMP default); cc, cflags and cache_dir as in beat.c_backend.compile_scheme()

  • cache_dir – Compilation of the C kernel: openmp runs its update phases with OpenMP (num_threads threads, by default OMP_NUM_THREADS or the OpenMP default); cc, cflags and cache_dir as in beat.c_backend.compile_scheme()

solve(sources: Sequence[Source], *, tol: float = 1e-06, max_iter: int | None = None, allow_unreached: bool = False) → Function[source]#

The activation time \(t_a\) (P1 Function named "activation_time")

Parameters:
  • sources (Sequence[Source]) – Where the activation starts; where sources overlap the smallest t0 wins. A Function t0 gives each marked vertex its own start time

  • tol (float, optional) – FIM convergence tolerance (ms), by default 1e-6

  • max_iter (int | None, optional) – Maximum FIM passes per kernel call, by default 4 times the number of local vertices plus 1000

  • allow_unreached (bool, optional) – Warn instead of raising if some vertices are not reached; they get inf

beat.eikonal.FAR = 1e+300#

Value of vertices not (yet) reached; the kernel uses the same number

class beat.eikonal.Source(marker: Callable[[ndarray[tuple[Any, ...], dtype[float64]]], ndarray[tuple[Any, ...], dtype[bool]]] | tuple[MeshTags, int], t0: float | Function = 0.0)[source]#

Vertices where \(t_a = t_0\)

marker is either a function x -> bool array of the coordinates (x has shape (3, num_points), as in dolfinx.fem.locate_dofs_geometrical()), or a pair (meshtags, value): all vertices of the entities tagged with value.

t0 is a float, or a scalar P1 dolfinx.fem.Function on the solver’s mesh. For a Function, a marked vertex starts at the Function’s value there, and a vertex where that value is not finite (inf or nan) is not a source.

beat.eikonal.cell_metric(mesh: Mesh, velocities: Sequence[Any], fibers: Sequence[Any], mesh_unit: str = 'mm') → ndarray[tuple[Any, ...], dtype[float64]][source]#

\(V^{-1} = \sum_i v_i^{-2} e_i e_i^T\) at the midpoint of every local cell

velocities are floats (mesh units per ms), pint quantities, Constants or Functions; fibers are the directions (Constants, Functions or UFL vectors), normalised here. Give one velocity and one direction per geometric dimension. Returns (num_cells, 6) components (xx, yy, zz, xy, xz, yz), with zz = 1 on 2D meshes.

beat.eikonal.solve_eikonal(mesh: Mesh, velocities: Sequence[Any], fibers: Sequence[Any], sources: Sequence[Source], *, tol: float = 1e-06, max_iter: int | None = None, allow_unreached: bool = False, **solver_kwargs: Any) → Function[source]#

Build an EikonalSolver (solver_kwargs go to it) and solve once

beat.eikonal.vertex_connectivity(num_vertices: int, cells: ndarray[tuple[Any, ...], dtype[int32]]) → tuple[ndarray[tuple[Any, ...], dtype[int32]], ndarray[tuple[Any, ...], dtype[int32]], ndarray[tuple[Any, ...], dtype[int32]], ndarray[tuple[Any, ...], dtype[int32]]][source]#

Vertex-to-cell and vertex-to-vertex maps of cells as CSR arrays

Returns (v2c_ptr, v2c, nb_ptr, nb): the cells of vertex v are v2c[v2c_ptr[v]:v2c_ptr[v + 1]] and its neighbours (vertices sharing a cell, without v itself) are nb[nb_ptr[v]:nb_ptr[v + 1]].

The reaction-eikonal (R-E) model of Neic et al. (2017)

An activation map \(t_a\) (e.g. from beat.eikonal.solve_eikonal()) drives the cell model through a foot current that starts at \(t_a\):

\[\frac{dv}{dt} = \frac{A}{\tau_F} e^{(t - t_a)/\tau_F}, \qquad 0 \le t - t_a \le T_{\mathrm{foot}}, \; v < V_{th}.\]

A is in mV (paper Eqs. 45-46), so this already is \(dv/dt\) and no \(C_m\) enters. The window follows openCARP: the paper’s Eq. 27 states \([t_a - T_{foot}, t_a]\), which contradicts its own appendix and the openCARP implementation.

  • R-E+ (with diffusion): SplittingSolver(pde, FootCurrentODESolver(...)) with a PDE model without stimulus.

  • R-E- (without diffusion): SplittingSolver(None, FootCurrentODESolver(...)).

class beat.reaction_eikonal.ExponentialFoot(A: float = 0.91, tau_F: float = 0.25, V_th: float = -30.0, duration: float = 5.0)[source]#

The exponential foot current of Neic et al. (2017)

Parameters:
  • A (float) – Amplitude (mV), by default 0.91

  • tau_F (float) – Time constant (ms), by default 0.25

  • V_th (float) – The foot stops once \(v\) reaches this (mV), by default -30.0

  • duration (float) – The foot is active for \(0 \le t - t_a \le\) duration (ms), by default 5.0

rate(dT: ArrayLike, v: ArrayLike) → ndarray[tuple[Any, ...], dtype[float64]][source]#

\(dv/dt\) of the foot at dT = t - t_a

class beat.reaction_eikonal.FootCurrentODESolver(ode: ODESolver, t_a: Function, foot: ExponentialFoot | Mapping[int, ExponentialFoot] = ExponentialFoot(A=0.91, tau_F=0.25, V_th=-30.0, duration=5.0), markers: Function | None = None, allow_unreached: bool = False, period: float | None = None)[source]#

Wrap an ODE solver so that every step adds the foot current at the activation time

After the wrapped solver’s step from t0 to t1 = t0 + dt: v += dt * foot.rate(t1 - t_a, v). Evaluating at t1 means the step that contains \(t_a\) already gets the foot. All other ODESolver methods are the wrapped solver’s; anything else is reachable through ode.

Parameters:
  • ode (ODESolver) – The cell model solver (e.g. beat.odesolver.DolfinODESolver or beat.odesolver.DolfinMultiODESolver), with v_ode and v_pde

  • t_a (dolfinx.fem.Function) – The activation time; evaluated once into v_ode’s space

  • foot (ExponentialFoot | Mapping[int, ExponentialFoot], optional) – The foot, or one per marker value in markers

  • markers (dolfinx.fem.Function | None, optional) – Region markers on v_ode’s space (required with a mapping foot)

  • allow_unreached (bool, optional) – Allow non-finite t_a (no foot there) instead of raising, by default False

  • period (float | None, optional) – If given, the foot fires again every period (ms): from t_a on, the foot sees (t1 - t_a) mod period instead of t1 - t_a, i.e. it fires at t_a + k * period. This is how reaction-eikonal electromechanics studies run several beats (the eikonal problem is solved once and its trigger is re-fired each beat, the ionic states being continuous). Nothing fires before t_a and nothing where t_a is not finite. Must be positive and exceed every foot’s duration. By default None (fires once)

beat.reaction_eikonal.exponential_foot_rate(dT: ArrayLike, v: ArrayLike, A: ArrayLike, tau_F: ArrayLike, V_th: ArrayLike, duration: ArrayLike) → ndarray[tuple[Any, ...], dtype[float64]][source]#

\(dv/dt = (A/\tau_F) e^{dT/\tau_F}\) where 0 <= dT <= duration and v < V_th, zero elsewhere (arguments broadcast; dT = t - t_a)

Bath loading and the pseudo-bidomain model

Neic et al. (2017, Sec. 2.2) compute extracellular potentials from a monodomain model in two steps:

  • Augmented monodomain. Near a tissue-bath interface the extracellular current returns through the bath, which speeds up conduction along the surface (“bath loading”). Bishop & Plank (2011) reproduce this in a monodomain model by replacing, in a thin layer of tissue next to the interface, the harmonic mean of the intra- and extracellular conductivities by the harmonic mean of the intracellular and bath conductivities (Neic Eqs. 14 and 15): interface_layer() and define_augmented_conductivity_tensor().

  • Pseudo-bidomain. Given \(v\), the extracellular potential in tissue and bath solves the elliptic part of the bidomain model (Neic Eq. 11): VolumeConductor. Electrograms at a few points are cheaper through lead fields: LeadFieldElectrodes.

beat.pseudo_bidomain.DEFAULT_PETSC_OPTIONS: dict[str, Any] = {'ksp_rtol': 1e-10, 'ksp_type': 'cg', 'pc_hypre_boomeramg_P_max': 4, 'pc_hypre_boomeramg_agg_nl': 1, 'pc_hypre_boomeramg_coarsen_type': 'HMIS', 'pc_hypre_boomeramg_interp_type': 'ext+i', 'pc_hypre_boomeramg_strong_threshold': 0.5, 'pc_hypre_type': 'boomeramg', 'pc_type': 'hypre'}#

CG with BoomerAMG, aggressive coarsening (about twice as fast as the default BoomerAMG for the wedge in its bath, at the same memory)

class beat.pseudo_bidomain.LeadFieldElectrodes(conductor: VolumeConductor, v: Function, sigma_i: Any, electrodes: Mapping[str, ArrayLike])[source]#

\(\phi_e\) at a few electrodes from lead fields, cheap enough for every time step

One lead field per electrode is solved once (VolumeConductor.lead_field()) and interpolated onto v’s space; each call then assembles \(-\int \sigma_i \nabla v \cdot \nabla Z_P \, dx\) over v’s mesh, which must be the tissue (dynamics) mesh and nothing else. sigma_i is the intracellular conductivity on that mesh, in the units given to the VolumeConductor. The values equal point evaluation of VolumeConductor.solve() exactly when the tissue cells coincide, and up to interpolation error otherwise. Calling returns {name: value}, the same on every rank. Implements beat.ecg.ElectrodeRecorder.

classmethod from_lead_fields(v: Function, sigma_i: Any, lead_fields: Mapping[str, Function]) → LeadFieldElectrodes[source]#

The recorder for lead fields already on v’s mesh (e.g. loaded from disk)

class beat.pseudo_bidomain.VolumeConductor(mesh: Mesh, cell_tags: MeshTags, tissue_markers: int | Sequence[int], bath_markers: int | Sequence[int], sigma_i: Any, sigma_e: Any, sigma_b: Any = 1.0, petsc_options: dict[str, Any] | None = None)[source]#

The extracellular potential of the pseudo-bidomain model (Neic et al. 2017, Eq. 11)

Solves, on a mesh of tissue (cells tagged tissue_markers) and bath (bath_markers),

\[\int_\Omega \sigma \nabla\phi_e \cdot \nabla w \, dx = -\int_{\Omega_T} \sigma_i \nabla v \cdot \nabla w \, dx, \qquad \sigma = \sigma_i + \sigma_e \text{ in tissue}, \; \sigma_b \text{ in bath},\]

with no flux through the outer boundary and \(\phi_e\) normalised to zero mean. sigma_i, sigma_e (tensors or floats, on mesh) and sigma_b are plain conductivities, not scaled by \(\chi\); only their ratios matter, so use one unit for all three. bath_markers may be empty for tissue without a bath. Every cell must be tagged.

The matrix is assembled and the preconditioner built once, so solve() and lead_field() cost one Krylov solve each. petsc_options replaces DEFAULT_PETSC_OPTIONS.

lead_field(point: ArrayLike) → Function[source]#

The lead field \(Z_P\) of an electrode at point

\(\int_\Omega \sigma \nabla Z_P \cdot \nabla w\,dx = w(P) - |\Omega|^{-1} \int_\Omega w\,dx\), zero mean. Then \(\phi_e(P) = -\int_{\Omega_T} \sigma_i \nabla v \cdot \nabla Z_P\,dx\) for every \(v\) (reciprocity).

solve(v: Function) → Function[source]#

\(\phi_e\) for the transmembrane potential v

v is a function on this mesh or on a separate tissue mesh; in the latter case it is interpolated onto the tissue cells (exact when the tissue cells coincide).

beat.pseudo_bidomain.define_augmented_conductivity_tensor(chi: Quantity, f0: Function | Constant, layer: Function, g_il: float | Quantity = 0.17, g_it: float | Quantity = 0.019, g_el: float | Quantity = 0.62, g_et: float | Quantity = 0.24, g_b: float | Quantity = 1.0) → Any[source]#

The monodomain conductivity tensor with bath loading (Neic et al. 2017, Eqs. 14-15)

In the bulk each direction gets the harmonic mean of the intra- and extracellular conductivities, as in beat.conductivities.define_conductivity_tensor(); where layer is 1 (see interface_layer()) the extracellular conductivity is replaced by the bath conductivity g_b. Floats are in S/m; the result is scaled by \(1/\chi\) like define_conductivity_tensor, so it goes straight into beat.MonodomainModel.

beat.pseudo_bidomain.interface_layer(mesh: Mesh, num_layers: int = 3, facets: ndarray[tuple[Any, ...], dtype[int32]] | None = None) → Function[source]#

The cells within num_layers element rings of the tissue-bath interface

Ring 1 is every cell with a vertex on one of facets (by default all exterior facets, i.e. a tissue mesh fully immersed in bath); ring \(k + 1\) is every cell sharing a vertex with ring \(k\). Bishop & Plank (2011) use three rings on a 100 µm mesh. Returns a DG0 function that is 1 in the layer and 0 elsewhere; the result does not depend on the mesh partition.

Record local activation times during a simulation

class beat.activation.ActivationTracker(v: Function, method: Literal['max_dvdt', 'threshold'] = 'max_dvdt', threshold: float = -30.0, t0: float = 0.0)[source]#

Track the activation time of every dof of v

Call update() after every time step. With method="max_dvdt" the activation time is the midpoint of the step with the largest \(dv/dt\) (the marker used by Neic et al. 2017), counted only where \(v\) reached threshold; with method="threshold" it is the first upward crossing of threshold, interpolated linearly within the step.

Parameters:
  • v (dolfinx.fem.Function) – The transmembrane potential (any space; the result lives in the same space)

  • method ({"max_dvdt", "threshold"}, optional) – How to define activation, by default “max_dvdt”

  • threshold (float, optional) – The threshold (mV), by default -30.0

  • t0 (float, optional) – The time of the current values of v, by default 0.0

Notes

  • NaN marks dofs that have never activated, and point evaluation (PointEvaluator, or scifem.evaluate_function from scifem 0.27.1) returns NaN in any cell that has such a dof.

  • With max_dvdt the time is that of the steepest upstroke over the whole run. For multi-beat runs use one tracker per beat, or use threshold.

  • Dofs already at or above threshold at t0 never get a threshold crossing (they stay NaN), but they count as reached for max_dvdt.

  • The ghost values of v must be current when update() is called (true for the solvers in beat).

property t_a: Function#

The activation times so far (NaN where not activated)

update(t: float) → None[source]#

Account for the step from the previous time to t

Endocardial activation sequences: stimuli that mimic the Purkinje system

The Purkinje network activates the ventricles from a few early sites on the endocardium. Durrer et al. (1970) mapped them in isolated human hearts: three areas in the LV (the anterior paraseptal wall, the centre of the left septal surface and the posterior paraseptal wall, between 0 and 5 ms) and, about 5 ms later, two in the RV (the septal surface and the free wall near the insertion of the anterior papillary muscle). From there the activation spreads over the endocardium much faster than through the wall, and the base, which has few Purkinje fibres, is activated by the tissue.

EndocardialActivation builds such a sequence on a bi-ventricular mesh:

  1. a HeartFrame (apex, long axis, septal and anterior directions) from the marked surfaces;

  2. the root sites (RootSite, by default DURRER_ROOT_SITES) placed on the endocardium by height along the long axis and angle around the LV axis;

  3. the time at which an endocardial wave, starting at the root sites after their delays and travelling over the endocardial surface at a Purkinje-like speed, reaches each endocardial vertex, from the eikonal equation on the surface (beat.eikonal.EikonalSolver);

  4. a stimulus (EndocardialActivation.stimulus()) that switches on every cell with a facet on the endocardium below max_height when this wave reaches it.

For reaction-eikonal EP (beat.reaction_eikonal.FootCurrentODESolver), which needs an activation time at every vertex of the mesh and not only on the endocardium, EndocardialActivation.volume_activation_times() solves a volume eikonal seeded with the endocardial times, which gives the whole-heart Durrer sequence.

Reference: D. Durrer, R. T. van Dam, G. E. Freud, M. J. Janse, F. L. Meijler and R. C. Arzbaecher, Total excitation of the isolated human heart, Circulation 41 (1970) 899-912.

beat.activation_sequence.BASE_MARKER_NAMES = ('BASE', 'MV', 'AV', 'TV', 'PV')#

Names of the facet markers taken as the base (valve planes) by EndocardialActivation.from_geometry(), in the order they are looked for

beat.activation_sequence.DURRER_ROOT_SITES: dict[str, RootSite] = {'LV anterior paraseptal': RootSite(surface='LV', height=0.7, position=60.0, delay=0.0), 'LV mid-septal': RootSite(surface='LV', height=0.5, position=0.0, delay=0.0), 'LV posterior paraseptal': RootSite(surface='LV', height=0.33, position=-60.0, delay=0.0), 'RV free wall': RootSite(surface='RV', height=0.4, position='free', delay=5.0), 'RV septal': RootSite(surface='RV', height=0.5, position='septal', delay=5.0)}#

three LV sites at 0 ms and two RV sites 5 ms later (delays of a human heart; scale them with delay_scale for a smaller or larger heart)

Type:

The root sites of Durrer et al. (1970)

class beat.activation_sequence.EndocardialActivation(mesh: ~dolfinx.mesh.Mesh, facet_tags: ~dolfinx.mesh.MeshTags, lv: int | ~collections.abc.Sequence[int], rv: int | ~collections.abc.Sequence[int], epi: int | ~collections.abc.Sequence[int], base: int | ~collections.abc.Sequence[int], anterior: int | ~collections.abc.Sequence[int] | None = None, anterior_point: ArrayLike | None = None, root_sites: ~collections.abc.Mapping[str, ~beat.activation_sequence.RootSite] = <factory>, conduction_velocity: float | ~pint.registry.Quantity = <factory>, axis: ~typing.Literal['base_normal', 'apex_to_base'] = 'base_normal', max_height: float = 0.85, delay_scale: float = 1.0, mesh_unit: str = 'mm', stimulated_cells: ~typing.Literal['facet', 'vertex'] = 'facet', eikonal_kwargs: dict[str, ~typing.Any] = <factory>)[source]#

An endocardial activation sequence from root sites (by default those of Durrer et al.)

The activation times are computed when the object is created (collective). Use stimulus() to get the stimulus current for beat.MonodomainModel.

Parameters:
  • mesh – A bi-ventricular mesh and its facet tags

  • facet_tags – A bi-ventricular mesh and its facet tags

  • lv – Marker values of the LV and RV endocardium, the epicardium and the base (all the valve planes)

  • rv – Marker values of the LV and RV endocardium, the epicardium and the base (all the valve planes)

  • epi – Marker values of the LV and RV endocardium, the epicardium and the base (all the valve planes)

  • base – Marker values of the LV and RV endocardium, the epicardium and the base (all the valve planes)

  • anterior (int | collections.abc.Sequence[int] | None) – Marker value(s) of an anterior surface (the pulmonary valve), which fixes the sign of the anterior direction; see HeartFrame.from_facet_tags()

  • anterior_point (ArrayLike | None) – A point on the anterior side, instead of anterior

  • root_sites (collections.abc.Mapping[str, beat.activation_sequence.RootSite]) – The root sites, by default DURRER_ROOT_SITES

  • conduction_velocity (float | pint.registry.Quantity) – Speed of the endocardial wave, a float in mesh units per ms or a pint quantity, by default 2 mm/ms (a Purkinje-like speed)

  • axis ({"base_normal", "apex_to_base"}) – The long axis of the heart frame, see HeartFrame.from_facet_tags()

  • max_height (float) – No stimulus above this fraction of the apex-base distance (the base has few Purkinje fibres and is activated by the tissue), by default 0.85

  • delay_scale (float) – Multiplies the delays of the root sites (e.g. the size of the heart relative to a human heart), by default 1

  • mesh_unit (str) – Unit of the mesh coordinates, by default “mm”

  • stimulated_cells ({"facet", "vertex"}) – Which cells are stimulated: those with a facet on the endocardium (the default), or also those that only touch it at a vertex or an edge. Each cell is stimulated at the earliest time of its endocardial vertices. With "facet", nodes on a sharp concave edge of a cavity (where most of the surrounding tissue touches the endocardium only at the edge) get too little stimulus on a coarse mesh and are activated late, by the tissue; "vertex" stimulates the whole fan of cells around them.

  • eikonal_kwargs (dict[str, Any]) – Passed to beat.eikonal.EikonalSolver (openmp, cc, …)

frame#

The coordinate system of the heart

Type:

HeartFrame

roots#

Per root site: "x", the vertex it was placed on, and "delay" (ms, scaled)

Type:

dict[str, dict]

activation_times#

P1 time (ms) at which the endocardial wave reaches each vertex of the endocardium below max_height; inf elsewhere. These are the times that volume_activation_times() seeds its volume eikonal with

Type:

dolfinx.fem.Function

cell_activation_times#

DG0 time (ms) at which each stimulated cell (see stimulated_cells) is stimulated; inf for the other cells

Type:

dolfinx.fem.Function

classmethod from_geometry(geometry: Any, **kwargs: Any) → EndocardialActivation[source]#

Build from a geometry with mesh, ffun and markers (name -> (value, dim)), such as a cardiac_geometries.geometry.Geometry or a beat.geometry.Geometry. The markers LV, RV and EPI are required; the base is every marker in BASE_MARKER_NAMES that is present, and PV, if present, is the anterior surface. The other keyword arguments go to the class.

stimulus(time: Constant, dt: float | Constant, *, amplitude: float | Quantity = 40.0, duration: float = 2.0, start: float = 0.0, chi: float | Quantity | None = None) → Stimulus[source]#

The stimulus current, to pass as I_s to beat.MonodomainModel

Every cell with a facet on the endocardium gets amplitude for duration ms from start plus its activation time. The pulse is averaged over a window of length dt centred on time (the time at which the PDE evaluates the stimulus), so every cell receives the same charge whatever the time step and wherever its pulse starts within a step.

Parameters:
  • time – The time Constant of the PDE model

  • dt – The time step (a float, or a Constant to change it later)

  • amplitude – A membrane current density, a float in uA/cm^2 or a pint quantity in current per area, or in current per volume together with chi; by default 40 uA/cm^2

  • duration – Length of the pulse (ms), by default 2

  • start – Offset added to all the activation times (ms), e.g. the start of a beat

  • chi – The surface-to-volume ratio, only for a volumetric amplitude (float in 1 / mesh_unit or pint quantity)

summary() → dict[str, Any][source]#

Root sites, frame and the range of the stimulus times (collective), e.g. for logging

volume_activation_times(velocities: Sequence[Any], fibers: Sequence[Any], *, tol: float = 1e-06, max_iter: int | None = None, allow_unreached: bool = False) → Function[source]#

Activation time (ms) at every vertex: the Durrer sequence through the wall

Solves a volume eikonal on the mesh, seeded with activation_times on the endocardium. activation_times is inf above max_height and on the unstimulated surface, so those vertices are not seeds: the volume wave reaches the base from the endocardium below. The seeds are fixed: a seeded vertex keeps its endocardial time even where the volume wave would reach it earlier (in the Durrer demo, the wave from the LV would reach 127 of the 565 seeded RV vertices earlier, by up to 15.3 ms). Nothing on the object changes.

Parameters:
  • velocities – Conduction velocities along fibers, as for beat.eikonal.EikonalSolver: floats, Constants or Functions in the object’s mesh_unit per ms, or pint quantities, which are converted with mesh_unit

  • fibers – Three directions (fibre, sheet, normal), e.g. (f0, s0, n0). With the same velocity in all three, any orthonormal triple gives an isotropic speed

  • tol – Passed to beat.eikonal.EikonalSolver.solve(): a vertex the wave cannot reach raises ValueError, or, with allow_unreached=True, warns and gets inf

  • max_iter – Passed to beat.eikonal.EikonalSolver.solve(): a vertex the wave cannot reach raises ValueError, or, with allow_unreached=True, warns and gets inf

  • allow_unreached – Passed to beat.eikonal.EikonalSolver.solve(): a vertex the wave cannot reach raises ValueError, or, with allow_unreached=True, warns and gets inf

Returns:

P1 activation time (ms), named "activation_time"

Return type:

dolfinx.fem.Function

Example

The activation time of reaction-eikonal EP:

t_a = activation.volume_activation_times(velocities, (f0, s0, n0))
ode = beat.reaction_eikonal.FootCurrentODESolver(ode, t_a=t_a, ...)
class beat.activation_sequence.HeartFrame(apex: ndarray[tuple[Any, ...], dtype[float64]], base_center: ndarray[tuple[Any, ...], dtype[float64]], lv_center: ndarray[tuple[Any, ...], dtype[float64]], rv_center: ndarray[tuple[Any, ...], dtype[float64]], long_axis: ndarray[tuple[Any, ...], dtype[float64]], septal: ndarray[tuple[Any, ...], dtype[float64]], anterior: ndarray[tuple[Any, ...], dtype[float64]], length: float)[source]#

A coordinate system of a bi-ventricular geometry

long_axis points from the apex towards the base: by default along the normal of the base plane, so that the base is at height 1 all around (see axis in from_facet_tags()). septal points from the LV towards the RV (perpendicular to the long axis) and anterior = long_axis x septal, flipped if needed to point towards anterior_point (for instance the pulmonary valve). The height of a point is its distance from the apex along the long axis, divided by that of the centre of the base.

coordinates(x: ArrayLike) → tuple[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]]][source]#

Height fraction, angle (degrees, 0 = septum, 90 = anterior) and distance from the LV axis of the points x (shape (n, 3))

classmethod from_facet_tags(mesh: Mesh, facet_tags: MeshTags, *, lv: int | Sequence[int], rv: int | Sequence[int], epi: int | Sequence[int], base: int | Sequence[int], anterior: int | Sequence[int] | None = None, anterior_point: ArrayLike | None = None, axis: Literal['base_normal', 'apex_to_base'] = 'base_normal') → HeartFrame[source]#

Build the frame from the marked surfaces (collective)

Parameters:
  • mesh – The mesh and its facet tags

  • facet_tags – The mesh and its facet tags

  • lv – Marker values of the LV and RV endocardium, the epicardium and the base (all valve planes)

  • rv – Marker values of the LV and RV endocardium, the epicardium and the base (all valve planes)

  • epi – Marker values of the LV and RV endocardium, the epicardium and the base (all valve planes)

  • base – Marker values of the LV and RV endocardium, the epicardium and the base (all valve planes)

  • anterior – Marker value(s) of an anterior surface (the pulmonary valve) that fixes the sign of the anterior direction

  • anterior_point – A point on the anterior side, used instead of anterior. Without either the sign of the anterior direction is arbitrary (long_axis x septal).

  • axis ({"base_normal", "apex_to_base"}) – The direction of the long axis. "base_normal" (the default) is the normal of the plane fitted to the base. "apex_to_base" points from the apex to the centre of the base; when the RV pulls that centre to one side the axis is tilted, and heights on the base then differ between the ventricles (in the bi-ventricular ellipsoid the base is at height 0.9 on the LV free wall and 1.1 on the RV free wall).

point(height: float, angle: float, radius: float) → ndarray[tuple[Any, ...], dtype[float64]][source]#

The point at height (fraction), angle (degrees) and radius from the LV axis (the inverse of coordinates()), e.g. to place electrodes

class beat.activation_sequence.RootSite(surface: Literal['LV', 'RV'], height: float, position: float | Literal['septal', 'free'], delay: float = 0.0)[source]#

An early activation site on the endocardium

Parameters:
  • surface ({"LV", "RV"}) – The endocardial surface the site is on

  • height (float) – Height above the apex, as a fraction of the apex-base distance (0 at the apex, 1 at the base)

  • position (float | {"septal", "free"}) – A float is the angle (degrees) around the LV axis, measured from the septum (0) towards the anterior wall (90); the posterior wall is at -90. "septal" and "free" take the vertex of the surface at that height closest to or furthest from the LV axis (the septal surface or the free wall of the RV).

  • delay (float) – Time (ms) at which the site activates, before delay_scale

beat.activation_sequence.place_root_site(frame: HeartFrame, comm: Comm, x: ndarray[tuple[Any, ...], dtype[float64]], site: RootSite, tol: float = 0.03, angle_window: float = 30.0) → ndarray[tuple[Any, ...], dtype[float64]][source]#

The point of x (the owned vertices of the site’s surface on this rank) that best matches site

Among the vertices within tol (doubled until there are some) of its height: for an angle, the vertex closest to that angle; for "septal"/"free", the vertices within angle_window degrees (doubled until there are some) of the septal direction are split by their distance from the LV axis into the septal surface (the nearer half of the range) and the free wall (the further half), and the vertex of that side closest to the septal direction is taken. This keeps the septal site off the junctions of the RV with the LV, which are about as close to the LV axis as the septal surface itself.

class beat.geometry.Geometry(mesh, ffun, markers, f0, s0, n0)[source]#
f0: Constant | Function | None#

Alias for field number 3

ffun: MeshTags | None#

Alias for field number 1

markers: dict[str, tuple[int, int]] | None#

Alias for field number 2

mesh: Mesh#

Alias for field number 0

n0: Constant | Function | None#

Alias for field number 5

s0: Constant | Function | None#

Alias for field number 4

beat.geometry.WEDGE_BATH_MARKERS: dict[str, int] = {'BATH': 2, 'TISSUE': 1}#

Cell tags of get_3D_wedge_bath_geometry()

beat.geometry.WEDGE_LAYERS: dict[str, int] = {'ENDO': 3, 'EPI': 1, 'M': 2}#

Marker values of the transmural layers of the wedge

class beat.geometry.WedgeBathGeometry(geometry: Geometry, cell_tags: MeshTags, margins: ndarray[tuple[Any, ...], dtype[float64]])[source]#

The wedge of get_3D_wedge_geometry() immersed in a box of bath

geometry holds the box mesh and f0, the wedge’s fiber field extended over the box (only its tissue values matter); cell_tags marks tissue and bath (WEDGE_BATH_MARKERS), and margins the actual bath thickness on each side along \(x, y, z\) (mm).

cell_tags: MeshTags#

Alias for field number 1

geometry: Geometry#

Alias for field number 0

margins: ndarray[tuple[Any, ...], dtype[float64]]#

Alias for field number 2

class beat.geometry.WedgeGeometry(geometry: Geometry, cell_tags: MeshTags, stimuli: dict[str, tuple[int, float]], electrode: ndarray[tuple[Any, ...], dtype[float64]], length: float)[source]#

The transmural wedge of Neic et al. (2017)

geometry.markers and cell_tags hold the stimulus regions S1-S3, stimuli maps their names to (tag, t0) (t0 in ms), electrode is the recording site \(P_E\) and length the transmural extent (mm).

cell_tags: MeshTags#

Alias for field number 1

electrode: ndarray[tuple[Any, ...], dtype[float64]]#

Alias for field number 3

geometry: Geometry#

Alias for field number 0

length: float#

Alias for field number 4

stimuli: dict[str, tuple[int, float]]#

Alias for field number 2

beat.geometry.get_2D_slab_geometry(comm: ~mpi4py.MPI.Intracomm, dx: float, Lx: float, Ly: float, cell_type: ~dolfinx.cpp.mesh.CellType = CellType.triangle, dtype: type = <class 'numpy.float64'>, transverse: bool = False) → Geometry[source]#

Generate a 2D slab geometry

Parameters:
  • comm (MPI.Intracomm) – The MPI communicator

  • dx (float) – The mesh resolution

  • Lx (float) – The length of the slab in the x-direction

  • Ly (float) – The length of the slab in the y-direction

  • cell_type (dolfinx.mesh.CellType, optional) – The celltype, by default dolfinx.mesh.CellType.triangle

  • dtype (type, optional) – Data type, by default np.float64

  • transverse (bool, optional) – Whether the fiber in the slab is transverse, by default False

Returns:

The geometry object

Return type:

Geometry

beat.geometry.get_2D_slab_mesh(comm: ~mpi4py.MPI.Intracomm, dx: float, Lx: float, Ly: float, cell_type: ~dolfinx.cpp.mesh.CellType = CellType.triangle, dtype: type = <class 'numpy.float64'>)[source]#

Generate a 2D slab mesh

Parameters:
  • comm (MPI.Intracomm) – The MPI communicator

  • dx (float) – The mesh resolution

  • Lx (float) – The length of the slab in the x-direction

  • Ly (float) – The length of the slab in the y-direction

  • cell_type (dolfinx.mesh.CellType, optional) – The celltype, by default dolfinx.mesh.CellType.triangle

  • dtype (type, optional) – Data type, by default np.float64

Returns:

The mesh object

Return type:

dolfinx.mesh.Mesh

beat.geometry.get_2D_slab_microstructure(mesh: Mesh, transverse: bool = False) → tuple[Constant, Constant][source]#

Get the microstructure of a 2D slab

Parameters:
  • mesh (dolfinx.mesh.Mesh) – The mesh object

  • transverse (bool, optional) – Whether the fiber in the slab is transverse, by default False

Returns:

The fiber and sheet directions

Return type:

tuple[dolfinx.fem.Constant, dolfinx.fem.Constant]

beat.geometry.get_3D_slab_geometry(comm: ~mpi4py.MPI.Intracomm, dx: float, Lx: float, Ly: float, Lz: float, cell_type: ~dolfinx.cpp.mesh.CellType = CellType.tetrahedron, dtype: type = <class 'numpy.float64'>, transverse: bool = False) → Geometry[source]#

Generate a 3D slab geometry

Parameters:
  • comm (MPI.Intracomm) – The MPI communicator

  • dx (float) – The mesh resolution

  • Lx (float) – The length of the slab in the x-direction

  • Ly (float) – The length of the slab in the y-direction

  • Lz (float) – The length of the slab in the z-direction

  • cell_type (dolfinx.mesh.CellType, optional) – The celltype, by default dolfinx.mesh.CellType.tetrahedron

  • dtype (type, optional) – Data type, by default np.float64

  • transverse (bool, optional) – Whether the fiber in the slab is transverse, by default False

Returns:

The geometry object

Return type:

Geometry

beat.geometry.get_3D_slab_microstructure(mesh: Mesh, transverse: bool = False) → tuple[Constant, Constant, Constant][source]#

Get the microstructure of a 3D slab

Parameters:
  • mesh (dolfinx.mesh.Mesh) – The mesh object

  • transverse (bool, optional) – Whether the fiber in the slab is transverse, by default False

Returns:

The fiber, sheet, and normal directions

Return type:

tuple[dolfinx.fem.Constant, dolfinx.fem.Constant, dolfinx.fem.Constant]

beat.geometry.get_3D_wedge_bath_geometry(comm: Intracomm, dx: float = 0.4, *, margin: float = 2.0, length: float = 25.0, width: float = 25.0, thickness: float = 5.0, cell_type: CellType = CellType.tetrahedron) → WedgeBathGeometry[source]#

The wedge of Neic et al. (2017) in a bath that extends margin mm beyond every face

The box uses the same grid as get_3D_wedge_geometry(comm, dx) (whose spacing per axis is the side length divided by rint(side / dx)), extended by a whole number of cells, so the tissue part of this mesh has exactly the wedge’s vertices and cells. margin is therefore rounded up to whole cells on each axis; margins holds the result.

beat.geometry.get_3D_wedge_geometry(comm: Intracomm, dx: float = 0.4, *, length: float = 25.0, width: float = 25.0, thickness: float = 5.0, stimulus_size: float = 1.0, cell_type: CellType = CellType.tetrahedron, fiber_space: tuple[str, int] = ('DG', 0)) → WedgeGeometry[source]#

The wedge benchmark of Neic et al. (2017), in mm

The box \([0, L] \times [0, W] \times [0, H]\) has the wall across \(x\) (epi at \(x = 0\), endo at \(x = L\)). The fibres rotate in the \(yz\)-plane from -60 degrees at the epicardium to +60 degrees at the endocardium; the sheet direction is \(e_x\). The stimuli are full-thickness corner columns: S1 at \((0, W)\) and S3 at \((L, 0)\) at \(t = 0\), S2 at \((0, 0)\) at \(t = 5\) ms (read off the paper’s Figs. 1 and 2). \(P_E\) is the centre of the endocardial face.

The mesh size is rounded so that it divides the box, so dx is only approximate and the stimulus columns are whole cells of width approximately stimulus_size. geometry.markers names the stimulus tags (S1, S2, S3), whose cell tags are in cell_tags.

beat.geometry.wedge_layer_markers(V: FunctionSpace, length: float = 25.0) → Function[source]#

Layer markers (WEDGE_LAYERS) on V: epi for the 25% of the wall nearest \(x = 0\), then 45% M, then 30% endo

length must match the transmural length of the wedge (pass wedge.length).

class beat.bidomain_model.BidomainModel(time: Constant, mesh: Mesh, M_i: Coefficient | float, M_e: Coefficient | float, I_s: Stimulus | Sequence[Stimulus] | Expr | None = None, params: dict[str, Any] | None = None, C_m: float = 1.0, dx: Measure | None = None, **kwargs)[source]#

Solve the bidomain model

\[\begin{split}C_m \frac{\partial v}{\partial t} - \nabla \cdot (M_i \nabla v) - \nabla \cdot (M_i \nabla u_e) - I_{\mathrm{stim}} &= 0 \\ \nabla \cdot (M_i \nabla v) + \nabla \cdot ((M_i + M_e) \nabla u_e) &= 0\end{split}\]

for the transmembrane potential \(v\) and the extracellular potential \(u_e\), with insulating boundary conditions on both.

The two fields live in separate Lagrange spaces and the system is assembled blocked and solved monolithically. Keeping v in a space of its own – rather than making the pair one mixed element – is what lets the ODE solvers consume it unchanged.

\(u_e\) is only determined up to a constant. By default it is normalised to zero mean with a Lagrange multiplier in a real-valued space; supplying bcs that constrain \(u_e\) grounds it instead and the multiplier is dropped, since the two together would over-determine the problem.

The parameter lump_mass (default False) lumps the mass term of the parabolic row, as in beat.MonodomainModel; see there for the trade-off.

Parameters:
property state: BidomainState#

Both solved-for fields, in the order the blocked system holds them.

step(interval) → None[source]#

Perform a single time step.

Parameters:

interval (tuple[float, float]) – The time interval (T0, T)

property u_e: Function#

The extracellular potential.

property v: Function#

The transmembrane potential.

variational_forms(dt: Expr | float) → tuple[Form | Sequence[Sequence[Form | None]], Form | Sequence[Form]][source]#

Blocked theta-rule forms for the coupled system.

Both rows are written in terms of the midpoint pair. The elliptic row carries no time derivative, but it is linear and homogeneous, so imposing it on the midpoint is equivalent to imposing it at the new time given that it held at the old one – and it is the only choice under which the collapse to the monodomain model at equal anisotropy ratio stays exact away from theta = 1.

Parameters:

dt (Expr | float) – The time step

Returns:

The blocked bilinear and linear forms

Return type:

tuple[_BilinearForm, _LinearForm]

class beat.bidomain_model.BidomainState(v: dolfinx.fem.Function, u_e: dolfinx.fem.Function)[source]#

The pair of fields a bidomain model solves for.

u_e: Function#

Alias for field number 1

v: Function#

Alias for field number 0

class beat.ecg.ECGRecovery(v: dolfinx.fem.function.Function, sigma_b: float | dolfinx.fem.function.Constant = 1.0, C_m: float | dolfinx.fem.function.Constant = 1.0, dx: ufl.measure.Measure | None = None, M: float = 1.0, petsc_options: dict[str, typing.Any] = <factory>)[source]#
class beat.ecg.ElectrodePotentials(recovery: ECGRecovery, points: Mapping[str, ArrayLike])[source]#

Potentials at many electrodes from one recovery solve.

The forms recovery.eval(p) are compiled once, at construction. Calling the instance solves for the transmembrane current once, assembles each form and sums it over mesh.comm.

Parameters:
  • recovery (ECGRecovery) – The recovery whose solution is evaluated.

  • points (Mapping[str, ArrayLike]) – Electrode name to position.

class beat.ecg.ElectrodeRecorder(*args, **kwargs)[source]#

Records potentials at named electrodes from the current transmembrane potential

Built once with the electrode positions; each call returns {name: potential}, the same on every rank, ready for LeadSystem.leads(). Implemented by ElectrodePotentials (infinite homogeneous medium around the heart) and beat.pseudo_bidomain.LeadFieldElectrodes (bounded tissue-and-bath volume conductor).

Their conductivities follow different conventions: ECGRecovery takes the monodomain tensor M as used by the PDE model (scaled by \(1/\chi\)) and a bath conductivity sigma_b; beat.pseudo_bidomain.VolumeConductor and LeadFieldElectrodes take the unscaled bidomain tensors \(\sigma_i\), \(\sigma_e\) and \(\sigma_b\).

class beat.ecg.Lead(name: str, terms: Mapping[str, float])[source]#

One lead: a named linear combination of potentials, Σ c·φ[p].

class beat.ecg.LeadSystem(definitions: tuple[~beat.ecg.Lead, ...], derived: ~collections.abc.Mapping[str, ~collections.abc.Mapping[str, float]] = <factory>, layout: tuple[tuple[str, ...], ...] | None = None)[source]#

A set of leads, as data.

Parameters:
  • definitions (tuple[Lead, ...]) – The leads, in output order.

  • derived (Mapping[str, Mapping[str, float]]) – Points that are not electrodes, each a weighted sum of electrode positions, Σ w·x. The terms of a lead may refer to them.

  • layout (tuple[tuple[str, ...], ...] | None) – Optional plotting layout, one tuple of lead names per row.

property electrodes: tuple[str, ...]#

the non-derived points in the terms, plus those the derived points’ weights use, in order of first appearance.

Type:

The electrodes needed

leads(potentials: Mapping[str, float | ndarray]) → dict[str, float | ndarray][source]#

Each lead’s Σ c·φ[p], in definitions order, from potentials such as an ElectrodeRecorder returns.

points(electrodes: Mapping[str, ArrayLike]) → dict[str, ndarray][source]#

Every given electrode as a float array, then each derived point as Σ w·x.

class beat.ecg.QTIntervalResult(qt_interval, start_index, end_index)[source]#
end_index: int#

Alias for field number 2

qt_interval: float#

Alias for field number 0

start_index: int#

Alias for field number 1

beat.ecg.detect_r_peaks(ecg_signal: ndarray, min_distance: float = 20) → ndarray[source]#

Detects R-peaks in the ECG signal.

Parameters:
  • ecg_signal (numpy.ndarray) – The ECG signal to be processed. Should be filtered.

  • min_distance (float, optional) – Minimum distance between R-peaks in milliseconds. Defaults to 20 ms.

Returns:

Indices of the detected R-peaks in the ECG signal.

Return type:

numpy.ndarray

beat.ecg.detect_t_end(averaged_rr: ndarray, r_peak_index: int, window_start_offset: int = 50, window_end_offset: int = 400) → int[source]#

Detects the end of the T-wave in the averaged RR interval using a derivative-based method.

Parameters:
  • averaged_rr (numpy.ndarray) – The averaged RR interval. Should not be None.

  • r_peak_index (int) – The index of the R-peak in the averaged RR interval.

  • window_start_offset (int, optional) – Start of the search window relative to R-peak (milliseconds). Defaults to 50.

  • window_end_offset (int, optional) – End of the search window relative to R-peak (milliseconds). Defaults to 400.

Returns:

Index of the T-wave end relative to the start of averaged_rr.

Return type:

int

beat.ecg.example(sampling_rate_hz: int = 1000, duration_s: float = 10, heart_rate_bpm: float = 60, q_offset_ms: float = 40, s_offset_ms: float = 40, t_peak_offset_ms: float = 200, r_width_ms: float = 20, q_width_ms: float = 20, s_width_ms: float = 30, t_width_ms: float = 60, qrs_peak_time: float = 200, noise_amplitude: float = 0.0, wander_freq_hz: float = 0.2, wander_amplitude: float = 0.1)[source]#

Generate a synthetic ECG signal.

Parameters:
  • sampling_rate_hz (int) – Sampling rate in Hz.

  • duration_s (float) – Duration of the signal in seconds.

  • heart_rate_bpm (float) – Heart rate in beats per minute.

  • q_offset_ms (float) – Offset for the Q wave in milliseconds.

  • s_offset_ms (float) – Offset for the S wave in milliseconds.

  • t_peak_offset_ms (float) – Offset for the T peak in milliseconds.

  • r_width_ms (float) – Width of the R wave in milliseconds.

  • q_width_ms (float) – Width of the Q wave in milliseconds.

  • s_width_ms (float) – Width of the S wave in milliseconds.

  • t_width_ms (float) – Width of the T wave in milliseconds.

  • qrs_peak_time (float) – Start time for the qrs peak time in milliseconds.

  • noise_amplitude (float) – Amplitude of the noise to be added to the signal.

  • wander_freq_hz (float) – Frequency of the baseline wander in Hz.

  • wander_amplitude (float) – Amplitude of the baseline wander.

Returns:

  • t_ms (np.ndarray) – Time vector in milliseconds.

  • ecg_signal (np.ndarray) – Generated ECG signal.

beat.ecg.qt_interval(t: ndarray, ecg_signal: ndarray, min_distance: float = 20.0, window_start_offset: int = 50, window_end_offset: int = 400) → QTIntervalResult[source]#

Processes the ECG signal to compute the corrected QT interval (QTc).

Parameters:
  • t (np.ndarray) – Time vector corresponding to the ECG signal in seconds.

  • ecg_signal (np.ndarray) – The ECG signal to be processed. Should be filtered.

  • min_distance (float, optional) – Minimum distance between R-peaks in seconds. Defaults to 20 ms.

  • window_start_offset (int, optional) – Start of the search window for T-wave end relative to R-peak (milliseconds). Defaults to 50.

  • window_end_offset (int, optional) – End of the search window for T-wave end relative to R-peak (milliseconds). Defaults to 400.

Returns:

A named tuple containing the start index, end index, and the QT interval in seconds. Returns None if no R-peaks are detected or if the T-end cannot be determined.

Return type:

QTIntervalResult

beat.ecg.twelve_lead(reference: Literal['potential', 'position'] = 'potential') → LeadSystem[source]#

The standard 12-lead ECG (Einthoven, Goldberger, Wilson).

Parameters:

reference ({"potential", "position"}) – "potential": a negative pole of n electrodes contributes -1/n of each electrode’s potential (the textbook leads). "position": the legacy simcardems variant, where a negative pole of more than one electrode is a single point at the mean of their positions (WCT_pt, LA_LL_mid, RA_LL_mid, RA_LA_mid), and the lead is a difference of two potentials.

class beat.stimulation.Stimulus(expr, dZ, marker)[source]#
dZ: Measure#

Alias for field number 1

expr: Expr#

Alias for field number 0

marker: int | None#

Alias for field number 2

beat.stimulation.compute_effective_dim(mesh: Mesh, subdomain_data: MeshTags) → int[source]#

Compute the effective dimension of the stimulus domain based on the subdomain data and the mesh. The effective dimension is the dimension used to compute the correct unit of the stimulus.

Parameters:
Returns:

The effective dimension of the stimulus domain.

Return type:

int

Raises:

ValueError – If the mesh topology dimension is not 1, 2 or 3.

beat.stimulation.compute_stimulus_unit(effective_dim: int, mesh_unit: str) → Quantity[source]#

Compute the unit of the stimulus based on the effective dimension and mesh unit.

Parameters:
  • effective_dim (int) – The effective dimension of the stimulus.

  • mesh_unit (str) – The unit of the mesh.

Returns:

The unit of the stimulus.

Return type:

pint.Quantity

Raises:

ValueError – If the effective dimension is negative or greater than 3.

beat.stimulation.convert_amplitude(effective_dim: int, amplitude: float | Quantity) → Quantity[source]#

Convert the amplitude to the appropriate unit based on the effective dimension. The function checks if the amplitude is already a pint.Quantity. If it is, it returns it as is. Otherwise, it assumes the amplitude is in the appropriate unit based on the effective dimension and converts it to a pint.Quantity.

Parameters:
  • effective_dim (int) – The effective dimension of the stimulus domain.

  • amplitude (float | pint.Quantity) – The amplitude value to be converted.

Returns:

The converted amplitude value in the appropriate unit.

Return type:

pint.Quantity

Raises:

ValueError – If the effective dimension is negative or greater than 3.

beat.stimulation.convert_chi(chi: float | Quantity, mesh_unit: str) → Quantity[source]#

Convert the surface to volume ratio to the appropriate unit based on the mesh unit.

Parameters:
  • chi (float | pint.Quantity) – The surface to volume ratio.

  • mesh_unit (str) – The unit of the mesh.

Returns:

The converted conductivity value.

Return type:

pint.Quantity

beat.stimulation.define_stimulus(mesh: Mesh, chi: float | Quantity, time: Constant, subdomain_data: MeshTags, marker: int, mesh_unit: str = 'cm', duration: float = 2.0, amplitude: float | Quantity = 500.0, start: float = 0.0) → Stimulus[source]#

Define a stimulus for the given mesh and subdomain data. The function computes the effective dimension of the stimulus domain, converts the amplitude and surface to volume ratio to the appropriate units, and defines the stimulus expression based on the time variable. The stimulus is defined as a conditional expression that is active within the specified duration and start time.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – The mesh object.

  • chi (float | pint.Quantity) – The surface to volume ratio.

  • time (dolfinx.fem.Constant) – The time variable.

  • subdomain_data (dolfinx.mesh.MeshTags) – The subdomain data object.

  • marker (int) – The marker for the subdomain where the stimulus is applied.

  • mesh_unit (str, optional) – Unit of the mesh, by default “cm”

  • duration (float, optional) – Duration of the stimulus, by default 2.0

  • amplitude (float | pint.Quantity, optional) – Amplitude of the stimulus, by default 500.0. A float is taken to be in uA/cm, uA/cm**2 or uA/cm**3, for a 1D, 2D or 3D stimulus domain respectively.

  • start (float, optional) – Start time of the stimulus, by default 0.0

Returns:

The stimulus object containing the expression, measure, and marker.

Return type:

Stimulus

Raises:

ValueError – If the mesh topology dimension is not 1, 2 or 3, or if the subdomain data dimension is not compatible with the mesh topology dimension. If the effective dimension is negative or greater than 3. If the mesh unit is not valid.

beat.stimulation.generate_random_activation(mesh: Mesh, time: Constant, points: ndarray, delays: ndarray, stim_start: float = 0.0, stim_duration: float = 2.0, stim_amplitude: float = 1.0, tol: float = 1e-12)[source]#

Generate a UFL expression for a random spatio-temporal activation pattern.

This function creates a sum of UFL conditionals, where each conditional represents a localized stimulus that triggers at a specific spatial point and a specific time (defined by a base start time plus a point-specific delay). It builds a balanced UFL tree to avoid hitting Python’s maximum recursion depth during JIT compilation of large numbers of points.

Parameters:
  • mesh (dolfinx.mesh.Mesh) – The computational mesh over which the spatial coordinates are defined.

  • time (dolfinx.fem.Constant) – The UFL time variable used to evaluate the temporal conditions.

  • points (np.ndarray) – An array of shape (N, d) containing the spatial coordinates of the N activation points, where d is the geometric dimension.

  • delays (np.ndarray) – An array of shape (N,) containing the temporal delay for each activation point.

  • stim_start (float, optional) – The global start time for the stimulation, by default 0.0.

  • stim_duration (float, optional) – The duration that the stimulus remains active at each point, by default 2.0.

  • stim_amplitude (float, optional) – The amplitude (strength) of the stimulus, by default 1.0.

  • tol (float, optional) – The spatial tolerance used to match the continuous spatial coordinate X to the discrete activation points, by default 1e-12.

Returns:

A balanced UFL expression representing the total stimulus.

Return type:

ufl.core.expr.Expr

Raises:

AssertionError – If the lengths of the points and delays arrays do not match.

beat.stimulation.get_dZ(mesh: Mesh, subdomain_data: MeshTags) → Measure[source]#

Get the measure for the subdomain data based on the mesh topology dimension. The measure is used to define the integral over the subdomain where the stimulus is applied.

Parameters:
Returns:

The measure for the subdomain data.

Return type:

ufl.Measure

Raises:

ValueError – If the mesh topology dimension is not 1, 2 or 3, or if the subdomain data dimension is not compatible with the mesh topology dimension.

class beat.conductivities.Conductivities(s_l, s_t)[source]#
s_l: float#

Alias for field number 0

s_t: float#

Alias for field number 1

Measure the conduction velocity of a monodomain model, and calibrate its conductivities

A finite element mesh that is too coarse to resolve the upstroke of the action potential slows the wave down: the conduction velocity depends on the mesh size and the time step as well as on the conductivities and the cell model. The usual remedy (e.g. tuneCV in openCARP, Costa et al. 2013) is to choose the conductivities so that a plane wave on a slab, discretised as the simulation will be, travels at the measured conduction velocities of the tissue.

measure_conduction_velocity() runs such a plane wave along or across the fibres of a thin slab and fits the velocity to the activation times. calibrate_conductivities() scales the conductivities in each direction until the velocities match target values.

class beat.conduction_velocity.CalibrationResult(conductivities: dict[str, ~typing.Any], scales: dict[str, float], velocities: dict[str, float], history: list[tuple[dict[str, float], dict[str, float]]] = <factory>)[source]#

The result of calibrate_conductivities()

conductivities#

The calibrated conductivities, to pass to beat.conductivities.define_conductivity_tensor()

Type:

dict[str, Any]

scales#

The factors the conductivities along ("longitudinal") and across ("transverse") the fibres were multiplied by

Type:

dict[str, float]

velocities#

The conduction velocities (mm/ms) with the calibrated conductivities

Type:

dict[str, float]

history#

Every iteration: the scales and the velocities they gave

Type:

list[tuple[dict[str, float], dict[str, float]]]

beat.conduction_velocity.SCALED_KEYS: dict[str, tuple[str, str]] = {'longitudinal': ('g_il', 'g_el'), 'transverse': ('g_it', 'g_et')}#

the longitudinal velocity depends only on the conductivities along the fibres, the transverse velocity only on those across them

Type:

The conductivities that each direction scales

beat.conduction_velocity.calibrate_conductivities(target_longitudinal: float | Quantity, target_transverse: float | Quantity, *, conductivities: dict[str, Any], rtol: float = 0.02, max_iterations: int = 10, **kwargs) → CalibrationResult[source]#

Scale the conductivities so that plane waves along and across the fibres travel at the target velocities

Each iteration measures both velocities with measure_conduction_velocity() and updates the scale k of each direction’s conductivities by k <- k (c_target / c)^(1/p), until both velocities c are within rtol of their targets. With a resolved upstroke the velocity is proportional to the square root of the conductivity, so p starts at 1/2; after two iterations it is the slope of log c against log k between the last two, which is smaller on a coarse mesh. Both directions are measured with both scales applied: on a coarse mesh of tetrahedra a plane wave along one direction also feels the conductivity across it. The splitting is the beat.SplittingSolver default (Strang since beat 0.14), through measure_conduction_velocity().

Parameters:
  • target_longitudinal – Target velocities along and across the fibres, floats in mm/ms or pint quantities

  • target_transverse – Target velocities along and across the fibres, floats in mm/ms or pint quantities

  • conductivities – The conductivities to scale, as returned by beat.conductivities.default_conductivities(); they are also the first guess

  • rtol – Relative tolerance on the velocities, by default 2 %

  • max_iterations – Iterations at most (two simulations each); if the tolerance is not met the iteration with the smallest relative error is used and a RuntimeWarning issued

  • kwargs – Passed to measure_conduction_velocity(): the cell model (fun, init_states, parameters, v_index), the mesh size dx and the time step dt (both those of the simulation), and the others

Return type:

CalibrationResult

beat.conduction_velocity.measure_conduction_velocity(*, fun: ~typing.Callable[[...], ~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]]], init_states: ~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], parameters: ~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], v_index: int, conductivities: dict[str, ~typing.Any], dx: float | ~pint.registry.Quantity, dt: float = 0.05, direction: ~typing.Literal['longitudinal', 'transverse'] = 'longitudinal', C_m: float | ~pint.registry.Quantity = Quantity(1.0, "microfarad / centimeter ** 2"), amplitude: float | ~pint.registry.Quantity = Quantity(50.0, "microampere / centimeter ** 2"), threshold: float = -30.0, length: float | ~pint.registry.Quantity | None = None, t_max: float | None = None, comm: ~mpi4py.MPI.Intracomm = <mpi4py.MPI.Intracomm object>) → float[source]#

Conduction velocity (mm/ms) of a plane wave along or across the fibres of a slab

The slab is a box of cubes of side dx, each split into six tetrahedra (beat.geometry.get_3D_slab_mesh()), of length length and cross-section 2 dx x 2 dx, with the fibres along its length ("longitudinal") or across it ("transverse"). The cells within max(1 mm, dx) of one end are stimulated for 2 ms, and the velocity is the slope of a least-squares fit of position against activation time (threshold crossing) of the nodes between 40 % and 90 % of the length. The splitting is the beat.SplittingSolver default (Strang since beat 0.14).

Parameters:
  • fun – The cell model, as for beat.odesolver.DolfinODESolver (init_states of one cell, shape (num_states,))

  • init_states – The cell model, as for beat.odesolver.DolfinODESolver (init_states of one cell, shape (num_states,))

  • parameters – The cell model, as for beat.odesolver.DolfinODESolver (init_states of one cell, shape (num_states,))

  • v_index – The cell model, as for beat.odesolver.DolfinODESolver (init_states of one cell, shape (num_states,))

  • conductivities – g_il, g_it, g_el, g_et and chi, as returned by beat.conductivities.default_conductivities()

  • dx – Mesh size, a float in mm or a pint quantity. Use the mesh size of the simulation.

  • dt – Time step (ms). Use the time step of the simulation.

  • direction ({"longitudinal", "transverse"}) – Whether the wave travels along or across the fibres

  • C_m – Membrane capacitance, a float in uF/cm² or a pint quantity

  • amplitude – Stimulus current per membrane area, a float in uA/cm² or a pint quantity

  • threshold – The potential (mV) whose upward crossing is the activation time

  • length – Length of the slab, a float in mm or a pint quantity; by default max(10 mm, 10 dx)

  • t_max – Simulated time at most (ms); by default the time a wave at 0.05 mm/ms needs to cross the slab. The simulation also stops, as a conduction block, when no node has been activated for as long as such a wave needs to cross two elements (at least 10 ms).

  • comm – The MPI communicator

Returns:

The conduction velocity in mm/ms, or 0 if the wave did not cross the measured part of the slab within t_max (conduction block)

Return type:

float

beat.conduction_velocity.scale_conductivities(conductivities: dict[str, Any], longitudinal: float = 1.0, transverse: float = 1.0) → dict[str, Any][source]#

A copy of conductivities with the intra- and extracellular conductivities along the fibres multiplied by longitudinal and those across them by transverse

Scaling the intra- and extracellular conductivity of a direction by the same factor scales their harmonic mean, the monodomain conductivity, by that factor too.

class beat.telemetry.BaseMonitor[source]#
class beat.telemetry.NullMonitor[source]#
class beat.telemetry.PerformanceMonitor(log_frequency: int = 1, comm: ~mpi4py.MPI.Intracomm = <mpi4py.MPI.Intracomm object>)[source]#

A monitor that accumulates timings and KSP stats, logging them periodically, and can save/display a final summary.

display_summary() → None[source]#

Logs a nicely formatted summary of the accumulated timings and metrics.

save_summary(filepath: str | Path) → None[source]#

Saves the performance metrics to a JSON file.

exception beat.single_cell.NumbaWarning[source]#
exception beat.single_cell.PlottingWarning[source]#