diff --git a/alert_rule.py b/alert_rule.py index 9c6ea7a..b77856a 100644 --- a/alert_rule.py +++ b/alert_rule.py @@ -1,26 +1,54 @@ -"""The alert rule Hillclimb is allowed to change. +"""Robust per-animal baseline, multi-signal, coverage-aware.""" -risk(history, today, herd) -> float. Higher means more likely to be getting sick. +import statistics - history: this animal's previous days, oldest first (at most 60), each a dict - with keys animal, day, weekday, temp_c, activity, rumination, lying, coverage. - Sensor values are None on days the collar reported nothing. - today: the same dict for today. - herd: today's dicts for every animal in the herd (including this one). -Baseline: how far today's rumination has dropped below this animal's mean -over the previous 7 days, in units of its standard deviation. -""" +def _z(history, today, key, sign, n=21): + v = today[key] + if v is None or today["coverage"] < 0.6: + return None + vals = [h[key] for h in history[-n - 2:-2] if h[key] is not None and h["coverage"] >= 0.6] + if len(vals) < 4: + return None + med = statistics.median(vals) + mad = statistics.median([abs(x - med) for x in vals]) * 1.4826 + sd = max(mad, 0.3 * (statistics.pstdev(vals) or 1.0), 1e-6) + return sign * (med - v) / sd + + +_H = {} +_SHIFT = {} -import statistics + +def _shift(herd, day): + if day in _SHIFT: + return _SHIFT[day] + vals = [] + for r in herd: + h = _H.get(r["animal"], []) + if len(h) >= 5: + vals.append(_score(h, r)) + _SHIFT[day] = statistics.median(vals) if len(vals) >= 10 else 0.0 + for r in herd: + _H.setdefault(r["animal"], []).append(r) + return _SHIFT[day] def risk(history, today, herd): - if today["rumination"] is None: - return 0.0 - recent = [h["rumination"] for h in history[-7:] if h["rumination"] is not None] - if len(recent) < 3: - return 0.0 - mean = statistics.fmean(recent) - sd = statistics.stdev(recent) or 1.0 - return (mean - today["rumination"]) / sd + d = today["day"] + sh = _shift(herd, d) + t = _score(history, today) - sh + if len(history) >= 5: + t += 0.6 * (_score(history[:-1], history[-1]) - _SHIFT.get(d - 1, 0.0)) + return t + + +def _score(history, today): + zs = [_z(history, today, "rumination", 1), _z(history, today, "activity", 1), + _z(history, today, "lying", -1)] + w = [1.0, 0.5, 0.5] + tot = 0.0 + for z, wi in zip(zs, w): + if z is not None: + tot += wi * max(min(z, 6.0), -3.0) + return tot