#!/usr/bin/env python3 """Train the fixed hyperspectral s152 M5 architecture with four NPV weights.""" import argparse import csv import hashlib import json import math import os from pathlib import Path import statistics import subprocess ROOT = Path(__file__).resolve().parents[1] WEIGHTS = ("1", "1.5", "2", "3") METRICS = ("npv_precision", "npv_recall", "npv_f1", "npv_iou", "macro_f1", "miou") def sha256(path): digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def read_metrics(path): values = {} for line in path.read_text().splitlines(): key, separator, raw = line.partition(":") if separator and key in {"Precision", "Recall", "F1 Score", "IoU"}: numbers = [float(value.strip()) for value in raw.split(",")] if len(numbers) != 3 or not all(math.isfinite(value) for value in numbers): raise ValueError(f"Invalid three-class metrics in {path}: {line}") values[key] = numbers return { "npv_precision": values["Precision"][1], "npv_recall": values["Recall"][1], "npv_f1": values["F1 Score"][1], "npv_iou": values["IoU"][1], "macro_f1": statistics.mean(values["F1 Score"]), "miou": statistics.mean(values["IoU"]), } def summarize(output, manifest, validation=False): rows = [] for weight in manifest["weights"]: for fold in manifest["folds"]: folder = output / f"npv_{weight.replace('.', 'p')}" / f"fold_{fold}" if not (folder / "completed.json").is_file(): raise ValueError(f"Incomplete run: {folder}") if validation: saved = json.loads((folder / "block_1_best_val_metrics.json").read_text()) metrics = { "npv_precision": saved["precision"][1], "npv_recall": saved["recall"][1], "npv_f1": saved["f1"][1], "npv_iou": saved["iou"][1], "macro_f1": statistics.mean(saved["f1"]), "miou": statistics.mean(saved["iou"]), } else: metrics = read_metrics(folder / "best_model_metrics_block_1.txt") rows.append({ "npv_weight": weight, "fold": fold, **metrics, }) prefix = "validation_" if validation else "" with (output / f"{prefix}per_fold_metrics.csv").open("w") as stream: writer = csv.DictWriter(stream, fieldnames=["npv_weight", "fold", *METRICS]) writer.writeheader() writer.writerows(rows) means = [] for weight in manifest["weights"]: selected = [row for row in rows if row["npv_weight"] == weight] row = {"npv_weight": weight, "folds": len(selected)} for metric in METRICS: numbers = [item[metric] for item in selected] row[f"{metric}_mean"] = statistics.mean(numbers) row[f"{metric}_sd"] = statistics.stdev(numbers) if len(numbers) > 1 else 0.0 means.append(row) with (output / f"{prefix}weight_summary.csv").open("w") as stream: writer = csv.DictWriter(stream, fieldnames=list(means[0])) writer.writeheader() writer.writerows(means) print(f"{'Validation' if validation else 'Held-out test'} summary:", flush=True) print(json.dumps(means, indent=2), flush=True) def prepare(args): data = args.data_root images = data / "predictors/hyspec/FX10_FX17_215_trim_envi_152_crop304_ov76" masks = data / "masks/tiles_152_crop304_ov76/raw/fvc_class/downsample_10cm_mode_fx10_fx17_215_trim_from_5cm_152_crop304_ov76" split_root = data / "predictors/hyspec/FX10_FX17_215_trim_pca10_train_only_envi_152_crop304_ov76" aug_root = data / "outputs_ecosystems/medium/fx10_fx17_spectral_spatial_transformer_train_only" folds = {} for fold in args.folds: splits = split_root / f"fold_{fold}/split_tile_lists" previous = aug_root / f"fold_{fold}/FX10_FX17_215_trim_spectral_spatial_transformer_train_only_fold{fold}_M1" membership = {} split_hashes = {} for split in ("train", "val", "test"): path = splits / f"block_0_{split}_tiles.txt" with path.open() as stream: records = list(csv.DictReader(stream, delimiter="\t")) names = {row["image_file"] for row in records} if not names or len(names) != len(records): raise ValueError(f"Empty or duplicate split: {path}") with (previous / "split_tile_lists" / path.name).open() as stream: old_names = {row["image_file"] for row in csv.DictReader(stream, delimiter="\t")} if names != old_names: raise ValueError(f"Augmentation provenance has different splits: {path}") for row in records: if not (images / row["image_file"]).is_file() or not (masks / row["mask_file"]).is_file(): raise FileNotFoundError(f"Missing source pair: {row}") membership[split] = names split_hashes[str(path)] = sha256(path) for left, right in (("train", "val"), ("train", "test"), ("val", "test")): if membership[left] & membership[right]: raise ValueError(f"Overlapping {left}/{right} lists in fold {fold}") ids = lambda names: {name.split("hyperspectral_")[1].split("_")[0] for name in names} if ids(membership[left]) & ids(membership[right]): raise ValueError(f"Spatial tile leakage in fold {fold}: {left}/{right}") aug = previous / "aug" predictors = sorted((aug / "block0/predictor_10b").glob("*.dat")) if not predictors: raise FileNotFoundError(f"No reusable augmentation pool: {aug}") aug_hashes = {} for predictor in predictors: original = predictor.name.split("_", 1)[1] mask = aug / "block0/mask_fvc" / f"aug1_mask_{Path(original).stem}.tif" if original not in membership["train"] or not mask.is_file(): raise ValueError(f"Unpaired or non-training augmentation: {predictor}") for path in (predictor, predictor.with_suffix(".hdr"), mask): aug_hashes[str(path)] = sha256(path) if {path.name.split("_", 1)[1] for path in predictors} != membership["train"]: raise ValueError(f"Augmentation pool does not cover the complete training split: {aug}") folds[str(fold)] = { "split_dir": str(splits), "split_sha256": split_hashes, "counts": {key: len(value) for key, value in membership.items()}, "augmentation_dir": str(aug), "augmentation_sha256": aug_hashes, } return { "weights": list(args.weights), "folds": list(args.folds), "seed": args.seed, "epochs": args.epochs, "architecture": "unet", "sensor_profile": "fx10_fx17_215_trim_aug_spec_transformer_weights_s152", "spectral_embed_dim": 32, "loss": "FocalLoss", "gamma": 2, "ignore_index": -1, "images": str(images), "masks": str(masks), "fold_provenance": folds, "checkpoint_selection": "minimum source validation loss within each run", "aggregation": "unweighted mean and sample SD of held-out fold metrics; saved metrics rounded to four decimals", "weight_selection": "use source validation metrics only, not held-out test metrics or site-13 labels", "code_sha256": { str(path.relative_to(ROOT)): sha256(path) for path in ( Path(__file__), ROOT / "scripts/run_fx10_fx17_pca_s152.sh", ROOT / "phase_3_models/unet_site_models/config_param.py", ROOT / "phase_3_models/unet_site_models/main_site_specific_models.py", ) }, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data-root", type=Path, default=Path("/home/laura/Documents/data_model")) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--epochs", type=int, default=120) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--weights", nargs="+", choices=WEIGHTS, default=WEIGHTS) parser.add_argument("--folds", nargs="+", type=int, choices=(0, 1, 2), default=(0, 1, 2)) parser.add_argument("--precheck-only", action="store_true") parser.add_argument("--summarize-only", action="store_true") args = parser.parse_args() if args.epochs < 1 or len(set(args.weights)) != len(args.weights) or len(set(args.folds)) != len(args.folds): parser.error("Epochs must be positive; folds and weights must be unique.") output = args.output.resolve() if args.summarize_only: manifest = json.loads((output / "experiment.json").read_text()) summarize(output, manifest) summarize(output, manifest, validation=True) return manifest = prepare(args) print(f"Preflight passed: {len(args.folds)} folds x {len(args.weights)} weights; fixed cached augmentations.", flush=True) if args.precheck_only: return output.mkdir(parents=True, exist_ok=True) with (output / "experiment.json").open("x") as stream: json.dump(manifest, stream, indent=2) for weight in args.weights: for fold in args.folds: folder = output / f"npv_{weight.replace('.', 'p')}" / f"fold_{fold}" provenance = manifest["fold_provenance"][str(fold)] env = dict(os.environ, GLOBAL_SEED=str(args.seed), NUM_EPOCHS=str(args.epochs), CHECKPOINT_DIR_OVERRIDE=str(folder), OUTPUT_ROOT=str(folder), VARIANT=f"npv_{weight}_fold_{fold}", LOG_DIR=str(folder / "logs"), AUG_DIR_OVERRIDE=provenance["augmentation_dir"], IMAGE_FOLDER_OVERRIDE=manifest["images"], MASK_FOLDER_OVERRIDE=manifest["masks"], EXPLICIT_SPLIT_DIR=provenance["split_dir"], NUM_BLOCKS="1", MODEL_VARIANT="", MODEL_ARCHITECTURE="unet", USE_PROFILE_CRITERION="1", SENSOR_PROFILE=manifest["sensor_profile"], SPECTRAL_EMBED_DIM="32", SPECTRAL_EXPERIMENT_MODE="enhanced", USE_SPECTRAL_TRANSFORMER="1", CLASS_WEIGHTS=f"1,{weight},1", BE_WEIGHT_MULT="1", USE_SENESCENCE_AWARE_LOSS="0", PRETRAINED_WEIGHTS_PATH="", USE_STRUCTURE_HEAD="0", USE_INSTANCE_HEAD="0", FVC_CLASS_LABELS="BE=0,NPV=1,PV=2", FVC_OUT_CHANNELS="3", PCA_COMPONENTS="10", FVC_DETECTED_CHANNELS="296", BAND_OPTION="all", EXCLUDE_WATER_BANDS="0", PRELOAD_AUGMENTED_IN_MEMORY="0", REGENERATE_AUG="0", REUSE_EXISTING_AUG="1", ENABLE_SHADOW_ROBUST_AUGMENTATION="0", PATCH_SIZE="152", BATCH_SIZE="4", NUM_WORKERS="0", USE_DISCRIMINATIVE_LR="0", LEARNING_RATE="1e-4", SPLIT_RANDOM_SEED="42", USE_ONE_CYCLE="1", PRECHECK_ONLY="0") print(f"Starting weight={weight}, fold={fold}, epochs={args.epochs}", flush=True) subprocess.run(["bash", str(ROOT / "scripts/run_fx10_fx17_pca_s152.sh")], cwd=ROOT, env=env, check=True) read_metrics(folder / "best_model_metrics_block_1.txt") for path, expected in provenance["split_sha256"].items(): if sha256(Path(path)) != expected: raise ValueError(f"Split changed during training: {path}") for path, expected in provenance["augmentation_sha256"].items(): if sha256(Path(path)) != expected: raise ValueError(f"Cached augmentation changed during training: {path}") (folder / "completed.json").write_text(json.dumps({"weight": weight, "fold": fold})) summarize(output, manifest) summarize(output, manifest, validation=True) if __name__ == "__main__": main()