ayanjawed commited on
Commit
13e3d7a
·
verified ·
1 Parent(s): 2035ea3

Future dates with Open-Meteo forecast weather, ± range and warnings

Browse files
Files changed (4) hide show
  1. README.md +3 -2
  2. data.json +0 -0
  3. index.html +23 -7
  4. predict.js +133 -28
README.md CHANGED
@@ -11,8 +11,9 @@ short_description: Hourly bus ridership predictions for 24 NYC bus routes
11
 
12
  # TransitPulse
13
 
14
- Predict hourly bus ridership for 24 MTA routes in New York (January to September 2025).
15
- Pick a route, a date and an hour; the page shows the predicted riders and the predicted profile for the whole day.
 
16
 
17
  This is a static Space: the Gradient Boosting model runs in your browser. Its 500 trees were exported from
18
  scikit-learn to `model.json`, and `predict.js` adds them up exactly like scikit-learn; the predictions were
 
11
 
12
  # TransitPulse
13
 
14
+ Predict hourly bus ridership for 24 MTA routes in New York. Pick a route, a date and an hour; the page shows the
15
+ predicted riders with a ± range and the predicted profile for the whole day. 2025 dates use recorded weather; later
16
+ dates use Open-Meteo's forecast (16 days ahead) or weather you enter. Weather data by Open-Meteo.com (CC BY 4.0).
17
 
18
  This is a static Space: the Gradient Boosting model runs in your browser. Its 500 trees were exported from
19
  scikit-learn to `model.json`, and `predict.js` adds them up exactly like scikit-learn; the predictions were
data.json CHANGED
The diff for this file is too large to render. See raw diff
 
index.html CHANGED
@@ -27,6 +27,7 @@
27
  .big { font-size: 2.4rem; font-weight: 700; line-height: 1.1; }
28
  .sub { color: var(--muted); }
29
  canvas { display: block; width: 100%; height: 260px; margin-top: 1rem; }
 
30
  footer { margin-top: 2rem; font-size: 0.9rem; color: var(--muted); }
31
  a { color: var(--accent); }
32
  </style>
@@ -44,7 +45,7 @@
44
  <div><label for="hour">Hour (0-23)</label><input id="hour" type="number" min="0" max="23" step="1" value="8"></div>
45
  </div>
46
 
47
- <label class="check"><input type="checkbox" id="customWeather"> Enter the weather myself (otherwise the recorded weather for that date is used)</label>
48
  <div class="grid" id="weatherBox" hidden>
49
  <div><label for="temperature_2m">Temperature (°C)</label><input id="temperature_2m" type="number" step="0.1" value="15"></div>
50
  <div><label for="precipitation">Rain (mm/h)</label><input id="precipitation" type="number" step="0.1" value="0"></div>
@@ -59,13 +60,17 @@
59
  <div id="result" hidden>
60
  <div class="sub" id="resultLabel"></div>
61
  <div class="big" id="resultValue"></div>
 
 
62
  <canvas id="chart" aria-label="Predicted riders for each hour of the day"></canvas>
63
  <div class="sub">Predicted riders for every hour of that day; the chosen hour is highlighted.</div>
64
  </div>
65
 
66
  <footer>
67
- <p><strong>Limits:</strong> the model only knows the 24 routes it was trained on and dates from 2025-01-06 to 2025-09-28.
68
- Typical error on the test period was about 65 riders per route-hour (about 14.5% of an average hour).</p>
 
 
69
  <p>Gradient Boosting model trained on MTA bus ridership, MTA schedules and Open-Meteo weather.
70
  The same model runs here in your browser: its 500 trees were exported from scikit-learn, and the predictions were checked to match the Python model.</p>
71
  <p><a href="https://huggingface.co/ayanjawed/transitpulse-planning-model">Model card</a> ·
@@ -122,7 +127,7 @@ function drawChart(profile, chosenHour) {
122
  });
123
  }
124
 
125
- function predict() {
126
  $("error").textContent = "";
127
  const hourText = $("hour").value.trim();
128
  const hour = /^-?\d+$/.test(hourText) ? Number(hourText) : NaN;
@@ -135,13 +140,24 @@ function predict() {
135
  }
136
  }
137
  try {
138
- const result = TransitPulse.predictHour(model, data, $("route").value, $("date").value, hour, weather);
 
139
  $("resultLabel").textContent = `Predicted riders on ${result.route} at ${result.hour}:00 on ${result.date}`;
140
- $("resultValue").textContent = result.predicted_riders.toLocaleString();
 
 
 
 
 
 
 
 
141
  $("result").hidden = false;
142
  drawChart(result.daily_profile, result.hour);
143
  } catch (error) {
144
  showError(error instanceof TransitPulse.InputError ? error.message : "Something went wrong: " + error.message);
 
 
145
  }
146
  }
147
 
@@ -155,7 +171,7 @@ Promise.all([fetch("model.json"), fetch("data.json")])
155
  $("route").disabled = false;
156
  $("date").min = data.first_date;
157
  $("date").max = data.last_date;
158
- $("date").value = data.default_date;
159
  $("go").disabled = false;
160
  predict();
161
  })
 
27
  .big { font-size: 2.4rem; font-weight: 700; line-height: 1.1; }
28
  .sub { color: var(--muted); }
29
  canvas { display: block; width: 100%; height: 260px; margin-top: 1rem; }
30
+ .warn { margin-top: 0.6rem; padding: 0.5rem 0.75rem; border-left: 4px solid var(--accent); background: var(--panel); }
31
  footer { margin-top: 2rem; font-size: 0.9rem; color: var(--muted); }
32
  a { color: var(--accent); }
33
  </style>
 
45
  <div><label for="hour">Hour (0-23)</label><input id="hour" type="number" min="0" max="23" step="1" value="8"></div>
46
  </div>
47
 
48
+ <label class="check"><input type="checkbox" id="customWeather"> Enter the weather myself (otherwise: recorded weather, or Open-Meteo's forecast for the next 16 days)</label>
49
  <div class="grid" id="weatherBox" hidden>
50
  <div><label for="temperature_2m">Temperature (°C)</label><input id="temperature_2m" type="number" step="0.1" value="15"></div>
51
  <div><label for="precipitation">Rain (mm/h)</label><input id="precipitation" type="number" step="0.1" value="0"></div>
 
60
  <div id="result" hidden>
61
  <div class="sub" id="resultLabel"></div>
62
  <div class="big" id="resultValue"></div>
63
+ <div class="sub" id="resultRange"></div>
64
+ <div id="warnings"></div>
65
  <canvas id="chart" aria-label="Predicted riders for each hour of the day"></canvas>
66
  <div class="sub">Predicted riders for every hour of that day; the chosen hour is highlighted.</div>
67
  </div>
68
 
69
  <footer>
70
+ <p><strong>Limits:</strong> the model only knows the 24 routes it was trained on, and it learned from January to September 2025.
71
+ Later dates use Open-Meteo weather (forecasts reach 16 days ahead) and are rough guesses, especially for March and October to December, which the model never saw.
72
+ Typical error on the test period was about 65 riders per route-hour (about 14.5% of an average hour); the ± range uses the validation error (56 riders).
73
+ Weather data by <a href="https://open-meteo.com/">Open-Meteo.com</a> (CC BY 4.0).</p>
74
  <p>Gradient Boosting model trained on MTA bus ridership, MTA schedules and Open-Meteo weather.
75
  The same model runs here in your browser: its 500 trees were exported from scikit-learn, and the predictions were checked to match the Python model.</p>
76
  <p><a href="https://huggingface.co/ayanjawed/transitpulse-planning-model">Model card</a> ·
 
127
  });
128
  }
129
 
130
+ async function predict() {
131
  $("error").textContent = "";
132
  const hourText = $("hour").value.trim();
133
  const hour = /^-?\d+$/.test(hourText) ? Number(hourText) : NaN;
 
140
  }
141
  }
142
  try {
143
+ $("go").disabled = true;
144
+ const result = await TransitPulse.predict(model, data, $("route").value, $("date").value, hour, weather);
145
  $("resultLabel").textContent = `Predicted riders on ${result.route} at ${result.hour}:00 on ${result.date}`;
146
+ $("resultValue").textContent = `${result.predicted_riders.toLocaleString()} ± ${result.typical_error}`;
147
+ $("resultRange").textContent = `Likely between ${result.likely_range[0].toLocaleString()} and ${result.likely_range[1].toLocaleString()} riders. Weather used: ${result.weather_source}.`;
148
+ $("warnings").innerHTML = "";
149
+ for (const text of result.warnings) {
150
+ const box = document.createElement("div");
151
+ box.className = "warn";
152
+ box.textContent = text;
153
+ $("warnings").appendChild(box);
154
+ }
155
  $("result").hidden = false;
156
  drawChart(result.daily_profile, result.hour);
157
  } catch (error) {
158
  showError(error instanceof TransitPulse.InputError ? error.message : "Something went wrong: " + error.message);
159
+ } finally {
160
+ $("go").disabled = false;
161
  }
162
  }
163
 
 
171
  $("route").disabled = false;
172
  $("date").min = data.first_date;
173
  $("date").max = data.last_date;
174
+ $("date").value = TransitPulse.defaultDate();
175
  $("go").disabled = false;
176
  predict();
177
  })
predict.js CHANGED
@@ -4,7 +4,7 @@
4
  // 1. one-hot encoding of bus_route and borough (the other 18 inputs pass through unchanged),
5
  // 2. a HistGradientBoostingRegressor with 500 trees.
6
  // app/build_hf_space.py exports that pipeline to model.json (the trees) and the lookup tables
7
- // (route facts, schedule, recorded weather, calendar) to data.json.
8
  // This file rebuilds the input row exactly like app/features.py and adds up the trees exactly
9
  // like scikit-learn does. app/verify_static_space.py checks that the results are identical.
10
  // The same file runs in the browser (window.TransitPulse) and in Node.js (module.exports) for the check.
@@ -62,8 +62,10 @@
62
  return Number.isInteger(n) ? n.toFixed(1) : String(n);
63
  }
64
 
 
 
65
  function checkRoute(data, route) {
66
- if (!Object.prototype.hasOwnProperty.call(data.routes, route)) {
67
  throw new InputError(`Unknown route '${route}'. Choose one of: ${data.route_names.join(", ")}.`);
68
  }
69
  }
@@ -74,8 +76,8 @@
74
  if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text) {
75
  throw new InputError(`Date '${date}' is not valid. Use the format YYYY-MM-DD.`);
76
  }
77
- if (!Object.prototype.hasOwnProperty.call(data.calendar, text)) {
78
- throw new InputError(`Date must be between ${data.first_date} and ${data.last_date}, the period the model was trained on.`);
79
  }
80
  return text;
81
  }
@@ -91,7 +93,7 @@
91
  const clean = {};
92
  for (const [name, value] of Object.entries(weather || {})) {
93
  if (value === null || value === undefined) continue;
94
- if (!Object.prototype.hasOwnProperty.call(data.weather_limits, name)) {
95
  throw new InputError(`Unknown weather field '${name}'. Allowed: ${Object.keys(data.weather_limits).join(", ")}.`);
96
  }
97
  const [low, high] = data.weather_limits[name];
@@ -103,17 +105,114 @@
103
  return clean;
104
  }
105
 
106
- // ---- building the model's input rows (mirrors features.day_features) --------------------
107
 
108
- function dayRows(data, route, date, weather) {
109
- checkRoute(data, route);
110
- const day = checkDate(data, date);
111
- const chosenWeather = checkWeather(data, weather);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- const calendar = data.calendar[day];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  const dayType = calendar.day_of_week < 5 ? "weekday" : calendar.day_of_week === 5 ? "saturday" : "sunday";
115
  const schedule = data.schedule[route][dayType];
116
- const recorded = data.weather[day];
117
 
118
  const rows = [];
119
  for (let hour = 0; hour < 24; hour++) {
@@ -131,29 +230,35 @@
131
  };
132
  Object.assign(row, data.routes[route]);
133
  data.schedule_columns.forEach((column, i) => { row[column] = schedule[hour][i]; });
134
- for (const column of Object.keys(data.weather_limits)) {
135
- row[column] = column in chosenWeather ? chosenWeather[column] : recorded[column][hour];
136
- }
137
  rows.push(row);
138
  }
139
- return rows;
140
  }
141
 
142
- // Predicted riders for each hour of the day: never below 0, rounded to whole riders.
143
- function predictDay(model, data, route, date, weather) {
144
- return dayRows(data, route, date, weather).map((row) => ({
145
- hour: row.hour,
146
- predicted_riders: roundHalfEven(Math.max(rawPredict(model, encode(model, row)), 0)),
147
- }));
148
- }
149
-
150
- function predictHour(model, data, route, date, hour, weather) {
151
  checkHour(hour);
152
- const profile = predictDay(model, data, route, date, weather);
153
- return { route, date, hour, predicted_riders: profile[hour].predicted_riders, daily_profile: profile };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  }
155
 
156
- const api = { InputError, treeValue, rawPredict, encode, roundHalfEven, dayRows, predictDay, predictHour };
 
157
  if (typeof module === "object" && module.exports) module.exports = api;
158
  else root.TransitPulse = api;
159
  })(typeof window !== "undefined" ? window : globalThis);
 
4
  // 1. one-hot encoding of bus_route and borough (the other 18 inputs pass through unchanged),
5
  // 2. a HistGradientBoostingRegressor with 500 trees.
6
  // app/build_hf_space.py exports that pipeline to model.json (the trees) and the lookup tables
7
+ // (route facts, schedule, recorded 2025 weather, calendar) to data.json.
8
  // This file rebuilds the input row exactly like app/features.py and adds up the trees exactly
9
  // like scikit-learn does. app/verify_static_space.py checks that the results are identical.
10
  // The same file runs in the browser (window.TransitPulse) and in Node.js (module.exports) for the check.
 
62
  return Number.isInteger(n) ? n.toFixed(1) : String(n);
63
  }
64
 
65
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
66
+
67
  function checkRoute(data, route) {
68
+ if (!has(data.routes, route)) {
69
  throw new InputError(`Unknown route '${route}'. Choose one of: ${data.route_names.join(", ")}.`);
70
  }
71
  }
 
76
  if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text) {
77
  throw new InputError(`Date '${date}' is not valid. Use the format YYYY-MM-DD.`);
78
  }
79
+ if (!has(data.calendar, text)) {
80
+ throw new InputError(`Date must be between ${data.first_date} and ${data.last_date}.`);
81
  }
82
  return text;
83
  }
 
93
  const clean = {};
94
  for (const [name, value] of Object.entries(weather || {})) {
95
  if (value === null || value === undefined) continue;
96
+ if (!has(data.weather_limits, name)) {
97
  throw new InputError(`Unknown weather field '${name}'. Allowed: ${Object.keys(data.weather_limits).join(", ")}.`);
98
  }
99
  const [low, high] = data.weather_limits[name];
 
105
  return clean;
106
  }
107
 
108
+ // ---- dates and weather (mirrors features.fetch_weather / day_weather / date_warnings) -----
109
 
110
+ const DAY_MS = 86400000;
111
+ const dayNumber = (text) => Date.parse(text + "T00:00:00Z") / DAY_MS;
112
+
113
+ function todayInNewYork() {
114
+ return new Date().toLocaleDateString("en-CA", { timeZone: "America/New_York" }); // YYYY-MM-DD
115
+ }
116
+
117
+ function addDays(text, days) {
118
+ return new Date(Date.parse(text + "T00:00:00Z") + days * DAY_MS).toISOString().slice(0, 10);
119
+ }
120
+
121
+ function defaultDate() {
122
+ return addDays(todayInNewYork(), 1);
123
+ }
124
+
125
+ const weatherCache = {};
126
+
127
+ // Hourly weather for a date after the saved 2025 file, from Open-Meteo (CC BY 4.0).
128
+ async function fetchWeather(data, date, today = todayInNewYork()) {
129
+ const cached = weatherCache[date];
130
+ if (cached && Date.now() - cached.time < 3600000) return cached.result;
131
+ const ow = data.open_meteo;
132
+ if (dayNumber(date) > dayNumber(today) + ow.forecast_days - 1) {
133
+ throw new InputError(`No weather forecast exists yet for ${date} (forecasts reach ${ow.forecast_days} days ahead). Enter the weather yourself.`);
134
+ }
135
+ const archive = dayNumber(date) < dayNumber(today) - ow.archive_delay_days;
136
+ const params = new URLSearchParams({
137
+ latitude: ow.latitude, longitude: ow.longitude, hourly: Object.keys(data.weather_limits).join(","),
138
+ timezone: "America/New_York", start_date: date, end_date: date,
139
+ });
140
+ const problem = new InputError(`Could not get the weather for ${date} from Open-Meteo. Try again, or enter the weather yourself.`);
141
+ let hourly;
142
+ try {
143
+ const response = await fetch(`${archive ? ow.archive_url : ow.forecast_url}?${params}`);
144
+ if (!response.ok) throw problem;
145
+ hourly = (await response.json()).hourly;
146
+ if (!hourly) throw problem;
147
+ } catch (error) {
148
+ throw problem;
149
+ }
150
+ const values = {};
151
+ for (const column of Object.keys(data.weather_limits)) {
152
+ const byHour = {};
153
+ (hourly[column] || []).forEach((value, i) => {
154
+ const stamp = hourly.time[i];
155
+ const hour = Number(stamp.slice(11, 13));
156
+ if (stamp.startsWith(date) && !(hour in byHour) && value !== null) byHour[hour] = value;
157
+ });
158
+ const known = Object.values(byHour);
159
+ if (known.length === 0) throw problem;
160
+ // a missing hour (for example when clocks change) takes the value of the hour before it, or after it at midnight
161
+ const series = [];
162
+ for (let hour = 0; hour < 24; hour++) series.push(hour in byHour ? byHour[hour] : null);
163
+ for (let hour = 0; hour < 24; hour++) {
164
+ if (series[hour] === null) series[hour] = hour > 0 ? series[hour - 1] : series.find((v) => v !== null);
165
+ }
166
+ values[column] = series;
167
+ }
168
+ const result = { values, source: archive ? "archive" : "forecast" };
169
+ weatherCache[date] = { time: Date.now(), result };
170
+ return result;
171
+ }
172
 
173
+ // 24 hourly values per weather column and where they came from. `fetched` is fetchWeather's result when it was needed.
174
+ function dayWeather(data, date, weather, fetched) {
175
+ const columns = Object.keys(data.weather_limits);
176
+ let base = null, source = null;
177
+ if (has(data.weather, date)) {
178
+ base = data.weather[date];
179
+ source = "recorded weather (Open-Meteo)";
180
+ } else if (!columns.every((c) => c in weather)) {
181
+ base = fetched.values;
182
+ source = fetched.source === "archive" ? "Open-Meteo historical weather" : "Open-Meteo forecast";
183
+ }
184
+ const out = {};
185
+ for (const c of columns) out[c] = c in weather ? Array(24).fill(weather[c]) : base[c];
186
+ if (Object.keys(weather).length === columns.length) source = "your weather";
187
+ else if (Object.keys(weather).length > 0) source += ", with your values where given";
188
+ return { columns: out, source };
189
+ }
190
+
191
+ function needsFetch(data, date, weather) {
192
+ return !has(data.weather, date) && !Object.keys(data.weather_limits).every((c) => c in weather);
193
+ }
194
+
195
+ function dateWarnings(data, date) {
196
+ const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September",
197
+ "October", "November", "December"];
198
+ const month = Number(date.slice(5, 7));
199
+ const warnings = [];
200
+ if (!data.trained_months.includes(month)) {
201
+ warnings.push(`The model never saw ${months[month - 1]} in training (it learned from January, February and April to September 2025), so treat this as a rough guess.`);
202
+ }
203
+ if (dayNumber(date) > dayNumber(data.last_recorded_date)) {
204
+ warnings.push("This date is after the training data (January to September 2025); bus service may have changed since then.");
205
+ }
206
+ return warnings;
207
+ }
208
+
209
+ // ---- building the model's input rows (mirrors features.day_features) --------------------
210
+
211
+ function dayRows(data, route, date, weather, fetched) {
212
+ const calendar = data.calendar[date];
213
  const dayType = calendar.day_of_week < 5 ? "weekday" : calendar.day_of_week === 5 ? "saturday" : "sunday";
214
  const schedule = data.schedule[route][dayType];
215
+ const { columns, source } = dayWeather(data, date, weather, fetched);
216
 
217
  const rows = [];
218
  for (let hour = 0; hour < 24; hour++) {
 
230
  };
231
  Object.assign(row, data.routes[route]);
232
  data.schedule_columns.forEach((column, i) => { row[column] = schedule[hour][i]; });
233
+ for (const column of Object.keys(columns)) row[column] = columns[column][hour];
 
 
234
  rows.push(row);
235
  }
236
+ return { rows, source };
237
  }
238
 
239
+ // Everything the page shows; same fields as features.predict. Checks run in the same order as the Python app.
240
+ async function predict(model, data, route, date, hour, weather, today = todayInNewYork()) {
 
 
 
 
 
 
 
241
  checkHour(hour);
242
+ checkRoute(data, route);
243
+ const day = checkDate(data, date);
244
+ const chosen = checkWeather(data, weather);
245
+ const fetched = needsFetch(data, day, chosen) ? await fetchWeather(data, day, today) : null;
246
+ const { rows, source } = dayRows(data, route, day, chosen, fetched);
247
+ const profile = rows.map((row) => roundHalfEven(Math.max(rawPredict(model, encode(model, row)), 0)));
248
+ const value = profile[hour];
249
+ return {
250
+ route, date: day, hour,
251
+ predicted_riders: value,
252
+ typical_error: data.typical_error,
253
+ likely_range: [Math.max(0, value - data.typical_error), value + data.typical_error],
254
+ daily_profile: profile.map((p, h) => ({ hour: h, predicted_riders: p })),
255
+ warnings: dateWarnings(data, day),
256
+ weather_source: source,
257
+ };
258
  }
259
 
260
+ const api = { InputError, treeValue, rawPredict, encode, roundHalfEven, dayRows, predict, fetchWeather,
261
+ todayInNewYork, defaultDate };
262
  if (typeof module === "object" && module.exports) module.exports = api;
263
  else root.TransitPulse = api;
264
  })(typeof window !== "undefined" ? window : globalThis);