Esempio n. 1
0
    def run_sim(self,
                params_dict=None,
                write_results_json=False,
                population_type=None):
        if not self.simulation_parameters or params_dict:  # If we need one, or have one here
            self.set_simulation_parameters(params_dict=params_dict)
            pass

        self.simulation_parameters['interventions'] = self.interventions

        self.sim = Sim(pars=self.simulation_parameters, datafile=None)
        if not self.simulation_prognoses:
            self.simulation_prognoses = parameters.get_prognoses(
                self.simulation_parameters[
                    TestProperties.ParameterKeys.ProgressionKeys.
                    ProbabilityKeys.progression_by_age])
            pass

        self.sim['prognoses'] = self.simulation_prognoses
        if population_type:
            self.sim.update_pars(pop_type=population_type)
        self.sim.run(verbose=0)
        self.simulation_result = self.sim.to_json(tostring=False)
        if write_results_json or self.is_debugging:
            with open(self.expected_result_filename, 'w') as outfile:
                json.dump(self.simulation_result,
                          outfile,
                          indent=4,
                          sort_keys=True)
        pass
Esempio n. 2
0
    def set_simulation_prognosis_probability(self, params_dict):
        """
        Allows for testing prognoses probability as absolute rather than relative.
        NOTE: You can only call this once per test or you will overwrite your stuff.
        """
        ProbKeys = TestProperties.ParameterKeys.ProgressionKeys.ProbabilityKeys
        RelativeProbabilityKeys = ProbKeys.RelativeProbKeys
        supported_probabilities = [
            RelativeProbabilityKeys.inf_to_symptomatic_probability,
            RelativeProbabilityKeys.sym_to_severe_probability,
            RelativeProbabilityKeys.sev_to_critical_probability,
            RelativeProbabilityKeys.crt_to_death_probability
        ]
        if not self.simulation_parameters:
            self.set_simulation_parameters()
            pass

        if not self.simulation_prognoses:
            self.simulation_prognoses = parameters.get_prognoses(
                self.simulation_parameters[ProbKeys.progression_by_age])

        PrognosisKeys = ProbKeys.PrognosesListKeys
        for k in params_dict:
            prognosis_in_question = None
            expected_prob = params_dict[k]
            if k == RelativeProbabilityKeys.inf_to_symptomatic_probability:
                prognosis_in_question = PrognosisKeys.symptomatic_probabilities
            elif k == RelativeProbabilityKeys.sym_to_severe_probability:
                prognosis_in_question = PrognosisKeys.severe_probabilities
            elif k == RelativeProbabilityKeys.sev_to_critical_probability:
                prognosis_in_question = PrognosisKeys.critical_probabilities
            elif k == RelativeProbabilityKeys.crt_to_death_probability:
                prognosis_in_question = PrognosisKeys.death_probs
            else:
                raise KeyError(
                    f"Key {k} not found in {supported_probabilities}.")
            old_probs = self.simulation_prognoses[prognosis_in_question]
            self.simulation_prognoses[prognosis_in_question] = np.array(
                [expected_prob] * len(old_probs))
            pass
        pass
''' No prognoses by age'''
import numpy as np
import covasim as cv
import covasim.parameters as cvp

sim = cv.Sim({'prog_by_age': False, 'prognoses': cvp.get_prognoses(False)})
sim.run()
for key in ['symp_prob', 'severe_prob', 'crit_prob', 'death_prob', 'rel_sus']:
    assert (len(np.unique(sim.people[key])) == 1)

sim = cv.Sim({
    'prog_by_age': False,
    'prognoses': cvp.get_prognoses(False, cv.__version__)
})
sim.run()

for key in ['symp_prob', 'severe_prob', 'crit_prob', 'death_prob', 'rel_sus']:
    assert (len(np.unique(sim.people[key])) == 1)
Esempio n. 4
0
def make_people(sim,
                save_pop=False,
                popfile=None,
                die=True,
                reset=False,
                verbose=None,
                **kwargs):
    '''
    Make the actual people for the simulation. Usually called via sim.initialize(),
    not directly by the user.
    Args:
        sim (Sim): the simulation object
        save_pop (bool): whether to save the population to disk
        popfile (bool): if so, the filename to save to
        die (bool): whether or not to fail if synthetic populations are requested but not available
        reset (bool): whether to force population creation even if self.popdict/self.people exists
        verbose (bool): level of detail to print
        kwargs (dict): passed to make_randpop() or make_synthpop()
    Returns:
        people (People): people
    '''

    # Set inputs and defaults
    pop_size = int(sim['pop_size'])  # Shorten
    pop_type = sim['pop_type']  # Shorten
    if verbose is None:
        verbose = sim['verbose']
    if popfile is None:
        popfile = sim.popfile

    # Check which type of population to produce
    if pop_type == 'synthpops':
        if not cvreq.check_synthpops():
            errormsg = f'You have requested "{pop_type}" population, but synthpops is not available; please use random, clustered, or hybrid'
            if die:
                raise ValueError(errormsg)
            else:
                print(errormsg)
                pop_type = 'random'

        location = sim['location']
        if location:
            print(
                f'Warning: not setting ages or contacts for "{location}" since synthpops contacts are pre-generated'
            )

    # Actually create the population
    if sim.people and not reset:
        return sim.people  # If it's already there, just return
    elif sim.popdict and not reset:
        popdict = sim.popdict  # Use stored one
        sim.popdict = None  # Once loaded, remove
    else:
        # Create the population
        if pop_type in ['random', 'clustered', 'uni']:
            # calls make_randpop -- should have the argument chosen here
            popdict = make_randpop(sim, microstructure=pop_type)
        elif pop_type is None:
            errormsg = f'You have set pop_type=None. This is fine, but you must ensure sim.popdict exists before calling make_people().'
            raise ValueError(errormsg)
        else:
            errormsg = f'Population type "{pop_type}" not found; choices are random, clustered, hybrid, or synthpops'
            raise ValueError(errormsg)

    # Ensure prognoses are set
    if sim['prognoses'] is None:
        sim['prognoses'] = cvpars.get_prognoses(sim['prog_by_age'])

    # Actually create the people
    people = cvppl.People(
        sim.pars,
        uid=popdict['uid'],
        age=popdict['age'],
        sex=popdict['sex'],
        contacts=popdict['contacts'])  # List for storing the people

    average_age = sum(popdict['age'] / pop_size)
    sc.printv(
        f'Created {pop_size} people, average age {average_age:0.2f} years', 2,
        verbose)

    if save_pop:
        if popfile is None:
            errormsg = 'Please specify a file to save to using the popfile kwarg'
            raise FileNotFoundError(errormsg)
        else:
            filepath = sc.makefilepath(filename=popfile)
            cvm.save(filepath, people)
            if verbose:
                print(
                    f'Saved population of type "{pop_type}" with {pop_size:n} people to {filepath}'
                )

    return people