#!/usr/bin/env python3 """Ten winters of NYC heat and hot water complaints: every number in the article comes from here. Run after fetch.py: python3 -I analysis/heat/analyze.py Writes analysis/heat/derived/results.json (small, committed) and prints a readable report. Standard library only. """ import collections, datetime as dt, json, math, os, statistics as st, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import load # noqa: E402 W = load.WINTERS LAST = W[-1] OUT = {} BANDS = [('3-5', 3, 5), ('6-19', 6, 19), ('20-49', 20, 49), ('50-99', 50, 99), ('100+', 100, 10**9)] def pct(a, b): return round(100 * a / b, 1) if b else None def med(v): return st.median(v) if v else None def quant(sorted_v, q): if not sorted_v: return None return sorted_v[min(len(sorted_v) - 1, int(q * len(sorted_v)))] def say(*a): print(*a, flush=True) def band_of(u): for name, lo, hi in BANDS: if lo <= u <= hi: return name return None # ---------------------------------------------------------------- load C, problem_rows = load.complaints() P = load.pluto() T = load.temps() say('problem rows', problem_rows, 'distinct complaints', len(C)) OUT['rows'] = {'problem_rows': problem_rows, 'complaints': len(C), 'complaints_multi_problem': sum(1 for c in C if c[8] > 1)} by_w = collections.defaultdict(list) # winter -> complaints off_season = collections.Counter() for c in C: w = load.winter_of(c[1][:10]) if w is None: off_season[c[1][:4]] += 1 else: by_w[w].append(c) say('off-season (Jun-Sep) complaints by year', dict(sorted(off_season.items()))) OUT['off_season_by_year'] = dict(sorted(off_season.items())) # NYCHA lots in PLUTO, by owner name NYCHA = {b for b, p in P.items() if 'HOUSING AUTHORITY' in p['owner'] or p['owner'].startswith('NYCHA')} # Universe: PLUTO lots with 3+ residential units that are not public housing U3 = {b for b, p in P.items() if p['units'] >= 3 and b not in NYCHA} U6 = {b for b in U3 if P[b]['units'] >= 6} CONDO = {b for b in U3 if P[b]['cls'].startswith('R')} COOP = {b for b in U3 if P[b]['cls'] in ('C6', 'C8', 'D0', 'D4')} say('PLUTO lots with res units', len(P), '3+ non-NYCHA', len(U3), '6+', len(U6), 'NYCHA lots', len(NYCHA), 'condo', len(CONDO), 'coop', len(COOP)) units_U3 = sum(P[b]['units'] for b in U3) OUT['universe'] = {'pluto_res_lots': len(P), 'lots_3plus': len(U3), 'lots_6plus': len(U6), 'units_3plus': units_U3, 'units_6plus': sum(P[b]['units'] for b in U6), 'nycha_lots': len(NYCHA), 'nycha_units': sum(P[b]['units'] for b in NYCHA), 'condo_lots_3plus': len(CONDO), 'coop_lots_3plus': len(COOP)} # per-winter per-lot tallies cnt = {w: collections.Counter() for w in by_w} # complaints apts = {w: collections.defaultdict(collections.Counter) for w in by_w} # lot -> apartment -> complaints bw = {w: collections.Counter() for w in by_w} # building-wide complaints nobbl = collections.Counter() for w, cs in by_w.items(): for c in cs: b = c[2] if not b: nobbl[w] += 1 continue cnt[w][b] += 1 if c[5]: bw[w][b] += 1 if c[4]: apts[w][b][c[4]] += 1 # ---------------------------------------------------------------- 1. totals per winter say('\n== winters') OUT['winters'] = [] for w in W: cs = by_w[w] n = len(cs) lots = cnt[w] in_p = sum(v for b, v in lots.items() if b in P) in_u3 = sum(v for b, v in lots.items() if b in U3) in_nycha = sum(v for b, v in lots.items() if b in NYCHA) small = sum(v for b, v in lots.items() if b in P and P[b]['units'] < 3 and b not in NYCHA) row = {'winter': w, 'complaints': n, 'lots': len(lots), 'no_bbl': nobbl[w], 'pct_matched_pluto': pct(in_p, n), 'pct_in_3plus': pct(in_u3, n), 'pct_nycha_lots': pct(in_nycha, n), 'pct_1_2_unit_lots': pct(small, n), 'pct_building_wide': pct(sum(1 for c in cs if c[5]), n), 'pct_anonymous': pct(sum(1 for c in cs if c[6]), n), 'pct_with_apartment': pct(sum(1 for c in cs if c[4]), n), 'lots_3plus_complaining': sum(1 for b in lots if b in U3), 'pct_lots_3plus_complaining': pct(sum(1 for b in lots if b in U3), len(U3)), 'pct_lots_6plus_complaining': pct(sum(1 for b in lots if b in U6), len(U6)), 'pct_units_3plus_in_complaining_lots': pct(sum(P[b]['units'] for b in lots if b in U3), units_U3), 'median_per_complaining_lot': med(list(lots.values())), 'mean_per_complaining_lot': round(n / len(lots), 2)} OUT['winters'].append(row) say(row) # ---------------------------------------------------------------- 2. weather say('\n== degree days') daily = collections.Counter(c[1][:10] for c in C) # Days the complaint system was evidently not recording: a handful of late-December days hold almost nothing. GAPS = sorted(d for w in W for d in load.daterange('%d-11-01' % w, '%d-03-31' % (w + 1)) if daily[d] < 60) OUT['gap_days'] = [{'date': d, 'complaints': daily[d], 'weekday': dt.date.fromisoformat(d).strftime('%A')} for d in GAPS] say('gap days excluded from daily statistics', OUT['gap_days']) lowest_kept = min((daily[d], d) for w in W for d in load.daterange('%d-12-01' % w, '%d-02-28' % (w + 1)) if d not in GAPS) OUT['lowest_dec_feb_day_kept'] = {'date': lowest_kept[1], 'complaints': lowest_kept[0]} say('lowest Dec-Feb day kept', lowest_kept) for row in OUT['winters']: cs = by_w[row['winter']] row['lot_days'] = len({(c[2], c[1][:10]) for c in cs if c[2]}) ap = collections.Counter((c[2], c[4]) for c in cs if c[2] and c[4]) row['complaints_from_apartments_filing_50plus'] = sum(v for v in ap.values() if v >= 50) row['apartments_filing_50plus'] = sum(1 for v in ap.values() if v >= 50) row['most_from_one_apartment'] = max(ap.values()) for row in OUT['winters']: w = row['winter'] days = list(load.daterange('%d-10-01' % w, '%d-05-31' % (w + 1))) miss = [d for d in days if d not in T] hdd = sum(max(0, 65 - (T[d][0] + T[d][1]) / 2) for d in days if d in T) row.update({'hdd': round(hdd), 'missing_temp_days': len(miss), 'per_hdd': round(row['complaints'] / hdd, 1), 'lot_days_per_hdd': round(row['lot_days'] / hdd, 1), 'days_low_le_32': sum(1 for d in days if d in T and T[d][0] <= 32), 'days_low_lt_20': sum(1 for d in days if d in T and T[d][0] < 20), 'coldest_low': min(T[d][0] for d in days if d in T)}) say(w, 'hdd', row['hdd'], 'complaints/hdd', row['per_hdd'], 'lot-days', row['lot_days'], 'lot-days/hdd', row['lot_days_per_hdd'], 'heavy filers', row['complaints_from_apartments_filing_50plus'], row['apartments_filing_50plus'], row['most_from_one_apartment'], 'days<=32', row['days_low_le_32'], 'days<20', row['days_low_lt_20'], 'min', row['coldest_low'], 'missing', len(miss)) base = [r for r in OUT['winters'] if r['winter'] < LAST] # least-squares line through the nine earlier winters, then where the last winter lands mx = sum(r['hdd'] for r in base) / len(base); my = sum(r['complaints'] for r in base) / len(base) slope = sum((r['hdd'] - mx) * (r['complaints'] - my) for r in base) / sum((r['hdd'] - mx) ** 2 for r in base) r2 = (sum((r['hdd'] - mx) * (r['complaints'] - my) for r in base) ** 2 / (sum((r['hdd'] - mx) ** 2 for r in base) * sum((r['complaints'] - my) ** 2 for r in base))) lastrow = OUT['winters'][-1] OUT['hdd_fit'] = {'slope_per_hdd': round(slope, 1), 'r2_nine_winters': round(r2, 2), 'predicted_last': round(my + slope * (lastrow['hdd'] - mx)), 'actual_last': lastrow['complaints']} say('fit over first nine winters', OUT['hdd_fit']) def season_days(w): return [d for d in load.daterange('%d-10-01' % w, '%d-05-31' % (w + 1)) if d in T and d not in GAPS] # Counterfactual: what would each winter's weather have produced at another period's response to temperature? # Response = mean complaints per day by 5-degree band of the daily low, split into early season (Oct-Nov) and the rest. def response(ws): acc = collections.defaultdict(list) for w in ws: for d in season_days(w): acc[(min(max(T[d][0] // 5 * 5, 5), 60), d[5:7] in ('10', '11'))].append(daily[d]) return {k: sum(v) / len(v) for k, v in acc.items()} def expected(w, resp): tot = 0 for d in season_days(w): k = (min(max(T[d][0] // 5 * 5, 5), 60), d[5:7] in ('10', '11')) if k not in resp: # fall back to nearest band k = min((kk for kk in resp if kk[1] == k[1]), key=lambda kk: abs(kk[0] - k[0])) tot += resp[k] return round(tot) OUT['weather_adjusted'] = [] for w in W: e = expected(w, response([x for x in W if x != w])) a = sum(daily[d] for d in season_days(w)) OUT['weather_adjusted'].append({'winter': w, 'expected_at_other_nine_winters_response': e, 'actual': a, 'ratio': round(a / e, 2)}) say('weather-adjusted', w, 'expected', e, 'actual', a, 'ratio', round(a / e, 2)) # The last winter's weather at the previous three winters' response, and the previous winter's weather at the same response r3 = response(W[-4:-1]) OUT['last_winter_vs_prior3'] = {'response_from': W[-4:-1], 'expected_last': expected(LAST, r3), 'actual_last': sum(daily[d] for d in season_days(LAST)), 'expected_prev': expected(LAST - 1, r3), 'actual_prev': sum(daily[d] for d in season_days(LAST - 1))} OUT['last_winter_vs_prior3']['weather_only_change_pct'] = pct(OUT['last_winter_vs_prior3']['expected_last'] - OUT['last_winter_vs_prior3']['expected_prev'], OUT['last_winter_vs_prior3']['expected_prev']) OUT['last_winter_vs_prior3']['actual_over_expected'] = round(OUT['last_winter_vs_prior3']['actual_last'] / OUT['last_winter_vs_prior3']['expected_last'], 2) say('last winter at prior three winters response', OUT['last_winter_vs_prior3']) # ---------------------------------------------------------------- 3. temperature curve say('\n== complaints per day by daily low (heat-season days, ten winters)') alldays = [d for w in W for d in season_days(w)] OUT['by_low_10'] = [] for lo in range(0, 70, 10): v = sorted(daily[d] for d in alldays if (lo <= T[d][0] < lo + 10) or (lo == 0 and T[d][0] < 10) or (lo == 60 and T[d][0] >= 60)) OUT['by_low_10'].append({'low': lo, 'days': len(v), 'median': med(v), 'q1': quant(v, .25), 'q3': quant(v, .75), 'mean': round(sum(v) / len(v))}) say(OUT['by_low_10'][-1]) OUT['by_low_5'] = [] for lo in range(5, 70, 5): v = sorted(daily[d] for d in alldays if (lo <= T[d][0] < lo + 5) or (lo == 5 and T[d][0] < 10) or (lo == 65 and T[d][0] >= 65)) if v: OUT['by_low_5'].append({'low': lo, 'days': len(v), 'median': med(v), 'q1': quant(v, .25), 'q3': quant(v, .75)}) # the same curve for recent winters only, since volumes rose OUT['by_low_10_last3'] = [] for lo in range(0, 70, 10): v = sorted(daily[d] for w in W[-3:] for d in season_days(w) if (lo <= T[d][0] < lo + 10) or (lo == 0 and T[d][0] < 10) or (lo == 60 and T[d][0] >= 60)) OUT['by_low_10_last3'].append({'low': lo, 'days': len(v), 'median': med(v)}) top = sorted(((daily[d], d) for d in alldays), reverse=True)[:10] OUT['biggest_days'] = [{'date': d, 'complaints': n, 'low': T[d][0], 'high': T[d][1]} for n, d in top] say('biggest days', OUT['biggest_days']) # scatter points for the chart: every heat-season day OUT['scatter'] = [[T[d][0], daily[d], int(d[5:7])] for d in alldays] # ---------------------------------------------------------------- 4. the October effect say('\n== early season vs later at the same low') GROUPS = [('Oct', ('10',)), ('Nov', ('11',)), ('Dec-Feb', ('12', '01', '02')), ('Mar-Apr', ('03', '04')), ('May', ('05',))] OUT['season_effect'] = [] for lo in range(30, 55, 5): row = {'low': lo} for name, ms in GROUPS: v = [daily[d] for d in alldays if lo <= T[d][0] < lo + 5 and d[5:7] in ms] row[name] = {'days': len(v), 'median': med(v)} OUT['season_effect'].append(row) say(row) row = {'low': '35-44'} for name, ms in GROUPS: v = sorted(daily[d] for d in alldays if 35 <= T[d][0] < 45 and d[5:7] in ms) row[name] = {'days': len(v), 'median': med(v), 'q1': quant(v, .25), 'q3': quant(v, .75)} OUT['season_effect_35_44'] = row say(row) # the same comparison on the day's mean temperature instead of its low, and the average high in each group OUT['season_effect_mean_temp'] = [] for lo in (40, 45, 50): r = {'mean_temp': lo} for name, ms in GROUPS[:4]: v = [daily[d] for d in alldays if lo <= (T[d][0] + T[d][1]) / 2 < lo + 5 and d[5:7] in ms] r[name] = {'days': len(v), 'median': med(v)} OUT['season_effect_mean_temp'].append(r) say(r) OUT['avg_high_at_lows_35_44'] = {name: round(sum(T[d][1] for d in alldays if 35 <= T[d][0] < 45 and d[5:7] in ms) / max(1, sum(1 for d in alldays if 35 <= T[d][0] < 45 and d[5:7] in ms)), 1) for name, ms in GROUPS[:4]} say('avg high at lows 35-44', OUT['avg_high_at_lows_35_44']) say('-- each winter separately, lows 35-44: Oct median vs Dec-Feb median') OUT['season_effect_by_winter'] = [] for w in W: ds = season_days(w) o = [daily[d] for d in ds if 35 <= T[d][0] < 45 and d[5:7] == '10'] n = [daily[d] for d in ds if 35 <= T[d][0] < 45 and d[5:7] == '11'] m = [daily[d] for d in ds if 35 <= T[d][0] < 45 and d[5:7] in ('12', '01', '02')] r = {'winter': w, 'oct_days': len(o), 'oct_median': med(o), 'nov_days': len(n), 'nov_median': med(n), 'mid_days': len(m), 'mid_median': med(m), 'oct_over_mid': round(med(o) / med(m), 2) if o and m else None, 'nov_over_mid': round(med(n) / med(m), 2) if n and m else None} OUT['season_effect_by_winter'].append(r) say(r) say('-- by order of cold day within the season (days with low under 45F, counted from Oct 1)') order_acc = collections.defaultdict(list) order_rel = collections.defaultdict(list) # each day relative to that winter's Dec-Feb median at the same band oct_first = collections.defaultdict(list) for w in W: ds = season_days(w) midmed = {} for lo in (30, 35, 40): v = [daily[d] for d in ds if lo <= T[d][0] < lo + 5 and d[5:7] in ('12', '01', '02')] midmed[lo] = med(v) k = 0 for d in ds: if T[d][0] < 45: k += 1 grp = '1-3' if k <= 3 else '4-10' if k <= 10 else '11-20' if k <= 20 else '21-40' if k <= 40 else '41+' if 35 <= T[d][0] < 45: order_acc[grp].append(daily[d]) lo = T[d][0] // 5 * 5 if midmed.get(lo): order_rel[grp].append(daily[d] / midmed[lo]) # within the first ten cold days, does the calendar month still matter? oct_first[('first10' if k <= 10 else 'later', 'Oct' if d[5:7] == '10' else 'Nov' if d[5:7] == '11' else 'other')].append(daily[d]) OUT['cold_day_order'] = [] for g in ('1-3', '4-10', '11-20', '21-40', '41+'): v = sorted(order_acc[g]); rr = sorted(order_rel[g]) OUT['cold_day_order'].append({'nth_cold_day': g, 'days': len(v), 'median': med(v), 'q1': quant(v, .25), 'q3': quant(v, .75), 'median_ratio_to_own_midwinter': round(med(rr), 2) if rr else None}) say(OUT['cold_day_order'][-1]) OUT['cold_day_order_by_month'] = {'%s/%s' % k: {'days': len(v), 'median': med(v)} for k, v in sorted(oct_first.items())} say(OUT['cold_day_order_by_month']) # first day of each season with a low under 45, and the first under 40 OUT['first_cold_days'] = [] for w in W: ds = season_days(w) f45 = next(d for d in ds if T[d][0] < 45) OUT['first_cold_days'].append({'winter': w, 'first_low_under_45': f45, 'low': T[f45][0], 'complaints': daily[f45]}) say(OUT['first_cold_days']) # cold snap vs sustained cold: same low, split by the mean low of the previous 7 days (Dec-Feb only, lows 25-34) snap = collections.defaultdict(list) for w in W: for d in season_days(w): if d[5:7] in ('12', '01', '02') and 25 <= T[d][0] < 35: prev = [T[x][0] for x in load.daterange((dt.date.fromisoformat(d) - dt.timedelta(days=7)).isoformat(), (dt.date.fromisoformat(d) - dt.timedelta(days=1)).isoformat()) if x in T] snap['prev week warmer by 8F+' if sum(prev) / len(prev) - T[d][0] >= 8 else 'prev week within 8F'].append(daily[d]) OUT['cold_snap'] = {k: {'days': len(v), 'median': med(v)} for k, v in snap.items()} say('cold snap check', OUT['cold_snap']) # ---------------------------------------------------------------- 5. hour and weekday hours = collections.Counter(int(c[1][11:13]) for w in W for c in by_w[w]) OUT['by_hour'] = [hours[h] for h in range(24)] say('\nby hour', OUT['by_hour']) wd = collections.defaultdict(list) for d in alldays: if d[5:7] in ('12', '01', '02'): wd[dt.date.fromisoformat(d).weekday()].append(daily[d]) OUT['weekday_median_dec_feb'] = [med(wd[i]) for i in range(7)] say('weekday medians Dec-Feb, Mon first', OUT['weekday_median_dec_feb']) # ---------------------------------------------------------------- 6. concentration say('\n== concentration') OUT['concentration'] = [] for w in W: lots = cnt[w]; tot = sum(lots.values()) s = sorted(lots.values(), reverse=True); n = len(s) row = {'winter': w, 'top1pct_of_complaining_lots': pct(sum(s[:n // 100]), tot), 'top10pct_of_complaining_lots': pct(sum(s[:n // 10]), tot), 'median': med(s), 'lots_10plus': sum(1 for v in s if v >= 10), 'lots_50plus': sum(1 for v in s if v >= 50), 'share_from_lots_10plus': pct(sum(v for v in s if v >= 10), tot), 'share_from_lots_50plus': pct(sum(v for v in s if v >= 50), tot)} # against the whole universe of 3+ unit lots su = sorted((lots.get(b, 0) for b in U3), reverse=True); tu = sum(su) row['top1pct_of_all_3plus_lots'] = pct(sum(su[:len(su) // 100]), tu) row['top5pct_of_all_3plus_lots'] = pct(sum(su[:len(su) // 20]), tu) row['top10pct_of_all_3plus_lots'] = pct(sum(su[:len(su) // 10]), tu) # by apartments: rank 6+ unit lots by complaints per apartment, walk down until 1%, 5%, 10% of apartments are covered r6 = sorted(((lots.get(b, 0) / P[b]['units'], lots.get(b, 0), P[b]['units']) for b in U6), reverse=True) t6 = sum(x[1] for x in r6); u6 = sum(x[2] for x in r6) acc_u = acc_c = 0; marks = {} for rate, c_, u_ in r6: acc_u += u_; acc_c += c_ for q in (0.01, 0.05, 0.10, 0.20): if q not in marks and acc_u >= q * u6: marks[q] = pct(acc_c, t6) row['share_from_top_apartments_6plus'] = {'1%': marks[0.01], '5%': marks[0.05], '10%': marks[0.10], '20%': marks[0.20]} row['lots_in_top1pct'] = n // 100; row['lots_in_top10pct'] = n // 10 OUT['concentration'].append(row) say(row) # within size bands, last winter: complaints per apartment say('-- within size bands, winter', LAST) OUT['size_bands'] = [] for name, lo, hi in BANDS: lotsb = [b for b in U3 if lo <= P[b]['units'] <= hi] cs = [cnt[LAST].get(b, 0) for b in lotsb] rates = sorted(cnt[LAST].get(b, 0) / P[b]['units'] for b in lotsb) units = sum(P[b]['units'] for b in lotsb) srt = sorted(cs, reverse=True) row = {'band': name, 'lots': len(lotsb), 'units': units, 'complaints': sum(cs), 'pct_lots_any': pct(sum(1 for c_ in cs if c_), len(cs)), 'per_100_apartments': round(100 * sum(cs) / units, 1), 'top10pct_lots_share': pct(sum(srt[:len(srt) // 10]), sum(srt)), 'top1pct_lots_share': pct(sum(srt[:max(1, len(srt) // 100)]), sum(srt)), 'rate_p50': round(quant(rates, .5), 3), 'rate_p75': round(quant(rates, .75), 3), 'rate_p90': round(quant(rates, .9), 3), 'rate_p95': round(quant(rates, .95), 3), 'rate_p99': round(quant(rates, .99), 3), 'pct_lots_rate_ge_0.5': pct(sum(1 for r in rates if r >= .5), len(rates)), 'pct_lots_rate_ge_1': pct(sum(1 for r in rates if r >= 1), len(rates))} OUT['size_bands'].append(row) say(row) # ---------------------------------------------------------------- 7. persistence say('\n== persistence, raw counts (all lots with a BBL; zero group = 3+ unit lots with no complaints)') CB = [('0', 0, 0), ('1', 1, 1), ('2-4', 2, 4), ('5-9', 5, 9), ('10-24', 10, 24), ('25-49', 25, 49), ('50+', 50, 10**9)] def persist(a, b, universe, key=lambda lot, c: c): rows = [] for name, lo, hi in CB: g = [x for x in universe if lo <= a.get(x, 0) <= hi] if not g: rows.append(None); continue nxt = [b.get(x, 0) for x in g] rows.append({'band': name, 'lots': len(g), 'any_next': pct(sum(1 for v in nxt if v >= 1), len(g)), 'ge5_next': pct(sum(1 for v in nxt if v >= 5), len(g)), 'ge10_next': pct(sum(1 for v in nxt if v >= 10), len(g)), 'median_next': med(nxt)}) return rows OUT['persistence_counts'] = {} for a in W[:-1]: rows = persist(cnt[a], cnt[a + 1], U3) OUT['persistence_counts']['%d>%d' % (a, a + 1)] = rows say(a, '->', a + 1, [(r['band'], r['lots'], r['any_next'], r['ge10_next'], r['median_next']) for r in rows]) # pooled over the last four pairs, and over all nine for label, pairs in (('last4', W[-5:-1]), ('all9', W[:-1])): pooled = [] for i, (name, lo, hi) in enumerate(CB): rs = [OUT['persistence_counts']['%d>%d' % (a, a + 1)][i] for a in pairs] n = sum(r['lots'] for r in rs) pooled.append({'band': name, 'lots_per_pair': round(n / len(rs)), 'any_next': round(sum(r['any_next'] * r['lots'] for r in rs) / n, 1), 'ge5_next': round(sum(r['ge5_next'] * r['lots'] for r in rs) / n, 1), 'ge10_next': round(sum(r['ge10_next'] * r['lots'] for r in rs) / n, 1), 'min_ge10': min(r['ge10_next'] for r in rs), 'max_ge10': max(r['ge10_next'] for r in rs), 'min_any': min(r['any_next'] for r in rs), 'max_any': max(r['any_next'] for r in rs)}) OUT['persistence_counts_' + label] = pooled say(label, pooled) say('\n== persistence per apartment, within size bands (6+ unit lots)') # Rate bands: complaints per apartment in winter t. Outcome: rate in winter t+1. RB = [('0', 0, 0), ('under 0.1', 1e-9, 0.1), ('0.1-0.25', 0.1, 0.25), ('0.25-0.5', 0.25, 0.5), ('0.5-1', 0.5, 1.0), ('1+', 1.0, 1e9)] def rate_band(r): if r == 0: return 0 for i, (_, lo, hi) in enumerate(RB[1:], 1): if lo <= r < hi: return i def persist_rate(pairs, lots): acc = [[0, 0, 0, 0, []] for _ in RB] # n, any next, >=0.25 next, >=0.5 next, next rates for a in pairs: for b in lots: u = P[b]['units'] i = rate_band(cnt[a].get(b, 0) / u) nx = cnt[a + 1].get(b, 0) / u acc[i][0] += 1; acc[i][1] += nx > 0; acc[i][2] += nx >= 0.25; acc[i][3] += nx >= 0.5; acc[i][4].append(nx) return [{'band': RB[i][0], 'lot_winters': x[0], 'any_next': pct(x[1], x[0]), 'ge_quarter_next': pct(x[2], x[0]), 'ge_half_next': pct(x[3], x[0]), 'median_next_rate': round(med(x[4]), 3) if x[4] else None} for i, x in enumerate(acc)] OUT['persistence_rate'] = {'all_6plus_last4': persist_rate(W[-5:-1], U6), 'all_6plus_all9': persist_rate(W[:-1], U6)} for r in OUT['persistence_rate']['all_6plus_last4']: say('6+ last4', r) for name, lo, hi in BANDS[1:]: lotsb = [b for b in U6 if lo <= P[b]['units'] <= hi] OUT['persistence_rate'][name] = persist_rate(W[-5:-1], lotsb) say(name, [(r['band'], r['lot_winters'], r['any_next'], r['ge_half_next']) for r in OUT['persistence_rate'][name]]) # each pair separately, top rate bands, to show stability OUT['persistence_rate_by_pair'] = {} for a in W[:-1]: rs = persist_rate([a], U6) OUT['persistence_rate_by_pair']['%d>%d' % (a, a + 1)] = rs say(a, [(r['band'], r['ge_half_next'], r['any_next']) for r in rs]) # excluding condo and co-op lots OUT['persistence_rate']['6plus_excl_condo_coop_last4'] = persist_rate(W[-5:-1], U6 - CONDO - COOP) say('excl condo/coop', [(r['band'], r['lot_winters'], r['any_next'], r['ge_half_next']) for r in OUT['persistence_rate']['6plus_excl_condo_coop_last4']]) # decile transitions within size band: top decile by rate this winter -> where next winter say('-- top decile by complaints per apartment within size band -> next winter') OUT['decile_persistence'] = [] for name, lo, hi in BANDS[1:]: lotsb = [b for b in U6 if lo <= P[b]['units'] <= hi] stay = tot = top_half = 0 for a in W[-5:-1]: ra = sorted(lotsb, key=lambda b: -cnt[a].get(b, 0) / P[b]['units']) rb = sorted(lotsb, key=lambda b: -cnt[a + 1].get(b, 0) / P[b]['units']) k = len(lotsb) // 10 ta, tb = set(ra[:k]), set(rb[:k]) stay += len(ta & tb); tot += k top_half += len(ta & set(rb[:2 * k])) OUT['decile_persistence'].append({'band': name, 'lots': len(lotsb), 'top_decile_stays_top_decile': pct(stay, tot), 'top_decile_stays_top_fifth': pct(top_half, tot)}) say(OUT['decile_persistence'][-1]) def spearman(xs, ys): def rank(v): idx = sorted(range(len(v)), key=lambda i: v[i]); r = [0] * len(v); i = 0 while i < len(idx): j = i while j < len(idx) and v[idx[j]] == v[idx[i]]: j += 1 for k in idx[i:j]: r[k] = (i + j - 1) / 2 i = j return r rx, ry = rank(xs), rank(ys); n = len(xs); mx_ = sum(rx) / n; my_ = sum(ry) / n return sum((a - mx_) * (b - my_) for a, b in zip(rx, ry)) / math.sqrt(sum((a - mx_) ** 2 for a in rx) * sum((b - my_) ** 2 for b in ry)) l6 = sorted(U6) OUT['spearman_rate_6plus'] = {'%d>%d' % (a, b): round(spearman([cnt[a].get(x, 0) / P[x]['units'] for x in l6], [cnt[b].get(x, 0) / P[x]['units'] for x in l6]), 2) for a, b in ((2024, 2025), (2023, 2024), (2020, 2025), (2016, 2025))} say('spearman of per-apartment rate, 6+ lots', OUT['spearman_rate_6plus']) # chronic sets say('\n== chronic lots') allb = set().union(*[set(cnt[w]) for w in W]) tot_last = len(by_w[LAST]) c5 = [b for b in allb if all(cnt[w].get(b, 0) >= 10 for w in W[-5:])] c10 = [b for b in allb if all(cnt[w].get(b, 0) >= 10 for w in W)] e10 = [b for b in allb if all(cnt[w].get(b, 0) >= 1 for w in W)] e5 = [b for b in allb if all(cnt[w].get(b, 0) >= 1 for w in W[-5:])] r5 = [b for b in U6 if all(cnt[w].get(b, 0) / P[b]['units'] >= 0.25 for w in W[-5:])] OUT['chronic'] = { 'lots_ever_complained_10_winters': len(allb), 'ten_plus_each_of_last5': {'lots': len(c5), 'share_last_winter': pct(sum(cnt[LAST][b] for b in c5), tot_last), 'in_pluto': sum(1 for b in c5 if b in P), 'units': sum(P[b]['units'] for b in c5 if b in P), 'median_units': med([P[b]['units'] for b in c5 if b in P]), 'pct_units_of_3plus': pct(sum(P[b]['units'] for b in c5 if b in U3), units_U3), 'pct_lots_of_3plus': pct(sum(1 for b in c5 if b in U3), len(U3))}, 'ten_plus_each_of_10': {'lots': len(c10), 'share_last_winter': pct(sum(cnt[LAST][b] for b in c10), tot_last)}, 'any_each_of_10': {'lots': len(e10), 'share_last_winter': pct(sum(cnt[LAST][b] for b in e10), tot_last), 'units': sum(P[b]['units'] for b in e10 if b in P), 'pct_units_of_3plus': pct(sum(P[b]['units'] for b in e10 if b in U3), units_U3), 'pct_lots_of_3plus': pct(sum(1 for b in e10 if b in U3), len(U3))}, 'any_each_of_last5': {'lots': len(e5), 'share_last_winter': pct(sum(cnt[LAST][b] for b in e5), tot_last)}, 'quarter_per_apartment_each_of_last5_6plus': {'lots': len(r5), 'units': sum(P[b]['units'] for b in r5), 'share_last_winter': pct(sum(cnt[LAST][b] for b in r5), tot_last), 'pct_units_of_6plus': pct(sum(P[b]['units'] for b in r5), sum(P[b]['units'] for b in U6)), 'pct_lots_of_6plus': pct(len(r5), len(U6))}, } for k, v in OUT['chronic'].items(): say(k, v) # ---------------------------------------------------------------- 8. distinct apartments say('\n== distinct apartments') OUT['apartments'] = [] for w in W[-3:]: for name, lo, hi in (('1', 1, 1), ('2-4', 2, 4), ('5-9', 5, 9), ('10-24', 10, 24), ('25-49', 25, 49), ('50+', 50, 10**9)): g = [b for b, v in cnt[w].items() if lo <= v <= hi] na = [len(apts[w][b]) for b in g] top_share = [max(apts[w][b].values()) / cnt[w][b] if apts[w][b] else 0 for b in g] named = sum(sum(apts[w][b].values()) for b in g); total = sum(cnt[w][b] for b in g) cov = [len(apts[w][b]) / P[b]['units'] for b in g if b in U6] row = {'winter': w, 'band': name, 'lots': len(g), 'median_distinct_apartments': med(na), 'q1_distinct': quant(sorted(na), .25), 'q3_distinct': quant(sorted(na), .75), 'pct_lots_one_or_zero_apartments': pct(sum(1 for x in na if x <= 1), len(g)), 'pct_lots_under_3_apartments': pct(sum(1 for x in na if x < 3), len(g)), 'pct_lots_5plus_apartments': pct(sum(1 for x in na if x >= 5), len(g)), 'median_top_apartment_share': round(med(top_share), 2), 'pct_lots_one_apartment_majority': pct(sum(1 for x in top_share if x > .5), len(g)), 'pct_complaints_naming_apartment': pct(named, total), 'pct_building_wide': pct(sum(bw[w][b] for b in g), total), 'median_share_of_apartments_complaining_6plus': round(med(cov), 2) if cov else None} OUT['apartments'].append(row) say(row) # chronic set: how many apartments na5 = [len(apts[LAST][b]) for b in c5]; ts5 = [max(apts[LAST][b].values()) / cnt[LAST][b] if apts[LAST][b] else 0 for b in c5] OUT['chronic']['ten_plus_each_of_last5'].update({'median_distinct_apartments_last_winter': med(na5), 'pct_under_3_apartments': pct(sum(1 for x in na5 if x < 3), len(na5)), 'pct_5plus_apartments': pct(sum(1 for x in na5 if x >= 5), len(na5)), 'pct_one_apartment_majority': pct(sum(1 for x in ts5 if x > .5), len(ts5))}) say('chronic5 apartments', OUT['chronic']['ten_plus_each_of_last5']) # persistence on distinct apartments instead of complaints (last four pairs with apartments tallied for all winters) AB = [('0', 0, 0), ('1', 1, 1), ('2', 2, 2), ('3-4', 3, 4), ('5-9', 5, 9), ('10+', 10, 10**9)] acc = [[0, 0, 0, 0] for _ in AB] for a in W[-5:-1]: for b in U3: n = len(apts[a].get(b, ())) if b in apts[a] else 0 i = next(i for i, (_, lo, hi) in enumerate(AB) if lo <= n <= hi) nx = len(apts[a + 1][b]) if b in apts[a + 1] else 0 acc[i][0] += 1; acc[i][1] += nx >= 1; acc[i][2] += nx >= 3; acc[i][3] += nx >= 5 OUT['persistence_apartments_last4'] = [{'band': AB[i][0], 'lot_winters': x[0], 'any_next': pct(x[1], x[0]), 'ge3_next': pct(x[2], x[0]), 'ge5_next': pct(x[3], x[0])} for i, x in enumerate(acc)] say('persistence by distinct apartments', OUT['persistence_apartments_last4']) # citywide: how concentrated are complaints among filers? share of last winter's apartment-named complaints from apartments with 10+ ap_counts = sorted((v for b in apts[LAST] for v in apts[LAST][b].values()), reverse=True) OUT['filers'] = {'apartments_named_last_winter': len(ap_counts), 'complaints_naming_apartment': sum(ap_counts), 'pct_apartments_filing_once': pct(sum(1 for v in ap_counts if v == 1), len(ap_counts)), 'median_per_apartment': med(ap_counts), 'apartments_10plus': sum(1 for v in ap_counts if v >= 10), 'share_from_apartments_10plus': pct(sum(v for v in ap_counts if v >= 10), sum(ap_counts)), 'share_from_top1pct_apartments': pct(sum(ap_counts[:len(ap_counts) // 100]), sum(ap_counts)), 'max_from_one_apartment': ap_counts[0]} say('filers', OUT['filers']) # ---------------------------------------------------------------- 9. age and size say('\n== age and size, winter', LAST, '(3+ unit lots, not NYCHA)') AGE = [('before 1900', 1, 1899), ('1900-19', 1900, 1919), ('1920-39', 1920, 1939), ('1940-59', 1940, 1959), ('1960-79', 1960, 1979), ('1980-99', 1980, 1999), ('2000-09', 2000, 2009), ('2010 on', 2010, 2100)] OUT['by_age'] = [] for name, lo, hi in AGE: g = [b for b in U3 if lo <= P[b]['year'] <= hi] units = sum(P[b]['units'] for b in g); cs = sum(cnt[LAST].get(b, 0) for b in g) row = {'built': name, 'lots': len(g), 'units': units, 'per_100_apartments': round(100 * cs / units, 1), 'pct_lots_any': pct(sum(1 for b in g if cnt[LAST].get(b, 0)), len(g)), 'per_100_apartments_3yr_mean': round(100 * sum(cnt[w].get(b, 0) for w in W[-3:] for b in g) / units / 3, 1), 'pct_units_condo_coop': pct(sum(P[b]['units'] for b in g if b in CONDO or b in COOP), units)} g2 = [b for b in g if b not in CONDO and b not in COOP] u2 = sum(P[b]['units'] for b in g2) row['per_100_apartments_excl_condo_coop'] = round(100 * sum(cnt[LAST].get(b, 0) for b in g2) / u2, 1) row['lots_excl'] = len(g2); row['units_excl'] = u2 OUT['by_age'].append(row) say(row) OUT['by_age_size'] = [] for an, alo, ahi in (('before 1940', 1, 1939), ('1940-79', 1940, 1979), ('1980 on', 1980, 2100)): for name, lo, hi in BANDS: g = [b for b in U3 if alo <= P[b]['year'] <= ahi and lo <= P[b]['units'] <= hi] units = sum(P[b]['units'] for b in g) OUT['by_age_size'].append({'built': an, 'band': name, 'lots': len(g), 'units': units, 'per_100_apartments': round(100 * sum(cnt[LAST].get(b, 0) for b in g) / units, 1) if units else None}) say(OUT['by_age_size'][-1]) OUT['by_tenure'] = [] for name, g in (('condo', CONDO), ('coop', COOP), ('other (mostly rental)', U3 - CONDO - COOP)): units = sum(P[b]['units'] for b in g) OUT['by_tenure'].append({'type': name, 'lots': len(g), 'units': units, 'per_100_apartments': round(100 * sum(cnt[LAST].get(b, 0) for b in g) / units, 1), 'pct_lots_any': pct(sum(1 for b in g if cnt[LAST].get(b, 0)), len(g))}) say(OUT['by_tenure'][-1]) # ---------------------------------------------------------------- 10. this season so far, as an out-of-sample check say('\n== out of sample: last winter band vs Oct 1 - Nov 15 2026') now = collections.Counter(c[2] for c in by_w.get(LAST + 1, []) if c[2]) OUT['this_season'] = {'through': max(c[1][:10] for c in by_w[LAST + 1]), 'complaints': len(by_w[LAST + 1]), 'lots': len(now), 'by_last_winter': []} for name, lo, hi in CB: g = [b for b in U3 if lo <= cnt[LAST].get(b, 0) <= hi] OUT['this_season']['by_last_winter'].append({'band': name, 'lots': len(g), 'any_so_far': pct(sum(1 for b in g if now.get(b, 0)), len(g)), 'ge5_so_far': pct(sum(1 for b in g if now.get(b, 0) >= 5), len(g))}) say(OUT['this_season']) for w in W: # same window in earlier years, for the "is the season starting bigger" check n = sum(1 for c in by_w[w] if c[1][5:10] >= '10-01' and c[1][5:10] <= '11-15' and c[1][:4] == str(w)) OUT.setdefault('oct1_nov15', {})[w] = n OUT['oct1_nov15'][LAST + 1] = sum(1 for c in by_w[LAST + 1] if c[1][:10] <= '%d-11-15' % (LAST + 1)) say('Oct 1 - Nov 15 by year', OUT['oct1_nov15']) # ---------------------------------------------------------------- 11. thresholds for the lookup # Complaints per apartment last winter among all 3+ unit lots in each size band (zeros included). OUT['lookup'] = {'winter': LAST, 'bands': {}} for name, lo, hi in BANDS: lotsb = [b for b in U3 if lo <= P[b]['units'] <= hi] rates = sorted(cnt[LAST].get(b, 0) / P[b]['units'] for b in lotsb) counts = sorted(cnt[LAST].get(b, 0) for b in lotsb) OUT['lookup']['bands'][name] = {'lots': len(lotsb), 'pct_zero': pct(sum(1 for r in rates if r == 0), len(rates)), 'rate_cuts': {str(q): round(quant(rates, q / 100), 4) for q in (50, 60, 70, 75, 80, 85, 90, 95, 97, 99)}, 'count_cuts': {str(q): quant(counts, q / 100) for q in (50, 75, 90, 95, 99)}} say(name, OUT['lookup']['bands'][name]) # ---------------------------------------------------------------- 12. quirks say('\n== quirks') ny_last = [(b, cnt[LAST][b]) for b in cnt[LAST] if b in NYCHA] OUT['quirks'] = { 'nycha_lots_complaining_last_winter': len(ny_last), 'nycha_complaints_last_winter': sum(v for _, v in ny_last), 'nycha_pct_lots_any_last_winter': pct(len(ny_last), len(NYCHA)), 'nycha_per_100_apartments': round(100 * sum(v for _, v in ny_last) / sum(P[b]['units'] for b in NYCHA), 2), 'unmatched_bbl_complaints_last_winter': sum(v for b, v in cnt[LAST].items() if b not in P), 'unmatched_bbl_lots_last_winter': sum(1 for b in cnt[LAST] if b not in P), 'unmatched_condo_lot_range': sum(v for b, v in cnt[LAST].items() if b not in P and b[6:8] in ('75', '10', '11', '12')), 'multi_building_lots_3plus': sum(1 for b in U3 if P[b]['nb'] > 1), 'pct_complaints_last_winter_on_multi_building_lots': pct(sum(cnt[LAST].get(b, 0) for b in U3 if P[b]['nb'] > 1), tot_last), } bids = collections.defaultdict(set) for c in by_w[LAST]: if c[2]: bids[c[2]].add(c[3]) OUT['quirks']['pct_complaining_lots_with_2plus_hpd_buildings'] = pct(sum(1 for v in bids.values() if len(v) > 1), len(bids)) OUT['quirks']['pct_complaints_from_such_lots'] = pct(sum(cnt[LAST][b] for b, v in bids.items() if len(v) > 1), tot_last) import csv, glob # noqa: E402 B = {} for path in sorted(glob.glob(os.path.join(load.RAW, 'hpdbldg-*.csv'))): with open(path, newline='') as f: for r in csv.DictReader(f): B[r['buildingid']] = r act = [r for r in B.values() if r['recordstatus'] == 'Active' and r['lifecycle'] == 'Building'] h3 = [r for r in act if int(r['legalclassa'] or 0) >= 3 and r['managementprogram'] != 'NYCHA'] h6 = [r for r in h3 if int(r['legalclassa']) >= 6] bc = collections.Counter(c[3] for c in by_w[LAST]) nyb = [r for r in act if r['managementprogram'] == 'NYCHA'] OUT['hpd_list'] = {'buildings': len(B), 'active_buildings': len(act), 'active_3plus_classA_non_nycha': len(h3), 'pct_3plus_with_complaint_last_winter': pct(sum(1 for r in h3 if r['buildingid'] in bc), len(h3)), 'active_6plus': len(h6), 'pct_6plus_with_complaint_last_winter': pct(sum(1 for r in h6 if r['buildingid'] in bc), len(h6)), 'hpd_building_ids_complaining_last_winter': len(bc), 'nycha_buildings_listed': len(nyb), 'nycha_buildings_with_complaint_last_winter': sum(1 for r in nyb if r['buildingid'] in bc), 'nycha_complaints_last_winter': sum(bc[r['buildingid']] for r in nyb)} say('HPD building list', OUT['hpd_list']) # recording change: share of complaints marked building-wide, and share naming an apartment, by month around the change mm = collections.defaultdict(lambda: [0, 0, 0, 0]) for c in C: k = c[1][:7]; mm[k][0] += 1; mm[k][1] += c[5]; mm[k][2] += bool(c[4]); mm[k][3] += c[6] and bool(c[4]) OUT['recording_by_month'] = {k: {'complaints': v[0], 'pct_building_wide': pct(v[1], v[0]), 'pct_naming_apartment': pct(v[2], v[0]), 'pct_anonymous_with_apartment': pct(v[3], v[0])} for k, v in sorted(mm.items()) if '2021-01' <= k <= '2022-02'} for k, v in OUT['recording_by_month'].items(): say(k, v) OUT['quirks']['top_100_lots_share_last_winter'] = pct(sum(sorted(cnt[LAST].values(), reverse=True)[:100]), tot_last) say(OUT['quirks']) os.makedirs(os.path.join(load.HERE, 'derived'), exist_ok=True) with open(os.path.join(load.HERE, 'derived', 'results.json'), 'w') as f: json.dump(OUT, f, separators=(',', ':')) say('\nwrote derived/results.json', os.path.getsize(os.path.join(load.HERE, 'derived', 'results.json')), 'bytes')