"""Shared loaders for the heat analysis. Standard library only.""" import csv, glob, json, os, re, datetime as dt HERE = os.path.dirname(os.path.abspath(__file__)) RAW = os.path.join(HERE, 'raw') WINTERS = list(range(2016, 2026)) # keyed by the year the winter starts: 2025 = Oct 1 2025 to May 31 2026 def winter_of(date): """Start year of the heat season (Oct 1 to May 31) a YYYY-MM-DD date falls in, or None for June to September.""" y, m = int(date[:4]), int(date[5:7]) if m >= 10: return y if m <= 5: return y - 1 return None def norm_apt(a): """Normalize an apartment label so '4-B', 'APT 4B' and '04B' count as one apartment. Returns '' when it names no apartment.""" a = re.sub(r'[^A-Z0-9]', '', (a or '').upper()) a = re.sub(r'^(APARTMENT|APT|UNIT|NO)', '', a).lstrip('0') return '' if a in ('', 'BLDG', 'BUILDING', 'NA', 'NONE', 'NOAPT') else a def complaints(): """One record per distinct complaint_id: (id, timestamp, bbl, building_id, apartment, building_wide, anonymous, problem_codes, n_rows).""" seen = {} rows = 0 for path in sorted(glob.glob(os.path.join(RAW, 'heat-*.csv'))): with open(path, newline='') as f: for r in csv.DictReader(f): rows += 1 cid = r['complaint_id'] bw = r['unit_type'] == 'BUILDING-WIDE' if cid in seen: s = seen[cid] s[5] = s[5] or bw s[7] = s[7] + '|' + r['problem_code'] s[8] += 1 if r['received_date'] < s[1]: s[1] = r['received_date'] else: bbl = r['bbl'].split('.')[0] seen[cid] = [cid, r['received_date'], bbl if len(bbl) == 10 and bbl[0] in '12345' else '', r['building_id'], norm_apt(r['apartment']), bw, r['complaint_anonymous_flag'] == 'Y', r['problem_code'], 1] return list(seen.values()), rows def pluto(): """bbl -> dict(units, year, floors, cls, owner, nb) for every lot with at least one residential unit.""" out = {} for path in sorted(glob.glob(os.path.join(RAW, 'pluto-*.csv'))): with open(path, newline='') as f: for r in csv.DictReader(f): bbl = r['bbl'].split('.')[0] num = lambda k: int(float(r[k])) if r.get(k) else 0 out[bbl] = {'units': num('unitsres'), 'year': num('yearbuilt'), 'floors': float(r['numfloors'] or 0), 'cls': r['bldgclass'] or '', 'owner': (r['ownername'] or '').upper(), 'nb': num('numbldgs')} return out def temps(): """date -> (tmin, tmax) in whole degrees Fahrenheit, Central Park.""" with open(os.path.join(RAW, 'temps.json')) as f: return {r['DATE']: (int(r['TMIN']), int(r['TMAX'])) for r in json.load(f) if r.get('TMIN') and r.get('TMAX')} def daterange(a, b): d, e = dt.date.fromisoformat(a), dt.date.fromisoformat(b) while d <= e: yield d.isoformat() d += dt.timedelta(days=1)