File size: 9,616 Bytes
0107764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The 18 public test sets of the UniMTS suite in the model's input format.

Raw data
--------
The test windows come from `UniMTS_data.zip` of the UniMTS release on the Hugging Face hub. The archive has no
license and is not redistributed here. Download it once:

    hf download xiyuanz/UniMTS UniMTS_data.zip --revision 378531dbc1ec649b5bb792fd2e8f4c9a1a3ff99d --local-dir <dir>

`extract_test_files` checks the archive's sha256, extracts only the 54 test files used here (X_test.npy, y_test.npy
and <dataset>.json of each set, about 1.2 GB) and checks each file's sha256 against raw_data.json of the evaluation
data. If the archive changes upstream, the check fails instead of giving different numbers.

Model-ready caches
------------------
Every sensor goes to one of the 22 body sites. Columns, units and the resampling to 20 Hz follow UniMTS's data loader
(github.com/xiyuanzh/UniMTS, data.py). Each sensor is gravity-canonicalized at its original rate before resampling
(processing_setcon.py). A cache holds X9 (N, 200, 22, 9) float32, y (N,) and the class names.
"""
from __future__ import annotations

import hashlib
import json
import zipfile
from pathlib import Path

import numpy as np

from . import processing as PS
from .protocol import ACC_ONLY_SETS, DATASETS

G = 9.80665
SITE = PS.SITE_INDEX


def sha256(path, chunk=1 << 22):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(chunk), b""):
            h.update(block)
    return h.hexdigest()


# ---------------------------------------------------------------------------------------------- raw files
def raw_manifest(eval_data):
    return json.loads((Path(eval_data) / "raw_data.json").read_text())


def extract_test_files(zip_path, out_dir, eval_data, check_archive=True):
    """Extract the 54 test files from UniMTS_data.zip into out_dir/<dataset>/ and verify every sha256."""
    man = raw_manifest(eval_data)
    zip_path, out_dir = Path(zip_path), Path(out_dir)
    if check_archive:
        digest = sha256(zip_path)
        if digest != man["archive"]["sha256"]:
            raise SystemExit(f"{zip_path}: sha256 {digest} differs from the expected {man['archive']['sha256']}")
    with zipfile.ZipFile(zip_path) as z:
        for rel, rec in man["files"].items():
            dst = out_dir / rel
            if dst.exists() and sha256(dst) == rec["sha256"]:
                continue
            data = z.read(rec["member"])
            if hashlib.sha256(data).hexdigest() != rec["sha256"]:
                raise SystemExit(f"{rec['member']}: sha256 mismatch")
            dst.parent.mkdir(parents=True, exist_ok=True)
            dst.write_bytes(data)
    verify_test_files(out_dir, eval_data)
    return out_dir


def verify_test_files(unimts_dir, eval_data):
    """Every one of the 54 test files exists under unimts_dir with the expected sha256."""
    man = raw_manifest(eval_data)
    bad = [rel for rel, rec in man["files"].items()
           if not (Path(unimts_dir) / rel).exists() or sha256(Path(unimts_dir) / rel) != rec["sha256"]]
    if bad:
        raise SystemExit(f"{len(bad)} test files missing or changed under {unimts_dir}, e.g. {bad[:3]}")
    return True


# ---------------------------------------------------------------------------------------------- sensors
def sensors(dataset, X, y):
    """Sensor columns of one dataset -> [(site, acc (N, T, 3) m/s^2, gyro (N, T, 3) rad/s or None, window subset or
    None)], sampling rate. Only UTD-MHAD uses a subset: its sensor sits on the right wrist for the first 21 classes
    and on the right thigh for the last 6 (the convention of the UniMTS loader)."""
    A = None
    if dataset == "PAMAP":
        return [(SITE["r_wrist"], X[:, :, 0:3], X[:, :, 3:6], A), (SITE["c_spine3"], X[:, :, 18:21], X[:, :, 21:24], A),
                (SITE["r_foot"], X[:, :, 9:12], X[:, :, 12:15], A)], 100
    if dataset == "USCHAD":
        return [(SITE["r_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, A)], 100
    if dataset == "UCIHAR":
        return [(SITE["c_spine1"], X[:, :, 6:9] * G, X[:, :, 3:6], A)], 50
    if dataset == "Opp_g":
        return [(SITE[name], X[:, :, a:a + 3] / 1000 * 9.8, X[:, :, a + 3:a + 6] / 1000, A)
                for name, a in (("c_spine2", 0), ("r_uparm", 9), ("r_lowarm", 18), ("l_uparm", 27),
                                ("l_lowarm", 36))], 30
    if dataset == "WISDM":
        return [(SITE["r_wrist"], X[:, :, 0:3], X[:, :, 3:6], A)], 20
    if dataset == "DSADS":
        return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
                for name, a in (("c_spine3", 0), ("r_wrist", 9), ("l_wrist", 18), ("r_lowleg", 27),
                                ("l_lowleg", 36))], 25
    if dataset == "Harth":
        return [(SITE["c_spine1"], X[:, :, 0:3] * G, None, A), (SITE["r_lowleg"], X[:, :, 3:6] * G, None, A)], 50
    if dataset == "Wharf":
        Xc = -14.709 + X / 63 * (2 * 14.709)
        return [(SITE["r_wrist"], Xc[:, :, 0:3], None, A)], 32
    if dataset == "Mhealth":
        return [(SITE["c_spine3"], X[:, :, 0:3], None, A),
                (SITE["l_foot"], X[:, :, 6:9], X[:, :, 9:12] / 180 * np.pi, A),
                (SITE["r_wrist"], X[:, :, 15:18], X[:, :, 18:21] / 180 * np.pi, A)], 50
    if dataset == "UTD-MHAD":
        wrist = (y < 21)
        return [(SITE["r_wrist"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, wrist),
                (SITE["r_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, ~wrist)], 50
    if dataset == "MotionSense":
        return [(SITE["r_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6], A),
                (SITE["l_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6], A)], 50
    if dataset == "w-HAR":
        return [(SITE["r_foot"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, A)], 250
    if dataset == "Shoaib":
        return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
                for name, a in (("l_upleg", 0), ("r_upleg", 6), ("r_wrist", 12), ("r_lowarm", 18), ("root", 24))], 50
    if dataset == "har70plus":
        return [(SITE["root"], X[:, :, 0:3] * G, None, A), (SITE["r_upleg"], X[:, :, 3:6] * G, None, A)], 50
    if dataset == "MMAct":
        return [(SITE["r_upleg"], X[:, :, 0:3], X[:, :, 3:6], A), (SITE["r_wrist"], X[:, :, 6:9], None, A)], 50
    if dataset == "realworld":
        return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
                for name, a in (("l_clavicle", 0), ("l_lowarm", 6), ("c_head", 12), ("l_foot", 18),
                                ("l_upleg", 24), ("l_uparm", 30), ("c_spine1", 36))], 50
    if dataset == "TNDA-HAR":
        return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
                for name, a in (("r_lowarm", 0), ("l_lowleg", 6), ("r_wrist", 12), ("l_foot", 18),
                                ("c_spine3", 24))], 50
    if dataset == "ut-complex":
        return [(SITE["r_upleg"], X[:, :, 0:3], X[:, :, 3:6], A), (SITE["r_wrist"], X[:, :, 6:9], X[:, :, 9:12], A)], 50
    raise ValueError(dataset)


def build_benchmark(dataset, unimts_dir):
    """-> X9 (N, 200, 22, 9) float32, y (N,), class names, per-sensor log (site, gravity method, gyro used)."""
    d = Path(unimts_dir) / dataset
    X = np.load(d / "X_test.npy").astype(np.float64)
    y = np.load(d / "y_test.npy")
    meta = json.loads((d / f"{dataset}.json").read_text())
    N, T = X.shape[0], X.shape[1]
    sens, fs = sensors(dataset, X, y)
    all9 = np.zeros((N, T, len(PS.SITE_NAMES), 9))
    log = []
    for site, acc, gyro, subset in sens:
        sel = slice(None) if subset is None else subset
        acc_s = acc[sel]
        if acc_s.shape[0] == 0:
            continue
        x9, method = PS.canonical_device_windows(acc_s, None if gyro is None else gyro[sel], fs)
        all9[sel, :, site] = x9
        log.append(dict(site=PS.SITE_NAMES[site], gravity=method, gyro=gyro is not None and method == "mahony",
                        windows=int(acc_s.shape[0])))
    X9 = PS.to_model_rate(all9, fs)
    classes = [" ".join(v) for v in meta["label_dictionary"].values()]
    return X9, np.asarray(y), classes, log


def check_gyro_rule(dataset, X9):
    """Mean-13 holds the sets in which every worn site has a gyroscope; the other five must have an
    acceleration-only site. Fails loudly if a cache disagrees with protocol.ACC_ONLY_SETS."""
    acc_only = [PS.SITE_NAMES[s] for s in range(X9.shape[2])
                if np.any(X9[:, :, s, 6:9] != 0) and not np.any(X9[:, :, s, 3:6] != 0)]
    if bool(acc_only) != (dataset in ACC_ONLY_SETS):
        raise SystemExit(f"{dataset}: acceleration-only sites {acc_only} disagree with the Mean-13 rule")
    return acc_only


def write_benchmarks(unimts_dir, out_dir, datasets=DATASETS):
    """Build and store every cache as <out_dir>/<dataset>.npz (compressed, no pickles; about 0.35 GB in total)."""
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    for ds in datasets:
        X9, y, classes, log = build_benchmark(ds, unimts_dir)
        check_gyro_rule(ds, X9)
        np.savez_compressed(out_dir / f"{ds}.npz", X9=X9, y=y.astype(np.int64), classes=np.array(classes),
                            sensors=np.array(json.dumps(log)))
        print(f"  {ds:12s} {X9.shape[0]:5d} windows  " +
              ", ".join(f"{s['site']} ({s['gravity']})" for s in log), flush=True)


def load_benchmark(cache_dir, dataset):
    """-> X9, y, class names from <cache_dir>/<dataset>.npz."""
    with np.load(Path(cache_dir) / f"{dataset}.npz", allow_pickle=False) as z:
        return z["X9"], z["y"].astype(int), [str(c) for c in z["classes"]]