fix(weight,api): carry coop/location through consolidation, purge nan

Consolidation re-derived features/predictions without location/coop and
overwrote batch-written K1-L1 values with blanks; CSV reads then turned
blanks into literal "nan" and parquet rows fell back to bogus
FULL/FULL_CYCLE path inference.

- storage.py: pass location/coop from curation JSONs into
  aggregate_camera_features / build_cage_day_features_and_predictions
- dashboard.py: _enrich_records treats NaN/"nan" as missing;
  /api/weight/coops buckets and /api/weight/coop/<id> filter use
  row values instead of path inference
- tests: assert re-derived date-folder + merged rows keep K1/K1-L1
This commit is contained in:
andrew committed 2026-10-07 12:38:46 +07:00
1 parent 9abce58ac3
commit 61ca7c2cc5
3 files changed
+62 -23

No files matched your search

+31 -22
View File
@@ -1364,10 +1364,14 @@ class DashboardHandler(SimpleHTTPRequestHandler):
def _enrich_records(records: list[dict], file_path: Path) -> list[dict]:
inferred_coop, inferred_loc = _infer_coop_and_location(file_path)
enriched = []
def _clean(v: object) -> str:
s = "" if v is None else str(v)
return "" if s.strip().lower() in ("", "nan", "none") else s
for r in records:
d = dict(r)
loc = str(d.get("location") or inferred_loc or "")
coop = str(d.get("coop") or inferred_coop or (get_coop_for_location(loc) if loc else ""))
loc = _clean(d.get("location")) or _clean(inferred_loc)
coop = _clean(d.get("coop")) or _clean(inferred_coop) or (get_coop_for_location(loc) if loc else "")
d["coop"] = coop
d["location"] = loc
@@ -1409,28 +1413,36 @@ class DashboardHandler(SimpleHTTPRequestHandler):
continue
d_str = date_match.group(1)
inferred_coop, inferred_loc = _infer_coop_and_location(pred_file)
if inferred_coop not in coops_map:
coops_map[inferred_coop] = {
"coop": inferred_coop,
row_coop, row_loc = inferred_coop, inferred_loc
fused_df = None
try:
import pandas as pd
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
records = _enrich_records(df.to_dict(orient="records"), pred_file)
if records:
row_coop = records[0].get("coop") or inferred_coop
row_loc = records[0].get("location") or inferred_loc
fused = df[df["camera_id"] == "FUSED"] if "camera_id" in df.columns else df.iloc[0:0]
fused_df = fused if not fused.empty else df
except Exception:
pass
if row_coop not in coops_map:
coops_map[row_coop] = {
"coop": row_coop,
"locations": set(),
"dates": set(),
"latest_date": d_str,
"latest_weight_g": 0.0,
}
coops_map[inferred_coop]["locations"].add(inferred_loc)
coops_map[inferred_coop]["dates"].add(d_str)
if d_str >= coops_map[inferred_coop]["latest_date"]:
coops_map[inferred_coop]["latest_date"] = d_str
try:
import pandas as pd
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
fused = df[df["camera_id"] == "FUSED"]
if not fused.empty:
coops_map[inferred_coop]["latest_weight_g"] = float(fused.iloc[0].get("predicted_weight_g", 0.0))
elif not df.empty:
coops_map[inferred_coop]["latest_weight_g"] = float(df.iloc[0].get("predicted_weight_g", 0.0))
except Exception:
pass
coops_map[row_coop]["locations"].add(row_loc)
coops_map[row_coop]["dates"].add(d_str)
if d_str >= coops_map[row_coop]["latest_date"]:
coops_map[row_coop]["latest_date"] = d_str
if fused_df is not None and not fused_df.empty:
try:
coops_map[row_coop]["latest_weight_g"] = float(fused_df.iloc[0].get("predicted_weight_g", 0.0))
except Exception:
pass
coop_list = []
for c_id in sorted(coops_map.keys()):
@@ -1453,9 +1465,6 @@ class DashboardHandler(SimpleHTTPRequestHandler):
seen_keys = set()
for root in unique_roots:
for pred_file in sorted(root.rglob("predictions_*.parquet")) + sorted(root.rglob("predictions_*.csv")):
inferred_coop, inferred_loc = _infer_coop_and_location(pred_file)
if inferred_coop.upper() != target_coop:
continue
try:
import pandas as pd
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
+14
View File
@@ -340,14 +340,28 @@ def consolidate_full_cycle_datasets(
date=d_str,
cycle_day=cycle_day,
curation_stats=c_stat,
location=str(c_stat.get("location", "") if c_stat else ""),
coop=str(c_stat.get("coop", "") if c_stat else ""),
)
date_cam_aggs.append(cam_agg)
if date_cam_aggs:
# Carry location/coop written by batch (curation JSONs) so the
# re-derived overwrite never blanks them out of the date folders.
date_loc = next(
(str(s.get("location", "")) for s in date_curation_stats.values() if s.get("location")),
"",
)
date_coop = next(
(str(s.get("coop", "")) for s in date_curation_stats.values() if s.get("coop")),
"",
)
features_list, predictions_list = build_cage_day_features_and_predictions(
camera_aggregates=date_cam_aggs,
date=d_str,
cycle_day=cycle_day,
location=date_loc,
coop=date_coop,
)
if features_list:
df_feat = pd.DataFrame(features_list)
+17 -1
View File
@@ -452,7 +452,9 @@ class TestWeightEstimation(unittest.TestCase):
"outliers_discarded": 0,
"rejection_rate": 0.0,
}
save_curation_summary(cur_stat, d_out, date=d_str, camera_id="CC1")
save_curation_summary(
cur_stat, d_out, date=d_str, camera_id="CC1", location="K1-L1", coop="K1"
)
# Run consolidation (default output dir -> dataset_root / cycle_weight_parquet_data)
res = consolidate_full_cycle_datasets(dataset_root)
@@ -480,6 +482,20 @@ class TestWeightEstimation(unittest.TestCase):
pred_df = pd.read_parquet(out_dir / "full_cycle_predictions.parquet")
self.assertEqual(len(pred_df), 2)
# Re-derived rows must keep location/coop from curation JSONs (never blank)
for path in [
dataset_root / "2026-05-22" / "output" / "cage_day_features.parquet",
dataset_root / "2026-05-22" / "output" / "predictions_2026-05-22.parquet",
out_dir / "full_cycle_cage_features.parquet",
out_dir / "full_cycle_predictions.parquet",
]:
df = pd.read_parquet(path)
self.assertTrue(
all(str(v) == "K1-L1" for v in df["location"]),
f"location blanked in {path.name}: {df['location'].tolist()}",
)
self.assertTrue(all(str(v) == "K1" for v in df["coop"]), f"coop blanked in {path.name}")
with open(out_dir / "full_cycle_curation_summary.json") as f:
summary_json = json.load(f)
self.assertEqual(summary_json["total_dates"], 2)