"""Deterministic sensitivity of a published model, NOT a drive experiment.""" import argparse from datetime import datetime, timezone import hashlib import json import math from pathlib import Path import platform ROOT = Path(__file__).resolve().parent EA = 0.46 K = 8.62e-5 T_REF_C = 25.0 RH_REF_PERCENT = 50.0 BETAS = (0.0455, 0.0652) SHARES = (0.0, 0.5, 1.0) TRACES = { "steady": [(25.0, 50.0, 2.0)], "humidity_excursions": [(25.0, 20.0, 1.0), (25.0, 80.0, 1.0)], "hot_humid_paired": [(20.0, 30.0, 1.0), (30.0, 70.0, 1.0)], "hot_dry_paired": [(20.0, 70.0, 1.0), (30.0, 30.0, 1.0)], "unequal_durations": [(25.0, 20.0, 3.0), (25.0, 80.0, 1.0)], } def finite(value, label): if isinstance(value, bool) or not isinstance(value, (float, int)): raise ValueError(label + " must be a real number") try: value = float(value) except OverflowError as error: raise ValueError(label + " must be representable as a finite float") from error if not math.isfinite(value): raise ValueError(label + " must be finite") return value def factors(t_c, rh_percent, beta): t_c = finite(t_c, "temperature") rh_percent = finite(rh_percent, "relative humidity") beta = finite(beta, "beta") # A deliberately bounded teaching domain; not a hardware qualification range. if not 0 <= t_c <= 60 or not 0 <= rh_percent <= 100 or not 0 <= beta <= 0.1: raise ValueError("outside the declared calculation domain") thermal = math.exp((EA / K) * (1 / (T_REF_C + 273.15) - 1 / (t_c + 273.15))) humidity = math.exp(beta * (rh_percent - RH_REF_PERCENT)) return thermal, humidity def analyze(trace, beta): try: iterator = iter(trace) except TypeError as error: raise ValueError("trace must be an iterable of samples") from error samples = [] for sample in iterator: try: t_c, rh_percent, duration = sample except (TypeError, ValueError) as error: raise ValueError("each sample is temperature C, RH percent, duration hours") from error thermal, humidity = factors(t_c, rh_percent, beta) duration = finite(duration, "duration") if duration <= 0: raise ValueError("duration must be positive") samples.append((float(t_c), float(rh_percent), duration, thermal, humidity)) if not samples: raise ValueError("empty trace") try: total = math.fsum(s[2] for s in samples) except OverflowError as error: raise ValueError("total duration must be finite") from error if not math.isfinite(total): raise ValueError("total duration must be finite") weights = [s[2] / total for s in samples] mean_t = math.fsum(w * s[0] for w, s in zip(weights, samples)) mean_rh = math.fsum(w * s[1] for w, s in zip(weights, samples)) # Roundoff can put a convex combination outside the validated input domain. mean_t = min(60.0, max(0.0, mean_t)) mean_rh = min(100.0, max(0.0, mean_rh)) thermal = math.fsum(w * s[3] for w, s in zip(weights, samples)) humidity = math.fsum(w * s[4] for w, s in zip(weights, samples)) joint = math.fsum(w * s[3] * s[4] for w, s in zip(weights, samples)) mean_thermal, mean_humidity = factors(mean_t, mean_rh, beta) collapsed = mean_thermal * mean_humidity return { "mean_temperature_c": mean_t, "mean_rh_percent": mean_rh, "duration_hours": total, "sample_count": len(samples), "thermal_factor": thermal, "humidity_factor": humidity, "controller_factor_joint": joint, "controller_factor_at_means": collapsed, "controller_factor_product_of_marginals": thermal * humidity, "factor_covariance": joint - thermal * humidity, "controller_joint_over_means": joint / collapsed, "total_joint_over_means_by_reference_controller_share": [ {"share": q, "ratio": ((1 - q) * thermal + q * joint) / ((1 - q) * mean_thermal + q * collapsed)} for q in SHARES ], } def calculations(): return { "schema_version": 1, "classification": "constructed_trace_published_equation_sensitivity", "is_hardware_experiment": False, "is_replication_of_fleet_results": False, "parameters": {"Ea_eV": EA, "k_eV_per_K": K, "reference_temperature_c": T_REF_C, "reference_rh_percent": RH_REF_PERCENT, "beta_unit": "per RH percentage point"}, "units": {"temperature": "degree Celsius, converted to kelvin", "rh": "percent, e.g. 50 means 50%, not 0.5", "duration": "hours", "factors_and_ratios": "dimensionless"}, "rows": [ {"case": name, "beta": beta, "trace": [{"temperature_c": t, "rh_percent": rh, "hours": h} for t, rh, h in trace], **analyze(trace, beta)} for beta in BETAS for name, trace in TRACES.items() ], "limits": [ "No original fleet traces, event counts, person-time or baseline cause mixture.", "No estimated AFR, failure probability, causal effect or confidence interval.", "Both beta values are source-specific settings, not an uncertainty interval.", "Time-constant baseline rates are assumed in these short constructed examples.", "A zero reference controller share removes the humidity contribution.", "Joint pairing changes covariance, not temporal order or lagged damage.", "Sufficient telemetry cadence must be measured; no cadence is certified here.", "Input bounds are computational scope, not safe hardware operating limits.", ], } def table(data): rows = [ "# Constructed histories: model arithmetic, not measured disk failures", "", "Ratios compare duration-weighted joint factors with evaluation at the", "duration-weighted mean environment. q is an assumed reference controller", "rate share, not the observed fraction of failures in a different environment.", "", "| Case | b / RH point | Mean C | Mean RH % | Controller ratio | Total ratio, q=0.5 |", "| --- | ---: | ---: | ---: | ---: | ---: |", ] for r in data["rows"]: total = r["total_joint_over_means_by_reference_controller_share"][1]["ratio"] rows.append(f'| {r["case"]} | {r["beta"]:.4f} | {r["mean_temperature_c"]:.1f} | ' f'{r["mean_rh_percent"]:.1f} | {r["controller_joint_over_means"]:.6f} | {total:.6f} |') return "\n".join(rows) + "\n" def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def write_outputs(): result = { "generated_at_utc": datetime.now(timezone.utc).isoformat(), "environment": {"python": platform.python_version(), "platform": platform.platform()}, "input_sha256": {name: digest(ROOT / name) for name in ("model.py", "sources.json")}, "calculation": calculations(), } (ROOT / "results.json").write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") (ROOT / "table.md").write_text(table(result["calculation"])) def verify_outputs(): result = json.loads((ROOT / "results.json").read_text()) expected = calculations() if result["calculation"] != expected: raise ValueError("result values or scope differ from fresh calculation") if result["input_sha256"] != {name: digest(ROOT / name) for name in ("model.py", "sources.json")}: raise ValueError("source hashes differ") if (ROOT / "table.md").read_text() != table(expected): raise ValueError("generated table differs") datetime.fromisoformat(result["generated_at_utc"]) if not result["environment"]["python"] or not result["environment"]["platform"]: raise ValueError("missing environment") return result if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--write", action="store_true") args = parser.parse_args() if args.write: write_outputs() else: verify_outputs() print("Verified 10 constructed histories, exact outputs and source hashes.")