File size: 10,200 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""The fixed test protocol of the paper (Sec. 3.5 and 4.1).

Device      all windows of one participant at one site share one mounting. Participants come from
            person_groups.json of the evaluation data (kind "exact"); datasets without exact ids count as one group.
Context     draw k = 0..4 uses numpy.random.default_rng(1000 + k): every group with at least 7 windows gives six random
            context windows, which are never scored. Smaller groups have no context and get zero reference channels.
6 of 12     (last row of Tab. 1) groups with at least 18 windows draw six extra context windows from their scored
            windows, numpy.random.default_rng([0xCA12, i, k, g]) with i the dataset's index in DATASETS and g the group;
            the extras are not scored either.
Gait test   autocorrelation of the acceleration magnitude, peak at a lag of 0.4-1.4 s >= 0.5 and standard deviation
            >= 0.5 m/s^2; used only by the walking-frame reading. No label is used anywhere except to count.
Metrics     accuracy per dataset = mean over the five draws of the share of correct scored windows; Mean-13 = the
            unweighted mean over the 13 sets in which every sensor has a gyroscope; macro-F1 over the classes present
            in a draw's scored labels; seeds: mean and sample standard deviation (ddof 1).
"""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np

from . import processing as PS

DATASETS = ["Opp_g", "UCIHAR", "MotionSense", "w-HAR", "Shoaib", "har70plus", "realworld", "TNDA-HAR", "PAMAP",
            "USCHAD", "Mhealth", "Harth", "ut-complex", "Wharf", "WISDM", "DSADS", "UTD-MHAD", "MMAct"]
# Five sets with at least one acceleration-only sensor; the other 13 form Mean-13.
ACC_ONLY_SETS = {"har70plus", "Harth", "Wharf", "Mhealth", "MMAct"}
MEAN13 = [d for d in DATASETS if d not in ACC_ONLY_SETS]
DRAWS = 5
CONTEXT, MIN_GROUP = 6, 7
MIN_GROUP_12, EXTRA = 18, 6


class EvalData:
    """The evaluation-data folder: class vectors, class texts, person groups, reference window lists and the
    paper's per-window predictions."""

    def __init__(self, folder):
        self.dir = Path(folder)
        self.groups = json.loads((self.dir / "protocol" / "person_groups.json").read_text())["datasets"]
        self._vectors = None

    def class_vectors(self, dataset):
        """{'names', 'anchors', 'names_descriptions'}: (C, 512) float64 unit vectors in CLIP ViT-B/32 space."""
        if self._vectors is None:
            from safetensors.numpy import load_file
            self._vectors = load_file(str(self.dir / "anchors" / "clip_vit_b32_class_vectors.safetensors"))
        return {t: self._vectors[f"{dataset}/{t}"] for t in ("names", "anchors", "names_descriptions")}

    def windows(self, dataset):
        return json.loads((self.dir / "protocol" / "windows" / f"{dataset}.json").read_text())

    def person_groups(self, dataset, n):
        """Group id per window (kind 'exact'; otherwise one group)."""
        e = self.groups.get(dataset)
        if not e or e["kind"] != "exact":
            return np.zeros(n, int)
        g = np.concatenate([np.full(int(c), int(v), np.int64) for v, c in e["rle"]])
        if len(g) != n:
            raise ValueError(f"{dataset}: person_groups.json covers {len(g)} windows, the data has {n}")
        return g.astype(int)

    def reference_predictions(self, seed):
        from safetensors.numpy import load_file
        f = self.dir / "reference" / f"predictions_seed{seed}.safetensors"
        return load_file(str(f)) if f.exists() else {}


# ---------------------------------------------------------------------------------------------- gait test
GAIT_LAGS = (8, 29)                  # 0.4-1.4 s at 20 Hz
GAIT_MIN_PEAK, GAIT_MIN_SD = 0.5, 0.5


def gait_mask(X):
    """(N, T, 22, 9) -> bool (N,): autocorrelation of the acceleration magnitude (mean over worn sites)."""
    occ = np.abs(X[..., :3]).sum((0, 1, 3)) > 0
    a = np.linalg.norm(X[:, :, occ, :3].astype(np.float64), axis=-1)
    valid = np.abs(X[:, :, occ, :3]).sum(-1) > 0
    a = np.where(valid, a, np.nan)
    a = a - np.nanmean(a, 1, keepdims=True)
    a = np.nan_to_num(a)
    sd = a.std(1).mean(1)
    den = (a ** 2).sum(1) + 1e-9
    r = np.stack([(a[:, :-lag] * a[:, lag:]).sum(1) / den for lag in range(*GAIT_LAGS)], 1)
    return (r.mean(2).max(1) >= GAIT_MIN_PEAK) & (sd >= GAIT_MIN_SD)


# ---------------------------------------------------------------------------------------------- walking frame
def walking_frame(acc, gyr, g):
    """Training-free reference (paper Sec. 3.2): up = mean gravity direction, forward = principal horizontal axis of
    the dynamic acceleration, over the given windows. Returns D = [right; up; forward] (3, 3)."""
    has_gyro = np.abs(gyr).sum() > 0
    e = (gyr ** 2).sum(-1).mean(1) if has_gyro else acc.std(1).sum(-1)
    moving = e >= np.quantile(e, 0.0)                    # all given windows (they already passed the gait test)
    up = PS.unit(g[moving].mean((0, 1)))
    dyn = acc[moving] - acc[moving].mean(1, keepdims=True)
    h = dyn - (dyn @ up)[..., None] * up
    _, V = np.linalg.eigh(np.einsum("nti,ntj->ij", h, h))
    f = PS.unit(V[:, -1] - (V[:, -1] @ up) * up)
    return np.stack([np.cross(up, f), up, f])


def apply_walking_frame(X, frame_windows):
    """Reference channels of every worn site := D g_t with D from the windows `frame_windows` (bool over X)."""
    Xb = X.copy()
    for s in np.where(np.abs(X[..., 6:9]).sum((0, 1, 3)) > 0)[0]:
        D = walking_frame(*PS.device_frame_signals(X[frame_windows][:, :, s]))
        ge = PS.unit(X[:, :, s, 6:9].astype(np.float64))
        valid = np.abs(X[:, :, s, 6:9]).sum(-1) > 0
        Xb[:, :, s, 6:9] = np.where(valid[..., None], ge @ D.T, 0.0).astype(X.dtype)
    return Xb


# ---------------------------------------------------------------------------------------------- context draws
def context_draw(X, groups, gait, k):
    """Draw k: six random context windows per group (rng 1000 + k). Returns
      walking   X with the walking-frame reference (from the gait windows among the six; zero if there is none)
      context   bool (N,) the context windows (never scored)
      no_frame  bool (N,) windows of devices without a walking-frame reference (also every group < 7 windows)"""
    rng = np.random.default_rng(1000 + k)
    Xb = X.copy()
    cal = np.zeros(len(X), bool)
    unknown = np.zeros(len(X), bool)
    for g in np.unique(groups):
        idx = np.where(groups == g)[0]
        if len(idx) < MIN_GROUP:
            unknown[idx] = True
            Xb[idx, :, :, 6:9] = 0
            continue
        c = rng.choice(idx, CONTEXT, replace=False)
        cal[c] = True
        frame_rows = np.zeros(len(X), bool)
        frame_rows[c[gait[c]]] = True
        if frame_rows.any():
            Xb[idx] = apply_walking_frame(X[idx], frame_rows[idx])
        else:
            unknown[idx] = True
            Xb[idx, :, :, 6:9] = 0
    return Xb, cal, unknown


def worn_sites(X):
    return np.where(np.abs(X[..., 6:9]).sum((0, 1, 3)) > 0)[0]


def device_keys(X, groups, context):
    """[(group, site)] of every device (group >= 7 windows x worn site) and the six context rows of every group."""
    keys, rows = [], {}
    for g in np.unique(groups):
        idx = np.where(groups == g)[0]
        if len(idx) < MIN_GROUP:
            continue
        c = idx[context[idx]]
        assert len(c) == CONTEXT, (g, len(c))
        rows[int(g)] = c
        for s in worn_sites(X[idx]):
            keys.append((int(g), int(s)))
    return keys, rows


def extra_context(groups, context, context_rows, dataset_index, k):
    """6 of 12: six extra context windows for every group with >= 18 windows, drawn from its scored windows.
    Returns the extra windows (bool (N,)) and the twelve-window pool of every such group."""
    big = [int(g) for g in np.unique(groups) if (groups == g).sum() >= MIN_GROUP_12]
    extra = np.zeros(len(groups), bool)
    pools = {}
    for g in sorted(context_rows):
        if g not in big:
            continue
        rows_g = np.where(groups == g)[0]
        candidates = rows_g[~context[rows_g]]
        ex = np.sort(np.random.default_rng([0xCA12, dataset_index, k, g]).choice(candidates, EXTRA, replace=False))
        extra[ex] = True
        pools[g] = np.sort(np.concatenate([context_rows[g], ex]))
    return extra, pools


class Draw:
    """One context draw of one dataset, checked against the reference window lists of the evaluation data."""

    def __init__(self, dataset, X, groups, gait, k, reference):
        self.k = k
        self.walking, self.context, self.no_frame = context_draw(X, groups, gait, k)
        self.keys, self.rows = device_keys(X, groups, self.context)
        self.extra, self.pools = extra_context(groups, self.context, self.rows, DATASETS.index(dataset), k)
        r = reference["draws"][k]
        assert np.array_equal(np.flatnonzero(self.context), r["context"]), f"{dataset} draw {k}: context differs"
        assert np.array_equal(np.flatnonzero(self.no_frame), r["no_walking_frame"]), f"{dataset} draw {k}: walking frame"
        assert np.array_equal(np.flatnonzero(self.extra), r["extra_context_six_of_twelve"]), f"{dataset} draw {k}: 6 of 12"
        self.scored = ~self.context                      # every reading embeds these windows, in this order


def dataset_protocol(dataset, X, eval_data):
    """Person groups and gait windows of one dataset (checked against the reference lists) -> (groups, gait, ref)."""
    groups = eval_data.person_groups(dataset, len(X))
    gait = gait_mask(X)
    ref = eval_data.windows(dataset)
    assert ref["n_windows"] == len(X), dataset
    assert np.array_equal(np.flatnonzero(gait), ref["gait"]), f"{dataset}: gait windows differ"
    return groups, gait, ref


def macro_f1(pred, y, n_classes):
    f = []
    for c in range(n_classes):
        tp = np.sum((pred == c) & (y == c))
        fp = np.sum((pred == c) & (y != c))
        fn = np.sum((pred != c) & (y == c))
        if tp + fn == 0:
            continue
        f.append(0.0 if tp == 0 else 2 * tp / (2 * tp + fp + fn))
    return 100 * float(np.mean(f))