Datasets:
Add extraction utilities and dataset notes
Browse files- data/README.md +44 -0
- data/README_2D_cases.md +42 -0
- data/commented_dat_to_csv.py +106 -0
- data/dat_to_csv.py +109 -0
- data/extract_baseline_from_vtk.py +317 -0
- data/extract_wbj_surface_lines.py +102 -0
- data/faith_hill_to_csv.py +161 -0
data/README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Extended 3D Dataset — NeurIPS Closure Challenge additions
|
| 2 |
+
|
| 3 |
+
Three 3D cases added to extend the closure challenge beyond the existing 2D set:
|
| 4 |
+
|
| 5 |
+
| Folder | Case | Source | Required metrics |
|
| 6 |
+
|--------|------|--------|------------------|
|
| 7 |
+
| `ERCOFTAC_AhmedBody25/` | Ahmed Body 25° slant | ERCOFTAC case082 (Lienhart-Becker-Stoots 2003) | LDA velocity + Reynolds stresses on canonical x-z and y-z planes; rear surface Cp |
|
| 8 |
+
| `NASA_FaithHill/` | Faith Hill 3-D smooth-body separation | NASA TMR (Bell et al. 2012) | PIV centerline U/V/W + Reynolds stresses; PSP centerline Cp; FISF surface Cf |
|
| 9 |
+
| `ERCOFTAC_WingBodyJunction/` | Wing-body junction (NACA0020) | ERCOFTAC kbwiki DNS 1-6 (Bassi et al. 2023) | 10 symmetry-plane profiles upstream of root; bottom-wall + wing-root Cp lines |
|
| 10 |
+
|
| 11 |
+
## Per-case layout
|
| 12 |
+
```
|
| 13 |
+
<CASE>/
|
| 14 |
+
├── README.md case description, refs, submission format
|
| 15 |
+
├── 0/, <converged>/, constant/,
|
| 16 |
+
│ system/, postProcessing/ OpenFOAM case (rsync from OF_Baseline_Cases)
|
| 17 |
+
├── baseline_komegasst/ k-ω SST RANS extracted at experimental locations (.csv)
|
| 18 |
+
├── highfidelity/ LDA / PIV / DNS reference data (.csv + raw .dat where applicable)
|
| 19 |
+
└── plots/
|
| 20 |
+
├── plot_profiles.py set MODEL_DIR env var to overlay submitted model
|
| 21 |
+
└── *.pdf pre-rendered baseline-vs-experiment figures
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Tools at this level
|
| 25 |
+
- `commented_dat_to_csv.py` — converts simple `#`-commented headed .dat files (Ahmed format) to flat CSV
|
| 26 |
+
- `faith_hill_to_csv.py` — Faith Hill ingester; merges 14 single-scalar Tecplot POINT files per PIV dataset into one CSV; converts PSP and FISF too
|
| 27 |
+
- `extract_wbj_surface_lines.py` — Python+vtk script that reads the WingBody surface `.pvtu+_NNNN.vtu` partitioned files and extracts bottom-wall centerline (z/T=0) and wing-root chord (y/T~0.05) Cp strips
|
| 28 |
+
|
| 29 |
+
Re-run any of these by passing the source dir/file as arg.
|
| 30 |
+
|
| 31 |
+
## Cases skipped or excluded
|
| 32 |
+
- **Ahmed Body 35°**: 35° configuration data is in the same archive but excluded from this packaging — only the canonical 25° case (the famous one bracketing the critical 30° angle) is shipped.
|
| 33 |
+
- **Faith Hill Cobra probe**: 4-hole probe with 40° acceptance cone — cannot measure inside reverse-flow regions. Including it would mislead participants. PIV is the velocity reference; Cobra is intentionally not provided.
|
| 34 |
+
- **DNS 1-6 volume data**: 60–70 GB per scalar field (averaged_pressure, averaged_velocity_{x,y,z}, Reynolds_stress_{xx,xy,...,zz}, Taylor/Kolmogorov scales). Far too large to ship. The 10 pre-curated profile CSVs + 2 surface line CSVs (~5 MB total) are the curated equivalent.
|
| 35 |
+
|
| 36 |
+
## Decisions log (2026-04-29)
|
| 37 |
+
- Case naming: mixed prefixes — `NASA_FaithHill` (NASA TMR), `ERCOFTAC_AhmedBody25` and `ERCOFTAC_WingBodyJunction` (ERCOFTAC sources). Reflects source authority.
|
| 38 |
+
- Faith Hill OF: case is non-dimensional (U_inlet=1.0); sampled p maps to Cp directly. Documented in case README.
|
| 39 |
+
- Wing-body 5000/ extra fields (`Pk, PkDelta, Prodk, Rall, nutSwitch`) kept as-is (matches "keep as is" preference).
|
| 40 |
+
- Wing-body surface data: ship BOTH the extracted CSV centerline lines (primary) AND the raw partitioned `.pvtu+_NNNN.vtu` archives in `highfidelity/raw_surface/` (~298 MB) for full self-containment.
|
| 41 |
+
- Wing-body OF: WBJ provides constant/system/postProcessing/log; **time dirs 0 and 5000 are taken from `revised_inflow/`** (Inlet pressure changed from `zeroGradient` to `fixedValue uniform 0` — better convergence). 90+14 Windows `:Zone.Identifier` files skipped on copy.
|
| 42 |
+
|
| 43 |
+
## TODO
|
| 44 |
+
- `baseline_komegasst/` content per case — needs OpenFOAM post-hoc sampling at experimental locations. See `*/run_baseline_extraction.sh` (per-case script).
|
data/README_2D_cases.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Extended 2D Dataset — NeurIPS Closure Challenge additions
|
| 2 |
+
|
| 3 |
+
Three new 2D cases added to the closure challenge from the **NASA TMR Collaborative Testing Challenge 2022** ([turb-prs2022](https://tmbwg.github.io/turbmodels/turb-prs2022.html)):
|
| 4 |
+
|
| 5 |
+
| Folder | Case | Required metrics |
|
| 6 |
+
|--------|------|------------------|
|
| 7 |
+
| `NASA_2DZP/` | 2D Zero-Pressure-Gradient flat plate | Cf(x); u⁺(log y⁺) at x=0.97 — vs theory |
|
| 8 |
+
| `NASA_ASJ/` | Axisymmetric Subsonic Jet (M_jet ≈ 0.5) | u/Uj along axis; u/Uj and u'v'/Uj² at 5 stations — vs Bridges & Wernet PIV |
|
| 9 |
+
| `NASA_2DN00/` | NACA 0012 airfoil, α = 10/15/17/18° | CL(α), CD vs CL, Cp(x/c), Cf(x/c upper) — vs Ladson + Gregory |
|
| 10 |
+
|
| 11 |
+
## Per-case layout
|
| 12 |
+
```
|
| 13 |
+
NASA_<CASE>/
|
| 14 |
+
├── README.md Case description, refs, submission format
|
| 15 |
+
├── baseline_komegasst/ k-ω SST RANS baseline (.dat NASA Tecplot + .csv flat)
|
| 16 |
+
│ └── README.md
|
| 17 |
+
├── highfidelity/ Theory / experiment / CFD-cross-check references
|
| 18 |
+
│ └── README.md
|
| 19 |
+
└── plots/
|
| 20 |
+
├── plot_profiles.py Adapt: set MODEL_DIR env var to overlay your model
|
| 21 |
+
└── *.pdf Pre-rendered baseline-vs-experiment plots
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Tools at this level
|
| 25 |
+
- `dat_to_csv.py` — converts NASA Tecplot zone-format `.dat` files to flat CSV (single `zone` column to preserve zone identity). Re-run after editing data:
|
| 26 |
+
```
|
| 27 |
+
python dat_to_csv.py NASA_2DZP/baseline_komegasst NASA_2DZP/highfidelity \
|
| 28 |
+
NASA_ASJ/baseline_komegasst NASA_ASJ/highfidelity \
|
| 29 |
+
NASA_2DN00/baseline_komegasst NASA_2DN00/highfidelity
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Provenance
|
| 33 |
+
All `.dat` files copied from `OLD_NASA_CHALLENGE_SUBMISSION/finalModel/` (a baseline RANS submission to the 2022 NASA TMR Collaborative Testing Challenge), folders `baselineResults/` (k-ω SST baseline) and `NASAResults/` (theory / experiment) — see [plotFinal.py:10-14](OLD_NASA_CHALLENGE_SUBMISSION/finalModel/plotFinal.py#L10-L14) for the original mapping. The corresponding OpenFOAM cases live under `OLD_SETUPS/{00_2DZP, 02_ASJ, 04_2DN00}/00Baseline/`.
|
| 34 |
+
|
| 35 |
+
## TODO — full OpenFOAM `00Baseline_Data/` per case
|
| 36 |
+
The integral profiles + plots are complete. To match the structure of the existing 4 challenge cases (`ML4Fluids_2D_Dataset/{CBFS, NASA_2DWMH, PH_Breuer, Parm_PH_29}/00Baseline_Data/`), each new case still needs the converged k-ω SST OpenFOAM run packaged. Candidate sources:
|
| 37 |
+
|
| 38 |
+
| Case | OpenFOAM source | Notes |
|
| 39 |
+
|------|-----------------|-------|
|
| 40 |
+
| 2DZP | `OLD_SETUPS/00_2DZP/00Baseline/simpleFoam/` | `kOmegaSST`, converged at t=10000 |
|
| 41 |
+
| ASJ | `OLD_SETUPS/02_ASJ/BaselineRenzhi/Case/` or `00Baseline/CFDDomain/compressibleTransient/` | both `kOmegaSST`; pick one |
|
| 42 |
+
| 2DN00 | `OLD_SETUPS/04_2DN00/00Baseline/rhoSimpleFoam_Final/Case2/{10,15,17,18}_deg/` | only initial state — needs to be run, OR use the per-AoA cases under `OLD_NASA_CHALLENGE_SUBMISSION/finalModel/04_2DN00/` (latter were run with `propagationClassifierkOmegaSST` augmented model, not pure baseline) |
|
data/commented_dat_to_csv.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert simple commented-header .dat files (Ahmed Body, Faith Hill PIV/PSP/FISF
|
| 2 |
+
formats) to flat CSV.
|
| 3 |
+
|
| 4 |
+
Different from the NASA Tecplot zone parser (Extended_2D_Dataset/dat_to_csv.py).
|
| 5 |
+
These .dat files are:
|
| 6 |
+
- Header: any number of '#'-prefixed lines
|
| 7 |
+
- The last '#' line contains the column names, possibly with units in brackets
|
| 8 |
+
- Data: whitespace-separated floats, one row per measurement point
|
| 9 |
+
|
| 10 |
+
Usage:
|
| 11 |
+
python commented_dat_to_csv.py <dir_or_file> [<dir_or_file> ...]
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import sys
|
| 15 |
+
import os
|
| 16 |
+
import re
|
| 17 |
+
import glob
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Match e.g. "x[mm]" or "U[m/s]" -> capture name and unit
|
| 23 |
+
_NAMED_UNIT_RE = re.compile(r'(\S+?)\[([^\]]+)\]')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _parse_columns_from_header_line(line):
|
| 27 |
+
"""Parse a header line like '# x[mm] y[mm] z[mm] U[m/s] ...' -> list of column names.
|
| 28 |
+
|
| 29 |
+
Spatial coords gain a unit suffix ("x_mm", "y_in", "z_m") so downstream tooling
|
| 30 |
+
can map experiment coords to the OF mesh scale unambiguously. Non-spatial
|
| 31 |
+
columns retain their original names.
|
| 32 |
+
"""
|
| 33 |
+
s = line.lstrip('#').strip()
|
| 34 |
+
out = []
|
| 35 |
+
for tok in s.split():
|
| 36 |
+
m = _NAMED_UNIT_RE.match(tok)
|
| 37 |
+
if not m:
|
| 38 |
+
out.append(tok)
|
| 39 |
+
continue
|
| 40 |
+
name, unit = m.group(1), m.group(2).strip()
|
| 41 |
+
# only attach unit suffix to spatial coordinate columns
|
| 42 |
+
if name.lower() in ('x', 'y', 'z') and unit in ('mm', 'm', 'in', 'cm'):
|
| 43 |
+
out.append(f'{name}_{unit}')
|
| 44 |
+
else:
|
| 45 |
+
out.append(name)
|
| 46 |
+
return out
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def read_commented_dat(path):
|
| 50 |
+
"""Read a commented-header .dat file -> pandas DataFrame.
|
| 51 |
+
|
| 52 |
+
The last header line beginning with '#' is treated as the column-name line.
|
| 53 |
+
All other '#' lines are skipped. Data rows are whitespace-separated floats.
|
| 54 |
+
"""
|
| 55 |
+
with open(path) as f:
|
| 56 |
+
lines = f.readlines()
|
| 57 |
+
|
| 58 |
+
last_header_idx = -1
|
| 59 |
+
for i, line in enumerate(lines):
|
| 60 |
+
if line.lstrip().startswith('#'):
|
| 61 |
+
last_header_idx = i
|
| 62 |
+
else:
|
| 63 |
+
if line.strip():
|
| 64 |
+
break
|
| 65 |
+
|
| 66 |
+
if last_header_idx < 0:
|
| 67 |
+
raise ValueError(f'{path}: no commented header found')
|
| 68 |
+
|
| 69 |
+
columns = _parse_columns_from_header_line(lines[last_header_idx])
|
| 70 |
+
data = np.genfromtxt(path, comments='#')
|
| 71 |
+
if data.ndim == 1:
|
| 72 |
+
data = data.reshape(1, -1)
|
| 73 |
+
|
| 74 |
+
if data.shape[1] != len(columns):
|
| 75 |
+
# Some files have variables labeled with extra '*' or unusual chars;
|
| 76 |
+
# fall back to generic col_N names if mismatch
|
| 77 |
+
columns = [f'col_{i}' for i in range(data.shape[1])]
|
| 78 |
+
|
| 79 |
+
return pd.DataFrame(data, columns=columns)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def convert_path(path):
|
| 83 |
+
if os.path.isdir(path):
|
| 84 |
+
for dat in sorted(glob.glob(os.path.join(path, '*.dat'))):
|
| 85 |
+
convert_path(dat)
|
| 86 |
+
return
|
| 87 |
+
if not path.lower().endswith('.dat'):
|
| 88 |
+
return
|
| 89 |
+
try:
|
| 90 |
+
df = read_commented_dat(path)
|
| 91 |
+
except Exception as exc:
|
| 92 |
+
print(f' FAILED {path}: {exc}')
|
| 93 |
+
return
|
| 94 |
+
csv_path = path[:-4] + '.csv'
|
| 95 |
+
df.to_csv(csv_path, index=False)
|
| 96 |
+
print(f' {os.path.basename(path)} -> {os.path.basename(csv_path)}'
|
| 97 |
+
f' ({len(df)} rows, {len(df.columns)} cols)')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == '__main__':
|
| 101 |
+
if len(sys.argv) < 2:
|
| 102 |
+
print(__doc__)
|
| 103 |
+
sys.exit(1)
|
| 104 |
+
for arg in sys.argv[1:]:
|
| 105 |
+
print(f'\n[{arg}]')
|
| 106 |
+
convert_path(arg)
|
data/dat_to_csv.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert NASA Tecplot-zone .dat files to flat CSV.
|
| 2 |
+
|
| 3 |
+
Each .dat file in a given directory is read via the same parser used in
|
| 4 |
+
the original NASA challenge submission (readNasaZoneFile), then flattened
|
| 5 |
+
to a single CSV with one row per (zone, sample) and a `zone` column to
|
| 6 |
+
preserve the multi-zone structure.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python dat_to_csv.py <dir1> [<dir2> ...]
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
import os
|
| 14 |
+
import glob
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _text_in_line(line):
|
| 20 |
+
if line == '':
|
| 21 |
+
return False
|
| 22 |
+
return max(
|
| 23 |
+
[(ord(c) > 96) & (ord(c) < 101) | (ord(c) > 101) & (ord(c) < 123)
|
| 24 |
+
for c in line.lower()]
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def read_nasa_zone_file(path):
|
| 29 |
+
"""Parse a NASA Tecplot-zone .dat file into a dict {zone: {var: array}}."""
|
| 30 |
+
with open(path) as f:
|
| 31 |
+
data = f.read()
|
| 32 |
+
|
| 33 |
+
data_lower = data.lower()
|
| 34 |
+
|
| 35 |
+
var_start = data_lower.find('variables')
|
| 36 |
+
var_end = var_start + data_lower[var_start:].find('\n')
|
| 37 |
+
var_line = data[var_start:var_end]
|
| 38 |
+
variables = var_line.split('"')[1::2]
|
| 39 |
+
|
| 40 |
+
zones = []
|
| 41 |
+
zone_inds = []
|
| 42 |
+
data_start_inds = []
|
| 43 |
+
find_data_start = False
|
| 44 |
+
|
| 45 |
+
if 'zone' not in data_lower:
|
| 46 |
+
zones.append('zone')
|
| 47 |
+
zone_inds.append(0)
|
| 48 |
+
find_data_start = True
|
| 49 |
+
|
| 50 |
+
lines = data.split('\n')
|
| 51 |
+
lower_lines = data_lower.split('\n')
|
| 52 |
+
for i, (line, lower) in enumerate(zip(lines, lower_lines)):
|
| 53 |
+
if 'zone t=' in lower or 'zone, t=' in lower:
|
| 54 |
+
zones.append(line.split('"')[1])
|
| 55 |
+
zone_inds.append(i)
|
| 56 |
+
find_data_start = True
|
| 57 |
+
if find_data_start and not _text_in_line(line):
|
| 58 |
+
data_start_inds.append(i)
|
| 59 |
+
find_data_start = False
|
| 60 |
+
|
| 61 |
+
zone_inds.append(i + 1)
|
| 62 |
+
|
| 63 |
+
out = {}
|
| 64 |
+
for i, zone in enumerate(zones):
|
| 65 |
+
buff = np.genfromtxt(
|
| 66 |
+
path,
|
| 67 |
+
skip_header=data_start_inds[i],
|
| 68 |
+
max_rows=zone_inds[i + 1] - data_start_inds[i],
|
| 69 |
+
)
|
| 70 |
+
if buff.ndim == 1:
|
| 71 |
+
buff = buff.reshape(1, -1)
|
| 72 |
+
out[zone] = {variables[j]: buff[:, j] for j in range(len(variables))}
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def dat_to_dataframe(path):
|
| 77 |
+
zones = read_nasa_zone_file(path)
|
| 78 |
+
frames = []
|
| 79 |
+
for zone_name, var_dict in zones.items():
|
| 80 |
+
df = pd.DataFrame(var_dict)
|
| 81 |
+
df.insert(0, 'zone', zone_name)
|
| 82 |
+
frames.append(df)
|
| 83 |
+
return pd.concat(frames, ignore_index=True)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def convert_directory(directory):
|
| 87 |
+
dat_files = sorted(glob.glob(os.path.join(directory, '*.dat')))
|
| 88 |
+
if not dat_files:
|
| 89 |
+
print(f' (no .dat files in {directory})')
|
| 90 |
+
return
|
| 91 |
+
for dat_path in dat_files:
|
| 92 |
+
try:
|
| 93 |
+
df = dat_to_dataframe(dat_path)
|
| 94 |
+
except Exception as exc:
|
| 95 |
+
print(f' FAILED {dat_path}: {exc}')
|
| 96 |
+
continue
|
| 97 |
+
csv_path = dat_path[:-4] + '.csv'
|
| 98 |
+
df.to_csv(csv_path, index=False)
|
| 99 |
+
print(f' {os.path.basename(dat_path)} -> {os.path.basename(csv_path)}'
|
| 100 |
+
f' ({len(df)} rows, {len(df.columns)} cols)')
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == '__main__':
|
| 104 |
+
if len(sys.argv) < 2:
|
| 105 |
+
print(__doc__)
|
| 106 |
+
sys.exit(1)
|
| 107 |
+
for d in sys.argv[1:]:
|
| 108 |
+
print(f'\n[{d}]')
|
| 109 |
+
convert_directory(d)
|
data/extract_baseline_from_vtk.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extract baseline RANS at experimental locations using foamToVTK + Python+vtk.
|
| 2 |
+
|
| 3 |
+
Usage (per-case): the per-case shell script `run_baseline_extraction.sh` invokes
|
| 4 |
+
this module after producing a VTK/<case>_<time>.vtk file via foamToVTK.
|
| 5 |
+
|
| 6 |
+
Approach: the VTK volume is a vtkUnstructuredGrid containing U, k, omega, p, nut.
|
| 7 |
+
For each experimental measurement location, we use vtkProbeFilter with a
|
| 8 |
+
vtkPolyData of the experiment points to interpolate the volume fields onto
|
| 9 |
+
those exact (x,y,z). Output: one CSV per highfidelity .csv with the same
|
| 10 |
+
(x, y, z) coords replaced by sampled (U, V, W, k, omega, p, nut).
|
| 11 |
+
|
| 12 |
+
Reynolds stresses are computed from Boussinesq:
|
| 13 |
+
R_ij = (2/3) k delta_ij - nut * (dU_i/dx_j + dU_j/dx_i)
|
| 14 |
+
gradU is computed via vtkGradientFilter on the volume.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import glob
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
import vtk
|
| 23 |
+
from vtk.util import numpy_support as ns
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_volume(vtk_path):
|
| 27 |
+
"""Load a foamToVTK output (legacy .vtk or .vtu/.pvtu) -> vtkUnstructuredGrid."""
|
| 28 |
+
if vtk_path.endswith('.vtk'):
|
| 29 |
+
reader = vtk.vtkUnstructuredGridReader()
|
| 30 |
+
elif vtk_path.endswith('.vtu'):
|
| 31 |
+
reader = vtk.vtkXMLUnstructuredGridReader()
|
| 32 |
+
elif vtk_path.endswith('.pvtu'):
|
| 33 |
+
reader = vtk.vtkXMLPUnstructuredGridReader()
|
| 34 |
+
else:
|
| 35 |
+
raise ValueError(f'Unknown VTK format: {vtk_path}')
|
| 36 |
+
reader.SetFileName(vtk_path)
|
| 37 |
+
reader.Update()
|
| 38 |
+
return reader.GetOutput()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def add_grad_U(grid):
|
| 42 |
+
"""Compute gradU via vtkGradientFilter and attach as point data."""
|
| 43 |
+
grad = vtk.vtkGradientFilter()
|
| 44 |
+
grad.SetInputData(grid)
|
| 45 |
+
grad.SetInputScalars(grid.FIELD_ASSOCIATION_POINTS, 'U')
|
| 46 |
+
grad.SetResultArrayName('gradU')
|
| 47 |
+
grad.Update()
|
| 48 |
+
return grad.GetOutput()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def probe_at_points(volume, points_xyz):
|
| 52 |
+
"""Interpolate volume fields onto given (N,3) point cloud.
|
| 53 |
+
Points that fall outside the volume mesh are marked NaN (not 0) so plots
|
| 54 |
+
can mask missing data instead of treating zeros as real values."""
|
| 55 |
+
pts = vtk.vtkPoints()
|
| 56 |
+
pts.SetData(ns.numpy_to_vtk(np.ascontiguousarray(points_xyz, dtype=np.float64)))
|
| 57 |
+
poly = vtk.vtkPolyData()
|
| 58 |
+
poly.SetPoints(pts)
|
| 59 |
+
|
| 60 |
+
probe = vtk.vtkProbeFilter()
|
| 61 |
+
probe.SetSourceData(volume)
|
| 62 |
+
probe.SetInputData(poly)
|
| 63 |
+
probe.SetValidPointMaskArrayName('vtkValidPointMask')
|
| 64 |
+
probe.Update()
|
| 65 |
+
out = probe.GetOutput()
|
| 66 |
+
|
| 67 |
+
pdata = out.GetPointData()
|
| 68 |
+
valid_arr = pdata.GetArray('vtkValidPointMask')
|
| 69 |
+
valid = ns.vtk_to_numpy(valid_arr).astype(bool) if valid_arr else np.ones(len(points_xyz), bool)
|
| 70 |
+
n_invalid = int((~valid).sum())
|
| 71 |
+
if n_invalid:
|
| 72 |
+
print(f' [probe] {n_invalid}/{len(valid)} query points outside mesh -> NaN')
|
| 73 |
+
|
| 74 |
+
fields = {}
|
| 75 |
+
for i in range(pdata.GetNumberOfArrays()):
|
| 76 |
+
name = pdata.GetArrayName(i)
|
| 77 |
+
if name == 'vtkValidPointMask':
|
| 78 |
+
continue
|
| 79 |
+
arr = ns.vtk_to_numpy(pdata.GetArray(i)).astype(np.float64)
|
| 80 |
+
if arr.ndim == 1:
|
| 81 |
+
arr[~valid] = np.nan
|
| 82 |
+
else:
|
| 83 |
+
arr[~valid, :] = np.nan
|
| 84 |
+
fields[name] = arr
|
| 85 |
+
return fields
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def reynolds_from_boussinesq(U, gradU_flat, k, nut):
|
| 89 |
+
"""gradU_flat shape (N, 9): [du/dx du/dy du/dz dv/dx ... dw/dz]
|
| 90 |
+
Returns dict with R_xx, R_yy, R_zz, R_xy, R_xz, R_yz."""
|
| 91 |
+
g = gradU_flat.reshape(-1, 3, 3)
|
| 92 |
+
S = 0.5 * (g + g.transpose(0, 2, 1))
|
| 93 |
+
R = np.zeros_like(S)
|
| 94 |
+
for i in range(3):
|
| 95 |
+
R[:, i, i] = (2.0 / 3.0) * k
|
| 96 |
+
R = R - 2.0 * nut[:, None, None] * S
|
| 97 |
+
return {
|
| 98 |
+
'R_xx': R[:, 0, 0], 'R_yy': R[:, 1, 1], 'R_zz': R[:, 2, 2],
|
| 99 |
+
'R_xy': R[:, 0, 1], 'R_xz': R[:, 0, 2], 'R_yz': R[:, 1, 2],
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main():
|
| 104 |
+
if len(sys.argv) < 4:
|
| 105 |
+
print("Usage: extract_baseline_from_vtk.py <vtk_volume> <highfidelity_dir> <output_dir>")
|
| 106 |
+
sys.exit(1)
|
| 107 |
+
vtk_path, hf_dir, out_dir = sys.argv[1:4]
|
| 108 |
+
|
| 109 |
+
print(f'[load] {vtk_path}')
|
| 110 |
+
grid = load_volume(vtk_path)
|
| 111 |
+
print(f'[grad] computing gradU')
|
| 112 |
+
grid = add_grad_U(grid)
|
| 113 |
+
|
| 114 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 115 |
+
|
| 116 |
+
import re
|
| 117 |
+
|
| 118 |
+
# Per-case length scale: divide experiment coords by H_NORM to map into
|
| 119 |
+
# a non-dimensional OF mesh. Set via env var FH_H_NORM (default 1.0 = no rescale).
|
| 120 |
+
H_NORM = float(os.environ.get('H_NORM', '1.0'))
|
| 121 |
+
if H_NORM != 1.0:
|
| 122 |
+
print(f'[H_NORM={H_NORM} m -> dividing experiment coords by this length]')
|
| 123 |
+
|
| 124 |
+
for csv_in in sorted(glob.glob(os.path.join(hf_dir, '*.csv'))):
|
| 125 |
+
df = pd.read_csv(csv_in)
|
| 126 |
+
bn = os.path.basename(csv_in)
|
| 127 |
+
|
| 128 |
+
# Special-case Faith Hill PIV centerline: 2D plane data (x_mm, y_mm),
|
| 129 |
+
# implicit z=0 (centerline). Coord remap: (x_mm, y_mm)/h_mm -> OF (x, y), z=0.
|
| 130 |
+
if 'PIV_centerline' in bn:
|
| 131 |
+
x_mm = df['x_mm'].values
|
| 132 |
+
y_mm = df['y_mm'].values
|
| 133 |
+
# convert mm -> m -> divide by H_NORM
|
| 134 |
+
xyz = np.column_stack([x_mm * 1e-3 / H_NORM,
|
| 135 |
+
y_mm * 1e-3 / H_NORM,
|
| 136 |
+
np.zeros(len(df))])
|
| 137 |
+
print(f' [Faith Hill PIV] {bn}')
|
| 138 |
+
fields = probe_at_points(grid, xyz)
|
| 139 |
+
out = pd.DataFrame({'x_mm': x_mm, 'y_mm': y_mm})
|
| 140 |
+
if 'U' in fields:
|
| 141 |
+
U = fields['U'].reshape(-1, 3)
|
| 142 |
+
out['U_mean'] = U[:, 0]; out['V_mean'] = U[:, 1]; out['W_mean'] = U[:, 2]
|
| 143 |
+
for f in ['k', 'omega', 'p', 'nut']:
|
| 144 |
+
if f in fields:
|
| 145 |
+
out[f] = fields[f]
|
| 146 |
+
if all(f in fields for f in ['U', 'k', 'nut', 'gradU']):
|
| 147 |
+
stresses = reynolds_from_boussinesq(
|
| 148 |
+
fields['U'].reshape(-1, 3), fields['gradU'],
|
| 149 |
+
fields['k'], fields['nut'])
|
| 150 |
+
for k, v in stresses.items():
|
| 151 |
+
out[k] = v
|
| 152 |
+
out.to_csv(os.path.join(out_dir, bn), index=False)
|
| 153 |
+
print(f' {bn:40s} -> {bn} ({len(out)} rows)')
|
| 154 |
+
continue
|
| 155 |
+
|
| 156 |
+
# Special-case Faith Hill PSP centerline: 1D, x_in only. z=0 (sym).
|
| 157 |
+
# The wall follows a cosine bump h(r)=3*cos(pi*r/9)+3 [in] for |r|<=9 in.
|
| 158 |
+
# Probe just above the wall surface (y_wall + epsilon).
|
| 159 |
+
if 'PSP_centerline' in bn:
|
| 160 |
+
x_in = df['x_in'].values
|
| 161 |
+
# bump height in inches at each x (centerline so r=|x|)
|
| 162 |
+
r = np.abs(x_in)
|
| 163 |
+
y_in_wall = np.where(r <= 9.0, 3.0 * np.cos(np.pi * r / 9.0) + 3.0, 0.0)
|
| 164 |
+
# convert wall coord to OF mesh frame, add small offset
|
| 165 |
+
y_offset_OF = 0.005 # ~0.5% of hill in non-dim units
|
| 166 |
+
xyz = np.column_stack([
|
| 167 |
+
x_in * 0.0254 / H_NORM,
|
| 168 |
+
y_in_wall * 0.0254 / H_NORM + y_offset_OF,
|
| 169 |
+
np.zeros(len(df))
|
| 170 |
+
])
|
| 171 |
+
print(f' [Faith Hill PSP, bump-aware] {bn}')
|
| 172 |
+
fields = probe_at_points(grid, xyz)
|
| 173 |
+
out = pd.DataFrame({'x_in': x_in})
|
| 174 |
+
if 'p' in fields:
|
| 175 |
+
out['p'] = fields['p']
|
| 176 |
+
# Cp = (p - p_inf) / (0.5 * U_inf^2). For non-dim case U_inf=1 -> Cp = 2*p (since rho=1).
|
| 177 |
+
out['Cp'] = 2.0 * fields['p']
|
| 178 |
+
out.to_csv(os.path.join(out_dir, bn), index=False)
|
| 179 |
+
print(f' {bn:40s} -> {bn} ({len(out)} rows)')
|
| 180 |
+
continue
|
| 181 |
+
|
| 182 |
+
# Special-case Faith Hill FISF surface: (X, Y, Z) where Y=spanwise -> OF z, Z=wallnormal -> OF y.
|
| 183 |
+
if 'FISF' in bn:
|
| 184 |
+
X = df['X'].values
|
| 185 |
+
Yspan = df['Y'].values
|
| 186 |
+
Znorm = df['Z'].values
|
| 187 |
+
xyz = np.column_stack([X * 0.0254 / H_NORM,
|
| 188 |
+
Znorm * 0.0254 / H_NORM, # FISF Z -> OF y
|
| 189 |
+
Yspan * 0.0254 / H_NORM]) # FISF Y -> OF z
|
| 190 |
+
print(f' [Faith Hill FISF (Y/Z swap)] {bn}')
|
| 191 |
+
fields = probe_at_points(grid, xyz)
|
| 192 |
+
out = pd.DataFrame({'X': X, 'Y': Yspan, 'Z': Znorm})
|
| 193 |
+
if 'U' in fields:
|
| 194 |
+
U = fields['U'].reshape(-1, 3)
|
| 195 |
+
out['U'] = U[:, 0]; out['V'] = U[:, 1]; out['W'] = U[:, 2]
|
| 196 |
+
for f in ['k', 'omega', 'p', 'nut']:
|
| 197 |
+
if f in fields:
|
| 198 |
+
out[f] = fields[f]
|
| 199 |
+
out.to_csv(os.path.join(out_dir, bn), index=False)
|
| 200 |
+
print(f' {bn:40s} -> {bn} ({len(out)} rows)')
|
| 201 |
+
continue
|
| 202 |
+
|
| 203 |
+
# Special-case WingBody profile_midplane files: x station encoded in filename,
|
| 204 |
+
# z=0 (symmetry plane), y varies. Columns: y, u, v, Re_xx, ..., k.
|
| 205 |
+
prof_match = re.match(r'profile_midplane_([-+]?\d*\.?\d+)\.csv$',
|
| 206 |
+
os.path.basename(csv_in))
|
| 207 |
+
if prof_match:
|
| 208 |
+
T = 0.0717 # WingBody DNS thickness scale
|
| 209 |
+
x_over_T = float(prof_match.group(1))
|
| 210 |
+
xyz = np.column_stack([
|
| 211 |
+
np.full(len(df), x_over_T * T),
|
| 212 |
+
df['y'].values * T,
|
| 213 |
+
np.zeros(len(df)),
|
| 214 |
+
])
|
| 215 |
+
print(f' [profile_midplane x/T={x_over_T}] {os.path.basename(csv_in)}')
|
| 216 |
+
fields = probe_at_points(grid, xyz)
|
| 217 |
+
out = pd.DataFrame({'y': df['y']})
|
| 218 |
+
if 'U' in fields:
|
| 219 |
+
U = fields['U'].reshape(-1, 3)
|
| 220 |
+
out['u'] = U[:, 0] / 27.0 # u_ref = 27 m/s
|
| 221 |
+
out['v'] = U[:, 1] / 27.0
|
| 222 |
+
out['w'] = U[:, 2] / 27.0
|
| 223 |
+
# WingBody DNS normalises by u_ref = 27 m/s
|
| 224 |
+
U_REF = 27.0
|
| 225 |
+
if 'k' in fields:
|
| 226 |
+
out['k'] = fields['k'] / U_REF**2
|
| 227 |
+
if 'omega' in fields:
|
| 228 |
+
out['omega'] = fields['omega']
|
| 229 |
+
if 'p' in fields:
|
| 230 |
+
out['p'] = fields['p']
|
| 231 |
+
if 'nut' in fields:
|
| 232 |
+
out['nut'] = fields['nut']
|
| 233 |
+
if all(f in fields for f in ['U', 'k', 'nut', 'gradU']):
|
| 234 |
+
stresses = reynolds_from_boussinesq(
|
| 235 |
+
fields['U'].reshape(-1, 3), fields['gradU'],
|
| 236 |
+
fields['k'], fields['nut'])
|
| 237 |
+
for kk, v in stresses.items():
|
| 238 |
+
out[kk] = v / U_REF**2
|
| 239 |
+
out.to_csv(os.path.join(out_dir, os.path.basename(csv_in)), index=False)
|
| 240 |
+
print(f' {os.path.basename(csv_in):40s} -> {os.path.basename(csv_in)} '
|
| 241 |
+
f'({len(out)} rows)')
|
| 242 |
+
continue
|
| 243 |
+
|
| 244 |
+
cols = {c.lower(): c for c in df.columns}
|
| 245 |
+
|
| 246 |
+
# Resolve x / y / z column names (case-insensitive, allow common suffixes)
|
| 247 |
+
def _find(prefixes):
|
| 248 |
+
for p in prefixes:
|
| 249 |
+
if p in cols:
|
| 250 |
+
return cols[p]
|
| 251 |
+
return None
|
| 252 |
+
|
| 253 |
+
xname = _find(['x', 'x_mm', 'x_in', 'x_over_t'])
|
| 254 |
+
yname = _find(['y', 'y_mm', 'y_in', 'y_over_t'])
|
| 255 |
+
zname = _find(['z', 'z_mm', 'z_in', 'z_over_t'])
|
| 256 |
+
# If z missing (2D plane data), assume z=0
|
| 257 |
+
z_implicit = zname is None
|
| 258 |
+
if not (xname and yname):
|
| 259 |
+
print(f' skip {os.path.basename(csv_in)} - no x/y columns')
|
| 260 |
+
continue
|
| 261 |
+
|
| 262 |
+
# Detect coord scaling from magnitude + column-name hint.
|
| 263 |
+
x_vals = df[xname].abs().values
|
| 264 |
+
max_abs = x_vals.max() if len(x_vals) else 0
|
| 265 |
+
if 'mm' in xname.lower():
|
| 266 |
+
scale = 1e-3
|
| 267 |
+
elif 'in' in xname.lower():
|
| 268 |
+
scale = 0.0254
|
| 269 |
+
elif 'over_t' in xname.lower():
|
| 270 |
+
scale = 0.0717 # WingBody DNS reference thickness T = 71.7 mm
|
| 271 |
+
elif max_abs > 100:
|
| 272 |
+
scale = 1e-3 # likely mm
|
| 273 |
+
elif max_abs > 1.5:
|
| 274 |
+
scale = 0.0254 # likely inches
|
| 275 |
+
else:
|
| 276 |
+
scale = 1.0 # assume meters
|
| 277 |
+
|
| 278 |
+
if z_implicit:
|
| 279 |
+
xyz = np.column_stack([df[xname].values * scale,
|
| 280 |
+
df[yname].values * scale,
|
| 281 |
+
np.zeros(len(df))])
|
| 282 |
+
else:
|
| 283 |
+
xyz = df[[xname, yname, zname]].values * scale
|
| 284 |
+
# detect Wing-body surface CSVs (have x_over_T columns) and compute Cp from OF p
|
| 285 |
+
is_wbj_surface = ('over_t' in xname.lower())
|
| 286 |
+
print(f' [scale={scale:g}, z_implicit={z_implicit}, wbj={is_wbj_surface}] {os.path.basename(csv_in)}')
|
| 287 |
+
|
| 288 |
+
fields = probe_at_points(grid, xyz)
|
| 289 |
+
cols_keep = {xname: df[xname], yname: df[yname]}
|
| 290 |
+
if not z_implicit:
|
| 291 |
+
cols_keep[zname] = df[zname]
|
| 292 |
+
out = pd.DataFrame(cols_keep)
|
| 293 |
+
if is_wbj_surface and 'p' in fields:
|
| 294 |
+
U_REF = 27.0
|
| 295 |
+
out['Cp'] = 2.0 * fields['p'] / U_REF**2
|
| 296 |
+
if 'U' in fields:
|
| 297 |
+
U = fields['U'].reshape(-1, 3)
|
| 298 |
+
out['U'] = U[:, 0]; out['V'] = U[:, 1]; out['W'] = U[:, 2]
|
| 299 |
+
for f in ['k', 'omega', 'p', 'nut']:
|
| 300 |
+
if f in fields:
|
| 301 |
+
out[f] = fields[f]
|
| 302 |
+
if all(f in fields for f in ['U', 'k', 'nut', 'gradU']):
|
| 303 |
+
stresses = reynolds_from_boussinesq(
|
| 304 |
+
fields['U'].reshape(-1, 3),
|
| 305 |
+
fields['gradU'],
|
| 306 |
+
fields['k'],
|
| 307 |
+
fields['nut'])
|
| 308 |
+
for k, v in stresses.items():
|
| 309 |
+
out[k] = v
|
| 310 |
+
|
| 311 |
+
out_csv = os.path.join(out_dir, os.path.basename(csv_in))
|
| 312 |
+
out.to_csv(out_csv, index=False)
|
| 313 |
+
print(f' {os.path.basename(csv_in):40s} -> {out_csv} ({len(out)} rows, {len(out.columns)} cols)')
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
if __name__ == '__main__':
|
| 317 |
+
main()
|
data/extract_wbj_surface_lines.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extract centerline pressure lines from WingBody-junction surface .pvtu files.
|
| 2 |
+
|
| 3 |
+
DNS 1-6 coordinate convention (per kbwiki):
|
| 4 |
+
x = streamwise (origin at airfoil root leading edge)
|
| 5 |
+
y = normalwise (wall-normal; bottom wall at y=0)
|
| 6 |
+
z = spanwise (symmetry at z=0; lateral boundaries at z/T = +-4)
|
| 7 |
+
T = airfoil thickness = 71.7 mm (reference length)
|
| 8 |
+
|
| 9 |
+
Outputs (CSV with x/T, Cp = averaged_pressure / (rho_ref u_ref^2 / 2)):
|
| 10 |
+
bottom_wall_centerline.csv : z = 0 strip on the bottom wall
|
| 11 |
+
wing_root_chord.csv : y/T ~= 0.05 strip on the wing surface (near root)
|
| 12 |
+
|
| 13 |
+
The averaged_pressure stored in the .vtu is dimensionless: p / p_ref. We map to a
|
| 14 |
+
"reduced Cp" via: Cp = (p/p_ref - 1) * (gamma * Ma^2)^{-1} using gamma=1.4, Ma=0.078.
|
| 15 |
+
|
| 16 |
+
Usage: python extract_wbj_surface_lines.py
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import pathlib
|
| 21 |
+
import sys
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import vtk
|
| 25 |
+
from vtk.util import numpy_support as ns
|
| 26 |
+
|
| 27 |
+
T = 1.0 # work in normalised x/T (data is already normalised in the DNS, so keep T=1)
|
| 28 |
+
Z_TOL = 0.01 # strip half-width in z/T
|
| 29 |
+
Y_TARGET = 0.05 # wing extraction height (near root)
|
| 30 |
+
Y_TOL = 0.01
|
| 31 |
+
|
| 32 |
+
GAMMA = 1.4
|
| 33 |
+
MACH = 0.078
|
| 34 |
+
|
| 35 |
+
DST = os.environ.get('WBJ_HIGHFIDELITY_DIR',
|
| 36 |
+
str(pathlib.Path(__file__).parent / 'ERCOFTAC_WingBodyJunction' / 'highfidelity'))
|
| 37 |
+
RAW = os.path.join(DST, 'raw_surface')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_pvtu(path):
|
| 41 |
+
reader = vtk.vtkXMLPUnstructuredGridReader()
|
| 42 |
+
reader.SetFileName(path)
|
| 43 |
+
reader.Update()
|
| 44 |
+
grid = reader.GetOutput()
|
| 45 |
+
pts = ns.vtk_to_numpy(grid.GetPoints().GetData()) # shape (N, 3)
|
| 46 |
+
pdata = grid.GetPointData()
|
| 47 |
+
arr_names = [pdata.GetArrayName(i) for i in range(pdata.GetNumberOfArrays())]
|
| 48 |
+
if 'averaged_pressure' not in arr_names:
|
| 49 |
+
raise RuntimeError(f'No averaged_pressure in {path}: have {arr_names}')
|
| 50 |
+
p = ns.vtk_to_numpy(pdata.GetArray('averaged_pressure'))
|
| 51 |
+
return pts, p
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def p_to_cp(p_over_pref):
|
| 55 |
+
"""Convert dimensionless p/p_ref to a Cp-like coefficient.
|
| 56 |
+
For low Mach, Cp = (p - p_ref) / (0.5 rho_ref u_ref^2). Using p = (rho_ref/gamma) * (p/p_ref) * gamma:
|
| 57 |
+
Equivalently, (p/p_ref - 1) / (0.5 gamma Ma^2). At Ma=0.078, denom ~ 0.00426.
|
| 58 |
+
"""
|
| 59 |
+
return (p_over_pref - 1.0) / (0.5 * GAMMA * MACH**2)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def extract_strip(pts, p, axis_to_filter, target, tol):
|
| 63 |
+
mask = np.abs(pts[:, axis_to_filter] - target) < tol
|
| 64 |
+
return pts[mask], p[mask]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def main():
|
| 68 |
+
# --- bottom wall: z=0 strip ---
|
| 69 |
+
pts, p = load_pvtu(os.path.join(RAW, 'bottom_wall_averaged_pressure.pvtu'))
|
| 70 |
+
sub_pts, sub_p = extract_strip(pts, p, axis_to_filter=2, target=0.0, tol=Z_TOL)
|
| 71 |
+
cp = p_to_cp(sub_p)
|
| 72 |
+
df = pd.DataFrame({
|
| 73 |
+
'x_over_T': sub_pts[:, 0] / T,
|
| 74 |
+
'y_over_T': sub_pts[:, 1] / T,
|
| 75 |
+
'z_over_T': sub_pts[:, 2] / T,
|
| 76 |
+
'p_over_pref': sub_p,
|
| 77 |
+
'Cp': cp,
|
| 78 |
+
}).sort_values('x_over_T').reset_index(drop=True)
|
| 79 |
+
out = os.path.join(DST, 'bottom_wall_centerline.csv')
|
| 80 |
+
df.to_csv(out, index=False)
|
| 81 |
+
print(f' bottom_wall -> {os.path.basename(out)} '
|
| 82 |
+
f'({len(df)} rows; x range [{df.x_over_T.min():.2f}, {df.x_over_T.max():.2f}])')
|
| 83 |
+
|
| 84 |
+
# --- wing: y/T ~= 0.05 strip (root chord) ---
|
| 85 |
+
pts, p = load_pvtu(os.path.join(RAW, 'wing_averaged_pressure.pvtu'))
|
| 86 |
+
sub_pts, sub_p = extract_strip(pts, p, axis_to_filter=1, target=Y_TARGET, tol=Y_TOL)
|
| 87 |
+
cp = p_to_cp(sub_p)
|
| 88 |
+
df = pd.DataFrame({
|
| 89 |
+
'x_over_T': sub_pts[:, 0] / T,
|
| 90 |
+
'y_over_T': sub_pts[:, 1] / T,
|
| 91 |
+
'z_over_T': sub_pts[:, 2] / T,
|
| 92 |
+
'p_over_pref': sub_p,
|
| 93 |
+
'Cp': cp,
|
| 94 |
+
}).sort_values('x_over_T').reset_index(drop=True)
|
| 95 |
+
out = os.path.join(DST, 'wing_root_chord.csv')
|
| 96 |
+
df.to_csv(out, index=False)
|
| 97 |
+
print(f' wing_root -> {os.path.basename(out)} '
|
| 98 |
+
f'({len(df)} rows; x range [{df.x_over_T.min():.2f}, {df.x_over_T.max():.2f}])')
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == '__main__':
|
| 102 |
+
main()
|
data/faith_hill_to_csv.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert Faith Hill PIV / PSP / FISF data to flat CSV.
|
| 2 |
+
|
| 3 |
+
Faith Hill source layout:
|
| 4 |
+
- PIV: one folder per dataset (1kHz_3940samp / 2Hz_4000samps). Each folder has 14 .dat
|
| 5 |
+
files in Tecplot POINT format, each file containing (x, y, single_scalar). Merge them
|
| 6 |
+
on the (x, y) grid into one CSV per dataset.
|
| 7 |
+
- PSP: single Tecplot-style file with "VARIABLES =" line and one zone -> 2-col CSV.
|
| 8 |
+
- FISF: single Tecplot-style file with "Variables =" line, no zone -> N-col CSV.
|
| 9 |
+
|
| 10 |
+
Coords in mm (PIV) or inches (PSP/FISF) per source. Hill height h = 152.4 mm = 6 in.
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python faith_hill_to_csv.py <piv-data-folder|psp.dat|fisf.dat> <output_csv>
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import sys
|
| 19 |
+
import glob
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_SCALAR_FROM_NAME = {
|
| 25 |
+
'U_mean': 'U_mean',
|
| 26 |
+
'V_mean': 'V_mean',
|
| 27 |
+
'W_mean': 'W_mean',
|
| 28 |
+
'U_rms': 'U_rms',
|
| 29 |
+
'V_rms': 'V_rms',
|
| 30 |
+
'W_rms': 'W_rms',
|
| 31 |
+
'Re_stress_UU': 'UU',
|
| 32 |
+
'Re_stress_UV': 'UV',
|
| 33 |
+
'Re_stress_UW': 'UW',
|
| 34 |
+
'Re_stress_VV': 'VV',
|
| 35 |
+
'Re_stress_VW': 'VW',
|
| 36 |
+
'Re_stress_WW': 'WW',
|
| 37 |
+
'Ek_Ave': 'Ek_Ave',
|
| 38 |
+
'Ek_turb': 'Ek_turb',
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
_NUMERIC_RE = re.compile(r'^\s*[-+]?\d')
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _parse_tecplot_point(path):
|
| 46 |
+
"""Parse a Tecplot POINT-format .dat file -> (x, y, value) arrays.
|
| 47 |
+
|
| 48 |
+
Robust to multi-line headers: skips every line until the first one whose
|
| 49 |
+
first non-whitespace character is a digit or sign.
|
| 50 |
+
"""
|
| 51 |
+
with open(path) as f:
|
| 52 |
+
lines = f.readlines()
|
| 53 |
+
|
| 54 |
+
data_start = 0
|
| 55 |
+
for i, line in enumerate(lines):
|
| 56 |
+
if _NUMERIC_RE.match(line):
|
| 57 |
+
data_start = i
|
| 58 |
+
break
|
| 59 |
+
else:
|
| 60 |
+
raise RuntimeError(f'No numeric data found in {path}')
|
| 61 |
+
|
| 62 |
+
arr = np.genfromtxt(lines[data_start:], dtype=float)
|
| 63 |
+
if arr.ndim == 1:
|
| 64 |
+
arr = arr.reshape(1, -1)
|
| 65 |
+
if arr.shape[1] < 3:
|
| 66 |
+
raise RuntimeError(f'{path}: expected >=3 columns, got {arr.shape[1]}')
|
| 67 |
+
return arr[:, 0], arr[:, 1], arr[:, 2]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def merge_piv_dataset(folder, out_csv):
|
| 71 |
+
"""Merge 14 Tecplot-POINT files in `folder` into one CSV by (x, y) grid."""
|
| 72 |
+
dat_files = [p for p in sorted(glob.glob(os.path.join(folder, '*.dat')))
|
| 73 |
+
if not os.path.basename(p).startswith('._')]
|
| 74 |
+
if not dat_files:
|
| 75 |
+
raise RuntimeError(f'No .dat in {folder}')
|
| 76 |
+
|
| 77 |
+
df = None
|
| 78 |
+
for path in dat_files:
|
| 79 |
+
base = os.path.basename(path).replace('.dat', '').replace('_axis00', '')
|
| 80 |
+
col = _SCALAR_FROM_NAME.get(base, base)
|
| 81 |
+
x, y, v = _parse_tecplot_point(path)
|
| 82 |
+
cur = pd.DataFrame({'x_mm': x, 'y_mm': y, col: v})
|
| 83 |
+
if df is None:
|
| 84 |
+
df = cur
|
| 85 |
+
else:
|
| 86 |
+
df = pd.merge(df, cur, on=['x_mm', 'y_mm'], how='outer')
|
| 87 |
+
|
| 88 |
+
# add k = 0.5 * (UU + VV + WW)
|
| 89 |
+
if all(c in df.columns for c in ['UU', 'VV', 'WW']):
|
| 90 |
+
df['k'] = 0.5 * (df['UU'] + df['VV'] + df['WW'])
|
| 91 |
+
|
| 92 |
+
df = df.sort_values(['y_mm', 'x_mm']).reset_index(drop=True)
|
| 93 |
+
df.to_csv(out_csv, index=False)
|
| 94 |
+
print(f' PIV: {os.path.basename(folder)} -> {os.path.basename(out_csv)} '
|
| 95 |
+
f'({len(df)} rows, {len(df.columns)} cols)')
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def convert_psp(path, out_csv):
|
| 99 |
+
"""Parse PSP centerline .dat (Tecplot single-zone, 2 columns)."""
|
| 100 |
+
with open(path) as f:
|
| 101 |
+
content = f.read()
|
| 102 |
+
var_match = re.search(r'VARIABLES\s*=\s*([^\n]+)', content, re.IGNORECASE)
|
| 103 |
+
cols = []
|
| 104 |
+
if var_match:
|
| 105 |
+
cols = re.findall(r'"([^"]+)"', var_match.group(1))
|
| 106 |
+
arr = np.genfromtxt(path, comments=None,
|
| 107 |
+
skip_header=sum(1 for _ in re.findall(
|
| 108 |
+
r'^(?:VARIABLES|TITLE|ZONE|zone|#)[^\n]*\n', content, re.MULTILINE)))
|
| 109 |
+
# safer: parse line-by-line
|
| 110 |
+
lines = content.split('\n')
|
| 111 |
+
data_start = 0
|
| 112 |
+
for i, line in enumerate(lines):
|
| 113 |
+
s = line.strip().lower()
|
| 114 |
+
if s.startswith('zone') or s.startswith('#'):
|
| 115 |
+
data_start = i + 1
|
| 116 |
+
elif s.startswith('variables') or s.startswith('title'):
|
| 117 |
+
data_start = i + 1
|
| 118 |
+
arr = np.genfromtxt(lines[data_start:], dtype=float)
|
| 119 |
+
if arr.ndim == 1:
|
| 120 |
+
arr = arr.reshape(1, -1)
|
| 121 |
+
if not cols or len(cols) != arr.shape[1]:
|
| 122 |
+
cols = [f'col_{i}' for i in range(arr.shape[1])]
|
| 123 |
+
# rename common columns
|
| 124 |
+
rename = {'X': 'x_in', 'F1V1': 'Cp'}
|
| 125 |
+
cols = [rename.get(c, c) for c in cols]
|
| 126 |
+
df = pd.DataFrame(arr, columns=cols)
|
| 127 |
+
df.to_csv(out_csv, index=False)
|
| 128 |
+
print(f' PSP: {os.path.basename(path)} -> {os.path.basename(out_csv)} '
|
| 129 |
+
f'({len(df)} rows, {len(df.columns)} cols)')
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def convert_fisf(path, out_csv):
|
| 133 |
+
"""Parse FISF surface data ("Variables =..." header, N-col data)."""
|
| 134 |
+
with open(path) as f:
|
| 135 |
+
first_line = f.readline()
|
| 136 |
+
cols = re.findall(r'"([^"]+)"', first_line)
|
| 137 |
+
arr = np.genfromtxt(path, skip_header=1, dtype=float)
|
| 138 |
+
if arr.ndim == 1:
|
| 139 |
+
arr = arr.reshape(1, -1)
|
| 140 |
+
if not cols or len(cols) != arr.shape[1]:
|
| 141 |
+
cols = [f'col_{i}' for i in range(arr.shape[1])]
|
| 142 |
+
df = pd.DataFrame(arr, columns=cols)
|
| 143 |
+
df.to_csv(out_csv, index=False)
|
| 144 |
+
print(f' FISF: {os.path.basename(path)} -> {os.path.basename(out_csv)} '
|
| 145 |
+
f'({len(df)} rows, {len(df.columns)} cols)')
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == '__main__':
|
| 149 |
+
if len(sys.argv) != 3:
|
| 150 |
+
print(__doc__)
|
| 151 |
+
sys.exit(1)
|
| 152 |
+
src, dst = sys.argv[1], sys.argv[2]
|
| 153 |
+
if os.path.isdir(src):
|
| 154 |
+
merge_piv_dataset(src, dst)
|
| 155 |
+
elif 'centerline_p150' in src.lower() or 'psp' in src.lower():
|
| 156 |
+
convert_psp(src, dst)
|
| 157 |
+
elif 'fisf' in src.lower():
|
| 158 |
+
convert_fisf(src, dst)
|
| 159 |
+
else:
|
| 160 |
+
print(f'Unknown source type: {src}')
|
| 161 |
+
sys.exit(1)
|