python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import pandas as pd from hdx.api.configuration import Configuration from hdx.data.dataset import Dataset import shutil from glob import glob import os from covid19_spread.data.usa.process_cases import get_index import re SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) def main(): Configuration.create( hdx_site="prod", user_agent="A_Quick_Example", hdx_read_only=True ) dataset = Dataset.read_from_hdx("movement-range-maps") resources = dataset.get_resources() resource = [ x for x in resources if re.match(".*/movement-range-data-\d{4}-\d{2}-\d{2}\.zip", x["url"]) ] assert len(resource) == 1 resource = resource[0] url, path = resource.download() if os.path.exists(f"{SCRIPT_DIR}/fb_mobility"): shutil.rmtree(f"{SCRIPT_DIR}/fb_mobility") shutil.unpack_archive(path, f"{SCRIPT_DIR}/fb_mobility", "zip") fips_map = get_index() fips_map["location"] = fips_map["name"] + ", " + fips_map["subregion1_name"] cols = [ "date", "region", "all_day_bing_tiles_visited_relative_change", "all_day_ratio_single_tile_users", ] def get_county_mobility_fb(fin): df_mobility_global = pd.read_csv( fin, parse_dates=["ds"], delimiter="\t", dtype={"polygon_id": str} ) df_mobility_usa = df_mobility_global.query("country == 'USA'") return df_mobility_usa # fin = sys.argv[1] if len(sys.argv) == 2 else None txt_files = glob(f"{SCRIPT_DIR}/fb_mobility/movement-range*.txt") assert len(txt_files) == 1 fin = txt_files[0] df = get_county_mobility_fb(fin) df = df.rename(columns={"ds": "date", "polygon_id": "region"}) df = df.merge(fips_map, left_on="region", right_on="fips")[ list(df.columns) + ["location"] ] df = df.drop(columns="region").rename(columns={"location": "region"}) def zscore(df): # z-scores df = (df.values - df.mean(skipna=True)) / df.std(skipna=True) return df def process_df(df, cols): df = df[cols].copy() regions = [] for (name, _df) in df.groupby("region"): _df = _df.sort_values(by="date") _df = _df.drop_duplicates(subset="date") dates = _df["date"].to_list() assert len(dates) == len(np.unique(dates)), _df _df = _df.loc[:, ~_df.columns.duplicated()] _df = _df.drop(columns=["region", "date"]).transpose() # take 7 day average _df = _df.rolling(7, min_periods=1, axis=1).mean() # convert relative change into absolute numbers _df.loc["all_day_bing_tiles_visited_relative_change"] += 1 _df["region"] = [name] * len(_df) _df.columns = list(map(lambda x: x.strftime("%Y-%m-%d"), dates)) + [ "region" ] regions.append(_df.reset_index()) df = pd.concat(regions, axis=0, ignore_index=True) cols = ["region"] + [x for x in df.columns if x != "region"] df = df[cols] df = df.rename(columns={"index": "type"}) return df county = process_df(df, cols) state = df.copy() state["region"] = state["region"].apply(lambda x: x.split(", ")[-1]) state = state.groupby(["region", "date"]).mean().reset_index() state = process_df(state, cols) county = county.fillna(0) state = state.fillna(0) county.round(4).to_csv(f"{SCRIPT_DIR}/mobility_features_county_fb.csv", index=False) state.round(4).to_csv(f"{SCRIPT_DIR}/mobility_features_state_fb.csv", index=False) if __name__ == "__main__": main()
covid19_spread-main
covid19_spread/data/usa/fb/process_mobility.py
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .process_mobility import main def prepare(): main()
covid19_spread-main
covid19_spread/data/usa/fb/__init__.py
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .process_testing import main def prepare(): main()
covid19_spread-main
covid19_spread/data/usa/testing/__init__.py
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import pandas as pd from datetime import datetime import os from covid19_spread.data.usa.process_cases import get_index SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) def main(): df = pd.read_csv( "https://beta.healthdata.gov/api/views/j8mb-icvb/rows.csv?accessType=DOWNLOAD", parse_dates=["date"], ) df_piv = df.pivot( columns=["overall_outcome"], values="total_results_reported", index=["state", "date"], ) df_piv = df_piv.fillna(0).groupby(level=0).cummax() index = get_index() states = index.drop_duplicates("subregion1_name") with_index = df_piv.reset_index().merge( states, left_on="state", right_on="subregion1_code" ) df = with_index[ ["subregion1_name", "Negative", "Positive", "Inconclusive", "date"] ].set_index("date") df = df.rename(columns={"subregion1_name": "state_name"}) df["Total"] = df["Positive"] + df["Negative"] + df["Inconclusive"] def zscore(df): df.iloc[:, 0:] = ( df.iloc[:, 0:].values - df.iloc[:, 0:].mean(axis=1, skipna=True).values[:, None] ) / df.iloc[:, 0:].std(axis=1, skipna=True).values[:, None] df = df.fillna(0) return df def zero_one(df): df = df.fillna(0) df = df.div(df.max(axis=1), axis=0) # df = df / df.max() df = df.fillna(0) return df def fmt_features(pivot, key, func_smooth, func_normalize): df = pivot.transpose() df = func_smooth(df) if func_normalize is not None: df = func_normalize(df) df = df.fillna(0) df.index.set_names("region", inplace=True) df["type"] = f"testing_{key}" merge = df.merge(index, left_index=True, right_on="subregion1_name") merge.index = merge["name"] + ", " + merge["subregion1_name"] return df, merge[df.columns] def _diff(df): return df.diff(axis=1).rolling(7, axis=1, min_periods=1).mean() state_r, county_r = fmt_features( df.pivot(columns="state_name", values=["Positive", "Total"]), "ratio", lambda _df: (_diff(_df.loc["Positive"]) / _diff(_df.loc["Total"])), None, ) state_t, county_t = fmt_features( df.pivot(columns="state_name", values="Total"), "Total", _diff, zero_one, ) def write_features(df, res, fout): df = df[["type"] + [c for c in df.columns if isinstance(c, datetime)]] df.columns = [ str(x.date()) if isinstance(x, datetime) else x for x in df.columns ] df.round(3).to_csv( f"{SCRIPT_DIR}/{fout}_features_{res}.csv", index_label="region" ) write_features(state_t, "state", "total") write_features(state_r, "state", "ratio") write_features(county_t, "county", "total") write_features(county_r, "county", "ratio") if __name__ == "__main__": main()
covid19_spread-main
covid19_spread/data/usa/testing/process_testing.py
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import pandas as pd import sys from datetime import timedelta from delphi_epidata import Epidata import covidcast # Fetch data SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) def main(geo_value, source, signal): # grab start and end date from metadata df = covidcast.metadata().drop(columns=["time_type", "min_lag", "max_lag"]) df.min_time = pd.to_datetime(df.min_time) df.max_time = pd.to_datetime(df.max_time) df = df.query( f"data_source == '{source}' and signal == '{signal}' and geo_type == '{geo_value}'" ) assert len(df) == 1 base_date = df.iloc[0].min_time - timedelta(1) end_date = df.iloc[0].max_time dfs = [] current_date = base_date while current_date < end_date: current_date = current_date + timedelta(1) date_str = current_date.strftime("%Y%m%d") os.makedirs(os.path.join(SCRIPT_DIR, geo_value, source), exist_ok=True) fout = f"{SCRIPT_DIR}/{geo_value}/{source}/{signal}-{date_str}.csv" # d/l only if we don't have the file already if os.path.exists(fout): dfs.append(pd.read_csv(fout)) continue for _ in range(3): res = Epidata.covidcast(source, signal, "day", geo_value, [date_str], "*") print(date_str, res["result"], res["message"]) if res["result"] == 1: break if res["result"] != 1: # response may be non-zero if there aren't enough respondants # See: https://github.com/cmu-delphi/delphi-epidata/issues/613#event-4962274038 print(f"Skipping {source}/{signal} for {date_str}") continue df = pd.DataFrame(res["epidata"]) df.rename( columns={ "geo_value": geo_value, "time_value": "date", "value": signal, "direction": f"{signal}_direction", "stderr": f"{signal}_stderr", "sample_size": f"{signal}_sample_size", }, inplace=True, ) df.to_csv(fout, index=False) dfs.append(df) pd.concat(dfs).to_csv(f"{SCRIPT_DIR}/{geo_value}/{source}/{signal}.csv") SIGNALS = [ ("fb-survey", "smoothed_hh_cmnty_cli"), ("fb-survey", "smoothed_wcli"), ("doctor-visits", "smoothed_adj_cli"), ("fb-survey", "smoothed_wcovid_vaccinated_or_accept"), ("fb-survey", "smoothed_wearing_mask"), ("fb-survey", "smoothed_wearing_mask_7d"), ("fb-survey", "smoothed_wothers_masked"), ("fb-survey", "smoothed_wcovid_vaccinated_or_accept"), ] if __name__ == "__main__": main(sys.argv[1], *sys.argv[2].split("/"))
covid19_spread-main
covid19_spread/data/usa/symptom_survey/fetch.py
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import pandas as pd import argparse from datetime import datetime import os from covid19_spread.data.usa.process_cases import get_index SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) def get_df(source, signal, resolution): df = pd.read_csv( f"{SCRIPT_DIR}/{resolution}/{source}/{signal}.csv", parse_dates=["date"] ) df.dropna(axis=0, subset=["date"], inplace=True) index = get_index() state_index = index.drop_duplicates("subregion1_code") if "state" in df.columns: df["state"] = df["state"].str.upper() merged = df.merge(state_index, left_on="state", right_on="subregion1_code") df = merged[["subregion1_name", "date", signal]].rename( columns={"subregion1_name": "loc"} ) else: df["county"] = df["county"].astype(str).str.zfill(5) merged = df.merge(index, left_on="county", right_on="fips") merged["loc"] = merged["name"] + ", " + merged["subregion1_name"] df = merged[["loc", "date", signal]] df = df.pivot(index="date", columns="loc", values=signal).copy() # Fill in NaNs df.iloc[0] = 0 df = df.fillna(0) # Normalize df = df.transpose() / 100 df["type"] = f"{source}_{signal}_{resolution}" return df def main(signal, resolution): source, signal = signal.split("/") df = get_df(source, signal, resolution) if resolution == "county": # Fill in missing counties with zeros cases = pd.read_csv( f"{SCRIPT_DIR}/../data_cases.csv", index_col="region" ).index.to_frame() cases["state"] = [x.split(", ")[-1] for x in cases.index] cases = cases.drop(columns="region") idx = pd.MultiIndex.from_product([cases.index, df["type"].unique()]) type_ = df["type"].iloc[0] df = df.reset_index().set_index(["loc", "type"]).reindex(idx).fillna(0) df2 = get_df(source, signal, "state") df2 = df2.merge(cases[["state"]], left_index=True, right_on="state")[ df2.columns ] df = pd.concat([df, df2.set_index("type", append=True)]) df = df[[c for c in df.columns if isinstance(c, datetime)]] df.columns = [str(x.date()) if isinstance(x, datetime) else x for x in df.columns] df.round(3).to_csv( f"{SCRIPT_DIR}/{source}_{signal}-{resolution}.csv", index_label=["region", "type"], ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-signal", default="smoothed_hh_cmnty_cli") parser.add_argument("-resolution", choices=["state", "county"], default="county") opt = parser.parse_args() main(opt.signal, opt.resolution)
covid19_spread-main
covid19_spread/data/usa/symptom_survey/process_symptom_survey.py
#!/usr/bin/env python3 # Copyright (c) 2021-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from covid19_spread.data.usa.symptom_survey.fetch import main as fetch, SIGNALS from covid19_spread.data.usa.symptom_survey.process_symptom_survey import ( main as process, ) import os import pandas SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) def concat_mask_data(resolution): df1 = pandas.read_csv( os.path.join(SCRIPT_DIR, resolution, "fb-survey", "smoothed_wearing_mask.csv") ) df2 = pandas.read_csv( os.path.join( SCRIPT_DIR, resolution, "fb-survey", "smoothed_wearing_mask_7d.csv" ) ) df2.columns = [c.replace("_7d", "") for c in df2.columns] df = pandas.concat([df1, df2]) df.columns = [ c.replace("smoothed_wearing_mask", "smoothed_wearing_mask_all") for c in df.columns ] df = df.sort_values(by="signal", ascending=False) df["signal"] = "smoothed_wearing_mask_all" df = df.drop_duplicates([resolution, "date"]) df.to_csv( os.path.join( SCRIPT_DIR, resolution, "fb-survey", "smoothed_wearing_mask_all.csv" ), index=False, ) def prepare(): for source, signal in SIGNALS: fetch("state", source, signal) fetch("county", source, signal) concat_mask_data("county") concat_mask_data("state") for source, signal in SIGNALS: if "wearing_mask" in signal: # Skip these since we end up concatenating the wearing_mask and wearing_mask_7d features continue process(f"{source}/{signal}", "state") process(f"{source}/{signal}", "county") process(f"fb-survey/smoothed_wearing_mask_all", "county") process(f"fb-survey/smoothed_wearing_mask_all", "state") if __name__ == "__main__": prepare()
covid19_spread-main
covid19_spread/data/usa/symptom_survey/__init__.py