Datasets:
Download data/commented_dat_to_csv.py from anon-closure-challenge-v2/closure-challenge-v2-cfd-cases: direct link, hf CLI and curl.
- Browser
- Download file 3.31 kB
-
https://huggingface.co/datasets/anon-closure-challenge-v2/closure-challenge-v2-cfd-cases/resolve/1c3cbe6498040f3ef2cc8ac67daf010555addd5e/data/commented_dat_to_csv.py
- Command line
-
hf download hf://datasets/anon-closure-challenge-v2/closure-challenge-v2-cfd-cases@1c3cbe6498040f3ef2cc8ac67daf010555addd5e/data/commented_dat_to_csv.py
-
curl -L -o commented_dat_to_csv.py https://huggingface.co/datasets/anon-closure-challenge-v2/closure-challenge-v2-cfd-cases/resolve/1c3cbe6498040f3ef2cc8ac67daf010555addd5e/data/commented_dat_to_csv.py
3.31 kB
| """Convert simple commented-header .dat files (Ahmed Body, Faith Hill PIV/PSP/FISF | |
| formats) to flat CSV. | |
| Different from the NASA Tecplot zone parser (Extended_2D_Dataset/dat_to_csv.py). | |
| These .dat files are: | |
| - Header: any number of '#'-prefixed lines | |
| - The last '#' line contains the column names, possibly with units in brackets | |
| - Data: whitespace-separated floats, one row per measurement point | |
| Usage: | |
| python commented_dat_to_csv.py <dir_or_file> [<dir_or_file> ...] | |
| """ | |
| import sys | |
| import os | |
| import re | |
| import glob | |
| import numpy as np | |
| import pandas as pd | |
| # Match e.g. "x[mm]" or "U[m/s]" -> capture name and unit | |
| _NAMED_UNIT_RE = re.compile(r'(\S+?)\[([^\]]+)\]') | |
| def _parse_columns_from_header_line(line): | |
| """Parse a header line like '# x[mm] y[mm] z[mm] U[m/s] ...' -> list of column names. | |
| Spatial coords gain a unit suffix ("x_mm", "y_in", "z_m") so downstream tooling | |
| can map experiment coords to the OF mesh scale unambiguously. Non-spatial | |
| columns retain their original names. | |
| """ | |
| s = line.lstrip('#').strip() | |
| out = [] | |
| for tok in s.split(): | |
| m = _NAMED_UNIT_RE.match(tok) | |
| if not m: | |
| out.append(tok) | |
| continue | |
| name, unit = m.group(1), m.group(2).strip() | |
| # only attach unit suffix to spatial coordinate columns | |
| if name.lower() in ('x', 'y', 'z') and unit in ('mm', 'm', 'in', 'cm'): | |
| out.append(f'{name}_{unit}') | |
| else: | |
| out.append(name) | |
| return out | |
| def read_commented_dat(path): | |
| """Read a commented-header .dat file -> pandas DataFrame. | |
| The last header line beginning with '#' is treated as the column-name line. | |
| All other '#' lines are skipped. Data rows are whitespace-separated floats. | |
| """ | |
| with open(path) as f: | |
| lines = f.readlines() | |
| last_header_idx = -1 | |
| for i, line in enumerate(lines): | |
| if line.lstrip().startswith('#'): | |
| last_header_idx = i | |
| else: | |
| if line.strip(): | |
| break | |
| if last_header_idx < 0: | |
| raise ValueError(f'{path}: no commented header found') | |
| columns = _parse_columns_from_header_line(lines[last_header_idx]) | |
| data = np.genfromtxt(path, comments='#') | |
| if data.ndim == 1: | |
| data = data.reshape(1, -1) | |
| if data.shape[1] != len(columns): | |
| # Some files have variables labeled with extra '*' or unusual chars; | |
| # fall back to generic col_N names if mismatch | |
| columns = [f'col_{i}' for i in range(data.shape[1])] | |
| return pd.DataFrame(data, columns=columns) | |
| def convert_path(path): | |
| if os.path.isdir(path): | |
| for dat in sorted(glob.glob(os.path.join(path, '*.dat'))): | |
| convert_path(dat) | |
| return | |
| if not path.lower().endswith('.dat'): | |
| return | |
| try: | |
| df = read_commented_dat(path) | |
| except Exception as exc: | |
| print(f' FAILED {path}: {exc}') | |
| return | |
| csv_path = path[:-4] + '.csv' | |
| df.to_csv(csv_path, index=False) | |
| print(f' {os.path.basename(path)} -> {os.path.basename(csv_path)}' | |
| f' ({len(df)} rows, {len(df.columns)} cols)') | |
| if __name__ == '__main__': | |
| if len(sys.argv) < 2: | |
| print(__doc__) | |
| sys.exit(1) | |
| for arg in sys.argv[1:]: | |
| print(f'\n[{arg}]') | |
| convert_path(arg) | |