weights, code, eval script
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +14 -0
- LICENSE +27 -0
- README.md +89 -0
- code/ezflow_v3/__init__.py +1 -0
- code/ezflow_v3/__pycache__/__init__.cpython-310.pyc +0 -0
- code/ezflow_v3/app/README.md +152 -0
- code/ezflow_v3/app/__init__.py +0 -0
- code/ezflow_v3/app/frontend/app.js +1058 -0
- code/ezflow_v3/app/frontend/index.html +370 -0
- code/ezflow_v3/app/frontend/style.css +673 -0
- code/ezflow_v3/app/frontend/vendor/OrbitControls.js +1045 -0
- code/ezflow_v3/app/frontend/vendor/three.min.js +0 -0
- code/ezflow_v3/app/infer_app.py +223 -0
- code/ezflow_v3/app/premesh.py +250 -0
- code/ezflow_v3/app/run_app.py +33 -0
- code/ezflow_v3/app/serve.py +342 -0
- code/ezflow_v3/app/shape_generator.py +34 -0
- code/ezflow_v3/baselines/README.md +38 -0
- code/ezflow_v3/baselines/Transolver-main/.gitignore +160 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/LICENSE +540 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/README.md +89 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/dataset/dataset.py +245 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/dataset/dataset_stats.ipynb +103 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/fig/results.png +3 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/fig/task.png +3 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/main.py +114 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/main_evaluation.py +75 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/GUNet.py +221 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/GraphSAGE.py +58 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/MLP.py +62 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/NN.py +25 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/PointNet.py +45 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/Transolver.py +210 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/params.yaml +63 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/requirements.txt +8 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/scripts/Evaluation.sh +3 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/scripts/GraphSAGE.sh +3 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/scripts/Transolver.sh +3 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/train.py +343 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/metrics.py +447 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/metrics_NACA.py +221 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/naca_generator.py +112 -0
- code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/reorganize.py +14 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/README.md +100 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/dataset/dataset.py +408 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/dataset/load_dataset.py +56 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/car_slice_surf.png +3 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/case_study.png +3 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/results.png +3 -0
- code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/task.png +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,17 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/fig/results.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/fig/task.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/car_slice_surf.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/case_study.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/results.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/task.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
code/ezflow_v3/baselines/Transolver-main/PDE-Solving-StandardBenchmark/fig/scalibility.png filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
code/ezflow_v3/baselines/Transolver-main/PDE-Solving-StandardBenchmark/fig/showcase.png filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
code/ezflow_v3/baselines/Transolver-main/PDE-Solving-StandardBenchmark/fig/standard_benchmark.png filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
code/ezflow_v3/baselines/Transolver-main/pic/physical_states.png filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
code/ezflow_v3/baselines/Transolver-main/pic/showcases.png filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
code/ezflow_v3/baselines/Transolver-main/pic/Transolver.png filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
code/ezflow_v3/baselines/Transolver_plus-main/figs/main_table.png filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
code/ezflow_v3/baselines/Transolver_plus-main/figs/standard_benchmarks.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2026 The Anonymous Authors
|
| 2 |
+
(identity withheld for double blind review; this notice will be updated with the
|
| 3 |
+
copyright holder upon publication)
|
| 4 |
+
|
| 5 |
+
This release contains three kinds of material under two licenses:
|
| 6 |
+
|
| 7 |
+
1. MODEL WEIGHTS (weights/) and DATA (companion dataset repository):
|
| 8 |
+
Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).
|
| 9 |
+
Full text: https://creativecommons.org/licenses/by-nc/4.0/legalcode
|
| 10 |
+
You may share and adapt for non-commercial purposes with attribution.
|
| 11 |
+
|
| 12 |
+
2. CODE (code/, easy_eval.py):
|
| 13 |
+
PolyForm Noncommercial License 1.0.0.
|
| 14 |
+
Full text: https://polyformproject.org/licenses/noncommercial/1.0.0/
|
| 15 |
+
Use permitted for any noncommercial purpose. Commercial use requires a
|
| 16 |
+
separate written agreement with the copyright holder.
|
| 17 |
+
|
| 18 |
+
3. VENDORED THIRD PARTY CODE (code/ezflow_v3/baselines/ and
|
| 19 |
+
code/ezflow_v3/app/frontend/vendor/): retains the original authors'
|
| 20 |
+
licenses and copyrights as stated in those files. It is included solely
|
| 21 |
+
to reproduce the paper's baselines and interface.
|
| 22 |
+
|
| 23 |
+
THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 24 |
+
IMPLIED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM,
|
| 25 |
+
DAMAGES, OR OTHER LIABILITY ARISING FROM THE USE OF THE MATERIALS. CFD-trained
|
| 26 |
+
surrogate predictions are approximations; do not use them as the sole basis
|
| 27 |
+
for safety critical engineering decisions.
|
README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
tags:
|
| 4 |
+
- physics
|
| 5 |
+
- computational-fluid-dynamics
|
| 6 |
+
- graph-neural-networks
|
| 7 |
+
- surrogate-model
|
| 8 |
+
- rans
|
| 9 |
+
library_name: pytorch
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Steady-RANS flow field surrogates (GeoReNet and HybridFlow)
|
| 13 |
+
|
| 14 |
+
Trained checkpoints and code for the paper *"Towards generalized flow field prediction: one
|
| 15 |
+
model across unseen object families"* (under double blind review; this account is anonymous
|
| 16 |
+
for that reason).
|
| 17 |
+
|
| 18 |
+
Given a 3D geometry and an operating point (Reynolds number and yaw angle), each model
|
| 19 |
+
predicts the full steady RANS field, velocity `(u, v, w)`, pressure `p`, and turbulence
|
| 20 |
+
variables `(k, omega, nu_t)`, at every node of a sampled graph covering the flow volume, in a
|
| 21 |
+
single forward pass with no solver in the loop. Training and evaluation data are in the
|
| 22 |
+
companion dataset repo:
|
| 23 |
+
[steady-rans-generalization](https://huggingface.co/datasets/BlidReview/steady-rans-generalization).
|
| 24 |
+
|
| 25 |
+
## Checkpoints (`weights/<run>/model.pt` + `norms.npz`)
|
| 26 |
+
|
| 27 |
+
| Run | Architecture | Params | Note |
|
| 28 |
+
|---|---|--:|---|
|
| 29 |
+
| `geore_fieldonly_s0/s1/s2` | GeoReNet (local MP + pooled global node + FiLM) | 3.28M | ours, 3 seeds |
|
| 30 |
+
| `hybrid_s0/s1/s2` | HybridFlow (local MP + slice attention + FiLM) | 3.04M | ours, 3 seeds |
|
| 31 |
+
| `tpp_s0/s1/s2` | Transolver++ (pure attention baseline) | 3.37M | baseline, 3 seeds |
|
| 32 |
+
| `pfaff_s0/s1/s2` | MeshGraphNet (local MP baseline) | 2.94M | baseline, 3 seeds |
|
| 33 |
+
| `hybrid_nolocal_s0` | HybridFlow without local operator | 0.98M | ablation |
|
| 34 |
+
| `hybrid_nolocal_h300_s0` | Same, capacity matched (hidden 300) | 3.07M | ablation |
|
| 35 |
+
| `geore_noglobal_s0` | GeoReNet without global node, capacity matched | 3.26M | ablation |
|
| 36 |
+
|
| 37 |
+
Headline mean field R2 (seed 0, fixed deterministic splits):
|
| 38 |
+
|
| 39 |
+
| Model | val | OOD object | OOD Reynolds |
|
| 40 |
+
|---|--:|--:|--:|
|
| 41 |
+
| MeshGraphNet | 0.963 | 0.865 | 0.939 |
|
| 42 |
+
| GeoReNet (ours) | 0.969 | **0.888** | 0.946 |
|
| 43 |
+
| Transolver++ | 0.970 | 0.835 | 0.939 |
|
| 44 |
+
| HybridFlow (ours) | **0.972** | 0.880 | **0.948** |
|
| 45 |
+
|
| 46 |
+
## Install
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
# 1) PyTorch first, pinned; do not let later installs upgrade it
|
| 50 |
+
pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cu128 --no-deps
|
| 51 |
+
# CPU-only: pip install torch==2.11.0
|
| 52 |
+
# 2) PyTorch Geometric
|
| 53 |
+
pip install torch_geometric==2.8.0 --no-deps
|
| 54 |
+
# 3) everything else
|
| 55 |
+
pip install -r requirements.txt
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
## Reproduce the fixed split table
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
huggingface-cli download BlidReview/steady-rans-surrogates --local-dir .
|
| 62 |
+
huggingface-cli download BlidReview/steady-rans-generalization --local-dir ./data --repo-type dataset
|
| 63 |
+
python easy_eval.py --cache ./data/cache_v3 --weights ./weights --device cuda
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
`easy_eval.py` rebuilds each architecture from its stored args, evaluates the deterministic
|
| 67 |
+
val / OOD object / OOD Reynolds splits, and prints the table above (per channel R2 included).
|
| 68 |
+
Single runs: `python code/ezflow_v3/gnn/eval_run.py --run weights/hybrid_s0 --cache ./data/cache_v3`.
|
| 69 |
+
|
| 70 |
+
Zero shot external families: `code/ezflow_v3/gnn/zeroshot_eval.py` with
|
| 71 |
+
`data/ext_dataset_of` from the dataset repo.
|
| 72 |
+
|
| 73 |
+
## Predict on a new geometry
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
python code/ezflow_v3/app/run_app.py # web app: upload an STL, set Re and yaw, inspect fields
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## Scope
|
| 80 |
+
|
| 81 |
+
Steady, incompressible, single phase Newtonian external flow at Reynolds numbers between
|
| 82 |
+
500 and 1e5 (k-omega SST ground truth). Full scale automotive and flight conditions lie
|
| 83 |
+
above this range. Predictions are on a sampled graph of about 10^4 nodes. See the paper for
|
| 84 |
+
limits and the applicability domain score.
|
| 85 |
+
|
| 86 |
+
## License
|
| 87 |
+
|
| 88 |
+
Weights and data: CC BY-NC 4.0. Code: PolyForm Noncommercial 1.0.0. See `LICENSE`.
|
| 89 |
+
Vendored baseline code in `code/ezflow_v3/baselines/` retains its original authors' licenses.
|
code/ezflow_v3/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
code/ezflow_v3/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (163 Bytes). View file
|
|
|
code/ezflow_v3/app/README.md
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ezflow_v2/app — interactive web app (turbulent-RANS GNN predictor)
|
| 2 |
+
|
| 3 |
+
A self-contained FastAPI + Three.js app that predicts steady turbulent-RANS flow
|
| 4 |
+
fields around a body **in milliseconds** with a choice of surrogate models, an
|
| 5 |
+
interactive 3D viewer, slice planes, and a point-probe tool.
|
| 6 |
+
|
| 7 |
+
> Self-contained under `ezflow_v2/`; **separate from the v1 app** (`app/`, port 8000)
|
| 8 |
+
> per the v1/v2 separation rule. The v2 app runs on **port 8001**.
|
| 9 |
+
|
| 10 |
+
```bash
|
| 11 |
+
python ezflow_v2/app/run_app.py # -> http://127.0.0.1:8001 (opens a browser)
|
| 12 |
+
```
|
| 13 |
+
First prediction lazily loads the model(s) (the ensemble loads all three, ~10–20 s);
|
| 14 |
+
every prediction after that runs in milliseconds. Requires the trained runs under
|
| 15 |
+
`ezflow_v2/gnn/_runs/` (rans_v5, hybrid, transolver) and the v2 env (torch
|
| 16 |
+
2.11+cu128, gmsh, trimesh, pyvista, fastapi, uvicorn).
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
## What it does (pipeline)
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
geometry (procedural shape OR uploaded STL)
|
| 24 |
+
│
|
| 25 |
+
├─ premesh: normalize to L=1 → surface (true geometry if watertight, else
|
| 26 |
+
│ voxel envelope) → graded tet mesh (fine near body)
|
| 27 |
+
│
|
| 28 |
+
├─ graph: nodes = mesh points; features = geometry + (Re, yaw) ONLY
|
| 29 |
+
│ (same features.py as training — no solved field is ever an input)
|
| 30 |
+
│
|
| 31 |
+
├─ model: GeoReNet / HybridFlow / Transolver / mean(G,T,H) ensemble
|
| 32 |
+
│
|
| 33 |
+
└─ outputs: per-node u, v, w, p, k, ω, ν_t → 3D viewer + slice planes + probe
|
| 34 |
+
```
|
| 35 |
+
**No CFD is run for a prediction.** Inputs are the shape and the operating condition
|
| 36 |
+
(`Re`, yaw) only; OpenFOAM is used solely offline to train the models.
|
| 37 |
+
|
| 38 |
+
---
|
| 39 |
+
|
| 40 |
+
## Controls & features
|
| 41 |
+
|
| 42 |
+
### Surrogate Model (dropdown)
|
| 43 |
+
| Option | Backed by run | Params |
|
| 44 |
+
|---|---|--:|
|
| 45 |
+
| **mean(G,T,H) ensemble** (default) | average of the three below | ~10.2M |
|
| 46 |
+
| HybridFlow | `_runs/hybrid` | 3.04M |
|
| 47 |
+
| GeoReNet | `_runs/rans_v5` | 3.28M |
|
| 48 |
+
| Transolver | `_runs/transolver` | 3.88M |
|
| 49 |
+
|
| 50 |
+
The ensemble averages the three models per node (in the transformed target space).
|
| 51 |
+
To add GINO: append `"GINO": ["gino"]` to `MODELS` in `infer_app.py`.
|
| 52 |
+
|
| 53 |
+
### Mesh Resolution (dropdown) — the premesher
|
| 54 |
+
| Preset | Surface | Near-body size | Typical nodes | Use |
|
| 55 |
+
|---|---|--:|--:|---|
|
| 56 |
+
| Coarse | voxel envelope (vox 64) | h≈0.12 | ~3k | fastest, smoothed |
|
| 57 |
+
| **Medium** (default) | **true geometry** (watertight) | h≈0.045 | ~10k | detail + training density |
|
| 58 |
+
| Fine | true geometry | h≈0.022 | ~25k+ | most detail (slower) |
|
| 59 |
+
|
| 60 |
+
- **Watertight, genus-0 uploads keep their true surface** (mirrors/edges survive) and
|
| 61 |
+
are meshed with curvature-aware near-body refinement.
|
| 62 |
+
- **Non-watertight / complex bodies** (e.g. DrivAer: open underbody, wheel wells) can't
|
| 63 |
+
be parametrized into a clean external-flow solid, so they **auto-fall-back** to a
|
| 64 |
+
robust voxel **envelope** (smooth shell) at the requested volume density. This is
|
| 65 |
+
automatic — a complex STL will predict (as an envelope) rather than error.
|
| 66 |
+
- Medium ≈ the ~10k-node density the models were trained on (the sweet spot).
|
| 67 |
+
|
| 68 |
+
### Geometry input
|
| 69 |
+
- **Simple Shape** tab: cylinder / sphere / box / capsule / cone / torus (sliders).
|
| 70 |
+
- **Upload STL** tab: drag-and-drop or browse any `.stl` (auto-normalized to L=1).
|
| 71 |
+
Test geometries live in `C:\dev\ezflow_eval\test_stls\`.
|
| 72 |
+
|
| 73 |
+
### Physics
|
| 74 |
+
Inlet speed, viscosity, density sliders → **Reynolds number** (the only physical knob,
|
| 75 |
+
`Re = ρ U∞ L / μ`), plus a **yaw** slider. Models were trained on **Re ≈ 5×10²–1×10⁵**;
|
| 76 |
+
predictions far outside that range are extrapolation.
|
| 77 |
+
|
| 78 |
+
### Visualize Field (slice viewer)
|
| 79 |
+
All seven outputs are selectable: **|U|, u, v, w, p, k, ω, ν_t**. A slice plane (X/Y/Z
|
| 80 |
+
axis + position slider) is colored by the chosen field; optional flow vectors on the slice.
|
| 81 |
+
Color map is **green (low) → gold → red (high)**; the legend shows the range and a
|
| 82 |
+
non-dimensional unit label.
|
| 83 |
+
|
| 84 |
+
### Mouse controls
|
| 85 |
+
- **Left-drag** — rotate
|
| 86 |
+
- **Mouse-wheel scroll** — zoom
|
| 87 |
+
- **Wheel-press (middle) drag** — pan
|
| 88 |
+
- **Single left-click** — set the rotation pivot at that point **and** probe values there
|
| 89 |
+
|
| 90 |
+
### Point Query (probe)
|
| 91 |
+
Click any point in the 3D view → the sidebar shows the predicted **x,y,z and all field
|
| 92 |
+
values** (|U|, u, v, w, p, k, ω, ν_t) at the nearest node (`/api/probe`).
|
| 93 |
+
|
| 94 |
+
### Display & View (right sidebar)
|
| 95 |
+
Body style (glass / wireframe / hidden), wind-tunnel box, slice grid lines, flow vectors,
|
| 96 |
+
and view presets (3D / Side / Top / Front).
|
| 97 |
+
|
| 98 |
+
---
|
| 99 |
+
|
| 100 |
+
## HTTP API
|
| 101 |
+
|
| 102 |
+
| Endpoint | Method | Purpose |
|
| 103 |
+
|---|---|---|
|
| 104 |
+
| `/` | GET | the app page |
|
| 105 |
+
| `/api/models` | GET | `{models, default}` |
|
| 106 |
+
| `/api/predict` | POST (form) | `shape_type, model_name, resolution, Re, yaw_deg`, shape params or `file`; returns coords, wall_tris, per-field `ranges`, `geom_meta` (incl. surface `method`/`n_faces`), `mesh_meta` (incl. `resolution`, `n_nodes_approx`), `model {name, params_m, members}`, bounds |
|
| 107 |
+
| `/api/slice` | POST (json) | `{normal_axis, position, field_type}` → slice `points/faces/scalars/vectors` |
|
| 108 |
+
| `/api/probe` | POST (json) | `{x, y, z}` → nearest-node `{point, values{...}, velocity_vec}` |
|
| 109 |
+
|
| 110 |
+
All responses are sent with `Cache-Control: no-store` so the browser always loads the
|
| 111 |
+
latest build (static assets are also versioned, `?v=N`).
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
## Files
|
| 116 |
+
- `run_app.py` — launcher (port 8001).
|
| 117 |
+
- `serve.py` — FastAPI: endpoints above, no-cache middleware, caches the current
|
| 118 |
+
`pyvista` grid for slicing/probing.
|
| 119 |
+
- `infer_app.py` — model loading (architecture rebuilt per checkpoint) + uniform
|
| 120 |
+
ensemble; `mesh_stl()` (premesh + read) with the auto-fallback; `predict_fields()`
|
| 121 |
+
(predicts on the **full mesh** — the models are mesh-density-robust — and returns
|
| 122 |
+
physical fields via `features.inverse_targets`).
|
| 123 |
+
- `premesh.py` — detail-preserving premesher: `prepare_surface()` (true geometry vs
|
| 124 |
+
voxel envelope) + `build_volume()` (graded, curvature-aware gmsh mesh); `PRESETS`.
|
| 125 |
+
- `shape_generator.py` — procedural watertight shapes (trimesh).
|
| 126 |
+
- `frontend/` — `index.html`, `app.js` (Three.js viewer, slicing, probe, colormap),
|
| 127 |
+
`style.css`.
|
| 128 |
+
|
| 129 |
+
Geometry meshing reuses the shared, geometry-neutral gmsh tooling in
|
| 130 |
+
`datasets/gen/shapenet/` (same as `infer_v5`); it carries no v1 physics.
|
| 131 |
+
|
| 132 |
+
---
|
| 133 |
+
|
| 134 |
+
## Caveats / limitations
|
| 135 |
+
- **Training fidelity:** the models were trained on the *smoothed envelope* geometries
|
| 136 |
+
(ModelNet shapes passed through the same voxel remesh). A high-detail mesh improves the
|
| 137 |
+
geometry/visualization and lets the model run on a faithful body, but the model **cannot
|
| 138 |
+
fully exploit fine features it never saw** (e.g. mirror wakes). True fine-detail
|
| 139 |
+
prediction on complex cars would need **retraining on high-fidelity geometry + CFD**.
|
| 140 |
+
- **Complex/dirty STLs** (open underbody, non-watertight) are served as a smooth envelope
|
| 141 |
+
(see Mesh Resolution). In-app gmsh can't make them a clean external-flow solid; the
|
| 142 |
+
CFD-grade route (snappyHexMesh) is out of scope for the interactive app.
|
| 143 |
+
- **Outputs are non-dimensional** (U∞ = 1, ρ = 1, L = 1); labels reflect this
|
| 144 |
+
(`p/ρU∞²`, `ν_t/ν`, …).
|
| 145 |
+
- **Out-of-distribution** geometry (e.g. ModelNet car/airplane, sharp finned bodies) and
|
| 146 |
+
Reynolds numbers outside ~5×10²–1×10⁵ are extrapolation — interpret with care.
|
| 147 |
+
|
| 148 |
+
## Troubleshooting
|
| 149 |
+
- **Page looks stale / controls unresponsive:** hard-refresh once (Ctrl+Shift+R) or open
|
| 150 |
+
an Incognito window. The server sends no-cache headers, so it stays fresh afterward.
|
| 151 |
+
- **An STL errors:** it should auto-fall-back to the envelope; if not, try Coarse
|
| 152 |
+
resolution (goes straight to the robust envelope).
|
code/ezflow_v3/app/__init__.py
ADDED
|
File without changes
|
code/ezflow_v3/app/frontend/app.js
ADDED
|
@@ -0,0 +1,1058 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// EZFlow Standalone Client-Side App Logic
|
| 2 |
+
|
| 3 |
+
// Global Application State
|
| 4 |
+
let scene, camera, renderer, controls;
|
| 5 |
+
let perspCamera = null, orthoCamera = null;
|
| 6 |
+
let slices = []; // extra movable slices: [{id, axis, pos, field, baseField, diffOn, mesh}]
|
| 7 |
+
let _sliceId = 0;
|
| 8 |
+
let inflowArrow = null;
|
| 9 |
+
let lastProbe = null;
|
| 10 |
+
let raycaster = null, _downXY = null;
|
| 11 |
+
let bodyMesh = null;
|
| 12 |
+
let sliceMesh = null;
|
| 13 |
+
let sliceGridMesh = null;
|
| 14 |
+
let sliceArrowsGroup = null;
|
| 15 |
+
let tunnelBox = null;
|
| 16 |
+
let currentGeomData = null; // cached coords, bounds, ranges
|
| 17 |
+
let activeTab = "tab-procedural";
|
| 18 |
+
let uploadedFile = null;
|
| 19 |
+
|
| 20 |
+
// --- UI feedback helpers (loading overlay + toast + screenshot) ---
|
| 21 |
+
function showOverlay(text) {
|
| 22 |
+
const o = document.getElementById("viewport-overlay");
|
| 23 |
+
const t = document.getElementById("viewport-overlay-text");
|
| 24 |
+
if (t) t.innerText = text || "Working...";
|
| 25 |
+
if (o) o.style.display = "flex";
|
| 26 |
+
}
|
| 27 |
+
function hideOverlay() {
|
| 28 |
+
const o = document.getElementById("viewport-overlay");
|
| 29 |
+
if (o) o.style.display = "none";
|
| 30 |
+
}
|
| 31 |
+
let _toastTimer = null;
|
| 32 |
+
function showToast(msg, isError) {
|
| 33 |
+
const el = document.getElementById("toast");
|
| 34 |
+
if (!el) { alert(msg); return; }
|
| 35 |
+
el.innerText = msg;
|
| 36 |
+
el.className = "toast" + (isError ? " toast-error" : "");
|
| 37 |
+
el.style.display = "block";
|
| 38 |
+
clearTimeout(_toastTimer);
|
| 39 |
+
_toastTimer = setTimeout(() => { el.style.display = "none"; }, isError ? 8000 : 4000);
|
| 40 |
+
}
|
| 41 |
+
function saveScreenshot() {
|
| 42 |
+
if (!renderer) return;
|
| 43 |
+
renderer.render(scene, camera); // ensure the current frame is in the buffer
|
| 44 |
+
const model = (currentGeomData && currentGeomData.model) ? currentGeomData.model.name : "view";
|
| 45 |
+
const a = document.createElement("a");
|
| 46 |
+
a.href = renderer.domElement.toDataURL("image/png");
|
| 47 |
+
a.download = "ezflow_" + model.replace(/[^a-z0-9]/gi, "_") + ".png";
|
| 48 |
+
document.body.appendChild(a); a.click(); document.body.removeChild(a);
|
| 49 |
+
}
|
| 50 |
+
function exportFields() {
|
| 51 |
+
if (!currentGeomData) { showToast("Run a prediction first.", true); return; }
|
| 52 |
+
window.location = "/api/export";
|
| 53 |
+
}
|
| 54 |
+
function setStatus(state, text) {
|
| 55 |
+
const dot = document.getElementById("status-dot");
|
| 56 |
+
const t = document.getElementById("status-text");
|
| 57 |
+
if (dot) dot.className = "status-indicator " + state; // online | running | error
|
| 58 |
+
if (t) t.innerText = text;
|
| 59 |
+
}
|
| 60 |
+
let probeMarker = null;
|
| 61 |
+
function placeProbeMarker(p) {
|
| 62 |
+
if (!probeMarker) {
|
| 63 |
+
probeMarker = new THREE.Mesh(
|
| 64 |
+
new THREE.SphereGeometry(0.04, 16, 16),
|
| 65 |
+
new THREE.MeshBasicMaterial({ color: 0x00f0ff })
|
| 66 |
+
);
|
| 67 |
+
scene.add(probeMarker);
|
| 68 |
+
}
|
| 69 |
+
probeMarker.position.copy(p);
|
| 70 |
+
probeMarker.visible = true;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// ---- orientation gizmo label (billboard sprite that always faces the camera) ----
|
| 74 |
+
function makeAxisLabel(text, color, pos) {
|
| 75 |
+
const canvas = document.createElement("canvas");
|
| 76 |
+
canvas.width = 64; canvas.height = 64;
|
| 77 |
+
const ctx = canvas.getContext("2d");
|
| 78 |
+
ctx.fillStyle = color; ctx.font = "bold 46px sans-serif";
|
| 79 |
+
ctx.textAlign = "center"; ctx.textBaseline = "middle";
|
| 80 |
+
ctx.fillText(text, 32, 34);
|
| 81 |
+
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
|
| 82 |
+
map: new THREE.CanvasTexture(canvas), depthTest: false, transparent: true
|
| 83 |
+
}));
|
| 84 |
+
sprite.position.copy(pos); sprite.scale.set(0.55, 0.55, 0.55);
|
| 85 |
+
scene.add(sprite);
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
// ---- multiple movable slices (each gets its own slider in the right panel) ----
|
| 89 |
+
async function fetchSliceData(axis, pos, field) {
|
| 90 |
+
const res = await fetch("/api/slice", {
|
| 91 |
+
method: "POST", headers: { "Content-Type": "application/json" },
|
| 92 |
+
body: JSON.stringify({ normal_axis: axis, position: pos, field_type: field })
|
| 93 |
+
});
|
| 94 |
+
if (!res.ok) throw new Error("slice failed");
|
| 95 |
+
return await res.json();
|
| 96 |
+
}
|
| 97 |
+
function buildSliceMesh(data, field) {
|
| 98 |
+
if (!data.points || !data.points.length) return null;
|
| 99 |
+
const range = (currentGeomData && currentGeomData.ranges[field]) || [0, 1];
|
| 100 |
+
const dom = fieldDomain(field, range);
|
| 101 |
+
const geom = new THREE.BufferGeometry();
|
| 102 |
+
geom.setAttribute("position", new THREE.BufferAttribute(new Float32Array(data.points.flat()), 3));
|
| 103 |
+
const colors = [];
|
| 104 |
+
for (let j = 0; j < data.scalars.length; j++) {
|
| 105 |
+
const c = colorFor(data.scalars[j], field, dom[0], dom[1]);
|
| 106 |
+
colors.push(c.r, c.g, c.b);
|
| 107 |
+
}
|
| 108 |
+
geom.setAttribute("color", new THREE.BufferAttribute(new Float32Array(colors), 3));
|
| 109 |
+
geom.setIndex(new THREE.BufferAttribute(new Uint32Array(data.faces.flat()), 1));
|
| 110 |
+
geom.computeVertexNormals();
|
| 111 |
+
return new THREE.Mesh(geom, new THREE.MeshBasicMaterial({ vertexColors: true, side: THREE.DoubleSide }));
|
| 112 |
+
}
|
| 113 |
+
async function addSlice() {
|
| 114 |
+
if (!currentGeomData) { showToast("Run a prediction first.", true); return; }
|
| 115 |
+
const axis = document.getElementById("slice_axis").value;
|
| 116 |
+
const pos = parseFloat(document.getElementById("slice_pos").value);
|
| 117 |
+
const ef = effectiveField();
|
| 118 |
+
const baseField = ef.baseField;
|
| 119 |
+
const diffOn = ef.isDiff;
|
| 120 |
+
const field = ef.field;
|
| 121 |
+
try {
|
| 122 |
+
const data = await fetchSliceData(axis, pos, field);
|
| 123 |
+
const mesh = buildSliceMesh(data, field);
|
| 124 |
+
if (!mesh) { showToast("Empty slice at this position.", true); return; }
|
| 125 |
+
scene.add(mesh);
|
| 126 |
+
slices.push({ id: ++_sliceId, axis, pos, field, baseField, diffOn, view: ef.view, mesh, _timer: null });
|
| 127 |
+
renderSlicesList();
|
| 128 |
+
} catch (e) { showToast("Could not add slice.", true); }
|
| 129 |
+
}
|
| 130 |
+
function moveSlice(id, val) {
|
| 131 |
+
const s = slices.find(x => x.id === id); if (!s) return;
|
| 132 |
+
s.pos = parseFloat(val);
|
| 133 |
+
const lbl = document.getElementById("sl-val-" + id); if (lbl) lbl.innerText = s.pos.toFixed(2);
|
| 134 |
+
clearTimeout(s._timer);
|
| 135 |
+
s._timer = setTimeout(async () => {
|
| 136 |
+
try {
|
| 137 |
+
const data = await fetchSliceData(s.axis, s.pos, s.field);
|
| 138 |
+
const mesh = buildSliceMesh(data, s.field);
|
| 139 |
+
if (s.mesh) { scene.remove(s.mesh); s.mesh.geometry.dispose(); }
|
| 140 |
+
s.mesh = mesh; if (mesh) scene.add(mesh);
|
| 141 |
+
} catch (e) { /* ignore transient slice errors during drag */ }
|
| 142 |
+
}, 50);
|
| 143 |
+
}
|
| 144 |
+
function removeSlice(id) {
|
| 145 |
+
const i = slices.findIndex(x => x.id === id); if (i < 0) return;
|
| 146 |
+
const s = slices[i];
|
| 147 |
+
if (s.mesh) { scene.remove(s.mesh); s.mesh.geometry.dispose(); }
|
| 148 |
+
slices.splice(i, 1); renderSlicesList();
|
| 149 |
+
}
|
| 150 |
+
function clearSlices() {
|
| 151 |
+
slices.forEach(s => { if (s.mesh) { scene.remove(s.mesh); s.mesh.geometry.dispose(); } });
|
| 152 |
+
slices = []; renderSlicesList();
|
| 153 |
+
}
|
| 154 |
+
function renderSlicesList() {
|
| 155 |
+
const box = document.getElementById("slices-list"); if (!box) return;
|
| 156 |
+
if (!slices.length) {
|
| 157 |
+
box.innerHTML = '<p style="font-size:.8rem;opacity:.6">No extra slices yet. Position the main slice (bottom bar) and click + Add slice.</p>';
|
| 158 |
+
return;
|
| 159 |
+
}
|
| 160 |
+
const b = (currentGeomData && currentGeomData.bounds) || [-4, 4, -4, 4, -4, 4];
|
| 161 |
+
box.innerHTML = slices.map(s => {
|
| 162 |
+
const ai = { x: 0, y: 2, z: 4 }[s.axis];
|
| 163 |
+
const mn = b[ai], mx = b[ai + 1];
|
| 164 |
+
const step = ((mx - mn) / 200).toFixed(4);
|
| 165 |
+
const _vs = s.view === "diff" ? " Δ" : (s.view === "b" ? " (B)" : "");
|
| 166 |
+
const label = s.axis.toUpperCase() + " · " + (s.baseField || s.field) + _vs;
|
| 167 |
+
return '<div class="slice-row"><div class="slice-row-head"><span>' + label +
|
| 168 |
+
'</span><button class="slice-x" title="remove" onclick="removeSlice(' + s.id + ')">×</button></div>' +
|
| 169 |
+
'<div class="slider-group" style="margin:6px 0 0"><label style="font-size:.75rem">pos: <span id="sl-val-' + s.id +
|
| 170 |
+
'">' + s.pos.toFixed(2) + '</span></label><input type="range" min="' + mn + '" max="' + mx +
|
| 171 |
+
'" step="' + step + '" value="' + s.pos + '" oninput="moveSlice(' + s.id + ', this.value)"></div></div>';
|
| 172 |
+
}).join("");
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// inflow direction indicator: arrow points along [cos(yaw), sin(yaw), 0]
|
| 176 |
+
function updateInflowArrow() {
|
| 177 |
+
if (!scene) return;
|
| 178 |
+
if (inflowArrow) { scene.remove(inflowArrow); inflowArrow = null; }
|
| 179 |
+
const show = document.getElementById("show_inflow");
|
| 180 |
+
if (show && !show.checked) return;
|
| 181 |
+
const yaw = parseFloat(document.getElementById("yaw_deg").value || "0") * Math.PI / 180;
|
| 182 |
+
const dir = new THREE.Vector3(Math.cos(yaw), Math.sin(yaw), 0);
|
| 183 |
+
const origin = dir.clone().multiplyScalar(-2.6).add(new THREE.Vector3(0, 0, 1.4));
|
| 184 |
+
inflowArrow = new THREE.ArrowHelper(dir, origin, 1.7, 0x00f0ff, 0.5, 0.28);
|
| 185 |
+
scene.add(inflowArrow);
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
function validateStl(file) {
|
| 189 |
+
if (!file.name.toLowerCase().endsWith(".stl")) { showToast("Please choose a .stl file.", true); return false; }
|
| 190 |
+
const mb = file.size / (1024 * 1024);
|
| 191 |
+
if (mb > 200) { showToast("This STL is " + mb.toFixed(0) + " MB. Very large files may be slow; a decimated STL works better.", true); }
|
| 192 |
+
return true;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// Initialize Three.js on Load
|
| 196 |
+
window.addEventListener("DOMContentLoaded", () => {
|
| 197 |
+
initThree();
|
| 198 |
+
toggleShapeParams();
|
| 199 |
+
updatePhysics();
|
| 200 |
+
updateInflowArrow();
|
| 201 |
+
renderSlicesList();
|
| 202 |
+
});
|
| 203 |
+
|
| 204 |
+
// 1. THREE.JS SCENE SETUP
|
| 205 |
+
function initThree() {
|
| 206 |
+
const container = document.getElementById("canvas-container");
|
| 207 |
+
const width = container.clientWidth;
|
| 208 |
+
const height = container.clientHeight;
|
| 209 |
+
|
| 210 |
+
// Scene
|
| 211 |
+
scene = new THREE.Scene();
|
| 212 |
+
scene.background = new THREE.Color(0x07090b);
|
| 213 |
+
|
| 214 |
+
// Cameras: perspective (default) + orthographic (parallel projection). `camera` = active.
|
| 215 |
+
perspCamera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100);
|
| 216 |
+
perspCamera.position.set(4, 3, 5);
|
| 217 |
+
orthoCamera = new THREE.OrthographicCamera(-3, 3, 3, -3, -100, 100);
|
| 218 |
+
orthoCamera.position.set(4, 3, 5);
|
| 219 |
+
camera = perspCamera;
|
| 220 |
+
|
| 221 |
+
// Renderer
|
| 222 |
+
renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
|
| 223 |
+
renderer.setSize(width, height);
|
| 224 |
+
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
| 225 |
+
renderer.shadowMap.enabled = true;
|
| 226 |
+
container.appendChild(renderer.domElement);
|
| 227 |
+
|
| 228 |
+
// Controls
|
| 229 |
+
controls = new THREE.OrbitControls(camera, renderer.domElement);
|
| 230 |
+
controls.enableDamping = true;
|
| 231 |
+
controls.dampingFactor = 0.05;
|
| 232 |
+
controls.maxPolarAngle = Math.PI;
|
| 233 |
+
// Mouse scheme: LEFT = rotate, wheel scroll = zoom, MIDDLE (wheel-press) drag = pan
|
| 234 |
+
controls.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.PAN, RIGHT: THREE.MOUSE.PAN };
|
| 235 |
+
controls.enableZoom = true;
|
| 236 |
+
controls.zoomSpeed = 1.1;
|
| 237 |
+
setupClickProbe();
|
| 238 |
+
|
| 239 |
+
// Ambient Light
|
| 240 |
+
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
|
| 241 |
+
scene.add(ambientLight);
|
| 242 |
+
|
| 243 |
+
// Directional Lights
|
| 244 |
+
const dirLight1 = new THREE.DirectionalLight(0xffffff, 0.8);
|
| 245 |
+
dirLight1.position.set(5, 10, 7);
|
| 246 |
+
scene.add(dirLight1);
|
| 247 |
+
|
| 248 |
+
const dirLight2 = new THREE.DirectionalLight(0x00f0ff, 0.3);
|
| 249 |
+
dirLight2.position.set(-5, -5, -5);
|
| 250 |
+
scene.add(dirLight2);
|
| 251 |
+
|
| 252 |
+
// Orientation gizmo (axes + X/Y/Z labels) in a corner. Floor grid removed (not needed).
|
| 253 |
+
const axesHelper = new THREE.AxesHelper(1.5);
|
| 254 |
+
const gizmoOrigin = new THREE.Vector3(-4, -1.9, -3.9);
|
| 255 |
+
axesHelper.position.copy(gizmoOrigin);
|
| 256 |
+
scene.add(axesHelper);
|
| 257 |
+
const _gl = 1.85;
|
| 258 |
+
makeAxisLabel("X", "#ff6b6b", new THREE.Vector3(gizmoOrigin.x + _gl, gizmoOrigin.y, gizmoOrigin.z));
|
| 259 |
+
makeAxisLabel("Y", "#69db7c", new THREE.Vector3(gizmoOrigin.x, gizmoOrigin.y + _gl, gizmoOrigin.z));
|
| 260 |
+
makeAxisLabel("Z", "#74c0fc", new THREE.Vector3(gizmoOrigin.x, gizmoOrigin.y, gizmoOrigin.z + _gl));
|
| 261 |
+
|
| 262 |
+
// Handle Resize
|
| 263 |
+
window.addEventListener("resize", onWindowResize);
|
| 264 |
+
|
| 265 |
+
// Animation Loop
|
| 266 |
+
function animate() {
|
| 267 |
+
requestAnimationFrame(animate);
|
| 268 |
+
controls.update();
|
| 269 |
+
renderer.render(scene, camera);
|
| 270 |
+
}
|
| 271 |
+
animate();
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
function onWindowResize() {
|
| 275 |
+
const container = document.getElementById("canvas-container");
|
| 276 |
+
const w = container.clientWidth, h = container.clientHeight;
|
| 277 |
+
const aspect = w / h;
|
| 278 |
+
perspCamera.aspect = aspect; perspCamera.updateProjectionMatrix();
|
| 279 |
+
const oh = (orthoCamera.top - orthoCamera.bottom) || 6;
|
| 280 |
+
orthoCamera.left = -oh * aspect / 2; orthoCamera.right = oh * aspect / 2;
|
| 281 |
+
orthoCamera.updateProjectionMatrix();
|
| 282 |
+
renderer.setSize(w, h);
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
function sizeOrtho(viewHeight) {
|
| 286 |
+
const c = document.getElementById("canvas-container");
|
| 287 |
+
const aspect = c.clientWidth / c.clientHeight;
|
| 288 |
+
orthoCamera.top = viewHeight / 2; orthoCamera.bottom = -viewHeight / 2;
|
| 289 |
+
orthoCamera.left = -viewHeight * aspect / 2; orthoCamera.right = viewHeight * aspect / 2;
|
| 290 |
+
orthoCamera.updateProjectionMatrix();
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
// switch between perspective and parallel (orthographic) projection
|
| 294 |
+
function setProjection(mode) {
|
| 295 |
+
if (!controls) return;
|
| 296 |
+
const tgt = controls.target.clone();
|
| 297 |
+
const from = camera;
|
| 298 |
+
const to = (mode === "parallel") ? orthoCamera : perspCamera;
|
| 299 |
+
if (to !== from) {
|
| 300 |
+
to.position.copy(from.position);
|
| 301 |
+
if (mode === "parallel") {
|
| 302 |
+
const dist = from.position.distanceTo(tgt);
|
| 303 |
+
const hgt = 2 * dist * Math.tan((perspCamera.fov * Math.PI / 180) / 2);
|
| 304 |
+
to.zoom = 1; sizeOrtho(hgt);
|
| 305 |
+
}
|
| 306 |
+
camera = to;
|
| 307 |
+
controls.object = camera;
|
| 308 |
+
}
|
| 309 |
+
camera.lookAt(tgt);
|
| 310 |
+
controls.target.copy(tgt);
|
| 311 |
+
controls.update();
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
// 2. TABS & FORM UI LOGIC
|
| 315 |
+
function switchTab(tabId) {
|
| 316 |
+
activeTab = tabId;
|
| 317 |
+
document.querySelectorAll(".tab-btn").forEach(btn => {
|
| 318 |
+
btn.classList.remove("active");
|
| 319 |
+
});
|
| 320 |
+
document.querySelectorAll(".tab-content").forEach(c => {
|
| 321 |
+
c.classList.remove("active");
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
// Activate clicked
|
| 325 |
+
const clickedBtn = event.target;
|
| 326 |
+
clickedBtn.classList.add("active");
|
| 327 |
+
document.getElementById(tabId).classList.add("active");
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
function toggleShapeParams() {
|
| 331 |
+
const shape = document.getElementById("shape_type").value;
|
| 332 |
+
document.querySelectorAll(".shape-params-group").forEach(g => {
|
| 333 |
+
g.style.display = "none";
|
| 334 |
+
});
|
| 335 |
+
if (shape === "cylinder" || shape === "capsule" || shape === "cone") {
|
| 336 |
+
document.getElementById("params-cylinder").style.display = "block";
|
| 337 |
+
} else if (shape === "sphere") {
|
| 338 |
+
document.getElementById("params-sphere").style.display = "block";
|
| 339 |
+
} else if (shape === "box") {
|
| 340 |
+
document.getElementById("params-box").style.display = "block";
|
| 341 |
+
} else if (shape === "torus") {
|
| 342 |
+
document.getElementById("params-torus").style.display = "block";
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// File Drop / Selection
|
| 347 |
+
function handleFileSelect(input) {
|
| 348 |
+
if (input.files && input.files[0]) {
|
| 349 |
+
if (!validateStl(input.files[0])) { input.value = ""; return; }
|
| 350 |
+
uploadedFile = input.files[0];
|
| 351 |
+
document.getElementById("file-info").innerText = `Loaded: ${uploadedFile.name} (${(uploadedFile.size / 1024).toFixed(1)} KB)`;
|
| 352 |
+
}
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
// Drag & Drop bindings
|
| 356 |
+
const dropZone = document.getElementById("drop-zone");
|
| 357 |
+
if (dropZone) {
|
| 358 |
+
dropZone.addEventListener("dragover", e => { e.preventDefault(); dropZone.classList.add("hover"); });
|
| 359 |
+
dropZone.addEventListener("dragleave", () => { dropZone.classList.remove("hover"); });
|
| 360 |
+
dropZone.addEventListener("drop", e => {
|
| 361 |
+
e.preventDefault();
|
| 362 |
+
dropZone.classList.remove("hover");
|
| 363 |
+
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
|
| 364 |
+
const file = e.dataTransfer.files[0];
|
| 365 |
+
if (validateStl(file)) {
|
| 366 |
+
uploadedFile = file;
|
| 367 |
+
document.getElementById("file-info").innerText = `Loaded: ${uploadedFile.name} (${(uploadedFile.size / 1024).toFixed(1)} KB)`;
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
});
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
function updatePhysics() {
|
| 374 |
+
const u = parseFloat(document.getElementById("uinf").value);
|
| 375 |
+
const mu = parseFloat(document.getElementById("viscosity").value);
|
| 376 |
+
const rho = parseFloat(document.getElementById("density").value);
|
| 377 |
+
|
| 378 |
+
// Update slider label values
|
| 379 |
+
document.getElementById("val-uinf").innerText = u.toFixed(1);
|
| 380 |
+
document.getElementById("val-visc").innerText = mu.toFixed(5);
|
| 381 |
+
document.getElementById("val-density").innerText = rho.toFixed(1);
|
| 382 |
+
|
| 383 |
+
// Re = rho * U_inf * L_ref / mu. (L_ref is normalized to 1.0 by make_watertight)
|
| 384 |
+
const Re = (rho * u * 1.0) / mu;
|
| 385 |
+
document.getElementById("calculated-re").innerText = Math.round(Re);
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
// 3. API & PREDICTION RUN
|
| 389 |
+
async function runPrediction() {
|
| 390 |
+
const form = document.getElementById("predict-form");
|
| 391 |
+
const btn = document.getElementById("btn-submit");
|
| 392 |
+
const spinner = document.getElementById("spinner");
|
| 393 |
+
|
| 394 |
+
// Build FormData
|
| 395 |
+
const formData = new FormData();
|
| 396 |
+
|
| 397 |
+
if (activeTab === "tab-procedural") {
|
| 398 |
+
const shapeType = document.getElementById("shape_type").value;
|
| 399 |
+
formData.append("shape_type", shapeType);
|
| 400 |
+
|
| 401 |
+
if (shapeType === "cylinder" || shapeType === "capsule" || shapeType === "cone") {
|
| 402 |
+
formData.append("radius", document.getElementById("radius").value);
|
| 403 |
+
formData.append("height", document.getElementById("height").value);
|
| 404 |
+
} else if (shapeType === "sphere") {
|
| 405 |
+
formData.append("radius", document.getElementById("sphere-radius").value);
|
| 406 |
+
} else if (shapeType === "box") {
|
| 407 |
+
formData.append("length", document.getElementById("length").value);
|
| 408 |
+
formData.append("width", document.getElementById("width").value);
|
| 409 |
+
formData.append("box_height", document.getElementById("box-height").value);
|
| 410 |
+
} else if (shapeType === "torus") {
|
| 411 |
+
formData.append("radius", document.getElementById("torus-major").value);
|
| 412 |
+
formData.append("minor_radius", document.getElementById("torus-minor").value);
|
| 413 |
+
}
|
| 414 |
+
} else {
|
| 415 |
+
// Upload tab
|
| 416 |
+
if (!uploadedFile) {
|
| 417 |
+
showToast("Please upload or drop an STL file first.", true);
|
| 418 |
+
return;
|
| 419 |
+
}
|
| 420 |
+
formData.append("shape_type", "custom");
|
| 421 |
+
formData.append("file", uploadedFile);
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
// Model + mesh resolution + common boundary and physics conditions
|
| 425 |
+
formData.append("model_name", document.getElementById("model_name").value);
|
| 426 |
+
formData.append("resolution", document.getElementById("mesh_res").value);
|
| 427 |
+
formData.append("model_b", document.getElementById("model_b").value);
|
| 428 |
+
formData.append("Re", document.getElementById("calculated-re").innerText);
|
| 429 |
+
formData.append("yaw_deg", document.getElementById("yaw_deg").value);
|
| 430 |
+
|
| 431 |
+
// Set loading state
|
| 432 |
+
btn.classList.add("loading");
|
| 433 |
+
btn.disabled = true;
|
| 434 |
+
if (probeMarker) probeMarker.visible = false;
|
| 435 |
+
clearSlices();
|
| 436 |
+
setStatus("running", "Running inference...");
|
| 437 |
+
showOverlay("Meshing geometry and running " + document.getElementById("model_name").value
|
| 438 |
+
+ " (the first run also loads the model)");
|
| 439 |
+
|
| 440 |
+
try {
|
| 441 |
+
const response = await fetch("/api/predict", {
|
| 442 |
+
method: "POST",
|
| 443 |
+
body: formData
|
| 444 |
+
});
|
| 445 |
+
|
| 446 |
+
if (!response.ok) {
|
| 447 |
+
const err = await response.json();
|
| 448 |
+
throw new Error(err.detail || "Prediction failed");
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
const data = await response.json();
|
| 452 |
+
currentGeomData = data; // Cache coords, wall_tris, ranges, bounds
|
| 453 |
+
if (!data.compare) { const _vm = document.getElementById("view_mode"); if (_vm) _vm.value = "a"; }
|
| 454 |
+
|
| 455 |
+
// Update stats panel
|
| 456 |
+
document.getElementById("stat-lref").innerText = data.geom_meta.L_ref.toFixed(2) + " m";
|
| 457 |
+
document.getElementById("stat-aref").innerText = data.geom_meta.A_ref.toFixed(4) + " m²";
|
| 458 |
+
document.getElementById("stat-nodes").innerText = data.mesh_meta.n_nodes_approx +
|
| 459 |
+
(data.mesh_meta.resolution ? " (" + data.mesh_meta.resolution + ")" : "");
|
| 460 |
+
document.getElementById("stat-inference-device").innerText = data.device.includes("cuda") ? "GPU (CUDA)" : "CPU";
|
| 461 |
+
if (data.timing_ms != null) document.getElementById("stat-timing").innerText = data.timing_ms + " ms";
|
| 462 |
+
if (data.model) {
|
| 463 |
+
document.getElementById("stat-model-name").innerText = data.model.name;
|
| 464 |
+
document.getElementById("stat-model-params").innerText = data.model.params_m + " M";
|
| 465 |
+
}
|
| 466 |
+
// Integrated pressure force coefficients (force-head free). When comparing, show A | B.
|
| 467 |
+
if (data.forces) {
|
| 468 |
+
const cdB = data.compare && data.compare.forces ? data.compare.forces.Cd : null;
|
| 469 |
+
const clB = data.compare && data.compare.forces ? data.compare.forces.Cl : null;
|
| 470 |
+
const fmtF = (a, b) => a.toFixed(3) + (b !== null ? " | " + b.toFixed(3) : "");
|
| 471 |
+
document.getElementById("stat-cd").innerText = fmtF(data.forces.Cd, cdB);
|
| 472 |
+
document.getElementById("stat-cl").innerText = fmtF(data.forces.Cl, clB);
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
// 1) Render transparent body
|
| 476 |
+
renderTransparentBody(data.coords, data.wall_tris);
|
| 477 |
+
|
| 478 |
+
// 2) Render the wind tunnel bounding box
|
| 479 |
+
renderTunnelBox(data.bounds);
|
| 480 |
+
|
| 481 |
+
// 3) Configure slice plane sweeper slider min/max/val
|
| 482 |
+
configureSliceSlider(data.bounds);
|
| 483 |
+
|
| 484 |
+
// 4) Fit camera focus to geometry wake (first prediction only or always)
|
| 485 |
+
setViewPreset("perspective");
|
| 486 |
+
|
| 487 |
+
// 5) Retrieve and render initial slice
|
| 488 |
+
await requestAndRenderSlice();
|
| 489 |
+
updateInflowArrow();
|
| 490 |
+
// 6) Re-apply body surface coloring + streamlines if their toggles were active
|
| 491 |
+
await updateBodySurface();
|
| 492 |
+
if (document.getElementById("show_streamlines") && document.getElementById("show_streamlines").checked) {
|
| 493 |
+
await toggleStreamlines(true);
|
| 494 |
+
}
|
| 495 |
+
setStatus("online", "Prediction ready");
|
| 496 |
+
|
| 497 |
+
} catch (error) {
|
| 498 |
+
showToast("Inference error: " + error.message, true);
|
| 499 |
+
setStatus("error", "Error");
|
| 500 |
+
} finally {
|
| 501 |
+
hideOverlay();
|
| 502 |
+
btn.classList.remove("loading");
|
| 503 |
+
btn.disabled = false;
|
| 504 |
+
}
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
// 4. RENDER PROCEDURAL TRANSPARENT MESH
|
| 508 |
+
function renderTransparentBody(coords, tris) {
|
| 509 |
+
// Clear previous body if exists
|
| 510 |
+
if (bodyMesh) {
|
| 511 |
+
scene.remove(bodyMesh);
|
| 512 |
+
bodyMesh.geometry.dispose();
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
const geometry = new THREE.BufferGeometry();
|
| 516 |
+
|
| 517 |
+
// Flatten coordinates
|
| 518 |
+
const vertices = new Float32Array(coords.flat());
|
| 519 |
+
// Flatten indices
|
| 520 |
+
const indices = new Uint32Array(tris.flat());
|
| 521 |
+
|
| 522 |
+
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
|
| 523 |
+
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
|
| 524 |
+
geometry.computeVertexNormals();
|
| 525 |
+
|
| 526 |
+
const material = new THREE.MeshPhysicalMaterial({
|
| 527 |
+
color: 0x9aa6b2,
|
| 528 |
+
transparent: true,
|
| 529 |
+
opacity: 0.35,
|
| 530 |
+
roughness: 0.2,
|
| 531 |
+
metalness: 0.1,
|
| 532 |
+
transmission: 0.6,
|
| 533 |
+
thickness: 0.5,
|
| 534 |
+
side: THREE.DoubleSide,
|
| 535 |
+
depthWrite: false
|
| 536 |
+
});
|
| 537 |
+
|
| 538 |
+
bodyMesh = new THREE.Mesh(geometry, material);
|
| 539 |
+
scene.add(bodyMesh);
|
| 540 |
+
updateBodyRenderStyle();
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
// Configure the position slider depending on the selected axis bounds
|
| 544 |
+
function configureSliceSlider(bounds) {
|
| 545 |
+
// bounds: [x_min, x_max, y_min, y_max, z_min, z_max]
|
| 546 |
+
const axis = document.getElementById("slice_axis").value;
|
| 547 |
+
const slider = document.getElementById("slice_pos");
|
| 548 |
+
|
| 549 |
+
let min = -4.0, max = 4.0;
|
| 550 |
+
if (axis === "x") {
|
| 551 |
+
min = bounds[0];
|
| 552 |
+
max = bounds[1];
|
| 553 |
+
} else if (axis === "y") {
|
| 554 |
+
min = bounds[2];
|
| 555 |
+
max = bounds[3];
|
| 556 |
+
} else {
|
| 557 |
+
min = bounds[4];
|
| 558 |
+
max = bounds[5];
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
slider.min = min.toFixed(2);
|
| 562 |
+
slider.max = max.toFixed(2);
|
| 563 |
+
slider.step = ((max - min) / 400).toFixed(4); // finer dragging
|
| 564 |
+
|
| 565 |
+
// Center plane
|
| 566 |
+
const mid = 0.5 * (min + max);
|
| 567 |
+
slider.value = mid.toFixed(2);
|
| 568 |
+
document.getElementById("val-slice-pos").innerText = mid.toFixed(2);
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
// Triggered when axis normal or variable is changed
|
| 572 |
+
function onSliceParamsChanged() {
|
| 573 |
+
if (!currentGeomData) return;
|
| 574 |
+
configureSliceSlider(currentGeomData.bounds);
|
| 575 |
+
requestAndRenderSlice();
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
let _sliceTimer = null;
|
| 579 |
+
function onSlicePosSliderInput(val) {
|
| 580 |
+
document.getElementById("val-slice-pos").innerText = parseFloat(val).toFixed(2);
|
| 581 |
+
clearTimeout(_sliceTimer);
|
| 582 |
+
_sliceTimer = setTimeout(requestAndRenderSlice, 60); // debounce rapid drags
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
// Colormaps: sequential green->red for magnitudes; diverging blue-white-red for
|
| 586 |
+
// signed fields (pressure, u, v, w), centered at zero so sign reads clearly.
|
| 587 |
+
const CMAP_SEQ = [
|
| 588 |
+
[0.00, 0x1a, 0x98, 0x50], [0.30, 0xa6, 0xd9, 0x6a], [0.50, 0xf7, 0xe4, 0x63],
|
| 589 |
+
[0.70, 0xfd, 0xae, 0x61], [1.00, 0xd7, 0x30, 0x27],
|
| 590 |
+
];
|
| 591 |
+
const CMAP_DIV = [
|
| 592 |
+
[0.00, 0x3b, 0x4c, 0xc0], [0.50, 0xf7, 0xf7, 0xf7], [1.00, 0xb4, 0x04, 0x26],
|
| 593 |
+
];
|
| 594 |
+
const SIGNED_FIELDS = ["pressure", "u", "v", "w"];
|
| 595 |
+
function isSigned(field) {
|
| 596 |
+
if (field.endsWith("_diff")) return true;
|
| 597 |
+
const base = field.replace(/_b$/, "");
|
| 598 |
+
return SIGNED_FIELDS.indexOf(base) !== -1;
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
function _interp(stops, t) {
|
| 602 |
+
t = Math.min(Math.max(t, 0.0), 1.0);
|
| 603 |
+
let i = 0;
|
| 604 |
+
while (i < stops.length - 1 && t > stops[i + 1][0]) i++;
|
| 605 |
+
const a = stops[i], b = stops[Math.min(i + 1, stops.length - 1)];
|
| 606 |
+
const f = (b[0] === a[0]) ? 0 : (t - a[0]) / (b[0] - a[0]);
|
| 607 |
+
return new THREE.Color(
|
| 608 |
+
(a[1] + f * (b[1] - a[1])) / 255,
|
| 609 |
+
(a[2] + f * (b[2] - a[2])) / 255,
|
| 610 |
+
(a[3] + f * (b[3] - a[3])) / 255
|
| 611 |
+
);
|
| 612 |
+
}
|
| 613 |
+
// color domain for a field, given its [min,max]: signed -> symmetric about 0
|
| 614 |
+
function fieldDomain(field, range) {
|
| 615 |
+
if (isSigned(field)) {
|
| 616 |
+
const M = Math.max(Math.abs(range[0]), Math.abs(range[1]), 1e-9);
|
| 617 |
+
return [-M, M];
|
| 618 |
+
}
|
| 619 |
+
return [range[0], range[1]];
|
| 620 |
+
}
|
| 621 |
+
function colorFor(value, field, dmin, dmax) {
|
| 622 |
+
const t = (value - dmin) / (dmax - dmin + 1e-9);
|
| 623 |
+
return _interp(isSigned(field) ? CMAP_DIV : CMAP_SEQ, t);
|
| 624 |
+
}
|
| 625 |
+
function cmapCss(field) {
|
| 626 |
+
const stops = isSigned(field) ? CMAP_DIV : CMAP_SEQ;
|
| 627 |
+
const parts = stops.map(s => `rgb(${s[1]},${s[2]},${s[3]}) ${Math.round(s[0] * 100)}%`);
|
| 628 |
+
return "linear-gradient(to top, " + parts.join(", ") + ")";
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
// ---- display units (normalized U_inf=1, or SI using the typed U_inf and rho) ----
|
| 632 |
+
const NDUNIT = {velocity_mag:"|U|/U∞", u:"u/U∞", v:"v/U∞", w:"w/U∞",
|
| 633 |
+
pressure:"p/ρU∞²", k:"k (nd)", omega:"ω (nd)", nut:"ν_t/ν"};
|
| 634 |
+
function baseOf(field) { return field.replace(/_diff$/, "").replace(/_b$/, ""); }
|
| 635 |
+
function unitScale(field) {
|
| 636 |
+
const vm = document.getElementById("units_mode");
|
| 637 |
+
const base = baseOf(field);
|
| 638 |
+
if (!vm || vm.value !== "si") return { f: 1, unit: NDUNIT[base] || base };
|
| 639 |
+
const U = parseFloat(document.getElementById("uinf").value) || 1;
|
| 640 |
+
const rho = parseFloat(document.getElementById("density").value) || 1;
|
| 641 |
+
if (base === "velocity_mag" || base === "u" || base === "v" || base === "w") return { f: U, unit: "m/s" };
|
| 642 |
+
if (base === "pressure") return { f: rho * U * U, unit: "Pa" };
|
| 643 |
+
if (base === "k") return { f: U * U, unit: "m²/s²" };
|
| 644 |
+
return { f: 1, unit: (NDUNIT[base] || base) + " (nd)" }; // omega, nut need the body length
|
| 645 |
+
}
|
| 646 |
+
function onUnitsChanged() {
|
| 647 |
+
onSliceParamsChanged();
|
| 648 |
+
if (lastProbe) renderProbe(lastProbe);
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
// which field key to show, from the View selector (A / B / difference)
|
| 652 |
+
function effectiveField() {
|
| 653 |
+
const baseField = document.getElementById("field_type").value;
|
| 654 |
+
const vm = document.getElementById("view_mode");
|
| 655 |
+
const want = vm ? vm.value : "a";
|
| 656 |
+
const hasCompare = !!(currentGeomData && currentGeomData.compare);
|
| 657 |
+
const view = (hasCompare && (want === "b" || want === "diff")) ? want : "a";
|
| 658 |
+
let field = baseField, isDiff = false;
|
| 659 |
+
if (view === "b") field = baseField + "_b";
|
| 660 |
+
else if (view === "diff") { field = baseField + "_diff"; isDiff = true; }
|
| 661 |
+
return { field, baseField, isDiff, view };
|
| 662 |
+
}
|
| 663 |
+
function onViewModeChanged() {
|
| 664 |
+
const vm = document.getElementById("view_mode");
|
| 665 |
+
if (vm && vm.value !== "a" && !(currentGeomData && currentGeomData.compare)) {
|
| 666 |
+
showToast("Pick a model in 'Compare with (B)' and Predict first to use this view.", true);
|
| 667 |
+
}
|
| 668 |
+
onSliceParamsChanged();
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
// 5. SLICING ENDPOINT QUERY & THREE.JS RENDER
|
| 672 |
+
async function requestAndRenderSlice() {
|
| 673 |
+
if (!currentGeomData) return;
|
| 674 |
+
|
| 675 |
+
const normal_axis = document.getElementById("slice_axis").value;
|
| 676 |
+
const position = parseFloat(document.getElementById("slice_pos").value);
|
| 677 |
+
const ef = effectiveField();
|
| 678 |
+
const baseField = ef.baseField;
|
| 679 |
+
const diffOn = ef.isDiff;
|
| 680 |
+
const field_type = ef.field;
|
| 681 |
+
|
| 682 |
+
try {
|
| 683 |
+
const response = await fetch("/api/slice", {
|
| 684 |
+
method: "POST",
|
| 685 |
+
headers: { "Content-Type": "application/json" },
|
| 686 |
+
body: JSON.stringify({ normal_axis, position, field_type })
|
| 687 |
+
});
|
| 688 |
+
|
| 689 |
+
if (!response.ok) {
|
| 690 |
+
throw new Error("Slicing failed");
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
const data = await response.json(); // { points, faces, scalars }
|
| 694 |
+
|
| 695 |
+
// Clear previous slice and grid
|
| 696 |
+
if (sliceMesh) {
|
| 697 |
+
scene.remove(sliceMesh);
|
| 698 |
+
sliceMesh.geometry.dispose();
|
| 699 |
+
}
|
| 700 |
+
if (sliceGridMesh) {
|
| 701 |
+
scene.remove(sliceGridMesh);
|
| 702 |
+
sliceGridMesh.geometry.dispose();
|
| 703 |
+
}
|
| 704 |
+
if (sliceArrowsGroup) {
|
| 705 |
+
scene.remove(sliceArrowsGroup);
|
| 706 |
+
sliceArrowsGroup = null;
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
if (data.points.length === 0) return;
|
| 710 |
+
|
| 711 |
+
// Field-aware color domain: signed fields use a diverging map centered at 0.
|
| 712 |
+
const val_range = currentGeomData.ranges[field_type] || [0, 1];
|
| 713 |
+
const dom = fieldDomain(field_type, val_range);
|
| 714 |
+
const minVal = dom[0], maxVal = dom[1];
|
| 715 |
+
|
| 716 |
+
// legend (values scaled to the chosen units; colors are relative so they are unaffected)
|
| 717 |
+
const us = unitScale(field_type);
|
| 718 |
+
const dmin = minVal * us.f, dmax = maxVal * us.f;
|
| 719 |
+
const dec = (Math.max(Math.abs(dmin), Math.abs(dmax)) < 10) ? 3 : 1;
|
| 720 |
+
document.getElementById("legend-min").innerText = dmin.toFixed(dec);
|
| 721 |
+
document.getElementById("legend-max").innerText = dmax.toFixed(dec);
|
| 722 |
+
document.getElementById("legend-unit").innerText = (diffOn ? "Δ " : "") + us.unit + (ef.view === "b" ? " (B)" : "");
|
| 723 |
+
const _bar = document.querySelector(".legend-color-bar"); if (_bar) _bar.style.background = cmapCss(field_type);
|
| 724 |
+
|
| 725 |
+
// Build Geometry
|
| 726 |
+
const geometry = new THREE.BufferGeometry();
|
| 727 |
+
const vertices = new Float32Array(data.points.flat());
|
| 728 |
+
const indices = new Uint32Array(data.faces.flat());
|
| 729 |
+
|
| 730 |
+
// Color attributes based on colormap
|
| 731 |
+
const colors = [];
|
| 732 |
+
for (let j = 0; j < data.scalars.length; j++) {
|
| 733 |
+
const color = colorFor(data.scalars[j], field_type, minVal, maxVal);
|
| 734 |
+
colors.push(color.r, color.g, color.b);
|
| 735 |
+
}
|
| 736 |
+
const colorsArr = new Float32Array(colors);
|
| 737 |
+
|
| 738 |
+
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
|
| 739 |
+
geometry.setAttribute("color", new THREE.BufferAttribute(colorsArr, 3));
|
| 740 |
+
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
|
| 741 |
+
geometry.computeVertexNormals();
|
| 742 |
+
|
| 743 |
+
const material = new THREE.MeshBasicMaterial({
|
| 744 |
+
vertexColors: true,
|
| 745 |
+
side: THREE.DoubleSide,
|
| 746 |
+
transparent: false,
|
| 747 |
+
depthWrite: true
|
| 748 |
+
});
|
| 749 |
+
|
| 750 |
+
sliceMesh = new THREE.Mesh(geometry, material);
|
| 751 |
+
scene.add(sliceMesh);
|
| 752 |
+
|
| 753 |
+
// Create slice grid overlay
|
| 754 |
+
const gridMat = new THREE.MeshBasicMaterial({
|
| 755 |
+
color: 0x000000,
|
| 756 |
+
wireframe: true,
|
| 757 |
+
transparent: true,
|
| 758 |
+
opacity: 0.18,
|
| 759 |
+
side: THREE.DoubleSide,
|
| 760 |
+
polygonOffset: true,
|
| 761 |
+
polygonOffsetFactor: -1,
|
| 762 |
+
polygonOffsetUnits: -1
|
| 763 |
+
});
|
| 764 |
+
sliceGridMesh = new THREE.Mesh(geometry, gridMat);
|
| 765 |
+
|
| 766 |
+
if (document.getElementById("show_slice_grid").checked) {
|
| 767 |
+
scene.add(sliceGridMesh);
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
// Create slice arrows
|
| 771 |
+
if (data.vectors && data.vectors.length > 0) {
|
| 772 |
+
sliceArrowsGroup = new THREE.Group();
|
| 773 |
+
const numPoints = data.points.length; // points is [x, y, z, x, y, z] Wait no, points is 1D flat array, length is 3N. Or points is array of [x, y, z]? wait, data.points.flat() is used. So data.points is an array of [x,y,z].
|
| 774 |
+
const pointsCount = data.points.length;
|
| 775 |
+
const step = Math.max(1, Math.floor(pointsCount / 600)); // cap at ~600 arrows
|
| 776 |
+
for (let i = 0; i < pointsCount; i += step) {
|
| 777 |
+
const pt = data.points[i];
|
| 778 |
+
const v = data.vectors[i];
|
| 779 |
+
const px = pt[0], py = pt[1], pz = pt[2];
|
| 780 |
+
const vx = v[0], vy = v[1], vz = v[2];
|
| 781 |
+
const dir = new THREE.Vector3(vx, vy, vz);
|
| 782 |
+
const length = dir.length();
|
| 783 |
+
if (length < 1e-4) continue;
|
| 784 |
+
dir.normalize();
|
| 785 |
+
|
| 786 |
+
const c = colorFor(data.scalars[i], field_type, minVal, maxVal);
|
| 787 |
+
const hex = (Math.floor(c.r * 255) << 16) | (Math.floor(c.g * 255) << 8) | Math.floor(c.b * 255);
|
| 788 |
+
|
| 789 |
+
// arrow length scale
|
| 790 |
+
const arrowLength = 0.05 + 0.1 * (length / (maxVal || 1));
|
| 791 |
+
const arrowHelper = new THREE.ArrowHelper(dir, new THREE.Vector3(px, py, pz), arrowLength, hex, arrowLength * 0.3, arrowLength * 0.2);
|
| 792 |
+
sliceArrowsGroup.add(arrowHelper);
|
| 793 |
+
}
|
| 794 |
+
|
| 795 |
+
if (document.getElementById("show_vectors").checked) {
|
| 796 |
+
scene.add(sliceArrowsGroup);
|
| 797 |
+
}
|
| 798 |
+
}
|
| 799 |
+
|
| 800 |
+
} catch (error) {
|
| 801 |
+
console.error("Slice rendering error: ", error);
|
| 802 |
+
}
|
| 803 |
+
}
|
| 804 |
+
|
| 805 |
+
// 6. VIEWPORT DISPLAY & OPTION HANDLERS
|
| 806 |
+
function updateBodyRenderStyle() {
|
| 807 |
+
if (!bodyMesh) return;
|
| 808 |
+
const style = document.getElementById("body_style").value;
|
| 809 |
+
if (style === "glass") {
|
| 810 |
+
bodyMesh.visible = true;
|
| 811 |
+
bodyMesh.material.wireframe = false;
|
| 812 |
+
bodyMesh.material.transparent = true;
|
| 813 |
+
bodyMesh.material.opacity = 0.35;
|
| 814 |
+
} else if (style === "wireframe") {
|
| 815 |
+
bodyMesh.visible = true;
|
| 816 |
+
bodyMesh.material.wireframe = true;
|
| 817 |
+
bodyMesh.material.transparent = true;
|
| 818 |
+
bodyMesh.material.opacity = 0.4;
|
| 819 |
+
} else if (style === "hidden") {
|
| 820 |
+
bodyMesh.visible = false;
|
| 821 |
+
}
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
let streamlineGroup = null;
|
| 825 |
+
|
| 826 |
+
// Paint the body surface by a predicted field (pressure / |U| / k), or revert to translucent gray.
|
| 827 |
+
async function updateBodySurface() {
|
| 828 |
+
if (!bodyMesh) return;
|
| 829 |
+
const sel = document.getElementById("surface_field").value;
|
| 830 |
+
if (sel === "none" || !currentGeomData) {
|
| 831 |
+
if (bodyMesh.geometry.getAttribute("color")) bodyMesh.geometry.deleteAttribute("color");
|
| 832 |
+
bodyMesh.material.vertexColors = false;
|
| 833 |
+
bodyMesh.material.color.setHex(0x9aa6b2);
|
| 834 |
+
bodyMesh.material.transmission = 0.6;
|
| 835 |
+
bodyMesh.material.needsUpdate = true;
|
| 836 |
+
updateBodyRenderStyle();
|
| 837 |
+
return;
|
| 838 |
+
}
|
| 839 |
+
try {
|
| 840 |
+
const res = await fetch("/api/surface", {
|
| 841 |
+
method: "POST", headers: { "Content-Type": "application/json" },
|
| 842 |
+
body: JSON.stringify({ field: sel })
|
| 843 |
+
});
|
| 844 |
+
if (!res.ok) throw new Error("surface failed");
|
| 845 |
+
const d = await res.json();
|
| 846 |
+
const dom = fieldDomain(sel, d.range);
|
| 847 |
+
const cols = new Float32Array(d.values.length * 3);
|
| 848 |
+
for (let i = 0; i < d.values.length; i++) {
|
| 849 |
+
const c = colorFor(d.values[i], sel, dom[0], dom[1]);
|
| 850 |
+
cols[3 * i] = c.r; cols[3 * i + 1] = c.g; cols[3 * i + 2] = c.b;
|
| 851 |
+
}
|
| 852 |
+
bodyMesh.geometry.setAttribute("color", new THREE.BufferAttribute(cols, 3));
|
| 853 |
+
bodyMesh.material.vertexColors = true;
|
| 854 |
+
bodyMesh.material.color.setHex(0xffffff);
|
| 855 |
+
bodyMesh.material.wireframe = false;
|
| 856 |
+
bodyMesh.material.transparent = true;
|
| 857 |
+
bodyMesh.material.opacity = 0.98;
|
| 858 |
+
bodyMesh.material.transmission = 0.0;
|
| 859 |
+
bodyMesh.material.needsUpdate = true;
|
| 860 |
+
bodyMesh.visible = true;
|
| 861 |
+
} catch (e) { showToast("Could not color surface.", true); }
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
// Toggle forward streamlines of the predicted velocity, colored by |U|.
|
| 865 |
+
async function toggleStreamlines(checked) {
|
| 866 |
+
if (streamlineGroup) { scene.remove(streamlineGroup); streamlineGroup = null; }
|
| 867 |
+
if (!checked) return;
|
| 868 |
+
if (!currentGeomData) {
|
| 869 |
+
showToast("Run a prediction first.", true);
|
| 870 |
+
const cb = document.getElementById("show_streamlines"); if (cb) cb.checked = false; return;
|
| 871 |
+
}
|
| 872 |
+
showOverlay("Computing streamlines…");
|
| 873 |
+
try {
|
| 874 |
+
const res = await fetch("/api/streamlines", {
|
| 875 |
+
method: "POST", headers: { "Content-Type": "application/json" },
|
| 876 |
+
body: JSON.stringify({ n: 14 })
|
| 877 |
+
});
|
| 878 |
+
if (!res.ok) throw new Error("streamlines failed");
|
| 879 |
+
const d = await res.json();
|
| 880 |
+
streamlineGroup = new THREE.Group();
|
| 881 |
+
const dom = [d.range[0], d.range[1]];
|
| 882 |
+
for (const ln of d.lines) {
|
| 883 |
+
if (!ln.points || ln.points.length < 2) continue;
|
| 884 |
+
const g = new THREE.BufferGeometry();
|
| 885 |
+
g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(ln.points.flat()), 3));
|
| 886 |
+
const cols = new Float32Array(ln.points.length * 3);
|
| 887 |
+
for (let i = 0; i < ln.points.length; i++) {
|
| 888 |
+
const c = colorFor(ln.scalars[i], "velocity_mag", dom[0], dom[1]);
|
| 889 |
+
cols[3 * i] = c.r; cols[3 * i + 1] = c.g; cols[3 * i + 2] = c.b;
|
| 890 |
+
}
|
| 891 |
+
g.setAttribute("color", new THREE.BufferAttribute(cols, 3));
|
| 892 |
+
streamlineGroup.add(new THREE.Line(g, new THREE.LineBasicMaterial({ vertexColors: true })));
|
| 893 |
+
}
|
| 894 |
+
scene.add(streamlineGroup);
|
| 895 |
+
if (!d.lines.length) showToast("No streamlines produced for this flow.", true);
|
| 896 |
+
} catch (e) {
|
| 897 |
+
showToast("Streamlines failed.", true);
|
| 898 |
+
const cb = document.getElementById("show_streamlines"); if (cb) cb.checked = false;
|
| 899 |
+
}
|
| 900 |
+
hideOverlay();
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
function toggleTunnelBox(checked) {
|
| 904 |
+
if (!tunnelBox) return;
|
| 905 |
+
tunnelBox.visible = checked;
|
| 906 |
+
if (checked && !scene.children.includes(tunnelBox)) {
|
| 907 |
+
scene.add(tunnelBox);
|
| 908 |
+
}
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
function renderTunnelBox(bounds) {
|
| 912 |
+
// Clear previous tunnelBox if exists
|
| 913 |
+
if (tunnelBox) {
|
| 914 |
+
scene.remove(tunnelBox);
|
| 915 |
+
tunnelBox.geometry.dispose();
|
| 916 |
+
}
|
| 917 |
+
|
| 918 |
+
// bounds: [x_min, x_max, y_min, y_max, z_min, z_max]
|
| 919 |
+
const xSize = bounds[1] - bounds[0];
|
| 920 |
+
const ySize = bounds[3] - bounds[2];
|
| 921 |
+
const zSize = bounds[5] - bounds[4];
|
| 922 |
+
|
| 923 |
+
const boxGeom = new THREE.BoxGeometry(xSize, ySize, zSize);
|
| 924 |
+
const edges = new THREE.EdgesGeometry(boxGeom);
|
| 925 |
+
|
| 926 |
+
tunnelBox = new THREE.LineSegments(
|
| 927 |
+
edges,
|
| 928 |
+
new THREE.LineBasicMaterial({
|
| 929 |
+
color: 0x1b49aa,
|
| 930 |
+
transparent: true,
|
| 931 |
+
opacity: 0.4
|
| 932 |
+
})
|
| 933 |
+
);
|
| 934 |
+
|
| 935 |
+
// Position box center
|
| 936 |
+
tunnelBox.position.set(
|
| 937 |
+
0.5 * (bounds[1] + bounds[0]),
|
| 938 |
+
0.5 * (bounds[3] + bounds[2]),
|
| 939 |
+
0.5 * (bounds[5] + bounds[4])
|
| 940 |
+
);
|
| 941 |
+
|
| 942 |
+
// Show if checkbox is checked
|
| 943 |
+
const isChecked = document.getElementById("show_tunnel").checked;
|
| 944 |
+
tunnelBox.visible = isChecked;
|
| 945 |
+
if (isChecked) {
|
| 946 |
+
scene.add(tunnelBox);
|
| 947 |
+
}
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
function toggleSliceGrid(checked) {
|
| 951 |
+
if (!sliceGridMesh) return;
|
| 952 |
+
sliceGridMesh.visible = checked;
|
| 953 |
+
if (checked && !scene.children.includes(sliceGridMesh)) {
|
| 954 |
+
scene.add(sliceGridMesh);
|
| 955 |
+
}
|
| 956 |
+
}
|
| 957 |
+
|
| 958 |
+
function toggleVectors(checked) {
|
| 959 |
+
if (!sliceArrowsGroup) return;
|
| 960 |
+
sliceArrowsGroup.visible = checked;
|
| 961 |
+
if (checked && !scene.children.includes(sliceArrowsGroup)) {
|
| 962 |
+
scene.add(sliceArrowsGroup);
|
| 963 |
+
}
|
| 964 |
+
}
|
| 965 |
+
|
| 966 |
+
function setViewPreset(preset) {
|
| 967 |
+
if (!controls || !camera) return;
|
| 968 |
+
|
| 969 |
+
// The body is around (0,0,0) and the wake extends downstream to +x.
|
| 970 |
+
// Center our focus on the wake area: x=1.5, y=0.0, z=0.0
|
| 971 |
+
const targetX = 1.5;
|
| 972 |
+
const targetY = 0.0;
|
| 973 |
+
const targetZ = 0.0;
|
| 974 |
+
|
| 975 |
+
controls.target.set(targetX, targetY, targetZ);
|
| 976 |
+
|
| 977 |
+
if (preset === "perspective") {
|
| 978 |
+
camera.position.set(5.5, 4.0, 6.0);
|
| 979 |
+
} else if (preset === "side") {
|
| 980 |
+
// Look along Y axis (slice symmetry plane view)
|
| 981 |
+
camera.position.set(targetX, 8.0, targetZ + 0.001); // offset slightly to avoid gimbal lock
|
| 982 |
+
} else if (preset === "top") {
|
| 983 |
+
// Look along Z axis (horizontal cut view)
|
| 984 |
+
camera.position.set(targetX, targetY, 8.0);
|
| 985 |
+
} else if (preset === "front") {
|
| 986 |
+
// Look along X axis from downstream wake back at the body
|
| 987 |
+
camera.position.set(8.5, targetY, targetZ);
|
| 988 |
+
}
|
| 989 |
+
|
| 990 |
+
controls.update();
|
| 991 |
+
}
|
| 992 |
+
|
| 993 |
+
// 7. CLICK-TO-PROBE: single left-click sets the rotation pivot AND queries values
|
| 994 |
+
function setupClickProbe() {
|
| 995 |
+
raycaster = new THREE.Raycaster();
|
| 996 |
+
const el = renderer.domElement;
|
| 997 |
+
el.addEventListener("pointerdown", e => { if (e.button === 0) _downXY = [e.clientX, e.clientY]; });
|
| 998 |
+
el.addEventListener("pointerup", e => {
|
| 999 |
+
if (!_downXY || e.button !== 0) { _downXY = null; return; }
|
| 1000 |
+
const moved = Math.hypot(e.clientX - _downXY[0], e.clientY - _downXY[1]);
|
| 1001 |
+
_downXY = null;
|
| 1002 |
+
if (moved > 5) return; // it was a rotate-drag, not a click
|
| 1003 |
+
pickPoint(e);
|
| 1004 |
+
});
|
| 1005 |
+
}
|
| 1006 |
+
|
| 1007 |
+
function pickPoint(e) {
|
| 1008 |
+
if (!raycaster) return;
|
| 1009 |
+
const rect = renderer.domElement.getBoundingClientRect();
|
| 1010 |
+
const ndc = new THREE.Vector2(
|
| 1011 |
+
((e.clientX - rect.left) / rect.width) * 2 - 1,
|
| 1012 |
+
-((e.clientY - rect.top) / rect.height) * 2 + 1
|
| 1013 |
+
);
|
| 1014 |
+
raycaster.setFromCamera(ndc, camera);
|
| 1015 |
+
const targets = [sliceMesh, bodyMesh].filter(Boolean);
|
| 1016 |
+
const hits = raycaster.intersectObjects(targets, false);
|
| 1017 |
+
if (!hits.length) return;
|
| 1018 |
+
const p = hits[0].point;
|
| 1019 |
+
controls.target.copy(p); controls.update(); // set rotation pivot
|
| 1020 |
+
placeProbeMarker(p); // visual marker at the queried point
|
| 1021 |
+
probePoint(p.x, p.y, p.z); // read field values there
|
| 1022 |
+
}
|
| 1023 |
+
|
| 1024 |
+
async function probePoint(x, y, z) {
|
| 1025 |
+
try {
|
| 1026 |
+
const res = await fetch("/api/probe", {
|
| 1027 |
+
method: "POST", headers: { "Content-Type": "application/json" },
|
| 1028 |
+
body: JSON.stringify({ x, y, z })
|
| 1029 |
+
});
|
| 1030 |
+
if (!res.ok) return;
|
| 1031 |
+
renderProbe(await res.json());
|
| 1032 |
+
} catch (err) { console.error("probe error:", err); }
|
| 1033 |
+
}
|
| 1034 |
+
|
| 1035 |
+
function renderProbe(d) {
|
| 1036 |
+
lastProbe = d;
|
| 1037 |
+
const hint = document.getElementById("probe-hint");
|
| 1038 |
+
const box = document.getElementById("probe-results");
|
| 1039 |
+
if (!box) return;
|
| 1040 |
+
if (hint) hint.style.display = "none";
|
| 1041 |
+
const v = d.values;
|
| 1042 |
+
const fx = (a, dec = 4) => (Math.abs(a) >= 1e4 || (a !== 0 && Math.abs(a) < 1e-3)) ? a.toExponential(2) : a.toFixed(dec);
|
| 1043 |
+
const uU = unitScale("velocity_mag"), uP = unitScale("pressure"),
|
| 1044 |
+
uK = unitScale("k"), uW = unitScale("omega"), uN = unitScale("nut");
|
| 1045 |
+
const rows = [
|
| 1046 |
+
["x, y, z", d.point.map(a => a.toFixed(3)).join(", ")],
|
| 1047 |
+
["|U| (" + uU.unit + ")", fx(v.velocity_mag * uU.f)],
|
| 1048 |
+
["u, v, w (" + uU.unit + ")", [v.u, v.v, v.w].map(a => fx(a * uU.f)).join(", ")],
|
| 1049 |
+
["pressure (" + uP.unit + ")", fx(v.pressure * uP.f)],
|
| 1050 |
+
["k (" + uK.unit + ")", fx(v.k * uK.f)],
|
| 1051 |
+
["ω (" + uW.unit + ")", fx(v.omega * uW.f)],
|
| 1052 |
+
["ν_t (" + uN.unit + ")", fx(v.nut * uN.f)],
|
| 1053 |
+
];
|
| 1054 |
+
box.innerHTML = rows.map(r =>
|
| 1055 |
+
`<div class="stat-item"><span>${r[0]}</span><span class="code-font">${r[1]}</span></div>`).join("");
|
| 1056 |
+
box.style.display = "flex";
|
| 1057 |
+
}
|
| 1058 |
+
|
code/ezflow_v3/app/frontend/index.html
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>EZFlow v2 - Turbulent-RANS GNN Flow Predictor</title>
|
| 7 |
+
<link rel="stylesheet" href="/static/style.css?v=11">
|
| 8 |
+
<!-- Three.js + OrbitControls vendored locally so the app works offline / when packaged -->
|
| 9 |
+
<script src="/static/vendor/three.min.js"></script>
|
| 10 |
+
<script src="/static/vendor/OrbitControls.js"></script>
|
| 11 |
+
</head>
|
| 12 |
+
<body>
|
| 13 |
+
|
| 14 |
+
<header class="app-header">
|
| 15 |
+
<div class="logo">
|
| 16 |
+
<span class="neon-text">EZFlow v2</span> Turbulent-RANS GNN
|
| 17 |
+
</div>
|
| 18 |
+
<div class="system-status">
|
| 19 |
+
<span class="status-indicator online" id="status-dot"></span> <span id="status-text">Ready</span>
|
| 20 |
+
</div>
|
| 21 |
+
</header>
|
| 22 |
+
|
| 23 |
+
<main class="app-layout">
|
| 24 |
+
|
| 25 |
+
<!-- LEFT SIDE: CONTROLS & PARAMS -->
|
| 26 |
+
<section class="control-panel panel">
|
| 27 |
+
|
| 28 |
+
<!-- MODEL SELECTOR -->
|
| 29 |
+
<div class="section-card">
|
| 30 |
+
<h2>Surrogate Model</h2>
|
| 31 |
+
<div class="input-group">
|
| 32 |
+
<label for="model_name">Choose model (A)</label>
|
| 33 |
+
<select id="model_name">
|
| 34 |
+
<option value="HybridFlow" selected>HybridFlow (local MP + slice attention, 3.04M)</option>
|
| 35 |
+
<option value="GeoReNet">GeoReNet (local MP + global node, 3.28M)</option>
|
| 36 |
+
</select>
|
| 37 |
+
</div>
|
| 38 |
+
<div class="input-group">
|
| 39 |
+
<label for="model_b">Compare with (B)</label>
|
| 40 |
+
<select id="model_b">
|
| 41 |
+
<option value="" selected>None</option>
|
| 42 |
+
<option value="HybridFlow">HybridFlow</option>
|
| 43 |
+
<option value="GeoReNet">GeoReNet</option>
|
| 44 |
+
</select>
|
| 45 |
+
</div>
|
| 46 |
+
<div class="input-group">
|
| 47 |
+
<label for="view_mode">View (after a compare prediction)</label>
|
| 48 |
+
<select id="view_mode" onchange="onViewModeChanged()">
|
| 49 |
+
<option value="a" selected>Model A result</option>
|
| 50 |
+
<option value="b">Model B result</option>
|
| 51 |
+
<option value="diff">Difference (A − B)</option>
|
| 52 |
+
</select>
|
| 53 |
+
</div>
|
| 54 |
+
<div class="input-group">
|
| 55 |
+
<label for="mesh_res">Mesh Resolution</label>
|
| 56 |
+
<select id="mesh_res">
|
| 57 |
+
<option value="coarse">Coarse — fast, smoothed envelope</option>
|
| 58 |
+
<option value="medium" selected>Medium — detail-preserving</option>
|
| 59 |
+
<option value="fine">Fine — most detail (slower)</option>
|
| 60 |
+
</select>
|
| 61 |
+
</div>
|
| 62 |
+
</div>
|
| 63 |
+
|
| 64 |
+
<!-- GEOMETRY SETUP -->
|
| 65 |
+
<div class="section-card">
|
| 66 |
+
<h2>1. Geometry Definition</h2>
|
| 67 |
+
<div class="tabs">
|
| 68 |
+
<button type="button" class="tab-btn active" onclick="switchTab('tab-procedural')">Simple Shape</button>
|
| 69 |
+
<button type="button" class="tab-btn" onclick="switchTab('tab-upload')">Upload STL</button>
|
| 70 |
+
</div>
|
| 71 |
+
|
| 72 |
+
<form id="predict-form" onsubmit="event.preventDefault(); runPrediction();">
|
| 73 |
+
<!-- Procedural Shapes Tab -->
|
| 74 |
+
<div id="tab-procedural" class="tab-content active">
|
| 75 |
+
<div class="input-group">
|
| 76 |
+
<label for="shape_type">Shape Type</label>
|
| 77 |
+
<select id="shape_type" name="shape_type" onchange="toggleShapeParams()">
|
| 78 |
+
<option value="cylinder">Cylinder (fused/base)</option>
|
| 79 |
+
<option value="sphere">Sphere</option>
|
| 80 |
+
<option value="box">Box (prism)</option>
|
| 81 |
+
<option value="capsule">Capsule</option>
|
| 82 |
+
<option value="cone">Cone</option>
|
| 83 |
+
<option value="torus">Torus</option>
|
| 84 |
+
</select>
|
| 85 |
+
</div>
|
| 86 |
+
|
| 87 |
+
<!-- Shape parameters dynamically toggled -->
|
| 88 |
+
<div id="params-cylinder" class="shape-params-group">
|
| 89 |
+
<div class="slider-group">
|
| 90 |
+
<label>Radius: <span id="val-radius">0.30</span></label>
|
| 91 |
+
<input type="range" id="radius" name="radius" min="0.1" max="0.8" step="0.05" value="0.30" oninput="document.getElementById('val-radius').innerText = parseFloat(this.value).toFixed(2)">
|
| 92 |
+
</div>
|
| 93 |
+
<div class="slider-group">
|
| 94 |
+
<label>Height: <span id="val-height">1.20</span></label>
|
| 95 |
+
<input type="range" id="height" name="height" min="0.2" max="2.0" step="0.1" value="1.20" oninput="document.getElementById('val-height').innerText = parseFloat(this.value).toFixed(2)">
|
| 96 |
+
</div>
|
| 97 |
+
</div>
|
| 98 |
+
|
| 99 |
+
<div id="params-sphere" class="shape-params-group" style="display:none;">
|
| 100 |
+
<div class="slider-group">
|
| 101 |
+
<label>Radius: <span id="val-sphere-radius">0.40</span></label>
|
| 102 |
+
<input type="range" id="sphere-radius" min="0.1" max="0.8" step="0.05" value="0.40" oninput="document.getElementById('val-sphere-radius').innerText = parseFloat(this.value).toFixed(2)">
|
| 103 |
+
</div>
|
| 104 |
+
</div>
|
| 105 |
+
|
| 106 |
+
<div id="params-box" class="shape-params-group" style="display:none;">
|
| 107 |
+
<div class="slider-group">
|
| 108 |
+
<label>Length: <span id="val-length">0.80</span></label>
|
| 109 |
+
<input type="range" id="length" min="0.2" max="2.0" step="0.1" value="0.80" oninput="document.getElementById('val-length').innerText = parseFloat(this.value).toFixed(2)">
|
| 110 |
+
</div>
|
| 111 |
+
<div class="slider-group">
|
| 112 |
+
<label>Width: <span id="val-width">0.50</span></label>
|
| 113 |
+
<input type="range" id="width" min="0.2" max="1.5" step="0.05" value="0.50" oninput="document.getElementById('val-width').innerText = parseFloat(this.value).toFixed(2)">
|
| 114 |
+
</div>
|
| 115 |
+
<div class="slider-group">
|
| 116 |
+
<label>Height: <span id="val-box-height">0.50</span></label>
|
| 117 |
+
<input type="range" id="box-height" min="0.2" max="1.5" step="0.05" value="0.50" oninput="document.getElementById('val-box-height').innerText = parseFloat(this.value).toFixed(2)">
|
| 118 |
+
</div>
|
| 119 |
+
</div>
|
| 120 |
+
|
| 121 |
+
<div id="params-torus" class="shape-params-group" style="display:none;">
|
| 122 |
+
<div class="slider-group">
|
| 123 |
+
<label>Major Radius: <span id="val-torus-major">0.40</span></label>
|
| 124 |
+
<input type="range" id="torus-major" min="0.2" max="0.8" step="0.05" value="0.40" oninput="document.getElementById('val-torus-major').innerText = parseFloat(this.value).toFixed(2)">
|
| 125 |
+
</div>
|
| 126 |
+
<div class="slider-group">
|
| 127 |
+
<label>Minor Radius: <span id="val-torus-minor">0.15</span></label>
|
| 128 |
+
<input type="range" id="torus-minor" min="0.05" max="0.3" step="0.01" value="0.15" oninput="document.getElementById('val-torus-minor').innerText = parseFloat(this.value).toFixed(2)">
|
| 129 |
+
</div>
|
| 130 |
+
</div>
|
| 131 |
+
</div>
|
| 132 |
+
|
| 133 |
+
<!-- Upload Tab -->
|
| 134 |
+
<div id="tab-upload" class="tab-content">
|
| 135 |
+
<div class="upload-area" id="drop-zone" onclick="document.getElementById('file-input').click()">
|
| 136 |
+
<svg class="upload-icon" viewBox="0 0 24 24"><path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/></svg>
|
| 137 |
+
<p>Drag & Drop watertight 3D STL file here or <span>browse</span></p>
|
| 138 |
+
<input type="file" id="file-input" name="file" accept=".stl" style="display:none;" onchange="handleFileSelect(this)">
|
| 139 |
+
<div id="file-info" class="file-info"></div>
|
| 140 |
+
</div>
|
| 141 |
+
</div>
|
| 142 |
+
|
| 143 |
+
<!-- PHYSICS & BOUNDARY CONDITIONS -->
|
| 144 |
+
<div class="section-card">
|
| 145 |
+
<h2>2. Physics & Flow Conditions</h2>
|
| 146 |
+
<div class="slider-group">
|
| 147 |
+
<label>Inlet velocity U∞ (m/s): <span id="val-uinf">1.0</span></label>
|
| 148 |
+
<input type="range" id="uinf" min="0.2" max="2.0" step="0.1" value="1.0" oninput="updatePhysics()">
|
| 149 |
+
</div>
|
| 150 |
+
<div class="slider-group">
|
| 151 |
+
<label>Dynamic viscosity μ (Pa·s): <span id="val-visc">0.00020</span></label>
|
| 152 |
+
<input type="range" id="viscosity" min="0.00001" max="0.002" step="0.00001" value="0.0002" oninput="updatePhysics()">
|
| 153 |
+
</div>
|
| 154 |
+
<div class="slider-group">
|
| 155 |
+
<label>Density ρ (kg/m³): <span id="val-density">1.0</span></label>
|
| 156 |
+
<input type="range" id="density" min="0.1" max="2.0" step="0.1" value="1.0" oninput="updatePhysics()">
|
| 157 |
+
</div>
|
| 158 |
+
<div class="slider-group">
|
| 159 |
+
<label>Yaw angle α (deg): <span id="val-yaw">0.0</span></label>
|
| 160 |
+
<input type="range" id="yaw_deg" name="yaw_deg" min="-20" max="20" step="1" value="0" oninput="document.getElementById('val-yaw').innerText = parseFloat(this.value).toFixed(1); updateInflowArrow();">
|
| 161 |
+
</div>
|
| 162 |
+
<div class="reynolds-info">
|
| 163 |
+
Reynolds number (Re): <strong id="calculated-re">5000</strong> <span style="opacity:.6">(trained 5×10² to 1×10⁵)</span>
|
| 164 |
+
</div>
|
| 165 |
+
</div>
|
| 166 |
+
|
| 167 |
+
<button type="submit" class="btn btn-predict" id="btn-submit">
|
| 168 |
+
<span class="btn-text">Predict Flow Field</span>
|
| 169 |
+
<div class="spinner" id="spinner"></div>
|
| 170 |
+
</button>
|
| 171 |
+
</form>
|
| 172 |
+
</div>
|
| 173 |
+
|
| 174 |
+
</section>
|
| 175 |
+
|
| 176 |
+
<!-- CENTER: 3D VIEWPORT -->
|
| 177 |
+
<section class="viewport-panel panel">
|
| 178 |
+
<div id="canvas-container">
|
| 179 |
+
<!-- Three.js render target -->
|
| 180 |
+
</div>
|
| 181 |
+
|
| 182 |
+
<!-- loading overlay + toast (inside the positioned viewport panel) -->
|
| 183 |
+
<div id="viewport-overlay" class="viewport-overlay" style="display:none;">
|
| 184 |
+
<div class="vo-spinner"></div>
|
| 185 |
+
<div id="viewport-overlay-text">Working...</div>
|
| 186 |
+
</div>
|
| 187 |
+
<div id="toast" class="toast" style="display:none;"></div>
|
| 188 |
+
|
| 189 |
+
<!-- (Display Settings & View Presets moved to the right sidebar) -->
|
| 190 |
+
|
| 191 |
+
<!-- FLOATING VIEWPORT TOOLBAR (SLICING CONTROLS) -->
|
| 192 |
+
<div class="viewport-toolbar glass">
|
| 193 |
+
<div class="toolbar-group">
|
| 194 |
+
<label for="slice_axis">Slice Normal</label>
|
| 195 |
+
<select id="slice_axis" onchange="onSliceParamsChanged()">
|
| 196 |
+
<option value="y" selected>Y-Axis (Symmetry Plane)</option>
|
| 197 |
+
<option value="z">Z-Axis (Horizontal Cut)</option>
|
| 198 |
+
<option value="x">X-Axis (Spanwise/Wake Cut)</option>
|
| 199 |
+
</select>
|
| 200 |
+
</div>
|
| 201 |
+
|
| 202 |
+
<div class="toolbar-group slider-wide">
|
| 203 |
+
<label>Plane Position: <span id="val-slice-pos">0.00</span></label>
|
| 204 |
+
<input type="range" id="slice_pos" min="-4.0" max="4.0" step="0.1" value="0.0" oninput="onSlicePosSliderInput(this.value)">
|
| 205 |
+
</div>
|
| 206 |
+
|
| 207 |
+
<div class="toolbar-group">
|
| 208 |
+
<label for="field_type">Visualize Field</label>
|
| 209 |
+
<select id="field_type" onchange="onSliceParamsChanged()">
|
| 210 |
+
<option value="velocity_mag" selected>Velocity |U|</option>
|
| 211 |
+
<option value="u">u (streamwise)</option>
|
| 212 |
+
<option value="v">v (lateral)</option>
|
| 213 |
+
<option value="w">w (vertical)</option>
|
| 214 |
+
<option value="pressure">Pressure p</option>
|
| 215 |
+
<option value="k">TKE k</option>
|
| 216 |
+
<option value="omega">ω (spec. dissipation)</option>
|
| 217 |
+
<option value="nut">ν_t (eddy viscosity)</option>
|
| 218 |
+
</select>
|
| 219 |
+
</div>
|
| 220 |
+
|
| 221 |
+
<div class="toolbar-group">
|
| 222 |
+
<button type="button" class="btn-preset" onclick="addSlice()">+ Add slice</button>
|
| 223 |
+
<button type="button" class="btn-preset" onclick="clearSlices()">Clear</button>
|
| 224 |
+
</div>
|
| 225 |
+
</div>
|
| 226 |
+
</section>
|
| 227 |
+
|
| 228 |
+
<!-- RIGHT SIDE: DISPLAY, LEGEND, QUERY, METADATA -->
|
| 229 |
+
<section class="metadata-panel panel">
|
| 230 |
+
|
| 231 |
+
<div class="section-card">
|
| 232 |
+
<h2>Display & View</h2>
|
| 233 |
+
<div class="option-row">
|
| 234 |
+
<label for="body_style">Body Style</label>
|
| 235 |
+
<select id="body_style" onchange="updateBodyRenderStyle()">
|
| 236 |
+
<option value="glass" selected>Glass Translucent</option>
|
| 237 |
+
<option value="wireframe">Wireframe</option>
|
| 238 |
+
<option value="hidden">Hidden</option>
|
| 239 |
+
</select>
|
| 240 |
+
</div>
|
| 241 |
+
<div class="option-row">
|
| 242 |
+
<label for="surface_field">Surface Color</label>
|
| 243 |
+
<select id="surface_field" onchange="updateBodySurface()">
|
| 244 |
+
<option value="none" selected>None (translucent)</option>
|
| 245 |
+
<option value="pressure">Pressure p</option>
|
| 246 |
+
<option value="velocity_mag">Velocity |U|</option>
|
| 247 |
+
<option value="k">Turb. energy k</option>
|
| 248 |
+
</select>
|
| 249 |
+
</div>
|
| 250 |
+
<div class="option-row">
|
| 251 |
+
<label for="projection">Projection</label>
|
| 252 |
+
<select id="projection" onchange="setProjection(this.value)">
|
| 253 |
+
<option value="perspective" selected>Perspective</option>
|
| 254 |
+
<option value="parallel">Parallel (ortho)</option>
|
| 255 |
+
</select>
|
| 256 |
+
</div>
|
| 257 |
+
<div class="option-row">
|
| 258 |
+
<label for="units_mode">Units</label>
|
| 259 |
+
<select id="units_mode" onchange="onUnitsChanged()">
|
| 260 |
+
<option value="nd" selected>Normalized (U∞=1)</option>
|
| 261 |
+
<option value="si">SI (m/s, Pa)</option>
|
| 262 |
+
</select>
|
| 263 |
+
</div>
|
| 264 |
+
<div class="option-row checkbox-row">
|
| 265 |
+
<input type="checkbox" id="show_tunnel" onchange="toggleTunnelBox(this.checked)">
|
| 266 |
+
<label for="show_tunnel">Wind Tunnel Box</label>
|
| 267 |
+
</div>
|
| 268 |
+
<div class="option-row checkbox-row">
|
| 269 |
+
<input type="checkbox" id="show_slice_grid" onchange="toggleSliceGrid(this.checked)">
|
| 270 |
+
<label for="show_slice_grid">Slice Grid Lines</label>
|
| 271 |
+
</div>
|
| 272 |
+
<div class="option-row checkbox-row">
|
| 273 |
+
<input type="checkbox" id="show_vectors" onchange="toggleVectors(this.checked)">
|
| 274 |
+
<label for="show_vectors">Show Flow Vectors</label>
|
| 275 |
+
</div>
|
| 276 |
+
<div class="option-row checkbox-row">
|
| 277 |
+
<input type="checkbox" id="show_streamlines" onchange="toggleStreamlines(this.checked)">
|
| 278 |
+
<label for="show_streamlines">Show Streamlines</label>
|
| 279 |
+
</div>
|
| 280 |
+
<div class="option-row checkbox-row">
|
| 281 |
+
<input type="checkbox" id="show_inflow" checked onchange="updateInflowArrow()">
|
| 282 |
+
<label for="show_inflow">Show Inflow Arrow</label>
|
| 283 |
+
</div>
|
| 284 |
+
<div class="preset-buttons" style="margin-top:12px;">
|
| 285 |
+
<button type="button" class="btn-preset" onclick="setViewPreset('perspective')">3D View</button>
|
| 286 |
+
<button type="button" class="btn-preset" onclick="setViewPreset('side')">Side (Y)</button>
|
| 287 |
+
<button type="button" class="btn-preset" onclick="setViewPreset('top')">Top (Z)</button>
|
| 288 |
+
<button type="button" class="btn-preset" onclick="setViewPreset('front')">Front (X)</button>
|
| 289 |
+
</div>
|
| 290 |
+
<button type="button" class="btn-preset" onclick="saveScreenshot()" style="width:100%;margin-top:8px;">Save screenshot (PNG)</button>
|
| 291 |
+
<button type="button" class="btn-preset" onclick="exportFields()" style="width:100%;margin-top:6px;">Export fields (CSV)</button>
|
| 292 |
+
</div>
|
| 293 |
+
|
| 294 |
+
<div class="section-card">
|
| 295 |
+
<h2>Extra Slices</h2>
|
| 296 |
+
<div id="slices-list"></div>
|
| 297 |
+
</div>
|
| 298 |
+
|
| 299 |
+
<div class="section-card">
|
| 300 |
+
<h2>3. Legend</h2>
|
| 301 |
+
<div class="legend-container">
|
| 302 |
+
<div class="legend-labels">
|
| 303 |
+
<span id="legend-max">1.50</span>
|
| 304 |
+
<span>Scale Max</span>
|
| 305 |
+
</div>
|
| 306 |
+
<div class="legend-color-bar"></div>
|
| 307 |
+
<div class="legend-labels">
|
| 308 |
+
<span id="legend-min">0.00</span>
|
| 309 |
+
<span>Scale Min</span>
|
| 310 |
+
</div>
|
| 311 |
+
<div class="legend-unit" id="legend-unit">m/s</div>
|
| 312 |
+
</div>
|
| 313 |
+
</div>
|
| 314 |
+
|
| 315 |
+
<div class="section-card">
|
| 316 |
+
<h2>4. Prediction Statistics</h2>
|
| 317 |
+
<div class="stats-list">
|
| 318 |
+
<div class="stat-item">
|
| 319 |
+
<span>Reference length (L<sub>ref</sub>):</span>
|
| 320 |
+
<span id="stat-lref">--</span>
|
| 321 |
+
</div>
|
| 322 |
+
<div class="stat-item">
|
| 323 |
+
<span>Frontal area (A<sub>ref</sub>):</span>
|
| 324 |
+
<span id="stat-aref">--</span>
|
| 325 |
+
</div>
|
| 326 |
+
<div class="stat-item">
|
| 327 |
+
<span>Mesh Nodes:</span>
|
| 328 |
+
<span id="stat-nodes">--</span>
|
| 329 |
+
</div>
|
| 330 |
+
<div class="stat-item">
|
| 331 |
+
<span>Pressure drag (C<sub>d</sub>):</span>
|
| 332 |
+
<span id="stat-cd" class="highlight-cyan">--</span>
|
| 333 |
+
</div>
|
| 334 |
+
<div class="stat-item">
|
| 335 |
+
<span>Lift (C<sub>l</sub>):</span>
|
| 336 |
+
<span id="stat-cl">--</span>
|
| 337 |
+
</div>
|
| 338 |
+
<div class="stat-item">
|
| 339 |
+
<span>Model parameters:</span>
|
| 340 |
+
<span id="stat-model-params">--</span>
|
| 341 |
+
</div>
|
| 342 |
+
<div class="stat-item">
|
| 343 |
+
<span>Model name:</span>
|
| 344 |
+
<span id="stat-model-name" class="code-font">HybridFlow</span>
|
| 345 |
+
</div>
|
| 346 |
+
<div class="stat-item">
|
| 347 |
+
<span>GNN Inference:</span>
|
| 348 |
+
<span id="stat-inference-device" class="highlight-cyan">CPU/GPU</span>
|
| 349 |
+
</div>
|
| 350 |
+
<div class="stat-item">
|
| 351 |
+
<span>Inference time:</span>
|
| 352 |
+
<span id="stat-timing" class="highlight-cyan">--</span>
|
| 353 |
+
</div>
|
| 354 |
+
</div>
|
| 355 |
+
</div>
|
| 356 |
+
|
| 357 |
+
<div class="section-card">
|
| 358 |
+
<h2>Point Query</h2>
|
| 359 |
+
<p id="probe-hint">Click any point in the 3D view to read all predicted values there
|
| 360 |
+
(and set it as the rotation pivot).</p>
|
| 361 |
+
<div id="probe-results" class="stats-list" style="display:none;"></div>
|
| 362 |
+
</div>
|
| 363 |
+
|
| 364 |
+
</section>
|
| 365 |
+
|
| 366 |
+
</main>
|
| 367 |
+
|
| 368 |
+
<script src="/static/app.js?v=12"></script>
|
| 369 |
+
</body>
|
| 370 |
+
</html>
|
code/ezflow_v3/app/frontend/style.css
ADDED
|
@@ -0,0 +1,673 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* EZFlow Standalone App Styling - Dark Mode Glassmorphism Theme */
|
| 2 |
+
|
| 3 |
+
:root {
|
| 4 |
+
--bg-color: #0b0d10;
|
| 5 |
+
--panel-bg: rgba(22, 26, 33, 0.85);
|
| 6 |
+
--panel-border: rgba(255, 255, 255, 0.06);
|
| 7 |
+
--text-main: #f0f3f8;
|
| 8 |
+
--text-muted: #8b99ae;
|
| 9 |
+
--accent-cyan: #00f0ff;
|
| 10 |
+
--accent-blue: #1b49aa;
|
| 11 |
+
--danger-red: #ff3e3e;
|
| 12 |
+
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
| 13 |
+
--shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
|
| 14 |
+
--radius: 12px;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
* {
|
| 18 |
+
box-sizing: border-box;
|
| 19 |
+
margin: 0;
|
| 20 |
+
padding: 0;
|
| 21 |
+
-webkit-font-smoothing: antialiased;
|
| 22 |
+
-moz-osx-font-smoothing: grayscale;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
body {
|
| 26 |
+
font-family: var(--font-family);
|
| 27 |
+
background-color: var(--bg-color);
|
| 28 |
+
color: var(--text-main);
|
| 29 |
+
height: 100vh;
|
| 30 |
+
display: flex;
|
| 31 |
+
flex-direction: column;
|
| 32 |
+
overflow: hidden;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/* HEADER styling */
|
| 36 |
+
.app-header {
|
| 37 |
+
height: 60px;
|
| 38 |
+
background-color: rgba(13, 16, 21, 0.95);
|
| 39 |
+
border-bottom: 1px solid var(--panel-border);
|
| 40 |
+
display: flex;
|
| 41 |
+
justify-content: space-between;
|
| 42 |
+
align-items: center;
|
| 43 |
+
padding: 0 24px;
|
| 44 |
+
z-index: 100;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
.logo {
|
| 48 |
+
font-weight: 700;
|
| 49 |
+
font-size: 1.25rem;
|
| 50 |
+
letter-spacing: 0.5px;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
.neon-text {
|
| 54 |
+
color: var(--accent-cyan);
|
| 55 |
+
text-shadow: 0 0 10px rgba(0, 240, 255, 0.35);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
.system-status {
|
| 59 |
+
font-size: 0.85rem;
|
| 60 |
+
color: var(--text-muted);
|
| 61 |
+
display: flex;
|
| 62 |
+
align-items: center;
|
| 63 |
+
gap: 8px;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
.status-indicator {
|
| 67 |
+
width: 8px;
|
| 68 |
+
height: 8px;
|
| 69 |
+
border-radius: 50%;
|
| 70 |
+
display: inline-block;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
.status-indicator.online {
|
| 74 |
+
background-color: #00e676;
|
| 75 |
+
box-shadow: 0 0 8px #00e676;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
.status-indicator.running {
|
| 79 |
+
background-color: #ffb300;
|
| 80 |
+
box-shadow: 0 0 8px #ffb300;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
.status-indicator.error {
|
| 84 |
+
background-color: var(--danger-red);
|
| 85 |
+
box-shadow: 0 0 8px var(--danger-red);
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/* APP LAYOUT */
|
| 89 |
+
.app-layout {
|
| 90 |
+
flex: 1;
|
| 91 |
+
display: flex;
|
| 92 |
+
padding: 16px;
|
| 93 |
+
gap: 16px;
|
| 94 |
+
height: calc(100vh - 60px);
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
.panel {
|
| 98 |
+
background: var(--panel-bg);
|
| 99 |
+
backdrop-filter: blur(12px);
|
| 100 |
+
-webkit-backdrop-filter: blur(12px);
|
| 101 |
+
border: 1px solid var(--panel-border);
|
| 102 |
+
border-radius: var(--radius);
|
| 103 |
+
box-shadow: var(--shadow);
|
| 104 |
+
display: flex;
|
| 105 |
+
flex-direction: column;
|
| 106 |
+
overflow: hidden;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
/* PANEL DIVISION */
|
| 110 |
+
.control-panel {
|
| 111 |
+
width: 380px;
|
| 112 |
+
padding: 20px;
|
| 113 |
+
overflow-y: auto;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
.viewport-panel {
|
| 117 |
+
flex: 1;
|
| 118 |
+
position: relative;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
.metadata-panel {
|
| 122 |
+
width: 320px;
|
| 123 |
+
padding: 20px;
|
| 124 |
+
gap: 20px;
|
| 125 |
+
overflow-y: auto;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
/* CARDS inside panels */
|
| 129 |
+
.section-card {
|
| 130 |
+
margin-bottom: 24px;
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
.section-card:last-child {
|
| 134 |
+
margin-bottom: 0;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
h2 {
|
| 138 |
+
font-size: 0.95rem;
|
| 139 |
+
text-transform: uppercase;
|
| 140 |
+
letter-spacing: 1px;
|
| 141 |
+
color: var(--text-muted);
|
| 142 |
+
margin-bottom: 16px;
|
| 143 |
+
font-weight: 600;
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
h3 {
|
| 147 |
+
font-size: 0.95rem;
|
| 148 |
+
color: var(--accent-cyan);
|
| 149 |
+
margin-bottom: 8px;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
p {
|
| 153 |
+
font-size: 0.85rem;
|
| 154 |
+
line-height: 1.5;
|
| 155 |
+
color: var(--text-muted);
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/* TABS */
|
| 159 |
+
.tabs {
|
| 160 |
+
display: flex;
|
| 161 |
+
background-color: rgba(0, 0, 0, 0.25);
|
| 162 |
+
border-radius: 8px;
|
| 163 |
+
padding: 4px;
|
| 164 |
+
margin-bottom: 16px;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
.tab-btn {
|
| 168 |
+
flex: 1;
|
| 169 |
+
background: none;
|
| 170 |
+
border: none;
|
| 171 |
+
color: var(--text-muted);
|
| 172 |
+
padding: 8px;
|
| 173 |
+
font-size: 0.85rem;
|
| 174 |
+
font-weight: 500;
|
| 175 |
+
cursor: pointer;
|
| 176 |
+
border-radius: 6px;
|
| 177 |
+
transition: all 0.2s ease;
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
.tab-btn.active {
|
| 181 |
+
background-color: var(--accent-blue);
|
| 182 |
+
color: var(--text-main);
|
| 183 |
+
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
.tab-content {
|
| 187 |
+
display: none;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
.tab-content.active {
|
| 191 |
+
display: block;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
/* FORMS & INPUTS */
|
| 195 |
+
.input-group {
|
| 196 |
+
margin-bottom: 16px;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
label {
|
| 200 |
+
display: block;
|
| 201 |
+
font-size: 0.85rem;
|
| 202 |
+
color: var(--text-main);
|
| 203 |
+
margin-bottom: 8px;
|
| 204 |
+
font-weight: 500;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
select {
|
| 208 |
+
width: 100%;
|
| 209 |
+
background-color: rgba(0, 0, 0, 0.3);
|
| 210 |
+
border: 1px solid var(--panel-border);
|
| 211 |
+
color: var(--text-main);
|
| 212 |
+
padding: 10px;
|
| 213 |
+
border-radius: 6px;
|
| 214 |
+
font-size: 0.9rem;
|
| 215 |
+
outline: none;
|
| 216 |
+
cursor: pointer;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
select:focus {
|
| 220 |
+
border-color: var(--accent-cyan);
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
/* SLIDERS */
|
| 224 |
+
.slider-group {
|
| 225 |
+
margin-bottom: 16px;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
.slider-group label {
|
| 229 |
+
display: flex;
|
| 230 |
+
justify-content: space-between;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
.slider-group label span {
|
| 234 |
+
color: var(--accent-cyan);
|
| 235 |
+
font-weight: 600;
|
| 236 |
+
font-family: monospace;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
input[type="range"] {
|
| 240 |
+
width: 100%;
|
| 241 |
+
-webkit-appearance: none;
|
| 242 |
+
background: rgba(255, 255, 255, 0.1);
|
| 243 |
+
height: 6px;
|
| 244 |
+
border-radius: 3px;
|
| 245 |
+
outline: none;
|
| 246 |
+
margin: 10px 0;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
input[type="range"]::-webkit-slider-thumb {
|
| 250 |
+
-webkit-appearance: none;
|
| 251 |
+
background: var(--accent-cyan);
|
| 252 |
+
width: 24px;
|
| 253 |
+
height: 24px;
|
| 254 |
+
border-radius: 50%;
|
| 255 |
+
cursor: pointer;
|
| 256 |
+
box-shadow: 0 0 10px var(--accent-cyan);
|
| 257 |
+
transition: transform 0.1s ease;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
input[type="range"]::-webkit-slider-thumb:hover {
|
| 261 |
+
transform: scale(1.15);
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
input[type="range"]::-moz-range-thumb {
|
| 265 |
+
background: var(--accent-cyan);
|
| 266 |
+
width: 24px;
|
| 267 |
+
height: 24px;
|
| 268 |
+
border-radius: 50%;
|
| 269 |
+
cursor: pointer;
|
| 270 |
+
box-shadow: 0 0 10px var(--accent-cyan);
|
| 271 |
+
transition: transform 0.1s ease;
|
| 272 |
+
border: none;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
input[type="range"]::-moz-range-thumb:hover {
|
| 276 |
+
transform: scale(1.15);
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
/* DRAG & DROP AREA */
|
| 280 |
+
.upload-area {
|
| 281 |
+
border: 2px dashed rgba(255, 255, 255, 0.15);
|
| 282 |
+
border-radius: 8px;
|
| 283 |
+
padding: 24px;
|
| 284 |
+
text-align: center;
|
| 285 |
+
cursor: pointer;
|
| 286 |
+
background-color: rgba(0, 0, 0, 0.15);
|
| 287 |
+
transition: border-color 0.2s ease;
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
.upload-area:hover {
|
| 291 |
+
border-color: var(--accent-cyan);
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
.upload-icon {
|
| 295 |
+
width: 48px;
|
| 296 |
+
height: 48px;
|
| 297 |
+
fill: var(--text-muted);
|
| 298 |
+
margin-bottom: 12px;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
.upload-area p {
|
| 302 |
+
font-size: 0.8rem;
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
.upload-area span {
|
| 306 |
+
color: var(--accent-cyan);
|
| 307 |
+
text-decoration: underline;
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
.file-info {
|
| 311 |
+
margin-top: 12px;
|
| 312 |
+
font-size: 0.8rem;
|
| 313 |
+
color: var(--accent-cyan);
|
| 314 |
+
font-weight: 500;
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
/* BUTTONS */
|
| 318 |
+
.btn {
|
| 319 |
+
width: 100%;
|
| 320 |
+
padding: 14px;
|
| 321 |
+
border: none;
|
| 322 |
+
border-radius: 8px;
|
| 323 |
+
font-size: 0.95rem;
|
| 324 |
+
font-weight: 600;
|
| 325 |
+
cursor: pointer;
|
| 326 |
+
display: flex;
|
| 327 |
+
justify-content: center;
|
| 328 |
+
align-items: center;
|
| 329 |
+
position: relative;
|
| 330 |
+
overflow: hidden;
|
| 331 |
+
transition: all 0.3s ease;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
.btn-predict {
|
| 335 |
+
background: linear-gradient(135deg, var(--accent-blue) 0%, #0d2c6c 100%);
|
| 336 |
+
color: var(--text-main);
|
| 337 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 338 |
+
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
.btn-predict:hover {
|
| 342 |
+
background: linear-gradient(135deg, var(--accent-cyan) 0%, var(--accent-blue) 100%);
|
| 343 |
+
color: #0b0d10;
|
| 344 |
+
box-shadow: 0 0 20px rgba(0, 240, 255, 0.4);
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
.btn-predict:active {
|
| 348 |
+
transform: scale(0.98);
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
.btn.loading .btn-text {
|
| 352 |
+
visibility: hidden;
|
| 353 |
+
opacity: 0;
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
.btn.loading .spinner {
|
| 357 |
+
display: block;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
.spinner {
|
| 361 |
+
display: none;
|
| 362 |
+
width: 24px;
|
| 363 |
+
height: 24px;
|
| 364 |
+
border: 3px solid rgba(255, 255, 255, 0.3);
|
| 365 |
+
border-radius: 50%;
|
| 366 |
+
border-top-color: var(--text-main);
|
| 367 |
+
animation: spin 1s ease-in-out infinite;
|
| 368 |
+
position: absolute;
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
@keyframes spin {
|
| 372 |
+
to { transform: rotate(360deg); }
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
.reynolds-info {
|
| 376 |
+
background-color: rgba(27, 73, 170, 0.25);
|
| 377 |
+
border: 1px solid rgba(27, 73, 170, 0.5);
|
| 378 |
+
border-radius: 6px;
|
| 379 |
+
padding: 10px;
|
| 380 |
+
text-align: center;
|
| 381 |
+
font-size: 0.85rem;
|
| 382 |
+
color: var(--text-main);
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
.reynolds-info strong {
|
| 386 |
+
color: var(--accent-cyan);
|
| 387 |
+
font-family: monospace;
|
| 388 |
+
font-size: 1rem;
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
/* VIEWPORT & FLOATING TOOLBAR */
|
| 392 |
+
#canvas-container {
|
| 393 |
+
width: 100%;
|
| 394 |
+
height: 100%;
|
| 395 |
+
background-color: #07090b;
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
.viewport-toolbar {
|
| 399 |
+
position: absolute;
|
| 400 |
+
bottom: 24px;
|
| 401 |
+
left: 50%;
|
| 402 |
+
transform: translateX(-50%);
|
| 403 |
+
display: flex;
|
| 404 |
+
gap: 24px;
|
| 405 |
+
padding: 12px 24px;
|
| 406 |
+
border-radius: 30px;
|
| 407 |
+
align-items: center;
|
| 408 |
+
z-index: 10;
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
.glass {
|
| 412 |
+
background: rgba(13, 16, 21, 0.85);
|
| 413 |
+
backdrop-filter: blur(16px);
|
| 414 |
+
-webkit-backdrop-filter: blur(16px);
|
| 415 |
+
border: 1px solid var(--panel-border);
|
| 416 |
+
box-shadow: var(--shadow);
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
.toolbar-group {
|
| 420 |
+
display: flex;
|
| 421 |
+
align-items: center;
|
| 422 |
+
gap: 12px;
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
.toolbar-group label {
|
| 426 |
+
margin-bottom: 0;
|
| 427 |
+
font-size: 0.8rem;
|
| 428 |
+
color: var(--text-muted);
|
| 429 |
+
white-space: nowrap;
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
.toolbar-group select {
|
| 433 |
+
padding: 6px 12px;
|
| 434 |
+
font-size: 0.8rem;
|
| 435 |
+
background-color: rgba(0, 0, 0, 0.4);
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
.slider-wide {
|
| 439 |
+
width: clamp(340px, 44vw, 680px);
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
/* bigger slice slider in the floating toolbar -> easier, finer dragging */
|
| 443 |
+
.viewport-toolbar input[type="range"] {
|
| 444 |
+
height: 10px;
|
| 445 |
+
}
|
| 446 |
+
.viewport-toolbar input[type="range"]::-webkit-slider-thumb {
|
| 447 |
+
width: 30px;
|
| 448 |
+
height: 30px;
|
| 449 |
+
}
|
| 450 |
+
.viewport-toolbar input[type="range"]::-moz-range-thumb {
|
| 451 |
+
width: 30px;
|
| 452 |
+
height: 30px;
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
/* LEGEND SCALE PANEL (RIGHT) */
|
| 456 |
+
.legend-container {
|
| 457 |
+
display: flex;
|
| 458 |
+
flex-direction: column;
|
| 459 |
+
align-items: center;
|
| 460 |
+
padding: 10px 0;
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
.legend-color-bar {
|
| 464 |
+
width: 25px;
|
| 465 |
+
height: 200px;
|
| 466 |
+
background: linear-gradient(to top,
|
| 467 |
+
#1a9850 0%,
|
| 468 |
+
#a6d96a 30%,
|
| 469 |
+
#f7e463 50%,
|
| 470 |
+
#fdae61 70%,
|
| 471 |
+
#d73027 100%
|
| 472 |
+
);
|
| 473 |
+
border-radius: 4px;
|
| 474 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 475 |
+
margin: 10px 0;
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
.legend-labels {
|
| 479 |
+
display: flex;
|
| 480 |
+
width: 100%;
|
| 481 |
+
justify-content: space-between;
|
| 482 |
+
font-size: 0.85rem;
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
.legend-labels span:first-child {
|
| 486 |
+
font-family: monospace;
|
| 487 |
+
font-weight: 600;
|
| 488 |
+
color: var(--accent-cyan);
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
.legend-unit {
|
| 492 |
+
font-size: 0.8rem;
|
| 493 |
+
color: var(--text-muted);
|
| 494 |
+
font-weight: 500;
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
/* METADATA STATS LIST */
|
| 498 |
+
.stats-list {
|
| 499 |
+
display: flex;
|
| 500 |
+
flex-direction: column;
|
| 501 |
+
gap: 12px;
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
.stat-item {
|
| 505 |
+
display: flex;
|
| 506 |
+
justify-content: space-between;
|
| 507 |
+
font-size: 0.85rem;
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
.stat-item span:first-child {
|
| 511 |
+
color: var(--text-muted);
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
.stat-item span:last-child {
|
| 515 |
+
font-weight: 500;
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
.highlight-cyan {
|
| 519 |
+
color: var(--accent-cyan);
|
| 520 |
+
font-weight: 600 !important;
|
| 521 |
+
text-shadow: 0 0 8px rgba(0, 240, 255, 0.2);
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
.code-font {
|
| 525 |
+
font-family: monospace;
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
.info-box {
|
| 529 |
+
background-color: rgba(0, 240, 255, 0.04);
|
| 530 |
+
border: 1px solid rgba(0, 240, 255, 0.15);
|
| 531 |
+
border-radius: 8px;
|
| 532 |
+
padding: 16px;
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
/* FLOATING OPTIONS CARD (TOP RIGHT) */
|
| 536 |
+
.viewport-options {
|
| 537 |
+
position: absolute;
|
| 538 |
+
top: 20px;
|
| 539 |
+
right: 20px;
|
| 540 |
+
padding: 16px;
|
| 541 |
+
border-radius: var(--radius);
|
| 542 |
+
width: 240px;
|
| 543 |
+
z-index: 10;
|
| 544 |
+
display: flex;
|
| 545 |
+
flex-direction: column;
|
| 546 |
+
gap: 16px;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
.options-section h3 {
|
| 550 |
+
font-size: 0.75rem;
|
| 551 |
+
text-transform: uppercase;
|
| 552 |
+
letter-spacing: 0.5px;
|
| 553 |
+
color: var(--text-muted);
|
| 554 |
+
margin-bottom: 10px;
|
| 555 |
+
font-weight: 600;
|
| 556 |
+
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
| 557 |
+
padding-bottom: 4px;
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
.option-row {
|
| 561 |
+
display: flex;
|
| 562 |
+
justify-content: space-between;
|
| 563 |
+
align-items: center;
|
| 564 |
+
margin-bottom: 8px;
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
.option-row:last-child {
|
| 568 |
+
margin-bottom: 0;
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
.option-row label {
|
| 572 |
+
font-size: 0.8rem;
|
| 573 |
+
color: var(--text-muted);
|
| 574 |
+
margin-bottom: 0;
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
.option-row select {
|
| 578 |
+
width: 120px;
|
| 579 |
+
padding: 4px 8px;
|
| 580 |
+
font-size: 0.8rem;
|
| 581 |
+
background-color: rgba(0, 0, 0, 0.4);
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
.checkbox-row {
|
| 585 |
+
justify-content: flex-start;
|
| 586 |
+
gap: 10px;
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
.checkbox-row input[type="checkbox"] {
|
| 590 |
+
accent-color: var(--accent-cyan);
|
| 591 |
+
cursor: pointer;
|
| 592 |
+
width: 14px;
|
| 593 |
+
height: 14px;
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
.checkbox-row label {
|
| 597 |
+
cursor: pointer;
|
| 598 |
+
user-select: none;
|
| 599 |
+
font-size: 0.8rem;
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
.preset-buttons {
|
| 603 |
+
display: grid;
|
| 604 |
+
grid-template-columns: 1fr 1fr;
|
| 605 |
+
gap: 6px;
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
.btn-preset {
|
| 609 |
+
background-color: rgba(255, 255, 255, 0.05);
|
| 610 |
+
border: 1px solid var(--panel-border);
|
| 611 |
+
color: var(--text-main);
|
| 612 |
+
padding: 6px 4px;
|
| 613 |
+
font-size: 0.75rem;
|
| 614 |
+
border-radius: 4px;
|
| 615 |
+
cursor: pointer;
|
| 616 |
+
font-weight: 500;
|
| 617 |
+
transition: all 0.2s ease;
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
.btn-preset:hover {
|
| 621 |
+
background-color: var(--accent-blue);
|
| 622 |
+
border-color: var(--accent-cyan);
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
/* (6) light adaptiveness to monitor size: scale rem fonts + panel widths */
|
| 626 |
+
@media (max-width: 1500px) {
|
| 627 |
+
html { font-size: 15px; }
|
| 628 |
+
.control-panel { width: 340px; }
|
| 629 |
+
.metadata-panel { width: 300px; }
|
| 630 |
+
}
|
| 631 |
+
@media (max-width: 1200px) {
|
| 632 |
+
html { font-size: 14px; }
|
| 633 |
+
.control-panel { width: 300px; padding: 14px; }
|
| 634 |
+
.metadata-panel { width: 270px; padding: 14px; }
|
| 635 |
+
.app-layout { gap: 10px; padding: 10px; }
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
/* viewport loading overlay */
|
| 639 |
+
.viewport-overlay {
|
| 640 |
+
position: absolute; inset: 0; z-index: 20;
|
| 641 |
+
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
| 642 |
+
gap: 18px; text-align: center; padding: 24px;
|
| 643 |
+
background: rgba(7, 9, 11, 0.55); backdrop-filter: blur(2px);
|
| 644 |
+
color: var(--text-main); font-size: 0.95rem;
|
| 645 |
+
}
|
| 646 |
+
.vo-spinner {
|
| 647 |
+
width: 46px; height: 46px; border-radius: 50%;
|
| 648 |
+
border: 4px solid rgba(0, 240, 255, 0.2); border-top-color: var(--accent-cyan);
|
| 649 |
+
animation: spin 0.9s linear infinite;
|
| 650 |
+
}
|
| 651 |
+
#viewport-overlay-text { max-width: 460px; line-height: 1.5; color: var(--text-muted); }
|
| 652 |
+
|
| 653 |
+
/* toast (transient status / error message over the viewport) */
|
| 654 |
+
.toast {
|
| 655 |
+
position: absolute; bottom: 92px; left: 50%; transform: translateX(-50%);
|
| 656 |
+
z-index: 30; max-width: 72%; padding: 12px 18px; border-radius: 8px;
|
| 657 |
+
background: rgba(13, 16, 21, 0.96); border: 1px solid var(--panel-border);
|
| 658 |
+
color: var(--text-main); font-size: 0.85rem; box-shadow: var(--shadow);
|
| 659 |
+
}
|
| 660 |
+
.toast-error { border-color: var(--danger-red); color: #ffd9d9; }
|
| 661 |
+
|
| 662 |
+
/* drag-over highlight on the upload area */
|
| 663 |
+
.upload-area.hover { border-color: var(--accent-cyan); background: rgba(0, 240, 255, 0.06); }
|
| 664 |
+
|
| 665 |
+
/* extra movable slices list (right panel) */
|
| 666 |
+
.slice-row { border-top: 1px solid var(--panel-border); padding-top: 10px; margin-top: 10px; }
|
| 667 |
+
.slice-row:first-child { border-top: none; padding-top: 0; margin-top: 0; }
|
| 668 |
+
.slice-row-head { display: flex; justify-content: space-between; align-items: center;
|
| 669 |
+
font-size: 0.82rem; color: var(--text-main); font-weight: 500; }
|
| 670 |
+
.slice-x { background: none; border: none; color: var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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
( function () {
|
| 2 |
+
|
| 3 |
+
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
|
| 4 |
+
//
|
| 5 |
+
// Orbit - left mouse / touch: one-finger move
|
| 6 |
+
// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
|
| 7 |
+
// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
|
| 8 |
+
|
| 9 |
+
const _changeEvent = {
|
| 10 |
+
type: 'change'
|
| 11 |
+
};
|
| 12 |
+
const _startEvent = {
|
| 13 |
+
type: 'start'
|
| 14 |
+
};
|
| 15 |
+
const _endEvent = {
|
| 16 |
+
type: 'end'
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
class OrbitControls extends THREE.EventDispatcher {
|
| 20 |
+
|
| 21 |
+
constructor( object, domElement ) {
|
| 22 |
+
|
| 23 |
+
super();
|
| 24 |
+
if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' );
|
| 25 |
+
if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
|
| 26 |
+
this.object = object;
|
| 27 |
+
this.domElement = domElement; // Set to false to disable this control
|
| 28 |
+
|
| 29 |
+
this.enabled = true; // "target" sets the location of focus, where the object orbits around
|
| 30 |
+
|
| 31 |
+
this.target = new THREE.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
|
| 32 |
+
|
| 33 |
+
this.minDistance = 0;
|
| 34 |
+
this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
|
| 35 |
+
|
| 36 |
+
this.minZoom = 0;
|
| 37 |
+
this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
|
| 38 |
+
// Range is 0 to Math.PI radians.
|
| 39 |
+
|
| 40 |
+
this.minPolarAngle = 0; // radians
|
| 41 |
+
|
| 42 |
+
this.maxPolarAngle = Math.PI; // radians
|
| 43 |
+
// How far you can orbit horizontally, upper and lower limits.
|
| 44 |
+
// If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
|
| 45 |
+
|
| 46 |
+
this.minAzimuthAngle = - Infinity; // radians
|
| 47 |
+
|
| 48 |
+
this.maxAzimuthAngle = Infinity; // radians
|
| 49 |
+
// Set to true to enable damping (inertia)
|
| 50 |
+
// If damping is enabled, you must call controls.update() in your animation loop
|
| 51 |
+
|
| 52 |
+
this.enableDamping = false;
|
| 53 |
+
this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
|
| 54 |
+
// Set to false to disable zooming
|
| 55 |
+
|
| 56 |
+
this.enableZoom = true;
|
| 57 |
+
this.zoomSpeed = 1.0; // Set to false to disable rotating
|
| 58 |
+
|
| 59 |
+
this.enableRotate = true;
|
| 60 |
+
this.rotateSpeed = 1.0; // Set to false to disable panning
|
| 61 |
+
|
| 62 |
+
this.enablePan = true;
|
| 63 |
+
this.panSpeed = 1.0;
|
| 64 |
+
this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
|
| 65 |
+
|
| 66 |
+
this.keyPanSpeed = 7.0; // pixels moved per arrow key push
|
| 67 |
+
// Set to true to automatically rotate around the target
|
| 68 |
+
// If auto-rotate is enabled, you must call controls.update() in your animation loop
|
| 69 |
+
|
| 70 |
+
this.autoRotate = false;
|
| 71 |
+
this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
|
| 72 |
+
// The four arrow keys
|
| 73 |
+
|
| 74 |
+
this.keys = {
|
| 75 |
+
LEFT: 'ArrowLeft',
|
| 76 |
+
UP: 'ArrowUp',
|
| 77 |
+
RIGHT: 'ArrowRight',
|
| 78 |
+
BOTTOM: 'ArrowDown'
|
| 79 |
+
}; // Mouse buttons
|
| 80 |
+
|
| 81 |
+
this.mouseButtons = {
|
| 82 |
+
LEFT: THREE.MOUSE.ROTATE,
|
| 83 |
+
MIDDLE: THREE.MOUSE.DOLLY,
|
| 84 |
+
RIGHT: THREE.MOUSE.PAN
|
| 85 |
+
}; // Touch fingers
|
| 86 |
+
|
| 87 |
+
this.touches = {
|
| 88 |
+
ONE: THREE.TOUCH.ROTATE,
|
| 89 |
+
TWO: THREE.TOUCH.DOLLY_PAN
|
| 90 |
+
}; // for reset
|
| 91 |
+
|
| 92 |
+
this.target0 = this.target.clone();
|
| 93 |
+
this.position0 = this.object.position.clone();
|
| 94 |
+
this.zoom0 = this.object.zoom; // the target DOM element for key events
|
| 95 |
+
|
| 96 |
+
this._domElementKeyEvents = null; //
|
| 97 |
+
// public methods
|
| 98 |
+
//
|
| 99 |
+
|
| 100 |
+
this.getPolarAngle = function () {
|
| 101 |
+
|
| 102 |
+
return spherical.phi;
|
| 103 |
+
|
| 104 |
+
};
|
| 105 |
+
|
| 106 |
+
this.getAzimuthalAngle = function () {
|
| 107 |
+
|
| 108 |
+
return spherical.theta;
|
| 109 |
+
|
| 110 |
+
};
|
| 111 |
+
|
| 112 |
+
this.listenToKeyEvents = function ( domElement ) {
|
| 113 |
+
|
| 114 |
+
domElement.addEventListener( 'keydown', onKeyDown );
|
| 115 |
+
this._domElementKeyEvents = domElement;
|
| 116 |
+
|
| 117 |
+
};
|
| 118 |
+
|
| 119 |
+
this.saveState = function () {
|
| 120 |
+
|
| 121 |
+
scope.target0.copy( scope.target );
|
| 122 |
+
scope.position0.copy( scope.object.position );
|
| 123 |
+
scope.zoom0 = scope.object.zoom;
|
| 124 |
+
|
| 125 |
+
};
|
| 126 |
+
|
| 127 |
+
this.reset = function () {
|
| 128 |
+
|
| 129 |
+
scope.target.copy( scope.target0 );
|
| 130 |
+
scope.object.position.copy( scope.position0 );
|
| 131 |
+
scope.object.zoom = scope.zoom0;
|
| 132 |
+
scope.object.updateProjectionMatrix();
|
| 133 |
+
scope.dispatchEvent( _changeEvent );
|
| 134 |
+
scope.update();
|
| 135 |
+
state = STATE.NONE;
|
| 136 |
+
|
| 137 |
+
}; // this method is exposed, but perhaps it would be better if we can make it private...
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
this.update = function () {
|
| 141 |
+
|
| 142 |
+
const offset = new THREE.Vector3(); // so camera.up is the orbit axis
|
| 143 |
+
|
| 144 |
+
const quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
|
| 145 |
+
const quatInverse = quat.clone().invert();
|
| 146 |
+
const lastPosition = new THREE.Vector3();
|
| 147 |
+
const lastQuaternion = new THREE.Quaternion();
|
| 148 |
+
const twoPI = 2 * Math.PI;
|
| 149 |
+
return function update() {
|
| 150 |
+
|
| 151 |
+
const position = scope.object.position;
|
| 152 |
+
offset.copy( position ).sub( scope.target ); // rotate offset to "y-axis-is-up" space
|
| 153 |
+
|
| 154 |
+
offset.applyQuaternion( quat ); // angle from z-axis around y-axis
|
| 155 |
+
|
| 156 |
+
spherical.setFromVector3( offset );
|
| 157 |
+
|
| 158 |
+
if ( scope.autoRotate && state === STATE.NONE ) {
|
| 159 |
+
|
| 160 |
+
rotateLeft( getAutoRotationAngle() );
|
| 161 |
+
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
if ( scope.enableDamping ) {
|
| 165 |
+
|
| 166 |
+
spherical.theta += sphericalDelta.theta * scope.dampingFactor;
|
| 167 |
+
spherical.phi += sphericalDelta.phi * scope.dampingFactor;
|
| 168 |
+
|
| 169 |
+
} else {
|
| 170 |
+
|
| 171 |
+
spherical.theta += sphericalDelta.theta;
|
| 172 |
+
spherical.phi += sphericalDelta.phi;
|
| 173 |
+
|
| 174 |
+
} // restrict theta to be between desired limits
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
let min = scope.minAzimuthAngle;
|
| 178 |
+
let max = scope.maxAzimuthAngle;
|
| 179 |
+
|
| 180 |
+
if ( isFinite( min ) && isFinite( max ) ) {
|
| 181 |
+
|
| 182 |
+
if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
|
| 183 |
+
if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
|
| 184 |
+
|
| 185 |
+
if ( min <= max ) {
|
| 186 |
+
|
| 187 |
+
spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
|
| 188 |
+
|
| 189 |
+
} else {
|
| 190 |
+
|
| 191 |
+
spherical.theta = spherical.theta > ( min + max ) / 2 ? Math.max( min, spherical.theta ) : Math.min( max, spherical.theta );
|
| 192 |
+
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
} // restrict phi to be between desired limits
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
|
| 199 |
+
spherical.makeSafe();
|
| 200 |
+
spherical.radius *= scale; // restrict radius to be between desired limits
|
| 201 |
+
|
| 202 |
+
spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); // move target to panned location
|
| 203 |
+
|
| 204 |
+
if ( scope.enableDamping === true ) {
|
| 205 |
+
|
| 206 |
+
scope.target.addScaledVector( panOffset, scope.dampingFactor );
|
| 207 |
+
|
| 208 |
+
} else {
|
| 209 |
+
|
| 210 |
+
scope.target.add( panOffset );
|
| 211 |
+
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
offset.setFromSpherical( spherical ); // rotate offset back to "camera-up-vector-is-up" space
|
| 215 |
+
|
| 216 |
+
offset.applyQuaternion( quatInverse );
|
| 217 |
+
position.copy( scope.target ).add( offset );
|
| 218 |
+
scope.object.lookAt( scope.target );
|
| 219 |
+
|
| 220 |
+
if ( scope.enableDamping === true ) {
|
| 221 |
+
|
| 222 |
+
sphericalDelta.theta *= 1 - scope.dampingFactor;
|
| 223 |
+
sphericalDelta.phi *= 1 - scope.dampingFactor;
|
| 224 |
+
panOffset.multiplyScalar( 1 - scope.dampingFactor );
|
| 225 |
+
|
| 226 |
+
} else {
|
| 227 |
+
|
| 228 |
+
sphericalDelta.set( 0, 0, 0 );
|
| 229 |
+
panOffset.set( 0, 0, 0 );
|
| 230 |
+
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
scale = 1; // update condition is:
|
| 234 |
+
// min(camera displacement, camera rotation in radians)^2 > EPS
|
| 235 |
+
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
|
| 236 |
+
|
| 237 |
+
if ( zoomChanged || lastPosition.distanceToSquared( scope.object.position ) > EPS || 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
|
| 238 |
+
|
| 239 |
+
scope.dispatchEvent( _changeEvent );
|
| 240 |
+
lastPosition.copy( scope.object.position );
|
| 241 |
+
lastQuaternion.copy( scope.object.quaternion );
|
| 242 |
+
zoomChanged = false;
|
| 243 |
+
return true;
|
| 244 |
+
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
return false;
|
| 248 |
+
|
| 249 |
+
};
|
| 250 |
+
|
| 251 |
+
}();
|
| 252 |
+
|
| 253 |
+
this.dispose = function () {
|
| 254 |
+
|
| 255 |
+
scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
|
| 256 |
+
scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
|
| 257 |
+
scope.domElement.removeEventListener( 'wheel', onMouseWheel );
|
| 258 |
+
scope.domElement.removeEventListener( 'touchstart', onTouchStart );
|
| 259 |
+
scope.domElement.removeEventListener( 'touchend', onTouchEnd );
|
| 260 |
+
scope.domElement.removeEventListener( 'touchmove', onTouchMove );
|
| 261 |
+
scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
|
| 262 |
+
scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
|
| 263 |
+
|
| 264 |
+
if ( scope._domElementKeyEvents !== null ) {
|
| 265 |
+
|
| 266 |
+
scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
|
| 267 |
+
|
| 268 |
+
} //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
|
| 269 |
+
|
| 270 |
+
}; //
|
| 271 |
+
// internals
|
| 272 |
+
//
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
const scope = this;
|
| 276 |
+
const STATE = {
|
| 277 |
+
NONE: - 1,
|
| 278 |
+
ROTATE: 0,
|
| 279 |
+
DOLLY: 1,
|
| 280 |
+
PAN: 2,
|
| 281 |
+
TOUCH_ROTATE: 3,
|
| 282 |
+
TOUCH_PAN: 4,
|
| 283 |
+
TOUCH_DOLLY_PAN: 5,
|
| 284 |
+
TOUCH_DOLLY_ROTATE: 6
|
| 285 |
+
};
|
| 286 |
+
let state = STATE.NONE;
|
| 287 |
+
const EPS = 0.000001; // current position in spherical coordinates
|
| 288 |
+
|
| 289 |
+
const spherical = new THREE.Spherical();
|
| 290 |
+
const sphericalDelta = new THREE.Spherical();
|
| 291 |
+
let scale = 1;
|
| 292 |
+
const panOffset = new THREE.Vector3();
|
| 293 |
+
let zoomChanged = false;
|
| 294 |
+
const rotateStart = new THREE.Vector2();
|
| 295 |
+
const rotateEnd = new THREE.Vector2();
|
| 296 |
+
const rotateDelta = new THREE.Vector2();
|
| 297 |
+
const panStart = new THREE.Vector2();
|
| 298 |
+
const panEnd = new THREE.Vector2();
|
| 299 |
+
const panDelta = new THREE.Vector2();
|
| 300 |
+
const dollyStart = new THREE.Vector2();
|
| 301 |
+
const dollyEnd = new THREE.Vector2();
|
| 302 |
+
const dollyDelta = new THREE.Vector2();
|
| 303 |
+
|
| 304 |
+
function getAutoRotationAngle() {
|
| 305 |
+
|
| 306 |
+
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
|
| 307 |
+
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
function getZoomScale() {
|
| 311 |
+
|
| 312 |
+
return Math.pow( 0.95, scope.zoomSpeed );
|
| 313 |
+
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
function rotateLeft( angle ) {
|
| 317 |
+
|
| 318 |
+
sphericalDelta.theta -= angle;
|
| 319 |
+
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
function rotateUp( angle ) {
|
| 323 |
+
|
| 324 |
+
sphericalDelta.phi -= angle;
|
| 325 |
+
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
const panLeft = function () {
|
| 329 |
+
|
| 330 |
+
const v = new THREE.Vector3();
|
| 331 |
+
return function panLeft( distance, objectMatrix ) {
|
| 332 |
+
|
| 333 |
+
v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
|
| 334 |
+
|
| 335 |
+
v.multiplyScalar( - distance );
|
| 336 |
+
panOffset.add( v );
|
| 337 |
+
|
| 338 |
+
};
|
| 339 |
+
|
| 340 |
+
}();
|
| 341 |
+
|
| 342 |
+
const panUp = function () {
|
| 343 |
+
|
| 344 |
+
const v = new THREE.Vector3();
|
| 345 |
+
return function panUp( distance, objectMatrix ) {
|
| 346 |
+
|
| 347 |
+
if ( scope.screenSpacePanning === true ) {
|
| 348 |
+
|
| 349 |
+
v.setFromMatrixColumn( objectMatrix, 1 );
|
| 350 |
+
|
| 351 |
+
} else {
|
| 352 |
+
|
| 353 |
+
v.setFromMatrixColumn( objectMatrix, 0 );
|
| 354 |
+
v.crossVectors( scope.object.up, v );
|
| 355 |
+
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
v.multiplyScalar( distance );
|
| 359 |
+
panOffset.add( v );
|
| 360 |
+
|
| 361 |
+
};
|
| 362 |
+
|
| 363 |
+
}(); // deltaX and deltaY are in pixels; right and down are positive
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
const pan = function () {
|
| 367 |
+
|
| 368 |
+
const offset = new THREE.Vector3();
|
| 369 |
+
return function pan( deltaX, deltaY ) {
|
| 370 |
+
|
| 371 |
+
const element = scope.domElement;
|
| 372 |
+
|
| 373 |
+
if ( scope.object.isPerspectiveCamera ) {
|
| 374 |
+
|
| 375 |
+
// perspective
|
| 376 |
+
const position = scope.object.position;
|
| 377 |
+
offset.copy( position ).sub( scope.target );
|
| 378 |
+
let targetDistance = offset.length(); // half of the fov is center to top of screen
|
| 379 |
+
|
| 380 |
+
targetDistance *= Math.tan( scope.object.fov / 2 * Math.PI / 180.0 ); // we use only clientHeight here so aspect ratio does not distort speed
|
| 381 |
+
|
| 382 |
+
panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
|
| 383 |
+
panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
|
| 384 |
+
|
| 385 |
+
} else if ( scope.object.isOrthographicCamera ) {
|
| 386 |
+
|
| 387 |
+
// orthographic
|
| 388 |
+
panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
|
| 389 |
+
panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
|
| 390 |
+
|
| 391 |
+
} else {
|
| 392 |
+
|
| 393 |
+
// camera neither orthographic nor perspective
|
| 394 |
+
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
|
| 395 |
+
scope.enablePan = false;
|
| 396 |
+
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
};
|
| 400 |
+
|
| 401 |
+
}();
|
| 402 |
+
|
| 403 |
+
function dollyOut( dollyScale ) {
|
| 404 |
+
|
| 405 |
+
if ( scope.object.isPerspectiveCamera ) {
|
| 406 |
+
|
| 407 |
+
scale /= dollyScale;
|
| 408 |
+
|
| 409 |
+
} else if ( scope.object.isOrthographicCamera ) {
|
| 410 |
+
|
| 411 |
+
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
|
| 412 |
+
scope.object.updateProjectionMatrix();
|
| 413 |
+
zoomChanged = true;
|
| 414 |
+
|
| 415 |
+
} else {
|
| 416 |
+
|
| 417 |
+
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
|
| 418 |
+
scope.enableZoom = false;
|
| 419 |
+
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
function dollyIn( dollyScale ) {
|
| 425 |
+
|
| 426 |
+
if ( scope.object.isPerspectiveCamera ) {
|
| 427 |
+
|
| 428 |
+
scale *= dollyScale;
|
| 429 |
+
|
| 430 |
+
} else if ( scope.object.isOrthographicCamera ) {
|
| 431 |
+
|
| 432 |
+
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
|
| 433 |
+
scope.object.updateProjectionMatrix();
|
| 434 |
+
zoomChanged = true;
|
| 435 |
+
|
| 436 |
+
} else {
|
| 437 |
+
|
| 438 |
+
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
|
| 439 |
+
scope.enableZoom = false;
|
| 440 |
+
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
} //
|
| 444 |
+
// event callbacks - update the object state
|
| 445 |
+
//
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
function handleMouseDownRotate( event ) {
|
| 449 |
+
|
| 450 |
+
rotateStart.set( event.clientX, event.clientY );
|
| 451 |
+
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
function handleMouseDownDolly( event ) {
|
| 455 |
+
|
| 456 |
+
dollyStart.set( event.clientX, event.clientY );
|
| 457 |
+
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
function handleMouseDownPan( event ) {
|
| 461 |
+
|
| 462 |
+
panStart.set( event.clientX, event.clientY );
|
| 463 |
+
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
function handleMouseMoveRotate( event ) {
|
| 467 |
+
|
| 468 |
+
rotateEnd.set( event.clientX, event.clientY );
|
| 469 |
+
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
|
| 470 |
+
const element = scope.domElement;
|
| 471 |
+
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
|
| 472 |
+
|
| 473 |
+
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
|
| 474 |
+
rotateStart.copy( rotateEnd );
|
| 475 |
+
scope.update();
|
| 476 |
+
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
function handleMouseMoveDolly( event ) {
|
| 480 |
+
|
| 481 |
+
dollyEnd.set( event.clientX, event.clientY );
|
| 482 |
+
dollyDelta.subVectors( dollyEnd, dollyStart );
|
| 483 |
+
|
| 484 |
+
if ( dollyDelta.y > 0 ) {
|
| 485 |
+
|
| 486 |
+
dollyOut( getZoomScale() );
|
| 487 |
+
|
| 488 |
+
} else if ( dollyDelta.y < 0 ) {
|
| 489 |
+
|
| 490 |
+
dollyIn( getZoomScale() );
|
| 491 |
+
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
dollyStart.copy( dollyEnd );
|
| 495 |
+
scope.update();
|
| 496 |
+
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
function handleMouseMovePan( event ) {
|
| 500 |
+
|
| 501 |
+
panEnd.set( event.clientX, event.clientY );
|
| 502 |
+
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
|
| 503 |
+
pan( panDelta.x, panDelta.y );
|
| 504 |
+
panStart.copy( panEnd );
|
| 505 |
+
scope.update();
|
| 506 |
+
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
function handleMouseUp( ) { // no-op
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
function handleMouseWheel( event ) {
|
| 513 |
+
|
| 514 |
+
if ( event.deltaY < 0 ) {
|
| 515 |
+
|
| 516 |
+
dollyIn( getZoomScale() );
|
| 517 |
+
|
| 518 |
+
} else if ( event.deltaY > 0 ) {
|
| 519 |
+
|
| 520 |
+
dollyOut( getZoomScale() );
|
| 521 |
+
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
scope.update();
|
| 525 |
+
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
function handleKeyDown( event ) {
|
| 529 |
+
|
| 530 |
+
let needsUpdate = false;
|
| 531 |
+
|
| 532 |
+
switch ( event.code ) {
|
| 533 |
+
|
| 534 |
+
case scope.keys.UP:
|
| 535 |
+
pan( 0, scope.keyPanSpeed );
|
| 536 |
+
needsUpdate = true;
|
| 537 |
+
break;
|
| 538 |
+
|
| 539 |
+
case scope.keys.BOTTOM:
|
| 540 |
+
pan( 0, - scope.keyPanSpeed );
|
| 541 |
+
needsUpdate = true;
|
| 542 |
+
break;
|
| 543 |
+
|
| 544 |
+
case scope.keys.LEFT:
|
| 545 |
+
pan( scope.keyPanSpeed, 0 );
|
| 546 |
+
needsUpdate = true;
|
| 547 |
+
break;
|
| 548 |
+
|
| 549 |
+
case scope.keys.RIGHT:
|
| 550 |
+
pan( - scope.keyPanSpeed, 0 );
|
| 551 |
+
needsUpdate = true;
|
| 552 |
+
break;
|
| 553 |
+
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
if ( needsUpdate ) {
|
| 557 |
+
|
| 558 |
+
// prevent the browser from scrolling on cursor keys
|
| 559 |
+
event.preventDefault();
|
| 560 |
+
scope.update();
|
| 561 |
+
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
function handleTouchStartRotate( event ) {
|
| 567 |
+
|
| 568 |
+
if ( event.touches.length == 1 ) {
|
| 569 |
+
|
| 570 |
+
rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
|
| 571 |
+
|
| 572 |
+
} else {
|
| 573 |
+
|
| 574 |
+
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
|
| 575 |
+
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
|
| 576 |
+
rotateStart.set( x, y );
|
| 577 |
+
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
function handleTouchStartPan( event ) {
|
| 583 |
+
|
| 584 |
+
if ( event.touches.length == 1 ) {
|
| 585 |
+
|
| 586 |
+
panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
|
| 587 |
+
|
| 588 |
+
} else {
|
| 589 |
+
|
| 590 |
+
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
|
| 591 |
+
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
|
| 592 |
+
panStart.set( x, y );
|
| 593 |
+
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
function handleTouchStartDolly( event ) {
|
| 599 |
+
|
| 600 |
+
const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
|
| 601 |
+
const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
|
| 602 |
+
const distance = Math.sqrt( dx * dx + dy * dy );
|
| 603 |
+
dollyStart.set( 0, distance );
|
| 604 |
+
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
function handleTouchStartDollyPan( event ) {
|
| 608 |
+
|
| 609 |
+
if ( scope.enableZoom ) handleTouchStartDolly( event );
|
| 610 |
+
if ( scope.enablePan ) handleTouchStartPan( event );
|
| 611 |
+
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
function handleTouchStartDollyRotate( event ) {
|
| 615 |
+
|
| 616 |
+
if ( scope.enableZoom ) handleTouchStartDolly( event );
|
| 617 |
+
if ( scope.enableRotate ) handleTouchStartRotate( event );
|
| 618 |
+
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
function handleTouchMoveRotate( event ) {
|
| 622 |
+
|
| 623 |
+
if ( event.touches.length == 1 ) {
|
| 624 |
+
|
| 625 |
+
rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
|
| 626 |
+
|
| 627 |
+
} else {
|
| 628 |
+
|
| 629 |
+
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
|
| 630 |
+
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
|
| 631 |
+
rotateEnd.set( x, y );
|
| 632 |
+
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
|
| 636 |
+
const element = scope.domElement;
|
| 637 |
+
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
|
| 638 |
+
|
| 639 |
+
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
|
| 640 |
+
rotateStart.copy( rotateEnd );
|
| 641 |
+
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
function handleTouchMovePan( event ) {
|
| 645 |
+
|
| 646 |
+
if ( event.touches.length == 1 ) {
|
| 647 |
+
|
| 648 |
+
panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
|
| 649 |
+
|
| 650 |
+
} else {
|
| 651 |
+
|
| 652 |
+
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
|
| 653 |
+
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
|
| 654 |
+
panEnd.set( x, y );
|
| 655 |
+
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
|
| 659 |
+
pan( panDelta.x, panDelta.y );
|
| 660 |
+
panStart.copy( panEnd );
|
| 661 |
+
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
function handleTouchMoveDolly( event ) {
|
| 665 |
+
|
| 666 |
+
const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
|
| 667 |
+
const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
|
| 668 |
+
const distance = Math.sqrt( dx * dx + dy * dy );
|
| 669 |
+
dollyEnd.set( 0, distance );
|
| 670 |
+
dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
|
| 671 |
+
dollyOut( dollyDelta.y );
|
| 672 |
+
dollyStart.copy( dollyEnd );
|
| 673 |
+
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
function handleTouchMoveDollyPan( event ) {
|
| 677 |
+
|
| 678 |
+
if ( scope.enableZoom ) handleTouchMoveDolly( event );
|
| 679 |
+
if ( scope.enablePan ) handleTouchMovePan( event );
|
| 680 |
+
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
function handleTouchMoveDollyRotate( event ) {
|
| 684 |
+
|
| 685 |
+
if ( scope.enableZoom ) handleTouchMoveDolly( event );
|
| 686 |
+
if ( scope.enableRotate ) handleTouchMoveRotate( event );
|
| 687 |
+
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
function handleTouchEnd( ) { // no-op
|
| 691 |
+
} //
|
| 692 |
+
// event handlers - FSM: listen for events and reset state
|
| 693 |
+
//
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
function onPointerDown( event ) {
|
| 697 |
+
|
| 698 |
+
if ( scope.enabled === false ) return;
|
| 699 |
+
|
| 700 |
+
switch ( event.pointerType ) {
|
| 701 |
+
|
| 702 |
+
case 'mouse':
|
| 703 |
+
case 'pen':
|
| 704 |
+
onMouseDown( event );
|
| 705 |
+
break;
|
| 706 |
+
// TODO touch
|
| 707 |
+
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
}
|
| 711 |
+
|
| 712 |
+
function onPointerMove( event ) {
|
| 713 |
+
|
| 714 |
+
if ( scope.enabled === false ) return;
|
| 715 |
+
|
| 716 |
+
switch ( event.pointerType ) {
|
| 717 |
+
|
| 718 |
+
case 'mouse':
|
| 719 |
+
case 'pen':
|
| 720 |
+
onMouseMove( event );
|
| 721 |
+
break;
|
| 722 |
+
// TODO touch
|
| 723 |
+
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
function onPointerUp( event ) {
|
| 729 |
+
|
| 730 |
+
switch ( event.pointerType ) {
|
| 731 |
+
|
| 732 |
+
case 'mouse':
|
| 733 |
+
case 'pen':
|
| 734 |
+
onMouseUp( event );
|
| 735 |
+
break;
|
| 736 |
+
// TODO touch
|
| 737 |
+
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
function onMouseDown( event ) {
|
| 743 |
+
|
| 744 |
+
// Prevent the browser from scrolling.
|
| 745 |
+
event.preventDefault(); // Manually set the focus since calling preventDefault above
|
| 746 |
+
// prevents the browser from setting it automatically.
|
| 747 |
+
|
| 748 |
+
scope.domElement.focus ? scope.domElement.focus() : window.focus();
|
| 749 |
+
let mouseAction;
|
| 750 |
+
|
| 751 |
+
switch ( event.button ) {
|
| 752 |
+
|
| 753 |
+
case 0:
|
| 754 |
+
mouseAction = scope.mouseButtons.LEFT;
|
| 755 |
+
break;
|
| 756 |
+
|
| 757 |
+
case 1:
|
| 758 |
+
mouseAction = scope.mouseButtons.MIDDLE;
|
| 759 |
+
break;
|
| 760 |
+
|
| 761 |
+
case 2:
|
| 762 |
+
mouseAction = scope.mouseButtons.RIGHT;
|
| 763 |
+
break;
|
| 764 |
+
|
| 765 |
+
default:
|
| 766 |
+
mouseAction = - 1;
|
| 767 |
+
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
switch ( mouseAction ) {
|
| 771 |
+
|
| 772 |
+
case THREE.MOUSE.DOLLY:
|
| 773 |
+
if ( scope.enableZoom === false ) return;
|
| 774 |
+
handleMouseDownDolly( event );
|
| 775 |
+
state = STATE.DOLLY;
|
| 776 |
+
break;
|
| 777 |
+
|
| 778 |
+
case THREE.MOUSE.ROTATE:
|
| 779 |
+
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
|
| 780 |
+
|
| 781 |
+
if ( scope.enablePan === false ) return;
|
| 782 |
+
handleMouseDownPan( event );
|
| 783 |
+
state = STATE.PAN;
|
| 784 |
+
|
| 785 |
+
} else {
|
| 786 |
+
|
| 787 |
+
if ( scope.enableRotate === false ) return;
|
| 788 |
+
handleMouseDownRotate( event );
|
| 789 |
+
state = STATE.ROTATE;
|
| 790 |
+
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
break;
|
| 794 |
+
|
| 795 |
+
case THREE.MOUSE.PAN:
|
| 796 |
+
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
|
| 797 |
+
|
| 798 |
+
if ( scope.enableRotate === false ) return;
|
| 799 |
+
handleMouseDownRotate( event );
|
| 800 |
+
state = STATE.ROTATE;
|
| 801 |
+
|
| 802 |
+
} else {
|
| 803 |
+
|
| 804 |
+
if ( scope.enablePan === false ) return;
|
| 805 |
+
handleMouseDownPan( event );
|
| 806 |
+
state = STATE.PAN;
|
| 807 |
+
|
| 808 |
+
}
|
| 809 |
+
|
| 810 |
+
break;
|
| 811 |
+
|
| 812 |
+
default:
|
| 813 |
+
state = STATE.NONE;
|
| 814 |
+
|
| 815 |
+
}
|
| 816 |
+
|
| 817 |
+
if ( state !== STATE.NONE ) {
|
| 818 |
+
|
| 819 |
+
scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
|
| 820 |
+
scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
|
| 821 |
+
scope.dispatchEvent( _startEvent );
|
| 822 |
+
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
}
|
| 826 |
+
|
| 827 |
+
function onMouseMove( event ) {
|
| 828 |
+
|
| 829 |
+
if ( scope.enabled === false ) return;
|
| 830 |
+
event.preventDefault();
|
| 831 |
+
|
| 832 |
+
switch ( state ) {
|
| 833 |
+
|
| 834 |
+
case STATE.ROTATE:
|
| 835 |
+
if ( scope.enableRotate === false ) return;
|
| 836 |
+
handleMouseMoveRotate( event );
|
| 837 |
+
break;
|
| 838 |
+
|
| 839 |
+
case STATE.DOLLY:
|
| 840 |
+
if ( scope.enableZoom === false ) return;
|
| 841 |
+
handleMouseMoveDolly( event );
|
| 842 |
+
break;
|
| 843 |
+
|
| 844 |
+
case STATE.PAN:
|
| 845 |
+
if ( scope.enablePan === false ) return;
|
| 846 |
+
handleMouseMovePan( event );
|
| 847 |
+
break;
|
| 848 |
+
|
| 849 |
+
}
|
| 850 |
+
|
| 851 |
+
}
|
| 852 |
+
|
| 853 |
+
function onMouseUp( event ) {
|
| 854 |
+
|
| 855 |
+
scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
|
| 856 |
+
scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
|
| 857 |
+
if ( scope.enabled === false ) return;
|
| 858 |
+
handleMouseUp( event );
|
| 859 |
+
scope.dispatchEvent( _endEvent );
|
| 860 |
+
state = STATE.NONE;
|
| 861 |
+
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
function onMouseWheel( event ) {
|
| 865 |
+
|
| 866 |
+
if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE ) return;
|
| 867 |
+
event.preventDefault();
|
| 868 |
+
scope.dispatchEvent( _startEvent );
|
| 869 |
+
handleMouseWheel( event );
|
| 870 |
+
scope.dispatchEvent( _endEvent );
|
| 871 |
+
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
function onKeyDown( event ) {
|
| 875 |
+
|
| 876 |
+
if ( scope.enabled === false || scope.enablePan === false ) return;
|
| 877 |
+
handleKeyDown( event );
|
| 878 |
+
|
| 879 |
+
}
|
| 880 |
+
|
| 881 |
+
function onTouchStart( event ) {
|
| 882 |
+
|
| 883 |
+
if ( scope.enabled === false ) return;
|
| 884 |
+
event.preventDefault(); // prevent scrolling
|
| 885 |
+
|
| 886 |
+
switch ( event.touches.length ) {
|
| 887 |
+
|
| 888 |
+
case 1:
|
| 889 |
+
switch ( scope.touches.ONE ) {
|
| 890 |
+
|
| 891 |
+
case THREE.TOUCH.ROTATE:
|
| 892 |
+
if ( scope.enableRotate === false ) return;
|
| 893 |
+
handleTouchStartRotate( event );
|
| 894 |
+
state = STATE.TOUCH_ROTATE;
|
| 895 |
+
break;
|
| 896 |
+
|
| 897 |
+
case THREE.TOUCH.PAN:
|
| 898 |
+
if ( scope.enablePan === false ) return;
|
| 899 |
+
handleTouchStartPan( event );
|
| 900 |
+
state = STATE.TOUCH_PAN;
|
| 901 |
+
break;
|
| 902 |
+
|
| 903 |
+
default:
|
| 904 |
+
state = STATE.NONE;
|
| 905 |
+
|
| 906 |
+
}
|
| 907 |
+
|
| 908 |
+
break;
|
| 909 |
+
|
| 910 |
+
case 2:
|
| 911 |
+
switch ( scope.touches.TWO ) {
|
| 912 |
+
|
| 913 |
+
case THREE.TOUCH.DOLLY_PAN:
|
| 914 |
+
if ( scope.enableZoom === false && scope.enablePan === false ) return;
|
| 915 |
+
handleTouchStartDollyPan( event );
|
| 916 |
+
state = STATE.TOUCH_DOLLY_PAN;
|
| 917 |
+
break;
|
| 918 |
+
|
| 919 |
+
case THREE.TOUCH.DOLLY_ROTATE:
|
| 920 |
+
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
|
| 921 |
+
handleTouchStartDollyRotate( event );
|
| 922 |
+
state = STATE.TOUCH_DOLLY_ROTATE;
|
| 923 |
+
break;
|
| 924 |
+
|
| 925 |
+
default:
|
| 926 |
+
state = STATE.NONE;
|
| 927 |
+
|
| 928 |
+
}
|
| 929 |
+
|
| 930 |
+
break;
|
| 931 |
+
|
| 932 |
+
default:
|
| 933 |
+
state = STATE.NONE;
|
| 934 |
+
|
| 935 |
+
}
|
| 936 |
+
|
| 937 |
+
if ( state !== STATE.NONE ) {
|
| 938 |
+
|
| 939 |
+
scope.dispatchEvent( _startEvent );
|
| 940 |
+
|
| 941 |
+
}
|
| 942 |
+
|
| 943 |
+
}
|
| 944 |
+
|
| 945 |
+
function onTouchMove( event ) {
|
| 946 |
+
|
| 947 |
+
if ( scope.enabled === false ) return;
|
| 948 |
+
event.preventDefault(); // prevent scrolling
|
| 949 |
+
|
| 950 |
+
switch ( state ) {
|
| 951 |
+
|
| 952 |
+
case STATE.TOUCH_ROTATE:
|
| 953 |
+
if ( scope.enableRotate === false ) return;
|
| 954 |
+
handleTouchMoveRotate( event );
|
| 955 |
+
scope.update();
|
| 956 |
+
break;
|
| 957 |
+
|
| 958 |
+
case STATE.TOUCH_PAN:
|
| 959 |
+
if ( scope.enablePan === false ) return;
|
| 960 |
+
handleTouchMovePan( event );
|
| 961 |
+
scope.update();
|
| 962 |
+
break;
|
| 963 |
+
|
| 964 |
+
case STATE.TOUCH_DOLLY_PAN:
|
| 965 |
+
if ( scope.enableZoom === false && scope.enablePan === false ) return;
|
| 966 |
+
handleTouchMoveDollyPan( event );
|
| 967 |
+
scope.update();
|
| 968 |
+
break;
|
| 969 |
+
|
| 970 |
+
case STATE.TOUCH_DOLLY_ROTATE:
|
| 971 |
+
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
|
| 972 |
+
handleTouchMoveDollyRotate( event );
|
| 973 |
+
scope.update();
|
| 974 |
+
break;
|
| 975 |
+
|
| 976 |
+
default:
|
| 977 |
+
state = STATE.NONE;
|
| 978 |
+
|
| 979 |
+
}
|
| 980 |
+
|
| 981 |
+
}
|
| 982 |
+
|
| 983 |
+
function onTouchEnd( event ) {
|
| 984 |
+
|
| 985 |
+
if ( scope.enabled === false ) return;
|
| 986 |
+
handleTouchEnd( event );
|
| 987 |
+
scope.dispatchEvent( _endEvent );
|
| 988 |
+
state = STATE.NONE;
|
| 989 |
+
|
| 990 |
+
}
|
| 991 |
+
|
| 992 |
+
function onContextMenu( event ) {
|
| 993 |
+
|
| 994 |
+
if ( scope.enabled === false ) return;
|
| 995 |
+
event.preventDefault();
|
| 996 |
+
|
| 997 |
+
} //
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
scope.domElement.addEventListener( 'contextmenu', onContextMenu );
|
| 1001 |
+
scope.domElement.addEventListener( 'pointerdown', onPointerDown );
|
| 1002 |
+
scope.domElement.addEventListener( 'wheel', onMouseWheel, {
|
| 1003 |
+
passive: false
|
| 1004 |
+
} );
|
| 1005 |
+
scope.domElement.addEventListener( 'touchstart', onTouchStart, {
|
| 1006 |
+
passive: false
|
| 1007 |
+
} );
|
| 1008 |
+
scope.domElement.addEventListener( 'touchend', onTouchEnd );
|
| 1009 |
+
scope.domElement.addEventListener( 'touchmove', onTouchMove, {
|
| 1010 |
+
passive: false
|
| 1011 |
+
} ); // force an update at start
|
| 1012 |
+
|
| 1013 |
+
this.update();
|
| 1014 |
+
|
| 1015 |
+
}
|
| 1016 |
+
|
| 1017 |
+
} // This set of controls performs orbiting, dollying (zooming), and panning.
|
| 1018 |
+
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
|
| 1019 |
+
// This is very similar to OrbitControls, another set of touch behavior
|
| 1020 |
+
//
|
| 1021 |
+
// Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
|
| 1022 |
+
// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
|
| 1023 |
+
// Pan - left mouse, or arrow keys / touch: one-finger move
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
class MapControls extends OrbitControls {
|
| 1027 |
+
|
| 1028 |
+
constructor( object, domElement ) {
|
| 1029 |
+
|
| 1030 |
+
super( object, domElement );
|
| 1031 |
+
this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up
|
| 1032 |
+
|
| 1033 |
+
this.mouseButtons.LEFT = THREE.MOUSE.PAN;
|
| 1034 |
+
this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE;
|
| 1035 |
+
this.touches.ONE = THREE.TOUCH.PAN;
|
| 1036 |
+
this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE;
|
| 1037 |
+
|
| 1038 |
+
}
|
| 1039 |
+
|
| 1040 |
+
}
|
| 1041 |
+
|
| 1042 |
+
THREE.MapControls = MapControls;
|
| 1043 |
+
THREE.OrbitControls = OrbitControls;
|
| 1044 |
+
|
| 1045 |
+
} )();
|
code/ezflow_v3/app/frontend/vendor/three.min.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
code/ezflow_v3/app/infer_app.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Multi-model serving core for the EZFlow v2 web app.
|
| 2 |
+
|
| 3 |
+
STL geometry -> (gmsh tet mesh) -> v2 graph -> predicted RANS fields, for a chosen
|
| 4 |
+
model: GeoReNet / HybridFlow / Transolver / mean(G,T,H) ensemble.
|
| 5 |
+
|
| 6 |
+
Notes
|
| 7 |
+
-----
|
| 8 |
+
* Inputs are simulation-free: the graph features are built from geometry + (Re, yaw)
|
| 9 |
+
only (the SAME `features.py` as training); no solved field is ever an input.
|
| 10 |
+
* The model is mesh-density-robust (GeoReNet's mean+sum aggregation), so we predict
|
| 11 |
+
on ALL mesh nodes and attach the fields directly to the tet grid for slicing --
|
| 12 |
+
no interpolation needed.
|
| 13 |
+
* STL meshing reuses the shared, geometry-neutral gmsh tooling (same as `infer_v5`).
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
import os, sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from torch_geometric.data import Data
|
| 21 |
+
|
| 22 |
+
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
| 23 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 24 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 25 |
+
sys.path.insert(0, str(REPO))
|
| 26 |
+
from ezflow_v3.gnn import features as F
|
| 27 |
+
from ezflow_v3.gnn.infer_v5 import _tri_point_normals
|
| 28 |
+
# geometry-neutral meshing (shared with the data pipeline; not v1 physics)
|
| 29 |
+
from datasets.gen.shapenet.watertight import make_watertight
|
| 30 |
+
from datasets.gen.shapenet.mesh_stl import build_mesh_from_stl
|
| 31 |
+
from datasets.gen.mesh import read_mesh
|
| 32 |
+
|
| 33 |
+
RUNS = REPO / "ezflow_v3" / "gnn" / "_runs"
|
| 34 |
+
|
| 35 |
+
# UI label -> run tags. The paper's seed-0 (s0) checkpoints from the TMLR submission.
|
| 36 |
+
MODELS: dict[str, list[str]] = {
|
| 37 |
+
"HybridFlow": ["hybrid_s0"], # local MP + slice attention (3.04M)
|
| 38 |
+
"GeoReNet": ["geore_fieldonly_s0"], # local MP + global virtual node (3.28M)
|
| 39 |
+
}
|
| 40 |
+
DEFAULT_MODEL = "HybridFlow"
|
| 41 |
+
_CACHE: dict[tuple, tuple] = {} # (tag, device_type) -> (model, norms)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def available_models() -> list[str]:
|
| 45 |
+
return list(MODELS.keys())
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _pick_ckpt(run: Path) -> Path:
|
| 49 |
+
for n in ("model.pt", "best.pt", "ckpt.pt"):
|
| 50 |
+
if (run / n).exists():
|
| 51 |
+
return run / n
|
| 52 |
+
raise FileNotFoundError(f"no checkpoint in {run}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _build(tag: str, device):
|
| 56 |
+
"""Rebuild the architecture matching the checkpoint's saved args (any model type)."""
|
| 57 |
+
ck = torch.load(_pick_ckpt(RUNS / tag), map_location=device, weights_only=False)
|
| 58 |
+
ar = ck["args"]; mt = ar.get("model")
|
| 59 |
+
if mt == "transolver":
|
| 60 |
+
from ezflow_v3.baselines.transolver_wrap import TransolverWrapper
|
| 61 |
+
m = TransolverWrapper(node_in=F.NODE_FEATURE_DIM, space_dim=3, global_dim=F.GLOBAL_DIM,
|
| 62 |
+
out_dim=F.TARGET_DIM, n_hidden=256, n_layers=8, slice_num=64)
|
| 63 |
+
elif mt == "hybrid":
|
| 64 |
+
from ezflow_v3.gnn.model_hybrid import HybridFlow
|
| 65 |
+
m = HybridFlow(F.NODE_FEATURE_DIM, 4, F.GLOBAL_DIM, hidden=int(ar["hidden"]), K=8,
|
| 66 |
+
out_dim=F.TARGET_DIM, slice_num=64)
|
| 67 |
+
elif mt == "gino":
|
| 68 |
+
from ezflow_v3.gnn.model_gino import GINO
|
| 69 |
+
m = GINO(F.NODE_FEATURE_DIM, 4, F.GLOBAL_DIM, out_dim=F.TARGET_DIM)
|
| 70 |
+
else:
|
| 71 |
+
from ezflow_v3.gnn.model_v5 import MeshGraphNetV5
|
| 72 |
+
m = MeshGraphNetV5(F.NODE_FEATURE_DIM, 4, F.GLOBAL_DIM, hidden=int(ar["hidden"]),
|
| 73 |
+
K=int(ar["K"]), out_dim=F.TARGET_DIM,
|
| 74 |
+
use_film=not ar.get("no_film", False),
|
| 75 |
+
use_global=not ar.get("no_global", False),
|
| 76 |
+
agg=ar.get("agg", "meansum"))
|
| 77 |
+
m.load_state_dict(ck["model"]); m.eval().to(device)
|
| 78 |
+
nz = np.load(RUNS / tag / "norms.npz")
|
| 79 |
+
norms = {k: torch.tensor(nz[k], dtype=torch.float32, device=device)
|
| 80 |
+
for k in ("y_mean", "y_std", "g_mean", "g_std")}
|
| 81 |
+
return m, norms
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def get_model(tag: str, device):
|
| 85 |
+
# key by device TYPE too: warmup loads on cuda, but large meshes now run inference on cpu.
|
| 86 |
+
# Caching by tag alone handed the cuda model back for a cpu graph -> device-mismatch error.
|
| 87 |
+
key = (tag, torch.device(device).type)
|
| 88 |
+
if key not in _CACHE:
|
| 89 |
+
_CACHE[key] = _build(tag, device)
|
| 90 |
+
return _CACHE[key]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def param_count(model_name: str, device) -> float:
|
| 94 |
+
"""Total parameters across the model (or the ensemble members), in millions."""
|
| 95 |
+
tags = MODELS[model_name]
|
| 96 |
+
n = sum(sum(p.numel() for p in get_model(t, device)[0].parameters()) for t in tags)
|
| 97 |
+
return n / 1e6
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def mesh_stl(stl_path, temp_dir, resolution="medium", repair="auto"):
|
| 101 |
+
"""STL -> detail-preserving surface (L=1) -> graded tet mesh -> arrays + meta.
|
| 102 |
+
resolution in {coarse, medium, fine}: detail vs node-count/speed (see premesh.py).
|
| 103 |
+
repair in {auto, envelope, none}: how to handle a non-watertight upload (auto = light
|
| 104 |
+
hole-fill, else robust voxel envelope; envelope = force the envelope; none = as-is)."""
|
| 105 |
+
from ezflow_v3.app import premesh
|
| 106 |
+
temp_dir = Path(temp_dir); temp_dir.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
surf = temp_dir / "surface.stl"; msh = temp_dir / "mesh.msh"
|
| 108 |
+
force_env = (repair == "envelope")
|
| 109 |
+
try:
|
| 110 |
+
geom = premesh.prepare_surface(stl_path, surf, preset=resolution, target_L=1.0,
|
| 111 |
+
force_envelope=force_env, repair=repair)
|
| 112 |
+
minfo = premesh.build_volume(surf, msh, preset=resolution)
|
| 113 |
+
except Exception as e:
|
| 114 |
+
# the true-geometry path can fail on complex/high-genus bodies (open underbody,
|
| 115 |
+
# wheel wells, mirrors -> bad surface parametrization). Fall back to the robust
|
| 116 |
+
# voxel envelope, which closes gaps into a clean solid.
|
| 117 |
+
print(f"[mesh_stl] direct meshing failed ({type(e).__name__}: {e}); robust envelope fallback", flush=True)
|
| 118 |
+
geom = premesh.prepare_surface(stl_path, surf, preset="coarse", target_L=1.0, force_envelope=True)
|
| 119 |
+
minfo = premesh.build_volume(surf, msh, preset=resolution) # robust surface, requested volume density
|
| 120 |
+
geom["method"] = geom.get("method", "voxel envelope") + f" [auto-fallback: complex geometry, {resolution} volume]"
|
| 121 |
+
minfo["resolution"] = resolution
|
| 122 |
+
pts, tets, tris = read_mesh(msh)
|
| 123 |
+
return np.asarray(pts), np.asarray(tets), np.asarray(tris["wall"]), geom, minfo
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def build_graph_full(pts, tets, wall_tris, Re, yaw_deg, knn=8) -> Data:
|
| 127 |
+
"""Graph over ALL mesh nodes; features from geometry + (Re, yaw) only."""
|
| 128 |
+
yaw = float(np.deg2rad(yaw_deg))
|
| 129 |
+
pos = pts.astype(np.float32)
|
| 130 |
+
wall_nodes = np.unique(np.asarray(wall_tris).reshape(-1))
|
| 131 |
+
wall_pts = pts[wall_nodes]
|
| 132 |
+
wall_nrm = _tri_point_normals(pts, np.asarray(wall_tris))[wall_nodes]
|
| 133 |
+
is_wall = np.zeros(len(pts), np.float32); is_wall[wall_nodes] = 1.0
|
| 134 |
+
edge_index = F.knn_edges(pos, knn)
|
| 135 |
+
x = F.build_node_features(pos, wall_pts, wall_nrm, yaw, Re, edge_index, is_wall=is_wall)
|
| 136 |
+
diff = pos[edge_index[1]] - pos[edge_index[0]]
|
| 137 |
+
ea = np.concatenate([diff, np.linalg.norm(diff, axis=1, keepdims=True)], 1).astype(np.float32)
|
| 138 |
+
d = Data(pos=torch.tensor(pos), x=torch.tensor(x),
|
| 139 |
+
edge_index=torch.tensor(edge_index), edge_attr=torch.tensor(ea),
|
| 140 |
+
global_feat=torch.tensor(F.global_features(Re, yaw)))
|
| 141 |
+
d.batch = torch.zeros(len(pos), dtype=torch.long) # single-graph (global-node scatter safe)
|
| 142 |
+
return d
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _smooth_scalar(x, ei, iters, step, mode):
|
| 146 |
+
"""Graph smoothing of one scalar field on the (bidirectional) mesh graph.
|
| 147 |
+
mode 'tv' -> TV-L1: weight = sign(neighbour diff), edge preserving / median-like.
|
| 148 |
+
mode 'diffusion' -> Laplacian: weight = raw diff, gentle blurring (step is the blend fraction)."""
|
| 149 |
+
x = np.asarray(x, dtype=np.float64).copy()
|
| 150 |
+
N = len(x)
|
| 151 |
+
deg = np.maximum(np.bincount(ei[1], minlength=N), 1)
|
| 152 |
+
for _ in range(int(iters)):
|
| 153 |
+
d = x[ei[1]] - x[ei[0]]
|
| 154 |
+
w = np.sign(d) if mode == "tv" else d
|
| 155 |
+
s = np.bincount(ei[1], weights=w, minlength=N)
|
| 156 |
+
x -= step * s / deg
|
| 157 |
+
return x
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def smooth_prediction(pred, edge_index, cfg):
|
| 161 |
+
"""Post-inference smoothing of a (N,7) de-normalized prediction. cfg keys:
|
| 162 |
+
mode ('tv'|'diffusion'), iters, step, speed (bool), pressure (bool). Speed smoothing keeps
|
| 163 |
+
each velocity vector's direction and rescales to the smoothed magnitude (guards ~zero nodes)."""
|
| 164 |
+
pred = np.asarray(pred, dtype=np.float64).copy()
|
| 165 |
+
ei = np.asarray(edge_index)
|
| 166 |
+
mode = cfg.get("mode", "tv"); iters = int(cfg.get("iters", 24)); step = float(cfg.get("step", 0.006))
|
| 167 |
+
if cfg.get("speed", True):
|
| 168 |
+
speed = np.sqrt((pred[:, :3] ** 2).sum(1))
|
| 169 |
+
sm = _smooth_scalar(speed, ei, iters, step, mode)
|
| 170 |
+
scale = np.where(speed > 1e-6, sm / np.maximum(speed, 1e-12), 1.0)
|
| 171 |
+
pred[:, :3] *= scale[:, None]
|
| 172 |
+
if cfg.get("pressure", False):
|
| 173 |
+
pred[:, 3] = _smooth_scalar(pred[:, 3], ei, iters, step, mode)
|
| 174 |
+
return pred.astype(np.float32)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@torch.no_grad()
|
| 178 |
+
def predict_fields(pts, tets, wall_tris, model_name, Re, yaw_deg, device, smooth=None):
|
| 179 |
+
"""Return physical fields {U:[N,3], p, k, omega, nut} on the full mesh
|
| 180 |
+
(ensemble = average of members in the transformed target space, then inverse).
|
| 181 |
+
smooth: optional cfg dict for post-inference smoothing (see smooth_prediction)."""
|
| 182 |
+
tags = MODELS[model_name]
|
| 183 |
+
g = build_graph_full(pts, tets, wall_tris, Re, yaw_deg).to(device)
|
| 184 |
+
raw_global = g.global_feat.clone()
|
| 185 |
+
acc = None
|
| 186 |
+
for tag in tags:
|
| 187 |
+
model, norms = get_model(tag, device)
|
| 188 |
+
g.global_feat = (raw_global - norms["g_mean"]) / norms["g_std"]
|
| 189 |
+
out = model(g) * norms["y_std"] + norms["y_mean"] # [N,7] de-normalized
|
| 190 |
+
acc = out if acc is None else acc + out
|
| 191 |
+
pred = (acc / len(tags)).cpu().numpy()
|
| 192 |
+
if smooth:
|
| 193 |
+
pred = smooth_prediction(pred, g.edge_index.cpu().numpy(), smooth)
|
| 194 |
+
return F.inverse_targets(pred, Re) # {U:[N,3], p, k, omega, nut} (physical)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def pressure_forces(pts, wall_tris, p_nodal, yaw_deg, Aref):
|
| 198 |
+
"""Pressure drag and lift coefficients by integrating the predicted wall pressure over the
|
| 199 |
+
body surface, the same way the paper does (true triangle areas + outward normals; force
|
| 200 |
+
head free). Non-dimensional (rho=1, U_inf=1, L_ref=1). Returns (Cd_p, Cl_p).
|
| 201 |
+
|
| 202 |
+
This is the PRESSURE component only; the viscous (skin-friction) share is not recovered from
|
| 203 |
+
the field, so on slender streamlined bodies this understates the total drag (see the paper's
|
| 204 |
+
limitations). It is an estimate, not a calibrated value.
|
| 205 |
+
"""
|
| 206 |
+
import pyvista as pv
|
| 207 |
+
tris = np.asarray(wall_tris)
|
| 208 |
+
if tris.size == 0:
|
| 209 |
+
return float("nan"), float("nan")
|
| 210 |
+
faces = np.hstack([np.full((len(tris), 1), 3), tris]).astype(np.int64).ravel()
|
| 211 |
+
surf = pv.PolyData(np.asarray(pts, dtype=float), faces)
|
| 212 |
+
surf.point_data["p"] = np.asarray(p_nodal, dtype=float)
|
| 213 |
+
surf = surf.compute_normals(cell_normals=True, point_normals=False,
|
| 214 |
+
auto_orient_normals=True, consistent_normals=True)
|
| 215 |
+
surf = surf.compute_cell_sizes(length=False, area=True, volume=False)
|
| 216 |
+
pc = np.asarray(surf.point_data_to_cell_data().cell_data["p"]).reshape(-1) # mean p per face
|
| 217 |
+
Sf = -np.asarray(surf.cell_normals) * np.asarray(surf.cell_data["Area"]).reshape(-1, 1)
|
| 218 |
+
Fp = (Sf * pc[:, None]).sum(0) # net pressure force on the body
|
| 219 |
+
yaw = float(np.deg2rad(yaw_deg))
|
| 220 |
+
drag_dir = np.array([np.cos(yaw), np.sin(yaw), 0.0])
|
| 221 |
+
lift_dir = np.array([-np.sin(yaw), np.cos(yaw), 0.0])
|
| 222 |
+
a = max(float(Aref), 1e-9)
|
| 223 |
+
return float(2.0 * Fp @ drag_dir / a), float(2.0 * Fp @ lift_dir / a)
|
code/ezflow_v3/app/premesh.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Detail-preserving premesher for the v2 app.
|
| 2 |
+
|
| 3 |
+
The data pipeline's `make_watertight` rebuilds every body as a smooth voxel
|
| 4 |
+
*envelope* (great for CFD robustness, but it erases mirrors/wheels/sharp edges).
|
| 5 |
+
For app uploads we usually want to KEEP the real geometry:
|
| 6 |
+
|
| 7 |
+
prepare_surface() - if the upload is already watertight, keep its true surface
|
| 8 |
+
(only light cleanup + optional decimation); fall back to a
|
| 9 |
+
higher-resolution voxel envelope only for non-watertight
|
| 10 |
+
"triangle soup". Normalizes the body to L = 1.
|
| 11 |
+
build_volume() - external-flow tet mesh refined near the body, with optional
|
| 12 |
+
curvature-aware sizing so detailed regions get a finer mesh.
|
| 13 |
+
|
| 14 |
+
RESOLUTION presets trade geometric detail against node count / speed.
|
| 15 |
+
|
| 16 |
+
NOTE: the surrogate models were trained on the *enveloped* (smoothed) geometries,
|
| 17 |
+
so a high-detail mesh mainly improves the geometry/visualisation and lets the model
|
| 18 |
+
run at higher resolution; fully exploiting fine features would require retraining on
|
| 19 |
+
high-fidelity geometry.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
import os, math
|
| 23 |
+
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
| 24 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
import numpy as np
|
| 27 |
+
from datasets.gen.shapenet.watertight import make_watertight, _load_mesh
|
| 28 |
+
from datasets.gen.shapenet.mesh_stl import _add_box_surfaces
|
| 29 |
+
|
| 30 |
+
# preset -> meshing knobs. h_* in units of body length L_ref = 1.
|
| 31 |
+
PRESETS = {
|
| 32 |
+
"coarse": dict(h_min=0.12, h_max=1.2, dist_min=0.4, dist_max=4.0, curv=0,
|
| 33 |
+
surf_faces=8000, vox_res=64, preserve=False), # = legacy envelope
|
| 34 |
+
"medium": dict(h_min=0.045, h_max=0.9, dist_min=0.2, dist_max=3.0, curv=20,
|
| 35 |
+
surf_faces=80000, vox_res=128, preserve=True),
|
| 36 |
+
"fine": dict(h_min=0.022, h_max=0.7, dist_min=0.1, dist_max=2.5, curv=30,
|
| 37 |
+
surf_faces=150000, vox_res=192, preserve=True),
|
| 38 |
+
# much denser near-wall band. Slow to build and heavy on memory -> the app auto-runs inference
|
| 39 |
+
# on CPU when the node count would overflow GPU VRAM. h_min is in body lengths (0.012*L),
|
| 40 |
+
# so on a 5 m car this is ~60 mm cells; a true 16 mm would need h_min~0.003 and explode the count.
|
| 41 |
+
"very fine": dict(h_min=0.012, h_max=0.6, dist_min=0.08, dist_max=2.2, curv=40,
|
| 42 |
+
surf_faces=250000, vox_res=256, preserve=True),
|
| 43 |
+
}
|
| 44 |
+
DEFAULT_PRESET = "medium"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def quick_extents(in_stl):
|
| 48 |
+
"""Raw bounding-box extents (x, y, z) in the file's native units, no repair/meshing.
|
| 49 |
+
|
| 50 |
+
Used to advise a reference length before simulation: the model normalizes geometry to unit
|
| 51 |
+
size, so the real longest dimension has to come from the file. process=False keeps it fast
|
| 52 |
+
on heavy CAD (no vertex merging)."""
|
| 53 |
+
import trimesh
|
| 54 |
+
m = trimesh.load(str(in_stl), process=False, force="mesh")
|
| 55 |
+
e = m.extents
|
| 56 |
+
return [float(e[0]), float(e[1]), float(e[2])]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def inspect_geometry(in_stl) -> dict:
|
| 60 |
+
"""Cheap watertightness / topology report for an STL (one load, no meshing).
|
| 61 |
+
|
| 62 |
+
Returns a dict the UI can show BEFORE meshing so the user knows what they uploaded:
|
| 63 |
+
watertight?, face/vertex counts, Euler number + genus (for closed bodies), number of
|
| 64 |
+
open (boundary) edges, and whether the face winding is consistent.
|
| 65 |
+
"""
|
| 66 |
+
import trimesh
|
| 67 |
+
try:
|
| 68 |
+
mesh = _load_mesh(Path(in_stl))
|
| 69 |
+
except Exception as e:
|
| 70 |
+
return {"ok": False, "error": f"{type(e).__name__}: {e}"}
|
| 71 |
+
if mesh.is_empty or len(mesh.faces) == 0:
|
| 72 |
+
return {"ok": False, "error": "empty / unreadable mesh"}
|
| 73 |
+
wt = bool(mesh.is_watertight)
|
| 74 |
+
try:
|
| 75 |
+
euler = int(mesh.euler_number)
|
| 76 |
+
except Exception:
|
| 77 |
+
euler = None
|
| 78 |
+
try: # edges used by exactly one face = open boundary
|
| 79 |
+
open_edges = int(len(trimesh.grouping.group_rows(mesh.edges_sorted, require_count=1)))
|
| 80 |
+
except Exception:
|
| 81 |
+
open_edges = None
|
| 82 |
+
try:
|
| 83 |
+
winding = bool(mesh.is_winding_consistent)
|
| 84 |
+
except Exception:
|
| 85 |
+
winding = None
|
| 86 |
+
genus = ((2 - euler) // 2) if (wt and euler is not None) else None
|
| 87 |
+
return {"ok": True, "watertight": wt, "n_faces": int(len(mesh.faces)),
|
| 88 |
+
"n_vertices": int(len(mesh.vertices)), "euler": euler, "genus": genus,
|
| 89 |
+
"open_edges": open_edges, "winding_consistent": winding}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _repair_mesh(mesh):
|
| 93 |
+
"""Light, geometry-preserving repair: merge coincident verts, drop degenerate/duplicate
|
| 94 |
+
faces, make winding/normals consistent, and fill small holes. Returns (mesh, notes)."""
|
| 95 |
+
import trimesh
|
| 96 |
+
notes = []
|
| 97 |
+
n0 = len(mesh.faces); wt0 = bool(mesh.is_watertight)
|
| 98 |
+
mesh.merge_vertices()
|
| 99 |
+
mesh.update_faces(mesh.nondegenerate_faces())
|
| 100 |
+
mesh.update_faces(mesh.unique_faces())
|
| 101 |
+
mesh.remove_unreferenced_vertices()
|
| 102 |
+
try:
|
| 103 |
+
trimesh.repair.fix_winding(mesh)
|
| 104 |
+
trimesh.repair.fix_inversion(mesh)
|
| 105 |
+
trimesh.repair.fix_normals(mesh)
|
| 106 |
+
except Exception:
|
| 107 |
+
pass
|
| 108 |
+
if not mesh.is_watertight:
|
| 109 |
+
try:
|
| 110 |
+
trimesh.repair.fill_holes(mesh) # triangle-fan fill of small boundary loops
|
| 111 |
+
except Exception:
|
| 112 |
+
pass
|
| 113 |
+
if len(mesh.faces) != n0:
|
| 114 |
+
notes.append(f"cleaned {n0}->{len(mesh.faces)} faces")
|
| 115 |
+
if not wt0 and bool(mesh.is_watertight):
|
| 116 |
+
notes.append("filled holes -> watertight")
|
| 117 |
+
return mesh, notes
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def prepare_surface(in_stl, out_stl, preset=DEFAULT_PRESET, target_L=1.0,
|
| 121 |
+
force_envelope=False, repair="auto") -> dict:
|
| 122 |
+
cfg = PRESETS[preset]
|
| 123 |
+
mesh = _load_mesh(Path(in_stl))
|
| 124 |
+
if mesh.is_empty or len(mesh.faces) == 0:
|
| 125 |
+
raise ValueError(f"empty mesh: {in_stl}")
|
| 126 |
+
mesh.apply_translation(-mesh.centroid)
|
| 127 |
+
mesh.apply_scale(target_L / float(mesh.extents.max())) # normalize L=1, centered
|
| 128 |
+
# remedy for non-watertight uploads: try a light repair first (keeps real geometry);
|
| 129 |
+
# if it becomes watertight+genus0 we take the detail-preserving path below, otherwise
|
| 130 |
+
# we still fall through to the robust voxel envelope.
|
| 131 |
+
repair_notes = []
|
| 132 |
+
if repair == "auto" and not force_envelope and not bool(mesh.is_watertight):
|
| 133 |
+
mesh, repair_notes = _repair_mesh(mesh)
|
| 134 |
+
watertight = bool(mesh.is_watertight)
|
| 135 |
+
|
| 136 |
+
# direct (true-geometry) path only for clean, genus-0 closed surfaces; complex/
|
| 137 |
+
# high-genus bodies (DrivAer underbody/wheels) go straight to the robust envelope.
|
| 138 |
+
genus0 = False
|
| 139 |
+
try:
|
| 140 |
+
genus0 = int(mesh.euler_number) == 2
|
| 141 |
+
except Exception:
|
| 142 |
+
genus0 = False
|
| 143 |
+
if cfg["preserve"] and watertight and genus0 and not force_envelope:
|
| 144 |
+
# KEEP true geometry: light cleanup + decimate only if very heavy (quadric
|
| 145 |
+
# decimation preserves features far better than a voxel envelope).
|
| 146 |
+
mesh.update_faces(mesh.nondegenerate_faces())
|
| 147 |
+
mesh.remove_unreferenced_vertices()
|
| 148 |
+
mesh.fix_normals()
|
| 149 |
+
if len(mesh.faces) > cfg["surf_faces"]:
|
| 150 |
+
try:
|
| 151 |
+
mesh = mesh.simplify_quadric_decimation(face_count=cfg["surf_faces"])
|
| 152 |
+
mesh.fix_normals()
|
| 153 |
+
except Exception:
|
| 154 |
+
pass
|
| 155 |
+
try:
|
| 156 |
+
a_ref = float(abs(mesh.projected(normal=[1.0, 0.0, 0.0]).area))
|
| 157 |
+
except Exception:
|
| 158 |
+
a_ref = float(mesh.extents[1] * mesh.extents[2])
|
| 159 |
+
if not np.isfinite(a_ref) or a_ref <= 1e-6:
|
| 160 |
+
a_ref = float(mesh.extents[1] * mesh.extents[2])
|
| 161 |
+
Path(out_stl).parent.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
mesh.export(str(out_stl))
|
| 163 |
+
method = f"direct (true geometry, {len(mesh.faces)} faces)"
|
| 164 |
+
if repair_notes:
|
| 165 |
+
method += " [repaired: " + "; ".join(repair_notes) + "]"
|
| 166 |
+
return {"L_ref": float(mesh.extents.max()), "A_ref": a_ref,
|
| 167 |
+
"extents": [float(x) for x in mesh.extents], "n_faces": int(len(mesh.faces)),
|
| 168 |
+
"watertight": True, "method": method}
|
| 169 |
+
|
| 170 |
+
# voxel envelope (smooth genus-0 solid). Keep the face count low (~8k) so gmsh's
|
| 171 |
+
# surface parametrization stays robust; vox_res controls how faithfully the blob
|
| 172 |
+
# samples the body (higher = closer to the true silhouette, still a smooth shell).
|
| 173 |
+
meta = make_watertight(Path(in_stl), Path(out_stl), target_L=target_L,
|
| 174 |
+
vox_res=cfg["vox_res"], max_faces=8000)
|
| 175 |
+
tag = "" if watertight else " [non-watertight input]"
|
| 176 |
+
meta["method"] = f"voxel envelope (res {cfg['vox_res']}){tag}"
|
| 177 |
+
return meta
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def build_volume(stl_path, out_msh, preset=DEFAULT_PRESET) -> dict:
|
| 181 |
+
"""External-flow tet mesh around the body surface.
|
| 182 |
+
|
| 183 |
+
Primary path reparametrizes the surface (classifySurfaces + createGeometry): nice smooth
|
| 184 |
+
patches, but gmsh CANNOT reparametrize a high-genus surface, so it fails on cars/aircraft
|
| 185 |
+
envelopes (wheels/wings/props punch handles -> "Wrong topology of boundary mesh"). On that
|
| 186 |
+
failure we fall back to a reparametrization-FREE discrete mesh: the merged STL triangles are
|
| 187 |
+
used directly as the volume boundary, which meshes at ANY genus (just no smooth patches)."""
|
| 188 |
+
cfg = PRESETS[preset]
|
| 189 |
+
import gmsh
|
| 190 |
+
|
| 191 |
+
def _build(discrete):
|
| 192 |
+
# interruptible=False -> skip gmsh's signal.signal(SIGINT) install, which raises
|
| 193 |
+
# "signal only works in main thread" when meshing runs on a background worker thread.
|
| 194 |
+
gmsh.initialize(interruptible=False)
|
| 195 |
+
gmsh.option.setNumber("General.Terminal", 0)
|
| 196 |
+
gmsh.option.setNumber("Geometry.Tolerance", 1e-4)
|
| 197 |
+
gmsh.option.setNumber("Mesh.ToleranceInitialDelaunay", 1e-6)
|
| 198 |
+
gmsh.option.setNumber("Mesh.Algorithm3D", 1)
|
| 199 |
+
gmsh.model.add("v2app")
|
| 200 |
+
try:
|
| 201 |
+
gmsh.merge(str(stl_path))
|
| 202 |
+
if not discrete: # reparametrize the STL into smooth CAD patches
|
| 203 |
+
gmsh.model.mesh.classifySurfaces(math.radians(40), True, True, math.radians(180))
|
| 204 |
+
gmsh.model.mesh.createGeometry()
|
| 205 |
+
body_surfs = [e[1] for e in gmsh.model.getEntities(2)]
|
| 206 |
+
if not body_surfs:
|
| 207 |
+
raise RuntimeError("no body surface recovered from STL")
|
| 208 |
+
body_loop = gmsh.model.geo.addSurfaceLoop(body_surfs)
|
| 209 |
+
box_surfs, cls = _add_box_surfaces(gmsh)
|
| 210 |
+
box_loop = gmsh.model.geo.addSurfaceLoop(box_surfs)
|
| 211 |
+
vol = gmsh.model.geo.addVolume([box_loop, body_loop])
|
| 212 |
+
gmsh.model.geo.synchronize()
|
| 213 |
+
gmsh.model.addPhysicalGroup(3, [vol], name="fluid")
|
| 214 |
+
gmsh.model.addPhysicalGroup(2, cls["inlet"], name="inlet")
|
| 215 |
+
gmsh.model.addPhysicalGroup(2, cls["outlet"], name="outlet")
|
| 216 |
+
gmsh.model.addPhysicalGroup(2, cls["farfield"], name="farfield")
|
| 217 |
+
gmsh.model.addPhysicalGroup(2, body_surfs, name="wall")
|
| 218 |
+
# size field: fine near body, coarse far. Sampling 100 (600 is pathologically slow).
|
| 219 |
+
gmsh.model.mesh.field.add("Distance", 1)
|
| 220 |
+
gmsh.model.mesh.field.setNumbers(1, "SurfacesList", body_surfs)
|
| 221 |
+
gmsh.model.mesh.field.setNumber(1, "Sampling", 100)
|
| 222 |
+
gmsh.model.mesh.field.add("Threshold", 2)
|
| 223 |
+
gmsh.model.mesh.field.setNumber(2, "InField", 1)
|
| 224 |
+
gmsh.model.mesh.field.setNumber(2, "SizeMin", cfg["h_min"])
|
| 225 |
+
gmsh.model.mesh.field.setNumber(2, "SizeMax", cfg["h_max"])
|
| 226 |
+
gmsh.model.mesh.field.setNumber(2, "DistMin", cfg["dist_min"])
|
| 227 |
+
gmsh.model.mesh.field.setNumber(2, "DistMax", cfg["dist_max"])
|
| 228 |
+
gmsh.model.mesh.field.setAsBackgroundMesh(2)
|
| 229 |
+
gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0)
|
| 230 |
+
gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0)
|
| 231 |
+
gmsh.option.setNumber("Mesh.MeshSizeMin", cfg["h_min"])
|
| 232 |
+
# curvature refinement only makes sense on the reparametrized patches
|
| 233 |
+
gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0 if discrete else cfg["curv"])
|
| 234 |
+
gmsh.model.mesh.generate(3)
|
| 235 |
+
try:
|
| 236 |
+
gmsh.model.mesh.optimize("Netgen")
|
| 237 |
+
except Exception:
|
| 238 |
+
pass
|
| 239 |
+
out = Path(out_msh); out.parent.mkdir(parents=True, exist_ok=True)
|
| 240 |
+
gmsh.write(str(out))
|
| 241 |
+
n_nodes = gmsh.model.mesh.getNodes()[0].size
|
| 242 |
+
return {"n_body_surfs": len(body_surfs), "n_nodes_approx": int(n_nodes),
|
| 243 |
+
"mesher": "discrete" if discrete else "reparam"}
|
| 244 |
+
finally:
|
| 245 |
+
gmsh.finalize()
|
| 246 |
+
|
| 247 |
+
try:
|
| 248 |
+
return _build(discrete=False)
|
| 249 |
+
except Exception:
|
| 250 |
+
return _build(discrete=True) # robust fallback: meshes any genus (F1, cars, ...)
|
code/ezflow_v3/app/run_app.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Launcher for the EZFlow v3 web app (turbulent-RANS GNN predictor).
|
| 2 |
+
|
| 3 |
+
python ezflow_v3/app/run_app.py -> http://127.0.0.1:8000
|
| 4 |
+
|
| 5 |
+
Serves the TMLR paper's seed-0 models (HybridFlow / GeoReNet) with a model selector,
|
| 6 |
+
model-vs-model compare, robust STL meshing, slicing, point probe, and CSV export.
|
| 7 |
+
This supersedes the old v1 app under app/ (which used the archived ezflow_gnn poc_v4).
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
import os, sys, webbrowser
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import uvicorn
|
| 13 |
+
|
| 14 |
+
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
| 15 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 16 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 21 |
+
os.chdir(str(REPO_ROOT))
|
| 22 |
+
url = "http://127.0.0.1:8000"
|
| 23 |
+
print(f"EZFlow v3 app -> {url} (models: HybridFlow / GeoReNet, seed-0 TMLR checkpoints)", flush=True)
|
| 24 |
+
try:
|
| 25 |
+
webbrowser.open(url)
|
| 26 |
+
except Exception:
|
| 27 |
+
pass
|
| 28 |
+
import ezflow_v3.app.serve as serve
|
| 29 |
+
uvicorn.run(serve.app, host="127.0.0.1", port=8000, log_level="info", reload=False)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
main()
|
code/ezflow_v3/app/serve.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI server for the EZFlow v2 web app (GeoReNet / HybridFlow / Transolver /
|
| 2 |
+
mean(G,T,H) ensemble). Geometry -> v2 graph -> chosen model -> fields -> 3D viewer.
|
| 3 |
+
Mirrors the v1 app's UX (procedural/STL geometry, 3D body + slice planes) but serves
|
| 4 |
+
the v2 turbulent-RANS models with a model selector.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
import os, shutil, tempfile, hashlib, io, time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
| 12 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 13 |
+
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Response
|
| 14 |
+
from fastapi.staticfiles import StaticFiles
|
| 15 |
+
from fastapi.responses import HTMLResponse
|
| 16 |
+
from pydantic import BaseModel
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pyvista as pv
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from ezflow_v3.app import infer_app
|
| 22 |
+
from ezflow_v3.app.shape_generator import (create_cylinder, create_sphere, create_box,
|
| 23 |
+
create_capsule, create_cone, create_torus)
|
| 24 |
+
|
| 25 |
+
HERE = Path(__file__).resolve().parent
|
| 26 |
+
FRONTEND = HERE / "frontend"
|
| 27 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 28 |
+
CURRENT_GRID: Optional[pv.UnstructuredGrid] = None
|
| 29 |
+
_MESH_CACHE: dict = {"sig": None, "data": None} # geometry mesh cache (reused across Re/yaw/model)
|
| 30 |
+
FIELD_KEYS = ["velocity_mag", "u", "v", "w", "pressure", "k", "omega", "nut"]
|
| 31 |
+
|
| 32 |
+
app = FastAPI(title="EZFlow v3 — turbulent-RANS GNN predictor (HybridFlow / GeoReNet)")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@app.on_event("startup")
|
| 36 |
+
def _warmup_models():
|
| 37 |
+
"""Load both seed-0 checkpoints AND run one dummy forward at startup, so the first user
|
| 38 |
+
prediction (and its reported timing) reflects pure inference rather than the one-time weight
|
| 39 |
+
load and CUDA kernel compilation."""
|
| 40 |
+
for tag in {t for tags in infer_app.MODELS.values() for t in tags}:
|
| 41 |
+
try:
|
| 42 |
+
infer_app.get_model(tag, DEVICE)
|
| 43 |
+
print(f"[warmup] loaded {tag}", flush=True)
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"[warmup] skip {tag}: {e}", flush=True)
|
| 46 |
+
try:
|
| 47 |
+
pts = np.random.rand(3000, 3).astype(np.float32)
|
| 48 |
+
wall = np.random.randint(0, 3000, size=(400, 3))
|
| 49 |
+
for name in infer_app.MODELS:
|
| 50 |
+
infer_app.predict_fields(pts, None, wall, name, 1e4, 0.0, DEVICE)
|
| 51 |
+
print("[warmup] forward pass compiled", flush=True)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"[warmup] forward warmup skipped: {e}", flush=True)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@app.middleware("http")
|
| 57 |
+
async def _no_cache(request, call_next):
|
| 58 |
+
"""Never cache (HTML/JS/CSS) so the browser always loads the latest build."""
|
| 59 |
+
resp = await call_next(request)
|
| 60 |
+
resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
|
| 61 |
+
resp.headers["Pragma"] = "no-cache"
|
| 62 |
+
return resp
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class SliceRequest(BaseModel):
|
| 66 |
+
normal_axis: str
|
| 67 |
+
position: float
|
| 68 |
+
field_type: str
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@app.get("/api/models")
|
| 72 |
+
async def models():
|
| 73 |
+
return {"models": infer_app.available_models(), "default": infer_app.DEFAULT_MODEL}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@app.post("/api/predict")
|
| 77 |
+
async def predict(
|
| 78 |
+
shape_type: str = Form(...),
|
| 79 |
+
model_name: str = Form(infer_app.DEFAULT_MODEL),
|
| 80 |
+
radius: Optional[float] = Form(None),
|
| 81 |
+
height: Optional[float] = Form(None),
|
| 82 |
+
length: Optional[float] = Form(None),
|
| 83 |
+
width: Optional[float] = Form(None),
|
| 84 |
+
box_height: Optional[float] = Form(None),
|
| 85 |
+
minor_radius: Optional[float] = Form(None),
|
| 86 |
+
Re: float = Form(1000.0),
|
| 87 |
+
yaw_deg: float = Form(0.0),
|
| 88 |
+
resolution: str = Form("medium"),
|
| 89 |
+
model_b: str = Form(""),
|
| 90 |
+
file: Optional[UploadFile] = File(None),
|
| 91 |
+
):
|
| 92 |
+
global CURRENT_GRID
|
| 93 |
+
if model_name not in infer_app.MODELS:
|
| 94 |
+
raise HTTPException(status_code=400, detail=f"Unknown model: {model_name}")
|
| 95 |
+
if resolution not in ("coarse", "medium", "fine"):
|
| 96 |
+
resolution = "medium"
|
| 97 |
+
temp_dir = None
|
| 98 |
+
try:
|
| 99 |
+
# geometry signature: the mesh depends on geometry + resolution only (not on
|
| 100 |
+
# Re/yaw/model), so changing the condition or model reuses the cached mesh and
|
| 101 |
+
# only re-runs inference -- much faster for sweeps.
|
| 102 |
+
if shape_type == "custom":
|
| 103 |
+
if not file:
|
| 104 |
+
raise HTTPException(status_code=400, detail="Custom shape requires an STL file")
|
| 105 |
+
file_bytes = await file.read()
|
| 106 |
+
sig = ("custom", hashlib.md5(file_bytes).hexdigest(), resolution)
|
| 107 |
+
else:
|
| 108 |
+
sig = (shape_type, radius, height, length, width, box_height, minor_radius, resolution)
|
| 109 |
+
|
| 110 |
+
if _MESH_CACHE["sig"] == sig and _MESH_CACHE["data"] is not None:
|
| 111 |
+
pts, tets, wall_tris, geom, minfo = _MESH_CACHE["data"]
|
| 112 |
+
print(f"[predict] reuse cached mesh ({shape_type}, {resolution})", flush=True)
|
| 113 |
+
else:
|
| 114 |
+
temp_dir = Path(tempfile.mkdtemp())
|
| 115 |
+
stl_path = temp_dir / "geom.stl"
|
| 116 |
+
if shape_type == "cylinder":
|
| 117 |
+
create_cylinder(radius, height, stl_path)
|
| 118 |
+
elif shape_type == "sphere":
|
| 119 |
+
create_sphere(radius, stl_path)
|
| 120 |
+
elif shape_type == "box":
|
| 121 |
+
create_box(length, width, box_height, stl_path)
|
| 122 |
+
elif shape_type == "capsule":
|
| 123 |
+
create_capsule(height, radius, stl_path)
|
| 124 |
+
elif shape_type == "cone":
|
| 125 |
+
create_cone(radius, height, stl_path)
|
| 126 |
+
elif shape_type == "torus":
|
| 127 |
+
create_torus(radius, minor_radius, stl_path)
|
| 128 |
+
elif shape_type == "custom":
|
| 129 |
+
with open(stl_path, "wb") as f:
|
| 130 |
+
f.write(file_bytes)
|
| 131 |
+
else:
|
| 132 |
+
raise HTTPException(status_code=400, detail=f"Unknown shape type: {shape_type}")
|
| 133 |
+
print(f"[predict] meshing {shape_type} (res={resolution})", flush=True)
|
| 134 |
+
pts, tets, wall_tris, geom, minfo = infer_app.mesh_stl(stl_path, temp_dir, resolution=resolution)
|
| 135 |
+
_MESH_CACHE["sig"] = sig
|
| 136 |
+
_MESH_CACHE["data"] = (pts, tets, wall_tris, geom, minfo)
|
| 137 |
+
|
| 138 |
+
# inference (always; Re/yaw/model may have changed)
|
| 139 |
+
print(f"[predict] model={model_name} Re={Re} yaw={yaw_deg}", flush=True)
|
| 140 |
+
t_inf = time.perf_counter()
|
| 141 |
+
fields = infer_app.predict_fields(pts, tets, wall_tris, model_name, Re, yaw_deg, DEVICE)
|
| 142 |
+
params_m = infer_app.param_count(model_name, DEVICE)
|
| 143 |
+
cd_a, cl_a = infer_app.pressure_forces(pts, wall_tris, fields["p"], yaw_deg, geom.get("A_ref", 1.0))
|
| 144 |
+
|
| 145 |
+
# 3) build + cache the volume grid for slicing (ALL output fields)
|
| 146 |
+
cells = np.hstack([np.full((tets.shape[0], 1), 4), tets]).astype(np.int64).ravel()
|
| 147 |
+
types = np.full(tets.shape[0], pv.CellType.TETRA, dtype=np.uint8)
|
| 148 |
+
CURRENT_GRID = pv.UnstructuredGrid(cells, types, pts.astype(float))
|
| 149 |
+
U = np.asarray(fields["U"])
|
| 150 |
+
CURRENT_GRID.point_data["velocity"] = U # vector (for arrows)
|
| 151 |
+
CURRENT_GRID.point_data["velocity_mag"] = np.linalg.norm(U, axis=1)
|
| 152 |
+
CURRENT_GRID.point_data["u"] = U[:, 0]
|
| 153 |
+
CURRENT_GRID.point_data["v"] = U[:, 1]
|
| 154 |
+
CURRENT_GRID.point_data["w"] = U[:, 2]
|
| 155 |
+
CURRENT_GRID.point_data["pressure"] = np.asarray(fields["p"])
|
| 156 |
+
CURRENT_GRID.point_data["k"] = np.asarray(fields["k"])
|
| 157 |
+
CURRENT_GRID.point_data["omega"] = np.asarray(fields["omega"])
|
| 158 |
+
CURRENT_GRID.point_data["nut"] = np.asarray(fields["nut"])
|
| 159 |
+
# optional model compare: run a 2nd model on the SAME mesh, store difference fields
|
| 160 |
+
compare = None
|
| 161 |
+
if model_b and model_b in infer_app.MODELS and model_b != model_name:
|
| 162 |
+
fb = infer_app.predict_fields(pts, tets, wall_tris, model_b, Re, yaw_deg, DEVICE)
|
| 163 |
+
Ub = np.asarray(fb["U"])
|
| 164 |
+
cd_b, cl_b = infer_app.pressure_forces(pts, wall_tris, fb["p"], yaw_deg, geom.get("A_ref", 1.0))
|
| 165 |
+
diff = {
|
| 166 |
+
"velocity_mag_diff": np.linalg.norm(U, axis=1) - np.linalg.norm(Ub, axis=1),
|
| 167 |
+
"u_diff": U[:, 0] - Ub[:, 0], "v_diff": U[:, 1] - Ub[:, 1], "w_diff": U[:, 2] - Ub[:, 2],
|
| 168 |
+
"pressure_diff": np.asarray(fields["p"]) - np.asarray(fb["p"]),
|
| 169 |
+
"k_diff": np.asarray(fields["k"]) - np.asarray(fb["k"]),
|
| 170 |
+
"omega_diff": np.asarray(fields["omega"]) - np.asarray(fb["omega"]),
|
| 171 |
+
"nut_diff": np.asarray(fields["nut"]) - np.asarray(fb["nut"]),
|
| 172 |
+
}
|
| 173 |
+
bvals = {
|
| 174 |
+
"velocity_mag_b": np.linalg.norm(Ub, axis=1),
|
| 175 |
+
"u_b": Ub[:, 0], "v_b": Ub[:, 1], "w_b": Ub[:, 2],
|
| 176 |
+
"pressure_b": np.asarray(fb["p"]), "k_b": np.asarray(fb["k"]),
|
| 177 |
+
"omega_b": np.asarray(fb["omega"]), "nut_b": np.asarray(fb["nut"]),
|
| 178 |
+
}
|
| 179 |
+
for kk, vv in {**diff, **bvals}.items():
|
| 180 |
+
CURRENT_GRID.point_data[kk] = np.asarray(vv)
|
| 181 |
+
compare = {"model_b": model_b,
|
| 182 |
+
"params_m": round(infer_app.param_count(model_b, DEVICE), 2),
|
| 183 |
+
"forces": {"Cd": round(cd_b, 4), "Cl": round(cl_b, 4)},
|
| 184 |
+
"fields_diff": list(diff.keys()), "fields_b": list(bvals.keys())}
|
| 185 |
+
|
| 186 |
+
timing_ms = round((time.perf_counter() - t_inf) * 1000.0, 1) # GNN inference (A, + B if compared)
|
| 187 |
+
extra_keys = (compare["fields_diff"] + compare["fields_b"]) if compare else []
|
| 188 |
+
keys_for_range = list(FIELD_KEYS) + extra_keys
|
| 189 |
+
ranges = {k: [float(CURRENT_GRID.point_data[k].min()),
|
| 190 |
+
float(CURRENT_GRID.point_data[k].max())] for k in keys_for_range}
|
| 191 |
+
if temp_dir:
|
| 192 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 193 |
+
return {
|
| 194 |
+
"wall_tris": np.asarray(wall_tris).tolist(),
|
| 195 |
+
"coords": pts.tolist(),
|
| 196 |
+
"geom_meta": geom,
|
| 197 |
+
"mesh_meta": minfo,
|
| 198 |
+
"device": str(DEVICE),
|
| 199 |
+
"model": {"name": model_name, "params_m": round(params_m, 2),
|
| 200 |
+
"members": infer_app.MODELS[model_name]},
|
| 201 |
+
"forces": {"Cd": round(cd_a, 4), "Cl": round(cl_a, 4)},
|
| 202 |
+
"timing_ms": timing_ms,
|
| 203 |
+
"bounds": list(CURRENT_GRID.bounds),
|
| 204 |
+
"ranges": ranges,
|
| 205 |
+
"fields": FIELD_KEYS,
|
| 206 |
+
"compare": compare,
|
| 207 |
+
}
|
| 208 |
+
except HTTPException:
|
| 209 |
+
if temp_dir:
|
| 210 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 211 |
+
raise
|
| 212 |
+
except Exception as e:
|
| 213 |
+
if temp_dir:
|
| 214 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 215 |
+
print(f"[predict] error: {e}", flush=True)
|
| 216 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@app.post("/api/slice")
|
| 220 |
+
async def slice_grid(req: SliceRequest):
|
| 221 |
+
global CURRENT_GRID
|
| 222 |
+
if CURRENT_GRID is None:
|
| 223 |
+
raise HTTPException(status_code=400, detail="No active prediction; run a prediction first.")
|
| 224 |
+
try:
|
| 225 |
+
normal = {"x": (1, 0, 0), "y": (0, 1, 0), "z": (0, 0, 1)}[req.normal_axis]
|
| 226 |
+
origin = [0, 0, 0]; origin[{"x": 0, "y": 1, "z": 2}[req.normal_axis]] = req.position
|
| 227 |
+
sl = CURRENT_GRID.slice(normal=normal, origin=tuple(origin))
|
| 228 |
+
faces, i, raw = [], 0, sl.faces
|
| 229 |
+
while i < len(raw):
|
| 230 |
+
n = raw[i]; verts = raw[i + 1:i + 1 + n]
|
| 231 |
+
for j in range(1, n - 1):
|
| 232 |
+
faces.append([int(verts[0]), int(verts[j]), int(verts[j + 1])])
|
| 233 |
+
i += n + 1
|
| 234 |
+
field = req.field_type if req.field_type in sl.point_data else "velocity_mag"
|
| 235 |
+
return {
|
| 236 |
+
"points": sl.points.tolist(),
|
| 237 |
+
"faces": faces,
|
| 238 |
+
"scalars": sl.point_data[field].tolist(),
|
| 239 |
+
"vectors": sl.point_data["velocity"].tolist() if "velocity" in sl.point_data else [],
|
| 240 |
+
}
|
| 241 |
+
except Exception as e:
|
| 242 |
+
print(f"[slice] error: {e}", flush=True)
|
| 243 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class ProbeRequest(BaseModel):
|
| 247 |
+
x: float
|
| 248 |
+
y: float
|
| 249 |
+
z: float
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@app.post("/api/probe")
|
| 253 |
+
async def probe(req: ProbeRequest):
|
| 254 |
+
"""Nearest-node query: all field values at the clicked 3D point."""
|
| 255 |
+
if CURRENT_GRID is None:
|
| 256 |
+
raise HTTPException(status_code=400, detail="No active prediction; run one first.")
|
| 257 |
+
pts = np.asarray(CURRENT_GRID.points)
|
| 258 |
+
d = pts - np.array([req.x, req.y, req.z], dtype=float)
|
| 259 |
+
i = int(np.argmin((d * d).sum(axis=1)))
|
| 260 |
+
vals = {k: float(CURRENT_GRID.point_data[k][i]) for k in FIELD_KEYS}
|
| 261 |
+
vel = CURRENT_GRID.point_data["velocity"][i]
|
| 262 |
+
return {"node": i, "point": [float(v) for v in pts[i]],
|
| 263 |
+
"velocity_vec": [float(v) for v in vel], "values": vals}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.get("/api/export")
|
| 267 |
+
async def export_csv():
|
| 268 |
+
"""Download the full predicted field at every mesh node as CSV."""
|
| 269 |
+
if CURRENT_GRID is None:
|
| 270 |
+
raise HTTPException(status_code=400, detail="No active prediction; run one first.")
|
| 271 |
+
pts = np.asarray(CURRENT_GRID.points)
|
| 272 |
+
cols = ["x", "y", "z"] + FIELD_KEYS
|
| 273 |
+
arr = np.column_stack([pts[:, 0], pts[:, 1], pts[:, 2]]
|
| 274 |
+
+ [np.asarray(CURRENT_GRID.point_data[k]) for k in FIELD_KEYS])
|
| 275 |
+
buf = io.StringIO()
|
| 276 |
+
buf.write(",".join(cols) + "\n")
|
| 277 |
+
for row in arr:
|
| 278 |
+
buf.write(",".join(f"{v:.6g}" for v in row) + "\n")
|
| 279 |
+
return Response(content=buf.getvalue(), media_type="text/csv",
|
| 280 |
+
headers={"Content-Disposition": "attachment; filename=ezflow_fields.csv"})
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class FieldRequest(BaseModel):
|
| 284 |
+
field: str
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@app.post("/api/surface")
|
| 288 |
+
async def surface(req: FieldRequest):
|
| 289 |
+
"""Per-node values of one field over the whole mesh (aligned with `coords`), so the client
|
| 290 |
+
can paint the body surface by e.g. predicted wall pressure. Only the wall nodes are visible."""
|
| 291 |
+
if CURRENT_GRID is None:
|
| 292 |
+
raise HTTPException(status_code=400, detail="No active prediction; run one first.")
|
| 293 |
+
field = req.field if req.field in CURRENT_GRID.point_data else "pressure"
|
| 294 |
+
vals = np.asarray(CURRENT_GRID.point_data[field]).reshape(-1)
|
| 295 |
+
return {"field": field, "values": vals.tolist(),
|
| 296 |
+
"range": [float(vals.min()), float(vals.max())]}
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class StreamRequest(BaseModel):
|
| 300 |
+
n: int = 12
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@app.post("/api/streamlines")
|
| 304 |
+
async def streamlines(req: StreamRequest):
|
| 305 |
+
"""Forward streamlines of the predicted velocity, seeded on an n x n grid just downstream of
|
| 306 |
+
the inlet plane. Returns polylines with per-point speed |U| for coloring."""
|
| 307 |
+
if CURRENT_GRID is None:
|
| 308 |
+
raise HTTPException(status_code=400, detail="No active prediction; run one first.")
|
| 309 |
+
g = CURRENT_GRID
|
| 310 |
+
b = g.bounds
|
| 311 |
+
n = max(3, min(int(req.n or 12), 26))
|
| 312 |
+
xr, yr, zr = b[1] - b[0], b[3] - b[2], b[5] - b[4]
|
| 313 |
+
x0 = b[0] + 0.03 * xr
|
| 314 |
+
ys = np.linspace(b[2] + 0.12 * yr, b[3] - 0.12 * yr, n)
|
| 315 |
+
zs = np.linspace(b[4] + 0.12 * zr, b[5] - 0.12 * zr, n)
|
| 316 |
+
YY, ZZ = np.meshgrid(ys, zs)
|
| 317 |
+
seeds = np.column_stack([np.full(YY.size, x0), YY.ravel(), ZZ.ravel()]).astype(float)
|
| 318 |
+
try:
|
| 319 |
+
strl = g.streamlines_from_source(
|
| 320 |
+
pv.PolyData(seeds), vectors="velocity", integration_direction="forward",
|
| 321 |
+
initial_step_length=0.2, max_steps=4000, terminal_speed=1e-4)
|
| 322 |
+
except Exception as e:
|
| 323 |
+
raise HTTPException(status_code=500, detail=f"streamline integration failed: {e}")
|
| 324 |
+
pts = np.asarray(strl.points)
|
| 325 |
+
if pts.size == 0 or "velocity" not in strl.point_data:
|
| 326 |
+
return {"lines": [], "range": [0.0, 1.0]}
|
| 327 |
+
umag = np.linalg.norm(np.asarray(strl.point_data["velocity"]), axis=1)
|
| 328 |
+
lines, raw, i = [], np.asarray(strl.lines), 0
|
| 329 |
+
while i < len(raw):
|
| 330 |
+
cnt = int(raw[i]); idx = raw[i + 1:i + 1 + cnt]
|
| 331 |
+
if cnt >= 2:
|
| 332 |
+
lines.append({"points": pts[idx].tolist(), "scalars": umag[idx].tolist()})
|
| 333 |
+
i += cnt + 1
|
| 334 |
+
return {"lines": lines, "range": [float(umag.min()), float(umag.max())]}
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
app.mount("/static", StaticFiles(directory=str(FRONTEND)), name="static")
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@app.get("/", response_class=HTMLResponse)
|
| 341 |
+
async def index():
|
| 342 |
+
return HTMLResponse((FRONTEND / "index.html").read_text(encoding="utf-8"))
|
code/ezflow_v3/app/shape_generator.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Procedural watertight STL shapes (trimesh) for the v2 app. Geometry-neutral."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import trimesh
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _save(mesh, out_path: Path):
|
| 8 |
+
mesh.vertices -= mesh.bounds.mean(axis=0) # center
|
| 9 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 10 |
+
mesh.export(str(out_path))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def create_cylinder(radius, height, out_path):
|
| 14 |
+
_save(trimesh.creation.cylinder(radius=radius, height=height), out_path)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def create_sphere(radius, out_path):
|
| 18 |
+
_save(trimesh.creation.icosphere(subdivisions=3, radius=radius), out_path)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def create_box(length, width, height, out_path):
|
| 22 |
+
_save(trimesh.creation.box(extents=[length, width, height]), out_path)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def create_capsule(height, radius, out_path):
|
| 26 |
+
_save(trimesh.creation.capsule(height=height, radius=radius), out_path)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def create_cone(radius, height, out_path):
|
| 30 |
+
_save(trimesh.creation.cone(radius=radius, height=height), out_path)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def create_torus(major_radius, minor_radius, out_path):
|
| 34 |
+
_save(trimesh.creation.torus(major_radius=major_radius, minor_radius=minor_radius), out_path)
|
code/ezflow_v3/baselines/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ezflow_v2/baselines — external neural-operator baselines
|
| 2 |
+
|
| 3 |
+
For a high-impact submission we must compare GeoReNet against current SOTA neural
|
| 4 |
+
operators, not only the original MeshGraphNet. Per the lit review, the two required
|
| 5 |
+
baselines are **Transolver** (ICML 2024) and **GINO** (NeurIPS 2023).
|
| 6 |
+
|
| 7 |
+
Approach (user-chosen): **Transolver first, then decide on GINO.** We use each
|
| 8 |
+
method's **official model code inside our training/eval harness** — same data
|
| 9 |
+
(`cache_v2`), same split, loss, augmentation, and `paper2/eval_table.py` — so the
|
| 10 |
+
comparison is apples-to-apples.
|
| 11 |
+
|
| 12 |
+
## Transolver (in progress)
|
| 13 |
+
- Official repo vendored under `Transolver-main/` (downloaded zip; git not installed).
|
| 14 |
+
We load `Car-Design-ShapeNetCar/models/Transolver.py` **verbatim** (the 3D
|
| 15 |
+
point-cloud Physics-Attention model).
|
| 16 |
+
- `transolver_wrap.py` — thin wrapper: feeds our graphs as
|
| 17 |
+
`cat([pos, node_features, broadcast(Re,yaw globals)])` so Transolver gets the
|
| 18 |
+
**same conditioning** GeoReNet's FiLM uses (fair); returns `[N, 7]`.
|
| 19 |
+
- Train: `train_v5.py --model transolver --tag transolver --cache cache_v2 --epochs 160 --batch 1`.
|
| 20 |
+
~3.88M params (≈ GeoReNet's 3.28M); **~45 s/epoch, ~1.2 GB VRAM** (attention-only,
|
| 21 |
+
much faster than the GNNs). Evaluated by `paper2/eval_table.py` (Transolver branch).
|
| 22 |
+
|
| 23 |
+
### ⚠️ Dependency lesson (important)
|
| 24 |
+
`pip install timm` (Transolver's only non-obvious dep) **silently upgraded torch
|
| 25 |
+
2.11.0+cu128 → 2.12.1+cpu**, killing CUDA. Fix applied:
|
| 26 |
+
- removed `timm`/`torchvision`; restored `torch==2.11.0+cu128` via
|
| 27 |
+
`pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cu128 --no-deps --force-reinstall`;
|
| 28 |
+
- **stubbed the one symbol Transolver needs** (`timm.models.layers.trunc_normal_`
|
| 29 |
+
→ `torch.nn.init.trunc_normal_`) in `transolver_wrap._stub_timm()`, so **timm is
|
| 30 |
+
no longer required**. `einops` (pure-python) is kept.
|
| 31 |
+
- **Rule:** never `pip install` a package that depends on torch without `--no-deps`
|
| 32 |
+
(or check it won't move the pinned `torch==2.11.0+cu128`).
|
| 33 |
+
|
| 34 |
+
## GINO (pending — decide after Transolver)
|
| 35 |
+
GINO (GNO+FNO, `neuraloperator` library, SDF + latent grid) is heavier and more
|
| 36 |
+
dependency-sensitive (risk of another torch conflict; FNO on a latent grid may
|
| 37 |
+
strain the 8 GB GPU). If the official path is painful, fall back to a faithful
|
| 38 |
+
in-framework reimplementation. Decision deferred until Transolver lands.
|
code/ezfl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te-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
develop-eggs/
|
| 13 |
+
dist/
|
| 14 |
+
downloads/
|
| 15 |
+
eggs/
|
| 16 |
+
.eggs/
|
| 17 |
+
lib/
|
| 18 |
+
lib64/
|
| 19 |
+
parts/
|
| 20 |
+
sdist/
|
| 21 |
+
var/
|
| 22 |
+
wheels/
|
| 23 |
+
share/python-wheels/
|
| 24 |
+
*.egg-info/
|
| 25 |
+
.installed.cfg
|
| 26 |
+
*.egg
|
| 27 |
+
MANIFEST
|
| 28 |
+
|
| 29 |
+
# PyInstaller
|
| 30 |
+
# Usually these files are written by a python script from a template
|
| 31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 32 |
+
*.manifest
|
| 33 |
+
*.spec
|
| 34 |
+
|
| 35 |
+
# Installer logs
|
| 36 |
+
pip-log.txt
|
| 37 |
+
pip-delete-this-directory.txt
|
| 38 |
+
|
| 39 |
+
# Unit test / coverage reports
|
| 40 |
+
htmlcov/
|
| 41 |
+
.tox/
|
| 42 |
+
.nox/
|
| 43 |
+
.coverage
|
| 44 |
+
.coverage.*
|
| 45 |
+
.cache
|
| 46 |
+
nosetests.xml
|
| 47 |
+
coverage.xml
|
| 48 |
+
*.cover
|
| 49 |
+
*.py,cover
|
| 50 |
+
.hypothesis/
|
| 51 |
+
.pytest_cache/
|
| 52 |
+
cover/
|
| 53 |
+
|
| 54 |
+
# Translations
|
| 55 |
+
*.mo
|
| 56 |
+
*.pot
|
| 57 |
+
|
| 58 |
+
# Django stuff:
|
| 59 |
+
*.log
|
| 60 |
+
local_settings.py
|
| 61 |
+
db.sqlite3
|
| 62 |
+
db.sqlite3-journal
|
| 63 |
+
|
| 64 |
+
# Flask stuff:
|
| 65 |
+
instance/
|
| 66 |
+
.webassets-cache
|
| 67 |
+
|
| 68 |
+
# Scrapy stuff:
|
| 69 |
+
.scrapy
|
| 70 |
+
|
| 71 |
+
# Sphinx documentation
|
| 72 |
+
docs/_build/
|
| 73 |
+
|
| 74 |
+
# PyBuilder
|
| 75 |
+
.pybuilder/
|
| 76 |
+
target/
|
| 77 |
+
|
| 78 |
+
# Jupyter Notebook
|
| 79 |
+
.ipynb_checkpoints
|
| 80 |
+
|
| 81 |
+
# IPython
|
| 82 |
+
profile_default/
|
| 83 |
+
ipython_config.py
|
| 84 |
+
|
| 85 |
+
# pyenv
|
| 86 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 87 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 88 |
+
# .python-version
|
| 89 |
+
|
| 90 |
+
# pipenv
|
| 91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 94 |
+
# install all needed dependencies.
|
| 95 |
+
#Pipfile.lock
|
| 96 |
+
|
| 97 |
+
# poetry
|
| 98 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 99 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 100 |
+
# commonly ignored for libraries.
|
| 101 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 102 |
+
#poetry.lock
|
| 103 |
+
|
| 104 |
+
# pdm
|
| 105 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 106 |
+
#pdm.lock
|
| 107 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
| 108 |
+
# in version control.
|
| 109 |
+
# https://pdm.fming.dev/#use-with-ide
|
| 110 |
+
.pdm.toml
|
| 111 |
+
|
| 112 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 113 |
+
__pypackages__/
|
| 114 |
+
|
| 115 |
+
# Celery stuff
|
| 116 |
+
celerybeat-schedule
|
| 117 |
+
celerybeat.pid
|
| 118 |
+
|
| 119 |
+
# SageMath parsed files
|
| 120 |
+
*.sage.py
|
| 121 |
+
|
| 122 |
+
# Environments
|
| 123 |
+
.env
|
| 124 |
+
.venv
|
| 125 |
+
env/
|
| 126 |
+
venv/
|
| 127 |
+
ENV/
|
| 128 |
+
env.bak/
|
| 129 |
+
venv.bak/
|
| 130 |
+
|
| 131 |
+
# Spyder project settings
|
| 132 |
+
.spyderproject
|
| 133 |
+
.spyproject
|
| 134 |
+
|
| 135 |
+
# Rope project settings
|
| 136 |
+
.ropeproject
|
| 137 |
+
|
| 138 |
+
# mkdocs documentation
|
| 139 |
+
/site
|
| 140 |
+
|
| 141 |
+
# mypy
|
| 142 |
+
.mypy_cache/
|
| 143 |
+
.dmypy.json
|
| 144 |
+
dmypy.json
|
| 145 |
+
|
| 146 |
+
# Pyre type checker
|
| 147 |
+
.pyre/
|
| 148 |
+
|
| 149 |
+
# pytype static type analyzer
|
| 150 |
+
.pytype/
|
| 151 |
+
|
| 152 |
+
# Cython debug symbols
|
| 153 |
+
cython_debug/
|
| 154 |
+
|
| 155 |
+
# PyCharm
|
| 156 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 157 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 158 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 159 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 160 |
+
#.idea/
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/LICENSE
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## ODC Open Database License (ODbL)
|
| 2 |
+
|
| 3 |
+
### Preamble
|
| 4 |
+
|
| 5 |
+
The Open Database License (ODbL) is a license agreement intended to
|
| 6 |
+
allow users to freely share, modify, and use this Database while
|
| 7 |
+
maintaining this same freedom for others. Many databases are covered by
|
| 8 |
+
copyright, and therefore this document licenses these rights. Some
|
| 9 |
+
jurisdictions, mainly in the European Union, have specific rights that
|
| 10 |
+
cover databases, and so the ODbL addresses these rights, too. Finally,
|
| 11 |
+
the ODbL is also an agreement in contract for users of this Database to
|
| 12 |
+
act in certain ways in return for accessing this Database.
|
| 13 |
+
|
| 14 |
+
Databases can contain a wide variety of types of content (images,
|
| 15 |
+
audiovisual material, and sounds all in the same database, for example),
|
| 16 |
+
and so the ODbL only governs the rights over the Database, and not the
|
| 17 |
+
contents of the Database individually. Licensors should use the ODbL
|
| 18 |
+
together with another license for the contents, if the contents have a
|
| 19 |
+
single set of rights that uniformly covers all of the contents. If the
|
| 20 |
+
contents have multiple sets of different rights, Licensors should
|
| 21 |
+
describe what rights govern what contents together in the individual
|
| 22 |
+
record or in some other way that clarifies what rights apply.
|
| 23 |
+
|
| 24 |
+
Sometimes the contents of a database, or the database itself, can be
|
| 25 |
+
covered by other rights not addressed here (such as private contracts,
|
| 26 |
+
trade mark over the name, or privacy rights / data protection rights
|
| 27 |
+
over information in the contents), and so you are advised that you may
|
| 28 |
+
have to consult other documents or clear other rights before doing
|
| 29 |
+
activities not covered by this License.
|
| 30 |
+
|
| 31 |
+
------
|
| 32 |
+
|
| 33 |
+
The Licensor (as defined below)
|
| 34 |
+
|
| 35 |
+
and
|
| 36 |
+
|
| 37 |
+
You (as defined below)
|
| 38 |
+
|
| 39 |
+
agree as follows:
|
| 40 |
+
|
| 41 |
+
### 1.0 Definitions of Capitalised Words
|
| 42 |
+
|
| 43 |
+
"Collective Database" – Means this Database in unmodified form as part
|
| 44 |
+
of a collection of independent databases in themselves that together are
|
| 45 |
+
assembled into a collective whole. A work that constitutes a Collective
|
| 46 |
+
Database will not be considered a Derivative Database.
|
| 47 |
+
|
| 48 |
+
"Convey" – As a verb, means Using the Database, a Derivative Database,
|
| 49 |
+
or the Database as part of a Collective Database in any way that enables
|
| 50 |
+
a Person to make or receive copies of the Database or a Derivative
|
| 51 |
+
Database. Conveying does not include interaction with a user through a
|
| 52 |
+
computer network, or creating and Using a Produced Work, where no
|
| 53 |
+
transfer of a copy of the Database or a Derivative Database occurs.
|
| 54 |
+
"Contents" – The contents of this Database, which includes the
|
| 55 |
+
information, independent works, or other material collected into the
|
| 56 |
+
Database. For example, the contents of the Database could be factual
|
| 57 |
+
data or works such as images, audiovisual material, text, or sounds.
|
| 58 |
+
|
| 59 |
+
"Database" – A collection of material (the Contents) arranged in a
|
| 60 |
+
systematic or methodical way and individually accessible by electronic
|
| 61 |
+
or other means offered under the terms of this License.
|
| 62 |
+
|
| 63 |
+
"Database Directive" – Means Directive 96/9/EC of the European
|
| 64 |
+
Parliament and of the Council of 11 March 1996 on the legal protection
|
| 65 |
+
of databases, as amended or succeeded.
|
| 66 |
+
|
| 67 |
+
"Database Right" – Means rights resulting from the Chapter III ("sui
|
| 68 |
+
generis") rights in the Database Directive (as amended and as transposed
|
| 69 |
+
by member states), which includes the Extraction and Re-utilisation of
|
| 70 |
+
the whole or a Substantial part of the Contents, as well as any similar
|
| 71 |
+
rights available in the relevant jurisdiction under Section 10.4.
|
| 72 |
+
|
| 73 |
+
"Derivative Database" – Means a database based upon the Database, and
|
| 74 |
+
includes any translation, adaptation, arrangement, modification, or any
|
| 75 |
+
other alteration of the Database or of a Substantial part of the
|
| 76 |
+
Contents. This includes, but is not limited to, Extracting or
|
| 77 |
+
Re-utilising the whole or a Substantial part of the Contents in a new
|
| 78 |
+
Database.
|
| 79 |
+
|
| 80 |
+
"Extraction" – Means the permanent or temporary transfer of all or a
|
| 81 |
+
Substantial part of the Contents to another medium by any means or in
|
| 82 |
+
any form.
|
| 83 |
+
|
| 84 |
+
"License" – Means this license agreement and is both a license of rights
|
| 85 |
+
such as copyright and Database Rights and an agreement in contract.
|
| 86 |
+
|
| 87 |
+
"Licensor" – Means the Person that offers the Database under the terms
|
| 88 |
+
of this License.
|
| 89 |
+
|
| 90 |
+
"Person" – Means a natural or legal person or a body of persons
|
| 91 |
+
corporate or incorporate.
|
| 92 |
+
|
| 93 |
+
"Produced Work" – a work (such as an image, audiovisual material, text,
|
| 94 |
+
or sounds) resulting from using the whole or a Substantial part of the
|
| 95 |
+
Contents (via a search or other query) from this Database, a Derivative
|
| 96 |
+
Database, or this Database as part of a Collective Database.
|
| 97 |
+
|
| 98 |
+
"Publicly" – means to Persons other than You or under Your control by
|
| 99 |
+
either more than 50% ownership or by the power to direct their
|
| 100 |
+
activities (such as contracting with an independent consultant).
|
| 101 |
+
|
| 102 |
+
"Re-utilisation" – means any form of making available to the public all
|
| 103 |
+
or a Substantial part of the Contents by the distribution of copies, by
|
| 104 |
+
renting, by online or other forms of transmission.
|
| 105 |
+
|
| 106 |
+
"Substantial" – Means substantial in terms of quantity or quality or a
|
| 107 |
+
combination of both. The repeated and systematic Extraction or
|
| 108 |
+
Re-utilisation of insubstantial parts of the Contents may amount to the
|
| 109 |
+
Extraction or Re-utilisation of a Substantial part of the Contents.
|
| 110 |
+
|
| 111 |
+
"Use" – As a verb, means doing any act that is restricted by copyright
|
| 112 |
+
or Database Rights whether in the original medium or any other; and
|
| 113 |
+
includes without limitation distributing, copying, publicly performing,
|
| 114 |
+
publicly displaying, and preparing derivative works of the Database, as
|
| 115 |
+
well as modifying the Database as may be technically necessary to use it
|
| 116 |
+
in a different mode or format.
|
| 117 |
+
|
| 118 |
+
"You" – Means a Person exercising rights under this License who has not
|
| 119 |
+
previously violated the terms of this License with respect to the
|
| 120 |
+
Database, or who has received express permission from the Licensor to
|
| 121 |
+
exercise rights under this License despite a previous violation.
|
| 122 |
+
|
| 123 |
+
Words in the singular include the plural and vice versa.
|
| 124 |
+
|
| 125 |
+
### 2.0 What this License covers
|
| 126 |
+
|
| 127 |
+
2.1. Legal effect of this document. This License is:
|
| 128 |
+
|
| 129 |
+
a. A license of applicable copyright and neighbouring rights;
|
| 130 |
+
|
| 131 |
+
b. A license of the Database Right; and
|
| 132 |
+
|
| 133 |
+
c. An agreement in contract between You and the Licensor.
|
| 134 |
+
|
| 135 |
+
2.2 Legal rights covered. This License covers the legal rights in the
|
| 136 |
+
Database, including:
|
| 137 |
+
|
| 138 |
+
a. Copyright. Any copyright or neighbouring rights in the Database.
|
| 139 |
+
The copyright licensed includes any individual elements of the
|
| 140 |
+
Database, but does not cover the copyright over the Contents
|
| 141 |
+
independent of this Database. See Section 2.4 for details. Copyright
|
| 142 |
+
law varies between jurisdictions, but is likely to cover: the Database
|
| 143 |
+
model or schema, which is the structure, arrangement, and organisation
|
| 144 |
+
of the Database, and can also include the Database tables and table
|
| 145 |
+
indexes; the data entry and output sheets; and the Field names of
|
| 146 |
+
Contents stored in the Database;
|
| 147 |
+
|
| 148 |
+
b. Database Rights. Database Rights only extend to the Extraction and
|
| 149 |
+
Re-utilisation of the whole or a Substantial part of the Contents.
|
| 150 |
+
Database Rights can apply even when there is no copyright over the
|
| 151 |
+
Database. Database Rights can also apply when the Contents are removed
|
| 152 |
+
from the Database and are selected and arranged in a way that would
|
| 153 |
+
not infringe any applicable copyright; and
|
| 154 |
+
|
| 155 |
+
c. Contract. This is an agreement between You and the Licensor for
|
| 156 |
+
access to the Database. In return you agree to certain conditions of
|
| 157 |
+
use on this access as outlined in this License.
|
| 158 |
+
|
| 159 |
+
2.3 Rights not covered.
|
| 160 |
+
|
| 161 |
+
a. This License does not apply to computer programs used in the making
|
| 162 |
+
or operation of the Database;
|
| 163 |
+
|
| 164 |
+
b. This License does not cover any patents over the Contents or the
|
| 165 |
+
Database; and
|
| 166 |
+
|
| 167 |
+
c. This License does not cover any trademarks associated with the
|
| 168 |
+
Database.
|
| 169 |
+
|
| 170 |
+
2.4 Relationship to Contents in the Database. The individual items of
|
| 171 |
+
the Contents contained in this Database may be covered by other rights,
|
| 172 |
+
including copyright, patent, data protection, privacy, or personality
|
| 173 |
+
rights, and this License does not cover any rights (other than Database
|
| 174 |
+
Rights or in contract) in individual Contents contained in the Database.
|
| 175 |
+
For example, if used on a Database of images (the Contents), this
|
| 176 |
+
License would not apply to copyright over individual images, which could
|
| 177 |
+
have their own separate licenses, or one single license covering all of
|
| 178 |
+
the rights over the images.
|
| 179 |
+
|
| 180 |
+
### 3.0 Rights granted
|
| 181 |
+
|
| 182 |
+
3.1 Subject to the terms and conditions of this License, the Licensor
|
| 183 |
+
grants to You a worldwide, royalty-free, non-exclusive, terminable (but
|
| 184 |
+
only under Section 9) license to Use the Database for the duration of
|
| 185 |
+
any applicable copyright and Database Rights. These rights explicitly
|
| 186 |
+
include commercial use, and do not exclude any field of endeavour. To
|
| 187 |
+
the extent possible in the relevant jurisdiction, these rights may be
|
| 188 |
+
exercised in all media and formats whether now known or created in the
|
| 189 |
+
future.
|
| 190 |
+
|
| 191 |
+
The rights granted cover, for example:
|
| 192 |
+
|
| 193 |
+
a. Extraction and Re-utilisation of the whole or a Substantial part of
|
| 194 |
+
the Contents;
|
| 195 |
+
|
| 196 |
+
b. Creation of Derivative Databases;
|
| 197 |
+
|
| 198 |
+
c. Creation of Collective Databases;
|
| 199 |
+
|
| 200 |
+
d. Creation of temporary or permanent reproductions by any means and
|
| 201 |
+
in any form, in whole or in part, including of any Derivative
|
| 202 |
+
Databases or as a part of Collective Databases; and
|
| 203 |
+
|
| 204 |
+
e. Distribution, communication, display, lending, making available, or
|
| 205 |
+
performance to the public by any means and in any form, in whole or in
|
| 206 |
+
part, including of any Derivative Database or as a part of Collective
|
| 207 |
+
Databases.
|
| 208 |
+
|
| 209 |
+
3.2 Compulsory license schemes. For the avoidance of doubt:
|
| 210 |
+
|
| 211 |
+
a. Non-waivable compulsory license schemes. In those jurisdictions in
|
| 212 |
+
which the right to collect royalties through any statutory or
|
| 213 |
+
compulsory licensing scheme cannot be waived, the Licensor reserves
|
| 214 |
+
the exclusive right to collect such royalties for any exercise by You
|
| 215 |
+
of the rights granted under this License;
|
| 216 |
+
|
| 217 |
+
b. Waivable compulsory license schemes. In those jurisdictions in
|
| 218 |
+
which the right to collect royalties through any statutory or
|
| 219 |
+
compulsory licensing scheme can be waived, the Licensor waives the
|
| 220 |
+
exclusive right to collect such royalties for any exercise by You of
|
| 221 |
+
the rights granted under this License; and,
|
| 222 |
+
|
| 223 |
+
c. Voluntary license schemes. The Licensor waives the right to collect
|
| 224 |
+
royalties, whether individually or, in the event that the Licensor is
|
| 225 |
+
a member of a collecting society that administers voluntary licensing
|
| 226 |
+
schemes, via that society, from any exercise by You of the rights
|
| 227 |
+
granted under this License.
|
| 228 |
+
|
| 229 |
+
3.3 The right to release the Database under different terms, or to stop
|
| 230 |
+
distributing or making available the Database, is reserved. Note that
|
| 231 |
+
this Database may be multiple-licensed, and so You may have the choice
|
| 232 |
+
of using alternative licenses for this Database. Subject to Section
|
| 233 |
+
10.4, all other rights not expressly granted by Licensor are reserved.
|
| 234 |
+
|
| 235 |
+
### 4.0 Conditions of Use
|
| 236 |
+
|
| 237 |
+
4.1 The rights granted in Section 3 above are expressly made subject to
|
| 238 |
+
Your complying with the following conditions of use. These are important
|
| 239 |
+
conditions of this License, and if You fail to follow them, You will be
|
| 240 |
+
in material breach of its terms.
|
| 241 |
+
|
| 242 |
+
4.2 Notices. If You Publicly Convey this Database, any Derivative
|
| 243 |
+
Database, or the Database as part of a Collective Database, then You
|
| 244 |
+
must:
|
| 245 |
+
|
| 246 |
+
a. Do so only under the terms of this License or another license
|
| 247 |
+
permitted under Section 4.4;
|
| 248 |
+
|
| 249 |
+
b. Include a copy of this License (or, as applicable, a license
|
| 250 |
+
permitted under Section 4.4) or its Uniform Resource Identifier (URI)
|
| 251 |
+
with the Database or Derivative Database, including both in the
|
| 252 |
+
Database or Derivative Database and in any relevant documentation; and
|
| 253 |
+
|
| 254 |
+
c. Keep intact any copyright or Database Right notices and notices
|
| 255 |
+
that refer to this License.
|
| 256 |
+
|
| 257 |
+
d. If it is not possible to put the required notices in a particular
|
| 258 |
+
file due to its structure, then You must include the notices in a
|
| 259 |
+
location (such as a relevant directory) where users would be likely to
|
| 260 |
+
look for it.
|
| 261 |
+
|
| 262 |
+
4.3 Notice for using output (Contents). Creating and Using a Produced
|
| 263 |
+
Work does not require the notice in Section 4.2. However, if you
|
| 264 |
+
Publicly Use a Produced Work, You must include a notice associated with
|
| 265 |
+
the Produced Work reasonably calculated to make any Person that uses,
|
| 266 |
+
views, accesses, interacts with, or is otherwise exposed to the Produced
|
| 267 |
+
Work aware that Content was obtained from the Database, Derivative
|
| 268 |
+
Database, or the Database as part of a Collective Database, and that it
|
| 269 |
+
is available under this License.
|
| 270 |
+
|
| 271 |
+
a. Example notice. The following text will satisfy notice under
|
| 272 |
+
Section 4.3:
|
| 273 |
+
|
| 274 |
+
Contains information from DATABASE NAME, which is made available
|
| 275 |
+
here under the Open Database License (ODbL).
|
| 276 |
+
|
| 277 |
+
DATABASE NAME should be replaced with the name of the Database and a
|
| 278 |
+
hyperlink to the URI of the Database. "Open Database License" should
|
| 279 |
+
contain a hyperlink to the URI of the text of this License. If
|
| 280 |
+
hyperlinks are not possible, You should include the plain text of the
|
| 281 |
+
required URI's with the above notice.
|
| 282 |
+
|
| 283 |
+
4.4 Share alike.
|
| 284 |
+
|
| 285 |
+
a. Any Derivative Database that You Publicly Use must be only under
|
| 286 |
+
the terms of:
|
| 287 |
+
|
| 288 |
+
i. This License;
|
| 289 |
+
|
| 290 |
+
ii. A later version of this License similar in spirit to this
|
| 291 |
+
License; or
|
| 292 |
+
|
| 293 |
+
iii. A compatible license.
|
| 294 |
+
|
| 295 |
+
If You license the Derivative Database under one of the licenses
|
| 296 |
+
mentioned in (iii), You must comply with the terms of that license.
|
| 297 |
+
|
| 298 |
+
b. For the avoidance of doubt, Extraction or Re-utilisation of the
|
| 299 |
+
whole or a Substantial part of the Contents into a new database is a
|
| 300 |
+
Derivative Database and must comply with Section 4.4.
|
| 301 |
+
|
| 302 |
+
c. Derivative Databases and Produced Works. A Derivative Database is
|
| 303 |
+
Publicly Used and so must comply with Section 4.4. if a Produced Work
|
| 304 |
+
created from the Derivative Database is Publicly Used.
|
| 305 |
+
|
| 306 |
+
d. Share Alike and additional Contents. For the avoidance of doubt,
|
| 307 |
+
You must not add Contents to Derivative Databases under Section 4.4 a
|
| 308 |
+
that are incompatible with the rights granted under this License.
|
| 309 |
+
|
| 310 |
+
e. Compatible licenses. Licensors may authorise a proxy to determine
|
| 311 |
+
compatible licenses under Section 4.4 a iii. If they do so, the
|
| 312 |
+
authorised proxy's public statement of acceptance of a compatible
|
| 313 |
+
license grants You permission to use the compatible license.
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
4.5 Limits of Share Alike. The requirements of Section 4.4 do not apply
|
| 317 |
+
in the following:
|
| 318 |
+
|
| 319 |
+
a. For the avoidance of doubt, You are not required to license
|
| 320 |
+
Collective Databases under this License if You incorporate this
|
| 321 |
+
Database or a Derivative Database in the collection, but this License
|
| 322 |
+
still applies to this Database or a Derivative Database as a part of
|
| 323 |
+
the Collective Database;
|
| 324 |
+
|
| 325 |
+
b. Using this Database, a Derivative Database, or this Database as
|
| 326 |
+
part of a Collective Database to create a Produced Work does not
|
| 327 |
+
create a Derivative Database for purposes of Section 4.4; and
|
| 328 |
+
|
| 329 |
+
c. Use of a Derivative Database internally within an organisation is
|
| 330 |
+
not to the public and therefore does not fall under the requirements
|
| 331 |
+
of Section 4.4.
|
| 332 |
+
|
| 333 |
+
4.6 Access to Derivative Databases. If You Publicly Use a Derivative
|
| 334 |
+
Database or a Produced Work from a Derivative Database, You must also
|
| 335 |
+
offer to recipients of the Derivative Database or Produced Work a copy
|
| 336 |
+
in a machine readable form of:
|
| 337 |
+
|
| 338 |
+
a. The entire Derivative Database; or
|
| 339 |
+
|
| 340 |
+
b. A file containing all of the alterations made to the Database or
|
| 341 |
+
the method of making the alterations to the Database (such as an
|
| 342 |
+
algorithm), including any additional Contents, that make up all the
|
| 343 |
+
differences between the Database and the Derivative Database.
|
| 344 |
+
|
| 345 |
+
The Derivative Database (under a.) or alteration file (under b.) must be
|
| 346 |
+
available at no more than a reasonable production cost for physical
|
| 347 |
+
distributions and free of charge if distributed over the internet.
|
| 348 |
+
|
| 349 |
+
4.7 Technological measures and additional terms
|
| 350 |
+
|
| 351 |
+
a. This License does not allow You to impose (except subject to
|
| 352 |
+
Section 4.7 b.) any terms or any technological measures on the
|
| 353 |
+
Database, a Derivative Database, or the whole or a Substantial part of
|
| 354 |
+
the Contents that alter or restrict the terms of this License, or any
|
| 355 |
+
rights granted under it, or have the effect or intent of restricting
|
| 356 |
+
the ability of any person to exercise those rights.
|
| 357 |
+
|
| 358 |
+
b. Parallel distribution. You may impose terms or technological
|
| 359 |
+
measures on the Database, a Derivative Database, or the whole or a
|
| 360 |
+
Substantial part of the Contents (a "Restricted Database") in
|
| 361 |
+
contravention of Section 4.74 a. only if You also make a copy of the
|
| 362 |
+
Database or a Derivative Database available to the recipient of the
|
| 363 |
+
Restricted Database:
|
| 364 |
+
|
| 365 |
+
i. That is available without additional fee;
|
| 366 |
+
|
| 367 |
+
ii. That is available in a medium that does not alter or restrict
|
| 368 |
+
the terms of this License, or any rights granted under it, or have
|
| 369 |
+
the effect or intent of restricting the ability of any person to
|
| 370 |
+
exercise those rights (an "Unrestricted Database"); and
|
| 371 |
+
|
| 372 |
+
iii. The Unrestricted Database is at least as accessible to the
|
| 373 |
+
recipient as a practical matter as the Restricted Database.
|
| 374 |
+
|
| 375 |
+
c. For the avoidance of doubt, You may place this Database or a
|
| 376 |
+
Derivative Database in an authenticated environment, behind a
|
| 377 |
+
password, or within a similar access control scheme provided that You
|
| 378 |
+
do not alter or restrict the terms of this License or any rights
|
| 379 |
+
granted under it or have the effect or intent of restricting the
|
| 380 |
+
ability of any person to exercise those rights.
|
| 381 |
+
|
| 382 |
+
4.8 Licensing of others. You may not sublicense the Database. Each time
|
| 383 |
+
You communicate the Database, the whole or Substantial part of the
|
| 384 |
+
Contents, or any Derivative Database to anyone else in any way, the
|
| 385 |
+
Licensor offers to the recipient a license to the Database on the same
|
| 386 |
+
terms and conditions as this License. You are not responsible for
|
| 387 |
+
enforcing compliance by third parties with this License, but You may
|
| 388 |
+
enforce any rights that You have over a Derivative Database. You are
|
| 389 |
+
solely responsible for any modifications of a Derivative Database made
|
| 390 |
+
by You or another Person at Your direction. You may not impose any
|
| 391 |
+
further restrictions on the exercise of the rights granted or affirmed
|
| 392 |
+
under this License.
|
| 393 |
+
|
| 394 |
+
### 5.0 Moral rights
|
| 395 |
+
|
| 396 |
+
5.1 Moral rights. This section covers moral rights, including any rights
|
| 397 |
+
to be identified as the author of the Database or to object to treatment
|
| 398 |
+
that would otherwise prejudice the author's honour and reputation, or
|
| 399 |
+
any other derogatory treatment:
|
| 400 |
+
|
| 401 |
+
a. For jurisdictions allowing waiver of moral rights, Licensor waives
|
| 402 |
+
all moral rights that Licensor may have in the Database to the fullest
|
| 403 |
+
extent possible by the law of the relevant jurisdiction under Section
|
| 404 |
+
10.4;
|
| 405 |
+
|
| 406 |
+
b. If waiver of moral rights under Section 5.1 a in the relevant
|
| 407 |
+
jurisdiction is not possible, Licensor agrees not to assert any moral
|
| 408 |
+
rights over the Database and waives all claims in moral rights to the
|
| 409 |
+
fullest extent possible by the law of the relevant jurisdiction under
|
| 410 |
+
Section 10.4; and
|
| 411 |
+
|
| 412 |
+
c. For jurisdictions not allowing waiver or an agreement not to assert
|
| 413 |
+
moral rights under Section 5.1 a and b, the author may retain their
|
| 414 |
+
moral rights over certain aspects of the Database.
|
| 415 |
+
|
| 416 |
+
Please note that some jurisdictions do not allow for the waiver of moral
|
| 417 |
+
rights, and so moral rights may still subsist over the Database in some
|
| 418 |
+
jurisdictions.
|
| 419 |
+
|
| 420 |
+
### 6.0 Fair dealing, Database exceptions, and other rights not affected
|
| 421 |
+
|
| 422 |
+
6.1 This License does not affect any rights that You or anyone else may
|
| 423 |
+
independently have under any applicable law to make any use of this
|
| 424 |
+
Database, including without limitation:
|
| 425 |
+
|
| 426 |
+
a. Exceptions to the Database Right including: Extraction of Contents
|
| 427 |
+
from non-electronic Databases for private purposes, Extraction for
|
| 428 |
+
purposes of illustration for teaching or scientific research, and
|
| 429 |
+
Extraction or Re-utilisation for public security or an administrative
|
| 430 |
+
or judicial procedure.
|
| 431 |
+
|
| 432 |
+
b. Fair dealing, fair use, or any other legally recognised limitation
|
| 433 |
+
or exception to infringement of copyright or other applicable laws.
|
| 434 |
+
|
| 435 |
+
6.2 This License does not affect any rights of lawful users to Extract
|
| 436 |
+
and Re-utilise insubstantial parts of the Contents, evaluated
|
| 437 |
+
quantitatively or qualitatively, for any purposes whatsoever, including
|
| 438 |
+
creating a Derivative Database (subject to other rights over the
|
| 439 |
+
Contents, see Section 2.4). The repeated and systematic Extraction or
|
| 440 |
+
Re-utilisation of insubstantial parts of the Contents may however amount
|
| 441 |
+
to the Extraction or Re-utilisation of a Substantial part of the
|
| 442 |
+
Contents.
|
| 443 |
+
|
| 444 |
+
### 7.0 Warranties and Disclaimer
|
| 445 |
+
|
| 446 |
+
7.1 The Database is licensed by the Licensor "as is" and without any
|
| 447 |
+
warranty of any kind, either express, implied, or arising by statute,
|
| 448 |
+
custom, course of dealing, or trade usage. Licensor specifically
|
| 449 |
+
disclaims any and all implied warranties or conditions of title,
|
| 450 |
+
non-infringement, accuracy or completeness, the presence or absence of
|
| 451 |
+
errors, fitness for a particular purpose, merchantability, or otherwise.
|
| 452 |
+
Some jurisdictions do not allow the exclusion of implied warranties, so
|
| 453 |
+
this exclusion may not apply to You.
|
| 454 |
+
|
| 455 |
+
### 8.0 Limitation of liability
|
| 456 |
+
|
| 457 |
+
8.1 Subject to any liability that may not be excluded or limited by law,
|
| 458 |
+
the Licensor is not liable for, and expressly excludes, all liability
|
| 459 |
+
for loss or damage however and whenever caused to anyone by any use
|
| 460 |
+
under this License, whether by You or by anyone else, and whether caused
|
| 461 |
+
by any fault on the part of the Licensor or not. This exclusion of
|
| 462 |
+
liability includes, but is not limited to, any special, incidental,
|
| 463 |
+
consequential, punitive, or exemplary damages such as loss of revenue,
|
| 464 |
+
data, anticipated profits, and lost business. This exclusion applies
|
| 465 |
+
even if the Licensor has been advised of the possibility of such
|
| 466 |
+
damages.
|
| 467 |
+
|
| 468 |
+
8.2 If liability may not be excluded by law, it is limited to actual and
|
| 469 |
+
direct financial loss to the extent it is caused by proved negligence on
|
| 470 |
+
the part of the Licensor.
|
| 471 |
+
|
| 472 |
+
### 9.0 Termination of Your rights under this License
|
| 473 |
+
|
| 474 |
+
9.1 Any breach by You of the terms and conditions of this License
|
| 475 |
+
automatically terminates this License with immediate effect and without
|
| 476 |
+
notice to You. For the avoidance of doubt, Persons who have received the
|
| 477 |
+
Database, the whole or a Substantial part of the Contents, Derivative
|
| 478 |
+
Databases, or the Database as part of a Collective Database from You
|
| 479 |
+
under this License will not have their licenses terminated provided
|
| 480 |
+
their use is in full compliance with this License or a license granted
|
| 481 |
+
under Section 4.8 of this License. Sections 1, 2, 7, 8, 9 and 10 will
|
| 482 |
+
survive any termination of this License.
|
| 483 |
+
|
| 484 |
+
9.2 If You are not in breach of the terms of this License, the Licensor
|
| 485 |
+
will not terminate Your rights under it.
|
| 486 |
+
|
| 487 |
+
9.3 Unless terminated under Section 9.1, this License is granted to You
|
| 488 |
+
for the duration of applicable rights in the Database.
|
| 489 |
+
|
| 490 |
+
9.4 Reinstatement of rights. If you cease any breach of the terms and
|
| 491 |
+
conditions of this License, then your full rights under this License
|
| 492 |
+
will be reinstated:
|
| 493 |
+
|
| 494 |
+
a. Provisionally and subject to permanent termination until the 60th
|
| 495 |
+
day after cessation of breach;
|
| 496 |
+
|
| 497 |
+
b. Permanently on the 60th day after cessation of breach unless
|
| 498 |
+
otherwise reasonably notified by the Licensor; or
|
| 499 |
+
|
| 500 |
+
c. Permanently if reasonably notified by the Licensor of the
|
| 501 |
+
violation, this is the first time You have received notice of
|
| 502 |
+
violation of this License from the Licensor, and You cure the
|
| 503 |
+
violation prior to 30 days after your receipt of the notice.
|
| 504 |
+
|
| 505 |
+
Persons subject to permanent termination of rights are not eligible to
|
| 506 |
+
be a recipient and receive a license under Section 4.8.
|
| 507 |
+
|
| 508 |
+
9.5 Notwithstanding the above, Licensor reserves the right to release
|
| 509 |
+
the Database under different license terms or to stop distributing or
|
| 510 |
+
making available the Database. Releasing the Database under different
|
| 511 |
+
license terms or stopping the distribution of the Database will not
|
| 512 |
+
withdraw this License (or any other license that has been, or is
|
| 513 |
+
required to be, granted under the terms of this License), and this
|
| 514 |
+
License will continue in full force and effect unless terminated as
|
| 515 |
+
stated above.
|
| 516 |
+
|
| 517 |
+
### 10.0 General
|
| 518 |
+
|
| 519 |
+
10.1 If any provision of this License is held to be invalid or
|
| 520 |
+
unenforceable, that must not affect the validity or enforceability of
|
| 521 |
+
the remainder of the terms and conditions of this License and each
|
| 522 |
+
remaining provision of this License shall be valid and enforced to the
|
| 523 |
+
fullest extent permitted by law.
|
| 524 |
+
|
| 525 |
+
10.2 This License is the entire agreement between the parties with
|
| 526 |
+
respect to the rights granted here over the Database. It replaces any
|
| 527 |
+
earlier understandings, agreements or representations with respect to
|
| 528 |
+
the Database.
|
| 529 |
+
|
| 530 |
+
10.3 If You are in breach of the terms of this License, You will not be
|
| 531 |
+
entitled to rely on the terms of this License or to complain of any
|
| 532 |
+
breach by the Licensor.
|
| 533 |
+
|
| 534 |
+
10.4 Choice of law. This License takes effect in and will be governed by
|
| 535 |
+
the laws of the relevant jurisdiction in which the License terms are
|
| 536 |
+
sought to be enforced. If the standard suite of rights granted under
|
| 537 |
+
applicable copyright law and Database Rights in the relevant
|
| 538 |
+
jurisdiction includes additional rights not granted under this License,
|
| 539 |
+
these additional rights are granted in this License in order to meet the
|
| 540 |
+
terms of this License.
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Transolver for Airfoil Design
|
| 2 |
+
|
| 3 |
+
**Paper Correction:** There is a typo in our descriptions about evaluation metrics for the physics fields of volume and surface. The paper's reported results are MSE (not Relative L2), which is completely the same as the AirfRANS paper. We are sincerely sorry for this mistake.
|
| 4 |
+
|
| 5 |
+
We test [Transolver](https://arxiv.org/abs/2402.02366) on practical design tasks. The airfoil design task requires the model to estimate the surrounding and surface physical quantities of a 2D airfoil under different Reynolds and angles of attacks.
|
| 6 |
+
|
| 7 |
+
<p align="center">
|
| 8 |
+
<img src=".\fig\task.png" height = "200" alt="" align=center />
|
| 9 |
+
<br><br>
|
| 10 |
+
<b>Figure 1.</b> Airfoil design task. Left: surrounding pressure; Right: x-direction wind speed.
|
| 11 |
+
</p>
|
| 12 |
+
|
| 13 |
+
## Get Started
|
| 14 |
+
|
| 15 |
+
This part of code is developed based on the [[AirfRANS]](https://github.com/Extrality/AirfRANS).
|
| 16 |
+
|
| 17 |
+
1. Install Python 3.8. For convenience, execute the following command.
|
| 18 |
+
|
| 19 |
+
```bash
|
| 20 |
+
pip install -r requirements.txt
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Note: You need to install [pytorch_geometric](https://github.com/pyg-team/pytorch_geometric).
|
| 24 |
+
|
| 25 |
+
2. Prepare Data.
|
| 26 |
+
|
| 27 |
+
The experiment data is provided by [[AirfRANS]](https://github.com/Extrality/AirfRANS). You can directly download it with this [link](https://data.isir.upmc.fr/extrality/NeurIPS_2022/Dataset.zip) (9.3GB).
|
| 28 |
+
|
| 29 |
+
3. Train and evaluate model. We provide the experiment scripts under the folder `./scripts/`. You can reproduce the experiment results as the following examples:
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
bash scripts/Transolver.sh # for Training Transolver (will take 20-24 hours on one single A100)
|
| 33 |
+
bash scripts/Evaluation.sh # for Evaluation
|
| 34 |
+
bash scripts/GraphSAGE.sh # for Training GraphSAGE (will take 30-36 hours on one single A100)
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Note: You need to change the argument `--my_path` to your dataset path.
|
| 38 |
+
|
| 39 |
+
4. Test model with different settings. This benchmark supports four types of settings.
|
| 40 |
+
|
| 41 |
+
| Settings | Argument |
|
| 42 |
+
| -------------------------------------------- | ------------- |
|
| 43 |
+
| Use full data | `-t full` |
|
| 44 |
+
| Use scarce data | `-t scarce` |
|
| 45 |
+
| Test on out-of-distribution Reynolds | `-t reynolds` |
|
| 46 |
+
| Test on out-of-distribution Angle of Attacks | `-t aoa` |
|
| 47 |
+
|
| 48 |
+
5. Develop your own model. Here are the instructions:
|
| 49 |
+
|
| 50 |
+
- Add the model file under folder `./models/`.
|
| 51 |
+
|
| 52 |
+
- Add the training details in `./params.yaml`. If you donot want to change setting, just copy other models' configuration.
|
| 53 |
+
|
| 54 |
+
- Add the model configuration into `./main.py`.
|
| 55 |
+
|
| 56 |
+
- Add a script file under folder `./scripts/` and change the argument `--model`.
|
| 57 |
+
|
| 58 |
+
## Main Results
|
| 59 |
+
|
| 60 |
+
Transolver achieves the consistent best performance in practical design tasks.
|
| 61 |
+
|
| 62 |
+
<p align="center">
|
| 63 |
+
<img src=".\fig\results.png" height = "300" alt="" align=center />
|
| 64 |
+
<br><br>
|
| 65 |
+
<b>Table 1.</b> Model comparisons on the practical design tasks.
|
| 66 |
+
</p>
|
| 67 |
+
|
| 68 |
+
## Citation
|
| 69 |
+
|
| 70 |
+
If you find this repo useful, please cite our paper.
|
| 71 |
+
|
| 72 |
+
```
|
| 73 |
+
@inproceedings{wu2024Transolver,
|
| 74 |
+
title={Transolver: A Fast Transformer Solver for PDEs on General Geometries},
|
| 75 |
+
author={Haixu Wu and Huakun Luo and Haowen Wang and Jianmin Wang and Mingsheng Long},
|
| 76 |
+
booktitle={International Conference on Machine Learning},
|
| 77 |
+
year={2024}
|
| 78 |
+
}
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
## Contact
|
| 82 |
+
|
| 83 |
+
If you have any questions or want to use the code, please contact [wuhx23@mails.tsinghua.edu.cn](mailto:wuhx23@mails.tsinghua.edu.cn).
|
| 84 |
+
|
| 85 |
+
## Acknowledgement
|
| 86 |
+
|
| 87 |
+
We appreciate the following github repos a lot for their valuable code base or datasets:
|
| 88 |
+
|
| 89 |
+
https://github.com/Extrality/AirfRANS
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/dataset/dataset.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pyvista as pv
|
| 3 |
+
from utils.reorganize import reorganize
|
| 4 |
+
import os.path as osp
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch_geometric.data import Data
|
| 8 |
+
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def cell_sampling_2d(cell_points, cell_attr=None):
|
| 13 |
+
'''
|
| 14 |
+
Sample points in a two dimensional cell via parallelogram sampling and triangle interpolation via barycentric coordinates. The vertices have to be ordered in a certain way.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
cell_points (array): Vertices of the 2 dimensional cells. Shape (N, 4) for N cells with 4 vertices.
|
| 18 |
+
cell_attr (array, optional): Features of the vertices of the 2 dimensional cells. Shape (N, 4, k) for N cells with 4 edges and k features.
|
| 19 |
+
If given shape (N, 4) it will resize it automatically in a (N, 4, 1) array. Default: ``None``
|
| 20 |
+
'''
|
| 21 |
+
# Sampling via triangulation of the cell and parallelogram sampling
|
| 22 |
+
v0, v1 = cell_points[:, 1] - cell_points[:, 0], cell_points[:, 3] - cell_points[:, 0]
|
| 23 |
+
v2, v3 = cell_points[:, 3] - cell_points[:, 2], cell_points[:, 1] - cell_points[:, 2]
|
| 24 |
+
a0, a1 = np.abs(np.linalg.det(np.hstack([v0[:, :2], v1[:, :2]]).reshape(-1, 2, 2))), np.abs(
|
| 25 |
+
np.linalg.det(np.hstack([v2[:, :2], v3[:, :2]]).reshape(-1, 2, 2)))
|
| 26 |
+
p = a0 / (a0 + a1)
|
| 27 |
+
index_triangle = np.random.binomial(1, p)[:, None]
|
| 28 |
+
u = np.random.uniform(size=(len(p), 2))
|
| 29 |
+
sampled_point = index_triangle * (u[:, 0:1] * v0 + u[:, 1:2] * v1) + (1 - index_triangle) * (
|
| 30 |
+
u[:, 0:1] * v2 + u[:, 1:2] * v3)
|
| 31 |
+
sampled_point_mirror = index_triangle * ((1 - u[:, 0:1]) * v0 + (1 - u[:, 1:2]) * v1) + (1 - index_triangle) * (
|
| 32 |
+
(1 - u[:, 0:1]) * v2 + (1 - u[:, 1:2]) * v3)
|
| 33 |
+
reflex = (u.sum(axis=1) > 1)
|
| 34 |
+
sampled_point[reflex] = sampled_point_mirror[reflex]
|
| 35 |
+
|
| 36 |
+
# Interpolation on a triangle via barycentric coordinates
|
| 37 |
+
if cell_attr is not None:
|
| 38 |
+
t0, t1, t2 = np.zeros_like(v0), index_triangle * v0 + (1 - index_triangle) * v2, index_triangle * v1 + (
|
| 39 |
+
1 - index_triangle) * v3
|
| 40 |
+
w = (t1[:, 1] - t2[:, 1]) * (t0[:, 0] - t2[:, 0]) + (t2[:, 0] - t1[:, 0]) * (t0[:, 1] - t2[:, 1])
|
| 41 |
+
w0 = (t1[:, 1] - t2[:, 1]) * (sampled_point[:, 0] - t2[:, 0]) + (t2[:, 0] - t1[:, 0]) * (
|
| 42 |
+
sampled_point[:, 1] - t2[:, 1])
|
| 43 |
+
w1 = (t2[:, 1] - t0[:, 1]) * (sampled_point[:, 0] - t2[:, 0]) + (t0[:, 0] - t2[:, 0]) * (
|
| 44 |
+
sampled_point[:, 1] - t2[:, 1])
|
| 45 |
+
w0, w1 = w0 / w, w1 / w
|
| 46 |
+
w2 = 1 - w0 - w1
|
| 47 |
+
|
| 48 |
+
if len(cell_attr.shape) == 2:
|
| 49 |
+
cell_attr = cell_attr[:, :, None]
|
| 50 |
+
attr0 = index_triangle * cell_attr[:, 0] + (1 - index_triangle) * cell_attr[:, 2]
|
| 51 |
+
attr1 = index_triangle * cell_attr[:, 1] + (1 - index_triangle) * cell_attr[:, 1]
|
| 52 |
+
attr2 = index_triangle * cell_attr[:, 3] + (1 - index_triangle) * cell_attr[:, 3]
|
| 53 |
+
sampled_attr = w0[:, None] * attr0 + w1[:, None] * attr1 + w2[:, None] * attr2
|
| 54 |
+
|
| 55 |
+
sampled_point += index_triangle * cell_points[:, 0] + (1 - index_triangle) * cell_points[:, 2]
|
| 56 |
+
|
| 57 |
+
return np.hstack([sampled_point[:, :2], sampled_attr]) if cell_attr is not None else sampled_point[:, :2]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def cell_sampling_1d(line_points, line_attr=None):
|
| 61 |
+
'''
|
| 62 |
+
Sample points in a one dimensional cell via linear sampling and interpolation.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
line_points (array): Edges of the 1 dimensional cells. Shape (N, 2) for N cells with 2 edges.
|
| 66 |
+
line_attr (array, optional): Features of the edges of the 1 dimensional cells. Shape (N, 2, k) for N cells with 2 edges and k features.
|
| 67 |
+
If given shape (N, 2) it will resize it automatically in a (N, 2, 1) array. Default: ``None``
|
| 68 |
+
'''
|
| 69 |
+
# Linear sampling
|
| 70 |
+
u = np.random.uniform(size=(len(line_points), 1))
|
| 71 |
+
sampled_point = u * line_points[:, 0] + (1 - u) * line_points[:, 1]
|
| 72 |
+
|
| 73 |
+
# Linear interpolation
|
| 74 |
+
if line_attr is not None:
|
| 75 |
+
if len(line_attr.shape) == 2:
|
| 76 |
+
line_attr = line_attr[:, :, None]
|
| 77 |
+
sampled_attr = u * line_attr[:, 0] + (1 - u) * line_attr[:, 1]
|
| 78 |
+
|
| 79 |
+
return np.hstack([sampled_point[:, :2], sampled_attr]) if line_attr is not None else sampled_point[:, :2]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def Dataset(set, norm=False, coef_norm=None, crop=None, sample=None, n_boot=int(5e5), surf_ratio=.1,
|
| 83 |
+
my_path='/data/path'):
|
| 84 |
+
'''
|
| 85 |
+
Create a list of simulation to input in a PyTorch Geometric DataLoader. Simulation are transformed by keeping vertices of the CFD mesh or
|
| 86 |
+
by sampling (uniformly or via the mesh density) points in the simulation cells.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
set (list): List of geometry names to include in the dataset.
|
| 90 |
+
norm (bool, optional): If norm is set to ``True``, the mean and the standard deviation of the dataset will be computed and returned.
|
| 91 |
+
Moreover, the dataset will be normalized by these quantities. Ignored when ``coef_norm`` is not None. Default: ``False``
|
| 92 |
+
coef_norm (tuple, optional): This has to be a tuple of the form (mean input, std input, mean output, std ouput) if not None.
|
| 93 |
+
The dataset generated will be normalized by those quantites. Default: ``None``
|
| 94 |
+
crop (list, optional): List of the vertices of the rectangular [xmin, xmax, ymin, ymax] box to crop simulations. Default: ``None``
|
| 95 |
+
sample (string, optional): Type of sampling. If ``None``, no sampling strategy is applied and the nodes of the CFD mesh are returned.
|
| 96 |
+
If ``uniform`` or ``mesh`` is chosen, uniform or mesh density sampling is applied on the domain. Default: ``None``
|
| 97 |
+
n_boot (int, optional): Used only if sample is not None, gives the size of the sampling for each simulation. Defaul: ``int(5e5)``
|
| 98 |
+
surf_ratio (float, optional): Used only if sample is not None, gives the ratio of point over the airfoil to sample with respect to point
|
| 99 |
+
in the volume. Default: ``0.1``
|
| 100 |
+
'''
|
| 101 |
+
if norm and coef_norm is not None:
|
| 102 |
+
raise ValueError('If coef_norm is not None and norm is True, the normalization will be done via coef_norm')
|
| 103 |
+
|
| 104 |
+
dataset = []
|
| 105 |
+
|
| 106 |
+
for k, s in enumerate(tqdm(set)):
|
| 107 |
+
# Get the 3D mesh, add the signed distance function and slice it to return in 2D
|
| 108 |
+
internal = pv.read(osp.join(my_path, s, s + '_internal.vtu'))
|
| 109 |
+
aerofoil = pv.read(osp.join(my_path, s, s + '_aerofoil.vtp'))
|
| 110 |
+
internal = internal.compute_cell_sizes(length=False, volume=False)
|
| 111 |
+
|
| 112 |
+
# Cropping if needed, crinkle is True.
|
| 113 |
+
if crop is not None:
|
| 114 |
+
bounds = (crop[0], crop[1], crop[2], crop[3], 0, 1)
|
| 115 |
+
internal = internal.clip_box(bounds=bounds, invert=False, crinkle=True)
|
| 116 |
+
|
| 117 |
+
# If sampling strategy is chosen, it will sample points in the cells of the simulation instead of directly taking the nodes of the mesh.
|
| 118 |
+
if sample is not None:
|
| 119 |
+
# Sample on a new point cloud
|
| 120 |
+
if sample == 'uniform': # Uniform sampling strategy
|
| 121 |
+
p = internal.cell_data['Area'] / internal.cell_data['Area'].sum()
|
| 122 |
+
sampled_cell_indices = np.random.choice(internal.n_cells, size=n_boot, p=p)
|
| 123 |
+
surf_p = aerofoil.cell_data['Length'] / aerofoil.cell_data['Length'].sum()
|
| 124 |
+
sampled_line_indices = np.random.choice(aerofoil.n_cells, size=int(n_boot * surf_ratio), p=surf_p)
|
| 125 |
+
elif sample == 'mesh': # Sample via mesh density
|
| 126 |
+
sampled_cell_indices = np.random.choice(internal.n_cells, size=n_boot)
|
| 127 |
+
sampled_line_indices = np.random.choice(aerofoil.n_cells, size=int(n_boot * surf_ratio))
|
| 128 |
+
|
| 129 |
+
cell_dict = internal.cells.reshape(-1, 5)[sampled_cell_indices, 1:]
|
| 130 |
+
cell_points = internal.points[cell_dict]
|
| 131 |
+
line_dict = aerofoil.lines.reshape(-1, 3)[sampled_line_indices, 1:]
|
| 132 |
+
line_points = aerofoil.points[line_dict]
|
| 133 |
+
|
| 134 |
+
# Geometry information
|
| 135 |
+
geom = -internal.point_data['implicit_distance'][cell_dict, None] # Signed distance function
|
| 136 |
+
Uinf, alpha = float(s.split('_')[2]), float(s.split('_')[3]) * np.pi / 180
|
| 137 |
+
# u = (np.array([np.cos(alpha), np.sin(alpha)])*Uinf).reshape(1, 2)*(internal.point_data['U'][cell_dict, :1] != 0)
|
| 138 |
+
u = (np.array([np.cos(alpha), np.sin(alpha)]) * Uinf).reshape(1, 2) * np.ones_like(
|
| 139 |
+
internal.point_data['U'][cell_dict, :1])
|
| 140 |
+
normal = np.zeros_like(u)
|
| 141 |
+
|
| 142 |
+
surf_geom = np.zeros_like(aerofoil.point_data['U'][line_dict, :1])
|
| 143 |
+
# surf_u = np.zeros_like(aerofoil.point_data['U'][line_dict, :2])
|
| 144 |
+
surf_u = (np.array([np.cos(alpha), np.sin(alpha)]) * Uinf).reshape(1, 2) * np.ones_like(
|
| 145 |
+
aerofoil.point_data['U'][line_dict, :1])
|
| 146 |
+
surf_normal = -aerofoil.point_data['Normals'][line_dict, :2]
|
| 147 |
+
|
| 148 |
+
attr = np.concatenate([u, geom, normal, internal.point_data['U'][cell_dict, :2],
|
| 149 |
+
internal.point_data['p'][cell_dict, None],
|
| 150 |
+
internal.point_data['nut'][cell_dict, None]], axis=-1)
|
| 151 |
+
surf_attr = np.concatenate([surf_u, surf_geom, surf_normal, aerofoil.point_data['U'][line_dict, :2],
|
| 152 |
+
aerofoil.point_data['p'][line_dict, None],
|
| 153 |
+
aerofoil.point_data['nut'][line_dict, None]], axis=-1)
|
| 154 |
+
sampled_points = cell_sampling_2d(cell_points, attr)
|
| 155 |
+
surf_sampled_points = cell_sampling_1d(line_points, surf_attr)
|
| 156 |
+
|
| 157 |
+
# Define the inputs and the targets
|
| 158 |
+
pos = sampled_points[:, :2]
|
| 159 |
+
init = sampled_points[:, :7]
|
| 160 |
+
target = sampled_points[:, 7:]
|
| 161 |
+
surf_pos = surf_sampled_points[:, :2]
|
| 162 |
+
surf_init = surf_sampled_points[:, :7]
|
| 163 |
+
surf_target = surf_sampled_points[:, 7:]
|
| 164 |
+
|
| 165 |
+
# Put everything in tensor
|
| 166 |
+
surf = torch.cat([torch.zeros(len(pos)), torch.ones(len(surf_pos))], dim=0)
|
| 167 |
+
pos = torch.cat([torch.tensor(pos, dtype=torch.float), torch.tensor(surf_pos, dtype=torch.float)], dim=0)
|
| 168 |
+
x = torch.cat([torch.tensor(init, dtype=torch.float), torch.tensor(surf_init, dtype=torch.float)], dim=0)
|
| 169 |
+
y = torch.cat([torch.tensor(target, dtype=torch.float), torch.tensor(surf_target, dtype=torch.float)],
|
| 170 |
+
dim=0)
|
| 171 |
+
|
| 172 |
+
else: # Keep the mesh nodes
|
| 173 |
+
surf_bool = (internal.point_data['U'][:, 0] == 0)
|
| 174 |
+
geom = -internal.point_data['implicit_distance'][:, None] # Signed distance function
|
| 175 |
+
Uinf, alpha = float(s.split('_')[2]), float(s.split('_')[3]) * np.pi / 180
|
| 176 |
+
u = (np.array([np.cos(alpha), np.sin(alpha)]) * Uinf).reshape(1, 2) * np.ones_like(
|
| 177 |
+
internal.point_data['U'][:, :1])
|
| 178 |
+
normal = np.zeros_like(u)
|
| 179 |
+
normal[surf_bool] = reorganize(aerofoil.points[:, :2], internal.points[surf_bool, :2],
|
| 180 |
+
-aerofoil.point_data['Normals'][:, :2])
|
| 181 |
+
|
| 182 |
+
attr = np.concatenate([u, geom, normal,
|
| 183 |
+
internal.point_data['U'][:, :2], internal.point_data['p'][:, None],
|
| 184 |
+
internal.point_data['nut'][:, None]], axis=-1)
|
| 185 |
+
|
| 186 |
+
pos = internal.points[:, :2]
|
| 187 |
+
init = np.concatenate([pos, attr[:, :5]], axis=1)
|
| 188 |
+
target = attr[:, 5:]
|
| 189 |
+
|
| 190 |
+
# Put everything in tensor
|
| 191 |
+
surf = torch.tensor(surf_bool)
|
| 192 |
+
pos = torch.tensor(pos, dtype=torch.float)
|
| 193 |
+
x = torch.tensor(init, dtype=torch.float)
|
| 194 |
+
y = torch.tensor(target, dtype=torch.float)
|
| 195 |
+
|
| 196 |
+
if norm and coef_norm is None:
|
| 197 |
+
if k == 0:
|
| 198 |
+
old_length = init.shape[0]
|
| 199 |
+
mean_in = init.mean(axis=0, dtype=np.double)
|
| 200 |
+
mean_out = target.mean(axis=0, dtype=np.double)
|
| 201 |
+
else:
|
| 202 |
+
new_length = old_length + init.shape[0]
|
| 203 |
+
mean_in += (init.sum(axis=0, dtype=np.double) - init.shape[0] * mean_in) / new_length
|
| 204 |
+
mean_out += (target.sum(axis=0, dtype=np.double) - init.shape[0] * mean_out) / new_length
|
| 205 |
+
old_length = new_length
|
| 206 |
+
|
| 207 |
+
data = Data(pos=pos, x=x, y=y, surf=surf.bool())
|
| 208 |
+
dataset.append(data)
|
| 209 |
+
|
| 210 |
+
if norm and coef_norm is None:
|
| 211 |
+
# Compute normalization
|
| 212 |
+
mean_in = mean_in.astype(np.single)
|
| 213 |
+
mean_out = mean_out.astype(np.single)
|
| 214 |
+
for k, data in enumerate(dataset):
|
| 215 |
+
|
| 216 |
+
if k == 0:
|
| 217 |
+
old_length = data.x.numpy().shape[0]
|
| 218 |
+
std_in = ((data.x.numpy() - mean_in) ** 2).sum(axis=0, dtype=np.double) / old_length
|
| 219 |
+
std_out = ((data.y.numpy() - mean_out) ** 2).sum(axis=0, dtype=np.double) / old_length
|
| 220 |
+
else:
|
| 221 |
+
new_length = old_length + data.x.numpy().shape[0]
|
| 222 |
+
std_in += (((data.x.numpy() - mean_in) ** 2).sum(axis=0, dtype=np.double) - data.x.numpy().shape[
|
| 223 |
+
0] * std_in) / new_length
|
| 224 |
+
std_out += (((data.y.numpy() - mean_out) ** 2).sum(axis=0, dtype=np.double) - data.x.numpy().shape[
|
| 225 |
+
0] * std_out) / new_length
|
| 226 |
+
old_length = new_length
|
| 227 |
+
|
| 228 |
+
std_in = np.sqrt(std_in).astype(np.single)
|
| 229 |
+
std_out = np.sqrt(std_out).astype(np.single)
|
| 230 |
+
|
| 231 |
+
# Normalize
|
| 232 |
+
for data in dataset:
|
| 233 |
+
data.x = (data.x - mean_in) / (std_in + 1e-8)
|
| 234 |
+
data.y = (data.y - mean_out) / (std_out + 1e-8)
|
| 235 |
+
|
| 236 |
+
coef_norm = (mean_in, std_in, mean_out, std_out)
|
| 237 |
+
dataset = (dataset, coef_norm)
|
| 238 |
+
|
| 239 |
+
elif coef_norm is not None:
|
| 240 |
+
# Normalize
|
| 241 |
+
for data in dataset:
|
| 242 |
+
data.x = (data.x - coef_norm[0]) / (coef_norm[1] + 1e-8)
|
| 243 |
+
data.y = (data.y - coef_norm[2]) / (coef_norm[3] + 1e-8)
|
| 244 |
+
|
| 245 |
+
return dataset
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/dataset/dataset_stats.ipynb
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [],
|
| 8 |
+
"source": [
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import json\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import seaborn as sns\n",
|
| 13 |
+
"import os.path as osp\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"NU = 1.56e-5\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"sets = ['full_train', 'scarce_train', 'reynolds_train', 'aoa_train', 'full_test', 'reynolds_test', 'aoa_test']\n",
|
| 18 |
+
"colors = ['cornflowerblue']*4 + ['burlywood']*3\n",
|
| 19 |
+
"data_dir = 'MY_ROOT_DIRECTORY'\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"for c, s in zip(colors, sets):\n",
|
| 22 |
+
" with open(osp.join(data_dir, 'manifest.json'), 'r') as f:\n",
|
| 23 |
+
" manifest = json.load(f)[s]\n",
|
| 24 |
+
"\n",
|
| 25 |
+
" us = []\n",
|
| 26 |
+
" angles = []\n",
|
| 27 |
+
" digits4 = []\n",
|
| 28 |
+
" digits5 = []\n",
|
| 29 |
+
" for sim in manifest:\n",
|
| 30 |
+
" params = sim.split('_')\n",
|
| 31 |
+
" us.append(float(params[2])/NU)\n",
|
| 32 |
+
" angles.append(float(params[3]))\n",
|
| 33 |
+
"\n",
|
| 34 |
+
" if len(params) == 7:\n",
|
| 35 |
+
" digits4.append(list(map(float, params[-3:])))\n",
|
| 36 |
+
" else:\n",
|
| 37 |
+
" digits5.append(list(map(float, params[-4:])))\n",
|
| 38 |
+
"\n",
|
| 39 |
+
" digits4 = np.array(digits4)\n",
|
| 40 |
+
" digits5 = np.array(digits5)\n",
|
| 41 |
+
"\n",
|
| 42 |
+
" sns.set()\n",
|
| 43 |
+
"\n",
|
| 44 |
+
" fig, ax = plt.subplots(3, 3, figsize = (12, 12))\n",
|
| 45 |
+
" ax[2, 1].hist(us, bins = 20, color = c)\n",
|
| 46 |
+
" ax[2, 1].set_title('Reynolds number')\n",
|
| 47 |
+
"\n",
|
| 48 |
+
" ax[2, 2].hist(angles, bins = 20, color = c)\n",
|
| 49 |
+
" ax[2, 2].set_xlabel('Degrees')\n",
|
| 50 |
+
" ax[2, 2].set_title('Angle of attack')\n",
|
| 51 |
+
"\n",
|
| 52 |
+
" ax[0, 0].hist(digits4[:, 0], bins = 20, color = c)\n",
|
| 53 |
+
" ax[0, 0].set_title(r'$1^{st}$ digit')\n",
|
| 54 |
+
"\n",
|
| 55 |
+
" ax[0, 1].hist(digits4[:, 1], bins = 20, color = c)\n",
|
| 56 |
+
" ax[0, 1].set_title(r'$2^{nd}$ digit')\n",
|
| 57 |
+
"\n",
|
| 58 |
+
" ax[0, 2].hist(digits4[:, 2], bins = 20, color = c)\n",
|
| 59 |
+
" ax[0, 2].set_title(r'$3^{rd}$ and $4^{th}$ digits')\n",
|
| 60 |
+
"\n",
|
| 61 |
+
" ax[1, 0].hist(digits5[:, 0], bins = 20, color = c)\n",
|
| 62 |
+
" ax[1, 0].set_title(r'$1^{st}$ digit')\n",
|
| 63 |
+
"\n",
|
| 64 |
+
" ax[1, 1].hist(digits5[:, 1], bins = 20, color = c)\n",
|
| 65 |
+
" ax[1, 1].set_title(r'$2^{nd}$ digit')\n",
|
| 66 |
+
"\n",
|
| 67 |
+
" ax[2, 0].hist(digits5[:, 2], bins = 2, color = c)\n",
|
| 68 |
+
" ax[2, 0].set_title(r'$3^{rd}$ digit')\n",
|
| 69 |
+
"\n",
|
| 70 |
+
" ax[1, 2].hist(digits5[:, 3], bins = 20, color = c)\n",
|
| 71 |
+
" ax[1, 2].set_title(r'$4^{th}$ and $5^{th}$ digits');\n",
|
| 72 |
+
" fig.savefig(s, bbox_inches = 'tight', dpi = 150)"
|
| 73 |
+
]
|
| 74 |
+
}
|
| 75 |
+
],
|
| 76 |
+
"metadata": {
|
| 77 |
+
"kernelspec": {
|
| 78 |
+
"display_name": "Python 3.9.12 ('isir')",
|
| 79 |
+
"language": "python",
|
| 80 |
+
"name": "python3"
|
| 81 |
+
},
|
| 82 |
+
"language_info": {
|
| 83 |
+
"codemirror_mode": {
|
| 84 |
+
"name": "ipython",
|
| 85 |
+
"version": 3
|
| 86 |
+
},
|
| 87 |
+
"file_extension": ".py",
|
| 88 |
+
"mimetype": "text/x-python",
|
| 89 |
+
"name": "python",
|
| 90 |
+
"nbconvert_exporter": "python",
|
| 91 |
+
"pygments_lexer": "ipython3",
|
| 92 |
+
"version": "3.9.12"
|
| 93 |
+
},
|
| 94 |
+
"orig_nbformat": 4,
|
| 95 |
+
"vscode": {
|
| 96 |
+
"interpreter": {
|
| 97 |
+
"hash": "d00e44851a3a4d5201bc229183e4c0de3fea7314717b82800f8d82d2168b4a23"
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
},
|
| 101 |
+
"nbformat": 4,
|
| 102 |
+
"nbformat_minor": 2
|
| 103 |
+
}
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/fig/results.png
ADDED
|
Git LFS Details
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/fig/task.png
ADDED
|
Git LFS Details
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/main.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse, yaml, json
|
| 2 |
+
import torch
|
| 3 |
+
import train
|
| 4 |
+
import utils.metrics as metrics
|
| 5 |
+
from dataset.dataset import Dataset
|
| 6 |
+
import os.path as osp
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
parser = argparse.ArgumentParser()
|
| 10 |
+
parser.add_argument('--model', help='The model you want to train, choose between MLP, GraphSAGE, PointNet, GUNet',
|
| 11 |
+
type=str)
|
| 12 |
+
parser.add_argument('-n', '--nmodel', help='Number of trained models for standard deviation estimation (default: 1)',
|
| 13 |
+
default=1, type=int)
|
| 14 |
+
parser.add_argument('-w', '--weight', help='Weight in front of the surface loss (default: 1)', default=1, type=float)
|
| 15 |
+
parser.add_argument('-t', '--task',
|
| 16 |
+
help='Task to train on. Choose between "full", "scarce", "reynolds" and "aoa" (default: full)',
|
| 17 |
+
default='full', type=str)
|
| 18 |
+
parser.add_argument('-s', '--score',
|
| 19 |
+
help='If you want to compute the score of the models on the associated test set. (default: 0)',
|
| 20 |
+
default=0, type=int)
|
| 21 |
+
parser.add_argument('--my_path',
|
| 22 |
+
default='/data/path', type=str)
|
| 23 |
+
parser.add_argument('--save_path',
|
| 24 |
+
default='metrics', type=str)
|
| 25 |
+
args = parser.parse_args()
|
| 26 |
+
|
| 27 |
+
with open(args.my_path + '/manifest.json', 'r') as f:
|
| 28 |
+
manifest = json.load(f)
|
| 29 |
+
|
| 30 |
+
manifest_train = manifest[args.task + '_train']
|
| 31 |
+
test_dataset = manifest[args.task + '_test'] if args.task != 'scarce' else manifest['full_test']
|
| 32 |
+
n = int(.1 * len(manifest_train))
|
| 33 |
+
train_dataset = manifest_train[:-n]
|
| 34 |
+
val_dataset = manifest_train[-n:]
|
| 35 |
+
print("start load data")
|
| 36 |
+
train_dataset, coef_norm = Dataset(train_dataset, norm=True, sample=None, my_path=args.my_path)
|
| 37 |
+
val_dataset = Dataset(val_dataset, sample=None, coef_norm=coef_norm, my_path=args.my_path)
|
| 38 |
+
print("load data finish")
|
| 39 |
+
# Cuda
|
| 40 |
+
use_cuda = torch.cuda.is_available()
|
| 41 |
+
device = 'cuda:0' if use_cuda else 'cpu'
|
| 42 |
+
if use_cuda:
|
| 43 |
+
print('Using GPU')
|
| 44 |
+
else:
|
| 45 |
+
print('Using CPU')
|
| 46 |
+
|
| 47 |
+
with open('params.yaml', 'r') as f: # hyperparameters of the model
|
| 48 |
+
hparams = yaml.safe_load(f)[args.model]
|
| 49 |
+
|
| 50 |
+
from models.MLP import MLP
|
| 51 |
+
|
| 52 |
+
models = []
|
| 53 |
+
for i in range(args.nmodel):
|
| 54 |
+
|
| 55 |
+
if args.model == 'Transolver':
|
| 56 |
+
from models.Transolver import Transolver
|
| 57 |
+
|
| 58 |
+
model = Transolver(n_hidden=256,
|
| 59 |
+
n_layers=8,
|
| 60 |
+
space_dim=7,
|
| 61 |
+
fun_dim=0,
|
| 62 |
+
n_head=8,
|
| 63 |
+
mlp_ratio=2,
|
| 64 |
+
out_dim=4,
|
| 65 |
+
slice_num=32,
|
| 66 |
+
unified_pos=1).cuda()
|
| 67 |
+
else:
|
| 68 |
+
encoder = MLP(hparams['encoder'], batch_norm=False)
|
| 69 |
+
decoder = MLP(hparams['decoder'], batch_norm=False)
|
| 70 |
+
if args.model == 'GraphSAGE':
|
| 71 |
+
from models.GraphSAGE import GraphSAGE
|
| 72 |
+
|
| 73 |
+
model = GraphSAGE(hparams, encoder, decoder)
|
| 74 |
+
|
| 75 |
+
elif args.model == 'PointNet':
|
| 76 |
+
from models.PointNet import PointNet
|
| 77 |
+
|
| 78 |
+
model = PointNet(hparams, encoder, decoder)
|
| 79 |
+
|
| 80 |
+
elif args.model == 'MLP':
|
| 81 |
+
from models.NN import NN
|
| 82 |
+
|
| 83 |
+
model = NN(hparams, encoder, decoder)
|
| 84 |
+
|
| 85 |
+
elif args.model == 'GUNet':
|
| 86 |
+
from models.GUNet import GUNet
|
| 87 |
+
|
| 88 |
+
model = GUNet(hparams, encoder, decoder)
|
| 89 |
+
|
| 90 |
+
log_path = osp.join(args.save_path, args.task, args.model) # path where you want to save log and figures
|
| 91 |
+
print('start training')
|
| 92 |
+
model = train.main(device, train_dataset, val_dataset, model, hparams, log_path,
|
| 93 |
+
criterion='MSE_weighted', val_iter=10, reg=args.weight, name_mod=args.model, val_sample=True)
|
| 94 |
+
print('end training')
|
| 95 |
+
models.append(model)
|
| 96 |
+
torch.save(models, osp.join(args.save_path, args.task, args.model, args.model))
|
| 97 |
+
|
| 98 |
+
if bool(args.score):
|
| 99 |
+
print('start score')
|
| 100 |
+
s = args.task + '_test' if args.task != 'scarce' else 'full_test'
|
| 101 |
+
coefs = metrics.Results_test(device, [models], [hparams], coef_norm, args.my_path, path_out='scores', n_test=3,
|
| 102 |
+
criterion='MSE', s=s)
|
| 103 |
+
# models can be a stack of the same model (for example MLP) on the task s, if you have another stack of another model (for example GraphSAGE)
|
| 104 |
+
# you can put in model argument [models_MLP, models_GraphSAGE] and it will output the results for both models (mean and std) in an ordered array.
|
| 105 |
+
np.save(osp.join('scores', args.task, 'true_coefs'), coefs[0])
|
| 106 |
+
np.save(osp.join('scores', args.task, 'pred_coefs_mean'), coefs[1])
|
| 107 |
+
np.save(osp.join('scores', args.task, 'pred_coefs_std'), coefs[2])
|
| 108 |
+
for n, file in enumerate(coefs[3]):
|
| 109 |
+
np.save(osp.join('scores', args.task, 'true_surf_coefs_' + str(n)), file)
|
| 110 |
+
for n, file in enumerate(coefs[4]):
|
| 111 |
+
np.save(osp.join('scores', args.task, 'surf_coefs_' + str(n)), file)
|
| 112 |
+
np.save(osp.join('scores', args.task, 'true_bls'), coefs[5])
|
| 113 |
+
np.save(osp.join('scores', args.task, 'bls'), coefs[6])
|
| 114 |
+
print('end score')
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/main_evaluation.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml, json
|
| 2 |
+
import torch
|
| 3 |
+
import utils.metrics as metrics
|
| 4 |
+
from dataset.dataset import Dataset
|
| 5 |
+
import os.path as osp
|
| 6 |
+
import argparse
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
parser = argparse.ArgumentParser()
|
| 10 |
+
parser.add_argument('--my_path', default='/data/path', type=str) # data save path
|
| 11 |
+
parser.add_argument('--save_path', default='./', type=str) # model save path
|
| 12 |
+
args = parser.parse_args()
|
| 13 |
+
|
| 14 |
+
# Compute the normalization used for the training
|
| 15 |
+
|
| 16 |
+
use_cuda = torch.cuda.is_available()
|
| 17 |
+
device = 'cuda:0' if use_cuda else 'cpu'
|
| 18 |
+
if use_cuda:
|
| 19 |
+
print('Using GPU')
|
| 20 |
+
else:
|
| 21 |
+
print('Using CPU')
|
| 22 |
+
|
| 23 |
+
data_root_dir = args.my_path
|
| 24 |
+
ckpt_root_dir = args.save_path
|
| 25 |
+
|
| 26 |
+
tasks = ['full']
|
| 27 |
+
|
| 28 |
+
for task in tasks:
|
| 29 |
+
print('Generating results for task ' + task + '...')
|
| 30 |
+
# task = 'full' # Choose between 'full', 'scarce', 'reynolds', and 'aoa'
|
| 31 |
+
s = task + '_test' if task != 'scarce' else 'full_test'
|
| 32 |
+
s_train = task + '_train'
|
| 33 |
+
|
| 34 |
+
data_dir = osp.join(data_root_dir, 'Dataset')
|
| 35 |
+
with open(osp.join(data_dir, 'manifest.json'), 'r') as f:
|
| 36 |
+
manifest = json.load(f)
|
| 37 |
+
|
| 38 |
+
manifest_train = manifest[s_train]
|
| 39 |
+
n = int(.1 * len(manifest_train))
|
| 40 |
+
train_dataset = manifest_train[:-n]
|
| 41 |
+
|
| 42 |
+
_, coef_norm = Dataset(train_dataset, norm=True, sample=None, my_path=data_dir)
|
| 43 |
+
|
| 44 |
+
# Compute the scores on the test set
|
| 45 |
+
|
| 46 |
+
model_names = ['Transolver']
|
| 47 |
+
models = []
|
| 48 |
+
hparams = []
|
| 49 |
+
|
| 50 |
+
for model in model_names:
|
| 51 |
+
model_path = osp.join(ckpt_root_dir, 'metrics', task, model, model)
|
| 52 |
+
mod = torch.load(model_path)
|
| 53 |
+
print(mod)
|
| 54 |
+
mod = [m.to(device) for m in mod]
|
| 55 |
+
models.append(mod)
|
| 56 |
+
|
| 57 |
+
with open('params.yaml', 'r') as f:
|
| 58 |
+
hparam = yaml.safe_load(f)[model]
|
| 59 |
+
hparams.append(hparam)
|
| 60 |
+
|
| 61 |
+
results_dir = osp.join(ckpt_root_dir, 'scores', task)
|
| 62 |
+
coefs = metrics.Results_test(device, models, hparams, coef_norm, data_dir, results_dir, n_test=3, criterion='MSE',
|
| 63 |
+
s=s)
|
| 64 |
+
# models can be a stack of the same model (for example MLP) on the task s, if you have another stack of another model (for example GraphSAGE)
|
| 65 |
+
# you can put in model argument [models_MLP, models_GraphSAGE] and it will output the results for both models (mean and std) in an ordered array.
|
| 66 |
+
|
| 67 |
+
np.save(osp.join(results_dir, 'true_coefs'), coefs[0])
|
| 68 |
+
np.save(osp.join(results_dir, 'pred_coefs_mean'), coefs[1])
|
| 69 |
+
np.save(osp.join(results_dir, 'pred_coefs_std'), coefs[2])
|
| 70 |
+
for n, file in enumerate(coefs[3]):
|
| 71 |
+
np.save(osp.join(results_dir, 'true_surf_coefs_' + str(n)), file)
|
| 72 |
+
for n, file in enumerate(coefs[4]):
|
| 73 |
+
np.save(osp.join(results_dir, 'surf_coefs_' + str(n)), file)
|
| 74 |
+
np.save(osp.join(results_dir, 'true_bls'), coefs[5])
|
| 75 |
+
np.save(osp.join(results_dir, 'bls'), coefs[6])
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/GUNet.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch_geometric.nn as nng
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
def DownSample(id, x, edge_index, pos_x, pool, pool_ratio, r, max_neighbors):
|
| 7 |
+
y = x.clone()
|
| 8 |
+
n = int(x.size(0))
|
| 9 |
+
|
| 10 |
+
if pool is not None:
|
| 11 |
+
y, _, _, _, id_sampled, _ = pool(y, edge_index)
|
| 12 |
+
else:
|
| 13 |
+
k = int((pool_ratio*torch.tensor(n, dtype = torch.float)).ceil())
|
| 14 |
+
id_sampled = random.sample(range(n), k)
|
| 15 |
+
id_sampled = torch.tensor(id_sampled, dtype = torch.long)
|
| 16 |
+
y = y[id_sampled]
|
| 17 |
+
|
| 18 |
+
pos_x = pos_x[id_sampled]
|
| 19 |
+
id.append(id_sampled)
|
| 20 |
+
|
| 21 |
+
# if training:
|
| 22 |
+
# edge_index_sampled = nng.radius_graph(x = pos_x.detach(), r = r, loop = True, max_num_neighbors = 64)
|
| 23 |
+
# else:
|
| 24 |
+
# edge_index_sampled = nng.radius_graph(x = pos_x.detach(), r = r, loop = True, max_num_neighbors = 512)
|
| 25 |
+
edge_index_sampled = nng.radius_graph(x = pos_x.detach(), r = r, loop = True, max_num_neighbors = max_neighbors)
|
| 26 |
+
|
| 27 |
+
return y, edge_index_sampled
|
| 28 |
+
|
| 29 |
+
def UpSample(x, pos_x_up, pos_x_down):
|
| 30 |
+
cluster = nng.nearest(pos_x_up, pos_x_down)
|
| 31 |
+
x_up = x[cluster]
|
| 32 |
+
|
| 33 |
+
return x_up
|
| 34 |
+
|
| 35 |
+
class GUNet(nn.Module):
|
| 36 |
+
def __init__(self, hparams, encoder, decoder):
|
| 37 |
+
super(GUNet, self).__init__()
|
| 38 |
+
|
| 39 |
+
self.L = hparams['nb_scale']
|
| 40 |
+
self.layer = hparams['layer']
|
| 41 |
+
self.pool_type = hparams['pool']
|
| 42 |
+
self.pool_ratio = hparams['pool_ratio']
|
| 43 |
+
self.list_r = hparams['list_r']
|
| 44 |
+
self.size_hidden_layers = hparams['size_hidden_layers']
|
| 45 |
+
self.size_hidden_layers_init = hparams['size_hidden_layers']
|
| 46 |
+
self.max_neighbors = hparams['max_neighbors']
|
| 47 |
+
self.dim_enc = hparams['encoder'][-1]
|
| 48 |
+
self.bn_bool = hparams['batchnorm']
|
| 49 |
+
self.res = hparams['res']
|
| 50 |
+
self.head = 2
|
| 51 |
+
self.activation = nn.ReLU()
|
| 52 |
+
|
| 53 |
+
self.encoder = encoder
|
| 54 |
+
self.decoder = decoder
|
| 55 |
+
|
| 56 |
+
self.down_layers = nn.ModuleList()
|
| 57 |
+
|
| 58 |
+
if self.pool_type != 'random':
|
| 59 |
+
self.pool = nn.ModuleList()
|
| 60 |
+
else:
|
| 61 |
+
self.pool = None
|
| 62 |
+
|
| 63 |
+
if self.layer == 'SAGE':
|
| 64 |
+
self.down_layers.append(nng.SAGEConv(
|
| 65 |
+
in_channels = self.dim_enc,
|
| 66 |
+
out_channels = self.size_hidden_layers
|
| 67 |
+
))
|
| 68 |
+
bn_in = self.size_hidden_layers
|
| 69 |
+
|
| 70 |
+
elif self.layer == 'GAT':
|
| 71 |
+
self.down_layers.append(nng.GATConv(
|
| 72 |
+
in_channels = self.dim_enc,
|
| 73 |
+
out_channels = self.size_hidden_layers,
|
| 74 |
+
heads = self.head,
|
| 75 |
+
add_self_loops = False,
|
| 76 |
+
concat = True
|
| 77 |
+
))
|
| 78 |
+
bn_in = self.head*self.size_hidden_layers
|
| 79 |
+
|
| 80 |
+
if self.bn_bool == True:
|
| 81 |
+
self.bn = nn.ModuleList()
|
| 82 |
+
self.bn.append(nng.BatchNorm(
|
| 83 |
+
in_channels = bn_in,
|
| 84 |
+
track_running_stats = False
|
| 85 |
+
))
|
| 86 |
+
else:
|
| 87 |
+
self.bn = None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
for n in range(1, self.L):
|
| 91 |
+
if self.pool_type != 'random':
|
| 92 |
+
self.pool.append(nng.TopKPooling(
|
| 93 |
+
in_channels = self.size_hidden_layers,
|
| 94 |
+
ratio = self.pool_ratio[n - 1],
|
| 95 |
+
nonlinearity = torch.sigmoid
|
| 96 |
+
))
|
| 97 |
+
|
| 98 |
+
if self.layer == 'SAGE':
|
| 99 |
+
self.down_layers.append(nng.SAGEConv(
|
| 100 |
+
in_channels = self.size_hidden_layers,
|
| 101 |
+
out_channels = 2*self.size_hidden_layers,
|
| 102 |
+
))
|
| 103 |
+
self.size_hidden_layers = 2*self.size_hidden_layers
|
| 104 |
+
bn_in = self.size_hidden_layers
|
| 105 |
+
|
| 106 |
+
elif self.layer == 'GAT':
|
| 107 |
+
self.down_layers.append(nng.GATConv(
|
| 108 |
+
in_channels = self.head*self.size_hidden_layers,
|
| 109 |
+
out_channels = self.size_hidden_layers,
|
| 110 |
+
heads = 2,
|
| 111 |
+
add_self_loops = False,
|
| 112 |
+
concat = True
|
| 113 |
+
))
|
| 114 |
+
|
| 115 |
+
if self.bn_bool == True:
|
| 116 |
+
self.bn.append(nng.BatchNorm(
|
| 117 |
+
in_channels = bn_in,
|
| 118 |
+
track_running_stats = False
|
| 119 |
+
))
|
| 120 |
+
|
| 121 |
+
self.up_layers = nn.ModuleList()
|
| 122 |
+
|
| 123 |
+
if self.layer == 'SAGE':
|
| 124 |
+
self.up_layers.append(nng.SAGEConv(
|
| 125 |
+
in_channels = 3*self.size_hidden_layers_init,
|
| 126 |
+
out_channels = self.dim_enc
|
| 127 |
+
))
|
| 128 |
+
self.size_hidden_layers_init = 2*self.size_hidden_layers_init
|
| 129 |
+
|
| 130 |
+
elif self.layer == 'GAT':
|
| 131 |
+
self.up_layers.append(nng.GATConv(
|
| 132 |
+
in_channels = 2*self.head*self.size_hidden_layers,
|
| 133 |
+
out_channels = self.dim_enc,
|
| 134 |
+
heads = 2,
|
| 135 |
+
add_self_loops = False,
|
| 136 |
+
concat = False
|
| 137 |
+
))
|
| 138 |
+
|
| 139 |
+
if self.bn_bool == True:
|
| 140 |
+
self.bn.append(nng.BatchNorm(
|
| 141 |
+
in_channels = self.dim_enc,
|
| 142 |
+
track_running_stats = False
|
| 143 |
+
))
|
| 144 |
+
|
| 145 |
+
for n in range(1, self.L - 1):
|
| 146 |
+
if self.layer == 'SAGE':
|
| 147 |
+
self.up_layers.append(nng.SAGEConv(
|
| 148 |
+
in_channels = 3*self.size_hidden_layers_init,
|
| 149 |
+
out_channels = self.size_hidden_layers_init,
|
| 150 |
+
))
|
| 151 |
+
bn_in = self.size_hidden_layers_init
|
| 152 |
+
self.size_hidden_layers_init = 2*self.size_hidden_layers_init
|
| 153 |
+
|
| 154 |
+
elif self.layer == 'GAT':
|
| 155 |
+
self.up_layers.append(nng.GATConv(
|
| 156 |
+
in_channels = 2*self.head*self.size_hidden_layers,
|
| 157 |
+
out_channels = self.size_hidden_layers,
|
| 158 |
+
heads = 2,
|
| 159 |
+
add_self_loops = False,
|
| 160 |
+
concat = True
|
| 161 |
+
))
|
| 162 |
+
|
| 163 |
+
if self.bn_bool == True:
|
| 164 |
+
self.bn.append(nng.BatchNorm(
|
| 165 |
+
in_channels = bn_in,
|
| 166 |
+
track_running_stats = False
|
| 167 |
+
))
|
| 168 |
+
|
| 169 |
+
def forward(self, data):
|
| 170 |
+
x, edge_index = data.x, data.edge_index
|
| 171 |
+
id = []
|
| 172 |
+
edge_index_list = [edge_index.clone()]
|
| 173 |
+
pos_x_list = []
|
| 174 |
+
z = self.encoder(x)
|
| 175 |
+
if self.res:
|
| 176 |
+
z_res = z.clone()
|
| 177 |
+
|
| 178 |
+
z = self.down_layers[0](z, edge_index)
|
| 179 |
+
|
| 180 |
+
if self.bn_bool == True:
|
| 181 |
+
z = self.bn[0](z)
|
| 182 |
+
|
| 183 |
+
z = self.activation(z)
|
| 184 |
+
z_list = [z.clone()]
|
| 185 |
+
for n in range(self.L - 1):
|
| 186 |
+
pos_x = x[:, :2] if n == 0 else pos_x[id[n - 1]]
|
| 187 |
+
pos_x_list.append(pos_x.clone())
|
| 188 |
+
|
| 189 |
+
if self.pool_type != 'random':
|
| 190 |
+
z, edge_index = DownSample(id, z, edge_index, pos_x, self.pool[n], self.pool_ratio[n], self.list_r[n], self.max_neighbors)
|
| 191 |
+
else:
|
| 192 |
+
z, edge_index = DownSample(id, z, edge_index, pos_x, None, self.pool_ratio[n], self.list_r[n], self.max_neighbors)
|
| 193 |
+
edge_index_list.append(edge_index.clone())
|
| 194 |
+
|
| 195 |
+
z = self.down_layers[n + 1](z, edge_index)
|
| 196 |
+
|
| 197 |
+
if self.bn_bool == True:
|
| 198 |
+
z = self.bn[n + 1](z)
|
| 199 |
+
|
| 200 |
+
z = self.activation(z)
|
| 201 |
+
z_list.append(z.clone())
|
| 202 |
+
pos_x_list.append(pos_x[id[-1]].clone())
|
| 203 |
+
|
| 204 |
+
for n in range(self.L - 1, 0, -1):
|
| 205 |
+
z = UpSample(z, pos_x_list[n - 1], pos_x_list[n])
|
| 206 |
+
z = torch.cat([z, z_list[n - 1]], dim = 1)
|
| 207 |
+
z = self.up_layers[n - 1](z, edge_index_list[n - 1])
|
| 208 |
+
|
| 209 |
+
if self.bn_bool == True:
|
| 210 |
+
z = self.bn[self.L + n - 1](z)
|
| 211 |
+
|
| 212 |
+
z = self.activation(z) if n != 1 else z
|
| 213 |
+
|
| 214 |
+
del(z_list, pos_x_list, edge_index_list)
|
| 215 |
+
|
| 216 |
+
if self.res:
|
| 217 |
+
z = z + z_res
|
| 218 |
+
|
| 219 |
+
z = self.decoder(z)
|
| 220 |
+
|
| 221 |
+
return z
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/GraphSAGE.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import torch_geometric.nn as nng
|
| 3 |
+
|
| 4 |
+
class GraphSAGE(nn.Module):
|
| 5 |
+
def __init__(self, hparams, encoder, decoder):
|
| 6 |
+
super(GraphSAGE, self).__init__()
|
| 7 |
+
|
| 8 |
+
self.nb_hidden_layers = hparams['nb_hidden_layers']
|
| 9 |
+
self.size_hidden_layers = hparams['size_hidden_layers']
|
| 10 |
+
self.bn_bool = hparams['bn_bool']
|
| 11 |
+
self.activation = nn.ReLU()
|
| 12 |
+
|
| 13 |
+
self.encoder = encoder
|
| 14 |
+
self.decoder = decoder
|
| 15 |
+
|
| 16 |
+
self.in_layer = nng.SAGEConv(
|
| 17 |
+
in_channels = hparams['encoder'][-1],
|
| 18 |
+
out_channels = self.size_hidden_layers
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
self.hidden_layers = nn.ModuleList()
|
| 22 |
+
for n in range(self.nb_hidden_layers - 1):
|
| 23 |
+
self.hidden_layers.append(nng.SAGEConv(
|
| 24 |
+
in_channels = self.size_hidden_layers,
|
| 25 |
+
out_channels = self.size_hidden_layers
|
| 26 |
+
))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
self.out_layer = nng.SAGEConv(
|
| 30 |
+
in_channels = self.size_hidden_layers,
|
| 31 |
+
out_channels = hparams['decoder'][0]
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
if self.bn_bool:
|
| 35 |
+
self.bn = nn.ModuleList()
|
| 36 |
+
for n in range(self.nb_hidden_layers):
|
| 37 |
+
self.bn.append(nn.BatchNorm1d(self.size_hidden_layers, track_running_stats = False))
|
| 38 |
+
|
| 39 |
+
def forward(self, data):
|
| 40 |
+
z, edge_index = data.x, data.edge_index
|
| 41 |
+
z = self.encoder(z)
|
| 42 |
+
|
| 43 |
+
z = self.in_layer(z, edge_index)
|
| 44 |
+
if self.bn_bool:
|
| 45 |
+
z = self.bn[0](z)
|
| 46 |
+
z = self.activation(z)
|
| 47 |
+
|
| 48 |
+
for n in range(self.nb_hidden_layers - 1):
|
| 49 |
+
z = self.hidden_layers[n](z, edge_index)
|
| 50 |
+
if self.bn_bool:
|
| 51 |
+
z = self.bn[n + 1](z)
|
| 52 |
+
z = self.activation(z)
|
| 53 |
+
|
| 54 |
+
z = self.out_layer(z, edge_index)
|
| 55 |
+
|
| 56 |
+
z = self.decoder(z)
|
| 57 |
+
|
| 58 |
+
return z
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/MLP.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from torch import Tensor
|
| 4 |
+
from torch.nn import BatchNorm1d, Identity
|
| 5 |
+
from torch_geometric.nn import Linear
|
| 6 |
+
|
| 7 |
+
class MLP(torch.nn.Module):
|
| 8 |
+
r"""A multi-layer perception (MLP) model.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
channel_list (List[int]): List of input, intermediate and output
|
| 12 |
+
channels. :obj:`len(channel_list) - 1` denotes the number of layers
|
| 13 |
+
of the MLP.
|
| 14 |
+
dropout (float, optional): Dropout probability of each hidden
|
| 15 |
+
embedding. (default: :obj:`0.`)
|
| 16 |
+
batch_norm (bool, optional): If set to :obj:`False`, will not make use
|
| 17 |
+
of batch normalization. (default: :obj:`True`)
|
| 18 |
+
relu_first (bool, optional): If set to :obj:`True`, ReLU activation is
|
| 19 |
+
applied before batch normalization. (default: :obj:`False`)
|
| 20 |
+
"""
|
| 21 |
+
def __init__(self, channel_list, dropout = 0.,
|
| 22 |
+
batch_norm = True, relu_first = False):
|
| 23 |
+
super().__init__()
|
| 24 |
+
assert len(channel_list) >= 2
|
| 25 |
+
self.channel_list = channel_list
|
| 26 |
+
self.dropout = dropout
|
| 27 |
+
self.relu_first = relu_first
|
| 28 |
+
|
| 29 |
+
self.lins = torch.nn.ModuleList()
|
| 30 |
+
for dims in zip(self.channel_list[:-1], self.channel_list[1:]):
|
| 31 |
+
self.lins.append(Linear(*dims))
|
| 32 |
+
|
| 33 |
+
self.norms = torch.nn.ModuleList()
|
| 34 |
+
for dim in zip(self.channel_list[1:-1]):
|
| 35 |
+
self.norms.append(BatchNorm1d(dim, track_running_stats = False) if batch_norm else Identity())
|
| 36 |
+
|
| 37 |
+
self.reset_parameters()
|
| 38 |
+
|
| 39 |
+
def reset_parameters(self):
|
| 40 |
+
for lin in self.lins:
|
| 41 |
+
lin.reset_parameters()
|
| 42 |
+
for norm in self.norms:
|
| 43 |
+
if hasattr(norm, 'reset_parameters'):
|
| 44 |
+
norm.reset_parameters()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 48 |
+
""""""
|
| 49 |
+
x = self.lins[0](x)
|
| 50 |
+
for lin, norm in zip(self.lins[1:], self.norms):
|
| 51 |
+
if self.relu_first:
|
| 52 |
+
x = x.relu_()
|
| 53 |
+
x = norm(x)
|
| 54 |
+
if not self.relu_first:
|
| 55 |
+
x = x.relu_()
|
| 56 |
+
x = F.dropout(x, p = self.dropout, training = self.training)
|
| 57 |
+
x = lin.forward(x)
|
| 58 |
+
return x
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def __repr__(self) -> str:
|
| 62 |
+
return f'{self.__class__.__name__}({str(self.channel_list)[1:-1]})'
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/NN.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from models.MLP import MLP
|
| 3 |
+
|
| 4 |
+
class NN(nn.Module):
|
| 5 |
+
def __init__(self, hparams, encoder, decoder):
|
| 6 |
+
super(NN, self).__init__()
|
| 7 |
+
|
| 8 |
+
self.nb_hidden_layers = hparams['nb_hidden_layers']
|
| 9 |
+
self.size_hidden_layers = hparams['size_hidden_layers']
|
| 10 |
+
self.bn_bool = hparams['bn_bool']
|
| 11 |
+
self.activation = nn.ReLU()
|
| 12 |
+
|
| 13 |
+
self.encoder = encoder
|
| 14 |
+
self.decoder = decoder
|
| 15 |
+
|
| 16 |
+
self.dim_enc = hparams['encoder'][-1]
|
| 17 |
+
|
| 18 |
+
self.nn = MLP([self.dim_enc] + [self.size_hidden_layers]*self.nb_hidden_layers + [self.dim_enc], batch_norm = self.bn_bool)
|
| 19 |
+
|
| 20 |
+
def forward(self, data):
|
| 21 |
+
z = self.encoder(data.x)
|
| 22 |
+
z = self.nn(z)
|
| 23 |
+
z = self.decoder(z)
|
| 24 |
+
|
| 25 |
+
return z
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/models/PointNet.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch_geometric.nn as nng
|
| 4 |
+
from models.MLP import MLP
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class PointNet(nn.Module):
|
| 8 |
+
def __init__(self, hparams, encoder, decoder):
|
| 9 |
+
super(PointNet, self).__init__()
|
| 10 |
+
|
| 11 |
+
self.base_nb = hparams['base_nb']
|
| 12 |
+
|
| 13 |
+
self.in_block = MLP([hparams['encoder'][-1], self.base_nb, self.base_nb * 2], batch_norm=False)
|
| 14 |
+
self.max_block = MLP([self.base_nb * 2, self.base_nb * 4, self.base_nb * 8, self.base_nb * 32],
|
| 15 |
+
batch_norm=False)
|
| 16 |
+
|
| 17 |
+
self.out_block = MLP([self.base_nb * (32 + 2), self.base_nb * 16, self.base_nb * 8, self.base_nb * 4],
|
| 18 |
+
batch_norm=False)
|
| 19 |
+
|
| 20 |
+
self.encoder = encoder
|
| 21 |
+
self.decoder = decoder
|
| 22 |
+
|
| 23 |
+
self.fcfinal = nn.Linear(self.base_nb * 4, hparams['encoder'][-1])
|
| 24 |
+
|
| 25 |
+
def forward(self, data):
|
| 26 |
+
z, batch = data.x.float(), data.batch.long()
|
| 27 |
+
|
| 28 |
+
z = self.encoder(z)
|
| 29 |
+
z = self.in_block(z)
|
| 30 |
+
|
| 31 |
+
global_coef = self.max_block(z)
|
| 32 |
+
global_coef = nng.global_max_pool(global_coef, batch=batch)
|
| 33 |
+
nb_points = torch.zeros(global_coef.shape[0], device=z.device)
|
| 34 |
+
|
| 35 |
+
for i in range(batch.max() + 1):
|
| 36 |
+
nb_points[i] = (batch == i).sum()
|
| 37 |
+
nb_points = nb_points.long()
|
| 38 |
+
global_coef = torch.repeat_interleave(global_coef, nb_points, dim=0)
|
| 39 |
+
|
| 40 |
+
z = torch.cat([z, global_coef], dim=1)
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from timm.models.layers import trunc_normal_
|
| 5 |
+
from einops import rearrange, repeat
|
| 6 |
+
|
| 7 |
+
ACTIVATION = {'gelu': nn.GELU, 'tanh': nn.Tanh, 'sigmoid': nn.Sigmoid, 'relu': nn.ReLU, 'leaky_relu': nn.LeakyReLU(0.1),
|
| 8 |
+
'softplus': nn.Softplus, 'ELU': nn.ELU, 'silu': nn.SiLU}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Physics_Attention_Irregular_Mesh(nn.Module):
|
| 12 |
+
def __init__(self, dim, heads=8, dim_head=64, dropout=0., slice_num=64):
|
| 13 |
+
super().__init__()
|
| 14 |
+
inner_dim = dim_head * heads
|
| 15 |
+
self.dim_head = dim_head
|
| 16 |
+
self.heads = heads
|
| 17 |
+
self.scale = dim_head ** -0.5
|
| 18 |
+
self.softmax = nn.Softmax(dim=-1)
|
| 19 |
+
self.dropout = nn.Dropout(dropout)
|
| 20 |
+
self.temperature = nn.Parameter(torch.ones([1, heads, 1, 1]) * 0.5)
|
| 21 |
+
|
| 22 |
+
self.in_project_x = nn.Linear(dim, inner_dim)
|
| 23 |
+
self.in_project_fx = nn.Linear(dim, inner_dim)
|
| 24 |
+
self.in_project_slice = nn.Linear(dim_head, slice_num)
|
| 25 |
+
for l in [self.in_project_slice]:
|
| 26 |
+
torch.nn.init.orthogonal_(l.weight) # use a principled initialization
|
| 27 |
+
self.to_q = nn.Linear(dim_head, dim_head, bias=False)
|
| 28 |
+
self.to_k = nn.Linear(dim_head, dim_head, bias=False)
|
| 29 |
+
self.to_v = nn.Linear(dim_head, dim_head, bias=False)
|
| 30 |
+
self.to_out = nn.Sequential(
|
| 31 |
+
nn.Linear(inner_dim, dim),
|
| 32 |
+
nn.Dropout(dropout)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
# B N C
|
| 37 |
+
B, N, C = x.shape
|
| 38 |
+
|
| 39 |
+
### (1) Slice
|
| 40 |
+
fx_mid = self.in_project_fx(x).reshape(B, N, self.heads, self.dim_head) \
|
| 41 |
+
.permute(0, 2, 1, 3).contiguous() # B H N C
|
| 42 |
+
x_mid = self.in_project_x(x).reshape(B, N, self.heads, self.dim_head) \
|
| 43 |
+
.permute(0, 2, 1, 3).contiguous() # B H N C
|
| 44 |
+
slice_weights = self.softmax(self.in_project_slice(x_mid) / self.temperature) # B H N G
|
| 45 |
+
slice_norm = slice_weights.sum(2) # B H G
|
| 46 |
+
slice_token = torch.einsum("bhnc,bhng->bhgc", fx_mid, slice_weights)
|
| 47 |
+
slice_token = slice_token / ((slice_norm + 1e-5)[:, :, :, None].repeat(1, 1, 1, self.dim_head))
|
| 48 |
+
|
| 49 |
+
### (2) Attention among slice tokens
|
| 50 |
+
q_slice_token = self.to_q(slice_token)
|
| 51 |
+
k_slice_token = self.to_k(slice_token)
|
| 52 |
+
v_slice_token = self.to_v(slice_token)
|
| 53 |
+
dots = torch.matmul(q_slice_token, k_slice_token.transpose(-1, -2)) * self.scale
|
| 54 |
+
attn = self.softmax(dots)
|
| 55 |
+
attn = self.dropout(attn)
|
| 56 |
+
out_slice_token = torch.matmul(attn, v_slice_token) # B H G D
|
| 57 |
+
|
| 58 |
+
### (3) Deslice
|
| 59 |
+
out_x = torch.einsum("bhgc,bhng->bhnc", out_slice_token, slice_weights)
|
| 60 |
+
out_x = rearrange(out_x, 'b h n d -> b n (h d)')
|
| 61 |
+
return self.to_out(out_x)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class MLP(nn.Module):
|
| 65 |
+
def __init__(self, n_input, n_hidden, n_output, n_layers=1, act='gelu', res=True):
|
| 66 |
+
super(MLP, self).__init__()
|
| 67 |
+
|
| 68 |
+
if act in ACTIVATION.keys():
|
| 69 |
+
act = ACTIVATION[act]
|
| 70 |
+
else:
|
| 71 |
+
raise NotImplementedError
|
| 72 |
+
self.n_input = n_input
|
| 73 |
+
self.n_hidden = n_hidden
|
| 74 |
+
self.n_output = n_output
|
| 75 |
+
self.n_layers = n_layers
|
| 76 |
+
self.res = res
|
| 77 |
+
self.linear_pre = nn.Sequential(nn.Linear(n_input, n_hidden), act())
|
| 78 |
+
self.linear_post = nn.Linear(n_hidden, n_output)
|
| 79 |
+
self.linears = nn.ModuleList([nn.Sequential(nn.Linear(n_hidden, n_hidden), act()) for _ in range(n_layers)])
|
| 80 |
+
|
| 81 |
+
def forward(self, x):
|
| 82 |
+
x = self.linear_pre(x)
|
| 83 |
+
for i in range(self.n_layers):
|
| 84 |
+
if self.res:
|
| 85 |
+
x = self.linears[i](x) + x
|
| 86 |
+
else:
|
| 87 |
+
x = self.linears[i](x)
|
| 88 |
+
x = self.linear_post(x)
|
| 89 |
+
return x
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class Transolver_block(nn.Module):
|
| 93 |
+
"""Transformer encoder block."""
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
num_heads: int,
|
| 98 |
+
hidden_dim: int,
|
| 99 |
+
dropout: float,
|
| 100 |
+
act='gelu',
|
| 101 |
+
mlp_ratio=4,
|
| 102 |
+
last_layer=False,
|
| 103 |
+
out_dim=1,
|
| 104 |
+
slice_num=32,
|
| 105 |
+
):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.last_layer = last_layer
|
| 108 |
+
self.ln_1 = nn.LayerNorm(hidden_dim)
|
| 109 |
+
self.Attn = Physics_Attention_Irregular_Mesh(hidden_dim, heads=num_heads, dim_head=hidden_dim // num_heads,
|
| 110 |
+
dropout=dropout, slice_num=slice_num)
|
| 111 |
+
self.ln_2 = nn.LayerNorm(hidden_dim)
|
| 112 |
+
self.mlp = MLP(hidden_dim, hidden_dim * mlp_ratio, hidden_dim, n_layers=0, res=False, act=act)
|
| 113 |
+
self.mlp_new = MLP(hidden_dim, hidden_dim * mlp_ratio, hidden_dim, n_layers=0, res=False, act=act)
|
| 114 |
+
if self.last_layer:
|
| 115 |
+
self.ln_3 = nn.LayerNorm(hidden_dim)
|
| 116 |
+
self.mlp2 = nn.Linear(hidden_dim, out_dim)
|
| 117 |
+
|
| 118 |
+
def forward(self, fx):
|
| 119 |
+
fx = self.Attn(self.ln_1(fx)) + fx
|
| 120 |
+
fx = self.mlp(self.ln_2(fx)) + fx
|
| 121 |
+
if self.last_layer:
|
| 122 |
+
return self.mlp2(self.ln_3(fx))
|
| 123 |
+
else:
|
| 124 |
+
return fx
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Transolver(nn.Module):
|
| 128 |
+
def __init__(self,
|
| 129 |
+
space_dim=1,
|
| 130 |
+
n_layers=5,
|
| 131 |
+
n_hidden=256,
|
| 132 |
+
dropout=0,
|
| 133 |
+
n_head=8,
|
| 134 |
+
act='gelu',
|
| 135 |
+
mlp_ratio=1,
|
| 136 |
+
fun_dim=1,
|
| 137 |
+
out_dim=1,
|
| 138 |
+
slice_num=32,
|
| 139 |
+
ref=8,
|
| 140 |
+
unified_pos=False
|
| 141 |
+
):
|
| 142 |
+
super(Transolver, self).__init__()
|
| 143 |
+
self.__name__ = 'Transolver'
|
| 144 |
+
self.ref = ref
|
| 145 |
+
self.unified_pos = unified_pos
|
| 146 |
+
if self.unified_pos:
|
| 147 |
+
self.preprocess = MLP(fun_dim + space_dim + self.ref * self.ref, n_hidden * 2, n_hidden,
|
| 148 |
+
n_layers=0,
|
| 149 |
+
res=False, act=act)
|
| 150 |
+
else:
|
| 151 |
+
self.preprocess = MLP(fun_dim + space_dim, n_hidden * 2, n_hidden, n_layers=0, res=False, act=act)
|
| 152 |
+
|
| 153 |
+
self.n_hidden = n_hidden
|
| 154 |
+
self.space_dim = space_dim
|
| 155 |
+
|
| 156 |
+
self.blocks = nn.ModuleList([Transolver_block(num_heads=n_head, hidden_dim=n_hidden,
|
| 157 |
+
dropout=dropout,
|
| 158 |
+
act=act,
|
| 159 |
+
mlp_ratio=mlp_ratio, out_dim=out_dim,
|
| 160 |
+
slice_num=slice_num,
|
| 161 |
+
last_layer=(_ == n_layers - 1))
|
| 162 |
+
for _ in range(n_layers)])
|
| 163 |
+
self.initialize_weights()
|
| 164 |
+
self.placeholder = nn.Parameter((1 / (n_hidden)) * torch.rand(n_hidden, dtype=torch.float))
|
| 165 |
+
|
| 166 |
+
def initialize_weights(self):
|
| 167 |
+
self.apply(self._init_weights)
|
| 168 |
+
|
| 169 |
+
def _init_weights(self, m):
|
| 170 |
+
if isinstance(m, nn.Linear):
|
| 171 |
+
trunc_normal_(m.weight, std=0.02)
|
| 172 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 173 |
+
nn.init.constant_(m.bias, 0)
|
| 174 |
+
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm1d)):
|
| 175 |
+
nn.init.constant_(m.bias, 0)
|
| 176 |
+
nn.init.constant_(m.weight, 1.0)
|
| 177 |
+
|
| 178 |
+
def get_grid(self, my_pos):
|
| 179 |
+
# my_pos 1 N 3
|
| 180 |
+
batchsize = my_pos.shape[0]
|
| 181 |
+
|
| 182 |
+
gridx = torch.tensor(np.linspace(-2, 4, self.ref), dtype=torch.float)
|
| 183 |
+
gridx = gridx.reshape(1, self.ref, 1, 1).repeat([batchsize, 1, self.ref, 1])
|
| 184 |
+
gridy = torch.tensor(np.linspace(-1.5, 1.5, self.ref), dtype=torch.float)
|
| 185 |
+
gridy = gridy.reshape(1, 1, self.ref, 1).repeat([batchsize, self.ref, 1, 1])
|
| 186 |
+
grid_ref = torch.cat((gridx, gridy), dim=-1).cuda().reshape(batchsize, self.ref ** 2, 2) # B 4 4 4 3
|
| 187 |
+
|
| 188 |
+
pos = torch.sqrt(
|
| 189 |
+
torch.sum((my_pos[:, :, None, :] - grid_ref[:, None, :, :]) ** 2,
|
| 190 |
+
dim=-1)). \
|
| 191 |
+
reshape(batchsize, my_pos.shape[1], self.ref * self.ref).contiguous()
|
| 192 |
+
return pos
|
| 193 |
+
|
| 194 |
+
def forward(self, data):
|
| 195 |
+
x, fx, T = data.x, None, None
|
| 196 |
+
x = x[None, :, :]
|
| 197 |
+
if self.unified_pos:
|
| 198 |
+
new_pos = self.get_grid(data.pos[None, :, :])
|
| 199 |
+
x = torch.cat((x, new_pos), dim=-1)
|
| 200 |
+
if fx is not None:
|
| 201 |
+
fx = torch.cat((x, fx), -1)
|
| 202 |
+
fx = self.preprocess(fx)
|
| 203 |
+
else:
|
| 204 |
+
fx = self.preprocess(x)
|
| 205 |
+
fx = fx + self.placeholder[None, None, :]
|
| 206 |
+
|
| 207 |
+
for block in self.blocks:
|
| 208 |
+
fx = block(fx)
|
| 209 |
+
|
| 210 |
+
return fx[0]
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/params.yaml
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GraphSAGE:
|
| 2 |
+
encoder: [ 7, 64, 64, 8 ]
|
| 3 |
+
decoder: [ 8, 64, 64, 4 ]
|
| 4 |
+
|
| 5 |
+
nb_hidden_layers: 3
|
| 6 |
+
size_hidden_layers: 64
|
| 7 |
+
batch_size: 1
|
| 8 |
+
nb_epochs: 398
|
| 9 |
+
lr: 0.001
|
| 10 |
+
max_neighbors: 64
|
| 11 |
+
bn_bool: True
|
| 12 |
+
subsampling: 32000
|
| 13 |
+
r: 0.05
|
| 14 |
+
|
| 15 |
+
Transolver:
|
| 16 |
+
batch_size: 1
|
| 17 |
+
nb_epochs: 398
|
| 18 |
+
lr: 0.001
|
| 19 |
+
max_neighbors: 64
|
| 20 |
+
subsampling: 32000
|
| 21 |
+
r: 0.05
|
| 22 |
+
|
| 23 |
+
PointNet:
|
| 24 |
+
encoder: [ 7, 64, 64, 8 ]
|
| 25 |
+
decoder: [ 8, 64, 64, 4 ]
|
| 26 |
+
|
| 27 |
+
base_nb: 8
|
| 28 |
+
batch_size: 1
|
| 29 |
+
nb_epochs: 398
|
| 30 |
+
lr: 0.001
|
| 31 |
+
subsampling: 32000
|
| 32 |
+
|
| 33 |
+
MLP:
|
| 34 |
+
encoder: [ 7, 64, 64, 8 ]
|
| 35 |
+
decoder: [ 8, 64, 64, 4 ]
|
| 36 |
+
|
| 37 |
+
nb_hidden_layers: 3
|
| 38 |
+
size_hidden_layers: 64
|
| 39 |
+
batch_size: 1
|
| 40 |
+
nb_epochs: 398
|
| 41 |
+
lr: 0.001
|
| 42 |
+
bn_bool: True
|
| 43 |
+
subsampling: 32000
|
| 44 |
+
|
| 45 |
+
GUNet:
|
| 46 |
+
encoder: [ 7, 64, 64, 8 ]
|
| 47 |
+
decoder: [ 8, 64, 64, 4 ]
|
| 48 |
+
|
| 49 |
+
layer: 'SAGE'
|
| 50 |
+
pool: 'random'
|
| 51 |
+
nb_scale: 5
|
| 52 |
+
pool_ratio: [ .5, .5, .5, .5 ]
|
| 53 |
+
list_r: [ .05, .2, .5, 1, 10 ]
|
| 54 |
+
size_hidden_layers: 8
|
| 55 |
+
batchnorm: True
|
| 56 |
+
res: False
|
| 57 |
+
|
| 58 |
+
batch_size: 1
|
| 59 |
+
nb_epochs: 398
|
| 60 |
+
lr: 0.001
|
| 61 |
+
max_neighbors: 64
|
| 62 |
+
subsampling: 32000
|
| 63 |
+
r: 0.05
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torch_geometric
|
| 3 |
+
torch-cluster
|
| 4 |
+
vtk
|
| 5 |
+
timm
|
| 6 |
+
einops
|
| 7 |
+
seaborn
|
| 8 |
+
pyvista
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/scripts/Evaluation.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export CUDA_VISIBLE_DEVICES=4
|
| 2 |
+
|
| 3 |
+
python main_evaluation.py --my_path /data/naca/
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/scripts/GraphSAGE.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export CUDA_VISIBLE_DEVICES=4
|
| 2 |
+
|
| 3 |
+
python main.py --model GraphSAGE -t full --my_path /data/naca/Dataset --score 1
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/scripts/Transolver.sh
ADDED
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import seaborn as sns
|
| 5 |
+
|
| 6 |
+
import time, json
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch_geometric.nn as nng
|
| 11 |
+
from torch_geometric.loader import DataLoader
|
| 12 |
+
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import os.path as osp
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_nb_trainable_params(model):
|
| 20 |
+
'''
|
| 21 |
+
Return the number of trainable parameters
|
| 22 |
+
'''
|
| 23 |
+
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
|
| 24 |
+
return sum([np.prod(p.size()) for p in model_parameters])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def train(device, model, train_loader, optimizer, scheduler, criterion='MSE', reg=1):
|
| 28 |
+
model.train()
|
| 29 |
+
avg_loss_per_var = torch.zeros(4, device=device)
|
| 30 |
+
avg_loss = 0
|
| 31 |
+
avg_loss_surf_var = torch.zeros(4, device=device)
|
| 32 |
+
avg_loss_vol_var = torch.zeros(4, device=device)
|
| 33 |
+
avg_loss_surf = 0
|
| 34 |
+
avg_loss_vol = 0
|
| 35 |
+
iter = 0
|
| 36 |
+
|
| 37 |
+
for data in train_loader:
|
| 38 |
+
data_clone = data.clone()
|
| 39 |
+
data_clone = data_clone.to(device)
|
| 40 |
+
optimizer.zero_grad()
|
| 41 |
+
out = model(data_clone)
|
| 42 |
+
targets = data_clone.y
|
| 43 |
+
|
| 44 |
+
if criterion == 'MSE' or criterion == 'MSE_weighted':
|
| 45 |
+
loss_criterion = nn.MSELoss(reduction='none')
|
| 46 |
+
elif criterion == 'MAE':
|
| 47 |
+
loss_criterion = nn.L1Loss(reduction='none')
|
| 48 |
+
loss_per_var = loss_criterion(out, targets).mean(dim=0)
|
| 49 |
+
total_loss = loss_per_var.mean()
|
| 50 |
+
loss_surf_var = loss_criterion(out[data_clone.surf, :], targets[data_clone.surf, :]).mean(dim=0)
|
| 51 |
+
loss_vol_var = loss_criterion(out[~data_clone.surf, :], targets[~data_clone.surf, :]).mean(dim=0)
|
| 52 |
+
loss_surf = loss_surf_var.mean()
|
| 53 |
+
loss_vol = loss_vol_var.mean()
|
| 54 |
+
|
| 55 |
+
if criterion == 'MSE_weighted':
|
| 56 |
+
(loss_vol + reg * loss_surf).backward()
|
| 57 |
+
else:
|
| 58 |
+
total_loss.backward()
|
| 59 |
+
|
| 60 |
+
optimizer.step()
|
| 61 |
+
scheduler.step()
|
| 62 |
+
avg_loss_per_var += loss_per_var
|
| 63 |
+
avg_loss += total_loss
|
| 64 |
+
avg_loss_surf_var += loss_surf_var
|
| 65 |
+
avg_loss_vol_var += loss_vol_var
|
| 66 |
+
avg_loss_surf += loss_surf
|
| 67 |
+
avg_loss_vol += loss_vol
|
| 68 |
+
iter += 1
|
| 69 |
+
|
| 70 |
+
return avg_loss.cpu().data.numpy() / iter, avg_loss_per_var.cpu().data.numpy() / iter, avg_loss_surf_var.cpu().data.numpy() / iter, avg_loss_vol_var.cpu().data.numpy() / iter, \
|
| 71 |
+
avg_loss_surf.cpu().data.numpy() / iter, avg_loss_vol.cpu().data.numpy() / iter
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@torch.no_grad()
|
| 75 |
+
def test(device, model, test_loader, criterion='MSE'):
|
| 76 |
+
model.eval()
|
| 77 |
+
avg_loss_per_var = np.zeros(4)
|
| 78 |
+
avg_loss = 0
|
| 79 |
+
avg_loss_surf_var = np.zeros(4)
|
| 80 |
+
avg_loss_vol_var = np.zeros(4)
|
| 81 |
+
avg_loss_surf = 0
|
| 82 |
+
avg_loss_vol = 0
|
| 83 |
+
iter = 0
|
| 84 |
+
|
| 85 |
+
for data in test_loader:
|
| 86 |
+
data_clone = data.clone()
|
| 87 |
+
data_clone = data_clone.to(device)
|
| 88 |
+
out = model(data_clone)
|
| 89 |
+
|
| 90 |
+
targets = data_clone.y
|
| 91 |
+
if criterion == 'MSE' or 'MSE_weighted':
|
| 92 |
+
loss_criterion = nn.MSELoss(reduction='none')
|
| 93 |
+
elif criterion == 'MAE':
|
| 94 |
+
loss_criterion = nn.L1Loss(reduction='none')
|
| 95 |
+
|
| 96 |
+
loss_per_var = loss_criterion(out, targets).mean(dim=0)
|
| 97 |
+
loss = loss_per_var.mean()
|
| 98 |
+
loss_surf_var = loss_criterion(out[data_clone.surf, :], targets[data_clone.surf, :]).mean(dim=0)
|
| 99 |
+
loss_vol_var = loss_criterion(out[~data_clone.surf, :], targets[~data_clone.surf, :]).mean(dim=0)
|
| 100 |
+
loss_surf = loss_surf_var.mean()
|
| 101 |
+
loss_vol = loss_vol_var.mean()
|
| 102 |
+
|
| 103 |
+
avg_loss_per_var += loss_per_var.cpu().numpy()
|
| 104 |
+
avg_loss += loss.cpu().numpy()
|
| 105 |
+
avg_loss_surf_var += loss_surf_var.cpu().numpy()
|
| 106 |
+
avg_loss_vol_var += loss_vol_var.cpu().numpy()
|
| 107 |
+
avg_loss_surf += loss_surf.cpu().numpy()
|
| 108 |
+
avg_loss_vol += loss_vol.cpu().numpy()
|
| 109 |
+
iter += 1
|
| 110 |
+
|
| 111 |
+
return avg_loss / iter, avg_loss_per_var / iter, avg_loss_surf_var / iter, avg_loss_vol_var / iter, avg_loss_surf / iter, avg_loss_vol / iter
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class NumpyEncoder(json.JSONEncoder):
|
| 115 |
+
def default(self, obj):
|
| 116 |
+
if isinstance(obj, np.ndarray):
|
| 117 |
+
return obj.tolist()
|
| 118 |
+
return json.JSONEncoder.default(self, obj)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def main(device, train_dataset, val_dataset, Net, hparams, path, criterion='MSE', reg=1, val_iter=10,
|
| 122 |
+
name_mod='GraphSAGE', val_sample=True):
|
| 123 |
+
'''
|
| 124 |
+
Args:
|
| 125 |
+
device (str): device on which you want to do the computation.
|
| 126 |
+
train_dataset (list): list of the data in the training set.
|
| 127 |
+
val_dataset (list): list of the data in the validation set.
|
| 128 |
+
Net (class): network to train.
|
| 129 |
+
hparams (dict): hyper parameters of the network.
|
| 130 |
+
path (str): where to save the trained model and the figures.
|
| 131 |
+
criterion (str, optional): chose between 'MSE', 'MAE', and 'MSE_weigthed'. The latter is the volumetric MSE plus the surface MSE computed independently. Default: 'MSE'.
|
| 132 |
+
reg (float, optional): weigth for the surface loss when criterion is 'MSE_weighted'. Default: 1.
|
| 133 |
+
val_iter (int, optional): number of epochs between each validation step. Default: 10.
|
| 134 |
+
name_mod (str, optional): type of model. Default: 'GraphSAGE'.
|
| 135 |
+
'''
|
| 136 |
+
Path(path).mkdir(parents=True, exist_ok=True)
|
| 137 |
+
|
| 138 |
+
model = Net.to(device)
|
| 139 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=hparams['lr'])
|
| 140 |
+
lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(
|
| 141 |
+
optimizer,
|
| 142 |
+
max_lr=hparams['lr'],
|
| 143 |
+
total_steps=(len(train_dataset) // hparams['batch_size'] + 1) * hparams['nb_epochs'],
|
| 144 |
+
)
|
| 145 |
+
val_loader = DataLoader(val_dataset, batch_size=1)
|
| 146 |
+
start = time.time()
|
| 147 |
+
|
| 148 |
+
train_loss_surf_list = []
|
| 149 |
+
train_loss_vol_list = []
|
| 150 |
+
loss_surf_var_list = []
|
| 151 |
+
loss_vol_var_list = []
|
| 152 |
+
val_surf_list = []
|
| 153 |
+
val_vol_list = []
|
| 154 |
+
val_surf_var_list = []
|
| 155 |
+
val_vol_var_list = []
|
| 156 |
+
|
| 157 |
+
pbar_train = tqdm(range(hparams['nb_epochs']), position=0)
|
| 158 |
+
for epoch in pbar_train:
|
| 159 |
+
train_dataset_sampled = []
|
| 160 |
+
for data in train_dataset:
|
| 161 |
+
data_sampled = data.clone()
|
| 162 |
+
idx = random.sample(range(data_sampled.x.size(0)), hparams['subsampling'])
|
| 163 |
+
idx = torch.tensor(idx)
|
| 164 |
+
|
| 165 |
+
data_sampled.pos = data_sampled.pos[idx]
|
| 166 |
+
data_sampled.x = data_sampled.x[idx]
|
| 167 |
+
data_sampled.y = data_sampled.y[idx]
|
| 168 |
+
data_sampled.surf = data_sampled.surf[idx]
|
| 169 |
+
|
| 170 |
+
if name_mod != 'PointNet' and name_mod != 'MLP':
|
| 171 |
+
data_sampled.edge_index = nng.radius_graph(x=data_sampled.pos.to(device), r=hparams['r'], loop=True,
|
| 172 |
+
max_num_neighbors=int(hparams['max_neighbors'])).cpu()
|
| 173 |
+
|
| 174 |
+
train_dataset_sampled.append(data_sampled)
|
| 175 |
+
train_loader = DataLoader(train_dataset_sampled, batch_size=hparams['batch_size'], shuffle=True)
|
| 176 |
+
del (train_dataset_sampled)
|
| 177 |
+
|
| 178 |
+
train_loss, _, loss_surf_var, loss_vol_var, loss_surf, loss_vol = train(device, model, train_loader, optimizer,
|
| 179 |
+
lr_scheduler, criterion, reg=reg)
|
| 180 |
+
print('epoch: ' + str(epoch))
|
| 181 |
+
print('train_loss: ' + str(train_loss))
|
| 182 |
+
print('loss_vol: ' + str(loss_vol))
|
| 183 |
+
print('loss_surf: ' + str(loss_surf))
|
| 184 |
+
|
| 185 |
+
if criterion == 'MSE_weighted':
|
| 186 |
+
train_loss = reg * loss_surf + loss_vol
|
| 187 |
+
del (train_loader)
|
| 188 |
+
|
| 189 |
+
train_loss_surf_list.append(loss_surf)
|
| 190 |
+
train_loss_vol_list.append(loss_vol)
|
| 191 |
+
loss_surf_var_list.append(loss_surf_var)
|
| 192 |
+
loss_vol_var_list.append(loss_vol_var)
|
| 193 |
+
|
| 194 |
+
if val_iter is not None:
|
| 195 |
+
if epoch % val_iter == val_iter - 1 or epoch == 0:
|
| 196 |
+
if val_sample:
|
| 197 |
+
val_surf_vars, val_vol_vars, val_surfs, val_vols = [], [], [], []
|
| 198 |
+
for i in range(20):
|
| 199 |
+
val_dataset_sampled = []
|
| 200 |
+
for data in val_dataset:
|
| 201 |
+
data_sampled = data.clone()
|
| 202 |
+
idx = random.sample(range(data_sampled.x.size(0)), hparams['subsampling'])
|
| 203 |
+
idx = torch.tensor(idx)
|
| 204 |
+
|
| 205 |
+
data_sampled.pos = data_sampled.pos[idx]
|
| 206 |
+
data_sampled.x = data_sampled.x[idx]
|
| 207 |
+
data_sampled.y = data_sampled.y[idx]
|
| 208 |
+
data_sampled.surf = data_sampled.surf[idx]
|
| 209 |
+
|
| 210 |
+
if name_mod != 'PointNet' and name_mod != 'MLP':
|
| 211 |
+
data_sampled.edge_index = nng.radius_graph(x=data_sampled.pos.to(device),
|
| 212 |
+
r=hparams['r'], loop=True,
|
| 213 |
+
max_num_neighbors=int(
|
| 214 |
+
hparams['max_neighbors'])).cpu()
|
| 215 |
+
|
| 216 |
+
# if name_mod == 'GNO' or name_mod == 'MGNO':
|
| 217 |
+
# x, edge_index = data_sampled.x, data_sampled.edge_index
|
| 218 |
+
# x_i, x_j = x[edge_index[0], 0:2], x[edge_index[1], 0:2]
|
| 219 |
+
# v_i, v_j = x[edge_index[0], 2:4], x[edge_index[1], 2:4]
|
| 220 |
+
# p_i, p_j = x[edge_index[0], 4:5], x[edge_index[1], 4:5]
|
| 221 |
+
# v_inf = torch.linalg.norm(v_i, dim = 1, keepdim = True)
|
| 222 |
+
# sdf_i, sdf_j = x[edge_index[0], 5:6], x[edge_index[1], 5:6]
|
| 223 |
+
# normal_i, normal_j = x[edge_index[0], 6:8], x[edge_index[1], 6:8]
|
| 224 |
+
|
| 225 |
+
# data_sampled.edge_attr = torch.cat([x_i - x_j, v_i - v_j, p_i - p_j, sdf_i, sdf_j, v_inf, normal_i, normal_j], dim = 1)
|
| 226 |
+
|
| 227 |
+
val_dataset_sampled.append(data_sampled)
|
| 228 |
+
val_loader = DataLoader(val_dataset_sampled, batch_size=1, shuffle=True)
|
| 229 |
+
del (val_dataset_sampled)
|
| 230 |
+
|
| 231 |
+
val_loss, _, val_surf_var, val_vol_var, val_surf, val_vol = test(device, model, val_loader,
|
| 232 |
+
criterion)
|
| 233 |
+
del (val_loader)
|
| 234 |
+
val_surf_vars.append(val_surf_var)
|
| 235 |
+
val_vol_vars.append(val_vol_var)
|
| 236 |
+
val_surfs.append(val_surf)
|
| 237 |
+
val_vols.append(val_vol)
|
| 238 |
+
val_surf_var = np.array(val_surf_vars).mean(axis=0)
|
| 239 |
+
val_vol_var = np.array(val_vol_vars).mean(axis=0)
|
| 240 |
+
val_surf = np.array(val_surfs).mean(axis=0)
|
| 241 |
+
val_vol = np.array(val_vols).mean(axis=0)
|
| 242 |
+
else:
|
| 243 |
+
val_loss, _, val_surf_var, val_vol_var, val_surf, val_vol = test(device, model, val_loader,
|
| 244 |
+
criterion)
|
| 245 |
+
print("=====validation=====")
|
| 246 |
+
print('epoch: ' + str(epoch))
|
| 247 |
+
print('val_vol: ' + str(val_vol))
|
| 248 |
+
print('val_surf: ' + str(val_surf))
|
| 249 |
+
if criterion == 'MSE_weigthed':
|
| 250 |
+
val_loss = reg * val_surf + val_vol
|
| 251 |
+
val_surf_list.append(val_surf)
|
| 252 |
+
val_vol_list.append(val_vol)
|
| 253 |
+
val_surf_var_list.append(val_surf_var)
|
| 254 |
+
val_vol_var_list.append(val_vol_var)
|
| 255 |
+
pbar_train.set_postfix(train_loss=train_loss, loss_surf=loss_surf, val_loss=val_loss, val_surf=val_surf)
|
| 256 |
+
else:
|
| 257 |
+
pbar_train.set_postfix(train_loss=train_loss, loss_surf=loss_surf, val_loss=val_loss, val_surf=val_surf)
|
| 258 |
+
else:
|
| 259 |
+
pbar_train.set_postfix(train_loss=train_loss, loss_surf=loss_surf)
|
| 260 |
+
|
| 261 |
+
loss_surf_var_list = np.array(loss_surf_var_list)
|
| 262 |
+
loss_vol_var_list = np.array(loss_vol_var_list)
|
| 263 |
+
val_surf_var_list = np.array(val_surf_var_list)
|
| 264 |
+
val_vol_var_list = np.array(val_vol_var_list)
|
| 265 |
+
|
| 266 |
+
end = time.time()
|
| 267 |
+
time_elapsed = end - start
|
| 268 |
+
params_model = get_nb_trainable_params(model).astype('float')
|
| 269 |
+
print('Number of parameters:', params_model)
|
| 270 |
+
print('Time elapsed: {0:.2f} seconds'.format(time_elapsed))
|
| 271 |
+
torch.save(model, osp.join(path, 'model'))
|
| 272 |
+
|
| 273 |
+
sns.set()
|
| 274 |
+
fig_train_surf, ax_train_surf = plt.subplots(figsize=(20, 5))
|
| 275 |
+
ax_train_surf.plot(train_loss_surf_list, label='Mean loss')
|
| 276 |
+
ax_train_surf.plot(loss_surf_var_list[:, 0], label=r'$v_x$ loss')
|
| 277 |
+
ax_train_surf.plot(loss_surf_var_list[:, 1], label=r'$v_y$ loss')
|
| 278 |
+
ax_train_surf.plot(loss_surf_var_list[:, 2], label=r'$p$ loss')
|
| 279 |
+
ax_train_surf.plot(loss_surf_var_list[:, 3], label=r'$\nu_t$ loss')
|
| 280 |
+
ax_train_surf.set_xlabel('epochs')
|
| 281 |
+
ax_train_surf.set_yscale('log')
|
| 282 |
+
ax_train_surf.set_title('Train losses over the surface')
|
| 283 |
+
ax_train_surf.legend(loc='best')
|
| 284 |
+
fig_train_surf.savefig(osp.join(path, 'train_loss_surf.png'), dpi=150, bbox_inches='tight')
|
| 285 |
+
|
| 286 |
+
fig_train_vol, ax_train_vol = plt.subplots(figsize=(20, 5))
|
| 287 |
+
ax_train_vol.plot(train_loss_vol_list, label='Mean loss')
|
| 288 |
+
ax_train_vol.plot(loss_vol_var_list[:, 0], label=r'$v_x$ loss')
|
| 289 |
+
ax_train_vol.plot(loss_vol_var_list[:, 1], label=r'$v_y$ loss')
|
| 290 |
+
ax_train_vol.plot(loss_vol_var_list[:, 2], label=r'$p$ loss')
|
| 291 |
+
ax_train_vol.plot(loss_vol_var_list[:, 3], label=r'$\nu_t$ loss')
|
| 292 |
+
ax_train_vol.set_xlabel('epochs')
|
| 293 |
+
ax_train_vol.set_yscale('log')
|
| 294 |
+
ax_train_vol.set_title('Train losses over the volume')
|
| 295 |
+
ax_train_vol.legend(loc='best')
|
| 296 |
+
fig_train_vol.savefig(osp.join(path, 'train_loss_vol.png'), dpi=150, bbox_inches='tight')
|
| 297 |
+
|
| 298 |
+
if val_iter is not None:
|
| 299 |
+
fig_val_surf, ax_val_surf = plt.subplots(figsize=(20, 5))
|
| 300 |
+
ax_val_surf.plot(val_surf_list, label='Mean loss')
|
| 301 |
+
ax_val_surf.plot(val_surf_var_list[:, 0], label=r'$v_x$ loss')
|
| 302 |
+
ax_val_surf.plot(val_surf_var_list[:, 1], label=r'$v_y$ loss')
|
| 303 |
+
ax_val_surf.plot(val_surf_var_list[:, 2], label=r'$p$ loss')
|
| 304 |
+
ax_val_surf.plot(val_surf_var_list[:, 3], label=r'$\nu_t$ loss')
|
| 305 |
+
ax_val_surf.set_xlabel('epochs')
|
| 306 |
+
ax_val_surf.set_yscale('log')
|
| 307 |
+
ax_val_surf.set_title('Validation losses over the surface')
|
| 308 |
+
ax_val_surf.legend(loc='best')
|
| 309 |
+
fig_val_surf.savefig(osp.join(path, 'val_loss_surf.png'), dpi=150, bbox_inches='tight')
|
| 310 |
+
|
| 311 |
+
fig_val_vol, ax_val_vol = plt.subplots(figsize=(20, 5))
|
| 312 |
+
ax_val_vol.plot(val_vol_list, label='Mean loss')
|
| 313 |
+
ax_val_vol.plot(val_vol_var_list[:, 0], label=r'$v_x$ loss')
|
| 314 |
+
ax_val_vol.plot(val_vol_var_list[:, 1], label=r'$v_y$ loss')
|
| 315 |
+
ax_val_vol.plot(val_vol_var_list[:, 2], label=r'$p$ loss')
|
| 316 |
+
ax_val_vol.plot(val_vol_var_list[:, 3], label=r'$\nu_t$ loss')
|
| 317 |
+
ax_val_vol.set_xlabel('epochs')
|
| 318 |
+
ax_val_vol.set_yscale('log')
|
| 319 |
+
ax_val_vol.set_title('Validation losses over the volume')
|
| 320 |
+
ax_val_vol.legend(loc='best')
|
| 321 |
+
fig_val_vol.savefig(osp.join(path, 'val_loss_vol.png'), dpi=150, bbox_inches='tight')
|
| 322 |
+
|
| 323 |
+
if val_iter is not None:
|
| 324 |
+
with open(osp.join(path, name_mod + '_log.json'), 'a') as f:
|
| 325 |
+
json.dump(
|
| 326 |
+
{
|
| 327 |
+
'regression': 'Total',
|
| 328 |
+
'loss': 'MSE',
|
| 329 |
+
'nb_parameters': params_model,
|
| 330 |
+
'time_elapsed': time_elapsed,
|
| 331 |
+
'hparams': hparams,
|
| 332 |
+
'train_loss_surf': str(train_loss_surf_list[-1]),
|
| 333 |
+
'train_loss_surf_var': str(loss_surf_var_list[-1]),
|
| 334 |
+
'train_loss_vol': str(train_loss_vol_list[-1]),
|
| 335 |
+
'train_loss_vol_var': str(loss_vol_var_list[-1]),
|
| 336 |
+
'val_loss_surf': str(val_surf_list[-1]),
|
| 337 |
+
'val_loss_surf_var': str(val_surf_var_list[-1]),
|
| 338 |
+
'val_loss_vol': str(val_vol_list[-1]),
|
| 339 |
+
'val_loss_vol_var': str(val_vol_var_list[-1]),
|
| 340 |
+
}, f, indent=12, cls=NumpyEncoder
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
return model
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/metrics.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os.path as osp
|
| 2 |
+
import pathlib
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import scipy as sc
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch_geometric.nn as nng
|
| 9 |
+
from torch_geometric.loader import DataLoader
|
| 10 |
+
|
| 11 |
+
import pyvista as pv
|
| 12 |
+
import json
|
| 13 |
+
import seaborn as sns
|
| 14 |
+
import random
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
import utils.metrics_NACA as metrics_NACA
|
| 18 |
+
from utils.reorganize import reorganize
|
| 19 |
+
from dataset.dataset import Dataset
|
| 20 |
+
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
|
| 23 |
+
NU = np.array(1.56e-5)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class NumpyEncoder(json.JSONEncoder):
|
| 27 |
+
def default(self, obj):
|
| 28 |
+
if isinstance(obj, np.ndarray):
|
| 29 |
+
return obj.tolist()
|
| 30 |
+
return json.JSONEncoder.default(self, obj)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def rsquared(predict, true):
|
| 34 |
+
'''
|
| 35 |
+
Args:
|
| 36 |
+
predict (tensor): Predicted values, shape (N, *)
|
| 37 |
+
true (tensor): True values, shape (N, *)
|
| 38 |
+
|
| 39 |
+
Out:
|
| 40 |
+
rsquared (tensor): Coefficient of determination of the prediction, shape (*,)
|
| 41 |
+
'''
|
| 42 |
+
mean = true.mean(dim=0)
|
| 43 |
+
return 1 - ((true - predict) ** 2).sum(dim=0) / ((true - mean) ** 2).sum(dim=0)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def rel_err(a, b):
|
| 47 |
+
return np.abs((a - b) / a)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def WallShearStress(Jacob_U, normals):
|
| 51 |
+
S = .5 * (Jacob_U + Jacob_U.transpose(0, 2, 1))
|
| 52 |
+
S = S - S.trace(axis1=1, axis2=2).reshape(-1, 1, 1) * np.eye(2)[None] / 3
|
| 53 |
+
ShearStress = 2 * NU.reshape(-1, 1, 1) * S
|
| 54 |
+
ShearStress = (ShearStress * normals[:, :2].reshape(-1, 1, 2)).sum(axis=2)
|
| 55 |
+
|
| 56 |
+
return ShearStress
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@torch.no_grad()
|
| 60 |
+
def Infer_test(device, models, hparams, data, coef_norm=None):
|
| 61 |
+
# Inference procedure on new simulation
|
| 62 |
+
outs = [torch.zeros_like(data.y)] * len(models)
|
| 63 |
+
n_out = torch.zeros_like(data.y[:, :1])
|
| 64 |
+
idx_points = set(map(tuple, data.pos[:, :2].numpy()))
|
| 65 |
+
cond = True
|
| 66 |
+
i = 0
|
| 67 |
+
while cond:
|
| 68 |
+
i += 1
|
| 69 |
+
data_sampled = data.clone()
|
| 70 |
+
idx = random.sample(range(data_sampled.x.size(0)), hparams[0]['subsampling'])
|
| 71 |
+
idx = torch.tensor(idx)
|
| 72 |
+
idx_points = idx_points - set(map(tuple, data_sampled.pos[idx, :2].numpy()))
|
| 73 |
+
data_sampled.pos = data_sampled.pos[idx]
|
| 74 |
+
data_sampled.x = data_sampled.x[idx]
|
| 75 |
+
data_sampled.y = data_sampled.y[idx]
|
| 76 |
+
data_sampled.surf = data_sampled.surf[idx]
|
| 77 |
+
data_sampled.batch = data_sampled.batch[idx]
|
| 78 |
+
|
| 79 |
+
# try:
|
| 80 |
+
# data_sampled.edge_index = nng.radius_graph(x = data_sampled.pos.to(device), r = hparams['r'], loop = True, max_num_neighbors = int(hparams['max_neighbors'])).cpu()
|
| 81 |
+
# except KeyError:
|
| 82 |
+
# None
|
| 83 |
+
|
| 84 |
+
out = [torch.zeros_like(data.y)] * len(models)
|
| 85 |
+
tim = np.zeros(len(models))
|
| 86 |
+
for n, model in enumerate(models):
|
| 87 |
+
try:
|
| 88 |
+
data_sampled.edge_index = nng.radius_graph(x=data_sampled.pos.to(device), r=hparams[n]['r'], loop=True,
|
| 89 |
+
max_num_neighbors=int(hparams[n]['max_neighbors'])).cpu()
|
| 90 |
+
except KeyError:
|
| 91 |
+
data_sampled.edge_index = None
|
| 92 |
+
|
| 93 |
+
model.eval()
|
| 94 |
+
data_sampled = data_sampled.to(device)
|
| 95 |
+
start = time.time()
|
| 96 |
+
o = model(data_sampled)
|
| 97 |
+
tim[n] += time.time() - start
|
| 98 |
+
out[n][idx] = o.cpu()
|
| 99 |
+
|
| 100 |
+
outs[n] = outs[n] + out[n]
|
| 101 |
+
n_out[idx] = n_out[idx] + torch.ones_like(n_out[idx])
|
| 102 |
+
|
| 103 |
+
cond = (len(idx_points) > 0)
|
| 104 |
+
|
| 105 |
+
for n, out in enumerate(outs):
|
| 106 |
+
outs[n] = out / n_out
|
| 107 |
+
if coef_norm is not None:
|
| 108 |
+
outs[n][data.surf, :2] = -torch.tensor(coef_norm[2][None, :2]) * torch.ones_like(out[data.surf, :2]) / (
|
| 109 |
+
torch.tensor(coef_norm[3][None, :2]) + 1e-8)
|
| 110 |
+
outs[n][data.surf, 3] = -torch.tensor(coef_norm[2][3]) * torch.ones_like(out[data.surf, 3]) / (
|
| 111 |
+
torch.tensor(coef_norm[3][3]) + 1e-8)
|
| 112 |
+
else:
|
| 113 |
+
outs[n][data.surf, :2] = torch.zeros_like(out[data.surf, :2])
|
| 114 |
+
outs[n][data.surf, 3] = torch.zeros_like(out[data.surf, 3])
|
| 115 |
+
|
| 116 |
+
return outs, tim / i
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def Airfoil_test(internal, airfoil, outs, coef_norm, bool_surf):
|
| 120 |
+
# Produce multiple copies of a simulation for different predictions.
|
| 121 |
+
# stocker les internals, airfoils, calculer le wss, calculer le drag, le lift, plot pressure coef, plot skin friction coef, plot drag/drag, plot lift/lift
|
| 122 |
+
# calcul spearsman coef, boundary layer
|
| 123 |
+
internals = []
|
| 124 |
+
airfoils = []
|
| 125 |
+
for out in outs:
|
| 126 |
+
intern = internal.copy()
|
| 127 |
+
aerofoil = airfoil.copy()
|
| 128 |
+
|
| 129 |
+
point_mesh = intern.points[bool_surf, :2]
|
| 130 |
+
point_surf = aerofoil.points[:, :2]
|
| 131 |
+
out = (out * (coef_norm[3] + 1e-8) + coef_norm[2]).numpy()
|
| 132 |
+
out[bool_surf.numpy(), :2] = np.zeros_like(out[bool_surf.numpy(), :2])
|
| 133 |
+
out[bool_surf.numpy(), 3] = np.zeros_like(out[bool_surf.numpy(), 3])
|
| 134 |
+
intern.point_data['U'][:, :2] = out[:, :2]
|
| 135 |
+
intern.point_data['p'] = out[:, 2]
|
| 136 |
+
intern.point_data['nut'] = out[:, 3]
|
| 137 |
+
|
| 138 |
+
surf_p = intern.point_data['p'][bool_surf]
|
| 139 |
+
surf_p = reorganize(point_mesh, point_surf, surf_p)
|
| 140 |
+
aerofoil.point_data['p'] = surf_p
|
| 141 |
+
|
| 142 |
+
intern = intern.ptc(pass_point_data=True)
|
| 143 |
+
aerofoil = aerofoil.ptc(pass_point_data=True)
|
| 144 |
+
|
| 145 |
+
internals.append(intern)
|
| 146 |
+
airfoils.append(aerofoil)
|
| 147 |
+
|
| 148 |
+
return internals, airfoils
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def Airfoil_mean(internals, airfoils):
|
| 152 |
+
# Average multiple prediction over one simulation
|
| 153 |
+
|
| 154 |
+
oi_point = np.zeros((internals[0].points.shape[0], 4))
|
| 155 |
+
oi_cell = np.zeros((internals[0].cell_data['U'].shape[0], 4))
|
| 156 |
+
oa_point = np.zeros((airfoils[0].points.shape[0], 4))
|
| 157 |
+
oa_cell = np.zeros((airfoils[0].cell_data['U'].shape[0], 4))
|
| 158 |
+
|
| 159 |
+
for k in range(len(internals)):
|
| 160 |
+
oi_point[:, :2] += internals[k].point_data['U'][:, :2]
|
| 161 |
+
oi_point[:, 2] += internals[k].point_data['p']
|
| 162 |
+
oi_point[:, 3] += internals[k].point_data['nut']
|
| 163 |
+
oi_cell[:, :2] += internals[k].cell_data['U'][:, :2]
|
| 164 |
+
oi_cell[:, 2] += internals[k].cell_data['p']
|
| 165 |
+
oi_cell[:, 3] += internals[k].cell_data['nut']
|
| 166 |
+
|
| 167 |
+
oa_point[:, :2] += airfoils[k].point_data['U'][:, :2]
|
| 168 |
+
oa_point[:, 2] += airfoils[k].point_data['p']
|
| 169 |
+
oa_point[:, 3] += airfoils[k].point_data['nut']
|
| 170 |
+
oa_cell[:, :2] += airfoils[k].cell_data['U'][:, :2]
|
| 171 |
+
oa_cell[:, 2] += airfoils[k].cell_data['p']
|
| 172 |
+
oa_cell[:, 3] += airfoils[k].cell_data['nut']
|
| 173 |
+
oi_point = oi_point / len(internals)
|
| 174 |
+
oi_cell = oi_cell / len(internals)
|
| 175 |
+
oa_point = oa_point / len(airfoils)
|
| 176 |
+
oa_cell = oa_cell / len(airfoils)
|
| 177 |
+
internal_mean = internals[0].copy()
|
| 178 |
+
internal_mean.point_data['U'][:, :2] = oi_point[:, :2]
|
| 179 |
+
internal_mean.point_data['p'] = oi_point[:, 2]
|
| 180 |
+
internal_mean.point_data['nut'] = oi_point[:, 3]
|
| 181 |
+
internal_mean.cell_data['U'][:, :2] = oi_cell[:, :2]
|
| 182 |
+
internal_mean.cell_data['p'] = oi_cell[:, 2]
|
| 183 |
+
internal_mean.cell_data['nut'] = oi_cell[:, 3]
|
| 184 |
+
|
| 185 |
+
airfoil_mean = airfoils[0].copy()
|
| 186 |
+
airfoil_mean.point_data['U'][:, :2] = oa_point[:, :2]
|
| 187 |
+
airfoil_mean.point_data['p'] = oa_point[:, 2]
|
| 188 |
+
airfoil_mean.point_data['nut'] = oa_point[:, 3]
|
| 189 |
+
airfoil_mean.cell_data['U'][:, :2] = oa_cell[:, :2]
|
| 190 |
+
airfoil_mean.cell_data['p'] = oa_cell[:, 2]
|
| 191 |
+
airfoil_mean.cell_data['nut'] = oa_cell[:, 3]
|
| 192 |
+
|
| 193 |
+
return internal_mean, airfoil_mean
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def Compute_coefficients(internals, airfoils, bool_surf, Uinf, angle, keep_vtk=False):
|
| 197 |
+
# Compute force coefficients, if keet_vtk is True, also return the .vtu/.vtp with wall shear stress added over the airfoil and velocity gradient over the volume.
|
| 198 |
+
|
| 199 |
+
coefs = []
|
| 200 |
+
if keep_vtk:
|
| 201 |
+
new_internals = []
|
| 202 |
+
new_airfoils = []
|
| 203 |
+
|
| 204 |
+
for internal, airfoil in zip(internals, airfoils):
|
| 205 |
+
intern = internal.copy()
|
| 206 |
+
aerofoil = airfoil.copy()
|
| 207 |
+
|
| 208 |
+
point_mesh = intern.points[bool_surf, :2]
|
| 209 |
+
point_surf = aerofoil.points[:, :2]
|
| 210 |
+
|
| 211 |
+
intern = intern.compute_derivative(scalars='U', gradient='pred_grad')
|
| 212 |
+
|
| 213 |
+
surf_grad = intern.point_data['pred_grad'].reshape(-1, 3, 3)[bool_surf, :2, :2]
|
| 214 |
+
surf_p = intern.point_data['p'][bool_surf]
|
| 215 |
+
|
| 216 |
+
surf_grad = reorganize(point_mesh, point_surf, surf_grad)
|
| 217 |
+
surf_p = reorganize(point_mesh, point_surf, surf_p)
|
| 218 |
+
|
| 219 |
+
Wss_pred = WallShearStress(surf_grad, -aerofoil.point_data['Normals'])
|
| 220 |
+
aerofoil.point_data['wallShearStress'] = Wss_pred
|
| 221 |
+
aerofoil.point_data['p'] = surf_p
|
| 222 |
+
|
| 223 |
+
intern = intern.ptc(pass_point_data=True)
|
| 224 |
+
aerofoil = aerofoil.ptc(pass_point_data=True)
|
| 225 |
+
|
| 226 |
+
WP_int = -aerofoil.cell_data['p'][:, None] * aerofoil.cell_data['Normals'][:, :2]
|
| 227 |
+
|
| 228 |
+
Wss_int = (aerofoil.cell_data['wallShearStress'] * aerofoil.cell_data['Length'].reshape(-1, 1)).sum(axis=0)
|
| 229 |
+
WP_int = (WP_int * aerofoil.cell_data['Length'].reshape(-1, 1)).sum(axis=0)
|
| 230 |
+
force = Wss_int - WP_int
|
| 231 |
+
|
| 232 |
+
alpha = angle * np.pi / 180
|
| 233 |
+
basis = np.array([[np.cos(alpha), np.sin(alpha)], [-np.sin(alpha), np.cos(alpha)]])
|
| 234 |
+
force_rot = basis @ force
|
| 235 |
+
coef = 2 * force_rot / Uinf ** 2
|
| 236 |
+
coefs.append(coef)
|
| 237 |
+
if keep_vtk:
|
| 238 |
+
new_internals.append(intern)
|
| 239 |
+
new_airfoils.append(aerofoil)
|
| 240 |
+
|
| 241 |
+
if keep_vtk:
|
| 242 |
+
return coefs, new_internals, new_airfoils
|
| 243 |
+
else:
|
| 244 |
+
return coefs
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def Results_test(device, models, hparams, coef_norm, path_in, path_out, n_test=3, criterion='MSE',
|
| 248 |
+
x_bl=[.2, .4, .6, .8], s='full_test'):
|
| 249 |
+
'''
|
| 250 |
+
Compute criterion scores for the fields over the volume and the surface, and for the force coefficients. Also compute Spearman's correlation scores
|
| 251 |
+
for the force coefficients and the relative error for the wall shear stress and the pressure over the airfoil. Outputs the true, the mean predicted
|
| 252 |
+
and the std predicted integrated force coefficients, the true and mean predicted local force coefficients (at the surface of airfoils) and the true
|
| 253 |
+
mean predicted boundary layers at chord x_bl.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
device (str): Device on which you do the prediction.
|
| 257 |
+
models (torch_geometric.nn.Module): List of models to predict with. It is a list of a list of different training of the same model.
|
| 258 |
+
For example, it can be [model_MLP, model_GraphSAGE] where model_MLP is itself a list of the form [MLP_1, MLP_2].
|
| 259 |
+
hparams (list): List of dictionnaries of hyperparameters of the models.
|
| 260 |
+
coef_norm (tuple): Tuple of the form (mean_in, mean_out, std_in, std_out) for the denormalization of the data.
|
| 261 |
+
path_in (str): Path to find the manifest.json file and the dataset.
|
| 262 |
+
path_out (str): Path to write the scores.
|
| 263 |
+
n_test (int, optional): Number of airfoils on which you want to infer (they will be drawn randomly in the given set). Default: ``3``
|
| 264 |
+
criterion(str, optional): Criterion for the fields scores. Choose between MSE and MAE. Default: ``"MSE"``
|
| 265 |
+
x_bl (list, optional): List of chord where the extract boundary layer prediction will be extracted. Default: ``[.2, .4, .6, .8]``
|
| 266 |
+
s (str, optional): Dataset in which the simulation names are going to be sampled. Default: ``"full_test"``
|
| 267 |
+
'''
|
| 268 |
+
# Compute scores and all metrics for a
|
| 269 |
+
sns.set()
|
| 270 |
+
pathlib.Path(path_out).mkdir(parents=True, exist_ok=True)
|
| 271 |
+
|
| 272 |
+
with open(osp.join(path_in, 'manifest.json'), 'r') as f:
|
| 273 |
+
manifest = json.load(f)
|
| 274 |
+
|
| 275 |
+
test_dataset = manifest[s]
|
| 276 |
+
idx = random.sample(range(len(test_dataset)), k=n_test)
|
| 277 |
+
idx.sort()
|
| 278 |
+
|
| 279 |
+
test_dataset_vtk = Dataset(test_dataset, sample=None, coef_norm=coef_norm, my_path=path_in)
|
| 280 |
+
test_loader = DataLoader(test_dataset_vtk, shuffle=False)
|
| 281 |
+
|
| 282 |
+
if criterion == 'MSE':
|
| 283 |
+
criterion = nn.MSELoss(reduction='none')
|
| 284 |
+
elif criterion == 'MAE':
|
| 285 |
+
criterion = nn.L1Loss(reduction='none')
|
| 286 |
+
|
| 287 |
+
scores_vol = []
|
| 288 |
+
scores_surf = []
|
| 289 |
+
scores_force = []
|
| 290 |
+
scores_p = []
|
| 291 |
+
scores_wss = []
|
| 292 |
+
internals = []
|
| 293 |
+
airfoils = []
|
| 294 |
+
true_internals = []
|
| 295 |
+
true_airfoils = []
|
| 296 |
+
times = []
|
| 297 |
+
true_coefs = []
|
| 298 |
+
pred_coefs = []
|
| 299 |
+
for i in range(len(models[0])):
|
| 300 |
+
model = [models[n][i] for n in range(len(models))]
|
| 301 |
+
avg_loss_per_var = np.zeros((len(model), 4))
|
| 302 |
+
avg_loss = np.zeros(len(model))
|
| 303 |
+
avg_loss_surf_var = np.zeros((len(model), 4))
|
| 304 |
+
avg_loss_vol_var = np.zeros((len(model), 4))
|
| 305 |
+
avg_loss_surf = np.zeros(len(model))
|
| 306 |
+
avg_loss_vol = np.zeros(len(model))
|
| 307 |
+
avg_rel_err_force = np.zeros((len(model), 2))
|
| 308 |
+
avg_loss_p = np.zeros((len(model)))
|
| 309 |
+
avg_loss_wss = np.zeros((len(model), 2))
|
| 310 |
+
internal = []
|
| 311 |
+
airfoil = []
|
| 312 |
+
pred_coef = []
|
| 313 |
+
|
| 314 |
+
for j, data in enumerate(tqdm(test_loader)):
|
| 315 |
+
Uinf, angle = float(test_dataset[j].split('_')[2]), float(test_dataset[j].split('_')[3])
|
| 316 |
+
outs, tim = Infer_test(device, model, hparams, data, coef_norm=coef_norm)
|
| 317 |
+
times.append(tim)
|
| 318 |
+
intern = pv.read(osp.join(path_in, test_dataset[j], test_dataset[j] + '_internal.vtu'))
|
| 319 |
+
aerofoil = pv.read(osp.join(path_in, test_dataset[j], test_dataset[j] + '_aerofoil.vtp'))
|
| 320 |
+
tc, true_intern, true_airfoil = Compute_coefficients([intern], [aerofoil], data.surf, Uinf, angle,
|
| 321 |
+
keep_vtk=True)
|
| 322 |
+
tc, true_intern, true_airfoil = tc[0], true_intern[0], true_airfoil[0]
|
| 323 |
+
intern, aerofoil = Airfoil_test(intern, aerofoil, outs, coef_norm, data.surf)
|
| 324 |
+
pc, intern, aerofoil = Compute_coefficients(intern, aerofoil, data.surf, Uinf, angle, keep_vtk=True)
|
| 325 |
+
if i == 0:
|
| 326 |
+
true_coefs.append(tc)
|
| 327 |
+
pred_coef.append(pc)
|
| 328 |
+
|
| 329 |
+
if j in idx:
|
| 330 |
+
internal.append(intern)
|
| 331 |
+
airfoil.append(aerofoil)
|
| 332 |
+
if i == 0:
|
| 333 |
+
true_internals.append(true_intern)
|
| 334 |
+
true_airfoils.append(true_airfoil)
|
| 335 |
+
|
| 336 |
+
for n, out in enumerate(outs):
|
| 337 |
+
loss_per_var = criterion(out, data.y).mean(dim=0)
|
| 338 |
+
loss = loss_per_var.mean()
|
| 339 |
+
loss_surf_var = criterion(out[data.surf, :], data.y[data.surf, :]).mean(dim=0)
|
| 340 |
+
loss_vol_var = criterion(out[~data.surf, :], data.y[~data.surf, :]).mean(dim=0)
|
| 341 |
+
loss_surf = loss_surf_var.mean()
|
| 342 |
+
loss_vol = loss_vol_var.mean()
|
| 343 |
+
|
| 344 |
+
avg_loss_per_var[n] += loss_per_var.cpu().numpy()
|
| 345 |
+
avg_loss[n] += loss.cpu().numpy()
|
| 346 |
+
avg_loss_surf_var[n] += loss_surf_var.cpu().numpy()
|
| 347 |
+
avg_loss_vol_var[n] += loss_vol_var.cpu().numpy()
|
| 348 |
+
avg_loss_surf[n] += loss_surf.cpu().numpy()
|
| 349 |
+
avg_loss_vol[n] += loss_vol.cpu().numpy()
|
| 350 |
+
avg_rel_err_force[n] += rel_err(tc, pc[n])
|
| 351 |
+
avg_loss_wss[n] += rel_err(true_airfoil.point_data['wallShearStress'],
|
| 352 |
+
aerofoil[n].point_data['wallShearStress']).mean(axis=0)
|
| 353 |
+
avg_loss_p[n] += rel_err(true_airfoil.point_data['p'], aerofoil[n].point_data['p']).mean(axis=0)
|
| 354 |
+
|
| 355 |
+
internals.append(internal)
|
| 356 |
+
airfoils.append(airfoil)
|
| 357 |
+
pred_coefs.append(pred_coef)
|
| 358 |
+
|
| 359 |
+
score_var = np.array(avg_loss_per_var) / len(test_loader)
|
| 360 |
+
score = np.array(avg_loss) / len(test_loader)
|
| 361 |
+
score_surf_var = np.array(avg_loss_surf_var) / len(test_loader)
|
| 362 |
+
score_vol_var = np.array(avg_loss_vol_var) / len(test_loader)
|
| 363 |
+
score_surf = np.array(avg_loss_surf) / len(test_loader)
|
| 364 |
+
score_vol = np.array(avg_loss_vol) / len(test_loader)
|
| 365 |
+
score_force = np.array(avg_rel_err_force) / len(test_loader)
|
| 366 |
+
score_p = np.array(avg_loss_p) / len(test_loader)
|
| 367 |
+
score_wss = np.array(avg_loss_wss) / len(test_loader)
|
| 368 |
+
|
| 369 |
+
score = score_surf + score_vol
|
| 370 |
+
scores_vol.append(score_vol_var)
|
| 371 |
+
scores_surf.append(score_surf_var)
|
| 372 |
+
scores_force.append(score_force)
|
| 373 |
+
scores_p.append(score_p)
|
| 374 |
+
scores_wss.append(score_wss)
|
| 375 |
+
|
| 376 |
+
scores_vol = np.array(scores_vol)
|
| 377 |
+
scores_surf = np.array(scores_surf)
|
| 378 |
+
scores_force = np.array(scores_force)
|
| 379 |
+
scores_p = np.array(scores_p)
|
| 380 |
+
scores_wss = np.array(scores_wss)
|
| 381 |
+
times = np.array(times)
|
| 382 |
+
true_coefs = np.array(true_coefs)
|
| 383 |
+
pred_coefs = np.array(pred_coefs)
|
| 384 |
+
pred_coefs_mean = pred_coefs.mean(axis=0)
|
| 385 |
+
pred_coefs_std = pred_coefs.std(axis=0)
|
| 386 |
+
|
| 387 |
+
spear_coefs = []
|
| 388 |
+
for j in range(pred_coefs.shape[0]):
|
| 389 |
+
spear_coef = []
|
| 390 |
+
for k in range(pred_coefs.shape[2]):
|
| 391 |
+
spear_drag = sc.stats.spearmanr(true_coefs[:, 0], pred_coefs[j, :, k, 0])[0]
|
| 392 |
+
spear_lift = sc.stats.spearmanr(true_coefs[:, 1], pred_coefs[j, :, k, 1])[0]
|
| 393 |
+
spear_coef.append([spear_drag, spear_lift])
|
| 394 |
+
spear_coefs.append(spear_coef)
|
| 395 |
+
spear_coefs = np.array(spear_coefs)
|
| 396 |
+
|
| 397 |
+
with open(osp.join(path_out, 'score.json'), 'w') as f:
|
| 398 |
+
json.dump(
|
| 399 |
+
{
|
| 400 |
+
'mean_time': times.mean(axis=0),
|
| 401 |
+
'std_time': times.std(axis=0),
|
| 402 |
+
'mean_score_vol': scores_vol.mean(axis=0),
|
| 403 |
+
'std_score_vol': scores_vol.std(axis=0),
|
| 404 |
+
'mean_score_surf': scores_surf.mean(axis=0),
|
| 405 |
+
'std_score_surf': scores_surf.std(axis=0),
|
| 406 |
+
'mean_rel_p': scores_p.mean(axis=0),
|
| 407 |
+
'std_rel_p': scores_p.std(axis=0),
|
| 408 |
+
'mean_rel_wss': scores_wss.mean(axis=0),
|
| 409 |
+
'std_rel_wss': scores_wss.std(axis=0),
|
| 410 |
+
'mean_score_force': scores_force.mean(axis=0),
|
| 411 |
+
'std_score_force': scores_force.std(axis=0),
|
| 412 |
+
'spearman_coef_mean': spear_coefs.mean(axis=0),
|
| 413 |
+
'spearman_coef_std': spear_coefs.std(axis=0)
|
| 414 |
+
}, f, indent=4, cls=NumpyEncoder
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
surf_coefs = []
|
| 418 |
+
true_surf_coefs = []
|
| 419 |
+
bls = []
|
| 420 |
+
true_bls = []
|
| 421 |
+
for i in range(len(internals[0])):
|
| 422 |
+
aero_name = test_dataset[idx[i]]
|
| 423 |
+
true_internal = true_internals[i]
|
| 424 |
+
true_airfoil = true_airfoils[i]
|
| 425 |
+
surf_coef = []
|
| 426 |
+
bl = []
|
| 427 |
+
for j in range(len(internals[0][0])):
|
| 428 |
+
internal_mean, airfoil_mean = Airfoil_mean([internals[k][i][j] for k in range(len(internals))],
|
| 429 |
+
[airfoils[k][i][j] for k in range(len(airfoils))])
|
| 430 |
+
internal_mean.save(osp.join(path_out, test_dataset[idx[i]] + '_' + str(j) + '.vtu'))
|
| 431 |
+
surf_coef.append(np.array(metrics_NACA.surface_coefficients(airfoil_mean, aero_name)))
|
| 432 |
+
b = []
|
| 433 |
+
for x in x_bl:
|
| 434 |
+
b.append(np.array(metrics_NACA.boundary_layer(airfoil_mean, internal_mean, aero_name, x)))
|
| 435 |
+
bl.append(np.array(b))
|
| 436 |
+
true_surf_coefs.append(np.array(metrics_NACA.surface_coefficients(true_airfoil, aero_name)))
|
| 437 |
+
true_bl = []
|
| 438 |
+
for x in x_bl:
|
| 439 |
+
true_bl.append(np.array(metrics_NACA.boundary_layer(true_airfoil, true_internal, aero_name, x)))
|
| 440 |
+
true_bls.append(np.array(true_bl))
|
| 441 |
+
surf_coefs.append(np.array(surf_coef))
|
| 442 |
+
bls.append(np.array(bl))
|
| 443 |
+
|
| 444 |
+
true_bls = np.array(true_bls)
|
| 445 |
+
bls = np.array(bls)
|
| 446 |
+
|
| 447 |
+
return true_coefs, pred_coefs_mean, pred_coefs_std, true_surf_coefs, surf_coefs, true_bls, bls
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/metrics_NACA.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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born as sns
|
| 4 |
+
from utils.naca_generator import camber_line
|
| 5 |
+
|
| 6 |
+
sns.set()
|
| 7 |
+
|
| 8 |
+
# Properties of air at sea level and 293.15K
|
| 9 |
+
RHO = 1.184
|
| 10 |
+
NU = 1.56e-5
|
| 11 |
+
C = 346.1
|
| 12 |
+
P_ref = 1.013e5
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def surface_coefficients(airfoil, aero_name, compressible=False, extrado=False):
|
| 16 |
+
u_inf = float(aero_name.split('_')[2])
|
| 17 |
+
digits = list(map(float, aero_name.split('_')[4:-1]))
|
| 18 |
+
if compressible:
|
| 19 |
+
qInf = 0.5 * u_inf ** 2 * RHO
|
| 20 |
+
else:
|
| 21 |
+
qInf = 0.5 * u_inf ** 2
|
| 22 |
+
|
| 23 |
+
if extrado:
|
| 24 |
+
camber = camber_line(digits, airfoil.points[:, 0])[0]
|
| 25 |
+
idx_extrado = (airfoil.points[:, 1] > camber)
|
| 26 |
+
points = airfoil.points[:, 0]
|
| 27 |
+
pressure = airfoil.point_data['p']
|
| 28 |
+
wss = np.linalg.norm(airfoil.point_data['wallShearStress'][:, :2], axis=1)
|
| 29 |
+
|
| 30 |
+
c_p = np.concatenate([points[:, None], pressure[:, None] / qInf], axis=1)
|
| 31 |
+
c_l = np.concatenate([points[:, None], wss[:, None] / qInf], axis=1)
|
| 32 |
+
|
| 33 |
+
if extrado:
|
| 34 |
+
return c_p, c_l, idx_extrado
|
| 35 |
+
else:
|
| 36 |
+
return c_p, c_l
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def compare_surface_coefs(coefs1, coefs2, extrado=True, path=None):
|
| 40 |
+
ycp1, ycp2, c_p1, c_p2 = coefs1[0][:, 0], coefs2[0][:, 0], coefs1[0][:, 1], coefs2[0][:, 1]
|
| 41 |
+
ycl1, ycl2, c_f1, c_f2 = coefs1[1][:, 0], coefs2[1][:, 0], coefs1[1][:, 1], coefs2[1][:, 1]
|
| 42 |
+
|
| 43 |
+
fig, ax = plt.subplots(2, figsize=(20, 10))
|
| 44 |
+
if extrado:
|
| 45 |
+
n_extrado1, n_extrado2 = coefs1[2], coefs2[2]
|
| 46 |
+
ax[0].scatter(ycp1[:n_extrado1], c_p1[:n_extrado1], label='Extrado 1')
|
| 47 |
+
ax[0].scatter(ycp1[n_extrado1:], c_p1[n_extrado1:], color='r', marker='x', label='Intrado 1')
|
| 48 |
+
ax[0].scatter(ycp2[:n_extrado2], c_p2[:n_extrado2], color='y', label='Extrado Target')
|
| 49 |
+
ax[0].scatter(ycp2[n_extrado2:], c_p2[n_extrado2:], color='g', marker='x', label='Intrado Target')
|
| 50 |
+
|
| 51 |
+
ax[1].scatter(ycl1[:n_extrado1], c_f1[:n_extrado1], label='Extrado 1')
|
| 52 |
+
ax[1].scatter(ycl1[n_extrado1:], c_f1[n_extrado1:], color='r', marker='x', label='Intrado 1')
|
| 53 |
+
ax[1].scatter(ycl2[:n_extrado2], c_f2[:n_extrado2], color='y', label='Extrado Target')
|
| 54 |
+
ax[1].scatter(ycl2[n_extrado2:], c_f2[n_extrado2:], color='g', marker='x', label='Intrado Target')
|
| 55 |
+
|
| 56 |
+
else:
|
| 57 |
+
ax[0].scatter(ycp1, c_p1, label='Experiment 1')
|
| 58 |
+
ax[0].scatter(ycp2, c_p2, color='y', label='Experiment Target')
|
| 59 |
+
|
| 60 |
+
ax[1].scatter(ycl1, c_f1, label='Experiment 1')
|
| 61 |
+
ax[1].scatter(ycl2, c_f2, color='y', label='Experiment Targer')
|
| 62 |
+
|
| 63 |
+
ax[0].invert_yaxis()
|
| 64 |
+
ax[0].set_xlabel('x/c')
|
| 65 |
+
ax[1].set_xlabel('x/c')
|
| 66 |
+
ax[0].set_ylabel(r'$C_p$')
|
| 67 |
+
ax[1].set_ylabel(r'$C_f$')
|
| 68 |
+
ax[0].set_title('Pressure coefficient')
|
| 69 |
+
ax[1].set_title('Skin friction coefficient')
|
| 70 |
+
ax[0].legend(loc='best')
|
| 71 |
+
ax[1].legend(loc='best')
|
| 72 |
+
|
| 73 |
+
if path != None:
|
| 74 |
+
fig.savefig(path + 'surface_coefs.png', bbox_inches='tight', dpi=150)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def boundary_layer(airfoil, internal, aero_name, x, y=1e-3, resolution=int(1e3), direction='normals', rotation=False,
|
| 78 |
+
extrado=True):
|
| 79 |
+
u_inf = float(aero_name.split('_')[2])
|
| 80 |
+
digits = list(map(float, aero_name.split('_')[4:-1]))
|
| 81 |
+
camber = camber_line(digits, airfoil.points[:, 0])[0]
|
| 82 |
+
idx_extrado = (airfoil.points[:, 1] > camber)
|
| 83 |
+
|
| 84 |
+
if extrado:
|
| 85 |
+
arg = np.argmin(np.abs(airfoil.points[idx_extrado, 0] - x)) + 1
|
| 86 |
+
arg = np.argwhere(idx_extrado.cumsum() == arg).min()
|
| 87 |
+
else:
|
| 88 |
+
arg = np.argmin(np.abs(airfoil.points[~idx_extrado, 0] - x)) + 1
|
| 89 |
+
arg = np.argwhere((~idx_extrado).cumsum() == arg).min()
|
| 90 |
+
|
| 91 |
+
if direction == 'normals':
|
| 92 |
+
normals = -airfoil.point_data['Normals'][arg]
|
| 93 |
+
|
| 94 |
+
elif direction == 'y':
|
| 95 |
+
normals = np.array([0, 2 * int(extrado) - 1, 0])
|
| 96 |
+
|
| 97 |
+
a, b = airfoil.points[arg], airfoil.points[arg] + y * normals
|
| 98 |
+
bl = internal.sample_over_line(a, b, resolution=resolution)
|
| 99 |
+
|
| 100 |
+
if rotation:
|
| 101 |
+
rot = np.array([[0, 1, 0], [-1, 0, 0], [0, 0, 1]])
|
| 102 |
+
u = (bl.point_data['U'] * (rot @ normals)).sum(axis=1)
|
| 103 |
+
v = (bl.point_data['U'] * normals).sum(axis=1)
|
| 104 |
+
else:
|
| 105 |
+
u = bl.point_data['U'][:, 0]
|
| 106 |
+
v = bl.point_data['U'][:, 1]
|
| 107 |
+
|
| 108 |
+
nut = bl.point_data['nut']
|
| 109 |
+
yc = bl.points[:, 1] - a[1]
|
| 110 |
+
|
| 111 |
+
return yc, u / u_inf, v / u_inf, nut / NU
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def compare_boundary_layer(coefs1, coefs2, ylim=.1, path=None, ylog=False):
|
| 115 |
+
yc1, u1, v1, nut1 = coefs1
|
| 116 |
+
yc2, u2, v2, nut2 = coefs2
|
| 117 |
+
|
| 118 |
+
fig, ax = plt.subplots(1, 3, figsize=(30, 10))
|
| 119 |
+
ax[0].scatter(u1, yc1, label='Experiment 1')
|
| 120 |
+
ax[0].scatter(u2, yc2, label='Experiment 2', color='r', marker='x')
|
| 121 |
+
ax[0].set_xlabel(r'$u/U_\infty$')
|
| 122 |
+
ax[0].set_ylabel(r'$(y-y_0)/c$')
|
| 123 |
+
# ax[0].set_xlim([-0.2, 1.4])
|
| 124 |
+
# ax[0].set_ylim([0, ylim])
|
| 125 |
+
ax[0].legend(loc='best')
|
| 126 |
+
|
| 127 |
+
ax[1].scatter(v1, yc1, label='Experiment 1')
|
| 128 |
+
ax[1].scatter(v2, yc2, label='Experiment 2', color='r', marker='x')
|
| 129 |
+
ax[1].set_xlabel(r'$v/U_\infty$')
|
| 130 |
+
ax[1].set_ylabel(r'$(y-y_0)/c$')
|
| 131 |
+
# ax[1].set_xlim([-0.2, 0.2])
|
| 132 |
+
# ax[1].set_ylim([0, ylim])
|
| 133 |
+
ax[1].legend(loc='best')
|
| 134 |
+
|
| 135 |
+
ax[2].scatter(nut1, yc1, label='Experience 1')
|
| 136 |
+
ax[2].scatter(nut2, yc2, label='Experience 2', color='r', marker='x')
|
| 137 |
+
# ax[2].set_ylim([0, ylim])
|
| 138 |
+
ax[2].set_xlabel(r'$\nu_t/\nu$')
|
| 139 |
+
ax[2].set_ylabel(r'$(y-y_0)/c$')
|
| 140 |
+
ax[2].legend(loc='best')
|
| 141 |
+
|
| 142 |
+
if ylog:
|
| 143 |
+
ax[0].set_yscale('log')
|
| 144 |
+
ax[1].set_yscale('log')
|
| 145 |
+
ax[2].set_yscale('log')
|
| 146 |
+
|
| 147 |
+
if path != None:
|
| 148 |
+
fig.savefig(path + 'boundary_layer.png', bbox_inches='tight', dpi=150)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def plot_residuals(path, params):
|
| 152 |
+
datas = dict()
|
| 153 |
+
if params['turbulence'] == 'SA':
|
| 154 |
+
fields = ['Ux', 'Uy', 'p', 'nuTilda']
|
| 155 |
+
elif params['turbulence'] == 'SST':
|
| 156 |
+
fields = ['Ux', 'Uy', 'p', 'k', 'omega']
|
| 157 |
+
for field in fields:
|
| 158 |
+
data = np.loadtxt(path + 'logs/' + field + '_0')[:, 1]
|
| 159 |
+
datas[field] = data
|
| 160 |
+
|
| 161 |
+
if params['turbulence'] == 'SA':
|
| 162 |
+
fig, ax = plt.subplots(2, 2, figsize=(20, 20))
|
| 163 |
+
ax[1, 1].plot(datas['nuTilda'])
|
| 164 |
+
ax[1, 1].set_yscale('log')
|
| 165 |
+
ax[1, 1].set_title('nuTilda residual')
|
| 166 |
+
ax[1, 1].set_xlabel('Number of iterations')
|
| 167 |
+
|
| 168 |
+
elif params['turbulence'] == 'SST':
|
| 169 |
+
fig, ax = plt.subplots(3, 2, figsize=(30, 20))
|
| 170 |
+
ax[1, 1].plot(datas['k'])
|
| 171 |
+
ax[1, 1].set_yscale('log')
|
| 172 |
+
ax[1, 1].set_title('k residual')
|
| 173 |
+
ax[1, 1].set_xlabel('Number of iterations')
|
| 174 |
+
|
| 175 |
+
ax[2, 0].plot(datas['omega'])
|
| 176 |
+
ax[2, 0].set_yscale('log')
|
| 177 |
+
ax[2, 0].set_title('omega residual')
|
| 178 |
+
ax[2, 0].set_xlabel('Number of iterations');
|
| 179 |
+
|
| 180 |
+
ax[0, 0].plot(datas['Ux'])
|
| 181 |
+
ax[0, 0].set_yscale('log')
|
| 182 |
+
ax[0, 0].set_title('Ux residual')
|
| 183 |
+
|
| 184 |
+
ax[0, 1].plot(datas['Uy'])
|
| 185 |
+
ax[0, 1].set_yscale('log')
|
| 186 |
+
ax[0, 1].set_title('Uy residual')
|
| 187 |
+
|
| 188 |
+
ax[1, 0].plot(datas['p'])
|
| 189 |
+
ax[1, 0].set_yscale('log')
|
| 190 |
+
ax[1, 0].set_title('p residual')
|
| 191 |
+
ax[1, 0].set_xlabel('Number of iterations');
|
| 192 |
+
|
| 193 |
+
fig.savefig(path + 'residuals.png', bbox_inches='tight', dpi=150)
|
| 194 |
+
|
| 195 |
+
return datas
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def plot_coef_convergence(path, params):
|
| 199 |
+
datas = dict()
|
| 200 |
+
datas['c_d'] = np.loadtxt(path + 'postProcessing/forceCoeffs1/0/coefficient.dat')[:, 1]
|
| 201 |
+
datas['c_l'] = np.loadtxt(path + 'postProcessing/forceCoeffs1/0/coefficient.dat')[:, 3]
|
| 202 |
+
c_d, c_l = datas['c_d'][-1], datas['c_l'][-1]
|
| 203 |
+
|
| 204 |
+
fig, ax = plt.subplots(2, figsize=(30, 15))
|
| 205 |
+
ax[0].plot(datas['c_d'])
|
| 206 |
+
ax[0].set_ylim([.5 * c_d, 1.5 * c_d])
|
| 207 |
+
ax[0].set_title('Drag coefficient')
|
| 208 |
+
ax[0].set_xlabel('Number of iterations')
|
| 209 |
+
ax[0].set_ylabel(r'$C_D$')
|
| 210 |
+
|
| 211 |
+
ax[1].plot(datas['c_l'])
|
| 212 |
+
ax[1].set_title('Lift coefficient')
|
| 213 |
+
ax[1].set_ylim([.5 * c_l, 1.5 * c_l])
|
| 214 |
+
ax[1].set_ylabel(r'$C_L$')
|
| 215 |
+
ax[1].set_xlabel('Number of iterations');
|
| 216 |
+
|
| 217 |
+
print('Drag coefficient: {0:.5}, lift coefficient: {1:.5}'.format(c_d, c_l))
|
| 218 |
+
|
| 219 |
+
fig.savefig(path + 'coef_convergence.png', bbox_inches='tight', dpi=150)
|
| 220 |
+
|
| 221 |
+
return datas, c_d, c_l
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/naca_generator.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def thickness_dist(t, x, CTE=True):
|
| 5 |
+
# CTE for close trailing edge
|
| 6 |
+
if CTE:
|
| 7 |
+
a = -0.1036
|
| 8 |
+
else:
|
| 9 |
+
a = -0.1015
|
| 10 |
+
return 5 * t * (0.2969 * np.sqrt(x) - 0.1260 * x - 0.3516 * x ** 2 + 0.2843 * x ** 3 + a * x ** 4)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def camber_line(params, x):
|
| 14 |
+
# assert np.all(np.logical_and(x >= -1e-1, x <= 1)), 'Found x > 1 or x < 0'
|
| 15 |
+
y_c = np.zeros_like(x)
|
| 16 |
+
dy_c = np.zeros_like(x)
|
| 17 |
+
|
| 18 |
+
if len(params) == 2:
|
| 19 |
+
m = params[0] / 100
|
| 20 |
+
p = params[1] / 10
|
| 21 |
+
|
| 22 |
+
if p == 0:
|
| 23 |
+
dy_c = -2 * m * x
|
| 24 |
+
return y_c, dy_c
|
| 25 |
+
elif p == 1:
|
| 26 |
+
dy_c = 2 * m * (1 - x)
|
| 27 |
+
return y_c, dy_c
|
| 28 |
+
|
| 29 |
+
mask1 = (x < p)
|
| 30 |
+
mask2 = (x >= p)
|
| 31 |
+
y_c[mask1] = (m / p ** 2) * (2 * p * x[mask1] - x[mask1] ** 2)
|
| 32 |
+
dy_c[mask1] = (2 * m / p ** 2) * (p - x[mask1])
|
| 33 |
+
y_c[mask2] = (m / (1 - p) ** 2) * ((1 - 2 * p) + 2 * p * x[mask2] - x[mask2] ** 2)
|
| 34 |
+
dy_c[mask2] = (2 * m / (1 - p) ** 2) * (p - x[mask2])
|
| 35 |
+
|
| 36 |
+
elif len(params) == 3:
|
| 37 |
+
l, p, q = params
|
| 38 |
+
c_l, x_f = 3 / 20 * l, p / 20
|
| 39 |
+
|
| 40 |
+
f = lambda x: x * (1 - np.sqrt(x / 3)) - x_f
|
| 41 |
+
df = lambda x: 1 - 3 * np.sqrt(x / 3) / 2
|
| 42 |
+
old_m = 0.5
|
| 43 |
+
cond = True
|
| 44 |
+
while cond:
|
| 45 |
+
new_m = np.max([old_m - f(old_m) / df(old_m), 0])
|
| 46 |
+
cond = (np.abs(old_m - new_m) > 1e-15)
|
| 47 |
+
old_m = new_m
|
| 48 |
+
m = old_m
|
| 49 |
+
r = (3 * m - 7 * m ** 2 + 8 * m ** 3 - 4 * m ** 4) / np.sqrt(m * (1 - m)) - 3 / 2 * (1 - 2 * m) * (
|
| 50 |
+
np.pi / 2 - np.arcsin(1 - 2 * m))
|
| 51 |
+
k_1 = c_l / r
|
| 52 |
+
|
| 53 |
+
mask1 = (x <= m)
|
| 54 |
+
mask2 = (x > m)
|
| 55 |
+
if q == 0:
|
| 56 |
+
y_c[mask1] = k_1 * ((x[mask1] ** 3 - 3 * m * x[mask1] ** 2 + m ** 2 * (3 - m) * x[mask1]))
|
| 57 |
+
dy_c[mask1] = k_1 * (3 * x[mask1] ** 2 - 6 * m * x[mask1] + m ** 2 * (3 - m))
|
| 58 |
+
y_c[mask2] = k_1 * m ** 3 * (1 - x[mask2])
|
| 59 |
+
dy_c[mask2] = -k_1 * m ** 3 * np.ones_like(dy_c[mask2])
|
| 60 |
+
|
| 61 |
+
elif q == 1:
|
| 62 |
+
k = (3 * (m - x_f) ** 2 - m ** 3) / (1 - m) ** 3
|
| 63 |
+
y_c[mask1] = k_1 * ((x[mask1] - m) ** 3 - k * (1 - m) ** 3 * x[mask1] - m ** 3 * x[mask1] + m ** 3)
|
| 64 |
+
dy_c[mask1] = k_1 * (3 * (x[mask1] - m) ** 2 - k * (1 - m) ** 3 - m ** 3)
|
| 65 |
+
y_c[mask2] = k_1 * (k * (x[mask2] - m) ** 3 - k * (1 - m) ** 3 * x[mask2] - m ** 3 * x[mask2] + m ** 3)
|
| 66 |
+
dy_c[mask2] = k_1 * (3 * k * (x[mask2] - m) ** 2 - k * (1 - m) ** 3 - m ** 3)
|
| 67 |
+
|
| 68 |
+
else:
|
| 69 |
+
raise ValueError('Q must be 0 for normal camber or 1 for reflex camber.')
|
| 70 |
+
|
| 71 |
+
else:
|
| 72 |
+
raise ValueError('The first input must be a tuple of the 2 or 3 digits that represent the camber line.')
|
| 73 |
+
|
| 74 |
+
return y_c, dy_c
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def naca_generator(params, nb_samples=400, scale=1, origin=(0, 0), cosine_spacing=True, verbose=True, CTE=True):
|
| 78 |
+
if len(params) == 3:
|
| 79 |
+
params_c = params[:2]
|
| 80 |
+
t = params[2] / 100
|
| 81 |
+
if verbose:
|
| 82 |
+
print(f'Generating naca M = {params_c[0]}, P = {params_c[1]}, XX = {t * 100}')
|
| 83 |
+
elif len(params) == 4:
|
| 84 |
+
params_c = params[:3]
|
| 85 |
+
t = params[3] / 100
|
| 86 |
+
if verbose:
|
| 87 |
+
print(f'Generating naca L = {params_c[0]}, P = {params_c[1]}, Q = {params_c[2]}, XX = {t * 100}')
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError('The first argument must be a tuple of the 4 or 5 digits of the airfoil.')
|
| 90 |
+
|
| 91 |
+
if cosine_spacing:
|
| 92 |
+
beta = np.pi * np.linspace(1, 0, nb_samples + 1, endpoint=True)
|
| 93 |
+
x = (1 - np.cos(beta)) / 2
|
| 94 |
+
else:
|
| 95 |
+
x = np.linspace(1, 0, nb_samples + 1, endpoint=True)
|
| 96 |
+
|
| 97 |
+
y_c, dy_c = camber_line(params_c, x)
|
| 98 |
+
y_t = thickness_dist(t, x, CTE)
|
| 99 |
+
theta = np.arctan(dy_c)
|
| 100 |
+
x_u = x - y_t * np.sin(theta)
|
| 101 |
+
x_l = x + y_t * np.sin(theta)
|
| 102 |
+
y_u = y_c + y_t * np.cos(theta)
|
| 103 |
+
y_l = y_c - y_t * np.cos(theta)
|
| 104 |
+
x = np.concatenate([x_u, x_l[:-1][::-1]], axis=0)
|
| 105 |
+
y = np.concatenate([y_u, y_l[:-1][::-1]], axis=0)
|
| 106 |
+
pos = np.stack([
|
| 107 |
+
x * scale + origin[0],
|
| 108 |
+
y * scale + origin[1]
|
| 109 |
+
], axis=-1
|
| 110 |
+
)
|
| 111 |
+
pos[0], pos[-1] = np.array([1, 0]), np.array([1, 0])
|
| 112 |
+
return pos
|
code/ezflow_v3/baselines/Transolver-main/Airfoil-Design-AirfRANS/utils/reorganize.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
def reorganize(in_order_points, out_order_points, quantity_to_reordered):
|
| 4 |
+
n = out_order_points.shape[0]
|
| 5 |
+
idx = np.zeros(n)
|
| 6 |
+
for i in range(n):
|
| 7 |
+
cond = (out_order_points[i] == in_order_points)
|
| 8 |
+
cond = cond[:, 0]*cond[:, 1]
|
| 9 |
+
idx[i] = np.argwhere(cond)[0][0]
|
| 10 |
+
idx = idx.astype('int')
|
| 11 |
+
|
| 12 |
+
assert (in_order_points[idx] == out_order_points).all()
|
| 13 |
+
|
| 14 |
+
return quantity_to_reordered[idx]
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Transolver for Car Design
|
| 2 |
+
|
| 3 |
+
We test [Transolver](https://arxiv.org/abs/2402.02366) on practical design tasks. The car design task requires the model to estimate the surrounding wind speed and surface pressure for a driving car.
|
| 4 |
+
|
| 5 |
+
<p align="center">
|
| 6 |
+
<img src=".\fig\task.png" height = "200" alt="" align=center />
|
| 7 |
+
<br><br>
|
| 8 |
+
<b>Figure 1.</b> Car design task.
|
| 9 |
+
</p>
|
| 10 |
+
|
| 11 |
+
Relative error of surrounding wind, surface pressure and [drag coefficient](https://en.wikipedia.org/wiki/Drag_coefficient) are recorded, as well as [Spearman's rank correlations](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient), which can be used to quantify the model's capability in ranking different designs.
|
| 12 |
+
|
| 13 |
+
<p align="center">
|
| 14 |
+
<img src=".\fig\results.png" height = "300" alt="" align=center />
|
| 15 |
+
<br><br>
|
| 16 |
+
<b>Table 1.</b> Model comparisons of the car design task.
|
| 17 |
+
</p>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
## Get Started
|
| 21 |
+
|
| 22 |
+
1. Install Python 3.8. For convenience, execute the following command.
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
pip install -r requirements.txt
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Note: You need to install [pytorch_geometric](https://github.com/pyg-team/pytorch_geometric).
|
| 29 |
+
|
| 30 |
+
2. Prepare Data.
|
| 31 |
+
|
| 32 |
+
The raw data can be found [[here]](http://www.nobuyuki-umetani.com/publication/mlcfd_data.zip), which is provided by [Nobuyuki Umetani](https://dl.acm.org/doi/abs/10.1145/3197517.3201325).
|
| 33 |
+
|
| 34 |
+
If you find the download button does not work, please directly try this link: http://www.nobuyuki-umetani.com/publication/mlcfd_data.zip
|
| 35 |
+
|
| 36 |
+
3. Train and evaluate model. We provide the experiment scripts under the folder `./scripts/`. You can reproduce the experiment results as the following examples:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
bash scripts/Transolver.sh # for Training (will take 8-10 hours on one single A100)
|
| 40 |
+
bash scripts/Evaluation.sh # for Evaluation
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Note: You need to change the argument `--data_dir` and `--save_dir` to your dataset path. Here `data_dir` is for the raw data and `save_dir` is to save the preprocessed data.
|
| 44 |
+
|
| 45 |
+
If you have already downloaded or generated the preprocecessed data, you can change `--preprocessed` as True for speed up.
|
| 46 |
+
|
| 47 |
+
4. Develop your own model. Here are the instructions:
|
| 48 |
+
|
| 49 |
+
- Add the model file under folder `./models/`.
|
| 50 |
+
- Add the model configuration into `./main.py`.
|
| 51 |
+
- Add a script file under folder `./scripts/` and change the argument `--model`.
|
| 52 |
+
|
| 53 |
+
## Slice Visualization
|
| 54 |
+
|
| 55 |
+
Transolver proposes to **learn physical states** hidden under the unwieldy meshes.
|
| 56 |
+
|
| 57 |
+
The following visualization demonstrates that Transolver can successfully learn to ascribe the points under similar physical state to the same slice, such as windshield, license plate and headlight.
|
| 58 |
+
|
| 59 |
+
<p align="center">
|
| 60 |
+
<img src=".\fig\car_slice_surf.png" height = "300" alt="" align=center />
|
| 61 |
+
<br><br>
|
| 62 |
+
<b>Figure 2.</b> Visualization for Transolver learned physical states.
|
| 63 |
+
</p>
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
## Showcases
|
| 67 |
+
|
| 68 |
+
Transolver achieves the best performance in complex geometries and hybrid physics.
|
| 69 |
+
|
| 70 |
+
<p align="center">
|
| 71 |
+
<img src=".\fig\case_study.png" height = "150" alt="" align=center />
|
| 72 |
+
<br><br>
|
| 73 |
+
<b>Figure 3.</b> Case study of Transolver and other models.
|
| 74 |
+
</p>
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
## Citation
|
| 78 |
+
|
| 79 |
+
If you find this repo useful, please cite our paper.
|
| 80 |
+
|
| 81 |
+
```
|
| 82 |
+
@inproceedings{wu2024Transolver,
|
| 83 |
+
title={Transolver: A Fast Transformer Solver for PDEs on General Geometries},
|
| 84 |
+
author={Haixu Wu and Huakun Luo and Haowen Wang and Jianmin Wang and Mingsheng Long},
|
| 85 |
+
booktitle={International Conference on Machine Learning},
|
| 86 |
+
year={2024}
|
| 87 |
+
}
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
## Contact
|
| 91 |
+
|
| 92 |
+
If you have any questions or want to use the code, please contact [wuhx23@mails.tsinghua.edu.cn](mailto:wuhx23@mails.tsinghua.edu.cn).
|
| 93 |
+
|
| 94 |
+
## Acknowledgement
|
| 95 |
+
|
| 96 |
+
We appreciate the following papers a lot for their valuable code base or datasets:
|
| 97 |
+
|
| 98 |
+
https://dl.acm.org/doi/abs/10.1145/3197517.3201325
|
| 99 |
+
|
| 100 |
+
https://openreview.net/forum?id=EyQO9RPhwN
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/dataset/dataset.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import vtk
|
| 3 |
+
import os
|
| 4 |
+
import itertools
|
| 5 |
+
import random
|
| 6 |
+
import numpy as np
|
| 7 |
+
from torch_geometric import nn as nng
|
| 8 |
+
from sklearn.neighbors import NearestNeighbors
|
| 9 |
+
from torch_geometric.data import Data, Dataset
|
| 10 |
+
from torch_geometric.utils import k_hop_subgraph, subgraph
|
| 11 |
+
from vtk.util.numpy_support import vtk_to_numpy
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_unstructured_grid_data(file_name):
|
| 15 |
+
reader = vtk.vtkUnstructuredGridReader()
|
| 16 |
+
reader.SetFileName(file_name)
|
| 17 |
+
reader.Update()
|
| 18 |
+
output = reader.GetOutput()
|
| 19 |
+
return output
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def unstructured_grid_data_to_poly_data(unstructured_grid_data):
|
| 23 |
+
filter = vtk.vtkDataSetSurfaceFilter()
|
| 24 |
+
filter.SetInputData(unstructured_grid_data)
|
| 25 |
+
filter.Update()
|
| 26 |
+
poly_data = filter.GetOutput()
|
| 27 |
+
return poly_data, filter
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_sdf(target, boundary):
|
| 31 |
+
nbrs = NearestNeighbors(n_neighbors=1).fit(boundary)
|
| 32 |
+
dists, indices = nbrs.kneighbors(target)
|
| 33 |
+
neis = np.array([boundary[i[0]] for i in indices])
|
| 34 |
+
dirs = (target - neis) / (dists + 1e-8)
|
| 35 |
+
return dists.reshape(-1), dirs
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_normal(unstructured_grid_data):
|
| 39 |
+
poly_data, surface_filter = unstructured_grid_data_to_poly_data(unstructured_grid_data)
|
| 40 |
+
# visualize_poly_data(poly_data, surface_filter)
|
| 41 |
+
# poly_data.GetPointData().SetScalars(None)
|
| 42 |
+
normal_filter = vtk.vtkPolyDataNormals()
|
| 43 |
+
normal_filter.SetInputData(poly_data)
|
| 44 |
+
normal_filter.SetAutoOrientNormals(1)
|
| 45 |
+
normal_filter.SetConsistency(1)
|
| 46 |
+
# normal_filter.SetSplitting(0)
|
| 47 |
+
normal_filter.SetComputeCellNormals(1)
|
| 48 |
+
normal_filter.SetComputePointNormals(0)
|
| 49 |
+
normal_filter.Update()
|
| 50 |
+
'''
|
| 51 |
+
normal_filter.SetComputeCellNormals(0)
|
| 52 |
+
normal_filter.SetComputePointNormals(1)
|
| 53 |
+
normal_filter.Update()
|
| 54 |
+
#visualize_poly_data(poly_data, surface_filter, normal_filter)
|
| 55 |
+
poly_data.GetPointData().SetNormals(normal_filter.GetOutput().GetPointData().GetNormals())
|
| 56 |
+
p2c = vtk.vtkPointDataToCellData()
|
| 57 |
+
p2c.ProcessAllArraysOn()
|
| 58 |
+
p2c.SetInputData(poly_data)
|
| 59 |
+
p2c.Update()
|
| 60 |
+
unstructured_grid_data.GetCellData().SetNormals(p2c.GetOutput().GetCellData().GetNormals())
|
| 61 |
+
#visualize_poly_data(poly_data, surface_filter, p2c)
|
| 62 |
+
'''
|
| 63 |
+
|
| 64 |
+
unstructured_grid_data.GetCellData().SetNormals(normal_filter.GetOutput().GetCellData().GetNormals())
|
| 65 |
+
c2p = vtk.vtkCellDataToPointData()
|
| 66 |
+
# c2p.ProcessAllArraysOn()
|
| 67 |
+
c2p.SetInputData(unstructured_grid_data)
|
| 68 |
+
c2p.Update()
|
| 69 |
+
unstructured_grid_data = c2p.GetOutput()
|
| 70 |
+
# return unstructured_grid_data
|
| 71 |
+
normal = vtk_to_numpy(c2p.GetOutput().GetPointData().GetNormals()).astype(np.double)
|
| 72 |
+
# print(np.max(np.max(np.abs(normal), axis=1)), np.min(np.max(np.abs(normal), axis=1)))
|
| 73 |
+
normal /= (np.max(np.abs(normal), axis=1, keepdims=True) + 1e-8)
|
| 74 |
+
normal /= (np.linalg.norm(normal, axis=1, keepdims=True) + 1e-8)
|
| 75 |
+
if np.isnan(normal).sum() > 0:
|
| 76 |
+
print(np.isnan(normal).sum())
|
| 77 |
+
print("recalculate")
|
| 78 |
+
return get_normal(unstructured_grid_data) # re-calculate
|
| 79 |
+
# print(normal)
|
| 80 |
+
return normal
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def visualize_poly_data(poly_data, surface_filter, normal_filter=None):
|
| 84 |
+
if normal_filter is not None:
|
| 85 |
+
mask = vtk.vtkMaskPoints()
|
| 86 |
+
mask.SetInputData(normal_filter.GetOutput())
|
| 87 |
+
# mask.RandomModeOn()
|
| 88 |
+
mask.Update()
|
| 89 |
+
arrow = vtk.vtkArrowSource()
|
| 90 |
+
arrow.Update()
|
| 91 |
+
glyph = vtk.vtkGlyph3D()
|
| 92 |
+
glyph.SetInputData(mask.GetOutput())
|
| 93 |
+
glyph.SetSourceData(arrow.GetOutput())
|
| 94 |
+
glyph.SetVectorModeToUseNormal()
|
| 95 |
+
glyph.SetScaleFactor(0.1)
|
| 96 |
+
glyph.Update()
|
| 97 |
+
norm_mapper = vtk.vtkPolyDataMapper()
|
| 98 |
+
norm_mapper.SetInputData(normal_filter.GetOutput())
|
| 99 |
+
glyph_mapper = vtk.vtkPolyDataMapper()
|
| 100 |
+
glyph_mapper.SetInputData(glyph.GetOutput())
|
| 101 |
+
norm_actor = vtk.vtkActor()
|
| 102 |
+
norm_actor.SetMapper(norm_mapper)
|
| 103 |
+
glyph_actor = vtk.vtkActor()
|
| 104 |
+
glyph_actor.SetMapper(glyph_mapper)
|
| 105 |
+
glyph_actor.GetProperty().SetColor(1, 0, 0)
|
| 106 |
+
norm_render = vtk.vtkRenderer()
|
| 107 |
+
norm_render.AddActor(norm_actor)
|
| 108 |
+
norm_render.SetBackground(0, 1, 0)
|
| 109 |
+
glyph_render = vtk.vtkRenderer()
|
| 110 |
+
glyph_render.AddActor(glyph_actor)
|
| 111 |
+
glyph_render.AddActor(norm_actor)
|
| 112 |
+
glyph_render.SetBackground(0, 0, 1)
|
| 113 |
+
|
| 114 |
+
scalar_range = poly_data.GetScalarRange()
|
| 115 |
+
|
| 116 |
+
mapper = vtk.vtkDataSetMapper()
|
| 117 |
+
mapper.SetInputConnection(surface_filter.GetOutputPort())
|
| 118 |
+
mapper.SetScalarRange(scalar_range)
|
| 119 |
+
|
| 120 |
+
actor = vtk.vtkActor()
|
| 121 |
+
actor.SetMapper(mapper)
|
| 122 |
+
|
| 123 |
+
renderer = vtk.vtkRenderer()
|
| 124 |
+
renderer.AddActor(actor)
|
| 125 |
+
renderer.SetBackground(1, 1, 1) # Set background to white
|
| 126 |
+
|
| 127 |
+
renderer_window = vtk.vtkRenderWindow()
|
| 128 |
+
renderer_window.AddRenderer(renderer)
|
| 129 |
+
if normal_filter is not None:
|
| 130 |
+
renderer_window.AddRenderer(norm_render)
|
| 131 |
+
renderer_window.AddRenderer(glyph_render)
|
| 132 |
+
renderer_window.Render()
|
| 133 |
+
|
| 134 |
+
interactor = vtk.vtkRenderWindowInteractor()
|
| 135 |
+
interactor.SetRenderWindow(renderer_window)
|
| 136 |
+
interactor.Initialize()
|
| 137 |
+
interactor.Start()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_datalist(root, samples, norm=False, coef_norm=None, savedir=None, preprocessed=False):
|
| 141 |
+
dataset = []
|
| 142 |
+
mean_in, mean_out = 0, 0
|
| 143 |
+
std_in, std_out = 0, 0
|
| 144 |
+
for k, s in enumerate(samples):
|
| 145 |
+
if preprocessed and savedir is not None:
|
| 146 |
+
save_path = os.path.join(savedir, s)
|
| 147 |
+
if not os.path.exists(save_path):
|
| 148 |
+
continue
|
| 149 |
+
init = np.load(os.path.join(save_path, 'x.npy'))
|
| 150 |
+
target = np.load(os.path.join(save_path, 'y.npy'))
|
| 151 |
+
pos = np.load(os.path.join(save_path, 'pos.npy'))
|
| 152 |
+
surf = np.load(os.path.join(save_path, 'surf.npy'))
|
| 153 |
+
edge_index = np.load(os.path.join(save_path, 'edge_index.npy'))
|
| 154 |
+
else:
|
| 155 |
+
file_name_press = os.path.join(root, os.path.join(s, 'quadpress_smpl.vtk'))
|
| 156 |
+
file_name_velo = os.path.join(root, os.path.join(s, 'hexvelo_smpl.vtk'))
|
| 157 |
+
|
| 158 |
+
if not os.path.exists(file_name_press) or not os.path.exists(file_name_velo):
|
| 159 |
+
continue
|
| 160 |
+
|
| 161 |
+
unstructured_grid_data_press = load_unstructured_grid_data(file_name_press)
|
| 162 |
+
unstructured_grid_data_velo = load_unstructured_grid_data(file_name_velo)
|
| 163 |
+
|
| 164 |
+
velo = vtk_to_numpy(unstructured_grid_data_velo.GetPointData().GetVectors())
|
| 165 |
+
press = vtk_to_numpy(unstructured_grid_data_press.GetPointData().GetScalars())
|
| 166 |
+
points_velo = vtk_to_numpy(unstructured_grid_data_velo.GetPoints().GetData())
|
| 167 |
+
points_press = vtk_to_numpy(unstructured_grid_data_press.GetPoints().GetData())
|
| 168 |
+
|
| 169 |
+
edges_press = get_edges(unstructured_grid_data_press, points_press, cell_size=4)
|
| 170 |
+
edges_velo = get_edges(unstructured_grid_data_velo, points_velo, cell_size=8)
|
| 171 |
+
|
| 172 |
+
sdf_velo, normal_velo = get_sdf(points_velo, points_press)
|
| 173 |
+
sdf_press = np.zeros(points_press.shape[0])
|
| 174 |
+
normal_press = get_normal(unstructured_grid_data_press)
|
| 175 |
+
|
| 176 |
+
surface = {tuple(p) for p in points_press}
|
| 177 |
+
exterior_indices = [i for i, p in enumerate(points_velo) if tuple(p) not in surface]
|
| 178 |
+
velo_dict = {tuple(p): velo[i] for i, p in enumerate(points_velo)}
|
| 179 |
+
|
| 180 |
+
pos_ext = points_velo[exterior_indices]
|
| 181 |
+
pos_surf = points_press
|
| 182 |
+
sdf_ext = sdf_velo[exterior_indices]
|
| 183 |
+
sdf_surf = sdf_press
|
| 184 |
+
normal_ext = normal_velo[exterior_indices]
|
| 185 |
+
normal_surf = normal_press
|
| 186 |
+
velo_ext = velo[exterior_indices]
|
| 187 |
+
velo_surf = np.array([velo_dict[tuple(p)] if tuple(p) in velo_dict else np.zeros(3) for p in pos_surf])
|
| 188 |
+
press_ext = np.zeros([len(exterior_indices), 1])
|
| 189 |
+
press_surf = press
|
| 190 |
+
|
| 191 |
+
init_ext = np.c_[pos_ext, sdf_ext, normal_ext]
|
| 192 |
+
init_surf = np.c_[pos_surf, sdf_surf, normal_surf]
|
| 193 |
+
target_ext = np.c_[velo_ext, press_ext]
|
| 194 |
+
target_surf = np.c_[velo_surf, press_surf]
|
| 195 |
+
|
| 196 |
+
surf = np.concatenate([np.zeros(len(pos_ext)), np.ones(len(pos_surf))])
|
| 197 |
+
pos = np.concatenate([pos_ext, pos_surf])
|
| 198 |
+
init = np.concatenate([init_ext, init_surf])
|
| 199 |
+
target = np.concatenate([target_ext, target_surf])
|
| 200 |
+
edge_index = get_edge_index(pos, edges_press, edges_velo)
|
| 201 |
+
|
| 202 |
+
if savedir is not None:
|
| 203 |
+
save_path = os.path.join(savedir, s)
|
| 204 |
+
if not os.path.exists(save_path):
|
| 205 |
+
os.makedirs(save_path)
|
| 206 |
+
np.save(os.path.join(save_path, 'x.npy'), init)
|
| 207 |
+
np.save(os.path.join(save_path, 'y.npy'), target)
|
| 208 |
+
np.save(os.path.join(save_path, 'pos.npy'), pos)
|
| 209 |
+
np.save(os.path.join(save_path, 'surf.npy'), surf)
|
| 210 |
+
np.save(os.path.join(save_path, 'edge_index.npy'), edge_index)
|
| 211 |
+
|
| 212 |
+
surf = torch.tensor(surf)
|
| 213 |
+
pos = torch.tensor(pos)
|
| 214 |
+
x = torch.tensor(init)
|
| 215 |
+
y = torch.tensor(target)
|
| 216 |
+
edge_index = torch.tensor(edge_index)
|
| 217 |
+
|
| 218 |
+
if norm and coef_norm is None:
|
| 219 |
+
if k == 0:
|
| 220 |
+
old_length = init.shape[0]
|
| 221 |
+
mean_in = init.mean(axis=0)
|
| 222 |
+
mean_out = target.mean(axis=0)
|
| 223 |
+
else:
|
| 224 |
+
new_length = old_length + init.shape[0]
|
| 225 |
+
mean_in += (init.sum(axis=0) - init.shape[0] * mean_in) / new_length
|
| 226 |
+
mean_out += (target.sum(axis=0) - init.shape[0] * mean_out) / new_length
|
| 227 |
+
old_length = new_length
|
| 228 |
+
data = Data(pos=pos, x=x, y=y, surf=surf.bool(), edge_index=edge_index)
|
| 229 |
+
# data = Data(pos=pos, x=x, y=y, surf=surf.bool())
|
| 230 |
+
dataset.append(data)
|
| 231 |
+
|
| 232 |
+
if norm and coef_norm is None:
|
| 233 |
+
for k, data in enumerate(dataset):
|
| 234 |
+
if k == 0:
|
| 235 |
+
old_length = data.x.numpy().shape[0]
|
| 236 |
+
std_in = ((data.x.numpy() - mean_in) ** 2).sum(axis=0) / old_length
|
| 237 |
+
std_out = ((data.y.numpy() - mean_out) ** 2).sum(axis=0) / old_length
|
| 238 |
+
else:
|
| 239 |
+
new_length = old_length + data.x.numpy().shape[0]
|
| 240 |
+
std_in += (((data.x.numpy() - mean_in) ** 2).sum(axis=0) - data.x.numpy().shape[
|
| 241 |
+
0] * std_in) / new_length
|
| 242 |
+
std_out += (((data.y.numpy() - mean_out) ** 2).sum(axis=0) - data.x.numpy().shape[
|
| 243 |
+
0] * std_out) / new_length
|
| 244 |
+
old_length = new_length
|
| 245 |
+
|
| 246 |
+
std_in = np.sqrt(std_in)
|
| 247 |
+
std_out = np.sqrt(std_out)
|
| 248 |
+
|
| 249 |
+
for data in dataset:
|
| 250 |
+
data.x = ((data.x - mean_in) / (std_in + 1e-8)).float()
|
| 251 |
+
data.y = ((data.y - mean_out) / (std_out + 1e-8)).float()
|
| 252 |
+
|
| 253 |
+
coef_norm = (mean_in, std_in, mean_out, std_out)
|
| 254 |
+
dataset = (dataset, coef_norm)
|
| 255 |
+
|
| 256 |
+
elif coef_norm is not None:
|
| 257 |
+
for data in dataset:
|
| 258 |
+
data.x = ((data.x - coef_norm[0]) / (coef_norm[1] + 1e-8)).float()
|
| 259 |
+
data.y = ((data.y - coef_norm[2]) / (coef_norm[3] + 1e-8)).float()
|
| 260 |
+
|
| 261 |
+
return dataset
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def get_edges(unstructured_grid_data, points, cell_size=4):
|
| 265 |
+
edge_indeces = set()
|
| 266 |
+
cells = vtk_to_numpy(unstructured_grid_data.GetCells().GetData()).reshape(-1, cell_size + 1)
|
| 267 |
+
for i in range(len(cells)):
|
| 268 |
+
for j, k in itertools.product(range(1, cell_size + 1), repeat=2):
|
| 269 |
+
edge_indeces.add((cells[i][j], cells[i][k]))
|
| 270 |
+
edge_indeces.add((cells[i][k], cells[i][j]))
|
| 271 |
+
edges = [[], []]
|
| 272 |
+
for u, v in edge_indeces:
|
| 273 |
+
edges[0].append(tuple(points[u]))
|
| 274 |
+
edges[1].append(tuple(points[v]))
|
| 275 |
+
return edges
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def get_edge_index(pos, edges_press, edges_velo):
|
| 279 |
+
indices = {tuple(pos[i]): i for i in range(len(pos))}
|
| 280 |
+
edges = set()
|
| 281 |
+
for i in range(len(edges_press[0])):
|
| 282 |
+
edges.add((indices[edges_press[0][i]], indices[edges_press[1][i]]))
|
| 283 |
+
for i in range(len(edges_velo[0])):
|
| 284 |
+
edges.add((indices[edges_velo[0][i]], indices[edges_velo[1][i]]))
|
| 285 |
+
edge_index = np.array(list(edges)).T
|
| 286 |
+
return edge_index
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def get_induced_graph(data, idx, num_hops):
|
| 290 |
+
subset, sub_edge_index, _, _ = k_hop_subgraph(node_idx=idx, num_hops=num_hops, edge_index=data.edge_index,
|
| 291 |
+
relabel_nodes=True)
|
| 292 |
+
return Data(x=data.x[subset], y=data.y[idx], edge_index=sub_edge_index)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def pc_normalize(pc):
|
| 296 |
+
centroid = torch.mean(pc, axis=0)
|
| 297 |
+
pc = pc - centroid
|
| 298 |
+
m = torch.max(torch.sqrt(torch.sum(pc ** 2, axis=1)))
|
| 299 |
+
pc = pc / m
|
| 300 |
+
return pc
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def get_shape(data, max_n_point=8192, normalize=True, use_height=False):
|
| 304 |
+
surf_indices = torch.where(data.surf)[0].tolist()
|
| 305 |
+
|
| 306 |
+
if len(surf_indices) > max_n_point:
|
| 307 |
+
surf_indices = np.array(random.sample(range(len(surf_indices)), max_n_point))
|
| 308 |
+
|
| 309 |
+
shape_pc = data.pos[surf_indices].clone()
|
| 310 |
+
|
| 311 |
+
if normalize:
|
| 312 |
+
shape_pc = pc_normalize(shape_pc)
|
| 313 |
+
|
| 314 |
+
if use_height:
|
| 315 |
+
gravity_dim = 1
|
| 316 |
+
height_array = shape_pc[:, gravity_dim:gravity_dim + 1] - shape_pc[:, gravity_dim:gravity_dim + 1].min()
|
| 317 |
+
shape_pc = torch.cat((shape_pc, height_array), axis=1)
|
| 318 |
+
|
| 319 |
+
return shape_pc
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def create_edge_index_radius(data, r, max_neighbors=32):
|
| 323 |
+
data.edge_index = nng.radius_graph(x=data.pos, r=r, loop=True, max_num_neighbors=max_neighbors)
|
| 324 |
+
# print(f'r = {r}, #edges = {data.edge_index.size(1)}')
|
| 325 |
+
return data
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class GraphDataset(Dataset):
|
| 329 |
+
def __init__(self, datalist, use_height=False, use_cfd_mesh=True, r=None):
|
| 330 |
+
super().__init__()
|
| 331 |
+
self.datalist = datalist
|
| 332 |
+
self.use_height = use_height
|
| 333 |
+
if not use_cfd_mesh:
|
| 334 |
+
assert r is not None
|
| 335 |
+
for i in range(len(self.datalist)):
|
| 336 |
+
self.datalist[i] = create_edge_index_radius(self.datalist[i], r)
|
| 337 |
+
|
| 338 |
+
def len(self):
|
| 339 |
+
return len(self.datalist)
|
| 340 |
+
|
| 341 |
+
def get(self, idx):
|
| 342 |
+
data = self.datalist[idx]
|
| 343 |
+
shape = get_shape(data, use_height=self.use_height)
|
| 344 |
+
return self.datalist[idx], shape
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
if __name__ == '__main__':
|
| 348 |
+
import numpy as np
|
| 349 |
+
|
| 350 |
+
file_name = '1a0bc9ab92c915167ae33d942430658c'
|
| 351 |
+
|
| 352 |
+
root = '/data/PDE_data/mlcfd_data/training_data'
|
| 353 |
+
save_path = '/data/PDE_data/mlcfd_data/preprocessed_data/param0/' + file_name
|
| 354 |
+
file_name_press = 'param0/' + file_name + '/quadpress_smpl.vtk'
|
| 355 |
+
file_name_velo = 'param0/' + file_name + '/hexvelo_smpl.vtk'
|
| 356 |
+
file_name_press = os.path.join(root, file_name_press)
|
| 357 |
+
file_name_velo = os.path.join(root, file_name_velo)
|
| 358 |
+
unstructured_grid_data_press = load_unstructured_grid_data(file_name_press)
|
| 359 |
+
unstructured_grid_data_velo = load_unstructured_grid_data(file_name_velo)
|
| 360 |
+
|
| 361 |
+
velo = vtk_to_numpy(unstructured_grid_data_velo.GetPointData().GetVectors())
|
| 362 |
+
press = vtk_to_numpy(unstructured_grid_data_press.GetPointData().GetScalars())
|
| 363 |
+
points_velo = vtk_to_numpy(unstructured_grid_data_velo.GetPoints().GetData())
|
| 364 |
+
points_press = vtk_to_numpy(unstructured_grid_data_press.GetPoints().GetData())
|
| 365 |
+
|
| 366 |
+
edges_press = get_edges(unstructured_grid_data_press, points_press, cell_size=4)
|
| 367 |
+
edges_velo = get_edges(unstructured_grid_data_velo, points_velo, cell_size=8)
|
| 368 |
+
|
| 369 |
+
sdf_velo, normal_velo = get_sdf(points_velo, points_press)
|
| 370 |
+
sdf_press = np.zeros(points_press.shape[0])
|
| 371 |
+
normal_press = get_normal(unstructured_grid_data_press)
|
| 372 |
+
|
| 373 |
+
surface = {tuple(p) for p in points_press}
|
| 374 |
+
exterior_indices = [i for i, p in enumerate(points_velo) if tuple(p) not in surface]
|
| 375 |
+
velo_dict = {tuple(p): velo[i] for i, p in enumerate(points_velo)}
|
| 376 |
+
|
| 377 |
+
pos_ext = points_velo[exterior_indices]
|
| 378 |
+
pos_surf = points_press
|
| 379 |
+
sdf_ext = sdf_velo[exterior_indices]
|
| 380 |
+
sdf_surf = sdf_press
|
| 381 |
+
normal_ext = normal_velo[exterior_indices]
|
| 382 |
+
normal_surf = normal_press
|
| 383 |
+
velo_ext = velo[exterior_indices]
|
| 384 |
+
velo_surf = np.array([velo_dict[tuple(p)] if tuple(p) in velo_dict else np.zeros(3) for p in pos_surf])
|
| 385 |
+
press_ext = np.zeros([len(exterior_indices), 1])
|
| 386 |
+
press_surf = press
|
| 387 |
+
|
| 388 |
+
init_ext = np.c_[pos_ext, sdf_ext, normal_ext]
|
| 389 |
+
init_surf = np.c_[pos_surf, sdf_surf, normal_surf]
|
| 390 |
+
target_ext = np.c_[velo_ext, press_ext]
|
| 391 |
+
target_surf = np.c_[velo_surf, press_surf]
|
| 392 |
+
|
| 393 |
+
surf = np.concatenate([np.zeros(len(pos_ext)), np.ones(len(pos_surf))])
|
| 394 |
+
pos = np.concatenate([pos_ext, pos_surf])
|
| 395 |
+
init = np.concatenate([init_ext, init_surf])
|
| 396 |
+
target = np.concatenate([target_ext, target_surf])
|
| 397 |
+
|
| 398 |
+
edge_index = get_edge_index(pos, edges_press, edges_velo)
|
| 399 |
+
|
| 400 |
+
data = Data(pos=torch.tensor(pos), edge_index=torch.tensor(edge_index))
|
| 401 |
+
data = create_edge_index_radius(data, r=0.2)
|
| 402 |
+
x, y = data.edge_index
|
| 403 |
+
import torch_geometric
|
| 404 |
+
|
| 405 |
+
print(max(torch_geometric.utils.degree(x)), max(torch_geometric.utils.degree(y)))
|
| 406 |
+
|
| 407 |
+
print(points_velo.shape, points_press.shape)
|
| 408 |
+
print(surf.shape, pos.shape, init.shape, target.shape, edge_index.shape)
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/dataset/load_dataset.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataset.dataset import get_datalist
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_samples(root):
|
| 6 |
+
folds = [f'param{i}' for i in range(9)]
|
| 7 |
+
samples = []
|
| 8 |
+
for fold in folds:
|
| 9 |
+
fold_samples = []
|
| 10 |
+
files = os.listdir(os.path.join(root, fold))
|
| 11 |
+
for file in files:
|
| 12 |
+
path = os.path.join(root, os.path.join(fold, file))
|
| 13 |
+
if os.path.isdir(path):
|
| 14 |
+
fold_samples.append(os.path.join(fold, file))
|
| 15 |
+
samples.append(fold_samples)
|
| 16 |
+
return samples # 100 + 99 + 97 + 100 + 100 + 96 + 100 + 98 + 99 = 889 samples
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def load_train_val_fold(args, preprocessed):
|
| 20 |
+
samples = get_samples(args.data_dir)
|
| 21 |
+
trainlst = []
|
| 22 |
+
for i in range(len(samples)):
|
| 23 |
+
if i == args.fold_id:
|
| 24 |
+
continue
|
| 25 |
+
trainlst += samples[i]
|
| 26 |
+
vallst = samples[args.fold_id] if 0 <= args.fold_id < len(samples) else None
|
| 27 |
+
|
| 28 |
+
if preprocessed:
|
| 29 |
+
print("use preprocessed data")
|
| 30 |
+
print("loading data")
|
| 31 |
+
train_dataset, coef_norm = get_datalist(args.data_dir, trainlst, norm=True, savedir=args.save_dir,
|
| 32 |
+
preprocessed=preprocessed)
|
| 33 |
+
val_dataset = get_datalist(args.data_dir, vallst, coef_norm=coef_norm, savedir=args.save_dir,
|
| 34 |
+
preprocessed=preprocessed)
|
| 35 |
+
print("load data finish")
|
| 36 |
+
return train_dataset, val_dataset, coef_norm
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_train_val_fold_file(args, preprocessed):
|
| 40 |
+
samples = get_samples(args.data_dir)
|
| 41 |
+
trainlst = []
|
| 42 |
+
for i in range(len(samples)):
|
| 43 |
+
if i == args.fold_id:
|
| 44 |
+
continue
|
| 45 |
+
trainlst += samples[i]
|
| 46 |
+
vallst = samples[args.fold_id] if 0 <= args.fold_id < len(samples) else None
|
| 47 |
+
|
| 48 |
+
if preprocessed:
|
| 49 |
+
print("use preprocessed data")
|
| 50 |
+
print("loading data")
|
| 51 |
+
train_dataset, coef_norm = get_datalist(args.data_dir, trainlst, norm=True, savedir=args.save_dir,
|
| 52 |
+
preprocessed=preprocessed)
|
| 53 |
+
val_dataset = get_datalist(args.data_dir, vallst, coef_norm=coef_norm, savedir=args.save_dir,
|
| 54 |
+
preprocessed=preprocessed)
|
| 55 |
+
print("load data finish")
|
| 56 |
+
return train_dataset, val_dataset, coef_norm, vallst
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/car_slice_surf.png
ADDED
|
Git LFS Details
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/case_study.png
ADDED
|
Git LFS Details
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/results.png
ADDED
|
Git LFS Details
|
code/ezflow_v3/baselines/Transolver-main/Car-Design-ShapeNetCar/fig/task.png
ADDED
|
Git LFS Details
|