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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standardized v0.0 benchmark evaluation runner.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
# Evaluate predictions on a split
|
| 5 |
+
python dataset_v3/benchmark/evaluate.py \
|
| 6 |
+
--splits random_80_10_10 \
|
| 7 |
+
--predictions results/my_model_preds.json
|
| 8 |
+
|
| 9 |
+
# Generate baseline predictions (dummy/no-skill)
|
| 10 |
+
python dataset_v3/benchmark/evaluate.py --baseline mean
|
| 11 |
+
"""
|
| 12 |
+
import json, os, sys, time, argparse
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from collections import Counter, defaultdict
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from src.evaluation.metrics import compute_metrics
|
| 21 |
+
|
| 22 |
+
BENCHMARK_DIR = Path(__file__).resolve().parent
|
| 23 |
+
SPLITS_DIR = BENCHMARK_DIR / "splits"
|
| 24 |
+
RESULTS_DIR = BENCHMARK_DIR / "results"
|
| 25 |
+
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
DATASET_PATH = os.path.join(os.path.dirname(__file__), "..", "dataset", "entries_final_v3.json")
|
| 28 |
+
TARGETS = ["formation_energy_per_atom", "energy_above_hull", "band_gap"]
|
| 29 |
+
TARGET_LABELS = dict(zip(TARGETS, ["FE", "EaH", "BG"]))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_dataset():
|
| 33 |
+
with open(DATASET_PATH) as f:
|
| 34 |
+
return json.load(f)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_split(name):
|
| 38 |
+
path = SPLITS_DIR / f"{name}.json"
|
| 39 |
+
with open(path) as f:
|
| 40 |
+
return json.load(f)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def evaluate_predictions(entries, split, predictions):
|
| 44 |
+
"""Compute metrics for each target on each split.
|
| 45 |
+
|
| 46 |
+
predictions: dict {entry_index: {target: value, ...}}
|
| 47 |
+
"""
|
| 48 |
+
results = {}
|
| 49 |
+
for target in TARGETS:
|
| 50 |
+
label = TARGET_LABELS[target]
|
| 51 |
+
y_true, y_pred = [], []
|
| 52 |
+
for idx in split["test"]:
|
| 53 |
+
e = entries[idx]
|
| 54 |
+
true_val = e.get(target)
|
| 55 |
+
pred_val = predictions.get(str(idx), {}).get(target)
|
| 56 |
+
if true_val is not None and pred_val is not None:
|
| 57 |
+
y_true.append(true_val)
|
| 58 |
+
y_pred.append(pred_val)
|
| 59 |
+
|
| 60 |
+
if len(y_true) < 10:
|
| 61 |
+
results[label] = {"n": len(y_true), "error": "insufficient data"}
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
metrics = compute_metrics(np.array(y_true), np.array(y_pred))
|
| 65 |
+
metrics["n"] = len(y_true)
|
| 66 |
+
results[label] = metrics
|
| 67 |
+
|
| 68 |
+
return results
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def per_family_metrics(entries, split, predictions):
|
| 72 |
+
"""Metrics broken down by material family."""
|
| 73 |
+
results = {}
|
| 74 |
+
families = defaultdict(lambda: {t: {"y_true": [], "y_pred": []} for t in TARGETS})
|
| 75 |
+
|
| 76 |
+
for idx in split["test"]:
|
| 77 |
+
e = entries[idx]
|
| 78 |
+
fams = e.get("families", ["unknown"])
|
| 79 |
+
primary_fam = fams[0] if fams else "unknown"
|
| 80 |
+
for target in TARGETS:
|
| 81 |
+
true_val = e.get(target)
|
| 82 |
+
pred_val = predictions.get(str(idx), {}).get(target)
|
| 83 |
+
if true_val is not None and pred_val is not None:
|
| 84 |
+
families[primary_fam][target]["y_true"].append(true_val)
|
| 85 |
+
families[primary_fam][target]["y_pred"].append(pred_val)
|
| 86 |
+
|
| 87 |
+
for fam, targets_dict in families.items():
|
| 88 |
+
results[fam] = {}
|
| 89 |
+
for target in TARGETS:
|
| 90 |
+
label = TARGET_LABELS[target]
|
| 91 |
+
yt = np.array(targets_dict[target]["y_true"])
|
| 92 |
+
yp = np.array(targets_dict[target]["y_pred"])
|
| 93 |
+
if len(yt) < 5:
|
| 94 |
+
results[fam][label] = {"n": len(yt), "error": "insufficient data"}
|
| 95 |
+
else:
|
| 96 |
+
m = compute_metrics(yt, yp)
|
| 97 |
+
m["n"] = len(yt)
|
| 98 |
+
results[fam][label] = m
|
| 99 |
+
|
| 100 |
+
return results
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def per_source_metrics(entries, split, predictions):
|
| 104 |
+
"""Metrics broken down by source."""
|
| 105 |
+
results = {}
|
| 106 |
+
sources = defaultdict(lambda: {t: {"y_true": [], "y_pred": []} for t in TARGETS})
|
| 107 |
+
|
| 108 |
+
for idx in split["test"]:
|
| 109 |
+
e = entries[idx]
|
| 110 |
+
src = e.get("source", "unknown")
|
| 111 |
+
for target in TARGETS:
|
| 112 |
+
tv = e.get(target)
|
| 113 |
+
pv = predictions.get(str(idx), {}).get(target)
|
| 114 |
+
if tv is not None and pv is not None:
|
| 115 |
+
sources[src][target]["y_true"].append(tv)
|
| 116 |
+
sources[src][target]["y_pred"].append(pv)
|
| 117 |
+
|
| 118 |
+
for src, targets_dict in sources.items():
|
| 119 |
+
results[src] = {}
|
| 120 |
+
for target in TARGETS:
|
| 121 |
+
label = TARGET_LABELS[target]
|
| 122 |
+
yt = np.array(targets_dict[target]["y_true"])
|
| 123 |
+
yp = np.array(targets_dict[target]["y_pred"])
|
| 124 |
+
if len(yt) < 5:
|
| 125 |
+
results[src][label] = {"n": len(yt), "error": "insufficient data"}
|
| 126 |
+
else:
|
| 127 |
+
m = compute_metrics(yt, yp)
|
| 128 |
+
m["n"] = len(yt)
|
| 129 |
+
results[src][label] = m
|
| 130 |
+
|
| 131 |
+
return results
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def generate_baseline(entries, split, strategy="mean"):
|
| 135 |
+
"""Generate baseline predictions (mean or median).
|
| 136 |
+
|
| 137 |
+
Useful for measuring how much better models perform than trivial baselines.
|
| 138 |
+
"""
|
| 139 |
+
predictions = {}
|
| 140 |
+
targets_values = {t: [] for t in TARGETS}
|
| 141 |
+
|
| 142 |
+
for idx in split["train"]:
|
| 143 |
+
e = entries[idx]
|
| 144 |
+
for t in TARGETS:
|
| 145 |
+
v = e.get(t)
|
| 146 |
+
if v is not None:
|
| 147 |
+
targets_values[t].append(v)
|
| 148 |
+
|
| 149 |
+
baseline = {}
|
| 150 |
+
for t in TARGETS:
|
| 151 |
+
arr = np.array(targets_values[t])
|
| 152 |
+
if strategy == "mean":
|
| 153 |
+
baseline[t] = float(np.mean(arr))
|
| 154 |
+
elif strategy == "median":
|
| 155 |
+
baseline[t] = float(np.median(arr))
|
| 156 |
+
|
| 157 |
+
for idx in split["test"]:
|
| 158 |
+
predictions[str(idx)] = dict(baseline)
|
| 159 |
+
|
| 160 |
+
return predictions
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main():
|
| 164 |
+
parser = argparse.ArgumentParser()
|
| 165 |
+
parser.add_argument("--splits", type=str, nargs="+",
|
| 166 |
+
default=["random_80_10_10"],
|
| 167 |
+
help="Split names to evaluate on")
|
| 168 |
+
parser.add_argument("--predictions", type=str, default=None,
|
| 169 |
+
help="JSON file with predictions {idx: {target: val}}")
|
| 170 |
+
parser.add_argument("--baseline", type=str, default=None,
|
| 171 |
+
choices=["mean", "median"],
|
| 172 |
+
help="Generate baseline predictions instead of loading")
|
| 173 |
+
parser.add_argument("--output", type=str, default=None,
|
| 174 |
+
help="Output path for results")
|
| 175 |
+
parser.add_argument("--model-name", type=str, default="baseline",
|
| 176 |
+
help="Model name for results")
|
| 177 |
+
args = parser.parse_args()
|
| 178 |
+
|
| 179 |
+
print("=" * 60, flush=True)
|
| 180 |
+
print(" V3.0 BENCHMARK EVALUATION", flush=True)
|
| 181 |
+
print("=" * 60, flush=True)
|
| 182 |
+
|
| 183 |
+
entries = load_dataset()
|
| 184 |
+
print(f" Dataset: {len(entries):,} entries", flush=True)
|
| 185 |
+
|
| 186 |
+
all_results = {}
|
| 187 |
+
|
| 188 |
+
for split_name in args.splits:
|
| 189 |
+
print(f"\n Split: {split_name}", flush=True)
|
| 190 |
+
split = load_split(split_name)
|
| 191 |
+
print(f" Train: {len(split['train']):,} Val: {len(split['val']):,} "
|
| 192 |
+
f"Test: {len(split['test']):,}", flush=True)
|
| 193 |
+
|
| 194 |
+
# Load or generate predictions
|
| 195 |
+
if args.baseline:
|
| 196 |
+
print(f" Baseline: {args.baseline}", flush=True)
|
| 197 |
+
predictions = generate_baseline(entries, split, args.baseline)
|
| 198 |
+
elif args.predictions:
|
| 199 |
+
with open(args.predictions) as f:
|
| 200 |
+
predictions = json.load(f)
|
| 201 |
+
print(f" Predictions: {len(predictions)} entries", flush=True)
|
| 202 |
+
else:
|
| 203 |
+
print(f" No predictions — use --predictions or --baseline", flush=True)
|
| 204 |
+
continue
|
| 205 |
+
|
| 206 |
+
# Overall metrics
|
| 207 |
+
overall = evaluate_predictions(entries, split, predictions)
|
| 208 |
+
print(f"\n Overall:")
|
| 209 |
+
for target, metrics in overall.items():
|
| 210 |
+
if "error" in metrics:
|
| 211 |
+
print(f" {target:5s}: {metrics['error']}")
|
| 212 |
+
else:
|
| 213 |
+
print(f" {target:5s}: MAE={metrics['mae']:.4f} "
|
| 214 |
+
f"RMSE={metrics['rmse']:.4f} R²={metrics['r2']:.4f} "
|
| 215 |
+
f"N={metrics['n']:,}")
|
| 216 |
+
|
| 217 |
+
# Per-family
|
| 218 |
+
pf = per_family_metrics(entries, split, predictions)
|
| 219 |
+
print(f"\n Per-Family (MAE):")
|
| 220 |
+
for fam in sorted(pf.keys()):
|
| 221 |
+
vals = []
|
| 222 |
+
for t in TARGETS:
|
| 223 |
+
lbl = TARGET_LABELS[t]
|
| 224 |
+
m = pf[fam].get(lbl, {})
|
| 225 |
+
if "error" not in m:
|
| 226 |
+
vals.append(f"{m['mae']:.4f}")
|
| 227 |
+
else:
|
| 228 |
+
vals.append("N/A")
|
| 229 |
+
print(f" {fam:25s}: FE={vals[0]:>8s} EaH={vals[1]:>8s} BG={vals[2]:>8s}")
|
| 230 |
+
|
| 231 |
+
# Per-source
|
| 232 |
+
ps = per_source_metrics(entries, split, predictions)
|
| 233 |
+
print(f"\n Per-Source (MAE):")
|
| 234 |
+
for src in sorted(ps.keys()):
|
| 235 |
+
vals = []
|
| 236 |
+
for t in TARGETS:
|
| 237 |
+
lbl = TARGET_LABELS[t]
|
| 238 |
+
m = ps[src].get(lbl, {})
|
| 239 |
+
if "error" not in m:
|
| 240 |
+
vals.append(f"{m['mae']:.4f}")
|
| 241 |
+
else:
|
| 242 |
+
vals.append("N/A")
|
| 243 |
+
print(f" {src:10s}: FE={vals[0]:>8s} EaH={vals[1]:>8s} BG={vals[2]:>8s}")
|
| 244 |
+
|
| 245 |
+
all_results[split_name] = {
|
| 246 |
+
"model": args.model_name,
|
| 247 |
+
"split": split_name,
|
| 248 |
+
"overall": overall,
|
| 249 |
+
"per_family": pf,
|
| 250 |
+
"per_source": ps,
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
# Save
|
| 254 |
+
if args.output:
|
| 255 |
+
with open(args.output, "w") as f:
|
| 256 |
+
json.dump(all_results, f, indent=2)
|
| 257 |
+
print(f"\n Results saved: {args.output}", flush=True)
|
| 258 |
+
else:
|
| 259 |
+
# Save with default name
|
| 260 |
+
default_name = f"results_{args.model_name}_{time.strftime('%Y%m%d_%H%M%S')}.json"
|
| 261 |
+
out_path = RESULTS_DIR / default_name
|
| 262 |
+
with open(out_path, "w") as f:
|
| 263 |
+
json.dump(all_results, f, indent=2)
|
| 264 |
+
print(f"\n Results saved: {out_path}", flush=True)
|
| 265 |
+
|
| 266 |
+
print(f"\n{'=' * 60}", flush=True)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
if __name__ == "__main__":
|
| 270 |
+
main()
|