|
| 1 | +from io import BytesIO |
| 2 | +import logging |
| 3 | +from typing import List |
| 4 | +from zipfile import ZipFile |
| 5 | +import pandas as pd |
| 6 | +from policyengine_core.data import Dataset |
| 7 | +import requests |
| 8 | +from tqdm import tqdm |
| 9 | +from policyengine_us_data.storage import STORAGE_FOLDER |
| 10 | + |
| 11 | +logging.getLogger().setLevel(logging.INFO) |
| 12 | + |
| 13 | +PERSON_COLUMNS = [ |
| 14 | + "SERIALNO", # Household ID |
| 15 | + "SPORDER", # Person number within household |
| 16 | + "PWGTP", # Person weight |
| 17 | + "AGEP", # Age |
| 18 | + "CIT", # Citizenship |
| 19 | + "MAR", # Marital status |
| 20 | + "WAGP", # Wage/salary |
| 21 | + "SSP", # Social security income |
| 22 | + "SSIP", # Supplemental security income |
| 23 | + "SEX", # Sex |
| 24 | + "SEMP", # Self-employment income |
| 25 | + "SCHL", # Educational attainment |
| 26 | + "RETP", # Retirement income |
| 27 | + "PAP", # Public assistance income |
| 28 | + "OIP", # Other income |
| 29 | + "PERNP", # Total earnings |
| 30 | + "PINCP", # Total income |
| 31 | + "POVPIP", # Income-to-poverty line percentage |
| 32 | + "RAC1P", # Race |
| 33 | +] |
| 34 | + |
| 35 | +HOUSEHOLD_COLUMNS = [ |
| 36 | + "SERIALNO", # Household ID |
| 37 | + "PUMA", # PUMA area code |
| 38 | + "ST", # State code |
| 39 | + "ADJHSG", # Adjustment factor for housing dollar amounts |
| 40 | + "ADJINC", # Adjustment factor for income |
| 41 | + "WGTP", # Household weight |
| 42 | + "NP", # Number of persons in household |
| 43 | + "BDSP", # Number of bedrooms |
| 44 | + "ELEP", # Electricity monthly cost |
| 45 | + "FULP", # Fuel monthly cost |
| 46 | + "GASP", # Gas monthly cost |
| 47 | + "RMSP", # Number of rooms |
| 48 | + "RNTP", # Monthly rent |
| 49 | + "TEN", # Tenure |
| 50 | + "VEH", # Number of vehicles |
| 51 | + "FINCP", # Total income |
| 52 | + "GRNTP", # Gross rent |
| 53 | + "TAXAMT", # Property taxes |
| 54 | +] |
| 55 | + |
| 56 | + |
| 57 | +class CensusACS(Dataset): |
| 58 | + data_format = Dataset.TABLES |
| 59 | + |
| 60 | + def generate(self) -> None: |
| 61 | + spm_url = f"https://www2.census.gov/programs-surveys/supplemental-poverty-measure/datasets/spm/spm_{self.time_period}_pu.dta" |
| 62 | + person_url = f"https://www2.census.gov/programs-surveys/acs/data/pums/{self.time_period}/1-Year/csv_pus.zip" |
| 63 | + household_url = f"https://www2.census.gov/programs-surveys/acs/data/pums/{self.time_period}/1-Year/csv_hus.zip" |
| 64 | + |
| 65 | + with pd.HDFStore(self.file_path, mode="w") as storage: |
| 66 | + household = self.process_household_data( |
| 67 | + household_url, "psam_hus", HOUSEHOLD_COLUMNS |
| 68 | + ) |
| 69 | + person = self.process_person_data( |
| 70 | + person_url, "psam_pus", PERSON_COLUMNS |
| 71 | + ) |
| 72 | + person = person[person.SERIALNO.isin(household.SERIALNO)] |
| 73 | + household = household[household.SERIALNO.isin(person.SERIALNO)] |
| 74 | + storage["household"] = household |
| 75 | + storage["person"] = person |
| 76 | + |
| 77 | + @staticmethod |
| 78 | + def process_household_data( |
| 79 | + url: str, prefix: str, columns: List[str] |
| 80 | + ) -> pd.DataFrame: |
| 81 | + req = requests.get(url, stream=True) |
| 82 | + with BytesIO() as f: |
| 83 | + pbar = tqdm() |
| 84 | + for chunk in req.iter_content(chunk_size=1024): |
| 85 | + if chunk: |
| 86 | + pbar.update(len(chunk)) |
| 87 | + f.write(chunk) |
| 88 | + f.seek(0) |
| 89 | + zf = ZipFile(f) |
| 90 | + a = pd.read_csv( |
| 91 | + zf.open(prefix + "a.csv"), |
| 92 | + usecols=columns, |
| 93 | + dtype={"SERIALNO": str}, |
| 94 | + ) |
| 95 | + b = pd.read_csv( |
| 96 | + zf.open(prefix + "b.csv"), |
| 97 | + usecols=columns, |
| 98 | + dtype={"SERIALNO": str}, |
| 99 | + ) |
| 100 | + res = pd.concat([a, b]).fillna(0) |
| 101 | + res.columns = res.columns.str.upper() |
| 102 | + |
| 103 | + # Ensure correct data types |
| 104 | + res["ST"] = res["ST"].astype(int) |
| 105 | + |
| 106 | + return res |
| 107 | + |
| 108 | + @staticmethod |
| 109 | + def process_person_data( |
| 110 | + url: str, prefix: str, columns: List[str] |
| 111 | + ) -> pd.DataFrame: |
| 112 | + req = requests.get(url, stream=True) |
| 113 | + with BytesIO() as f: |
| 114 | + pbar = tqdm() |
| 115 | + for chunk in req.iter_content(chunk_size=1024): |
| 116 | + if chunk: |
| 117 | + pbar.update(len(chunk)) |
| 118 | + f.write(chunk) |
| 119 | + f.seek(0) |
| 120 | + zf = ZipFile(f) |
| 121 | + a = pd.read_csv( |
| 122 | + zf.open(prefix + "a.csv"), |
| 123 | + usecols=columns, |
| 124 | + dtype={"SERIALNO": str}, |
| 125 | + ) |
| 126 | + b = pd.read_csv( |
| 127 | + zf.open(prefix + "b.csv"), |
| 128 | + usecols=columns, |
| 129 | + dtype={"SERIALNO": str}, |
| 130 | + ) |
| 131 | + res = pd.concat([a, b]).fillna(0) |
| 132 | + res.columns = res.columns.str.upper() |
| 133 | + |
| 134 | + # Ensure correct data types |
| 135 | + res["SPORDER"] = res["SPORDER"].astype(int) |
| 136 | + |
| 137 | + return res |
| 138 | + |
| 139 | + @staticmethod |
| 140 | + def create_spm_unit_table( |
| 141 | + storage: pd.HDFStore, person: pd.DataFrame |
| 142 | + ) -> None: |
| 143 | + SPM_UNIT_COLUMNS = [ |
| 144 | + "CAPHOUSESUB", |
| 145 | + "CAPWKCCXPNS", |
| 146 | + "CHILDCAREXPNS", |
| 147 | + "EITC", |
| 148 | + "ENGVAL", |
| 149 | + "EQUIVSCALE", |
| 150 | + "FEDTAX", |
| 151 | + "FEDTAXBC", |
| 152 | + "FICA", |
| 153 | + "GEOADJ", |
| 154 | + "MEDXPNS", |
| 155 | + "NUMADULTS", |
| 156 | + "NUMKIDS", |
| 157 | + "NUMPER", |
| 158 | + "POOR", |
| 159 | + "POVTHRESHOLD", |
| 160 | + "RESOURCES", |
| 161 | + "SCHLUNCH", |
| 162 | + "SNAPSUB", |
| 163 | + "STTAX", |
| 164 | + "TENMORTSTATUS", |
| 165 | + "TOTVAL", |
| 166 | + "WCOHABIT", |
| 167 | + "WICVAL", |
| 168 | + "WKXPNS", |
| 169 | + "WUI_LT15", |
| 170 | + "ID", |
| 171 | + ] |
| 172 | + spm_table = ( |
| 173 | + person[["SPM_" + column for column in SPM_UNIT_COLUMNS]] |
| 174 | + .groupby(person.SPM_ID) |
| 175 | + .first() |
| 176 | + ) |
| 177 | + |
| 178 | + original_person_table = storage["person"] |
| 179 | + original_person_table.to_csv("person.csv") |
| 180 | + person.to_csv("spm_person.csv") |
| 181 | + |
| 182 | + # Ensure SERIALNO is treated as string |
| 183 | + JOIN_COLUMNS = ["SERIALNO", "SPORDER"] |
| 184 | + original_person_table["SERIALNO"] = original_person_table[ |
| 185 | + "SERIALNO" |
| 186 | + ].astype(str) |
| 187 | + original_person_table["SPORDER"] = original_person_table[ |
| 188 | + "SPORDER" |
| 189 | + ].astype(int) |
| 190 | + person["SERIALNO"] = person["SERIALNO"].astype(str) |
| 191 | + person["SPORDER"] = person["SPORDER"].astype(int) |
| 192 | + |
| 193 | + # Add SPM_ID from the SPM person table to the original person table. |
| 194 | + combined_person_table = pd.merge( |
| 195 | + original_person_table, |
| 196 | + person[JOIN_COLUMNS + ["SPM_ID"]], |
| 197 | + on=JOIN_COLUMNS, |
| 198 | + ) |
| 199 | + |
| 200 | + storage["person_matched"] = combined_person_table |
| 201 | + storage["spm_unit"] = spm_table |
| 202 | + |
| 203 | + |
| 204 | +class CensusACS_2022(CensusACS): |
| 205 | + label = "Census ACS (2022)" |
| 206 | + name = "census_acs_2022.h5" |
| 207 | + file_path = STORAGE_FOLDER / "census_acs_2022.h5" |
| 208 | + time_period = 2022 |
0 commit comments