https://github.com/cdcgov/forecasttools-py

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

https://github.com/cdcgov/forecasttools-py

Science Score: 26.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (10.1%) to scientific vocabulary

Keywords

abstraction automation forecasting infectious-disease-modeling infrastructure

Keywords from Contributors

epidemiology infectious-disease-models renewal-process
Last synced: 5 months ago · JSON representation

Repository

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

Basic Info
  • Host: GitHub
  • Owner: CDCgov
  • License: apache-2.0
  • Language: Python
  • Default Branch: main
  • Homepage:
  • Size: 4.31 MB
Statistics
  • Stars: 8
  • Watchers: 9
  • Forks: 2
  • Open Issues: 20
  • Releases: 0
Topics
abstraction automation forecasting infectious-disease-modeling infrastructure
Created almost 2 years ago · Last pushed 6 months ago
Metadata Files
Readme Contributing License Codeowners

README.md

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 ``` mermaid %%{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 ```

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.

python 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:

python 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:

python 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.

python 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:

python 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:

python 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:

``` python

access COVID data

covidnhsndata = forecasttools.nhsnhospCOVID

access flu data

flunhsndata = forecasttools.nhsnhospflu

display flu data

print(flunhsndata) ```

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:

``` python

generate COVID dataset

makenshnfittingdataset( dataset="COVID", nhsndatasetpath="NHSNRAW20240926.csv", filesavepath=os.path.join( os.getcwd(), "nhsnhosp_COVID.csv" ) )

generate flu dataset

makenshnfittingdataset( dataset="flu", nhsndatasetpath="NHSNRAW20240926.csv", filesavepath=os.path.join( os.getcwd(), "nhsnhosp_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:

``` python

idata with dates as coordinates

idatawdates = forecasttools.nhsnfluforecastwdates print(idatawdates) ```

Inference data with groups:
    > posterior
    > posterior_predictive
    > log_likelihood
    > sample_stats
    > prior
    > prior_predictive
    > observed_data

``` python

show dates

print(idatawdates["observed_data"]["obs"]["obsdim0"][: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

``` python

idata without dates as coordinates

idatawodates = forecasttools.nhsnfluforecastwodates print(idatawodates["observed_data"]["obs"]["obsdim0"][: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 - [Open Practices](./rules-and-policies/open_practices.md) - [Rules of Behavior](./rules-and-policies/rules_of_behavior.md) - [Thanks and Acknowledgements](./rules-and-policies/thanks.md) - [Disclaimer](DISCLAIMER.md) - [Contribution Notice](CONTRIBUTING.md) - [Code of Conduct](./rules-and-policies/code-of-conduct.md)
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](https://creativecommons.org/publicdomain/zero/1.0/). 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](DISCLAIMER.md) and [Code of Conduct](code-of-conduct.md). For more information about CDC’s privacy policy, please visit [http://www.cdc.gov/other/privacy.html](https://www.cdc.gov/other/privacy.html).
Contributing Standard Notice Anyone is encouraged to contribute to the repository by [forking](https://help.github.com/articles/fork-a-repo) and submitting a pull request. (If you are new to GitHub, you might start with a [basic tutorial](https://help.github.com/articles/set-up-git).) 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](http://www.apache.org/licenses/LICENSE-2.0.html) 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 .
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](http://www.cdc.gov).
Additional Standard Notices Please refer to [CDC’s Template Repository](https://github.com/CDCgov/template) for more information about [contributing to this repository](https://github.com/CDCgov/template/blob/main/CONTRIBUTING.md), [public domain notices and disclaimers](https://github.com/CDCgov/template/blob/main/DISCLAIMER.md), and [code of conduct](https://github.com/CDCgov/template/blob/main/code-of-conduct.md).

Owner

  • Name: Centers for Disease Control and Prevention
  • Login: CDCgov
  • Kind: organization
  • Email: data@cdc.gov
  • Location: Atlanta, GA

CDC's collaborative software projects to protect America from health, safety, and security threats, both foreign and in the U.S.

Committers

Last synced: 10 months ago

All Time
  • Total Commits: 35
  • Total Committers: 4
  • Avg Commits per committer: 8.75
  • Development Distribution Score (DDS): 0.143
Past Year
  • Commits: 34
  • Committers: 3
  • Avg Commits per committer: 11.333
  • Development Distribution Score (DDS): 0.118
Top Committers
Name Email Commits
AFg6K7h4fhy2 1****2 30
Samuel Brand 4****1 3
sswanikcdc 1****c 1
Dylan H. Morris d****s 1

Issues and Pull Requests

Last synced: 5 months ago

All Time
  • Total issues: 50
  • Total pull requests: 79
  • Average time to close issues: 13 days
  • Average time to close pull requests: 6 days
  • Total issue authors: 4
  • Total pull request authors: 8
  • Average comments per issue: 0.8
  • Average comments per pull request: 2.54
  • Merged pull requests: 43
  • Bot issues: 0
  • Bot pull requests: 18
Past Year
  • Issues: 50
  • Pull requests: 79
  • Average time to close issues: 13 days
  • Average time to close pull requests: 6 days
  • Issue authors: 4
  • Pull request authors: 8
  • Average comments per issue: 0.8
  • Average comments per pull request: 2.54
  • Merged pull requests: 43
  • Bot issues: 0
  • Bot pull requests: 18
Top Authors
Issue Authors
  • AFg6K7h4fhy2 (37)
  • dylanhmorris (7)
  • SamuelBrand1 (4)
  • damonbayer (2)
Pull Request Authors
  • AFg6K7h4fhy2 (42)
  • dependabot[bot] (15)
  • SamuelBrand1 (6)
  • dylanhmorris (6)
  • damonbayer (4)
  • pre-commit-ci[bot] (3)
  • gvegayon (2)
  • sbidari (1)
Top Labels
Issue Labels
enhancement (14) Low Priority (9) documentation (4) testing (4) High Priority (3) feature (3) scope (2) first-pass (2) Medium Priority (2) actions (2) user-feedback (2) warnings (2) reproducibility (1) visuals (1) tidiness (1) website (1) bug (1)
Pull Request Labels
enhancement (23) dependencies (12) Low Priority (12) feature (5) High Priority (4) testing (4) reproducibility (4) warnings (4) automation (3) documentation (3) tidiness (2) bug (2) user-feedback (2) data (2) Medium Priority (2) first-pass (1) actions (1)