A General CTMC solver

EpiStochModels also provides a class to simulate any CTMC model you want, as long as you provide it with a transition matrix and propensity functions. So far this class is available for D programs, because of the impossibility of passing the propensity functions from Python into D. Nevertheless, We will demonstrate here how to use it:

Let’s use the SIRD model as an example. The corresponding ODE model is:

\begin{align} \frac{dS}{dt} &= -\beta S \frac{I}{N}\\ \frac{dI}{dt} &= \beta S \frac{I}{N} -\gamma I -\mu I\\ \frac{dR}{dt} &= \gamma I\\ \frac{dD}{dt} &= \mu I \end{align}

For this model, the following events are possible:

  1. Infection propensity: \(\beta S \frac{I}{N}\)

  2. Recovery propensity: \(\gamma I\)

  3. Death propensity: \(\mu I\)

The following transition matrix describe the changes in the state of the system when these events happen:

TM =

\begin{bmatrix} -1 & 1 & 0 & 0\\ 0 & -1 & 1 & 0\\ 0 & -1 & 0 & 1 \end{bmatrix}

.

The D code required to implement this model is:

int[][] tmat = [[-1,1,0,0],
                    [0,-1,1,0],
                    [0,-1,0,1]];
double[string] pars = [
    "beta": 0.3,
    "gam": 0.05,
    "mu": 0.01
];
alias double delegate(int[], double[string]) dy;
dy[] props = [
    (v,p)=> p["beta"]*v[0]*v[1]/sum(v[0..$-1]), // infection
    (v,p)=> p["gam"]*v[1], // recovery
    (v,p)=> p["mu"]*v[1] // death
    ];
CTMC model = new CTMC(tmat, props,["S", "I", "R", "D"], ["beta", "gamma", "mu"]);
model.initialize([995,5,0,0],pars);
auto res = model.run(0, 1000);
[1]:
!dub run --build=release --compiler=ldc2 --single CTMC_example.d
Locally registered package pyd 0.13.1+commit.5.g93d8235 was not found. Please run 'dub remove-local "/home/fccoelho/Downloads/pyd/"'.
Locally registered package epistochmodels ~master was not found. Please run 'dub remove-local "/home/fccoelho/Documentos/Software_projects/EpiStochModels/epistochmodels/"'.
Performing "release" build using ldc2 for x86_64.
mir-core 1.0.3: target for configuration "library" is up to date.
mir-algorithm 3.5.7: target for configuration "default" is up to date.
mir-random 2.2.15: target for configuration "extended" is up to date.
pyd 0.14.0: target for configuration "python38" is up to date.
epistochmodels 0.3.1: target for configuration "library" is up to date.
CTMC_example ~master: building configuration "application"...
Linking...
To force a rebuild of up-to-date targets, run again with --force.
Running ./CTMC_example
Time of the SIR run with N=1000: 1 ms, 350 μs, and 5 hnsecs

After running the line above, an executable called CTCM_example will be created alongside the source file that you can simply run:

[2]:
!./CTMC_example
Time of the SIR run with N=1000: 1 ms, 261 μs, and 8 hnsecs
[ ]: