463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620 | def run_batch(
input_dir: Path,
output_zip: Path,
threshold: float = 0.5,
metadata_csv: Path | None = None,
dish_size_mm: float = DEFAULT_DISH_SIZE_MM,
seed: int | None = 0,
) -> None:
_set_seed(seed)
if metadata_csv and metadata_csv.exists():
meta_df = _load_metadata(metadata_csv)
tasks = _build_metadata_tasks(input_dir, meta_df)
if meta_df.shape[0] and not tasks:
raise FileNotFoundError(
f"No metadata image_path entries in {metadata_csv} matched files "
f"under {input_dir}. Update the metadata file, pass a matching "
"--metadata file, or remove/rename the metadata file to scan images directly."
)
else:
paths = _find_images(input_dir)
# Auto-detect image dates; anchor experiment_date to earliest found date
raw_dates = {p: _detect_image_date(p) for p in paths}
known = [d for d in raw_dates.values() if d]
auto_exp_date = min(known) if known else ""
tasks = [
(
p,
{
"image_path": str(p.relative_to(input_dir)),
"image_date": raw_dates[p],
"experiment_date": auto_exp_date,
},
)
for p in paths
]
if not tasks:
raise FileNotFoundError(f"No images found in {input_dir}")
print(f"Processing {len(tasks)} image(s) …", flush=True)
results: list[dict] = []
all_overlays: dict[str, Image.Image] = {}
for i, (img_path, meta) in enumerate(tasks, 1):
print(f" [{i}/{len(tasks)}] {img_path.name}", flush=True)
try:
row, overlays = _process_image(
img_path, meta, threshold, dish_size_mm=dish_size_mm
)
results.append(row)
all_overlays.update(overlays)
except Exception as exc:
print(f" WARNING: {exc}", file=sys.stderr, flush=True)
results.append({**meta, "error": str(exc)})
def _dc_to_num(s: object, fallback: int = 0) -> int:
if isinstance(s, str) and s.startswith("d") and s[1:].isdigit():
return int(s[1:])
return fallback
df = pd.DataFrame(results)
# days_since_start: prefer numeric value from day_code column (set by the user
# in the GUI or metadata CSV); fall back to (image_date - experiment_date) arithmetic.
if "day_code" in df.columns:
dc_nums = df["day_code"].apply(_dc_to_num)
df["days_since_start"] = dc_nums
elif "image_date" in df.columns and "experiment_date" in df.columns:
_id = pd.to_datetime(df["image_date"], errors="coerce")
_ed = pd.to_datetime(df["experiment_date"], errors="coerce")
df["days_since_start"] = (_id - _ed).dt.days.fillna(0).astype(int) + 1
# Growth-rate calculations using actual calendar-day intervals between images
if "image_date" in df.columns and "experiment_date" in df.columns:
df["image_date"] = pd.to_datetime(df["image_date"], errors="coerce")
df["experiment_date"] = pd.to_datetime(df["experiment_date"], errors="coerce")
# Sort by day_code numeric value so rows are in chronological order
if "days_since_start" in df.columns:
sort_cols = (
["experiment_name", "days_since_start"]
if "experiment_name" in df.columns
else ["days_since_start"]
)
else:
sort_cols = (
["experiment_name", "image_date"]
if "experiment_name" in df.columns
else ["image_date"]
)
df = df.sort_values(sort_cols)
df["rgr_per_day"] = float("nan")
df["relative_growth_per_day"] = float("nan")
grp_col = "experiment_name" if "experiment_name" in df.columns else None
groups = df.groupby(grp_col) if grp_col else [(None, df)]
for _, g in groups:
g = g.sort_values("days_since_start" if "days_since_start" in g.columns else "image_date")
for j in range(1, len(g)):
# Use actual calendar days for rate math, not just day-code difference
try:
dd = int((g.iloc[j]["image_date"] - g.iloc[j - 1]["image_date"]).days)
except Exception:
dd = int(g.iloc[j].get("days_since_start", j) - g.iloc[j - 1].get("days_since_start", j - 1))
a1 = g.iloc[j - 1].get("area_mm2") or 0
a2 = g.iloc[j].get("area_mm2") or 0
if dd > 0 and a1 > 0 and a2 > 0:
df.loc[g.index[j], "rgr_per_day"] = (
math.log(float(a2)) - math.log(float(a1))
) / dd
df.loc[g.index[j], "relative_growth_per_day"] = (
float(a2) - float(a1)
) / dd
# Write zip
tmp = Path(tempfile.mkdtemp())
csv_p = tmp / "analysis_full.csv"
json_p = tmp / "analysis_full.json"
df.to_csv(csv_p, index=False)
df.to_json(json_p, orient="records", indent=2, date_format="iso")
overlays_dir = tmp / "overlays"
overlays_dir.mkdir()
for name, img_pil in all_overlays.items():
img_pil.save(overlays_dir / name, quality=92)
charts_dir = tmp / "charts"
_write_charts(df, charts_dir)
from .pipeline import DEVICE
provenance_p = tmp / "provenance.json"
provenance_p.write_text(
json.dumps(
build_provenance(
interface="metrics-petri-cli",
threshold=threshold,
dish_size_mm=dish_size_mm,
device=DEVICE,
seed=seed,
),
indent=2,
)
+ "\n",
encoding="utf-8",
)
with zipfile.ZipFile(output_zip, "w", zipfile.ZIP_DEFLATED) as zf:
zf.write(csv_p, "analysis_full.csv")
zf.write(json_p, "analysis_full.json")
zf.write(provenance_p, "provenance.json")
for f in sorted(overlays_dir.glob("*.jpg")):
zf.write(f, f"overlays/{f.name}")
for f in sorted(charts_dir.glob("*.png")):
zf.write(f, f"charts/{f.name}")
ok = sum(1 for r in results if "error" not in r)
print(f"\n✓ {ok}/{len(results)} images analysed")
print(f"✓ Output: {output_zip}")
|