diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..02d906d13ca3aed76ec91eee8ea33df2393d2825 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +ground_truth/direct_stats_noisy.mat filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19d9db30b3e201d2d49c5f8f6040295191aa4fc6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,33 @@ +Creative Commons Attribution 4.0 International (CC BY 4.0) + +Copyright (c) 2026 Morgan T. Taylor, J. M. Lawson, B. Ganapathisubramani +University of Southampton + +You are free to: + + Share — copy and redistribute the material in any medium or format + Adapt — remix, transform, and build upon the material for any purpose, + even commercially. + +Under the following terms: + + Attribution — You must give appropriate credit, provide a link to the + license, and indicate if changes were made. You may do so + in any reasonable manner, but not in any way that suggests + the licensor endorses you or your use. + + No additional restrictions — You may not apply legal terms or + technological measures that legally restrict others from + doing anything the license permits. + +Full license text: https://creativecommons.org/licenses/by/4.0/legalcode + +When citing, please reference the PIVtools paper: + + Taylor, M. T., Lawson, J. M., & Ganapathisubramani, B. (2026). + PIVtools: an open-source PIV framework with integrated planar, + stereoscopic, and ensemble pipelines. SoftwareX (submitted). + +The DNS ground-truth data is derived from the Johns Hopkins Turbulence +Database (JHTDB, http://turbulence.pha.jhu.edu). Consult the JHTDB usage +policy for their citation requirements. diff --git a/README.md b/README.md index 7da79263d0e701a53a0d662d245c4fc3db39b287..dea620ac478145de39c3ad9bb144d229a3e1e873 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,244 @@ ---- -license: cc-by-4.0 ---- +--- +license: cc-by-4.0 +language: +- en +tags: +- piv +- particle-image-velocimetry +- fluid-dynamics +- turbulence +- channel-flow +- validation +- benchmark +- synthetic-data +pretty_name: PIVtools Turbulent Channel Validation Dataset +size_categories: +- 10K \ + --num-frames 4000 \ + --output-dir ./out +``` + +| Flag | Description | +|------|-------------| +| `--mode` / `-m` | `instantaneous` or `ensemble` | +| `--runs` / `-r` | Comma-separated 0-based pass indices (e.g. `2,3`) | +| `--windows` / `-w` | Labels for those passes (e.g. `32,16`) | +| `--gt-dir` / `-g` | Directory containing `direct_stats_noisy.mat` (required) | +| `--base-dir` / `-b` | PIV results base (instantaneous mode) | +| `--ensemble-dir` / `-e` | Direct path to ensemble result directory | +| `--num-frames` / `-n` | Frame count subdirectory (default 1000; use 4000 for this dataset) | +| `--output-dir` / `-o` | Output directory | +| `--y-plus-offset` / `-y` | Additional y+ offset on top of hardcoded +1 | +| `--show-fit-lines` | Overlay log-law and viscous sublayer curves | + +### `stereo_benchmark_comparison.py` — stereo 3C + 6-stress benchmark + +Uses LaTeX for labels (`text.usetex=True`); requires MiKTeX / TeXLive. + +```bash +python scripts/stereo_benchmark_comparison.py \ + --gt-dir ./ground_truth \ + --stereo-base \ + --num-frames 4000 \ + --output-dir ./out +``` + +### `cross_method_comparison.py` — multi-method overlay + +Publication-quality plots comparing one pass from each of instantaneous, ensemble, and stereo against DNS on the same axes. Okabe-Ito colourblind palette. + +```bash +python scripts/cross_method_comparison.py \ + --gt-dir ./ground_truth \ + --output-dir ./out \ + --inst-stats \ + --ens-dir \ + --stereo-stats +``` + +### `paper_figures.py` — combined Case A + Case B figures + +Reproduces the figures in the PIVtools paper: Case A (open symbols) and Case B (filled symbols) overlaid. Any combination of paths may be supplied — the script plots whichever it receives. + +```bash +# Case B only (what this dataset ships today) +python scripts/paper_figures.py \ + --gt-noisy-dir ./ground_truth \ + --inst-noisy-stats \ + --ens-noisy-dir \ + --stereo-noisy-stats \ + --output-dir ./out +``` + +### `tcf_direct_stats.py` — recompute ground truth + +If you regenerate the synthetic images via EUROSIG, this script recomputes `direct_stats.mat` from the underlying JHTDB particle position files (`B*_A.data`, `B*_B.data`). + +```bash +python scripts/tcf_direct_stats.py \ + --data-dir \ + --output-dir ./ground_truth +``` + +## Unit conventions + +| Quantity | PIVtools storage | Benchmark display | +|----------|-----------------|-------------------| +| Velocity | m/s | mm/s (× 1000) | +| Reynolds stress | (m/s)² | (mm/s)² (× 1e6) | +| Spatial coordinates | mm | wall units y⁺ = y / δ_ν | + +## Masks + +`stereo_noisy/mask_Cam{1,2}.mat` hold pixel-space boolean masks (same shape as images) that exclude regions outside the valid field of view. PIVtools loads them automatically when configured with `masking.enabled: true` and `mask_file_pattern: mask_Cam{cam}.mat`. + +## Citation + +If you use this dataset, please cite both the PIVtools paper and the underlying DNS source. + +```bibtex +@article{taylor_pivtools, + title={PIVtools: an open-source PIV framework with integrated planar, stereoscopic, and ensemble pipelines}, + author={Taylor, M.T. and Lawson, J.M. and Ganapathisubramani, B.}, + journal={SoftwareX}, + note={submitted} +} + +@article{lee2015direct, + title={Direct numerical simulation of turbulent channel flow up to Re_tau = 5200}, + author={Lee, M. and Moser, R.D.}, + journal={J. Fluid Mech.}, + year={2015} +} + +@article{li2008public, + title={A public turbulence database cluster and applications to study Lagrangian evolution of velocity increments in turbulence}, + author={Li, Y. and others}, + journal={J. Turbulence}, + year={2008} +} +``` + +DNS reference data is from the **Johns Hopkins Turbulence Database** (JHTDB). + +## License + +CC-BY-4.0 — free to use, modify, and redistribute with attribution to the PIVtools paper. + +The DNS ground truth is derived from publicly accessible JHTDB data and is redistributed here under the same permissive terms; consult the JHTDB usage policy (http://turbulence.pha.jhu.edu) for their citation requirements. diff --git a/ground_truth/direct_stats_noisy.mat b/ground_truth/direct_stats_noisy.mat new file mode 100644 index 0000000000000000000000000000000000000000..767ef58cf59f800092d60669f152be02aea0e78d --- /dev/null +++ b/ground_truth/direct_stats_noisy.mat @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb9fbc35b7a751ff46f7d3d29048b81755f19b75cc49e6bc3adc9391d0f846fb +size 1856680 diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_01.tif b/planar_noisy/calibration_boards/planar_calibration_plate_01.tif new file mode 100644 index 0000000000000000000000000000000000000000..9a805989e6a0aaaa09848c6026e41a6fa148e063 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_01.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_02.tif b/planar_noisy/calibration_boards/planar_calibration_plate_02.tif new file mode 100644 index 0000000000000000000000000000000000000000..3aafe54e5fb005eb2c21f0616bf2a3a670713bae Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_02.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_03.tif b/planar_noisy/calibration_boards/planar_calibration_plate_03.tif new file mode 100644 index 0000000000000000000000000000000000000000..c1d00237a247af3e0df4ecbbe51e98c81c73b8ed Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_03.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_04.tif b/planar_noisy/calibration_boards/planar_calibration_plate_04.tif new file mode 100644 index 0000000000000000000000000000000000000000..ea10e808c3e0ba52984d4aae355680bd2be87ab3 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_04.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_05.tif b/planar_noisy/calibration_boards/planar_calibration_plate_05.tif new file mode 100644 index 0000000000000000000000000000000000000000..57eff232de23d7f9236dba4cef8950f06c806b67 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_05.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_06.tif b/planar_noisy/calibration_boards/planar_calibration_plate_06.tif new file mode 100644 index 0000000000000000000000000000000000000000..2c68b5858977ca00e75175e75a748bd48dff0f14 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_06.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_07.tif b/planar_noisy/calibration_boards/planar_calibration_plate_07.tif new file mode 100644 index 0000000000000000000000000000000000000000..09d00c9b27b3dd6d29a11542e56033e3140ea0a3 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_07.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_08.tif b/planar_noisy/calibration_boards/planar_calibration_plate_08.tif new file mode 100644 index 0000000000000000000000000000000000000000..6c41814912a1aebbb26d8a6039710dd62e95df39 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_08.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_09.tif b/planar_noisy/calibration_boards/planar_calibration_plate_09.tif new file mode 100644 index 0000000000000000000000000000000000000000..7ac117df7bcb60c629a0ed63377abe11985011e1 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_09.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_10.tif b/planar_noisy/calibration_boards/planar_calibration_plate_10.tif new file mode 100644 index 0000000000000000000000000000000000000000..46deebf4009f2f670b1ca565bdae6ef02453bbbb Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_10.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_11.tif b/planar_noisy/calibration_boards/planar_calibration_plate_11.tif new file mode 100644 index 0000000000000000000000000000000000000000..7db41b5c9e145acdec3df9eb54c86ca7c0f46fbe Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_11.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_12.tif b/planar_noisy/calibration_boards/planar_calibration_plate_12.tif new file mode 100644 index 0000000000000000000000000000000000000000..5e2d01204877fa47bcc72f936f7998ec8a660459 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_12.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_13.tif b/planar_noisy/calibration_boards/planar_calibration_plate_13.tif new file mode 100644 index 0000000000000000000000000000000000000000..1eb67e4e41bbbc6624c9f11cbe9ff8c938456c45 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_13.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_14.tif b/planar_noisy/calibration_boards/planar_calibration_plate_14.tif new file mode 100644 index 0000000000000000000000000000000000000000..d334ab6bb23a4ece3ec74b2e590918bd058be900 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_14.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_15.tif b/planar_noisy/calibration_boards/planar_calibration_plate_15.tif new file mode 100644 index 0000000000000000000000000000000000000000..eab78b3333d67f5ec44a62c1f4506e73f82fc646 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_15.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_16.tif b/planar_noisy/calibration_boards/planar_calibration_plate_16.tif new file mode 100644 index 0000000000000000000000000000000000000000..cae64fcdcd8894f19b0072cdbbc65a3411915994 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_16.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_17.tif b/planar_noisy/calibration_boards/planar_calibration_plate_17.tif new file mode 100644 index 0000000000000000000000000000000000000000..924cfc20cb11fc451dd88cf62ca75f05d1074614 Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_17.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_18.tif b/planar_noisy/calibration_boards/planar_calibration_plate_18.tif new file mode 100644 index 0000000000000000000000000000000000000000..a3d0a85138b5c8d60e12f8c4dc8fa54712556dce Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_18.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_19.tif b/planar_noisy/calibration_boards/planar_calibration_plate_19.tif new file mode 100644 index 0000000000000000000000000000000000000000..29f9318ca93edea8fde592a12b634986bf6397bc Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_19.tif differ diff --git a/planar_noisy/calibration_boards/planar_calibration_plate_20.tif b/planar_noisy/calibration_boards/planar_calibration_plate_20.tif new file mode 100644 index 0000000000000000000000000000000000000000..6f5e7125319becd984da83e9124de1ae259d954e Binary files /dev/null and b/planar_noisy/calibration_boards/planar_calibration_plate_20.tif differ diff --git a/scripts/benchmark_comparison.py b/scripts/benchmark_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..80dd2492efaf3b6dcccabcad6575f28508a55f7f --- /dev/null +++ b/scripts/benchmark_comparison.py @@ -0,0 +1,1906 @@ +#!/usr/bin/env python3 +""" +Benchmark comparison of PIV results against JHTDB ground truth. + +Compares: +- Mean velocity profile U+ vs y+ +- Reynolds normal stresses uu+, vv+ vs y+ +- Reynolds shear stress uv+ vs y+ + +Excludes first/last 5mm in x-direction (out-of-plane particle loss). +""" + +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 + +# Use LaTeX-style fonts everywhere (Computer Modern via mathtext — no LaTeX install needed) +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, +}) + + +def log_smooth(y_plus, values, sigma_decades=0.06): + """LOWESS-style smooth in log(y+) space, evaluated at original points. + + Each output point is a locally-weighted LINEAR regression of neighbours, + where distance is measured in decades of y+. Using local linear fits + instead of local averages gives: + - Better peak tracking (local slope captures gradients) + - Better edge behaviour (linear extrapolation, not mean bias) + + Parameters + ---------- + y_plus : array + y+ coordinates (positive) + values : array + Values to smooth + sigma_decades : float + Smoothing width in decades of y+ (0.06 ~ +/-15% local y+) + + Returns + ------- + y_out, smoothed : arrays + Sorted y+ and smoothed values (at original data points) + """ + valid = (y_plus > 0) & ~np.isnan(values) + yp = y_plus[valid] + vals = values[valid] + if len(yp) < 5: + return yp, vals + + # Sort by y+ + order = np.argsort(yp) + yp = yp[order] + vals = vals[order] + log_yp = np.log10(yp) + + # Local linear regression (LOWESS) at each point + smoothed = np.empty_like(vals) + for i in range(len(vals)): + d = (log_yp - log_yp[i]) / sigma_decades + w = np.exp(-0.5 * d * d) + wsum = np.sum(w) + wmean_x = np.sum(w * log_yp) / wsum + wmean_y = np.sum(w * vals) / wsum + dx = log_yp - wmean_x + denom = np.sum(w * dx * dx) + if denom > 1e-30: + slope = np.sum(w * dx * vals) / denom + smoothed[i] = wmean_y + slope * (log_yp[i] - wmean_x) + else: + smoothed[i] = wmean_y + + return yp, smoothed + + +def plot_ci_band(ax, y_plus, ci_lo, ci_hi, sign=1, color='k', alpha=0.3, zorder=1): + """Plot a 95% CI shaded band around a reference line. + + Parameters + ---------- + ax : matplotlib Axes + y_plus : array + x-axis values (y+ coordinates) + ci_lo, ci_hi : array + Lower/upper CI bounds (same units as the plotted variable) + sign : int + 1 or -1 (for variables like -uv+ that flip sign) + color : str + Fill color + alpha : float + Fill transparency + zorder : int + Drawing order + """ + lo = sign * ci_lo if sign == 1 else sign * ci_hi # sign flip swaps lo/hi + hi = sign * ci_hi if sign == 1 else sign * ci_lo + ax.fill_between(y_plus, lo, hi, color=color, alpha=alpha, zorder=zorder, + linewidth=0) + # Add thin edge lines so the CI is visible even when narrow + ax.plot(y_plus, lo, color=color, linewidth=0.5, alpha=0.4, zorder=zorder) + ax.plot(y_plus, hi, color=color, linewidth=0.5, alpha=0.4, zorder=zorder) + + +def load_wall_units(wall_units_path): + """Load wall units from .mat file (scipy v5 or h5py v7.3). + + Supports three formats: + - wall_units.mat with 'wall_units' struct + - diagnostics.mat with 'diagnostics' group (HDF5) + - direct_stats.mat with top-level u_tau, delta_nu, Re_tau keys + """ + try: + wall = sio.loadmat(wall_units_path, squeeze_me=True, struct_as_record=False) + + # Format: direct_stats.mat (top-level scalar keys) + if 'u_tau' in wall and 'delta_nu' in wall and 'Re_tau' in wall: + u_tau = float(wall['u_tau']) + delta_nu = float(wall['delta_nu']) + Re_tau = float(wall['Re_tau']) + return { + 'u_tau': u_tau, + 'nu': u_tau * delta_nu, + 'delta_nu': delta_nu, + 'h_mm': float(wall['h_mm']) if 'h_mm' in wall else Re_tau * delta_nu, + 'Re_tau': Re_tau, + } + + # Format: wall_units.mat (struct) + wu = wall['wall_units'] + return { + 'u_tau': float(wu.u_tau), # mm/s + 'nu': float(wu.nu), # mm^2/s + 'delta_nu': float(wu.delta_nu), # mm + 'h_mm': float(wu.h_mm), # mm + 'Re_tau': float(wu.Re_tau) + } + except NotImplementedError: + # MATLAB v7.3 (HDF5) format - use h5py + import h5py + with h5py.File(str(wall_units_path), 'r') as f: + if 'wall_units' in f: + grp = f['wall_units'] + result = { + 'u_tau': float(np.array(grp['u_tau']).flat[0]), + 'delta_nu': float(np.array(grp['delta_nu']).flat[0]), + 'Re_tau': float(np.array(grp['Re_tau']).flat[0]), + } + if 'nu' in grp: + result['nu'] = float(np.array(grp['nu']).flat[0]) + else: + result['nu'] = result['u_tau'] * result['delta_nu'] + if 'h_mm' in grp: + result['h_mm'] = float(np.array(grp['h_mm']).flat[0]) + else: + result['h_mm'] = result['Re_tau'] * result['delta_nu'] + return result + elif 'diagnostics' in f: + grp = f['diagnostics'] + result = { + 'u_tau': float(np.array(grp['u_tau']).flat[0]), + 'delta_nu': float(np.array(grp['delta_nu']).flat[0]), + 'Re_tau': float(np.array(grp['Re_tau']).flat[0]), + } + if 'nu' in grp: + result['nu'] = float(np.array(grp['nu']).flat[0]) + else: + result['nu'] = result['u_tau'] * result['delta_nu'] + if 'h_mm' in grp: + result['h_mm'] = float(np.array(grp['h_mm']).flat[0]) + else: + result['h_mm'] = result['Re_tau'] * result['delta_nu'] + return result + else: + raise ValueError(f"No 'wall_units' or 'diagnostics' group in {wall_units_path}") + + +def load_ground_truth(profiles_path, wall_units_path=None): + """Load ground truth profiles (scipy v5 or h5py v7.3). + + Supports three formats: + - profiles.mat with 'profiles.win_1px' struct + - ensemble_statistics_full.mat with 'ref_profile' + 'ensemble_stats' (HDF5) + - direct_stats.mat with top-level y_plus, U_plus, stress_plus arrays + """ + try: + profiles = sio.loadmat(profiles_path, squeeze_me=True, struct_as_record=False) + + # Format: direct_stats.mat (top-level arrays) + if 'U_plus' in profiles and 'stress_plus' in profiles and 'y_plus' in profiles: + y_plus_full = profiles['y_plus'] + Re_tau = float(profiles['Re_tau']) + u_tau = float(profiles['u_tau']) + delta_nu = float(profiles['delta_nu']) + u_tau2 = u_tau ** 2 + + # Select lower half of channel (y+ <= Re_tau) + mask = y_plus_full <= Re_tau + y_plus = y_plus_full[mask] + y_mm = y_plus * delta_nu + + # U_plus: (N, 3) -> columns [U, V, W] + U_plus = profiles['U_plus'][mask, 0] + V_plus = profiles['U_plus'][mask, 1] + + # stress_plus: (N, 3, 3) -> Reynolds stress tensor in plus units + uu_plus = profiles['stress_plus'][mask, 0, 0] + vv_plus = profiles['stress_plus'][mask, 1, 1] + uv_plus = profiles['stress_plus'][mask, 0, 1] + + result = { + 'y_mm': y_mm, + 'y_plus': y_plus, + 'U': U_plus * u_tau, # mm/s + 'V': V_plus * u_tau, # mm/s + 'uu': uu_plus * u_tau2, # (mm/s)^2 + 'vv': vv_plus * u_tau2, # (mm/s)^2 + 'uv': uv_plus * u_tau2, # (mm/s)^2 + 'U_plus': U_plus, + 'uu_plus': uu_plus, + 'vv_plus': vv_plus, + 'uv_plus': uv_plus, + } + + # Load 95% confidence intervals if available + if 'stress_ci_lo' in profiles and 'stress_ci_hi' in profiles: + result['uu_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 0, 0] + result['uu_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 0, 0] + result['vv_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 1, 1] + result['vv_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 1, 1] + result['uv_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 0, 1] + result['uv_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 0, 1] + if 'umean_ci_lo' in profiles and 'umean_ci_hi' in profiles: + result['U_plus_ci_lo'] = profiles['umean_ci_lo'][mask, 0] + result['U_plus_ci_hi'] = profiles['umean_ci_hi'][mask, 0] + result['V_plus_ci_lo'] = profiles['umean_ci_lo'][mask, 1] + result['V_plus_ci_hi'] = profiles['umean_ci_hi'][mask, 1] + + return result + + # Format: profiles.mat (struct) + win1px = profiles['profiles'].win_1px + return { + 'y_mm': win1px.y_mm, + 'y_plus': win1px.y_plus, + 'U': win1px.U, # mm/s + 'V': win1px.V, # mm/s + 'uu': win1px.uu, # (mm/s)^2 + 'vv': win1px.vv, # (mm/s)^2 + 'uv': win1px.uv, # (mm/s)^2 + 'U_plus': win1px.U_plus, + 'uu_plus': win1px.uu_plus, + 'vv_plus': win1px.vv_plus, + 'uv_plus': win1px.uv_plus, + } + except NotImplementedError: + # MATLAB v7.3 (HDF5) format + import h5py + + # Load wall units for normalisation + if wall_units_path is not None: + wu = load_wall_units(wall_units_path) + else: + wu_path = Path(profiles_path).parent / 'diagnostics.mat' + if wu_path.exists(): + wu = load_wall_units(wu_path) + else: + raise ValueError("Need wall_units_path to normalise HDF5 ground truth") + + u_tau = wu['u_tau'] + u_tau2 = u_tau ** 2 + delta_nu = wu['delta_nu'] + + with h5py.File(str(profiles_path), 'r') as f: + ref = f['ref_profile'] + + # Check if ref_profile has stress data directly + if 'uu' in ref: + y_mm = np.array(ref['y_mm']).flatten() + U = np.array(ref['U']).flatten() + V = np.array(ref['V']).flatten() + uu = np.array(ref['uu']).flatten() + vv = np.array(ref['vv']).flatten() + uv = np.array(ref['uv']).flatten() + y_plus = y_mm / delta_nu + return { + 'y_mm': y_mm, 'y_plus': y_plus, + 'U': U, 'V': V, 'uu': uu, 'vv': vv, 'uv': uv, + 'U_plus': U / u_tau, 'uu_plus': uu / u_tau2, + 'vv_plus': vv / u_tau2, 'uv_plus': uv / u_tau2, + } + + # Use ensemble_stats profiles (pre-averaged, consistent y_plus) + if 'ensemble_stats' not in f: + raise ValueError("No stress data in ref_profile and no ensemble_stats") + + es = f['ensemble_stats'] + # Use finest window (index 0) as reference + win_idx = 0 + + def _deref(field, idx=win_idx): + refs = np.array(es[field]).flatten() + return np.array(f[refs[idx]]).flatten() + + # Ensemble stats y_plus (255 points for 16x16 window) + es_y_plus = _deref('y_plus') + es_y_mm = es_y_plus * delta_nu + + # Stresses are already in plus units + uu_plus = _deref('uu_plus') + vv_plus = _deref('vv_plus') + uv_plus = _deref('uv_plus') + + # Velocity: interpolate DNS onto ensemble y_plus grid + dns_y_mm = np.array(ref['y_mm']).flatten() + dns_U = np.array(ref['U']).flatten() + dns_V = np.array(ref['V']).flatten() + dns_y_plus = dns_y_mm / delta_nu + + U_interp = interp1d(dns_y_plus, dns_U, kind='linear', + bounds_error=False, fill_value=np.nan)(es_y_plus) + V_interp = interp1d(dns_y_plus, dns_V, kind='linear', + bounds_error=False, fill_value=np.nan)(es_y_plus) + + return { + 'y_mm': es_y_mm, + 'y_plus': es_y_plus, + 'U': U_interp, + 'V': V_interp, + 'uu': uu_plus * u_tau2, + 'vv': vv_plus * u_tau2, + 'uv': uv_plus * u_tau2, + 'U_plus': U_interp / u_tau, + 'uu_plus': uu_plus, + 'vv_plus': vv_plus, + 'uv_plus': uv_plus, + } + + +def load_piv_statistics(stats_path, run_idx=3): + """ + Load PIV statistics from mean_stats.mat (instantaneous). + + Parameters + ---------- + stats_path : Path + Path to mean_stats.mat + run_idx : int + Run index (0-based). run_idx=3 corresponds to run 4 (16x16 window) + """ + stats = sio.loadmat(stats_path, squeeze_me=True, struct_as_record=False) + piv = stats['piv_result'][run_idx] + coords = stats['coordinates'][run_idx] + + return { + 'ux': piv.ux, # m/s (need to convert to mm/s) + 'uy': piv.uy, # m/s + 'uu': piv.uu, # (m/s)^2 + 'vv': piv.vv, # (m/s)^2 + 'uv': piv.uv, # (m/s)^2 + 'x': coords.x, # mm + 'y': coords.y, # mm + } + + +def load_ensemble_statistics(ensemble_path, coords_path, run_idx=3): + """ + Load PIV statistics from ensemble_result.mat. + + Parameters + ---------- + ensemble_path : Path + Path to ensemble_result.mat + coords_path : Path + Path to coordinates.mat + run_idx : int + Run index (0-based). run_idx=3 corresponds to run 4 + """ + ens = sio.loadmat(ensemble_path, squeeze_me=True, struct_as_record=False) + coords_data = sio.loadmat(coords_path, squeeze_me=True, struct_as_record=False) + + piv = ens['ensemble_result'][run_idx] + coords = coords_data['coordinates'][run_idx] + + return { + 'ux': piv.ux, # m/s + 'uy': piv.uy, # m/s + 'uu': piv.UU_stress, # (m/s)^2 + 'vv': piv.VV_stress, # (m/s)^2 + 'uv': piv.UV_stress, # (m/s)^2 + 'x': coords.x, # mm + 'y': coords.y, # mm + } + + +def compute_piv_profiles(piv_data, x_exclude_vectors=4): + """ + Compute x-averaged PIV profiles, excluding edges. + + Parameters + ---------- + piv_data : dict + PIV statistics dictionary (velocities in m/s, stresses in (m/s)^2) + x_exclude_vectors : int + Number of vectors to exclude from each side in x-direction + + Returns + ------- + dict with y_mm, U, uu, vv, uv profiles (in mm/s and (mm/s)^2) + """ + x = piv_data['x'] + y = piv_data['y'] + + # Get unique y values (assuming regular grid) + y_unique = y[:, 0] + x_unique = x[0, :] + nx = len(x_unique) + + # Create mask excluding first/last x_exclude_vectors + x_mask = np.zeros(nx, dtype=bool) + x_mask[x_exclude_vectors:nx-x_exclude_vectors] = True + + print(f" X range: {x_unique.min():.2f} to {x_unique.max():.2f} mm") + print(f" Excluding {x_exclude_vectors} vectors from each x-edge") + print(f" X points: {x_mask.sum()} / {nx}") + + # Convert velocities from m/s to mm/s + ux_mm = piv_data['ux'] * 1000 # m/s -> mm/s + uy_mm = piv_data['uy'] * 1000 + uu_mm2 = piv_data['uu'] * 1e6 # (m/s)^2 -> (mm/s)^2 + vv_mm2 = piv_data['vv'] * 1e6 + uv_mm2 = piv_data['uv'] * 1e6 + + # Average over valid x range + U_profile = np.nanmean(ux_mm[:, x_mask], axis=1) + V_profile = np.nanmean(uy_mm[:, x_mask], axis=1) + uu_profile = np.nanmean(uu_mm2[:, x_mask], axis=1) + vv_profile = np.nanmean(vv_mm2[:, x_mask], axis=1) + uv_profile = np.nanmean(uv_mm2[:, x_mask], axis=1) + + return { + 'y_mm': y_unique, + 'U': U_profile, + 'V': V_profile, + 'uu': uu_profile, + 'vv': vv_profile, + 'uv': uv_profile, + } + + +def convert_to_wall_units(profiles, wall_units, y_offset_mm=0.0): + """ + Convert profiles to wall units (plus units). + + Parameters + ---------- + profiles : dict + PIV profiles with y_mm, U, etc. + wall_units : dict + Wall unit parameters + y_offset_mm : float + Offset to add to y_mm before converting to y+ (for coordinate alignment) + """ + u_tau = wall_units['u_tau'] + delta_nu = wall_units['delta_nu'] + u_tau2 = u_tau ** 2 + + # Apply y offset (to align PIV coordinate system with ground truth) + y_mm_aligned = profiles['y_mm'] + y_offset_mm + + return { + 'y_mm': y_mm_aligned, + 'y_plus': y_mm_aligned / delta_nu, + 'U_plus': profiles['U'] / u_tau, + 'V_plus': profiles['V'] / u_tau, + 'uu_plus': profiles['uu'] / u_tau2, + 'vv_plus': profiles['vv'] / u_tau2, + 'uv_plus': profiles['uv'] / u_tau2, + } + + +def compute_errors(piv_plus, gt_plus, y_plus_range=(10, 500)): + """ + Compute error metrics between PIV and ground truth. + + Parameters + ---------- + piv_plus : dict + PIV profiles in wall units + gt_plus : dict + Ground truth profiles in wall units + y_plus_range : tuple + y+ range for comparison (exclude near-wall and centerline regions) + """ + # Interpolate ground truth to PIV y+ locations + y_piv = piv_plus['y_plus'] + y_gt = gt_plus['y_plus'] + + # Only compare in specified y+ range + mask_piv = (y_piv >= y_plus_range[0]) & (y_piv <= y_plus_range[1]) + y_compare = y_piv[mask_piv] + + if len(y_compare) == 0: + print(f" Warning: No PIV points in y+ range {y_plus_range}") + return {} + + errors = {} + for var in ['U_plus', 'V_plus', 'uu_plus', 'vv_plus', 'uv_plus']: + piv_vals = piv_plus[var][mask_piv] + + # Interpolate ground truth + gt_interp = interp1d(y_gt, gt_plus[var], kind='linear', + bounds_error=False, fill_value=np.nan) + gt_vals = gt_interp(y_compare) + + # Remove NaN values + valid = ~np.isnan(piv_vals) & ~np.isnan(gt_vals) + if valid.sum() == 0: + continue + + piv_valid = piv_vals[valid] + gt_valid = gt_vals[valid] + + # Compute metrics + diff = piv_valid - gt_valid + rms_error = np.sqrt(np.mean(diff**2)) + mean_abs_error = np.mean(np.abs(diff)) + + # Relative RMS error (as percentage of GT range) + gt_range = np.ptp(gt_valid) # peak-to-peak + rms_rel = (rms_error / gt_range * 100) if gt_range > 0 else np.nan + + # Correlation coefficient + corr = np.corrcoef(piv_valid, gt_valid)[0, 1] + + # R-squared + ss_res = np.sum(diff**2) + ss_tot = np.sum((gt_valid - gt_valid.mean())**2) + r2 = 1 - (ss_res / ss_tot) if ss_tot > 0 else np.nan + + errors[var] = { + 'rms': rms_error, + 'rms_rel': rms_rel, + 'mae': mean_abs_error, + 'corr': corr, + 'r2': r2, + 'n_points': valid.sum(), + } + + return errors + + +def plot_comparison(piv_plus, gt_plus, wall_units, errors, output_dir, window_label='16x16', show_fit_lines=False): + """Generate comparison plots.""" + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + Re_tau = wall_units['Re_tau'] + + # Check for CI data + has_ci = 'uu_plus_ci_lo' in gt_plus + + # Figure 1: Mean velocity profile (semi-log) + fig, ax = plt.subplots(figsize=(10, 7)) + + # Ground truth with CI band + if has_ci and 'U_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], + gt_plus['U_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', + linewidth=2, label='DNS (1px)', zorder=3) + + # PIV + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], 'ro', + markersize=4, alpha=0.7, label=f'PIV ({window_label})', zorder=2) + + if show_fit_lines: + y_log = np.logspace(1, np.log10(Re_tau), 100) + kappa, B = 0.41, 5.2 + ax.semilogx(y_log, (1/kappa)*np.log(y_log)+B, 'b--', linewidth=1, alpha=0.7, + label=r'Log law: $U^+ = \frac{1}{\kappa}\ln(y^+) + B$') + y_visc = np.linspace(0.1, 10, 50) + ax.semilogx(y_visc, y_visc, 'g--', linewidth=1, alpha=0.7, + label=r'Viscous sublayer: $U^+ = y^+$') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title(f'Mean Velocity Profile (Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=11) + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 25) + ax.grid(True, alpha=0.3) + + if 'U_plus' in errors: + ax.text(0.02, 0.98, f"R² = {errors['U_plus']['r2']:.4f}\n" + f"RMS = {errors['U_plus']['rms_rel']:.1f}%", + transform=ax.transAxes, fontsize=11, verticalalignment='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_profile.png', dpi=150) + plt.close(fig) + + # Figure 2: Reynolds stresses (semi-log) + fig, axes = plt.subplots(1, 3, figsize=(15, 5)) + + # uu+ + ax = axes[0] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uu_plus_ci_lo'], + gt_plus['uu_plus_ci_hi'], color='k', zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['uu_plus'], 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], piv_plus['uu_plus'], 'ro', markersize=4, + alpha=0.7, label='PIV') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+$", fontsize=12) + ax.set_title('Streamwise Normal Stress', fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'uu_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['uu_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + # vv+ + ax = axes[1] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['vv_plus_ci_lo'], + gt_plus['vv_plus_ci_hi'], color='k', zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['vv_plus'], 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], piv_plus['vv_plus'], 'ro', markersize=4, + alpha=0.7, label='PIV') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{v'v'}^+$", fontsize=12) + ax.set_title('Wall-Normal Normal Stress', fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'vv_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['vv_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + # -uv+ + ax = axes[2] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uv_plus_ci_lo'], + gt_plus['uv_plus_ci_hi'], sign=-1, color='k', zorder=1) + ax.semilogx(gt_plus['y_plus'], -gt_plus['uv_plus'], 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], -piv_plus['uv_plus'], 'ro', markersize=4, + alpha=0.7, label='PIV') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$-\overline{u'v'}^+$", fontsize=12) + ax.set_title('Reynolds Shear Stress', fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'uv_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['uv_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'reynolds_stresses.png', dpi=150) + plt.close(fig) + + # Figure 3: V+ profile (wall-normal mean velocity) + fig, ax = plt.subplots(figsize=(10, 7)) + + if has_ci and 'V_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['V_plus_ci_lo'], + gt_plus['V_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['V_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['V_plus'], 'ro', markersize=4, + alpha=0.7, label='PIV') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5, alpha=0.7) + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$V^+$', fontsize=14) + ax.set_title(f'Mean Wall-Normal Velocity Profile (Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=11) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + if 'V_plus' in errors: + ax.text(0.02, 0.98, f"R² = {errors['V_plus']['r2']:.4f}\n" + f"Corr = {errors['V_plus']['corr']:.4f}", + transform=ax.transAxes, fontsize=11, verticalalignment='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'V_plus_profile.png', dpi=150) + plt.close(fig) + + # Figure 4: All profiles on linear scale + fig, ax = plt.subplots(figsize=(10, 7)) + + ax.plot(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', linewidth=2, label='DNS U+') + ax.plot(piv_plus['y_plus'], piv_plus['U_plus'], 'ko', markersize=3, + alpha=0.5, label='PIV U+') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title('Mean Velocity Profile', fontsize=16) + ax.legend(fontsize=11) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_linear.png', dpi=150) + plt.close(fig) + + # Figure 5: Smoothed line plots (log-space moving average) + # ---- U+ smoothed ---- + fig, ax = plt.subplots(figsize=(10, 7)) + + if has_ci and 'U_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], + gt_plus['U_plus_ci_hi'], color='k', zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', + linewidth=2, label='DNS (1px)', zorder=3) + + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], 'ro', + markersize=4, alpha=0.7, label=f'PIV ({window_label})', zorder=2) + + if show_fit_lines: + y_log = np.logspace(1, np.log10(Re_tau), 100) + kappa, B = 0.41, 5.2 + ax.semilogx(y_log, (1/kappa)*np.log(y_log)+B, 'b--', linewidth=1, alpha=0.7, + label=r'Log law') + y_visc = np.linspace(0.1, 10, 50) + ax.semilogx(y_visc, y_visc, 'g--', linewidth=1, alpha=0.7, label=r'$U^+=y^+$') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title(f'Mean Velocity Profile - Smoothed ({window_label})', fontsize=16) + ax.legend(fontsize=11) + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 25) + ax.grid(True, alpha=0.3) + if 'U_plus' in errors: + ax.text(0.02, 0.98, f"R² = {errors['U_plus']['r2']:.4f}\n" + f"RMS = {errors['U_plus']['rms_rel']:.1f}%", + transform=ax.transAxes, fontsize=11, verticalalignment='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_profile_smooth.png', dpi=150) + plt.close(fig) + + # ---- Reynolds stresses smoothed ---- + fig, axes = plt.subplots(1, 3, figsize=(15, 5)) + + stress_configs = [ + ('uu_plus', r"$\overline{u'u'}^+$", 'Streamwise Normal Stress', 1), + ('vv_plus', r"$\overline{v'v'}^+$", 'Wall-Normal Normal Stress', 1), + ('uv_plus', r"$-\overline{u'v'}^+$", 'Reynolds Shear Stress', -1), + ] + for ax, (var, ylabel, title, sign) in zip(axes, stress_configs): + gt_vals = sign * gt_plus[var] + piv_vals = sign * piv_plus[var] + + ci_lo_key = f'{var}_ci_lo' + ci_hi_key = f'{var}_ci_hi' + if has_ci and ci_lo_key in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus[ci_lo_key], + gt_plus[ci_hi_key], sign=sign, color='k', zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_vals, 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], piv_vals, 'ro', markersize=4, alpha=0.7, label='PIV') + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if var in errors: + ax.text(0.98, 0.98, f"R² = {errors[var]['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'reynolds_stresses_smooth.png', dpi=150) + plt.close(fig) + + # Figure 6: Trace invariant (u'u' + v'v') - rotation diagnostic + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + # Compute trace + gt_trace = gt_plus['uu_plus'] + gt_plus['vv_plus'] + piv_trace = piv_plus['uu_plus'] + piv_plus['vv_plus'] + + # Left: Individual components + ax = axes[0] + ax.semilogx(gt_plus['y_plus'], gt_plus['uu_plus'], 'k-', linewidth=2, label="DNS u'u'+") + ax.semilogx(gt_plus['y_plus'], gt_plus['vv_plus'], 'k--', linewidth=2, label="DNS v'v'+") + ax.semilogx(piv_plus['y_plus'], piv_plus['uu_plus'], 'ro', markersize=3, alpha=0.7, label="PIV u'u'+") + ax.semilogx(piv_plus['y_plus'], piv_plus['vv_plus'], 'bs', markersize=3, alpha=0.7, label="PIV v'v'+") + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Stress$^+$", fontsize=12) + ax.set_title('Individual Normal Stresses', fontsize=14) + ax.legend(fontsize=9) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Middle: Trace comparison + ax = axes[1] + ax.semilogx(gt_plus['y_plus'], gt_trace, 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], piv_trace, 'ro', markersize=4, alpha=0.7, label='PIV') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+ + \overline{v'v'}^+$", fontsize=12) + ax.set_title("Trace Invariant (u'u' + v'v')", fontsize=14) + ax.legend(fontsize=11) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Right: Ratio of components (rotation indicator) + ax = axes[2] + gt_ratio = gt_plus['uu_plus'] / (gt_plus['vv_plus'] + 1e-10) # avoid div by zero + piv_ratio = piv_plus['uu_plus'] / (piv_plus['vv_plus'] + 1e-10) + ax.semilogx(gt_plus['y_plus'], gt_ratio, 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], piv_ratio, 'ro', markersize=4, alpha=0.7, label='PIV') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+ / \overline{v'v'}^+$", fontsize=12) + ax.set_title("Stress Ratio (rotation indicator)", fontsize=14) + ax.legend(fontsize=11) + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 10) + ax.grid(True, alpha=0.3) + + fig.suptitle("Rotation Diagnostic: Trace is invariant under rotation", fontsize=14, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'trace_invariant.png', dpi=150) + plt.close(fig) + + # Figure 7: Residuals (PIV - Ref) vs y+ — velocities and stresses + fig, axes = plt.subplots(2, 3, figsize=(15, 10)) + + # Interpolate ground truth onto PIV y+ grid + gt_interp_fn = {} + for var in ['U_plus', 'V_plus', 'uu_plus', 'vv_plus', 'uv_plus']: + gt_interp_fn[var] = interp1d(gt_plus['y_plus'], gt_plus[var], kind='linear', + bounds_error=False, fill_value=np.nan) + + # Top row: velocity residuals + vel_configs = [ + ('U_plus', r"$U^+_{\mathrm{PIV}} - U^+_{\mathrm{Ref}}$", + 'Mean Streamwise Velocity Residual', 1), + ('V_plus', r"$V^+_{\mathrm{PIV}} - V^+_{\mathrm{Ref}}$", + 'Mean Wall-Normal Velocity Residual', 1), + ] + for ax, (var, ylabel, title, sign) in zip(axes[0, :2], vel_configs): + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + + ax.semilogx(piv_plus['y_plus'], residual, 'ro', markersize=3, alpha=0.5) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2, label=f'PIV ({window_label})') + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + axes[0, 2].set_visible(False) # Empty top-right panel + + # Bottom row: stress residuals + stress_configs = [ + ('uu_plus', r"$\overline{u'u'}^+_{\mathrm{PIV}} - \overline{u'u'}^+_{\mathrm{Ref}}$", + 'Streamwise Normal Stress Residual', 1), + ('vv_plus', r"$\overline{v'v'}^+_{\mathrm{PIV}} - \overline{v'v'}^+_{\mathrm{Ref}}$", + 'Wall-Normal Normal Stress Residual', 1), + ('uv_plus', r"$-\overline{u'v'}^+_{\mathrm{PIV}} - (-\overline{u'v'}^+_{\mathrm{Ref}})$", + 'Shear Stress Residual', -1), + ] + for ax, (var, ylabel, title, sign) in zip(axes[1, :], stress_configs): + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + + ax.semilogx(piv_plus['y_plus'], residual, 'ro', markersize=3, alpha=0.5) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2, label=f'PIV ({window_label})') + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'residuals.png', dpi=150) + plt.close(fig) + + # Figure 8: Noise floor vs gradient correction decomposition + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + # Compute residuals + uu_residual = piv_plus['uu_plus'] - gt_interp_fn['uu_plus'](piv_plus['y_plus']) + vv_residual = piv_plus['vv_plus'] - gt_interp_fn['vv_plus'](piv_plus['y_plus']) + gradient_only = uu_residual - vv_residual # u'u' residual minus noise floor + + # Left: Noise floor (v'v' residual) + ax = axes[0] + ax.semilogx(piv_plus['y_plus'], vv_residual, 'bo', markersize=2, alpha=0.3) + yp_s, r_s = log_smooth(piv_plus['y_plus'], vv_residual) + ax.semilogx(yp_s, r_s, 'b-', linewidth=2.5, label=r"$v'v'$ residual (noise floor)") + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{v'v'}^+_{\mathrm{PIV}} - \overline{v'v'}^+_{\mathrm{Ref}}$", fontsize=12) + ax.set_title('Noise Floor (isotropic)', fontsize=14) + ax.legend(fontsize=10) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Middle: Gradient-only residual + ax = axes[1] + ax.semilogx(piv_plus['y_plus'], gradient_only, 'ro', markersize=2, alpha=0.3) + yp_s, r_s = log_smooth(piv_plus['y_plus'], gradient_only) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2.5, + label=r"$(\overline{u'u'} - \overline{v'v'})_{\mathrm{PIV}} - (\overline{u'u'} - \overline{v'v'})_{\mathrm{Ref}}$") + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Gradient-only residual$^+$", fontsize=12) + ax.set_title(r"Gradient Correction Residual ($u'u' - v'v'$ removes noise)", fontsize=14) + ax.legend(fontsize=9) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Right: All three overlaid + ax = axes[2] + ax.semilogx(piv_plus['y_plus'], uu_residual, 'ro', markersize=2, alpha=0.15) + yp_s_uu, r_s_uu = log_smooth(piv_plus['y_plus'], uu_residual) + ax.semilogx(yp_s_uu, r_s_uu, 'r-', linewidth=2, label=r"$u'u'$ residual (total)") + + ax.semilogx(piv_plus['y_plus'], vv_residual, 'bo', markersize=2, alpha=0.15) + yp_s_vv, r_s_vv = log_smooth(piv_plus['y_plus'], vv_residual) + ax.semilogx(yp_s_vv, r_s_vv, 'b-', linewidth=2, label=r"$v'v'$ residual (noise floor)") + + yp_s_g, r_s_g = log_smooth(piv_plus['y_plus'], gradient_only) + ax.semilogx(yp_s_g, r_s_g, 'g--', linewidth=2, label=r"$u'u' - v'v'$ residual (gradient only)") + + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Residual$^+$", fontsize=12) + ax.set_title('Decomposition: Total = Noise + Gradient', fontsize=14) + ax.legend(fontsize=9) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.suptitle(f'Noise Floor vs Gradient Correction ({window_label})', fontsize=14, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'noise_gradient_decomposition.png', dpi=150) + plt.close(fig) + + print(f"\nPlots saved to: {output_dir}") + + +def plot_combined_stresses(piv_plus, gt_plus, wall_units, errors, output_dir, window_label='16x16'): + """Plot uu+, vv+, -uv+ all on one axis.""" + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + Re_tau = wall_units['Re_tau'] + + has_ci = 'uu_plus_ci_lo' in gt_plus + + fig, ax = plt.subplots(figsize=(12, 8)) + + # CI bands (before reference lines so they render behind) + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uu_plus_ci_lo'], + gt_plus['uu_plus_ci_hi'], color='k', alpha=0.12, zorder=1) + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['vv_plus_ci_lo'], + gt_plus['vv_plus_ci_hi'], color='k', alpha=0.12, zorder=1) + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uv_plus_ci_lo'], + gt_plus['uv_plus_ci_hi'], sign=-1, color='k', alpha=0.12, zorder=1) + + # Reference (solid lines) + ax.plot(gt_plus['y_plus'], gt_plus['uu_plus'], 'k-', linewidth=2, + label=r"Ref $\overline{u'u'}^+$") + ax.plot(gt_plus['y_plus'], gt_plus['vv_plus'], 'k--', linewidth=2, + label=r"Ref $\overline{v'v'}^+$") + ax.plot(gt_plus['y_plus'], -gt_plus['uv_plus'], 'k:', linewidth=2, + label=r"Ref $-\overline{u'v'}^+$") + + # PIV markers + marker_configs = [ + ('uu_plus', 1, 'r', 'o', r"PIV $\overline{u'u'}^+$"), + ('vv_plus', 1, 'g', 's', r"PIV $\overline{v'v'}^+$"), + ('uv_plus', -1, 'm', 'D', r"PIV $-\overline{u'v'}^+$"), + ] + for var, sign, col, mkr, label in marker_configs: + piv_vals = sign * piv_plus[var] + ax.plot(piv_plus['y_plus'], piv_vals, color=col, marker=mkr, + markersize=4, alpha=0.7, linestyle='none', label=label, zorder=5) + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'Stress$^+$', fontsize=14) + ax.set_title(f'Reynolds Stresses ({window_label}) - PIV vs Reference ' + f'(Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=10, ncol=2, loc='upper right') + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'combined_stresses.png', dpi=150) + plt.close(fig) + print(f" Combined stresses plot saved to: {output_dir / 'combined_stresses.png'}") + + +def main(mode='instantaneous', gt_dir=None, base_dir=None, ensemble_dir=None, num_frames=1000, output_dir_override=None, show_fit_lines=False): + """Main benchmark comparison function. + + Parameters + ---------- + mode : str + 'instantaneous' or 'ensemble' + gt_dir : Path + Ground truth directory path (required) + base_dir : Path, optional + Base directory containing PIV results + ensemble_dir : Path, optional + Direct path to ensemble directory containing ensemble_result.mat and coordinates.mat. + If provided, overrides base_dir for ensemble mode. + num_frames : int + Number of frames subdirectory (e.g. 1000 or 4000). Used in path construction. + output_dir_override : Path, optional + Custom output directory. If None, uses default naming. + """ + if gt_dir is None: + raise ValueError("gt_dir is required. Please provide the ground truth directory path.") + + # Paths + script_dir = Path(__file__).parent + gt_dir = Path(gt_dir) + + if mode == 'ensemble': + if ensemble_dir is not None: + ensemble_dir = Path(ensemble_dir) + ensemble_path = ensemble_dir / 'ensemble_result.mat' + coords_path = ensemble_dir / 'coordinates.mat' + elif base_dir is not None: + base_dir = Path(base_dir) + ensemble_path = base_dir / f'calibrated_piv/{num_frames}/Cam1/ensemble/ensemble_result.mat' + coords_path = base_dir / f'calibrated_piv/{num_frames}/Cam1/ensemble/coordinates.mat' + else: + raise ValueError("Either ensemble_dir or base_dir must be provided for ensemble mode.") + output_dir = output_dir_override or (script_dir / 'benchmark_results_ensemble') + else: + if base_dir is None: + raise ValueError("base_dir is required for instantaneous mode.") + base_dir = Path(base_dir) + stats_path = base_dir / f'statistics/{num_frames}/Cam1/instantaneous/mean_stats/mean_stats.mat' + output_dir = output_dir_override or (script_dir / 'benchmark_results') + + print("=" * 70) + print(f"PIV BENCHMARK COMPARISON ({mode.upper()})") + print("=" * 70) + + # Load data - auto-detect file names + print("\n[1] Loading wall units...") + wall_units_file = gt_dir / 'wall_units.mat' + if not wall_units_file.exists(): + wall_units_file = gt_dir / 'diagnostics.mat' + if not wall_units_file.exists(): + wall_units_file = gt_dir / 'direct_stats.mat' + wall_units = load_wall_units(wall_units_file) + print(f" u_tau = {wall_units['u_tau']:.4f} mm/s") + print(f" nu = {wall_units['nu']:.4f} mm²/s") + print(f" delta_nu = {wall_units['delta_nu']:.4f} mm") + print(f" Re_tau = {wall_units['Re_tau']:.0f}") + + print("\n[2] Loading ground truth...") + profiles_file = gt_dir / 'profiles.mat' + if not profiles_file.exists(): + profiles_file = gt_dir / 'ensemble_statistics_full.mat' + if not profiles_file.exists(): + profiles_file = gt_dir / 'direct_stats.mat' + gt = load_ground_truth(profiles_file, wall_units_path=wall_units_file) + print(f" y+ range: {gt['y_plus'].min():.1f} to {gt['y_plus'].max():.1f}") + print(f" U range: {gt['U'].min():.2f} to {gt['U'].max():.2f} mm/s") + + print(f"\n[3] Loading PIV statistics ({mode}, run 4)...") + if mode == 'ensemble': + piv = load_ensemble_statistics(ensemble_path, coords_path, run_idx=3) + else: + piv = load_piv_statistics(stats_path, run_idx=3) + print(f" Grid size: {piv['ux'].shape}") + print(f" ux range: {np.nanmin(piv['ux'])*1000:.2f} to {np.nanmax(piv['ux'])*1000:.2f} mm/s") + + print("\n[4] Computing x-averaged PIV profiles...") + piv_profiles = compute_piv_profiles(piv, x_exclude_vectors=4) + print(f" y range: {piv_profiles['y_mm'].min():.2f} to {piv_profiles['y_mm'].max():.2f} mm") + print(f" U range: {np.nanmin(piv_profiles['U']):.2f} to {np.nanmax(piv_profiles['U']):.2f} mm/s") + + print("\n[5] Converting to wall units...") + # Calculate y-offset to align PIV coordinate system with ground truth + # Ground truth has y=0 at the wall, PIV may have an offset + y_offset_mm = -piv_profiles['y_mm'].min() # Shift so y_min = 0 + print(f" Applying y-offset: {y_offset_mm:.2f} mm (aligning y_min to wall)") + + piv_plus = convert_to_wall_units(piv_profiles, wall_units, y_offset_mm=y_offset_mm) + piv_plus['y_plus'] = piv_plus['y_plus'] + 1.0 # shift y+ by +1 + print(f" Aligned y range: {piv_plus['y_mm'].min():.2f} to {piv_plus['y_mm'].max():.2f} mm") + print(f" y+ range: {piv_plus['y_plus'].min():.1f} to {piv_plus['y_plus'].max():.1f} (y+ +1 applied)") + print(f" U+ range: {np.nanmin(piv_plus['U_plus']):.2f} to {np.nanmax(piv_plus['U_plus']):.2f}") + + # Ground truth - convert V to wall units and include pre-computed values + gt_plus = { + 'y_plus': gt['y_plus'], + 'U_plus': gt['U_plus'], + 'V_plus': gt['V'] / wall_units['u_tau'], # Convert V to wall units + 'uu_plus': gt['uu_plus'], + 'vv_plus': gt['vv_plus'], + 'uv_plus': gt['uv_plus'], + } + # Thread CI bounds through if available + for ci_key in ['U_plus_ci_lo', 'U_plus_ci_hi', 'V_plus_ci_lo', 'V_plus_ci_hi', + 'uu_plus_ci_lo', 'uu_plus_ci_hi', 'vv_plus_ci_lo', 'vv_plus_ci_hi', + 'uv_plus_ci_lo', 'uv_plus_ci_hi']: + if ci_key in gt: + gt_plus[ci_key] = gt[ci_key] + + # Verify V sign convention matches (should be correct after save_results.py fix) + # Sample at mid-channel to check sign + y_mid_idx = len(piv_plus['y_plus']) // 4 # ~25% from wall + piv_v_sample = piv_plus['V_plus'][y_mid_idx] + gt_v_idx = np.argmin(np.abs(gt_plus['y_plus'] - piv_plus['y_plus'][y_mid_idx])) + gt_v_sample = gt['V'][gt_v_idx] / wall_units['u_tau'] + + print(f"\n Sign check at y+ ≈ {piv_plus['y_plus'][y_mid_idx]:.0f}:") + print(f" PIV V+ = {piv_v_sample:+.4f}") + print(f" DNS V+ = {gt_v_sample:+.4f}") + + v_sign_match = np.sign(piv_v_sample) == np.sign(gt_v_sample) or abs(gt_v_sample) < 0.01 + if v_sign_match: + print(" => V sign MATCHES ✓ (no flip needed)") + else: + print(" => V sign MISMATCH ✗ (PIV pipeline may still have sign issue)") + + # No manual flipping - the save_results.py fix should handle this + # If signs still don't match, it indicates the fix didn't work correctly + + print("\n[6] Computing error metrics (y+ = 10-500)...") + errors = compute_errors(piv_plus, gt_plus, y_plus_range=(10, 500)) + + print("\n" + "=" * 70) + print("BENCHMARK RESULTS") + print("=" * 70) + + for var, err in errors.items(): + var_name = { + 'U_plus': 'Mean Streamwise Velocity (U+)', + 'V_plus': 'Mean Wall-normal Velocity (V+)', + 'uu_plus': 'Streamwise Stress (uu+)', + 'vv_plus': 'Wall-normal Stress (vv+)', + 'uv_plus': 'Shear Stress (uv+)', + }.get(var, var) + + print(f"\n{var_name}:") + print(f" RMS Error: {err['rms']:.4f} ({err['rms_rel']:.1f}% of range)") + print(f" MAE: {err['mae']:.4f}") + print(f" R²: {err['r2']:.4f}") + print(f" Correlation: {err['corr']:.4f}") + print(f" Points compared: {err['n_points']}") + + print("\n[7] Generating plots...") + plot_comparison(piv_plus, gt_plus, wall_units, errors, output_dir, + show_fit_lines=show_fit_lines) + plot_combined_stresses(piv_plus, gt_plus, wall_units, errors, output_dir) + + print("\n" + "=" * 70) + print("BENCHMARK COMPLETE") + print("=" * 70) + + +def plot_combined_comparison(all_results, gt_plus, wall_units, output_dir, show_fit_lines=False): + """ + Generate combined comparison plots with all window sizes on one figure. + + Parameters + ---------- + all_results : list of dict + List of dicts with keys: 'piv_plus', 'errors', 'window_label', 'window_size' + gt_plus : dict + Ground truth profiles in wall units + wall_units : dict + Wall unit parameters + output_dir : Path + Output directory for plots + """ + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + Re_tau = wall_units['Re_tau'] + + # Color/marker cycle for different window sizes + colors = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#a65628'] + markers = ['o', 's', '^', 'D', 'v', 'p'] + + # Check for CI data + has_ci = 'uu_plus_ci_lo' in gt_plus + + # ========================================================================== + # Figure 1: Mean velocity profile (semi-log) - ALL WINDOWS + # ========================================================================== + fig, ax = plt.subplots(figsize=(12, 8)) + + # Ground truth with CI band + if has_ci and 'U_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], + gt_plus['U_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', + linewidth=2.5, label='DNS (1px)', zorder=10) + + # PIV results for each window + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=4, alpha=0.7, linestyle='none', + label=f'PIV ({label})', zorder=5-i*0.1) + + if show_fit_lines: + y_log = np.logspace(1, np.log10(Re_tau), 100) + kappa, B = 0.41, 5.2 + ax.semilogx(y_log, (1/kappa)*np.log(y_log)+B, 'b--', linewidth=1.5, alpha=0.5, + label=r'Log law: $U^+ = \frac{1}{\kappa}\ln(y^+) + B$') + y_visc = np.linspace(0.1, 10, 50) + ax.semilogx(y_visc, y_visc, 'g--', linewidth=1.5, alpha=0.5, + label=r'Viscous sublayer: $U^+ = y^+$') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title(f'Mean Velocity Profile - All Window Sizes (Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=10, loc='upper left') + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 25) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_profile_combined.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 2: Reynolds stresses - ALL WINDOWS + # ========================================================================== + fig, axes = plt.subplots(1, 3, figsize=(18, 6)) + + # uu+ + ax = axes[0] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uu_plus_ci_lo'], + gt_plus['uu_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['uu_plus'], 'k-', linewidth=2.5, label='DNS', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + ax.plot(piv_plus['y_plus'], piv_plus['uu_plus'], + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=3, alpha=0.7, linestyle='none', label=f'PIV ({label})') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+$", fontsize=12) + ax.set_title('Streamwise Normal Stress', fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # vv+ + ax = axes[1] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['vv_plus_ci_lo'], + gt_plus['vv_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['vv_plus'], 'k-', linewidth=2.5, label='DNS', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + ax.plot(piv_plus['y_plus'], piv_plus['vv_plus'], + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=3, alpha=0.7, linestyle='none', label=f'PIV ({label})') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{v'v'}^+$", fontsize=12) + ax.set_title('Wall-Normal Normal Stress', fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # -uv+ + ax = axes[2] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uv_plus_ci_lo'], + gt_plus['uv_plus_ci_hi'], sign=-1, color='k', zorder=1) + ax.plot(gt_plus['y_plus'], -gt_plus['uv_plus'], 'k-', linewidth=2.5, label='DNS', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + ax.plot(piv_plus['y_plus'], -piv_plus['uv_plus'], + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=3, alpha=0.7, linestyle='none', label=f'PIV ({label})') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$-\overline{u'v'}^+$", fontsize=12) + ax.set_title('Reynolds Shear Stress', fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'reynolds_stresses_combined.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 3: V+ profile - ALL WINDOWS + # ========================================================================== + fig, ax = plt.subplots(figsize=(12, 8)) + + if has_ci and 'V_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['V_plus_ci_lo'], + gt_plus['V_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['V_plus'], 'k-', linewidth=2.5, label='DNS', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + ax.plot(piv_plus['y_plus'], piv_plus['V_plus'], + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=4, alpha=0.7, linestyle='none', label=f'PIV ({label})') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5, alpha=0.7) + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$V^+$', fontsize=14) + ax.set_title(f'Mean Wall-Normal Velocity Profile - All Window Sizes (Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=10) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'V_plus_profile_combined.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 4: U+ linear scale - ALL WINDOWS + # ========================================================================== + fig, ax = plt.subplots(figsize=(12, 8)) + + ax.plot(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', linewidth=2.5, label='DNS U+', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + ax.plot(piv_plus['y_plus'], piv_plus['U_plus'], + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=3, alpha=0.6, linestyle='none', label=f'PIV ({label})') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title('Mean Velocity Profile - All Window Sizes', fontsize=16) + ax.legend(fontsize=10) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_linear_combined.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 5: Smoothed U+ combined - ALL WINDOWS + # ========================================================================== + fig, ax = plt.subplots(figsize=(12, 8)) + + if has_ci and 'U_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], + gt_plus['U_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', + linewidth=2.5, label='DNS (1px)', zorder=10) + + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + c = colors[i % len(colors)] + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], + color=c, marker=markers[i % len(markers)], + markersize=4, alpha=0.7, linestyle='none', + label=f'PIV ({label})', zorder=5-i*0.1) + + if show_fit_lines: + y_log = np.logspace(1, np.log10(Re_tau), 100) + kappa, B = 0.41, 5.2 + ax.semilogx(y_log, (1/kappa)*np.log(y_log)+B, 'b--', linewidth=1.5, alpha=0.5, + label='Log law') + y_visc = np.linspace(0.1, 10, 50) + ax.semilogx(y_visc, y_visc, 'g--', linewidth=1.5, alpha=0.5, label=r'$U^+=y^+$') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title(f'Mean Velocity Profile - Smoothed (Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=10, loc='upper left') + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 25) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_profile_combined_smooth.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 6: Smoothed Reynolds stresses combined - ALL WINDOWS + # ========================================================================== + fig, axes = plt.subplots(1, 3, figsize=(18, 6)) + + stress_configs = [ + ('uu_plus', r"$\overline{u'u'}^+$", 'Streamwise Normal Stress', 1), + ('vv_plus', r"$\overline{v'v'}^+$", 'Wall-Normal Normal Stress', 1), + ('uv_plus', r"$-\overline{u'v'}^+$", 'Reynolds Shear Stress', -1), + ] + for ax, (var, ylabel, title, sign) in zip(axes, stress_configs): + gt_vals = sign * gt_plus[var] + ci_lo_key = f'{var}_ci_lo' + ci_hi_key = f'{var}_ci_hi' + if has_ci and ci_lo_key in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus[ci_lo_key], + gt_plus[ci_hi_key], sign=sign, color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_vals, 'k-', linewidth=2.5, label='DNS', zorder=10) + + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + c = colors[i % len(colors)] + piv_vals = sign * piv_plus[var] + ax.plot(piv_plus['y_plus'], piv_vals, + color=c, marker=markers[i % len(markers)], + markersize=4, alpha=0.7, linestyle='none', + label=f'PIV ({label})', zorder=5-i*0.1) + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'reynolds_stresses_combined_smooth.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 7: Trace invariant (u'u' + v'v') - ALL WINDOWS + # ========================================================================== + fig, axes = plt.subplots(1, 2, figsize=(14, 6)) + + # Compute ground truth trace + gt_trace = gt_plus['uu_plus'] + gt_plus['vv_plus'] + + # Left: Trace comparison + ax = axes[0] + ax.semilogx(gt_plus['y_plus'], gt_trace, 'k-', linewidth=2.5, label='DNS', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + piv_trace = piv_plus['uu_plus'] + piv_plus['vv_plus'] + ax.semilogx(piv_plus['y_plus'], piv_trace, + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=4, alpha=0.7, linestyle='none', label=f'PIV ({label})') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+ + \overline{v'v'}^+$", fontsize=12) + ax.set_title("Trace Invariant (rotation-invariant)", fontsize=14) + ax.legend(fontsize=10) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Right: Ratio of components (rotation indicator) + ax = axes[1] + gt_ratio = gt_plus['uu_plus'] / (gt_plus['vv_plus'] + 1e-10) + ax.semilogx(gt_plus['y_plus'], gt_ratio, 'k-', linewidth=2.5, label='DNS', zorder=10) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + piv_ratio = piv_plus['uu_plus'] / (piv_plus['vv_plus'] + 1e-10) + ax.semilogx(piv_plus['y_plus'], piv_ratio, + color=colors[i % len(colors)], marker=markers[i % len(markers)], + markersize=4, alpha=0.7, linestyle='none', label=f'PIV ({label})') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+ / \overline{v'v'}^+$", fontsize=12) + ax.set_title("Stress Ratio (rotation indicator)", fontsize=14) + ax.legend(fontsize=10) + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 10) + ax.grid(True, alpha=0.3) + + fig.suptitle("Rotation Diagnostic: If trace matches but ratio differs, rotation problem exists", fontsize=12, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'trace_invariant_combined.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 8: Residuals (PIV - Ref) vs y+ - ALL WINDOWS + # ========================================================================== + fig, axes = plt.subplots(2, 3, figsize=(18, 12)) + + # Interpolate ground truth + gt_interp_fn = {} + for var in ['U_plus', 'V_plus', 'uu_plus', 'vv_plus', 'uv_plus']: + gt_interp_fn[var] = interp1d(gt_plus['y_plus'], gt_plus[var], kind='linear', + bounds_error=False, fill_value=np.nan) + + # Top row: velocity residuals + vel_configs = [ + ('U_plus', r"$U^+_{\mathrm{PIV}} - U^+_{\mathrm{Ref}}$", + 'Mean Streamwise Velocity Residual', 1), + ('V_plus', r"$V^+_{\mathrm{PIV}} - V^+_{\mathrm{Ref}}$", + 'Mean Wall-Normal Velocity Residual', 1), + ] + for ax, (var, ylabel, title, sign) in zip(axes[0, :2], vel_configs): + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + c = colors[i % len(colors)] + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + ax.plot(piv_plus['y_plus'], residual, + color=c, marker=markers[i % len(markers)], + markersize=2, alpha=0.15, linestyle='none', zorder=2) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.plot(yp_s, r_s, color=c, linewidth=2, + label=f'PIV ({label})', zorder=5-i*0.1) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + axes[0, 2].set_visible(False) # Empty top-right panel + + # Bottom row: stress residuals + stress_configs = [ + ('uu_plus', r"$\overline{u'u'}^+_{\mathrm{PIV}} - \overline{u'u'}^+_{\mathrm{Ref}}$", + 'Streamwise Normal Stress Residual', 1), + ('vv_plus', r"$\overline{v'v'}^+_{\mathrm{PIV}} - \overline{v'v'}^+_{\mathrm{Ref}}$", + 'Wall-Normal Normal Stress Residual', 1), + ('uv_plus', r"$-\overline{u'v'}^+_{\mathrm{PIV}} - (-\overline{u'v'}^+_{\mathrm{Ref}})$", + 'Shear Stress Residual', -1), + ] + for ax, (var, ylabel, title, sign) in zip(axes[1, :], stress_configs): + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + c = colors[i % len(colors)] + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + ax.plot(piv_plus['y_plus'], residual, + color=c, marker=markers[i % len(markers)], + markersize=2, alpha=0.15, linestyle='none', zorder=2) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.plot(yp_s, r_s, color=c, linewidth=2, + label=f'PIV ({label})', zorder=5-i*0.1) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'residuals_combined.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 9: Noise floor vs gradient correction decomposition - ALL WINDOWS + # ========================================================================== + fig, axes = plt.subplots(1, 3, figsize=(18, 6)) + + # Left: Noise floor (v'v' residual) — all windows + ax = axes[0] + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + c = colors[i % len(colors)] + vv_res = piv_plus['vv_plus'] - gt_interp_fn['vv_plus'](piv_plus['y_plus']) + ax.plot(piv_plus['y_plus'], vv_res, + color=c, marker=markers[i % len(markers)], + markersize=2, alpha=0.15, linestyle='none', zorder=2) + yp_s, r_s = log_smooth(piv_plus['y_plus'], vv_res) + ax.plot(yp_s, r_s, color=c, linewidth=2, + label=f'PIV ({label})', zorder=5-i*0.1) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{v'v'}^+_{\mathrm{PIV}} - \overline{v'v'}^+_{\mathrm{Ref}}$", fontsize=12) + ax.set_title('Noise Floor (isotropic)', fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Middle: Gradient-only residual (u'u' - v'v') — all windows + ax = axes[1] + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + for i, res in enumerate(all_results): + piv_plus = res['piv_plus'] + label = res['window_label'] + c = colors[i % len(colors)] + uu_res = piv_plus['uu_plus'] - gt_interp_fn['uu_plus'](piv_plus['y_plus']) + vv_res = piv_plus['vv_plus'] - gt_interp_fn['vv_plus'](piv_plus['y_plus']) + grad_only = uu_res - vv_res + ax.plot(piv_plus['y_plus'], grad_only, + color=c, marker=markers[i % len(markers)], + markersize=2, alpha=0.15, linestyle='none', zorder=2) + yp_s, r_s = log_smooth(piv_plus['y_plus'], grad_only) + ax.plot(yp_s, r_s, color=c, linewidth=2, + label=f'PIV ({label})', zorder=5-i*0.1) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Gradient-only residual$^+$", fontsize=12) + ax.set_title(r"Gradient Correction Residual ($u'u' - v'v'$ removes noise)", fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Right: All three overlaid for the finest window + ax = axes[2] + finest = all_results[-1] # Last (finest) window + piv_plus = finest['piv_plus'] + label = finest['window_label'] + uu_res = piv_plus['uu_plus'] - gt_interp_fn['uu_plus'](piv_plus['y_plus']) + vv_res = piv_plus['vv_plus'] - gt_interp_fn['vv_plus'](piv_plus['y_plus']) + grad_only = uu_res - vv_res + + ax.plot(piv_plus['y_plus'], uu_res, 'ro', markersize=2, alpha=0.1) + yp_s, r_s = log_smooth(piv_plus['y_plus'], uu_res) + ax.plot(yp_s, r_s, 'r-', linewidth=2, label=r"$u'u'$ residual (total)") + + ax.plot(piv_plus['y_plus'], vv_res, 'bo', markersize=2, alpha=0.1) + yp_s, r_s = log_smooth(piv_plus['y_plus'], vv_res) + ax.plot(yp_s, r_s, 'b-', linewidth=2, label=r"$v'v'$ residual (noise floor)") + + yp_s, r_s = log_smooth(piv_plus['y_plus'], grad_only) + ax.plot(yp_s, r_s, 'g--', linewidth=2, label=r"$u'u' - v'v'$ residual (gradient only)") + + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Residual$^+$", fontsize=12) + ax.set_title(f'Decomposition ({label}): Total = Noise + Gradient', fontsize=14) + ax.legend(fontsize=9) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'noise_gradient_decomposition_combined.png', dpi=150) + plt.close(fig) + + print(f"\nCombined plots saved to: {output_dir}") + + +def main_multi_run(mode='ensemble', run_indices=None, window_sizes=None, run_labels=None, gt_dir=None, base_dir=None, ensemble_dir=None, y_plus_offset=0.0, num_frames=1000, output_dir_override=None, show_fit_lines=False): + """ + Main benchmark comparison function for multiple runs/window sizes. + + Parameters + ---------- + mode : str + 'instantaneous' or 'ensemble' + run_indices : list of int + List of run indices (0-based) to process + window_sizes : list of int + Corresponding window sizes for labels (e.g., [16, 8, 6, 4]) + run_labels : list of str, optional + Custom labels for output folders (e.g., ['run_1', 'run_2', 'run_3']) + gt_dir : Path, optional + Ground truth directory. Defaults to script_dir/ground_truth/ensemble_statistics + base_dir : Path, optional + Base directory containing PIV results. Defaults to window_validation folder. + ensemble_dir : Path, optional + Direct path to ensemble directory containing ensemble_result.mat and coordinates.mat. + If provided, overrides base_dir for ensemble mode. + y_plus_offset : float, optional + Offset to add to y+ coordinates (for calibration correction) + """ + # Paths + script_dir = Path(__file__).parent + if gt_dir is None: + raise ValueError("gt_dir is required. Please provide the ground truth directory path.") + gt_dir = Path(gt_dir) + + if mode == 'ensemble': + if ensemble_dir is not None: + ensemble_dir = Path(ensemble_dir) + ensemble_path = ensemble_dir / 'ensemble_result.mat' + coords_path = ensemble_dir / 'coordinates.mat' + elif base_dir is not None: + base_dir = Path(base_dir) + ensemble_path = base_dir / f'calibrated_piv/{num_frames}/Cam1/ensemble/ensemble_result.mat' + coords_path = base_dir / f'calibrated_piv/{num_frames}/Cam1/ensemble/coordinates.mat' + else: + raise ValueError("Either ensemble_dir or base_dir must be provided for ensemble mode.") + output_dir = output_dir_override or (script_dir / 'benchmark_results_ensemble') + else: + if base_dir is None: + raise ValueError("base_dir is required for instantaneous mode.") + base_dir = Path(base_dir) + stats_path = base_dir / f'statistics/{num_frames}/Cam1/instantaneous/mean_stats/mean_stats.mat' + output_dir = output_dir_override or (script_dir / 'benchmark_results') + + print("=" * 70) + print(f"PIV BENCHMARK COMPARISON ({mode.upper()}) - MULTI-RUN") + print("=" * 70) + print(f"Processing runs: {run_indices}") + print(f"Window sizes: {window_sizes}") + + # Load common data - auto-detect file names + print("\n[1] Loading wall units...") + wall_units_file = gt_dir / 'wall_units.mat' + if not wall_units_file.exists(): + wall_units_file = gt_dir / 'diagnostics.mat' + if not wall_units_file.exists(): + wall_units_file = gt_dir / 'direct_stats.mat' + wall_units = load_wall_units(wall_units_file) + print(f" u_tau = {wall_units['u_tau']:.4f} mm/s") + print(f" nu = {wall_units['nu']:.4f} mm²/s") + print(f" delta_nu = {wall_units['delta_nu']:.4f} mm") + print(f" Re_tau = {wall_units['Re_tau']:.0f}") + + print("\n[2] Loading ground truth...") + profiles_file = gt_dir / 'profiles.mat' + if not profiles_file.exists(): + profiles_file = gt_dir / 'ensemble_statistics_full.mat' + if not profiles_file.exists(): + profiles_file = gt_dir / 'direct_stats.mat' + gt = load_ground_truth(profiles_file, wall_units_path=wall_units_file) + print(f" y+ range: {gt['y_plus'].min():.1f} to {gt['y_plus'].max():.1f}") + + # Ground truth in wall units + gt_plus = { + 'y_plus': gt['y_plus'], + 'U_plus': gt['U_plus'], + 'V_plus': gt['V'] / wall_units['u_tau'], + 'uu_plus': gt['uu_plus'], + 'vv_plus': gt['vv_plus'], + 'uv_plus': gt['uv_plus'], + } + # Thread CI bounds through if available + for ci_key in ['U_plus_ci_lo', 'U_plus_ci_hi', 'V_plus_ci_lo', 'V_plus_ci_hi', + 'uu_plus_ci_lo', 'uu_plus_ci_hi', 'vv_plus_ci_lo', 'vv_plus_ci_hi', + 'uv_plus_ci_lo', 'uv_plus_ci_hi']: + if ci_key in gt: + gt_plus[ci_key] = gt[ci_key] + + # Process each run + all_results = [] + if run_labels is None: + run_labels = [f'{ws}x{ws}' for ws in window_sizes] + for i, (run_idx, win_size) in enumerate(zip(run_indices, window_sizes)): + window_label = f'{win_size}x{win_size}' + run_output_dir = output_dir / run_labels[i] + + print(f"\n{'='*70}") + print(f"Processing Run {run_idx+1} (Window: {window_label})") + print('='*70) + + try: + if mode == 'ensemble': + piv = load_ensemble_statistics(ensemble_path, coords_path, run_idx=run_idx) + else: + piv = load_piv_statistics(stats_path, run_idx=run_idx) + + print(f" Grid size: {piv['ux'].shape}") + print(f" ux range: {np.nanmin(piv['ux'])*1000:.2f} to {np.nanmax(piv['ux'])*1000:.2f} mm/s") + + # Compute profiles + piv_profiles = compute_piv_profiles(piv, x_exclude_vectors=4) + print(f" y range: {piv_profiles['y_mm'].min():.2f} to {piv_profiles['y_mm'].max():.2f} mm") + + # Convert to wall units + y_offset_mm = -piv_profiles['y_mm'].min() + piv_plus = convert_to_wall_units(piv_profiles, wall_units, y_offset_mm=y_offset_mm) + piv_plus['y_plus'] = piv_plus['y_plus'] + 1.0 # shift y+ by +1 + # Apply additional y+ offset if specified + if y_plus_offset != 0.0: + piv_plus['y_plus'] = piv_plus['y_plus'] + y_plus_offset + print(f" y+ offset applied: {y_plus_offset:+.1f}") + print(f" y+ range: {piv_plus['y_plus'].min():.1f} to {piv_plus['y_plus'].max():.1f} (y+ +1 applied)") + + # Compute errors + errors = compute_errors(piv_plus, gt_plus, y_plus_range=(10, 500)) + + # Print error summary + if 'U_plus' in errors: + print(f" U+ R² = {errors['U_plus']['r2']:.4f}, RMS = {errors['U_plus']['rms_rel']:.1f}%") + if 'uu_plus' in errors: + print(f" uu+ R² = {errors['uu_plus']['r2']:.4f}") + + # Generate individual plots + plot_comparison(piv_plus, gt_plus, wall_units, errors, run_output_dir, + window_label=window_label, show_fit_lines=show_fit_lines) + plot_combined_stresses(piv_plus, gt_plus, wall_units, errors, run_output_dir, + window_label=window_label) + + # Store for combined plot + all_results.append({ + 'piv_plus': piv_plus, + 'errors': errors, + 'window_label': window_label, + 'window_size': win_size, + }) + + except Exception as e: + print(f" ERROR processing run {run_idx}: {e}") + import traceback + traceback.print_exc() + + # Generate combined plots if we have multiple results + if len(all_results) > 1: + print(f"\n{'='*70}") + print("Generating combined comparison plots...") + print('='*70) + plot_combined_comparison(all_results, gt_plus, wall_units, output_dir, + show_fit_lines=show_fit_lines) + + # Print final summary + print("\n" + "=" * 70) + print("BENCHMARK SUMMARY") + print("=" * 70) + print(f"\n{'Window':<12} {'U+ R²':<10} {'U+ RMS%':<10} {'uu+ R²':<10} {'vv+ R²':<10} {'-uv+ R²':<10}") + print("-" * 62) + for res in all_results: + errs = res['errors'] + u_r2 = errs.get('U_plus', {}).get('r2', np.nan) + u_rms = errs.get('U_plus', {}).get('rms_rel', np.nan) + uu_r2 = errs.get('uu_plus', {}).get('r2', np.nan) + vv_r2 = errs.get('vv_plus', {}).get('r2', np.nan) + uv_r2 = errs.get('uv_plus', {}).get('r2', np.nan) + print(f"{res['window_label']:<12} {u_r2:<10.4f} {u_rms:<10.1f} {uu_r2:<10.4f} {vv_r2:<10.4f} {uv_r2:<10.4f}") + + print("\n" + "=" * 70) + print("BENCHMARK COMPLETE") + print("=" * 70) + + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser(description='PIV Benchmark Comparison') + parser.add_argument('--mode', '-m', choices=['instantaneous', 'ensemble'], + default='instantaneous', help='PIV mode (default: instantaneous)') + parser.add_argument('--runs', '-r', type=str, default=None, + help='Comma-separated run indices (0-based), e.g., "0,1,2"') + parser.add_argument('--windows', '-w', type=str, default=None, + help='Comma-separated window sizes for labels, e.g., "32,8,8"') + parser.add_argument('--labels', '-l', type=str, default=None, + help='Comma-separated output folder labels, e.g., "run_1,run_2,run_3"') + parser.add_argument('--gt-dir', '-g', type=str, required=True, + help='Ground truth directory path (required)') + parser.add_argument('--base-dir', '-b', type=str, default=None, + help='Base directory containing PIV results') + parser.add_argument('--ensemble-dir', '-e', type=str, default=None, + help='Direct path to ensemble directory containing ensemble_result.mat and coordinates.mat') + parser.add_argument('--y-plus-offset', '-y', type=float, default=0.0, + help='Offset to add to y+ coordinates (calibration correction)') + parser.add_argument('--num-frames', '-n', type=int, default=1000, + help='Frame count subdirectory in paths (default: 1000)') + parser.add_argument('--output-dir', '-o', type=str, default=None, + help='Custom output directory for results') + parser.add_argument('--show-fit-lines', action='store_true', default=False, + help='Show log-law and viscous sublayer reference lines on U+ plots') + args = parser.parse_args() + + gt_dir = Path(args.gt_dir) + base_dir = Path(args.base_dir) if args.base_dir else None + ensemble_dir = Path(args.ensemble_dir) if args.ensemble_dir else None + output_dir_override = Path(args.output_dir) if args.output_dir else None + + if args.runs and args.windows: + run_indices = [int(r) for r in args.runs.split(',')] + window_sizes = [int(w) for w in args.windows.split(',')] + run_labels = args.labels.split(',') if args.labels else None + main_multi_run(mode=args.mode, run_indices=run_indices, window_sizes=window_sizes, + run_labels=run_labels, gt_dir=gt_dir, base_dir=base_dir, + ensemble_dir=ensemble_dir, y_plus_offset=args.y_plus_offset, + num_frames=args.num_frames, output_dir_override=output_dir_override, + show_fit_lines=args.show_fit_lines) + else: + main(mode=args.mode, gt_dir=gt_dir, base_dir=base_dir, ensemble_dir=ensemble_dir, + num_frames=args.num_frames, output_dir_override=output_dir_override, + show_fit_lines=args.show_fit_lines) diff --git a/scripts/cross_method_comparison.py b/scripts/cross_method_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1f5f4b5b10e64b275bad928201b6cb69b03c1a --- /dev/null +++ b/scripts/cross_method_comparison.py @@ -0,0 +1,611 @@ +#!/usr/bin/env python3 +""" +Cross-method PIV comparison: Instantaneous vs Ensemble vs Stereo. + +Publication-quality plots comparing one pass from each method against DNS +ground truth. Designed for academic journal submission. + +Produces: + 1. mean_velocity_comparison.png — U+ vs y+ (semi-log) + 2. stresses_comparison.png — 1×3 subplots (uu+, vv+, −uv+) + 3. combined_stresses_comparison.png — all stresses on one axis + +Usage (Python API): + from cross_method_comparison import compare_methods + compare_methods( + gt_dir='path/to/ground_truth', + inst_stats_path='path/to/mean_stats.mat', + ens_ensemble_path='path/to/ensemble_result.mat', + ens_coords_path='path/to/coordinates.mat', + stereo_stats_path='path/to/stereo/mean_stats.mat', + output_dir='path/to/output', + ... + ) +""" + +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-quality font setup ──────────────────────────────────────────── +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': 12, + 'axes.titlesize': 13, + 'legend.fontsize': 11, + '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 ──────────────────────────────────────── +METHOD_STYLES = { + 'Instantaneous': {'color': '#0072B2', 'marker': 'o'}, # blue + 'Ensemble': {'color': '#D55E00', 'marker': 's'}, # vermillion + 'Stereo': {'color': '#009E73', 'marker': '^'}, # teal +} +DNS_COLOR = 'k' + + +def _get_style(name): + """Look up style by method name prefix (e.g. 'Instantaneous (16x16)' → Instantaneous).""" + for key in METHOD_STYLES: + if name.startswith(key): + return METHOD_STYLES[key] + return {'color': 'gray', 'marker': 'x'} + + +# ============================================================================= +# Data loading helpers (reuse from benchmark_comparison where possible) +# ============================================================================= + +def _load_wall_units(gt_dir): + """Load wall units from ground truth directory (auto-detect format).""" + from benchmark_comparison import load_wall_units + gt_dir = Path(gt_dir) + for name in ('wall_units.mat', 'diagnostics.mat', 'direct_stats.mat'): + p = gt_dir / name + if p.exists(): + return load_wall_units(p) + raise FileNotFoundError(f"No wall-units file found in {gt_dir}") + + +def _load_ground_truth(gt_dir): + """Load ground truth profiles + wall units.""" + from benchmark_comparison import load_ground_truth + gt_dir = Path(gt_dir) + wu = _load_wall_units(gt_dir) + + 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 + else: + raise FileNotFoundError(f"No ground-truth profiles in {gt_dir}") + + gt_plus = { + 'y_plus': gt['y_plus'], + 'U_plus': gt['U_plus'], + 'V_plus': gt['V'] / wu['u_tau'], + 'uu_plus': gt['uu_plus'], + 'vv_plus': gt['vv_plus'], + 'uv_plus': gt['uv_plus'], + } + # Thread CI bounds if available + for key in ('U_plus_ci_lo', 'U_plus_ci_hi', + 'uu_plus_ci_lo', 'uu_plus_ci_hi', + 'vv_plus_ci_lo', 'vv_plus_ci_hi', + 'uv_plus_ci_lo', 'uv_plus_ci_hi'): + if key in gt: + gt_plus[key] = gt[key] + return gt_plus, wu + + +def _profiles_from_regular_grid(piv_data, x_exclude_vectors=4): + """X-averaged profiles from a regular (no NaN border) grid.""" + from benchmark_comparison import compute_piv_profiles + return compute_piv_profiles(piv_data, x_exclude_vectors=x_exclude_vectors) + + +def _profiles_from_stereo_grid(piv_struct, coords_struct, x_exclude_vectors=4): + """X-averaged profiles from a stereo grid with NaN borders.""" + x = coords_struct.x + y = coords_struct.y + + # Find valid subgrid + 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_col = y[:, mid_col] + valid_rows = ~np.isnan(y_col) + y_unique = y_col[valid_rows] + + # X exclusion + x_start = col_indices[0] + x_exclude_vectors + x_end = col_indices[-1] - x_exclude_vectors + 1 + x_mask = np.zeros(x.shape[1], dtype=bool) + x_mask[x_start:x_end] = True + + def _avg(field): + return np.nanmean(field[valid_rows][:, x_mask], axis=1) + + return { + 'y_mm': y_unique, + 'U': _avg(piv_struct.ux) * 1000, + 'V': _avg(piv_struct.uy) * 1000, + 'uu': _avg(piv_struct.uu) * 1e6, + 'vv': _avg(piv_struct.vv) * 1e6, + 'uv': _avg(piv_struct.uv) * 1e6, + } + + +def _to_wall_units(profiles, wall_units, y_plus_offset): + """Convert profiles to plus units with y-offset.""" + from benchmark_comparison import convert_to_wall_units + y_offset_mm = -profiles['y_mm'].min() + piv_plus = convert_to_wall_units(profiles, wall_units, y_offset_mm=y_offset_mm) + piv_plus['y_plus'] = piv_plus['y_plus'] + 1.0 + y_plus_offset + return piv_plus + + +def load_instantaneous(stats_path, run_idx, wall_units, y_plus_offset, + x_exclude=4): + """Load instantaneous PIV and return wall-unit profiles.""" + from benchmark_comparison import load_piv_statistics + piv = load_piv_statistics(Path(stats_path), run_idx=run_idx) + profiles = _profiles_from_regular_grid(piv, x_exclude_vectors=x_exclude) + return _to_wall_units(profiles, wall_units, y_plus_offset) + + +def load_ensemble(ensemble_path, coords_path, run_idx, wall_units, + y_plus_offset, x_exclude=4): + """Load ensemble PIV and return wall-unit profiles.""" + from benchmark_comparison import load_ensemble_statistics + piv = load_ensemble_statistics(Path(ensemble_path), Path(coords_path), + run_idx=run_idx) + profiles = _profiles_from_regular_grid(piv, x_exclude_vectors=x_exclude) + return _to_wall_units(profiles, wall_units, y_plus_offset) + + +def load_stereo(stats_path, run_idx, wall_units, y_plus_offset, + x_exclude=4, trim_top=0): + """Load stereo PIV (NaN-aware) and return wall-unit profiles.""" + stats = sio.loadmat(str(stats_path), squeeze_me=True, struct_as_record=False) + piv = stats['piv_result'][run_idx] + coords = stats['coordinates'][run_idx] + profiles = _profiles_from_stereo_grid(piv, coords, x_exclude_vectors=x_exclude) + + if trim_top > 0 and len(profiles['y_mm']) > trim_top: + y = profiles['y_mm'] + # Trim from the high-y end + if y[0] > y[-1]: + sl = slice(trim_top, None) + else: + sl = slice(None, -trim_top) + profiles = {k: v[sl] if isinstance(v, np.ndarray) else v + for k, v in profiles.items()} + + return _to_wall_units(profiles, wall_units, y_plus_offset) + + +# ============================================================================= +# Plotting +# ============================================================================= + +def _ci_band(ax, y_plus, lo, hi, sign=1, **kwargs): + """Shade a 95 % confidence-interval band.""" + if sign == -1: + lo, hi = hi, lo + ax.fill_between(y_plus, sign * lo, sign * hi, + color=DNS_COLOR, alpha=0.10, linewidth=0, **kwargs) + + +def plot_velocity_comparison(methods, gt_plus, wall_units, output_dir, title_suffix=''): + """ + U+ vs y+ — one marker series per method, DNS as reference line. + + Parameters + ---------- + methods : dict + {method_name: piv_plus_dict} (keys must be in METHOD_STYLES) + gt_plus : dict + Ground truth in wall units + wall_units : dict + output_dir : Path + """ + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + Re_tau = wall_units['Re_tau'] + + fig, ax = plt.subplots(figsize=(7, 5)) + + # DNS reference + has_ci = 'U_plus_ci_lo' in gt_plus + if has_ci: + _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) + + # PIV methods + for name, piv_plus in methods.items(): + sty = _get_style(name) + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], + color=sty['color'], marker=sty['marker'], + markersize=3.5, alpha=0.7, linestyle='none', + label=name, zorder=5) + + ax.set_xlabel(r'$y^+$') + ax.set_ylabel(r'$U^+$') + title = 'Mean Velocity Profile Comparison with DNS' + if title_suffix: + title += f' ({title_suffix})' + ax.set_title(title) + 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() + fig.savefig(output_dir / 'mean_velocity_comparison.png') + plt.close(fig) + print(f" Saved: {output_dir / 'mean_velocity_comparison.png'}") + + +def plot_stresses_subplots(methods, gt_plus, wall_units, output_dir, title_suffix=''): + """ + 1×3 subplot: uu+, vv+, −uv+ — one marker series per method per panel. + """ + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + Re_tau = wall_units['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) + + # PIV methods + for name, piv_plus in methods.items(): + sty = _get_style(name) + ax.plot(piv_plus['y_plus'], sign * piv_plus[var], + color=sty['color'], marker=sty['marker'], + markersize=2.5, alpha=0.65, linestyle='none', + label=name, zorder=5) + + 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) + + # Single shared legend below the title + handles, labels = axes[0].get_legend_handles_labels() + fig.legend(handles, labels, loc='upper center', ncol=len(methods) + 1, + bbox_to_anchor=(0.5, 1.02), framealpha=0.9) + + suptitle = 'Reynolds Stresses Method Comparison with DNS' + if title_suffix: + suptitle += f' ({title_suffix})' + fig.suptitle(suptitle, y=1.08) + fig.tight_layout() + fig.subplots_adjust(top=0.88) + fig.savefig(output_dir / 'stresses_comparison.png') + plt.close(fig) + print(f" Saved: {output_dir / 'stresses_comparison.png'}") + + +def plot_combined_stresses(methods, gt_plus, wall_units, output_dir, title_suffix=''): + """ + All stresses on one axis — line styles distinguish components, + colours distinguish methods. + """ + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + Re_tau = wall_units['Re_tau'] + has_ci = 'uu_plus_ci_lo' in gt_plus + + component_styles = { + 'uu_plus': {'linestyle': '-', 'label_tex': r"$\overline{u'u'}^+$", 'sign': 1}, + 'vv_plus': {'linestyle': '--', 'label_tex': r"$\overline{v'v'}^+$", 'sign': 1}, + 'uv_plus': {'linestyle': ':', 'label_tex': r"$-\overline{u'v'}^+$", 'sign': -1}, + } + + fig, ax = plt.subplots(figsize=(7, 5)) + + # ── DNS reference lines ────────────────────────────────────────────── + for var, csty in component_styles.items(): + sign = csty['sign'] + # CI band + 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['linestyle'], + zorder=10) + + # ── PIV method markers ─────────────────────────────────────────────── + for name, piv_plus in methods.items(): + sty = _get_style(name) + for var, csty in component_styles.items(): + sign = csty['sign'] + ax.plot(piv_plus['y_plus'], sign * piv_plus[var], + color=sty['color'], marker=sty['marker'], + markersize=2.5, alpha=0.55, linestyle='none', + zorder=5) + + # ── Build a clean two-part legend ──────────────────────────────────── + # Part 1: method colours (dummy markers) + method_handles = [] + for name in methods: + sty = _get_style(name) + h = plt.Line2D([], [], color=sty['color'], marker=sty['marker'], + markersize=5, linestyle='none', label=name) + method_handles.append(h) + # DNS entry + dns_handle = plt.Line2D([], [], color=DNS_COLOR, linewidth=1.8, + linestyle='-', label='DNS') + method_handles.insert(0, dns_handle) + + # Part 2: component line styles (black dummy lines) + comp_handles = [] + for var, csty in component_styles.items(): + h = plt.Line2D([], [], color='gray', linewidth=1.5, + linestyle=csty['linestyle'], label=csty['label_tex']) + comp_handles.append(h) + + 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$^+$') + title = 'Reynolds Stresses Method Comparison with DNS' + if title_suffix: + title += f' ({title_suffix})' + ax.set_title(title) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.25, linewidth=0.5) + + fig.tight_layout() + fig.savefig(output_dir / 'combined_stresses_comparison.png') + plt.close(fig) + print(f" Saved: {output_dir / 'combined_stresses_comparison.png'}") + + +# ============================================================================= +# Error summary +# ============================================================================= + +def print_error_table(methods, gt_plus): + """Print R² summary for all methods.""" + from benchmark_comparison import compute_errors + + header = f"{'Method':<18} {'U+ R²':<10} {'U+ RMS%':<10} {'uu+ R²':<10} {'vv+ R²':<10} {'-uv+ R²':<10}" + print("\n" + header) + print("-" * len(header)) + + for name, piv_plus in methods.items(): + errs = compute_errors(piv_plus, gt_plus, y_plus_range=(10, 500)) + u_r2 = errs.get('U_plus', {}).get('r2', float('nan')) + u_rms = errs.get('U_plus', {}).get('rms_rel', float('nan')) + uu_r2 = errs.get('uu_plus', {}).get('r2', float('nan')) + vv_r2 = errs.get('vv_plus', {}).get('r2', float('nan')) + uv_r2 = errs.get('uv_plus', {}).get('r2', float('nan')) + print(f"{name:<18} {u_r2:<10.4f} {u_rms:<10.1f} {uu_r2:<10.4f} {vv_r2:<10.4f} {uv_r2:<10.4f}") + + print() + + +# ============================================================================= +# Main entry point +# ============================================================================= + +def compare_methods( + gt_dir, + output_dir, + # Instantaneous + inst_stats_path=None, inst_run_idx=3, inst_y_offset=3.0, + # Ensemble + ens_ensemble_path=None, ens_coords_path=None, + ens_run_idx=4, ens_y_offset=0.8, + # Stereo + stereo_stats_path=None, stereo_run_idx=3, stereo_y_offset=0.8, + stereo_trim_top=10, + # Shared + x_exclude=4, + title_suffix='', + inst_window_label=None, + ens_window_label=None, + stereo_window_label=None, + trim_near_wall=0, +): + """ + Compare one pass from each method against DNS ground truth. + + Parameters + ---------- + gt_dir : str or Path + Directory containing ground truth (direct_stats.mat etc.) + output_dir : str or Path + Where to save figures. + inst_stats_path : str or Path, optional + Path to instantaneous mean_stats.mat + inst_run_idx : int + 0-based run index for instantaneous + inst_y_offset : float + Additional y+ offset for instantaneous (on top of hardcoded +1) + ens_ensemble_path, ens_coords_path : str or Path, optional + Paths to ensemble_result.mat and coordinates.mat + ens_run_idx : int + 0-based run index for ensemble + ens_y_offset : float + Additional y+ offset for ensemble + stereo_stats_path : str or Path, optional + Path to stereo mean_stats.mat + stereo_run_idx : int + 0-based run index for stereo + stereo_y_offset : float + Additional y+ offset for stereo + stereo_trim_top : int + Trim this many high-y points from stereo (NaN border cleanup) + x_exclude : int + Vectors to exclude from each x-edge + """ + gt_plus, wu = _load_ground_truth(gt_dir) + print(f"DNS: Re_tau={wu['Re_tau']:.0f}, u_tau={wu['u_tau']:.4f} mm/s") + + methods = {} + + def _trim(piv_plus, n): + """Remove n lowest y+ points (nearest wall).""" + if n <= 0: + return piv_plus + yp = piv_plus['y_plus'] + if yp[0] > yp[-1]: + # Sorted high-to-low: wall is at the end + sl = slice(None, -n if n > 0 else None) + else: + # Sorted low-to-high: wall is at the start + sl = slice(n, None) + return {k: (v[sl] if isinstance(v, np.ndarray) and len(v) > n else v) + for k, v in piv_plus.items()} + + if inst_stats_path is not None: + label = f"Instantaneous ({inst_window_label})" if inst_window_label else "Instantaneous" + print(f"\nLoading {label} (run {inst_run_idx}, y+ offset +{inst_y_offset})...") + data = load_instantaneous(inst_stats_path, inst_run_idx, wu, inst_y_offset, x_exclude) + methods[label] = _trim(data, trim_near_wall) + p = methods[label] + print(f" y+ range: {p['y_plus'].min():.1f} – {p['y_plus'].max():.1f}") + + if ens_ensemble_path is not None and ens_coords_path is not None: + label = f"Ensemble ({ens_window_label})" if ens_window_label else "Ensemble" + print(f"\nLoading {label} (run {ens_run_idx}, y+ offset +{ens_y_offset})...") + methods[label] = load_ensemble( + ens_ensemble_path, ens_coords_path, + ens_run_idx, wu, ens_y_offset, x_exclude) + p = methods[label] + print(f" y+ range: {p['y_plus'].min():.1f} – {p['y_plus'].max():.1f}") + + if stereo_stats_path is not None: + label = f"Stereo ({stereo_window_label})" if stereo_window_label else "Stereo" + print(f"\nLoading {label} (run {stereo_run_idx}, y+ offset +{stereo_y_offset}, " + f"trim top {stereo_trim_top})...") + data = load_stereo( + stereo_stats_path, stereo_run_idx, wu, stereo_y_offset, + x_exclude, stereo_trim_top) + methods[label] = _trim(data, trim_near_wall) + p = methods[label] + print(f" y+ range: {p['y_plus'].min():.1f} – {p['y_plus'].max():.1f}") + + if not methods: + raise ValueError("No data loaded — provide at least one method path.") + + print_error_table(methods, gt_plus) + + print("Generating plots...") + output_dir = Path(output_dir) + plot_velocity_comparison(methods, gt_plus, wu, output_dir, title_suffix=title_suffix) + plot_stresses_subplots(methods, gt_plus, wu, output_dir, title_suffix=title_suffix) + plot_combined_stresses(methods, gt_plus, wu, output_dir, title_suffix=title_suffix) + print("Done.") + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser( + description='Cross-method PIV comparison (Instantaneous / Ensemble / Stereo)') + + parser.add_argument('--gt-dir', '-g', required=True, + help='Ground truth directory') + parser.add_argument('--output-dir', '-o', required=True, + help='Output directory for figures') + + # Instantaneous + parser.add_argument('--inst-stats', type=str, default=None, + help='Path to instantaneous mean_stats.mat') + parser.add_argument('--inst-run', type=int, default=3, + help='0-based run index (default: 3)') + parser.add_argument('--inst-y-offset', type=float, default=3.0, + help='Additional y+ offset (default: 3.0)') + + # Ensemble + parser.add_argument('--ens-dir', type=str, default=None, + help='Directory with ensemble_result.mat + coordinates.mat') + parser.add_argument('--ens-run', type=int, default=4, + help='0-based run index (default: 4)') + parser.add_argument('--ens-y-offset', type=float, default=0.8, + help='Additional y+ offset (default: 0.8)') + + # Stereo + parser.add_argument('--stereo-stats', type=str, default=None, + help='Path to stereo mean_stats.mat') + parser.add_argument('--stereo-run', type=int, default=3, + help='0-based run index (default: 3)') + parser.add_argument('--stereo-y-offset', type=float, default=0.8, + help='Additional y+ offset (default: 0.8)') + parser.add_argument('--stereo-trim-top', type=int, default=10, + help='Trim N highest y points from stereo (default: 10)') + + parser.add_argument('--x-exclude', type=int, default=4, + help='Vectors to exclude from each x-edge (default: 4)') + + args = parser.parse_args() + + ens_ensemble_path = None + ens_coords_path = None + if args.ens_dir: + ens_dir = Path(args.ens_dir) + ens_ensemble_path = ens_dir / 'ensemble_result.mat' + ens_coords_path = ens_dir / 'coordinates.mat' + + compare_methods( + gt_dir=args.gt_dir, + output_dir=args.output_dir, + inst_stats_path=args.inst_stats, + inst_run_idx=args.inst_run, + inst_y_offset=args.inst_y_offset, + ens_ensemble_path=ens_ensemble_path, + ens_coords_path=ens_coords_path, + ens_run_idx=args.ens_run, + ens_y_offset=args.ens_y_offset, + stereo_stats_path=args.stereo_stats, + stereo_run_idx=args.stereo_run, + stereo_y_offset=args.stereo_y_offset, + stereo_trim_top=args.stereo_trim_top, + x_exclude=args.x_exclude, + ) diff --git a/scripts/paper_figures.py b/scripts/paper_figures.py new file mode 100644 index 0000000000000000000000000000000000000000..30bbf3986f9cc977ff3f8e398f92bbd4be7feb1d --- /dev/null +++ b/scripts/paper_figures.py @@ -0,0 +1,462 @@ +#!/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.") diff --git a/scripts/sig_configs/SIGconf_Stereo_cam1.cdl b/scripts/sig_configs/SIGconf_Stereo_cam1.cdl new file mode 100644 index 0000000000000000000000000000000000000000..7a8344ceedcaed86ef5d64bb938bde31aec2c52e --- /dev/null +++ b/scripts/sig_configs/SIGconf_Stereo_cam1.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2240 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -159.0625 ; + + r_ymax = 5 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "angular" ; + + projection_angle = 315 ; + + projection_tilt_angle = 357.61 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 0 ; + + ccd_background_std_noise = 0 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 1 ; + + seed_number2 = 100 ; + + seed_number3 = 10000 ; +} diff --git a/scripts/sig_configs/SIGconf_Stereo_cam1_noisy_A.cdl b/scripts/sig_configs/SIGconf_Stereo_cam1_noisy_A.cdl new file mode 100644 index 0000000000000000000000000000000000000000..d64846661a67af2a4a4212fac0e46a9bad46c455 --- /dev/null +++ b/scripts/sig_configs/SIGconf_Stereo_cam1_noisy_A.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2240 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -159.0625 ; + + r_ymax = 5 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "angular" ; + + projection_angle = 315 ; + + projection_tilt_angle = 357.61 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 80 ; + + ccd_background_std_noise = 16 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 1 ; + + seed_number2 = 100 ; + + seed_number3 = 10000 ; +} diff --git a/scripts/sig_configs/SIGconf_Stereo_cam1_noisy_B.cdl b/scripts/sig_configs/SIGconf_Stereo_cam1_noisy_B.cdl new file mode 100644 index 0000000000000000000000000000000000000000..6445f0fd4d02cdc5aa2a12b2f76f08b3da6d08d4 --- /dev/null +++ b/scripts/sig_configs/SIGconf_Stereo_cam1_noisy_B.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2240 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -159.0625 ; + + r_ymax = 5 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "angular" ; + + projection_angle = 315 ; + + projection_tilt_angle = 357.61 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 80 ; + + ccd_background_std_noise = 16 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 7 ; + + seed_number2 = 500 ; + + seed_number3 = 20000 ; +} diff --git a/scripts/sig_configs/SIGconf_Stereo_cam2.cdl b/scripts/sig_configs/SIGconf_Stereo_cam2.cdl new file mode 100644 index 0000000000000000000000000000000000000000..a240d09a2661407d78397dbcad3bc502de7c15da --- /dev/null +++ b/scripts/sig_configs/SIGconf_Stereo_cam2.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2240 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -159.0625 ; + + r_ymax = 5 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "angular" ; + + projection_angle = 45 ; + + projection_tilt_angle = 2.39 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 0 ; + + ccd_background_std_noise = 0 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 1 ; + + seed_number2 = 100 ; + + seed_number3 = 10000 ; +} diff --git a/scripts/sig_configs/SIGconf_Stereo_cam2_noisy_A.cdl b/scripts/sig_configs/SIGconf_Stereo_cam2_noisy_A.cdl new file mode 100644 index 0000000000000000000000000000000000000000..2d905ba58f11b158f7dde5be59d4b765fb010a22 --- /dev/null +++ b/scripts/sig_configs/SIGconf_Stereo_cam2_noisy_A.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2240 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -159.0625 ; + + r_ymax = 5 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "angular" ; + + projection_angle = 45 ; + + projection_tilt_angle = 2.39 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 80 ; + + ccd_background_std_noise = 16 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 1 ; + + seed_number2 = 100 ; + + seed_number3 = 10000 ; +} diff --git a/scripts/sig_configs/SIGconf_Stereo_cam2_noisy_B.cdl b/scripts/sig_configs/SIGconf_Stereo_cam2_noisy_B.cdl new file mode 100644 index 0000000000000000000000000000000000000000..c4a14612a37bd128c8306aa9fff9e86ca1638903 --- /dev/null +++ b/scripts/sig_configs/SIGconf_Stereo_cam2_noisy_B.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2240 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -159.0625 ; + + r_ymax = 5 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "angular" ; + + projection_angle = 45 ; + + projection_tilt_angle = 2.39 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 80 ; + + ccd_background_std_noise = 16 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 7 ; + + seed_number2 = 500 ; + + seed_number3 = 20000 ; +} diff --git a/scripts/sig_configs/sigconf_planar.cdl b/scripts/sig_configs/sigconf_planar.cdl new file mode 100644 index 0000000000000000000000000000000000000000..0df4e031f7e00d8de5af9d96253af866e6e9903a --- /dev/null +++ b/scripts/sig_configs/sigconf_planar.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2048 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -150 ; + + r_ymax = 0 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "normal" ; + + projection_angle = 0 ; + + projection_tilt_angle = 0 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 0 ; + + ccd_background_std_noise = 0 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 1 ; + + seed_number2 = 100 ; + + seed_number3 = 10000 ; +} diff --git a/scripts/sig_configs/sigconf_planar_noisy_A.cdl b/scripts/sig_configs/sigconf_planar_noisy_A.cdl new file mode 100644 index 0000000000000000000000000000000000000000..096b1a1cd4e05642df0f66ef11854adc08044463 --- /dev/null +++ b/scripts/sig_configs/sigconf_planar_noisy_A.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2048 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -150 ; + + r_ymax = 0 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "normal" ; + + projection_angle = 0 ; + + projection_tilt_angle = 0 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 80 ; + + ccd_background_std_noise = 16 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 1 ; + + seed_number2 = 100 ; + + seed_number3 = 10000 ; +} diff --git a/scripts/sig_configs/sigconf_planar_noisy_B.cdl b/scripts/sig_configs/sigconf_planar_noisy_B.cdl new file mode 100644 index 0000000000000000000000000000000000000000..39f41de2acc6226ae6836e8a19a3925e658bf287 --- /dev/null +++ b/scripts/sig_configs/sigconf_planar_noisy_B.cdl @@ -0,0 +1,373 @@ + +// ************************************************************** +// ************************************************************** +// *********** netcdf configuration file for SIG program ******* +// *********** Version 1.0 ******* +// ************************************************************** +// ************************************************************** +// ************************************************************** +// ** EUROPIV II Project ** +// ** Synthetic Image Generator ** +// ** Feb. 2001 ** +// ************************************************************** +// ** Bertrand Lecordier : Bertrand.Lecordier@coria.fr ** +// ** Jerry Westerweel : j.westerweel@wbmt.tudelft.nl ** +// *************************************************************/ + + +netcdf sig_conf { + +dimensions: + d_chaine = unlimited; + + +//********************************************* +//************************Variables *********** +//********************************************* + +variables: + + int p_dimX; + p_dimX:valid_min = 1; + p_dimX:valid_max = 4096; + p_dimX:units = "pixel"; + p_dimX:long_name = "main image width"; + + int p_dimY; + p_dimY:valid_min = 1; + p_dimY:valid_max = 4096; + p_dimY:units = "pixel"; + p_dimY:long_name = "main image height"; + + int p_dimL; + p_dimL:valid_min = 0; + p_dimL:valid_max = 1024; + p_dimL:units = "pixel"; + p_dimL:long_name = "left strip"; + + int p_dimR; + p_dimR:valid_min = 0; + p_dimR:valid_max = 1024; + p_dimR:units = "pixel"; + p_dimR:long_name = "right strip"; + + int p_dimT; + p_dimT:valid_min = 0; + p_dimT:valid_max = 1024; + p_dimT:units = "pixel"; + p_dimT:long_name = "top strip"; + + int p_dimB; + p_dimB:valid_min = 0; + p_dimB:valid_max = 1024; + p_dimB:units = "pixel"; + p_dimB:long_name = "bottom strip"; + + char periodic_flag(d_chaine); + +//********************************************* +//********************************************* +// Particle field dimension (real space) +// r_[x,y,z]min, r_[x,y,z]max defined the region of interest +// into the particle field - the particle field can be largeur +// +// The magnification factor is obtained from +// Gx = (r_xmax-r_xmin)/p_dimX (real/pixel) +// Gy = (r_ymax-r_ymin)/p_dimY (real/pixel) +// Important : Gx and Gy can be different + + // ******* X axis ************************** + double r_xmin; + r_xmin:units = "real"; + r_xmin:long_name = "x minimum"; + + double r_xmax; + r_xmax:units = "real"; + r_xmax:long_name = "x maximum"; + + // ******* Y axis ************************** + double r_ymin; + r_ymin:units = "real"; + r_ymin:long_name = "y minimum"; + + double r_ymax; + r_ymax:units = "real"; + r_ymax:long_name = "y maximum"; + + // ******* Z axis *************************** + // ** for the 2D particle (x,y), used the same value for + // ** r_zmin, r_zmin and sheet_rpos_z + double r_zmin; + r_zmin:units = "real"; + r_zmin:long_name = "z minimum"; + + double r_zmax; + r_zmax:units = "real"; + r_zmax:long_name = "z maximum"; + + +// **************************************** +// **************************************** +// Light sheet information +// **************************************** +// **************************************** + + char lsheet_type(d_chaine); + lsheet_type:long_name = "type of light sheet"; + // possible values : + // uniform + // gaussian + // triangle + // cosine + // squarecosine + + // location in the real domain of the center + // of laser sheet (perpendicular to the z axis) + double lsheet_rpos_z; + lsheet_rpos_z:units = "real"; + lsheet_rpos_z:long_name = "z location of light sheet"; + + double lsheet_rthickness; + lsheet_rthickness:valid_min = 0.0; + lsheet_rthickness:units = "real"; + lsheet_rthickness:long_name = "light sheet thickness"; + + double lsheet_wave_length; + lsheet_wave_length:valid_min = 0.0; + lsheet_wave_length:units = "real"; + lsheet_wave_length:long_name = "laser wave length"; + +// ************************************************ +// ************* Particle distribution ************ +// ************************************************ + + char part_distribution(d_chaine); + // Possible alternative + // uniform : constant diameter equal to part_mean_diam + // + // gaussian: gaussian distribution for the particle diameter + // mean diameter : part_mean_diam + // std diameter : part_std_diam + double part_min_diam; + part_min_diam:valid_min = 0.0; + part_min_diam:long_name = "minimum particle diameter"; + double part_max_diam; + part_max_diam:valid_min = 0.0; + part_max_diam:valid_max = 10.0; + part_max_diam:long_name = "maximum particle diameter"; + double part_mean_diam; + part_mean_diam:long_name= "mean particle diamete"; + double part_std_diam; + part_std_diam:long_name= "std. of distribution of particle diameter"; + +// ***************************************************** +// ************ image pattern information ************** +// ***************************************************** + + char pattern_type(d_chaine); + // possible values + // gaussian : gaussian particle shape + // circle : circle particle shape + // rectangle: rectangle particle shape + double pattern_meanx; + pattern_meanx:valid_min = 0.0; + pattern_meanx:long_name = "pattern size for the part_meanx_diam"; + double pattern_meany; + pattern_meany:valid_min = 0.0; + pattern_meany:long_name = "pattern size for the part_meany_diam"; + + +// ************************************************ +// ************ Projection information ************ +// ************************************************ + + char projection_type(d_chaine); + // possible values + // normal : Normal projection without effect of particle motion along z + // znormal : Normal projection with effect of particule motion along z + // angular : Angular projection for stereo PIV + + double projection_angle; // For angular projection + projection_angle:valid_min = 0.0; + projection_angle:valid_max = 360; + projection_angle:long_name = "Angle of view"; + double projection_tilt_angle; // For angular projection + projection_tilt_angle:valid_min = 0.0; + projection_tilt_angle:valid_max = 360; + projection_tilt_angle:long_name = "Tilt angle"; + +// ************************************************ +// ************* CCD information ************ +// ************************************************ + + // Pixel active area size : ccd_fill_ratio_x*ccd_fill_ratio_y + double ccd_fill_ratio_x; + ccd_fill_ratio_x:valid_min = 0.0; + ccd_fill_ratio_x:valid_max = 1.0; + ccd_fill_ratio_x:long_name = "X CCD fill ration"; + double ccd_fill_ratio_y; + ccd_fill_ratio_y:valid_min = 0.0; + ccd_fill_ratio_y:valid_max = 1.0; + ccd_fill_ratio_y:long_name = "Y CCD fill ration"; + double ccd_saturation_level; + ccd_saturation_level:valid_min = 0.0; + ccd_saturation_level:valid_max = 1.0; + ccd_saturation_level:long_name = "saturation level"; + + + + //****** Initial background information *******/ + + char ccd_background_type(d_chaine); + // Possible alternative + // uniform : uniform background with + // level ccd_background_mean_level + // gaussian: gaussian noise with a mean value + // equal to ccd_background_mean_level + // and a std. equal to ccd_background_std_noise + double ccd_background_mean_level; + ccd_background_mean_level:valid_min = 0; + ccd_background_mean_level:long_name = "mean initial background level"; + double ccd_background_std_noise; + ccd_background_std_noise:valid_min = 0; + ccd_background_std_noise:long_name = "std. noise for initial background"; + + double ccd_pixel_horizontal_pitch; + ccd_pixel_horizontal_pitch:valid_min = 0.0; + ccd_pixel_horizontal_pitch:units = "pixel/real"; + ccd_pixel_horizontal_pitch:long_name = "horizontal pixel pitch"; + + double ccd_pixel_vertical_pitch; + ccd_pixel_vertical_pitch:valid_min = 0.0; + ccd_pixel_vertical_pitch:units = "pixel/real"; + ccd_pixel_vertical_pitch:long_name = "vertical pixel pitch"; + + +// ************************************************* +// **********optics information ******************** +// ************************************************* + + double optic_object_distance; + optic_object_distance:long_name = "object distance"; + + double optic_image_distance; + optic_image_distance:long_name = "image distance"; + + double optic_aperture; + optic_aperture:valid_min = 1.; + optic_aperture:long_name = "optic aperture"; + + double optic_magnification; + optic_magnification:valid_min = 0.0; + optic_magnification:long_name = "optic magnification"; + + + + + +// ************************************************ +// ** initial seed numbers for the random generator +// ************************************************ + + int seed_number1; + seed_number1:valid_min = 0; + seed_number1:valid_max = 30000; + seed_number1:long_name = "seed number 1"; + + int seed_number2; + seed_number2:valid_min = 0; + seed_number2:valid_max = 30000; + seed_number2:long_name = "seed number 2"; + + int seed_number3; + seed_number3:valid_min = 0; + seed_number3:valid_max = 30000; + seed_number3:long_name = "seed number 3"; +data: + + p_dimX = 2048 ; + + p_dimY = 2048 ; + + p_dimL = 0 ; + + p_dimR = 0 ; + + p_dimT = 0 ; + + p_dimB = 0 ; + + periodic_flag = "no_periodic" ; + + r_xmin = 0 ; + + r_xmax = 150; + + r_ymin = -150 ; + + r_ymax = 0 ; + + r_zmin = -0.6 ; + + r_zmax = 0.6 ; + + lsheet_type = "uniform" ; + + lsheet_rpos_z = 0 ; + + lsheet_rthickness = 1.2 ; + + lsheet_wave_length = 532e-9 ; + + part_distribution = "uniform" ; + + part_min_diam = 0.7 ; + + part_max_diam = 0.7; + + part_mean_diam = 0.7 ; + + part_std_diam = 0; + + pattern_type = "gaussian" ; + + pattern_meanx = 1.274; + + pattern_meany = 1.274 ; + + projection_type = "normal" ; + + projection_angle = 0 ; + + projection_tilt_angle = 0 ; + + ccd_fill_ratio_x = 1 ; + + ccd_fill_ratio_y = 1 ; + + ccd_saturation_level = 1 ; + + ccd_background_type = "gaussian" ; + + ccd_background_mean_level = 80 ; + + ccd_background_std_noise = 16 ; + + ccd_pixel_horizontal_pitch = 327.68 ; + + ccd_pixel_vertical_pitch = 327.68 ; + + optic_object_distance = 5000 ; + + optic_image_distance = 208.5 ; + + optic_aperture = 2 ; + + optic_magnification = 0.0417; + + seed_number1 = 7 ; + + seed_number2 = 500 ; + + seed_number3 = 20000 ; +} diff --git a/scripts/stereo_benchmark_comparison.py b/scripts/stereo_benchmark_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..fb161566cf789e8132821938e1b75acb1bd3ae4e --- /dev/null +++ b/scripts/stereo_benchmark_comparison.py @@ -0,0 +1,1261 @@ +#!/usr/bin/env python3 +""" +Stereo PIV Benchmark Comparison against JHTDB DNS Ground Truth. + +Compares 3-component velocity (U, V, W) and all 6 Reynolds stresses +(uu, vv, ww, uv, uw, vw) against DNS channel flow data. + +Usage: + python stereo_benchmark_comparison.py [--run RUN_IDX] [--x-min X_MIN] [--x-max X_MAX] +""" + +import numpy as np +import scipy.io as sio +from scipy.interpolate import interp1d +import matplotlib +import matplotlib.pyplot as plt +from pathlib import Path +import argparse + +# LaTeX-style fonts (no LaTeX install required) +matplotlib.rcParams.update({ + 'text.usetex': False, + 'font.family': 'serif', + 'font.serif': ['CMU Serif', 'Computer Modern Roman', 'DejaVu Serif'], + 'mathtext.fontset': 'cm', + 'axes.labelsize': 14, + 'axes.titlesize': 16, + 'legend.fontsize': 11, + 'xtick.labelsize': 12, + 'ytick.labelsize': 12, +}) + + +def log_smooth(y_plus, values, sigma_decades=0.06): + """LOWESS-style smooth in log(y+) space, evaluated at original points. + + Each output point is a locally-weighted LINEAR regression of neighbours, + where distance is measured in decades of y+. Using local linear fits + instead of local averages gives: + - Better peak tracking (local slope captures gradients) + - Better edge behaviour (linear extrapolation, not mean bias) + + Parameters + ---------- + y_plus : array + y+ coordinates (positive) + values : array + Values to smooth + sigma_decades : float + Smoothing width in decades of y+ (0.06 ~ +/-15% local y+) + + Returns + ------- + y_out, smoothed : arrays + Sorted y+ and smoothed values (at original data points) + """ + valid = (y_plus > 0) & ~np.isnan(values) + yp = y_plus[valid] + vals = values[valid] + if len(yp) < 5: + return yp, vals + + order = np.argsort(yp) + yp = yp[order] + vals = vals[order] + log_yp = np.log10(yp) + + smoothed = np.empty_like(vals) + for i in range(len(vals)): + d = (log_yp - log_yp[i]) / sigma_decades + w = np.exp(-0.5 * d * d) + # Local linear regression (LOWESS) instead of weighted mean + wsum = np.sum(w) + wmean_x = np.sum(w * log_yp) / wsum + wmean_y = np.sum(w * vals) / wsum + dx = log_yp - wmean_x + denom = np.sum(w * dx * dx) + if denom > 1e-30: + slope = np.sum(w * dx * vals) / denom + smoothed[i] = wmean_y + slope * (log_yp[i] - wmean_x) + else: + smoothed[i] = wmean_y + + return yp, smoothed + + +def plot_ci_band(ax, y_plus, ci_lo, ci_hi, sign=1, color='k', alpha=0.3, zorder=1): + """Plot a 95% CI shaded band around a reference line. + + Parameters + ---------- + ax : matplotlib Axes + y_plus : array + x-axis values (y+ coordinates) + ci_lo, ci_hi : array + Lower/upper CI bounds (same units as the plotted variable) + sign : int + 1 or -1 (for variables like -uv+ that flip sign) + color : str + Fill color + alpha : float + Fill transparency + zorder : int + Drawing order + """ + lo = sign * ci_lo if sign == 1 else sign * ci_hi # sign flip swaps lo/hi + hi = sign * ci_hi if sign == 1 else sign * ci_lo + ax.fill_between(y_plus, lo, hi, color=color, alpha=alpha, zorder=zorder, + linewidth=0) + # Add thin edge lines so the CI is visible even when narrow + ax.plot(y_plus, lo, color=color, linewidth=0.5, alpha=0.4, zorder=zorder) + ax.plot(y_plus, hi, color=color, linewidth=0.5, alpha=0.4, zorder=zorder) + + +def load_wall_units(wall_units_path): + """Load wall units from .mat file (supports v5 struct, v7.3/HDF5, and direct_stats).""" + wall_units_path = str(wall_units_path) + try: + wall = sio.loadmat(wall_units_path, squeeze_me=True, struct_as_record=False) + + # Format: direct_stats.mat (top-level scalar keys) + if 'u_tau' in wall and 'delta_nu' in wall and 'Re_tau' in wall: + u_tau = float(wall['u_tau']) + delta_nu = float(wall['delta_nu']) + Re_tau = float(wall['Re_tau']) + return { + 'u_tau': u_tau, + 'nu': u_tau * delta_nu, + 'delta_nu': delta_nu, + 'h_mm': float(wall['h_mm']) if 'h_mm' in wall else Re_tau * delta_nu, + 'Re_tau': Re_tau, + } + + # Format: wall_units.mat (struct) + wu = wall['wall_units'] + return { + 'u_tau': float(wu.u_tau), + 'nu': float(wu.nu), + 'delta_nu': float(wu.delta_nu), + 'h_mm': float(wu.h_mm), + 'Re_tau': float(wu.Re_tau) + } + except NotImplementedError: + import h5py + with h5py.File(wall_units_path, 'r') as f: + d = f['diagnostics'] + u_tau = float(d['u_tau'][0, 0]) + Re_tau = float(d['Re_tau'][0, 0]) + delta_nu = float(d['delta_nu'][0, 0]) + return { + 'u_tau': u_tau, + 'nu': u_tau * delta_nu, + 'delta_nu': delta_nu, + 'h_mm': Re_tau * delta_nu, + 'Re_tau': Re_tau + } + + +def load_ground_truth_3d(profiles_path): + """Load ground truth 1px profiles including W component (supports v5 struct, v7.3/HDF5, and direct_stats).""" + profiles_path = str(profiles_path) + try: + profiles = sio.loadmat(profiles_path, squeeze_me=True, struct_as_record=False) + + # Format: direct_stats.mat (top-level arrays) + if 'U_plus' in profiles and 'stress_plus' in profiles and 'y_plus' in profiles: + y_plus_full = profiles['y_plus'] + Re_tau = float(profiles['Re_tau']) + u_tau = float(profiles['u_tau']) + delta_nu = float(profiles['delta_nu']) + u_tau2 = u_tau ** 2 + + # Select lower half of channel (y+ <= Re_tau) + mask = y_plus_full <= Re_tau + y_plus = y_plus_full[mask] + y_mm = y_plus * delta_nu + + # U_plus: (N, 3) -> columns [U, V, W] + U_plus = profiles['U_plus'][mask, 0] + V_plus = profiles['U_plus'][mask, 1] + W_plus = profiles['U_plus'][mask, 2] + + # stress_plus: (N, 3, 3) -> Reynolds stress tensor + uu_plus = profiles['stress_plus'][mask, 0, 0] + vv_plus = profiles['stress_plus'][mask, 1, 1] + ww_plus = profiles['stress_plus'][mask, 2, 2] + uv_plus = profiles['stress_plus'][mask, 0, 1] + uw_plus = profiles['stress_plus'][mask, 0, 2] + vw_plus = profiles['stress_plus'][mask, 1, 2] + + result = { + 'y_mm': y_mm, + 'y_plus': y_plus, + 'U': U_plus * u_tau, + 'V': V_plus * u_tau, + 'W': W_plus * u_tau, + 'uu': uu_plus * u_tau2, + 'vv': vv_plus * u_tau2, + 'ww': ww_plus * u_tau2, + 'uv': uv_plus * u_tau2, + 'uw': uw_plus * u_tau2, + 'vw': vw_plus * u_tau2, + 'U_plus': U_plus, + 'uu_plus': uu_plus, + 'vv_plus': vv_plus, + 'ww_plus': ww_plus, + 'uv_plus': uv_plus, + } + + # Load 95% confidence intervals if available + if 'stress_ci_lo' in profiles and 'stress_ci_hi' in profiles: + result['uu_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 0, 0] + result['uu_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 0, 0] + result['vv_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 1, 1] + result['vv_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 1, 1] + result['ww_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 2, 2] + result['ww_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 2, 2] + result['uv_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 0, 1] + result['uv_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 0, 1] + result['uw_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 0, 2] + result['uw_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 0, 2] + result['vw_plus_ci_lo'] = profiles['stress_ci_lo'][mask, 1, 2] + result['vw_plus_ci_hi'] = profiles['stress_ci_hi'][mask, 1, 2] + if 'umean_ci_lo' in profiles and 'umean_ci_hi' in profiles: + result['U_plus_ci_lo'] = profiles['umean_ci_lo'][mask, 0] + result['U_plus_ci_hi'] = profiles['umean_ci_hi'][mask, 0] + result['V_plus_ci_lo'] = profiles['umean_ci_lo'][mask, 1] + result['V_plus_ci_hi'] = profiles['umean_ci_hi'][mask, 1] + result['W_plus_ci_lo'] = profiles['umean_ci_lo'][mask, 2] + result['W_plus_ci_hi'] = profiles['umean_ci_hi'][mask, 2] + + return result + + # Format: profiles.mat (struct) + win1px = profiles['profiles'].win_1px + return { + 'y_mm': win1px.y_mm, + 'y_plus': win1px.y_plus, + 'U': win1px.U, + 'V': win1px.V, + 'W': win1px.W, + 'uu': win1px.uu, + 'vv': win1px.vv, + 'ww': win1px.ww, + 'uv': win1px.uv, + 'uw': win1px.uw, + 'vw': win1px.vw, + 'U_plus': win1px.U_plus, + 'uu_plus': win1px.uu_plus, + 'vv_plus': win1px.vv_plus, + 'ww_plus': win1px.ww_plus, + 'uv_plus': win1px.uv_plus, + } + except NotImplementedError: + import h5py + with h5py.File(profiles_path, 'r') as f: + rp = f['ref_profile'] + y_plus = rp['y_plus'][0, :] + U = rp['U'][0, :] + V = rp['V'][0, :] + W = rp['W'][0, :] + + # Also load ensemble_stats for stress profiles (win_idx=0 = 16x16) + es = f['ensemble_stats'] + + def deref(field, idx=0): + ref = es[field][idx, 0] + return f[ref][:].flatten() + + y_mm_es = deref('y_mm') + y_plus_es = deref('y_plus') + + # Wall units from diagnostics sibling file + diag_path = str(Path(profiles_path).parent / 'diagnostics.mat') + wu = load_wall_units(diag_path) + u_tau = wu['u_tau'] + u_tau2 = u_tau ** 2 + + uu = deref('uu_profile') + vv = deref('vv_profile') + ww = deref('ww_profile') + uv = deref('uv_profile') + uw = deref('uw_profile') + vw = deref('vw_profile') + + return { + 'y_mm': y_mm_es, + 'y_plus': y_plus_es, + 'U': deref('U_profile'), + 'V': deref('V_profile'), + 'W': deref('W_profile'), + 'uu': uu, + 'vv': vv, + 'ww': ww, + 'uv': uv, + 'uw': uw, + 'vw': vw, + 'U_plus': deref('U_profile') / u_tau, + 'uu_plus': uu / u_tau2, + 'vv_plus': vv / u_tau2, + 'ww_plus': ww / u_tau2, + 'uv_plus': uv / u_tau2, + } + + +def load_stereo_statistics(stats_path, coords_path, run_idx=3): + """ + Load stereo PIV statistics from mean_stats.mat and coordinates from separate file. + + Parameters + ---------- + stats_path : Path + Path to mean_stats.mat + coords_path : Path + Path to coordinates.mat (from stereo_calibrated folder) + run_idx : int + Run index (0-based). run_idx=3 is typically finest resolution (16x16) + """ + stats = sio.loadmat(stats_path, squeeze_me=True, struct_as_record=False) + coords_data = sio.loadmat(coords_path, squeeze_me=True, struct_as_record=False) + + # Get piv_result for the requested run + piv_result = stats['piv_result'] + if isinstance(piv_result, np.ndarray) and piv_result.ndim == 0: + piv = piv_result.item() + elif hasattr(piv_result, '__len__') and len(piv_result) > run_idx: + piv = piv_result[run_idx] + else: + piv = piv_result + + # Get coordinates from separate file + coords = coords_data['coordinates'] + if isinstance(coords, np.ndarray) and coords.ndim == 0: + coord = coords.item() + elif hasattr(coords, '__len__') and len(coords) > run_idx: + coord = coords[run_idx] + else: + coord = coords + + return { + # Velocities (m/s -> mm/s) + 'ux': piv.ux * 1000, + 'uy': piv.uy * 1000, + 'uz': piv.uz * 1000, + # Normal stresses ((m/s)^2 -> (mm/s)^2) + 'uu': piv.uu * 1e6, + 'vv': piv.vv * 1e6, + 'ww': piv.ww * 1e6, + # Shear stresses + 'uv': piv.uv * 1e6, + 'uw': piv.uw * 1e6, + 'vw': piv.vw * 1e6, + # Coordinates (already in mm from calibrated file) + 'x': coord.x, + 'y': coord.y, + } + + +def compute_stereo_profiles(piv_data, x_min=5.0, x_max=145.0): + """ + Compute x-averaged stereo PIV profiles. + + Parameters + ---------- + piv_data : dict + Stereo PIV data dictionary + x_min : float + Minimum x to include (mm) + x_max : float + Maximum x to include (mm) + + Returns + ------- + dict with y_mm and all velocity/stress profiles + """ + x = piv_data['x'] + y = piv_data['y'] + + # Stereo coordinates have NaN at edges (outside overlap region) + # Find valid region + valid_mask = ~np.isnan(x) + valid_rows = np.any(valid_mask, axis=1) + valid_cols = np.any(valid_mask, axis=0) + + # Find first valid column to get y values from + first_valid_col = np.argmax(valid_cols) + last_valid_col = len(valid_cols) - np.argmax(valid_cols[::-1]) - 1 + mid_col = (first_valid_col + last_valid_col) // 2 + + # Find first valid row to get x values from + first_valid_row = np.argmax(valid_rows) + last_valid_row = len(valid_rows) - np.argmax(valid_rows[::-1]) - 1 + mid_row = (first_valid_row + last_valid_row) // 2 + + # Get unique coordinates from valid region + y_full = y[:, mid_col] + x_unique = x[mid_row, :] + + print(f" Valid row range: {first_valid_row} to {last_valid_row}") + print(f" Valid col range: {first_valid_col} to {last_valid_col}") + print(f" X range: {np.nanmin(x_unique):.2f} to {np.nanmax(x_unique):.2f} mm") + print(f" Y range: {np.nanmin(y_full):.2f} to {np.nanmax(y_full):.2f} mm") + + # Apply x range filter + x_mask = (x_unique >= x_min) & (x_unique <= x_max) & ~np.isnan(x_unique) + + print(f" Keeping X: {x_min:.2f} to {x_max:.2f} mm") + print(f" X points: {x_mask.sum()} / {len(x_unique)}") + + # Filter out rows with invalid y values + y_valid_mask = ~np.isnan(y_full) + + # Compute profiles for all variables + profiles = {} + + for var in ['ux', 'uy', 'uz', 'uu', 'vv', 'ww', 'uv', 'uw', 'vw']: + data = piv_data[var] + # Average along x for each row, then keep only valid y rows + row_means = np.nanmean(data[:, x_mask], axis=1) + profiles[var] = row_means[y_valid_mask] + + # Store y for valid rows only + profiles['y_mm'] = y_full[y_valid_mask] + + # Rename for clarity + profiles['U'] = profiles.pop('ux') + profiles['V'] = profiles.pop('uy') + profiles['W'] = profiles.pop('uz') + + return profiles + + +def convert_to_wall_units(profiles, wall_units, y_offset_mm=0.0): + """ + Convert profiles to wall units. + + Parameters + ---------- + profiles : dict + PIV profiles with y_mm, U, V, W, stresses + wall_units : dict + Wall unit parameters + y_offset_mm : float + Offset to add to y_mm for coordinate alignment + """ + u_tau = wall_units['u_tau'] + delta_nu = wall_units['delta_nu'] + u_tau2 = u_tau ** 2 + + y_mm_aligned = profiles['y_mm'] + y_offset_mm + + return { + 'y_mm': y_mm_aligned, + 'y_plus': y_mm_aligned / delta_nu, + # Velocities + 'U_plus': profiles['U'] / u_tau, + 'V_plus': profiles['V'] / u_tau, + 'W_plus': profiles['W'] / u_tau, + # Normal stresses + 'uu_plus': profiles['uu'] / u_tau2, + 'vv_plus': profiles['vv'] / u_tau2, + 'ww_plus': profiles['ww'] / u_tau2, + # Shear stresses + 'uv_plus': profiles['uv'] / u_tau2, + 'uw_plus': profiles['uw'] / u_tau2, + 'vw_plus': profiles['vw'] / u_tau2, + } + + +def compute_errors(piv_plus, gt_plus, y_plus_range=(10, 500)): + """Compute error metrics between PIV and ground truth.""" + y_piv = piv_plus['y_plus'] + y_gt = gt_plus['y_plus'] + + mask_piv = (y_piv >= y_plus_range[0]) & (y_piv <= y_plus_range[1]) + y_compare = y_piv[mask_piv] + + if len(y_compare) == 0: + print(f" Warning: No PIV points in y+ range {y_plus_range}") + return {} + + errors = {} + variables = ['U_plus', 'V_plus', 'W_plus', 'uu_plus', 'vv_plus', 'ww_plus', + 'uv_plus', 'uw_plus', 'vw_plus'] + + for var in variables: + if var not in piv_plus or var not in gt_plus: + continue + + piv_vals = piv_plus[var][mask_piv] + + # Interpolate ground truth + gt_interp = interp1d(y_gt, gt_plus[var], kind='linear', + bounds_error=False, fill_value=np.nan) + gt_vals = gt_interp(y_compare) + + # Remove NaN values + valid = ~np.isnan(piv_vals) & ~np.isnan(gt_vals) + if valid.sum() == 0: + continue + + piv_valid = piv_vals[valid] + gt_valid = gt_vals[valid] + + # Compute metrics + diff = piv_valid - gt_valid + rms_error = np.sqrt(np.mean(diff**2)) + mean_abs_error = np.mean(np.abs(diff)) + + gt_range = np.ptp(gt_valid) + rms_rel = (rms_error / gt_range * 100) if gt_range > 0 else np.nan + + corr = np.corrcoef(piv_valid, gt_valid)[0, 1] if len(piv_valid) > 1 else np.nan + + ss_res = np.sum(diff**2) + ss_tot = np.sum((gt_valid - gt_valid.mean())**2) + r2 = 1 - (ss_res / ss_tot) if ss_tot > 0 else np.nan + + errors[var] = { + 'rms': rms_error, + 'rms_rel': rms_rel, + 'mae': mean_abs_error, + 'corr': corr, + 'r2': r2, + 'n_points': valid.sum(), + } + + return errors + + +def plot_velocity_comparison(piv_plus, gt_plus, wall_units, errors, output_dir): + """Generate velocity comparison plots (U+, V+, W+).""" + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + Re_tau = wall_units['Re_tau'] + has_ci = 'uu_plus_ci_lo' in gt_plus + + # ========================================================================== + # Figure 1: U+ profile (semilog) + # ========================================================================== + fig, ax = plt.subplots(figsize=(10, 7)) + + if has_ci and 'U_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], + gt_plus['U_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', + linewidth=2, label='DNS (1px)', zorder=3) + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], 'ro', + markersize=4, alpha=0.7, label='Stereo PIV', zorder=2) + + # Log law reference + y_log = np.logspace(1, np.log10(Re_tau), 100) + kappa, B = 0.41, 5.2 + U_log = (1/kappa) * np.log(y_log) + B + ax.semilogx(y_log, U_log, 'b--', linewidth=1, alpha=0.7, + label=r'Log law: $U^+ = \frac{1}{\kappa}\ln(y^+) + B$') + + # Viscous sublayer + y_visc = np.linspace(0.1, 10, 50) + ax.semilogx(y_visc, y_visc, 'g--', linewidth=1, alpha=0.7, + label=r'Viscous sublayer: $U^+ = y^+$') + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$U^+$', fontsize=14) + ax.set_title(f'Mean Streamwise Velocity - Stereo PIV (Re$_\\tau$ = {Re_tau:.0f})', fontsize=16) + ax.legend(fontsize=11) + ax.set_xlim(1, Re_tau) + ax.set_ylim(0, 25) + ax.grid(True, alpha=0.3) + + if 'U_plus' in errors: + ax.text(0.02, 0.98, f"R² = {errors['U_plus']['r2']:.4f}\n" + f"RMS = {errors['U_plus']['rms_rel']:.1f}%", + transform=ax.transAxes, fontsize=11, verticalalignment='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'U_plus_profile.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 2: V+ profile + # ========================================================================== + fig, ax = plt.subplots(figsize=(10, 7)) + + if has_ci and 'V_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['V_plus_ci_lo'], + gt_plus['V_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['V_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['V_plus'], 'ro', markersize=4, + alpha=0.7, label='Stereo PIV') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$V^+$', fontsize=14) + ax.set_title('Mean Wall-Normal Velocity - Stereo PIV', fontsize=16) + ax.legend(fontsize=11) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + if 'V_plus' in errors: + ax.text(0.02, 0.98, f"R² = {errors['V_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=11, verticalalignment='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'V_plus_profile.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 3: W+ profile (spanwise - should be ~0 for channel flow) + # ========================================================================== + fig, ax = plt.subplots(figsize=(10, 7)) + + if has_ci and 'W_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['W_plus_ci_lo'], + gt_plus['W_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['W_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['W_plus'], 'bo', markersize=4, + alpha=0.7, label='Stereo PIV') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=14) + ax.set_ylabel(r'$W^+$', fontsize=14) + ax.set_title('Mean Spanwise Velocity - Stereo PIV (should be ~0)', fontsize=16) + ax.legend(fontsize=11) + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + if 'W_plus' in errors: + ax.text(0.02, 0.98, f"R² = {errors['W_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=11, verticalalignment='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.tight_layout() + fig.savefig(output_dir / 'W_plus_profile.png', dpi=150) + plt.close(fig) + + # ========================================================================== + # Figure 4: All velocities combined + # ========================================================================== + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + # U+ + ax = axes[0] + if has_ci and 'U_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['U_plus_ci_lo'], + gt_plus['U_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.semilogx(gt_plus['y_plus'], gt_plus['U_plus'], 'k-', linewidth=2, label='DNS') + ax.semilogx(piv_plus['y_plus'], piv_plus['U_plus'], 'ro', markersize=3, alpha=0.7, label='Stereo') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r'$U^+$', fontsize=12) + ax.set_title('Streamwise Velocity', fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # V+ + ax = axes[1] + if has_ci and 'V_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['V_plus_ci_lo'], + gt_plus['V_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['V_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['V_plus'], 'ro', markersize=3, alpha=0.7, label='Stereo') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r'$V^+$', fontsize=12) + ax.set_title('Wall-Normal Velocity', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # W+ + ax = axes[2] + if has_ci and 'W_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['W_plus_ci_lo'], + gt_plus['W_plus_ci_hi'], color='k', alpha=0.15, zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['W_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['W_plus'], 'bo', markersize=3, alpha=0.7, label='Stereo') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r'$W^+$', fontsize=12) + ax.set_title('Spanwise Velocity', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'velocities_combined.png', dpi=150) + plt.close(fig) + + +def plot_normal_stresses(piv_plus, gt_plus, wall_units, errors, output_dir): + """Generate normal stress plots (uu+, vv+, ww+).""" + output_dir = Path(output_dir) + Re_tau = wall_units['Re_tau'] + has_ci = 'uu_plus_ci_lo' in gt_plus + + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + # uu+ + ax = axes[0] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uu_plus_ci_lo'], + gt_plus['uu_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['uu_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['uu_plus'], 'ro', markersize=3, alpha=0.7, label='Stereo') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{u'u'}^+$", fontsize=12) + ax.set_title('Streamwise Normal Stress', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'uu_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['uu_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + # vv+ + ax = axes[1] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['vv_plus_ci_lo'], + gt_plus['vv_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['vv_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['vv_plus'], 'go', markersize=3, alpha=0.7, label='Stereo') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{v'v'}^+$", fontsize=12) + ax.set_title('Wall-Normal Normal Stress', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'vv_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['vv_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + # ww+ + ax = axes[2] + if has_ci and 'ww_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['ww_plus_ci_lo'], + gt_plus['ww_plus_ci_hi'], color='k', zorder=1) + ax.plot(gt_plus['y_plus'], gt_plus['ww_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], piv_plus['ww_plus'], 'bo', markersize=3, alpha=0.7, label='Stereo') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$\overline{w'w'}^+$", fontsize=12) + ax.set_title('Spanwise Normal Stress', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'ww_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['ww_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.suptitle('Normal Reynolds Stresses - Stereo PIV', fontsize=16, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'normal_stresses.png', dpi=150) + plt.close(fig) + + +def plot_shear_stresses(piv_plus, gt_plus, wall_units, errors, output_dir): + """Generate shear stress plots (-uv+, -uw+, -vw+).""" + output_dir = Path(output_dir) + Re_tau = wall_units['Re_tau'] + has_ci = 'uv_plus_ci_lo' in gt_plus + + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + # -uv+ + ax = axes[0] + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uv_plus_ci_lo'], + gt_plus['uv_plus_ci_hi'], sign=-1, color='k', zorder=1) + ax.plot(gt_plus['y_plus'], -gt_plus['uv_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], -piv_plus['uv_plus'], 'ro', markersize=3, alpha=0.7, label='Stereo') + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$-\overline{u'v'}^+$", fontsize=12) + ax.set_title('Reynolds Shear Stress (u-v)', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'uv_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['uv_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + # -uw+ + ax = axes[1] + if has_ci and 'uw_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uw_plus_ci_lo'], + gt_plus['uw_plus_ci_hi'], sign=-1, color='k', zorder=1) + ax.plot(gt_plus['y_plus'], -gt_plus['uw_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], -piv_plus['uw_plus'], 'go', markersize=3, alpha=0.7, label='Stereo') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$-\overline{u'w'}^+$", fontsize=12) + ax.set_title('Reynolds Shear Stress (u-w)', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'uw_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['uw_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + # -vw+ + ax = axes[2] + if has_ci and 'vw_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['vw_plus_ci_lo'], + gt_plus['vw_plus_ci_hi'], sign=-1, color='k', zorder=1) + ax.plot(gt_plus['y_plus'], -gt_plus['vw_plus'], 'k-', linewidth=2, label='DNS') + ax.plot(piv_plus['y_plus'], -piv_plus['vw_plus'], 'bo', markersize=3, alpha=0.7, label='Stereo') + ax.axhline(y=0, color='gray', linestyle='--', linewidth=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"$-\overline{v'w'}^+$", fontsize=12) + ax.set_title('Reynolds Shear Stress (v-w)', fontsize=14) + ax.legend() + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + if 'vw_plus' in errors: + ax.text(0.98, 0.98, f"R² = {errors['vw_plus']['r2']:.4f}", + transform=ax.transAxes, fontsize=10, ha='right', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + fig.suptitle('Reynolds Shear Stresses - Stereo PIV', fontsize=16, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'shear_stresses.png', dpi=150) + plt.close(fig) + + +def plot_combined_stresses(piv_plus, gt_plus, wall_units, errors, output_dir): + """Plot uu+, vv+, ww+, -uv+ all on a single axis.""" + output_dir = Path(output_dir) + Re_tau = wall_units['Re_tau'] + has_ci = 'uu_plus_ci_lo' in gt_plus + + fig, ax = plt.subplots(figsize=(12, 8)) + + # CI bands (behind everything) + if has_ci: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uu_plus_ci_lo'], + gt_plus['uu_plus_ci_hi'], color='k', alpha=0.12, zorder=1) + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['vv_plus_ci_lo'], + gt_plus['vv_plus_ci_hi'], color='k', alpha=0.12, zorder=1) + if 'ww_plus_ci_lo' in gt_plus: + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['ww_plus_ci_lo'], + gt_plus['ww_plus_ci_hi'], color='k', alpha=0.12, zorder=1) + plot_ci_band(ax, gt_plus['y_plus'], gt_plus['uv_plus_ci_lo'], + gt_plus['uv_plus_ci_hi'], sign=-1, color='k', alpha=0.12, zorder=1) + + # Ground truth / reference + ax.plot(gt_plus['y_plus'], gt_plus['uu_plus'], 'k-', linewidth=2, label=r"Ref $\overline{u'u'}^+$") + ax.plot(gt_plus['y_plus'], gt_plus['vv_plus'], 'k--', linewidth=2, label=r"Ref $\overline{v'v'}^+$") + ax.plot(gt_plus['y_plus'], gt_plus['ww_plus'], 'k-.', linewidth=2, label=r"Ref $\overline{w'w'}^+$") + ax.plot(gt_plus['y_plus'], -gt_plus['uv_plus'], 'k:', linewidth=2, label=r"Ref $-\overline{u'v'}^+$") + + # Stereo PIV — markers only (no smoothed lines) + piv_configs = [ + ('uu_plus', 1, 'r', 'o', r"Stereo $\overline{u'u'}^+$"), + ('vv_plus', 1, 'g', 's', r"Stereo $\overline{v'v'}^+$"), + ('ww_plus', 1, 'b', '^', r"Stereo $\overline{w'w'}^+$"), + ('uv_plus', -1, 'm', 'D', r"Stereo $-\overline{u'v'}^+$"), + ] + for var, sign, col, mkr, label in piv_configs: + piv_vals = sign * piv_plus[var] + ax.plot(piv_plus['y_plus'], piv_vals, color=col, marker=mkr, + markersize=4, alpha=0.7, linestyle='none', label=label, zorder=5) + + ax.set_xlabel(r'$y^+$') + ax.set_ylabel(r'Stress$^+$') + ax.set_title(r'Reynolds Stresses -- Stereo PIV vs Reference ($\mathrm{Re}_\tau$ = ' + f'{Re_tau:.0f})') + ax.legend(ncol=2, loc='upper right') + ax.set_xscale('log') + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'combined_stresses.png', dpi=150) + plt.close(fig) + + +def plot_residuals(piv_plus, gt_plus, wall_units, output_dir): + """Plot residuals (PIV - Ref) for velocities and stresses.""" + output_dir = Path(output_dir) + Re_tau = wall_units['Re_tau'] + + fig, axes = plt.subplots(2, 3, figsize=(16, 10)) + + # Interpolate ground truth onto PIV y+ grid + gt_interp_fn = {} + for var in ['U_plus', 'V_plus', 'W_plus', 'uu_plus', 'vv_plus', 'ww_plus', + 'uv_plus', 'uw_plus', 'vw_plus']: + if var in gt_plus: + gt_interp_fn[var] = interp1d(gt_plus['y_plus'], gt_plus[var], kind='linear', + bounds_error=False, fill_value=np.nan) + + # Top row: velocity residuals (U+, V+, W+) + vel_configs = [ + ('U_plus', r"$U^+_{\mathrm{PIV}} - U^+_{\mathrm{Ref}}$", + 'Streamwise Velocity Residual', 1), + ('V_plus', r"$V^+_{\mathrm{PIV}} - V^+_{\mathrm{Ref}}$", + 'Wall-Normal Velocity Residual', 1), + ('W_plus', r"$W^+_{\mathrm{PIV}} - W^+_{\mathrm{Ref}}$", + 'Spanwise Velocity Residual', 1), + ] + for ax, (var, ylabel, title, sign) in zip(axes[0, :], vel_configs): + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + + ax.semilogx(piv_plus['y_plus'], residual, 'ro', markersize=3, alpha=0.5) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2, label='Stereo PIV') + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Bottom row: normal stress residuals (uu+, vv+, ww+) + stress_configs = [ + ('uu_plus', r"$\overline{u'u'}^+_{\mathrm{PIV}} - \overline{u'u'}^+_{\mathrm{Ref}}$", + 'Streamwise Normal Stress Residual', 1), + ('vv_plus', r"$\overline{v'v'}^+_{\mathrm{PIV}} - \overline{v'v'}^+_{\mathrm{Ref}}$", + 'Wall-Normal Normal Stress Residual', 1), + ('ww_plus', r"$\overline{w'w'}^+_{\mathrm{PIV}} - \overline{w'w'}^+_{\mathrm{Ref}}$", + 'Spanwise Normal Stress Residual', 1), + ] + for ax, (var, ylabel, title, sign) in zip(axes[1, :], stress_configs): + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + + ax.semilogx(piv_plus['y_plus'], residual, 'ro', markersize=3, alpha=0.5) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2, label='Stereo PIV') + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.tight_layout() + fig.savefig(output_dir / 'residuals.png', dpi=150) + plt.close(fig) + + # Additional figure: shear stress residuals (uv+, uw+, vw+) + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + shear_configs = [ + ('uv_plus', r"$-\overline{u'v'}^+_{\mathrm{PIV}} - (-\overline{u'v'}^+_{\mathrm{Ref}})$", + 'Shear Stress Residual (u-v)', -1), + ('uw_plus', r"$-\overline{u'w'}^+_{\mathrm{PIV}} - (-\overline{u'w'}^+_{\mathrm{Ref}})$", + 'Shear Stress Residual (u-w)', -1), + ('vw_plus', r"$-\overline{v'w'}^+_{\mathrm{PIV}} - (-\overline{v'w'}^+_{\mathrm{Ref}})$", + 'Shear Stress Residual (v-w)', -1), + ] + for ax, (var, ylabel, title, sign) in zip(axes, shear_configs): + gt_at_piv = gt_interp_fn[var](piv_plus['y_plus']) + residual = sign * piv_plus[var] - sign * gt_at_piv + + ax.semilogx(piv_plus['y_plus'], residual, 'ro', markersize=3, alpha=0.5) + yp_s, r_s = log_smooth(piv_plus['y_plus'], residual) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2, label='Stereo PIV') + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(ylabel, fontsize=12) + ax.set_title(title, fontsize=14) + ax.legend() + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.suptitle('Shear Stress Residuals - Stereo PIV', fontsize=14, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'residuals_shear.png', dpi=150) + plt.close(fig) + + +def plot_noise_gradient_decomposition(piv_plus, gt_plus, wall_units, output_dir): + """Plot noise floor vs gradient correction decomposition. + + Uses the fact that PIV measurement noise is approximately isotropic + (vv+ residual ~ noise floor), while velocity gradient bias is + anisotropic (uu+ - vv+ removes the isotropic noise contribution). + Extended for stereo: ww+ residual provides an independent noise floor check. + """ + output_dir = Path(output_dir) + Re_tau = wall_units['Re_tau'] + + # Interpolate ground truth onto PIV y+ grid + gt_interp = {} + for var in ['uu_plus', 'vv_plus', 'ww_plus']: + gt_interp[var] = interp1d(gt_plus['y_plus'], gt_plus[var], kind='linear', + bounds_error=False, fill_value=np.nan) + + uu_residual = piv_plus['uu_plus'] - gt_interp['uu_plus'](piv_plus['y_plus']) + vv_residual = piv_plus['vv_plus'] - gt_interp['vv_plus'](piv_plus['y_plus']) + ww_residual = piv_plus['ww_plus'] - gt_interp['ww_plus'](piv_plus['y_plus']) + gradient_only = uu_residual - vv_residual + + fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + + # Left: Noise floor (vv+ residual — isotropic) + ax = axes[0] + ax.semilogx(piv_plus['y_plus'], vv_residual, 'bo', markersize=2, alpha=0.3) + yp_s, r_s = log_smooth(piv_plus['y_plus'], vv_residual) + ax.semilogx(yp_s, r_s, 'b-', linewidth=2.5, label=r"$v'v'$ residual (noise floor)") + # Overlay ww+ as independent noise check + ax.semilogx(piv_plus['y_plus'], ww_residual, 'co', markersize=2, alpha=0.2) + yp_s_ww, r_s_ww = log_smooth(piv_plus['y_plus'], ww_residual) + ax.semilogx(yp_s_ww, r_s_ww, 'c--', linewidth=2, label=r"$w'w'$ residual (check)") + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Noise floor residual$^+$", fontsize=12) + ax.set_title('Noise Floor (isotropic)', fontsize=14) + ax.legend(fontsize=10) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Middle: Gradient-only residual (uu+ - vv+ removes isotropic noise) + ax = axes[1] + ax.semilogx(piv_plus['y_plus'], gradient_only, 'ro', markersize=2, alpha=0.3) + yp_s, r_s = log_smooth(piv_plus['y_plus'], gradient_only) + ax.semilogx(yp_s, r_s, 'r-', linewidth=2.5, + label=r"$(\overline{u'u'} - \overline{v'v'})_{\mathrm{PIV}} - (\overline{u'u'} - \overline{v'v'})_{\mathrm{Ref}}$") + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Gradient-only residual$^+$", fontsize=12) + ax.set_title(r"Gradient Correction Residual ($u'u' - v'v'$ removes noise)", fontsize=14) + ax.legend(fontsize=9) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + # Right: All overlaid + ax = axes[2] + ax.semilogx(piv_plus['y_plus'], uu_residual, 'ro', markersize=2, alpha=0.15) + yp_s_uu, r_s_uu = log_smooth(piv_plus['y_plus'], uu_residual) + ax.semilogx(yp_s_uu, r_s_uu, 'r-', linewidth=2, label=r"$u'u'$ residual (total)") + + ax.semilogx(piv_plus['y_plus'], vv_residual, 'bo', markersize=2, alpha=0.15) + yp_s_vv, r_s_vv = log_smooth(piv_plus['y_plus'], vv_residual) + ax.semilogx(yp_s_vv, r_s_vv, 'b-', linewidth=2, label=r"$v'v'$ residual (noise floor)") + + yp_s_g, r_s_g = log_smooth(piv_plus['y_plus'], gradient_only) + ax.semilogx(yp_s_g, r_s_g, 'g--', linewidth=2, label=r"$u'u' - v'v'$ residual (gradient only)") + + ax.axhline(y=0, color='k', linestyle='-', linewidth=1, alpha=0.5) + ax.set_xlabel(r'$y^+$', fontsize=12) + ax.set_ylabel(r"Residual$^+$", fontsize=12) + ax.set_title('Decomposition: Total = Noise + Gradient', fontsize=14) + ax.legend(fontsize=9) + ax.set_xlim(1, Re_tau) + ax.grid(True, alpha=0.3) + + fig.suptitle('Noise Floor vs Gradient Correction - Stereo PIV', fontsize=14, y=1.02) + fig.tight_layout() + fig.savefig(output_dir / 'noise_gradient_decomposition.png', dpi=150) + plt.close(fig) + + +def main(run_idx=2, x_min=5.0, x_max=145.0, gt_dir=None, stereo_base=None, num_frames=1000, output_dir_override=None, trim_top=0): + """Main stereo benchmark comparison function.""" + + # Paths + script_dir = Path(__file__).parent + + if gt_dir is None: + raise ValueError("gt_dir is required. Provide the ground truth directory path.") + gt_dir = Path(gt_dir) + + if stereo_base is None: + raise ValueError("stereo_base is required. Provide the stereo PIV results directory path.") + stereo_base = Path(stereo_base) + + stats_path = stereo_base / f'statistics/{num_frames}/stereo/Cam1_Cam2/instantaneous/mean_stats/mean_stats.mat' + coords_path = stereo_base / f'stereo_calibrated/{num_frames}/Cam1_Cam2/instantaneous/coordinates.mat' + + output_dir = output_dir_override or (script_dir / 'benchmark_results_stereo') + + print("=" * 70) + print("STEREO PIV BENCHMARK COMPARISON") + print("=" * 70) + print(f"Run index: {run_idx}") + print(f"X range: {x_min} to {x_max} mm") + + # Load data - detect file format + wall_units_file = gt_dir / 'wall_units.mat' + if not wall_units_file.exists(): + wall_units_file = gt_dir / 'diagnostics.mat' + if not wall_units_file.exists(): + wall_units_file = gt_dir / 'direct_stats.mat' + + profiles_file = gt_dir / 'profiles.mat' + if not profiles_file.exists(): + profiles_file = gt_dir / 'ensemble_statistics_full.mat' + if not profiles_file.exists(): + profiles_file = gt_dir / 'direct_stats.mat' + + print("\n[1] Loading wall units...") + print(f" Source: {wall_units_file.name}") + wall_units = load_wall_units(wall_units_file) + print(f" u_tau = {wall_units['u_tau']:.4f} mm/s") + print(f" delta_nu = {wall_units['delta_nu']:.4f} mm") + print(f" Re_tau = {wall_units['Re_tau']:.0f}") + + print("\n[2] Loading ground truth (3-component)...") + print(f" Source: {profiles_file.name}") + gt = load_ground_truth_3d(profiles_file) + print(f" y+ range: {gt['y_plus'].min():.1f} to {gt['y_plus'].max():.1f}") + print(f" U range: {gt['U'].min():.2f} to {gt['U'].max():.2f} mm/s") + print(f" W range: {gt['W'].min():.2f} to {gt['W'].max():.2f} mm/s") + + print(f"\n[3] Loading stereo PIV statistics (run {run_idx})...") + piv = load_stereo_statistics(stats_path, coords_path, run_idx=run_idx) + print(f" Grid size: {piv['ux'].shape}") + print(f" ux range: {np.nanmin(piv['ux']):.2f} to {np.nanmax(piv['ux']):.2f} mm/s") + print(f" uz (W) range: {np.nanmin(piv['uz']):.2f} to {np.nanmax(piv['uz']):.2f} mm/s") + + print("\n[4] Computing x-averaged profiles...") + piv_profiles = compute_stereo_profiles(piv, x_min=x_min, x_max=x_max) + print(f" y range: {piv_profiles['y_mm'].min():.2f} to {piv_profiles['y_mm'].max():.2f} mm") + + print("\n[5] Converting to wall units...") + y_offset_mm = -piv_profiles['y_mm'].min() + print(f" Applying y-offset: {y_offset_mm:.2f} mm") + + piv_plus = convert_to_wall_units(piv_profiles, wall_units, y_offset_mm=y_offset_mm) + piv_plus['y_plus'] = piv_plus['y_plus'] + 1.0 # shift y+ by +1 + print(f" y+ range: {piv_plus['y_plus'].min():.1f} to {piv_plus['y_plus'].max():.1f} (after +1 shift)") + + if trim_top > 0: + # Sort by y+ to ensure we trim from the correct end + sort_idx = np.argsort(piv_plus['y_plus']) + for key in piv_plus: + piv_plus[key] = piv_plus[key][sort_idx] + # Now trim the last N points (highest y+) + keep = slice(None, len(piv_plus['y_plus']) - trim_top) + for key in piv_plus: + piv_plus[key] = piv_plus[key][keep] + print(f" Trimmed top {trim_top} highest-y+ points -> {len(piv_plus['y_plus'])} remaining") + print(f" y+ range after trim: {piv_plus['y_plus'].min():.1f} to {piv_plus['y_plus'].max():.1f}") + + # Ground truth in wall units + u_tau = wall_units['u_tau'] + u_tau2 = u_tau ** 2 + gt_plus = { + 'y_plus': gt['y_plus'], + 'U_plus': gt['U_plus'], + 'V_plus': gt['V'] / u_tau, + 'W_plus': gt['W'] / u_tau, + 'uu_plus': gt['uu_plus'], + 'vv_plus': gt['vv_plus'], + 'ww_plus': gt['ww_plus'], + 'uv_plus': gt['uv_plus'], + 'uw_plus': gt['uw'] / u_tau2, + 'vw_plus': gt['vw'] / u_tau2, + } + # Thread CI bounds through if available + for ci_key in ['U_plus_ci_lo', 'U_plus_ci_hi', 'V_plus_ci_lo', 'V_plus_ci_hi', + 'W_plus_ci_lo', 'W_plus_ci_hi', + 'uu_plus_ci_lo', 'uu_plus_ci_hi', 'vv_plus_ci_lo', 'vv_plus_ci_hi', + 'ww_plus_ci_lo', 'ww_plus_ci_hi', + 'uv_plus_ci_lo', 'uv_plus_ci_hi', 'uw_plus_ci_lo', 'uw_plus_ci_hi', + 'vw_plus_ci_lo', 'vw_plus_ci_hi']: + if ci_key in gt: + gt_plus[ci_key] = gt[ci_key] + + print("\n[6] Computing error metrics (y+ = 10-500)...") + errors = compute_errors(piv_plus, gt_plus, y_plus_range=(10, 500)) + + # Print results + print("\n" + "=" * 70) + print("STEREO BENCHMARK RESULTS") + print("=" * 70) + + var_names = { + 'U_plus': 'Streamwise Velocity (U+)', + 'V_plus': 'Wall-normal Velocity (V+)', + 'W_plus': 'Spanwise Velocity (W+)', + 'uu_plus': 'Streamwise Stress (uu+)', + 'vv_plus': 'Wall-normal Stress (vv+)', + 'ww_plus': 'Spanwise Stress (ww+)', + 'uv_plus': 'Shear Stress (uv+)', + 'uw_plus': 'Shear Stress (uw+)', + 'vw_plus': 'Shear Stress (vw+)', + } + + for var, err in errors.items(): + name = var_names.get(var, var) + print(f"\n{name}:") + print(f" RMS Error: {err['rms']:.4f} ({err['rms_rel']:.1f}% of range)") + print(f" R²: {err['r2']:.4f}") + print(f" Correlation: {err['corr']:.4f}") + + print("\n[7] Generating plots...") + plot_velocity_comparison(piv_plus, gt_plus, wall_units, errors, output_dir) + plot_normal_stresses(piv_plus, gt_plus, wall_units, errors, output_dir) + plot_shear_stresses(piv_plus, gt_plus, wall_units, errors, output_dir) + plot_combined_stresses(piv_plus, gt_plus, wall_units, errors, output_dir) + plot_residuals(piv_plus, gt_plus, wall_units, output_dir) + plot_noise_gradient_decomposition(piv_plus, gt_plus, wall_units, output_dir) + + print(f"\nPlots saved to: {output_dir}") + + # Summary table + print("\n" + "=" * 70) + print("SUMMARY TABLE") + print("=" * 70) + print(f"\n{'Variable':<20} {'R²':<10} {'RMS%':<10} {'Corr':<10}") + print("-" * 50) + for var in ['U_plus', 'V_plus', 'W_plus', 'uu_plus', 'vv_plus', 'ww_plus', 'uv_plus', 'uw_plus', 'vw_plus']: + if var in errors: + e = errors[var] + print(f"{var:<20} {e['r2']:<10.4f} {e['rms_rel']:<10.1f} {e['corr']:<10.4f}") + + print("\n" + "=" * 70) + print("STEREO BENCHMARK COMPLETE") + print("=" * 70) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Stereo PIV Benchmark Comparison') + parser.add_argument('--run', '-r', type=int, default=2, + help='Run index (0-based), default=2 (finest available)') + parser.add_argument('--x-min', type=float, default=5.0, + help='Minimum x to include (mm), default=5.0') + parser.add_argument('--x-max', type=float, default=145.0, + help='Maximum x to include (mm), default=145.0') + parser.add_argument('--gt-dir', '-g', type=str, default=None, + help='Ground truth directory path') + parser.add_argument('--stereo-base', '-s', type=str, default=None, + help='Base directory containing stereo PIV results') + parser.add_argument('--num-frames', '-n', type=int, default=1000, + help='Frame count subdirectory in paths (default: 1000)') + parser.add_argument('--output-dir', '-o', type=str, default=None, + help='Custom output directory for results') + parser.add_argument('--trim-top', '-t', type=int, default=0, + help='Number of highest-y+ vectors to exclude (default: 0)') + args = parser.parse_args() + + output_dir = Path(args.output_dir) if args.output_dir else None + main(run_idx=args.run, x_min=args.x_min, x_max=args.x_max, + gt_dir=args.gt_dir, stereo_base=args.stereo_base, + num_frames=args.num_frames, output_dir_override=output_dir, + trim_top=args.trim_top) diff --git a/scripts/tcf_direct_stats.py b/scripts/tcf_direct_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ac5015612034f5ad317a724ac9e257b13546ac --- /dev/null +++ b/scripts/tcf_direct_stats.py @@ -0,0 +1,614 @@ +#!/usr/bin/env python3 +""" +tcf_direct_stats.py — Direct binning statistics for JHTDB channel flow data. + +Reimplements the tcf_mean.m direct binning approach in Python: + - Cosine-stretched (Chebyshev) y-bins for wall-normal resolution + - Single-pass accumulation of velocity moments + - Self-consistent variance: Var = - + - No spatial smoothing bias from convolution + - 2D uniform grid for spatial mean/stress fields + +Reads particle position pairs (B#####_A.data, B#####_B.data) and computes +turbulence statistics (mean velocity, Reynolds stress tensor) in wall units. +""" + +import numpy as np +from pathlib import Path +import time + +from scipy.io import loadmat, savemat + +# ============================================================================ +# CONFIGURATION +# ============================================================================ + +import argparse as _argparse +_parser = _argparse.ArgumentParser(description='Compute ground truth statistics from JHTDB particle data') +_parser.add_argument('--data-dir', '-d', type=str, required=True, + help='Directory containing B#####_A.data / B#####_B.data particle files') +_parser.add_argument('--params-file', '-p', type=str, default=None, + help='Path to download_parameters.mat (default: /../download_parameters.mat)') +_parser.add_argument('--output-dir', '-o', type=str, required=True, + help='Output directory for direct_stats.mat') +_args = _parser.parse_args() + +data_folder = Path(_args.data_dir) +params_file = Path(_args.params_file) if _args.params_file else data_folder.parent / "download_parameters.mat" +output_folder = Path(_args.output_dir) + +n_y = 90 # Number of y-bins (was 64; ~2x near-wall resolution since dy_wall ~ 1/n_y²) + +# 2D grid bin size (mm) — uniform grid for spatial fields +dx_2d = 1.0 +dy_2d = 1.0 + +# DNS Re_tau=1000 fallback constants (used if params file missing fields) +u_tau_nondim = 0.0499 # Friction velocity (non-dimensional) +nu_nondim = 5e-5 # Kinematic viscosity (non-dimensional) + +# ============================================================================ +# STEP 1: Load parameters from download_parameters.mat +# ============================================================================ + +print("=" * 60) +print(" Direct Binning Statistics — JHTDB Channel Flow") +print("=" * 60) +print() + +print(f"Loading parameters from:\n {params_file}") +mat_data = loadmat(str(params_file)) +p = mat_data["params"].flat[0] + +n_frames = int(p["n_frames"].flat[0]) +dt = float(p["dt"].flat[0]) +h_mm = float(p["h_mm"].flat[0]) +Nx = int(p["Nx"].flat[0]) +Ny = int(p["Ny"].flat[0]) +mm_per_pixel = float(p["mm_per_pixel"].flat[0]) +velocity_conv = float(p["velocity_conv"].flat[0]) +length_conv = float(p["length_conv"].flat[0]) + +# Compute wall units +u_tau = u_tau_nondim * velocity_conv # mm/s +nu = nu_nondim * length_conv * velocity_conv # mm^2/s +delta_nu = nu / u_tau # viscous length scale (mm) +Re_tau = h_mm / delta_nu # friction Reynolds number + +print(f"\n--- Physical Parameters ---") +print(f" Channel half-height h = {h_mm:.1f} mm") +print(f" Time step dt = {dt:.6e}") +print(f" Friction velocity u_tau = {u_tau:.4f} mm/s") +print(f" Kinematic viscosity nu = {nu:.2e} mm^2/s") +print(f" Viscous length delta_nu = {delta_nu:.4f} mm") +print(f" Friction Reynolds Re_tau = {Re_tau:.0f}") +print() + +# ============================================================================ +# STEP 2: Scan for frame pairs +# ============================================================================ + +print("Scanning for frame pairs...") +a_files = sorted(data_folder.glob("B*_A.data")) + +frame_pairs = [] +for af in a_files: + stem = af.stem # e.g. "B00001_A" + frame_str = stem.split("_")[0][1:] # e.g. "00001" + bf = af.parent / f"B{frame_str}_B.data" + if bf.exists(): + frame_pairs.append((af, bf, int(frame_str))) + +frame_pairs.sort(key=lambda x: x[2]) +n_available = len(frame_pairs) + +if n_available == 0: + raise RuntimeError(f"No frame pairs found in {data_folder}") + +print(f" Found {n_available} complete frame pairs.") +print(f" Frame range: {frame_pairs[0][2]} to {frame_pairs[-1][2]}") +print() + +# ============================================================================ +# STEP 3: Create cosine-stretched (Chebyshev) y-bins +# ============================================================================ +# Based on tcf_mean.m but restricted to the bottom channel [-h, 0]. +# phi from pi to pi/2 maps cos(phi) from -1 to 0, giving y in [-h, 0]. +# All n_y bins cover the data range — no wasted bins in the empty top channel. + +phi = np.linspace(np.pi, np.pi / 2, n_y + 1) +y_edges = h_mm * np.cos(phi) # -h … 0 +y_centers = 0.5 * (y_edges[:-1] + y_edges[1:]) + +print(f"Chebyshev y-bins: {n_y} bins spanning [{y_edges[0]:.1f}, {y_edges[-1]:.1f}] mm") +print(f" First bin width (near wall): {y_edges[1] - y_edges[0]:.3f} mm") +print(f" Mid bin width (near centre): {y_edges[n_y // 2 + 1] - y_edges[n_y // 2]:.3f} mm") +print() + +# ============================================================================ +# STEP 3b: Create uniform 2D grid for spatial fields +# ============================================================================ +# x in [0, Lx], y in [-h, 0]. Lx determined from params grid. + +Lx = Nx * mm_per_pixel +x2d_edges = np.arange(0, Lx + dx_2d, dx_2d) +y2d_edges = np.arange(-h_mm, 0 + dy_2d, dy_2d) +nx_2d = len(x2d_edges) - 1 +ny_2d = len(y2d_edges) - 1 +x2d_centers = 0.5 * (x2d_edges[:-1] + x2d_edges[1:]) +y2d_centers = 0.5 * (y2d_edges[:-1] + y2d_edges[1:]) + +print(f"2D uniform grid: {nx_2d} x {ny_2d} bins ({dx_2d} x {dy_2d} mm)") +print(f" x range: [0, {Lx:.1f}] mm y range: [{-h_mm:.1f}, 0] mm") +print(f" Resolution: {dx_2d} x {dy_2d} mm = " + f"{dx_2d / mm_per_pixel:.2f} x {dy_2d / mm_per_pixel:.2f} px") +print() + +# Pixel-space coordinate arrays +x2d_centers_px = x2d_centers / mm_per_pixel +y2d_centers_px = (y2d_centers + h_mm) / mm_per_pixel # wall at 0 px, centreline at Ny px +x2d_edges_px = x2d_edges / mm_per_pixel +y2d_edges_px = (y2d_edges + h_mm) / mm_per_pixel + +# ============================================================================ +# STEP 4: Single-pass accumulation (1D Chebyshev + 2D uniform) +# ============================================================================ + +print("Accumulating statistics (single pass)...") + +# --- 1D Chebyshev accumulators --- +n_sum = np.zeros(n_y, dtype=np.float64) +u_sum = np.zeros((n_y, 3), dtype=np.float64) +uu_sum = np.zeros((n_y, 3, 3), dtype=np.float64) + +# --- Per-frame accumulators for bootstrap CI --- +n_per_frame = np.zeros((n_available, n_y), dtype=np.float64) +u_sum_per_frame = np.zeros((n_available, n_y, 3), dtype=np.float64) +uu_sum_per_frame = np.zeros((n_available, n_y, 3, 3), dtype=np.float64) + +# --- 2D uniform grid accumulators (individual components) --- +n_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +# Means +u_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +v_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +w_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +# Second moments (6 unique components of symmetric tensor) +uu_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +vv_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +ww_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +uv_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +uw_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) +vw_sum_2d = np.zeros((nx_2d, ny_2d), dtype=np.float64) + +t_start = time.time() +total_particles = 0 +progress_interval = max(1, n_available // 20) + +for idx, (file_a, file_b, frame_num) in enumerate(frame_pairs): + # Load positions — 3 columns: x, y, z in mm + pos_A = np.loadtxt(str(file_a)) + pos_B = np.loadtxt(str(file_b)) + + if pos_A.shape[0] != pos_B.shape[0]: + print(f" Warning: frame {frame_num} particle count mismatch, skipping.") + continue + + # Velocity = displacement / dt (mm/s) + vel = (pos_B - pos_A) / dt + u, v, w = vel[:, 0], vel[:, 1], vel[:, 2] + + # Midpoint positions for bin assignment + x_mid = 0.5 * (pos_A[:, 0] + pos_B[:, 0]) + y_mid = 0.5 * (pos_A[:, 1] + pos_B[:, 1]) + + # --- 1D Chebyshev accumulation --- + bin_idx = np.digitize(y_mid, y_edges) - 1 # 0-based bin index + valid = (bin_idx >= 0) & (bin_idx < n_y) + bi = bin_idx[valid] + vel_v = vel[valid] + + n_particles = int(valid.sum()) + total_particles += n_particles + + n_frame = np.bincount(bi, minlength=n_y).astype(np.float64) + n_per_frame[idx] = n_frame + n_sum += n_frame + for i in range(3): + u_frame_i = np.bincount(bi, weights=vel_v[:, i], minlength=n_y) + u_sum_per_frame[idx, :, i] = u_frame_i + u_sum[:, i] += u_frame_i + for j in range(3): + uu_frame_ij = np.bincount( + bi, weights=vel_v[:, i] * vel_v[:, j], minlength=n_y + ) + uu_sum_per_frame[idx, :, i, j] = uu_frame_ij + uu_sum[:, i, j] += uu_frame_ij + + # --- 2D uniform grid accumulation --- + ix = np.floor(x_mid / dx_2d).astype(int) + iy = np.floor((y_mid - y2d_edges[0]) / dy_2d).astype(int) + ok = (ix >= 0) & (ix < nx_2d) & (iy >= 0) & (iy < ny_2d) + lin = ix[ok] * ny_2d + iy[ok] + u_ok, v_ok, w_ok = u[ok], v[ok], w[ok] + flat_sz = nx_2d * ny_2d + + n_sum_2d += np.bincount(lin, minlength=flat_sz).reshape(nx_2d, ny_2d) + u_sum_2d += np.bincount(lin, weights=u_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + v_sum_2d += np.bincount(lin, weights=v_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + w_sum_2d += np.bincount(lin, weights=w_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + uu_sum_2d += np.bincount(lin, weights=u_ok * u_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + vv_sum_2d += np.bincount(lin, weights=v_ok * v_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + ww_sum_2d += np.bincount(lin, weights=w_ok * w_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + uv_sum_2d += np.bincount(lin, weights=u_ok * v_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + uw_sum_2d += np.bincount(lin, weights=u_ok * w_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + vw_sum_2d += np.bincount(lin, weights=v_ok * w_ok, minlength=flat_sz).reshape(nx_2d, ny_2d) + + if (idx + 1) % progress_interval == 0 or idx == n_available - 1: + elapsed = time.time() - t_start + print( + f" {idx + 1:>5d}/{n_available} frames " + f"({100 * (idx + 1) / n_available:5.1f}%) — " + f"{total_particles / 1e6:.2f}M particles — {elapsed:.1f}s" + ) + +elapsed = time.time() - t_start +print(f"\n Finished: {n_available} frames, " + f"{total_particles / 1e6:.3f}M particles in {elapsed:.1f}s") +print() + +# ============================================================================ +# STEP 5: Compute statistics +# ============================================================================ + +print("Computing statistics...") + +# --- 1D Chebyshev profiles --- +valid_bins = n_sum > 0 + +u_mean = np.full((n_y, 3), np.nan) +uu_mean = np.full((n_y, 3, 3), np.nan) +u_var = np.full((n_y, 3, 3), np.nan) + +u_mean[valid_bins] = u_sum[valid_bins] / n_sum[valid_bins, None] +uu_mean[valid_bins] = uu_sum[valid_bins] / n_sum[valid_bins, None, None] + +# Reynolds stress tensor: = - +u_var[valid_bins] = ( + uu_mean[valid_bins] + - u_mean[valid_bins, :, None] * u_mean[valid_bins, None, :] +) + +print(f" 1D bins with data: {int(valid_bins.sum())} / {n_y}") + +# --- 2D fields: individual named variables --- +min_count_2d = 10 +ok2d = n_sum_2d >= min_count_2d +N = np.where(ok2d, n_sum_2d, np.nan) + +# Mean velocities (nx_2d x ny_2d each) +U_mean_2d = np.where(ok2d, u_sum_2d / N, np.nan) +V_mean_2d = np.where(ok2d, v_sum_2d / N, np.nan) +W_mean_2d = np.where(ok2d, w_sum_2d / N, np.nan) + +# Mean second moments +UU_mom_2d = np.where(ok2d, uu_sum_2d / N, np.nan) +VV_mom_2d = np.where(ok2d, vv_sum_2d / N, np.nan) +WW_mom_2d = np.where(ok2d, ww_sum_2d / N, np.nan) +UV_mom_2d = np.where(ok2d, uv_sum_2d / N, np.nan) +UW_mom_2d = np.where(ok2d, uw_sum_2d / N, np.nan) +VW_mom_2d = np.where(ok2d, vw_sum_2d / N, np.nan) + +# Reynolds stresses: = - +uu_stress_2d = UU_mom_2d - U_mean_2d * U_mean_2d +vv_stress_2d = VV_mom_2d - V_mean_2d * V_mean_2d +ww_stress_2d = WW_mom_2d - W_mean_2d * W_mean_2d +uv_stress_2d = UV_mom_2d - U_mean_2d * V_mean_2d +uw_stress_2d = UW_mom_2d - U_mean_2d * W_mean_2d +vw_stress_2d = VW_mom_2d - V_mean_2d * W_mean_2d + +print(f" 2D grid cells with data: {int(ok2d.sum())} / {nx_2d * ny_2d}") +print() + +# ============================================================================ +# STEP 5b: Bootstrap 95% confidence intervals (1D profiles) +# ============================================================================ + +N_boot = 2000 +print(f"Bootstrap CI: {N_boot} resamples over {n_available} frames...") +t_boot = time.time() + +rng_boot = np.random.default_rng(42) +stress_boot = np.full((N_boot, n_y, 3, 3), np.nan, dtype=np.float64) +umean_boot = np.full((N_boot, n_y, 3), np.nan, dtype=np.float64) + +for b in range(N_boot): + idx_b = rng_boot.integers(0, n_available, size=n_available) + n_b = n_per_frame[idx_b].sum(axis=0) + u_b = u_sum_per_frame[idx_b].sum(axis=0) + uu_b = uu_sum_per_frame[idx_b].sum(axis=0) + + ok_b = n_b > 0 + mean_b = np.full((n_y, 3), np.nan) + mean_b[ok_b] = u_b[ok_b] / n_b[ok_b, None] + + mom2_b = np.full((n_y, 3, 3), np.nan) + mom2_b[ok_b] = uu_b[ok_b] / n_b[ok_b, None, None] + + var_b = np.full((n_y, 3, 3), np.nan) + var_b[ok_b] = mom2_b[ok_b] - mean_b[ok_b, :, None] * mean_b[ok_b, None, :] + + stress_boot[b] = var_b / u_tau**2 + umean_boot[b] = mean_b / u_tau + +# 95% CI (2.5th and 97.5th percentiles) +stress_ci_lo = np.nanpercentile(stress_boot, 2.5, axis=0) +stress_ci_hi = np.nanpercentile(stress_boot, 97.5, axis=0) +umean_ci_lo = np.nanpercentile(umean_boot, 2.5, axis=0) +umean_ci_hi = np.nanpercentile(umean_boot, 97.5, axis=0) + +print(f" Done in {time.time() - t_boot:.1f}s") +if valid_bins.any(): + mid_bin = n_y // 2 + ci_width = stress_ci_hi[mid_bin, 0, 0] - stress_ci_lo[mid_bin, 0, 0] + print(f" Example u'u'+ CI width at bin {mid_bin}: {ci_width:.4f} wall units") +print() + +# ============================================================================ +# STEP 6: Wall-unit normalization +# ============================================================================ + +y_plus = (h_mm + y_centers) / delta_nu # wall distance in wall units +U_plus = u_mean / u_tau # mean velocity in wall units +stress_plus = u_var / u_tau**2 # Reynolds stresses in wall units + +rng = valid_bins # all bins are in [-h, 0] + +print("Wall-unit normalization:") +print(f" y+ range (with data): " + f"[{np.nanmin(y_plus[rng]):.1f}, {np.nanmax(y_plus[rng]):.1f}]") +print(f" U+ max (streamwise): {np.nanmax(U_plus[rng, 0]):.2f}") +if rng.any(): + peak_uu = np.nanmax(stress_plus[rng, 0, 0]) + peak_yp = y_plus[rng][np.nanargmax(stress_plus[rng, 0, 0])] + print(f" + peak: {peak_uu:.2f} at y+ ~ {peak_yp:.0f}") +print() + +# ============================================================================ +# STEP 7: Save outputs +# ============================================================================ + +output_folder.mkdir(parents=True, exist_ok=True) + +# Collect all 2D fields in a dict for easy saving +fields_2d = { + # Coordinates in mm + "x2d_centers": x2d_centers, + "y2d_centers": y2d_centers, + "x2d_edges": x2d_edges, + "y2d_edges": y2d_edges, + # Coordinates in pixels + "x2d_centers_px": x2d_centers_px, + "y2d_centers_px": y2d_centers_px, + "x2d_edges_px": x2d_edges_px, + "y2d_edges_px": y2d_edges_px, + # Counts + "n_sum_2d": n_sum_2d, + # Mean velocities + "U_mean_2d": U_mean_2d, + "V_mean_2d": V_mean_2d, + "W_mean_2d": W_mean_2d, + # Reynolds stresses + "uu_stress_2d": uu_stress_2d, + "vv_stress_2d": vv_stress_2d, + "ww_stress_2d": ww_stress_2d, + "uv_stress_2d": uv_stress_2d, + "uw_stress_2d": uw_stress_2d, + "vw_stress_2d": vw_stress_2d, +} + +fields_1d = { + "y_centers": y_centers, + "y_edges": y_edges, + "y_plus": y_plus, + "n_sum": n_sum, + "u_mean": u_mean, + "uu_mean": uu_mean, + "u_var": u_var, + "U_plus": U_plus, + "stress_plus": stress_plus, + # Bootstrap 95% CI + "stress_ci_lo": stress_ci_lo, + "stress_ci_hi": stress_ci_hi, + "umean_ci_lo": umean_ci_lo, + "umean_ci_hi": umean_ci_hi, +} + +scalars = { + "h_mm": h_mm, + "u_tau": u_tau, + "delta_nu": delta_nu, + "Re_tau": Re_tau, + "dt": dt, + "n_frames": np.array(n_available), + "mm_per_pixel": mm_per_pixel, + "dx_2d_mm": dx_2d, + "dy_2d_mm": dy_2d, + "dx_2d_px": dx_2d / mm_per_pixel, + "dy_2d_px": dy_2d / mm_per_pixel, +} + +# --- .npz file --- +npz_file = output_folder / "direct_stats.npz" +np.savez(str(npz_file), **fields_1d, **fields_2d, **scalars) +print(f"Saved: {npz_file}") + +# --- .mat file --- +mat_file = output_folder / "direct_stats.mat" +mat_dict = {} +mat_dict.update(fields_1d) +mat_dict.update(fields_2d) +mat_dict.update(scalars) +mat_dict["n_frames"] = n_available # savemat prefers plain int +savemat(str(mat_file), mat_dict) +print(f"Saved: {mat_file}") +print() + +# ============================================================================ +# STEP 8: Validation plots +# ============================================================================ + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +print("Generating validation plots...") + +kappa = 0.41 +B_const = 5.2 + +# ---- Figure 1: Mean velocity profile (semilog U+ vs y+) ---- +fig1, ax1 = plt.subplots(figsize=(8, 5)) + +yp_visc = np.linspace(0.1, 5, 100) +ax1.semilogx(yp_visc, yp_visc, "r-", lw=2, label=r"$U^+ = y^+$") + +yp_log = np.logspace(1, 3, 100) +up_log = (1.0 / kappa) * np.log(yp_log) + B_const +ax1.semilogx( + yp_log, up_log, "k--", lw=2, + label=rf"Log law ($\kappa={kappa}$, $B={B_const}$)", +) + +comp_names = [r"$\langle U_1 \rangle^+$", + r"$\langle U_2 \rangle^+$", + r"$\langle U_3 \rangle^+$"] +for ic in range(3): + ax1.semilogx(y_plus[rng], U_plus[rng, ic], ".-", ms=4, label=comp_names[ic]) + +ax1.set_xlabel(r"$y^+$") +ax1.set_ylabel(r"$U^+$") +ax1.set_title(rf"Mean Velocity Profile ($Re_{{\tau}} = {Re_tau:.0f}$)") +ax1.legend(loc="upper left") +ax1.set_xlim(0.1, Re_tau) +ax1.set_ylim(-0.5, 25) +ax1.grid(True, which="both", alpha=0.3) +fig1.tight_layout() +fig1.savefig(str(output_folder / "fig1_mean_velocity_semilog.png"), dpi=200) +plt.close(fig1) +print(" Fig 1: Mean velocity (semilog U+ vs y+)") + +# ---- Figure 2: Reynolds normal stresses vs y/h ---- +fig2, ax2 = plt.subplots(figsize=(8, 5)) + +diag_labels = [r"$\langle u'_1 u'_1 \rangle^+$", + r"$\langle u'_2 u'_2 \rangle^+$", + r"$\langle u'_3 u'_3 \rangle^+$"] +for i in range(3): + ax2.plot( + stress_plus[rng, i, i], y_centers[rng] / h_mm, ".-", ms=4, + label=diag_labels[i], + ) + +ax2.set_xlabel(r"$\langle u'_i u'_i \rangle^+$") +ax2.set_ylabel(r"$y / h$") +ax2.set_title("Reynolds Normal Stresses") +ax2.legend(loc="best") +ax2.set_xlim(0, 10) +ax2.grid(True, alpha=0.3) +fig2.tight_layout() +fig2.savefig(str(output_folder / "fig2_normal_stresses_yh.png"), dpi=200) +plt.close(fig2) +print(" Fig 2: Reynolds normal stresses vs y/h") + +# ---- Figure 3: Reynolds shear stresses vs y/h ---- +fig3, ax3 = plt.subplots(figsize=(8, 5)) + +shear_pairs = [(0, 1), (0, 2), (1, 2)] +for i, j in shear_pairs: + label = rf"$\langle u'_{i+1} u'_{j+1} \rangle^+$" + ax3.plot( + stress_plus[rng, i, j], y_centers[rng] / h_mm, ".-", ms=4, + label=label, + ) + +yh_theory = np.linspace(-1, 0, 100) +ax3.plot(-(1 + yh_theory), yh_theory, "k-", lw=2, label=r"$-(1+y/h)$") + +ax3.set_xlabel(r"$\langle u'_i u'_j \rangle^+$") +ax3.set_ylabel(r"$y / h$") +ax3.set_title("Reynolds Shear Stresses") +ax3.legend(loc="best") +ax3.set_xlim(-1, 1) +ax3.grid(True, alpha=0.3) +fig3.tight_layout() +fig3.savefig(str(output_folder / "fig3_shear_stresses_yh.png"), dpi=200) +plt.close(fig3) +print(" Fig 3: Reynolds shear stresses vs y/h") + +# ---- Figure 4: Normal stresses vs y+ (semilog x-axis) with 95% CI ---- +fig4, ax4 = plt.subplots(figsize=(8, 5)) + +ci_colors = ["C0", "C1", "C2"] +for i in range(3): + ax4.semilogx( + y_plus[rng], stress_plus[rng, i, i], ".-", ms=4, + color=ci_colors[i], label=diag_labels[i], + ) + ax4.fill_between( + y_plus[rng], + stress_ci_lo[rng, i, i], + stress_ci_hi[rng, i, i], + color=ci_colors[i], alpha=0.2, + label=f"95% CI" if i == 0 else None, + ) + +ax4.set_xlabel(r"$y^+$") +ax4.set_ylabel(r"$\langle u'_i u'_i \rangle^+$") +ax4.set_title("Reynolds Normal Stresses (wall units) — 95% bootstrap CI") +ax4.legend(loc="best") +ax4.set_xlim(0.1, Re_tau) +ax4.set_ylim(0, 10) +ax4.grid(True, which="both", alpha=0.3) +fig4.tight_layout() +fig4.savefig(str(output_folder / "fig4_normal_stresses_yplus.png"), dpi=200) +plt.close(fig4) +print(" Fig 4: Normal stresses vs y+ with 95% CI (semilog)") + +# ---- Figure 5: 2D mean streamwise velocity field ---- +# x horizontal (streamwise), y vertical (wall-normal, wall at bottom) +fig5, ax5 = plt.subplots(figsize=(12, 5)) +im = ax5.pcolormesh( + x2d_centers, y2d_centers + h_mm, U_mean_2d.T, + cmap="viridis", shading="auto", rasterized=True, +) +fig5.colorbar(im, ax=ax5, label=r"$\langle u_x \rangle$ (mm/s)") +ax5.set_xlabel("x (mm)") +ax5.set_ylabel("y (mm, wall at 0)") +ax5.set_title(r"2D mean streamwise velocity $\langle u_x \rangle$") +ax5.set_aspect("equal") +fig5.tight_layout() +fig5.savefig(str(output_folder / "fig5_mean_ux_2d.png"), dpi=250) +plt.close(fig5) +print(" Fig 5: 2D mean streamwise velocity (mm)") + +# ---- Figure 6: 2D mean streamwise velocity in pixel space ---- +fig6, ax6 = plt.subplots(figsize=(12, 5)) +im6 = ax6.pcolormesh( + x2d_centers_px, y2d_centers_px, U_mean_2d.T, + cmap="viridis", shading="auto", rasterized=True, +) +fig6.colorbar(im6, ax=ax6, label=r"$\langle u_x \rangle$ (mm/s)") +ax6.set_xlabel("x (px)") +ax6.set_ylabel("y (px, wall at 0)") +ax6.set_title(r"2D mean streamwise velocity $\langle u_x \rangle$ (pixel coords)") +ax6.set_aspect("equal") +fig6.tight_layout() +fig6.savefig(str(output_folder / "fig6_mean_ux_2d_px.png"), dpi=250) +plt.close(fig6) +print(" Fig 6: 2D mean streamwise velocity (px)") + +print() +print("=" * 60) +print(" All done.") +print(f" Outputs in: {output_folder}") +print("=" * 60) diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_01.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_01.tif new file mode 100644 index 0000000000000000000000000000000000000000..2804013609ecea20aefd6f25abd0dc4e338d2a83 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_01.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_02.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_02.tif new file mode 100644 index 0000000000000000000000000000000000000000..9c2562404b052f635edfdf58e45d05da9b00827f Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_02.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_03.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_03.tif new file mode 100644 index 0000000000000000000000000000000000000000..1e4b2514738a66bb024166afb45a5254d1375cb5 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_03.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_04.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_04.tif new file mode 100644 index 0000000000000000000000000000000000000000..aa08bae2d1ba278bbc9dfcbdeeb9a475a4264db4 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_04.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_05.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_05.tif new file mode 100644 index 0000000000000000000000000000000000000000..bba01888fddb53b594a7f4a30c8ed4418e93ada3 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_05.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_06.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_06.tif new file mode 100644 index 0000000000000000000000000000000000000000..0c3d6dd71d0c7de5d255705df4130e0e28d57721 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_06.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_07.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_07.tif new file mode 100644 index 0000000000000000000000000000000000000000..fdce27c5467f127992e45bff2336184ff684ba28 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_07.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_08.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_08.tif new file mode 100644 index 0000000000000000000000000000000000000000..ae3a0acebb19737336c99b11f68c1201927a208d Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_08.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_09.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_09.tif new file mode 100644 index 0000000000000000000000000000000000000000..a399198811bc3bd16c189e18e8aa7f2f2aa34bca Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_09.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_10.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_10.tif new file mode 100644 index 0000000000000000000000000000000000000000..562d65c4719f6e6963fe83b8824f83f53106efa7 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_10.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_11.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_11.tif new file mode 100644 index 0000000000000000000000000000000000000000..40513d58cdd44473ac8b9f6b6caa95e9be079a3f Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_11.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_12.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_12.tif new file mode 100644 index 0000000000000000000000000000000000000000..4863e833d945ac4674d14f80563ef31cb02a85bf Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_12.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_13.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_13.tif new file mode 100644 index 0000000000000000000000000000000000000000..e780af9428a6577b86eb18ece37b0f2e19a00bd3 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_13.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_14.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_14.tif new file mode 100644 index 0000000000000000000000000000000000000000..4259598a304515ffbf1a2bf987b3625a474410c1 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_14.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_15.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_15.tif new file mode 100644 index 0000000000000000000000000000000000000000..308381d93c4625262d09eee81b22b818325bf958 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_15.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_16.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_16.tif new file mode 100644 index 0000000000000000000000000000000000000000..8741f679a73ed4d9f1a5e2b75e08354e408c16d4 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_16.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_17.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_17.tif new file mode 100644 index 0000000000000000000000000000000000000000..5793cf05530e610ec49384c9d1586bd2deb03264 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_17.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_18.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_18.tif new file mode 100644 index 0000000000000000000000000000000000000000..b3ca7f2df27af90ad2a5ab42ee5e9c7c1489e232 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_18.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_19.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_19.tif new file mode 100644 index 0000000000000000000000000000000000000000..0c145e9e0c544c382285f7689c144203890aab22 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_19.tif differ diff --git a/stereo_noisy/calibration/cam1/planar_calibration_plate_20.tif b/stereo_noisy/calibration/cam1/planar_calibration_plate_20.tif new file mode 100644 index 0000000000000000000000000000000000000000..4cd6394674c8e0bb95ba6468df25b62bac09cde6 Binary files /dev/null and b/stereo_noisy/calibration/cam1/planar_calibration_plate_20.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_01.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_01.tif new file mode 100644 index 0000000000000000000000000000000000000000..c37feea5beba42e5c0f3e999f98368ab546e05ed Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_01.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_02.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_02.tif new file mode 100644 index 0000000000000000000000000000000000000000..1277cc58d51906d1e5322882abcc01832efc424c Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_02.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_03.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_03.tif new file mode 100644 index 0000000000000000000000000000000000000000..8d3ed09108f8fbc693b96bbc50191043e07c9524 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_03.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_04.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_04.tif new file mode 100644 index 0000000000000000000000000000000000000000..8b9dc5143cc77d3e9eb3feabea1f3082bda08742 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_04.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_05.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_05.tif new file mode 100644 index 0000000000000000000000000000000000000000..51af19b7a4e44073afe9b83c137ed8e90c84d37a Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_05.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_06.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_06.tif new file mode 100644 index 0000000000000000000000000000000000000000..47f216ffc591e709f3580546493b880b277e8dc2 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_06.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_07.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_07.tif new file mode 100644 index 0000000000000000000000000000000000000000..c65d943195f31599d28a27607179779eb8e90d59 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_07.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_08.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_08.tif new file mode 100644 index 0000000000000000000000000000000000000000..d8fccc0d752f2135c6138d633e6e8fdaf0fd8d8e Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_08.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_09.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_09.tif new file mode 100644 index 0000000000000000000000000000000000000000..ed85e3b4e57290cae1c9c4677005eace8d3102d2 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_09.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_10.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_10.tif new file mode 100644 index 0000000000000000000000000000000000000000..ec752f0a99dc84be0975f4c5f460bc38f2184da5 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_10.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_11.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_11.tif new file mode 100644 index 0000000000000000000000000000000000000000..1ec1d5dd77188982cd6005f3f66fdb208d54e256 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_11.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_12.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_12.tif new file mode 100644 index 0000000000000000000000000000000000000000..1700c3ce7de6cd7dfd637f864d50c7a69fdd2127 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_12.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_13.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_13.tif new file mode 100644 index 0000000000000000000000000000000000000000..c012565f14e3d5a0f7a7b0cc5d60849dc01568f1 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_13.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_14.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_14.tif new file mode 100644 index 0000000000000000000000000000000000000000..cf0552dc5c224dacf78ac309534a4194e11a053a Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_14.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_15.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_15.tif new file mode 100644 index 0000000000000000000000000000000000000000..0846653f2c0e5e89dca9c0c4be7717f34f5d6797 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_15.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_16.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_16.tif new file mode 100644 index 0000000000000000000000000000000000000000..12133ab67ec48cdc6aa9aa92fb264833dc0ee513 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_16.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_17.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_17.tif new file mode 100644 index 0000000000000000000000000000000000000000..897fb2bbb0983cc502011894354291e2786ab24c Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_17.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_18.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_18.tif new file mode 100644 index 0000000000000000000000000000000000000000..3167a5c686033aba6ee53d4a951a24ea67278aa3 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_18.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_19.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_19.tif new file mode 100644 index 0000000000000000000000000000000000000000..6815caeca282bbd7b068a56dc8cb03a756356693 Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_19.tif differ diff --git a/stereo_noisy/calibration/cam2/planar_calibration_plate_20.tif b/stereo_noisy/calibration/cam2/planar_calibration_plate_20.tif new file mode 100644 index 0000000000000000000000000000000000000000..e47973acd5b9b2ee33f5d93231a3158b295a296d Binary files /dev/null and b/stereo_noisy/calibration/cam2/planar_calibration_plate_20.tif differ