#!/usr/bin/env python3 """Download the raw inputs for the heat-complaint analysis into analysis/heat/raw/. Standard library only. Re-running skips files that already exist. Run: python3 -I analysis/heat/fetch.py Sources HPD Housing Maintenance Code Complaints and Problems data.cityofnewyork.us ygpa-z7cr PLUTO (tax lots) data.cityofnewyork.us 64uk-42ks Buildings Subject to HPD Jurisdiction data.cityofnewyork.us kj4p-ruqc NOAA daily summaries, Central Park (USW00094728) ncei.noaa.gov """ import os, sys, time, urllib.parse, urllib.request from concurrent.futures import ThreadPoolExecutor HERE = os.path.dirname(os.path.abspath(__file__)) RAW = os.path.join(HERE, 'raw') SODA = 'https://data.cityofnewyork.us/resource/' FIRST = (2016, 10) # first month fetched END = '2026-11-16' # complaints received before this date (the day the analysis was run) def get(url, dest, tries=6): if os.path.exists(dest) and os.path.getsize(dest) > 0: return for i in range(tries): try: req = urllib.request.Request(url, headers={'User-Agent': 'heat-analysis/1.0'}) with urllib.request.urlopen(req, timeout=300) as r: body = r.read() with open(dest + '.part', 'wb') as f: f.write(body) os.replace(dest + '.part', dest) print('ok', os.path.basename(dest), len(body), flush=True) return except Exception as e: # noqa: BLE001 print('retry', os.path.basename(dest), e, flush=True) time.sleep(5 * (i + 1)) raise SystemExit('failed: ' + url) def soda(dataset, params, fmt='csv'): return SODA + dataset + '.' + fmt + '?' + urllib.parse.urlencode(params) def months(): y, m = FIRST while (y, m) <= (int(END[:4]), int(END[5:7])): ny, nm = (y + 1, 1) if m == 12 else (y, m + 1) yield '%04d-%02d-01' % (y, m), min('%04d-%02d-01' % (ny, nm), END) y, m = ny, nm def main(): os.makedirs(RAW, exist_ok=True) jobs = [] # 1. Heat and hot water problem rows, one file per month. A complaint can carry # several problem rows; the analysis de-duplicates on complaint_id. cols = ('complaint_id,problem_id,received_date,bbl,building_id,borough,apartment,unit_type,' 'space_type,problem_code,problem_duplicate_flag,complaint_anonymous_flag') for a, b in months(): if a >= b: continue where = "major_category='HEAT/HOT WATER' AND received_date>='%s' AND received_date<'%s'" % (a, b) jobs.append((soda('ygpa-z7cr', {'$select': cols, '$where': where, '$order': 'problem_id', '$limit': 1000000}), os.path.join(RAW, 'heat-%s.csv' % a[:7]))) # 2. PLUTO: every lot with at least one residential unit. pcols = 'bbl,unitsres,unitstotal,yearbuilt,numfloors,numbldgs,bldgclass,ownername,landuse,borough' for i in range(20): jobs.append((soda('64uk-42ks', {'$select': pcols, '$where': 'unitsres>=1', '$order': 'bbl', '$limit': 50000, '$offset': i * 50000}), os.path.join(RAW, 'pluto-%02d.csv' % i))) # 3. HPD's own building list (used for the universe and the NYCHA check). for i in range(8): jobs.append((soda('kj4p-ruqc', {'$order': 'buildingid', '$limit': 50000, '$offset': i * 50000}), os.path.join(RAW, 'hpdbldg-%02d.csv' % i))) # 4. Daily high and low at Central Park. noaa = ('https://www.ncei.noaa.gov/access/services/data/v1?dataset=daily-summaries&stations=USW00094728' '&startDate=2016-07-01&endDate=%s&dataTypes=TMIN,TMAX&units=standard&format=json' % END) jobs.append((noaa, os.path.join(RAW, 'temps.json'))) # 5. Row counts by category and year, to document the category rename and coverage. jobs.append((soda('ygpa-z7cr', {'$select': 'major_category,date_extract_y(received_date) as y,count(*) as n,count(distinct complaint_id) as c', '$where': "major_category like '%HEAT%'", '$group': 'major_category,y', '$order': 'y'}, 'json'), os.path.join(RAW, 'category-years.json'))) with ThreadPoolExecutor(4) as ex: list(ex.map(lambda j: get(*j), jobs)) if __name__ == '__main__': main()