Пример #1
0
def get_nr_of_contacts():
    df = get_contacts_for_country()
    df = df.drop(columns='place_type').groupby('participant_age').sum()
    s = df.sum(axis=1)
    idx = list(s.index.map(lambda x: tuple([int(y) for y in x.split('-')])))
    s.index = idx
    return s.sort_index()
Пример #2
0
def get_contacts_per_day():
    df = get_contacts_for_country()
    df = pd.melt(df, id_vars=['place_type', 'participant_age'], var_name='contact_age', value_name='contacts')
    df['participant_age'] = df['participant_age'].map(lambda x: tuple([int(y) for y in x.split('-')]))
    df['contact_age'] = df['contact_age'].map(lambda x: tuple([int(y) for y in x.split('-')]))

    return df
Пример #3
0
def get_contacts_per_day():
    df = get_contacts_for_country()
    df = pd.melt(df,
                 id_vars=['place_type', 'participant_age'],
                 var_name='contact_age',
                 value_name='contacts')
    df['participant_age'] = df['participant_age'].map(
        lambda x: tuple([int(y) for y in x.split('-')]))
    df['contact_age'] = df['contact_age'].map(
        lambda x: tuple([int(y) for y in x.split('-')]))

    df = pd.DataFrame(
        [(t.place_type, p, t.contact_age, t.contacts) for t in df.itertuples()
         for p in range(t.participant_age[0], t.participant_age[1] + 1)],
        columns=['place_type', 'participant_age', 'contact_age', 'contacts'])
    # df = pd.DataFrame(
    #    [(t.place_type, t.participant_age, c, t.contacts / (t.contact_age[1] - t.contact_age[0] + 1)) for t in df.itertuples() for c in range(t.contact_age[0], t.contact_age[1] + 1)],
    #    columns=['place_type', 'participant_age', 'contact_age', 'contacts']
    # )

    return df
Пример #4
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
Пример #5
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