File size: 3,058 Bytes
07c2907 da5759b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | """Tool layer: dataset registry + calls to the R plumber API. All results are JSON-serialisable."""
import os
from pathlib import Path
import httpx, pandas as pd
DATA = Path(__file__).resolve().parent.parent / "data"
R_API = os.environ.get("R_API_URL", "http://127.0.0.1:8001")
DATASETS = {
"secom": {"file": "secom_sample.csv", "desc": "Semiconductor manufacturing process sensors per batch (UCI SECOM). Columns: batch, timestamp, fail, sensor_*.", "kind": "process"},
"ryegrass": {"file": "ryegrass_dose_response.csv", "desc": "Ryegrass root length (rootl) vs herbicide concentration (conc): dose-response.", "kind": "dose_response"},
"pastes": {"file": "pastes_strength.csv", "desc": "Paint-paste strength by production batch and cask: batch-to-batch variability.", "kind": "batch"},
}
_cache = {}
def load(name):
if name not in DATASETS: raise ValueError(f"unknown dataset '{name}'; choose from {list(DATASETS)}")
if name not in _cache: _cache[name] = pd.read_csv(DATA / DATASETS[name]["file"])
return _cache[name]
def _clean(v):
return [None if pd.isna(x) else x for x in v]
def _post(path, body):
r = httpx.post(f"{R_API}{path}", json=body, timeout=120); r.raise_for_status()
out = r.json()
if isinstance(out, dict) and "error" in out: raise ValueError(out["error"])
return out
def list_datasets(): return {k: v["desc"] for k, v in DATASETS.items()}
def detect_drift(dataset: str, column: str, baseline_n: int = 100):
df = load(dataset)
if column not in df.columns: raise ValueError(f"column '{column}' not in {list(df.columns)}")
res = _post("/drift", {"values": _clean(df[column]), "baseline_n": baseline_n})
res.update(dataset=dataset, column=column, units_note="shift_in_sd is the mean shift in units of BASELINE standard deviations (5.0 means five SDs); mean_before/mean_after are in raw sensor units; changepoint and its CI are batch numbers", method="Phase-I 3-sigma limits + least-squares mean-shift changepoint, residual bootstrap 95% CI")
return res
def fit_dose_response(dataset: str = "ryegrass"):
df = load(dataset)
res = _post("/dose_response", {"dose": df["conc"].tolist(), "response": df["rootl"].tolist()})
res.update(dataset=dataset, method="4-parameter log-logistic (drc::LL.4), Wald 95% CI")
return res
def batch_variance(dataset: str = "pastes"):
df = load(dataset)
res = _post("/batch_variance", {"group": df["batch"].tolist(), "values": df["strength"].tolist()})
res.update(dataset=dataset, method="Random-intercept mixed model (lme4, REML), profile 95% CI")
return res
def power_calc(delta: float, sd: float, power: float = 0.8, alpha: float = 0.05):
return _post("/power", {"delta": delta, "sd": sd, "power": power, "alpha": alpha})
def series(dataset, column):
"""Raw series for plotting."""
df = load(dataset)
# JSON has no NaN: missing readings (SECOM has some) become null, which the UI plots as gaps
return {"x": df.iloc[:, 0].tolist(), "y": [None if v != v else v for v in df[column].tolist()]}
|