File size: 5,419 Bytes
6e1d960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build the V3 / V5 (optionally V1) companion cache of cache2023/ from the CurrentS files in raw/ (welding2023 dataset).

Row i of every array below is the recording that is row i of cache2023/meta.parquet and x2560.npy (the V2 cache): the CurrentS file
captured simultaneously with that V2 file (same session and condition folder, nearest start time; the pairing is unique and every
pair starts within 0.22 s).  Per point P in --points (default V3,V5):
  cache2023/x10000_<p>.npy  (N, 100000, 3) float32  native 10 kHz, channels <P>V, <P>H, <P>A (the raw column order V3A,V3H,V3V / V5V,V5H,V5A
                                                    is reordered to V, H, A like the V2 cache), per-channel mean removed, first 10 s, zero-padded
  cache2023/x2560_<p>.npy   (N,  25600, 3) float32  the same signal resampled 10 kHz -> 2560 Hz (polyphase FIR, up 32 / down 125, scipy
                                                    resample_poly), the rate and length of x2560.npy
  cache2023/meta_currents.parquet   one row per i: CurrentS path, its t0, dt to the V2 file, sample counts, the removed means, label_conflict
Run from the dataset root (needs raw/, metadata/files_full.csv, cache2023/meta.parquet):
  python scripts/build_cache_currents.py [--points V3,V5] [--out cache2023] [--procs 16] [--limit N]
"""
import argparse, math
from multiprocessing import Pool
from pathlib import Path
import numpy as np, pandas as pd
from scipy import signal

ROOT = Path(__file__).resolve().parents[1]; RAW = ROOT / "raw"
FS_RAW, FS_OUT, SEC = 10000, 2560, 10
NAMES = ["V1A", "V1H", "V1V", "V3A", "V3H", "V3V", "V5V", "V5H", "V5A"]      # CSV columns 1..9 (column 0 is the timestamp)
POINTS = None


def pair(meta, files):
    """CurrentS twin of every V2 cache row: same session + folder, nearest start time."""
    t = pd.to_datetime(files.t_first.str.replace(r"\s+", " ", regex=True), format="%m/%d/%Y %H:%M:%S.%f")
    files = files.assign(t=t, sid=files.session.astype(str) + "|" + files.folder)
    cur = files[files.sensor == "CurrentS"]; v2 = files[files.sensor != "CurrentS"]
    v2 = v2.set_index(v2.session.astype(str).str[4:] + "|" + v2.folder + "|" + v2.file)
    out = []
    for k in meta.day + "|" + meta.folder + "|" + meta.file:
        r = v2.loc[k]; cc = cur[cur.sid == r.sid]; dt = (cc.t - r.t).dt.total_seconds(); j = dt.abs().idxmin()
        c = cc.loc[j]
        out.append(dict(session=int(c.session), folder=c.folder, cur_file=c.file, header=bool(c.header), t0_cur=c.t_first, dt_s=round(float(dt.loc[j]), 6),
                        label_conflict=bool(any(c[f] != r[f] for f in ("cond", "torque", "rpm", "rep", "take")))))
    p = pd.DataFrame(out); assert not (p.session.astype(str) + p.folder + p.cur_file).duplicated().any() and p.dt_s.abs().max() < 1
    return p


def load_one(r):
    p = RAW / str(r["session"]) / r["folder"] / "CurrentS" / r["cur_file"]
    x = pd.read_csv(p, skiprows=5 if r["header"] else 0, header=None, usecols=range(1, 10)).dropna().to_numpy(np.float64)
    n = len(x); out = {}
    for P in POINTS:
        xp = x[:, [NAMES.index(P + ax) for ax in "VHA"]]; mu = xp.mean(0); xp = xp - mu
        y = signal.resample_poly(xp, 32, 125, axis=0)                      # 10 000 -> 2560 Hz
        out[P] = (xp[:SEC * FS_RAW].astype(np.float32), y[:SEC * FS_OUT].astype(np.float32), mu)
    return n, out


def main(points, out, procs, limit):
    global POINTS; POINTS = points
    meta = pd.read_parquet(ROOT / "cache2023" / "meta.parquet"); files = pd.read_csv(ROOT / "metadata" / "files_full.csv")
    p = pair(meta, files)
    if limit: meta, p = meta.iloc[:limit], p.iloc[:limit]
    N = len(p); X10 = {P: np.zeros((N, SEC * FS_RAW, 3), np.float32) for P in points}; X25 = {P: np.zeros((N, SEC * FS_OUT, 3), np.float32) for P in points}
    nraw = np.zeros(N, int); mus = {P: np.zeros((N, 3)) for P in points}
    with Pool(procs) as pool:
        for i, (n, o) in enumerate(pool.imap(load_one, p.to_dict("records"), chunksize=4)):
            nraw[i] = n
            for P in points: a, b, mu = o[P]; X10[P][i, :len(a)] = a; X25[P][i, :len(b)] = b; mus[P][i] = mu
            if i % 100 == 0: print(i, "/", N, flush=True)
    mc = pd.DataFrame(dict(v2_file=meta.file.values, cur_path="raw/" + p.session.astype(str) + "/" + p.folder + "/CurrentS/" + p.cur_file, t0_cur=p.t0_cur, dt_s=p.dt_s,
                           n_raw=nraw, n_valid_10000=np.minimum(nraw, SEC * FS_RAW), n_valid_2560=np.minimum(np.ceil(nraw * 32 / 125).astype(int), SEC * FS_OUT),
                           label_conflict=p.label_conflict))
    for P in points:
        for k, ax in enumerate("VHA"): mc[f"mean_{P}{ax}"] = mus[P][:, k]
    out = ROOT / out; out.mkdir(parents=True, exist_ok=True)
    for P in points: np.save(out / f"x10000_{P.lower()}.npy", X10[P]); np.save(out / f"x2560_{P.lower()}.npy", X25[P])
    mc.to_parquet(out / "meta_currents.parquet", index=False)
    print("saved", {P: X10[P].shape for P in points}, "+ 2560 Hz versions ->", out, "; dt_s range", mc.dt_s.min(), mc.dt_s.max(), "; label_conflict", int(mc.label_conflict.sum()))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); ap.add_argument("--points", default="V3,V5"); ap.add_argument("--out", default="cache2023")
    ap.add_argument("--procs", type=int, default=16); ap.add_argument("--limit", type=int, default=0); a = ap.parse_args()
    main(a.points.split(","), a.out, a.procs, a.limit)