Spaces:
Running
Running
File size: 26,013 Bytes
d1ffd83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 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 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 | import os
import re
import json
import math
import glob
import pandas as pd
output_base = "/media/laura/8402326D023263F8/calperumResearch/site1_1_DD0001/outputs_ecosystems/medium"
report_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "analyse_perclass_exports")
os.makedirs(report_dir, exist_ok=True)
sensors = ["FX10", "FX17", "FX10_FX17", "MICA"]
variants = ["", "_aug", "_aug_spectral", "_aug_spectral_weights", "_aug_spec_transformer", "_aug_spec_transformer_weights"]
scales = ["", "_s224", "_s304"]
CLASS_NAMES = {0: "BE", 1: "NPV", 2: "PV"}
def average_metric_dicts(metric_dicts):
if not metric_dicts:
return {}
keys = sorted({key for metrics in metric_dicts for key in metrics.keys()})
averaged = {}
for key in keys:
values = [metrics[key] for metrics in metric_dicts if key in metrics]
if values:
averaged[key] = sum(values) / len(values)
return averaged
def get_best_block(dir_path):
"""Returns the block number with the lowest validation loss."""
fpath = os.path.join(dir_path, "best_model_paths_and_validation_losses.txt")
if not os.path.exists(fpath):
return None
best_block, best_loss = None, float("inf")
with open(fpath) as f:
for line in f:
m = re.search(r"Block (\d+).*validation loss: ([0-9.]+)", line)
if m:
block, loss = int(m.group(1)), float(m.group(2))
if loss < best_loss:
best_loss, best_block = loss, block
return best_block
def parse_best_metrics(dir_path, block):
"""Parses per-class IoU and F1 from the best_model_metrics_block_{N}.txt."""
fpath = os.path.join(dir_path, f"best_model_metrics_block_{block}.txt")
metrics = {}
if not os.path.exists(fpath):
return metrics
with open(fpath) as f:
for line in f:
if line.startswith("Accuracy:"):
metrics["Accuracy"] = float(line.split(":")[1].strip())
elif line.startswith("MIoU:"):
metrics["MIoU"] = float(line.split(":")[1].strip())
elif line.startswith("IoU:"):
vals = [float(v.strip()) for v in line.split(":")[1].split(",")]
for i, v in enumerate(vals):
metrics[f"IoU_{CLASS_NAMES.get(i, i)}"] = v
elif line.startswith("F1 Score:"):
vals = [float(v.strip()) for v in line.split(":")[1].split(",")]
for i, v in enumerate(vals):
metrics[f"F1_{CLASS_NAMES.get(i, i)}"] = v
return metrics
def parse_best_validation_metrics(dir_path, block):
"""Parses per-class IoU and F1 from block_{N}_best_val_metrics.json."""
fpath = os.path.join(dir_path, f"block_{block}_best_val_metrics.json")
metrics = {}
if not os.path.exists(fpath):
return metrics
with open(fpath) as f:
raw = json.load(f)
if "accuracy" in raw:
metrics["Val_Accuracy"] = float(raw["accuracy"])
if "miou" in raw:
metrics["Val_MIoU"] = float(raw["miou"])
iou_vals = raw.get("iou", [])
for i, value in enumerate(iou_vals):
metrics[f"Val_IoU_{CLASS_NAMES.get(i, i)}"] = float(value)
f1_vals = raw.get("f1", [])
for i, value in enumerate(f1_vals):
metrics[f"Val_F1_{CLASS_NAMES.get(i, i)}"] = float(value)
return metrics
def find_available_blocks(dir_path):
blocks = set()
if not os.path.isdir(dir_path):
return []
for name in os.listdir(dir_path):
match = re.match(r"best_model_metrics_block_(\d+)\.txt$", name)
if match:
blocks.add(int(match.group(1)))
continue
match = re.match(r"block_(\d+)_best_val_metrics\.json$", name)
if match:
blocks.add(int(match.group(1)))
return sorted(blocks)
def parse_average_test_metrics(dir_path):
all_metrics = []
for block in find_available_blocks(dir_path):
metrics = parse_best_metrics(dir_path, block)
if metrics:
all_metrics.append(metrics)
averaged = average_metric_dicts(all_metrics)
return {f"Avg_{key}": value for key, value in averaged.items()}
def parse_average_validation_metrics(dir_path):
all_metrics = []
for block in find_available_blocks(dir_path):
metrics = parse_best_validation_metrics(dir_path, block)
if metrics:
all_metrics.append(metrics)
averaged = average_metric_dicts(all_metrics)
return {f"Avg_{key}": value for key, value in averaged.items()}
def parse_senescence_summary(dir_path):
csv_path = os.path.join(dir_path, "senescence_analysis_all_blocks_summary.csv")
if not os.path.exists(csv_path):
return {}
try:
df = pd.read_csv(csv_path)
except Exception:
return {}
if df.empty:
return {}
metrics = {}
if "transition_fraction" in df.columns:
metrics["Sen_Transition_Fraction_Mean"] = float(df["transition_fraction"].mean())
for trait in ["NDVI", "NDRE", "PSRI", "PWI_900_970", "NDWI_860_1240", "MSI_1600_817", "ANMB1450"]:
npv_minus_pv = f"{trait}_NPV_minus_PV"
npv_minus_be = f"{trait}_NPV_minus_BE"
if npv_minus_pv in df.columns:
metrics[f"Sen_{npv_minus_pv}_Mean"] = float(df[npv_minus_pv].mean())
if npv_minus_be in df.columns:
metrics[f"Sen_{npv_minus_be}_Mean"] = float(df[npv_minus_be].mean())
return metrics
def parse_model_driven_senescence_summary(dir_path):
block_metrics = []
block_dirs = sorted(glob.glob(os.path.join(dir_path, "senescence_analysis_block_*")))
for block_dir in block_dirs:
block_summary = {}
sensitivity_path = os.path.join(block_dir, "senescence_sensitivity_per_band.csv")
if os.path.exists(sensitivity_path):
sensitivity_df = pd.read_csv(sensitivity_path)
if "sensitivity" in sensitivity_df.columns:
values = pd.to_numeric(sensitivity_df["sensitivity"], errors="coerce").dropna()
if not values.empty:
top_n = max(5, int(math.ceil(len(values) * 0.05)))
abs_values = values.abs()
block_summary["ModelSen_AbsSensitivityMean"] = float(abs_values.mean())
block_summary["ModelSen_AbsSensitivityTopMean"] = float(abs_values.nlargest(top_n).mean())
block_summary["ModelSen_NPVFavorFraction"] = float((values > 0).mean())
importance_path = os.path.join(block_dir, "senescence_band_importance_per_band.csv")
if os.path.exists(importance_path):
importance_df = pd.read_csv(importance_path)
required_cols = {"pv_masked_logit_sensitivity", "npv_masked_logit_sensitivity"}
if required_cols.issubset(importance_df.columns):
pv_vals = pd.to_numeric(importance_df["pv_masked_logit_sensitivity"], errors="coerce")
npv_vals = pd.to_numeric(importance_df["npv_masked_logit_sensitivity"], errors="coerce")
response = ((pv_vals.abs() + npv_vals.abs()) / 2.0).dropna()
if not response.empty:
top_n = max(5, int(math.ceil(len(response) * 0.05)))
block_summary["ModelSen_ClassResponseMean"] = float(response.mean())
block_summary["ModelSen_ClassResponseTopMean"] = float(response.nlargest(top_n).mean())
gate_path = os.path.join(block_dir, "senescence_band_importance_grouped.csv")
if os.path.exists(gate_path):
gate_df = pd.read_csv(gate_path)
if "global_gate_mean" in gate_df.columns:
gate_vals = pd.to_numeric(gate_df["global_gate_mean"], errors="coerce").dropna()
if not gate_vals.empty:
top_n = max(3, int(math.ceil(len(gate_vals) * 0.10)))
gate_mean = float(gate_vals.mean())
gate_top_mean = float(gate_vals.nlargest(top_n).mean())
block_summary["ModelSen_GateMean"] = gate_mean
block_summary["ModelSen_GateTopMean"] = gate_top_mean
block_summary["ModelSen_GateSelectivity"] = float(gate_top_mean / gate_mean) if gate_mean else 0.0
if block_summary:
block_metrics.append(block_summary)
averaged = average_metric_dicts(block_metrics)
if averaged:
averaged["ModelSen_BlockCount"] = len(block_metrics)
return averaged
def normalize_series(series, inverse=False):
numeric = pd.to_numeric(series, errors="coerce")
if numeric.isna().all():
return pd.Series(0.0, index=series.index)
minimum = numeric.min()
maximum = numeric.max()
if pd.isna(minimum) or pd.isna(maximum) or maximum == minimum:
return pd.Series(0.0, index=series.index)
scaled = (numeric - minimum) / (maximum - minimum)
if inverse:
scaled = 1.0 - scaled
return scaled.fillna(0.0)
def build_overall_model_ranking(df):
required = {"Avg_IoU_NPV", "Avg_Val_IoU_NPV", "Avg_MIoU", "Avg_Val_MIoU"}
if not required.issubset(df.columns):
return pd.DataFrame()
ranked = df.copy()
ranked["Score_Avg_IoU_NPV"] = normalize_series(ranked["Avg_IoU_NPV"])
ranked["Score_Avg_Val_IoU_NPV"] = normalize_series(ranked["Avg_Val_IoU_NPV"])
ranked["Score_Avg_MIoU"] = normalize_series(ranked["Avg_MIoU"])
ranked["Score_Avg_Val_MIoU"] = normalize_series(ranked["Avg_Val_MIoU"])
if "Sen_Transition_Fraction_Mean" in ranked.columns:
ranked["Score_Low_Transition"] = normalize_series(ranked["Sen_Transition_Fraction_Mean"], inverse=True)
else:
ranked["Score_Low_Transition"] = 0.0
ranked["Overall_Score"] = (
0.35 * ranked["Score_Avg_IoU_NPV"]
+ 0.35 * ranked["Score_Avg_Val_IoU_NPV"]
+ 0.15 * ranked["Score_Avg_MIoU"]
+ 0.10 * ranked["Score_Avg_Val_MIoU"]
+ 0.05 * ranked["Score_Low_Transition"]
)
ranked = ranked.sort_values(
by=["Overall_Score", "Avg_IoU_NPV", "Avg_Val_IoU_NPV", "Avg_MIoU"],
ascending=False,
).reset_index(drop=True)
ranked.insert(0, "Rank", ranked.index + 1)
return ranked
def build_model_driven_senescence_ranking(df):
required = {
"ModelSen_AbsSensitivityMean",
"ModelSen_AbsSensitivityTopMean",
"ModelSen_ClassResponseTopMean",
"ModelSen_GateSelectivity",
}
if not required.issubset(df.columns):
return pd.DataFrame()
ranked = df.copy()
ranked["Score_ModelSen_AbsSensitivityMean"] = normalize_series(ranked["ModelSen_AbsSensitivityMean"])
ranked["Score_ModelSen_AbsSensitivityTopMean"] = normalize_series(ranked["ModelSen_AbsSensitivityTopMean"])
ranked["Score_ModelSen_ClassResponseTopMean"] = normalize_series(ranked["ModelSen_ClassResponseTopMean"])
ranked["Score_ModelSen_GateSelectivity"] = normalize_series(ranked["ModelSen_GateSelectivity"])
if "Sen_Transition_Fraction_Mean" in ranked.columns:
ranked["Score_ModelSen_LowTransition"] = normalize_series(ranked["Sen_Transition_Fraction_Mean"], inverse=True)
else:
ranked["Score_ModelSen_LowTransition"] = 0.0
ranked["ModelDriven_Senescence_Score"] = (
0.35 * ranked["Score_ModelSen_AbsSensitivityTopMean"]
+ 0.25 * ranked["Score_ModelSen_AbsSensitivityMean"]
+ 0.20 * ranked["Score_ModelSen_ClassResponseTopMean"]
+ 0.15 * ranked["Score_ModelSen_GateSelectivity"]
+ 0.05 * ranked["Score_ModelSen_LowTransition"]
)
ranked = ranked.sort_values(
by=["ModelDriven_Senescence_Score", "ModelSen_AbsSensitivityTopMean", "ModelSen_GateSelectivity"],
ascending=False,
).reset_index(drop=True)
ranked.insert(0, "Rank", ranked.index + 1)
return ranked
def export_table(df, filename):
if df.empty:
return None
output_path = os.path.join(report_dir, filename)
df.to_csv(output_path, index=False)
return output_path
def print_model_driven_table(df):
sci_cols = {
"ModelSen_AbsSensitivityMean",
"ModelSen_AbsSensitivityTopMean",
"ModelSen_ClassResponseMean",
"ModelSen_ClassResponseTopMean",
}
fixed_cols = {
"ModelSen_GateSelectivity",
"Sen_Transition_Fraction_Mean",
"ModelDriven_Senescence_Score",
}
formatters = {}
for col in df.columns:
if col in sci_cols:
formatters[col] = lambda value: "" if pd.isna(value) else f"{value:.6e}"
elif col in fixed_cols:
formatters[col] = lambda value: "" if pd.isna(value) else f"{value:.4f}"
print(df.to_string(index=False, formatters=formatters))
def build_baseline_delta_summary(df):
required_cols = {
"Sensor",
"Variant",
"Scale",
"Avg_IoU_NPV",
"Avg_MIoU",
"Avg_Val_IoU_NPV",
"Avg_Val_MIoU",
}
if not required_cols.issubset(df.columns):
return pd.DataFrame()
summary_rows = []
for sensor in sorted(df["Sensor"].unique()):
sensor_df = df[df["Sensor"] == sensor].copy()
baseline_by_scale = sensor_df[sensor_df["Variant"] == "baseline"].set_index("Scale")
candidate_rows = []
for _, row in sensor_df[sensor_df["Variant"] != "baseline"].iterrows():
scale = row["Scale"]
if scale not in baseline_by_scale.index:
continue
baseline = baseline_by_scale.loc[scale]
candidate_rows.append({
"Sensor": sensor,
"Recommended": row["Variant"],
"Scale": scale,
"Baseline_Avg_IoU_NPV": baseline["Avg_IoU_NPV"],
"Avg_IoU_NPV": row["Avg_IoU_NPV"],
"Delta_Avg_IoU_NPV": row["Avg_IoU_NPV"] - baseline["Avg_IoU_NPV"],
"Baseline_Avg_MIoU": baseline["Avg_MIoU"],
"Avg_MIoU": row["Avg_MIoU"],
"Delta_Avg_MIoU": row["Avg_MIoU"] - baseline["Avg_MIoU"],
"Baseline_Avg_Val_IoU_NPV": baseline["Avg_Val_IoU_NPV"],
"Avg_Val_IoU_NPV": row["Avg_Val_IoU_NPV"],
"Delta_Avg_Val_IoU_NPV": row["Avg_Val_IoU_NPV"] - baseline["Avg_Val_IoU_NPV"],
"Avg_Val_MIoU": row["Avg_Val_MIoU"],
"Delta_Avg_Val_MIoU": row["Avg_Val_MIoU"] - baseline["Avg_Val_MIoU"],
})
if not candidate_rows:
continue
candidate_df = pd.DataFrame(candidate_rows).sort_values(
by=["Delta_Avg_IoU_NPV", "Delta_Avg_Val_IoU_NPV", "Delta_Avg_MIoU"],
ascending=False,
)
summary_rows.append(candidate_df.iloc[0].to_dict())
if not summary_rows:
return pd.DataFrame()
summary_df = pd.DataFrame(summary_rows).sort_values(
by=["Delta_Avg_IoU_NPV", "Delta_Avg_Val_IoU_NPV", "Delta_Avg_MIoU"],
ascending=False,
).reset_index(drop=True)
summary_df.insert(0, "Rank", summary_df.index + 1)
return summary_df
data = []
scale_labels = {
"": "native",
"_s224": "224px",
"_s304": "304px",
}
for sensor in sensors:
for variant in variants:
for scale in scales:
dir_name = f"{sensor}{variant}{scale}"
dir_path = os.path.join(output_base, dir_name)
best_block = get_best_block(dir_path)
if best_block is None:
continue
metrics = parse_best_metrics(dir_path, best_block)
val_metrics = parse_best_validation_metrics(dir_path, best_block)
avg_test_metrics = parse_average_test_metrics(dir_path)
avg_val_metrics = parse_average_validation_metrics(dir_path)
if metrics or val_metrics or avg_test_metrics or avg_val_metrics:
row = {
"Sensor": sensor,
"Variant": variant if variant else "baseline",
"Scale": scale_labels.get(scale, scale),
"Best_Block": best_block,
"Directory": dir_name,
}
row.update(metrics)
row.update(val_metrics)
row.update(avg_test_metrics)
row.update(avg_val_metrics)
row.update(parse_senescence_summary(dir_path))
row.update(parse_model_driven_senescence_summary(dir_path))
data.append(row)
if data:
df = pd.DataFrame(data)
sort_cols = ["Variant", "Sensor", "Scale"]
df = df.sort_values(by=sort_cols)
test_cols = [
"Sensor", "Variant", "Scale", "Best_Block",
"Accuracy", "MIoU",
"IoU_BE", "IoU_NPV", "IoU_PV",
"F1_BE", "F1_NPV", "F1_PV",
]
test_cols = [c for c in test_cols if c in df.columns]
val_cols = [
"Sensor", "Variant", "Scale", "Best_Block",
"Val_Accuracy", "Val_MIoU",
"Val_IoU_BE", "Val_IoU_NPV", "Val_IoU_PV",
"Val_F1_BE", "Val_F1_NPV", "Val_F1_PV",
]
val_cols = [c for c in val_cols if c in df.columns]
avg_test_cols = [
"Sensor", "Variant", "Scale",
"Avg_Accuracy", "Avg_MIoU",
"Avg_IoU_BE", "Avg_IoU_NPV", "Avg_IoU_PV",
"Avg_F1_BE", "Avg_F1_NPV", "Avg_F1_PV",
]
avg_test_cols = [c for c in avg_test_cols if c in df.columns]
avg_val_cols = [
"Sensor", "Variant", "Scale",
"Avg_Val_Accuracy", "Avg_Val_MIoU",
"Avg_Val_IoU_BE", "Avg_Val_IoU_NPV", "Avg_Val_IoU_PV",
"Avg_Val_F1_BE", "Avg_Val_F1_NPV", "Avg_Val_F1_PV",
]
avg_val_cols = [c for c in avg_val_cols if c in df.columns]
print("\n=== Best Block Test Metrics (BE / NPV / PV) ===")
pd.set_option("display.float_format", "{:.4f}".format)
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 200)
if test_cols:
print(df[test_cols].to_string(index=False))
else:
print("No best-model test metrics found.")
print("\n=== Best Block Validation Metrics (BE / NPV / PV) ===")
if val_cols:
print(df[val_cols].to_string(index=False))
else:
print("No best-model validation metrics found.")
print("\n=== Average Test Metrics Across Blocks (BE / NPV / PV) ===")
if avg_test_cols:
print(df[avg_test_cols].to_string(index=False))
else:
print("No average test metrics found.")
print("\n=== Average Validation Metrics Across Blocks (BE / NPV / PV) ===")
if avg_val_cols:
print(df[avg_val_cols].to_string(index=False))
else:
print("No average validation metrics found.")
print("\n=== Ranked by Test IoU_NPV (hardest class) ===")
if "IoU_NPV" in df.columns:
print(df.sort_values("IoU_NPV", ascending=False)[
["Sensor", "Variant", "Scale", "IoU_BE", "IoU_NPV", "IoU_PV", "MIoU"]
].to_string(index=False))
else:
print("No best-model test IoU_NPV found.")
print("\n=== Ranked by Validation IoU_NPV (hardest class) ===")
if "Val_IoU_NPV" in df.columns:
print(df.sort_values("Val_IoU_NPV", ascending=False)[
["Sensor", "Variant", "Scale", "Val_IoU_BE", "Val_IoU_NPV", "Val_IoU_PV", "Val_MIoU"]
].to_string(index=False))
else:
print("No best-model validation IoU_NPV found.")
print("\n=== Ranked by Average Test IoU_NPV Across Blocks ===")
if "Avg_IoU_NPV" in df.columns:
print(df.sort_values("Avg_IoU_NPV", ascending=False)[
["Sensor", "Variant", "Scale", "Avg_IoU_BE", "Avg_IoU_NPV", "Avg_IoU_PV", "Avg_MIoU"]
].to_string(index=False))
else:
print("No average test IoU_NPV found.")
print("\n=== Ranked by Average Validation IoU_NPV Across Blocks ===")
if "Avg_Val_IoU_NPV" in df.columns:
print(df.sort_values("Avg_Val_IoU_NPV", ascending=False)[
["Sensor", "Variant", "Scale", "Avg_Val_IoU_BE", "Avg_Val_IoU_NPV", "Avg_Val_IoU_PV", "Avg_Val_MIoU"]
].to_string(index=False))
else:
print("No average validation IoU_NPV found.")
print("\n=== Recommended Variant Per Sensor (Delta vs Baseline at Same Scale) ===")
summary_df = build_baseline_delta_summary(df)
if not summary_df.empty:
print(summary_df[[
"Rank",
"Sensor",
"Recommended",
"Scale",
"Baseline_Avg_IoU_NPV",
"Avg_IoU_NPV",
"Delta_Avg_IoU_NPV",
"Baseline_Avg_MIoU",
"Avg_MIoU",
"Delta_Avg_MIoU",
"Baseline_Avg_Val_IoU_NPV",
"Avg_Val_IoU_NPV",
"Delta_Avg_Val_IoU_NPV",
]].to_string(index=False))
else:
print("No baseline delta summary available.")
print("\n=== Overall Model Ranking (metrics-first, lower transition as tie-breaker) ===")
overall_df = build_overall_model_ranking(df)
if not overall_df.empty:
ranking_cols = [
"Rank",
"Sensor",
"Variant",
"Scale",
"Directory",
"Avg_IoU_NPV",
"Avg_Val_IoU_NPV",
"Avg_MIoU",
"Avg_Val_MIoU",
"Sen_Transition_Fraction_Mean",
"Overall_Score",
]
ranking_cols = [col for col in ranking_cols if col in overall_df.columns]
print(overall_df[ranking_cols].to_string(index=False))
export_path = export_table(overall_df[ranking_cols], "overall_model_ranking.csv")
if export_path:
print(f"Exported overall model ranking CSV: {export_path}")
else:
print("No overall ranking available.")
print("\n=== FX10_FX17 Ranking (metrics-first, lower transition as tie-breaker) ===")
fx10_fx17_df = build_overall_model_ranking(df[df["Sensor"] == "FX10_FX17"].copy())
if not fx10_fx17_df.empty:
ranking_cols = [
"Rank",
"Variant",
"Scale",
"Directory",
"Avg_IoU_NPV",
"Avg_Val_IoU_NPV",
"Avg_MIoU",
"Avg_Val_MIoU",
"Sen_Transition_Fraction_Mean",
"Overall_Score",
"Sen_NDRE_NPV_minus_PV_Mean",
"Sen_PSRI_NPV_minus_PV_Mean",
"Sen_NDWI_860_1240_NPV_minus_PV_Mean",
"Sen_ANMB1450_NPV_minus_PV_Mean",
]
ranking_cols = [col for col in ranking_cols if col in fx10_fx17_df.columns]
print(fx10_fx17_df[ranking_cols].to_string(index=False))
export_path = export_table(fx10_fx17_df[ranking_cols], "fx10_fx17_ranking.csv")
if export_path:
print(f"Exported FX10_FX17 ranking CSV: {export_path}")
else:
print("No FX10_FX17 ranking available.")
print("\n=== FX10_FX17 Extensions-Only Ranking (metrics-first, excludes baseline) ===")
fx10_fx17_extensions_df = build_overall_model_ranking(
df[(df["Sensor"] == "FX10_FX17") & (df["Variant"] != "baseline")].copy()
)
if not fx10_fx17_extensions_df.empty:
ranking_cols = [
"Rank",
"Variant",
"Scale",
"Directory",
"Avg_IoU_NPV",
"Avg_Val_IoU_NPV",
"Avg_MIoU",
"Avg_Val_MIoU",
"Sen_Transition_Fraction_Mean",
"Overall_Score",
]
ranking_cols = [col for col in ranking_cols if col in fx10_fx17_extensions_df.columns]
print(fx10_fx17_extensions_df[ranking_cols].to_string(index=False))
export_path = export_table(fx10_fx17_extensions_df[ranking_cols], "fx10_fx17_extensions_only_ranking.csv")
if export_path:
print(f"Exported FX10_FX17 extensions-only ranking CSV: {export_path}")
else:
print("No FX10_FX17 extensions-only ranking available.")
print("\n=== Model-Driven Senescence Ranking (gradient/gate-based) ===")
model_driven_df = build_model_driven_senescence_ranking(df)
if not model_driven_df.empty:
ranking_cols = [
"Rank",
"Sensor",
"Variant",
"Scale",
"Directory",
"ModelSen_AbsSensitivityMean",
"ModelSen_AbsSensitivityTopMean",
"ModelSen_ClassResponseTopMean",
"ModelSen_GateSelectivity",
"Sen_Transition_Fraction_Mean",
"ModelDriven_Senescence_Score",
]
ranking_cols = [col for col in ranking_cols if col in model_driven_df.columns]
print_model_driven_table(model_driven_df[ranking_cols])
export_path = export_table(model_driven_df[ranking_cols], "model_driven_senescence_ranking.csv")
if export_path:
print(f"Exported model-driven senescence ranking CSV: {export_path}")
else:
print("No model-driven senescence ranking available.")
print("\n=== FX10_FX17 Extensions-Only Model-Driven Senescence Ranking ===")
fx10_fx17_model_driven_df = build_model_driven_senescence_ranking(
df[(df["Sensor"] == "FX10_FX17") & (df["Variant"] != "baseline")].copy()
)
if not fx10_fx17_model_driven_df.empty:
ranking_cols = [
"Rank",
"Variant",
"Scale",
"Directory",
"ModelSen_AbsSensitivityMean",
"ModelSen_AbsSensitivityTopMean",
"ModelSen_ClassResponseTopMean",
"ModelSen_GateSelectivity",
"Sen_Transition_Fraction_Mean",
"ModelDriven_Senescence_Score",
]
ranking_cols = [col for col in ranking_cols if col in fx10_fx17_model_driven_df.columns]
print_model_driven_table(fx10_fx17_model_driven_df[ranking_cols])
export_path = export_table(
fx10_fx17_model_driven_df[ranking_cols],
"fx10_fx17_extensions_only_model_driven_senescence_ranking.csv",
)
if export_path:
print(f"Exported FX10_FX17 extensions-only model-driven ranking CSV: {export_path}")
else:
print("No FX10_FX17 extensions-only model-driven ranking available.")
else:
print("No data found.")
|