339 lines
15 KiB
Python
339 lines
15 KiB
Python
# CelerisLab/config.py
|
||
"""
|
||
Unified configuration system.
|
||
|
||
Two JSON files:
|
||
config_lbm.json – grid, physics, method, cuda
|
||
config_body.json – object list
|
||
|
||
LBMConfig / BodyConfig are plain dataclasses; they translate to
|
||
macro dicts consumed by `cuda/compiler_v2.py` for header generation.
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import math
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# String ↔ integer mappings (used in JSON and macro generation)
|
||
# ---------------------------------------------------------------------------
|
||
LATTICE_MODEL_MAP = {
|
||
"D2Q9": {"dim": 2, "nq": 9, "id": 0},
|
||
"D3Q19": {"dim": 3, "nq": 19, "id": 1},
|
||
}
|
||
COLLISION_MAP = {"SRT": 0, "TRT": 1, "MRT": 2}
|
||
STREAMING_MAP = {"double_buffer": 0, "esopull": 1}
|
||
PRECISION_MAP = {"FP32": 0, "FP16S": 1, "FP16C": 2}
|
||
INLET_MAP = {"uniform": 0, "parabolic": 1}
|
||
INLET_SCHEME_MAP = {
|
||
"zou_he_local": 0,
|
||
"channel_stabilized": 1,
|
||
"equilibrium": 2,
|
||
"regularized": 3,
|
||
}
|
||
OUTLET_MAP = {"neq_extrap": 0, "zero_gradient": 1, "blended": 2}
|
||
Y_WALL_BC_MAP = {"bounce_back": 0, "free_slip": 1, "on_site_velocity": 2}
|
||
TOP_WALL_BC_MAP = {"velocity": 0, "reservoir": 1}
|
||
DTYPE_MAP = {"FP32": "float", "FP64": "double"}
|
||
|
||
|
||
def _float_literal(value: float) -> str:
|
||
"""Emit a round-trip numeric literal; display precision must not alter physics."""
|
||
return repr(float(value)) + "f"
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# LBM config
|
||
# ---------------------------------------------------------------------------
|
||
# ⚠ THIS IS NOT THE CONFIGURATION LOCATION.
|
||
# All parameters come from configs/config_lbm.json (the single source of truth).
|
||
# Use load_lbm_config() to construct; do not instantiate LBMConfig() with
|
||
# bare defaults. Tests may pass explicit kwargs for override only.
|
||
# See configs/CONFIG.md for parameter documentation.
|
||
# ---------------------------------------------------------------------------
|
||
@dataclass
|
||
class LBMConfig:
|
||
# Lattice model (canonical: determines dim and nq)
|
||
lattice_model: str = "D2Q9"
|
||
|
||
# Grid
|
||
nx: int = 512
|
||
ny: int = 256
|
||
nz: int = 1
|
||
|
||
# Physics
|
||
data_type: str = "FP32"
|
||
viscosity: float = 0.002
|
||
velocity: float = 0.03
|
||
rho: float = 1.0
|
||
|
||
# Method – collision / streaming / storage
|
||
collision: str = "SRT"
|
||
streaming: str = "double_buffer"
|
||
store_precision: str = "FP32"
|
||
ddf_shifting: bool = False
|
||
les_enabled: bool = False
|
||
les_cs: float = 0.16
|
||
les_closed_form: bool = True
|
||
trt_magic_param: float = 0.1875
|
||
inlet_profile: str = "parabolic"
|
||
inlet_scheme: str = "zou_he_local"
|
||
outlet_mode: str = "neq_extrap"
|
||
outlet_blend_alpha: float = 0.7
|
||
outlet_backflow_clamp: bool = True
|
||
inlet_trt_neq_damp: float = 0.5
|
||
inlet_regularized_neq_damp: float = 0.5
|
||
outlet_srt_neq_damp: float = 0.5
|
||
y_wall_bc: str = "bounce_back"
|
||
wall_normal_velocity: float = 0.0
|
||
wall_slot_width: int = 0
|
||
top_wall_bc: str = "velocity"
|
||
omega_min: float = 0.01
|
||
omega_max: float = 1.99
|
||
|
||
# CUDA
|
||
threads_per_block: int = 256
|
||
compute_capability: str = "auto"
|
||
|
||
# Derived (computed on validate — do not set manually)
|
||
dim: int = 0
|
||
nq: int = 0
|
||
omega: float = 0.0
|
||
|
||
@property
|
||
def is_d2q9(self) -> bool:
|
||
return self.lattice_model == "D2Q9"
|
||
|
||
@property
|
||
def is_d3q19(self) -> bool:
|
||
return self.lattice_model == "D3Q19"
|
||
|
||
def validate(self):
|
||
for name, allowed in (
|
||
("lattice_model", LATTICE_MODEL_MAP), ("collision", COLLISION_MAP),
|
||
("streaming", STREAMING_MAP), ("y_wall_bc", Y_WALL_BC_MAP),
|
||
("top_wall_bc", TOP_WALL_BC_MAP),
|
||
("data_type", DTYPE_MAP), ("store_precision", PRECISION_MAP),
|
||
("inlet_profile", INLET_MAP), ("inlet_scheme", INLET_SCHEME_MAP),
|
||
("outlet_mode", OUTLET_MAP),
|
||
):
|
||
if getattr(self, name) not in allowed:
|
||
raise ValueError(f"Unknown {name}: {getattr(self, name)!r}")
|
||
lm = LATTICE_MODEL_MAP[self.lattice_model]
|
||
self.dim, self.nq, self.lattice_model_id = lm["dim"], lm["nq"], lm["id"]
|
||
for name in ("nx", "ny", "nz", "threads_per_block"):
|
||
value = getattr(self, name)
|
||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||
raise ValueError(f"{name} must be a positive integer.")
|
||
if self.threads_per_block > 1024:
|
||
raise ValueError("threads_per_block must not exceed 1024.")
|
||
for name in ("viscosity", "velocity", "rho", "les_cs", "trt_magic_param",
|
||
"outlet_blend_alpha", "inlet_trt_neq_damp",
|
||
"inlet_regularized_neq_damp", "outlet_srt_neq_damp",
|
||
"omega_min", "omega_max", "wall_normal_velocity"):
|
||
if not math.isfinite(getattr(self, name)):
|
||
raise ValueError(f"{name} must be finite.")
|
||
if self.viscosity <= 0 or self.rho <= 0:
|
||
raise ValueError("viscosity and rho must be positive.")
|
||
if self.les_cs < 0 or self.trt_magic_param <= 0:
|
||
raise ValueError("les_cs must be nonnegative and trt_magic_param positive.")
|
||
if not 0 <= self.outlet_blend_alpha <= 1:
|
||
raise ValueError("outlet_blend_alpha must lie in [0, 1].")
|
||
if self.omega_min <= 0:
|
||
raise ValueError("omega_min must be positive.")
|
||
if self.store_precision == "FP16C":
|
||
raise ValueError(
|
||
"store_precision='FP16C' is not supported in the current runtime path. "
|
||
"Supported store_precision values: FP32, FP16S."
|
||
)
|
||
if self.data_type != "FP32":
|
||
raise ValueError(
|
||
"Only data_type='FP32' is supported: CUDA kernels and LBMField "
|
||
"paths use float32; LBtype is not wired through device code yet."
|
||
)
|
||
if self.dim == 2 and self.nz != 1:
|
||
raise ValueError("nz must be 1 for 2D")
|
||
if (isinstance(self.wall_slot_width, bool) or not isinstance(self.wall_slot_width, int)
|
||
or self.wall_slot_width != 0 and not 2 <= self.wall_slot_width <= self.nx):
|
||
raise ValueError("wall_slot_width must be 0 (disabled) or an integer in [2, nx]")
|
||
if self.wall_slot_width and (self.y_wall_bc != "on_site_velocity" or self.velocity != 0):
|
||
raise ValueError("wall_slot_width requires on_site_velocity and velocity=0")
|
||
if self.top_wall_bc == "reservoir" and (self.y_wall_bc != "on_site_velocity" or self.velocity != 0):
|
||
raise ValueError("reservoir requires on_site_velocity and velocity=0")
|
||
if self.y_wall_bc == "on_site_velocity":
|
||
if (not self.is_d2q9 or self.collision != "SRT"
|
||
or self.streaming != "double_buffer" or self.store_precision != "FP32"
|
||
or self.ddf_shifting or self.les_enabled):
|
||
raise ValueError("on_site_velocity requires D2Q9/SRT/FP32/unshifted/double_buffer without LES")
|
||
if abs(self.wall_normal_velocity) >= 1:
|
||
raise ValueError("on_site_velocity requires abs(wall_normal_velocity) < 1")
|
||
if not (0.0 <= self.inlet_trt_neq_damp <= 1.0):
|
||
raise ValueError("method.inlet.trt_neq_damp must lie in [0, 1].")
|
||
if not (0.0 <= self.inlet_regularized_neq_damp <= 1.0):
|
||
raise ValueError("method.inlet.regularized_neq_damp must lie in [0, 1].")
|
||
if not (0.0 <= self.outlet_srt_neq_damp <= 1.0):
|
||
raise ValueError("method.outlet.srt_neq_damp must lie in [0, 1].")
|
||
if self.dim == 3 and self.y_wall_bc == "free_slip":
|
||
raise ValueError("y_wall_bc='free_slip' is currently supported for D2Q9 only.")
|
||
if self.omega_max >= 2.0:
|
||
raise ValueError("method.omega_guard.max must be < 2.0.")
|
||
if self.omega_min >= self.omega_max:
|
||
raise ValueError(
|
||
f"Invalid omega guard window: min={self.omega_min}, max={self.omega_max}."
|
||
)
|
||
self.omega = 1.0 / (3.0 * self.viscosity + 0.5)
|
||
if not (self.omega_min <= self.omega <= self.omega_max):
|
||
raise ValueError(
|
||
f"Computed omega={self.omega:.6f} outside guard "
|
||
f"[{self.omega_min:.6f}, {self.omega_max:.6f}]."
|
||
)
|
||
|
||
def validate_runtime(self):
|
||
"""Validate the currently complete Simulation path, not local operators."""
|
||
self.validate()
|
||
if self.is_d3q19:
|
||
raise NotImplementedError(
|
||
"D3Q19 Simulation is not supported yet: boundary/auxiliary kernels "
|
||
"and object projection are not dimension-complete. D3Q19 local "
|
||
"descriptors and collision operators remain available for research."
|
||
)
|
||
if self.nx < 3 or self.ny < 4:
|
||
raise ValueError("Simulation requires nx >= 3 and ny >= 4: x ghost layers and distinct wall-adjacent rows.")
|
||
|
||
def allocation_signature(self) -> tuple:
|
||
"""Parameters that cannot change while field allocations/state are retained."""
|
||
self.validate()
|
||
return (self.lattice_model, self.nx, self.ny, self.nz, self.data_type,
|
||
self.store_precision, bool(self.ddf_shifting), self.streaming,
|
||
(self.velocity, self.wall_normal_velocity, self.wall_slot_width,
|
||
self.top_wall_bc, self.rho if self.top_wall_bc == "reservoir" else None)
|
||
if self.y_wall_bc == "on_site_velocity" else None)
|
||
|
||
@property
|
||
def top_wall_normal_velocity(self) -> float:
|
||
"""Volume-balanced top velocity target, or reservoir initialization guess."""
|
||
if self.wall_slot_width in (0, self.nx):
|
||
return self.wall_normal_velocity
|
||
weights = (max(0.0, 1.0-((2*x-(self.nx-1))/self.wall_slot_width)**2)**2
|
||
for x in range(self.nx))
|
||
return self.wall_normal_velocity * math.fsum(weights) / self.nx
|
||
|
||
def to_macros(self) -> Dict[str, Any]:
|
||
"""Return flat dict of macro_name → value for header generation."""
|
||
self.validate()
|
||
return {
|
||
"NT": self.threads_per_block,
|
||
"MULT_GPU": 0,
|
||
"NX": self.nx,
|
||
"NY": self.ny,
|
||
"NZ": self.nz,
|
||
"LATTICE_MODEL": self.lattice_model_id,
|
||
"LBtype": DTYPE_MAP[self.data_type],
|
||
"VIS": repr(float(self.viscosity)),
|
||
"RHO": repr(float(self.rho)),
|
||
"U0": repr(float(self.velocity)),
|
||
"COLLISION_MODEL": COLLISION_MAP[self.collision],
|
||
"STREAMING_MODEL": STREAMING_MAP[self.streaming],
|
||
"STORE_PRECISION": PRECISION_MAP[self.store_precision],
|
||
"USE_DDF_SHIFTING": int(self.ddf_shifting),
|
||
"USE_LES": int(self.les_enabled),
|
||
"LES_CS": _float_literal(self.les_cs),
|
||
"LES_CLOSED_FORM": int(self.les_closed_form),
|
||
"INLET_PROFILE": INLET_MAP[self.inlet_profile],
|
||
"INLET_SCHEME": INLET_SCHEME_MAP[self.inlet_scheme],
|
||
"OUTLET_MODE": OUTLET_MAP[self.outlet_mode],
|
||
"OUTLET_BLEND_ALPHA": _float_literal(self.outlet_blend_alpha),
|
||
"OUTLET_BACKFLOW_CLAMP": int(self.outlet_backflow_clamp),
|
||
"Y_WALL_BC": Y_WALL_BC_MAP[self.y_wall_bc],
|
||
"WALL_NORMAL_VELOCITY": _float_literal(self.wall_normal_velocity),
|
||
"WALL_SLOT_WIDTH": self.wall_slot_width,
|
||
"TOP_WALL_NORMAL_VELOCITY": _float_literal(self.top_wall_normal_velocity),
|
||
"TOP_WALL_BC": TOP_WALL_BC_MAP[self.top_wall_bc],
|
||
"OMEGA_COLLISION_MIN": _float_literal(self.omega_min),
|
||
"OMEGA_COLLISION_MAX": _float_literal(self.omega_max),
|
||
"TRT_MAGIC_PARAM": _float_literal(self.trt_magic_param),
|
||
"INLET_TRT_NEQ_DAMP": _float_literal(self.inlet_trt_neq_damp),
|
||
"INLET_REGULARIZED_NEQ_DAMP": _float_literal(self.inlet_regularized_neq_damp),
|
||
"OUTLET_SRT_NEQ_DAMP": _float_literal(self.outlet_srt_neq_damp),
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Body config
|
||
# ---------------------------------------------------------------------------
|
||
@dataclass
|
||
class BodyConfig:
|
||
objects: List[Dict[str, Any]] = field(default_factory=list)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Loaders
|
||
# ---------------------------------------------------------------------------
|
||
def _find_config(filename: str, explicit_path: Optional[str] = None) -> str:
|
||
"""Search for config file in standard locations."""
|
||
candidates = []
|
||
if explicit_path is not None:
|
||
explicit_path = os.fspath(explicit_path)
|
||
if not os.path.isfile(explicit_path):
|
||
raise FileNotFoundError(f"Explicit config path does not exist: {explicit_path}")
|
||
return os.path.abspath(explicit_path)
|
||
env_dir = os.environ.get("CELERISLAB_CONFIG_DIR")
|
||
if env_dir:
|
||
candidates.append(os.path.join(env_dir, filename))
|
||
candidates.append(os.path.join(os.getcwd(), "configs", filename))
|
||
pkg_root = os.path.dirname(os.path.abspath(__file__))
|
||
candidates.append(os.path.join(pkg_root, "configs", filename))
|
||
for p in candidates:
|
||
if os.path.isfile(p):
|
||
return os.path.abspath(p)
|
||
raise FileNotFoundError(
|
||
f"Config '{filename}' not found. Searched:\n"
|
||
+ "\n".join(f" - {p}" for p in candidates)
|
||
)
|
||
|
||
|
||
def load_lbm_config(path: Optional[str] = None) -> LBMConfig:
|
||
fpath = _find_config("config_lbm.json", path)
|
||
with open(fpath) as f:
|
||
d = json.load(f)
|
||
g, p, m, c = d["grid"], d["physics"], d["method"], d["cuda"]
|
||
cfg = LBMConfig(
|
||
lattice_model=g["lattice_model"],
|
||
nx=g["nx"], ny=g["ny"], nz=g["nz"],
|
||
data_type=p["data_type"], viscosity=p["viscosity"],
|
||
velocity=p["velocity"], rho=p["rho"],
|
||
collision=m["collision"], streaming=m["streaming"],
|
||
store_precision=m["store_precision"],
|
||
ddf_shifting=m["ddf_shifting"],
|
||
les_enabled=m["les"]["enabled"], les_cs=m["les"]["cs"],
|
||
les_closed_form=m["les"].get("closed_form", True),
|
||
trt_magic_param=m["trt"]["magic_param"],
|
||
inlet_profile=m["inlet"]["profile"],
|
||
inlet_scheme=m["inlet"].get("scheme", "zou_he_local"),
|
||
outlet_mode=m["outlet"]["mode"],
|
||
outlet_blend_alpha=m["outlet"]["blend_alpha"],
|
||
outlet_backflow_clamp=m["outlet"]["backflow_clamp"],
|
||
inlet_trt_neq_damp=m["inlet"].get("trt_neq_damp", 0.5),
|
||
inlet_regularized_neq_damp=m["inlet"].get("regularized_neq_damp", 0.5),
|
||
outlet_srt_neq_damp=m["outlet"].get("srt_neq_damp", 0.5),
|
||
y_wall_bc=m.get("y_wall_bc", "bounce_back"),
|
||
wall_normal_velocity=m.get("wall_normal_velocity", 0.0),
|
||
wall_slot_width=m.get("wall_slot_width", 0),
|
||
top_wall_bc=m.get("top_wall_bc", "velocity"),
|
||
omega_min=m["omega_guard"]["min"],
|
||
omega_max=m["omega_guard"]["max"],
|
||
threads_per_block=c["threads_per_block"],
|
||
compute_capability=c["compute_capability"],
|
||
)
|
||
cfg.validate()
|
||
return cfg
|
||
|
||
|
||
def load_body_config(path: Optional[str] = None) -> BodyConfig:
|
||
fpath = _find_config("config_body.json", path)
|
||
with open(fpath) as f:
|
||
d = json.load(f)
|
||
return BodyConfig(objects=d.get("objects", []))
|