예제 #1
0
def make_sim(do_save=False, **kwargs):

    # Shared settings
    pars = dict(pop_size=pop_size, verbose=0)
    pars.update(kwargs)

    # Versioning was introduced in 2.0
    if cv.check_version('2.0.0', verbose=False) >= 0:
        pars.update({'version': version})

    sim = cv.Sim(**pars)
    sim.run()

    if do_save:
        print(sim.summary)
        sim.save(filename)

    return sim
예제 #2
0
'''
UK scenarios for evaluating effectivness of masks
'''

import sciris as sc
import covasim as cv
import pylab as pl
import numpy as np
import matplotlib as mplt
# pl.switch_backend('agg')

# Check version
cv.check_version('1.5.2')
cv.git_info('covasim_version.json')

mplt.rcParams['font.family'] = 'Roboto'

do_plot = 1
do_save = 1
do_show = 0
verbose = 1
seed = 1

scenario = ['more_intense', 'more_relaxed'
            ][1]  # Set a number to pick a scenario from the available options
tti_scen = ['current'][0]  # Ditt0

version = 'v1'
date = '2020sep20'
folder = f'results_FINAL_{date}'
file_path = f'{folder}/phase_{version}'  # Completed below
예제 #3
0
def test_misc():
    sc.heading('Testing miscellaneous functions')

    sim_path = 'test_misc.sim'
    json_path = 'test_misc.json'

    # Data loading
    cv.load_data(csv_file)
    cv.load_data(xlsx_file)

    with pytest.raises(NotImplementedError):
        cv.load_data('example_data.unsupported_extension')

    with pytest.raises(ValueError):
        cv.load_data(xlsx_file, columns=['missing_column'])

    # Dates
    d1 = cv.date('2020-04-04')
    d2 = cv.date(sc.readdate('2020-04-04'))
    ds = cv.date('2020-04-04', d2)
    assert d1 == d2
    assert d2 == ds[0]

    with pytest.raises(ValueError):
        cv.date([(2020, 4, 4)])  # Raises a TypeError which raises a ValueError

    with pytest.raises(ValueError):
        cv.date('Not a date')

    cv.daydiff('2020-04-04')

    # Saving and loading
    sim = cv.Sim()
    cv.save(filename=sim_path, obj=sim)
    cv.load(filename=sim_path)

    # Version checks
    cv.check_version('0.0.0')  # Nonsense version
    print('↑ Should complain about version')
    with pytest.raises(ValueError):
        cv.check_version('0.0.0', die=True)

    # Git checks
    cv.git_info(json_path)
    cv.git_info(json_path, check=True)

    # Poisson tests
    c1 = 5
    c2 = 8
    for alternative in ['two-sided', 'larger', 'smaller']:
        cv.poisson_test(c1, c2, alternative=alternative)
    for method in ['score', 'wald', 'sqrt', 'exact-cond']:
        cv.poisson_test(c1, c2, method=method)

    with pytest.raises(ValueError):
        cv.poisson_test(c1, c2, method='not a method')

    # Tidy up
    remove_files(sim_path, json_path)

    return
import sciris as sc
import covasim as cv
import covasim.base as cvb
import covasim.parameters as cvp
import pylab as pl
import numpy as np
import matplotlib as mplt
import pandas as pd

########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('3.0.5')
cv.git_info('covasim_version.json')

# Saving and plotting settings
do_plot = 1
do_save = 1
save_sim = 1
plot_hist = 0  # Whether to plot an age histogram
do_show = 0
verbose = 1
seed = 1
n_runs = 200
to_plot = sc.objdict({
    'Cumulative diagnoses': ['cum_diagnoses'],
    'Cumulative hospitalisations': ['cum_severe'],
    'Cumulative deaths': ['cum_deaths'],
    'Daily infections': ['new_diagnoses'],
    'Daily hospitalisations': ['new_severe'],
'''
Calculate vaccine efficiency for protection against symptomatic covid after first dose
'''

import numpy as np
import sciris as sc
import covasim as cv

cv.check_version('>=3.0.0')

vaccines = ['pfizer', 'moderna', 'az', 'j&j']


# construct analyzer to select placebo arm
class placebo_arm(cv.Analyzer):
    def __init__(self, day, trial_size, **kwargs):
        super().__init__(**kwargs)
        self.day = day
        self.trial_size = trial_size
        return

    def initialize(self, sim=None):
        self.placebo_inds = []
        self.initialized = True
        return

    def apply(self, sim):
        if sim.t == self.day:
            eligible = cv.true(~np.isfinite(sim.people.date_exposed)
                               & ~sim.people.vaccinated)
            self.placebo_inds = eligible[cv.choose(
'''
UK scenarios
'''

import sciris as sc
import numpy as np
import covasim as cv
import pylab as pl

# Check version
cv.check_version('1.3.2', die=True)
#cv.git_info('covasim_version.json')

do_plot = 1
do_save = 1
do_show = 1
verbose = 1
seed = 1

version = 'v1'
date = '2020may26'
folder = f'results_FINAL_{date}'
file_path = f'{folder}/phase_{version}'  # Completed below
data_path = 'UK_Covid_cases_may21.xlsx'
pop_path = f'{file_path}.pop'
fig_path = f'{file_path}.png'
#ig_paths = [f'results/testing_scen_{i}.png' for i in range(3)]

start_day = sc.readdate('2020-01-21')
end_day = sc.readdate('2021-05-31')
n_days = (end_day - start_day).days
예제 #7
0
'''
UK scenarios for evaluating effectivness of masks
'''

import sciris as sc
import covasim as cv
import pylab as pl
import numpy as np
import matplotlib as mplt
# pl.switch_backend('agg')

# Check version
cv.check_version('1.7.4')
cv.git_info('covasim_version.json')

mplt.rcParams['font.family'] = 'Roboto'


do_plot = 1
do_save = 1
do_show = 0
verbose = 1
seed    = 1

scenario = ['med_comp'][0] # Set a number to pick a scenario from the available options
tti_scen = ['current', 'optimal_med_comp', 'optimal_med_comp_work'][0] # Ditt0

version   = 'v1'
date      = '2020sep20'
folder    = f'results_FINAL_{date}'
file_path = f'{folder}/phase_{version}' # Completed below
예제 #8
0
import sciris as sc
import covasim as cv
import covasim.base as cvb
import pylab as pl
import numpy as np
import matplotlib as mplt
import utils

########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('2.0.0')
cv.git_info('covasim_version.json')

# Saving and plotting settings
do_plot = 1
do_save = 1
save_sim = 1
do_show = 0
verbose = 1
seed = 1
n_runs = 200
to_plot = sc.objdict({
    'Cumulative diagnoses': ['cum_diagnoses'],
    'New Doses': ['new_doses'],
    'Single dosed': ['n_dose_1'],
    'Double dosed': ['n_dose_2'],
    'New infections': ['new_infections'],
    'R': ['r_eff'],
    'Cumulative hospitalisations': ['cum_severe'],
import sciris as sc
import covasim as cv
import covasim.parameters as cvp
import pylab as pl
import numpy as np


########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('3.1.0')
cv.git_info('covasim_version.json')

# Saving and plotting settings
do_plot = 1
do_save = 1
save_sim = 1
plot_hist = 0 # Whether to plot an age histogram
do_show = 0
verbose = 1
seed    = 1
keep_people = 0 # Whether to keep people
to_plot = sc.objdict({
    'Cumulative diagnoses': ['cum_diagnoses'],
    'Cumulative hospitalisations': ['cum_severe'],
    'Cumulative deaths': ['cum_deaths'],
    'Daily infections': ['new_diagnoses'],
    'Daily hospitalisations': ['new_severe'],
    'Daily ICUs': ['new_critical'],
    'Daily deaths': ['new_deaths'],
예제 #10
0
import sciris as sc
import covasim as cv

cv.check_version('0.27.12')

pars = sc.objdict(
    pop_size=100e3,  # Population size
    pop_infected=1,  # Number of initial infections
    n_days=60,  # Number of days to simulate
    rand_seed=1,  # Random seed
    pop_type='random',
    verbose=0,
)

sim = cv.Sim(pars=pars)

sc.tic()
sim.initialize()
sc.toc()

#%% Version 0.27.11
'''
>>> import sciris as sc
>>> import covasim as cv
Covasim 0.27.11 (2020-04-17) — © 2020 by IDM
>>> sim = cv.Sim(pop_size=1e6)
>>> sc.tic(); sim.initialize(); sc.toc()
1587187959.2373662
Initializing sim with 1e+06 people for 60 days
Elapsed time: 230 s
'''
'''
shrink vaccination intervention
'''
import covasim as cv
import sciris as sc

cv.check_version('>3.0.0', die=True)

pars = {
    'pop_size': 50000,
    'use_waning': True,
}

for vaccine in ['jj', 'pfizer']:
    print('\nFor ' + vaccine)

    sim = cv.Sim(pars)
    sim['interventions'] = [cv.vaccinate(vaccine='jj', days=10, prob=0.4)]
    sim.run(verbose=False)

    print('Sim size is:')
    sc.checkmem(sim, descend=False)

    sim.shrink()

    print('Shrunk size is:')
    sc.checkmem(sim, descend=False)

    print('Shrunk vaccination')
    sim['interventions'][0].shrink()
    sc.checkmem(sim, descend=False)
예제 #12
0
'''
UK scenarios for evaluating effectivness of masks
'''

import os
import shutil
import sciris as sc
import covasim as cv
import numpy as np

########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('2.0.2')
cv.git_info('covasim_version.json')

# Saving and plotting settings
debug = 1  # Whether to do a small debug run (for sweeps)
use_mean = 1  # Whether to use the mean instead of median
do_plot = 1
do_save = 1
save_sim = 1
do_show = 0
verbose = 1
seed = 1
to_plot = sc.objdict({
    'Cumulative diagnoses': ['cum_diagnoses'],
    'Cumulative infections': ['cum_infections'],
    'New infections': ['new_infections'],
    'Cumulative deaths': ['cum_deaths'],
예제 #13
0
'''
Illustration of an automatic calibration to NY state data
'''

import numpy as np
import pylab as pl
import sciris as sc
import covasim as cv
import scipy as sp
import optuna as op

cv.check_version('1.6.1', die=False)  # Ensure Covasim version is correct


class Calibration:
    def __init__(self, storage):

        # Settings
        self.pop_size = 100e3  # Number of agents
        self.start_day = '2020-02-01'
        self.end_day = '2020-07-30'  # Change final day here
        self.state = 'NY'
        self.datafile = 'NY.csv'
        self.total_pop = 19453561  # Population of NY from census, nst-est2019-alldata.csv

        # Saving and running
        self.n_trials = 20  # Number of sequential Optuna trials
        self.n_workers = 4  # Number of parallel Optuna threads -- incompatible with n_runs > 1
        self.n_runs = 1  # Number of sims being averaged together in a single trial -- incompatible with n_workers > 1
        self.storage = storage  # Database location
        self.name = 'covasim'  # Optuna study name -- not important but required
import sciris as sc
import covasim as cv
import load_data as ld
import os as os

cv.check_version('1.5.0', die=True)

# we use vb to keep functions identical to source
vb = sc.objdict()
vb.verbose = 0

# The simulation is stochastic; how often should it be realized?
n_runs_per_parameter_set = 50


def create_sim_from_calibrated_pars(filename):
    '''Wrapper around create_sim that reads the parameters from a file'''
    pars_calib = sc.loadjson(filename)
    # Take care to use the same order that create_sim expects!
    pars = [
        pars_calib["pop_infected"], pars_calib["beta"], pars_calib["beta_day"],
        pars_calib["beta_change"], pars_calib["symp_test"]
    ]
    return create_sim(pars)


def create_sim(x, vb=vb):
    ''' Create the simulation from the parameters '''

    # Convert parameters
    pop_infected = x[0]
'''
UK scenarios
'''

import sciris as sc
import covasim as cv
import pylab as pl

# Check version
cv.check_version('1.3.3')
cv.git_info('covasim_version.json')

do_plot = 1
do_save = 1
do_show = 1
verbose = 1
seed = 1

scenario = ['jun-opening', 'sep-opening', 'phased', 'phased-delayed'
            ][3]  # Set a number to pick a scenario from the available options
tti_scen = ['none', '40%', '80%'][2]  # Ditto

version = 'v1'
date = '2020may26'
folder = f'results_FINAL_{date}'
file_path = f'{folder}/phase_{version}'  # Completed below
data_path = 'UK_Covid_cases_may21.xlsx'
fig_path = f'{file_path}_{scenario}.png'

start_day = '2020-01-21'
end_day = '2021-05-31'
예제 #16
0
def test_misc():
    sc.heading('Testing miscellaneous functions')

    sim_path = 'test_misc.sim'
    json_path = 'test_misc.json'
    gitinfo_path = 'test_misc.gitinfo'
    fig_path = 'test_misc.png'
    fig_comments = 'Test comment'

    # Data loading
    cv.load_data(csv_file)
    cv.load_data(xlsx_file)

    with pytest.raises(NotImplementedError):
        cv.load_data('example_data.unsupported_extension')

    with pytest.raises(ValueError):
        cv.load_data(xlsx_file, columns=['missing_column'])

    # Dates
    d1 = cv.date('2020-04-04')
    d2 = cv.date(sc.readdate('2020-04-04'))
    ds = cv.date('2020-04-04', d2)
    assert d1 == d2
    assert d2 == ds[0]

    with pytest.raises(ValueError):
        cv.date([(2020, 4, 4)])  # Raises a TypeError which raises a ValueError

    with pytest.raises(ValueError):
        cv.date('Not a date')

    cv.daydiff('2020-04-04')

    # Run sim for more investigations
    sim = cv.Sim(pop_size=500, verbose=0)
    sim.run()
    sim.plot(do_show=False)

    # Saving and loading
    cv.savefig(fig_path, comments=fig_comments)
    cv.save(filename=sim_path, obj=sim)
    cv.load(filename=sim_path)

    # Version checks
    cv.check_version('0.0.0')  # Nonsense version
    print('↑ Should complain about version')
    with pytest.raises(ValueError):
        cv.check_version('0.0.0', die=True)

    # Git checks
    cv.git_info(json_path)
    cv.git_info(json_path, check=True)

    # Poisson tests
    c1 = 5
    c2 = 8
    for alternative in ['two-sided', 'larger', 'smaller']:
        cv.poisson_test(c1, c2, alternative=alternative)
    for method in ['score', 'wald', 'sqrt', 'exact-cond']:
        cv.poisson_test(c1, c2, method=method)

    with pytest.raises(ValueError):
        cv.poisson_test(c1, c2, method='not a method')

    # Test locations
    for location in [None, 'viet-nam']:
        cv.data.show_locations(location)

    # Test versions
    with pytest.raises(ValueError):
        cv.check_save_version('1.3.2', die=True)
    cv.check_save_version(cv.__version__,
                          filename=gitinfo_path,
                          comments='Test')

    # Test PNG
    try:
        metadata = cv.get_png_metadata(fig_path, output=True)
        assert metadata['Covasim version'] == cv.__version__
        assert metadata['Covasim comments'] == fig_comments
    except ImportError as E:
        print(
            f'Cannot test PNG function since pillow not installed ({str(E)}), skipping'
        )

    # Tidy up
    remove_files(sim_path, json_path, fig_path, gitinfo_path)

    return
예제 #17
0
import sciris as sc
import covasim as cv
import covasim.base as cvb
import pylab as pl
import numpy as np
import matplotlib as mplt
import utils

########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('3.0.0')
cv.git_info('covasim_version.json')



# Saving and plotting settings
do_plot = 1
do_save = 1
save_sim = 1
plot_hist = 0 # Whether to plot an age histogram
do_show = 0
verbose = 1
seed    = 1
n_runs = 200
to_plot = sc.objdict({
    'Cumulative tests': ['cum_tests'],
    'First vaccine dose': ['n_dose_1'],
    'Second vaccine dose': ['n_dose_2'],
    'Cumulative diagnoses': ['cum_diagnoses'],
'''
UK scenarios for evaluating effectivness of masks
'''

import sciris as sc
import covasim as cv
import pylab as pl
import numpy as np
pl.switch_backend('agg')

# Check version
cv.check_version('1.4.7')
cv.git_info('covasim_version.json')

mplt.rcParams['font.family'] = 'Roboto'

do_plot = 1
do_save = 1
do_show = 1
verbose = 1
seed    = 1

scenario = ['no_vaccine', 'vaccinate_elderly', 'vaccinate_HW', 'vaccinate_SW'][0] # pharmaceutical interventions
tti_scen = ['currentTTI', 'optimal_TTI_no_vaccine', 'optima_TTI_with_vaccinate_elderly', 'optimal_TTI_vaccine_HW','optimal_TTI_vaccinate_SW'][0] # non-pharmeceutical intervention

version   = 'v1'
date      = '2020august25'
folder    = f'results_FINAL_{date}'
file_path = f'{folder}/phase_{version}' # Completed below
data_path = 'UK_Covid_cases_august02.xlsx'
fig_path  = f'{file_path}_{scenario}.png'
예제 #19
0
import sciris as sc
import covasim as cv
import covasim.parameters as cvp
import pylab as pl
import numpy as np


########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('3.0.7')
cv.git_info('covasim_version.json')

# Saving and plotting settings
do_plot = 1
do_save = 1
save_sim = 1
plot_hist = 0 # Whether to plot an age histogram
do_show = 0
verbose = 1
seed    = 1
keep_people = 0 # Whether to keep people
to_plot = sc.objdict({
    'Cumulative diagnoses': ['cum_diagnoses'],
    'Cumulative hospitalisations': ['cum_severe'],
    'Cumulative deaths': ['cum_deaths'],
    'Daily infections': ['new_diagnoses'],
    'Daily hospitalisations': ['new_severe'],
    'Daily ICUs': ['new_critical'],
    'Daily deaths': ['new_deaths'],
예제 #20
0
import covasim as cv
import sciris as sc

cv.check_version('0.27.9')

do_plot = 1

datafile = sc.thisdir(__file__, '../../example_data.csv')

pars = sc.objdict(diag_factor=1.0, n_days=30, pop_infected=100)

sim = cv.Sim(pars, datafile=datafile)

case = 2
testprobdict = {
    0:
    cv.test_prob(symp_prob=0,
                 asymp_prob=0,
                 test_sensitivity=1.0,
                 loss_prob=0.0,
                 test_delay=0,
                 start_day=0),  # works, no diagnoses
    1:
    cv.test_prob(symp_prob=1,
                 asymp_prob=0,
                 test_sensitivity=1.0,
                 loss_prob=0.0,
                 test_delay=0,
                 start_day=0),  # works, ~half diagnosed
    2:
    cv.test_prob(
'''
UK scenarios
'''

import sciris as sc
import numpy as np
import covasim as cv
import pylab as pl

# Check version
cv.check_version('0.30.3')
cv.git_info('covasim_version.json')

do_plot = 1
do_save = 1
do_show = 1
verbose = 1
seed = 1

version = 'v1'
date = '2020may25'
folder = f'results_transmisibility100_TIonly_{date}'
file_path = f'{folder}/phase_{version}'  # Completed below
data_path = 'UK_Covid_cases_may21.xlsx'
pop_path = f'{file_path}.pop'
fig_path = f'{file_path}.png'
#ig_paths = [f'results/testing_scen_{i}.png' for i in range(3)]

start_day = sc.readdate(
    '2020-01-21'
)  # start_day = sc.readdate('2020-01-21') or start_day = sc.readdate('2020-02-04')
예제 #22
0
import sciris as sc
import covasim as cv
import covasim.base as cvb
import covasim.parameters as cvp
import pylab as pl
import numpy as np
import matplotlib as mplt
import utils_vac

########################################################################
# Settings and initialisation
########################################################################
# Check version
cv.check_version('3.0.2')
cv.git_info('covasim_version.json')

# Saving and plotting settings
do_plot = 1
do_save = 1
save_sim = 1
plot_hist = 0  # Whether to plot an age histogram
do_show = 0
verbose = 1
seed = 1
n_runs = 200
to_plot = sc.objdict({
    'Cumulative tests': ['cum_tests'],
    'Cumulative diagnoses': ['cum_diagnoses'],
    'Cumulative hospitalisations': ['cum_severe'],
    'Cumulative deaths': ['cum_deaths'],
    'New infections': ['new_infections'],
예제 #23
0
'''
UK scenarios
'''
# import matplotlib
# matplotlib.use('Agg')
import sciris as sc
import covasim as cv
import pylab as pl

# Check version
cv.check_version('1.4.1')
cv.git_info('covasim_version.json')

# Plotting and output controls
do_plot = 1
do_save = 0
do_show = 1
verbose = 1
seed = 1
do_parallel = 1

# Analysis steps
rerun = True  # If false, loads saved runs

# Paths for saving and loading
version = 'v1'
date = '2020may30'
folder = f'results_FINAL_{date}'
file_path = f'{folder}/phase_{version}'
data_path = 'UK_Covid_cases_may21.xlsx'