Download loaders/linger_loaders/__init__.py from anonymous-uploader/linger-sample: direct link, hf CLI and curl.
- Browser
- Download file 6.82 kB
-
https://huggingface.co/datasets/anonymous-uploader/linger-sample/resolve/main/loaders/linger_loaders/__init__.py
- Command line
-
hf download hf://datasets/anonymous-uploader/linger-sample/loaders/linger_loaders/__init__.py
-
curl -L -o __init__.py https://huggingface.co/datasets/anonymous-uploader/linger-sample/resolve/main/loaders/linger_loaders/__init__.py
6.82 kB
| # SPDX-License-Identifier: MIT | |
| """Loaders for the LiNGER release (standard library and NumPy only). | |
| Coordinates are in the shared coordinate frame, the frame of node N2: x and y horizontal, z up, in meters. The floor is | |
| near z = -2.65 m. Field names follow the appendix table "Fields of the released files". | |
| All timestamps are UTC and shifted by a whole number of weeks; see the README. | |
| """ | |
| import csv | |
| import gzip | |
| import io | |
| import json | |
| import os | |
| import numpy as np | |
| __all__ = ["load_tracklets", "load_segment", "iter_frames", "load_static_map", "load_furniture", | |
| "load_study_area", "track_runs", "LIVE_FIELDS", "OFFLINE_FIELDS"] | |
| __version__ = "0.1.0" | |
| LIVE_FIELDS = ("stamp", "received_at", "id", "x", "y", "z", "w", "l", "h", "state") | |
| OFFLINE_FIELDS = ("t_unix", "track_id", "x", "y", "state") | |
| def _open_text(path): | |
| return io.TextIOWrapper(gzip.open(path, "rb"), encoding="utf-8") if str(path).endswith(".gz") else open(path, encoding="utf-8") | |
| def _window(session): | |
| """session is None, a two-item sequence (start, stop), or a dict with 'start' and 'stop'; times in Unix seconds.""" | |
| if session is None: | |
| return None | |
| if isinstance(session, dict): | |
| return float(session["start"]), float(session["stop"]) | |
| a, b = session | |
| return float(a), float(b) | |
| def load_tracklets(path, session=None): | |
| """Read a live log or an offline track file into a dict of equal-length NumPy columns, one row per track and frame. | |
| Args: | |
| path: live log (``.jsonl`` or ``.jsonl.gz``) or offline file (``.csv`` or ``.csv.gz``). | |
| session: optional time window in Unix seconds: a two-item sequence ``(start, stop)`` or a dict | |
| ``{"start": .., "stop": ..}``; rows with ``start <= t < stop`` are kept. | |
| Returns: | |
| Live logs give the columns in LIVE_FIELDS, offline files those in OFFLINE_FIELDS. Both also get a boolean | |
| ``coasting`` column, true where the state ends in ``~coasting`` (predicted, no detection). Live IDs are | |
| valid within one tracker run only (see track_runs). | |
| """ | |
| win = _window(session) | |
| p = str(path) | |
| if p.endswith((".jsonl", ".jsonl.gz")): | |
| cols = {k: [] for k in LIVE_FIELDS} | |
| with _open_text(p) as fh: | |
| try: | |
| for line in fh: | |
| try: | |
| msg = json.loads(line).get("msg", {}) | |
| except ValueError: | |
| continue | |
| if msg.get("type") != "frame": | |
| continue | |
| t = float(msg["stamp"]) | |
| if win and not (win[0] <= t < win[1]): | |
| continue | |
| for tr in msg.get("tracks", []): | |
| cols["stamp"].append(t) | |
| cols["received_at"].append(float(msg.get("received_at", np.nan))) | |
| for k in ("id", "x", "y", "z", "w", "l", "h", "state"): | |
| cols[k].append(tr.get(k)) | |
| except EOFError: | |
| # A log that is still being written ends in a truncated gzip member; keep what was read. | |
| pass | |
| out = {k: np.asarray(cols[k], dtype=float) for k in ("stamp", "received_at", "x", "y", "z", "w", "l", "h")} | |
| out["id"] = np.asarray(cols["id"], dtype=np.int64) | |
| out["state"] = np.asarray(cols["state"], dtype=object) | |
| elif p.endswith((".csv", ".csv.gz")): | |
| cols = {k: [] for k in OFFLINE_FIELDS} | |
| with _open_text(p) as fh: | |
| for r in csv.DictReader(fh): | |
| t = float(r["t_unix"]) | |
| if win and not (win[0] <= t < win[1]): | |
| continue | |
| for k in OFFLINE_FIELDS: | |
| cols[k].append(r[k]) | |
| out = {"t_unix": np.asarray(cols["t_unix"], dtype=float), "track_id": np.asarray(cols["track_id"], dtype=np.int64), | |
| "x": np.asarray(cols["x"], dtype=float), "y": np.asarray(cols["y"], dtype=float), | |
| "state": np.asarray(cols["state"], dtype=object)} | |
| else: | |
| raise ValueError(f"unknown tracklet format: {p}") | |
| out["coasting"] = np.array([str(s).endswith("~coasting") for s in out["state"]], dtype=bool) | |
| return out | |
| def track_runs(stamp, run_starts): | |
| """Index of the tracker run each row belongs to, so that live tracks can be keyed as (run, id). | |
| The live tracker restarts daily and its IDs restart with it. ``run_starts`` holds the Unix times of the restarts: | |
| the started_unix values in metadata/tracker_runs.csv. | |
| """ | |
| return np.searchsorted(np.sort(np.asarray(run_starts, dtype=float)), np.asarray(stamp, dtype=float), side="right") | |
| def load_segment(path): | |
| """Read one recorded segment directory (``frames.npz`` and ``meta.json``, format cloudframes-v1). | |
| Returns: | |
| dict with ``points`` (N x 3 float32, shared coordinate frame), ``offsets`` (int64, index of each frame's first point, | |
| frames + 1 entries), ``t_ms`` (int64, Unix milliseconds per frame) and ``meta`` (the parsed meta.json). | |
| """ | |
| with np.load(os.path.join(path, "frames.npz")) as z: | |
| seg = {"points": z["points"], "offsets": z["offsets"], "t_ms": z["t_ms"]} | |
| with open(os.path.join(path, "meta.json"), encoding="utf-8") as fh: | |
| seg["meta"] = json.load(fh) | |
| if seg["meta"].get("format") != "cloudframes-v1": | |
| raise ValueError(f"unexpected segment format {seg['meta'].get('format')!r} in {path}") | |
| return seg | |
| def iter_frames(segment): | |
| """Yield ``(t_ms, points)`` for each frame of a segment from load_segment.""" | |
| P, off = segment["points"], segment["offsets"] | |
| for i, t in enumerate(segment["t_ms"]): | |
| yield int(t), P[off[i]:off[i + 1]] | |
| def load_static_map(path): | |
| """Read the static map, which is stored in centimeters. | |
| Returns: | |
| dict with ``points`` (N x 3 float64, meters, shared coordinate frame), ``node`` (the node, 1-7, that observed each | |
| point) and ``floor_z`` (meters). | |
| """ | |
| with np.load(path) as z: | |
| return {"points": z["xyz"].astype(np.float64) / 100.0, "node": z["node"].astype(np.int16), | |
| "floor_z": float(z["floor_z_m"])} | |
| def load_furniture(path): | |
| """Read the furniture layer as a list of dicts with id, label, center x and y, footprint len_m and wid_m, | |
| heading yaw_rad and shape (shared coordinate frame).""" | |
| with open(path, encoding="utf-8") as fh: | |
| d = json.load(fh) | |
| keep = ("id", "label", "x", "y", "len_m", "wid_m", "yaw_rad", "shape") | |
| return [{k: e.get(k) for k in keep} for e in (d["entries"] if isinstance(d, dict) else d)] | |
| def load_study_area(path): | |
| """Read the study-area polygon as an n x 2 array of vertices in meters.""" | |
| with open(path, encoding="utf-8") as fh: | |
| return np.asarray(json.load(fh)["polygon_xy_m"], dtype=float) | |