File size: 9,970 Bytes
3609368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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

# --- CONFIGURATION ---
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
    
    # Safely find columns dynamically to handle schema evolution
    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()

    # --- THE FIX: FILTER OUT GRANULAR ROWS ---
    naics_raw = chunk[col_naics].astype(str).str.strip()
    
    # Match ONLY top-level 2-digit sectors (e.g., '11', '11----') or hyphenated groups ('31-33')
    is_top_level = naics_raw.str.match(r'^(\d{2}-*|\d{2}-\d{2}-*)$')
    is_not_total = ~naics_raw.str.startswith('00') # Exclude the "All Sectors" total
    
    # This perfectly standardizes 2010-2012 to match the 2013+ methodology
    chunk = chunk[is_top_level & is_not_total].copy()
    
    # Clean the NAICS codes to the standard format for our crosswalk
    # Removes trailing dashes the Census sometimes uses (e.g. '11----' -> '11')
    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')
    
    # Local cache to prevent redundant crosswalk scans inside the chunk
    resolved_sics_cache = {}
    
    for _, row in chunk.iterrows():
        naics_code = str(row[col_naics]).strip()
        
        # --- PREFIX-MATCHING LOGIC ---
        if naics_code not in resolved_sics_cache:
            sics = set()
            # Handle hyphenated aggregated sectors (e.g. "31-33")
            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,)
                
            # Scan crosswalk for any 6-digit NAICS that starts with this prefix
            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()