epimodelstudio 0.11.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. epimodelstudio-0.11.0/LICENSE.txt +22 -0
  2. epimodelstudio-0.11.0/PKG-INFO +125 -0
  3. epimodelstudio-0.11.0/README.md +104 -0
  4. epimodelstudio-0.11.0/epimodelstudio/__init__.py +7 -0
  5. epimodelstudio-0.11.0/epimodelstudio/__main__.py +38 -0
  6. epimodelstudio-0.11.0/epimodelstudio/advisor.py +214 -0
  7. epimodelstudio-0.11.0/epimodelstudio/analysis.py +528 -0
  8. epimodelstudio-0.11.0/epimodelstudio/backward.py +102 -0
  9. epimodelstudio-0.11.0/epimodelstudio/bundle.py +70 -0
  10. epimodelstudio-0.11.0/epimodelstudio/categories.py +51 -0
  11. epimodelstudio-0.11.0/epimodelstudio/cite.py +84 -0
  12. epimodelstudio-0.11.0/epimodelstudio/diagram.py +216 -0
  13. epimodelstudio-0.11.0/epimodelstudio/evidence.py +549 -0
  14. epimodelstudio-0.11.0/epimodelstudio/glossary.py +184 -0
  15. epimodelstudio-0.11.0/epimodelstudio/latex.py +239 -0
  16. epimodelstudio-0.11.0/epimodelstudio/layout_editor.py +116 -0
  17. epimodelstudio-0.11.0/epimodelstudio/literature.py +179 -0
  18. epimodelstudio-0.11.0/epimodelstudio/lyapunov.py +57 -0
  19. epimodelstudio-0.11.0/epimodelstudio/metrics.py +291 -0
  20. epimodelstudio-0.11.0/epimodelstudio/model.py +125 -0
  21. epimodelstudio-0.11.0/epimodelstudio/plain.py +276 -0
  22. epimodelstudio-0.11.0/epimodelstudio/report.py +477 -0
  23. epimodelstudio-0.11.0/epimodelstudio/repro.py +220 -0
  24. epimodelstudio-0.11.0/epimodelstudio/results.py +38 -0
  25. epimodelstudio-0.11.0/epimodelstudio/safeparse.py +135 -0
  26. epimodelstudio-0.11.0/epimodelstudio/settings.py +21 -0
  27. epimodelstudio-0.11.0/epimodelstudio/summary.py +67 -0
  28. epimodelstudio-0.11.0/epimodelstudio/templates.py +672 -0
  29. epimodelstudio-0.11.0/epimodelstudio/units.py +405 -0
  30. epimodelstudio-0.11.0/epimodelstudio/validate.py +178 -0
  31. epimodelstudio-0.11.0/epimodelstudio/verify.py +226 -0
  32. epimodelstudio-0.11.0/epimodelstudio.egg-info/PKG-INFO +125 -0
  33. epimodelstudio-0.11.0/epimodelstudio.egg-info/SOURCES.txt +83 -0
  34. epimodelstudio-0.11.0/epimodelstudio.egg-info/dependency_links.txt +1 -0
  35. epimodelstudio-0.11.0/epimodelstudio.egg-info/requires.txt +14 -0
  36. epimodelstudio-0.11.0/epimodelstudio.egg-info/top_level.txt +2 -0
  37. epimodelstudio-0.11.0/epimodelstudio_api/__init__.py +6 -0
  38. epimodelstudio-0.11.0/epimodelstudio_api/__main__.py +29 -0
  39. epimodelstudio-0.11.0/epimodelstudio_api/app.py +250 -0
  40. epimodelstudio-0.11.0/epimodelstudio_api/config.py +30 -0
  41. epimodelstudio-0.11.0/epimodelstudio_api/jobs.py +255 -0
  42. epimodelstudio-0.11.0/pyproject.toml +19 -0
  43. epimodelstudio-0.11.0/setup.cfg +4 -0
  44. epimodelstudio-0.11.0/tests/test_T3_T6.py +167 -0
  45. epimodelstudio-0.11.0/tests/test_advisor.py +86 -0
  46. epimodelstudio-0.11.0/tests/test_api.py +362 -0
  47. epimodelstudio-0.11.0/tests/test_backward.py +99 -0
  48. epimodelstudio-0.11.0/tests/test_categories.py +34 -0
  49. epimodelstudio-0.11.0/tests/test_chitnis2006.py +162 -0
  50. epimodelstudio-0.11.0/tests/test_cite_bundle.py +89 -0
  51. epimodelstudio-0.11.0/tests/test_codeco.py +94 -0
  52. epimodelstudio-0.11.0/tests/test_dengue.py +184 -0
  53. epimodelstudio-0.11.0/tests/test_diagram.py +54 -0
  54. epimodelstudio-0.11.0/tests/test_ebola.py +115 -0
  55. epimodelstudio-0.11.0/tests/test_evidence.py +42 -0
  56. epimodelstudio-0.11.0/tests/test_feng.py +44 -0
  57. epimodelstudio-0.11.0/tests/test_glossary.py +93 -0
  58. epimodelstudio-0.11.0/tests/test_hiv.py +113 -0
  59. epimodelstudio-0.11.0/tests/test_latex.py +37 -0
  60. epimodelstudio-0.11.0/tests/test_launcher.py +82 -0
  61. epimodelstudio-0.11.0/tests/test_layout_summary.py +56 -0
  62. epimodelstudio-0.11.0/tests/test_literature.py +68 -0
  63. epimodelstudio-0.11.0/tests/test_literature2.py +169 -0
  64. epimodelstudio-0.11.0/tests/test_literature_section.py +65 -0
  65. epimodelstudio-0.11.0/tests/test_malaria.py +203 -0
  66. epimodelstudio-0.11.0/tests/test_metrics.py +233 -0
  67. epimodelstudio-0.11.0/tests/test_plain.py +287 -0
  68. epimodelstudio-0.11.0/tests/test_quarantine.py +323 -0
  69. epimodelstudio-0.11.0/tests/test_report_html.py +55 -0
  70. epimodelstudio-0.11.0/tests/test_repro.py +100 -0
  71. epimodelstudio-0.11.0/tests/test_safeparse.py +150 -0
  72. epimodelstudio-0.11.0/tests/test_scope_wording.py +25 -0
  73. epimodelstudio-0.11.0/tests/test_sepia_gatto.py +77 -0
  74. epimodelstudio-0.11.0/tests/test_sidarthe.py +125 -0
  75. epimodelstudio-0.11.0/tests/test_sirs_nonlinear_original.py +58 -0
  76. epimodelstudio-0.11.0/tests/test_sis_vaccination.py +183 -0
  77. epimodelstudio-0.11.0/tests/test_tien_earn.py +170 -0
  78. epimodelstudio-0.11.0/tests/test_timeouts.py +22 -0
  79. epimodelstudio-0.11.0/tests/test_units.py +339 -0
  80. epimodelstudio-0.11.0/tests/test_validation.py +149 -0
  81. epimodelstudio-0.11.0/tests/test_verify.py +96 -0
  82. epimodelstudio-0.11.0/tests/test_wearing.py +92 -0
  83. epimodelstudio-0.11.0/tests/test_web_e2e.py +789 -0
  84. epimodelstudio-0.11.0/tests/test_windows_compat.py +105 -0
  85. epimodelstudio-0.11.0/tests/test_wording.py +25 -0
@@ -0,0 +1,22 @@
1
+ MIT License
2
+ license-files = ["LICENSE.txt"]
3
+
4
+ Copyright (c) 2026 Mohammed Fadul
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: epimodelstudio
3
+ Version: 0.11.0
4
+ Summary: Epidemic Model Studio: define SIR-family compartmental models, get equations, stability analysis with trust labels, simulations and a reproducible run record.
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE.txt
8
+ Requires-Dist: numpy
9
+ Requires-Dist: scipy
10
+ Requires-Dist: sympy
11
+ Requires-Dist: matplotlib
12
+ Requires-Dist: markdown
13
+ Requires-Dist: cloudpickle
14
+ Provides-Extra: api
15
+ Requires-Dist: fastapi; extra == "api"
16
+ Requires-Dist: uvicorn[standard]; extra == "api"
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest; extra == "test"
19
+ Requires-Dist: httpx; extra == "test"
20
+ Dynamic: license-file
21
+
22
+ # epimodelstudio (analysis engine)
23
+ Define a compartment model as flows -> get diagram, ODEs, well-posedness, DFE, R0 (next-generation matrix),
24
+ Routh-Hurwitz stability, endemic equilibrium, R0 sensitivity, simulations, and an HTML/Markdown report.
25
+
26
+ pip install -r requirements.txt
27
+ python -m epimodelstudio run my_model.json my_run (see the command line below)
28
+ python -m pytest tests (needs: pip install pytest)
29
+ python -m epimodelstudio reproduce my_run (repeat a run and compare it with its run record)
30
+
31
+ Every run folder also holds `how_to_cite.txt` and `reproducibility_bundle.zip`. Changes by version are in `CHANGELOG.md`.
32
+
33
+ Mark each flow that is a NEW infection with infection=True (that is what lets R0 be derived automatically).
34
+ Status labels in the report: PROVED / CHECKED NUMERICALLY / NOT DECIDED.
35
+ Backward bifurcation (Castillo-Chavez & Song) and LaTeX/PDF export are built. Lyapunov/global-DFE module (T3) and multi-infected models incl. numeric fallbacks (T6) are built. The web interface (canvas, API, advisor, library of templates) is built; see `START_HERE.md`.
36
+
37
+ **Just want to use the tool on your own computer?** See `START_HERE.md` (double-click `start.bat` on Windows, or run `./start.sh`). **Hosting a small pilot?** See `DEPLOY_CLOUD_RUN.md` (a `Dockerfile` is included).
38
+
39
+ ## Windows quick start for the command-line engine (PowerShell or Command Prompt)
40
+ Use a virtual environment inside the project folder so the libraries do not touch your other Python installs.
41
+
42
+ cd path\to\epimodelstudio_tool
43
+ py -3.13 -m venv .venv (any Python 3.11 or newer; run `py -0` to list the ones you have)
44
+ .venv\Scripts\python -m pip install -r requirements.txt
45
+ .venv\Scripts\python -m epimodelstudio templates
46
+ .venv\Scripts\python -m epimodelstudio template seir_demography my_model.json
47
+ .venv\Scripts\python -m epimodelstudio run my_model.json my_run
48
+
49
+ Calling `.venv\Scripts\python` directly means you never need to "activate" the environment (activation can be blocked by PowerShell policy).
50
+ Open `my_run\report.html` in a browser. A PDF is built only if LaTeX is installed (MiKTeX or TeX Live); without it you still get the HTML report and
51
+ the `report.tex` source.
52
+
53
+ Notes
54
+ - On Windows the time-limited symbolic steps start a fresh process each time, which takes a few seconds (importing SymPy and SciPy); runs are slower than on
55
+ Linux or macOS but give the same results. The time limit counts only the work itself, not the start-up.
56
+ - If you call the engine from your own script on Windows, put the calls under `if __name__ == "__main__":` (a Python requirement for programs that start
57
+ child processes).
58
+
59
+ ## Units and durations (model file format 2)
60
+
61
+ A model file may declare what its numbers mean. Files without this (format 1) still load, with a notice.
62
+
63
+ ```json
64
+ "time_unit": "day", // hour | day | week | month | year | unspecified
65
+ "population_unit": "proportion", // people | individuals | animals | proportion | unspecified
66
+ "parameters": {
67
+ "beta": {"value": 0.6, "unit": "1/day", "label": "Transmission rate", "min": 0.3, "max": 0.9, "source": "your reference"},
68
+ "sigma": {"duration": 5, "label": "Latent period"}, // 5 days -> rate 0.2 per day
69
+ "mu": {"duration": 70, "duration_unit": "year"}, // converted to a daily rate
70
+ "gamma": 0.1428 // a bare number is still fine
71
+ },
72
+ "observations": [{"name": "weekly cases", "quantity": "new_infections", "reporting_fraction": 0.3, "time_unit": "week"}]
73
+ ```
74
+
75
+ * The tool converts everything to the model's time unit (1 year = 365.25 days) and checks that every flow has units of "population per time". If every parameter has a unit, a mismatch is an error; if only some do, it is a warning.
76
+ * Bounds, labels, sources and observations are stored and shown but do not change the model hash; units do.
77
+ * `observations` is reserved for later data comparison. It is checked but not used yet.
78
+ * The built-in templates carry units and parameter names but no literature sources.
79
+
80
+ ## Views and the plain-language summary
81
+
82
+ `report.html` opens on an **Overview** with four buttons at the top. The analysis is the same in every view; only what is shown changes.
83
+
84
+ * **Overview** (default): the findings in plain sentences, each with its trust label, a "Read with care" list, the diagram and the outbreak curve.
85
+ * **Epidemiology**: the Overview plus the technical summary table, outcome measures, all figures and the sensitivity results.
86
+ * **Mathematics**: equations, derivations and proofs, verification and reproducibility.
87
+ * **Everything**: all of it (this is also `report.md`).
88
+
89
+ The plain sentences are built from the results, not written by hand. A proved result is stated plainly; a numerically checked one is worded as evidence ("the numbers indicate", "in the simulation"); an undecided one says it could not be decided. If any automatic cross-check fails, a warning comes first. The LaTeX/PDF report carries the same plain panel before its summary table.
90
+
91
+ ## Running the API (for the web app)
92
+
93
+ ```
94
+ pip install -r requirements-api.txt
95
+ python -m epimodelstudio_api --port 8000 # http://127.0.0.1:8000/api/docs lists every endpoint
96
+ ```
97
+
98
+ | Endpoint | What it does |
99
+ |---|---|
100
+ | `GET /api/health` | engine version and number of running analyses |
101
+ | `GET /api/templates`, `GET /api/templates/{name}` | the 12 built-in models; the second returns the model file |
102
+ | `POST /api/models/validate` | checks a model file; returns a summary (parameters with units, warnings) and the normalised file. Nothing is stored |
103
+ | `POST /api/models/diagram` | the compartment diagram as a PNG |
104
+ | `POST /api/analyses` | starts an analysis (202), or returns the finished one for an identical model (200, `cached: true`) |
105
+ | `GET /api/analyses/{id}` | status; when done, `results` (plain-language findings, summary, outcome measures, verification) and the list of files |
106
+ | `GET /api/analyses/{id}/files/{name}` | `report.html` (four views), `report.pdf`, `report.md`, `report.tex`, `latex_bundle.zip`, figures, `model.json`, `run_record.json`, `results.json` |
107
+ | `DELETE /api/analyses/{id}` | cancels a running analysis and deletes the run |
108
+
109
+ Safety: every model is checked before a job exists (safe rate parser, size and complexity limits, request size limit); each analysis runs in its own process with a time limit and is killed with everything it started; report pages are served in a sandbox; text typed by the user is escaped in reports. There are no accounts yet, so run it on your own machine or behind a login. Limits can be changed with `EPIMODELSTUDIO_*` environment variables (see `epimodelstudio_api/config.py`).
110
+
111
+
112
+ ## Web app
113
+
114
+ The browser app (React canvas) lives in `web/`; the built copy in `web/dist/` is served by the API server, so Node is only needed to change the app.
115
+
116
+ ```
117
+ pip install -r requirements.txt -r requirements-api.txt
118
+ python -m epimodelstudio_api --port 8000 # then open http://127.0.0.1:8000
119
+ ```
120
+
121
+ Develop the front end: `cd web && npm install && npm run dev` (proxies to the server), tests `npm test`, rebuild `npm run build`.
122
+ Browser end-to-end tests (`tests/test_web_e2e.py`) need Playwright and Chrome (`CHROME_PATH` if not at a standard location) and are skipped otherwise.
123
+ The report's equations are drawn by MathJax from a CDN, so the HTML report needs internet for them; the PDF does not.
124
+
125
+ Run the program from a normal local folder (for example `C:\epimodelstudio`), not from OneDrive, Dropbox or another synced folder: each analysis loads thousands of small files and syncing makes that many times slower.
@@ -0,0 +1,104 @@
1
+ # epimodelstudio (analysis engine)
2
+ Define a compartment model as flows -> get diagram, ODEs, well-posedness, DFE, R0 (next-generation matrix),
3
+ Routh-Hurwitz stability, endemic equilibrium, R0 sensitivity, simulations, and an HTML/Markdown report.
4
+
5
+ pip install -r requirements.txt
6
+ python -m epimodelstudio run my_model.json my_run (see the command line below)
7
+ python -m pytest tests (needs: pip install pytest)
8
+ python -m epimodelstudio reproduce my_run (repeat a run and compare it with its run record)
9
+
10
+ Every run folder also holds `how_to_cite.txt` and `reproducibility_bundle.zip`. Changes by version are in `CHANGELOG.md`.
11
+
12
+ Mark each flow that is a NEW infection with infection=True (that is what lets R0 be derived automatically).
13
+ Status labels in the report: PROVED / CHECKED NUMERICALLY / NOT DECIDED.
14
+ Backward bifurcation (Castillo-Chavez & Song) and LaTeX/PDF export are built. Lyapunov/global-DFE module (T3) and multi-infected models incl. numeric fallbacks (T6) are built. The web interface (canvas, API, advisor, library of templates) is built; see `START_HERE.md`.
15
+
16
+ **Just want to use the tool on your own computer?** See `START_HERE.md` (double-click `start.bat` on Windows, or run `./start.sh`). **Hosting a small pilot?** See `DEPLOY_CLOUD_RUN.md` (a `Dockerfile` is included).
17
+
18
+ ## Windows quick start for the command-line engine (PowerShell or Command Prompt)
19
+ Use a virtual environment inside the project folder so the libraries do not touch your other Python installs.
20
+
21
+ cd path\to\epimodelstudio_tool
22
+ py -3.13 -m venv .venv (any Python 3.11 or newer; run `py -0` to list the ones you have)
23
+ .venv\Scripts\python -m pip install -r requirements.txt
24
+ .venv\Scripts\python -m epimodelstudio templates
25
+ .venv\Scripts\python -m epimodelstudio template seir_demography my_model.json
26
+ .venv\Scripts\python -m epimodelstudio run my_model.json my_run
27
+
28
+ Calling `.venv\Scripts\python` directly means you never need to "activate" the environment (activation can be blocked by PowerShell policy).
29
+ Open `my_run\report.html` in a browser. A PDF is built only if LaTeX is installed (MiKTeX or TeX Live); without it you still get the HTML report and
30
+ the `report.tex` source.
31
+
32
+ Notes
33
+ - On Windows the time-limited symbolic steps start a fresh process each time, which takes a few seconds (importing SymPy and SciPy); runs are slower than on
34
+ Linux or macOS but give the same results. The time limit counts only the work itself, not the start-up.
35
+ - If you call the engine from your own script on Windows, put the calls under `if __name__ == "__main__":` (a Python requirement for programs that start
36
+ child processes).
37
+
38
+ ## Units and durations (model file format 2)
39
+
40
+ A model file may declare what its numbers mean. Files without this (format 1) still load, with a notice.
41
+
42
+ ```json
43
+ "time_unit": "day", // hour | day | week | month | year | unspecified
44
+ "population_unit": "proportion", // people | individuals | animals | proportion | unspecified
45
+ "parameters": {
46
+ "beta": {"value": 0.6, "unit": "1/day", "label": "Transmission rate", "min": 0.3, "max": 0.9, "source": "your reference"},
47
+ "sigma": {"duration": 5, "label": "Latent period"}, // 5 days -> rate 0.2 per day
48
+ "mu": {"duration": 70, "duration_unit": "year"}, // converted to a daily rate
49
+ "gamma": 0.1428 // a bare number is still fine
50
+ },
51
+ "observations": [{"name": "weekly cases", "quantity": "new_infections", "reporting_fraction": 0.3, "time_unit": "week"}]
52
+ ```
53
+
54
+ * The tool converts everything to the model's time unit (1 year = 365.25 days) and checks that every flow has units of "population per time". If every parameter has a unit, a mismatch is an error; if only some do, it is a warning.
55
+ * Bounds, labels, sources and observations are stored and shown but do not change the model hash; units do.
56
+ * `observations` is reserved for later data comparison. It is checked but not used yet.
57
+ * The built-in templates carry units and parameter names but no literature sources.
58
+
59
+ ## Views and the plain-language summary
60
+
61
+ `report.html` opens on an **Overview** with four buttons at the top. The analysis is the same in every view; only what is shown changes.
62
+
63
+ * **Overview** (default): the findings in plain sentences, each with its trust label, a "Read with care" list, the diagram and the outbreak curve.
64
+ * **Epidemiology**: the Overview plus the technical summary table, outcome measures, all figures and the sensitivity results.
65
+ * **Mathematics**: equations, derivations and proofs, verification and reproducibility.
66
+ * **Everything**: all of it (this is also `report.md`).
67
+
68
+ The plain sentences are built from the results, not written by hand. A proved result is stated plainly; a numerically checked one is worded as evidence ("the numbers indicate", "in the simulation"); an undecided one says it could not be decided. If any automatic cross-check fails, a warning comes first. The LaTeX/PDF report carries the same plain panel before its summary table.
69
+
70
+ ## Running the API (for the web app)
71
+
72
+ ```
73
+ pip install -r requirements-api.txt
74
+ python -m epimodelstudio_api --port 8000 # http://127.0.0.1:8000/api/docs lists every endpoint
75
+ ```
76
+
77
+ | Endpoint | What it does |
78
+ |---|---|
79
+ | `GET /api/health` | engine version and number of running analyses |
80
+ | `GET /api/templates`, `GET /api/templates/{name}` | the 12 built-in models; the second returns the model file |
81
+ | `POST /api/models/validate` | checks a model file; returns a summary (parameters with units, warnings) and the normalised file. Nothing is stored |
82
+ | `POST /api/models/diagram` | the compartment diagram as a PNG |
83
+ | `POST /api/analyses` | starts an analysis (202), or returns the finished one for an identical model (200, `cached: true`) |
84
+ | `GET /api/analyses/{id}` | status; when done, `results` (plain-language findings, summary, outcome measures, verification) and the list of files |
85
+ | `GET /api/analyses/{id}/files/{name}` | `report.html` (four views), `report.pdf`, `report.md`, `report.tex`, `latex_bundle.zip`, figures, `model.json`, `run_record.json`, `results.json` |
86
+ | `DELETE /api/analyses/{id}` | cancels a running analysis and deletes the run |
87
+
88
+ Safety: every model is checked before a job exists (safe rate parser, size and complexity limits, request size limit); each analysis runs in its own process with a time limit and is killed with everything it started; report pages are served in a sandbox; text typed by the user is escaped in reports. There are no accounts yet, so run it on your own machine or behind a login. Limits can be changed with `EPIMODELSTUDIO_*` environment variables (see `epimodelstudio_api/config.py`).
89
+
90
+
91
+ ## Web app
92
+
93
+ The browser app (React canvas) lives in `web/`; the built copy in `web/dist/` is served by the API server, so Node is only needed to change the app.
94
+
95
+ ```
96
+ pip install -r requirements.txt -r requirements-api.txt
97
+ python -m epimodelstudio_api --port 8000 # then open http://127.0.0.1:8000
98
+ ```
99
+
100
+ Develop the front end: `cd web && npm install && npm run dev` (proxies to the server), tests `npm test`, rebuild `npm run build`.
101
+ Browser end-to-end tests (`tests/test_web_e2e.py`) need Playwright and Chrome (`CHROME_PATH` if not at a standard location) and are skipped otherwise.
102
+ The report's equations are drawn by MathJax from a CDN, so the HTML report needs internet for them; the PDF does not.
103
+
104
+ Run the program from a normal local folder (for example `C:\epimodelstudio`), not from OneDrive, Dropbox or another synced folder: each analysis loads thousands of small files and syncing makes that many times slower.
@@ -0,0 +1,7 @@
1
+ from .model import Model, Flow
2
+ from .templates import TEMPLATES
3
+ from .report import run, analyse
4
+ from .layout_editor import export_editor, apply_layout
5
+ from .validate import ModelError
6
+ from .repro import save_model, load_model, model_hash
7
+ from .settings import ENGINE_VERSION
@@ -0,0 +1,38 @@
1
+ """Command line: python -m epimodelstudio <command> ...
2
+ templates list the built-in models
3
+ template NAME [file.json] write a built-in model to a model file (default NAME.json)
4
+ run model.json [outdir] analyse a model file and write the report (HTML, LaTeX, PDF, model.json, run_record.json)
5
+ reproduce <run folder> rerun the analysis stored in a run folder and compare it with its run record
6
+ """
7
+ import sys
8
+ from . import TEMPLATES, load_model, save_model, run, ModelError
9
+ from .repro import reproduce
10
+
11
+
12
+ def main(argv):
13
+ for stream in (sys.stdout, sys.stderr): # Windows consoles often default to a legacy code page that cannot print the maths symbols
14
+ if hasattr(stream, "reconfigure"):
15
+ stream.reconfigure(encoding="utf-8", errors="replace")
16
+ if not argv or argv[0] in ("-h", "--help"):
17
+ print(__doc__); return 0
18
+ cmd, args = argv[0], argv[1:]
19
+ try:
20
+ if cmd == "templates":
21
+ print("\n".join(sorted(TEMPLATES))); return 0
22
+ if cmd == "template" and args:
23
+ if args[0] not in TEMPLATES: print(f"unknown template {args[0]!r}; try: python -m epimodelstudio templates"); return 2
24
+ print("wrote", save_model(TEMPLATES[args[0]](), args[1] if len(args) > 1 else args[0] + ".json")); return 0
25
+ if cmd == "run" and args:
26
+ m = load_model(args[0]); out = args[1] if len(args) > 1 else "out"
27
+ r = run(m, out); print(f"report written to {out}/ (PDF {'ok' if r['pdf_ok'] else 'not built'})"); return 0
28
+ if cmd == "reproduce" and args:
29
+ res = reproduce(args[0]); print(res["status"])
30
+ for d in res["differences"]: print(" -", d)
31
+ return 0 if res["status"] == "REPRODUCED" else 1
32
+ except ModelError as e:
33
+ print("Model error:", e); return 2
34
+ print(__doc__); return 2
35
+
36
+
37
+ if __name__ == "__main__":
38
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,214 @@
1
+ """Questionnaire advisor: from a few plain questions to two or three starting models from the library.
2
+
3
+ Library-only by design: it never invents a model. Each library model has a profile (what it assumes); the answers are compared
4
+ with the profiles by a transparent rules table, and every suggestion says what matched and what differs, so the researcher
5
+ knows what to edit. The suggestion is a starting point, never a verdict about the disease.
6
+ """
7
+ from . import evidence as EV
8
+ from . import templates as T
9
+ from . import glossary as G
10
+
11
+ # ---------------------------------------------------------------- questions (id, text, options, glossary terms shown with it)
12
+ QUESTIONS = [
13
+ dict(id="pathway", text="How does the infection mainly spread?", terms=["force_of_infection", "vector_host"],
14
+ options=[("direct", "From person to person (contact, air, droplets)"),
15
+ ("vector", "Through a carrier species such as a mosquito (a vector)"),
16
+ ("environment", "From the environment: water, soil, spores or carcasses"),
17
+ ("both", "Both person to person and through the environment (for example water)")]),
18
+ dict(id="latent", text="Is there a delay between catching the infection and being able to pass it on?", terms=["infected_compartment"],
19
+ options=[("none", "No, or the delay is negligible"),
20
+ ("short", "Yes, one exposed (latent) period"),
21
+ ("staged", "Yes, and the delay is not exponential: it is better described in several stages")]),
22
+ dict(id="immunity", text="What happens after recovery?", terms=["compartment"],
23
+ options=[("lifelong", "Lasting immunity"),
24
+ ("temporary", "Immunity that fades, so people become susceptible again"),
25
+ ("partial", "Partial immunity: reinfection is possible but less likely"),
26
+ ("none", "No immunity: people are susceptible again at once")]),
27
+ dict(id="vaccine", text="Do you need to include vaccination that is imperfect (it does not always protect)?", terms=["compartment"],
28
+ options=[("no", "No"), ("yes", "Yes")]),
29
+ dict(id="population", text="Over what time span do you want to study it?", terms=["open_closed", "demography"],
30
+ options=[("closed", "One outbreak, short enough to ignore births and deaths"),
31
+ ("open", "Long term, so births and deaths matter")]),
32
+ dict(id="features", text="Does your question involve any of these (choose any)?", multi=True, terms=["incidence", "bifurcation"],
33
+ options=[("disease_death", "Deaths caused by the disease"),
34
+ ("saturation", "Transmission that levels off at high infection (crowding, behaviour change)"),
35
+ ("reinfection", "Reinfection of people who already had the disease"),
36
+ ("oscillation", "Repeated waves or cycles (periodic behaviour)"),
37
+ ("backward", "Whether control must push R0 well below 1 (backward bifurcation)"),
38
+ ("quarantine", "Isolation or quarantine of some infected people")]),
39
+ ]
40
+ _Q = {q["id"]: q for q in QUESTIONS}
41
+ _VALUES = {q["id"]: {o[0] for o in q["options"]} for q in QUESTIONS}
42
+
43
+
44
+ def questions():
45
+ """The questionnaire as served to the client (options as objects, glossary ids to show beside each question)."""
46
+ return [dict(id=q["id"], text=q["text"], multi=bool(q.get("multi")), terms=q["terms"],
47
+ options=[dict(value=v, label=l) for v, l in q["options"]]) for q in QUESTIONS]
48
+
49
+
50
+ # ---------------------------------------------------------------- what each library model assumes
51
+ def _p(pathway, latent, immunity, population, vaccine=False, features=(), source=""):
52
+ return dict(pathway=set(pathway), latent=latent, immunity=immunity, population=population, vaccine=vaccine,
53
+ features=set(features), source=source)
54
+
55
+
56
+ _HZS = "Hethcote, Zhien & Shengbing (2002), Math. Biosci. 180:141-160"
57
+ PROFILES = dict(
58
+ sir_closed=_p({"direct"}, "none", "lifelong", "closed", source="Kermack & McKendrick (1927)"),
59
+ sir_demography=_p({"direct"}, "none", "lifelong", "open", source="Hethcote (2000), The mathematics of infectious diseases"),
60
+ seir_demography=_p({"direct"}, "short", "lifelong", "open", source="Hethcote (2000), The mathematics of infectious diseases"),
61
+ erlang_seir=_p({"direct"}, "staged", "lifelong", "open", source="Wearing, Rohani & Keeling (2005), PLoS Med 2:e174"),
62
+ sis_vaccination=_p({"direct"}, "none", "none", "open", vaccine=True, features={"backward"},
63
+ source="Kribs-Zaleta & Velasco-Hernandez (2000); Arino et al. (2004)"),
64
+ tb_feng_exogenous=_p({"direct"}, "staged", "partial", "open", features={"reinfection", "disease_death", "backward"},
65
+ source="Feng, Castillo-Chavez & Capurro, Theor. Popul. Biol. 57 (2000)"),
66
+ tb_reinfection=_p({"direct"}, "staged", "partial", "open", features={"reinfection", "disease_death", "backward"},
67
+ source="Wangari & Stone, PLoS ONE 13(3):e0194256 (2018)"),
68
+ sirs_diff_mortality=_p({"direct"}, "none", "temporary", "open", features={"disease_death"}, source="arXiv:1112.2662"),
69
+ sirs_saturated_incidence=_p({"direct"}, "none", "temporary", "open", features={"saturation", "disease_death"},
70
+ source="Nonlinear Analysis paper, system (1)"),
71
+ sirs_nonlinear_hopf=_p({"direct"}, "none", "temporary", "open", features={"saturation", "oscillation"},
72
+ source="Tang, Huang, Ruan & Zhang, SIAM J. Appl. Math. 69 (2008)"),
73
+ cholera_tien_earn=_p({"direct", "environment"}, "none", "lifelong", "open", source="Tien & Earn (2010), Bull. Math. Biol. 72:1506-1533"),
74
+ cholera_two_pathways=_p({"direct", "environment"}, "none", "lifelong", "open", source="Tien & Earn (2010); van den Driessche (2017)"),
75
+ anthrax=_p({"environment"}, "none", "none", "open", features={"disease_death"}, source="van den Driessche (2017), Sec. 7"),
76
+ ross_macdonald=_p({"vector"}, "none", "none", "open", source="Iiyambo (2017)"),
77
+ malaria_sirs_tilahun=_p({"vector"}, "none", "temporary", "open", features={"disease_death", "backward"},
78
+ source="Tilahun, arXiv:1707.00924"),
79
+ malaria_partial_immunity=_p({"vector"}, "none", "partial", "open", features={"backward"}, source="Partial-immunity malaria model, standard incidence"),
80
+ malaria_partial_immunity_mass_action=_p({"vector"}, "none", "partial", "open", features={"backward"},
81
+ source="Partial-immunity malaria model, mass action"),
82
+ cholera_codeco=_p({"environment"}, "none", "lifelong", "open", source="Codeco (2001), BMC Infect. Dis. 1:1"),
83
+ dengue_esteva_vargas=_p({"vector"}, "none", "lifelong", "open", source="Esteva & Vargas (1998), Math. Biosci. 150:131-151"),
84
+ hiv_anderson=_p({"direct"}, "none", "none", "open", features={"disease_death"},
85
+ source="Anderson, Medley, May & Johnson (1986), IMA J. Math. Appl. Med. Biol. 3:229-263"),
86
+ sepia_gatto=_p({"direct"}, "short", "lifelong", "closed", features={"disease_death", "quarantine"},
87
+ source="Gatto et al. (2020), PNAS 117:10484-10491 (one-community version)"),
88
+ sidarthe=_p({"direct"}, "none", "lifelong", "closed", features={"disease_death"},
89
+ source="Giordano et al. (2020), Nature Medicine 26:855-860"),
90
+ ebola_legrand=_p({"direct"}, "short", "lifelong", "closed", features={"disease_death"},
91
+ source="Legrand, Grais, Boelle, Valleron & Flahault (2007), Epidemiol. Infect. 135:610-621"),
92
+ malaria_chitnis=_p({"vector"}, "short", "temporary", "open", features={"disease_death", "backward"}, source="Chitnis (thesis, 2005)"),
93
+ malaria_chitnis_2006=_p({"vector"}, "short", "temporary", "open", features={"disease_death", "backward"}, source="Chitnis, Cushing & Hyman (2006), SIAM J. Appl. Math. 67:24-45"),
94
+ siqs_mass_action=_p({"direct"}, "none", "none", "open", features={"quarantine"}, source=_HZS),
95
+ siqs_standard=_p({"direct"}, "none", "none", "open", features={"quarantine"}, source=_HZS),
96
+ siqs_adjusted=_p({"direct"}, "none", "none", "open", features={"quarantine"}, source=_HZS),
97
+ siqr_mass_action=_p({"direct"}, "none", "lifelong", "open", features={"quarantine"}, source=_HZS),
98
+ siqr_standard=_p({"direct"}, "none", "lifelong", "open", features={"quarantine"}, source=_HZS),
99
+ siqr_adjusted=_p({"direct"}, "none", "lifelong", "open", features={"quarantine", "oscillation"}, source=_HZS),
100
+ )
101
+
102
+ _PATHWAY_WORDS = {"direct": "person-to-person spread", "vector": "spread through a vector", "environment": "spread through the environment"}
103
+ _ANSWER_PATHWAY = {"direct": {"direct"}, "vector": {"vector"}, "environment": {"environment"}, "both": {"direct", "environment"}}
104
+ _FEATURE_WORDS = {"disease_death": "deaths caused by the disease", "saturation": "transmission that levels off",
105
+ "reinfection": "reinfection", "oscillation": "repeated waves", "backward": "backward bifurcation",
106
+ "quarantine": "isolation or quarantine of infected people"}
107
+ _FEATURE_TERMS = {"saturation": ("incidence",), "oscillation": ("hopf",), "backward": ("backward_bifurcation",)}
108
+ _IMMUNITY_WORDS = {"lifelong": "lasting immunity", "temporary": "immunity that fades", "partial": "partial immunity", "none": "no immunity"}
109
+ _LATENT_WORDS = {"none": "no delay before infectiousness", "short": "one latent period", "staged": "a latent period in several stages"}
110
+
111
+
112
+ def check_answers(answers):
113
+ """Validate the answers (ValueError with a readable message). Returns a clean dict; a missing or 'skip' answer is simply not used."""
114
+ if not isinstance(answers, dict):
115
+ raise ValueError("The answers must be an object of question -> answer.")
116
+ clean = {}
117
+ for k, v in answers.items():
118
+ if k not in _Q:
119
+ raise ValueError(f"Unknown question '{str(k)[:40]}'.")
120
+ if v in (None, "", "skip", []):
121
+ continue
122
+ if _Q[k].get("multi"):
123
+ if not isinstance(v, list) or not all(isinstance(x, str) for x in v) or not set(v) <= _VALUES[k]:
124
+ raise ValueError(f"Question '{k}' needs a list of listed options.")
125
+ clean[k] = sorted(set(v))
126
+ else:
127
+ if not isinstance(v, str) or v not in _VALUES[k]:
128
+ raise ValueError(f"Question '{k}' needs one of its listed options.")
129
+ clean[k] = v
130
+ return clean
131
+
132
+
133
+ def _score(profile, a):
134
+ """Rules table. Returns (points, asked, matched, matches, differences, terms)."""
135
+ pts, asked, matched, matches, diffs, terms = 0, 0, 0, [], [], []
136
+ def hit(points, text, *t):
137
+ nonlocal pts, matched
138
+ pts += points; matched += 1; matches.append(text); terms.extend(t)
139
+ def miss(points, text, *t):
140
+ nonlocal pts
141
+ pts += points; diffs.append(text); terms.extend(t)
142
+
143
+ if "pathway" in a:
144
+ asked += 1
145
+ want, have = _ANSWER_PATHWAY[a["pathway"]], profile["pathway"]
146
+ if want == have:
147
+ hit(4, f"It models {_PATHWAY_WORDS[next(iter(have))] if len(have) == 1 else 'both person-to-person and environmental spread'}, as you described.", "vector_host" if "vector" in have else "force_of_infection")
148
+ elif want & have:
149
+ miss(1, "It also includes a second route of spread that you did not mention; remove it by setting its rate to zero or deleting that flow.", "force_of_infection")
150
+ else:
151
+ miss(-6, f"It models {' and '.join(sorted(_PATHWAY_WORDS[x] for x in have))}, not what you described.", "vector_host")
152
+ if "latent" in a:
153
+ asked += 1
154
+ if a["latent"] == profile["latent"]:
155
+ hit(3, f"It has {_LATENT_WORDS[a['latent']]}, as you described.", "infected_compartment")
156
+ else:
157
+ near = {a["latent"], profile["latent"]} == {"short", "staged"}
158
+ miss(-1 if near else -2, f"It has {_LATENT_WORDS[profile['latent']]}; you described {_LATENT_WORDS[a['latent']]}. You can add or remove exposed compartments on the canvas.", "infected_compartment")
159
+ if "immunity" in a:
160
+ asked += 1
161
+ if a["immunity"] == profile["immunity"]:
162
+ hit(3, f"It assumes {_IMMUNITY_WORDS[a['immunity']]} after recovery, as you described.", "compartment")
163
+ else:
164
+ miss(-2, f"It assumes {_IMMUNITY_WORDS[profile['immunity']]}; you described {_IMMUNITY_WORDS[a['immunity']]}.", "compartment")
165
+ if "vaccine" in a:
166
+ if a["vaccine"] == "yes":
167
+ asked += 1
168
+ if profile["vaccine"]:
169
+ hit(4, "It includes imperfect vaccination.")
170
+ else:
171
+ miss(-1, "It has no vaccination; you would add a vaccinated compartment yourself.")
172
+ elif profile["vaccine"]:
173
+ miss(-2, "It includes vaccination, which you did not ask for; set the vaccination rate to zero to remove its effect.")
174
+ if "population" in a:
175
+ asked += 1
176
+ if a["population"] == profile["population"]:
177
+ hit(2, "It treats births and deaths as you described." if a["population"] == "open" else "It ignores births and deaths, as you described.", "open_closed")
178
+ else:
179
+ miss(-2, "It includes births and deaths; you wanted a single outbreak." if a["population"] == "closed" else "It ignores births and deaths; you wanted a long-term view.", "demography")
180
+ for f in a.get("features", []):
181
+ asked += 1
182
+ if f in profile["features"]:
183
+ hit(2, f"It includes {_FEATURE_WORDS[f]}, which your question involves.", *_FEATURE_TERMS.get(f, ()))
184
+ else:
185
+ miss(-1, f"It does not include {_FEATURE_WORDS[f]}.")
186
+ if "quarantine" in profile["features"] and "quarantine" not in a.get("features", []):
187
+ miss(-1, "It includes quarantine of infected people, which you did not ask for; set the quarantine rate delta to zero to remove its effect.")
188
+ seen, uniq = set(), []
189
+ for t in terms:
190
+ if t not in seen and t in G.BY_ID:
191
+ seen.add(t); uniq.append(t)
192
+ return pts, asked, matched, matches, diffs, uniq
193
+
194
+
195
+ def recommend(answers, limit=3):
196
+ """Rank the library models for the answers. Returns dict(asked, suggestions=[...], note)."""
197
+ a = check_answers(answers)
198
+ out = []
199
+ for name, prof in PROFILES.items():
200
+ pts, asked, matched, matches, diffs, terms = _score(prof, a)
201
+ if asked and pts > 0:
202
+ m = T.TEMPLATES[name]()
203
+ out.append(dict(name=name, title=m.name, compartments=list(m.compartments), points=pts, asked=asked, matched=matched,
204
+ matches=matches, differences=diffs, terms=terms, source=prof["source"],
205
+ evidence=EV.record(name)))
206
+ out.sort(key=lambda r: (-r["points"], r["evidence"]["evidence"] == "thesis", len(r["compartments"]), r["name"])) # on equal scores a thesis version ranks after the journal paper
207
+ from . import categories as C
208
+ for r in out:
209
+ r["category_title"] = C.info(r["name"])["category_title"]
210
+ del r["points"] # the ranking is the output; the raw score is not meaningful to a researcher
211
+ note = ("Answer at least one question to see suggestions." if not a else
212
+ "No library model fits these answers. Start from the simplest SIR template and edit it on the canvas." if not out else
213
+ "These are starting points from the library, not a judgement about your disease. Check every assumption against your own knowledge and sources.")
214
+ return dict(asked=len(a), suggestions=out[:limit], note=note)