"""HerdSight synthetic simulator: 10,000 cows x 1,000 days, 8 daily signals. Sensors: the ear tag has a motion sensor + GPS only (steps, distance, feeding, rumination, lying, isolation, geofence). It has NO thermometer. Temperature comes from the barn drone's thermal camera on hourly rounds (`thermal_drone`): per cow-day the mean of that day's hourly body-surface readings, noisier than a contact sensor and often missing (see below). Everything here is SYNTHETIC. Effect sizes are "literature-style": the direction and rough size follow published dairy-sensor studies where named; anything not sourced is marked ASSUMPTION. Effect sizes are randomised per farm and per event (domain randomisation) so a label is never a fixed, trivially readable signature. Run: python simulate.py -> writes data/*.npy (about 450 MB, git-ignored) """ import json import os import time import numpy as np SIGNALS = ["steps", "distance_km", "feeding_min", "rumination_min", "lying_min", "isolation_m", "thermal_drone", "outside_fence_min"] CLASSES = ["normal", "brd", "lame", "estrus", "calving_24h", "stray"] EVENT_TYPES = CLASSES[1:] # Typical daily values for a healthy lactating dairy cow. BASE = { "steps": 3500.0, # ASSUMPTION: pedometer/accelerometer step counts, housed + grazing mix "rumination_min": 500.0, # ~8-9 h/day (Schirmann et al. 2009; Soriani et al. 2013) "feeding_min": 270.0, # ~4-5 h/day (Grant & Albright 1995; DeVries 2003) "lying_min": 690.0, # ~11-12 h/day (Tucker et al. 2021 review: 10-13 h) "isolation_m": 25.0, # ASSUMPTION: mean distance to herd-mates from GPS/UWB tags } STRIDE_KM = 0.0008 # ASSUMPTION: ~0.8 m per step -> 3,500 steps ~ 2.8 km # Mean effect at full intensity: relative change (x0.20 = -20 %) except thermal_drone (degC added) # and outside_fence_min (minutes added). Columns follow SIGNALS. EFFECT = { # BRD: lower feed intake/feeding time days before clinical signs (Wolfger et al. 2015), # lower rumination + activity, fever; isolation ASSUMPTION. Body SURFACE (thermal camera) # rises less than core (core +1-2 degC); +1.0 degC at the surface is an ASSUMPTION. "brd": [-0.20, -0.20, -0.30, -0.25, +0.10, +0.60, +1.0, 0], # Lameness: fewer steps, longer lying (~+1-2 h, Ito et al. 2010; Thorup et al. 2015), # slightly less feeding; isolation ASSUMPTION. "lame": [-0.25, -0.25, -0.08, -0.05, +0.15, +0.30, +0.1, 0], # Estrus: activity 2-4x for ~12-18 h (Roelofs et al. 2005) -> ~+60-120 % per day, # rumination -15-20 % on the day (Reith & Hoy 2012), less lying; temp ASSUMPTION. "estrus": [+0.90, +0.80, -0.10, -0.18, -0.15, -0.10, +0.3, 0], # Calving in next 24 h: rumination drops (Schirmann et al. 2013 ~ -25-35 %), restless, # seeks isolation (Proudfoot et al. 2014); core temp falls ~0.4 degC -> surface -0.2 ASSUMPTION. "calving_24h": [+0.20, +0.10, -0.20, -0.30, -0.08, +1.00, -0.2, 0], # Stray / out of fence: ASSUMPTION throughout; fence minutes drawn per event (60-600). "stray": [+0.30, +0.50, -0.15, -0.05, -0.10, +3.00, 0.0, 0], } # Label priority when events overlap (first wins). PRIORITY = ["calving_24h", "brd", "stray", "lame", "estrus"] RATES_PER_COW_YEAR = { "brd": 0.08, # ASSUMPTION: adult dairy respiratory disease is uncommon; raised for data volume "lame": 0.30, # ASSUMPTION, in line with ~20-30 % lameness prevalence (Thomsen et al. 2023) "stray": 0.40, # ASSUMPTION } def thi(temp_c, rh): """Temperature-humidity index (NRC 1971 form); >= 72 = heat stress for dairy cows.""" t_f = 1.8 * temp_c + 32 return t_f - (0.55 - 0.0055 * rh) * (t_f - 58) def simulate(n_cows=10_000, n_days=1_000, n_farms=20, seed=0): rng = np.random.default_rng(seed) C, D, F = n_cows, n_days, n_farms farm = np.sort(rng.integers(0, F, C)).astype(np.int16) # ---- farm weather: climate (random effect per farm) + season + AR(1) weather + heat waves start_doy = int(rng.integers(0, 365)) doy = (np.arange(D) + start_doy) % 365 season = -np.cos(2 * np.pi * (doy - 20) / 365) # coldest ~20 Jan, hottest ~20 Jul t_mean = rng.uniform(9, 17, F)[:, None] # breeds/climates differ per farm t_amp = rng.uniform(7, 12, F)[:, None] ar = np.zeros((F, D)) eps = rng.normal(0, 2.0, (F, D)) for d in range(1, D): ar[:, d] = 0.75 * ar[:, d - 1] + eps[:, d] waves = np.zeros((F, D)) for f in range(F): # ~3 summer heat waves per year for _ in range(rng.poisson(3 * D / 365)): s = int(rng.integers(0, D)) if season[s] < 0.4: continue waves[f, s:s + rng.integers(3, 9)] += rng.uniform(4, 9) temp = t_mean + t_amp * season + ar + waves rh = np.clip(rng.uniform(55, 80, F)[:, None] + rng.normal(0, 8, (F, D)), 20, 100) thi_fd = thi(temp, rh).astype(np.float32) heat_stress = thi_fd >= 72 # herd-level state, not an illness hs_load = np.clip((thi_fd - 68) / 12, 0, 1.5) # 0 below THI 68, grows with THI # ---- events per cow (python loop over cows; arrays filled by slices) I = {e: np.zeros((C, D), np.float32) for e in EVENT_TYPES} # intensity incl. severity lab = {e: np.zeros((C, D), bool) for e in EVENT_TYPES} post_calving = np.zeros((C, D), np.float32) # fresh-cow dip, labelled normal fence_min = np.zeros((C, D), np.float32) events = [] # (cow, type, label_start, onset, label_end_exclusive) years = D / 365 def put(c, e, a, b, inten, onset): a0, b0 = max(a, 0), min(b, D) if a0 >= b0: return I[e][c, a0:b0] = np.maximum(I[e][c, a0:b0], inten[a0 - a:b0 - a]) lab[e][c, a0:b0] = True events.append((c, EVENT_TYPES.index(e), a0, onset, b0)) for c in range(C): # reproduction: calving -> cycles from ~25-50 d postpartum every 21+-2 d until # conception (35 % per heat, ASSUMPTION), gestation 280+-5 d. calv = int(rng.integers(-330, 40)) while calv < D + 300: if calv >= 1: put(c, "calving_24h", calv - 1, calv, np.array([rng.uniform(0.7, 1.3)]), calv) if 0 <= calv - 2 < D: I["calving_24h"][c, calv - 2] = max(I["calving_24h"][c, calv - 2], 0.3) if 0 <= calv < D: # fresh-cow rumination dip, recovering over 7 days (ASSUMPTION) k = min(7, D - calv) post_calving[c, calv:calv + k] = np.linspace(1, 0, 7)[:k] h = calv + int(rng.integers(25, 50)) while True: if rng.random() > 0.2: # 20 % silent heats (ASSUMPTION) frac = rng.uniform(0.5, 1.0) # share of the 12-18 h bout on day h sev = rng.uniform(0.6, 1.4) put(c, "estrus", h, h + 1, np.array([frac * sev]), h) if 0 <= h + 1 < D: I["estrus"][c, h + 1] = max(I["estrus"][c, h + 1], (1 - frac) * sev) if rng.random() < 0.35 or h - calv > 250: break h += int(rng.integers(19, 24)) calv = h + int(rng.integers(275, 286)) # BRD: 2-4 day subclinical ramp before clinical onset, then 4-10 clinical days for _ in range(rng.poisson(RATES_PER_COW_YEAR["brd"] * years)): on, k, dur = int(rng.integers(0, D)), int(rng.integers(2, 5)), int(rng.integers(4, 11)) sev = rng.uniform(0.6, 1.4) put(c, "brd", on - k, on + dur, sev * np.concatenate([np.linspace(0.2, 0.8, k), np.ones(dur)]), on) # Lameness: 3-5 day gradual ramp before it is scoreable, then 10-40 days for _ in range(rng.poisson(RATES_PER_COW_YEAR["lame"] * years)): on, k, dur = int(rng.integers(0, D)), int(rng.integers(3, 6)), int(rng.integers(10, 41)) sev = rng.uniform(0.6, 1.4) put(c, "lame", on - k, on + dur, sev * np.concatenate([np.linspace(0.2, 0.8, k), np.ones(dur)]), on) for _ in range(rng.poisson(RATES_PER_COW_YEAR["stray"] * years)): on = int(rng.integers(0, D)) put(c, "stray", on, on + 1, np.array([rng.uniform(0.6, 1.4)]), on) fence_min[c, on] = rng.uniform(60, 600) # ---- labels by priority y = np.zeros((C, D), np.int8) for e in reversed(PRIORITY): y[lab[e]] = CLASSES.index(e) del lab # ---- signals farm_mult = rng.uniform(0.6, 1.4, (len(EVENT_TYPES), 8, F)) # domain randomisation hs = hs_load[farm] # (C, D) herd heat load cow_hs_sens = rng.uniform(0.5, 1.5, C)[:, None] # individual heat sensitivity hs_c = hs * cow_hs_sens # heat-stress effect per unit load (ASSUMPTION, direction from Cook et al. 2007 and # Soriani et al. 2013: less lying, less rumination and feeding, warmer body surface) HS = [-0.08, -0.08, -0.12, -0.15, -0.12, -0.15, +1.2, 0] # shared farm-day disturbance (feeding delays, regrouping): ~3 % sd, ASSUMPTION herd_day = rng.normal(0, 0.03, (F, D, 8)).astype(np.float32) X = np.empty((C, D, 8), np.float32) ambient = temp[farm] for s, name in enumerate(SIGNALS): eff = sum(EFFECT[e][s] * farm_mult[i, s][farm][:, None] * I[e] for i, e in enumerate(EVENT_TYPES)) if name == "thermal_drone": # Drone thermal camera, hourly rounds (ASSUMPTION: 12 daylight/barn rounds a day). # Body SURFACE temp tracks ambient (ASSUMPTION ~0.2 degC per degC). Each cow misses # 10-30 % of rounds (under trees / inside the barn); fewer readings -> noisier mean. # Per-reading noise 1.2 degC (distance, angle, wet coat, emissivity: ASSUMPTION), # plus a shared per-flight calibration offset per farm-day. cow_off = rng.normal(0, 0.4, C)[:, None] p_seen = 1 - rng.uniform(0.10, 0.30, C)[:, None] n_read = rng.binomial(12, p_seen, (C, D)) flight_bias = rng.normal(0, 0.3, (F, D))[farm] v = 32.0 + 0.2 * (ambient - 15) + cow_off + eff + HS[s] * hs_c + flight_bias v = v + rng.normal(0, 1.0, (C, D)) * 1.2 / np.sqrt(np.maximum(n_read, 1)) v = np.clip(v, 20.0, 38.5).astype(np.float32) # whole-farm grounded days: storms/heavy snow. 3 % of days anywhere, 30 % of # sub-zero days (ASSUMPTION) grounded = (rng.random((F, D)) < 0.03) | ((temp < 0) & (rng.random((F, D)) < 0.3)) v[(n_read == 0) | grounded[farm]] = np.nan thermal = v X[:, :, s] = v continue if name == "outside_fence_min": glitch = (rng.random((C, D)) < 0.02) * rng.uniform(1, 15, (C, D)) # GPS jitter X[:, :, s] = fence_min + glitch continue if name == "distance_km": X[:, :, s] = X[:, :, 0] * STRIDE_KM * (1 + eff - EFFECT_STEPS_PART) \ * rng.normal(1, 0.05, (C, D)) continue base = BASE[name] * rng.normal(1, 0.08, F)[farm] * rng.normal(1, 0.12, C) mult = 1 + eff + HS[s] * hs_c + herd_day[farm, :, s] mult += 0.03 * season[None, :] * (1 if name == "lying_min" else -1) # mild season if name == "rumination_min": mult -= 0.25 * post_calving noise = rng.lognormal(0, 0.2 if name == "isolation_m" else 0.08, (C, D)) v = base[:, None] * np.clip(mult, 0.05, None) * noise X[:, :, s] = np.clip(v, 0, 1440) if name.endswith("_min") else v if name == "steps": EFFECT_STEPS_PART = eff # distance reuses step effect # sensor missing data: 2 % random cow-days + tag outages (1 per cow-year, 1-5 days) miss = rng.random((C, D)) < 0.02 for c in np.flatnonzero(rng.random(C) < 1 - np.exp(-years)): for _ in range(rng.poisson(years) + 1): s = int(rng.integers(0, D)) miss[c, s:s + rng.integers(1, 6)] = True X[miss] = np.nan # tag gaps hit the tag signals... X[:, :, SIGNALS.index("thermal_drone")] = thermal # ...but not the drone ev = np.array(events, dtype=np.int32) return dict(X=X, y=y, farm=farm, thi=thi_fd, heat_stress=heat_stress, events=ev) def save(out, path="data"): os.makedirs(path, exist_ok=True) for k, v in out.items(): np.save(os.path.join(path, f"{k}.npy"), v) if __name__ == "__main__": t0 = time.time() out = simulate() save(out, os.environ.get("HS_DATA", "data")) y = out["y"] rates = {c: float((y == i).mean()) for i, c in enumerate(CLASSES)} rates["heat_stress_farm_days"] = float(out["heat_stress"].mean()) rates["missing_cow_days_tag"] = float(np.isnan(out["X"][:, :, 0]).mean()) rates["missing_cow_days_thermal_drone"] = float(np.isnan(out["X"][:, :, 6]).mean()) json.dump(rates, open(os.environ.get("HS_DATA", "data") + "/label_rates.json", "w"), indent=1) print(json.dumps(rates, indent=1), f"\n{time.time() - t0:.0f}s")