| import pandas as pd
|
| import numpy as np
|
| import os
|
| import re
|
| import gc
|
| from datetime import datetime
|
| from concurrent.futures import ProcessPoolExecutor, as_completed
|
| from tqdm import tqdm
|
|
|
|
|
| RAW_DATA_DIR = "data/raw"
|
| CBP_DIR = os.path.join(RAW_DATA_DIR, "district_industries")
|
| NAICS_DIR = os.path.join(RAW_DATA_DIR, "industry_codes_NAICS")
|
| OUTPUT_FILE = "data/processed/events_geographical_industry.csv"
|
| MAX_WORKERS = os.cpu_count() - 1 or 1
|
|
|
| STATE_ABBREV = {
|
| 'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA',
|
| 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA',
|
| 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA',
|
| 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD',
|
| 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
|
| 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH',
|
| 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC',
|
| 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA',
|
| 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN',
|
| 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA',
|
| 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY', 'District of Columbia': 'DC',
|
| 'Puerto Rico': 'PR'
|
| }
|
|
|
| def load_crosswalks():
|
| print("[INFO] Loading NAICS-to-SIC Crosswalks...")
|
| cw_2012 = pd.read_csv(os.path.join(NAICS_DIR, "2012-NAICS-to-SIC-Crosswalk.csv"), dtype=str)
|
| cw_2017 = pd.read_csv(os.path.join(NAICS_DIR, "2017-NAICS-to-SIC-Crosswalk.csv"), dtype=str)
|
|
|
| dict_2012 = cw_2012.groupby('NAICS')['SIC'].apply(list).to_dict()
|
| dict_2017 = cw_2017.groupby('NAICS')['SIC'].apply(list).to_dict()
|
| return dict_2012, dict_2017
|
|
|
| def load_release_dates():
|
| print("[INFO] Loading Survey Release Dates...")
|
| release_df = pd.read_csv(os.path.join(CBP_DIR, "survey_release_dates.csv"))
|
| release_df['date'] = pd.to_datetime(release_df['date'], format='mixed')
|
| return dict(zip(release_df['survey_reference_year'], release_df['date']))
|
|
|
| def load_legislators():
|
| print("[INFO] Loading Legislator Metadata...")
|
| terms_df = pd.read_csv(os.path.join(RAW_DATA_DIR, "congress_terms_all_github.csv"), low_memory=False)
|
| terms_df['start'] = pd.to_datetime(terms_df['start'])
|
| terms_df['end'] = pd.to_datetime(terms_df['end'])
|
| terms_df['district'] = terms_df['district'].replace('At Large', 0)
|
| terms_df['district'] = pd.to_numeric(terms_df['district'], errors='coerce')
|
| return terms_df
|
|
|
| def parse_geography(name_str):
|
| if pd.isna(name_str):
|
| return None, None
|
| match = re.search(r'(?:Congressional District (\d+)|District \(At Large\)).*?,\s*(.*)', str(name_str), re.IGNORECASE)
|
| if match:
|
| dist_str = match.group(1)
|
| district = int(dist_str) if dist_str else 0
|
| state_name = match.group(2).strip()
|
| state_abbr = STATE_ABBREV.get(state_name, None)
|
| return state_abbr, district
|
| return None, None
|
|
|
| def get_active_legislator(terms_df, state, district, release_date):
|
| if state is None or pd.isna(district):
|
| return None
|
| active = terms_df[
|
| (terms_df['state'] == state) &
|
| (terms_df['district'] == district) &
|
| (terms_df['start'] <= release_date) &
|
| (terms_df['end'] >= release_date) &
|
| (terms_df['type'] == 'rep')
|
| ]
|
| if not active.empty:
|
| return active.iloc[0]['id_bioguide']
|
| return None
|
|
|
| def process_chunk(chunk, year, release_date, crosswalk, terms_df):
|
| edges = []
|
| cols = chunk.columns
|
|
|
|
|
| col_name = next((c for c in cols if 'NAME' in c), None)
|
| col_naics = next((c for c in cols if 'NAICS' in c and 'LABEL' not in c), None)
|
| col_estab = next((c for c in cols if 'ESTAB' in c), None)
|
| col_emp = next((c for c in cols if 'EMP' in c and 'EMPSZES' not in c), None)
|
| col_payann = next((c for c in cols if 'PAYANN' in c), None)
|
|
|
| if not all([col_name, col_naics, col_estab, col_emp, col_payann]):
|
| return pd.DataFrame()
|
|
|
|
|
| naics_raw = chunk[col_naics].astype(str).str.strip()
|
|
|
|
|
| is_top_level = naics_raw.str.match(r'^(\d{2}-*|\d{2}-\d{2}-*)$')
|
| is_not_total = ~naics_raw.str.startswith('00')
|
|
|
|
|
| chunk = chunk[is_top_level & is_not_total].copy()
|
|
|
|
|
|
|
| chunk[col_naics] = chunk[col_naics].astype(str).str.replace(r'-+$', '', regex=True).str.strip()
|
|
|
| for c in [col_estab, col_emp, col_payann]:
|
| chunk[c] = chunk[c].astype(str).str.replace(',', '')
|
| chunk[c] = pd.to_numeric(chunk[c], errors='coerce')
|
|
|
| chunk = chunk.dropna(subset=[col_estab, col_emp, col_payann], how='all')
|
|
|
|
|
| resolved_sics_cache = {}
|
|
|
| for _, row in chunk.iterrows():
|
| naics_code = str(row[col_naics]).strip()
|
|
|
|
|
| if naics_code not in resolved_sics_cache:
|
| sics = set()
|
|
|
| if '-' in naics_code:
|
| try:
|
| start, end = naics_code.split('-')
|
| prefixes = tuple(str(p) for p in range(int(start), int(end)+1))
|
| except:
|
| prefixes = (naics_code,)
|
| else:
|
| prefixes = (naics_code,)
|
|
|
|
|
| for cw_naics, cw_sics in crosswalk.items():
|
| if str(cw_naics).startswith(prefixes):
|
| sics.update(cw_sics)
|
| resolved_sics_cache[naics_code] = list(sics)
|
|
|
| sic_list = resolved_sics_cache[naics_code]
|
|
|
| if not sic_list:
|
| continue
|
|
|
| state, dist = parse_geography(row[col_name])
|
| bioguide_id = get_active_legislator(terms_df, state, dist, release_date)
|
|
|
| if bioguide_id:
|
| for sic in sic_list:
|
| edges.append({
|
| 'bioguide_id': bioguide_id,
|
| 'sic_code': sic,
|
| 'release_date': release_date,
|
| 'reference_year': year,
|
| 'establishments': row[col_estab],
|
| 'employment': row[col_emp],
|
| 'annual_payroll': row[col_payann]
|
| })
|
|
|
| return pd.DataFrame(edges)
|
|
|
| def process_cbp_file(file_path, year, release_date, crosswalk, terms_df):
|
| print(f"\n[INFO] Reading Year {year} (Release: {release_date.date()})")
|
|
|
| chunk_size = 25000
|
| chunks = []
|
| for chunk in pd.read_csv(file_path, chunksize=chunk_size, dtype=str):
|
| chunks.append(chunk)
|
|
|
| print(f" Spawned {len(chunks)} chunks. Processing across {MAX_WORKERS} cores...")
|
|
|
| results = []
|
| with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
|
| futures = {
|
| executor.submit(process_chunk, c, year, release_date, crosswalk, terms_df): i
|
| for i, c in enumerate(chunks)
|
| }
|
|
|
| for future in tqdm(as_completed(futures), total=len(chunks), desc=f"Year {year}", unit="chunk"):
|
| res_df = future.result()
|
| if not res_df.empty:
|
| results.append(res_df)
|
|
|
| if results:
|
| return pd.concat(results, ignore_index=True)
|
| return pd.DataFrame()
|
|
|
| def main():
|
| print("=====================================================")
|
| print(" BUILDING INDUSTRY-GEOGRAPHICAL EDGES (CBP)")
|
| print(f" Mode: Multiprocessing enabled ({MAX_WORKERS} Workers)")
|
| print("=====================================================")
|
|
|
| cw_2012, cw_2017 = load_crosswalks()
|
| release_dates = load_release_dates()
|
| terms_df = load_legislators()
|
|
|
| all_edges = []
|
|
|
| for year in range(2010, 2024):
|
| file_name = f"{year}_CB_estimates.csv" if year <= 2012 else f"{year}_CB_survey.csv"
|
| file_path = os.path.join(CBP_DIR, file_name)
|
|
|
| if not os.path.exists(file_path):
|
| continue
|
|
|
| release_date = release_dates.get(year)
|
| if not release_date:
|
| continue
|
|
|
| active_crosswalk = cw_2012 if year <= 2012 else cw_2017
|
| df_edges = process_cbp_file(file_path, year, release_date, active_crosswalk, terms_df)
|
|
|
| if not df_edges.empty:
|
| all_edges.append(df_edges)
|
|
|
| print("\n[INFO] Concatenating and saving final edge list...")
|
| if all_edges:
|
| final_df = pd.concat(all_edges, ignore_index=True)
|
| os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True)
|
| final_df.to_csv(OUTPUT_FILE, index=False)
|
|
|
| print(f"[SUCCESS] Saved {len(final_df)} geographical-industry edges to {OUTPUT_FILE}.")
|
| print(f"[STATS] Unique Legislators Mapped: {final_df['bioguide_id'].nunique()}")
|
| print(f"[STATS] Unique SIC Sectors Mapped: {final_df['sic_code'].nunique()}")
|
| else:
|
| print("[WARNING] No edges generated.")
|
|
|
| if __name__ == "__main__":
|
| main() |