""" generate_paper_figures.py — Conference Paper Figure Generator for MFAF-Net Generates publication-ready figures in `static/results/paper_figures/` from: 1. Procedure-aware attention weights (from trained checkpoint if available, otherwise Module 3 clinical priors). 2. Live dataset distribution from `data/` (complete_plasticSurgery_dataset). 3. Training convergence & validation image quality metrics from `models/training_history.json` (generated by `train_mfaf_net.py`). Usage: python generate_paper_figures.py """ import os import json import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from mfaf_net.dataset_loader import DatasetLoader from mfaf_net.module2_patient_analysis import PROCEDURES from mfaf_net.module3_feature_fusion import PROCEDURE_ATTENTION from mfaf_net.model_arch import REGION_NAMES, DEFAULT_MODELS_DIR, load_trained_model OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'results', 'paper_figures') def plot_attention_matrix(out_dir: str): """Plot the 6x6 Procedure-to-Facial-Region Attention Heatmap.""" model, _ = load_trained_model() if model is not None: import torch with torch.no_grad(): mat = (torch.relu(model.proc_region_attn) + 0.5).numpy() subtitle = 'Learned Procedure-Aware Attention Weights (MFAF-Net)' else: mat = np.array([ [PROCEDURE_ATTENTION[p].get(r, 1.0) for r in REGION_NAMES] for p in PROCEDURES ], dtype=np.float32) subtitle = 'Procedure-Aware Attention Weights (Module 3 Clinical Priors)' fig, ax = plt.subplots(figsize=(8.2, 5.4)) im = ax.imshow(mat, cmap='YlGnBu', aspect='auto') proc_labels = [p.replace('_', ' ').title() for p in PROCEDURES] reg_labels = [r.title() for r in REGION_NAMES] ax.set_xticks(np.arange(len(reg_labels))) ax.set_yticks(np.arange(len(proc_labels))) ax.set_xticklabels(reg_labels, fontsize=10, fontweight='bold') ax.set_yticklabels(proc_labels, fontsize=10, fontweight='bold') plt.setp(ax.get_xticklabels(), rotation=20, ha='right') for i in range(mat.shape[0]): for j in range(mat.shape[1]): val = mat[i, j] color = 'white' if val > (mat.max() * 0.6) else '#0f172a' ax.text(j, i, f'{val:.2f}', ha='center', va='center', color=color, fontsize=9, fontweight='bold') ax.set_title(subtitle, fontsize=12, fontweight='bold', pad=12) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) cbar.set_label('Attention Weight', fontsize=9) plt.tight_layout() path = os.path.join(out_dir, 'paper_attention_matrix.png') plt.savefig(path, dpi=200, bbox_inches='tight') plt.close(fig) print(f"[saved] {path}") def plot_dataset_distribution(out_dir: str): """Plot image/pair distribution across categories found in data/.""" stats = DatasetLoader('data').get_stats() by_proc = stats.get('by_procedure', {}) if not by_proc: print("[skip] No dataset images found in data/ for distribution chart.") return labels = [k.replace('_', ' ').title() for k in by_proc.keys()] counts = [v.get('count', 0) if isinstance(v, dict) else int(v) for v in by_proc.values()] fig, ax = plt.subplots(figsize=(8.0, 4.6)) colors = ['#2563eb', '#06b6d4', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899'] bars = ax.bar(labels, counts, color=[colors[i % len(colors)] for i in range(len(labels))], edgecolor='#0f172a') ax.set_title(f"Dataset Sample Distribution (Total Images: {stats.get('total_images', 0)})", fontsize=12, fontweight='bold') ax.set_ylabel('Number of Images') ax.grid(axis='y', alpha=0.25) plt.setp(ax.get_xticklabels(), rotation=18, ha='right') for bar, c in zip(bars, counts): ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + max(counts) * 0.015, str(c), ha='center', va='bottom', fontsize=9, fontweight='bold') plt.tight_layout() path = os.path.join(out_dir, 'paper_dataset_distribution.png') plt.savefig(path, dpi=200, bbox_inches='tight') plt.close(fig) print(f"[saved] {path}") def plot_training_summary(out_dir: str): """Plot validation metrics summary from models/training_history.json if present.""" hist_path = os.path.join(DEFAULT_MODELS_DIR, 'training_history.json') if not os.path.isfile(hist_path): print("[skip] models/training_history.json not found — run `python train_mfaf_net.py` first.") return with open(hist_path, 'r', encoding='utf-8') as f: summary = json.load(f) sim_eval = summary.get('simulation_evaluation', {}) if not sim_eval: print("[skip] No simulation_evaluation block in training_history.json.") return fig, ax = plt.subplots(figsize=(7.5, 4.5)) metric_labels = ['SSIM (x100)', 'PSNR (dB)', 'MAE', 'Changed Pixels (%)'] metric_vals = [ sim_eval.get('mean_ssim', 0.0) * 100.0, sim_eval.get('mean_psnr', 0.0), sim_eval.get('mean_mae', 0.0), sim_eval.get('mean_changed_pixel_pct', 0.0), ] colors = ['#10b981', '#06b6d4', '#f59e0b', '#f43f5e'] bars = ax.bar(metric_labels, metric_vals, color=colors, edgecolor='#0f172a') ax.set_title( f"MFAF-Net Validation Evaluation (n={sim_eval.get('eval_samples', 0)}, " f"Val Acc={summary.get('final_val_acc_pct', 0)}%)", fontsize=11.5, fontweight='bold' ) ax.grid(axis='y', alpha=0.25) for bar, v in zip(bars, metric_vals): ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.5, f'{v:.2f}', ha='center', va='bottom', fontsize=9, fontweight='bold') plt.tight_layout() path = os.path.join(out_dir, 'paper_evaluation_summary.png') plt.savefig(path, dpi=200, bbox_inches='tight') plt.close(fig) print(f"[saved] {path}") def main(): os.makedirs(OUT_DIR, exist_ok=True) print("Generating MFAF-Net conference paper figures...") plot_attention_matrix(OUT_DIR) plot_dataset_distribution(OUT_DIR) plot_training_summary(OUT_DIR) print("Done.") if __name__ == '__main__': main()