Beispiel #1
0
def get_target_outputs(start_date, end_date):
    targets = load_targets("covid_19", Region.VICTORIA)

    # Total Victorian notifications for each time point
    notification_times, notification_values = get_truncated_output(
        targets["notifications"], start_date, end_date)
    notification_values = [round(value) for value in notification_values]
    target_outputs = [{
        "output_key": "notifications",
        "years": notification_times,
        "values": notification_values,
        "loglikelihood_distri": "poisson",
    }]

    death_times, death_values = get_truncated_output(
        targets["infection_deaths"], start_date, end_date)
    target_outputs += [{
        "output_key": "infection_deaths",
        "years": death_times,
        "values": apply_moving_average(death_values, 7),
        "loglikelihood_distri": "poisson",
    }]

    hospitalisation_times, hospitalisation_values = get_truncated_output(
        targets["hospital_admissions"], start_date, end_date)
    target_outputs += [{
        "output_key": "hospital_admissions",
        "years": hospitalisation_times,
        "values": hospitalisation_values,
        "loglikelihood_distri": "poisson",
    }]

    icu_admission_times, icu_admission_values = get_truncated_output(
        targets["icu_admissions"], start_date, end_date)
    target_outputs += [{
        "output_key": "icu_admissions",
        "years": icu_admission_times,
        "values": icu_admission_values,
        "loglikelihood_distri": "poisson",
    }]

    # Smoothed notifications for all clusters
    for cluster in CLUSTERS:
        output_key = f"notifications_for_cluster_{cluster}"
        cluster_notification_targets = apply_moving_average(
            targets[output_key]["values"], period=4)
        dispersion_value = max(
            cluster_notification_targets) * DISPERSION_TARGET_RATIO
        target_outputs += [{
            "output_key": output_key,
            "years": targets[output_key]["times"],
            "values": cluster_notification_targets,
            "loglikelihood_distri": "normal",
            "sd": dispersion_value,
        }]

    return target_outputs
Beispiel #2
0
def plot_multicluster_mobility(
    plotter: StreamlitPlotter,
    calib_dir_path: str,
    mcmc_tables: List[pd.DataFrame],
    mcmc_params: List[pd.DataFrame],
    targets: dict,
    app_name: str,
    region: str,
):

    app = covid_19.app.get_region("victoria")
    params = app.params["default"]

    all_cluster_mobility_values = {}
    fig, axes, max_dims, n_rows, n_cols, _ = plotter.get_figure()

    for i_region in Region.VICTORIA_METRO + Region.VICTORIA_RURAL:
        google_mobility_values, google_mobility_days = get_mobility_data(
            params["country"]["iso3"],
            i_region.replace("-", "_").upper(), BASE_DATE,
            params["mobility"]["google_mobility_locations"])

        all_cluster_mobility_values[i_region] = google_mobility_values
    for i_region in Region.VICTORIA_METRO:
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["work"], 7),
                  color="k",
                  alpha=0.5)
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["other_locations"],
                      7),
                  color="g",
                  alpha=0.5)
    for i_region in Region.VICTORIA_RURAL:
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["work"], 7),
                  color="b",
                  alpha=0.5)
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["other_locations"],
                      7),
                  color="brown",
                  alpha=0.5)
    axes.set_xlim(left=STANDARD_X_LIMITS[0], right=STANDARD_X_LIMITS[1])
    axes.set_ylim(top=1.)
    change_xaxis_to_date(axes, REF_DATE, rotation=0)

    plotter.save_figure(fig,
                        filename=f"multi_cluster_mobility",
                        title_text="Google mobility")
Beispiel #3
0
def get_vic_testing_numbers():
    """
    Returns 7-day moving average of number of tests administered in Victoria.
    """
    input_db = get_input_db()
    df = input_db.query("covid_au",
                        columns=["date", "tests"],
                        conditions={"state_abbrev": "VIC"})
    date_str_to_int = lambda s: (datetime.strptime(s, "%Y-%m-%d") -
                                 COVID_BASE_DATETIME).days
    test_dates = df.date.apply(date_str_to_int).to_numpy()
    test_values = df.tests.to_numpy()
    epsilon = 1e-6  # A really tiny number to avoid having any zeros
    avg_vals = np.array(apply_moving_average(test_values, 7)) + epsilon
    return test_dates, avg_vals
Beispiel #4
0
def get_phl_subregion_testing_numbers(region):
    """
    Returns 7-day moving average of number of tests administered in Philippines & sub regions.
    """

    input_db = get_input_db()
    df = input_db.query(
        "covid_phl",
        columns=["date_index", "daily_output_unique_individuals"],
        conditions={"facility_name": region},
    )
    test_dates = df.date_index.to_numpy()
    test_values = df.daily_output_unique_individuals.to_numpy()
    epsilon = 1e-6  # A really tiny number to avoid having any zeros
    avg_vals = np.array(apply_moving_average(test_values, 7)) + epsilon
    return test_dates, avg_vals
Beispiel #5
0
def find_cdr_function_from_test_data(
    assumed_tests_parameter,
    assumed_cdr_parameter,
    smoothing_period,
    country_iso3,
    total_pops,
    subregion=None,
):

    # Get the appropriate testing data
    if country_iso3 == "AUS":
        test_dates, test_values = get_dhhs_testing_numbers()
    elif country_iso3 == "PHL":
        phl_region = subregion.lower() if subregion else "philippines"
        test_dates, test_values = get_phl_subregion_testing_numbers(phl_region)
    elif subregion == "Sabah":
        test_dates, test_values = get_international_testing_numbers(
            country_iso3)
    else:
        test_dates, test_values = get_international_testing_numbers(
            country_iso3)

    # Convert test numbers to per capita testing rates
    per_capita_tests = [i_tests / sum(total_pops) for i_tests in test_values]

    # Smooth the testing data if requested
    smoothed_per_capita_tests = (apply_moving_average(per_capita_tests,
                                                      smoothing_period)
                                 if smoothing_period > 1 else per_capita_tests)

    # Calculate CDRs and the resulting CDR function over time
    cdr_from_tests_func = create_cdr_function(assumed_tests_parameter,
                                              assumed_cdr_parameter)
    return scale_up_function(
        test_dates,
        [
            cdr_from_tests_func(i_test_rate)
            for i_test_rate in smoothed_per_capita_tests
        ],
        smoothness=0.2,
        method=4,
        bound_low=0.0,
    )
Beispiel #6
0
def get_mobility_funcs(
    country: Country,
    region: str,
    mixing: Dict[str, MixingLocation],
    google_mobility_locations: List[str],
    npi_effectiveness_params: Dict[str, float],
    square_mobility_effect: bool,
    smooth_google_data: bool,
) -> Dict[str, Callable[[float], float]]:
    """
    Loads google mobility data, combines it with user requested timeseries data
    and then returns a mobility function for each location.
    """
    google_mobility_values, google_mobility_days = get_mobility_data(
        country.iso3, region, BASE_DATETIME, google_mobility_locations)
    if smooth_google_data:
        for loc in google_mobility_values:
            google_mobility_values[loc] = apply_moving_average(
                google_mobility_values[loc], 7)

    # Build mixing data timeseries
    mixing = update_mixing_data(
        {k: v.dict()
         for k, v in mixing.items()},
        npi_effectiveness_params,
        google_mobility_values,
        google_mobility_days,
    )

    # Build the time variant location-specific macrodistancing adjustment functions from mixing timeseries
    mobility_funcs = {}
    for location, timeseries in mixing.items():
        if square_mobility_effect:
            loc_vals = [v**2 for v in timeseries["values"]]
        else:
            loc_vals = timeseries["values"]
        mobility_funcs[location] = scale_up_function(timeseries["times"],
                                                     loc_vals,
                                                     method=4)

    return mobility_funcs
Beispiel #7
0
def get_dhhs_testing_numbers(cluster: str = None):
    """
    Returns 7-day moving average of number of tests administered in Victoria.
    """
    input_db = get_input_db()

    if cluster is None:
        df = input_db.query("covid_dhhs_test", columns=["date", "test"])
        df = df.groupby("date", as_index=False).sum()
    else:
        df = input_db.query("covid_dhhs_test",
                            columns=["date", "test"],
                            conditions={"cluster_name": cluster})
    date_str_to_int = lambda s: (datetime.strptime(s, "%Y-%m-%d") -
                                 COVID_BASE_DATETIME).days

    test_dates = (pd.to_datetime(df.date) -
                  pd.datetime(2019, 12, 31)).dt.days.to_numpy()
    test_values = df.test.to_numpy()
    epsilon = 1e-6  # A really tiny number to avoid having any zeros
    avg_vals = np.array(apply_moving_average(test_values, 7)) + epsilon
    return test_dates, avg_vals