cisdeli commited on
Commit
3ecb175
·
1 Parent(s): 56e40b6

feat: ports codebase from notebooks

Browse files
scripts/build_plot_model_dataset.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the per-plot modeling dataset from per-tuber morphometrics and ground truth.
2
+
3
+ QC-filter the per-tuber dataframe, aggregate to (trial, Plot_std), merge
4
+ with the cleaned ground truth, and compute the regression target
5
+ obs_sum_B_A1_A2_OV.
6
+
7
+ Usage:
8
+ uv run python scripts/build_plot_model_dataset.py \\
9
+ --tubers outputs/df_class_real_scale_ALL.csv \\
10
+ --out outputs/df_model_yield_by_plot.csv
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+
20
+ from potatopheno.aggregation import aggregate_by_plot
21
+ from potatopheno.filtering import (
22
+ ADC_QC_DROP_PLOTS,
23
+ derive_axis_ratio_pca,
24
+ drop_qc_plots,
25
+ filter_axis_ratio,
26
+ )
27
+ from potatopheno.harvest import add_plot_std, merge_with_ground_truth
28
+
29
+
30
+ def _parse_args() -> argparse.Namespace:
31
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
32
+ p.add_argument(
33
+ "--tubers",
34
+ type=Path,
35
+ required=True,
36
+ help="Per-tuber morphometrics CSV produced by extract_morphometrics.py.",
37
+ )
38
+ p.add_argument(
39
+ "--gt",
40
+ type=Path,
41
+ required=True,
42
+ help="Cleaned ground-truth CSV.",
43
+ )
44
+ p.add_argument(
45
+ "--out",
46
+ type=Path,
47
+ required=True,
48
+ help="Path of the plot-level model CSV to write.",
49
+ )
50
+ p.add_argument(
51
+ "--qc-drop-plots",
52
+ type=lambda s: tuple(t.strip() for t in s.split(",") if t.strip()),
53
+ default=ADC_QC_DROP_PLOTS,
54
+ help="Comma-separated list of Plot IDs (image_id[-8:]) to drop as QC. "
55
+ f"Default: {','.join(ADC_QC_DROP_PLOTS)}.",
56
+ )
57
+ p.add_argument(
58
+ "--no-ar-filter",
59
+ action="store_true",
60
+ help="Skip the axis-ratio-PCA filter entirely.",
61
+ )
62
+ return p.parse_args()
63
+
64
+
65
+ def main() -> None:
66
+ args = _parse_args()
67
+
68
+ df_tubers = pd.read_csv(args.tubers)
69
+ n0 = len(df_tubers)
70
+
71
+ df = drop_qc_plots(df_tubers, drop_plots=args.qc_drop_plots)
72
+ n1 = len(df)
73
+
74
+ df = derive_axis_ratio_pca(df)
75
+ if not args.no_ar_filter:
76
+ df = filter_axis_ratio(df)
77
+ n2 = len(df)
78
+
79
+ df = add_plot_std(df)
80
+
81
+ df_agg = aggregate_by_plot(df)
82
+ df_gt = pd.read_csv(args.gt)
83
+ df_model = merge_with_ground_truth(df_agg, df_gt)
84
+
85
+ args.out.parent.mkdir(parents=True, exist_ok=True)
86
+ df_model.to_csv(args.out, index=False)
87
+
88
+ print(f"qc_drop_plots={list(args.qc_drop_plots)} ar_filter={'OFF' if args.no_ar_filter else 'ON'}")
89
+ print(
90
+ f"tubers: {n0} → after qc-drop: {n1} → "
91
+ f"after AR filter: {n2}"
92
+ )
93
+ print(
94
+ f"plots: {df_model['Plot_std'].nunique()} across "
95
+ f"{df_model['trial'].nunique()} trials"
96
+ )
97
+ print(f"[DONE] wrote {len(df_model)} rows → {args.out}")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
scripts/extract_morphometrics.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the morphometrics stage end-to-end across all trials.
2
+
3
+ Reads YOLO-seg .txt predictions and the matching source images, computes
4
+ per-tuber polygon morphometrics, converts to real-scale (inches and
5
+ square inches), assigns USDA size class, and concatenates the three
6
+ trials into a single combined CSV.
7
+
8
+ Usage:
9
+ uv run python scripts/extract_morphometrics.py \\
10
+ --out outputs/df_class_real_scale_ALL.csv
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+
20
+ from potatopheno.calibration import BELT_WIDTH_IN_DEFAULT, apply_real_scale
21
+ from potatopheno.classification import assign_usda_class
22
+ from potatopheno.io import build_morphometrics_dataframe, plot_id_from_image_id
23
+
24
+ TRIALS = ("NCPT", "ADC", "NCR")
25
+
26
+
27
+ def _parse_args() -> argparse.Namespace:
28
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
29
+ p.add_argument(
30
+ "--preds-root",
31
+ type=Path,
32
+ required=True,
33
+ help="Root of YOLO preds. Expects <trial>/preds/*.txt under it.",
34
+ )
35
+ p.add_argument(
36
+ "--images-root",
37
+ type=Path,
38
+ required=True,
39
+ help="Root of raw images. Expects 2025<TRIAL>/*.JPG under it.",
40
+ )
41
+ p.add_argument(
42
+ "--out",
43
+ type=Path,
44
+ required=True,
45
+ help="Path of the combined per-tuber CSV to write.",
46
+ )
47
+ p.add_argument(
48
+ "--trials",
49
+ type=lambda s: tuple(t.strip() for t in s.split(",") if t.strip()),
50
+ default=TRIALS,
51
+ help=f"Comma-separated trial names. Default: {','.join(TRIALS)}.",
52
+ )
53
+ p.add_argument(
54
+ "--belt-width-in",
55
+ type=float,
56
+ default=BELT_WIDTH_IN_DEFAULT,
57
+ help="Conveyor belt width in inches used for pixel-to-inch calibration.",
58
+ )
59
+ return p.parse_args()
60
+
61
+
62
+ def main() -> None:
63
+ args = _parse_args()
64
+ args.out.parent.mkdir(parents=True, exist_ok=True)
65
+
66
+ per_trial: list[pd.DataFrame] = []
67
+ for trial in args.trials:
68
+ preds_dir = args.preds_root / trial / "preds"
69
+ images_dir = args.images_root / f"2025{trial}"
70
+
71
+ df = build_morphometrics_dataframe(trial, images_dir, preds_dir)
72
+ df["Plot"] = plot_id_from_image_id(df["image_id"])
73
+ df = apply_real_scale(df, belt_width_in=args.belt_width_in)
74
+ df = assign_usda_class(df)
75
+
76
+ print(
77
+ f"[{trial}] images={df['image_id'].nunique()} "
78
+ f"instances={len(df)} "
79
+ f"class_counts={df['class'].value_counts().to_dict()}"
80
+ )
81
+ per_trial.append(df)
82
+
83
+ combined = pd.concat(per_trial, ignore_index=True)
84
+ combined.to_csv(args.out, index=False)
85
+
86
+ print(
87
+ f"\n[DONE] wrote {len(combined)} rows across "
88
+ f"{combined['trial'].nunique()} trials → {args.out}"
89
+ )
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()
scripts/fit_final_models.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit M1, M2, M3 on the full plot-level dataset and save coefficients.
2
+
3
+ These in-sample fits are used by the demo app for single-image yield
4
+ prediction. The demo only has features from one uploaded image, so there
5
+ is no test fold; we want the best-known M3 mapping from (class areas,
6
+ mean_area) to predicted obs_sum_B_A1_A2_OV.
7
+
8
+ Usage:
9
+ uv run python scripts/fit_final_models.py \\
10
+ --input outputs/df_model_yield_by_plot.csv \\
11
+ --out app/m3_coefficients.json
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ from pathlib import Path
19
+
20
+ import pandas as pd
21
+ from sklearn.linear_model import LinearRegression
22
+ from sklearn.metrics import r2_score
23
+
24
+ from potatopheno.models import (
25
+ PREDICTORS_M1,
26
+ PREDICTORS_M2,
27
+ PREDICTORS_M3,
28
+ RESPONSE,
29
+ add_model_features,
30
+ )
31
+
32
+
33
+ def _parse_args() -> argparse.Namespace:
34
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
35
+ p.add_argument("--input", type=Path, required=True, help="Plot-level model dataset.")
36
+ p.add_argument(
37
+ "--out",
38
+ type=Path,
39
+ required=True,
40
+ help="Path to write the JSON coefficients file (used by the Gradio app).",
41
+ )
42
+ return p.parse_args()
43
+
44
+
45
+ def _fit(df: pd.DataFrame, predictors: tuple[str, ...], name: str) -> dict:
46
+ subset = df.dropna(subset=list(predictors) + [RESPONSE])
47
+ X = subset[list(predictors)]
48
+ y = subset[RESPONSE]
49
+ model = LinearRegression()
50
+ model.fit(X, y)
51
+ pred = model.predict(X)
52
+ return {
53
+ "name": name,
54
+ "predictors": list(predictors),
55
+ "response": RESPONSE,
56
+ "intercept": float(model.intercept_),
57
+ "coefficients": {p: float(c) for p, c in zip(predictors, model.coef_)},
58
+ "n_train_plots": int(len(subset)),
59
+ "in_sample_r2": float(r2_score(y, pred)),
60
+ }
61
+
62
+
63
+ def main() -> None:
64
+ args = _parse_args()
65
+ df = pd.read_csv(args.input)
66
+ df = add_model_features(df)
67
+
68
+ fits = {
69
+ "M1": _fit(df, PREDICTORS_M1, "M1"),
70
+ "M2": _fit(df, PREDICTORS_M2, "M2"),
71
+ "M3": _fit(df, PREDICTORS_M3, "M3"),
72
+ }
73
+
74
+ args.out.parent.mkdir(parents=True, exist_ok=True)
75
+ with open(args.out, "w") as f:
76
+ json.dump(fits, f, indent=2)
77
+
78
+ for name, fit in fits.items():
79
+ print(
80
+ f"{name}: n_train={fit['n_train_plots']:>4} in-sample R²={fit['in_sample_r2']:.3f} "
81
+ f"intercept={fit['intercept']:+.3f}"
82
+ )
83
+ print(f"\n[DONE] wrote → {args.out}")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
scripts/run_loto_models.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run M1, M2, M3, and RF under leave-one-trial-out yield prediction.
2
+
3
+ Adds the M3 structural features, runs LOTO for each of the four models,
4
+ and writes the per-fold metrics, per-plot predictions, and the cross-fold
5
+ summary.
6
+
7
+ Usage:
8
+ uv run python scripts/run_loto_models.py \\
9
+ --input outputs/df_model_yield_by_plot.csv \\
10
+ --out-dir outputs/loto/
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+
20
+ from potatopheno.evaluate import (
21
+ run_loto_linear,
22
+ run_loto_rf,
23
+ summarize_across_trials,
24
+ )
25
+ from potatopheno.models import (
26
+ PREDICTORS_M1,
27
+ PREDICTORS_M2,
28
+ PREDICTORS_M3,
29
+ PREDICTORS_RF,
30
+ RESPONSE,
31
+ RF_KWARGS,
32
+ add_model_features,
33
+ )
34
+
35
+
36
+ def _parse_args() -> argparse.Namespace:
37
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
38
+ p.add_argument(
39
+ "--input",
40
+ type=Path,
41
+ required=True,
42
+ help="Plot-level model dataset (output of build_plot_model_dataset.py).",
43
+ )
44
+ p.add_argument(
45
+ "--out-dir",
46
+ type=Path,
47
+ required=True,
48
+ help="Directory to write the metrics, predictions, and summary CSVs.",
49
+ )
50
+ return p.parse_args()
51
+
52
+
53
+ def main() -> None:
54
+ args = _parse_args()
55
+ args.out_dir.mkdir(parents=True, exist_ok=True)
56
+
57
+ df = pd.read_csv(args.input)
58
+ df = add_model_features(df)
59
+
60
+ runs = [
61
+ ("M1", run_loto_linear, PREDICTORS_M1, {}),
62
+ ("M2", run_loto_linear, PREDICTORS_M2, {}),
63
+ ("M3", run_loto_linear, PREDICTORS_M3, {}),
64
+ ("RF", run_loto_rf, PREDICTORS_RF, RF_KWARGS),
65
+ ]
66
+
67
+ pred_parts: list[pd.DataFrame] = []
68
+ metric_parts: list[pd.DataFrame] = []
69
+ for name, runner, predictors, extra in runs:
70
+ df_pred, df_metrics = runner(df, predictors, RESPONSE, name, **extra)
71
+ pred_parts.append(df_pred)
72
+ metric_parts.append(df_metrics)
73
+
74
+ df_pred_all = pd.concat(pred_parts, ignore_index=True)
75
+ df_metrics_all = (
76
+ pd.concat(metric_parts, ignore_index=True)
77
+ .sort_values(["model", "test_trial"])
78
+ .reset_index(drop=True)
79
+ )
80
+ df_summary = summarize_across_trials(df_metrics_all).sort_values("mean_MAPE")
81
+
82
+ df_metrics_all.to_csv(args.out_dir / "loto_metrics_by_fold.csv", index=False)
83
+ df_pred_all.to_csv(args.out_dir / "loto_predictions_by_plot.csv", index=False)
84
+ df_summary.to_csv(args.out_dir / "loto_summary_by_model.csv", index=False)
85
+
86
+ print("\nLOTO metrics by fold:\n")
87
+ print(df_metrics_all.round(3).to_string(index=False))
88
+ print("\nLOTO summary across folds (mean of trial-level metrics):\n")
89
+ print(df_summary.round(3).to_string(index=False))
90
+ print(f"\n[DONE] wrote 3 CSVs → {args.out_dir}")
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
scripts/run_yolo_inference.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run YOLOv11-seg inference on tuber images and emit per-image .txt files.
2
+
3
+ Default predict parameters: conf=0.25, imgsz=1280. Output .txt files
4
+ follow the YOLO-seg format consumed by the morphometrics stage.
5
+
6
+ Single-trial usage:
7
+ uv run python scripts/run_yolo_inference.py \\
8
+ --weights path/to/bestModel.pt \\
9
+ --images path/to/2025NCPT \\
10
+ --out-dir outputs/preds/NCPT
11
+
12
+ All three trials usage:
13
+ uv run python scripts/run_yolo_inference.py \\
14
+ --weights path/to/bestModel.pt \\
15
+ --images-root path/to/rawData/images \\
16
+ --out-root outputs/preds
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ from pathlib import Path
23
+
24
+ from potatopheno.segmentation import load_model, predict_directory
25
+
26
+ TRIALS = ("NCPT", "ADC", "NCR")
27
+
28
+
29
+ def _parse_args() -> argparse.Namespace:
30
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
31
+ p.add_argument("--weights", type=Path, required=True, help="Path to bestModel.pt.")
32
+
33
+ single = p.add_argument_group("single-trial mode")
34
+ single.add_argument(
35
+ "--images",
36
+ type=Path,
37
+ help="Directory of input images (single trial).",
38
+ )
39
+ single.add_argument(
40
+ "--out-dir",
41
+ type=Path,
42
+ help="Directory to write .txt files into.",
43
+ )
44
+
45
+ multi = p.add_argument_group("all-trials mode")
46
+ multi.add_argument(
47
+ "--images-root",
48
+ type=Path,
49
+ help="Parent directory with 2025<TRIAL>/ subdirs.",
50
+ )
51
+ multi.add_argument(
52
+ "--out-root",
53
+ type=Path,
54
+ help="Parent directory; <TRIAL>/preds/ will be created under it.",
55
+ )
56
+ multi.add_argument(
57
+ "--trials",
58
+ type=lambda s: tuple(t.strip() for t in s.split(",") if t.strip()),
59
+ default=TRIALS,
60
+ help=f"Comma-separated trial names (default: {','.join(TRIALS)}).",
61
+ )
62
+
63
+ p.add_argument("--conf", type=float, default=0.25, help="Confidence threshold.")
64
+ p.add_argument("--imgsz", type=int, default=1280, help="Inference image size.")
65
+ p.add_argument("--chunk-size", type=int, default=15, help="Images per streaming chunk.")
66
+ return p.parse_args()
67
+
68
+
69
+ def main() -> None:
70
+ args = _parse_args()
71
+
72
+ single_mode = args.images is not None and args.out_dir is not None
73
+ multi_mode = args.images_root is not None and args.out_root is not None
74
+ if single_mode == multi_mode:
75
+ raise SystemExit(
76
+ "Pass EITHER (--images and --out-dir) OR (--images-root and --out-root), not both."
77
+ )
78
+
79
+ model = load_model(args.weights)
80
+ predict_kwargs = {"conf": args.conf, "imgsz": args.imgsz, "verbose": False}
81
+
82
+ if single_mode:
83
+ predict_directory(
84
+ model=model,
85
+ input_dir=args.images,
86
+ output_dir=args.out_dir,
87
+ chunk_size=args.chunk_size,
88
+ **predict_kwargs,
89
+ )
90
+ return
91
+
92
+ for trial in args.trials:
93
+ predict_directory(
94
+ model=model,
95
+ input_dir=args.images_root / f"2025{trial}",
96
+ output_dir=args.out_root / trial / "preds",
97
+ chunk_size=args.chunk_size,
98
+ **predict_kwargs,
99
+ )
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
src/potatopheno/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.1.0"
src/potatopheno/aggregation.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plot-level aggregation of per-tuber morphometrics.
2
+
3
+ Per (trial, Plot_std): total projected area and tuber count.
4
+ Per (trial, Plot_std, class): class-specific projected area, pivoted
5
+ wide to area_{B,A1,A2,OV}_in2 with NaN replaced by 0 for absent classes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import pandas as pd
11
+
12
+ CLASS_AREA_COLUMNS: tuple[str, ...] = (
13
+ "area_B_in2",
14
+ "area_A1_in2",
15
+ "area_A2_in2",
16
+ "area_OV_in2",
17
+ )
18
+
19
+
20
+ def aggregate_total_area(df: pd.DataFrame) -> pd.DataFrame:
21
+ """One row per (trial, Plot_std) with total_area_in2 and n_tubers."""
22
+ return (
23
+ df.groupby(["trial", "Plot_std"], as_index=False)
24
+ .agg(
25
+ total_area_in2=("area_poly_in2", "sum"),
26
+ n_tubers=("detection_id", "count"),
27
+ )
28
+ )
29
+
30
+
31
+ def aggregate_area_by_class_wide(df: pd.DataFrame) -> pd.DataFrame:
32
+ """One row per (trial, Plot_std) with one column per USDA class area."""
33
+ long = (
34
+ df.groupby(["trial", "Plot_std", "class"], as_index=False, observed=True)
35
+ .agg(class_area_in2=("area_poly_in2", "sum"))
36
+ )
37
+ wide = (
38
+ long.pivot(index=["trial", "Plot_std"], columns="class", values="class_area_in2")
39
+ .fillna(0)
40
+ .reset_index()
41
+ .rename(
42
+ columns={
43
+ "B": "area_B_in2",
44
+ "A1": "area_A1_in2",
45
+ "A2": "area_A2_in2",
46
+ "OV": "area_OV_in2",
47
+ }
48
+ )
49
+ )
50
+ wide.columns.name = None
51
+ for col in CLASS_AREA_COLUMNS:
52
+ if col not in wide.columns:
53
+ wide[col] = 0.0
54
+ return wide
55
+
56
+
57
+ def aggregate_by_plot(df: pd.DataFrame) -> pd.DataFrame:
58
+ """Combine total-area and class-area-wide aggregations on (trial, Plot_std)."""
59
+ df_total = aggregate_total_area(df)
60
+ df_wide = aggregate_area_by_class_wide(df)
61
+ return df_total.merge(df_wide, on=["trial", "Plot_std"], how="left")
src/potatopheno/calibration.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pixel-to-inch calibration using the conveyor belt as a known reference.
2
+
3
+ The 30" belt width is mapped to the image HEIGHT (in pixels), not image
4
+ width. This matches the camera setup where the 30" cross-belt dimension
5
+ corresponds to the shorter side of the cropped region of interest.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import pandas as pd
11
+
12
+ BELT_WIDTH_IN_DEFAULT = 30.0
13
+
14
+
15
+ def apply_real_scale(df: pd.DataFrame, belt_width_in: float = BELT_WIDTH_IN_DEFAULT) -> pd.DataFrame:
16
+ """Add real-scale columns derived from belt-width calibration.
17
+
18
+ Adds: width_in, height_in, inMinDim, area_poly_in2.
19
+
20
+ Expects columns: img_height_px, width_px, height_px, area_poly_px.
21
+ """
22
+ df = df.copy()
23
+ inch_per_px = belt_width_in / df["img_height_px"]
24
+ scale_area_in2 = inch_per_px**2
25
+
26
+ df["width_in"] = df["width_px"] * inch_per_px
27
+ df["height_in"] = df["height_px"] * inch_per_px
28
+ df["inMinDim"] = df[["width_in", "height_in"]].min(axis=1)
29
+ df["area_poly_in2"] = df["area_poly_px"] * scale_area_in2
30
+ return df
src/potatopheno/classification.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """USDA size-class assignment from the minimum in-plane tuber dimension.
2
+
3
+ Reference: https://www.ams.usda.gov/grades-standards/potatoes-grades-and-standards
4
+ Classification is based on min(width_in, height_in) of the polygon
5
+ bounding box (the inMinDim column). The PO ("pickout") class is not
6
+ assigned here, since PO is a quality grade rather than a size class.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ # Right-open bins: [B] < 1.875 ≤ [A1] < 2.5625 ≤ [A2] < 3.25 ≤ [OV]
15
+ USDA_BIN_EDGES_IN = [-np.inf, 1.875, 2.5625, 3.25, np.inf]
16
+ USDA_LABELS = ["B", "A1", "A2", "OV"]
17
+
18
+
19
+ def assign_usda_class(df: pd.DataFrame, dim_col: str = "inMinDim") -> pd.DataFrame:
20
+ """Add a categorical `class` column with USDA size label per tuber."""
21
+ df = df.copy()
22
+ df["class"] = pd.cut(
23
+ df[dim_col],
24
+ bins=USDA_BIN_EDGES_IN,
25
+ labels=USDA_LABELS,
26
+ right=False,
27
+ )
28
+ return df
src/potatopheno/evaluate.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Leave-one-trial-out evaluation for the yield-prediction models.
2
+
3
+ Each runner returns:
4
+ - df_pred: one row per plot per fold with predicted, error, abs_error,
5
+ fold_test_trial, and model columns appended.
6
+ - df_metrics: one row per (model, test_trial) with R2, RMSE, MAE, MAPE,
7
+ BIAS. BIAS uses the convention mean(obs - pred), so positive bias
8
+ means under-prediction.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterable
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ from sklearn.ensemble import RandomForestRegressor
18
+ from sklearn.linear_model import LinearRegression
19
+ from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
20
+
21
+
22
+ def _fold_metrics(
23
+ model_name: str,
24
+ test_trial: str,
25
+ y_test: np.ndarray | pd.Series,
26
+ pred: np.ndarray,
27
+ n_test: int,
28
+ ) -> dict:
29
+ return {
30
+ "model": model_name,
31
+ "test_trial": test_trial,
32
+ "n_test_plots": n_test,
33
+ "R2": r2_score(y_test, pred),
34
+ "RMSE": float(np.sqrt(mean_squared_error(y_test, pred))),
35
+ "MAE": mean_absolute_error(y_test, pred),
36
+ "MAPE": float(np.mean(np.abs((y_test - pred) / y_test)) * 100),
37
+ "BIAS": float(np.mean(y_test - pred)),
38
+ }
39
+
40
+
41
+ def _annotate_predictions(
42
+ test: pd.DataFrame,
43
+ pred: np.ndarray,
44
+ response: str,
45
+ test_trial: str,
46
+ model_name: str,
47
+ ) -> pd.DataFrame:
48
+ out = test.copy()
49
+ out["predicted"] = pred
50
+ out["error"] = out[response] - out["predicted"]
51
+ out["abs_error"] = out["error"].abs()
52
+ out["fold_test_trial"] = test_trial
53
+ out["model"] = model_name
54
+ return out
55
+
56
+
57
+ def run_loto_linear(
58
+ df: pd.DataFrame,
59
+ predictors: Iterable[str],
60
+ response: str,
61
+ model_name: str,
62
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
63
+ """LOTO over trials with a fresh `LinearRegression` per fold."""
64
+ predictors = list(predictors)
65
+ df = df.copy()
66
+ trials = sorted(df["trial"].dropna().unique())
67
+
68
+ pred_rows: list[pd.DataFrame] = []
69
+ metric_rows: list[dict] = []
70
+ for test_trial in trials:
71
+ train = df[df["trial"] != test_trial].copy()
72
+ test = df[df["trial"] == test_trial].copy()
73
+ train = train.dropna(subset=predictors + [response])
74
+ test = test.dropna(subset=predictors + [response])
75
+
76
+ X_train, y_train = train[predictors], train[response]
77
+ X_test, y_test = test[predictors], test[response]
78
+
79
+ model = LinearRegression()
80
+ model.fit(X_train, y_train)
81
+ pred = model.predict(X_test)
82
+
83
+ pred_rows.append(_annotate_predictions(test, pred, response, test_trial, model_name))
84
+ metric_rows.append(_fold_metrics(model_name, test_trial, y_test, pred, len(test)))
85
+
86
+ df_pred = pd.concat(pred_rows, axis=0, ignore_index=True)
87
+ df_metrics = pd.DataFrame(metric_rows)
88
+ return df_pred, df_metrics
89
+
90
+
91
+ def run_loto_rf(
92
+ df: pd.DataFrame,
93
+ predictors: Iterable[str],
94
+ response: str,
95
+ model_name: str,
96
+ **rf_kwargs,
97
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
98
+ """LOTO over trials with a fresh `RandomForestRegressor` per fold."""
99
+ predictors = list(predictors)
100
+ df = df.copy()
101
+ trials = sorted(df["trial"].dropna().unique())
102
+
103
+ pred_rows: list[pd.DataFrame] = []
104
+ metric_rows: list[dict] = []
105
+ for test_trial in trials:
106
+ train = df[df["trial"] != test_trial].copy()
107
+ test = df[df["trial"] == test_trial].copy()
108
+ train = train.dropna(subset=predictors + [response])
109
+ test = test.dropna(subset=predictors + [response])
110
+
111
+ X_train, y_train = train[predictors], train[response]
112
+ X_test, y_test = test[predictors], test[response]
113
+
114
+ model = RandomForestRegressor(**rf_kwargs)
115
+ model.fit(X_train, y_train)
116
+ pred = model.predict(X_test)
117
+
118
+ pred_rows.append(_annotate_predictions(test, pred, response, test_trial, model_name))
119
+ metric_rows.append(_fold_metrics(model_name, test_trial, y_test, pred, len(test)))
120
+
121
+ df_pred = pd.concat(pred_rows, axis=0, ignore_index=True)
122
+ df_metrics = pd.DataFrame(metric_rows)
123
+ return df_pred, df_metrics
124
+
125
+
126
+ def summarize_across_trials(df_metrics: pd.DataFrame) -> pd.DataFrame:
127
+ """Mean of each metric across LOTO folds, one row per model."""
128
+ return (
129
+ df_metrics.groupby("model", as_index=False)
130
+ .agg(
131
+ n_test_plots=("n_test_plots", "sum"),
132
+ mean_R2=("R2", "mean"),
133
+ mean_RMSE=("RMSE", "mean"),
134
+ mean_MAE=("MAE", "mean"),
135
+ mean_MAPE=("MAPE", "mean"),
136
+ mean_BIAS=("BIAS", "mean"),
137
+ )
138
+ )
src/potatopheno/filtering.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QC filters applied to the per-tuber morphometrics dataframe.
2
+
3
+ Three steps:
4
+ - Drop ADC plot images whose ROI cropping removed substantial tuber area.
5
+ - Derive the PCA-based axis ratio from eccentricity.
6
+ - Filter out tubers with axis_ratio_pca above the pooled 99.5th percentile.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ # ADC plot images dropped because the cropping step removed substantial
15
+ # tuber area. Values are the raw "Plot" column (image_id[-8:]).
16
+ ADC_QC_DROP_PLOTS: tuple[str, ...] = (
17
+ "5_ADC116", # MSDD247-07
18
+ "5_ADC131", # MSHH015-5
19
+ "5_ADC141", # NY174
20
+ "5_ADC129", # MSGG409-3
21
+ "5_ADC105", # Huron Chipper
22
+ "5_ADC205", # Huron Chipper
23
+ )
24
+
25
+ AR_PCA_FILTER_QUANTILE: float = 0.995
26
+
27
+
28
+ def drop_qc_plots(
29
+ df: pd.DataFrame,
30
+ drop_plots: tuple[str, ...] = ADC_QC_DROP_PLOTS,
31
+ plot_col: str = "Plot",
32
+ ) -> pd.DataFrame:
33
+ """Drop plots listed in drop_plots from the per-tuber dataframe."""
34
+ return df[~df[plot_col].isin(drop_plots)].copy()
35
+
36
+
37
+ def derive_axis_ratio_pca(df: pd.DataFrame) -> pd.DataFrame:
38
+ """Add axis_ratio_pca = 1 / sqrt(1 - eccentricity^2)."""
39
+ df = df.copy()
40
+ ecc = np.clip(df["eccentricity"], 0, 0.999999)
41
+ df["axis_ratio_pca"] = 1.0 / np.sqrt(1.0 - ecc**2)
42
+ return df
43
+
44
+
45
+ def filter_axis_ratio(
46
+ df: pd.DataFrame,
47
+ quantile: float = AR_PCA_FILTER_QUANTILE,
48
+ ) -> pd.DataFrame:
49
+ """Keep tubers with axis_ratio_pca at or below the pooled quantile threshold."""
50
+ upper = df["axis_ratio_pca"].quantile(quantile)
51
+ return df[df["axis_ratio_pca"] <= upper].copy()
src/potatopheno/harvest.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plot-ID standardization and harvest-data merging.
2
+
3
+ Standardizes raw plot identifiers (e.g. "5_ADC101", "NCRCH3") into a
4
+ canonical form (e.g. "ADC-101", "NCR-CH3") and merges plot-level
5
+ aggregations onto the ground-truth harvest data.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ # Yield columns from the harvest sheet that get summed into the regression target.
16
+ YIELD_CLASS_COLUMNS: tuple[str, ...] = ("B", "A1", "A2", "OV")
17
+ # Columns coerced to numeric after the merge. OV+ is coerced but NOT
18
+ # summed into the response.
19
+ NUMERIC_COERCION_COLUMNS: tuple[str, ...] = ("B", "A1", "A2", "OV", "OV+")
20
+ RESPONSE_COLUMN: str = "obs_sum_B_A1_A2_OV"
21
+
22
+
23
+ def standardize_plot_id(x, trial_name: str | None = None) -> str | float:
24
+ """Normalize a raw plot identifier.
25
+
26
+ Strips a leading numeric prefix like "5_", removes whitespace, expands
27
+ NCR-CH variants, and zero-pads the trial-suffix number to 3 digits.
28
+ When applied to a column derived from image filenames (last 8 chars),
29
+ trial_name can be omitted and standardization runs off the format alone.
30
+ """
31
+ if pd.isna(x):
32
+ return np.nan
33
+ x = str(x).strip()
34
+ if x == "" or x.lower() == "nan":
35
+ return np.nan
36
+
37
+ x = re.sub(r"^\d+_", "", x)
38
+ x = x.replace(" ", "")
39
+
40
+ if trial_name == "NCR" and re.fullmatch(r"CH\d+", x):
41
+ return f"NCR-{x}"
42
+
43
+ x = re.sub(r"^NCRCH(\d+)$", r"NCR-CH\1", x)
44
+ x = re.sub(r"^NCRC(\d+)$", r"NCR-CH\1", x)
45
+
46
+ if trial_name and re.fullmatch(r"\d+", x):
47
+ return f"{trial_name}-{x.zfill(3)}"
48
+
49
+ m = re.fullmatch(r"(ADC|NCR|NCPT)-?(\d+)", x)
50
+ if m:
51
+ return f"{m.group(1)}-{m.group(2).zfill(3)}"
52
+
53
+ return x
54
+
55
+
56
+ def add_plot_std(df: pd.DataFrame, plot_col: str = "Plot") -> pd.DataFrame:
57
+ """Add a `Plot_std` column derived from the raw plot identifier."""
58
+ df = df.copy()
59
+ df["Plot_std"] = df[plot_col].apply(standardize_plot_id)
60
+ return df
61
+
62
+
63
+ def merge_with_ground_truth(
64
+ df_aggregated: pd.DataFrame,
65
+ df_gt: pd.DataFrame,
66
+ ) -> pd.DataFrame:
67
+ """Left-join plot-level aggregations onto the standardized ground truth.
68
+
69
+ Adds the regression target obs_sum_B_A1_A2_OV = B + A1 + A2 + OV
70
+ using sum(min_count=1) so plots with all-NaN yield columns stay NaN.
71
+ """
72
+ df = df_aggregated.merge(
73
+ df_gt, on=["trial", "Plot_std"], how="left", suffixes=("", "_gt")
74
+ )
75
+ for col in NUMERIC_COERCION_COLUMNS:
76
+ if col in df.columns:
77
+ df[col] = pd.to_numeric(df[col], errors="coerce")
78
+ df[RESPONSE_COLUMN] = df[list(YIELD_CLASS_COLUMNS)].sum(axis=1, min_count=1)
79
+ return df
src/potatopheno/io.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read YOLO-seg .txt predictions and build a per-tuber morphometrics dataframe.
2
+
3
+ YOLO-seg .txt format (one detection per line):
4
+ class_id x1 y1 x2 y2 ... xN yN # coords normalized to [0, 1]
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ from PIL import Image
14
+
15
+ from .morphometrics import polygon_shape_metrics
16
+
17
+ IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff"}
18
+
19
+
20
+ def read_yolo_seg_txt(txt_path: str | Path) -> list[dict]:
21
+ """Parse a YOLO-seg .txt file into a list of {class_id, xy_norm}.
22
+
23
+ Lines with fewer than 3 vertices (6 coordinates) or an odd coordinate
24
+ count are skipped.
25
+ """
26
+ polys: list[dict] = []
27
+ with open(txt_path) as f:
28
+ for line in f:
29
+ line = line.strip()
30
+ if not line:
31
+ continue
32
+ parts = line.split()
33
+ class_id = int(float(parts[0]))
34
+ coords = np.array(list(map(float, parts[1:])), dtype=float)
35
+ if coords.size < 6 or coords.size % 2 != 0:
36
+ continue
37
+ polys.append({"class_id": class_id, "xy_norm": coords.reshape(-1, 2)})
38
+ return polys
39
+
40
+
41
+ def _list_images(folder: Path) -> list[Path]:
42
+ return sorted(p for p in folder.rglob("*") if p.suffix.lower() in IMG_EXTS)
43
+
44
+
45
+ def build_morphometrics_dataframe(
46
+ trial_name: str,
47
+ images_dir: str | Path,
48
+ preds_dir: str | Path,
49
+ ) -> pd.DataFrame:
50
+ """Produce one row per detected tuber with all pixel-scale shape metrics.
51
+
52
+ Pairs each .txt file in `preds_dir` with the image of the same stem in
53
+ `images_dir` so we can read the image dimensions (needed both for
54
+ denormalizing polygon coordinates and for the downstream calibration).
55
+ """
56
+ images_dir = Path(images_dir)
57
+ preds_dir = Path(preds_dir)
58
+
59
+ if not preds_dir.exists():
60
+ raise FileNotFoundError(f"[{trial_name}] preds_dir not found: {preds_dir}")
61
+ if not images_dir.exists():
62
+ raise FileNotFoundError(f"[{trial_name}] images_dir not found: {images_dir}")
63
+
64
+ image_map = {p.stem: p for p in _list_images(images_dir)}
65
+ txt_files = sorted(preds_dir.glob("*.txt"))
66
+ if not txt_files:
67
+ raise ValueError(f"[{trial_name}] No .txt files found in {preds_dir}")
68
+
69
+ rows: list[dict] = []
70
+ skipped_txt_no_image = 0
71
+
72
+ for txt in txt_files:
73
+ img_stem = txt.stem
74
+ img_path = image_map.get(img_stem)
75
+ if img_path is None:
76
+ skipped_txt_no_image += 1
77
+ continue
78
+
79
+ with Image.open(img_path) as im:
80
+ img_width, img_height = im.size
81
+
82
+ for line_idx, poly in enumerate(read_yolo_seg_txt(txt), start=1):
83
+ xy = poly["xy_norm"]
84
+ xs = xy[:, 0] * img_width
85
+ ys = xy[:, 1] * img_height
86
+ metrics = polygon_shape_metrics(xs, ys)
87
+
88
+ rows.append(
89
+ {
90
+ "trial": trial_name,
91
+ "image_id": img_stem,
92
+ "detection_id": f"{img_stem}_{line_idx}",
93
+ "class_id": poly["class_id"],
94
+ "img_width_px": img_width,
95
+ "img_height_px": img_height,
96
+ "n_points": len(xs),
97
+ **metrics,
98
+ }
99
+ )
100
+
101
+ df = pd.DataFrame(rows)
102
+ if skipped_txt_no_image:
103
+ print(
104
+ f"[{trial_name}] images={len(image_map)} txt={len(txt_files)} "
105
+ f"instances={len(df)} skipped_txt_no_image={skipped_txt_no_image}"
106
+ )
107
+ return df
108
+
109
+
110
+ def plot_id_from_image_id(image_id: pd.Series) -> pd.Series:
111
+ """Derive a raw plot identifier from the last 8 characters of the image stem.
112
+
113
+ The result (e.g. "NCPT-129", "5_ADC101") is further normalized by
114
+ standardize_plot_id in the yield-prediction stage.
115
+ """
116
+ return image_id.str[-8:]
src/potatopheno/models.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Predictor sets and feature engineering for the yield-prediction models.
2
+
3
+ M1, M2, M3 are linear regressions on increasingly rich plot-level
4
+ features. RF is a Random Forest baseline that uses a seven-feature
5
+ predictor set including squared and total-area aggregate features.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import pandas as pd
11
+
12
+ PREDICTORS_M1: tuple[str, ...] = ("total_area_in2",)
13
+ PREDICTORS_M2: tuple[str, ...] = (
14
+ "area_B_in2",
15
+ "area_A1_in2",
16
+ "area_A2_in2",
17
+ "area_OV_in2",
18
+ )
19
+ PREDICTORS_M3: tuple[str, ...] = (
20
+ "area_B_in2",
21
+ "area_A1_in2",
22
+ "area_A2_in2",
23
+ "area_OV_in2",
24
+ "mean_area",
25
+ )
26
+ # Wider feature set for the Random Forest baseline: four class areas plus
27
+ # mean_area, total_area_sq, and total_area_in2.
28
+ PREDICTORS_RF: tuple[str, ...] = (
29
+ "area_B_in2",
30
+ "area_A1_in2",
31
+ "area_A2_in2",
32
+ "area_OV_in2",
33
+ "mean_area",
34
+ "total_area_sq",
35
+ "total_area_in2",
36
+ )
37
+
38
+ RESPONSE: str = "obs_sum_B_A1_A2_OV"
39
+
40
+ RF_KWARGS: dict = {
41
+ "n_estimators": 500,
42
+ "random_state": 42,
43
+ "max_depth": None,
44
+ "min_samples_split": 2,
45
+ "min_samples_leaf": 1,
46
+ "n_jobs": -1,
47
+ }
48
+
49
+
50
+ def add_model_features(df: pd.DataFrame) -> pd.DataFrame:
51
+ """Recompute total_area_in2 from class areas, add mean_area and total_area_sq.
52
+
53
+ total_area_in2 is overwritten with the sum of the four class-area
54
+ columns (this can differ from the upstream aggregate if any tubers
55
+ have a NaN class). mean_area = total_area_in2 / n_tubers, and
56
+ total_area_sq = total_area_in2 ** 2.
57
+ """
58
+ df = df.copy()
59
+ df["total_area_in2"] = df[list(PREDICTORS_M2)].sum(axis=1)
60
+ df["mean_area"] = df["total_area_in2"] / df["n_tubers"]
61
+ df["total_area_sq"] = df["total_area_in2"] ** 2
62
+ return df
src/potatopheno/morphometrics.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Polygon-based morphometric traits for a single segmented tuber.
2
+
3
+ The width and height used by downstream stages are the extents of the
4
+ polygon bounding box. The aspect_ratio field is bbox max/min and is not
5
+ used as the published axis-ratio; a PCA-based ratio is derived from
6
+ eccentricity in the modeling stage.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+
13
+
14
+ def close_polygon(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
15
+ if x.size == 0 or y.size == 0:
16
+ return x, y
17
+ if x[0] != x[-1] or y[0] != y[-1]:
18
+ x = np.concatenate([x, x[:1]])
19
+ y = np.concatenate([y, y[:1]])
20
+ return x, y
21
+
22
+
23
+ def polygon_area_px(x: np.ndarray, y: np.ndarray) -> float:
24
+ """Shoelace formula. Eq. (2) in the paper."""
25
+ x, y = close_polygon(x, y)
26
+ if x.size < 3:
27
+ return float("nan")
28
+ area = 0.0
29
+ for i in range(len(x) - 1):
30
+ area += x[i] * y[i + 1] - x[i + 1] * y[i]
31
+ return abs(area) / 2.0
32
+
33
+
34
+ def polygon_perimeter_px(x: np.ndarray, y: np.ndarray) -> float:
35
+ """Sum of Euclidean distances between consecutive vertices. Eq. (1) in the paper."""
36
+ x, y = close_polygon(x, y)
37
+ if x.size < 2:
38
+ return float("nan")
39
+ dx = np.diff(x)
40
+ dy = np.diff(y)
41
+ return float(np.sqrt(dx**2 + dy**2).sum())
42
+
43
+
44
+ def polygon_circularity(x: np.ndarray, y: np.ndarray) -> float:
45
+ """4·π·A / P²."""
46
+ A = polygon_area_px(x, y)
47
+ P = polygon_perimeter_px(x, y)
48
+ if not np.isfinite(A) or not np.isfinite(P) or P <= 0:
49
+ return float("nan")
50
+ return float(4.0 * np.pi * A / (P**2))
51
+
52
+
53
+ def polygon_eccentricity(x: np.ndarray, y: np.ndarray) -> float:
54
+ """sqrt(1 - λ_min / λ_max) of the polygon-vertex covariance matrix."""
55
+ if len(x) < 3:
56
+ return float("nan")
57
+ coords = np.column_stack([x, y])
58
+ coords_centered = coords - coords.mean(axis=0, keepdims=True)
59
+ cov_mat = np.cov(coords_centered, rowvar=False)
60
+ eigvals = np.linalg.eigvalsh(cov_mat)
61
+ eigvals = np.sort(eigvals)[::-1]
62
+ if eigvals.size < 2 or eigvals[0] <= 0:
63
+ return float("nan")
64
+ return float(np.sqrt(1.0 - eigvals[1] / eigvals[0]))
65
+
66
+
67
+ def aspect_ratio_bbox(width: float, height: float) -> float:
68
+ if width <= 0 or height <= 0:
69
+ return float("nan")
70
+ return float(max(width, height) / min(width, height))
71
+
72
+
73
+ def roundness_bbox(width: float, height: float) -> float:
74
+ if width <= 0 or height <= 0:
75
+ return float("nan")
76
+ area_bbox = width * height
77
+ max_dim = max(width, height)
78
+ return float(4.0 * area_bbox / (np.pi * max_dim**2))
79
+
80
+
81
+ def polygon_shape_metrics(x: np.ndarray, y: np.ndarray) -> dict[str, float]:
82
+ """All per-tuber pixel-space metrics in a single call.
83
+
84
+ Returns: area_poly_px, perimeter_px, circularity, eccentricity,
85
+ width_px, height_px, aspect_ratio, roundness_bbox.
86
+ """
87
+ area_px = polygon_area_px(x, y)
88
+ perim_px = polygon_perimeter_px(x, y)
89
+ circ = polygon_circularity(x, y)
90
+ ecc = polygon_eccentricity(x, y)
91
+
92
+ width_px = float(x.max() - x.min()) if x.size > 0 else float("nan")
93
+ height_px = float(y.max() - y.min()) if y.size > 0 else float("nan")
94
+ ar = aspect_ratio_bbox(width_px, height_px)
95
+ rb = roundness_bbox(width_px, height_px)
96
+
97
+ return {
98
+ "area_poly_px": area_px,
99
+ "perimeter_px": perim_px,
100
+ "circularity": circ,
101
+ "eccentricity": ecc,
102
+ "width_px": width_px,
103
+ "height_px": height_px,
104
+ "aspect_ratio": ar,
105
+ "roundness_bbox": rb,
106
+ }
src/potatopheno/segmentation.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """YOLOv11-seg instance segmentation for tuber detection.
2
+
3
+ Wraps the Ultralytics YOLO API with conf=0.25, imgsz=1280, default NMS
4
+ IoU, no augmentation. Polygon coordinates are normalized to [0, 1] and
5
+ written in the YOLO-seg .txt format consumed by io.read_yolo_seg_txt.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import gc
11
+ from collections.abc import Iterable, Iterator
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ from ultralytics import YOLO
17
+
18
+ from .io import IMG_EXTS
19
+
20
+ YOLO_PREDICT_DEFAULTS: dict[str, Any] = {
21
+ "conf": 0.25,
22
+ "imgsz": 1280,
23
+ "verbose": False,
24
+ }
25
+
26
+
27
+ def load_model(weights_path: str | Path) -> YOLO:
28
+ """Load YOLOv11-seg weights via the Ultralytics API."""
29
+ return YOLO(str(weights_path))
30
+
31
+
32
+ def predict_image(
33
+ model: YOLO,
34
+ image: str | Path | np.ndarray,
35
+ **predict_kwargs: Any,
36
+ ) -> list[tuple[int, np.ndarray]]:
37
+ """Run inference on a single image; return [(class_id, polygon_normalized)].
38
+
39
+ `polygon_normalized` is an (N, 2) float array of (x, y) coordinates in
40
+ [0, 1]. Returns an empty list if no instances were detected.
41
+ """
42
+ params = {**YOLO_PREDICT_DEFAULTS, **predict_kwargs}
43
+ results = model.predict(source=image, stream=False, **params)
44
+ r = results[0]
45
+ if r.masks is None:
46
+ return []
47
+ h, w = r.orig_shape
48
+ detections: list[tuple[int, np.ndarray]] = []
49
+ for poly_xy, box in zip(r.masks.xy, r.boxes):
50
+ class_id = int(box.cls[0])
51
+ normalized = poly_xy / np.array([w, h], dtype=poly_xy.dtype)
52
+ detections.append((class_id, normalized))
53
+ return detections
54
+
55
+
56
+ def write_yolo_seg_txt(detections: Iterable[tuple[int, np.ndarray]], txt_path: str | Path) -> None:
57
+ """Write detections in the legacy YOLO-seg format.
58
+
59
+ One line per detection: `class_id x1 y1 x2 y2 ...` with coords in [0, 1].
60
+ Creates an empty file if `detections` is empty (matches legacy behavior).
61
+ """
62
+ with open(txt_path, "w") as f:
63
+ for class_id, poly in detections:
64
+ coords = poly.reshape(-1)
65
+ f.write(f"{class_id} " + " ".join(map(str, coords)) + "\n")
66
+
67
+
68
+ def _list_images(folder: Path) -> list[Path]:
69
+ return sorted(p for p in folder.rglob("*") if p.suffix.lower() in IMG_EXTS)
70
+
71
+
72
+ def _chunked(lst: list[Path], n: int) -> Iterator[list[Path]]:
73
+ for i in range(0, len(lst), n):
74
+ yield lst[i : i + n]
75
+
76
+
77
+ def predict_directory(
78
+ model: YOLO,
79
+ input_dir: str | Path,
80
+ output_dir: str | Path,
81
+ chunk_size: int = 15,
82
+ **predict_kwargs: Any,
83
+ ) -> dict[str, int]:
84
+ """Run inference over every image under input_dir, writing one .txt per image.
85
+
86
+ Streams predictions in chunks of chunk_size and triggers GC between
87
+ chunks. Empty .txt files are still created for images with no detections.
88
+
89
+ Returns a dict with n_images, n_with_masks, n_seen for QC.
90
+ """
91
+ input_dir = Path(input_dir)
92
+ output_dir = Path(output_dir)
93
+ output_dir.mkdir(parents=True, exist_ok=True)
94
+
95
+ image_paths = _list_images(input_dir)
96
+ print(f"[INFO] {input_dir.name}: {len(image_paths)} images")
97
+ if not image_paths:
98
+ return {"n_images": 0, "n_seen": 0, "n_with_masks": 0}
99
+
100
+ params = {**YOLO_PREDICT_DEFAULTS, **predict_kwargs}
101
+ seen = 0
102
+ with_masks = 0
103
+
104
+ for ci, part in enumerate(_chunked(image_paths, chunk_size), start=1):
105
+ gen = model.predict(source=[p.as_posix() for p in part], stream=True, **params)
106
+ # zip() rather than trusting r.path: in some Ultralytics versions
107
+ # r.path falls back to "imageN" inside a batched/streamed call,
108
+ # which causes chunks to overwrite each other's outputs. stream=True
109
+ # preserves input order, so part[i] matches the i-th yielded result.
110
+ for img_path, r in zip(part, gen):
111
+ seen += 1
112
+ txt_path = output_dir / f"{img_path.stem}.txt"
113
+ with open(txt_path, "w") as f:
114
+ if r.masks is not None:
115
+ with_masks += 1
116
+ h, w = r.orig_shape
117
+ for poly_xy, box in zip(r.masks.xy, r.boxes):
118
+ class_id = int(box.cls[0])
119
+ coords: list[float] = []
120
+ for x, y in poly_xy:
121
+ coords.append(x / w)
122
+ coords.append(y / h)
123
+ f.write(f"{class_id} " + " ".join(map(str, coords)) + "\n")
124
+ del r
125
+ gc.collect()
126
+ if ci == 1 or ci % 10 == 0:
127
+ print(
128
+ f"[INFO] chunk {ci}: {min(ci * chunk_size, len(image_paths))}/"
129
+ f"{len(image_paths)} images"
130
+ )
131
+
132
+ print(f"[DONE] {output_dir}: seen={seen}, with_masks={with_masks}")
133
+ return {"n_images": len(image_paths), "n_seen": seen, "n_with_masks": with_masks}