Datasets:
Download scripts/plot_dataset_readme.py from tjtrans/Traffic-Demand-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.78 kB
-
https://huggingface.co/datasets/tjtrans/Traffic-Demand-Bench/resolve/main/scripts/plot_dataset_readme.py
- Command line
-
hf download hf://datasets/tjtrans/Traffic-Demand-Bench/scripts/plot_dataset_readme.py
-
curl -L -o plot_dataset_readme.py https://huggingface.co/datasets/tjtrans/Traffic-Demand-Bench/resolve/main/scripts/plot_dataset_readme.py
9.78 kB
| """Figures for datasets/README.md: copy appendix maps, draw BAY/TOR, full daily+MA, busiest-zone month.""" | |
| from __future__ import annotations | |
| import calendar | |
| import json | |
| import re | |
| import shutil | |
| from pathlib import Path | |
| import matplotlib.dates as mdates | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from matplotlib import font_manager | |
| from matplotlib.collections import PolyCollection | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DEMAND = ROOT / "datasets" / "demand" | |
| FIG = ROOT / "datasets" / "figures" | |
| REG = DEMAND / "regions" | |
| CITIES = [ | |
| ("NYCBIKE", "nycbike", "纽约共享单车", "单车"), | |
| ("NYCTAXI", "NYCtaxi", "纽约出租车", "出租"), | |
| ("CHIBIKE", "chibike", "芝加哥共享单车", "单车"), | |
| ("CHITAXI", "chitaxi", "芝加哥出租车", "出租"), | |
| ("BAYBIKE", "baybike", "湾区共享单车", "单车"), | |
| ("BOSBIKE", "bosbike", "波士顿共享单车", "单车"), | |
| ("TORBIKE", "torbike", "多伦多共享单车", "单车"), | |
| ] | |
| GEO = { | |
| "BAYBIKE": REG / "baybike" / "grid_data_bay.geojson", | |
| "TORBIKE": REG / "torbike" / "toranto_grids.geojson", | |
| } | |
| MONTH_RE = re.compile(r"(20\d{2})[-_]?(\d{2})$") | |
| def _setup_font() -> None: | |
| for p in ( | |
| Path(r"C:\Windows\Fonts\simhei.ttf"), | |
| Path(r"C:\Windows\Fonts\msyh.ttc"), | |
| Path(r"C:\Windows\Fonts\simsun.ttc"), | |
| ): | |
| if p.exists(): | |
| font_manager.fontManager.addfont(str(p)) | |
| name = font_manager.FontProperties(fname=str(p)).get_name() | |
| plt.rcParams["font.sans-serif"] = [name, "SimHei", "Microsoft YaHei", "SimSun"] | |
| break | |
| else: | |
| plt.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei", "SimSun", "DejaVu Sans"] | |
| plt.rcParams["axes.unicode_minus"] = False | |
| plt.rcParams["figure.facecolor"] = "white" | |
| plt.rcParams["axes.facecolor"] = "white" | |
| plt.rcParams["axes.grid"] = True | |
| plt.rcParams["grid.color"] = "#cccccc" | |
| plt.rcParams["grid.alpha"] = 0.45 | |
| plt.rcParams["grid.linestyle"] = "--" | |
| plt.rcParams["axes.edgecolor"] = "#262626" | |
| def _inflow(arr: np.ndarray) -> np.ndarray: | |
| if arr.ndim >= 1 and arr.shape[-1] == 2: | |
| return arr[..., 0] | |
| return arr | |
| def load_full(folder: str) -> tuple[np.ndarray, pd.DatetimeIndex]: | |
| ddir = DEMAND / folder | |
| files = [] | |
| for p in sorted(ddir.glob("*.npy")): | |
| if "副本" in p.name or "copy" in p.name.lower(): | |
| continue | |
| m = MONTH_RE.search(p.stem) | |
| if m: | |
| files.append(((int(m.group(1)), int(m.group(2))), p)) | |
| if not files: | |
| raise FileNotFoundError(ddir) | |
| chunks, index = [], [] | |
| for (year, month), path in files: | |
| raw = np.load(path) | |
| cal_days = calendar.monthrange(year, month)[1] | |
| if raw.ndim == 4: | |
| n_steps_day = int(raw.shape[2]) | |
| days = min(int(raw.shape[1]), cal_days) | |
| sl = _inflow(raw[:, :days]).astype(np.float32) | |
| sl = sl.reshape(sl.shape[0], -1).T | |
| if n_steps_day == 48: | |
| t = (sl.shape[0] // 2) * 2 | |
| sl = sl[:t].reshape(-1, 2, sl.shape[1]).sum(axis=1) | |
| elif raw.ndim == 3: | |
| take = cal_days * 24 | |
| sl = _inflow(raw[:take]).astype(np.float32) | |
| else: | |
| raise ValueError(path) | |
| sl = np.nan_to_num(sl, nan=0.0) | |
| start = pd.Timestamp(year=year, month=month, day=1) | |
| idx = pd.date_range(start, periods=sl.shape[0], freq="60min") | |
| chunks.append(sl) | |
| index.append(idx) | |
| data = np.concatenate(chunks, axis=0) | |
| times = pd.DatetimeIndex(np.concatenate([ix.to_numpy() for ix in index])) | |
| if len(times) != data.shape[0]: | |
| times = pd.date_range(times[0], periods=data.shape[0], freq="60min") | |
| return data.astype(np.float32), times | |
| def copy_appendix_maps() -> None: | |
| FIG.mkdir(parents=True, exist_ok=True) | |
| src = Path(r"H:\desk\大论文材料\1\defense-web\assets\figs") | |
| want = { | |
| "049": "map_nycbike.png", | |
| "050": "map_nyctaxi.png", | |
| "051": "map_chibike.png", | |
| "052": "map_chitaxi.png", | |
| "053": "map_bosbike.png", | |
| } | |
| for p in src.glob("*.png"): | |
| for prefix, dest in want.items(): | |
| if p.name.startswith(prefix): | |
| shutil.copy2(p, FIG / dest) | |
| print("copied", dest, flush=True) | |
| def _rings(geom: dict) -> list[np.ndarray]: | |
| g = geom.get("type") | |
| c = geom.get("coordinates") | |
| out = [] | |
| if g == "Polygon": | |
| out.append(np.asarray(c[0], dtype=np.float64)[:, :2]) | |
| elif g == "MultiPolygon": | |
| for poly in c: | |
| out.append(np.asarray(poly[0], dtype=np.float64)[:, :2]) | |
| return out | |
| def plot_geo_map(key: str, title: str, out: Path) -> None: | |
| import sys | |
| import transbigdata as tbd | |
| sys.path.insert(0, str(REG)) | |
| from map_config import MAP_STYLE, REGION_FILL, REGION_OUTLINE, bounds_with_pad, setup_mapbox # type: ignore | |
| setup_mapbox() | |
| feats = json.loads(GEO[key].read_text(encoding="utf-8"))["features"] | |
| polys = [] | |
| for f in feats: | |
| polys.extend(_rings(f["geometry"])) | |
| xs = np.concatenate([p[:, 0] for p in polys]) | |
| ys = np.concatenate([p[:, 1] for p in polys]) | |
| bounds = bounds_with_pad([xs.min(), ys.min(), xs.max(), ys.max()], pad_ratio=0.12) | |
| fig, ax = plt.subplots(figsize=(6.4, 5.6), dpi=160) | |
| tbd.plot_map(plt, bounds, zoom=13, style=MAP_STYLE) | |
| ax = plt.gca() | |
| fill = tuple(c / 255 for c in REGION_FILL[:3]) + (REGION_FILL[3] / 255,) | |
| edge = tuple(c / 255 for c in REGION_OUTLINE[:3]) + (REGION_OUTLINE[3] / 255,) | |
| coll = PolyCollection(polys, facecolor=fill, edgecolor=edge, linewidth=0.35) | |
| ax.add_collection(coll) | |
| ax.set_xlim(bounds[0], bounds[2]) | |
| ax.set_ylim(bounds[1], bounds[3]) | |
| ax.set_axis_off() | |
| fig.tight_layout() | |
| fig.savefig(out, bbox_inches="tight") | |
| plt.close(fig) | |
| print("wrote", out.name, title, flush=True) | |
| def plot_daily(cities: list[tuple]) -> None: | |
| n = len(cities) | |
| fig, axes = plt.subplots(n, 1, figsize=(11.6, 2.15 * n), dpi=140, sharex=False) | |
| for ax, (key, folder, title, _) in zip(axes, cities): | |
| data, times = load_full(folder) | |
| hourly = pd.Series(data.sum(axis=1), index=times) | |
| daily = hourly.resample("D").sum() | |
| ma = daily.rolling(30, min_periods=7).mean() | |
| ax.plot(daily.index, daily.values, color="#b7e0b2", lw=0.7, label="日取车 / 上车次数") | |
| ax.plot(ma.index, ma.values, color="#2e8b3a", lw=1.85, label="30 天移动平均") | |
| ax.set_ylabel("次数") | |
| ax.set_title(f"{title}({key})全市每日总量", loc="left", fontsize=11) | |
| ax.legend(loc="upper left", frameon=False, fontsize=8) | |
| ax.set_xlim(daily.index[0], daily.index[-1]) | |
| ax.xaxis.set_major_locator(mdates.YearLocator(2)) | |
| ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y")) | |
| print(f"{key}: {times[0].date()} → {times[-1].date()} T={len(times)} N={data.shape[1]}", flush=True) | |
| axes[-1].set_xlabel("年") | |
| fig.tight_layout(h_pad=0.9) | |
| out = FIG / "usage_daily_all.png" | |
| fig.savefig(out, bbox_inches="tight") | |
| plt.close(fig) | |
| print("wrote", out.name, flush=True) | |
| def _month_slice(times: pd.DatetimeIndex, start: str, days: int = 30): | |
| lo = pd.Timestamp(start) | |
| hi = lo + pd.Timedelta(days=days) | |
| m = (times >= lo) & (times < hi) | |
| return m | |
| def plot_busiest_month(cities: list[tuple], start: str = "2025-09-01") -> None: | |
| n = len(cities) | |
| fig, axes = plt.subplots(n, 1, figsize=(11.6, 2.05 * n), dpi=140) | |
| for ax, (key, folder, title, _) in zip(axes, cities): | |
| data, times = load_full(folder) | |
| mask = _month_slice(times, start) | |
| used = start[:7] | |
| if mask.sum() < 24 * 20 or float(data[mask].sum()) < 1: | |
| # last 30 calendar days that actually have trips | |
| daily = pd.Series(data.sum(1), index=times).resample("D").sum() | |
| ok = daily[daily > 0] | |
| hi = ok.index.max() | |
| lo = hi - pd.Timedelta(days=29) | |
| mask = (times >= lo) & (times < hi + pd.Timedelta(days=1)) | |
| used = f"{lo.date()}–{hi.date()}" | |
| zone = int(np.argmax(data[mask].sum(axis=0))) | |
| t = times[mask] | |
| y = data[mask, zone] | |
| ax.plot(t, y, color="#1f6f8b", lw=0.85) | |
| ax.set_ylabel("次数 / 小时") | |
| ax.set_title( | |
| f"{title}({key})用量最高区域 #{zone} · {used} 逐小时", | |
| loc="left", | |
| fontsize=11, | |
| ) | |
| lo = pd.Timestamp(t[0]).normalize() | |
| hi = pd.Timestamp(t[-1]) | |
| ticks = pd.date_range(lo, hi, freq="5D") | |
| ax.set_xticks(ticks) | |
| ax.set_xticklabels([ts.strftime("%m-%d") for ts in ticks], fontsize=8) | |
| pad = pd.Timedelta(hours=10) | |
| ax.set_xlim(t[0] - pad, t[-1] + pad) | |
| ax.tick_params(axis="x", pad=3) | |
| print(f"{key} busiest zone={zone} mean={y.mean():.2f} month={used}", flush=True) | |
| axes[-1].set_xlabel("日期") | |
| fig.tight_layout(h_pad=1.2) | |
| out = FIG / "busiest_zone_30d.png" | |
| fig.savefig(out, bbox_inches="tight", pad_inches=0.18) | |
| plt.close(fig) | |
| print("wrote", out.name, flush=True) | |
| def main() -> None: | |
| import sys | |
| _setup_font() | |
| FIG.mkdir(parents=True, exist_ok=True) | |
| only = sys.argv[1] if len(sys.argv) > 1 else "all" | |
| if only in ("all", "maps"): | |
| copy_appendix_maps() | |
| plot_geo_map("BAYBIKE", "湾区 Bay Wheels 空间划分(154 栅格)", FIG / "map_baybike.png") | |
| plot_geo_map("TORBIKE", "多伦多 Bike Share 空间划分(204 栅格)", FIG / "map_torbike.png") | |
| if only in ("all", "daily"): | |
| plot_daily(CITIES) | |
| if only in ("all", "busiest"): | |
| plot_busiest_month(CITIES) | |
| if __name__ == "__main__": | |
| main() | |