File size: 9,776 Bytes
11ebde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()