Download loader.py from Jgoldfeder/smart-buildings: direct link, hf CLI and curl.
- Browser
- Download file 4.34 kB
-
https://huggingface.co/datasets/Jgoldfeder/smart-buildings/resolve/main/loader.py
- Command line
-
hf download hf://datasets/Jgoldfeder/smart-buildings/loader.py
-
curl -L -o loader.py https://huggingface.co/datasets/Jgoldfeder/smart-buildings/resolve/main/loader.py
4.34 kB
| """Loader for the Smart Buildings dataset (SB1-SB11). | |
| import loader as sb | |
| sb.buildings() # one row per building | |
| pts = sb.points("SB4") # channel table | |
| temps = pts[(pts.quantity == "temperature") & (pts.kind == "sensor")].point_id | |
| df = sb.load("SB4", points=temps, start="2023-06-01", end="2023-07-01", si=True) | |
| Values on disk are exactly as recorded, in native units, at native resolution. Everything the | |
| loader does on top is opt-in: | |
| si=True convert with each point's `to_si` formula (degF/K -> degC, CFM -> m3/s, ...) | |
| mask_zero_fills=True set 0 -> NaN for points flagged `zero_means_missing` (SB2/SB3 zero-fill) | |
| irregular=True also return off-grid samples (long format) as a second frame | |
| Missing is always NaN on disk; SB1's validity mask lives in observations/<year>.valid.parquet. | |
| """ | |
| import glob | |
| import os | |
| import re | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = os.path.dirname(os.path.abspath(__file__)) | |
| _YEAR = re.compile(r"^(\d{4})\.parquet$") | |
| def buildings(root=ROOT): | |
| return pd.read_csv(os.path.join(root, "buildings.csv")) | |
| def points(building=None, root=ROOT): | |
| p = os.path.join(root, "points.parquet") | |
| if os.path.exists(p): | |
| df = pd.read_parquet(p) | |
| return df[df.building == building].reset_index(drop=True) if building else df | |
| files = [os.path.join(root, building, "points.csv")] if building else sorted(glob.glob(os.path.join(root, "SB*", "points.csv"))) | |
| return pd.concat([pd.read_csv(f, low_memory=False) for f in files], ignore_index=True) | |
| def _years(root, building, table): | |
| d = os.path.join(root, building, "timeseries", table) | |
| return sorted((int(m[1]), os.path.join(d, f)) for f in os.listdir(d) if (m := _YEAR.match(f))) | |
| def _si(series, formula): | |
| if not isinstance(formula, str) or formula in ("", "identity") or formula.startswith("identity"): | |
| return series # '' = unit unknown: left as recorded | |
| expr = formula.split(" ")[0] if formula.startswith("x") else formula.rsplit(" ", 1)[0] | |
| if not re.fullmatch(r"[\dx\.\+\-\*/\(\) e]+", expr): | |
| raise ValueError(f"unsupported to_si formula {formula!r}") | |
| return eval(expr, {"__builtins__": {}}, {"x": series}) # arithmetic only, checked above | |
| def load(building, table="observations", points=None, start=None, end=None, si=False, | |
| mask_zero_fills=False, irregular=False, root=ROOT): | |
| start, end = _utc(start), _utc(end) | |
| cols = None if points is None else list(points) | |
| frames, longs = [], [] | |
| for year, path in _years(root, building, table): | |
| if (start is not None and year < start.year) or (end is not None and year > end.year): | |
| continue | |
| df = pd.read_parquet(path, columns=None if cols is None else [c for c in cols if c in _schema(path)]) | |
| frames.append(df) | |
| ir = path.replace(".parquet", ".irregular.parquet") | |
| if irregular and os.path.exists(ir): | |
| lg = pd.read_parquet(ir) | |
| longs.append(lg if cols is None else lg[lg.point_id.isin(cols)]) | |
| if frames: | |
| df = pd.concat(frames, sort=False) | |
| else: | |
| df = pd.DataFrame(columns=cols or [], index=pd.DatetimeIndex([], tz="UTC", name="timestamp"), dtype=np.float32) | |
| if start is not None: | |
| df = df[df.index >= start] | |
| if end is not None: | |
| df = df[df.index < end] | |
| if si or mask_zero_fills: | |
| meta = _points_for(building, table, root).set_index("point_id") | |
| df = df.astype(np.float64) | |
| for c in df.columns: | |
| if c not in meta.index: | |
| continue | |
| if mask_zero_fills and "zero_means_missing" in str(meta.at[c, "flags"]): | |
| df[c] = df[c].mask(df[c] == 0) | |
| if si: | |
| df[c] = _si(df[c], meta.at[c, "to_si"]) | |
| if irregular: | |
| lg = pd.concat(longs, ignore_index=True) if longs else pd.DataFrame(columns=["timestamp", "point_id", "value"]) | |
| return df, lg | |
| return df | |
| def _utc(t): | |
| """Naive times are taken as UTC; aware times are converted.""" | |
| if t is None: | |
| return None | |
| t = pd.Timestamp(t) | |
| return t.tz_localize("UTC") if t.tzinfo is None else t.tz_convert("UTC") | |
| _schemas = {} | |
| def _schema(path): | |
| if path not in _schemas: | |
| import pyarrow.parquet as pq | |
| _schemas[path] = set(pq.read_schema(path).names) | |
| return _schemas[path] | |
| def _points_for(building, table, root): | |
| p = points(building, root) | |
| return p[p.table == table] if "table" in p.columns else p | |