Datasets:
Download scripts/piv_vs_hwa_paper.py from MTT69/TurbulentChannel: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/MTT69/TurbulentChannel/resolve/main/scripts/piv_vs_hwa_paper.py
- Command line
-
hf download hf://datasets/MTT69/TurbulentChannel/scripts/piv_vs_hwa_paper.py
-
curl -L -o piv_vs_hwa_paper.py https://huggingface.co/datasets/MTT69/TurbulentChannel/resolve/main/scripts/piv_vs_hwa_paper.py
10.8 kB
| #!/usr/bin/env python3 | |
| r"""Paper figure: PIVtools (ensemble + instantaneous) vs hot wire -- U^+ and <u'u'>^+. | |
| Cam4, x = 1000 mm. Both PIV pipelines read from the CALIBRATED outputs (ux in | |
| m/s, stresses in m^2/s^2, y in mm with y = 0 at the wall, so NO y+ shift is | |
| applied -- the wall datum lives in the calibration). The hot wire is the | |
| UNCORRECTED profile (variance_poly_corrected = wall-origin corrected, NOT | |
| Hutchins spatial-resolution corrected). | |
| All inputs are argparse-driven (dataset dirs, passes, u_tau, output). Defaults | |
| point at the current Cam4 experimental case. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from pathlib import Path | |
| import h5py | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| import scipy.io as sio # noqa: E402 | |
| matplotlib.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": 21, | |
| "axes.titlesize": 22, | |
| "legend.fontsize": 16, | |
| "xtick.labelsize": 18, | |
| "ytick.labelsize": 18, | |
| "lines.linewidth": 1.8, | |
| "savefig.dpi": 300, | |
| "savefig.bbox": "tight", | |
| }) | |
| ENS_COLOR = "#D55E00" # ensemble (orange-red) | |
| INST_COLOR = "#0072B2" # instantaneous (blue) | |
| HW_COLOR = "k" # hot wire | |
| # Marker convention matches paper_figures.py (synthetic cases): | |
| # reference = solid black line, each PIV method = its own marker, no line. | |
| ENS_MARKER = "s" | |
| INST_MARKERS = ["o", "^", "D"] # one per instantaneous pass | |
| # --------------------------------------------------------------------------- # | |
| # Profile helpers (central-column median about the station, wall-frame y) | |
| # --------------------------------------------------------------------------- # | |
| def _central_profile(field2d, x2d, y2d, bmask, half_mm): | |
| """Median over all columns within +/- half_mm of x = 0 (the station), | |
| masking b_mask == 1. Returns (y_mm, value, n_cols).""" | |
| col_x = np.nanmedian(x2d, axis=0) | |
| cols = np.where(np.abs(col_x) <= half_mm)[0] | |
| if cols.size == 0: | |
| cols = np.array([int(np.nanargmin(np.abs(col_x)))]) | |
| y_mm = np.nanmedian(y2d[:, cols], axis=1) | |
| if bmask is not None: | |
| field2d = np.where(bmask == 0, field2d, np.nan) | |
| val = np.nanmedian(field2d[:, cols], axis=1) | |
| return y_mm, val, cols.size | |
| def load_ensemble(ens_dir: Path, pass_idx: int, half_mm: float): | |
| er = np.atleast_1d(sio.loadmat(str(ens_dir / "ensemble_result.mat"), | |
| squeeze_me=True, struct_as_record=False)["ensemble_result"])[pass_idx] | |
| co = np.atleast_1d(sio.loadmat(str(ens_dir / "coordinates.mat"), | |
| squeeze_me=True, struct_as_record=False)["coordinates"])[pass_idx] | |
| ux = np.asarray(er.ux, float) | |
| uu = np.asarray(er.UU_stress, float) | |
| bm = np.asarray(er.b_mask, float) if hasattr(er, "b_mask") else None | |
| x = np.asarray(co.x, float) | |
| y = np.asarray(co.y, float) | |
| y_mm, U, n = _central_profile(ux, x, y, bm, half_mm) | |
| _, R, _ = _central_profile(uu, x, y, bm, half_mm) | |
| return y_mm, U, R, n | |
| def load_instantaneous(mean_stats: Path, pass_idx: int, half_mm: float): | |
| ms = sio.loadmat(str(mean_stats), squeeze_me=True, struct_as_record=False) | |
| p = np.atleast_1d(ms["piv_result"])[pass_idx] | |
| c = np.atleast_1d(ms["coordinates"])[pass_idx] | |
| ux = np.asarray(p.ux, float) | |
| uu = np.asarray(p.uu, float) | |
| bm = np.asarray(p.b_mask, float) if hasattr(p, "b_mask") else None | |
| x = np.asarray(c.x, float) | |
| y = np.asarray(c.y, float) | |
| y_mm, U, n = _central_profile(ux, x, y, bm, half_mm) | |
| _, R, _ = _central_profile(uu, x, y, bm, half_mm) | |
| return y_mm, U, R, n | |
| def _running_median(v, k): | |
| if k <= 1: | |
| return v | |
| h = k // 2 | |
| out = np.full_like(v, np.nan, dtype=float) | |
| for i in range(v.size): | |
| seg = v[max(0, i - h):i + h + 1] | |
| if np.any(np.isfinite(seg)): | |
| out[i] = np.nanmedian(seg) | |
| return out | |
| def log_smooth(y_plus, values, sigma_decades=0.06): | |
| """LOWESS-style local-linear fit in log(y+) space (display smoothing).""" | |
| valid = (y_plus > 0) & ~np.isnan(values) | |
| yp, vals = y_plus[valid], values[valid] | |
| if len(yp) < 5: | |
| return yp, vals | |
| order = np.argsort(yp) | |
| yp, vals = yp[order], vals[order] | |
| lyp = np.log10(yp) | |
| out = np.empty_like(vals) | |
| for i in range(len(vals)): | |
| d = (lyp - lyp[i]) / sigma_decades | |
| w = np.exp(-0.5 * d * d) | |
| ws = w.sum() | |
| mx, my = (w * lyp).sum() / ws, (w * vals).sum() / ws | |
| dx = lyp - mx | |
| den = (w * dx * dx).sum() | |
| out[i] = my + ((w * dx * vals).sum() / den) * (lyp[i] - mx) if den > 1e-30 else my | |
| return yp, out | |
| def piv_inner(y_mm, U, R, utau, nu, y_lo, y_hi, stress_smooth, drop_nearest=0): | |
| """Wall-frame profile -> inner units (wall at y = 0, so no shift). | |
| ``drop_nearest`` discards the N points closest to the wall (after the | |
| [y_lo, y_hi] gate) -- the railed first rows that are not physical.""" | |
| good = np.isfinite(y_mm) & np.isfinite(U) & (y_mm >= y_lo) & (y_mm <= y_hi) | |
| yp = y_mm[good] * 1e-3 * utau / nu | |
| Up = U[good] / utau | |
| Rp = R[good] / utau**2 | |
| order = np.argsort(yp) | |
| yp, Up, Rp = yp[order], Up[order], Rp[order] | |
| if drop_nearest > 0: | |
| yp, Up, Rp = yp[drop_nearest:], Up[drop_nearest:], Rp[drop_nearest:] | |
| return yp, Up, _running_median(Rp, stress_smooth) | |
| def load_hwa_uncorrected(hwa_mat: Path): | |
| with h5py.File(str(hwa_mat), "r") as f: | |
| c = f["caseData"] | |
| y = np.array(c["y_corrected_poly"]).ravel() # m | |
| U = np.array(c["meanvel_poly_corrected"]).ravel() # m/s | |
| uu = np.array(c["variance_poly_corrected"]).ravel() # m^2/s^2 (uncorrected) | |
| return y, U, uu | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument("--ens-dir", type=Path, required=True, | |
| help="calibrated ensemble dir (…/calibrated_piv/…/Cam1/ensemble)") | |
| ap.add_argument("--inst-stats", type=Path, required=True, | |
| help="instantaneous mean_stats.mat") | |
| ap.add_argument("--hwa", type=Path, required=True, | |
| help="hot-wire .mat with caseData (y_corrected_poly, " | |
| "meanvel_poly_corrected, variance_poly_corrected)") | |
| ap.add_argument("--ens-pass", type=int, default=2, help="1-based ensemble pass") | |
| ap.add_argument("--inst-pass", type=int, nargs="+", default=[2], | |
| help="1-based instantaneous pass(es); one line per pass") | |
| ap.add_argument("--inst-labels", type=str, nargs="+", default=None, | |
| help="legend label per instantaneous pass (e.g. '16x96 px')") | |
| ap.add_argument("--utau-piv", type=float, default=0.701) | |
| ap.add_argument("--utau-hwa", type=float, default=0.681) | |
| ap.add_argument("--nu", type=float, default=1.4942813452344682e-05) | |
| ap.add_argument("--half-mm", type=float, default=4.0) | |
| ap.add_argument("--y-lo", type=float, default=0.25) | |
| ap.add_argument("--y-hi", type=float, default=185.0) | |
| ap.add_argument("--stress-smooth", type=int, default=7) | |
| ap.add_argument("--drop-nearest", type=int, default=0, | |
| help="drop the N wall-nearest points from each PIV profile") | |
| ap.add_argument("--ens-stress-lowess", type=float, default=0.06) | |
| ap.add_argument("--out", type=Path, required=True) | |
| a = ap.parse_args() | |
| if a.inst_labels is not None and len(a.inst_labels) != len(a.inst_pass): | |
| ap.error("--inst-labels must match --inst-pass in length") | |
| yE, UE, RE, nE = load_ensemble(a.ens_dir, a.ens_pass - 1, a.half_mm) | |
| ypE, UpE, uupE = piv_inner(yE, UE, RE, a.utau_piv, a.nu, a.y_lo, a.y_hi, | |
| a.stress_smooth, a.drop_nearest) | |
| inst_profiles = [] | |
| for k, ip in enumerate(a.inst_pass): | |
| yI, UI, RI, nI = load_instantaneous(a.inst_stats, ip - 1, a.half_mm) | |
| ypI, UpI, uupI = piv_inner(yI, UI, RI, a.utau_piv, a.nu, a.y_lo, a.y_hi, | |
| a.stress_smooth, a.drop_nearest) | |
| lbl = (a.inst_labels[k] if a.inst_labels | |
| else f"pass {ip}") | |
| inst_profiles.append((lbl, ypI, UpI, uupI)) | |
| print(f"[avg] instantaneous pass {ip} ({lbl}): {nI} cols") | |
| print(f"[avg] +/-{a.half_mm} mm band -> ensemble {nE} cols") | |
| yh, Uh, uuh = load_hwa_uncorrected(a.hwa) | |
| yp_hw = yh * a.utau_hwa / a.nu | |
| Up_hw = Uh / a.utau_hwa | |
| uup_hw = uuh / a.utau_hwa**2 | |
| ens_lbl = "PIVtools ensemble" | |
| inst_colors = [INST_COLOR, "#CC79A7", "#56B4E9"] # Okabe-Ito, one per pass | |
| fig, ax = plt.subplots(1, 2, figsize=(14, 6)) | |
| a0 = ax[0] | |
| a0.plot(yp_hw, Up_hw, "-", color=HW_COLOR, lw=2, label="Hot wire", zorder=10) | |
| a0.plot(ypE, UpE, ENS_MARKER, color=ENS_COLOR, ms=4.5, alpha=0.7, | |
| linestyle="none", label=ens_lbl, zorder=5) | |
| for k, (lbl, ypI, UpI, _) in enumerate(inst_profiles): | |
| a0.plot(ypI, UpI, INST_MARKERS[k % len(INST_MARKERS)], | |
| color=inst_colors[k % len(inst_colors)], ms=4.5, alpha=0.7, | |
| linestyle="none", label=f"PIVtools inst. {lbl}", zorder=4) | |
| a0.set_xscale("log"); a0.set_xlim(8, 8000); a0.set_ylim(0, 30) | |
| a0.grid(True, which="both", alpha=0.3) | |
| a0.set_xlabel(r"$y^+$"); a0.set_ylabel(r"$U^+$"); a0.set_title("Mean velocity") | |
| a0.legend(loc="upper left") | |
| a1 = ax[1] | |
| a1.plot(yp_hw, uup_hw, "-", color=HW_COLOR, lw=2, | |
| label="Hot wire (uncorrected)", zorder=10) | |
| if a.ens_stress_lowess and a.ens_stress_lowess > 0: | |
| a1.plot(ypE, uupE, "-", color=ENS_COLOR, lw=0.7, alpha=0.22) | |
| s_yp, s_v = log_smooth(ypE, uupE, sigma_decades=a.ens_stress_lowess) | |
| a1.plot(s_yp, s_v, ENS_MARKER, color=ENS_COLOR, ms=4.5, alpha=0.7, | |
| linestyle="none", label=ens_lbl, zorder=5) | |
| else: | |
| a1.plot(ypE, uupE, ENS_MARKER, color=ENS_COLOR, ms=4.5, alpha=0.7, | |
| linestyle="none", label=ens_lbl, zorder=5) | |
| for k, (lbl, ypI, _, uupI) in enumerate(inst_profiles): | |
| a1.plot(ypI, uupI, INST_MARKERS[k % len(INST_MARKERS)], | |
| color=inst_colors[k % len(inst_colors)], ms=4.5, alpha=0.7, | |
| linestyle="none", label=f"PIVtools inst. {lbl}", zorder=4) | |
| a1.set_xscale("log"); a1.set_xlim(8, 8000) | |
| a1.set_ylim(0, max(12, np.nanmax(uup_hw) * 1.15)) | |
| a1.grid(True, which="both", alpha=0.3) | |
| a1.set_xlabel(r"$y^+$"); a1.set_ylabel(r"$\langle u'u'\rangle^+$") | |
| a1.set_title("Streamwise Reynolds stress") | |
| a1.legend(loc="upper right") | |
| fig.tight_layout() | |
| a.out.parent.mkdir(parents=True, exist_ok=True) | |
| fig.savefig(str(a.out)) | |
| print(f"[figure] wrote {a.out}") | |
| if __name__ == "__main__": | |
| main() | |