Upload folder using huggingface_hub
Browse filesFiles changed (23)
- README.mdAdded+153
- config/config.yamlAdded+56
- models/PointNetCFD.pyAdded+146
- models/__init__.pyAdded+5
- models/__pycache__/PointNetCFD.cpython-310.pycAdded
- models/__pycache__/PointNetCFD.cpython-311.pycAdded
- models/__pycache__/__init__.cpython-310.pycAdded
- models/__pycache__/__init__.cpython-311.pycAdded
- scripts/__init__.pyAdded+1
- scripts/__pycache__/__init__.cpython-311.pycAdded
- scripts/__pycache__/common.cpython-310.pycAdded
- scripts/__pycache__/common.cpython-311.pycAdded
- scripts/__pycache__/inference.cpython-310.pycAdded
- scripts/__pycache__/inference.cpython-311.pycAdded
- scripts/__pycache__/result.cpython-310.pycAdded
- scripts/__pycache__/result.cpython-311.pycAdded
- scripts/__pycache__/train.cpython-310.pycAdded
- scripts/__pycache__/train.cpython-311.pycAdded
- scripts/common.pyAdded+492
- scripts/inference.pyAdded+206
- scripts/result.pyAdded+147
- scripts/train.pyAdded+323
- weight/best_model.pthAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153---license: mitlanguage:- entags:- OneScience- fluid-mechanics- flow-field-prediction- point-cloudframeworks: PyTorch---<p align="center"> <strong> <span style="font-size: 30px;">PointNetCFD</span> </strong></p>
# Model Introduction
PointNetCFD is a point-cloud model for flow-field prediction proposed by Ali Kashefi, Davis Rempe, and Leonidas J. Guibas. It directly represents nodes of unstructured CFD meshes in irregular geometries as point clouds, uses PointNet to encode geometry and spatial position, and predicts two velocity components and pressure at each point. This repository is an independent reproduction based on the paper and implemented through the OneScience skill workflow.
Paper: [A Point-Cloud Deep Learning Framework for Prediction of Fluid Flow Fields on Irregular Geometries](https://arxiv.org/abs/2010.09469)
# Model Description
PointNetCFD is a pointwise CFD regression model for unstructured meshes. Each sample contains 1,024 points. It takes node coordinates `(x, y)` as input and predicts `(u, v, p)` at every point. T-Nets align the inputs and features; shared MLPs and global max pooling extract local and global features; and a `512 → 256 → 128 → 128 → 3` decoder predicts the flow field from the fused representation. Coordinates retain their original physical scale, while output variables are normalized to `[0, 1]` using training-set statistics.
## Use Cases
| Use case | Description || --- | --- || CFD flow-field prediction | Predicts velocity components `(u, v)` and pressure `p` point by point from the two-dimensional coordinates `(x, y)` of unstructured-mesh nodes. || Irregular-geometry modeling | Directly represents object boundaries and unstructured meshes as point clouds without interpolating CFD data onto a regular grid. || Geometry generalization | The corresponding experiment evaluates predictive performance on previously unseen geometries. |
# Usage
## 1. Using OneCode
Try intelligent, one-click AI4S programming in the OneCode online environment:
[Try intelligent, one-click AI4S programming](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
## 2. Manual Installation and Usage
**Hardware requirements**
- A GPU or DCU is recommended.- A CPU can be used for import checks and small-scale connectivity tests, but full training and inference will be slow.- DCU users must install DTK in advance. DTK 25.04.2 or later, or the OneScience-recommended version for the current cluster, is recommended.
### Download the Model Package
```bashmodelscope download --model OneScience/PointNetCFD --local_dir ./PointNetCFDcd PointNetCFD```
### Set Up the Runtime Environment
**DCU environment**
```bash# Activate DTK and Conda firstconda create -n onescience311 python=3.11 -yconda activate onescience311# Installation with uv is also supportedpip install onescience[cfd-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai```
**GPU environment**
```bash# Activate Conda firstconda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12conda activate onescience311# Installation with uv is also supportedpip install onescience[cfd-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai```
### Training Data
The OneScience community provides PointNetCFD training data. Download it with the command below, then make sure `paths.data_dir` in `config/config.yaml` points to the downloaded data directory:
```bashmodelscope download --dataset OneScience/pointnet_cfd --local_dir ./data```
Each sample in `CFDdata.npy` is a 1,024 × 5 point-cloud data matrix with columns `[x, y, p, u, v]`. Index files for the training, validation, and test sets are also provided.
### Training
The default `config/config.yaml` corresponds to the main experimental setup in the paper.
```bashpython scripts/train.py --config config/config.yaml```
During training, the training loss, validation loss, and evaluation metrics for each epoch are printed to standard output. The checkpoint with the best validation MSE is saved to:
```textweight/best_model.pth```
The training history, effective configuration, and training summary are stored in the `results/` directory. For an environment-connectivity check, run the minimal smoke test, which uses a separate output path:
```bashpython scripts/train.py --smoke-test```
### Trained Weights
The `weight/` directory contains weights pretrained on the PointNetCFD data and ready for inference.
### Inference
Before running inference, make sure the data path in `config/config.yaml` is valid and `weight/best_model.pth` exists. The following command runs inference on the fixed test set and prints the normalized MSE, RMSE for each physical variable, and relative L2 error in real time:
```bashpython scripts/inference.py \ --config config/config.yaml \ --checkpoint weight/best_model.pth \ --device auto \ --output-dir results```
Inference outputs are saved as:
- `results/test_metrics.json`: test metrics and reference metrics from the paper;- `results/predictions.npz`: coordinates, predictions, ground truth, and sample indices.
### Evaluation and Visualization
Numerical evaluation is performed by `scripts/inference.py` during inference. The visualization script depends on `results/predictions.npz`, so complete the inference step above before running:
```bashpython scripts/result.py \ --predictions results/predictions.npz \ --output-dir results/figures \ --num-cases 3```
# Official OneScience Resources
| Platform | OneScience Main Repository | Skills Repository || --- | --- | --- || Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills || GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
# Citation and License
- Paper: [A Point-Cloud Deep Learning Framework for Prediction of Fluid Flow Fields on Irregular Geometries](https://arxiv.org/abs/2010.09469), [DOI: 10.1063/5.0033376](https://doi.org/10.1063/5.0033376)- This repository preserves the attribution and copyright information of the original paper and official implementation. The official code is licensed under the MIT License; the paper, dataset, and other related resources remain subject to their respective copyright notices and terms of use.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# PointCFD main experiment from arXiv:2010.09469.experiment: name: pointcfd_main paper: https://arxiv.org/pdf/2010.09469
paths: data_dir: /public/share/sugonhpcapp01/onestore/onedatasets/PointNetCFD_data data_file: CFDdata.npy train_indices: training_idx.npy validation_indices: validation_idx.npy test_indices: test_idx.npy checkpoint: weight/best_model.pth results_dir: results
data: num_points: 1024 source_channels: [x, y, p, u, v] input_indices: [0, 1] target_indices: [3, 4, 2] input_names: [x, y] target_names: [u, v, p] coordinate_normalization: none target_normalization: train_minmax
model: input_dim: 2 output_dim: 3 global_feature_dim: 1024 expected_paper_parameters: 3552588
training: # The paper does not report a random seed; zero is the reproducible default. seed: 0 epochs: 4000 batch_size: 256 num_workers: 0 optimizer: adam learning_rate: 0.0005 beta1: 0.9 beta2: 0.999 epsilon: 0.000001 weight_decay: 0.0 scheduler: none precision: float32 validation_interval: 1 log_every_batches: 1 # The paper validates each epoch but does not define checkpoint selection. best_metric: val_mse
evaluation: relative_l2_epsilon: 1.0e-12 visualization_cases: 3 paper_reference_mean_relative_l2: u: 0.0449666 v: 0.0370540 p: 0.0271661123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Paper-faithful PointNet architecture for PointCFD field regression.
The model follows Figure 5 of Kashefi, Rempe, and Guibas (2021): an inputtransform, a feature transform, symmetric max aggregation, and a point-wisedecoder for the nondimensional velocity and pressure fields."""
from __future__ import annotations
from typing import Tuple, Union
import torchfrom torch import Tensor, nn
class ConvBNReLU(nn.Sequential): """A shared point-wise fully connected layer with BN and ReLU."""
def __init__(self, in_channels: int, out_channels: int) -> None: super().__init__( nn.Conv1d(in_channels, out_channels, kernel_size=1, bias=True), nn.BatchNorm1d(out_channels), nn.ReLU(inplace=True), )
class LinearBNReLU(nn.Sequential): """A fully connected layer with BN and ReLU."""
def __init__(self, in_features: int, out_features: int) -> None: super().__init__( nn.Linear(in_features, out_features, bias=True), nn.BatchNorm1d(out_features), nn.ReLU(inplace=True), )
class TransformNet(nn.Module): """PointNet transformation network for input or intermediate features."""
def __init__(self, k: int) -> None: super().__init__() if k <= 0: raise ValueError(f"k must be positive, got {k}") self.k = int(k) self.point_mlp = nn.Sequential( ConvBNReLU(self.k, 64), ConvBNReLU(64, 128), ConvBNReLU(128, 1024), ) self.global_mlp = nn.Sequential( LinearBNReLU(1024, 512), LinearBNReLU(512, 256), ) self.transform = nn.Linear(256, self.k * self.k, bias=True)
# The paper adopts PointNet's canonical identity initialization. nn.init.zeros_(self.transform.weight) nn.init.zeros_(self.transform.bias)
def forward(self, features: Tensor) -> Tensor: """Predict a transform from channel-first features ``[B, k, N]``.""" if features.ndim != 3 or features.shape[1] != self.k: raise ValueError( f"TransformNet({self.k}) expects [B,{self.k},N], " f"got {tuple(features.shape)}" ) encoded = self.point_mlp(features) global_feature = torch.amax(encoded, dim=2) transform_delta = self.transform(self.global_mlp(global_feature)) identity = torch.eye( self.k, dtype=features.dtype, device=features.device ).reshape(1, self.k * self.k) return (transform_delta + identity).reshape(-1, self.k, self.k)
class PointNetCFD(nn.Module): """Regress normalized ``(u, v, p)`` at every input point."""
def __init__(self, input_dim: int = 2, output_dim: int = 3) -> None: super().__init__() if input_dim <= 0 or output_dim <= 0: raise ValueError("input_dim and output_dim must be positive") self.input_dim = int(input_dim) self.output_dim = int(output_dim)
self.input_transform = TransformNet(self.input_dim) self.input_mlp = nn.Sequential( ConvBNReLU(self.input_dim, 64), ConvBNReLU(64, 64), ) self.feature_transform = TransformNet(64) self.global_mlp = nn.Sequential( ConvBNReLU(64, 64), ConvBNReLU(64, 128), ConvBNReLU(128, 1024), ) self.decoder = nn.Sequential( ConvBNReLU(64 + 1024, 512), ConvBNReLU(512, 256), ConvBNReLU(256, 128), ConvBNReLU(128, 128), nn.Conv1d(128, self.output_dim, kernel_size=1, bias=True), nn.Sigmoid(), )
def forward( self, points: Tensor, return_transforms: bool = False ) -> Union[Tensor, Tuple[Tensor, Tensor, Tensor]]: """Run point-wise regression.
Args: points: Physical coordinates shaped ``[batch, points, input_dim]``. return_transforms: Also return input and feature transform matrices. """ if points.ndim != 3 or points.shape[-1] != self.input_dim: raise ValueError( f"PointNetCFD expects [B,N,{self.input_dim}], got {tuple(points.shape)}" )
channel_first = points.transpose(1, 2).contiguous() input_transform = self.input_transform(channel_first) transformed_points = torch.bmm(points, input_transform)
local_feature = self.input_mlp( transformed_points.transpose(1, 2).contiguous() ) feature_transform = self.feature_transform(local_feature) transformed_local = torch.bmm( local_feature.transpose(1, 2), feature_transform ).transpose(1, 2).contiguous()
encoded = self.global_mlp(transformed_local) global_feature = torch.amax(encoded, dim=2, keepdim=True) global_repeated = global_feature.expand(-1, -1, points.shape[1]) decoded_input = torch.cat((transformed_local, global_repeated), dim=1) prediction = self.decoder(decoded_input).transpose(1, 2).contiguous()
if return_transforms: return prediction, input_transform, feature_transform return prediction
def count_trainable_parameters(model: nn.Module) -> int: """Return the number of parameters updated by gradient descent.""" return sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad)12345"""PointCFD model package."""
from .PointNetCFD import PointNetCFD, TransformNet, count_trainable_parameters
__all__ = ["PointNetCFD", "TransformNet", "count_trainable_parameters"]1"""Executable and shared utilities for the PointCFD reproduction."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492"""Shared data, metric, configuration, and serialization utilities."""
from __future__ import annotations
import jsonimport osimport randomfrom pathlib import Pathfrom typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple
import numpy as npimport torchimport yamlfrom torch import Tensor, nnfrom torch.utils.data import DataLoader, Dataset
PAPER_SAMPLE_COUNT = 2595AVAILABLE_SAMPLE_COUNT = 2215
def load_config(config_path: Path) -> Dict[str, Any]: """Load and minimally validate the experiment YAML.""" config_path = Path(config_path).expanduser().resolve() if not config_path.is_file(): raise FileNotFoundError(f"Configuration file not found: {config_path}") with config_path.open("r", encoding="utf-8") as handle: config = yaml.safe_load(handle) if not isinstance(config, dict): raise ValueError(f"Configuration must be a mapping: {config_path}") required_sections = ("experiment", "paths", "data", "model", "training", "evaluation") missing = [section for section in required_sections if section not in config] if missing: raise ValueError(f"Configuration is missing sections: {missing}")
data_config = config["data"] if data_config.get("coordinate_normalization") != "none": raise ValueError("Paper fidelity requires coordinate_normalization: none") if data_config.get("target_normalization") != "train_minmax": raise ValueError("Paper fidelity requires target_normalization: train_minmax") if list(data_config.get("target_names", [])) != ["u", "v", "p"]: raise ValueError("Model target order must be [u, v, p]") if config["training"].get("scheduler") != "none": raise ValueError("The paper does not specify a learning-rate scheduler") return config
def resolve_path(project_root: Path, configured_path: str) -> Path: """Resolve an absolute path or a path relative to the project root.""" path = Path(configured_path).expanduser() return path.resolve() if path.is_absolute() else (project_root / path).resolve()
def configured_paths(config: Mapping[str, Any], project_root: Path) -> Dict[str, Path]: """Resolve all data and output paths without consulting environment variables.""" paths = config["paths"] data_dir = resolve_path(project_root, str(paths["data_dir"])) return { "data": data_dir / str(paths["data_file"]), "train_indices": data_dir / str(paths["train_indices"]), "validation_indices": data_dir / str(paths["validation_indices"]), "test_indices": data_dir / str(paths["test_indices"]), "checkpoint": resolve_path(project_root, str(paths["checkpoint"])), "results_dir": resolve_path(project_root, str(paths["results_dir"])), }
def set_deterministic_seed(seed: int) -> None: """Seed every RNG used by this project.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) if hasattr(torch.backends, "cudnn"): torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False try: torch.use_deterministic_algorithms(True, warn_only=True) except (AttributeError, TypeError): pass
def choose_device(requested: str) -> torch.device: """Resolve ``auto``, CPU, or an explicit CUDA device.""" requested = requested.strip().lower() if requested == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") device = torch.device(requested) if device.type == "cuda" and not torch.cuda.is_available(): raise RuntimeError(f"CUDA device requested but CUDA is unavailable: {requested}") return device
def _load_index_array(path: Path) -> np.ndarray: if not path.is_file(): raise FileNotFoundError(f"Split index file not found: {path}") indices = np.load(path, allow_pickle=False) if indices.ndim != 1 or not np.issubdtype(indices.dtype, np.integer): raise ValueError(f"Split indices must be a one-dimensional integer array: {path}") return np.asarray(indices, dtype=np.int64)
def load_data_and_splits( config: Mapping[str, Any], project_root: Path) -> Tuple[np.ndarray, Dict[str, np.ndarray], Dict[str, Path]]: """Load the CFD array read-only and validate the fixed supplied splits.""" paths = configured_paths(config, project_root) if not paths["data"].is_file(): raise FileNotFoundError(f"CFD data file not found: {paths['data']}") data = np.load(paths["data"], mmap_mode="r", allow_pickle=False) expected_points = int(config["data"]["num_points"]) expected_channels = len(config["data"]["source_channels"]) if data.ndim != 3 or data.shape[1:] != (expected_points, expected_channels): raise ValueError( f"Expected CFD array [cases,{expected_points},{expected_channels}], " f"got {data.shape}" ) if data.dtype != np.float32: raise ValueError(f"Expected float32 CFD data, got {data.dtype}") if not np.isfinite(data).all(): raise ValueError("CFD data contains NaN or infinite values")
splits = { "train": _load_index_array(paths["train_indices"]), "validation": _load_index_array(paths["validation_indices"]), "test": _load_index_array(paths["test_indices"]), } total_cases = int(data.shape[0]) for name, indices in splits.items(): if indices.size == 0: raise ValueError(f"Split {name} is empty") if indices.min() < 0 or indices.max() >= total_cases: raise ValueError(f"Split {name} contains out-of-range indices") if np.unique(indices).size != indices.size: raise ValueError(f"Split {name} contains duplicate indices") split_sets = {name: set(values.tolist()) for name, values in splits.items()} if split_sets["train"] & split_sets["validation"]: raise ValueError("Training and validation splits overlap") if split_sets["train"] & split_sets["test"]: raise ValueError("Training and test splits overlap") if split_sets["validation"] & split_sets["test"]: raise ValueError("Validation and test splits overlap") covered = split_sets["train"] | split_sets["validation"] | split_sets["test"] if covered != set(range(total_cases)): raise ValueError("Fixed splits do not cover the dataset exactly") return data, splits, paths
def fit_target_minmax( data: np.ndarray, train_indices: np.ndarray, target_indices: Sequence[int]) -> Tuple[np.ndarray, np.ndarray]: """Fit per-variable extrema using the training split and no other cases.""" training_cases = np.asarray(data[train_indices], dtype=np.float32) training_targets = np.take(training_cases, target_indices, axis=-1) target_min = training_targets.min(axis=(0, 1)).astype(np.float32) target_max = training_targets.max(axis=(0, 1)).astype(np.float32) if not np.isfinite(target_min).all() or not np.isfinite(target_max).all(): raise ValueError("Target normalization extrema are not finite") if np.any(target_max <= target_min): raise ValueError( f"Every target must have positive min-max span: min={target_min}, max={target_max}" ) return target_min, target_max
class PointCFDDataset(Dataset): """A fixed case-index view of the supplied PointCFD NumPy array."""
def __init__( self, data: np.ndarray, case_indices: np.ndarray, input_indices: Sequence[int], target_indices: Sequence[int], target_min: np.ndarray, target_max: np.ndarray, ) -> None: self.data = data self.case_indices = np.asarray(case_indices, dtype=np.int64) self.input_indices = tuple(int(index) for index in input_indices) self.target_indices = tuple(int(index) for index in target_indices) self.target_min = np.asarray(target_min, dtype=np.float32) self.target_max = np.asarray(target_max, dtype=np.float32) if self.target_min.shape != (len(self.target_indices),): raise ValueError("target_min has the wrong shape") if self.target_max.shape != self.target_min.shape: raise ValueError("target_max has the wrong shape") self.target_span = self.target_max - self.target_min if np.any(self.target_span <= 0): raise ValueError("Target min-max span must be positive")
def __len__(self) -> int: return int(self.case_indices.size)
def __getitem__(self, item: int) -> Tuple[Tensor, Tensor, Tensor]: case_index = int(self.case_indices[item]) sample = self.data[case_index] coordinates = np.ascontiguousarray(sample[:, self.input_indices], dtype=np.float32) targets = np.ascontiguousarray(sample[:, self.target_indices], dtype=np.float32) normalized = np.ascontiguousarray( (targets - self.target_min) / self.target_span, dtype=np.float32 ) return ( torch.from_numpy(coordinates), torch.from_numpy(normalized), torch.tensor(case_index, dtype=torch.int64), )
def make_loader( dataset: Dataset, batch_size: int, shuffle: bool, num_workers: int, seed: int, pin_memory: bool,) -> DataLoader: if batch_size <= 0: raise ValueError("batch_size must be positive") if num_workers < 0: raise ValueError("num_workers cannot be negative") generator = torch.Generator() generator.manual_seed(seed)
def seed_worker(worker_id: int) -> None: worker_seed = (seed + worker_id) % (2**32) np.random.seed(worker_seed) random.seed(worker_seed)
return DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory, drop_last=False, generator=generator, worker_init_fn=seed_worker if num_workers else None, )
def inverse_target_minmax( normalized: np.ndarray, target_min: np.ndarray, target_max: np.ndarray) -> np.ndarray: return normalized * (target_max - target_min) + target_min
def compute_field_metrics( predictions_normalized: np.ndarray, targets_normalized: np.ndarray, target_min: np.ndarray, target_max: np.ndarray, target_names: Sequence[str], relative_l2_epsilon: float,) -> Tuple[Dict[str, Any], np.ndarray, np.ndarray]: """Compute paper-style field error metrics after inverse normalization.""" predictions_normalized = np.asarray(predictions_normalized, dtype=np.float32) targets_normalized = np.asarray(targets_normalized, dtype=np.float32) if predictions_normalized.shape != targets_normalized.shape: raise ValueError("Prediction and target shapes do not match") if predictions_normalized.ndim != 3: raise ValueError("Evaluation arrays must be [cases, points, variables]") if predictions_normalized.shape[-1] != len(target_names): raise ValueError("Target names do not match the evaluated variables") if relative_l2_epsilon <= 0: raise ValueError("relative_l2_epsilon must be positive")
normalized_error = predictions_normalized - targets_normalized normalized_mse = float(np.mean(np.square(normalized_error), dtype=np.float64)) predictions = inverse_target_minmax(predictions_normalized, target_min, target_max) targets = inverse_target_minmax(targets_normalized, target_min, target_max) error = predictions - targets
rmse: Dict[str, float] = {} relative_l2: Dict[str, Dict[str, float]] = {} for channel, name in enumerate(target_names): channel_error = error[:, :, channel].astype(np.float64) channel_target = targets[:, :, channel].astype(np.float64) rmse[str(name)] = float(np.sqrt(np.mean(np.square(channel_error)))) numerator = np.linalg.norm(channel_error, axis=1) denominator = np.maximum( np.linalg.norm(channel_target, axis=1), relative_l2_epsilon ) per_case = numerator / denominator relative_l2[str(name)] = { "mean": float(np.mean(per_case)), "max": float(np.max(per_case)), "min": float(np.min(per_case)), } metrics = { "normalized_mse": normalized_mse, "rmse": rmse, "relative_l2": relative_l2, } return metrics, predictions.astype(np.float32), targets.astype(np.float32)
def evaluate_model( model: nn.Module, loader: DataLoader, device: torch.device, target_min: np.ndarray, target_max: np.ndarray, target_names: Sequence[str], relative_l2_epsilon: float,) -> Tuple[Dict[str, Any], Dict[str, np.ndarray]]: """Evaluate a complete split and retain arrays needed for reporting.""" model.eval() coordinates_batches = [] prediction_batches = [] target_batches = [] index_batches = [] with torch.no_grad(): for coordinates, targets, case_indices in loader: predictions = model(coordinates.to(device, non_blocking=True)) coordinates_batches.append(coordinates.numpy()) prediction_batches.append(predictions.cpu().numpy()) target_batches.append(targets.numpy()) index_batches.append(case_indices.numpy()) if not prediction_batches: raise ValueError("Evaluation loader produced no batches") coordinates_array = np.concatenate(coordinates_batches, axis=0) predictions_normalized = np.concatenate(prediction_batches, axis=0) targets_normalized = np.concatenate(target_batches, axis=0) case_indices_array = np.concatenate(index_batches, axis=0) metrics, predictions, targets = compute_field_metrics( predictions_normalized, targets_normalized, target_min, target_max, target_names, relative_l2_epsilon, ) arrays = { "coordinates": coordinates_array.astype(np.float32), "predictions": predictions, "targets": targets, "predictions_normalized": predictions_normalized.astype(np.float32), "targets_normalized": targets_normalized.astype(np.float32), "case_indices": case_indices_array.astype(np.int64), } return metrics, arrays
def _json_safe(value: Any) -> Any: if isinstance(value, Mapping): return {str(key): _json_safe(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return [_json_safe(item) for item in value] if isinstance(value, Path): return str(value) if isinstance(value, np.ndarray): return value.tolist() if isinstance(value, np.generic): return value.item() if isinstance(value, torch.device): return str(value) if isinstance(value, float) and not np.isfinite(value): raise ValueError("JSON output cannot contain NaN or Infinity") return value
def write_json(path: Path, payload: Mapping[str, Any]) -> None: """Atomically write strict, human-readable JSON.""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") with temporary.open("w", encoding="utf-8") as handle: json.dump(_json_safe(payload), handle, indent=2, sort_keys=True, allow_nan=False) handle.write("\n") os.replace(temporary, path)
def append_jsonl(path: Path, payload: Mapping[str, Any]) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(_json_safe(payload), sort_keys=True, allow_nan=False) + "\n") handle.flush()
def write_npz(path: Path, **arrays: np.ndarray) -> None: """Atomically write a compressed NumPy archive.""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp.npz") np.savez_compressed(temporary, **arrays) os.replace(temporary, path)
def save_checkpoint(path: Path, payload: Mapping[str, Any]) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") torch.save(dict(payload), temporary) os.replace(temporary, path)
def load_checkpoint(path: Path, device: torch.device) -> Dict[str, Any]: path = Path(path).expanduser().resolve() if not path.is_file(): raise FileNotFoundError(f"Checkpoint not found: {path}") try: checkpoint = torch.load(path, map_location=device, weights_only=False) except TypeError: checkpoint = torch.load(path, map_location=device) if not isinstance(checkpoint, dict) or "model_state_dict" not in checkpoint: raise ValueError(f"Unsupported checkpoint payload: {path}") return checkpoint
def rng_state() -> Dict[str, Any]: state: Dict[str, Any] = { "python": random.getstate(), "numpy": np.random.get_state(), "torch": torch.get_rng_state(), } if torch.cuda.is_available(): state["cuda"] = torch.cuda.get_rng_state_all() return state
def restore_rng_state(state: Optional[Mapping[str, Any]]) -> None: if not state: return random.setstate(state["python"]) np.random.set_state(state["numpy"]) torch.set_rng_state(state["torch"]) if torch.cuda.is_available() and "cuda" in state: torch.cuda.set_rng_state_all(state["cuda"])
def checkpoint_metadata_matches( checkpoint: Mapping[str, Any], config: Mapping[str, Any], target_min: np.ndarray, target_max: np.ndarray,) -> None: """Reject silent channel or normalization changes on resume.""" expected = { "source_channels": list(config["data"]["source_channels"]), "input_names": list(config["data"]["input_names"]), "target_names": list(config["data"]["target_names"]), } for key, value in expected.items(): if list(checkpoint.get(key, [])) != value: raise ValueError(f"Checkpoint {key} metadata does not match the configuration") if not np.allclose(np.asarray(checkpoint.get("target_min")), target_min, rtol=0, atol=0): raise ValueError("Checkpoint target_min differs from the current training split") if not np.allclose(np.asarray(checkpoint.get("target_max")), target_max, rtol=0, atol=0): raise ValueError("Checkpoint target_max differs from the current training split")
def selected_indices(indices: np.ndarray, maximum_cases: Optional[int]) -> np.ndarray: if maximum_cases is None: return indices if maximum_cases <= 0: raise ValueError("maximum_cases must be positive") return indices[: min(maximum_cases, indices.size)]
def prepare_datasets( config: Mapping[str, Any], project_root: Path, smoke_test: bool = False,) -> Tuple[Dict[str, PointCFDDataset], np.ndarray, np.ndarray, Dict[str, Path], Dict[str, int]]: """Build all split datasets under one normalization contract.""" data, splits, paths = load_data_and_splits(config, project_root) if smoke_test: active_splits = { "train": selected_indices(splits["train"], 4), "validation": selected_indices(splits["validation"], 2), "test": selected_indices(splits["test"], 2), } else: active_splits = splits target_indices = tuple(int(i) for i in config["data"]["target_indices"]) target_min, target_max = fit_target_minmax(data, active_splits["train"], target_indices) datasets = { name: PointCFDDataset( data, indices, config["data"]["input_indices"], target_indices, target_min, target_max, ) for name, indices in active_splits.items() } counts = {name: len(dataset) for name, dataset in datasets.items()} return datasets, target_min, target_max, paths, counts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206#!/usr/bin/env python3"""Evaluate a PointCFD checkpoint on the fixed test split."""
from __future__ import annotations
import argparseimport sysfrom pathlib import Pathfrom typing import Any, Dict
import numpy as npimport torch
PROJECT_ROOT = Path(__file__).resolve().parents[1]project_root_string = str(PROJECT_ROOT)if project_root_string in sys.path: sys.path.remove(project_root_string)sys.path.insert(0, project_root_string)
from models import PointNetCFD, count_trainable_parameters # noqa: E402from scripts.common import ( # noqa: E402 AVAILABLE_SAMPLE_COUNT, PAPER_SAMPLE_COUNT, PointCFDDataset, choose_device, configured_paths, evaluate_model, load_checkpoint, load_config, load_data_and_splits, make_loader, resolve_path, selected_indices, set_deterministic_seed, write_json, write_npz,)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--config", type=Path, default=PROJECT_ROOT / "config" / "config.yaml" ) parser.add_argument( "--checkpoint", type=Path, default=None, help="Checkpoint path (default: paths.checkpoint from config)", ) parser.add_argument("--device", default="auto", help="auto, cpu, cuda, or cuda:N") parser.add_argument("--batch-size", type=int, default=None) parser.add_argument("--num-workers", type=int, default=None) parser.add_argument( "--output-dir", type=Path, default=None, help="Output directory (default: paths.results_dir from config)", ) parser.add_argument( "--max-cases", type=int, default=None, help="Evaluate only the first N fixed test cases (smoke testing only)", ) return parser.parse_args()
def validate_checkpoint_contract(checkpoint: Dict[str, Any], config: Dict[str, Any]) -> None: expected_metadata = { "source_channels": list(config["data"]["source_channels"]), "input_names": list(config["data"]["input_names"]), "target_names": list(config["data"]["target_names"]), "input_indices": list(config["data"]["input_indices"]), "target_indices": list(config["data"]["target_indices"]), } for key, expected in expected_metadata.items(): if list(checkpoint.get(key, [])) != expected: raise ValueError(f"Checkpoint {key} metadata does not match config: {key}") target_min = np.asarray(checkpoint.get("target_min"), dtype=np.float32) target_max = np.asarray(checkpoint.get("target_max"), dtype=np.float32) if target_min.shape != (3,) or target_max.shape != (3,): raise ValueError("Checkpoint target normalization must contain three variables") if np.any(target_max <= target_min): raise ValueError("Checkpoint target normalization spans must be positive")
def main() -> None: args = parse_args() config = load_config(args.config) seed = int(config["training"]["seed"]) set_deterministic_seed(seed) device = choose_device(args.device) paths = configured_paths(config, PROJECT_ROOT) checkpoint_path = ( resolve_path(PROJECT_ROOT, str(args.checkpoint)) if args.checkpoint is not None else paths["checkpoint"] ) output_dir = ( resolve_path(PROJECT_ROOT, str(args.output_dir)) if args.output_dir is not None else paths["results_dir"] )
checkpoint = load_checkpoint(checkpoint_path, device) validate_checkpoint_contract(checkpoint, config) checkpoint_model_config = checkpoint.get("model_config", config["model"]) model = PointNetCFD( input_dim=int(checkpoint_model_config["input_dim"]), output_dim=int(checkpoint_model_config["output_dim"]), ).to(device=device, dtype=torch.float32) model.load_state_dict(checkpoint["model_state_dict"], strict=True) print( f"checkpoint={checkpoint_path} epoch={checkpoint.get('epoch')} device={device} " f"trainable_parameters={count_trainable_parameters(model)}", flush=True, )
data, splits, _ = load_data_and_splits(config, PROJECT_ROOT) test_indices = selected_indices(splits["test"], args.max_cases) target_min = np.asarray(checkpoint["target_min"], dtype=np.float32) target_max = np.asarray(checkpoint["target_max"], dtype=np.float32) test_dataset = PointCFDDataset( data, test_indices, config["data"]["input_indices"], config["data"]["target_indices"], target_min, target_max, ) batch_size = int( args.batch_size if args.batch_size is not None else config["training"]["batch_size"] ) num_workers = int( args.num_workers if args.num_workers is not None else config["training"]["num_workers"] ) test_loader = make_loader( test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, seed=seed, pin_memory=device.type == "cuda", ) target_names = list(config["data"]["target_names"]) metrics, arrays = evaluate_model( model, test_loader, device, target_min, target_max, target_names, float(config["evaluation"]["relative_l2_epsilon"]), )
metrics_payload: Dict[str, Any] = { "checkpoint": str(checkpoint_path), "checkpoint_epoch": int(checkpoint.get("epoch", -1)), "device": str(device), "evaluated_test_cases": len(test_dataset), "fixed_test_split_cases": int(splits["test"].size), "available_sample_count": AVAILABLE_SAMPLE_COUNT, "paper_sample_count": PAPER_SAMPLE_COUNT, "metrics": metrics, "paper_reference_mean_relative_l2": config["evaluation"][ "paper_reference_mean_relative_l2" ], "dataset_limitation": ( "The supplied dataset has 2215 cases rather than the paper's 2595; " "these metrics are a best-available subset reproduction." ), } output_dir.mkdir(parents=True, exist_ok=True) metrics_path = output_dir / "test_metrics.json" predictions_path = output_dir / "predictions.npz" write_json(metrics_path, metrics_payload) write_npz( predictions_path, coordinates=arrays["coordinates"], predictions=arrays["predictions"], targets=arrays["targets"], case_indices=arrays["case_indices"], target_names=np.asarray(target_names), target_min=target_min, target_max=target_max, ) print( "normalized_mse={:.9e}".format(metrics["normalized_mse"]), flush=True ) for name in target_names: relative = metrics["relative_l2"][name] print( f"variable={name} rmse={metrics['rmse'][name]:.9e} " f"relative_l2_mean={relative['mean']:.9e} " f"relative_l2_max={relative['max']:.9e} " f"relative_l2_min={relative['min']:.9e}", flush=True, ) print(f"metrics={metrics_path}", flush=True) print(f"predictions={predictions_path}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147#!/usr/bin/env python3"""Render PointCFD ground truth, prediction, and absolute field errors."""
from __future__ import annotations
import argparseimport sysfrom pathlib import Pathfrom typing import Any, Dict, List
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as plt # noqa: E402import numpy as np # noqa: E402
PROJECT_ROOT = Path(__file__).resolve().parents[1]project_root_string = str(PROJECT_ROOT)if project_root_string in sys.path: sys.path.remove(project_root_string)sys.path.insert(0, project_root_string)
from scripts.common import resolve_path, write_json # noqa: E402
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--predictions", type=Path, default=PROJECT_ROOT / "results" / "predictions.npz", ) parser.add_argument( "--output-dir", type=Path, default=PROJECT_ROOT / "results" / "figures", ) parser.add_argument("--num-cases", type=int, default=3) parser.add_argument("--case-offset", type=int, default=0) return parser.parse_args()
def main() -> None: args = parse_args() predictions_path = resolve_path(PROJECT_ROOT, str(args.predictions)) output_dir = resolve_path(PROJECT_ROOT, str(args.output_dir)) if not predictions_path.is_file(): raise FileNotFoundError(f"Prediction archive not found: {predictions_path}") if args.num_cases <= 0: raise ValueError("num-cases must be positive") if args.case_offset < 0: raise ValueError("case-offset cannot be negative")
with np.load(predictions_path, allow_pickle=False) as archive: required = {"coordinates", "predictions", "targets", "case_indices", "target_names"} missing = required - set(archive.files) if missing: raise ValueError(f"Prediction archive is missing keys: {sorted(missing)}") coordinates = np.asarray(archive["coordinates"], dtype=np.float32) predictions = np.asarray(archive["predictions"], dtype=np.float32) targets = np.asarray(archive["targets"], dtype=np.float32) case_indices = np.asarray(archive["case_indices"], dtype=np.int64) target_names = [str(name) for name in archive["target_names"].tolist()] if coordinates.ndim != 3 or coordinates.shape[-1] != 2: raise ValueError(f"coordinates must be [cases,points,2], got {coordinates.shape}") if predictions.shape != targets.shape or predictions.ndim != 3: raise ValueError("predictions and targets must share [cases,points,variables]") if coordinates.shape[:2] != predictions.shape[:2]: raise ValueError("Coordinate and field case/point dimensions do not match") if predictions.shape[-1] != len(target_names): raise ValueError("target_names does not match prediction channels") if not (np.isfinite(coordinates).all() and np.isfinite(predictions).all() and np.isfinite(targets).all()): raise ValueError("Visualization inputs contain NaN or Infinity")
stop = min(args.case_offset + args.num_cases, coordinates.shape[0]) if args.case_offset >= stop: raise ValueError("case-offset is beyond the available predictions") output_dir.mkdir(parents=True, exist_ok=True) generated: List[str] = [] case_summaries: List[Dict[str, Any]] = [] for local_index in range(args.case_offset, stop): xy = coordinates[local_index] case_prediction = predictions[local_index] case_target = targets[local_index] absolute_error = np.abs(case_prediction - case_target) rows = len(target_names) figure, axes = plt.subplots(rows, 3, figsize=(13.5, 4.1 * rows), squeeze=False) variable_summary: Dict[str, Any] = {} for channel, name in enumerate(target_names): lower = float(min(case_target[:, channel].min(), case_prediction[:, channel].min())) upper = float(max(case_target[:, channel].max(), case_prediction[:, channel].max())) if upper <= lower: upper = lower + 1.0e-12 panels = ( (case_target[:, channel], "Ground truth", lower, upper, "viridis"), (case_prediction[:, channel], "Prediction", lower, upper, "viridis"), (absolute_error[:, channel], "Absolute error", 0.0, None, "magma"), ) for column, (values, title, vmin, vmax, color_map) in enumerate(panels): axis = axes[channel, column] scatter = axis.scatter( xy[:, 0], xy[:, 1], c=values, s=8, marker="o", linewidths=0, cmap=color_map, vmin=vmin, vmax=vmax, ) axis.set_aspect("equal", adjustable="box") axis.set_xlabel("x") axis.set_ylabel("y") axis.set_title(f"{name}: {title}") figure.colorbar(scatter, ax=axis, fraction=0.046, pad=0.04) variable_summary[name] = { "mean_absolute_error": float(np.mean(absolute_error[:, channel])), "max_absolute_error": float(np.max(absolute_error[:, channel])), } case_index = int(case_indices[local_index]) figure.suptitle(f"PointCFD fixed test case {case_index}") figure.tight_layout() output_path = output_dir / f"case_{case_index:04d}_fields.png" figure.savefig(output_path, dpi=180, bbox_inches="tight") plt.close(figure) generated.append(str(output_path)) case_summaries.append({"case_index": case_index, "variables": variable_summary}) print(f"figure={output_path}", flush=True)
summary = { "predictions": str(predictions_path), "visualization_method": ( "direct point scatter without triangulation or interpolation because mesh topology " "and obstacle boundaries are not provided" ), "generated_files": generated, "cases": case_summaries, } summary_path = output_dir / "visualization_summary.json" write_json(summary_path, summary) print(f"visualization_summary={summary_path}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323#!/usr/bin/env python3"""Train the paper-faithful PointCFD main experiment."""
from __future__ import annotations
import argparseimport copyimport sysimport timefrom pathlib import Pathfrom typing import Any, Dict, Optional
import numpy as npimport torchimport yamlfrom torch import nn
PROJECT_ROOT = Path(__file__).resolve().parents[1]project_root_string = str(PROJECT_ROOT)if project_root_string in sys.path: sys.path.remove(project_root_string)sys.path.insert(0, project_root_string)
from models import PointNetCFD, count_trainable_parameters # noqa: E402from scripts.common import ( # noqa: E402 AVAILABLE_SAMPLE_COUNT, PAPER_SAMPLE_COUNT, append_jsonl, checkpoint_metadata_matches, choose_device, configured_paths, evaluate_model, load_checkpoint, load_config, make_loader, prepare_datasets, resolve_path, restore_rng_state, rng_state, save_checkpoint, set_deterministic_seed, write_json,)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--config", type=Path, default=PROJECT_ROOT / "config" / "config.yaml", help="Experiment YAML (default: project config/config.yaml)", ) parser.add_argument("--device", default="auto", help="auto, cpu, cuda, or cuda:N") parser.add_argument("--epochs", type=int, default=None, help="Override configured epochs") parser.add_argument( "--batch-size", type=int, default=None, help="Override configured batch size" ) parser.add_argument( "--num-workers", type=int, default=None, help="Override DataLoader workers" ) parser.add_argument("--seed", type=int, default=None, help="Override configured seed") parser.add_argument( "--resume", type=Path, default=None, help="Resume model, optimizer, epoch, metrics, and RNG state", ) parser.add_argument( "--smoke-test", action="store_true", help="Use tiny fixed splits and isolated smoke output paths", ) return parser.parse_args()
def build_effective_config(config: Dict[str, Any], args: argparse.Namespace) -> Dict[str, Any]: effective = copy.deepcopy(config) training = effective["training"] if args.epochs is not None: training["epochs"] = args.epochs elif args.smoke_test: training["epochs"] = 1 if args.batch_size is not None: training["batch_size"] = args.batch_size elif args.smoke_test: training["batch_size"] = 2 if args.num_workers is not None: training["num_workers"] = args.num_workers if args.seed is not None: training["seed"] = args.seed if int(training["epochs"]) <= 0: raise ValueError("epochs must be positive") if int(training["batch_size"]) <= 0: raise ValueError("batch_size must be positive") if int(training["num_workers"]) < 0: raise ValueError("num_workers cannot be negative") if int(training["validation_interval"]) != 1: raise ValueError("The paper validates after every epoch") if str(training["optimizer"]).lower() != "adam": raise ValueError("The paper uses Adam") if str(training["precision"]).lower() != "float32": raise ValueError("This reproduction uses the paper-compatible float32 path") return effective
def metric_line(metrics: Dict[str, Any]) -> str: rmse = metrics["rmse"] relative = metrics["relative_l2"] return ( f"val_mse={metrics['normalized_mse']:.9e} " f"rmse_u={rmse['u']:.9e} rmse_v={rmse['v']:.9e} rmse_p={rmse['p']:.9e} " f"rel_l2_u={relative['u']['mean']:.9e} " f"rel_l2_v={relative['v']['mean']:.9e} " f"rel_l2_p={relative['p']['mean']:.9e}" )
def main() -> None: args = parse_args() base_config = load_config(args.config) config = build_effective_config(base_config, args) training = config["training"] seed = int(training["seed"]) set_deterministic_seed(seed) device = choose_device(args.device)
datasets, target_min, target_max, resolved_paths, split_counts = prepare_datasets( config, PROJECT_ROOT, smoke_test=args.smoke_test ) batch_size = int(training["batch_size"]) num_workers = int(training["num_workers"]) pin_memory = device.type == "cuda" train_loader = make_loader( datasets["train"], batch_size, True, num_workers, seed, pin_memory ) validation_loader = make_loader( datasets["validation"], batch_size, False, num_workers, seed, pin_memory )
model = PointNetCFD( input_dim=int(config["model"]["input_dim"]), output_dim=int(config["model"]["output_dim"]), ).to(device=device, dtype=torch.float32) parameter_count = count_trainable_parameters(model) paper_parameter_count = int(config["model"]["expected_paper_parameters"]) print( f"device={device} trainable_parameters={parameter_count} " f"paper_reference_parameters={paper_parameter_count}", flush=True, ) optimizer = torch.optim.Adam( model.parameters(), lr=float(training["learning_rate"]), betas=(float(training["beta1"]), float(training["beta2"])), eps=float(training["epsilon"]), weight_decay=float(training["weight_decay"]), ) criterion = nn.MSELoss(reduction="mean")
if args.smoke_test: checkpoint_path = PROJECT_ROOT / "weight" / "smoke_best_model.pth" results_dir = PROJECT_ROOT / "results" / "smoke" else: checkpoint_path = resolved_paths["checkpoint"] results_dir = resolved_paths["results_dir"] results_dir.mkdir(parents=True, exist_ok=True) checkpoint_path.parent.mkdir(parents=True, exist_ok=True) history_path = results_dir / "train_history.jsonl" if args.resume is None and history_path.exists(): history_path.unlink()
effective_config_path = results_dir / "effective_config.yaml" with effective_config_path.open("w", encoding="utf-8") as handle: yaml.safe_dump(config, handle, sort_keys=False)
start_epoch = 1 best_validation_mse = float("inf") if args.resume is not None: resume_path = resolve_path(PROJECT_ROOT, str(args.resume)) checkpoint = load_checkpoint(resume_path, device) checkpoint_metadata_matches(checkpoint, config, target_min, target_max) model.load_state_dict(checkpoint["model_state_dict"], strict=True) optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) start_epoch = int(checkpoint["epoch"]) + 1 best_validation_mse = float(checkpoint["best_validation_mse"]) restore_rng_state(checkpoint.get("rng_state")) if checkpoint.get("train_loader_generator_state") is not None: train_loader.generator.set_state(checkpoint["train_loader_generator_state"]) print( f"resumed_from={resume_path} start_epoch={start_epoch} " f"best_val_mse={best_validation_mse:.9e}", flush=True, )
final_epoch = int(training["epochs"]) if start_epoch > final_epoch: raise ValueError( f"Resume checkpoint epoch {start_epoch - 1} already reaches requested epoch {final_epoch}" ) target_names = list(config["data"]["target_names"]) relative_l2_epsilon = float(config["evaluation"]["relative_l2_epsilon"]) log_every = int(training["log_every_batches"]) if log_every <= 0: raise ValueError("log_every_batches must be positive")
run_started = time.time() for epoch in range(start_epoch, final_epoch + 1): epoch_started = time.time() model.train() squared_error_sum = 0.0 element_count = 0 for batch_number, (coordinates, targets, _) in enumerate(train_loader, start=1): coordinates = coordinates.to(device, non_blocking=True) targets = targets.to(device, non_blocking=True) optimizer.zero_grad(set_to_none=True) predictions = model(coordinates) loss = criterion(predictions, targets) loss.backward() optimizer.step()
batch_elements = targets.numel() squared_error_sum += float(loss.detach().item()) * batch_elements element_count += batch_elements if batch_number % log_every == 0 or batch_number == len(train_loader): print( f"epoch={epoch}/{final_epoch} " f"batch={batch_number}/{len(train_loader)} " f"train_loss={loss.detach().item():.9e}", flush=True, ) train_mse = squared_error_sum / element_count
validation_metrics, _ = evaluate_model( model, validation_loader, device, target_min, target_max, target_names, relative_l2_epsilon, ) validation_mse = float(validation_metrics["normalized_mse"]) elapsed = time.time() - epoch_started print( f"epoch={epoch}/{final_epoch} train_mse={train_mse:.9e} " f"{metric_line(validation_metrics)} epoch_seconds={elapsed:.3f}", flush=True, )
history_record = { "epoch": epoch, "train_mse": train_mse, "validation": validation_metrics, "epoch_seconds": elapsed, "learning_rate": float(optimizer.param_groups[0]["lr"]), "seed": seed, "smoke_test": bool(args.smoke_test), } append_jsonl(history_path, history_record)
if validation_mse < best_validation_mse: best_validation_mse = validation_mse checkpoint_payload: Dict[str, Any] = { "format_version": "pointcfd-checkpoint-v1", "epoch": epoch, "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict(), "best_validation_mse": best_validation_mse, "target_min": target_min, "target_max": target_max, "source_channels": list(config["data"]["source_channels"]), "input_names": list(config["data"]["input_names"]), "target_names": target_names, "input_indices": list(config["data"]["input_indices"]), "target_indices": list(config["data"]["target_indices"]), "model_config": copy.deepcopy(config["model"]), "training_config": copy.deepcopy(training), "data_paths": {key: str(value) for key, value in resolved_paths.items()}, "split_counts": split_counts, "seed": seed, "available_sample_count": AVAILABLE_SAMPLE_COUNT, "paper_sample_count": PAPER_SAMPLE_COUNT, "trainable_parameters": parameter_count, "rng_state": rng_state(), "train_loader_generator_state": train_loader.generator.get_state(), "smoke_test": bool(args.smoke_test), } save_checkpoint(checkpoint_path, checkpoint_payload) print( f"saved_best_checkpoint={checkpoint_path} " f"best_val_mse={best_validation_mse:.9e}", flush=True, )
summary = { "status": "completed", "start_epoch": start_epoch, "final_epoch": final_epoch, "best_validation_mse": best_validation_mse, "checkpoint": str(checkpoint_path), "history": str(history_path), "effective_config": str(effective_config_path), "trainable_parameters": parameter_count, "paper_reference_parameters": paper_parameter_count, "split_counts": split_counts, "available_sample_count": AVAILABLE_SAMPLE_COUNT, "paper_sample_count": PAPER_SAMPLE_COUNT, "dataset_limitation": ( "The supplied dataset has 2215 cases rather than the paper's 2595; " "this is a best-available subset reproduction." ), "elapsed_seconds": time.time() - run_started, "device": str(device), "smoke_test": bool(args.smoke_test), } write_json(results_dir / "training_summary.json", summary) print(f"training_complete summary={results_dir / 'training_summary.json'}", flush=True)
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:ba4d2d0903db703a91eca1b6542bfb336a01af21ed30bec55e645132ce50461dsize 42808802README.mdAdded+153
config/config.yamlAdded+56
models/PointNetCFD.pyAdded+146
models/__init__.pyAdded+5
models/__pycache__/PointNetCFD.cpython-310.pycAdded
models/__pycache__/PointNetCFD.cpython-311.pycAdded
models/__pycache__/__init__.cpython-310.pycAdded
models/__pycache__/__init__.cpython-311.pycAdded
scripts/__init__.pyAdded+1
scripts/__pycache__/__init__.cpython-311.pycAdded
scripts/__pycache__/common.cpython-310.pycAdded
scripts/__pycache__/common.cpython-311.pycAdded
scripts/__pycache__/inference.cpython-310.pycAdded
scripts/__pycache__/inference.cpython-311.pycAdded
scripts/__pycache__/result.cpython-310.pycAdded
scripts/__pycache__/result.cpython-311.pycAdded
scripts/__pycache__/train.cpython-310.pycAdded
scripts/__pycache__/train.cpython-311.pycAdded
scripts/common.pyAdded+492
scripts/inference.pyAdded+206
scripts/result.pyAdded+147
scripts/train.pyAdded+323
weight/best_model.pthAdded+3