Skip to content
generated from CDCgov/template

A Python package for common pre- and post-processing operations done by CFA Predict for short term forecasting, nowcasting, and scenario modeling.

License

Notifications You must be signed in to change notification settings

CDCgov/forecasttools-py

Repository files navigation

CFA Forecast Tools (Python)

Summary of forecasttools-py:

  • A Python package.
  • Primarily supports the Short Term Forecast’s team.
  • Intended to support wider Real Time Monitoring branch operations.
  • Has tools for pre- and post-processing.
    • Conversion of az.InferenceData forecast to Hubverse format.
    • Addition of time and or dates to az.InferenceData.

Notes:

  • This repository is a WORK IN PROGRESS.
  • For the R version of this toolkit, see forecasttools.
  • For CDC project expected to use forecasttools-py, see pyrenew-hew.

A Tentative Utilities Diagram

%%{init: {"theme": "neutral", "themeVariables": { "fontFamily": "Iosevka", "fontSize": "25px", "lineColor": "#808b96", "arrowheadColor": "#808b96", "edgeStrokeWidth": "10px", "arrowheadLength": "20px"}}}%%
flowchart TD
    A1[COVID-19 Data _from forecasttools_] --> A4[NumPyro Model]
    A2[Influenza Data _from forecasttools_] --> A4[NumPyro Model]
    A3[External Dataset] --> A4[NumPyro Model]
    A4[NumPyro Model] -->|_arviz.from_numpyro_| A5[Forecast As InferenceData Object wo/ Dates]
    A5[Forecast As InferenceData Object wo/ Dates] -->|_Add Dates To InferenceData_ - done| A6[InferenceData Object w/ Dates]
    A6[InferenceData Object w/ Dates] -->|_Convert To Tidy-Like Dataframe_ - done| A7[Polars Forecast Dataframe w/ Draws]
    A7[Polars Forecast Dataframe w/ Draws] -->|_Convert To Hubverse Formatted Dataframe_ - done| A8[FluSight Submission Dataframe]
    A7[Polars Forecast Dataframe w/ Draws] -->|_Convert To ScoringUtils Formatted Dataframe_ - in progress| A9[ScoringUtils DataFrame]
    A7[Polars Forecast Dataframe w/ Draws] -->|_Save_| A10[Parquet File]
    A8[FluSight Submission Dataframe] -->|_Save_| A11[Parquet File]
    A9[ScoringUtils DataFrame] -->|_Save_| A12[Parquet File]
    A8[FluSight Submission Dataframe] -->|_Convert To ScoringUtils Formatted Dataframe_ - in progress| A9[ScoringUtils DataFrame]
    A12[Parquet File] -->|_Get scores in R_| A13[Forecast Scores]
    A11[Parquet File] -->|_Model Forecast Hypothesis Testing_| A14[Model Comparison Report]

    B1[Pulled Parquet Hubverse Submissions] -->|_Model Forecast Hypothesis Testing_| A14[Model Comparison Report]

    linkStyle default stroke: #808b96
    linkStyle default stroke-width: 2.0px
Loading

Installation

Install forecasttools-py via:

pip3 install git+https://github.com/CDCgov/forecasttools-py@main

Vignettes

Coming soon as webpages, once Issue 26 is completed.

Datasets

Within forecasttools-py, one finds several packaged datasets. These datasets can aid with experimentation; some are directly necessary to other utilities provided by forecasttools-py.

import forecasttools

Summary of datasets:

  • forecasttools.location_table
    • A Polars dataframe of location abbreviations, codes, and names for Hubverse formatted forecast submissions.
  • forecasttools.example_flusight_submission
    • An example Hubverse formatted influenza forecast submission (as a Polars dataframe) submitted to the FluSight Hub.
  • forecasttools.nhsn_hosp_COVID
    • A Polars dataframe of NHSN COVID hospital admissions data.
  • forecasttools.nhsn_hosp_flu
    • A Polars dataframe of NHSN influenza hospital admissions data.
  • forecasttools.nhsn_flu_forecast_wo_dates
    • An az.InferenceData object containing a forecast made using NSHN influenza data for Texas.
  • forecasttools.nhsn_flu_forecast_w_dates
    • An modified (with dates as coordinates) az.InferenceData object containing a forecast made using NSHN influenza data for Texas.

See below for more information on the datasets.

Location Table

The location table contains abbreviations, codes, extended names, and populations for the jurisdictions of the United States that the FluSight and COVID forecasting hubs require users to generate forecasts. The US population value is the sum of all available states and territories (some territories have null population values).

The location table is stored in forecasttools-py as a polars dataframe and is accessed via:

loc_table = forecasttools.location_table
print(loc_table)
shape: (58, 5)
┌───────────────┬────────────┬─────────────────────────────┬────────────┬──────────┐
│ location_code ┆ short_name ┆ long_name                   ┆ population ┆ is_state │
│ ---           ┆ ---        ┆ ---                         ┆ ---        ┆ ---      │
│ str           ┆ str        ┆ str                         ┆ i64        ┆ bool     │
╞═══════════════╪════════════╪═════════════════════════════╪════════════╪══════════╡
│ US            ┆ US         ┆ United States               ┆ 334735155  ┆ false    │
│ 01            ┆ AL         ┆ Alabama                     ┆ 5024279    ┆ true     │
│ 02            ┆ AK         ┆ Alaska                      ┆ 733391     ┆ true     │
│ 04            ┆ AZ         ┆ Arizona                     ┆ 7151502    ┆ true     │
│ 05            ┆ AR         ┆ Arkansas                    ┆ 3011524    ┆ true     │
│ …             ┆ …          ┆ …                           ┆ …          ┆ …        │
│ 66            ┆ GU         ┆ Guam                        ┆ null       ┆ false    │
│ 69            ┆ MP         ┆ Northern Mariana Islands    ┆ null       ┆ false    │
│ 72            ┆ PR         ┆ Puerto Rico                 ┆ 3285874    ┆ false    │
│ 74            ┆ UM         ┆ U.S. Minor Outlying Islands ┆ null       ┆ false    │
│ 78            ┆ VI         ┆ U.S. Virgin Islands         ┆ null       ┆ false    │
└───────────────┴────────────┴─────────────────────────────┴────────────┴──────────┘

Using ./forecasttools/data.py, the location table was created by running the following:

make_census_dataset(
    file_save_path=os.path.join(
        os.getcwd(),
        "location_table.csv"
    ),
)

United States

Calling forecasttools.united_states simply returns a Python list that contains the 50 United States (United States itself is not included). While quite simple, it’s to have this capability available in fewer steps than through calling and selecting values from location_table.

united_states = forecasttools.united_states
print(united_states)
['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']

Example FluSight Hub Submission

The example FluSight submission comes from the following 2023-24 submission.

The example FluSight submission is stored in forecasttools-py as a polars dataframe and is accessed via:

submission = forecasttools.example_flusight_submission
print(submission)
shape: (4_876, 8)
┌────────────┬────────────┬─────────┬────────────┬──────────┬────────────┬────────────┬────────────┐
│ reference_ ┆ target     ┆ horizon ┆ target_end ┆ location ┆ output_typ ┆ output_typ ┆ value      │
│ date       ┆ ---        ┆ ---     ┆ _date      ┆ ---      ┆ e          ┆ e_id       ┆ ---        │
│ ---        ┆ str        ┆ i64     ┆ ---        ┆ str      ┆ ---        ┆ ---        ┆ f64        │
│ str        ┆            ┆         ┆ str        ┆          ┆ str        ┆ f64        ┆            │
╞════════════╪════════════╪═════════╪════════════╪══════════╪════════════╪════════════╪════════════╡
│ 2023-10-14 ┆ wk inc flu ┆ -1      ┆ 2023-10-07 ┆ 01       ┆ quantile   ┆ 0.01       ┆ 7.670286   │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆            │
│ 2023-10-14 ┆ wk inc flu ┆ -1      ┆ 2023-10-07 ┆ 01       ┆ quantile   ┆ 0.025      ┆ 9.968043   │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆            │
│ 2023-10-14 ┆ wk inc flu ┆ -1      ┆ 2023-10-07 ┆ 01       ┆ quantile   ┆ 0.05       ┆ 12.022354  │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆            │
│ 2023-10-14 ┆ wk inc flu ┆ -1      ┆ 2023-10-07 ┆ 01       ┆ quantile   ┆ 0.1        ┆ 14.497646  │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆            │
│ 2023-10-14 ┆ wk inc flu ┆ -1      ┆ 2023-10-07 ┆ 01       ┆ quantile   ┆ 0.15       ┆ 16.119813  │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆            │
│ …          ┆ …          ┆ …       ┆ …          ┆ …        ┆ …          ┆ …          ┆ …          │
│ 2023-10-14 ┆ wk inc flu ┆ 2       ┆ 2023-10-28 ┆ US       ┆ quantile   ┆ 0.85       ┆ 2451.87489 │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆ 9          │
│ 2023-10-14 ┆ wk inc flu ┆ 2       ┆ 2023-10-28 ┆ US       ┆ quantile   ┆ 0.9        ┆ 2806.92858 │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆ 8          │
│ 2023-10-14 ┆ wk inc flu ┆ 2       ┆ 2023-10-28 ┆ US       ┆ quantile   ┆ 0.95       ┆ 3383.74799 │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆            │
│ 2023-10-14 ┆ wk inc flu ┆ 2       ┆ 2023-10-28 ┆ US       ┆ quantile   ┆ 0.975      ┆ 3940.39253 │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆ 6          │
│ 2023-10-14 ┆ wk inc flu ┆ 2       ┆ 2023-10-28 ┆ US       ┆ quantile   ┆ 0.99       ┆ 4761.75738 │
│            ┆ hosp       ┆         ┆            ┆          ┆            ┆            ┆ 5          │
└────────────┴────────────┴─────────┴────────────┴──────────┴────────────┴────────────┴────────────┘

Using data.py, the example FluSight submission was created by running the following:

get_and_save_flusight_submission(
    file_save_path=os.path.join(
        os.getcwd(),
        "example_flusight_submission.csv"
    ),
)

NHSN COVID And Flu Hospital Admissions

NHSN hospital admissions fitting data for COVID and Flu is included in forecasttools-py as well, for user experimentation.

This data:

For influenza, the previous_day_admission_influenza_confirmed column is retained and for COVID the previous_day_admission_adult_covid_confirmed column is retained. As can be seen in the example below, some early dates for each jurisdiction do not have data.

The fitting data is stored in forecasttools-py as a polars dataframe and is accessed via:

# access COVID data
covid_nhsn_data = forecasttools.nhsn_hosp_COVID

# access flu data
flu_nhsn_data = forecasttools.nhsn_hosp_flu

# display flu data
print(flu_nhsn_data)
shape: (81_713, 3)
┌───────┬────────────┬──────┐
│ state ┆ date       ┆ hosp │
│ ---   ┆ ---        ┆ ---  │
│ str   ┆ str        ┆ str  │
╞═══════╪════════════╪══════╡
│ AK    ┆ 2020-03-23 ┆ null │
│ AK    ┆ 2020-03-24 ┆ null │
│ AK    ┆ 2020-03-25 ┆ null │
│ AK    ┆ 2020-03-26 ┆ null │
│ AK    ┆ 2020-03-27 ┆ null │
│ …     ┆ …          ┆ …    │
│ WY    ┆ 2024-04-23 ┆ 1    │
│ WY    ┆ 2024-04-24 ┆ 1    │
│ WY    ┆ 2024-04-25 ┆ 0    │
│ WY    ┆ 2024-04-26 ┆ 0    │
│ WY    ┆ 2024-04-27 ┆ 0    │
└───────┴────────────┴──────┘

The data was created by placing a csv file called NHSN_RAW_20240926.csv (the full NHSN dataset) into ./forecasttools/ and running, in data.py, the following:

# generate COVID dataset
make_nshn_fitting_dataset(
    dataset="COVID",
    nhsn_dataset_path="NHSN_RAW_20240926.csv",
    file_save_path=os.path.join(
        os.getcwd(),
        "nhsn_hosp_COVID.csv"
    )
)

# generate flu dataset
make_nshn_fitting_dataset(
    dataset="flu",
    nhsn_dataset_path="NHSN_RAW_20240926.csv",
    file_save_path=os.path.join(
        os.getcwd(),
        "nhsn_hosp_flu.csv"
    )
)

Influenza Hospitalizations Forecast(s)

Two example forecasts stored in Arviz InferenceData objects are included for vignettes and user experimentation. Both are 28 day influenza hospital admissions forecasts for Texas made using a spline regression model fitted to NHSN data between 2022-08-08 and 2022-12-08. The only difference between the forecasts is that example_flu_forecast_w_dates.nc has had dates added as its coordinates (this is not a native Arviz feature).

The forecast idatas are accessed via:

# idata with dates as coordinates
idata_w_dates = forecasttools.nhsn_flu_forecast_w_dates
print(idata_w_dates)
Inference data with groups:
    > posterior
    > posterior_predictive
    > log_likelihood
    > sample_stats
    > prior
    > prior_predictive
    > observed_data
# show dates
print(idata_w_dates["observed_data"]["obs"]["obs_dim_0"][:15])
<xarray.DataArray 'obs_dim_0' (obs_dim_0: 15)> Size: 120B
array(['2022-08-08T00:00:00.000000000', '2022-08-09T00:00:00.000000000',
       '2022-08-10T00:00:00.000000000', '2022-08-11T00:00:00.000000000',
       '2022-08-12T00:00:00.000000000', '2022-08-13T00:00:00.000000000',
       '2022-08-14T00:00:00.000000000', '2022-08-15T00:00:00.000000000',
       '2022-08-16T00:00:00.000000000', '2022-08-17T00:00:00.000000000',
       '2022-08-18T00:00:00.000000000', '2022-08-19T00:00:00.000000000',
       '2022-08-20T00:00:00.000000000', '2022-08-21T00:00:00.000000000',
       '2022-08-22T00:00:00.000000000'], dtype='datetime64[ns]')
Coordinates:
  * obs_dim_0  (obs_dim_0) datetime64[ns] 120B 2022-08-08 ... 2022-08-22
# idata without dates as coordinates
idata_wo_dates = forecasttools.nhsn_flu_forecast_wo_dates
print(idata_wo_dates["observed_data"]["obs"]["obs_dim_0"][:20])
<xarray.DataArray 'obs_dim_0' (obs_dim_0: 20)> Size: 160B
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19])
Coordinates:
  * obs_dim_0  (obs_dim_0) int64 160B 0 1 2 3 4 5 6 7 ... 13 14 15 16 17 18 19

CDC Open Source Considerations

General disclaimer This repository was created for use by CDC programs to collaborate on public health related projects in support of the CDC mission. GitHub is not hosted by the CDC, but is a third party website used by CDC and its partners to share information and collaborate on software. CDC use of GitHub does not imply an endorsement of any one particular service, product, or enterprise.

Rules, Policy, And Collaboration

Public Domain Standard Notice

This repository constitutes a work of the United States Government and is not subject to domestic copyright protection under 17 USC § 105. This repository is in the public domain within the United States, and copyright and related rights in the work worldwide are waived through the CC0 1.0 Universal public domain dedication. All contributions to this repository will be released under the CC0 dedication. By submitting a pull request you are agreeing to comply with this waiver of copyright interest.

License Standard Notice

The repository utilizes code licensed under the terms of the Apache Software License and therefore is licensed under ASL v2 or later.

This source code in this repository is free: you can redistribute it and/or modify it under the terms of the Apache Software License version 2, or (at your option) any later version.

This source code in this repository is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache Software License for more details.

You should have received a copy of the Apache Software License along with this program. If not, see http://www.apache.org/licenses/LICENSE-2.0.html

The source code forked from other open source projects will inherit its license.

Privacy Standard Notice

This repository contains only non-sensitive, publicly available data and information. All material and community participation is covered by the Disclaimer and Code of Conduct. For more information about CDC’s privacy policy, please visit http://www.cdc.gov/other/privacy.html.

Contributing Standard Notice

Anyone is encouraged to contribute to the repository by forking and submitting a pull request. (If you are new to GitHub, you might start with a basic tutorial.) By contributing to this project, you grant a world-wide, royalty-free, perpetual, irrevocable, non-exclusive, transferable license to all users under the terms of the Apache Software License v2 or later.

All comments, messages, pull requests, and other submissions received through CDC including this GitHub page may be subject to applicable federal law, including but not limited to the Federal Records Act, and may be archived. Learn more at http://www.cdc.gov/other/privacy.html.

Records Management Standard Notice

This repository is not a source of government records, but is a copy to increase collaboration and collaborative potential. All government records will be published through the CDC web site.

Additional Standard Notices

Please refer to CDC’s Template Repository for more information about contributing to this repository, public domain notices and disclaimers, and code of conduct.

About

A Python package for common pre- and post-processing operations done by CFA Predict for short term forecasting, nowcasting, and scenario modeling.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 10