""" RDE Spatial Field Extractor v1.2 (Auto-detect CSV columns) Extracts 2D spatial arrays from OpenFOAM case directories for ML training. Handles both scalar fields (p, T, H2, O2) and vector fields (U). Auto-detects CSV column names for case matching. Usage: python spatial_extractor.py --cases_dir ./ --cases RDE_01 RDE_02 ... RDE_12 Output: - spatial_fields.npz: (n_cases, n_timesteps, n_channels, H, W) """ import numpy as np import json import os import re import argparse from pathlib import Path import gzip import pandas as pd def sniff_csv_columns(csv_path): """ Deep-dive: Auto-detect case identifier column and parameter columns. Returns mapping of standard names to actual CSV column names. """ df = pd.read_csv(csv_path) cols = list(df.columns) print(f" CSV columns found: {cols}") mapping = {} # Case ID detection (deep dive: check multiple patterns) case_patterns = ['case_id', 'case', 'Case', 'CASE', 'case_name', 'simulation', 'run'] for pat in case_patterns: if pat in cols: mapping['case_id'] = pat break # If no explicit case column, check if first column looks like case names if 'case_id' not in mapping: first_col = cols[0] sample_vals = df[first_col].astype(str).tolist() # Check if values look like RDE_01, case_1, etc. if any(re.match(r'.*[_-]\d+', str(v)) for v in sample_vals[:5]): mapping['case_id'] = first_col print(f" Using first column '{first_col}' as case identifier") # Parameter detection param_patterns = { 'phi': ['phi', 'Phi', 'PHI', 'equivalence_ratio', 'ER'], 'p0_pa': ['p0', 'p0_pa', 'P0', 'pressure', 'inlet_pressure', 'p_init'], 'T0_k': ['T0', 'T0_k', 'temperature', 'inlet_temperature', 'T_init'], 'cj_speed_ms': ['cj_speed', 'cantera_cj_speed_ms', 'CJ_speed', 'dcj', 'D_CJ'] } for std_name, patterns in param_patterns.items(): for pat in patterns: if pat in cols: mapping[std_name] = pat break print(f" Column mapping: {mapping}") return mapping, df def read_openfoam_header(field_path): """Read OpenFOAM file header to determine field type and dimensions.""" field_path = Path(field_path) if not field_path.exists(): gz_path = field_path.with_suffix(field_path.suffix + '.gz') if gz_path.exists(): field_path = gz_path else: return {'is_uniform': False, 'is_vector': False} opener = gzip.open if str(field_path).endswith('.gz') else open with opener(field_path, 'rt', errors='replace') as f: header_lines = [] for i, line in enumerate(f): header_lines.append(line) if i > 50: break if 'internalField' in line: break header_text = ''.join(header_lines) is_uniform = 'uniform' in header_text.lower() and 'nonuniform' not in header_text.lower() is_vector = 'volVectorField' in header_text is_scalar = 'volScalarField' in header_text if not is_vector and not is_scalar: for line in header_lines: stripped = line.strip() if stripped.startswith('(') and len(stripped.split()) > 2: is_vector = True break return {'is_uniform': is_uniform, 'is_vector': is_vector} def read_openfoam_field(field_path, shape=(150, 300)): """ Read OpenFOAM field file and reshape to 2D. Returns: (H, W) for scalar or (H, W, 3) for vector """ field_path = Path(field_path) if not field_path.exists(): gz_path = field_path.with_suffix(field_path.suffix + '.gz') if gz_path.exists(): field_path = gz_path else: raise FileNotFoundError(f"Field file not found: {field_path}") field_info = read_openfoam_header(field_path) opener = gzip.open if str(field_path).endswith('.gz') else open with opener(field_path, 'rt', errors='replace') as f: lines = f.readlines() data_start = None n_cells = None for i, line in enumerate(lines): if 'internalField' in line: if 'uniform' in line.lower(): val_match = re.search(r'\(([^)]+)\)', line) if val_match: val_str = val_match.group(1) vals = [float(x) for x in val_str.split()] else: val_match = re.search(r'uniform\s+([0-9.eE+-]+)', line) vals = [float(val_match.group(1))] if val_match else [0.0] if len(vals) == 1: return np.full(shape, vals[0], dtype=np.float32) else: arr = np.full((*shape, len(vals)), vals, dtype=np.float32) return arr elif 'nonuniform' in line.lower(): for j in range(i+1, min(i+5, len(lines))): count_match = re.match(r'^\s*(\d+)\s*$', lines[j]) if count_match: n_cells = int(count_match.group(1)) data_start = j + 1 break break if data_start is None: raise ValueError(f"Could not find data section in {field_path}") values = [] paren_depth = 0 current_vec = [] for line in lines[data_start:]: line = line.strip() if line == ')' or line == ');': break if not line: continue if line.startswith('(') and ')' in line and line.index(')') == len(line) - 1: vec_str = line.strip('()') vals = [float(x) for x in vec_str.split() if x] if vals: values.append(vals) elif line.startswith('('): paren_depth = 1 vec_str = line[1:] vals = [float(x) for x in vec_str.split() if x] current_vec.extend(vals) elif paren_depth > 0: if ')' in line: paren_depth = 0 vec_str = line[:line.index(')')] vals = [float(x) for x in vec_str.split() if x] current_vec.extend(vals) if current_vec: values.append(current_vec) current_vec = [] else: vals = [float(x) for x in line.split() if x] current_vec.extend(vals) else: vals = [float(x) for x in line.split() if x] if vals: values.append(vals[0] if len(vals) == 1 else vals) if not values: raise ValueError(f"No data values found in {field_path}") arr = np.array(values, dtype=np.float32) expected_cells = shape[0] * shape[1] if arr.ndim == 1: if arr.size != expected_cells: print(f" WARNING: Expected {expected_cells} cells, got {arr.size}. Truncating/padding.") if arr.size > expected_cells: arr = arr[:expected_cells] else: arr = np.pad(arr, (0, expected_cells - arr.size), mode='edge') return arr.reshape(shape).astype(np.float32) else: if arr.shape[0] != expected_cells: print(f" WARNING: Expected {expected_cells} vectors, got {arr.shape[0]}. Truncating/padding.") if arr.shape[0] > expected_cells: arr = arr[:expected_cells] else: pad = np.zeros((expected_cells - arr.shape[0], arr.shape[1]), dtype=np.float32) arr = np.vstack([arr, pad]) return arr.reshape((*shape, arr.shape[-1])).astype(np.float32) def extract_case_spatial(case_dir, fields=['p', 'T', 'U', 'H2', 'O2'], shape=(150, 300), max_timesteps=20): """Extract spatial fields for all time steps in a case.""" case_path = Path(case_dir) time_dirs = [] for d in sorted(case_path.iterdir()): if d.is_dir(): try: t = float(d.name) if t > 1e-10: time_dirs.append((t, d)) except ValueError: continue time_dirs = sorted(time_dirs, key=lambda x: x[0])[:max_timesteps] if not time_dirs: raise ValueError(f"No valid time directories found in {case_dir}") snapshots = [] times = [] for t_val, t_dir in time_dirs: snapshot = {} valid = True for field in fields: field_file = t_dir / field try: arr = read_openfoam_field(field_file, shape) if field == 'U': if arr.ndim == 3 and arr.shape[-1] >= 2: snapshot['Ux'] = arr[..., 0] snapshot['Uy'] = arr[..., 1] if arr.shape[-1] > 2: snapshot['Uz'] = arr[..., 2] elif arr.ndim == 2: snapshot['Ux'] = arr snapshot['Uy'] = np.zeros_like(arr) else: print(f" WARNING: Unexpected U shape {arr.shape} at t={t_val}") valid = False break else: snapshot[field] = arr except Exception as e: print(f" ERROR reading {field} at t={t_val}: {e}") valid = False break if valid: channels = [] channel_order = ['p', 'T', 'Ux', 'Uy', 'H2', 'O2'] for key in channel_order: if key in snapshot: ch = snapshot[key] if ch.ndim != 2: print(f" WARNING: Channel {key} has shape {ch.shape}, expected 2D") if ch.ndim == 3: ch = ch[..., 0] channels.append(ch) else: print(f" WARNING: Missing channel {key} at t={t_val}") valid = False break if valid and len(channels) == 6: shapes = [ch.shape for ch in channels] if len(set(shapes)) != 1: print(f" ERROR: Shape mismatch at t={t_val}: {dict(zip(channel_order, shapes))}") valid = False else: snapshot_arr = np.stack(channels, axis=0) snapshots.append(snapshot_arr) times.append(t_val) if not valid: print(f" SKIPPED t={t_val:.6f}") if not snapshots: raise ValueError(f"No valid snapshots extracted from {case_dir}") return np.array(snapshots, dtype=np.float32), np.array(times, dtype=np.float32) def load_case_params_from_csv(csv_path, case_name, col_mapping, df): """Load parameters using auto-detected column mapping.""" if col_mapping is None or df is None: return None case_col = col_mapping.get('case_id') if case_col is None: return None # Try exact match first case_df = df[df[case_col].astype(str) == case_name] # If no match, try partial match if len(case_df) == 0: case_df = df[df[case_col].astype(str).str.contains(case_name, na=False)] if len(case_df) == 0: return None row = case_df.iloc[0] params = {'case_id': case_name} for std_name in ['phi', 'p0_pa', 'T0_k', 'cj_speed_ms']: csv_col = col_mapping.get(std_name) if csv_col and csv_col in row: params[std_name] = float(row[csv_col]) else: # Fallback defaults defaults = {'phi': 1.0, 'p0_pa': 101325, 'T0_k': 300, 'cj_speed_ms': 1900} params[std_name] = defaults.get(std_name, 0.0) return params def main(): parser = argparse.ArgumentParser(description='Extract RDE spatial fields') parser.add_argument('--cases_dir', type=str, default='.', help='Parent directory containing case folders') parser.add_argument('--cases', nargs='+', required=True, help='Case folder names (e.g., RDE_01 RDE_02)') parser.add_argument('--csv', type=str, default='RDE_hybrid_dataset_v9.csv', help='CSV file with case parameters') parser.add_argument('--output', type=str, default='spatial_fields.npz', help='Output NPZ file') parser.add_argument('--shape', nargs=2, type=int, default=[150, 300], help='Mesh dimensions H W') parser.add_argument('--max_t', type=int, default=20, help='Max time steps per case') parser.add_argument('--fields', nargs='+', default=['p', 'T', 'U', 'H2', 'O2'], help='Fields to extract') args = parser.parse_args() all_fields = [] all_times = [] all_params = [] print(f"Extracting fields: {args.fields}") print(f"Target shape: {tuple(args.shape)}") print(f"Max timesteps: {args.max_t}") print("=" * 70) # Load CSV and detect columns col_mapping = None df = None csv_path = Path(args.csv) if csv_path.exists(): print(f"\nAnalyzing CSV: {args.csv}") try: col_mapping, df = sniff_csv_columns(csv_path) if 'case_id' not in col_mapping: print(" WARNING: Could not detect case ID column. Will use defaults.") except Exception as e: print(f" ERROR reading CSV: {e}") else: print(f"\nWARNING: CSV not found: {args.csv}. Using default parameters.") for case in args.cases: case_dir = Path(args.cases_dir) / case print(f"\nProcessing {case}...") if not case_dir.exists(): print(f" ERROR: Directory not found: {case_dir}") continue try: fields, times = extract_case_spatial( case_dir, fields=args.fields, shape=tuple(args.shape), max_timesteps=args.max_t ) # Load parameters params = load_case_params_from_csv(args.csv, case, col_mapping, df) if params is None: print(f" WARNING: No params found for {case}, using defaults") params = { 'case_id': case, 'phi': 1.0, 'p0_pa': 101325, 'T0_k': 300, 'cj_speed_ms': 1900 } print(f" Extracted {len(times)} time steps, shape: {fields.shape}") print(f" Time range: [{times.min():.6f}, {times.max():.6f}]") print(f" Params: phi={params['phi']:.3f}, p0={params['p0_pa']:.0f}, " f"T0={params['T0_k']:.0f}, Dcj={params['cj_speed_ms']:.1f}") all_fields.append(fields) all_times.append(times) all_params.append(params) except Exception as e: print(f" ERROR processing {case}: {e}") import traceback traceback.print_exc() continue if not all_fields: print("\n" + "=" * 70) print("ERROR: No cases were successfully processed!") print("=" * 70) return all_fields = np.stack(all_fields, axis=0) all_times = np.stack(all_times, axis=0) print("\n" + "=" * 70) print(f"SAVED: {args.output}") print(f" Shape: {all_fields.shape}") print(f" Cases: {all_fields.shape[0]}") print(f" Time steps: {all_fields.shape[1]}") print(f" Channels: {all_fields.shape[2]}") print(f" Spatial: {all_fields.shape[3]} x {all_fields.shape[4]}") print(f" Size: {all_fields.nbytes / 1024**2:.1f} MB") print("=" * 70) np.savez_compressed(args.output, fields=all_fields, times=all_times, params=json.dumps(all_params)) if __name__ == '__main__': main()