Created
January 30, 2022 20:14
-
-
Save vittau/ef0e7d275feab1ec34fa169c0452eb6c to your computer and use it in GitHub Desktop.
Creates sample data for an SIR model plot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const TOTAL_POPULATION = 100000; | |
const INITIAL_INFECTED_POPULATION = 1; | |
const ALPHA = 1; | |
const BETA = 3; | |
const TIME_TICK = 0.1; | |
const MAXIMUM_TIME = 20; | |
if (TIME_TICK <= 0) throw new Error("Time tick must be greater than zero"); | |
if (INITIAL_INFECTED_POPULATION > TOTAL_POPULATION) | |
throw new Error( | |
"Infected population cannot be larger than the total population" | |
); | |
function writeToFile({ component, content }) { | |
try { | |
fs.writeFileSync(`sir-data-${component.toLowerCase()}.dat`, content); | |
//file written successfully | |
} catch (err) { | |
console.error(err); | |
} | |
} | |
function computeAndSaveToFile() { | |
const I_ar = []; | |
const S_ar = []; | |
const R_ar = []; | |
const t_ar = []; | |
let S = TOTAL_POPULATION; | |
let I = INITIAL_INFECTED_POPULATION; | |
let R = 0; | |
for (let t = 0; t <= MAXIMUM_TIME; t += TIME_TICK) { | |
const delS = ((-BETA * S * I) / TOTAL_POPULATION) * TIME_TICK; | |
const delI = | |
((BETA * S * I) / TOTAL_POPULATION) * TIME_TICK - ALPHA * I * TIME_TICK; | |
const delR = ALPHA * I * TIME_TICK; | |
S += delS; | |
I += delI; | |
R += delR; | |
I_ar.push(I); | |
S_ar.push(S); | |
R_ar.push(R); | |
t_ar.push(Number(t.toFixed(2))); | |
} | |
saveFiles({ t: t_ar, S: S_ar, I: I_ar, R: R_ar }); | |
} | |
function saveFiles({ t, S, I, R }) { | |
let content_S = "x y\n"; | |
let content_I = "x y\n"; | |
let content_R = "x y\n"; | |
for (let i = 0; i < t.length; i++) { | |
content_S += `${t[i]} ${S[i]}\n`; | |
content_I += `${t[i]} ${I[i]}\n`; | |
content_R += `${t[i]} ${R[i]}\n`; | |
} | |
writeToFile({ component: "s", content: content_S }); | |
writeToFile({ component: "i", content: content_I }); | |
writeToFile({ component: "r", content: content_R }); | |
} | |
computeAndSaveToFile(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on this gist.