|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | + |
| 4 | + |
| 5 | +def prep_samples_for_cohort_grouping(*, df_samples, area_by, period_by): |
| 6 | + # Take a copy, as we will modify the dataframe. |
| 7 | + df_samples = df_samples.copy() |
| 8 | + |
| 9 | + # Fix "intermediate" or "unassigned" taxon values - we only want to build |
| 10 | + # cohorts with clean taxon calls, so we set other values to None. |
| 11 | + loc_intermediate_taxon = ( |
| 12 | + df_samples["taxon"].str.startswith("intermediate").fillna(False) |
| 13 | + ) |
| 14 | + df_samples.loc[loc_intermediate_taxon, "taxon"] = None |
| 15 | + loc_unassigned_taxon = ( |
| 16 | + df_samples["taxon"].str.startswith("unassigned").fillna(False) |
| 17 | + ) |
| 18 | + df_samples.loc[loc_unassigned_taxon, "taxon"] = None |
| 19 | + |
| 20 | + # Add period column. |
| 21 | + if period_by == "year": |
| 22 | + make_period = _make_sample_period_year |
| 23 | + elif period_by == "quarter": |
| 24 | + make_period = _make_sample_period_quarter |
| 25 | + elif period_by == "month": |
| 26 | + make_period = _make_sample_period_month |
| 27 | + else: # pragma: no cover |
| 28 | + raise ValueError( |
| 29 | + f"Value for period_by parameter must be one of 'year', 'quarter', 'month'; found {period_by!r}." |
| 30 | + ) |
| 31 | + sample_period = df_samples.apply(make_period, axis="columns") |
| 32 | + df_samples["period"] = sample_period |
| 33 | + |
| 34 | + # Add area column for consistent output. |
| 35 | + df_samples["area"] = df_samples[area_by] |
| 36 | + |
| 37 | + return df_samples |
| 38 | + |
| 39 | + |
| 40 | +def build_cohorts_from_sample_grouping(*, group_samples_by_cohort, min_cohort_size): |
| 41 | + # Build cohorts dataframe. |
| 42 | + df_cohorts = group_samples_by_cohort.agg( |
| 43 | + size=("sample_id", len), |
| 44 | + lat_mean=("latitude", "mean"), |
| 45 | + lat_max=("latitude", "max"), |
| 46 | + lat_min=("latitude", "min"), |
| 47 | + lon_mean=("longitude", "mean"), |
| 48 | + lon_max=("longitude", "max"), |
| 49 | + lon_min=("longitude", "min"), |
| 50 | + ) |
| 51 | + # Reset index so that the index fields are included as columns. |
| 52 | + df_cohorts = df_cohorts.reset_index() |
| 53 | + |
| 54 | + # Add cohort helper variables. |
| 55 | + cohort_period_start = df_cohorts["period"].apply(lambda v: v.start_time) |
| 56 | + cohort_period_end = df_cohorts["period"].apply(lambda v: v.end_time) |
| 57 | + df_cohorts["period_start"] = cohort_period_start |
| 58 | + df_cohorts["period_end"] = cohort_period_end |
| 59 | + # Create a label that is similar to the cohort metadata, |
| 60 | + # although this won't be perfect. |
| 61 | + df_cohorts["label"] = df_cohorts.apply( |
| 62 | + lambda v: f"{v.area}_{v.taxon[:4]}_{v.period}", axis="columns" |
| 63 | + ) |
| 64 | + |
| 65 | + # Apply minimum cohort size. |
| 66 | + df_cohorts = df_cohorts.query(f"size >= {min_cohort_size}").reset_index(drop=True) |
| 67 | + |
| 68 | + # Early check for no cohorts. |
| 69 | + if len(df_cohorts) == 0: |
| 70 | + raise ValueError( |
| 71 | + "No cohorts available for the given sample selection parameters and minimum cohort size." |
| 72 | + ) |
| 73 | + |
| 74 | + return df_cohorts |
| 75 | + |
| 76 | + |
| 77 | +def add_frequency_ci(*, ds, ci_method): |
| 78 | + from statsmodels.stats.proportion import proportion_confint # type: ignore |
| 79 | + |
| 80 | + if ci_method is not None: |
| 81 | + count = ds["event_count"].values |
| 82 | + nobs = ds["event_nobs"].values |
| 83 | + with np.errstate(divide="ignore", invalid="ignore"): |
| 84 | + frq_ci_low, frq_ci_upp = proportion_confint( |
| 85 | + count=count, nobs=nobs, method=ci_method |
| 86 | + ) |
| 87 | + ds["event_frequency_ci_low"] = ("variants", "cohorts"), frq_ci_low |
| 88 | + ds["event_frequency_ci_upp"] = ("variants", "cohorts"), frq_ci_upp |
| 89 | + |
| 90 | + |
| 91 | +def _make_sample_period_month(row): |
| 92 | + year = row.year |
| 93 | + month = row.month |
| 94 | + if year > 0 and month > 0: |
| 95 | + return pd.Period(freq="M", year=year, month=month) |
| 96 | + else: |
| 97 | + return pd.NaT |
| 98 | + |
| 99 | + |
| 100 | +def _make_sample_period_quarter(row): |
| 101 | + year = row.year |
| 102 | + month = row.month |
| 103 | + if year > 0 and month > 0: |
| 104 | + return pd.Period(freq="Q", year=year, month=month) |
| 105 | + else: |
| 106 | + return pd.NaT |
| 107 | + |
| 108 | + |
| 109 | +def _make_sample_period_year(row): |
| 110 | + year = row.year |
| 111 | + if year > 0: |
| 112 | + return pd.Period(freq="Y", year=year) |
| 113 | + else: |
| 114 | + return pd.NaT |
0 commit comments