Spaces:
Running
Running
Future dates with Open-Meteo forecast weather, ± range and warnings
Browse filesFiles changed (4)
- README.md+3-2
- data.json
- index.html+23-7
- predict.js+133-28
10 unmodified lines111213141516171810 unmodified lines# TransitPulsePredict hourly bus ridership for 24 MTA routes in New York (January to September 2025).Pick a route, a date and an hour; the page shows the predicted riders and the predicted profile for the whole day.This is a static Space: the Gradient Boosting model runs in your browser. Its 500 trees were exported fromscikit-learn to `model.json`, and `predict.js` adds them up exactly like scikit-learn; the predictions were10 unmodified lines11121314151617181910 unmodified lines# TransitPulsePredict hourly bus ridership for 24 MTA routes in New York. Pick a route, a date and an hour; the page shows thepredicted riders with a ± range and the predicted profile for the whole day. 2025 dates use recorded weather; laterdates use Open-Meteo's forecast (16 days ahead) or weather you enter. Weather data by Open-Meteo.com (CC BY 4.0).This is a static Space: the Gradient Boosting model runs in your browser. Its 500 trees were exported fromscikit-learn to `model.json`, and `predict.js` adds them up exactly like scikit-learn; the predictions were
26 unmodified lines27282930313211 unmodified lines444546474849508 unmodified lines5960616263646566676869707150 unmodified lines1221231241251261271286 unmodified lines1351361371381391401411421431441451461477 unmodified lines15515615715815916016126 unmodified lines.big { font-size: 2.4rem; font-weight: 700; line-height: 1.1; }.sub { color: var(--muted); }canvas { display: block; width: 100%; height: 260px; margin-top: 1rem; }footer { margin-top: 2rem; font-size: 0.9rem; color: var(--muted); }a { color: var(--accent); }</style>11 unmodified lines<div><label for="hour">Hour (0-23)</label><input id="hour" type="number" min="0" max="23" step="1" value="8"></div></div><label class="check"><input type="checkbox" id="customWeather"> Enter the weather myself (otherwise the recorded weather for that date is used)</label><div class="grid" id="weatherBox" hidden><div><label for="temperature_2m">Temperature (°C)</label><input id="temperature_2m" type="number" step="0.1" value="15"></div><div><label for="precipitation">Rain (mm/h)</label><input id="precipitation" type="number" step="0.1" value="0"></div>8 unmodified lines<div id="result" hidden><div class="sub" id="resultLabel"></div><div class="big" id="resultValue"></div><canvas id="chart" aria-label="Predicted riders for each hour of the day"></canvas><div class="sub">Predicted riders for every hour of that day; the chosen hour is highlighted.</div></div><footer><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.Typical error on the test period was about 65 riders per route-hour (about 14.5% of an average hour).</p><p>Gradient Boosting model trained on MTA bus ridership, MTA schedules and Open-Meteo weather.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><p><a href="https://huggingface.co/ayanjawed/transitpulse-planning-model">Model card</a> ·50 unmodified lines});}function predict() {$("error").textContent = "";const hourText = $("hour").value.trim();const hour = /^-?\d+$/.test(hourText) ? Number(hourText) : NaN;6 unmodified lines}}try {const result = TransitPulse.predictHour(model, data, $("route").value, $("date").value, hour, weather);$("resultLabel").textContent = `Predicted riders on ${result.route} at ${result.hour}:00 on ${result.date}`;$("resultValue").textContent = result.predicted_riders.toLocaleString();$("result").hidden = false;drawChart(result.daily_profile, result.hour);} catch (error) {showError(error instanceof TransitPulse.InputError ? error.message : "Something went wrong: " + error.message);}}7 unmodified lines$("route").disabled = false;$("date").min = data.first_date;$("date").max = data.last_date;$("date").value = data.default_date;$("go").disabled = false;predict();})26 unmodified lines2728293031323311 unmodified lines454647484950518 unmodified lines606162636465666768697071727374757650 unmodified lines1271281291301311321336 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621637 unmodified lines17117217317417517617726 unmodified lines.big { font-size: 2.4rem; font-weight: 700; line-height: 1.1; }.sub { color: var(--muted); }canvas { display: block; width: 100%; height: 260px; margin-top: 1rem; }.warn { margin-top: 0.6rem; padding: 0.5rem 0.75rem; border-left: 4px solid var(--accent); background: var(--panel); }footer { margin-top: 2rem; font-size: 0.9rem; color: var(--muted); }a { color: var(--accent); }</style>11 unmodified lines<div><label for="hour">Hour (0-23)</label><input id="hour" type="number" min="0" max="23" step="1" value="8"></div></div><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><div class="grid" id="weatherBox" hidden><div><label for="temperature_2m">Temperature (°C)</label><input id="temperature_2m" type="number" step="0.1" value="15"></div><div><label for="precipitation">Rain (mm/h)</label><input id="precipitation" type="number" step="0.1" value="0"></div>8 unmodified lines<div id="result" hidden><div class="sub" id="resultLabel"></div><div class="big" id="resultValue"></div><div class="sub" id="resultRange"></div><div id="warnings"></div><canvas id="chart" aria-label="Predicted riders for each hour of the day"></canvas><div class="sub">Predicted riders for every hour of that day; the chosen hour is highlighted.</div></div><footer><p><strong>Limits:</strong> the model only knows the 24 routes it was trained on, and it learned from January to September 2025.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.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).Weather data by <a href="https://open-meteo.com/">Open-Meteo.com</a> (CC BY 4.0).</p><p>Gradient Boosting model trained on MTA bus ridership, MTA schedules and Open-Meteo weather.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><p><a href="https://huggingface.co/ayanjawed/transitpulse-planning-model">Model card</a> ·50 unmodified lines});}async function predict() {$("error").textContent = "";const hourText = $("hour").value.trim();const hour = /^-?\d+$/.test(hourText) ? Number(hourText) : NaN;6 unmodified lines}}try {$("go").disabled = true;const result = await TransitPulse.predict(model, data, $("route").value, $("date").value, hour, weather);$("resultLabel").textContent = `Predicted riders on ${result.route} at ${result.hour}:00 on ${result.date}`;$("resultValue").textContent = `${result.predicted_riders.toLocaleString()} ± ${result.typical_error}`;$("resultRange").textContent = `Likely between ${result.likely_range[0].toLocaleString()} and ${result.likely_range[1].toLocaleString()} riders. Weather used: ${result.weather_source}.`;$("warnings").innerHTML = "";for (const text of result.warnings) {const box = document.createElement("div");box.className = "warn";box.textContent = text;$("warnings").appendChild(box);}$("result").hidden = false;drawChart(result.daily_profile, result.hour);} catch (error) {showError(error instanceof TransitPulse.InputError ? error.message : "Something went wrong: " + error.message);} finally {$("go").disabled = false;}}7 unmodified lines$("route").disabled = false;$("date").min = data.first_date;$("date").max = data.last_date;$("date").value = TransitPulse.defaultDate();$("go").disabled = false;predict();})
3 unmodified lines4567891051 unmodified lines62636465666768694 unmodified lines74757677787980819 unmodified lines919293949596975 unmodified lines10310410510610710810911011111211311411511611711811911 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581593 unmodified lines// 1. one-hot encoding of bus_route and borough (the other 18 inputs pass through unchanged),// 2. a HistGradientBoostingRegressor with 500 trees.// app/build_hf_space.py exports that pipeline to model.json (the trees) and the lookup tables// (route facts, schedule, recorded weather, calendar) to data.json.// This file rebuilds the input row exactly like app/features.py and adds up the trees exactly// like scikit-learn does. app/verify_static_space.py checks that the results are identical.// The same file runs in the browser (window.TransitPulse) and in Node.js (module.exports) for the check.51 unmodified linesreturn Number.isInteger(n) ? n.toFixed(1) : String(n);}function checkRoute(data, route) {if (!Object.prototype.hasOwnProperty.call(data.routes, route)) {throw new InputError(`Unknown route '${route}'. Choose one of: ${data.route_names.join(", ")}.`);}}4 unmodified linesif (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text) {throw new InputError(`Date '${date}' is not valid. Use the format YYYY-MM-DD.`);}if (!Object.prototype.hasOwnProperty.call(data.calendar, text)) {throw new InputError(`Date must be between ${data.first_date} and ${data.last_date}, the period the model was trained on.`);}return text;}9 unmodified linesconst clean = {};for (const [name, value] of Object.entries(weather || {})) {if (value === null || value === undefined) continue;if (!Object.prototype.hasOwnProperty.call(data.weather_limits, name)) {throw new InputError(`Unknown weather field '${name}'. Allowed: ${Object.keys(data.weather_limits).join(", ")}.`);}const [low, high] = data.weather_limits[name];5 unmodified linesreturn clean;}// ---- building the model's input rows (mirrors features.day_features) --------------------function dayRows(data, route, date, weather) {checkRoute(data, route);const day = checkDate(data, date);const chosenWeather = checkWeather(data, weather);const calendar = data.calendar[day];const dayType = calendar.day_of_week < 5 ? "weekday" : calendar.day_of_week === 5 ? "saturday" : "sunday";const schedule = data.schedule[route][dayType];const recorded = data.weather[day];const rows = [];for (let hour = 0; hour < 24; hour++) {11 unmodified lines};Object.assign(row, data.routes[route]);data.schedule_columns.forEach((column, i) => { row[column] = schedule[hour][i]; });for (const column of Object.keys(data.weather_limits)) {row[column] = column in chosenWeather ? chosenWeather[column] : recorded[column][hour];}rows.push(row);}return rows;}// Predicted riders for each hour of the day: never below 0, rounded to whole riders.function predictDay(model, data, route, date, weather) {return dayRows(data, route, date, weather).map((row) => ({hour: row.hour,predicted_riders: roundHalfEven(Math.max(rawPredict(model, encode(model, row)), 0)),}));}function predictHour(model, data, route, date, hour, weather) {checkHour(hour);const profile = predictDay(model, data, route, date, weather);return { route, date, hour, predicted_riders: profile[hour].predicted_riders, daily_profile: profile };}const api = { InputError, treeValue, rawPredict, encode, roundHalfEven, dayRows, predictDay, predictHour };if (typeof module === "object" && module.exports) module.exports = api;else root.TransitPulse = api;})(typeof window !== "undefined" ? window : globalThis);3 unmodified lines4567891051 unmodified lines626364656667686970714 unmodified lines76777879808182839 unmodified lines939495969798995 unmodified lines10510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721811 unmodified lines2302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632643 unmodified lines// 1. one-hot encoding of bus_route and borough (the other 18 inputs pass through unchanged),// 2. a HistGradientBoostingRegressor with 500 trees.// app/build_hf_space.py exports that pipeline to model.json (the trees) and the lookup tables// (route facts, schedule, recorded 2025 weather, calendar) to data.json.// This file rebuilds the input row exactly like app/features.py and adds up the trees exactly// like scikit-learn does. app/verify_static_space.py checks that the results are identical.// The same file runs in the browser (window.TransitPulse) and in Node.js (module.exports) for the check.51 unmodified linesreturn Number.isInteger(n) ? n.toFixed(1) : String(n);}const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);function checkRoute(data, route) {if (!has(data.routes, route)) {throw new InputError(`Unknown route '${route}'. Choose one of: ${data.route_names.join(", ")}.`);}}4 unmodified linesif (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text) {throw new InputError(`Date '${date}' is not valid. Use the format YYYY-MM-DD.`);}if (!has(data.calendar, text)) {throw new InputError(`Date must be between ${data.first_date} and ${data.last_date}.`);}return text;}9 unmodified linesconst clean = {};for (const [name, value] of Object.entries(weather || {})) {if (value === null || value === undefined) continue;if (!has(data.weather_limits, name)) {throw new InputError(`Unknown weather field '${name}'. Allowed: ${Object.keys(data.weather_limits).join(", ")}.`);}const [low, high] = data.weather_limits[name];5 unmodified linesreturn clean;}// ---- dates and weather (mirrors features.fetch_weather / day_weather / date_warnings) -----const DAY_MS = 86400000;const dayNumber = (text) => Date.parse(text + "T00:00:00Z") / DAY_MS;function todayInNewYork() {return new Date().toLocaleDateString("en-CA", { timeZone: "America/New_York" }); // YYYY-MM-DD}function addDays(text, days) {return new Date(Date.parse(text + "T00:00:00Z") + days * DAY_MS).toISOString().slice(0, 10);}function defaultDate() {return addDays(todayInNewYork(), 1);}const weatherCache = {};// Hourly weather for a date after the saved 2025 file, from Open-Meteo (CC BY 4.0).async function fetchWeather(data, date, today = todayInNewYork()) {const cached = weatherCache[date];if (cached && Date.now() - cached.time < 3600000) return cached.result;const ow = data.open_meteo;if (dayNumber(date) > dayNumber(today) + ow.forecast_days - 1) {throw new InputError(`No weather forecast exists yet for ${date} (forecasts reach ${ow.forecast_days} days ahead). Enter the weather yourself.`);}const archive = dayNumber(date) < dayNumber(today) - ow.archive_delay_days;const params = new URLSearchParams({latitude: ow.latitude, longitude: ow.longitude, hourly: Object.keys(data.weather_limits).join(","),timezone: "America/New_York", start_date: date, end_date: date,});const problem = new InputError(`Could not get the weather for ${date} from Open-Meteo. Try again, or enter the weather yourself.`);let hourly;try {const response = await fetch(`${archive ? ow.archive_url : ow.forecast_url}?${params}`);if (!response.ok) throw problem;hourly = (await response.json()).hourly;if (!hourly) throw problem;} catch (error) {throw problem;}const values = {};for (const column of Object.keys(data.weather_limits)) {const byHour = {};(hourly[column] || []).forEach((value, i) => {const stamp = hourly.time[i];const hour = Number(stamp.slice(11, 13));if (stamp.startsWith(date) && !(hour in byHour) && value !== null) byHour[hour] = value;});const known = Object.values(byHour);if (known.length === 0) throw problem;// a missing hour (for example when clocks change) takes the value of the hour before it, or after it at midnightconst series = [];for (let hour = 0; hour < 24; hour++) series.push(hour in byHour ? byHour[hour] : null);for (let hour = 0; hour < 24; hour++) {if (series[hour] === null) series[hour] = hour > 0 ? series[hour - 1] : series.find((v) => v !== null);}values[column] = series;}const result = { values, source: archive ? "archive" : "forecast" };weatherCache[date] = { time: Date.now(), result };return result;}// 24 hourly values per weather column and where they came from. `fetched` is fetchWeather's result when it was needed.function dayWeather(data, date, weather, fetched) {const columns = Object.keys(data.weather_limits);let base = null, source = null;if (has(data.weather, date)) {base = data.weather[date];source = "recorded weather (Open-Meteo)";} else if (!columns.every((c) => c in weather)) {base = fetched.values;source = fetched.source === "archive" ? "Open-Meteo historical weather" : "Open-Meteo forecast";}const out = {};for (const c of columns) out[c] = c in weather ? Array(24).fill(weather[c]) : base[c];if (Object.keys(weather).length === columns.length) source = "your weather";else if (Object.keys(weather).length > 0) source += ", with your values where given";return { columns: out, source };}function needsFetch(data, date, weather) {return !has(data.weather, date) && !Object.keys(data.weather_limits).every((c) => c in weather);}function dateWarnings(data, date) {const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September","October", "November", "December"];const month = Number(date.slice(5, 7));const warnings = [];if (!data.trained_months.includes(month)) {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.`);}if (dayNumber(date) > dayNumber(data.last_recorded_date)) {warnings.push("This date is after the training data (January to September 2025); bus service may have changed since then.");}return warnings;}// ---- building the model's input rows (mirrors features.day_features) --------------------function dayRows(data, route, date, weather, fetched) {const calendar = data.calendar[date];const dayType = calendar.day_of_week < 5 ? "weekday" : calendar.day_of_week === 5 ? "saturday" : "sunday";const schedule = data.schedule[route][dayType];const { columns, source } = dayWeather(data, date, weather, fetched);const rows = [];for (let hour = 0; hour < 24; hour++) {11 unmodified lines};Object.assign(row, data.routes[route]);data.schedule_columns.forEach((column, i) => { row[column] = schedule[hour][i]; });for (const column of Object.keys(columns)) row[column] = columns[column][hour];rows.push(row);}return { rows, source };}// Everything the page shows; same fields as features.predict. Checks run in the same order as the Python app.async function predict(model, data, route, date, hour, weather, today = todayInNewYork()) {checkHour(hour);checkRoute(data, route);const day = checkDate(data, date);const chosen = checkWeather(data, weather);const fetched = needsFetch(data, day, chosen) ? await fetchWeather(data, day, today) : null;const { rows, source } = dayRows(data, route, day, chosen, fetched);const profile = rows.map((row) => roundHalfEven(Math.max(rawPredict(model, encode(model, row)), 0)));const value = profile[hour];return {route, date: day, hour,predicted_riders: value,typical_error: data.typical_error,likely_range: [Math.max(0, value - data.typical_error), value + data.typical_error],daily_profile: profile.map((p, h) => ({ hour: h, predicted_riders: p })),warnings: dateWarnings(data, day),weather_source: source,};}const api = { InputError, treeValue, rawPredict, encode, roundHalfEven, dayRows, predict, fetchWeather,todayInNewYork, defaultDate };if (typeof module === "object" && module.exports) module.exports = api;else root.TransitPulse = api;})(typeof window !== "undefined" ? window : globalThis);
README.md+3-2
data.json
index.html+23-7
predict.js+133-28