Files
rpotter6298 35cbd9ac3c 2026001
2026-07-01 17:35:58 +02:00

60 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""figure_s3.py — Example CT images from estimated patient clusters.
Usage: python scripts/visualizations/figure_s3.py [--tag TAG]"""
import os, sys, csv, argparse
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MANIFEST = os.path.join(ROOT, "results", "simple_patient_manifest.csv")
DATASET = os.path.join(os.path.dirname(ROOT), "The IQ-OTHNCCD lung cancer dataset")
PLOTS_DIR = os.path.join(ROOT, "plots")
N_EXAMPLES = 5
CLASS_MAP = {"Benign": ("Bengin cases", "B"), "Malignant": ("Malignant cases", "M"), "Normal": ("Normal cases", "N")}
def f2n_back(fname):
prefix = fname[0]; num = int(fname.split("_")[1])
cls = {"B": ("Bengin cases", "Bengin"), "M": ("Malignant cases", "Malignant"), "N": ("Normal cases", "Normal")}[prefix]
return cls[0], f"{cls[1]} case ({num}).jpg"
ap = argparse.ArgumentParser()
ap.add_argument("--tag", default="", help="Append tag to filename")
args = ap.parse_args()
tag = f"_{args.tag}" if args.tag else ""
patients = {}
with open(MANIFEST, newline="") as f:
reader = csv.DictReader(f)
img_col = "confirmed_images" if "confirmed_images" in reader.fieldnames else "images"
for row in reader:
imgs = row[img_col].split(";")
if imgs: patients[row["patient_id"]] = imgs
fig, axes = plt.subplots(3, N_EXAMPLES, figsize=(12, 8))
for row, (cls_label, (cls_dir, _)) in enumerate(CLASS_MAP.items()):
cls_patients = [(p, imgs) for p, imgs in patients.items() if p.lower().startswith(cls_label.lower()) and len(imgs) >= N_EXAMPLES]
if not cls_patients: continue
pid, imgs = cls_patients[0]
for col in range(N_EXAMPLES):
ax = axes[row, col]
try:
cls_dir_name, orig_fname = f2n_back(imgs[col])
img = Image.open(os.path.join(DATASET, cls_dir_name, orig_fname)).convert("L")
ax.imshow(img, cmap="gray")
except Exception as e:
ax.text(0.5, 0.5, f"error: {e}", ha="center", va="center", fontsize=7)
ax.set_xticks([]); ax.set_yticks([])
if col == 0: ax.set_ylabel(f"{cls_label}\nPatient {pid}", fontsize=9, rotation=0, labelpad=40, va="center")
fig.suptitle("Figure S3 — Example CT images from estimated patient clusters", fontsize=12, y=1.01)
plt.tight_layout()
out = os.path.join(PLOTS_DIR, "figure_s3", f"figure_s3{tag}.png")
os.makedirs(os.path.dirname(out), exist_ok=True)
plt.savefig(out, dpi=150)
plt.close()
print(f"Saved → {out}")