File size: 13,203 Bytes
304d3b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Riprap β€” Bulk mode (schools register).

const SOURCE_LABELS = {
  geocode:                "NYC DCP Geosearch",
  sandy:                  "NYC OpenData 5xsi-dfpx β€” Sandy 2012 inundation",
  dep_extreme_2080:       "NYC DEP Stormwater β€” Extreme 3.66 in/hr + 2080 SLR",
  dep_moderate_2050:      "NYC DEP Stormwater β€” Moderate 2.13 in/hr + 2050 SLR",
  dep_moderate_current:   "NYC DEP Stormwater β€” Moderate 2.13 in/hr current",
  floodnet:               "FloodNet NYC β€” live ultrasonic sensor network",
  nyc311:                 "NYC 311 (Socrata erm2-nwe9) β€” flood descriptors",
  microtopo:              "USGS 3DEP 30 m DEM via py3dep",
  ida_hwm:                "USGS STN β€” Hurricane Ida 2021 HWMs (Event 312, NY)",
  prithvi_water:          "Prithvi-EO 2.0 (300M, NASA/IBM) Sen1Floods11 β€” satellite water segmentation",
  rag_dep_2013:           "NYC DEP Wastewater Resiliency Plan (2013)",
  rag_nycha:              "NYCHA β€” Flood Resilience: Lessons Learned",
  rag_coned:              "Con Edison Climate Change Resilience Plan (Case 22-E-0222)",
  rag_mta:                "MTA Climate Resilience Roadmap (Oct 2025)",
  rag_comptroller:        "NYC Comptroller β€” \"Is NYC Ready for Rain?\" (2024)",
};

const $ = (s) => document.querySelector(s);

let allRows = [];
let filteredRows = [];
let selected = null;
let detailMap = null;

function tierBadge(t) {
  const cls = "tier-badge tier-" + t;
  return `<span class="${cls}">${t}</span>`;
}

function yn(b) { return b ? '<span class="yn yes">●</span>' : '<span class="yn no">β—‹</span>'; }

function renderTable() {
  const tbody = $("#regBody");
  tbody.innerHTML = filteredRows.map((r, i) => {
    const snap = r.snap || {};
    const sandy  = snap.sandy ? yn(true) : yn(false);
    const dep80  = snap.dep && snap.dep.dep_extreme_2080 && snap.dep.dep_extreme_2080.depth_class > 0 ? yn(true) : yn(false);
    const c311   = (snap.nyc311 && snap.nyc311.n) || 0;
    const fnEv   = (snap.floodnet && snap.floodnet.n_flood_events_3y) || 0;
    const idaN   = (snap.ida_hwm && snap.ida_hwm.n_within_radius) || 0;
    return `<tr data-idx="${i}">
      <td>${tierBadge(r.tier)}</td>
      <td class="num">${r.score}</td>
      <td>
        <div class="rname">${r.name}</div>
        <div class="raddr">${r.address || ""}</div>
      </td>
      <td>${r.borough || ""}</td>
      <td class="num">${sandy}</td>
      <td class="num">${dep80}</td>
      <td class="num">${c311 || ""}</td>
      <td class="num">${fnEv || ""}</td>
      <td class="num">${idaN || ""}</td>
    </tr>`;
  }).join("");

  tbody.querySelectorAll("tr").forEach((tr) => {
    tr.addEventListener("click", () => selectRow(parseInt(tr.dataset.idx, 10)));
  });
}

function applyFilters() {
  const q = ($("#filter").value || "").toLowerCase();
  const boro = $("#boroughFilter").value || "";
  filteredRows = allRows.filter((r) => {
    if (boro && r.borough !== boro) return false;
    if (!q) return true;
    return (
      (r.name || "").toLowerCase().includes(q) ||
      (r.address || "").toLowerCase().includes(q) ||
      (r.borough || "").toLowerCase().includes(q) ||
      (r.bbl || "").toString().includes(q)
    );
  });
  renderTable();
}

function selectRow(idx) {
  selected = filteredRows[idx];
  if (!selected) return;
  $("#detailEmpty").classList.add("hidden");
  $("#detailBody").classList.remove("hidden");
  $("#detailHeader").innerHTML = `
    <div class="rname">${selected.name}</div>
    <div class="raddr">${selected.address}, ${selected.borough}</div>
    <div class="rmeta">BBL: ${selected.bbl || "β€”"} Β· Tier ${selected.tier} Β· Score ${selected.score}</div>`;
  renderDetail(selected);
}

function renderDetail(row) {
  const snap = row.snap || {};
  // glance
  const rows = [];
  if (snap.sandy) rows.push({c:"hit", mark:"β– ", html:"Inside <strong>Sandy 2012</strong> inundation extent"});
  else            rows.push({c:"miss",mark:"β–‘", html:"Outside Sandy 2012 inundation extent"});
  const dep = snap.dep || {};
  const depHits = Object.entries(dep).filter(([_,v]) => (v.depth_class || 0) > 0);
  if (depHits.length) {
    for (const [scen, v] of depHits) {
      const lbl = scen.replace("dep_","").replace(/_/g, " ");
      rows.push({c:"hit", mark:"β– ", html:`Inside DEP ${lbl} β€” <strong>${v.depth_label}</strong>`});
    }
  } else {
    rows.push({c:"miss", mark:"β–‘", html:"Outside all DEP stormwater scenarios"});
  }
  const fn = snap.floodnet;
  if (fn && fn.n_sensors) {
    if (fn.n_flood_events_3y > 0) {
      const peak = fn.peak_event;
      const peakStr = peak && peak.max_depth_mm ? `, peak <span class="gnum">${peak.max_depth_mm} mm</span>` : "";
      rows.push({c:"hit", mark:"β– ", html:`<span class="gnum">${fn.n_flood_events_3y}</span> FloodNet events (3 yr)${peakStr}`});
    }
  }
  const ida = snap.ida_hwm;
  if (ida && ida.n_within_radius > 0) {
    const ht = ida.max_height_above_gnd_ft != null ? `up to <span class="gnum">${ida.max_height_above_gnd_ft} ft</span> above ground` : "";
    rows.push({c:"hit", mark:"β– ", html:`<span class="gnum">${ida.n_within_radius}</span> Ida HWMs ≀${ida.radius_m} m${ht ? ", " + ht : ""}`});
  }
  const mt = snap.microtopo;
  if (mt) {
    rows.push({c:"note", mark:"β—†", html:`Elevation <span class="gnum">${mt.point_elev_m} m</span>; lower than <span class="gnum">${mt.rel_elev_pct_200m}%</span> of nearby (200 m)`});
  }
  const c311 = snap.nyc311;
  if (c311 && c311.n > 0) {
    rows.push({c:"note", mark:"β—†", html:`<span class="gnum">${c311.n}</span> 311 flood complaints ≀${c311.radius_m} m, ${c311.years} yr`});
  }
  $("#detailGlance").innerHTML = rows.map(r =>
    `<li class="${r.c}"><span class="gmark">${r.mark}</span><span class="gtext">${r.html}</span></li>`).join("");

  // paragraph
  const para = snap.paragraph;
  const noPara = $("#detailNoPara");
  if (para) {
    $("#detailParagraph").innerHTML = (para || "").replace(/\[([a-z0-9_]+)\]/gi,
      (_, d) => `<span class="cite" title="document id: ${d}">[${d}]</span>`);
    noPara.classList.add("hidden");
  } else {
    $("#detailParagraph").innerHTML = "";
    noPara.classList.remove("hidden");
  }

  // sources
  const fired = new Set([...(para || "").matchAll(/\[([a-z0-9_]+)\]/g)].map(m => m[1]));
  const order = [
    "sandy", "dep_extreme_2080", "dep_moderate_2050", "dep_moderate_current",
    "floodnet", "ida_hwm", "microtopo", "nyc311",
    "rag_dep_2013", "rag_nycha", "rag_coned", "rag_mta", "rag_comptroller",
  ];
  const present = new Set();
  if (snap.sandy) present.add("sandy");
  for (const [k, v] of Object.entries(snap.dep || {})) {
    if ((v.depth_class || 0) > 0) present.add(k);
  }
  if (snap.floodnet && snap.floodnet.n_sensors > 0) present.add("floodnet");
  if (snap.ida_hwm && snap.ida_hwm.n_within_radius > 0) present.add("ida_hwm");
  if (snap.microtopo) present.add("microtopo");
  if (snap.nyc311 && snap.nyc311.n > 0) present.add("nyc311");
  if (snap.rag) for (const h of snap.rag) present.add(h.doc_id);

  $("#detailSources").innerHTML = order.filter(d => present.has(d)).map(d => {
    const dim = fired.has(d) ? "" : ' style="opacity:0.5"';
    return `<li${dim}><span class="src-tag">${d}</span><span class="src-cite">${SOURCE_LABELS[d] || d}</span></li>`;
  }).join("");

  showDetailMap(row);
}

function showDetailMap(row) {
  const div = $("#detailMap");
  if (!detailMap) {
    detailMap = new maplibregl.Map({
      container: "detailMap",
      style: {
        version: 8,
        sources: {
          carto: { type: "raster",
            tiles: ["https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"],
            tileSize: 256, attribution: "Β© OSM Β· CARTO" },
        },
        layers: [{ id: "bg", type: "raster", source: "carto" }],
      },
      center: [row.lon, row.lat], zoom: 14, attributionControl: { compact: true },
    });
    detailMap.on("load", () => {
      detailMap.addSource("addr", { type: "geojson", data: { type:"FeatureCollection", features:[] }});
      detailMap.addLayer({ id:"addr-marker", type:"circle", source:"addr",
        paint: { "circle-radius": 9, "circle-color": "#1642DF", "circle-stroke-color":"#fff", "circle-stroke-width": 2.5 }});
    });
  }
  const setMarker = () => {
    detailMap.getSource("addr").setData({ type:"FeatureCollection", features:[
      { type:"Feature", geometry:{ type:"Point", coordinates:[row.lon, row.lat] }, properties:{} }
    ]});
    detailMap.flyTo({ center: [row.lon, row.lat], zoom: 14 });
  };
  if (detailMap.loaded()) setMarker(); else detailMap.once("load", setMarker);
}

async function generateLiveParagraph() {
  if (!selected) return;
  const btn = $("#livePara"); btn.disabled = true; btn.textContent = "Generating…";
  try {
    const u = `/api/stream?q=${encodeURIComponent(selected.address + ", " + selected.borough)}`;
    // collect SSE final event
    const text = await new Promise((resolve, reject) => {
      const es = new EventSource(u);
      es.addEventListener("final", (m) => { resolve(JSON.parse(m.data)); es.close(); });
      es.addEventListener("error", () => { reject(new Error("stream error")); es.close(); });
      setTimeout(() => { reject(new Error("timeout")); es.close(); }, 90000);
    });
    if (text.paragraph) {
      selected.snap.paragraph = text.paragraph;
      selected.snap.rag = text.rag || selected.snap.rag;
      renderDetail(selected);
    }
  } catch (e) {
    btn.textContent = "Failed: " + e.message;
    btn.disabled = false;
  }
}

function exportCsv() {
  const cols = ["tier","score","name","address","borough","bbl","bin",
                "lat","lon","sandy","dep_extreme_2080","floodnet_events_3y",
                "ida_hwms_800m","nyc311_5y"];
  const lines = [cols.join(",")];
  for (const r of filteredRows) {
    const s = r.snap || {};
    const row = [
      r.tier, r.score, JSON.stringify(r.name), JSON.stringify(r.address || ""),
      r.borough || "", r.bbl || "", r.bin || "", r.lat, r.lon,
      s.sandy ? 1 : 0,
      (s.dep && s.dep.dep_extreme_2080 && s.dep.dep_extreme_2080.depth_class) || 0,
      (s.floodnet && s.floodnet.n_flood_events_3y) || 0,
      (s.ida_hwm && s.ida_hwm.n_within_radius) || 0,
      (s.nyc311 && s.nyc311.n) || 0,
    ];
    lines.push(row.join(","));
  }
  const blob = new Blob([lines.join("\n")], { type: "text/csv" });
  download(blob, "riprap_schools_register.csv");
}

function exportGeojson() {
  const features = filteredRows.map((r) => ({
    type: "Feature",
    geometry: { type: "Point", coordinates: [r.lon, r.lat] },
    properties: {
      tier: r.tier, score: r.score, name: r.name, address: r.address,
      borough: r.borough, bbl: r.bbl, bin: r.bin,
      sandy: !!(r.snap && r.snap.sandy),
      dep_extreme_2080: (r.snap && r.snap.dep && r.snap.dep.dep_extreme_2080 && r.snap.dep.dep_extreme_2080.depth_class) || 0,
    },
  }));
  const blob = new Blob([JSON.stringify({ type: "FeatureCollection", features })],
                        { type: "application/geo+json" });
  download(blob, "riprap_schools_register.geojson");
}

function download(blob, filename) {
  const u = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = u; a.download = filename;
  document.body.appendChild(a); a.click();
  setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(u); }, 200);
}

// Asset class is parsed from URL path: /register/<asset_class>
const ASSET_CLASS = (location.pathname.match(/\/register\/([^\/?]+)/) || [])[1] || "schools";

const ASSET_TITLES = {
  schools:        "NYC public schools β€” flood exposure register",
  nycha:          "NYCHA developments β€” flood exposure register",
  mta_entrances:  "MTA subway entrances β€” flood exposure register",
};
document.title = `Riprap β€” ${ASSET_TITLES[ASSET_CLASS] || ASSET_CLASS}`;
const tagSpan = document.querySelector(".brand-tag");
if (tagSpan) tagSpan.textContent = ASSET_TITLES[ASSET_CLASS] || ASSET_CLASS;

const classPicker = document.getElementById("classPicker");
if (classPicker) {
  classPicker.value = ASSET_CLASS;
  classPicker.addEventListener("change", () => {
    location.href = `/register/${classPicker.value}`;
  });
}

(async function init() {
  const r = await fetch(`/api/register/${ASSET_CLASS}`);
  if (!r.ok) {
    const script = `python scripts/build_${ASSET_CLASS}_register.py`;
    $("#regBody").innerHTML = `<tr><td colspan="9" style="padding: 20px; color: var(--text-muted);">Register not built. Run <code>${script}</code>.</td></tr>`;
    return;
  }
  const data = await r.json();
  allRows = data.rows || [];
  filteredRows = allRows.slice();

  // tier counts
  $("#totalCount").textContent = allRows.length;
  $("#tier1Count").textContent = allRows.filter(r => r.tier === 1).length;
  $("#tier2Count").textContent = allRows.filter(r => r.tier === 2).length;
  $("#tier3Count").textContent = allRows.filter(r => r.tier === 3).length;

  renderTable();

  $("#filter").addEventListener("input", applyFilters);
  $("#boroughFilter").addEventListener("change", applyFilters);
  $("#exportCsv").addEventListener("click", exportCsv);
  $("#exportGeojson").addEventListener("click", exportGeojson);
  $("#livePara").addEventListener("click", generateLiveParagraph);
})();