pax_global_header00006660000000000000000000000064140234234340014511gustar00rootroot0000000000000052 comment=bd6930bc6b56cad88731a422b9e5bd34bcf24b85 epimodels-0.3.20/000077500000000000000000000000001402342343400135545ustar00rootroot00000000000000epimodels-0.3.20/.coveragerc000066400000000000000000000011201402342343400156670ustar00rootroot00000000000000# .coveragerc to control coverage.py [run] branch = True source = epimodels # omit = bad_file.py [paths] source = src/ */site-packages/ [report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about missing debug-only code: def __repr__ if self\.debug # Don't complain if tests don't hit defensive assertion code: raise AssertionError raise NotImplementedError # Don't complain if non-runnable code isn't run: if 0: if __name__ == .__main__.: epimodels-0.3.20/.github/000077500000000000000000000000001402342343400151145ustar00rootroot00000000000000epimodels-0.3.20/.github/workflows/000077500000000000000000000000001402342343400171515ustar00rootroot00000000000000epimodels-0.3.20/.github/workflows/python-package.yml000066400000000000000000000023671402342343400226160ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python package on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.6, 3.7, 3.8] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pytest if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Test with pytest run: | pytest epimodels-0.3.20/.gitignore000066400000000000000000000010171402342343400155430ustar00rootroot00000000000000# Temporary and binary files *~ *.py[cod] *.so *.cfg !.isort.cfg !setup.cfg *.orig *.log *.pot __pycache__/* .cache/* .*.swp */.ipynb_checkpoints/* # Project files .ropeproject .project .pydevproject .settings .idea tags # Package files *.egg *.eggs/ .installed.cfg *.egg-info # Unittest and coverage htmlcov/* .coverage .tox junit.xml coverage.xml .pytest_cache/ # Build and docs folder/files build/* dist/* sdist/* docs/api/* docs/_rst/* docs/_build/* cover/* MANIFEST # Per-project virtualenvs .venv*/ # pycharm .idea epimodels-0.3.20/AUTHORS.rst000066400000000000000000000001261402342343400154320ustar00rootroot00000000000000============ Contributors ============ * Flávio Codeço Coelho epimodels-0.3.20/CHANGELOG.rst000066400000000000000000000002001402342343400155650ustar00rootroot00000000000000========= Changelog ========= Version 0.1 =========== - Feature A added - FIX: nasty bug #1729 fixed - add your changes here! epimodels-0.3.20/LICENSE.txt000066400000000000000000000021011402342343400153710ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2018 Flávio Codeço Coelho Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. epimodels-0.3.20/README.md000066400000000000000000000006241402342343400150350ustar00rootroot00000000000000 # Epimodels This library a simple interface to simulate mathematical epidemic models. ## Getting started Simple SIR simulation ```python from epimodels.continuous.models import SIR model = SIR() model([1000, 1, 0], [0, 50], 1001, {'beta': 2, 'gamma': .1}) model.plot_traces() ``` ### Related libraries For stochastic epidemic models check [this](https://github.com/fccoelho/EpiStochModels).epimodels-0.3.20/README.rst000066400000000000000000000004321402342343400152420ustar00rootroot00000000000000========= epimodels ========= Add a short description here! Description =========== A longer description of your project goes here... Note ==== This project has been set up using PyScaffold 3.2.3. For details and usage information on PyScaffold see https://pyscaffold.org/. epimodels-0.3.20/condarecipe/000077500000000000000000000000001402342343400160305ustar00rootroot00000000000000epimodels-0.3.20/condarecipe/epimodels/000077500000000000000000000000001402342343400200115ustar00rootroot00000000000000epimodels-0.3.20/condarecipe/epimodels/meta.yaml000066400000000000000000000013011402342343400216160ustar00rootroot00000000000000{% set name = "epimodels" %} {% set version = "0.3.19" %} package: name: "{{ name|lower }}" version: "{{ version }}" source: url: "https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz" sha256: 8dec0de96e6ec506e3c61b7af6d687791c6db0eb5f74a90538f2844505db60e8 build: number: 0 script: "{{ PYTHON }} -m pip install . -vv" requirements: host: - pip - python run: - python about: home: The package home page license: mit license_family: MIT license_file: summary: "Library of mathematical epidemic models for use in simulation studies and inference" doc_url: dev_url: extra: recipe-maintainers: - your-github-id-here epimodels-0.3.20/docs/000077500000000000000000000000001402342343400145045ustar00rootroot00000000000000epimodels-0.3.20/docs/Makefile000066400000000000000000000022011402342343400161370ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = . BUILDDIR = _build AUTODOCDIR = api # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $?), 1) $(error "The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/") endif .PHONY: help clean Makefile # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) clean: rm -rf $(BUILDDIR)/* $(AUTODOCDIR) # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) epimodels-0.3.20/docs/_static/000077500000000000000000000000001402342343400161325ustar00rootroot00000000000000epimodels-0.3.20/docs/_static/.gitignore000066400000000000000000000000221402342343400201140ustar00rootroot00000000000000# Empty directory epimodels-0.3.20/docs/_static/cSIR.png000066400000000000000000000045531402342343400174470ustar00rootroot00000000000000‰PNG  IHDR€à5ÑÜäsBIT|dˆ pHYsaa¨?§i8tEXtSoftwarematplotlib version3.1.1, http://matplotlib.org/fÉIDATxœíÖ1 À0À¿çáŽ& zvÏÌ,2ÎïÞ2€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb.&y¼§§²bIEND®B`‚epimodels-0.3.20/docs/_static/dSIR.png000066400000000000000000000045531402342343400174500ustar00rootroot00000000000000‰PNG  IHDR€à5ÑÜäsBIT|dˆ pHYsaa¨?§i8tEXtSoftwarematplotlib version3.1.1, http://matplotlib.org/fÉIDATxœíÖ1 À0À¿çáŽ& zvÏÌ,2ÎïÞ2€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb @Œˆ1€1 ÆÄ@€cb.&y¼§§²bIEND®B`‚epimodels-0.3.20/docs/authors.rst000066400000000000000000000000511402342343400167170ustar00rootroot00000000000000.. _authors: .. include:: ../AUTHORS.rst epimodels-0.3.20/docs/changelog.rst000066400000000000000000000000531402342343400171630ustar00rootroot00000000000000.. _changes: .. include:: ../CHANGELOG.rst epimodels-0.3.20/docs/conf.py000066400000000000000000000224341402342343400160100ustar00rootroot00000000000000# This file is execfile()d with the current directory set to its containing dir. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import inspect import shutil # -- Path setup -------------------------------------------------------------- __location__ = os.path.join( os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())) ) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.join(__location__, "../src")) # -- Run sphinx-apidoc ------------------------------------------------------- # This hack is necessary since RTD does not issue `sphinx-apidoc` before running # `sphinx-build -b html . _build/html`. See Issue: # https://github.com/rtfd/readthedocs.org/issues/1139 # DON'T FORGET: Check the box "Install your project inside a virtualenv using # setup.py install" in the RTD Advanced Settings. # Additionally it helps us to avoid running apidoc manually try: # for Sphinx >= 1.7 from sphinx.ext import apidoc except ImportError: from sphinx import apidoc output_dir = os.path.join(__location__, "api") module_dir = os.path.join(__location__, "../src/epimodels") try: shutil.rmtree(output_dir) except FileNotFoundError: pass try: import sphinx cmd_line_template = ( "sphinx-apidoc --implicit-namespaces -f -o {outputdir} {moduledir}" ) cmd_line = cmd_line_template.format(outputdir=output_dir, moduledir=module_dir) args = cmd_line.split(" ") if tuple(sphinx.__version__.split(".")) >= ("1", "7"): # This is a rudimentary parse_version to avoid external dependencies args = args[1:] apidoc.main(args) except Exception as e: print("Running `sphinx-apidoc` failed!\n{}".format(e)) # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.autosummary", "sphinx.ext.viewcode", "sphinx.ext.coverage", "sphinx.ext.doctest", "sphinx.ext.ifconfig", "sphinx.ext.mathjax", "sphinx.ext.napoleon", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "epimodels" copyright = "2021, Flávio Codeço Coelho" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "" # Is set by calling `setup.py docs` # The full version, including alpha/beta/rc tags. release = "" # Is set by calling `setup.py docs` # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".venv"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { "sidebar_width": "300px", "page_width": "1200px" } # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". try: from epimodels import __version__ as version except ImportError: pass else: release = version # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = "" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "epimodels-doc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ("letterpaper" or "a4paper"). # "papersize": "letterpaper", # The font size ("10pt", "11pt" or "12pt"). # "pointsize": "10pt", # Additional stuff for the LaTeX preamble. # "preamble": "", } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "user_guide.tex", "epimodels Documentation", "Flávio Codeço Coelho", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = "" # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- External mapping -------------------------------------------------------- python_version = ".".join(map(str, sys.version_info[0:2])) intersphinx_mapping = { "sphinx": ("http://www.sphinx-doc.org/en/stable", None), "python": ("https://docs.python.org/" + python_version, None), "matplotlib": ("https://matplotlib.org", None), "numpy": ("https://docs.scipy.org/doc/numpy", None), "sklearn": ("https://scikit-learn.org/stable", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable", None), "scipy": ("https://docs.scipy.org/doc/scipy/reference", None), "pyscaffold": ("https://pyscaffold.org/en/stable", None), } epimodels-0.3.20/docs/geting_started.rst000066400000000000000000000014701402342343400202430ustar00rootroot00000000000000Getting Started =============== Epimodels offers a variety of deterministic models pre-implemented for Infectious disease modeling. These models are split into `discrete` (based of difference equations) and `continuous` (based on Ordinary differential equations). The APIs exposed for both families of models is identical to facilitate use. Continuous models ----------------- .. code-block:: python import epimodels.continuous.models as CM model = CM.SIR() model([1000, 1, 0], [0, 50], 1001, {'beta': 2, 'gamma': .1}) model.plot_traces() .. image:: _static/cSIR.png Discrete models --------------- .. code-block:: python import epimodels.discrete.models as DM model = DM.SIR() model(([1000, 1, 0], [0,50], 1001, {'beta': 2, 'gamma': 1})) model.plot_traces() .. image:: _static/dSIR.png epimodels-0.3.20/docs/index.rst000066400000000000000000000031751402342343400163530ustar00rootroot00000000000000========= Epimodels ========= **Epimodels** is a library of mathematical models for epidemiology, to be used for simulations. It contains both Deterministic and Stochastic models in continuous and discrete time. Some Stochastic models are also discrete in the state variables (birth and death processes). .. note:: This library is under development. Contributions are welcome. Contents ======== .. toctree:: :maxdepth: 2 Getting Started License Authors Changelog Module Reference Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _toctree: http://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html .. _reStructuredText: http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html .. _references: http://www.sphinx-doc.org/en/stable/markup/inline.html .. _Python domain syntax: http://sphinx-doc.org/domains.html#the-python-domain .. _Sphinx: http://www.sphinx-doc.org/ .. _Python: http://docs.python.org/ .. _Numpy: http://docs.scipy.org/doc/numpy .. _SciPy: http://docs.scipy.org/doc/scipy/reference/ .. _matplotlib: https://matplotlib.org/contents.html# .. _Pandas: http://pandas.pydata.org/pandas-docs/stable .. _Scikit-Learn: http://scikit-learn.org/stable .. _autodoc: http://www.sphinx-doc.org/en/stable/ext/autodoc.html .. _Google style: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings .. _NumPy style: https://numpydoc.readthedocs.io/en/latest/format.html .. _classical style: http://www.sphinx-doc.org/en/stable/domains.html#info-field-lists epimodels-0.3.20/docs/license.rst000066400000000000000000000001031402342343400166520ustar00rootroot00000000000000.. _license: ======= License ======= .. include:: ../LICENSE.txt epimodels-0.3.20/requirements.txt000066400000000000000000000004331402342343400170400ustar00rootroot00000000000000# Add your pinned requirements so that they can be easily installed with: # pip install -r requirements.txt # Remember to also add them in setup.cfg but unpinned. # Example: # numpy==1.13.3 # scipy==1.0 cython numpy scipy sympy pytest pytest-cov matplotlib mypy sphinx pyitlib numba epimodels-0.3.20/setup.cfg000066400000000000000000000060251402342343400154000ustar00rootroot00000000000000# This file is used to configure your project. # Read more about the various options under: # http://setuptools.readthedocs.io/en/latest/setuptools.html#configuring-setup-using-setup-cfg-files [metadata] name = epimodels description = Library of mathematical epidemic models for use in simulation studies and inference author = Flávio Codeço Coelho author-email = fccoelho@gmail.com license = mit url = https://github.com/fccoelho/epimodels long-description = file: README.md # Change if running only on Windows, Mac or Linux (comma-separated) platforms = any # Add here all kinds of additional classifiers as defined under # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers = Development Status :: 4 - Beta Programming Language :: Python [options] zip_safe = False packages = find_namespace: include_package_data = True package_dir = =src # DON'T CHANGE THE FOLLOWING LINE! IT WILL BE UPDATED BY PYSCAFFOLD! # Add here dependencies of your project (semicolon/line-separated), e.g. install_requires = importlib-metadata; python_version<"3.8" numpy scipy cython # The usage of test_requires is discouraged, see `Dependency Management` docs # tests_require = pytest; pytest-cov # Require a specific Python version, e.g. Python 2.7 or >= 3.4 python_requires = >= 3.6 [options.packages.find] where = src exclude = tests [options.extras_require] # Add here additional requirements for extra features, to install with: # `pip install epimodels[PDF]` like: # PDF = ReportLab; RXP # Add here test requirements (semicolon/line-separated) testing = pytest pytest-cov [options.entry_points] # Add here console scripts like: # console_scripts = # script_name = epimodels.module:function # For example: # console_scripts = # fibonacci = epimodels.skeleton:run # And any other entry points, for example: # pyscaffold.cli = # awesome = pyscaffoldext.awesome.extension:AwesomeExtension [test] # py.test options when running `python setup.py test` # addopts = --verbose extras = True [tool:pytest] # Options for py.test: # Specify command line options as you would do when invoking py.test directly. # e.g. --cov-report html (or xml) for html/xml output or --junitxml junit.xml # in order to write a coverage file that can be read by Jenkins. #addopts = # --cov epimodels --cov-report term-missing # --verbose norecursedirs = dist build .tox testpaths = tests [aliases] release = sdist bdist_wheel upload [bdist_wheel] # Use this option if your package is pure-python universal = 1 [build_sphinx] source_dir = docs build_dir = docs/_build [devpi:upload] # Options for the devpi: PyPI server and packaging tool # VCS export must be deactivated since we are using setuptools-scm no-vcs = 1 formats = sdist bdist_wheel [flake8] # Some sane defaults for the code style checker flake8 exclude = .tox build dist .eggs docs/conf.py [pyscaffold] # PyScaffold's parameters when the project was created. # This will be used when updating. Do not change! version = 4.0 package = epimodels epimodels-0.3.20/setup.py000066400000000000000000000013001402342343400152600ustar00rootroot00000000000000""" Setup file for epimodels. Use setup.cfg to configure your project. This file was generated with PyScaffold 4.0. PyScaffold helps you to put up the scaffold of your new Python project. Learn more under: https://pyscaffold.org/ """ from setuptools import setup if __name__ == "__main__": try: setup(use_scm_version={"version_scheme": "no-guess-dev"}) except: # noqa print( "\n\nAn error occurred while building the project, " "please ensure you have the most updated version of setuptools, " "setuptools_scm and wheel with:\n" " pip install -U setuptools setuptools_scm wheel\n\n" ) raise epimodels-0.3.20/src/000077500000000000000000000000001402342343400143435ustar00rootroot00000000000000epimodels-0.3.20/src/epimodels/000077500000000000000000000000001402342343400163245ustar00rootroot00000000000000epimodels-0.3.20/src/epimodels/__init__.py000066400000000000000000000023571402342343400204440ustar00rootroot00000000000000import sys if sys.version_info[:2] >= (3, 8): # TODO: Import directly (no need for conditional) when `python_requires = >= 3.8` from importlib.metadata import PackageNotFoundError, version # pragma: no cover else: from importlib_metadata import PackageNotFoundError, version # pragma: no cover try: # Change here if project is renamed and does not equal the package name dist_name = __name__ __version__ = version(dist_name) except PackageNotFoundError: # pragma: no cover __version__ = "unknown" finally: del version, PackageNotFoundError from matplotlib import pyplot as P class BaseModel: """ Base class for all models both discrete and continuous """ def __init__(self): self.name = None self.model_type = None self.state_variables = {} self.parameters = {} self.traces = {} def plot_traces(self, vars: list=[]): """ Plots the simulations :param vars: variables to plot """ for series, data in self.traces.items(): if series in self.state_variables: P.plot(self.traces['time'], data, label=series) P.legend(loc=0) P.grid() P.title("{} model".format(self.model_type))epimodels-0.3.20/src/epimodels/continuous/000077500000000000000000000000001402342343400205325ustar00rootroot00000000000000epimodels-0.3.20/src/epimodels/continuous/__init__.py000066400000000000000000000001031402342343400226350ustar00rootroot00000000000000u""" Created on 29/10/18 by fccoelho license: GPL V3 or Later """ epimodels-0.3.20/src/epimodels/continuous/models.py000066400000000000000000000140751402342343400223760ustar00rootroot00000000000000u""" Created on 09/11/18 by fccoelho license: GPL V3 or Later """ import numpy as np from scipy.integrate import solve_ivp from epimodels import BaseModel import logging from collections import OrderedDict from functools import lru_cache import numba logging.basicConfig(filename='epimodels.log', filemode='w', level=logging.DEBUG) class ContinuousModel(BaseModel): """ Exposes a library of continuous time population models """ def __init__(self) -> None: """ Base class for Continuous models :param parallel: Boolean for parallel execution :param model_type: string identifying the model type """ super().__init__() # try: # assert model_type in model_types # self.model_type = model_type # except AssertionError: # logging.Error('Invalid model type: {}'.format(model_type)) def __call__(self, inits: list, trange: list, totpop: float, params: dict, method: str = 'RK45', **kwargs): self.method = method self.kwargs = kwargs sol = self.run(inits, trange, totpop, params, **kwargs) res = {v: sol.y[s, :] for v, s in zip(self.state_variables.keys(), range(sol.y.shape[0]))} res['time'] = sol.t self.traces.update(res) def _model(self, t: float, y: list, params: list): raise NotImplementedError @property def dimension(self) -> int: return len(self.state_variables) def run(self, inits, trange, totpop, params, **kwargs): # model = model_types[self.model_type]['function'] params['N'] = totpop sol = solve_ivp(lambda t, y: self._model(t, y, params), trange, inits, self.method, **kwargs) return sol class SIR(ContinuousModel): def __init__(self): super().__init__() self.state_variables = OrderedDict({'S': 'Susceptible', 'I': 'Infectious', 'R': 'Removed'}) self.parameters = OrderedDict({'beta': r'$\beta$', 'gamma': r'$\gamma$'}) self.model_type = 'SIR' @numba.jit def _model(self, t: float, y: list, params: dict) -> list: """ SIR Model. :param t: time step :param y: state of the model at time t :param params: parameter dictionary :return: """ S, I, R = y beta, gamma, N = params['beta'], params['gamma'], params['N'] return [ -beta * S * I / N, beta * S * I / N - gamma * I, gamma * I ] class SIS(ContinuousModel): def __init__(self): super().__init__() self.state_variables = OrderedDict({'S': 'Susceptible', 'I': 'Infectious'}) self.parameters = {'beta': r'\beta', 'gamma': r'\gamma'} self.model_type = 'SIS' # @lru_cache(1000) @numba.jit def _model(self, t: float, y: list, params: dict) -> list: """ SIS Model. :param t: :param y: :param params: :return: """ S, I = y beta, gamma, N = params['beta'], params['gamma'], params['N'] return [ -beta * S * I / N + gamma * I, beta * S * I / N - gamma * I, ] class SIRS(ContinuousModel): def __init__(self): super().__init__() self.state_variables = OrderedDict({'S': 'Susceptible', 'I': 'Infectious', 'R': 'Removed'}) self.parameters = OrderedDict({'beta': r'$\beta$', 'gamma': r'$\gamma$', 'xi': r'$\xi$'}) self.model_type = 'SIRS' @numba.jit def _model(self, t: float, y: list, params: dict) -> list: """ SIR Model. :param t: :param y: :param params: :return: """ S, I, R = y beta, gamma, xi, N = params['beta'], params['gamma'], params['xi'], params['N'] return [ -beta * S * I / N + xi * R, beta * S * I / N - gamma * I, gamma * I - xi * R ] class SEIR(ContinuousModel): def __init__(self): super().__init__() self.state_variables = OrderedDict({'S': 'Susceptible', 'E': 'Exposed', 'I': 'Infectious', 'R': 'Removed'}) self.parameters = OrderedDict({'beta': r'$\beta$', 'gamma': r'$\gamma$', 'epsilon': r'$\epsilon$'}) self.model_type = 'SEIR' @numba.jit def _model(self, t: float, y: list, params: dict) -> list: S, E, I, R = y beta, gamma, epsilon, N = params['beta'], params['gamma'], params['epsilon'], params['N'] return [ -beta * S * I / N, beta * S * I / N - epsilon * E, epsilon * E - gamma * I, gamma * I ] class SEQIAHR(ContinuousModel): def __init__(self): super().__init__() self.state_variables = OrderedDict( {'S': 'Susceptible', 'E': 'Exposed', 'I': 'Infectious', 'A': 'Asymptomatic', 'H': 'Hospitalized', 'R': 'Removed', 'C': 'Cumulative hospitalizations', 'D': 'Cumulative deaths'}) self.parameters = OrderedDict({'chi': r'$\chi$', 'phi': r'$\phi$', 'beta': r'$\beta$', 'rho': r'$\rho$', 'delta': r'$\delta$', 'gamma': r'$\gamma$', 'alpha': r'$\alpha$', 'mu': r'$\mu$', 'p': '$p$', 'q': '$q$', 'r': '$r$' }) self.model_type = 'SEQIAHR' @numba.jit def _model(self, t: float, y: list, params: dict) -> list: S, E, I, A, H, R, C, D = y chi, phi, beta, rho, delta, gamma, alpha, mu, p, q, r, N = params.values() lamb = beta * (I + A) # Turns on Quarantine on day q and off on day q+r chi *= ((1 + np.tanh(t - q)) / 2) * ((1 - np.tanh(t - (q + r))) / 2) return [ -lamb * ((1 - chi) * S), # dS/dt lamb * ((1 - chi) * S) - alpha * E, # dE/dt (1 - p) * alpha * E - delta * I - phi * I, # dI/dt p * alpha * E - gamma * A, phi * I - (rho + mu) * H, # dH/dt delta * I + rho * H + gamma * A, # dR/dt phi * I, # (1-p)*alpha*E+ p*alpha*E # Hospit. acumuladas mu * H # Morte acumuladas ] epimodels-0.3.20/src/epimodels/discrete/000077500000000000000000000000001402342343400201265ustar00rootroot00000000000000epimodels-0.3.20/src/epimodels/discrete/__init__.py000066400000000000000000000001031402342343400222310ustar00rootroot00000000000000u""" Created on 29/10/18 by fccoelho license: GPL V3 or Later """ epimodels-0.3.20/src/epimodels/discrete/models.py000066400000000000000000000561311402342343400217710ustar00rootroot00000000000000""" Library of discrete time Epidemic models copyright 2012 Flávio Codeco Coelho License: GPL-v3 """ __author__ = 'fccoelho' import numpy as np # from scipy.stats.distributions import poisson, nbinom # from numpy import inf, nan, nan_to_num # import sys # import logging from collections import OrderedDict # import cython from typing import Dict, List, Iterable, Any # import numba # from numba.experimental import jitclass from epimodels import BaseModel model_types = { 'SIR': {'variables': {'R': 'Removed', 'I': 'Infectious', 'S': 'Susceptible'}, 'parameters': {'beta': r'\beta', 'gamma': r'\gamma'} }, 'SIS': {'variables': {'I': 'Infectious', "S": 'Susceptible'}, 'parameters': {'beta': r'\beta', 'gamma': r'\gamma'} }, 'SEIS': {'variables': {'I': 'Infectious', "S": 'Susceptible', 'E': 'Exposed'}, 'parameters': {'b': 'b', 'beta': r'\beta', 'e': 'e', 'r': 'r'} }, 'SEIR': {'variables': {'I': 'Infectious', "S": 'Susceptible', 'E': 'Exposed', 'R': 'Removed'}, 'parameters': {'b': 'b', 'beta': r'\beta', 'e': 'e', 'r': 'r', 'alpha': r'\alpha'} }, 'SIpRpS': ['Exposed', 'Infectious', 'Susceptible'], 'SEIpRpS': ['Exposed', 'Infectious', 'Susceptible'], 'SEIpR': ['Exposed', 'Infectious', 'Susceptible'], 'SIpR': ['Exposed', 'Infectious', 'Susceptible'], 'SIRS': ['Exposed', 'Infectious', 'Susceptible'], 'Custom': ['Exposed', 'Infectious', 'Susceptible'], 'Influenza': {'variables': {'S1': 'Susc_age1', 'E1': 'Incub_age1', 'Is1': 'Subc_age1', 'Ic1': 'Sympt_age1', 'Ig1': 'Comp_age1', 'S2': 'Susc_age2', 'E2': 'Incub_age2', 'Is2': 'Subc_age2', 'Ic2': 'Sympt_age2', 'Ig2': 'Comp_age2', 'S3': 'Susc_age3', 'E3': 'Incub_age3', 'Is3': 'Subc_age3', 'Ic3': 'Sympt_age3', 'Ig3': 'Comp_age3', 'S4': 'Susc_age4', 'E4': 'Incub_age4', 'Is4': 'Subc_age4', 'Ic4': 'Sympt_age4', 'Ig4': 'Comp_age4'}, 'parameters': { 'beta': r'\beta', 'r': 'r', 'e': 'e', 'c': 'c', 'g': 'g', 'd': 'd', 'pc1': r'pc_1', 'pc2': r'pc_2', 'pc3': r'pc_3', 'pc4': r'pc_4', 'pp1': r'pp_1', 'pp2': r'pp_2', 'pp3': r'pp_3', 'pp4': r'pp_4', 'b': 'b' } }, 'SEQIAHR': { 'variables': {'S': 'Susceptible', 'E': 'Exposed', 'I': 'Infectious', 'A': 'Asymptomatic', 'H': 'Hospitalized', 'R': 'Removed', 'C': 'Cumulative hospitalizations', 'D': 'Cumulative deaths'}, 'parameters': {'chi': r'$\chi', 'phi': r'$\phi$', 'beta': r'$\beta$', 'rho': r'$\rho$', 'delta': r'$\delta$', 'alpha': r'$\alpha$', 'mu': r'$\mu$', 'p': '$p$', 'q': '$q$', 'r': '$r$' } } } class DiscreteModel(BaseModel): """ Exposes a library of discrete time population models """ def __init__(self): """ Difference equation based model (discrete time) """ super().__init__() def run(self, *args): raise NotImplementedError def __call__(self, *args, **kwargs): res = self.run(*args) self.traces.update(res) # return res class Influenza(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'Influenza' self.state_variables = {'S1': 'Susc_age1', 'E1': 'Incub_age1', 'Is1': 'Subc_age1', 'Ic1': 'Sympt_age1', 'Ig1': 'Comp_age1', 'S2': 'Susc_age2', 'E2': 'Incub_age2', 'Is2': 'Subc_age2', 'Ic2': 'Sympt_age2', 'Ig2': 'Comp_age2', 'S3': 'Susc_age3', 'E3': 'Incub_age3', 'Is3': 'Subc_age3', 'Ic3': 'Sympt_age3', 'Ig3': 'Comp_age3', 'S4': 'Susc_age4', 'E4': 'Incub_age4', 'Is4': 'Subc_age4', 'Ic4': 'Sympt_age4', 'Ig4': 'Comp_age4'} self.parameters = { 'beta': r'\beta', 'r': 'r', 'e': 'e', 'c': 'c', 'g': 'g', 'd': 'd', 'pc1': r'pc_1', 'pc2': r'pc_2', 'pc3': r'pc_3', 'pc4': r'pc_4', 'pp1': r'pp_1', 'pp2': r'pp_2', 'pp3': r'pp_3', 'pp4': r'pp_4', 'b': 'b' } self.run = self.model def model(self, inits: list, trange: list, totpop: int, params: dict) -> dict: """ Flu model with classes S,E,I subclinical, I mild, I medium, I serious, deaths """ S1 = np.zeros(trange[1] - trange[0]) E1 = np.zeros(trange[1] - trange[0]) Is1 = np.zeros(trange[1] - trange[0]) Ic1 = np.zeros(trange[1] - trange[0]) Ig1 = np.zeros(trange[1] - trange[0]) S2 = np.zeros(trange[1] - trange[0]) E2 = np.zeros(trange[1] - trange[0]) Is2 = np.zeros(trange[1] - trange[0]) Ic2 = np.zeros(trange[1] - trange[0]) Ig2 = np.zeros(trange[1] - trange[0]) S3 = np.zeros(trange[1] - trange[0]) E3 = np.zeros(trange[1] - trange[0]) Is3 = np.zeros(trange[1] - trange[0]) Ic3 = np.zeros(trange[1] - trange[0]) Ig3 = np.zeros(trange[1] - trange[0]) S4 = np.zeros(trange[1] - trange[0]) E4 = np.zeros(trange[1] - trange[0]) Is4 = np.zeros(trange[1] - trange[0]) Ic4 = np.zeros(trange[1] - trange[0]) Ig4 = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S1[0], E1[0], Is1[0], Ic1[0], Ig1[0], S2[0], E2[0], Is2[0], Ic2[0], Ig2[0], S3[0], E3[0], Is3[0], Ic3[0], Ig3[ 0], S4[0], E4[0], Is4[0], Ic4[0], Ig4[0] = inits N = totpop # for k, v in params.items(): # exec ('%s = %s' % (k, v)) beta = params['beta'] # Transmission r = params['r'] # recovery rate e = params['e'] # incubation rate c = params['c'] # g = params['g'] # d = params['d'] pc1 = params['pc1'] pc2 = params['pc2'] pc3 = params['pc3'] pc4 = params['pc4'] pp1 = params['pp1'] pp2 = params['pp2'] pp3 = params['pp3'] pp4 = params['pp4'] b = params['b'] # birth rate for i in tspan[:-1]: # Vacination event # if 'vaccineNow' in params: # TODO: add to params when creating model # vaccineNow = params['vaccineNow'] # vaccov = params['vaccov'] # S1 -= vaccov * S1 # S2 -= vaccov * S2 # S3 -= vaccov * S3 # S4 -= vaccov * S4 # New cases by age class # beta=eval(values[2]) Infectantes = Ig1[i] + Ig2[i] + Ig3[i] + Ig4[i] + Ic1[i] + Ic2[i] + Ic3[i] + Ic4[i] + 0.5 * ( Is1[i] + Is2[i] + Is3[i] + Is4[i]) L1pos = float(beta) * S1[i] * Infectantes / N L2pos = float(beta) * S2[i] * Infectantes / N L3pos = float(beta) * S3[i] * Infectantes / N L4pos = float(beta) * S4[i] * Infectantes / N ###################### Lpos = L1pos + L2pos + L3pos + L4pos # Model # 0-2 years old E1[i + 1] = L1pos + (1 - e) * E1[i] Is1[i + 1] = (1 - (pc1 * c + (1 - pc1) * r)) * Is1[i] + e * E1[i] Ic1[i + 1] = (1 - (pp1 * g + (1 - pp1) * r)) * Ic1[i] + pc1 * c * Is1[i] Ig1[i + 1] = (1 - d) * Ig1[i] + pp1 * g * Ic1[i] S1[i + 1] = b + S1[i] - L1pos # 3-14 years old E2[i + 1] = L2pos + (1 - e) * E2[i] Is2[i + 1] = (1 - (pc2 * c + (1 - pc2) * r)) * Is2[i] + e * E2[i] Ic2[i + 1] = (1 - (pp2 * g + (1 - pp2) * r)) * Ic2[i] + pc2 * c * Is2[i] Ig2[i + 1] = (1 - d) * Ig2[i] + pp2 * g * Ic2[i] S2[i + 1] = b + S2[i] - L2pos # 15-59 years old E3[i + 1] = L3pos + (1 - e) * E3[i] Is3[i + 1] = (1 - (pc3 * c + (1 - pc3) * r)) * Is3[i] + e * E3[i] Ic3[i + 1] = (1 - (pp3 * g + (1 - pp3) * r)) * Ic3[i] + pc3 * c * Is3[i] Ig3[i + 1] = (1 - d) * Ig3[i] + pp3 * g * Ic3[i] S3[i + 1] = b + S3[i] - L3pos # >60 years old E4[i + 1] = L4pos + (1 - e) * E4[i] Is4[i + 1] = (1 - (pc4 * c + (1 - pc4) * r)) * Is4[i] + e * E4[i] Ic4[i + 1] = (1 - (pp4 * g + (1 - pp4) * r)) * Ic4[i] + pc4 * c * Is4[i] Ig4[i + 1] = (1 - d) * Ig4[i] + pp4 * g * Ic4[i] S4[i + 1] = b + S4[i] - L4pos # Return variable values return {'S1': S1, 'E1': E1, 'Is1': Is1, 'Ic1': Ic1, 'Igl': Ig1, 'S2': S2, 'E2': E2, 'Is2': Is2, 'Ic2': Ic2, 'Ig2': Ig2, 'S3': S3, 'E3': E3, 'Is3': Is3, 'Ic3': Ic3, 'Ig3': Ig3, 'S4': S4, 'E4': E4, 'Is4': Is4, 'Ic4': Ic4, 'Ig4': Ig4, 'time': tspan} class SIS(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SIS' self.state_variables = {"S": 'Susceptible', 'I': 'Infectious'} self.parameters = {'beta': r'\beta', 'gamma': r'\gamma'} self.run = self.model def model(self, inits: list, trange: list, totpop: int, params: dict) -> dict: """ calculates the model SIS, and return its values (no demographics) - inits = (E,I,S) - theta = infectious individuals from neighbor sites :param trange: :param params: :param inits: tuple with initial conditions :param simstep: step of the simulation :param totpop: total population :return: """ S: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) E, I[0], S[0] = inits N = totpop beta = params['beta'] gamma = params['gamma'] for i in tspan[:-1]: Lpos = float(beta) * S[i] * I[i] / N # Model I[i + 1] = I[i] + Lpos - gamma * I[i] S[i + 1] = S[i] - Lpos + gamma * I[i] return {'S': S, 'I': I, 'time': tspan} class SIR(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SIR' self.state_variables = {'R': 'Removed', 'I': 'Infectious', 'S': 'Susceptible'} self.parameters = {'beta': r'\beta', 'gamma': r'\gamma'} self.run = self.model def model(self, inits: list, trange: list, totpop: int, params: dict) -> dict: """ calculates the model SIR, and return its values (no demographics) - inits = (E,I,S) - theta = infectious individuals from neighbor sites """ S: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], I[0], R[0] = inits N = totpop beta = params['beta'] gamma = params['gamma'] # Model for i in tspan[:-1]: Lpos = float(beta) * S[i] * I[i] / N # Number of new cases I[i + 1] = I[i] + Lpos - gamma * I[i] S[i + 1] = S[i] - Lpos R[i + 1] = N - (S[i + 1] + I[i + 1]) return {'time': tspan, 'S': S, 'I': I, 'R': R} class SEIS(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SEIS' self.state_variables = {'I': 'Infectious', "S": 'Susceptible', 'E': 'Exposed'} self.parameters = {'b': 'b', 'beta': r'\beta', 'e': 'e', 'r': 'r'} self.run = self.model def model(self, inits, trange, totpop, params): """ Defines the model SEIS: - inits = (E,I,S) - theta = infectious individuals from neighbor sites """ S: np.ndarray = np.zeros(trange[1] - trange[0]) E: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], E[0], I[0] = inits N = totpop beta = params['beta']; e = params['e']; r = params['r']; b = params['b']; for i in tspan[:-1]: Lpos = float(beta) * S[i] * I[i] / N # Number of new cases # Model E[i + 1] = (1 - e) * E[i] + Lpos I[i + 1] = e * E[i] + (1 - r) * I[i] S[i + 1] = S[i] + b - Lpos + r * I[i] return {'time': tspan, 'S': S, 'I': I, 'E': E} class SEIR(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SEIR' self.state_variables = {'I': 'Infectious', "S": 'Susceptible', 'E': 'Exposed', 'R': 'Removed'} self.parameters = {'b': 'b', 'beta': r'\beta', 'e': 'e', 'r': 'r', 'alpha': r'\alpha'} self.run = self.model def model(self, inits, trange, totpop, params): """ Defines the model SEIR: - inits = (E,I,S) - par = (Beta, alpha, E,r,delta,B,w,p) see docs. - theta = infectious individuals from neighbor sites """ S: np.ndarray = np.zeros(trange[1] - trange[0]) E: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], E[0], I[0], R[0] = inits N = totpop beta = params['beta']; alpha = params['alpha']; e = params['e']; r = params['r']; b = params['b']; for i in tspan[:-1]: Lpos = float(beta) * S[i] * I[i] / N # Number of new cases # Model E[i + 1] = (1 - e) * E[i] + Lpos I[i + 1] = e * E[i] + (1 - r) * I[i] S[i + 1] = S[i] + b - Lpos R[i + 1] = N - (S[i + 1] + E[i + 1] + I[i + 1]) return {'time': tspan, 'S': S, 'I': I, 'E': E, 'R': R} class SIpRpS(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SIpRpS' self.state_variables = {'I': 'Infectious', "S": 'Susceptible', 'R': 'Removed'} self.parameters = {'b': 'b', 'beta': r'$\beta$', 'e': 'e', 'r': 'r', 'delta': r'$\delta$'} self.run = self.model def model(self, inits, trange, totpop, params): """ calculates the model SIpRpS, and return its values (no demographics) - inits = (E,I,S) - theta = infectious individuals from neighbor sites """ S: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], I[0], R[0] = inits N = totpop beta = params['beta']; r = params['r']; delta = params['delta']; b = params['b']; # Model for i in tspan[:-1]: Lpos = float(beta) * S[i] * (I[i] / N) # Number of new cases I[i + 1] = (1 - r) * I[i] + Lpos S[i + 1] = S[i] + b - Lpos + (1 - delta) * r * I[i] R[i + 1] = N - (S[i + 1] + I[i + 1]) + delta * r * I[i] return {'time': tspan, 'S': S, 'I': I, 'R': R} class SEIpRpS(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SEIpRpS' self.state_variables = {'I': 'Infectious', "S": 'Susceptible', 'E': "Exposed", 'R': 'Removed'} self.parameters = {'b': 'b', 'beta': r'$\beta$', 'e': 'e', 'r': 'r', 'delta': r'$\delta$'} self.run = self.model def model(self, inits, trange, totpop, params): """ Defines the model SEIpRpS: - inits = (E,I,S) - theta = infectious individuals from neighbor sites """ S: np.ndarray = np.zeros(trange[1] - trange[0]) E: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], E[0], I[0], R[0] = inits N = totpop beta = params['beta']; e = params['e']; r = params['r']; delta = params['delta']; b = params['b']; for i in tspan[:-1]: Lpos = float(beta) * S[i] * (I[i] / N) # Number of new cases E[i + 1] = (1 - e) * E[i] + Lpos I[i + 1] = e * E[i] + (1 - r) * I[i] S[i + 1] = S[i] + b - Lpos + (1 - delta) * r * I[i] R[i + 1] = N - (S[i + 1] + E[i + 1] + I[i + 1]) + delta * r * I[i] return {'time': tspan, 'S': S, 'I': I, 'E': E, 'R': R} class SIpR(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SIpR' self.state_variables = {'I': 'Infectious', "S": 'Susceptible', 'R': 'Removed'} self.parameters = {'b': 'b', 'beta': r'$\beta$', 'r': 'r', 'p': 'p'} self.run = self.model def model(self, inits, trange, totpop, params): """ calculates the model SIpR, and return its values (no demographics) - inits = (S,I,R) """ S: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], I[0], R[0] = inits N = totpop beta = params['beta'] r = params['r'] b = params['b'] p = params['p'] for i in tspan[:-1]: Lpos = float(beta) * S[i] * (I[i] / N) # Number of new cases Lpos2 = p * float(beta) * R[i] * (I[i] / N) # number of secondary Infections # Model I[i + 1] = (1 - r) * I[i] + Lpos + Lpos2 S[i + 1] = S[i] + b - Lpos R[i + 1] = N - (S[i + 1] + I[i + 1]) - Lpos2 return {'time': tspan, 'S': S, 'I': I, 'R': R} class SEIpR(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SEIpR' self.state_variables = {'I': 'Infectious', "S": 'Susceptible', 'E': "Exposed", 'R': 'Removed'} self.parameters = {'b': 'b', 'beta': r'$\beta$', 'e': 'e', 'r': 'r', 'alpha': r'$\alpha$', 'p': 'p'} self.run = self.model def model(self, inits, trange, totpop, params): """ calculates the model SEIpR, and return its values (no demographics) - inits = (S,E,I,R) """ S: np.ndarray = np.zeros(trange[1] - trange[0]) E: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], E[0], I[0], R[0] = inits N = totpop beta = params['beta'] e = params['e'] r = params['r'] b = params['b'] p = params['p'] # print(tspan) for i in tspan[:-1]: # print(i) Lpos = float(beta) * S[i] * (I[i] / N) # Number of new cases Lpos2 = p * float(beta) * R[i] * (I[i] / N) # secondary infections # Model E[i + 1] = (1 - e) * E[i] + Lpos + Lpos2 I[i + 1] = e * E[i] + (1 - r) * I[i] S[i + 1] = S[i] + b - Lpos R[i + 1] = N - (S[i + 1] + I[i + 1]) - Lpos2 return {'time': tspan, 'S': S, 'I': I, 'E': E, 'R': R} # from numba.types import unicode_type, pyobject # spec = [ # ('model_type', unicode_type), # ('state_variables', pyobject), # ('parameters', pyobject), # ('run', pyobject) # ] # # @jitclass(spec) class SIRS(DiscreteModel): def __init__(self): super().__init__() self.model_type = 'SIRS' self.state_variables = {'R': 'Removed', 'I': 'Infectious', 'S': 'Susceptible'} self.parameters = {'beta': r'$\beta$', 'b': 'b', 'w': 'w'} self.run = self.model # @numba.jit def model(self, inits: List, trange: List, totpop: int, params: Dict) -> Dict: """ calculates the model SIRS, and return its values (no demographics) :param inits: (E,I,S) :param trange: :param totpop: :param params: :return: """ S: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], I[0], R[0] = inits N = totpop beta = params['beta']; r = params['r']; b = params['b']; w = params['w']; for i in tspan[:-1]: Lpos = float(beta) * S[i] * (I[i] / N) # Number of new cases # Model I[i + 1] = (1 - r) * I[i] + Lpos S[i + 1] = S[i] + b - Lpos + w * R[i] R[i + 1] = N - (S[i + 1] + I[i + 1]) - w * R[i] return {'time': tspan, 'S': S, 'I': I, 'R': R} class SEQIAHR(DiscreteModel): def __init__(self): super().__init__() self.state_variables = OrderedDict( {'S': 'Susceptible', 'E': 'Exposed', 'I': 'Infectious', 'A': 'Asymptomatic', 'H': 'Hospitalized', 'R': 'Removed', 'C': 'Cumulative hospitalizations', 'D': 'Cumulative deaths'}) self.parameters = OrderedDict({'chi': r'$\chi', 'phi': r'$\phi$', 'beta': r'$\beta$', 'rho': r'$\rho$', 'delta': r'$\delta$', 'gamma': r'$\gamma$', 'alpha': r'$\alpha$', 'mu': r'$\mu$', 'p': '$p$', 'q': '$q$', 'r': '$r$' }) self.model_type = 'SEQIAHR' self.run = self.model def model(self, inits, trange, totpop, params) -> dict: S: np.ndarray = np.zeros(trange[1] - trange[0]) E: np.ndarray = np.zeros(trange[1] - trange[0]) I: np.ndarray = np.zeros(trange[1] - trange[0]) A: np.ndarray = np.zeros(trange[1] - trange[0]) H: np.ndarray = np.zeros(trange[1] - trange[0]) R: np.ndarray = np.zeros(trange[1] - trange[0]) C: np.ndarray = np.zeros(trange[1] - trange[0]) D: np.ndarray = np.zeros(trange[1] - trange[0]) tspan = np.arange(*trange) S[0], E[0], I[0], A[0], H[0], R[0], C[0], D[0] = inits N = totpop chi, phi, beta, rho, delta, gamma, alpha, mu, p, q, r = params.values() for i in tspan[:-1]: # Turns on Quarantine on day q and off on day q+r chi_t = chi * ((1 + np.tanh(i - q)) / 2) * ((1 - np.tanh(i - (q + r))) / 2) ##### Modeling the number of new cases (incidence function) Lpos = beta * ((1 - chi_t) * S[i]) * (I[i] + A[i]) # Number of new cases ##### Epidemiological model (SEQIAHR) S[i + 1] = S[i] - Lpos E[i + 1] = E[i] + Lpos - alpha * E[i] I[i + 1] = I[i] + (1 - p) * alpha * E[i] - delta * I[i] - phi* I[i] A[i + 1] = A[i] + p * alpha * E[i] - gamma * A[i] H[i + 1] = H[i] + phi * I[i] - (rho + mu) * H[i] R[i + 1] = R[i] + delta * I[i] + rho * H[i] + gamma * A[i] C[i + 1] = C[i] + phi * delta * I[i] + (1 - p) * alpha * E[i] # Cumulative cases Hospitalizations + I D[i + 1] = D[i] + mu * H[i] # Cumulative deaths return {'time': tspan, 'S': S, 'E': E, 'I': I, 'A': A, 'H': H, 'R': R, 'C': C, 'D': D} epimodels-0.3.20/src/epimodels/tools/000077500000000000000000000000001402342343400174645ustar00rootroot00000000000000epimodels-0.3.20/src/epimodels/tools/__init__.py000066400000000000000000000001031402342343400215670ustar00rootroot00000000000000u""" Created on 29/11/18 by fccoelho license: GPL V3 or Later """ epimodels-0.3.20/src/epimodels/tools/phase.py000066400000000000000000000025771402342343400211510ustar00rootroot00000000000000""" This module offers tools for phase space representation of models' dynamics. Embedding tool is based of the following papers: 1. Basharat, A., & Shah, M. (2009, September). Time series prediction by chaotic modeling of nonlinear dynamical systems. In Computer Vision, 2009 IEEE 12th International Conference on (pp. 1941-1948). IEEE. 2. Cao, L. (1997). Practical method for determining the minimum embedding dimension of a scalar time series. Physica D: Nonlinear Phenomena, 110(1-2), 43-50. Created on 29/11/18 by fccoelho license: GPL V3 or Later """ # import numpy # # from pyitlib import discrete_random_variable as drv # import pylab as P # # class TimeDelayEmbedding: # def __init__(self, traces): # self.traces = traces # # def mutual_information(self, data, tau_max=100): # mis = [] # # for tau in range(1, tau_max): # unlagged = data[:-tau] # lagged = numpy.roll(data, -tau)[:-tau] # joint = numpy.hstack((unlagged, lagged)) # mis.append(drv.information_multi(joint)) # if len(mis) > 1 and mis[-2] < mis[-1]: # return first local minima # tau -= 1 # return tau, mis # # def _find_embedding_dimension(self, x, tau): # d = 2 # while True: # ai = max([]) # # def show_mutual_information(self, mis): # P.plot(mis) # P.show() epimodels-0.3.20/tests/000077500000000000000000000000001402342343400147165ustar00rootroot00000000000000epimodels-0.3.20/tests/conftest.py000066400000000000000000000003741402342343400171210ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Dummy conftest.py for epimodels. If you don't know what this is for, just leave it empty. Read more about conftest.py under: https://pytest.org/latest/plugins.html """ # import pytest epimodels-0.3.20/tests/test_continuous_models.py000066400000000000000000000042761402342343400221110ustar00rootroot00000000000000__author__ = 'fccoelho' import unittest import pytest from matplotlib import pyplot as P # import pyximport; pyximport.install(pyimport=True) from epimodels.continuous.models import * def test_SIR(): model = SIR() model([1000, 1, 0], [0, 500], 1001, {'beta': .2, 'gamma': .1}) assert len(model.traces) == 4 # assert len(model.traces['time']) == 50 model.plot_traces() P.show() def test_SIR_with_t_eval(): model = SIR() model([1000, 1, 0], [0, 500], 1001, {'beta': .2, 'gamma': .1}, t_eval=range(0, 500)) assert len(model.traces['S']) == 500 # assert len(model.traces['time']) == 50 def test_SIS(): model = SIS() model([1000, 1], [0, 50], 1001, {'beta': 2, 'gamma': .1}) assert len(model.traces) == 3 # assert len(model.traces['time']) == 50 model.plot_traces() P.show() def test_SIRS(): model = SIRS() model([1000, 1, 0], [0, 50], 1001, {'beta': 5, 'gamma': 1.9, 'xi': 0.05}) assert len(model.traces) == 4 # assert len(model.traces['time']) == 50 model.plot_traces() P.show() def test_SEIR(): model = SEIR() model([1000, 0, 1, 0], [0, 50], 1001, {'beta': 5, 'gamma': 1.9, 'epsilon': 0.1}) # print(model.traces) assert len(model.traces) == 5 # state variables plus time # assert len(model.traces['time']) == 50 model.plot_traces() P.show() def test_SEQIAHR(): model = SEQIAHR() model([.99, 0, 1e-6, 0, 0, 0, 0, 0], [0, 300], 1, {'chi': .7, 'phi': .01, 'beta': .5, 'rho': .05, 'delta': .1, 'gamma': .1, 'alpha': .33, 'mu': .03, 'p': .75, 'q': 50, 'r': 40 }) # print(model.traces) assert len(model.traces) == 9 # state variables plus time # assert len(model.traces['time']) == 50 model.plot_traces() P.show() # def test_SIS_with_cache(): # model = SIS() # model([1000, 1], [0, 50], 1001, {'beta': 2, 'gamma': .1}) # tr1 = model.traces # model([1000, 1], [0, 50], 1001, {'beta': 2, 'gamma': .1}) # tr2 = model.traces # assert (tr1 == tr2) epimodels-0.3.20/tests/test_discrete_models.py000066400000000000000000000105171402342343400215000ustar00rootroot00000000000000__author__ = 'fccoelho' import pytest # import pyximport; pyximport.install(pyimport=True) from epimodels.discrete.models import (DiscreteModel, Influenza, SIS, SIR, SEIS, SEIR, SIpRpS, SEIpRpS, SIpR, SEIpR, SIRS, SEQIAHR) from matplotlib import pyplot as P def test_SIS(): modelsis = SIS() modelsis([0, 1, 1000], [0,50], 1001, {'beta': 2, 'gamma': 1}) assert len(modelsis.traces) == 3 assert len(modelsis.traces['time']) == 50 modelsis.plot_traces() P.show() assert isinstance(modelsis, DiscreteModel) def test_SIR(): modelsir = SIR() modelsir([1000, 1, 0], [0,500], 1001, {'beta': .2, 'gamma': .1}) assert len(modelsir.traces) == 4 assert len(modelsir.traces['time']) == 500 modelsir.plot_traces() P.show() assert isinstance(modelsir, DiscreteModel) def test_FLU(): modelflu = Influenza() modelflu([250, 1, 0, 0, 0, 250, 1, 0, 0, 0, 250, 1, 0, 0, 0, 250, 1, 0, 0, 0], [0,50], 1004, {'beta': 2.0, 'r': 0.25, 'e': 0.5, 'c': 0.5, 'g': 1 / 3, 'd': 1 / 7, 'pc1': .67, 'pc2': .67, 'pc3': .67, 'pc4': .67, 'pp1': .32, 'pp2': .112, 'pp3': .13, 'pp4': .38, 'b': 0 }) assert len(modelflu.traces) == 21 assert len(modelflu.traces['time']) == 50 print(list(modelflu.traces.keys())) modelflu.plot_traces() P.show() assert isinstance(modelflu, DiscreteModel) def test_SEIS(): modelseis = SEIS() modelseis([1000, 1, 0], [0,50], 1001, {'beta': 2, 'r': 1, 'e': 1, 'b': 0}) assert len(modelseis.traces) == 4 assert len(modelseis.traces['time']) == 50 modelseis.plot_traces() P.show() assert isinstance(modelseis, DiscreteModel) def test_SEIR(): modelseir = SEIR() tsteps = [0,50] modelseir([1000, 1, 1, 0], tsteps, 1002, {'beta': 2, 'r': 1, 'e': 1, 'b': 0, 'alpha': 1}) assert len(modelseir.traces) == 5 assert len(modelseir.traces['time']) == tsteps[1] modelseir.plot_traces() P.show() assert isinstance(modelseir, DiscreteModel) def test_SIpRpS(): modelsiprps = SIpRpS() tsteps = [0,50] modelsiprps([1000, 1, 0], tsteps, 1002, {'beta': 2, 'r': 1, 'e': 1, 'b': 0, 'delta': 0.5}) assert len(modelsiprps.traces) == 4 assert len(modelsiprps.traces['time']) == tsteps[1] modelsiprps.plot_traces() P.show() assert isinstance(modelsiprps, DiscreteModel) def test_SEIpRpS(): modelseiprps = SEIpRpS() tsteps = [0,50] modelseiprps([1000, 1, 0, 0], tsteps, 1002, {'beta': 2, 'r': 1, 'e': 1, 'b': 0, 'delta': 0.5}) assert len(modelseiprps.traces) == 5 assert len(modelseiprps.traces['time']) == tsteps[1] modelseiprps.plot_traces() P.show() assert isinstance(modelseiprps, DiscreteModel) def test_SIpR(): modelsipr = SIpR() modelsipr([1000, 1, 0], [0,50], 1001, {'beta': 2, 'gamma': 1, 'b': 0, 'r': .5, 'p': .5}) assert len(modelsipr.traces) == 4 assert len(modelsipr.traces['time']) == 50 modelsipr.plot_traces() P.show() assert isinstance(modelsipr, DiscreteModel) def test_SEIpR(): modelseipr = SEIpR() tsteps = [0,50] modelseipr([1000, 1, 1, 0], tsteps, 1002, {'beta': 2, 'r': 1, 'e': 1, 'b': 0, 'p':0.5, 'alpha': 1}) assert len(modelseipr.traces) == 5 assert len(modelseipr.traces['time']) == tsteps[1] modelseipr.plot_traces() P.show() assert isinstance(modelseipr, DiscreteModel) def test_SIRS(): modelsirs = SIRS() modelsirs([1000, 1, 0], [0,50], 1001, {'beta': 2, 'b': 0, 'r': .5, 'w': .5}) assert len(modelsirs.traces) == 4 assert len(modelsirs.traces['time']) == 50 modelsirs.plot_traces() P.show() assert isinstance(modelsirs, DiscreteModel) def test_SEQIAHR(): model = SEQIAHR() model([.99, 0, 1e-6, 0, 0, 0, 0, 0], [0, 300], 1, {'chi': .7, 'phi': .01, 'beta': .5, 'rho': .05, 'delta': .1, 'gamma': .1, 'alpha': .33, 'mu': .03, 'p': .75, 'q': 50, 'r': 40 }) assert len(model.traces) == 9 model.plot_traces() P.show() assert isinstance(model, DiscreteModel)