"""cine-26 demo: detect a person moving on the other side of a wall from Wi-Fi signals alone.

Data: Alsaify et al., "A dataset for Wi-Fi-based human activity recognition in line-of-sight and non-line-of-sight
indoor environments" (Data in Brief 2020; github.com/lcsig/Dataset-for-Wi-Fi-based-human-activity-recognition-in-
LOS-and-NLOS-indoor-environments, MIT). Environment E3: an 8 cm wooden wall between the transmitter (outside the room)
and the receiver (inside), 5.44 m apart; Intel 5300 cards, 2.4 GHz, 320 packets a second, CSI on 30 subcarriers x 3
receive antennas. We use subjects 21-30, 5 trials each of "sit still on a chair" (C01 A01) and "walk from the
transmitter to the receiver" (C03 A06): 100 files.

    python presence.py DATA_DIR OUT_DIR

Features per file (how much the signal wobbles): the median over subcarriers and antennas of the amplitude's standard
deviation over time, and of its mean absolute change packet to packet. A logistic regression trained on subjects
21-27 is tested on subjects 28-30 (people it never saw).
"""
import glob, json, os, sys
import numpy as np
import csiread
from sklearn.linear_model import LogisticRegression

DATA, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)


def load(path):
    c = csiread.Intel(path, nrxnum=3, ntxnum=1, pl_size=0, if_report=False)
    c.read()
    amp = np.abs(c.get_scaled_csi())[:, :, :, 0]                 # packets x 30 subcarriers x 3 antennas
    t = (c.timestamp_low - c.timestamp_low[0]) / 1e6
    return t, amp


def features(amp):
    a = amp.reshape(len(amp), -1)
    return [float(np.median(a.std(axis=0))), float(np.median(np.abs(np.diff(a, axis=0)).mean(axis=0)))]


rows = []
for p in sorted(glob.glob(os.path.join(DATA, "E3_S*_C0*_A*_T*.dat"))):
    name = os.path.basename(p)
    subj = int(name.split("_")[1][1:])
    walk = "_C03_A06_" in name
    t, amp = load(p)
    rows.append({"file": name, "subject": subj, "moving": walk, "packets": int(len(amp)), "seconds": float(t[-1]),
                 "f_std": features(amp)[0], "f_diff": features(amp)[1]})
X = np.array([[r["f_std"], r["f_diff"]] for r in rows]); y = np.array([r["moving"] for r in rows])
train = np.array([r["subject"] <= 27 for r in rows]); test = ~train
clf = LogisticRegression().fit(X[train], y[train])
pred = clf.predict(X[test])
acc = float((pred == y[test]).mean())
wrong = [rows[i]["file"] for i in np.where(test)[0] if clf.predict(X[i:i + 1])[0] != y[i]]
print(f"files {len(rows)}; train subjects 21-27 ({train.sum()} files), test subjects 28-30 ({test.sum()} files)")
print(f"still: wobble {np.mean(X[~y, 0]):.2f} on average; walking: {np.mean(X[y, 0]):.2f}")
print(f"TEST (people it never saw): {int((pred == y[test]).sum())} / {int(test.sum())} right = {acc * 100:.0f} %")
print("wrong:", wrong)
# two example traces for the picture: one still, one walking (subject 29, trial 1)
ex = {}
for kind, pat in (("still", "E3_S29_C01_A01_T01.dat"), ("walking", "E3_S29_C03_A06_T01.dat")):
    t, amp = load(os.path.join(DATA, pat))
    ex[kind] = {"file": pat, "t": [round(float(v), 4) for v in t], "amp_sub15_ant1": [round(float(v), 3) for v in amp[:, 15, 0]],
                "heat": np.round(amp[:, :, 0].T, 2).tolist()}
json.dump({"result": {"test_files": int(test.sum()), "correct": int((pred == y[test]).sum()), "accuracy": acc, "wrong": wrong,
                      "coef": clf.coef_.tolist(), "intercept": clf.intercept_.tolist()},
           "rows": rows}, open(os.path.join(OUT, "presence.json"), "w"), indent=1)
json.dump(ex, open(os.path.join(OUT, "examples.json"), "w"))
