Ejemplo n.º 1
0
 def resolve_active_events(query, info):
     interventions = get_active_interventions()
     out = []
     for idx, iv in enumerate(interventions):
         obj = iv_to_graphql_obj(iv, obj_id=idx)
         out.append(obj)
     return out
Ejemplo n.º 2
0
 def resolve_active_events(query, info):
     interventions = sorted(get_active_interventions(),
                            key=lambda x: x.date)
     out = []
     for idx, iv in enumerate(interventions):
         obj = iv_to_graphql_obj(iv, idx)
         out.append(obj)
     return out
Ejemplo n.º 3
0
    def mutate(root, info, event_id):
        iv_objs = get_active_interventions()

        for iv in iv_objs:
            if iv.id and event_id == iv.id:
                break

        iv_tuple = iv.make_iv_tuple()

        iv_id = int(event_id)
        iv_list = list(get_variable('interventions'))
        for iv in iv_list:
            if iv == iv_tuple:
                break
        else:
            raise GraphQLError('invalid intervention ID')
        iv_list.remove(iv)
        set_variable('interventions', iv_list)
        return dict(ok=True)
Ejemplo n.º 4
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