#!/usr/bin/env python3 """ Paper-ready validation figures: clean + noisy data on the same axes. Open symbols = Case A (ideal conditions) Filled symbols = Case B (degraded, SNR ~8) DNS reference = solid black line with 95% CI band Produces: 1. fig_mean_velocity.png — U+ vs y+ 2. fig_stresses.png — 1x3 subplots (uu+, vv+, -uv+) 3. fig_combined_stresses.png — all stresses on one axis """ import numpy as np import scipy.io as sio from scipy.interpolate import interp1d import matplotlib.pyplot as plt import matplotlib as mpl from pathlib import Path # ── Publication font setup: match LaTeX body text ───────────────────────────── mpl.rcParams.update({ 'font.family': 'serif', 'font.serif': ['CMU Serif', 'Computer Modern Roman', 'DejaVu Serif'], 'mathtext.fontset': 'cm', 'axes.unicode_minus': False, 'text.usetex': False, 'axes.labelsize': 11, 'axes.titlesize': 11, 'legend.fontsize': 9, 'xtick.labelsize': 10, 'ytick.labelsize': 10, 'lines.linewidth': 1.5, 'figure.dpi': 600, 'savefig.dpi': 600, 'savefig.bbox': 'tight', 'savefig.pad_inches': 0.05, }) # ── Okabe-Ito colourblind-safe palette ──────────────────────────────────────── COLORS = { 'Instantaneous': '#0072B2', 'Ensemble': '#D55E00', 'Stereo': '#009E73', } MARKERS = { 'Instantaneous': 'o', 'Ensemble': 's', 'Stereo': '^', } DNS_COLOR = 'k' # ============================================================================= # Data loading (reuse from benchmark_comparison) # ============================================================================= def _load_gt(gt_dir): from benchmark_comparison import load_wall_units, load_ground_truth gt_dir = Path(gt_dir) for name in ('wall_units.mat', 'diagnostics.mat', 'direct_stats.mat'): p = gt_dir / name if p.exists(): wu = load_wall_units(p) break for name in ('profiles.mat', 'ensemble_statistics_full.mat', 'direct_stats.mat'): p = gt_dir / name if p.exists(): gt = load_ground_truth(p, wall_units_path=gt_dir / 'direct_stats.mat') break gt_plus = { 'y_plus': gt['y_plus'], 'U_plus': gt['U_plus'], 'uu_plus': gt['uu_plus'], 'vv_plus': gt['vv_plus'], 'uv_plus': gt['uv_plus'], } for key in ('uu_plus_ci_lo', 'uu_plus_ci_hi', 'vv_plus_ci_lo', 'vv_plus_ci_hi', 'uv_plus_ci_lo', 'uv_plus_ci_hi', 'U_plus_ci_lo', 'U_plus_ci_hi'): if key in gt: gt_plus[key] = gt[key] return gt_plus, wu def _load_inst(stats_path, run_idx, wu, y_offset): from benchmark_comparison import ( load_piv_statistics, compute_piv_profiles, convert_to_wall_units) piv = load_piv_statistics(Path(stats_path), run_idx=run_idx) prof = compute_piv_profiles(piv, x_exclude_vectors=4) plus = convert_to_wall_units(prof, wu, y_offset_mm=-prof['y_mm'].min()) plus['y_plus'] = plus['y_plus'] + 1.0 + y_offset return plus def _load_ens(ens_path, coords_path, run_idx, wu, y_offset): from benchmark_comparison import ( load_ensemble_statistics, compute_piv_profiles, convert_to_wall_units) piv = load_ensemble_statistics(Path(ens_path), Path(coords_path), run_idx=run_idx) prof = compute_piv_profiles(piv, x_exclude_vectors=4) plus = convert_to_wall_units(prof, wu, y_offset_mm=-prof['y_mm'].min()) plus['y_plus'] = plus['y_plus'] + 1.0 + y_offset return plus def _load_stereo(stats_path, run_idx, wu, y_offset, trim_top=10): from benchmark_comparison import convert_to_wall_units stats = sio.loadmat(str(stats_path), squeeze_me=True, struct_as_record=False) piv_s = stats['piv_result'][run_idx] coords_s = stats['coordinates'][run_idx] x, y = coords_s.x, coords_s.y valid_cols = np.any(~np.isnan(y), axis=0) col_indices = np.where(valid_cols)[0] mid_col = col_indices[len(col_indices) // 2] y_unique = y[:, mid_col] valid_rows = ~np.isnan(y_unique) y_unique = y_unique[valid_rows] if trim_top > 0: if y_unique[0] > y_unique[-1]: y_unique = y_unique[trim_top:] vi = np.where(valid_rows)[0][trim_top:] else: y_unique = y_unique[:-trim_top] vi = np.where(valid_rows)[0][:-trim_top] tm = np.zeros(valid_rows.shape, dtype=bool) tm[vi] = True valid_rows = tm xs = col_indices[0] + 4 xe = col_indices[-1] - 3 x_mask = np.zeros(x.shape[1], dtype=bool) x_mask[xs:xe] = True prof = { 'y_mm': y_unique, 'U': np.nanmean(piv_s.ux[valid_rows][:, x_mask] * 1000, axis=1), 'V': np.nanmean(piv_s.uy[valid_rows][:, x_mask] * 1000, axis=1), 'uu': np.nanmean(piv_s.uu[valid_rows][:, x_mask] * 1e6, axis=1), 'vv': np.nanmean(piv_s.vv[valid_rows][:, x_mask] * 1e6, axis=1), 'uv': np.nanmean(piv_s.uv[valid_rows][:, x_mask] * 1e6, axis=1), } plus = convert_to_wall_units(prof, wu, y_offset_mm=-prof['y_mm'].min()) plus['y_plus'] = plus['y_plus'] + 1.0 + y_offset return plus def _trim(plus, n=1): """Remove n near-wall points.""" if n <= 0: return plus yp = plus['y_plus'] if yp[0] > yp[-1]: sl = slice(None, -n) else: sl = slice(n, None) return {k: (v[sl] if isinstance(v, np.ndarray) and len(v) > n else v) for k, v in plus.items()} # ============================================================================= # Plotting helpers # ============================================================================= def _ci_band(ax, yp, lo, hi, sign=1): if sign == -1: lo, hi = hi, lo ax.fill_between(yp, sign * lo, sign * hi, color=DNS_COLOR, alpha=0.10, linewidth=0) def _plot_method(ax, yp, vals, method, filled=True, label=None, ms=3.5, alpha=0.7): """Plot a single method series — filled or open markers.""" color = COLORS[method] marker = MARKERS[method] if filled: ax.plot(yp, vals, color=color, marker=marker, markersize=ms, alpha=alpha, linestyle='none', label=label, zorder=5) else: ax.plot(yp, vals, marker=marker, markersize=ms, alpha=alpha, linestyle='none', label=label, zorder=4, markerfacecolor='none', markeredgecolor=color, markeredgewidth=0.8) # ============================================================================= # Figure 1: Mean velocity # ============================================================================= def plot_velocity(gt_plus, clean, noisy, wu, output_dir): Re_tau = wu['Re_tau'] fig, ax = plt.subplots(figsize=(7, 5)) # DNS + CI if 'U_plus_ci_lo' in gt_plus: _ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], gt_plus['U_plus_ci_hi']) ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], color=DNS_COLOR, linewidth=2, label='DNS', zorder=10) # Clean (open) for method, plus in clean.items(): _plot_method(ax, plus['y_plus'], plus['U_plus'], method, filled=False, label=f'{method} — Case A') # Noisy (filled) for method, plus in noisy.items(): _plot_method(ax, plus['y_plus'], plus['U_plus'], method, filled=True, label=f'{method} — Case B') ax.set_xlabel(r'$y^+$') ax.set_ylabel(r'$U^+$') ax.set_xlim(1, Re_tau) ax.set_ylim(0, 25) ax.grid(True, alpha=0.25, linewidth=0.5) ax.legend(loc='lower right', framealpha=0.9) fig.tight_layout() out = Path(output_dir) out.mkdir(parents=True, exist_ok=True) fig.savefig(out / 'fig_mean_velocity.png') fig.savefig(out / 'fig_mean_velocity.pdf') plt.close(fig) print(f' Saved: {out / "fig_mean_velocity.png"}') # ============================================================================= # Figure 2: Stresses — 1x3 subplots # ============================================================================= def plot_stresses_subplots(gt_plus, clean, noisy, wu, output_dir): Re_tau = wu['Re_tau'] has_ci = 'uu_plus_ci_lo' in gt_plus panels = [ ('uu_plus', r"$\overline{u'u'}^+$", 1), ('vv_plus', r"$\overline{v'v'}^+$", 1), ('uv_plus', r"$-\overline{u'v'}^+$", -1), ] fig, axes = plt.subplots(1, 3, figsize=(7, 2.8)) for ax, (var, ylabel, sign) in zip(axes, panels): # CI band ci_lo_key, ci_hi_key = f'{var}_ci_lo', f'{var}_ci_hi' if has_ci and ci_lo_key in gt_plus: _ci_band(ax, gt_plus['y_plus'], gt_plus[ci_lo_key], gt_plus[ci_hi_key], sign=sign) # DNS ax.plot(gt_plus['y_plus'], sign * gt_plus[var], color=DNS_COLOR, linewidth=1.8, label='DNS', zorder=10) # Clean (open) for method, plus in clean.items(): _plot_method(ax, plus['y_plus'], sign * plus[var], method, filled=False, label=f'{method} — A', ms=2.5, alpha=0.65) # Noisy (filled) for method, plus in noisy.items(): _plot_method(ax, plus['y_plus'], sign * plus[var], method, filled=True, label=f'{method} — B', ms=2.5, alpha=0.65) ax.set_xlabel(r'$y^+$') ax.set_ylabel(ylabel) ax.set_xscale('log') ax.set_xlim(1, Re_tau) ax.grid(True, alpha=0.25, linewidth=0.5) # Shared legend handles, labels = axes[0].get_legend_handles_labels() fig.legend(handles, labels, loc='upper center', ncol=4, bbox_to_anchor=(0.5, 1.05), framealpha=0.9, fontsize=8) fig.tight_layout() fig.subplots_adjust(top=0.82) out = Path(output_dir) out.mkdir(parents=True, exist_ok=True) fig.savefig(out / 'fig_stresses.png') fig.savefig(out / 'fig_stresses.pdf') plt.close(fig) print(f' Saved: {out / "fig_stresses.png"}') # ============================================================================= # Figure 3: Combined stresses — single axis # ============================================================================= def plot_combined_stresses(gt_plus, clean, noisy, wu, output_dir): Re_tau = wu['Re_tau'] has_ci = 'uu_plus_ci_lo' in gt_plus component_styles = { 'uu_plus': {'ls': '-', 'tex': r"$\overline{u'u'}^+$", 'sign': 1}, 'vv_plus': {'ls': '--', 'tex': r"$\overline{v'v'}^+$", 'sign': 1}, 'uv_plus': {'ls': ':', 'tex': r"$-\overline{u'v'}^+$", 'sign': -1}, } fig, ax = plt.subplots(figsize=(7, 5)) # DNS reference lines + CI bands for var, csty in component_styles.items(): sign = csty['sign'] ci_lo, ci_hi = f'{var}_ci_lo', f'{var}_ci_hi' if has_ci and ci_lo in gt_plus: _ci_band(ax, gt_plus['y_plus'], gt_plus[ci_lo], gt_plus[ci_hi], sign=sign) ax.plot(gt_plus['y_plus'], sign * gt_plus[var], color=DNS_COLOR, linewidth=1.8, linestyle=csty['ls'], zorder=10) # Clean (open) — all components for method, plus in clean.items(): for var, csty in component_styles.items(): _plot_method(ax, plus['y_plus'], csty['sign'] * plus[var], method, filled=False, ms=2.5, alpha=0.55) # Noisy (filled) — all components for method, plus in noisy.items(): for var, csty in component_styles.items(): _plot_method(ax, plus['y_plus'], csty['sign'] * plus[var], method, filled=True, ms=2.5, alpha=0.55) # ── Two-part legend ────────────────────────────────────────────────── # Part 1: method + condition method_handles = [ plt.Line2D([], [], color=DNS_COLOR, linewidth=1.8, linestyle='-', label='DNS') ] for method in list(clean.keys()) + [m for m in noisy if m not in clean]: c = COLORS[method] m = MARKERS[method] # Open (Case A) method_handles.append( plt.Line2D([], [], color=c, marker=m, markersize=5, linestyle='none', markerfacecolor='none', markeredgecolor=c, markeredgewidth=0.8, label=f'{method} — Case A')) # Filled (Case B) method_handles.append( plt.Line2D([], [], color=c, marker=m, markersize=5, linestyle='none', label=f'{method} — Case B')) # Part 2: component line styles comp_handles = [] for var, csty in component_styles.items(): comp_handles.append( plt.Line2D([], [], color='gray', linewidth=1.5, linestyle=csty['ls'], label=csty['tex'])) leg1 = ax.legend(handles=method_handles, loc='upper right', framealpha=0.9, title='Method') ax.add_artist(leg1) ax.legend(handles=comp_handles, loc='upper left', framealpha=0.9, title='Component') ax.set_xlabel(r'$y^+$') ax.set_ylabel(r'Stress$^+$') ax.set_xscale('log') ax.set_xlim(1, Re_tau) ax.grid(True, alpha=0.25, linewidth=0.5) fig.tight_layout() out = Path(output_dir) out.mkdir(parents=True, exist_ok=True) fig.savefig(out / 'fig_combined_stresses.png') fig.savefig(out / 'fig_combined_stresses.pdf') plt.close(fig) print(f' Saved: {out / "fig_combined_stresses.png"}') # ============================================================================= # Main # ============================================================================= if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Generate combined clean+noisy paper figures. ' 'All path arguments accept either the Case A (clean) or Case B (noisy) ' 'variant; if only noisy paths are supplied, only Case B is plotted.') parser.add_argument('--output-dir', '-o', type=str, required=True, help='Output directory for generated figures') # Ground truth (required — at least one of the two must be provided) parser.add_argument('--gt-clean-dir', type=str, default=None, help='Directory containing direct_stats.mat for Case A (clean / 85k particles)') parser.add_argument('--gt-noisy-dir', type=str, default=None, help='Directory containing direct_stats.mat for Case B (noisy / 22k particles)') # Case A (clean) PIV results parser.add_argument('--inst-clean-stats', type=str, default=None, help='Path to instantaneous mean_stats.mat for Case A') parser.add_argument('--ens-clean-dir', type=str, default=None, help='Directory containing ensemble_result.mat + coordinates.mat for Case A') parser.add_argument('--stereo-clean-stats', type=str, default=None, help='Path to stereo mean_stats.mat for Case A') # Case B (noisy) PIV results parser.add_argument('--inst-noisy-stats', type=str, default=None, help='Path to instantaneous mean_stats.mat for Case B') parser.add_argument('--ens-noisy-dir', type=str, default=None, help='Directory containing ensemble_result.mat + coordinates.mat for Case B') parser.add_argument('--stereo-noisy-stats', type=str, default=None, help='Path to stereo mean_stats.mat for Case B') args = parser.parse_args() output_dir = Path(args.output_dir) if not args.gt_clean_dir and not args.gt_noisy_dir: parser.error('At least one of --gt-clean-dir / --gt-noisy-dir must be provided') # Ground truth: prefer clean (85k particles, tighter CI) for reference axes gt_dir_primary = args.gt_clean_dir or args.gt_noisy_dir gt_plus, wu = _load_gt(Path(gt_dir_primary)) print(f"DNS: Re_tau={wu['Re_tau']:.0f}") # ── Case A (clean) ─────────────────────────────────────────────────── clean = {} if args.inst_clean_stats or args.ens_clean_dir or args.stereo_clean_stats: print("\nLoading Case A (ideal)...") if args.inst_clean_stats: inst_clean = _trim(_load_inst( Path(args.inst_clean_stats), run_idx=3, wu=wu, y_offset=3.0)) print(f" Instantaneous 16x16: y+={inst_clean['y_plus'].min():.1f}-{inst_clean['y_plus'].max():.1f}") clean['Instantaneous'] = inst_clean if args.ens_clean_dir: ens_dir = Path(args.ens_clean_dir) ens_clean = _load_ens( ens_dir / 'ensemble_result.mat', ens_dir / 'coordinates.mat', run_idx=3, wu=wu, y_offset=0.8) print(f" Ensemble 8x16: y+={ens_clean['y_plus'].min():.1f}-{ens_clean['y_plus'].max():.1f}") clean['Ensemble'] = ens_clean if args.stereo_clean_stats: stereo_clean = _trim(_load_stereo( Path(args.stereo_clean_stats), run_idx=3, wu=wu, y_offset=0.8)) print(f" Stereo 16x16: y+={stereo_clean['y_plus'].min():.1f}-{stereo_clean['y_plus'].max():.1f}") clean['Stereo'] = stereo_clean # ── Case B (noisy) ─────────────────────────────────────────────────── noisy = {} if args.inst_noisy_stats or args.ens_noisy_dir or args.stereo_noisy_stats: print("\nLoading Case B (degraded, SNR ~8)...") wu_n = wu # fallback to clean wu if args.gt_noisy_dir: _, wu_n = _load_gt(Path(args.gt_noisy_dir)) if args.inst_noisy_stats: inst_noisy = _trim(_load_inst( Path(args.inst_noisy_stats), run_idx=2, wu=wu_n, y_offset=3.0)) print(f" Instantaneous 32x32: y+={inst_noisy['y_plus'].min():.1f}-{inst_noisy['y_plus'].max():.1f}") noisy['Instantaneous'] = inst_noisy if args.ens_noisy_dir: ens_dir_n = Path(args.ens_noisy_dir) ens_noisy = _load_ens( ens_dir_n / 'ensemble_result.mat', ens_dir_n / 'coordinates.mat', run_idx=3, wu=wu_n, y_offset=1.0) print(f" Ensemble 8x16: y+={ens_noisy['y_plus'].min():.1f}-{ens_noisy['y_plus'].max():.1f}") noisy['Ensemble'] = ens_noisy if args.stereo_noisy_stats: stereo_noisy = _trim(_load_stereo( Path(args.stereo_noisy_stats), run_idx=2, wu=wu_n, y_offset=0.8)) print(f" Stereo 32x32: y+={stereo_noisy['y_plus'].min():.1f}-{stereo_noisy['y_plus'].max():.1f}") noisy['Stereo'] = stereo_noisy if not clean and not noisy: parser.error('At least one PIV result path must be provided (--*-clean-* or --*-noisy-*)') # ── Generate figures ───────────────────────────────────────────────── print("\nGenerating figures...") plot_velocity(gt_plus, clean, noisy, wu, output_dir) plot_stresses_subplots(gt_plus, clean, noisy, wu, output_dir) plot_combined_stresses(gt_plus, clean, noisy, wu, output_dir) print("Done.")