Ejemplo n.º 1
0
def sample_model_parameters(what, age, severity=None, variables=None):
    age_to_group = make_age_groups()
    max_age = variables['max_age']
    age_structure = pd.Series([1] * (max_age + 1), index=range(0, max_age + 1))
    age_groups = list(np.unique(age_to_group))
    pop_params = dict(age_structure=age_structure,
                      contacts_per_day=get_contacts_per_day(),
                      age_groups=dict(labels=age_groups,
                                      age_indices=[
                                          age_groups.index(x)
                                          for x in age_to_group
                                      ]))
    hc_params = dict(hospital_beds=0, icu_units=0)
    disease_params = create_disease_params(variables)
    context = model.Context(
        population_params=pop_params,
        healthcare_params=hc_params,
        disease_params=disease_params,
        start_date='2020-01-01',
    )

    if variables['sample_limit_mobility'] != 0:
        context.apply_intervention('limit-mobility',
                                   variables['sample_limit_mobility'])

    samples = context.sample(what, age, severity)

    if what == 'infectiousness':
        s = pd.Series(index=samples['day'], data=samples['val'])
        s = s[s != 0].sort_index()
        return s

    s = pd.Series(samples)
    c = s.value_counts().sort_index()
    if what == 'symptom_severity':
        c.index = c.index.map(model.SEVERITY_TO_STR)

    if True:
        c /= c.sum()
        for a, b in c.iteritems():
            # print('    (%d, %.2f),' % (a, b))
            print('    (%s, %.2f),' % (a, b))
        import matplotlib.pyplot as plt
        fig = plt.figure()
        print('Mean: %f, median: %f' % (s.mean(), s.median()))
        plt.plot(c)
        plt.show()

    return c
Ejemplo n.º 2
0
def sample_model_parameters(what, age, severity=None, variables=None):
    avg_contacts_per_day = get_contacts_for_country()
    age_counts = [1]
    pop = model.Population(age_counts, list(avg_contacts_per_day.items()))
    hc = model.HealthcareSystem(
        beds=0,
        icu_units=0,
        p_detected_anyway=variables['p_detected_anyway'] / 100)
    disease = create_disease(variables)
    context = model.Context(pop, hc, disease, start_date='2020-01-01')
    if variables['sample_limit_mobility'] != 0:
        context.apply_intervention('limit-mobility',
                                   variables['sample_limit_mobility'])

    samples = context.sample(what, age, severity)

    if what == 'infectiousness':
        s = pd.Series(index=samples['day'], data=samples['val'])
        s = s[s != 0].sort_index()
        return s

    s = pd.Series(samples)
    c = s.value_counts().sort_index()
    if what == 'symptom_severity':
        c.index = c.index.map(model.SEVERITY_TO_STR)

    if False:
        # c /= c.sum()
        for a, b in c.iteritems():
            print('    (%d, %.2f),' % (a, b))
        import matplotlib.pyplot as plt
        fig = plt.figure()
        print('Mean: %f, median: %f' % (s.mean(), s.median()))
        plt.plot(c)
        plt.show()

    return c
Ejemplo n.º 3
0
def simulate_individuals(variables,
                         step_callback=None,
                         callback_day_interval=1):
    pc = PerfCounter()

    age_structure = get_population_for_area().sum(axis=1)
    ipc = get_initial_population_condition()

    age_to_group = make_age_groups()

    age_groups = list(np.unique(age_to_group))
    pop_params = dict(
        age_structure=age_structure,
        contacts_per_day=get_contacts_per_day(),
        initial_population_condition=ipc,
        age_groups=dict(
            labels=age_groups,
            age_indices=[age_groups.index(x) for x in age_to_group]),
        imported_infection_ages=variables['imported_infection_ages'],
    )

    df = get_contacts_per_day()

    hc_params = dict(hospital_beds=variables['hospital_beds'],
                     icu_units=variables['icu_units'])
    disease_params = create_disease_params(variables)
    context = model.Context(population_params=pop_params,
                            healthcare_params=hc_params,
                            disease_params=disease_params,
                            start_date=variables['start_date'],
                            random_seed=variables['random_seed'])
    start_date = date.fromisoformat(variables['start_date'])

    ivs = get_active_interventions(variables)
    for iv in ivs:
        context.add_intervention(iv)

    pc.measure()

    days = variables['simulation_days']

    date_index = pd.date_range(start_date, periods=days)
    df = pd.DataFrame(
        columns=POP_ATTRS + STATE_ATTRS + EXPOSURES_ATTRS +
        ['us_per_infected'],
        index=date_index,
    )

    ag_array = np.empty((days, len(POP_ATTRS), len(age_groups)), dtype='i')

    for day in range(days):
        s = context.generate_state()

        today_date = (start_date + timedelta(days=day)).isoformat()

        for idx, attr in enumerate(POP_ATTRS):
            ag_array[day, idx, :] = s[attr]

        rec = {attr: s[attr].sum() for attr in POP_ATTRS}

        for state_attr in STATE_ATTRS:
            rec[state_attr] = s[state_attr]

        for place, nr in s['daily_contacts'].items():
            key = 'exposures_%s' % place
            assert key in df.columns
            rec[key] = nr

        rec['us_per_infected'] = pc.measure(
        ) * 1000 / rec['infected'] if rec['infected'] else 0

        if False:
            st = '\n%-15s' % today_date
            for ag in age_groups:
                st += '%8s' % ag
            print(st)
            for attr in ('all_detected', 'in_ward', 'dead', 'cum_icu'):
                st = '%-15s' % attr
                t = s[attr].sum()
                for val in s[attr]:
                    st += '%8.2f' % ((val / t) * 100)
                print(st)

        if False:
            dead = context.get_population_stats('dead')
            all_infected = context.get_population_stats('all_infected')
            detected = context.get_population_stats('all_detected')

            age_groups = pd.interval_range(0, 80, freq=10, closed='left')
            age_groups = age_groups.append(
                pd.Index([pd.Interval(80, 100, closed='left')]))

            s = pd.Series(dead)
            dead_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()
            dead_by_age.name = 'dead'

            s = pd.Series(all_infected)
            infected_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()
            infected_by_age.scenario_name = 'infected'

            s = pd.Series(detected)
            detected_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()
            detected_by_age.name = 'detected'

            print(dead_by_age / sum(dead_by_age) * 100)
            print(infected_by_age / sum(infected_by_age) * 100)
            print(detected_by_age / sum(detected_by_age) * 100)

            #zdf = pd.DataFrame(dead_by_age)
            #zdf['infected'] = infected_by_age
            #zdf['ifr'] = zdf.dead.divide(zdf.infected.replace(0, np.inf)) * 100
            #print(zdf)

        df.loc[today_date] = rec

        by_age_group = POP_ATTRS

        if step_callback is not None and (day % callback_day_interval == 0
                                          or day == range(days) - 1):
            ret = step_callback(df)
            if not ret:
                raise ExecutionInterrupted()

        context.iterate()
        if False:
            import cProfile
            import pstats
            cProfile.runctx("context.iterate()", globals(), locals(),
                            "profile.prof")
            s = pstats.Stats("profile.prof")
            s.strip_dirs().sort_stats("cumtime").print_stats()

    arr = ag_array.flatten()
    adf = pd.DataFrame(arr,
                       index=pd.MultiIndex.from_product(
                           [date_index, POP_ATTRS, age_groups],
                           names=['date', 'attr', 'age_group']),
                       columns=['pop'])
    adf = adf.unstack('attr').unstack('age_group')
    adf.columns = adf.columns.droplevel()

    return df, adf
Ejemplo n.º 4
0
def simulate_individuals(variables, step_callback=None):
    pc = PerfCounter()

    df = get_population_for_area().sum(axis=1)
    ages = df.index.values
    counts = df.values
    avg_contacts_per_day = get_contacts_for_country()
    hc_cap = (variables['hospital_beds'], variables['icu_units'])

    max_age = max(ages)
    age_counts = np.array(np.zeros(max_age + 1, dtype=np.int32))
    for age, count in zip(ages, counts):
        age_counts[age] = count

    pop = model.Population(age_counts, list(avg_contacts_per_day.items()))
    hc = model.HealthcareSystem(
        beds=hc_cap[0],
        icu_units=hc_cap[1],
        p_detected_anyway=variables['p_detected_anyway'] / 100)
    disease = create_disease(variables)
    context = model.Context(pop,
                            hc,
                            disease,
                            start_date=variables['start_date'],
                            random_seed=variables['random_seed'])
    start_date = date.fromisoformat(variables['start_date'])

    for iv in variables['interventions']:
        d = (date.fromisoformat(iv[1]) - start_date).days
        if len(iv) > 2:
            val = iv[2]
        else:
            val = 0
        context.add_intervention(d, iv[0], val)
    pc.measure()

    days = variables['simulation_days']

    df = pd.DataFrame(columns=POP_ATTRS + STATE_ATTRS + ['us_per_infected'],
                      index=pd.date_range(start_date, periods=days))

    for day in range(days):
        s = context.generate_state()

        rec = {attr: sum(s[attr]) for attr in POP_ATTRS}
        for state_attr in STATE_ATTRS:
            rec[state_attr] = s[state_attr]

        rec['us_per_infected'] = pc.measure(
        ) * 1000 / rec['infected'] if rec['infected'] else 0
        """
        dead = context.get_population_stats('dead')
        all_infected = context.get_population_stats('all_infected')
        age_groups = pd.interval_range(0, 100, freq=10, closed='left')
        s = pd.Series(dead)
        dead_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()
        dead_by_age.name = 'dead'
        s = pd.Series(all_infected)
        infected_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()

        zdf = pd.DataFrame(dead_by_age)
        zdf['infected'] = infected_by_age
        zdf['ifr'] = zdf.dead.divide(zdf.infected.replace(0, np.inf)) * 100
        print(zdf)
        """

        d = start_date + timedelta(days=day)
        df.loc[d] = rec

        if step_callback is not None:
            ret = step_callback(df)
            if not ret:
                raise ExecutionInterrupted()

        context.iterate()
        if False:
            import cProfile
            import pstats
            cProfile.runctx("context.iterate()", globals(), locals(),
                            "profile.prof")
            s = pstats.Stats("profile.prof")
            s.strip_dirs().sort_stats("time").print_stats()

    return df
Ejemplo n.º 5
0
def simulate_individuals(variables, step_callback=None):
    pc = PerfCounter()

    age_structure = get_population_for_area().sum(axis=1)
    pop_params = dict(
        age_structure=age_structure,
        contacts_per_day=get_contacts_per_day(),
    )

    hc_params = dict(hospital_beds=variables['hospital_beds'], icu_units=variables['icu_units'])
    disease_params = create_disease_params(variables)
    context = model.Context(
        population_params=pop_params,
        healthcare_params=hc_params,
        disease_params=disease_params,
        start_date=variables['start_date'],
        random_seed=variables['random_seed']
    )
    start_date = date.fromisoformat(variables['start_date'])

    for iv in variables['interventions']:
        d = (date.fromisoformat(iv[1]) - start_date).days
        if len(iv) > 2:
            val = iv[2]
        else:
            val = 0
        context.add_intervention(d, iv[0], val)
    pc.measure()

    days = variables['simulation_days']

    df = pd.DataFrame(
        columns=POP_ATTRS + STATE_ATTRS + ['us_per_infected'],
        index=pd.date_range(start_date, periods=days)
    )

    for day in range(days):
        s = context.generate_state()

        rec = {attr: sum(s[attr]) for attr in POP_ATTRS}
        for state_attr in STATE_ATTRS:
            rec[state_attr] = s[state_attr]

        rec['us_per_infected'] = pc.measure() * 1000 / rec['infected'] if rec['infected'] else 0

        if False:
            dead = context.get_population_stats('dead')
            all_infected = context.get_population_stats('all_infected')
            age_groups = pd.interval_range(0, 100, freq=10, closed='left')
            s = pd.Series(dead)
            dead_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()
            dead_by_age.name = 'dead'
            s = pd.Series(all_infected)
            infected_by_age = s.groupby(pd.cut(s.index, age_groups)).sum()
            print(infected_by_age)

            zdf = pd.DataFrame(dead_by_age)
            zdf['infected'] = infected_by_age
            zdf['ifr'] = zdf.dead.divide(zdf.infected.replace(0, np.inf)) * 100
            #print(zdf)

        d = start_date + timedelta(days=day)
        df.loc[d] = rec

        if step_callback is not None:
            ret = step_callback(df)
            if not ret:
                raise ExecutionInterrupted()

        context.iterate()
        if False:
            import cProfile
            import pstats
            cProfile.runctx("context.iterate()", globals(), locals(), "profile.prof")
            s = pstats.Stats("profile.prof")
            s.strip_dirs().sort_stats("time").print_stats()

    return df