Model-only repository: weights, config.json and model card; code lives on GitHub
Browse filesFiles changed (47)
- .gitattributes+2
- .gitignoreDeleted-10
- README.md+31-33
- config.jsonAdded+38
- data/properties/README.mdDeleted-25
- data/properties/materials.csvDeleted-3
- data/properties/molds.csvDeleted-2
- weights/gbm_std_v2.skops → gbm_std_v2.skopsRenamed
- weights/gbm_total_v3.skops → gbm_total_v3.skopsRenamed
- weights/gnn_v5.1.safetensors → gnn_v5.1.safetensorsRenamed
- weights/ood_ranges.json → ood_ranges.jsonRenamed
- requirements.txtDeleted-20
- src/features.pyDeleted-109
- src/gbm_heads.pyDeleted-69
- src/geometry.pyDeleted-128
- src/hybrid.pyDeleted-287
- src/inference_props.pyDeleted-170
- src/mesh_cache.pyDeleted-128
- src/meshing.pyDeleted-368
- src/model_api.pyDeleted-80
- src/model_gnn.pyDeleted-136
- src/msh_parse.pyDeleted-67
- src/ood.pyDeleted-23
- src/predict_casting.pyDeleted-283
- src/release_io.pyDeleted-47
- src/shrinkage.pyDeleted-498
- src/viz.pyDeleted-90
- src/webapp.pyDeleted-561
- tests/__init__.pyDeleted
- tests/conftest.pyDeleted-49
- tests/test_features.pyDeleted-55
- tests/test_gbm_heads.pyDeleted-55
- tests/test_geometry.pyDeleted-36
- tests/test_hybrid.pyDeleted-336
- tests/test_hybrid_max_anchor.pyDeleted-86
- tests/test_inference_props.pyDeleted-102
- tests/test_local_modulus.pyDeleted-63
- tests/test_mesh_cache.pyDeleted-176
- tests/test_meshing.pyDeleted-443
- tests/test_model_api.pyDeleted-25
- tests/test_model_gnn.pyDeleted-66
- tests/test_msh_parse.pyDeleted-22
- tests/test_ood.pyDeleted-19
- tests/test_predict_casting.pyDeleted-106
- tests/test_release_io.pyDeleted-55
- tests/test_shrinkage.pyDeleted-1186
- weights/SHA256SUMSDeleted-4
37 unmodified lines38394037 unmodified linesassets/solidification.gif filter=lfs diff=lfs merge=lfs -textweights/gbm_std_v2.skops filter=lfs diff=lfs merge=lfs -textweights/gbm_total_v3.skops filter=lfs diff=lfs merge=lfs -text37 unmodified lines383940414237 unmodified linesassets/solidification.gif filter=lfs diff=lfs merge=lfs -textweights/gbm_std_v2.skops filter=lfs diff=lfs merge=lfs -textweights/gbm_total_v3.skops filter=lfs diff=lfs merge=lfs -textgbm_std_v2.skops filter=lfs diff=lfs merge=lfs -textgbm_total_v3.skops filter=lfs diff=lfs merge=lfs -text
12345678910# Data stays out of the repository except the property tables.data/*!data/properties/!data/properties/*# Prediction output and the mesh cacheruns/# Python__pycache__/*.pyc.pytest_cache/50 unmodified lines5152535455565713 unmodified lines7172737475767778798081828384858687888990919293949596977 unmodified lines1051061071081091101111 unmodified line11311411511611711811912012112212312412512612712812913013113278 unmodified lines21121221321421521621721821922022122222322422522622722822923023196 unmodified lines32832933033133233333411 unmodified lines3463473483493503513522 unmodified lines35535635735835936036150 unmodified lines| Parameters | about 1.85 M (GNN) plus two `HistGradientBoostingRegressor` heads || Training data | FEniCSx enthalpy-method conduction simulations: about 9.7k primitive cases, 4.7k multi-alloy cases, 500 real-part cases || License | Apache-2.0 for code and weights || Pipeline | STEP import, meshing and result export are documented on [GitHub](https://github.com/eugenmik/castsolid-gnn) || Author | Eugen Miknevic, independent foundry engineer |## Contents13 unmodified linesThe model reads one casting at a time.**Mesh.** A tetrahedral volume mesh in millimetres, in gmsh 2.2 ASCII format (`.msh`). Surfacetriangles that cool into the mold belong to a physical group named `Cooling`; in this releasethat is the whole outer surface. The model was trained on meshes of roughly 7,500 to 10,000nodes, and that is the density it should be given. It does not use node numbering or absolutecoordinates: node inputs are distances, flags and volume-type quantities in millimetres, andedges carry only relative displacements between neighbouring nodes.**Alloy and mold.** Eight numbers describe the material and the mold: thermal conductivity,density, specific heat, latent heat, liquidus, solidus, pouring temperature and mold effusivity.Two alloys are tabulated in `data/properties/`, `EN-GJS-400-15` (ductile iron, the default) and`G20Mn5` (cast steel), together with one mold, green sand. You can also pass your own eightvalues.**Output.** One number per node: the time in seconds at which that node cools through thesolidus. The maximum over all nodes is the total solidification time, and the 10% of nodes withthe largest times are the hot spots.## How to use```bashhf download eugenmik/castsolid-gnn --local-dir castsolid-gnncd castsolid-gnnpython -m venv .venv && source .venv/bin/activatepip install "torch==2.3.0" --index-url https://download.pytorch.org/whl/cpu7 unmodified lines```pythonfrom src.model_api import CastSolidModelmodel = CastSolidModel() # loads the three weight files oncet = model.predict("part.msh") # EN-GJS-400-15 in green sandt_steel = model.predict("part.msh", alloy="G20Mn5")1 unmodified linehot = CastSolidModel.hotspots(t) # boolean mask, top 10% of nodes````predict` returns a NumPy array in the node order of the `.msh` file. To use another alloy,pass `props_json="my_alloy.json"` with exactly these keys (SI units, temperatures in °C;1018 is the green-sand effusivity):```json{"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0,"TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1018.0}```If you start from a STEP file, the[GitHub repository](https://github.com/eugenmik/castsolid-gnn) has the pipeline that heals theCAD, builds a mesh at the right density, runs this model and writes the result for ParaView.The same code is included here, so `python -m src.predict_casting part.step` works in thisrepository too.## Model architecture78 unmodified lines| File | Size | Content ||---|---:|---|| `weights/gnn_v5.1.safetensors` | 7.4 MB | GNN weights, feature and target normalization, and the architecture config (in the safetensors metadata) || `weights/gbm_total_v3.skops` | 0.6 MB | Total-time head || `weights/gbm_std_v2.skops` | 0.8 MB | Spread head || `weights/ood_ranges.json` | <1 KB | Training envelope (part volume, size, distance to cooling) for out-of-distribution warnings || `weights/SHA256SUMS` | <1 KB | Checksums || `src/model_api.py` | | `CastSolidModel`, the mesh-in, field-out interface shown above || `src/features.py`, `src/model_gnn.py`, `src/gbm_heads.py`, `src/hybrid.py` | | The model: node features, graph network, gradient-boosted heads, recomposition || `data/properties/` | | Alloy and mold tables ([README](data/properties/README.md)) |None of the weight files can execute code when loaded. The GNN is stored as[safetensors](https://github.com/huggingface/safetensors) and the heads as[skops](https://skops.readthedocs.io/); before loading a skops file, `src/release_io.py` checksevery type it names against an allowlist of scikit-learn and NumPy types. The rest of `src/`(meshing a STEP file, shrinkage screening, result export, a browser viewer) and `tests/` are thesupporting pipeline, described on GitHub. Training code is not part of this release.## Training data96 unmodified lines3. Meshes much coarser or finer than the training density (about 7,500 to 10,000 nodes) areoutside what the model has seen. At that density, large thin-walled parts can beunder-resolved.4. The training envelope in `weights/ood_ranges.json` only covers part size and distance tocooling. It is not a calibrated uncertainty estimate.Treat each prediction as a screening hypothesis: where should an engineer look first, and is11 unmodified lines| `gbm_total_v3.skops` | `hgb_v3.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range || `gbm_std_v2.skops` | `hgb_std_v2.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range |The code in this repository was also run side by side with the internal pipeline on fiveproduction parts (two of them with both alloys), plus a fixed-size mesh with a custom propertyset: every output field matched exactly. The heads were trained with scikit-learn 1.5.2, and other versions may refuse to load them or changetheir output. Other versions used: Python 3.11, PyTorch 2.3.0, PyTorch Geometric 2.7.0,2 unmodified lines## License and citationCode and weights are released under the [Apache License 2.0](LICENSE). The tables in`data/properties/` are modelling inputs, not certified material specifications.```bibtex@software{miknevic_casting_gnn_2026,50 unmodified lines5152535455565713 unmodified lines71727374757677787980818283848586878889909192939495969798997 unmodified lines1071081091101111121131 unmodified line11511611711811912012112212312412512612712812913013113213378 unmodified lines21221321421521621721821922022122222322422522622722896 unmodified lines32532632732832933033111 unmodified lines3433443453463473483492 unmodified lines35235335435535635735835950 unmodified lines| Parameters | about 1.85 M (GNN) plus two `HistGradientBoostingRegressor` heads || Training data | FEniCSx enthalpy-method conduction simulations: about 9.7k primitive cases, 4.7k multi-alloy cases, 500 real-part cases || License | Apache-2.0 for code and weights || Code | [github.com/eugenmik/castsolid-gnn](https://github.com/eugenmik/castsolid-gnn): loading, inference, and the STEP-to-result pipeline || Author | Eugen Miknevic, independent foundry engineer |## Contents13 unmodified linesThe model reads one casting at a time.The mesh is a tetrahedral volume mesh in millimetres, in gmsh 2.2 ASCII format (`.msh`). Surfacetriangles that cool into the mold belong to a physical group named `Cooling`; in this releasethat is the whole outer surface. The model was trained on meshes of roughly 7,500 to 10,000nodes, and that is the density it should be given. It does not use node numbering or absolutecoordinates: node inputs are distances, flags and volume-type quantities in millimetres, andedges carry only relative displacements between neighbouring nodes.Eight numbers describe the alloy and the mold: thermal conductivity, density, specific heat,latent heat, liquidus, solidus, pouring temperature and mold effusivity. The code ships twotabulated alloys, `EN-GJS-400-15` (ductile iron, the default) and `G20Mn5` (cast steel), and onemold, green sand. You can also pass your own eight values.The output is one number per node: the time in seconds at which that node cools through thesolidus. The maximum over all nodes is the total solidification time, and the 10% of nodes withthe largest times are the hot spots.## How to useThis repository holds the weights and this card. The code that loads and runs them is on[GitHub](https://github.com/eugenmik/castsolid-gnn):```bashgit clone https://github.com/eugenmik/castsolid-gnncd castsolid-gnnpython -m venv .venv && source .venv/bin/activatepip install "torch==2.3.0" --index-url https://download.pytorch.org/whl/cpu7 unmodified lines```pythonfrom src.model_api import CastSolidModelmodel = CastSolidModel.from_pretrained() # downloads this repository's files oncet = model.predict("part.msh") # EN-GJS-400-15 in green sandt_steel = model.predict("part.msh", alloy="G20Mn5")1 unmodified linehot = CastSolidModel.hotspots(t) # boolean mask, top 10% of nodes````from_pretrained()` fetches `config.json` and the files it lists into the local Hugging Facecache, pinned to the `v5.1` tag; later calls run offline. `predict` returns a NumPy array in thenode order of the `.msh` file. To use another alloy, pass `props_json="my_alloy.json"` withexactly these keys (SI units, temperatures in °C; 1018 is the green-sand effusivity):```json{"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0,"TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1018.0}```To start from a STEP file instead of a mesh, run `python -m src.predict_casting part.step` inthe GitHub repository. It heals the CAD, builds a mesh at the right density, runs the model andwrites the result for ParaView.## Model architecture78 unmodified lines| File | Size | Content ||---|---:|---|| `config.json` | 1 KB | Model version, file list, architecture summary, recomposition weights and input description || `gnn_v5.1.safetensors` | 7.4 MB | GNN weights, feature and target normalization, and the architecture config (in the safetensors metadata) || `gbm_total_v3.skops` | 0.6 MB | Total-time head || `gbm_std_v2.skops` | 0.8 MB | Spread head || `ood_ranges.json` | <1 KB | Training envelope (part volume, size, distance to cooling) used for out-of-distribution warnings |None of the weight files can execute code when loaded. The GNN is stored as[safetensors](https://github.com/huggingface/safetensors) and the heads as[skops](https://skops.readthedocs.io/). Before it opens a skops file, the loader on GitHub checksevery type the file names against an allowlist of scikit-learn and NumPy types. Training code isnot published.## Training data96 unmodified lines3. Meshes much coarser or finer than the training density (about 7,500 to 10,000 nodes) areoutside what the model has seen. At that density, large thin-walled parts can beunder-resolved.4. The training envelope in `ood_ranges.json` only covers part size and distance tocooling. It is not a calibrated uncertainty estimate.Treat each prediction as a screening hypothesis: where should an engineer look first, and is11 unmodified lines| `gbm_total_v3.skops` | `hgb_v3.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range || `gbm_std_v2.skops` | `hgb_std_v2.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range |The published inference code was also run side by side with the internal pipeline on fiveproduction parts (two of them with both alloys), plus a fixed-size mesh with a custom propertyset: every output field matched exactly. The heads were trained with scikit-learn 1.5.2, and other versions may refuse to load them or changetheir output. Other versions used: Python 3.11, PyTorch 2.3.0, PyTorch Geometric 2.7.0,2 unmodified lines## License and citationCode and weights are released under the [Apache License 2.0](LICENSE). The tables in`data/properties/` of the GitHub repository are modelling inputs, not certified materialspecifications.```bibtex@software{miknevic_casting_gnn_2026,
1234567891011121314151617181920212223242526272829303132333435363738{ "model_type": "casting-solidification-gnn", "version": "v5.1", "code": "https://github.com/eugenmik/castsolid-gnn", "files": { "gnn": "gnn_v5.1.safetensors", "total_head": "gbm_total_v3.skops", "spread_head": "gbm_std_v2.skops", "ood_ranges": "ood_ranges.json" }, "gnn": { "architecture": "MeshGraphNet-style encode-process-decode with FiLM conditioning", "node_features": 15, "edge_features": 5, "conditioning_features": 5, "hidden": 128, "message_passing_blocks": 12, "knn_neighbours": 16, "graph": "tetrahedral mesh edges union k-nearest neighbours" }, "heads": { "total_head_features": 16, "spread_head_features": 17, "sklearn_version": "1.5.2" }, "recomposition": { "method": "soft_anchor", "quantile": 0.995, "w_total": 1.0, "w_std": 4.0 }, "input": { "mesh": "gmsh 2.2 ASCII tetrahedral mesh in mm, cooling surface tagged 'Cooling'", "mesh_nodes_trained": [7500, 10000], "properties": ["k", "rho", "cp", "L_kJ_kg", "TL", "TS", "Tpour", "mold_effusivity"] }, "output": "solidification time in seconds per mesh node"}12345678910111213141516171819202122232425# Property tables
These two CSV files hold the material and mold rows that inference reads.
- `materials.csv` has two grades: `EN-GJS-400-15` (ductile iron, the default) and `G20Mn5` (cast steel). Columns: thermal conductivity `k_W_mK`, density `rho_kg_m3`, specific heat `cp_J_kgK`, latent heat `L_kJ_kg`, liquidus `TL_C`, solidus `TS_C` and the pouring temperature range `Tpour_lo_C`/`Tpour_hi_C`. The prediction uses the midpoint of that range.- `molds.csv` has one mold system, `green_sand`. The model reads its thermal effusivity (`effusivity_W_s05_m2K`), which is the square root of the product of the conductivity, density and specific heat in the same row.
The values come from handbook data. They are modelling inputs, not certified materialspecifications. Check them against your actual alloy and process, and keep the exact row youused with every result.
To try an alloy that is not listed, pass the properties directly instead of editing the table:
```bashpython -m src.predict_casting part.step --props my_alloy.json```
`my_alloy.json` needs exactly these keys: `k`, `rho`, `cp`, `L_kJ_kg`, `TL`, `TS`, `Tpour`,`mold_effusivity`. The model was trained on iron and steel grades in sand molds; properties farfrom that range are extrapolation.123material_id,family,k_W_mK,rho_kg_m3,cp_J_kgK,L_kJ_kg,TL_C,TS_C,Tpour_lo_C,Tpour_hi_CEN-GJS-400-15,ductile_iron,32.9,6800,515,220,1160,1120,1250,1270G20Mn5,low_alloy_steel,48.4,7800,590,260,1530,1495,1620,164012mold_system,k_W_mK,rho_kg_m3,cp_J_kgK,effusivity_W_s05_m2Kgreen_sand,0.607,1520,1123,10181234567891011121314151617181920# Install PyTorch 2.3 for your platform first, plus the matching torch-cluster# wheel, for example on CPU:# pip install "torch==2.3.0" --index-url https://download.pytorch.org/whl/cpu# pip install torch-cluster -f https://data.pyg.org/whl/torch-2.3.0+cpu.htmlnumpy>=2.0scipy>=1.11scikit-learn==1.5.2skops>=0.10safetensors>=0.4torch-geometric==2.7.0gmsh>=4.13meshio>=5.3pytest>=8.3# Optional: local browser viewer (python -m src.webapp)pyvista>=0.44trame>=3.6trame-vtk>=2.8trame-vuetify>=2.7trame-pyvista>=0.1imageio>=2.34123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Node features and the alloy/mold conditioning vector.
Every feature comes from the mesh and its surface tags ("Cooling", optionally"Adiabatic"), in millimetres. Nothing depends on node numbering, file names orabsolute position."""import numpy as np
from src.geometry import (total_area, mesh_volume, nearest_distance, boundary_node_mask, edges_from_tets, geodesic_distance, local_modulus)
FEATURE_NAMES = [ "geodesic_d_cool", "d_surf", "d_adiab", "is_cooling", "is_adiabatic", "is_interior", "volume_mm3", "surface_area_mm2", "cooling_area_frac", "geodesic_d_adiab", "local_modulus_r5", "local_modulus_r15", "local_modulus_r40", "boundary_extraction", "boundary_heat_input",]LOCAL_MODULUS_RADII = (5.0, 15.0, 40.0)
# Alloy/mold conditioning vector (raw, not standardized).G_VECTOR_NAMES = ["Ste", "dTf_norm", "alpha_ratio", "superheat_norm", "mold_eff_norm"]T_REF = 1000.0 # deg C, normalizes temperature differencesALPHA_REF = 1e-5 # m^2/s, typical alloy thermal diffusivityMOLD_EFF_REF = 1250.0 # W*s^0.5/(m^2*K), reference mold effusivity
def alloy_g_vector(props: dict) -> np.ndarray: """Five dimensionless numbers describing alloy and mold.
`props` keys: k, rho, cp, L_kJ_kg, TL, TS, Tpour, mold_effusivity.""" k = float(props["k"]); rho = float(props["rho"]); cp = float(props["cp"]) L = float(props["L_kJ_kg"]); TL = float(props["TL"]); TS = float(props["TS"]) Tpour = float(props["Tpour"]); b_mold = float(props["mold_effusivity"])
Ste = cp * (Tpour - TS) / (L * 1000.0) dTf_norm = (TL - TS) / T_REF alpha_ratio = (k / (rho * cp)) / ALPHA_REF superheat_norm = (Tpour - TL) / T_REF mold_eff_norm = b_mold / MOLD_EFF_REF return np.array([Ste, dTf_norm, alpha_ratio, superheat_norm, mold_eff_norm], dtype=np.float64)
def node_features(mesh, mold_effusivity: float) -> dict: """The (N, 15) float32 feature matrix `X`, node positions `pos` (mm) and the unique tetrahedral mesh edges `mesh_edges` for one casting.""" xyz = mesh.node_xyz N = xyz.shape[0] cool_tri = mesh.tris.get("Cooling", np.empty((0, 3), np.int64)) adiab_tri = mesh.tris.get("Adiabatic", np.empty((0, 3), np.int64))
cool_mask = boundary_node_mask(N, cool_tri) adiab_mask = boundary_node_mask(N, adiab_tri) adiab_only = adiab_mask & ~cool_mask surf_mask = cool_mask | adiab_mask interior_mask = ~surf_mask
bbox = xyz.max(0) - xyz.min(0) bbox_diag = float(np.linalg.norm(bbox))
edges = edges_from_tets(mesh.tets) edge_len = np.linalg.norm(xyz[edges[:, 0]] - xyz[edges[:, 1]], axis=1) if edges.shape[0] else np.empty(0) src = np.flatnonzero(cool_mask) g_cool = geodesic_distance(N, edges, edge_len, src) eucl_cool = nearest_distance(xyz, xyz[cool_mask]) eucl_cool = np.where(np.isinf(eucl_cool), bbox_diag, eucl_cool) g_cool = np.where(np.isinf(g_cool), eucl_cool, g_cool)
d_surf = nearest_distance(xyz, xyz[surf_mask]) d_adiab = nearest_distance(xyz, xyz[adiab_mask]) d_surf = np.where(np.isinf(d_surf), bbox_diag, d_surf) d_adiab = np.where(np.isinf(d_adiab), bbox_diag, d_adiab)
area_cool = total_area(xyz, cool_tri) area_total = area_cool + total_area(xyz, adiab_tri) cool_frac = area_cool / area_total if area_total > 0 else 0.0 volume = mesh_volume(xyz, mesh.tets)
g_adiab = geodesic_distance(N, edges, edge_len, np.flatnonzero(adiab_mask)) g_adiab = np.where(np.isinf(g_adiab), d_adiab, g_adiab) lm = local_modulus(xyz, mesh.tets, cool_tri, edges, edge_len, LOCAL_MODULUS_RADII)
# Boundary channels. Surface nodes carry the mold effusivity (how fast the # mold draws heat); interior nodes carry 0. The heat-input channel is for # heat sources on the boundary, and a plain sand-mold surface has none. boundary_extraction = np.zeros(N, dtype=np.float32) boundary_extraction[cool_mask] = mold_effusivity boundary_extraction[adiab_only] = mold_effusivity boundary_heat_input = np.zeros(N, dtype=np.float32)
cols = { "geodesic_d_cool": g_cool, "d_surf": d_surf, "d_adiab": d_adiab, "is_cooling": cool_mask.astype(np.float32), "is_adiabatic": adiab_only.astype(np.float32), "is_interior": interior_mask.astype(np.float32), "volume_mm3": np.full(N, volume), "surface_area_mm2": np.full(N, area_total), "cooling_area_frac": np.full(N, cool_frac), "geodesic_d_adiab": g_adiab, "local_modulus_r5": lm[:, 0], "local_modulus_r15": lm[:, 1], "local_modulus_r40": lm[:, 2], "boundary_extraction": boundary_extraction, "boundary_heat_input": boundary_heat_input, } X = np.stack([cols[n] for n in FEATURE_NAMES], axis=1).astype(np.float32) return {"X": X, "pos": xyz.astype(np.float32), "mesh_edges": edges.astype(np.int64)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""The two gradient-boosted heads: total solidification time and field spread.
Both are scikit-learn HistGradientBoostingRegressor models that see one rowper part and predict log1p of their target in seconds.
Row layout (16 columns for the total head, 17 for the spread head): 0-6 alloy: k, rho, cp, L_kJ_kg, TL, TS, Tpour 7 part volume / surface area (mm) 8 mold effusivity 9-15 boundary-condition descriptors from training. A casting that cools into the sand mold over its whole surface is the regime encoded as [1, 0, 0, 0, 0, 0, 0]; this release always uses it. 16 (spread head only) fraction of surface nodes tagged adiabatic"""import numpy as np
from src.features import FEATURE_NAMES
_IS_COOLING_IDX = FEATURE_NAMES.index("is_cooling")_IS_ADIABATIC_IDX = FEATURE_NAMES.index("is_adiabatic")_VOL_IDX = FEATURE_NAMES.index("volume_mm3")_AREA_IDX = FEATURE_NAMES.index("surface_area_mm2")
_SAND_MOLD_BOUNDARY = (1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)N_TOTAL_FEATURES = 16N_SPREAD_FEATURES = 17
def total_row(props: dict, X: np.ndarray) -> np.ndarray: """The 16-column row for the total-time head.""" v_over_a = float(X[0, _VOL_IDX]) / float(X[0, _AREA_IDX]) return np.array([ props["k"], props["rho"], props["cp"], props["L_kJ_kg"], props["TL"], props["TS"], props["Tpour"], float(v_over_a), props["mold_effusivity"], *_SAND_MOLD_BOUNDARY, ], dtype=np.float64)
def adiabatic_node_fraction(X: np.ndarray) -> float: """Adiabatic surface nodes / (adiabatic + cooling surface nodes).""" n_adiabatic = float(np.sum(X[:, _IS_ADIABATIC_IDX])) n_cooling = float(np.sum(X[:, _IS_COOLING_IDX])) return n_adiabatic / max(n_adiabatic + n_cooling, 1.0)
def spread_row(row_total: np.ndarray, X: np.ndarray) -> np.ndarray: """The 17-column row for the spread head.""" return np.concatenate([row_total, [adiabatic_node_fraction(X)]])
def predict_total_seconds(model, row: np.ndarray) -> float: total = float(np.expm1(float(model.predict(row.reshape(1, -1))[0]))) if total <= 0: raise ValueError(f"total-time head returned a non-positive total ({total!r})") return total
def predict_spread_seconds(model, row: np.ndarray) -> float: x = np.asarray(row, dtype=np.float64).reshape(1, -1) log_pred = float(model.predict(x)[0]) return max(0.0, float(np.expm1(log_pred)))
def check_head(model, n_features: int, name: str) -> None: n = getattr(model, "n_features_in_", None) if n is not None and int(n) != n_features: raise ValueError(f"{name} head expects {n} input columns, this code builds " f"{n_features}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Pure-geometry helpers: triangle areas, tet volumes, nearest-surfacedistances (via KD-tree), and boundary-node masks. All lengths in mm."""import numpy as npfrom scipy.spatial import cKDTreefrom scipy.sparse import coo_matrixfrom scipy.sparse.csgraph import dijkstra
def triangle_areas(node_xyz: np.ndarray, tri: np.ndarray) -> np.ndarray: if tri.shape[0] == 0: return np.zeros(0) a = node_xyz[tri[:, 0]] b = node_xyz[tri[:, 1]] c = node_xyz[tri[:, 2]] cross = np.cross(b - a, c - a) return 0.5 * np.linalg.norm(cross, axis=1)
def total_area(node_xyz: np.ndarray, tri: np.ndarray) -> float: return float(triangle_areas(node_xyz, tri).sum())
def tet_volumes(node_xyz: np.ndarray, tets: np.ndarray) -> np.ndarray: if tets.shape[0] == 0: return np.zeros(0) a = node_xyz[tets[:, 0]] b = node_xyz[tets[:, 1]] c = node_xyz[tets[:, 2]] d = node_xyz[tets[:, 3]] return np.abs(np.einsum('ij,ij->i', b - a, np.cross(c - a, d - a))) / 6.0
def mesh_volume(node_xyz: np.ndarray, tets: np.ndarray) -> float: if tets.shape[0] == 0: return 0.0 return float(tet_volumes(node_xyz, tets).sum())
def nearest_distance(points: np.ndarray, targets: np.ndarray) -> np.ndarray: """Euclidean distance from each point to the nearest target point. Returns +inf for every point when there are no targets.""" if targets.shape[0] == 0: return np.full(points.shape[0], np.inf) tree = cKDTree(targets) d, _ = tree.query(points, k=1) return d
def boundary_node_mask(n_nodes: int, tri: np.ndarray) -> np.ndarray: mask = np.zeros(n_nodes, dtype=bool) if tri.shape[0]: mask[np.unique(tri.reshape(-1))] = True return mask
_TET_EDGE_PAIRS = ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3))
def edges_from_tets(tets: np.ndarray) -> np.ndarray: if tets.shape[0] == 0: return np.empty((0, 2), dtype=np.int64) e = np.concatenate([tets[:, [a, b]] for a, b in _TET_EDGE_PAIRS], axis=0) e = np.sort(e, axis=1) return np.unique(e, axis=0).astype(np.int64)
def _edge_csr(n_nodes: int, edges: np.ndarray, edge_len: np.ndarray): r = np.concatenate([edges[:, 0], edges[:, 1]]) c = np.concatenate([edges[:, 1], edges[:, 0]]) w = np.concatenate([edge_len, edge_len]) return coo_matrix((w, (r, c)), shape=(n_nodes, n_nodes)).tocsr()
def geodesic_distance(n_nodes: int, edges: np.ndarray, edge_len: np.ndarray, source_idx: np.ndarray) -> np.ndarray: if source_idx.shape[0] == 0 or edges.shape[0] == 0: return np.full(n_nodes, np.inf) g = _edge_csr(n_nodes, edges, edge_len) d = dijkstra(g, directed=False, indices=source_idx, min_only=True) return d
def _local_modulus_for_query(tets: np.ndarray, cool_tri: np.ndarray, radii: np.ndarray, chunk: int, query_idx: np.ndarray, g, tvol: np.ndarray, tarea: np.ndarray, bbox_diag: float) -> np.ndarray: """Exact V/A geodesic-ball modulus, computed only for the nodes in `query_idx` (as Dijkstra sources). Returns (len(query_idx), len(radii)).""" rmax = float(radii.max()) vals = np.full((query_idx.shape[0], len(radii)), bbox_diag, dtype=np.float64) for start in range(0, query_idx.shape[0], chunk): sel = query_idx[start:start + chunk] dmat = dijkstra(g, directed=False, indices=sel, limit=rmax) # (c, N) for j, r in enumerate(radii): in_ball = dmat <= r # (c, N) vol = in_ball[:, tets].all(axis=2) @ tvol # (c,) area = (in_ball[:, cool_tri].all(axis=2) @ tarea if cool_tri.shape[0] else np.zeros(len(sel))) vals[start:start + len(sel), j] = np.where( area > 0, vol / np.maximum(area, 1e-12), bbox_diag) return vals
def local_modulus(node_xyz: np.ndarray, tets: np.ndarray, cool_tri: np.ndarray, edges: np.ndarray, edge_len: np.ndarray, radii, chunk: int = 128) -> np.ndarray: """Local cooling modulus per node: V/A over geodesic balls (mm).
For each node and radius r: (sum of volumes of tets whose 4 nodes all lie within geodesic distance r of the node) / (area of cooling triangles whose 3 nodes all lie within r). Balls with no cooling area get the bbox-diagonal sentinel (consistent with the other distance sentinels).""" N = node_xyz.shape[0] radii = np.asarray(radii, dtype=float) bbox_diag = float(np.linalg.norm(node_xyz.max(0) - node_xyz.min(0))) out = np.full((N, len(radii)), bbox_diag, dtype=np.float64) if edges.shape[0] == 0 or tets.shape[0] == 0: return out.astype(np.float32) tvol = tet_volumes(node_xyz, tets) tarea = triangle_areas(node_xyz, cool_tri) g = _edge_csr(N, edges, edge_len) query_idx = np.arange(N, dtype=np.int64) out[query_idx] = _local_modulus_for_query(tets, cool_tri, radii, chunk, query_idx, g, tvol, tarea, bbox_diag) return out.astype(np.float32)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""Recomposition: combine the GNN field shape with the two heads' targets.
The GNN predicts the spatial pattern of the field well but is less reliableabout its absolute level and spread. The heads predict the part's total time(used as the 99.5% quantile of the field) and the standard deviation of thefield. `hybrid_field_soft` maps the GNN field affinely,
pred(a, m) = clip(a * (gnn - mean(gnn)) + m, 0, None)
and picks (a, m) to minimize
J = w_total * r_total**2 + w_std * r_std**2, r_total = (quantile(pred, q) - total) / total r_std = (std(pred) - std_target) / std_target."""import logging
import numpy as np
logger = logging.getLogger(__name__)
def hybrid_field_max_anchor(gnn_seconds: np.ndarray, total_seconds: float, q: float = 0.995) -> np.ndarray: """Shift the GNN field so its q-quantile equals `total_seconds`, clip at 0.""" g = np.asarray(gnn_seconds, dtype=np.float64) anchor = np.quantile(g, q) out = g - anchor + float(total_seconds) return np.clip(out, 0.0, None)
def hybrid_field_affine(gnn_seconds: np.ndarray, total_seconds: float, std_seconds: float, q: float = 0.995, a_clamp: tuple = (0.3, 5.0)) -> tuple: """Hard two-target fit: the q-quantile is anchored exactly at `total_seconds` and the scale `a` is solved so that the clipped field's standard deviation matches `std_seconds`.
Anchoring the quantile gives raw(a) = a * d + total with d fixed by the GNN field. Below a_clipstart nothing is clipped and a = std/std(gnn) in closed form. Past it, the post-clip spread is not monotone in a (it rises to an interior peak and then falls), so the smallest root is found by a coarse scan followed by bisection; if no root exists the closest scanned point is used and `a_clamped` is set. Returns (field, info).""" g = np.asarray(gnn_seconds, dtype=np.float64) s = float(np.std(g)) if s < 1e-9: logger.warning("hybrid_field_affine: degenerate flat GNN field (std=%.3g) -- " "falling back to quantile-anchor recomposition", s) pred = hybrid_field_max_anchor(g, total_seconds, q=q) return pred, {"a": 1.0, "a_clamped": False, "degenerate_fallback": True, "clip_frac": float((pred == 0.0).mean()), "std_target_effective": float(std_seconds)}
std_target = float(std_seconds) lo, hi = float(a_clamp[0]), float(a_clamp[1]) total = float(total_seconds)
c = g - g.mean() shift = float(np.quantile(c, q)) d = c - shift eps = 1e-9 a_clipstart = total / max(-float(d.min()), eps)
def _raw_for_a(a): return a * d + total
def _post_clip_std(a): return float(np.std(np.clip(_raw_for_a(a), 0.0, None)))
a_raw = std_target / s
if a_raw <= a_clipstart: # Nothing is clipped at a_raw, so the closed form is exact. The clamp # to `lo` can still clip when the total is small next to the spread. a = float(np.clip(a_raw, lo, hi)) a_clamped = bool(a != a_raw) raw = _raw_for_a(a) else: lo_search = max(a_clipstart, lo) if lo_search >= hi: a, a_clamped = hi, True raw = _raw_for_a(a) else: n_scan = 64 scan_a = np.linspace(lo_search, hi, n_scan) scan_f = np.array([_post_clip_std(x) for x in scan_a]) diffs = scan_f - std_target crossing = None for i in range(1, n_scan): if diffs[i - 1] == 0.0 or diffs[i - 1] * diffs[i] <= 0.0: crossing = i break if crossing is not None: blo, bhi = float(scan_a[crossing - 1]), float(scan_a[crossing]) flo = float(diffs[crossing - 1]) if flo == 0.0: a = blo else: for _ in range(50): mid = 0.5 * (blo + bhi) fm = _post_clip_std(mid) - std_target if (fm > 0.0) == (flo > 0.0): blo, flo = mid, fm else: bhi = mid if (bhi - blo) <= 1e-9 * max(abs(bhi), 1e-12): break a = 0.5 * (blo + bhi) a_clamped = False raw = _raw_for_a(a) else: # The target exceeds the reachable spread: take the closest # scanned point instead of the upper clamp. best_idx = int(np.argmin(np.abs(diffs))) a = float(scan_a[best_idx]) a_clamped = True raw = _raw_for_a(a)
clip_frac = float((raw < 0.0).mean()) if clip_frac > 0.5: logger.warning("hybrid_field_affine: majority of field clipped " "(clip_frac=%.3f) -- GBM total/std may be inconsistent " "with the GNN shape", clip_frac) return np.clip(raw, 0.0, None), {"a": a, "a_clamped": a_clamped, "degenerate_fallback": False, "clip_frac": clip_frac, "std_target_effective": std_target}
def hybrid_field_soft(gnn_seconds: np.ndarray, total_seconds: float, std_seconds: float, q: float = 0.995, a_clamp: tuple = (0.3, 5.0), w_total: float = 1.0, w_std: float = 1.0) -> tuple: """Soft two-target fit (see the module docstring for J).
Seeded by `hybrid_field_affine`. When the seed already meets both targets it is returned unchanged; otherwise a 64 x 33 grid over (a, m), a 9 x 9 refinement around the best point and an exact re-check decide whether letting the total move buys a better spread match. Returns (field, info) with info keys a, m, target_unreachable, degenerate_fallback, clip_frac, total_deviation_frac, j_total_resid, j_std_resid, std_target_effective.""" g = np.asarray(gnn_seconds, dtype=np.float64) total = float(total_seconds) q = float(q) w_total = float(w_total) w_std = float(w_std)
if w_total < 0.0 or w_std < 0.0: raise ValueError( f"hybrid_field_soft: w_total/w_std must be >= 0 (got " f"w_total={w_total!r}, w_std={w_std!r})") if w_total == 0.0 and w_std == 0.0: raise ValueError("hybrid_field_soft: w_total and w_std cannot both be 0") if float(a_clamp[0]) <= 0.0: raise ValueError(f"hybrid_field_soft: a_clamp[0] must be > 0 (got {a_clamp[0]!r}) " "-- the a-grid is log-spaced")
pred_seed, info_affine = hybrid_field_affine(g, total, std_seconds, q=q, a_clamp=a_clamp)
# For every branch of the affine solve, m(a) = total - a * quantile(c, q). c = g - g.mean() shift = float(np.quantile(c, q)) a_seed = float(info_affine["a"]) m_seed = total - a_seed * shift std_target_eff = float(info_affine["std_target_effective"])
denom_total = total if abs(total) > 1e-9 else (1e-9 if total >= 0.0 else -1e-9) denom_std = std_target_eff if abs(std_target_eff) > 1e-9 else 1e-9
def _residuals(pred): r_total = (float(np.quantile(pred, q)) - total) / denom_total r_std = (float(np.std(pred)) - std_target_eff) / denom_std return r_total, r_std
def _build_info(final_a, final_m, final_rt, final_rs, clip_frac, target_unreachable): if clip_frac > 0.5: logger.warning("hybrid_field_soft: majority of the accepted soft-anchor " "field clipped (clip_frac=%.3f) -- GBM total/std may be " "inconsistent with the GNN shape", clip_frac) return { "a": final_a, "m": final_m, "target_unreachable": target_unreachable, "degenerate_fallback": False, "clip_frac": clip_frac, "total_deviation_frac": final_rt, "j_total_resid": float(w_total * final_rt ** 2), "j_std_resid": float(w_std * final_rs ** 2), "std_target_effective": std_target_eff, }
r_total_seed, r_std_seed = _residuals(pred_seed) j_seed = w_total * r_total_seed ** 2 + w_std * r_std_seed ** 2
if info_affine["degenerate_fallback"]: return pred_seed, { "a": a_seed, "m": m_seed, "target_unreachable": False, "degenerate_fallback": True, "clip_frac": info_affine["clip_frac"], "total_deviation_frac": r_total_seed, "j_total_resid": float(w_total * r_total_seed ** 2), "j_std_resid": float(w_std * r_std_seed ** 2), "std_target_effective": std_target_eff, }
target_unreachable = bool(info_affine["a_clamped"]) seed_clip_frac = float((c * a_seed + m_seed < 0.0).mean())
# Both targets already met: no search needed (the common case). if j_seed < 1e-12: return pred_seed, _build_info(a_seed, m_seed, r_total_seed, r_std_seed, seed_clip_frac, target_unreachable)
lo, hi = float(a_clamp[0]), float(a_clamp[1]) n_a, n_m = 64, 33 a_grid = np.logspace(np.log10(lo), np.log10(hi), n_a) # The m-window is centred on the seed. m_lo, m_hi = sorted((m_seed - 0.3 * total, m_seed + 0.3 * total)) m_grid = np.linspace(m_lo, m_hi, n_m)
# raw(a, m) = a*c + m is order-preserving and clipping only touches the # low tail, so quantile(clip(raw), q) == a*shift + m in closed form as # long as fewer than ~q of the nodes are clipped. Where that fails (all # nodes clipped) J is over-estimated, so such a point is never selected. # The winning candidate is re-scored exactly below. def _grid_eval(a_vals, m_vals): n_av, n_mv = len(a_vals), len(m_vals) J = np.empty((n_av, n_mv)) Rt = np.empty((n_av, n_mv)) Rs = np.empty((n_av, n_mv)) for i, av in enumerate(a_vals): raw = m_vals[:, None] + av * c[None, :] # (n_mv, n_nodes) clipped = np.clip(raw, 0.0, None) qv = av * shift + m_vals sv = np.std(clipped, axis=-1) rt = (qv - total) / denom_total rs = (sv - std_target_eff) / denom_std J[i] = w_total * rt ** 2 + w_std * rs ** 2 Rt[i] = rt Rs[i] = rs return J, Rt, Rs
J_coarse, Rt_coarse, Rs_coarse = _grid_eval(a_grid, m_grid) idx = np.unravel_index(int(np.argmin(J_coarse)), J_coarse.shape) best_a, best_m = float(a_grid[idx[0]]), float(m_grid[idx[1]]) best_J = float(J_coarse[idx]) best_rt, best_rs = float(Rt_coarse[idx]), float(Rs_coarse[idx])
if j_seed < best_J: best_a, best_m, best_J = a_seed, m_seed, j_seed best_rt, best_rs = r_total_seed, r_std_seed
# One refinement pass on a 9 x 9 sub-grid about one coarse cell wide # around the best point so far (log-spaced in a, linear in m). log_lo, log_hi = np.log10(lo), np.log10(hi) a_step = (log_hi - log_lo) / max(n_a - 1, 1) log_best_a = np.log10(best_a) ref_log_a = np.clip(np.linspace(log_best_a - a_step, log_best_a + a_step, 9), log_lo, log_hi) ref_a = 10.0 ** ref_log_a
m_step = (m_hi - m_lo) / max(n_m - 1, 1) ref_m = np.clip(np.linspace(best_m - m_step, best_m + m_step, 9), m_lo, m_hi)
J_ref, Rt_ref, Rs_ref = _grid_eval(ref_a, ref_m) idx_r = np.unravel_index(int(np.argmin(J_ref)), J_ref.shape) if float(J_ref[idx_r]) < best_J: best_a, best_m = float(ref_a[idx_r[0]]), float(ref_m[idx_r[1]]) best_J = float(J_ref[idx_r]) best_rt, best_rs = float(Rt_ref[idx_r]), float(Rs_ref[idx_r])
# Exact re-check of the winner before accepting it over the seed. if (best_a, best_m) != (a_seed, m_seed): best_pred = np.clip(best_a * c + best_m, 0.0, None) best_rt, best_rs = _residuals(best_pred) best_J = w_total * best_rt ** 2 + w_std * best_rs ** 2
if best_J < j_seed - 1e-12: final_a, final_m = best_a, best_m final_raw = final_a * c + final_m final_pred = np.clip(final_raw, 0.0, None) final_rt, final_rs = best_rt, best_rs else: final_a, final_m = a_seed, m_seed final_raw = final_a * c + final_m final_pred = pred_seed final_rt, final_rs = r_total_seed, r_std_seed
clip_frac = float((final_raw < 0.0).mean()) return final_pred, _build_info(final_a, final_m, final_rt, final_rs, clip_frac, target_unreachable)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Alloy and mold properties.
Turns a named alloy and mold (rows of `data/properties/materials.csv` and`molds.csv`), or a JSON file with raw values, into the 8-key dict the modelreads:
{k, rho, cp, L_kJ_kg, TL, TS, Tpour, mold_effusivity}
Units: W/(m K), kg/m^3, J/(kg K), kJ/kg, deg C, W s^0.5/(m^2 K). The pouringtemperature of a named alloy is the midpoint of its tabulated range."""from __future__ import annotations
import csvimport jsonfrom dataclasses import dataclassfrom pathlib import Path
DEFAULT_ALLOY = "EN-GJS-400-15"DEFAULT_MOLD = "green_sand"
_REQUIRED_KEYS = ("k", "rho", "cp", "L_kJ_kg", "TL", "TS", "Tpour", "mold_effusivity")
_MATERIALS_PATH = "data/properties/materials.csv"_MOLDS_PATH = "data/properties/molds.csv"
# Family used for shrinkage severity when the alloy family is unknown (a raw# property file has no grade). Steel has the largest shrinkage, so this errs# on the side of flagging._UNKNOWN_ALLOY_FAMILY_FALLBACK = "steel"
@dataclass(frozen=True)class Material: material_id: str alloy_family: str k: float rho: float cp: float L: float TL: float TS: float Tpour: float
def load_materials(path: str = _MATERIALS_PATH) -> list[Material]: """Rows of the materials table; rejects rows that are not TS < TL < Tpour.""" materials: list[Material] = [] with Path(path).open(newline="") as handle: for row in csv.DictReader(handle): material_id = row["material_id"] TL = float(row["TL_C"]) TS = float(row["TS_C"]) tpour = 0.5 * (float(row["Tpour_lo_C"]) + float(row["Tpour_hi_C"])) if not TS < TL < tpour: raise ValueError( f"material {material_id!r}: expected TS < TL < Tpour, " f"got {TS}, {TL}, {tpour}") materials.append(Material( material_id=material_id, alloy_family=row["family"], k=float(row["k_W_mK"]), rho=float(row["rho_kg_m3"]), cp=float(row["cp_J_kgK"]), L=float(row["L_kJ_kg"]), TL=TL, TS=TS, Tpour=tpour, )) return materials
def load_molds(path: str = _MOLDS_PATH) -> dict[str, float]: """{mold_system: effusivity} from the molds table.""" with Path(path).open(newline="") as f: return {row["mold_system"]: float(row["effusivity_W_s05_m2K"]) for row in csv.DictReader(f)}
_materials_cache: dict[str, Material] | None = None_molds_cache: dict[str, float] | None = None
def _materials() -> dict[str, Material]: global _materials_cache if _materials_cache is None: _materials_cache = {m.material_id: m for m in load_materials()} return _materials_cache
def _molds() -> dict[str, float]: global _molds_cache if _molds_cache is None: _molds_cache = load_molds() return _molds_cache
def list_alloys() -> list[str]: return list(_materials().keys())
def list_molds() -> list[str]: return list(_molds().keys())
def _validate_tl_ts(props: dict, source: str) -> None: """An inverted or equal liquidus/solidus pair would make the Niyama proxy zero everywhere and flag every node, so it is rejected up front.""" TL, TS = props["TL"], props["TS"] if TL <= TS: raise ValueError( f"resolve_props ({source}): TL ({TL!r}) must be strictly greater than " f"TS ({TS!r})")
def resolve_props(alloy: str | None = None, mold: str = DEFAULT_MOLD, props_json: str | None = None) -> dict: """The 8-key property dict.
`props_json` replaces `alloy` and `mold`; the file must hold all 8 keys. Otherwise `alloy` (default `DEFAULT_ALLOY`) and `mold` are looked up in the tables, and unknown names raise ValueError listing the options.""" if props_json is not None: with open(props_json) as f: data = json.load(f) missing = [k for k in _REQUIRED_KEYS if k not in data] if missing: raise ValueError( f"props_json '{props_json}' is missing required key(s): {missing} " f"(required: {list(_REQUIRED_KEYS)})") props = {k: float(data[k]) for k in _REQUIRED_KEYS} _validate_tl_ts(props, f"props_json={props_json!r}") return props
alloy_id = alloy if alloy is not None else DEFAULT_ALLOY materials = _materials() if alloy_id not in materials: raise ValueError( f"unknown alloy '{alloy_id}'; available alloys: {sorted(materials.keys())}") material = materials[alloy_id]
molds = _molds() if mold not in molds: raise ValueError( f"unknown mold system '{mold}'; available mold systems: {sorted(molds.keys())}")
props = { "k": float(material.k), "rho": float(material.rho), "cp": float(material.cp), "L_kJ_kg": float(material.L), "TL": float(material.TL), "TS": float(material.TS), "Tpour": float(material.Tpour), "mold_effusivity": float(molds[mold]), } _validate_tl_ts(props, f"alloy={alloy_id!r}") return props
def resolve_alloy_family(alloy: str | None, props_json: str | None = None) -> tuple[str, bool]: """(family, assumed) for shrinkage severity. The family comes from the materials table; `assumed` is True when it had to fall back to steel (a raw property file, or an alloy that is not in the table).""" if props_json is not None: return _UNKNOWN_ALLOY_FAMILY_FALLBACK, True material = _materials().get(alloy if alloy is not None else DEFAULT_ALLOY) if material is None: return _UNKNOWN_ALLOY_FAMILY_FALLBACK, True return material.alloy_family, False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Content-addressed on-disk cache for `src.meshing.heal_and_mesh`.
The key is sha256(STEP bytes) + target node count + `MESH_PIPELINE_VERSION`,so a byte-identical STEP file is meshed once. Each entry is a pair`<key>.msh` / `<key>.json` (the mesh and its meta dict), written through aper-writer temporary file and `os.replace`, so concurrent writers never leavea half-written entry. Failed meshes are not cached."""from __future__ import annotations
import hashlibimport jsonimport osimport shutilimport timeimport uuid
# MESH_PIPELINE_VERSION and heal_and_mesh are read through globals() so tests# can monkeypatch them.from src.meshing import DEFAULT_TARGET_NODES, MESH_PIPELINE_VERSION, heal_and_mesh # noqa: F401
_HASH_CHUNK_SIZE = 1 << 20 # 1 MiB# STEP files above this size get the defeaturing attempt first. Changing it# changes which mesh a file resolves to, so bump MESH_PIPELINE_VERSION too._BIG_FILE_THRESHOLD_BYTES = 8 * 1024 * 1024 # 8 MiB
def _sha256_file(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as f: while True: chunk = f.read(_HASH_CHUNK_SIZE) if not chunk: break h.update(chunk) return h.hexdigest()
def mesh_cache_key(step_path: str, target_nodes: int = DEFAULT_TARGET_NODES) -> str: """sha256 over the file digest, `target_nodes` and the pipeline version. The version is read from module globals so tests can monkeypatch it.""" digest = _sha256_file(step_path) pipeline_version = globals()["MESH_PIPELINE_VERSION"] key_input = f"{digest}:{int(target_nodes)}:{int(pipeline_version)}".encode("utf-8") return hashlib.sha256(key_input).hexdigest()
def _unique_tmp_path(final_path: str) -> str: return f"{final_path}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
def _paths(cache_dir: str, key: str) -> tuple[str, str]: return ( os.path.join(cache_dir, f"{key}.msh"), os.path.join(cache_dir, f"{key}.json"), )
def get_or_mesh(step_path: str, out_msh: str, target_nodes: int = DEFAULT_TARGET_NODES, cache_dir: str = "runs/mesh_cache") -> dict: """`heal_and_mesh`'s meta dict for `step_path`, plus a `"cache"` key.
On a hit the cached mesh is copied to `out_msh` (`"cache": "hit"`). On a miss the part is meshed; a successful mesh is stored and returned with `"cache": "miss"`, a failed one is returned unchanged and not stored. Small files try a plain pass first and retry once with defeaturing; files above 8 MiB try the defeatured pass first and retry once without it. """ os.makedirs(cache_dir, exist_ok=True) key = mesh_cache_key(step_path, target_nodes) msh_path, json_path = _paths(cache_dir, key)
if os.path.exists(msh_path) and os.path.exists(json_path): with open(json_path) as f: meta = json.load(f) shutil.copyfile(msh_path, out_msh) result = dict(meta) result["cache"] = "hit" return result
heal_and_mesh_fn = globals()["heal_and_mesh"] t0 = time.time() big_file = os.path.getsize(step_path) > _BIG_FILE_THRESHOLD_BYTES if big_file: meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=True) defeature_used, retry = True, False if not meta.get("ok"): meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=False) defeature_used, retry = False, True else: meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=False) defeature_used, retry = False, False if not meta.get("ok"): meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=True) defeature_used, retry = True, True wall_s = time.time() - t0
if not meta.get("ok"): result = dict(meta) result["cache"] = "miss" result["defeature"] = defeature_used result["retry"] = retry return result
stored_meta = dict(meta) stored_meta["mesh_wall_s"] = wall_s stored_meta["pipeline_version"] = globals()["MESH_PIPELINE_VERSION"] stored_meta["source_path"] = os.path.abspath(step_path) stored_meta["created_at"] = time.time() stored_meta["defeature"] = defeature_used stored_meta["retry"] = retry
msh_tmp = _unique_tmp_path(msh_path) json_tmp = _unique_tmp_path(json_path) shutil.copyfile(out_msh, msh_tmp) os.replace(msh_tmp, msh_path) with open(json_tmp, "w") as f: json.dump(stored_meta, f) os.replace(json_tmp, json_path)
result = dict(stored_meta) result["cache"] = "miss" return result
def clear_mesh_cache(cache_dir: str = "runs/mesh_cache") -> None: """Remove the entire cache directory, if present.""" shutil.rmtree(cache_dir, ignore_errors=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368"""STEP to tetrahedral mesh with Gmsh (OpenCASCADE kernel).
`heal_and_mesh` is the default path: import the STEP file, keep the largestsolid, tag every surface "Cooling" and the volume "Volume", and search theelement size until the mesh lands near `target_nodes` (the density the modelwas trained on). If the unhealed geometry cannot be meshed, a second pass healsit and retries. `mesh_step` meshes at one fixed element size instead.
Both write gmsh 2.2 ASCII meshes, the format `src.msh_parse` reads. Alllengths are in millimetres."""from __future__ import annotations
import numpy as np
DEFAULT_TARGET_NODES = 8500# Part of the mesh-cache key (src/mesh_cache.py): bump it whenever a change# here would produce a different mesh for the same STEP file.MESH_PIPELINE_VERSION = 3
# Element-size seed: sqrt(K_SURF * surface_area / target_nodes), calibrated so# the first guess usually lands within the density search's tolerance.K_SURF = 2.5
# Physical-group tags are pinned (not auto-assigned) so that repeated meshing# attempts in one Gmsh session keep the "Volume"/"Cooling" names bound._VOLUME_PHYS_TAG = 1_COOLING_PHYS_TAG = 2
def _reduce_to_largest_solid(): """Keep only the largest solid of the imported OCC model.
Returns (n_solids_in, kept_tag, kept_volume_mm3).""" import gmsh
vols = [t for (d, t) in gmsh.model.occ.getEntities(3)] n_in = len(vols) if n_in == 0: raise ValueError("no 3D solids found in STEP import") masses = [(t, gmsh.model.occ.getMass(3, t)) for t in vols] kept_tag, kept_vol = max(masses, key=lambda tv: tv[1]) if n_in > 1: drop = [(3, t) for (t, _v) in masses if t != kept_tag] gmsh.model.occ.remove(drop, recursive=True) gmsh.model.occ.synchronize() return n_in, kept_tag, float(kept_vol)
def _import_and_reduce(step_path: str) -> tuple[int, float, str | None]: """Import `step_path` into the current Gmsh session and keep its largest solid. Returns (n_solids_in, kept_volume_mm3, error_or_None).""" import gmsh
try: gmsh.model.occ.importShapes(step_path) gmsh.model.occ.synchronize() except Exception as e: return 0, 0.0, f"import failed: {e}" try: n_solids, _kept_tag, volume_mm3 = _reduce_to_largest_solid() except Exception as e: return 0, 0.0, f"largest-solid reduction failed: {e}" return n_solids, volume_mm3, None
def _elem_size(bbox_diag_mm: float) -> float: """Fallback element-size seed: bounding-box diagonal / 28.""" return bbox_diag_mm / 28.0
def _elem_size_from_area(area_mm2: float, target_nodes: int) -> float: """Element-size seed from the total surface area of the model.""" return float(np.sqrt(K_SURF * area_mm2 / target_nodes))
def _total_surface_area_mm2() -> float: """Total area of all surface entities of the current OCC model.""" import gmsh
surfs = [t for (d, t) in gmsh.model.occ.getEntities(2)] return float(sum(gmsh.model.occ.getMass(2, t) for t in surfs))
def _first_guess_elem_size(bbox_diag_mm: float, target_nodes: int) -> float: """Surface-area seed, or the bounding-box seed if the area query fails.""" try: area_mm2 = _total_surface_area_mm2() except Exception as e: print(f"[meshing] WARNING: OCC surface-area query failed ({e}); " f"falling back to bbox_diag/28 seed", flush=True) return _elem_size(bbox_diag_mm) if area_mm2 <= 0: print(f"[meshing] WARNING: OCC surface-area query returned " f"{area_mm2!r} (<=0); falling back to bbox_diag/28 seed", flush=True) return _elem_size(bbox_diag_mm) return _elem_size_from_area(area_mm2, target_nodes)
def _search_elem_size(build_fn, out_msh: str, target_nodes: int, max_iter: int = 3) -> tuple[int, float]: """Refine the element size assuming the node count scales as h^-3.""" n_nodes, elem_size = build_fn(out_msh, None) for _ in range(max_iter - 1): if n_nodes <= 0: break elem_size = elem_size * (n_nodes / target_nodes) ** (1.0 / 3.0) n_nodes, elem_size = build_fn(out_msh, elem_size) return n_nodes, elem_size
def _search_target_nodes(build_fn, out_msh: str, target_nodes: int, tol: float = 0.35, max_iter: int = 3) -> tuple[int, float, int]: """Density search towards `target_nodes`.
`build_fn(out_msh, elem_size) -> (n_nodes, elem_size_used)`, with `elem_size=None` meaning "use the seed" and `n_nodes == 0` meaning the mesh failed outright. Stops after the first attempt if it is already within `tol` of the target (or failed); otherwise refines for up to `max_iter` attempts. Returns (n_nodes, elem_size_used, attempts).""" calls = {"n": 0}
def counted_build_fn(msh_path, elem_size): calls["n"] += 1 return build_fn(msh_path, elem_size)
n0, es0 = counted_build_fn(out_msh, None) if n0 <= 0 or abs(n0 - target_nodes) <= tol * target_nodes: return n0, es0, calls["n"] n, es = _search_elem_size(counted_build_fn, out_msh, target_nodes, max_iter=max_iter) return n, es, calls["n"]
def _tag_and_mesh(size: float, out_msh: str) -> tuple[bool, int, str]: """Tag the current model ("Volume" + every surface as "Cooling") and mesh it at element size `size`. Returns (ok, n_nodes, note).
The tag numbers are pinned: Gmsh keeps a removed group's *name* bound to its old tag, so auto-assigned tags on a second attempt in the same session would leave the written mesh with unnamed groups.""" import gmsh
gmsh.model.mesh.clear() gmsh.model.removePhysicalGroups() vols = [t for (d, t) in gmsh.model.getEntities(3)] surfs = [t for (d, t) in gmsh.model.getEntities(2)] if not vols: return False, 0, "no volume entities to mesh" pv = gmsh.model.addPhysicalGroup(3, vols, tag=_VOLUME_PHYS_TAG) gmsh.model.setPhysicalName(3, pv, "Volume") pc = gmsh.model.addPhysicalGroup(2, surfs, tag=_COOLING_PHYS_TAG) gmsh.model.setPhysicalName(2, pc, "Cooling") # The mesh reader matches elements by group name, so an unnamed group # would silently look like a mesh without boundary. Fail loudly instead. if (gmsh.model.getPhysicalName(3, pv) != "Volume" or gmsh.model.getPhysicalName(2, pc) != "Cooling"): return False, 0, ("physical-group tagging did not register " "(Volume/Cooling name binding missing)") gmsh.option.setNumber("Mesh.MeshSizeMin", size) gmsh.option.setNumber("Mesh.MeshSizeMax", size) try: gmsh.model.mesh.generate(3) node_tags, _, _ = gmsh.model.mesh.getNodes() try: tet_tags = gmsh.model.mesh.getElementsByType(4)[0] except Exception: tet_tags = [] if len(node_tags) > 0 and len(tet_tags) > 0: gmsh.option.setNumber("Mesh.MshFileVersion", 2.2) gmsh.write(out_msh) return True, len(node_tags), "" return False, 0, f"empty mesh at size={size:.2f}mm" except Exception as e: return False, 0, f"mesh generate failed at size={size:.2f}mm: {e}"
def _apply_heal() -> tuple[bool, str]: """Run OCC shape healing. `healShapes()` can finish without raising and still leave no solid, so a heal only counts if a volume survives. Returns (effective, note).""" import gmsh
try: gmsh.model.occ.healShapes() gmsh.model.occ.synchronize() except Exception as e: return False, f"healShapes raised: {e}" n_vols = len(gmsh.model.getEntities(3)) if n_vols == 0: return False, ("healShapes ran but yielded 0 volume entities (solid could not be " "reconstructed -- likely a self-intersecting B-rep)") return True, ""
def _apply_defeature() -> tuple[bool, str]: """Merge literally duplicate OCC entities (`removeAllDuplicates`), a cheap clean-up for CAD exports. Returns (ok, note); not ok if the call raises or the solid is lost.""" import gmsh
n_vols_before = len(gmsh.model.getEntities(3)) try: gmsh.model.occ.removeAllDuplicates() gmsh.model.occ.synchronize() except Exception as e: return False, f"defeature (removeAllDuplicates) raised: {e}" n_vols_after = len(gmsh.model.getEntities(3)) if n_vols_before > 0 and n_vols_after == 0: return False, "defeature (removeAllDuplicates) yielded 0 volume entities (solid lost)" return True, ""
def heal_and_mesh(step_path: str, out_msh: str, target_nodes: int = DEFAULT_TARGET_NODES, defeature: bool = False) -> dict: """Mesh the largest solid of `step_path` near `target_nodes` nodes.
Pass 1 meshes the geometry as imported (healing can destroy a solid that would have meshed fine, so it is not applied by default). Only if pass 1 fails outright does pass 2, in a fresh Gmsh session, heal the geometry and retry the same density search. `defeature=True` runs `_apply_defeature` before meshing in both passes.
Returns {n_solids, volume_mm3, bbox_diag_mm, n_nodes, ok, healed, notes, attempts}; `notes` collects human-readable diagnostics. """ import gmsh
notes: list[str] = []
# ---- Pass 1: unhealed ---- gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("part") n_solids, volume_mm3, err = _import_and_reduce(step_path) if err is not None: notes.append(err) return dict(n_solids=0, volume_mm3=0.0, bbox_diag_mm=0.0, n_nodes=0, ok=False, healed=False, notes="; ".join(notes), attempts=0) if n_solids > 1: notes.append(f"multi-body: kept largest of {n_solids} solids (vol={volume_mm3:.1f} mm3)")
if defeature: defeature_ok, defeature_note = _apply_defeature() if defeature_note: notes.append(defeature_note) if not defeature_ok: return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=0.0, n_nodes=0, ok=False, healed=False, notes="; ".join(notes), attempts=0)
xmin, ymin, zmin, xmax, ymax, zmax = gmsh.model.getBoundingBox(-1, -1) bbox_diag_mm = float(np.linalg.norm([xmax - xmin, ymax - ymin, zmax - zmin])) base_size = _first_guess_elem_size(bbox_diag_mm, target_nodes)
fail_notes: list[str] = []
def build_fn(msh_path, elem_size): size = elem_size if elem_size is not None else base_size ok_, n_nodes_, note_ = _tag_and_mesh(size, msh_path) if not ok_: fail_notes.append(note_) return (n_nodes_ if ok_ else 0), size
n_nodes, _used_size, attempts = _search_target_nodes(build_fn, out_msh, target_nodes) if n_nodes > 0: return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm, n_nodes=n_nodes, ok=True, healed=False, notes="; ".join(notes), attempts=attempts) notes.append(f"unhealed mesh attempt failed: {fail_notes[-1] if fail_notes else 'unknown'}") finally: gmsh.finalize()
# ---- Pass 2: heal + density-searched retry (fresh session) ---- healed = False gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("part_healed") n_solids2, volume_mm32, err2 = _import_and_reduce(step_path) if err2 is not None: notes.append(f"pass-2 {err2}") return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm, n_nodes=0, ok=False, healed=False, notes="; ".join(notes), attempts=attempts)
if defeature: defeature_ok2, defeature_note2 = _apply_defeature() if defeature_note2: notes.append(defeature_note2) if not defeature_ok2: return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm, n_nodes=0, ok=False, healed=False, notes="; ".join(notes), attempts=attempts)
heal_ok, heal_note = _apply_heal() if heal_note: notes.append(heal_note) if not heal_ok: notes.append("meshing failed after heal attempt") return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm, n_nodes=0, ok=False, healed=False, notes="; ".join(notes), attempts=attempts) healed = True
fail_notes2: list[str] = []
def build_fn2(msh_path, elem_size): size = elem_size if elem_size is not None else base_size ok_, n_nodes_, note_ = _tag_and_mesh(size, msh_path) if not ok_: fail_notes2.append(note_) return (n_nodes_ if ok_ else 0), size
n_nodes2, _used_size2, attempts2 = _search_target_nodes(build_fn2, out_msh, target_nodes) if n_nodes2 > 0: notes.append("meshed after heal") return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm, n_nodes=n_nodes2, ok=True, healed=True, notes="; ".join(notes), attempts=attempts + attempts2) notes.append(f"post-heal mesh attempt failed: {fail_notes2[-1] if fail_notes2 else 'unknown'}") notes.append("meshing failed after heal attempt") return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm, n_nodes=0, ok=False, healed=healed, notes="; ".join(notes), attempts=attempts + attempts2) finally: gmsh.finalize()
def auto_elem_size(bbox_diag: float) -> float: """Default fixed element size for `mesh_step`: bounding-box diagonal / 60.""" return bbox_diag / 60.0
def mesh_step(step_path: str, out_msh: str, elem_size: float | None = None) -> dict: """Mesh the whole STEP model at one fixed element size (no healing, no density search). Every surface is tagged "Cooling".""" import gmsh
gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("casting") gmsh.model.occ.importShapes(step_path) gmsh.model.occ.synchronize()
xmin, ymin, zmin, xmax, ymax, zmax = gmsh.model.getBoundingBox(-1, -1) bbox = (xmax - xmin, ymax - ymin, zmax - zmin) diag = float(np.linalg.norm(bbox)) size = float(elem_size) if elem_size is not None else auto_elem_size(diag) gmsh.option.setNumber("Mesh.MeshSizeMin", size) gmsh.option.setNumber("Mesh.MeshSizeMax", size)
vols = [t for (d, t) in gmsh.model.getEntities(3)] surfs = [t for (d, t) in gmsh.model.getEntities(2)] pv = gmsh.model.addPhysicalGroup(3, vols); gmsh.model.setPhysicalName(3, pv, "Volume") pc = gmsh.model.addPhysicalGroup(2, surfs); gmsh.model.setPhysicalName(2, pc, "Cooling")
gmsh.model.mesh.generate(3) gmsh.option.setNumber("Mesh.MshFileVersion", 2.2) gmsh.write(out_msh)
node_tags, _, _ = gmsh.model.mesh.getNodes() tet_tags = gmsh.model.mesh.getElementsByType(4)[0] return {"n_nodes": len(node_tags), "n_tets": len(tet_tags), "bbox_mm": bbox, "elem_size": size} finally: gmsh.finalize()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Mesh in, solidification-time field out.
from src.model_api import CastSolidModel model = CastSolidModel() # loads weights/ once seconds = model.predict("part.msh", alloy="G20Mn5")
`predict` takes a gmsh 2.2 ASCII tetrahedral mesh (a path or a parsed`src.msh_parse.Mesh`) whose cooling surface is tagged "Cooling", and returnsthe solidification time in seconds for every node, in the mesh's node order."""from __future__ import annotations
import os
import numpy as npimport torch
from src import gbm_headsfrom src.features import alloy_g_vector, node_featuresfrom src.hybrid import hybrid_field_softfrom src.inference_props import DEFAULT_MOLD, resolve_propsfrom src.model_gnn import load_gnn, predict_graph_secondsfrom src.msh_parse import Mesh, parse_mshfrom src.release_io import load_gbm, load_gnn_state
# Recomposition weights of the published model (see src/hybrid.py).W_TOTAL = 1.0W_STD = 4.0
GNN_FILE = "gnn_v5.1.safetensors"TOTAL_HEAD_FILE = "gbm_total_v3.skops"SPREAD_HEAD_FILE = "gbm_std_v2.skops"
class CastSolidModel: def __init__(self, weights_dir: str = "weights", device: str | None = None): self.device = device or ("cuda" if torch.cuda.is_available() else "cpu") state = load_gnn_state(os.path.join(weights_dir, GNN_FILE), self.device) self.gnn, self.cfg, self.norm = load_gnn(state, self.device) self.total_head = load_gbm(os.path.join(weights_dir, TOTAL_HEAD_FILE)) self.spread_head = load_gbm(os.path.join(weights_dir, SPREAD_HEAD_FILE)) gbm_heads.check_head(self.total_head, gbm_heads.N_TOTAL_FEATURES, "total-time") gbm_heads.check_head(self.spread_head, gbm_heads.N_SPREAD_FEATURES, "spread")
def predict(self, mesh: str | Mesh, alloy: str | None = None, mold: str = DEFAULT_MOLD, props_json: str | None = None) -> np.ndarray: """Per-node solidification time (s).
`alloy`/`mold` name rows of `data/properties/` (default EN-GJS-400-15 in green sand); `props_json` replaces both with your own values.""" props = resolve_props(alloy=alloy, mold=mold, props_json=props_json) return self.predict_with_props(mesh, props)[0]
def predict_with_props(self, mesh: str | Mesh, props: dict) -> tuple[np.ndarray, dict]: """(seconds, details) for an already-resolved property dict.
`details` holds the node feature matrix `X`, the heads' `total_s` and `spread_s`, and the recomposition diagnostics `recomposition`.""" if not isinstance(mesh, Mesh): mesh = parse_msh(os.fspath(mesh)) feat = node_features(mesh, props["mold_effusivity"]) X = feat["X"] gnn_seconds = predict_graph_seconds(self.gnn, self.cfg, self.norm, X, feat["pos"], feat["mesh_edges"], alloy_g_vector(props), device=self.device) row = gbm_heads.total_row(props, X) total = gbm_heads.predict_total_seconds(self.total_head, row) spread = gbm_heads.predict_spread_seconds(self.spread_head, gbm_heads.spread_row(row, X)) seconds, info = hybrid_field_soft(gnn_seconds, total, spread, w_total=W_TOTAL, w_std=W_STD) return seconds, {"X": X, "total_s": total, "spread_s": spread, "recomposition": info}
@staticmethod def hotspots(seconds: np.ndarray, top_frac: float = 0.1) -> np.ndarray: """Boolean mask of the `top_frac` latest-solidifying nodes.""" seconds = np.asarray(seconds, dtype=np.float32) k = max(1, int(round(seconds.shape[0] * top_frac))) return seconds >= np.sort(seconds)[-k]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""The graph network: an encode-process-decode GNN in the style ofMeshGraphNets, conditioned on the alloy/mold vector through FiLM.
It predicts the standardized log1p solidification time of every node. Thegraph is the union of the tetrahedral mesh edges and each node's k nearestneighbours; an edge carries its displacement vector (mm), its length and aflag telling whether it is a mesh edge."""import numpy as npimport torchimport torch.nn as nnfrom torch_geometric.nn import knn_graphfrom torch_geometric.utils import scatter, to_undirected
def _mlp(i, h, o): return nn.Sequential(nn.Linear(i, h), nn.ReLU(), nn.Linear(h, o))
class ProcessorBlock(nn.Module): """One message-passing step with residual edge and node updates."""
def __init__(self, h): super().__init__() self.edge_mlp = _mlp(3 * h, h, h) self.edge_norm = nn.LayerNorm(h) self.node_mlp = _mlp(2 * h, h, h) self.node_norm = nn.LayerNorm(h)
def forward(self, hnode, edge_index, e): src, dst = edge_index e_new = self.edge_norm(self.edge_mlp(torch.cat([hnode[src], hnode[dst], e], dim=-1)) + e) agg = scatter(e_new, dst, dim=0, dim_size=hnode.shape[0], reduce="mean") h_new = self.node_norm(self.node_mlp(torch.cat([hnode, agg], dim=-1)) + hnode) return h_new, e_new
class FiLM(nn.Module): """g -> per-channel (gamma, beta); applied as h * (1 + gamma) + beta."""
def __init__(self, g_dim, hidden): super().__init__() self.net = nn.Sequential(nn.Linear(g_dim, hidden), nn.SiLU(), nn.Linear(hidden, 2 * hidden))
def forward(self, h, g_nodes): gamma, beta = self.net(g_nodes).chunk(2, dim=-1) return h * (1.0 + gamma) + beta
class SolidGNN(nn.Module): """12 processor blocks (hidden width 128 in the published model), FiLM after each block, and a two-head decoder: a per-node deviation head and a graph-level scale head on the mean node embedding."""
def __init__(self, node_in=15, edge_in=5, hidden=128, n_blocks=12, g_dim=5): super().__init__() self.node_encoder = nn.Sequential(_mlp(node_in, hidden, hidden), nn.LayerNorm(hidden)) self.edge_encoder = nn.Sequential(_mlp(edge_in, hidden, hidden), nn.LayerNorm(hidden)) self.blocks = nn.ModuleList([ProcessorBlock(hidden) for _ in range(n_blocks)]) self.decoder = _mlp(hidden, hidden // 2, 1) self.scale_head = _mlp(hidden, hidden // 2, 1) self.films = nn.ModuleList([FiLM(g_dim, hidden) for _ in range(n_blocks)])
def forward(self, x, edge_index, edge_attr, batch, g): h = self.node_encoder(x) e = self.edge_encoder(edge_attr) g_nodes = g[batch] for i, blk in enumerate(self.blocks): h, e = blk(h, edge_index, e) h = self.films[i](h, g_nodes) y_nodal = self.decoder(h).squeeze(-1) dev = y_nodal - scatter(y_nodal, batch, dim=0, reduce="mean")[batch] scale = self.scale_head(scatter(h, batch, dim=0, reduce="mean")).squeeze(-1) return dev + scale[batch]
def knn_edge_index(pos: torch.Tensor, k: int = 16) -> torch.Tensor: ei = knn_graph(pos, k=k, loop=False) # directed k-nearest return to_undirected(ei) # symmetric
def union_edge_index(pos: torch.Tensor, mesh_edges: torch.Tensor, k: int = 16): """Undirected union of the mesh edges and kNN edges, deduplicated.
mesh_edges: (M, 2) long tensor of unique node pairs (any orientation). Returns (edge_index (2, E) long, is_mesh (E,) float32 flag).""" n = pos.shape[0] knn = knn_edge_index(pos, k=k).to(torch.long) me = mesh_edges.t().to(torch.long) me = torch.cat([me, me.flip(0)], dim=1) # both directions mesh_key = me[0] * n + me[1] keys = torch.unique(torch.cat([mesh_key, knn[0] * n + knn[1]])) ei = torch.stack([keys // n, keys % n]) is_mesh = torch.isin(keys, mesh_key).to(torch.float32) return ei, is_mesh
def union_edge_attr(pos: torch.Tensor, edge_index: torch.Tensor, is_mesh: torch.Tensor) -> torch.Tensor: """(E, 5): displacement (3), length, mesh-edge flag.""" src, dst = edge_index d = pos[dst] - pos[src] return torch.cat([d, d.norm(dim=1, keepdim=True), is_mesh.unsqueeze(1)], dim=1)
def load_gnn(state: dict, device): """Build a `SolidGNN` from a `{model, norm, cfg}` dict (see `src.release_io.load_gnn_state`). Returns (model, cfg, norm).""" cfg, norm = state["cfg"], state["norm"] model = SolidGNN(node_in=cfg["node_in"], edge_in=cfg["edge_in"], hidden=cfg["hidden"], n_blocks=cfg["n_blocks"], g_dim=cfg.get("g_dim", 5)).to(device) model.load_state_dict(state["model"]) model.eval() return model, cfg, norm
def predict_graph_seconds(model, cfg, norm, X, pos_np, mesh_edges, g_vec, device="cpu") -> np.ndarray: """Per-node solidification time (s) predicted by the GNN alone.
`X` is the raw (N, 15) feature matrix, `g_vec` the raw (5,) alloy/mold vector; standardization uses the statistics stored with the weights.""" fmean = torch.tensor(norm["feat_mean"], dtype=torch.float32) fstd = torch.tensor(norm["feat_std"], dtype=torch.float32) x = (torch.tensor(X, dtype=torch.float32) - fmean) / fstd pos = torch.tensor(pos_np, dtype=torch.float32) me = torch.tensor(mesh_edges, dtype=torch.long) ei, is_mesh = union_edge_index(pos, me, k=cfg["k"]) ea = union_edge_attr(pos, ei, is_mesh) zeros = torch.zeros(x.shape[0], dtype=torch.long, device=device) g = torch.tensor(np.asarray(g_vec), dtype=torch.float32).reshape(1, -1).to(device) with torch.no_grad(): yn = model(x.to(device), ei.to(device), ea.to(device), zeros, g) pred_log = yn.cpu().numpy() * norm["y_log_std"] + norm["y_log_mean"] return np.clip(np.expm1(pred_log), 0.0, None)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Reader for gmsh 2.2 ASCII meshes.
Extracts node coordinates (mm, in the file's node order), surface trianglesgrouped by physical name ("Cooling", optionally "Adiabatic") and volumetetrahedra. Connectivity is remapped to 0-based node indices."""from dataclasses import dataclassimport numpy as np
_TRI_TYPE = 2 # 3-node triangle_TET_TYPE = 4 # 4-node tetrahedron
@dataclassclass Mesh: node_xyz: np.ndarray # (N, 3) float64, mm tris: dict # name -> (M, 3) int64, 0-based tets: np.ndarray # (K, 4) int64, 0-based
def parse_msh(path: str) -> Mesh: lines = open(path).read().splitlines() i, n = 0, len(lines) phys = {} # physical tag -> name node_ids = [] # id order coords = [] # xyz in that order tri_by_name = {} # name -> list of [i,j,k] tets = []
while i < n: s = lines[i].strip() if s == "$PhysicalNames": cnt = int(lines[i + 1]) for k in range(cnt): dim, tag, name = lines[i + 2 + k].split(maxsplit=2) phys[int(tag)] = name.strip().strip('"') i += 2 + cnt continue if s == "$Nodes": cnt = int(lines[i + 1]) for k in range(cnt): p = lines[i + 2 + k].split() node_ids.append(int(p[0])) coords.append((float(p[1]), float(p[2]), float(p[3]))) i += 2 + cnt continue if s == "$Elements": cnt = int(lines[i + 1]) id2idx = {nid: idx for idx, nid in enumerate(node_ids)} for k in range(cnt): p = [int(x) for x in lines[i + 2 + k].split()] etype, ntags = p[1], p[2] tags = p[3:3 + ntags] conn = [id2idx[v] for v in p[3 + ntags:]] name = phys.get(tags[0]) if ntags else None if etype == _TRI_TYPE and name is not None: tri_by_name.setdefault(name, []).append(conn) elif etype == _TET_TYPE: tets.append(conn) i += 2 + cnt continue i += 1
node_xyz = np.asarray(coords, dtype=np.float64) tris = {name: np.asarray(v, dtype=np.int64) for name, v in tri_by_name.items()} tets_arr = np.asarray(tets, dtype=np.int64) if tets else np.empty((0, 4), np.int64) return Mesh(node_xyz=node_xyz, tris=tris, tets=tets_arr)1234567891011121314151617181920212223"""Out-of-distribution size check: compare a casting's volume, bounding-boxdiagonal and largest distance to cooling with the training maxima(`weights/ood_ranges.json`) and warn when any of them is exceeded."""import json
def load_ranges(path: str) -> dict: with open(path) as f: return json.load(f)
def ood_flags(volume_mm3, bbox_diag, geodesic_d_cool_max, ranges, tol=1.05) -> list: w = [] if volume_mm3 > ranges["volume_mm3_max"] * tol: w.append(f"casting volume {volume_mm3:.0f} mm^3 exceeds training max " f"{ranges['volume_mm3_max']:.0f} mm^3 — prediction unreliable") if bbox_diag > ranges["bbox_diag_max"] * tol: w.append(f"bounding-box diagonal {bbox_diag:.0f} mm exceeds training max " f"{ranges['bbox_diag_max']:.0f} mm — prediction unreliable") if geodesic_d_cool_max > ranges["geodesic_d_cool_max"] * tol: w.append(f"max distance-to-cooling {geodesic_d_cool_max:.1f} mm exceeds training max " f"{ranges['geodesic_d_cool_max']:.1f} mm — prediction unreliable") return w123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283"""STEP file in, solidification field out.
python -m src.predict_casting part.step --out-dir out [--alloy G20Mn5]
Steps: mesh the STEP file (healed, density-searched and cached, or at a fixedelement size with --elem-size), run the model, check the training envelope,screen for shrinkage, and write `<name>.vtu`, `<name>_summary.txt` and themesh `<name>.msh` to the output directory."""from __future__ import annotations
import argparseimport loggingimport osimport os.path as osp
import numpy as np
from src import ood as _oodfrom src.features import FEATURE_NAMESfrom src.inference_props import DEFAULT_ALLOY, DEFAULT_MOLD, resolve_alloy_family, resolve_propsfrom src.mesh_cache import get_or_meshfrom src.meshing import DEFAULT_TARGET_NODES, mesh_stepfrom src.model_api import CastSolidModelfrom src.msh_parse import parse_mshfrom src.shrinkage import screen_casting
logger = logging.getLogger(__name__)
MODEL_VERSION = "v5.1"_VOL_IDX = FEATURE_NAMES.index("volume_mm3")_GCOOL_IDX = FEATURE_NAMES.index("geodesic_d_cool")
def write_vtu(out_path, node_xyz, tets, seconds, top_frac=0.1, extra_point_data=None): """Write the mesh with `solidification_time` (s) and `hotspot` (the `top_frac` latest-solidifying nodes) point fields, plus any extras.""" import meshio seconds = np.asarray(seconds, dtype=np.float32) n = seconds.shape[0] k = max(1, int(round(n * top_frac))) thresh = np.sort(seconds)[-k] hotspot = (seconds >= thresh).astype(np.int32) point_data = {"solidification_time": seconds, "hotspot": hotspot} if extra_point_data: point_data.update(extra_point_data) m = meshio.Mesh(points=np.asarray(node_xyz, dtype=np.float64), cells=[("tetra", np.asarray(tets))], point_data=point_data) m.write(out_path)
def _surface_and_feed_nodes(mesh): """All tagged surface nodes, and the adiabatic-tagged ones that can feed a shrinkage region (none on a STEP meshed by this pipeline).""" tri_arrays = [tri for tri in mesh.tris.values() if tri.size] surface_nodes = (np.unique(np.concatenate(tri_arrays, axis=0).reshape(-1)) if tri_arrays else np.zeros(0, dtype=np.int64)) adiab_tri = mesh.tris.get("Adiabatic") feed_nodes = (np.unique(adiab_tri.reshape(-1)) if adiab_tri is not None and adiab_tri.size else np.zeros(0, dtype=np.int64)) return surface_nodes.astype(np.int64), feed_nodes.astype(np.int64)
def _shrinkage_result_for_return(screen: dict) -> dict: """The screening result without its per-node arrays, plus counts.""" result = {k: v for k, v in screen.items() if k not in ("niyama", "porosity_risk")} risk = screen["porosity_risk"] result["flagged_frac"] = float(np.mean(risk)) if risk.size else 0.0 result["n_macro_regions"] = len(screen["macro_shrinkage"]) result["n_sinks"] = len(screen["top_sinks"]) result["n_feeders"] = len(screen["feeders"]) return result
def _shrinkage_point_data(mesh, screen: dict) -> dict: n_nodes = mesh.node_xyz.shape[0] macro_region_id = np.full(n_nodes, -1, dtype=np.int64) for region in screen["macro_shrinkage"]: macro_region_id[np.asarray(region["nodes"], dtype=np.int64)] = region["region_id"] return { "niyama": np.asarray(screen["niyama"], dtype=np.float32), "porosity_risk": np.asarray(screen["porosity_risk"], dtype=np.uint8), "macro_region_id": macro_region_id, }
def _write_shrinkage_summary(f, shrinkage) -> None: if shrinkage is None: f.write("shrinkage screening: disabled\n") return f.write("shrinkage screening:\n") f.write(f" niyama_source: {shrinkage['niyama_source']}\n") # The risk mask is the lowest Niyama decile of the part, so this # percentage is fixed by construction, not a measured severity. f.write(f" flagged nodes: {shrinkage['flagged_frac'] * 100.0:.1f}%" f" (bottom decile by construction)\n") macro = shrinkage["macro_shrinkage"] if macro: # Regions under 4 nodes are listed but get no feeder suggestion. n_sub_resolution = sum(1 for r in macro if r.get("sub_resolution")) region_count = str(len(macro)) if n_sub_resolution: region_count += f" (+{n_sub_resolution} sub-resolution)" worst = max(macro, key=lambda r: r["severity"]) c = worst["centroid"] f.write(f" macro shrinkage regions: {region_count} " f"(worst severity={worst['severity']:.4g} mm^3 @ " f"({c[0]:.1f},{c[1]:.1f},{c[2]:.1f}))\n") else: f.write(" macro shrinkage regions: 0\n") f.write(f" sinks: {len(shrinkage['top_sinks'])}\n") feeders = shrinkage["feeders"] if feeders: f.write(" feeder recommendations:\n") for feeder in feeders: loc = feeder["location"] f.write(f" - location=({loc[0]:.1f},{loc[1]:.1f},{loc[2]:.1f}) mm " f"min_modulus_mm={feeder['min_modulus_mm']:.4f}\n") else: f.write(" feeder recommendations: none\n") if shrinkage.get("alloy_family_assumed"): f.write(f" alloy_family_assumed: {shrinkage['material']['alloy_family']} " f"(alloy not in the materials table -- conservative fallback)\n")
def _mesh(step_path, out_msh, elem_size, target_nodes, cache_dir): if elem_size is not None: info = mesh_step(step_path, out_msh, elem_size) mesh = parse_msh(out_msh) return mesh, {"mode": "fixed", "n_nodes": info["n_nodes"], "n_tets": info["n_tets"], "elem_size": info["elem_size"], "cache": "n/a"} info = get_or_mesh(step_path, out_msh, target_nodes=target_nodes, cache_dir=cache_dir) if not info.get("ok", False): raise RuntimeError(f"meshing failed for {step_path!r}: {info.get('notes', '(no notes)')}") mesh = parse_msh(out_msh) return mesh, {"mode": "density-searched", "n_nodes": info["n_nodes"], "n_tets": int(mesh.tets.shape[0]), "elem_size": None, "cache": info.get("cache", "unknown")}
def predict_casting(step_path, out_dir="runs/castings", alloy=None, mold=DEFAULT_MOLD, props_json=None, elem_size=None, target_nodes: int = DEFAULT_TARGET_NODES, screen_shrinkage: bool = True, gravity: tuple = (0, 0, -1), model: CastSolidModel | None = None, weights_dir: str = "weights", ood_json: str | None = None, cache_dir: str = "runs/mesh_cache", device: str | None = None) -> dict: """Mesh `step_path`, predict, and write the result files.
`alloy`/`mold` name rows of `data/properties/` (default EN-GJS-400-15 in green sand); `props_json` replaces both. `elem_size` (mm) meshes at a fixed size instead of searching for `target_nodes`. Pass a loaded `model` to reuse it across calls.
Returns {name, vtu, summary, msh, total_time_s, hotspot_xyz (5 x 3 mm), ood_warnings, n_nodes, mesh_mode, elem_size, cache, recomposition_info, shrinkage}.""" if elem_size is not None and target_nodes != DEFAULT_TARGET_NODES: raise ValueError("predict_casting: give either elem_size or target_nodes, not both") os.makedirs(out_dir, exist_ok=True) name = osp.splitext(osp.basename(step_path))[0] out_msh = osp.join(out_dir, f"{name}.msh")
# Resolve properties before meshing so a bad alloy name fails fast. props = resolve_props(alloy=alloy, mold=mold, props_json=props_json) model = model or CastSolidModel(weights_dir=weights_dir, device=device)
mesh, minfo = _mesh(step_path, out_msh, elem_size, target_nodes, cache_dir) seconds, details = model.predict_with_props(mesh, props) X = details["X"]
warnings = [] ood_json = ood_json or osp.join(weights_dir, "ood_ranges.json") if osp.exists(ood_json): diag = float(np.linalg.norm(mesh.node_xyz.max(0) - mesh.node_xyz.min(0))) warnings = _ood.ood_flags(float(X[0, _VOL_IDX]), diag, float(X[:, _GCOOL_IDX].max()), _ood.load_ranges(ood_json))
shrinkage = None point_data = None if screen_shrinkage: surface_nodes, feed_nodes = _surface_and_feed_nodes(mesh) if surface_nodes.size == 0: logger.warning("predict_casting: no surface nodes on the mesh -- " "shrinkage screening skipped") else: alloy_family, assumed = resolve_alloy_family(alloy, props_json) screen = screen_casting(pos=mesh.node_xyz, tets=mesh.tets, surface_nodes=surface_nodes, t_s=seconds, TL=props["TL"], TS=props["TS"], alloy_family=alloy_family, gravity_vec=gravity, feed_nodes=feed_nodes) shrinkage = _shrinkage_result_for_return(screen) if assumed: shrinkage["alloy_family_assumed"] = True point_data = _shrinkage_point_data(mesh, screen)
vtu = osp.join(out_dir, f"{name}.vtu") write_vtu(vtu, mesh.node_xyz, mesh.tets, seconds, extra_point_data=point_data)
order = np.argsort(seconds)[::-1][:5] hot_xyz = mesh.node_xyz[order] total = float(seconds.max()) info = details["recomposition"] summary = osp.join(out_dir, f"{name}_summary.txt") alloy_label = (f"custom ({props_json})" if props_json is not None else alloy if alloy is not None else DEFAULT_ALLOY) mold_label = mold if props_json is None else "n/a (props_json)" bbox_mm = tuple(round(float(v), 1) for v in mesh.node_xyz.max(0) - mesh.node_xyz.min(0)) elem_label = (f"{minfo['elem_size']:.2f} mm" if minfo["elem_size"] is not None else "n/a (density-searched)") with open(summary, "w") as f: f.write(f"casting: {name}\n") f.write(f"total solidification time: {total:.1f} s\n") f.write(f"alloy: {alloy_label} mold: {mold_label} model: {MODEL_VERSION}\n") f.write(f"mesh: {minfo['mode']} cache: {minfo['cache']} nodes: {minfo['n_nodes']} " f"tets: {minfo['n_tets']} elem_size: {elem_label} bbox_mm: {bbox_mm}\n") line = (f"recomposition: a={info['a']:.4f}, m={info['m']:.4f}, " f"target_unreachable={info['target_unreachable']}, " f"clip_frac={info['clip_frac']:.4f}") if abs(info.get("total_deviation_frac", 0.0)) > 0.001: line += f", total_dev={info['total_deviation_frac'] * 100.0:+.1f}%" f.write(line + "\n") if screen_shrinkage: _write_shrinkage_summary(f, shrinkage) f.write("top hot spots (x,y,z mm : t_solidus s):\n") for xyz_i, i in zip(hot_xyz, order): f.write(f" ({xyz_i[0]:.1f},{xyz_i[1]:.1f},{xyz_i[2]:.1f}) : {seconds[i]:.1f}\n") if warnings: f.write("WARNINGS:\n") for w in warnings: f.write(f" - {w}\n")
return {"name": name, "vtu": vtu, "summary": summary, "msh": out_msh, "total_time_s": total, "hotspot_xyz": hot_xyz, "ood_warnings": warnings, "n_nodes": minfo["n_nodes"], "mesh_mode": minfo["mode"], "elem_size": minfo["elem_size"], "cache": minfo["cache"], "recomposition_info": info, "shrinkage": shrinkage}
def _parse_gravity(s: str) -> tuple: parts = [p.strip() for p in s.split(",")] if len(parts) != 3: raise ValueError(f"--gravity must be 'x,y,z' (3 comma-separated numbers), got {s!r}") vec = tuple(float(p) for p in parts) if all(v == 0.0 for v in vec): raise ValueError(f"--gravity must not be the zero vector (got {s!r})") return vec
def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("step_path") ap.add_argument("--out-dir", default="runs/castings") ap.add_argument("--alloy", default=None, help=f"alloy from data/properties/materials.csv (default {DEFAULT_ALLOY})") ap.add_argument("--mold", default=DEFAULT_MOLD, help=f"mold from data/properties/molds.csv (default {DEFAULT_MOLD})") ap.add_argument("--props", dest="props_json", default=None, help="JSON file with k, rho, cp, L_kJ_kg, TL, TS, Tpour, mold_effusivity " "(replaces --alloy and --mold)") ap.add_argument("--elem-size", type=float, default=None, help="mesh at this fixed element size in mm instead of searching for " f"about {DEFAULT_TARGET_NODES} nodes") ap.add_argument("--gravity", type=_parse_gravity, default=(0, 0, -1), help="gravity direction 'x,y,z' for sinks and feeder placement " "(default 0,0,-1)") ap.add_argument("--no-shrinkage", dest="screen_shrinkage", action="store_false", help="skip the shrinkage screening") ap.add_argument("--weights-dir", default="weights") a = ap.parse_args(argv) r = predict_casting(a.step_path, out_dir=a.out_dir, alloy=a.alloy, mold=a.mold, props_json=a.props_json, elem_size=a.elem_size, screen_shrinkage=a.screen_shrinkage, gravity=a.gravity, weights_dir=a.weights_dir) print(f"{r['name']}: total {r['total_time_s']:.1f}s nodes {r['n_nodes']} -> {r['vtu']}") for w in r["ood_warnings"]: print("WARNING:", w)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Loading the published weight files.
- GNN: one safetensors file with tensors `model.<state_dict key>` and `norm.<key>`; the architecture config (`cfg`) and the container type of each normalization entry are JSON strings in the safetensors metadata.- Gradient-boosted heads: skops files. Before loading, every type a file names is checked against an allowlist (scikit-learn and NumPy only).
Neither format runs code when loaded."""from __future__ import annotations
import jsonimport os
GNN_FORMAT = "foundry-gnn-release/1"
_SKOPS_ALLOWED_PREFIXES = ("sklearn.", "numpy.")
def load_gnn_state(path: str, device="cpu") -> dict: """The `{model, norm, cfg}` dict stored in a GNN safetensors file.""" from safetensors import safe_open with safe_open(path, framework="pt", device="cpu") as f: meta = f.metadata() or {} if meta.get("format") != GNN_FORMAT: raise ValueError(f"{path}: not a {GNN_FORMAT} file " f"(format={meta.get('format')!r})") tensors = {k: f.get_tensor(k) for k in f.keys()} norm_kinds = json.loads(meta["norm_kinds"]) model = {k[len("model."):]: v.to(device) for k, v in tensors.items() if k.startswith("model.")} norm = dict(json.loads(meta["norm_scalars"])) for k, kind in norm_kinds.items(): t = tensors[f"norm.{k}"] norm[k] = t.numpy() if kind == "numpy" else t return {"model": model, "norm": norm, "cfg": json.loads(meta["cfg"])}
def load_gbm(path): """A gradient-boosted head from a skops file, after the type check.""" import skops.io as sio untrusted = sio.get_untrusted_types(file=os.fspath(path)) bad = [t for t in untrusted if not t.startswith(_SKOPS_ALLOWED_PREFIXES)] if bad: raise ValueError(f"{path}: refusing to load unexpected types {bad}") return sio.load(os.fspath(path), trusted=untrusted)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498"""Shrinkage screening on a predicted solidification-time field.
Pure numpy/scipy, working on node positions `pos` (mm), tetrahedra `tets` andthe per-node solidification time `t_s` (s). Four outputs:
- A Niyama-style criterion. With only `t_s` available, the identity grad(T) = -Tdot * grad(t_s) gives Ny = sqrt(|Tdot|) * |grad(t_s)|, and the cooling rate is approximated by the freezing-interval rate (TL - TS) / t_s. The result is a relative ranking within one part, so the risk mask flags its lowest decile rather than applying absolute literature thresholds.- Macro-shrinkage regions: connected groups of the latest-solidifying nodes that no feed source can reach through metal that is still liquid.- Sinks: regions whose highest point (against gravity) is on the free surface, which would draw the surface in rather than void internally.- Feeder suggestions: a surface point above each region and the minimum feeder modulus (1.2 x the region's V/A, Chvorinov's rule)."""import logging
import numpy as npfrom scipy.sparse import csr_matrixfrom scipy.sparse.csgraph import connected_components
logger = logging.getLogger(__name__)
# Volumetric solidification shrinkage per alloy family, in percent. Severity# of a region = shrinkage_pct / 100 * region volume. Grey iron's graphite# expansion offsets its shrinkage, hence 0 (regions are still reported).SHRINKAGE_PCT = { "steel": 2.5, "low_alloy_steel": 2.5, "ductile_iron": 0.75, "grey_iron": 0.0,}
# Guards divisions and square roots without moving any physical value._EPS = 1e-9
def node_gradient(pos: np.ndarray, tets: np.ndarray, field: np.ndarray) -> np.ndarray: """(N, 3) nodal gradient of a P1 field on a tet mesh, in [field units]/mm.
The gradient is constant per tet (solve J g = df with J the tet's edge vectors from vertex 0), then averaged onto the nodes weighted by tet volume. Degenerate tets contribute nothing; isolated nodes get zero.""" pos = np.asarray(pos, dtype=np.float64) tets = np.asarray(tets, dtype=np.int64) field = np.asarray(field, dtype=np.float64) n_nodes = pos.shape[0]
if tets.shape[0] == 0: return np.zeros((n_nodes, 3))
p0 = pos[tets[:, 0]] p1 = pos[tets[:, 1]] p2 = pos[tets[:, 2]] p3 = pos[tets[:, 3]] f0 = field[tets[:, 0]] f1 = field[tets[:, 1]] f2 = field[tets[:, 2]] f3 = field[tets[:, 3]]
e1 = p1 - p0 e2 = p2 - p0 e3 = p3 - p0
jac = np.stack([e1, e2, e3], axis=1) # (M,3,3), rows = edge vectors rhs = np.stack([f1 - f0, f2 - f0, f3 - f0], axis=1) # (M,3)
vol = np.abs(np.einsum('ij,ij->i', e1, np.cross(e2, e3))) / 6.0 # (M,)
grad_tet = np.zeros_like(rhs) nondeg = vol > 0 if nondeg.any(): grad_tet[nondeg] = np.linalg.solve(jac[nondeg], rhs[nondeg, :, None])[..., 0]
node_grad_sum = np.zeros((n_nodes, 3)) node_vol_sum = np.zeros(n_nodes) weighted = grad_tet * vol[:, None] for k in range(4): idx = tets[:, k] np.add.at(node_grad_sum, idx, weighted) np.add.at(node_vol_sum, idx, vol)
return node_grad_sum / np.maximum(node_vol_sum, _EPS)[:, None]
def niyama_proxy(pos: np.ndarray, tets: np.ndarray, t_s: np.ndarray, TL: float, TS: float) -> np.ndarray: """sqrt((TL - TS) / max(t_s, eps)) * |grad(t_s)|, per node.
`TL`, `TS` in deg C, `t_s` in s, `pos` in mm. A relative ranking within one part; see the module docstring.""" t_s = np.asarray(t_s, dtype=np.float64) grad = node_gradient(pos, tets, t_s) grad_mag = np.linalg.norm(grad, axis=1)
t_safe = np.maximum(t_s, _EPS) tdot_proxy = (TL - TS) / t_safe return np.sqrt(np.maximum(tdot_proxy, 0.0)) * grad_mag
def porosity_risk(ny: np.ndarray, pct: float = 10.0) -> np.ndarray: """Boolean mask of the within-part lowest `pct`% Niyama values (`ny <= percentile(ny, pct)`; ties at the threshold are all flagged).""" ny = np.asarray(ny, dtype=np.float64) threshold = np.percentile(ny, pct) return ny <= threshold
# Local vertex-index pairs/triples of a tetrahedron._TET_EDGE_PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]_TET_FACES = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
def _tet_volumes(pos: np.ndarray, tets: np.ndarray) -> np.ndarray: """(M,) unsigned tet volumes in mm^3.""" if tets.shape[0] == 0: return np.zeros(0) p0, p1, p2, p3 = pos[tets[:, 0]], pos[tets[:, 1]], pos[tets[:, 2]], pos[tets[:, 3]] e1, e2, e3 = p1 - p0, p2 - p0, p3 - p0 return np.abs(np.einsum('ij,ij->i', e1, np.cross(e2, e3))) / 6.0
def _induced_components(n_nodes: int, tets: np.ndarray, mask: np.ndarray): """Connected components of the tet-adjacency graph restricted to `mask`.
Returns (n_comp, labels) with labels of shape (n_nodes,): the component id for masked nodes, -1 elsewhere.""" idx = np.flatnonzero(mask) labels_full = np.full(n_nodes, -1, dtype=np.int64) if idx.size == 0: return 0, labels_full
local_of = -np.ones(n_nodes, dtype=np.int64) local_of[idx] = np.arange(idx.size)
rows_list, cols_list = [], [] for a, b in _TET_EDGE_PAIRS: va, vb = tets[:, a], tets[:, b] both = mask[va] & mask[vb] if both.any(): rows_list.append(local_of[va[both]]) cols_list.append(local_of[vb[both]]) n_local = idx.size if rows_list: rows = np.concatenate(rows_list) cols = np.concatenate(cols_list) data = np.ones(rows.shape[0]) graph = csr_matrix((data, (rows, cols)), shape=(n_local, n_local)) else: graph = csr_matrix((n_local, n_local)) n_comp, labels_local = connected_components(graph, directed=False) labels_full[idx] = labels_local return n_comp, labels_full
def _boundary_faces(tets: np.ndarray) -> np.ndarray: """(F, 3) vertex triples of the mesh's outer faces: faces that belong to exactly one tet, in their original per-tet vertex order.""" tets = np.asarray(tets, dtype=np.int64) if tets.shape[0] == 0: return np.zeros((0, 3), dtype=np.int64) face_idx = np.asarray(_TET_FACES, dtype=np.int64) # (4, 3) all_faces = tets[:, face_idx].reshape(-1, 3) # (4*M, 3), original order sorted_faces = np.sort(all_faces, axis=1) _, first_idx, counts = np.unique(sorted_faces, axis=0, return_index=True, return_counts=True) boundary = counts == 1 return all_faces[first_idx[boundary]]
def _region_surface_area(pos: np.ndarray, tets: np.ndarray, nodes: np.ndarray, t_s: np.ndarray, threshold: float, boundary_faces: np.ndarray = None) -> float: """Surface area (mm^2) of a hot region, for its V/A modulus.
The interior part is the iso-surface `t_s == threshold` (the cut that selected the region), built by marching tetrahedra on the continuous field: a tet with 1 or 3 vertices above the threshold contributes a triangle, one with 2 contributes a planar quadrilateral, and crossing points sit at their interpolated position on each edge. A tet counts for this region if any of its vertices is in `nodes`. Outer faces of the mesh are added separately, weighted by the fraction of their 3 vertices in the region. `boundary_faces` can be passed in to avoid recomputing `_boundary_faces(tets)` for every region.""" n_nodes = pos.shape[0] is_member = np.zeros(n_nodes, dtype=bool) is_member[np.asarray(nodes, dtype=np.int64)] = True t_s = np.asarray(t_s, dtype=np.float64) threshold = float(threshold)
area = 0.0 if tets.shape[0] > 0: hot_mask = t_s >= threshold member_per_tet = hot_mask[tets] n_above = member_per_tet.sum(axis=1) mixed = np.flatnonzero((n_above >= 1) & (n_above <= 3)) for ti in mixed: tet = tets[ti] if not is_member[tet].any(): continue # this crossing belongs to a different region verts = pos[tet] vals = t_s[tet] above_local = member_per_tet[ti] k = int(n_above[ti]) if k in (1, 3): odd = int(np.flatnonzero(above_local)[0]) if k == 1 else \ int(np.flatnonzero(~above_local)[0]) others = [i for i in range(4) if i != odd] pts = [] for o in others: frac = (threshold - vals[odd]) / (vals[o] - vals[odd]) pts.append(verts[odd] + frac * (verts[o] - verts[odd])) area += 0.5 * float(np.linalg.norm(np.cross(pts[1] - pts[0], pts[2] - pts[0]))) else: # k == 2 hi = np.flatnonzero(above_local) lo = np.flatnonzero(~above_local)
def _cross_point(h, c, verts=verts, vals=vals): frac = (threshold - vals[h]) / (vals[c] - vals[h]) return verts[h] + frac * (verts[c] - verts[h])
a_pt = _cross_point(hi[0], lo[0]) b_pt = _cross_point(hi[0], lo[1]) c_pt = _cross_point(hi[1], lo[1]) d_pt = _cross_point(hi[1], lo[0]) area += 0.5 * float(np.linalg.norm(np.cross(c_pt - a_pt, d_pt - b_pt)))
if boundary_faces is None: boundary_faces = _boundary_faces(tets) if boundary_faces.shape[0] > 0: # Each outer face counts with the fraction of its 3 vertices in # the region. member_counts = is_member[boundary_faces].sum(axis=1).astype(np.float64) # (F,) frac = member_counts / 3.0 nonzero = frac > 0 if nonzero.any(): v = boundary_faces[nonzero] p0f, p1f, p2f = pos[v[:, 0]], pos[v[:, 1]], pos[v[:, 2]] tri_areas = 0.5 * np.linalg.norm(np.cross(p1f - p0f, p2f - p0f), axis=1) area += float(np.sum(frac[nonzero] * tri_areas)) return area
def hot_regions(pos: np.ndarray, tets: np.ndarray, t_s: np.ndarray, top_frac: float = 0.10) -> list: """Connected groups (via tet adjacency) of the top-`top_frac` latest- solidifying nodes, sorted by `t_max` descending.
Each region is a dict: `nodes` (sorted indices), `centroid` (mm), `volume_mm3`, `t_max`, `region_id` (its index in this list), `hot_threshold` (the percentile cut used) and `sub_resolution` (fewer than 4 nodes, too small for a meaningful V/A modulus). The volume sums, over all tets touching the region, tet volume times the fraction of its vertices that are hot, which converges with mesh refinement.""" top_frac = float(top_frac) if not (0.0 < top_frac <= 1.0): raise ValueError(f"hot_regions: top_frac must be in (0, 1], got {top_frac!r}")
pos = np.asarray(pos, dtype=np.float64) tets = np.asarray(tets, dtype=np.int64) t_s = np.asarray(t_s, dtype=np.float64) n_nodes = pos.shape[0]
if n_nodes == 0 or tets.shape[0] == 0: return []
threshold = np.percentile(t_s, 100.0 * (1.0 - top_frac)) hot_mask = t_s >= threshold if not hot_mask.any(): return []
n_comp, labels = _induced_components(n_nodes, tets, hot_mask)
vol = _tet_volumes(pos, tets) n_hot_per_tet = hot_mask[tets].sum(axis=1) has_hot = n_hot_per_tet > 0 region_vol = np.zeros(n_comp) if has_hot.any(): # any one hot vertex identifies the tet's (unique) component. first_hot_col = np.argmax(hot_mask[tets], axis=1) first_hot_node = tets[np.arange(tets.shape[0]), first_hot_col] comp_of_tet = labels[first_hot_node] weight = vol * (n_hot_per_tet / 4.0) np.add.at(region_vol, comp_of_tet[has_hot], weight[has_hot])
regions = [] for c in range(n_comp): nodes = np.sort(np.flatnonzero(labels == c)) regions.append({ "nodes": nodes, "centroid": pos[nodes].mean(axis=0), "volume_mm3": float(region_vol[c]), "t_max": float(t_s[nodes].max()), }) regions.sort(key=lambda r: r["t_max"], reverse=True) for i, r in enumerate(regions): r["region_id"] = i r["hot_threshold"] = float(threshold) # Below 4 nodes the iso-surface area and the lumped volume no longer # agree, so the V/A modulus is not meaningful. r["sub_resolution"] = len(r["nodes"]) < 4 return regions
def is_fed(region: dict, t_s: np.ndarray, tets: np.ndarray, feed_nodes: np.ndarray, corridor_frac: float = 0.95) -> bool: """Whether a feed source can still reach the region through liquid metal.
True iff some region node and some `feed_nodes` node are connected through nodes with `t_s >= corridor_frac * region["t_max"]` (a corridor that stays liquid until the region itself is nearly solid). Feed nodes are adiabatic-tagged surface nodes, for example a riser face. With no feed nodes every region is unfed, which is the conservative answer. A region with t_max <= 0 is reported unfed.""" t_s = np.asarray(t_s, dtype=np.float64) tets = np.asarray(tets, dtype=np.int64) feed_nodes = np.asarray(feed_nodes, dtype=np.int64) region_nodes = np.asarray(region["nodes"], dtype=np.int64)
if feed_nodes.size == 0: return False if tets.shape[0] == 0: return False region_t_max = float(region["t_max"]) if region_t_max <= 0: logger.debug( "is_fed: region t_max=%.6g <= 0 -- corridor threshold would be " "vacuous (every non-negative t_s qualifies); reporting unfed.", region_t_max) return False
n_nodes = t_s.shape[0] threshold = corridor_frac * region_t_max warm_mask = t_s >= threshold
_, labels = _induced_components(n_nodes, tets, warm_mask)
region_labels = set(int(l) for l in labels[region_nodes] if l >= 0) if not region_labels: return False feed_labels = set(int(l) for l in labels[feed_nodes] if l >= 0) return len(region_labels & feed_labels) > 0
def macro_shrinkage(pos: np.ndarray, tets: np.ndarray, t_s: np.ndarray, feed_nodes: np.ndarray, shrinkage_pct: float) -> list: """The hot regions that are not fed, each with `severity = shrinkage_pct / 100 * volume_mm3`. `region_id` keeps its value from `hot_regions`.""" regions = hot_regions(pos, tets, t_s) out = [] for r in regions: if is_fed(r, t_s, tets, feed_nodes): continue severity = shrinkage_pct / 100.0 * r["volume_mm3"] out.append({**r, "severity": severity}) return out
def top_sinks(regions: list, pos: np.ndarray, surface_nodes: np.ndarray, gravity_vec) -> list: """Regions whose highest node along -gravity is a surface node. Returns `{"region_id", "location" (mm), "volume_mm3"}` for each.""" pos = np.asarray(pos, dtype=np.float64) gravity_vec = np.asarray(gravity_vec, dtype=np.float64) up = -gravity_vec norm = np.linalg.norm(up) if norm > 0: up = up / norm surface_set = set(np.asarray(surface_nodes, dtype=np.int64).tolist())
sinks = [] for r in regions: nodes = np.asarray(r["nodes"], dtype=np.int64) proj = pos[nodes] @ up top_node = int(nodes[np.argmax(proj)]) if top_node in surface_set: sinks.append({ "region_id": r["region_id"], "location": pos[top_node].copy(), "volume_mm3": r["volume_mm3"], }) return sinks
def feeder_recommendations(regions: list, pos: np.ndarray, tets: np.ndarray, surface_nodes: np.ndarray, gravity_vec, t_s: np.ndarray) -> list: """Per region: a feeder `location` and `min_modulus_mm = 1.2 * V/A`.
The location is the surface node closest to the vertical line (along -gravity) through the region's centroid, among surface nodes at or above the centroid (all surface nodes if none are). Sub-resolution regions are skipped. A region with zero volume or area gets a warning and `min_modulus_mm = 0.0`. Raises ValueError if `surface_nodes` is empty.""" pos = np.asarray(pos, dtype=np.float64) tets = np.asarray(tets, dtype=np.int64) t_s = np.asarray(t_s, dtype=np.float64) gravity_vec = np.asarray(gravity_vec, dtype=np.float64) up = -gravity_vec norm = np.linalg.norm(up) if norm > 0: up = up / norm surface_nodes = np.asarray(surface_nodes, dtype=np.int64) if surface_nodes.size == 0: raise ValueError( "feeder_recommendations: surface_nodes is empty -- no candidate " "feeder location exists (a mesh with no free surface is not a " "valid casting)") surface_pos = pos[surface_nodes] boundary_faces = _boundary_faces(tets) # shared by every region
recs = [] n_skipped_sub_resolution = 0 for r in regions: if r.get("sub_resolution", False): n_skipped_sub_resolution += 1 continue nodes = np.asarray(r["nodes"], dtype=np.int64) volume = r["volume_mm3"] threshold = r["hot_threshold"] area = _region_surface_area(pos, tets, nodes, t_s, threshold, boundary_faces=boundary_faces) if area > 0 and volume > 0: region_modulus = volume / area else: logger.warning( "feeder_recommendations: region_id=%s has degenerate " "volume/area (V=%.6g mm^3, A=%.6g mm^2) -- min_modulus_mm is " "not meaningful and is reported as 0.0", r.get("region_id"), volume, area) region_modulus = 0.0
centroid = np.asarray(r["centroid"], dtype=np.float64) rel = surface_pos - centroid axis_comp = rel @ up perp = rel - np.outer(axis_comp, up) perp_dist = np.linalg.norm(perp, axis=1)
above = np.flatnonzero(axis_comp >= 0) candidates = above if above.size > 0 else np.arange(surface_pos.shape[0]) best = candidates[np.argmin(perp_dist[candidates])]
recs.append({ "location": surface_pos[best].copy(), "min_modulus_mm": 1.2 * region_modulus, "region_id": r["region_id"], }) if n_skipped_sub_resolution: logger.info( "feeder_recommendations: skipped %d sub-resolution region(s) (<4 " "nodes) -- V/A modulus is not meaningful at this resolution", n_skipped_sub_resolution) return recs
def screen_casting(pos: np.ndarray, tets: np.ndarray, surface_nodes: np.ndarray, t_s: np.ndarray, TL: float, TS: float, alloy_family: str, gravity_vec=(0, 0, -1), feed_nodes: np.ndarray = None) -> dict: """All four screening outputs for one part.
`alloy_family` must be a key of `SHRINKAGE_PCT`. `surface_nodes` are all surface nodes (for sinks and feeder placement); `feed_nodes` are the nodes that can feed a region (None means none).
Returns {"niyama", "porosity_risk", "niyama_source": "proxy", "macro_shrinkage", "top_sinks", "feeders", "material"}.""" if alloy_family not in SHRINKAGE_PCT: raise KeyError( f"screen_casting: unknown alloy_family {alloy_family!r} -- known " f"families: {sorted(SHRINKAGE_PCT)}" )
pos = np.asarray(pos, dtype=np.float64) tets = np.asarray(tets, dtype=np.int64) surface_nodes = np.asarray(surface_nodes, dtype=np.int64) t_s = np.asarray(t_s, dtype=np.float64) feed_nodes_arr = (np.zeros(0, dtype=np.int64) if feed_nodes is None else np.asarray(feed_nodes, dtype=np.int64))
ny = niyama_proxy(pos, tets, t_s, TL, TS) risk = porosity_risk(ny)
shrinkage_pct = SHRINKAGE_PCT[alloy_family] macro = macro_shrinkage(pos, tets, t_s, feed_nodes_arr, shrinkage_pct) sinks = top_sinks(macro, pos, surface_nodes, gravity_vec) feeders = feeder_recommendations(macro, pos, tets, surface_nodes, gravity_vec, t_s)
return { "niyama": ny, "porosity_risk": risk, "niyama_source": "proxy", "macro_shrinkage": macro, "top_sinks": sinks, "feeders": feeders, "material": {"alloy_family": alloy_family, "shrinkage_pct": shrinkage_pct}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""PyVista helpers for the solidification viewer. Pure/testable: load aprediction VTU and derive the ghost mesh, the still-liquid region above a timethreshold, and the hot-spot points."""import os
import numpy as npimport pyvista as pv
def load_prediction(vtu_path: str) -> pv.UnstructuredGrid: grid = pv.read(vtu_path) for name in ("solidification_time", "hotspot"): if name not in grid.point_data: raise ValueError(f"VTU missing point array '{name}'") return grid
def time_range(grid): t = np.asarray(grid.point_data["solidification_time"]) return float(t.min()), float(t.max())
def liquid_region(grid, tau: float): # cells still liquid at time tau (solidification_time >= tau) return grid.threshold(tau, scalars="solidification_time")
def hotspot_points(grid): mask = np.asarray(grid.point_data["hotspot"]) > 0.5 return pv.PolyData(np.asarray(grid.points)[mask])
def points_above_time(grid, t: float) -> pv.PolyData: """Points whose solidification_time is >= t. Used to thin out the hot-spot cloud with a user-controlled cutoff/threshold slider.""" times = np.asarray(grid.point_data["solidification_time"]) mask = times >= t pts = pv.PolyData(np.asarray(grid.points)[mask]) pts.point_data["solidification_time"] = times[mask] return pts
def solidification_animation(grid, out_path, *, n_frames=40, fps=10, cmap="turbo_r", ghost_opacity=0.15, scalar_bar_args=None, bg="#f7f7f5", window_size=(1280, 720), camera_position=None): """Render an animated GIF of progressive solidification: tau sweeps from tmin to tmax; already-solidified material (t < tau) shows as a low-opacity ghost of the full body, still-liquid material (t >= tau) is opaque and colored by solidification time. Each frame shows the color legend and the current time. Returns out_path. Off-screen; independent of any live view, except that when `camera_position` is given (e.g. captured from a live plotter) it is used verbatim so the GIF renders from that exact viewpoint; otherwise the camera is auto-framed via reset_camera().""" import pyvista as pv tmin, tmax = time_range(grid) taus = np.linspace(tmin, tmax, int(n_frames)) p = pv.Plotter(off_screen=True, window_size=list(window_size)) p.set_background(bg) try: # permanent ghost of the full body (owns the one legend) p.add_mesh(grid, scalars="solidification_time", opacity=ghost_opacity, cmap=cmap, clim=[tmin, tmax], smooth_shading=True, show_scalar_bar=True, scalar_bar_args=dict(scalar_bar_args or {})) p.add_mesh(liquid_region(grid, tmin), scalars="solidification_time", cmap=cmap, clim=[tmin, tmax], smooth_shading=True, name="liquid", show_scalar_bar=False) if camera_position is not None: p.camera_position = camera_position else: p.reset_camera() p.open_gif(out_path, fps=int(fps)) for tau in taus: liq = liquid_region(grid, float(tau)) if liq.n_cells > 0: p.add_mesh(liq, scalars="solidification_time", cmap=cmap, clim=[tmin, tmax], smooth_shading=True, name="liquid", show_scalar_bar=False) else: p.remove_actor("liquid") # fully solidified -> only the ghost p.add_text(f"t = {float(tau):6.1f} s", name="tlabel", position="upper_left", font_size=14, color="black") p.write_frame() except Exception: if os.path.exists(out_path): os.unlink(out_path) # don't leave a truncated/corrupt gif behind raise finally: p.close() return out_path123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561"""Local trame + PyVista web app: upload a STEP casting, run the prediction,and view the solidification field with a time slider (solidified =ghost, liquid = opaque) and a hot-spot toggle. Run: python -m src.webapp
A multi-solid STEP is meshed through the same prep pipeline as the CLI, whichkeeps the largest solid as the casting."""import osimport os.path as osp
import numpy as npimport pyvista as pvfrom trame.app import get_serverfrom trame.ui.vuetify3 import SinglePageWithDrawerLayoutfrom trame.widgets import html, vuetify3from pyvista.trame.ui import plotter_ui
from src import vizfrom src.inference_props import DEFAULT_ALLOY, list_alloys, list_moldsfrom src.predict_casting import predict_casting
DEFAULT_MOLD = "green_sand"
pv.OFF_SCREEN = True
GHOST_OPACITY = 0.15DEFAULT_HOTSPOT_SIZE = 12.0HOTSPOT_CUTOFF_PERCENTILE = 90.0
# --- visual identity -------------------------------------------------------# "Neuralcast" = a neural-network surrogate for a foundry casting process, so# the palette stays in the same molten-metal family as before but is rebuilt# for a light, legible workbench: warm parchment chrome, white control# surfaces, and a near-white VTK stage so the inferno field is what draws the# eye. The one recurring accent is a deeper burnt-orange (readable at text# contrast on white, unlike the original pale version). Wired into vuetify's# theme system so every stock control (slider, checkbox, buttons) inherits it.# The app bar is a deliberate exception: a dark charcoal strip (independent of# the light theme) so the header reads as instrument-panel chrome holding just# the title and a status line, not another content surface.BG_APP = "#f4f2ee" # app chrome background (warm parchment)SURFACE = "#ffffff" # drawer / card surfacesBORDER = "#ddd8cf" # hairline dividersVTK_BG = "#f7f7f5" # 3D viewport background -- near-white so the # colored field is the highest-contrast thing on screenACCENT_MOLTEN = "#c1440e" # burnt-orange -- the one recurring accent (readable on white)TEXT_PRIMARY = "#23262b"TEXT_MUTED = "#6b7078"HEADER_BG = "#1c1a17" # dark charcoal app-bar -- deliberately dark in the light themeHEADER_TEXT = "#f4f2ee"HEADER_TEXT_MUTED = "#b6afa1"FIELD_CMAP = "turbo_r" # reversed turbo (red -> blue): wide, high-contrast gradient # with far more distinguishable steps than a single-hue map, # so small time differences across the field stay legibleHOTSPOT_COLOR = "#0092b8" # deep cyan/teal marker: falls in the middle of turbo's # range but is rendered as small spheres (not a field # color), so it still reads as an overlay/alert
_MONO_STACK = ('"JetBrains Mono", ui-monospace, "SFMono-Regular", ' "Menlo, Consolas, monospace")_COND_STACK = '"Roboto Condensed", "Arial Narrow", sans-serif'
# Scalar bar (legend) for the solidification-time color field: a vertical bar# pinned to the right edge of the viewport, with generous title/label padding# so the title never collides with the tick numbers, and integer tick labels# (fractional seconds add no information at casting scale).SCALAR_BAR_ARGS = dict( title="Solidification Time, s", fmt="%.0f", color="black", bold=True, font_family="arial", vertical=True, position_x=0.91, position_y=0.06, width=0.055, height=0.80, title_font_size=20, label_font_size=16, n_labels=6,)
_CUSTOM_CSS = f""".neuralcast-title {{ display: flex; align-items: center; gap: 10px;}}.neuralcast-title-text {{ font-family: {_COND_STACK}; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; font-size: 1.05rem; color: {HEADER_TEXT};}}.neuralcast-status {{ font-family: {_COND_STACK}; letter-spacing: .08em; text-transform: uppercase; font-size: .7rem; color: {HEADER_TEXT_MUTED}; white-space: nowrap;}}.neuralcast-drawer-content {{ overflow-y: auto;}}.neuralcast-section-label {{ font-family: {_COND_STACK}; letter-spacing: .12em; text-transform: uppercase; font-size: .7rem; color: {TEXT_MUTED}; margin-bottom: 10px; flex: none;}}.neuralcast-section {{ margin-bottom: 4px;}}.neuralcast-section + .neuralcast-section {{ border-top: 1px solid {BORDER}; padding-top: 20px; margin-top: 20px;}}.neuralcast-tau-badge {{ display: inline-block; font-family: {_MONO_STACK}; font-size: .75rem; color: {ACCENT_MOLTEN}; background: {BG_APP}; border: 1px solid {BORDER}; border-radius: 4px; padding: 3px 10px; white-space: nowrap;}}.neuralcast-summary-box {{ min-height: 0;}}.neuralcast-summary-box .v-input {{ flex: 1 1 auto; min-height: 0;}}.neuralcast-summary-box .v-field__input,.neuralcast-summary-box textarea {{ font-family: {_MONO_STACK} !important; font-size: .78rem; line-height: 1.5; color: {TEXT_PRIMARY};}}.neuralcast-footer-text {{ width: 100%; text-align: center; font-family: {_COND_STACK}; letter-spacing: .06em; font-size: .72rem; color: {TEXT_MUTED};}}"""
def summary_text(result: dict, alloy: str = None, mold: str = None) -> str: lines = [f"casting: {result['name']}", f"total solidification time: {result['total_time_s']:.1f} s", f"nodes: {result['n_nodes']}"] if alloy is not None or mold is not None: cond_parts = [] if alloy is not None: cond_parts.append(f"alloy: {alloy}") if mold is not None: cond_parts.append(f"mold: {mold}") lines.append(" " + ", ".join(cond_parts)) lines.append("top hot spots (x,y,z mm):") for xyz in result["hotspot_xyz"]: lines.append(f" ({xyz[0]:.1f}, {xyz[1]:.1f}, {xyz[2]:.1f})") if result.get("ood_warnings"): lines.append("WARNINGS:") lines += [f" - {w}" for w in result["ood_warnings"]] return "\n".join(lines)
INITIAL_SUMMARY = "(upload a STEP file)"
def _run_prediction(step_path, out_dir, alloy, mold): """Thin wrapper around `predict_casting` forwarding alloy/mold conditioning.
Extracted so the upload handler's predict call is unit-testable without driving the full trame upload flow (module-level lookup of `predict_casting` so tests can monkeypatch `src.webapp.predict_casting`). """ return predict_casting(step_path, out_dir=out_dir, alloy=alloy, mold=mold)
def _rebuild_hotspots(app): """(Re)build the hot-spot point actor from the current cutoff/size state. Called on load and whenever the size or cutoff slider moves.""" plotter, server = app["plotter"], app["server"] state, ctrl = server.state, server.controller if app["grid"] is None: return pts = viz.points_above_time(app["grid"], float(state.hotspot_cutoff)) actor = plotter.add_mesh(pts, color=HOTSPOT_COLOR, point_size=float(state.hotspot_size), name="hotspots", render_points_as_spheres=True) actor.SetVisibility(bool(state.show_hotspots)) app["hotspot_actor"] = actor ctrl.view_update()
def _remove_scalar_bar(plotter): """Drop any existing scalar bar(s), regardless of how many are present. Guarded because pyvista raises if none exist (or if a title is required with more than one) -- callers just want a clean slate either way.""" try: plotter.remove_scalar_bar() except Exception: pass # Belt-and-suspenders: clear() takes the whole registry in one shot, in # case remove_scalar_bar() above only got one of several. try: plotter.scalar_bars.clear() except Exception: pass
def _process_upload(app, step_path, alloy, mold): """Core upload logic, extracted from the `uploaded_file` state-change handler so it is testable without a browser/file-upload round trip: run the prediction and render it, keeping the UI alive on failure.""" server = app["server"] state = server.state plotter = app["plotter"] out_dir = "runs/castings" try: result = _run_prediction(step_path, out_dir, alloy, mold) grid = viz.load_prediction(result["vtu"]) app["name"] = result["name"] render_prediction(app, grid, summary_text(result, alloy=alloy, mold=mold)) except Exception as e: # keep the UI alive on bad/unmeshable STEP plotter.clear_actors() _remove_scalar_bar(plotter) app["grid"] = None app["hotspot_actor"] = None state.loaded = False state.summary = f"Prediction failed for {osp.basename(step_path)}:\n{e}"
def render_prediction(app, grid, summary): plotter, server = app["plotter"], app["server"] state, ctrl = server.state, server.controller plotter.clear_actors() _remove_scalar_bar(plotter) tmin, tmax = viz.time_range(grid) app["grid"] = grid # The "ghost" actor is the single, permanent owner of the scalar bar/legend: # it is added once here and never touched again by the tau slider, so the # legend persists across playback without being re-added or dropped. The # "liquid" actor (re-added on every tau change) must NEVER own a scalar bar, # or scrubbing the slider would repeatedly add/replace it. plotter.add_mesh(grid, scalars="solidification_time", opacity=GHOST_OPACITY, cmap=FIELD_CMAP, name="ghost", clim=[tmin, tmax], smooth_shading=True, show_scalar_bar=True, scalar_bar_args=SCALAR_BAR_ARGS) plotter.add_mesh(viz.liquid_region(grid, tmin), scalars="solidification_time", cmap=FIELD_CMAP, name="liquid", clim=[tmin, tmax], smooth_shading=True, show_scalar_bar=False) state.tmin, state.tmax, state.tau = tmin, tmax, tmin times = np.asarray(grid.point_data["solidification_time"]) state.hotspot_cutoff = float(np.percentile(times, HOTSPOT_CUTOFF_PERCENTILE)) _rebuild_hotspots(app) state.anim_ready = False state.anim_uri = "" state.summary, state.loaded = summary, True plotter.reset_camera() ctrl.view_update()
def build_app(server=None): if server is None: server = get_server(client_type="vue3") state, ctrl = server.state, server.controller plotter = pv.Plotter() plotter.set_background(VTK_BG) app = {"server": server, "plotter": plotter, "grid": None, "hotspot_actor": None, "name": "casting"} server.app = app # exposes the app dict for tests / headless callers that # need render_prediction()/clear_casting() without the UI
state.trame__title = "Neuralcast Viewer"
# Custom light vuetify theme (molten-metal accent) applied through # Vuetify's own theme system, so every stock control (slider, checkbox, # buttons) picks up the palette automatically instead of one-off color # props. vuetify_config = { "theme": { "defaultTheme": "neuralcastLight", "themes": { "neuralcastLight": { "dark": False, "colors": { "background": BG_APP, "surface": SURFACE, "primary": ACCENT_MOLTEN, "secondary": TEXT_MUTED, "on-background": TEXT_PRIMARY, "on-surface": TEXT_PRIMARY, }, }, }, }, } for k, v in dict(tau=0.0, tmin=0.0, tmax=1.0, show_hotspots=False, summary=INITIAL_SUMMARY, loaded=False, uploaded_file=None, loading=False, hotspot_size=DEFAULT_HOTSPOT_SIZE, hotspot_cutoff=0.0, animating=False, anim_ready=False, anim_uri="", anim_name="solidification.gif", alloy=DEFAULT_ALLOY, mold=DEFAULT_MOLD, alloy_options=list_alloys(), mold_options=list_molds(), ).items(): state.setdefault(k, v)
@state.change("tau") def _on_tau(tau, **kwargs): if app["grid"] is None: return # show_scalar_bar=False: the "ghost" actor owns the one legend (see # render_prediction); re-adding it here would duplicate/replace it on # every slider tick. liq = viz.liquid_region(app["grid"], tau) if liq.n_cells > 0: plotter.add_mesh(liq, scalars="solidification_time", cmap=FIELD_CMAP, name="liquid", smooth_shading=True, clim=[state.tmin, state.tmax], show_scalar_bar=False) else: plotter.remove_actor("liquid") ctrl.view_update()
@state.change("show_hotspots") def _on_hot(show_hotspots, **kwargs): if app["hotspot_actor"] is not None: app["hotspot_actor"].SetVisibility(bool(show_hotspots)) ctrl.view_update()
@state.change("hotspot_cutoff", "hotspot_size") def _on_hotspot_controls(**kwargs): _rebuild_hotspots(app)
@state.change("uploaded_file") def _on_upload(uploaded_file, **kwargs): if not uploaded_file: return f = uploaded_file[0] if isinstance(uploaded_file, list) else uploaded_file out_dir = "runs/castings" os.makedirs(out_dir, exist_ok=True) step_path = osp.join(out_dir, f.get("name", "part.step")) with open(step_path, "wb") as fh: fh.write(f["content"]) state.loading = True state.flush() try: _process_upload(app, step_path, state.alloy, state.mold) finally: state.loading = False ctrl.view_update()
def clear_casting(): """Drop the loaded casting and return to a ready-for-upload state.""" plotter.clear_actors() _remove_scalar_bar(plotter) app["grid"] = None app["hotspot_actor"] = None state.loaded = False state.summary = INITIAL_SUMMARY state.uploaded_file = None state.tau, state.tmin, state.tmax = 0.0, 0.0, 1.0 state.show_hotspots = False state.anim_ready = False state.anim_uri = "" state.animating = False ctrl.view_update()
# Exposed on the controller so tests (and any future non-UI caller) can # invoke the same clear logic the "Clear" button uses. ctrl.clear_casting = clear_casting
def generate_animation(): """Render the solidification GIF for the loaded casting and expose it to the browser as a base64 data URI (preview + download). Blocking, like the upload prediction -- fine for this local single-user app.""" if app["grid"] is None: return state.animating = True state.flush() try: out_dir = "runs/castings" os.makedirs(out_dir, exist_ok=True) gif_path = osp.join(out_dir, f"{app['name']}_solidification.gif") viz.solidification_animation(app["grid"], gif_path, cmap=FIELD_CMAP, ghost_opacity=GHOST_OPACITY, scalar_bar_args=SCALAR_BAR_ARGS, bg=VTK_BG, camera_position=plotter.camera_position) import base64 with open(gif_path, "rb") as fh: b64 = base64.b64encode(fh.read()).decode("ascii") state.anim_uri = f"data:image/gif;base64,{b64}" state.anim_name = f"{app['name']}_solidification.gif" state.anim_ready = True except Exception as e: state.anim_ready = False state.summary = f"Animation failed:\n{e}" finally: state.animating = False ctrl.view_update() ctrl.generate_animation = generate_animation
with SinglePageWithDrawerLayout(server, vuetify_config=vuetify_config, width=360) as layout: html.Style(_CUSTOM_CSS)
# The nav-icon toggles the drawer, but the drawer is `permanent` (it # stays open as the fixed left control panel), so the toggle has no # visible effect -- hide it rather than show a button that does nothing. layout.icon.hide()
# Dark, compact app-bar: it holds only the title and a status line, so # it is styled as an instrument-panel strip distinct from the light # control surfaces below it, and kept slim since it carries no controls. layout.toolbar.color = HEADER_BG layout.toolbar.density = "compact" layout.toolbar.flat = True
layout.title.set_text( '<div class="neuralcast-title">' '<span class="neuralcast-title-text">Neuralcast Viewer</span>' "</div>" ) with layout.toolbar: vuetify3.VSpacer() html.Div( "{{ loading ? 'Predicting…' : (loaded ? 'Prediction loaded' " ": 'Awaiting upload') }}", classes="neuralcast-status mr-2", ) # Thin indeterminate progress bar pinned to the bottom edge of the # header -- visible only while a prediction is running, so the user # can see the model is working during the blocking STEP -> VTU call. vuetify3.VProgressLinear( indeterminate=True, absolute=True, location="bottom", height=3, color=ACCENT_MOLTEN, v_show=("loading",), )
with layout.drawer: with html.Div(classes="d-flex flex-column fill-height pa-4 " "neuralcast-drawer-content"): with html.Div(classes="neuralcast-section"): html.Div("Upload", classes="neuralcast-section-label") vuetify3.VSelect(v_model=("alloy",), items=("alloy_options",), label="Alloy", density="compact", variant="outlined", hide_details=True, classes="mb-2") vuetify3.VSelect(v_model=("mold",), items=("mold_options",), label="Mold system", density="compact", variant="outlined", hide_details=True, classes="mb-2") vuetify3.VFileInput(v_model=("uploaded_file", None), label="STEP file", prepend_inner_icon="mdi-file-upload-outline", accept=".step,.stp,.STEP,.STP", density="compact", variant="outlined", hide_details=True) vuetify3.VBtn("Clear", click=clear_casting, variant="text", size="small", color="secondary", disabled=("!loaded",), classes="mt-2", block=True)
with html.Div(classes="neuralcast-section"): html.Div("Playback", classes="neuralcast-section-label") vuetify3.VSlider(v_model=("tau",), min=("tmin",), max=("tmax",), label="time (s)", hide_details=True, disabled=("!loaded",), thumb_label=True) html.Div( "{{ Number(tau).toFixed(1) }} / {{ Number(tmax).toFixed(1) }} s", classes="neuralcast-tau-badge mt-1", )
with html.Div(classes="neuralcast-section"): html.Div("Hot Spots", classes="neuralcast-section-label") vuetify3.VCheckbox(v_model=("show_hotspots",), label="show hot spots", hide_details=True, disabled=("!loaded",)) vuetify3.VSlider(v_model=("hotspot_size",), min=2, max=40, step=1, label="size", hide_details=True, disabled=("!loaded",), thumb_label=True, classes="mt-4") vuetify3.VSlider(v_model=("hotspot_cutoff",), min=("tmin",), max=("tmax",), label="cutoff (s)", hide_details=True, disabled=("!loaded",), thumb_label=True, classes="mt-2")
with html.Div(classes="neuralcast-section"): html.Div("Animation", classes="neuralcast-section-label") vuetify3.VBtn("Generate GIF", click=generate_animation, variant="tonal", size="small", color="primary", disabled=("!loaded || animating",), block=True, loading=("animating",)) vuetify3.VProgressLinear(indeterminate=True, height=3, color=ACCENT_MOLTEN, v_show=("animating",), classes="mt-2") html.Img(src=("anim_uri",), v_show=("anim_ready",), style="max-width:100%; margin-top:10px; " f"border:1px solid {BORDER}; border-radius:4px;") html.A("Download GIF", href=("anim_uri",), download=("anim_name",), v_show=("anim_ready",), style=f"display:block; margin-top:8px; color:{ACCENT_MOLTEN}; " "font-size:.8rem; text-decoration:underline;")
with html.Div(classes="neuralcast-section flex-grow-1 d-flex " "flex-column neuralcast-summary-box"): html.Div("Summary", classes="neuralcast-section-label") vuetify3.VTextarea(v_model=("summary",), readonly=True, variant="outlined", density="compact", hide_details=True, no_resize=True, classes="flex-grow-1")
with layout.content: with vuetify3.VContainer(fluid=True, classes="fill-height pa-0"): # add_menu=True: keep pyvista's default view-toolbar overlay -- # it gives reset-camera / view-axis / screenshot controls that # users want when inspecting the casting. # mode="server": render server-side (VTK on the Python process, # frames streamed to the browser) rather than client-side # (geometry shipped to the browser and rendered there). This # keeps the server-side VTK camera in sync with the user's # mouse rotations/pans/zooms, so generate_animation() below can # read plotter.camera_position and reuse the exact view for # the GIF -- with client-side rendering the server-side camera # would stay frozen regardless of what the user sees. view = plotter_ui(plotter, add_menu=True, mode="server") ctrl.view_update = view.update
# Replace trame's default footer ("Powered by trame" / Kitware credit) # with our own. layout.footer.clear() with layout.footer: html.Div("© 2026 Eugen Miknevic", classes="neuralcast-footer-text")
# NOTE (deviation from brief): trame's `state.to_dict()` only reflects state # that has been *flushed*, and flushing is a no-op until the state is marked # `ready()` (normally done when a client connects, i.e. inside `.start()`). # Since `build_app()` must be unit-constructible without starting the server, # we mark the state ready here so the initial `setdefault(...)` values are # visible via `to_dict()`/attribute access immediately after construction. # This performs no networking (no client is connected yet) and is idempotent # (a later real `.start()` calling `ready()` again is a no-op). state.ready()
return server
def main(): build_app().start(port=8080)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Shared pytest fixtures: a minimal gmsh-2.2 mesh for unit tests.
The mesh is a unit-ish tetrahedron-based shape with 5 nodes: - one internal-ish apex, 4 base nodes forming two tets - two boundary triangles tagged 'Cooling', one tagged 'Adiabatic'Coordinates are in mm."""import textwrapimport pytest
# node ids 1..5 ; coords in mmMINI_MSH = textwrap.dedent("""\ $MeshFormat 2.2 0 8 $EndMeshFormat $PhysicalNames 3 2 1 "Adiabatic" 2 2 "Cooling" 3 3 "Volume" $EndPhysicalNames $Nodes 5 1 0 0 0 2 10 0 0 3 0 10 0 4 0 0 10 5 3 3 3 $EndNodes $Elements 4 1 2 2 2 1 1 2 3 2 2 2 2 1 1 2 4 3 2 2 1 1 2 3 4 4 4 2 3 1 1 2 3 4 $EndElements """)# Element lines: "id type ntags phys geom n1 n2 n3[ n4]"# el1: triangle (type 2), phys 2 = Cooling, nodes 1,2,3# el2: triangle, phys 2 = Cooling, nodes 1,2,4# el3: triangle, phys 1 = Adiabatic, nodes 2,3,4# el4: tetrahedron (type 4), phys 3 = Volume, nodes 1,2,3,4
@pytest.fixturedef mini_msh_file(tmp_path): p = tmp_path / "MINI_00.msh" p.write_text(MINI_MSH) return str(p)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import numpy as npimport pytest
from src.features import FEATURE_NAMES, alloy_g_vector, node_featuresfrom src.msh_parse import parse_msh
MOLD_EFF = 1018.0
def test_shapes_and_order(mini_msh_file): mesh = parse_msh(mini_msh_file) f = node_features(mesh, MOLD_EFF) assert f["X"].shape == (5, len(FEATURE_NAMES)) == (5, 15) assert f["X"].dtype == np.float32 assert f["pos"].shape == (5, 3) assert f["mesh_edges"].shape == (6, 2) # one tet -> 6 edges
def test_flags_and_boundary_channels(mini_msh_file): X = node_features(parse_msh(mini_msh_file), MOLD_EFF)["X"] col = {n: X[:, i] for i, n in enumerate(FEATURE_NAMES)} # nodes 0..3 lie on the tagged surface, node 4 (index 4) is not in any tet assert col["is_cooling"][:4].tolist() == [1, 1, 1, 1] assert col["is_adiabatic"].sum() == 0 # adiabatic nodes are also cooling here assert col["is_interior"][4] == 1 np.testing.assert_allclose(col["boundary_extraction"][:4], MOLD_EFF) assert col["boundary_extraction"][4] == 0 assert np.all(col["boundary_heat_input"] == 0)
def test_global_columns_are_constant(mini_msh_file): X = node_features(parse_msh(mini_msh_file), MOLD_EFF)["X"] for name in ("volume_mm3", "surface_area_mm2", "cooling_area_frac"): c = X[:, FEATURE_NAMES.index(name)] assert np.all(c == c[0]) assert X[0, FEATURE_NAMES.index("volume_mm3")] == pytest.approx(1000.0 / 6.0)
def test_translation_invariance(mini_msh_file): mesh = parse_msh(mini_msh_file) a = node_features(mesh, MOLD_EFF)["X"] mesh.node_xyz = mesh.node_xyz + np.array([100.0, -50.0, 7.0]) b = node_features(mesh, MOLD_EFF)["X"] np.testing.assert_allclose(a, b, rtol=1e-5, atol=1e-4)
def test_g_vector(): props = {"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0, "TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1250.0} g = alloy_g_vector(props) assert g.shape == (5,) assert g[0] == pytest.approx(515.0 * 140.0 / 220000.0) # Stefan number assert g[1] == pytest.approx(0.04) and g[3] == pytest.approx(0.1) assert g[2] == pytest.approx(32.9 / (6800.0 * 515.0) / 1e-5) assert g[4] == pytest.approx(1.0)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import numpy as npimport pytest
from src import gbm_headsfrom src.features import FEATURE_NAMES
PROPS = {"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0, "TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1018.0}
def _X(n=10, vol=8000.0, area=2400.0, n_adiab=0): X = np.zeros((n, len(FEATURE_NAMES)), np.float32) X[:, FEATURE_NAMES.index("volume_mm3")] = vol X[:, FEATURE_NAMES.index("surface_area_mm2")] = area X[:6, FEATURE_NAMES.index("is_cooling")] = 1 X[6:6 + n_adiab, FEATURE_NAMES.index("is_adiabatic")] = 1 return X
def test_total_row_layout(): row = gbm_heads.total_row(PROPS, _X()) assert row.shape == (gbm_heads.N_TOTAL_FEATURES,) assert row[:7].tolist() == [32.9, 6800.0, 515.0, 220.0, 1160.0, 1120.0, 1260.0] assert row[7] == pytest.approx(8000.0 / 2400.0) assert row[8] == 1018.0 assert row[9:].tolist() == [1, 0, 0, 0, 0, 0, 0]
def test_spread_row_appends_adiabatic_fraction(): X = _X(n_adiab=2) row = gbm_heads.spread_row(gbm_heads.total_row(PROPS, X), X) assert row.shape == (gbm_heads.N_SPREAD_FEATURES,) assert row[-1] == pytest.approx(2 / 8)
class _Stub: def __init__(self, value, n): self.value, self.n_features_in_ = value, n
def predict(self, x): return np.full(len(x), self.value)
def test_predictions_are_expm1_of_log_output(): row = np.zeros(16) assert gbm_heads.predict_total_seconds(_Stub(np.log1p(500.0), 16), row) == pytest.approx(500.0) assert gbm_heads.predict_spread_seconds(_Stub(-5.0, 17), np.zeros(17)) == 0.0 with pytest.raises(ValueError): gbm_heads.predict_total_seconds(_Stub(-1.0, 16), row)
def test_check_head_rejects_wrong_width(): gbm_heads.check_head(_Stub(0.0, 16), 16, "total-time") with pytest.raises(ValueError): gbm_heads.check_head(_Stub(0.0, 9), 16, "total-time")123456789101112131415161718192021222324252627282930313233343536import numpy as npfrom src.geometry import (triangle_areas, total_area, mesh_volume, nearest_distance, boundary_node_mask)
def test_triangle_area_right_triangle(): xyz = np.array([[0, 0, 0], [4, 0, 0], [0, 3, 0]], float) tri = np.array([[0, 1, 2]]) np.testing.assert_allclose(triangle_areas(xyz, tri), [6.0]) # 0.5*4*3 np.testing.assert_allclose(total_area(xyz, tri), 6.0)
def test_tet_volume_unit(): # tetrahedron with legs 3,3,3 along axes from origin -> vol = 3^3/6 = 4.5 xyz = np.array([[0, 0, 0], [3, 0, 0], [0, 3, 0], [0, 0, 3]], float) tets = np.array([[0, 1, 2, 3]]) np.testing.assert_allclose(mesh_volume(xyz, tets), 4.5)
def test_nearest_distance(): pts = np.array([[0, 0, 0], [10, 0, 0]], float) tgt = np.array([[0, 0, 0], [1, 0, 0]], float) np.testing.assert_allclose(nearest_distance(pts, tgt), [0.0, 9.0])
def test_nearest_distance_empty_targets(): pts = np.array([[0, 0, 0]], float) tgt = np.empty((0, 3), float) d = nearest_distance(pts, tgt) assert np.isinf(d).all()
def test_boundary_node_mask(): tri = np.array([[0, 1, 2], [1, 2, 3]]) m = boundary_node_mask(5, tri) np.testing.assert_array_equal(m, [True, True, True, True, False])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336import logging
import numpy as npimport pytestfrom src.hybrid import hybrid_field_affine, hybrid_field_max_anchor, hybrid_field_soft
def test_hybrid_affine_spread_match(): # gnn std is exactly 10 (two points, mean 10, deviations -+10) gnn = np.array([0.0, 20.0]) total = 1000.0 # large enough that nothing clips pred, info = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995) assert info["a"] == 2.0 np.testing.assert_allclose(np.std(pred), 20.0, atol=1e-9) assert info["clip_frac"] == 0.0
def test_hybrid_affine_total_anchor(): gnn = np.array([0.0, 20.0]) total = 1000.0 # large enough that nothing clips pred, info = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995) assert np.quantile(pred, 0.995) == pytest.approx(total, abs=1e-9) assert info["clip_frac"] == 0.0
def test_hybrid_affine_preserves_ranking(): gnn = np.array([3.0, 1.0, 9.0, 5.0]) total = 1000.0 pred, info = hybrid_field_affine(gnn, total, std_seconds=5.0) assert info["a"] > 0.0 assert list(np.argsort(pred)) == list(np.argsort(gnn))
def test_hybrid_affine_clamp_high(): # gnn std is 10; std_seconds=100 -> a_raw=10.0, clamped down to the a_clamp # ceiling 5.0. No clipping occurs at a=5.0 here (total=1000 is large), so # this exercises the closed-form path's own clamp handling. gnn = np.array([0.0, 20.0]) total = 1000.0 pred, info = hybrid_field_affine(gnn, total, std_seconds=100.0) assert info["a"] == 5.0 assert info["a_clamped"] is True
def test_hybrid_affine_degenerate_fallback(caplog): gnn = np.array([5.0, 5.0, 5.0]) total = 100.0 with caplog.at_level(logging.WARNING): pred, info = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995) expected = hybrid_field_max_anchor(gnn, total, q=0.995) np.testing.assert_allclose(pred, expected) assert info["degenerate_fallback"] is True assert any("degenerate" in rec.message.lower() for rec in caplog.records)
def test_hybrid_affine_clip_negative(): # gnn std is 50; the naive (pre-amendment) closed form a=std_seconds/s=1.0 # already clips the low node (raw would be [-89.5, 10.5]), so the # clip-aware solver kicks in. With only 2 nodes the post-clip std is capped # well below 50 everywhere in the clamp range (max achievable is at # a=5.0), so this lands on the a_clamp ceiling. gnn = np.array([0.0, 100.0]) total = 10.0 pred, info = hybrid_field_affine(gnn, total, std_seconds=50.0) np.testing.assert_allclose(pred, [0.0, 12.5]) assert info["a"] == 5.0 assert info["a_clamped"] is True assert info["clip_frac"] == pytest.approx(0.5)
def test_hybrid_affine_heavy_clip_achievable(): # Real fields sometimes need heavy scaling to hit the spread head's # target; a closed form that ignores clipping # entirely, so its implied `a` can leave the delivered std far short of # the target. Construct such a case (right-skewed field; the naive # closed-form `a` clips ~30% of nodes) and confirm the clip-aware solve # still lands on-target. g = np.random.default_rng(1).exponential(5.0, size=200) s = np.std(g) total = 8.0 target = 0.3 * s
# sanity: the pre-amendment closed form (a = target/s, unclamped) clips # ~30% of nodes here -- this is the regime the amendment targets. a_naive = target / s centered_naive = a_naive * (g - g.mean()) m_naive = total - np.quantile(centered_naive, 0.995) naive_clip_frac = float((centered_naive + m_naive < 0.0).mean()) assert 0.25 <= naive_clip_frac <= 0.35
pred, info = hybrid_field_affine(g, total, target) assert info["a_clamped"] is False assert np.std(pred) == pytest.approx(target, rel=1e-3)
def test_hybrid_affine_unachievable_due_to_clipping(): # std_seconds=8.0 exceeds this field's interior PEAK (f rises past # a_clipstart to a peak around a~1.78, std~3.82, then falls -- it never # reaches 8.0 anywhere in the clamp range). The unreachable case must pick the scanned point CLOSEST to # the target (here, at/near the peak) rather than blindly clamping to # a_clamp[1]=5.0 -- clamping to 5.0 would give a worse fit (std~3.45, # clip_frac 0.7) than the peak (std~3.82, clip_frac 0.4). gnn = np.arange(10.0) total = 10.5 pred, info = hybrid_field_affine(gnn, total, std_seconds=8.0) assert info["a"] != 5.0 # must NOT blindly clamp to the ceiling assert info["a_clamped"] is True achieved = np.std(pred) assert achieved == pytest.approx(3.816200508029165, rel=1e-6) assert achieved < 8.0 # the peak (this test's outcome) beats the naive hi=5.0 clamp on fit: at_hi = np.clip(5.0 * (gnn - gnn.mean() - np.quantile(gnn - gnn.mean(), 0.995)) + total, 0.0, None) assert abs(achieved - 8.0) < abs(np.std(at_hi) - 8.0)
def test_hybrid_affine_no_clip_matches_pre_amendment_closed_form(): # Invariant: when nothing clips at the closed-form solution, the amended # (clip-aware) function must reproduce the pre-amendment closed form # exactly (it takes it as a fast path; bisection is never invoked). def pre_amendment_closed_form(gnn_seconds, total_seconds, std_seconds, q=0.995, a_clamp=(0.3, 5.0)): g = np.asarray(gnn_seconds, dtype=np.float64) s = float(np.std(g)) a_raw = float(std_seconds) / s a = float(np.clip(a_raw, a_clamp[0], a_clamp[1])) centered = a * (g - g.mean()) m = float(total_seconds) - float(np.quantile(centered, q)) out = centered + m return np.clip(out, 0.0, None), a
gnn = np.array([3.0, 1.0, 9.0, 5.0]) total = 1000.0 std_seconds = 5.0 pred_new, info_new = hybrid_field_affine(gnn, total, std_seconds) pred_old, a_old = pre_amendment_closed_form(gnn, total, std_seconds) assert info_new["a_clamped"] is False assert info_new["a"] == pytest.approx(a_old, rel=1e-6) np.testing.assert_allclose(pred_new, pred_old, rtol=1e-6)
# --------------------------------------------------------------------------- ## hybrid_field_soft: weighted two-target soft recomposition# --------------------------------------------------------------------------- #def _squeezed_case(): # A field with a small (3%) group of low-value outlier nodes and a tight # high-value cluster: the affine solve's hard quantile-anchor pins the # top near `total`, so scaling enough to hit a large `std_seconds` clips # the low outliers hard -- `a_clamped` fires (the two-target problem is # unreachable via a pure affine map). Verified interactively: at these # exact parameters the affine solve lands short of the std target # (std ~169.8 vs target ~330.1, clip_frac 0.03, a_clamped True) while the # soft solve's default-weight optimum (~203.2) is strictly closer, by # trading a ~20% total-anchor deviation for less clipping. rng = np.random.default_rng(7) n = 200 n_low = int(0.03 * n) n_high = n - n_low high_vals = 1000.0 + rng.normal(0.0, 2.0, n_high) low_vals = rng.uniform(0.0, 50.0, n_low) g = np.concatenate([high_vals, low_vals]) total = 1000.0 target = 2.0 * float(np.std(g)) return g, total, target
def test_hybrid_soft_exact_degeneration_matches_affine(): # No-clip case (from test_hybrid_affine_spread_match/total_anchor): the # affine solve already hits both targets essentially exactly, so the soft # solve must return that seed unchanged. gnn = np.array([0.0, 20.0]) total = 1000.0 pred_affine, info_affine = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995) pred_soft, info_soft = hybrid_field_soft(gnn, total, std_seconds=20.0, q=0.995) np.testing.assert_allclose(pred_soft, pred_affine, rtol=1e-9) assert abs(info_soft["total_deviation_frac"]) < 1e-6 assert info_soft["degenerate_fallback"] is False
def test_hybrid_soft_trade_off_engages_on_squeezed_case(): g, total, target = _squeezed_case() pred_affine, info_affine = hybrid_field_affine(g, total, target) assert info_affine["a_clamped"] is True # affine truly cannot reach std_t
pred_soft, info_soft = hybrid_field_soft(g, total, target) d_affine = abs(np.std(pred_affine) - target) d_soft = abs(np.std(pred_soft) - target) assert d_soft < d_affine # soft's std is strictly closer to the target assert info_soft["total_deviation_frac"] > 0 # the top rose above total
def test_hybrid_soft_weight_monotonicity_on_squeezed_case(): g, total, target = _squeezed_case() pred_hi, info_hi = hybrid_field_soft(g, total, target, w_total=100.0, w_std=1.0) pred_lo, info_lo = hybrid_field_soft(g, total, target, w_total=0.01, w_std=1.0) assert abs(info_hi["total_deviation_frac"]) <= abs(info_lo["total_deviation_frac"]) assert np.std(pred_lo) >= np.std(pred_hi)
def test_hybrid_soft_determinism(): g, total, target = _squeezed_case() pred1, info1 = hybrid_field_soft(g, total, target) pred2, info2 = hybrid_field_soft(g, total, target) np.testing.assert_array_equal(pred1, pred2) assert info1 == info2
def test_hybrid_soft_degenerate_flat_field_falls_back(caplog): gnn = np.array([5.0, 5.0, 5.0]) total = 100.0 with caplog.at_level(logging.WARNING): pred, info = hybrid_field_soft(gnn, total, std_seconds=20.0, q=0.995) expected = hybrid_field_max_anchor(gnn, total, q=0.995) np.testing.assert_allclose(pred, expected) assert info["degenerate_fallback"] is True assert any("degenerate" in rec.message.lower() for rec in caplog.records)
# --------------------------------------------------------------------------- ## Edge cases: the a_clamp[0] <= 0 guard and degeneration to the affine solve# at a realistic scale.# --------------------------------------------------------------------------- #
def test_hybrid_soft_realistic_scale_exact_degeneration_matches_affine(): # The exact-degeneration test above uses a 2-node toy field; # this adds a realistic-scale (n=5000), right-skewed synthetic field with # an EASILY achievable std target (no clipping needed at all), so the # affine seed hits both targets and the soft solve must reduce to it # exactly (via the j_seed < 1e-12 early return, not by chance). rng = np.random.default_rng(11) g = rng.lognormal(mean=5.0, sigma=0.4, size=5000) total = 5000.0 # large relative to g's own scale -> no clipping at a~1 target = 0.8 * float(np.std(g)) # well within reach, a_raw < 1 < a_clamp[1]
pred_affine, info_affine = hybrid_field_affine(g, total, target) assert info_affine["a_clamped"] is False pred_soft, info_soft = hybrid_field_soft(g, total, target)
np.testing.assert_allclose(pred_soft, pred_affine, rtol=1e-9) assert info_soft["target_unreachable"] is False assert abs(info_soft["total_deviation_frac"]) < 1e-6
def test_hybrid_soft_a_clamp_lo_nonpositive_raises(): gnn = np.array([1.0, 2.0, 3.0]) with pytest.raises(ValueError, match="a_clamp"): hybrid_field_soft(gnn, 10.0, 1.0, a_clamp=(0.0, 5.0)) with pytest.raises(ValueError, match="a_clamp"): hybrid_field_soft(gnn, 10.0, 1.0, a_clamp=(-1.0, 5.0))
def test_hybrid_soft_negative_weight_raises(): # LOW: a negative weight rewards moving AWAY from that # target (minimizing J then maximizes the residual's square) -- must # raise loudly rather than silently drive a to a nonsensical optimum. gnn = np.array([1.0, 2.0, 3.0]) with pytest.raises(ValueError, match="w_total|w_std"): hybrid_field_soft(gnn, 10.0, 1.0, w_total=-1.0) with pytest.raises(ValueError, match="w_total|w_std"): hybrid_field_soft(gnn, 10.0, 1.0, w_std=-1.0)
def test_hybrid_soft_both_weights_zero_raises(): # LOW: w_total == w_std == 0 makes J identically zero # everywhere -- no signal for the search to optimize against. gnn = np.array([1.0, 2.0, 3.0]) with pytest.raises(ValueError, match="w_total|w_std"): hybrid_field_soft(gnn, 10.0, 1.0, w_total=0.0, w_std=0.0)
def test_hybrid_soft_one_weight_zero_is_allowed(): # Sanity: only BOTH-zero is forbidden -- a single zero weight (pure # single-target optimization) is a legitimate, deliberate use case. gnn = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) pred, info = hybrid_field_soft(gnn, 10.0, 1.0, w_total=0.0, w_std=1.0) assert np.all(np.isfinite(pred)) pred, info = hybrid_field_soft(gnn, 10.0, 1.0, w_total=1.0, w_std=0.0) assert np.all(np.isfinite(pred))
def test_hybrid_soft_accepted_optimum_majority_clipped_warns(caplog): # The affine path already warns when ITS OWN clip_frac > 0.5; the # soft path must emit the analogous warning when the ACCEPTED soft # optimum (which can differ from the affine seed) itself clips a # majority of the field. rng = np.random.default_rng(3) g = rng.exponential(1.0, size=500) ** 2 g = g - g.min() total = 3.0 target = 3.0 * float(np.std(g)) with caplog.at_level(logging.WARNING): pred, info = hybrid_field_soft(g, total, target, w_total=0.1, w_std=10.0) assert info["clip_frac"] > 0.5 assert any("hybrid_field_soft" in rec.message and "majority" in rec.message.lower() for rec in caplog.records)
def test_hybrid_soft_info_dict_carries_all_keys(): g, total, target = _squeezed_case() pred, info = hybrid_field_soft(g, total, target) expected_keys = {"a", "m", "target_unreachable", "degenerate_fallback", "clip_frac", "total_deviation_frac", "j_total_resid", "j_std_resid", "std_target_effective"} assert expected_keys <= set(info.keys()) # clip_frac must be measured on the FINAL (returned) field. a, m = info["a"], info["m"] c = g - g.mean() final_raw = a * c + m assert info["clip_frac"] == pytest.approx(float((final_raw < 0.0).mean()))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""max/quantile-anchor hybrid recomposition, in src/hybrid.py.
The exact-max anchor is fragile to a handful of outlier nodes (oneinflated GNN log-space prediction can drag the entire rest of the fieldbelow the zero clip). The anchor moved to a high quantile(`np.quantile(gnn, q)`, default `q=0.995`); `q=1.0` reproduces the oldexact-max behavior bit-for-bit (`np.quantile(x, 1.0) == x.max()`)."""import numpy as np
from src.hybrid import hybrid_field_max_anchor
def test_max_anchor_q1_sets_exact_max_and_preserves_shape(): """q=1.0 regression pin: reproduces the earlier exact-max behavior.""" g = np.array([1.0, 4.0, 2.5]) out = hybrid_field_max_anchor(g, 10.0, q=1.0) assert out.max() == 10.0 assert np.allclose(np.diff(out), np.diff(g)) # additive shift only
def test_max_anchor_default_q_preserves_shape_and_meets_or_exceeds_total(): """Default q<1: still an additive shift; max(out) >= total (not ==).""" g = np.array([1.0, 4.0, 2.5]) out = hybrid_field_max_anchor(g, 10.0) assert out.max() >= 10.0 assert out.shape == g.shape assert np.allclose(np.diff(out), np.diff(g)) # additive shift only
def test_max_anchor_clips_at_zero(): assert hybrid_field_max_anchor(np.array([0.0, 100.0]), 10.0)[0] == 0.0
def test_max_anchor_q1_reproduces_old_exact_max_on_random_vector(): """Regression pin: q=1.0 bit-for-bit equals the earlier formula `clip(g - g.max() + total, 0, None)` on an arbitrary random vector.""" rng = np.random.default_rng(42) g = rng.normal(loc=50.0, scale=20.0, size=200) total = 37.5
out = hybrid_field_max_anchor(g, total, q=1.0) expected = np.clip(g - g.max() + total, 0.0, None)
assert np.array_equal(out, expected)
def test_max_anchor_default_q_is_robust_to_a_single_outlier_node(): """The failure mode the promotion gate exposed: one wildly-inflated GNN prediction anchored to the exact max drags ~all other nodes below the zero clip. With the default quantile anchor (q=0.995), >=99% of a 1000-node field stays > 0 for the same outlier + total.""" rng = np.random.default_rng(0) bulk = rng.uniform(0.0, 100.0, size=1000) g = np.concatenate([bulk, [1e6]]) # one extreme outlier node total = 500.0
out_exact = hybrid_field_max_anchor(g, total, q=1.0) out_default = hybrid_field_max_anchor(g, total)
# Old exact-max behavior: the outlier alone sets the anchor, dragging # essentially the whole bulk to the zero clip. assert (out_exact[:-1] > 0).mean() < 0.01
# New default-q behavior: the bulk survives the clip. assert (out_default[:-1] > 0).mean() >= 0.99 assert out_default.shape == g.shape
def test_max_anchor_argsort_unchanged_between_q1_and_default_q(): """Hot-spot ranking must be unaffected by the anchor choice: both are per-graph additive shifts of the same field, so (absent clipping collisions) node order is identical regardless of q.""" rng = np.random.default_rng(7) g = rng.uniform(10.0, 200.0, size=500) # total large enough that neither anchor choice clips any node at zero # (min(g) - anchor + total > 0 for anchor <= max(g)): isolates ordering # from the (expected, separately-tested) clipping behavior. total = 300.0
out_q1 = hybrid_field_max_anchor(g, total, q=1.0) out_default = hybrid_field_max_anchor(g, total)
assert np.array_equal(np.argsort(out_q1), np.argsort(out_default))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import json, pytestfrom src.inference_props import resolve_props, list_alloys, list_molds, DEFAULT_ALLOY, \ resolve_alloy_familyfrom src.shrinkage import SHRINKAGE_PCT
REQ = {"k", "rho", "cp", "L_kJ_kg", "TL", "TS", "Tpour", "mold_effusivity"}
def test_default_is_gjs400_green_sand(): p = resolve_props() assert set(p) == REQ and all(isinstance(v, float) for v in p.values()) assert p["TL"] == 1160.0 and p["TS"] == 1120.0 # EN-GJS-400-15 row assert p["Tpour"] == pytest.approx((1250 + 1270) / 2) # midpoint rule assert p["mold_effusivity"] == pytest.approx(1018.0) # molds.csv, NOT 1250
def test_named_alloy_and_lists(): assert DEFAULT_ALLOY in list_alloys() assert list_alloys() == ["EN-GJS-400-15", "G20Mn5"] assert list_molds() == ["green_sand"] p = resolve_props(alloy="G20Mn5") assert p["TS"] == 1495.0
def test_unknown_names_raise_listing_options(): with pytest.raises(ValueError, match="EN-GJS-400-15"): resolve_props(alloy="unobtainium") with pytest.raises(ValueError, match="green_sand"): resolve_props(mold="vacuum")
def test_props_json_override_and_missing_keys(tmp_path): full = dict(k=30.0, rho=7000.0, cp=500.0, L_kJ_kg=220.0, TL=1200.0, TS=1120.0, Tpour=1350.0, mold_effusivity=900.0) f = tmp_path / "p.json"; f.write_text(json.dumps(full)) assert resolve_props(props_json=str(f)) == full f2 = tmp_path / "p2.json"; f2.write_text(json.dumps({"k": 30.0})) with pytest.raises(ValueError, match="L_kJ_kg"): resolve_props(props_json=str(f2))
# --------------------------------------------------------------------------- ## A `--props` custom-JSON override with TL <= TS was previously unvalidated -- silently# collapsing src.shrinkage.niyama_proxy to 0 everywhere (100% flagged).# --------------------------------------------------------------------------- #def test_props_json_tl_less_equal_ts_raises(tmp_path): inverted = dict(k=30.0, rho=7000.0, cp=500.0, L_kJ_kg=220.0, TL=1100.0, TS=1200.0, Tpour=1350.0, mold_effusivity=900.0) f = tmp_path / "inverted.json"; f.write_text(json.dumps(inverted)) with pytest.raises(ValueError, match=r"TL.*1100.*TS.*1200|TL.*must be strictly greater"): resolve_props(props_json=str(f))
def test_props_json_tl_equal_ts_raises(tmp_path): # degenerate (TL == TS), not just inverted -- niyama_proxy's tdot_proxy # would be exactly (TL-TS)/t_s == 0 for every node either way. degenerate = dict(k=30.0, rho=7000.0, cp=500.0, L_kJ_kg=220.0, TL=1150.0, TS=1150.0, Tpour=1350.0, mold_effusivity=900.0) f = tmp_path / "degenerate.json"; f.write_text(json.dumps(degenerate)) with pytest.raises(ValueError, match="TL"): resolve_props(props_json=str(f))
def test_named_alloy_tl_ts_still_valid_after_i2_guard(): # sanity: the new guard must not break any real named grade (already # validated by tools.doe.load_properties.load_materials's own TS<TL<Tpour # check at CSV-load time -- this just proves resolve_props's OWN check # doesn't double-reject a legitimately-ordered grade). for grade in list_alloys(): p = resolve_props(alloy=grade) assert p["TL"] > p["TS"]
def test_resolve_alloy_family_default_alloy_when_none(): # None -> DEFAULT_ALLOY (EN-GJS-400-15) -> ductile_iron, not assumed. assert resolve_alloy_family(None) == ("ductile_iron", False)
def test_resolve_alloy_family_unknown_prefix_falls_back_loud(): family, assumed = resolve_alloy_family("some_unknown_grade") assert family == "steel" and assumed is True
def test_resolve_alloy_family_covers_every_catalog_grade_exactly(): """a data-driven guard over the REAL property DB (`data/properties/materials.csv` via `list_alloys()`) -- every grade actually on file today must be an EXACT prefix match (`assumed is False`), not a fallback. This is the loud-failure trip-wire for a FUTURE grade added to the catalog under a name none of `_ALLOY_FAMILY_PREFIXES` recognizes: that grade would otherwise silently default to "steel" (a plausible-looking but wrong family for, say, a new aluminum or a differently-prefixed steel grade) with no test ever catching it.""" for grade in list_alloys(): family, assumed = resolve_alloy_family(grade) assert assumed is False, ( f"catalog grade {grade!r} fell back to the 'assumed' family map " f"(resolved family={family!r}) -- add a matching prefix to " f"src.inference_props._ALLOY_FAMILY_PREFIXES") assert family in SHRINKAGE_PCT123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import numpy as npfrom scipy.spatial import Delaunay
from src.geometry import (local_modulus, tet_volumes, edges_from_tets, mesh_volume, total_area)
def _cube(a=10.0): pts = np.array([[x, y, z] for x in (0, a) for y in (0, a) for z in (0, a)], float) dt = Delaunay(pts) tets = dt.simplices.astype(np.int64) cool = dt.convex_hull.astype(np.int64) # all 12 boundary triangles edges = edges_from_tets(tets) elen = np.linalg.norm(pts[edges[:, 0]] - pts[edges[:, 1]], axis=1) return pts, tets, cool, edges, elen
def _box_grid(n=4, a=10.0): """A structured grid of n^3 points spanning a cube of side `a`, Delaunay tetrahedralized, with the convex-hull triangles as the cooling surface. Denser than `_cube` (n=2) -> stands in for a training-density mesh.""" lin = np.linspace(0.0, a, n) pts = np.array([[x, y, z] for x in lin for y in lin for z in lin], float) dt = Delaunay(pts) tets = dt.simplices.astype(np.int64) cool = dt.convex_hull.astype(np.int64) edges = edges_from_tets(tets) elen = np.linalg.norm(pts[edges[:, 0]] - pts[edges[:, 1]], axis=1) return pts, tets, cool, edges, elen
def test_tet_volumes_sum_to_mesh_volume(): xyz, tets, _, _, _ = _cube() assert np.isclose(tet_volumes(xyz, tets).sum(), mesh_volume(xyz, tets)) assert np.isclose(mesh_volume(xyz, tets), 1000.0)
def test_large_radius_equals_global_v_over_a(): xyz, tets, cool, edges, elen = _cube() m = local_modulus(xyz, tets, cool, edges, elen, radii=[1e6]) expected = mesh_volume(xyz, tets) / total_area(xyz, cool) # 1000/600 assert m.shape == (8, 1) and np.allclose(m[:, 0], expected, rtol=1e-6)
def test_no_cooling_gives_bbox_sentinel(): xyz, tets, _, edges, elen = _cube() m = local_modulus(xyz, tets, np.empty((0, 3), np.int64), edges, elen, radii=[1e6]) assert np.allclose(m[:, 0], np.linalg.norm(xyz.max(0) - xyz.min(0)))
def test_tiny_radius_gives_sentinel(): # ball = the node itself: no complete tet, no complete cooling tri -> sentinel xyz, tets, cool, edges, elen = _cube() m = local_modulus(xyz, tets, cool, edges, elen, radii=[0.1]) assert np.allclose(m[:, 0], np.linalg.norm(xyz.max(0) - xyz.min(0)))
def test_multiple_radii_columns_ordered(): xyz, tets, cool, edges, elen = _cube() m = local_modulus(xyz, tets, cool, edges, elen, radii=[0.1, 1e6]) assert m.shape == (8, 2)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176import src.mesh_cache as mc
def _fake_heal(calls, ok=True, n_nodes=5000): def fake(step_path, out_msh, target_nodes=8500, **kw): calls.append((step_path, target_nodes)) if ok: with open(out_msh, "w") as f: f.write("MESH " + str(n_nodes)) return {"ok": ok, "n_nodes": n_nodes if ok else 0, "notes": "" if ok else "boom"} return fake
def _recording_heal(calls, results): """A monkeypatch fake that records the `defeature` kwarg passed on each call (`calls` accumulates dicts `{"defeature": bool}`) and returns `results[i]` for the i-th call (clamped to the last entry once exhausted) -- lets a single fake script a "fails plain, succeeds on defeature retry" sequence for the trigger-policy tests below.""" def fake(step_path, out_msh, target_nodes=8500, defeature=False, **kw): idx = min(len(calls), len(results) - 1) calls.append({"defeature": defeature}) r = results[idx] if r["ok"]: with open(out_msh, "w") as f: f.write("MESH " + str(r["n_nodes"])) return dict(r) return fake
def test_miss_then_hit(tmp_path, monkeypatch): step = tmp_path / "part.step"; step.write_bytes(b"solid-bytes-1") calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _fake_heal(calls)) r1 = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) r2 = mc.get_or_mesh(str(step), str(tmp_path / "b.msh"), 8500, cache_dir=str(tmp_path / "c")) assert r1["cache"] == "miss" and r2["cache"] == "hit" assert len(calls) == 1 # second call never meshed assert open(tmp_path / "b.msh").read() == open(tmp_path / "a.msh").read() assert r2["n_nodes"] == 5000 and r2["pipeline_version"] == mc.MESH_PIPELINE_VERSION
def test_key_changes_with_content_target_and_version(tmp_path, monkeypatch): step = tmp_path / "p.step"; step.write_bytes(b"AAA") k1 = mc.mesh_cache_key(str(step), 8500) step.write_bytes(b"BBB") k2 = mc.mesh_cache_key(str(step), 8500) k3 = mc.mesh_cache_key(str(step), 5000) monkeypatch.setattr(mc, "MESH_PIPELINE_VERSION", mc.MESH_PIPELINE_VERSION + 1) k4 = mc.mesh_cache_key(str(step), 8500) assert len({k1, k2, k3, k4}) == 4
def test_failure_not_cached(tmp_path, monkeypatch): step = tmp_path / "p.step"; step.write_bytes(b"X") calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _fake_heal(calls, ok=False)) r1 = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) r2 = mc.get_or_mesh(str(step), str(tmp_path / "b.msh"), 8500, cache_dir=str(tmp_path / "c")) # `_fake_heal` (ok=False) always fails, so each of the 2 `get_or_mesh` # calls tries twice (plain, then defeature=True): 4 calls in total. assert r1["ok"] is False and r2["cache"] == "miss" and len(calls) == 4
# --------------------------------------------------------------------------# size/failure auto-trigger policy for `defeature=`. Big STEP files# (>8 MiB) try defeature=True first; smaller files try plain first and retry ONCE with# defeature=True only if the plain attempt fails outright. Either way the# returned meta records which `defeature` value actually produced the# result and whether a retry happened, and the cache key is untouched by# any of this (the policy is a deterministic function of the input file,# so a given STEP always resolves to the same `defeature` choice).# --------------------------------------------------------------------------_BIG_FILE_THRESHOLD_BYTES = 8 * 1024 * 1024
def test_trigger_policy_big_file_single_defeature_call(tmp_path, monkeypatch): step = tmp_path / "big.step" step.write_bytes(b"x" * (_BIG_FILE_THRESHOLD_BYTES + 1)) calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [{"ok": True, "n_nodes": 999, "notes": ""}])) r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) assert len(calls) == 1 assert calls[0]["defeature"] is True assert r["ok"] is True and r["defeature"] is True and r["retry"] is False
def test_trigger_policy_small_file_ok_plain_no_retry(tmp_path, monkeypatch): step = tmp_path / "small.step" step.write_bytes(b"tiny") calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [{"ok": True, "n_nodes": 111, "notes": ""}])) r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) assert len(calls) == 1 assert calls[0]["defeature"] is False assert r["ok"] is True and r["defeature"] is False and r["retry"] is False
def test_trigger_policy_small_file_retries_with_defeature_on_failure(tmp_path, monkeypatch): step = tmp_path / "small.step" step.write_bytes(b"tiny") calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [ {"ok": False, "n_nodes": 0, "notes": "boom"}, {"ok": True, "n_nodes": 777, "notes": ""}, ])) r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) assert len(calls) == 2 assert calls[0]["defeature"] is False assert calls[1]["defeature"] is True assert r["ok"] is True and r["defeature"] is True and r["retry"] is True assert r["n_nodes"] == 777
def test_trigger_policy_big_file_defeature_fails_plain_retry_succeeds(tmp_path, monkeypatch): """Symmetric with the small-file retry: a big file's first (defeature=True) attempt can also fail outright, and must then retry ONCE with defeature=False -- not be left with a single, permanently-failed attempt. This must fail on pre-fix code (which had no big-file fallback at all).""" step = tmp_path / "big.step" step.write_bytes(b"x" * (_BIG_FILE_THRESHOLD_BYTES + 1)) calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [ {"ok": False, "n_nodes": 0, "notes": "boom"}, {"ok": True, "n_nodes": 321, "notes": ""}, ])) r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) assert len(calls) == 2 assert calls[0]["defeature"] is True assert calls[1]["defeature"] is False assert r["ok"] is True and r["defeature"] is False and r["retry"] is True assert r["n_nodes"] == 321 assert r["cache"] == "miss" # And now it must be cached: a second call must hit, with no further heal_and_mesh calls. r2 = mc.get_or_mesh(str(step), str(tmp_path / "b.msh"), 8500, cache_dir=str(tmp_path / "c")) assert r2["cache"] == "hit" and len(calls) == 2 assert r2["defeature"] is False and r2["retry"] is True
def test_trigger_policy_small_file_fails_both_attempts_no_extra_retry(tmp_path, monkeypatch): """Even if the defeature retry also fails, `get_or_mesh` must not retry a third time -- exactly one retry, ever.""" step = tmp_path / "small.step" step.write_bytes(b"tiny") calls = [] monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [ {"ok": False, "n_nodes": 0, "notes": "boom1"}, {"ok": False, "n_nodes": 0, "notes": "boom2"}, ])) r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c")) assert len(calls) == 2 assert r["ok"] is False and r["defeature"] is True and r["retry"] is True assert r["cache"] == "miss"
def test_tmp_names_are_unique_per_writer(tmp_path): # Two concurrent workers racing on the SAME cache miss must never derive # the same tmp path from the same final path -- otherwise their writes # could interleave on one inode before either os.replace runs, and # os.replace would then install a corrupted mesh for every later hit. final = str(tmp_path / "c" / "somekey.msh") tmp_a = mc._unique_tmp_path(final) tmp_b = mc._unique_tmp_path(final) assert tmp_a != tmp_b assert tmp_a != final + ".tmp" and tmp_b != final + ".tmp" # no fixed shared name
def test_pipeline_version_pinned_to_3(): assert mc.MESH_PIPELINE_VERSION == 3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443from pathlib import Path
import numpy as npimport pytest
import src.meshing as ppfrom src.meshing import ( heal_and_mesh, _elem_size_from_area, _elem_size, _first_guess_elem_size, K_SURF,)from src.msh_parse import parse_msh
def _make_one_box_step(path, dx=30.0, dy=20.0, dz=10.0): import gmsh gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("box") gmsh.model.occ.addBox(0, 0, 0, dx, dy, dz) gmsh.model.occ.synchronize() gmsh.write(str(path)) finally: gmsh.finalize()
def _make_two_box_step(path, big=40.0, small=10.0): """A synthetic 2-solid STEP: one `big`^3 box and one `small`^3 box, positioned so they don't touch (kept as two separate OCC solids).""" import gmsh gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("two_box") gmsh.model.occ.addBox(0, 0, 0, big, big, big) gmsh.model.occ.addBox(big + 100, 0, 0, small, small, small) gmsh.model.occ.synchronize() gmsh.write(str(path)) finally: gmsh.finalize()
# --------------------------------------------------------------------------# Surface-area density-search seed: the first element size comes from the# OCC surface area of the imported model (`_elem_size_from_area`, via# `_first_guess_elem_size`), with bbox_diag/28 as the fallback.# --------------------------------------------------------------------------def test_elem_size_from_area_matches_formula(): area_mm2, target_nodes = 2200.0, 500 expected = np.sqrt(K_SURF * area_mm2 / target_nodes) assert _elem_size_from_area(area_mm2, target_nodes) == pytest.approx(expected)
def test_heal_and_mesh_area_seed_converges_on_first_attempt(tmp_path): """The calibrated K_SURF must make the 30x20x10mm box @ target_nodes=500 converge within the +-35% band on the FIRST density-search attempt (no refinement rounds needed) -- this is the whole point of seeding from the OCC surface area instead of bbox_diag/28, which missed this same fixture badly (see the multi-round test below, forced via a bad monkeypatched K_SURF).""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
assert result["ok"] is True assert result["attempts"] == 1 assert 500 * 0.65 <= result["n_nodes"] <= 500 * 1.35
def test_first_guess_elem_size_falls_back_when_area_query_raises(monkeypatch): """If the OCC surface-area query raises, `_first_guess_elem_size` must fall back to the bbox_diag/28 heuristic rather than propagating the exception.""" def _boom(): raise RuntimeError("simulated gmsh area-query failure")
monkeypatch.setattr(pp, "_total_surface_area_mm2", _boom)
bbox_diag_mm = 37.4 assert _first_guess_elem_size(bbox_diag_mm, 500) == pytest.approx(_elem_size(bbox_diag_mm))
def test_first_guess_elem_size_falls_back_when_area_nonpositive(monkeypatch): """If the OCC surface-area query returns <= 0 (no exception, just a degenerate/empty answer), `_first_guess_elem_size` must fall back to the bbox_diag/28 heuristic rather than dividing by (or sqrt-ing) a non-positive area.""" monkeypatch.setattr(pp, "_total_surface_area_mm2", lambda: 0.0)
bbox_diag_mm = 37.4 assert _first_guess_elem_size(bbox_diag_mm, 500) == pytest.approx(_elem_size(bbox_diag_mm))
# --------------------------------------------------------------------------# Heal-only-as-fallback regression tests (guards the bug fixed in 5220dbc:# `healShapes()` can run without raising and still silently destroy the# solid -- monkeypatched, deterministic, no real-part meshing).# --------------------------------------------------------------------------def test_heal_and_mesh_clean_part_never_calls_heal(tmp_path, monkeypatch): """A part that meshes fine on pass 1 must never invoke `_apply_heal` -- this is the exact regression found in commit 5220dbc, where `healShapes()` was called unconditionally and silently reduced a perfectly meshable solid to 0 volume entities.""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
def _boom(): raise AssertionError("_apply_heal must not be called when pass 1 succeeds")
monkeypatch.setattr(pp, "_apply_heal", _boom)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500) assert result["ok"] is True assert result["healed"] is False
def test_heal_and_mesh_ineffective_heal_reported_as_failed(tmp_path, monkeypatch): """If pass 1's mesh attempt fails and the pass-2 heal runs but does NOT yield a volume (the historical bug: `healShapes()` silently zeroing out the solid), `heal_and_mesh` must (a) actually attempt the heal, and (b) report ok=False / healed=False -- never silently accept a heal that produced no usable geometry.""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
monkeypatch.setattr(pp, "_tag_and_mesh", lambda size, out_msh: (False, 0, "simulated mesh failure"))
heal_calls = []
def _fake_heal(): heal_calls.append(1) return False, "simulated heal ineffective (0 volumes)"
monkeypatch.setattr(pp, "_apply_heal", _fake_heal)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
assert len(heal_calls) == 1 # (a) heal WAS attempted after pass-1 failure assert result["ok"] is False # (b) not silently accepted assert result["healed"] is False assert "simulated heal ineffective" in result["notes"] assert not out_msh.exists()
def test_heal_and_mesh_effective_heal_then_succeeds(tmp_path, monkeypatch): """If pass 1 fails but the pass-2 heal IS effective, pass 2 should retry meshing and succeed (ok=True, healed=True).""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
calls = {"n": 0}
def _fake_tag_and_mesh(size, out_msh): calls["n"] += 1 if calls["n"] == 1: return False, 0, "simulated pass-1 failure" Path(out_msh).write_text("fake mesh") return True, 777, ""
monkeypatch.setattr(pp, "_tag_and_mesh", _fake_tag_and_mesh) monkeypatch.setattr(pp, "_apply_heal", lambda: (True, ""))
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=777)
assert calls["n"] >= 2 assert result["ok"] is True assert result["healed"] is True assert result["n_nodes"] == 777
# --------------------------------------------------------------------------# Untagged-mesh regression: `_tag_and_mesh` can run more than once within a single gmsh session (density-search# retries) -- `removePhysicalGroups()` frees the *tag number* but not the# *name registration*, so on the 2nd+ call an auto-assigned new tag number# silently fails to bind "Volume"/"Cooling" again. The fix pins explicit# tag numbers (`_VOLUME_PHYS_TAG`/`_COOLING_PHYS_TAG`) across every call in# a session, plus a loud-fail guard in case the binding fails for any other# reason.# --------------------------------------------------------------------------def test_heal_and_mesh_multi_round_density_search_keeps_tags(tmp_path, monkeypatch): """A part whose first-attempt guess misses `target_nodes` by more than the 35% early-exit tolerance forces `_search_target_nodes` into `_search_elem_size`'s multi-round refinement -- i.e. `_tag_and_mesh` runs MORE THAN ONCE in the same gmsh session (verified during triage: without the tag-pinning fix, this reliably ends with an untagged mesh -- `parse_msh(...).tris == {}` -- because only the FIRST round's physical names actually bind). This test's purpose is that TAG behavior, not seed quality -- since the calibrated K_SURF now makes this exact 30x20x10 @ target_nodes=500 fixture converge in ONE attempt (see `test_heal_and_mesh_area_seed_converges_on_first_attempt` above), K_SURF is monkeypatched to a deliberately bad value (50.0, which misses this fixture by >90%) purely to force the multi-round path back open. Regardless of how many rounds ran, the final written mesh must have a nonempty "Cooling" surface group and a nonempty tet volume.""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
monkeypatch.setattr(pp, "K_SURF", 50.0)
calls = [] orig_tag_and_mesh = pp._tag_and_mesh
def _counting(size, out_msh): calls.append(size) return orig_tag_and_mesh(size, out_msh)
monkeypatch.setattr(pp, "_tag_and_mesh", _counting)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
assert len(calls) >= 2, "test setup must force a multi-round density search" assert result["ok"] is True
mesh = parse_msh(str(out_msh)) assert "Cooling" in mesh.tris assert mesh.tris["Cooling"].shape[0] > 0 assert mesh.tets.shape[0] > 0
def test_fast_options_not_applied_in_plain_session(): """A plain fresh gmsh session (nothing fast-related called) must show gmsh's own, un-touched default for Mesh.Algorithm3D -- never HXT (10). Read BEFORE any fast call so this session can't have been polluted by another test in the same process.""" import gmsh
gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) algo = gmsh.option.getNumber("Mesh.Algorithm3D") assert algo != 10 assert algo == 1 # gmsh's documented default (classical Delaunay) finally: gmsh.finalize()
# --------------------------------------------------------------------------# Defeaturing pass: `removeAllDuplicates()`, enabled via `defeature=` and# off by default.# --------------------------------------------------------------------------def test_heal_and_mesh_defeature_true_synthetic_box(tmp_path): """defeature=True on a clean box must still succeed with a nonempty "Cooling" surface group and tet volume -- defeaturing a clean part must not break the Volume/Cooling tag guarantee.""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500, defeature=True)
assert result["ok"] is True assert result["n_nodes"] > 0
mesh = parse_msh(str(out_msh)) assert "Cooling" in mesh.tris assert mesh.tris["Cooling"].shape[0] > 0 assert mesh.tets.shape[0] > 0
def test_heal_and_mesh_defeature_true_calls_apply_defeature(tmp_path, monkeypatch): """defeature=True must actually invoke `_apply_defeature` (in pass 1).""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
calls = [] orig = pp._apply_defeature
def _wrap(): calls.append(1) return orig()
monkeypatch.setattr(pp, "_apply_defeature", _wrap)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500, defeature=True)
assert len(calls) >= 1 assert result["ok"] is True
def test_heal_and_mesh_destructive_defeature_returns_ok_false_not_a_crash(tmp_path, monkeypatch): """If `_apply_defeature` reports the solid was lost (ok=False), `heal_and_mesh` must branch on that and return a clean `ok=False` dict with the solid-loss note -- NOT fall through to `gmsh.model.getBoundingBox(-1, -1)` on an empty model, which raises an uncaught `Exception: Empty bounding box`.""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
monkeypatch.setattr(pp, "_apply_defeature", lambda: (False, "defeature (removeAllDuplicates) yielded 0 volume entities"))
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500, defeature=True)
assert result["ok"] is False assert "0 volume entities" in result["notes"] assert not out_msh.exists()
def test_heal_and_mesh_defeature_default_never_calls_apply_defeature(tmp_path, monkeypatch): """`defeature` defaults to False -- `heal_and_mesh` must not invoke `_apply_defeature` at all in that case (zero behavior change from before this flag existed).""" step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
def _boom(): raise AssertionError("_apply_defeature must not be called when defeature=False (default)")
monkeypatch.setattr(pp, "_apply_defeature", _boom)
out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500) assert result["ok"] is True
def test_apply_defeature_removes_duplicates_without_losing_solid(): """Direct test of `_apply_defeature()` inside an initialized gmsh session: runs cleanly on a plain box and does not destroy the solid.""" import gmsh
gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("box") gmsh.model.occ.addBox(0, 0, 0, 30, 20, 10) gmsh.model.occ.synchronize() ok, note = pp._apply_defeature() assert ok is True assert note == "" assert len(gmsh.model.getEntities(3)) == 1 finally: gmsh.finalize()
def test_tag_and_mesh_fails_loudly_when_name_binding_missing(tmp_path, monkeypatch): """Direct regression test for the loud-fail guard itself: if gmsh ever fails to bind the "Volume"/"Cooling" physical-group names (the exact silent failure that once produced an untagged mesh), `_tag_and_mesh` must return ok=False and must NOT write `out_msh` -- never silently hand back an untagged mesh.""" import gmsh
step = tmp_path / "box.step" _make_one_box_step(step, 30, 20, 10)
gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("box") gmsh.model.occ.importShapes(str(step)) gmsh.model.occ.synchronize()
monkeypatch.setattr(gmsh.model, "getPhysicalName", lambda dim, tag: "")
out_msh = tmp_path / "box.msh" ok, n_nodes, note = pp._tag_and_mesh(2.0, str(out_msh))
assert ok is False assert n_nodes == 0 assert "name binding missing" in note assert not out_msh.exists() finally: gmsh.finalize()
def test_heal_and_mesh_synthetic_box(tmp_path): """A small synthetic box runs the import + mesh + tag pipeline end to end.""" step = tmp_path / "box.step" _make_one_box_step(step) out_msh = tmp_path / "box.msh" result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
assert result["ok"] is True assert result["n_solids"] == 1 assert result["n_nodes"] > 0 assert result["volume_mm3"] == pytest.approx(30 * 20 * 10, rel=1e-2) assert np.isfinite(result["bbox_diag_mm"]) and result["bbox_diag_mm"] > 0 mesh = parse_msh(str(out_msh)) assert set(mesh.tris) == {"Cooling"} and mesh.tets.shape[0] > 0
def test_heal_and_mesh_keeps_largest_of_two_solids(tmp_path): step = tmp_path / "two.step" import gmsh gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("two_box") gmsh.model.occ.addBox(0, 0, 0, 40, 40, 40) gmsh.model.occ.addBox(140, 0, 0, 10, 10, 10) gmsh.model.occ.synchronize() gmsh.write(str(step)) finally: gmsh.finalize() result = heal_and_mesh(str(step), str(tmp_path / "two.msh"), target_nodes=500) assert result["ok"] is True and result["n_solids"] == 2 assert result["volume_mm3"] == pytest.approx(40 ** 3, rel=1e-2) assert "kept largest of 2 solids" in result["notes"]
def test_mesh_step_fixed_size(tmp_path): step = tmp_path / "box.step" _make_one_box_step(step) info = pp.mesh_step(str(step), str(tmp_path / "fixed.msh"), elem_size=5.0) assert info["elem_size"] == 5.0 and info["n_nodes"] > 0 and info["n_tets"] > 0 assert set(parse_msh(str(tmp_path / "fixed.msh")).tris) == {"Cooling"}12345678910111213141516171819202122232425"""CastSolidModel: mesh in, per-node seconds out (needs the published weights)."""import os
import numpy as npimport pytest
from src.model_api import CastSolidModel
WEIGHTS = "weights/gnn_v5.1.safetensors"
def test_hotspots_matches_top_fraction(): t = np.arange(100, dtype=np.float32) mask = CastSolidModel.hotspots(t) assert mask.sum() == 10 and mask[-10:].all()
@pytest.mark.skipif(not os.path.exists(WEIGHTS), reason="published weights not present")def test_predict_on_mesh(mini_msh_file): model = CastSolidModel(device="cpu") t_iron = model.predict(mini_msh_file) t_steel = model.predict(mini_msh_file, alloy="G20Mn5") assert t_iron.shape == t_steel.shape and t_iron.ndim == 1 assert np.all(np.isfinite(t_iron)) and np.all(t_iron >= 0) assert not np.allclose(t_iron, t_steel)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import numpy as npimport torch
from src.model_gnn import (SolidGNN, knn_edge_index, load_gnn, predict_graph_seconds, union_edge_attr, union_edge_index)
CFG = {"node_in": 15, "edge_in": 5, "hidden": 16, "n_blocks": 2, "g_dim": 5, "k": 4}
def _norm(): return {"feat_mean": np.zeros(15, np.float32), "feat_std": np.ones(15, np.float32), "y_log_mean": 3.0, "y_log_std": 0.5}
def _state(seed=0): torch.manual_seed(seed) model = SolidGNN(node_in=15, edge_in=5, hidden=16, n_blocks=2) return {"model": model.state_dict(), "norm": _norm(), "cfg": CFG}
def test_knn_edges_are_symmetric(): pos = torch.rand(30, 3) ei = knn_edge_index(pos, k=4) pairs = set(map(tuple, ei.t().tolist())) assert all((b, a) in pairs for a, b in pairs)
def test_union_graph_contains_mesh_edges_and_flags_them(): pos = torch.rand(20, 3) mesh_edges = torch.tensor([[0, 19], [3, 7]]) ei, is_mesh = union_edge_index(pos, mesh_edges, k=3) pairs = {tuple(p): f for p, f in zip(ei.t().tolist(), is_mesh.tolist())} for a, b in [(0, 19), (19, 0), (3, 7), (7, 3)]: assert pairs[(a, b)] == 1.0 assert len(pairs) == ei.shape[1] # no duplicates ea = union_edge_attr(pos, ei, is_mesh) assert ea.shape == (ei.shape[1], 5) src, dst = ei np.testing.assert_allclose(ea[:, 3], (pos[dst] - pos[src]).norm(dim=1), rtol=1e-6)
def test_film_conditioning_changes_output(): model, cfg, norm = load_gnn(_state(), "cpu") with torch.no_grad(): for film in model.films: # make FiLM non-trivial film.net[-1].weight.normal_(0, 0.5) rng = np.random.default_rng(0) X, pos = rng.normal(size=(25, 15)), rng.uniform(0, 50, size=(25, 3)) edges = np.array([[0, 1], [1, 2], [2, 3]]) a = predict_graph_seconds(model, cfg, norm, X, pos, edges, np.zeros(5)) b = predict_graph_seconds(model, cfg, norm, X, pos, edges, np.ones(5)) assert a.shape == (25,) and np.all(a >= 0) assert not np.allclose(a, b)
def test_prediction_ignores_node_order(): model, cfg, norm = load_gnn(_state(1), "cpu") rng = np.random.default_rng(1) X, pos = rng.normal(size=(25, 15)), rng.uniform(0, 50, size=(25, 3)) edges = np.array([[0, 1], [1, 2], [5, 9]]) g = rng.normal(size=5) a = predict_graph_seconds(model, cfg, norm, X, pos, edges, g) perm = rng.permutation(25) inv = np.argsort(perm) b = predict_graph_seconds(model, cfg, norm, X[perm], pos[perm], inv[edges], g) np.testing.assert_allclose(a[perm], b, rtol=1e-4)12345678910111213141516171819202122import numpy as npfrom src.msh_parse import parse_msh
def test_parse_mini(mini_msh_file): mesh = parse_msh(mini_msh_file)
# 5 nodes, in id order, in mm assert mesh.node_xyz.shape == (5, 3) np.testing.assert_allclose(mesh.node_xyz[0], [0, 0, 0]) np.testing.assert_allclose(mesh.node_xyz[4], [3, 3, 3])
# physical groups present, 0-based indices assert set(mesh.tris.keys()) == {"Cooling", "Adiabatic"} assert mesh.tris["Cooling"].shape == (2, 3) assert mesh.tris["Adiabatic"].shape == (1, 3) # cooling triangle 1 = nodes 1,2,3 (ids) -> indices 0,1,2 np.testing.assert_array_equal(sorted(mesh.tris["Cooling"][0]), [0, 1, 2])
# one tetrahedron, 0-based assert mesh.tets.shape == (1, 4) np.testing.assert_array_equal(sorted(mesh.tets[0]), [0, 1, 2, 3])12345678910111213141516171819import json
from src.ood import load_ranges, ood_flags
RANGES = {"volume_mm3_max": 400.0, "bbox_diag_max": 69.3, "geodesic_d_cool_max": 9.0}
def test_load_ranges(tmp_path): p = tmp_path / "ood.json" p.write_text(json.dumps(RANGES)) assert load_ranges(str(p)) == RANGES
def test_flags_only_beyond_tolerance(): assert ood_flags(400.0, 69.3, 9.0, RANGES) == [] assert ood_flags(410.0, 70.0, 9.3, RANGES) == [] # within the 5% tolerance w = ood_flags(1000.0, 200.0, 30.0, RANGES) assert len(w) == 3 assert "volume" in w[0] and "bounding-box" in w[1] and "distance-to-cooling" in w[2]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""predict_casting orchestration with meshing and the model replaced by fakes,plus an end-to-end run on a synthetic STEP when the weights are present."""import osimport shutil
import meshioimport numpy as npimport pytest
import src.predict_casting as pcfrom src.features import FEATURE_NAMESfrom src.msh_parse import parse_msh
class _FakeModel: def predict_with_props(self, mesh, props): n = mesh.node_xyz.shape[0] X = np.zeros((n, len(FEATURE_NAMES)), np.float32) X[:, FEATURE_NAMES.index("volume_mm3")] = 1000.0 / 6.0 seconds = np.arange(n, dtype=np.float64) + 1.0 info = {"a": 1.0, "m": 0.0, "target_unreachable": False, "clip_frac": 0.0, "total_deviation_frac": 0.0} return seconds, {"X": X, "total_s": float(n), "spread_s": 1.0, "recomposition": info}
def _fake_get_or_mesh(mini_msh_file, calls): def _fn(step_path, out_msh, target_nodes=None, cache_dir=None): calls.append(target_nodes) shutil.copy(mini_msh_file, out_msh) return {"ok": True, "n_nodes": 5, "cache": "miss"} return _fn
def test_writes_vtu_and_summary(monkeypatch, mini_msh_file, tmp_path): calls = [] monkeypatch.setattr(pc, "get_or_mesh", _fake_get_or_mesh(mini_msh_file, calls)) r = pc.predict_casting("part.step", out_dir=str(tmp_path), model=_FakeModel(), ood_json="missing.json") assert calls == [pc.DEFAULT_TARGET_NODES] assert r["total_time_s"] == 5.0 and r["n_nodes"] == 5 assert r["hotspot_xyz"].shape == (5, 3) vtu = meshio.read(r["vtu"]) assert {"solidification_time", "hotspot", "niyama", "porosity_risk", "macro_region_id"} <= set(vtu.point_data) text = open(r["summary"]).read() assert "total solidification time: 5.0 s" in text assert "alloy: EN-GJS-400-15 mold: green_sand model: v5.1" in text assert "shrinkage screening:" in text assert r["shrinkage"]["niyama_source"] == "proxy"
def test_bad_alloy_fails_before_meshing(monkeypatch, tmp_path): def boom(*a, **k): raise AssertionError("meshing must not run") monkeypatch.setattr(pc, "get_or_mesh", boom) with pytest.raises(ValueError, match="unknown alloy"): pc.predict_casting("part.step", out_dir=str(tmp_path), alloy="nope", model=_FakeModel())
def test_no_shrinkage_and_ood_warning(monkeypatch, mini_msh_file, tmp_path): monkeypatch.setattr(pc, "get_or_mesh", _fake_get_or_mesh(mini_msh_file, [])) ood = tmp_path / "ood.json" ood.write_text('{"volume_mm3_max": 1.0, "bbox_diag_max": 1000.0, ' '"geodesic_d_cool_max": 1000.0}') r = pc.predict_casting("part.step", out_dir=str(tmp_path), model=_FakeModel(), screen_shrinkage=False, ood_json=str(ood)) assert r["shrinkage"] is None assert len(r["ood_warnings"]) == 1 and "volume" in r["ood_warnings"][0] assert "porosity_risk" not in meshio.read(r["vtu"]).point_data
def test_elem_size_and_target_nodes_are_exclusive(tmp_path): with pytest.raises(ValueError): pc.predict_casting("part.step", out_dir=str(tmp_path), elem_size=4.0, target_nodes=9000, model=_FakeModel())
def test_parse_gravity(): assert pc._parse_gravity("0, 0, -1") == (0.0, 0.0, -1.0) for bad in ("1,2", "0,0,0", "a,b,c"): with pytest.raises(ValueError): pc._parse_gravity(bad)
@pytest.mark.skipif(not os.path.exists("weights/gnn_v5.1.safetensors"), reason="published weights not present")def test_end_to_end_on_a_box(tmp_path): import gmsh step = tmp_path / "box.step" gmsh.initialize() try: gmsh.option.setNumber("General.Terminal", 0) gmsh.model.add("box") gmsh.model.occ.addBox(0, 0, 0, 120, 80, 40) gmsh.model.occ.synchronize() gmsh.write(str(step)) finally: gmsh.finalize() r = pc.predict_casting(str(step), out_dir=str(tmp_path / "out"), cache_dir=str(tmp_path / "cache"), device="cpu") t = meshio.read(r["vtu"]).point_data["solidification_time"] assert np.all(np.isfinite(t)) and t.min() >= 0 and r["total_time_s"] > 0 assert set(parse_msh(r["msh"]).tris) == {"Cooling"} # the hottest point of a box sits near its centre assert np.linalg.norm(r["hotspot_xyz"][0] - np.array([60, 40, 20])) < 2512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import collectionsimport json
import numpy as npimport pytestimport torchfrom safetensors.torch import save_file
from src import release_io as rio
def _write_gnn(path, fmt=rio.GNN_FORMAT): tensors = {"model.w": torch.arange(6, dtype=torch.float32).reshape(2, 3), "norm.feat_mean": torch.from_numpy(np.arange(3, dtype=np.float32))} meta = {"format": fmt, "cfg": json.dumps({"hidden": 16, "k": 4}), "norm_kinds": json.dumps({"feat_mean": "numpy"}), "norm_scalars": json.dumps({"y_log_mean": 3.5})} save_file(tensors, str(path), metadata=meta)
def test_load_gnn_state(tmp_path): p = tmp_path / "gnn.safetensors" _write_gnn(p) state = rio.load_gnn_state(str(p)) assert state["cfg"] == {"hidden": 16, "k": 4} assert torch.equal(state["model"]["w"], torch.arange(6, dtype=torch.float32).reshape(2, 3)) assert isinstance(state["norm"]["feat_mean"], np.ndarray) assert state["norm"]["feat_mean"].dtype == np.float32 assert state["norm"]["y_log_mean"] == 3.5
def test_load_gnn_state_rejects_other_files(tmp_path): p = tmp_path / "other.safetensors" _write_gnn(p, fmt="something-else") with pytest.raises(ValueError, match="not a"): rio.load_gnn_state(str(p))
def test_load_gbm_roundtrip(tmp_path): skops = pytest.importorskip("skops.io") from sklearn.ensemble import HistGradientBoostingRegressor rng = np.random.default_rng(0) X, y = rng.normal(size=(200, 4)), rng.normal(size=200) m = HistGradientBoostingRegressor(max_iter=20).fit(X, y) p = tmp_path / "gbm.skops" skops.dump(m, str(p)) np.testing.assert_array_equal(rio.load_gbm(p).predict(X), m.predict(X))
def test_load_gbm_refuses_foreign_types(tmp_path): skops = pytest.importorskip("skops.io") p = tmp_path / "bad.skops" skops.dump({"c": collections.Counter(a=1)}, str(p)) with pytest.raises(ValueError, match="unexpected types"): rio.load_gbm(p)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186import numpy as npimport pytest
from src.shrinkage import ( node_gradient, niyama_proxy, porosity_risk, hot_regions, is_fed, macro_shrinkage, top_sinks, feeder_recommendations, SHRINKAGE_PCT, screen_casting, _boundary_faces,)
# ---------------------------------------------------------------------------# Structured tet-grid helpers -- a Kuhn/Freudenthal 6-tet-per-cube# decomposition of a regular nx*ny*nz node lattice (unit spacing unless# overridden). This is a conforming triangulation (verified numerically: tet# volumes sum exactly to the lattice bounding volume, and internal faces# between adjacent cubes cancel out of the boundary-surface-area count),# reused across the region/sink/feeder tests below.# ---------------------------------------------------------------------------
_KUHN_TETS = [(0, 1, 3, 7), (0, 1, 5, 7), (0, 4, 5, 7), (0, 2, 3, 7), (0, 2, 6, 7), (0, 4, 6, 7)]
def _node_idx(nx, ny): return lambda i, j, k: i + j * nx + k * nx * ny
def _grid_mesh(nx, ny, nz, spacing=1.0): idx = _node_idx(nx, ny) pos = np.zeros((nx * ny * nz, 3)) for k in range(nz): for j in range(ny): for i in range(nx): pos[idx(i, j, k)] = [i * spacing, j * spacing, k * spacing]
def local(i, j, k, bit): dx, dy, dz = bit & 1, (bit >> 1) & 1, (bit >> 2) & 1 return idx(i + dx, j + dy, k + dz)
tets = [] for k in range(nz - 1): for j in range(ny - 1): for i in range(nx - 1): for t in _KUHN_TETS: tets.append([local(i, j, k, b) for b in t]) return pos, np.array(tets, dtype=np.int64)
def _surface_nodes(nx, ny, nz): idx = _node_idx(nx, ny) nodes = [] for k in range(nz): for j in range(ny): for i in range(nx): if i in (0, nx - 1) or j in (0, ny - 1) or k in (0, nz - 1): nodes.append(idx(i, j, k)) return np.array(sorted(nodes), dtype=np.int64)
# ---------------------------------------------------------------------------# (a) node_gradient# ---------------------------------------------------------------------------
def test_node_gradient_single_regular_tet(): # unit tet at the origin: (0,0,0), (1,0,0), (0,1,0), (0,0,1) pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], float) tets = np.array([[0, 1, 2, 3]]) field = 2.0 * pos[:, 0] # f = 2x -> grad = (2, 0, 0) everywhere g = node_gradient(pos, tets, field) assert g.shape == (4, 3) np.testing.assert_allclose(g, np.tile([2.0, 0.0, 0.0], (4, 1)), atol=1e-10)
def test_node_gradient_two_tet_bipyramid(): # two tets sharing triangular face ABC, apexes D (above) and E (below) # A, B, C, D, E -> indices 0..4 pos = np.array([ [0, 0, 0], # A [1, 0, 0], # B [0, 1, 0], # C [0, 0, 1], # D (apex above) [0, 0, -1], # E (apex below) ], float) tets = np.array([ [0, 1, 2, 3], # A B C D [0, 1, 2, 4], # A B C E ]) field = pos[:, 0] + pos[:, 1] # f = x + y -> grad = (1, 1, 0) everywhere (exact, linear) g = node_gradient(pos, tets, field) assert g.shape == (5, 3) np.testing.assert_allclose(g, np.tile([1.0, 1.0, 0.0], (5, 1)), atol=1e-10)
def test_node_gradient_no_tets_returns_zeros(): pos = np.zeros((3, 3)) tets = np.empty((0, 4), dtype=np.int64) field = np.zeros(3) g = node_gradient(pos, tets, field) np.testing.assert_allclose(g, np.zeros((3, 3)))
# ---------------------------------------------------------------------------# (b) niyama_exact# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------# (c) niyama_proxy# ---------------------------------------------------------------------------
def test_niyama_proxy_linear_slab_hand_computed(): # single regular tet, t_s = 2 + 2x (linear ramp along x) -> |grad t_s| = 2 exactly pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], float) tets = np.array([[0, 1, 2, 3]]) t_s = np.array([2.0, 4.0, 2.0, 2.0]) # node0=2 (x=0), node1=4 (x=1), node2/3 at x=0 -> 2 TL, TS = 1400.0, 1100.0 # TL - TS = 300
ny = niyama_proxy(pos, tets, t_s, TL, TS) assert ny.shape == (4,)
# hand computation: sqrt((TL-TS)/t_s) * |grad t_s|, |grad t_s| = 2 at every node expected_node0 = np.sqrt(300.0 / 2.0) * 2.0 # ~24.494897... expected_node1 = np.sqrt(300.0 / 4.0) * 2.0 # ~17.320508... np.testing.assert_allclose(ny[0], expected_node0, rtol=1e-10) np.testing.assert_allclose(ny[1], expected_node1, rtol=1e-10)
def test_niyama_proxy_eps_guarded_at_zero_t_s(): pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], float) tets = np.array([[0, 1, 2, 3]]) t_s = np.array([0.0, 2.0, 0.0, 0.0]) ny = niyama_proxy(pos, tets, t_s, 1400.0, 1100.0) assert np.isfinite(ny).all()
# ---------------------------------------------------------------------------# (d) porosity_risk -- absolute mode# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------# (e) porosity_risk -- percentile mode# ---------------------------------------------------------------------------
def test_porosity_risk_percentile_exact_bottom_10pct(): ny = np.arange(20, dtype=float) # 0..19, no ties mask = porosity_risk(ny, pct=10.0) assert mask.sum() == 2 # exactly bottom 10% of 20 = 2 np.testing.assert_array_equal(np.where(mask)[0], [0, 1])
def test_porosity_risk_percentile_exact_bottom_10pct_n10(): ny = np.arange(10, dtype=float) # 0..9 mask = porosity_risk(ny, pct=10.0) assert mask.sum() == 1 np.testing.assert_array_equal(np.where(mask)[0], [0])
def test_porosity_risk_percentile_tie_handling_documented(): # duplicate values straddling the percentile threshold: both ties are # flagged (mask is defined as ny <= percentile(ny, pct), so a tie AT the # threshold is always included) -- this can flag slightly MORE than the # nominal pct% when duplicates sit at the boundary. Documented behavior, # not a bug: deterministic and order-independent. ny = np.array([0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]) mask = porosity_risk(ny, pct=10.0) assert mask.sum() == 2 np.testing.assert_array_equal(np.where(mask)[0], [0, 1])
# ---------------------------------------------------------------------------# (a) hot_regions + is_fed -- isolated boss (unfed) vs. surface-connected# band (fed), on one 7x7x7 mesh with two disjoint elevated node clusters.# ---------------------------------------------------------------------------
def _boss_and_band_mesh(): nx = ny = nz = 7 pos, tets = _grid_mesh(nx, ny, nz) idx = _node_idx(nx, ny) n_nodes = pos.shape[0] t_s = np.zeros(n_nodes)
# boss: a fully-interior unit cube {2,3}x{2,3}x{2,3} -- 8 nodes, none on # the (0 or 6) domain boundary, and not adjacent to the band below. boss_nodes = [idx(i, j, k) for i in (2, 3) for j in (2, 3) for k in (2, 3)] # band: a column at x=5,y=5, z=3..6 -- z=6 sits on the top boundary face, # so the band directly touches a free surface. band_nodes = [idx(5, 5, z) for z in (3, 4, 5, 6)]
t_s[boss_nodes] = 100.0 t_s[band_nodes] = 100.0 n_hot = len(boss_nodes) + len(band_nodes) top_frac = n_hot / n_nodes # sized so the percentile cut lands exactly on {0, 100}
surface_nodes = _surface_nodes(nx, ny, nz) return pos, tets, t_s, top_frac, surface_nodes, set(boss_nodes), set(band_nodes)
def test_hot_regions_finds_boss_and_band_as_separate_components(): pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert len(regions) == 2 node_sets = [set(r["nodes"].tolist()) for r in regions] assert boss_nodes in node_sets assert band_nodes in node_sets for r in regions: assert r["t_max"] == 100.0 np.testing.assert_allclose(r["centroid"], pos[np.array(sorted(r["nodes"]))].mean(axis=0))
def test_hot_regions_sorted_by_t_max_desc(): pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() # bump one region's peak so the sort order is unambiguous. idx = _node_idx(7, 7) t_s = t_s.copy() t_s[idx(5, 5, 6)] = 150.0 regions = hot_regions(pos, tets, t_s, top_frac=top_frac) t_maxes = [r["t_max"] for r in regions] assert t_maxes == sorted(t_maxes, reverse=True) assert t_maxes[0] == 150.0
def test_is_fed_isolated_boss_is_false(): # feed_nodes = surface_nodes here (this mesh's domain boundary stands in # for a riser/feed location) -- the boss never reaches the corridor # threshold (0.95*t_max) outside its own 8 nodes, so it can't connect. pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) boss_region = next(r for r in regions if set(r["nodes"].tolist()) == boss_nodes) assert is_fed(boss_region, t_s, tets, feed_nodes=surface_nodes) is False
def test_is_fed_surface_connected_band_is_true(): # the band's own top node (z=6) is itself in feed_nodes=surface_nodes, # so the region trivially self-connects to a feed node. pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) band_region = next(r for r in regions if set(r["nodes"].tolist()) == band_nodes) assert is_fed(band_region, t_s, tets, feed_nodes=surface_nodes) is True
def test_is_fed_empty_feed_nodes_is_always_false(): pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) band_region = next(r for r in regions if set(r["nodes"].tolist()) == band_nodes) # bare sand casting convention: no risers -> empty feed_nodes -> unfed, # even for a region that DOES touch the domain surface. assert is_fed(band_region, t_s, tets, feed_nodes=np.array([], dtype=np.int64)) is False
# --------------------------------------------------------------------------- ## Marginal ("sub-resolution", <4 nodes) hot regions mix a lumped-nodal V# (stays O(h^3)) with a true iso-surface A (shrinks toward zero as t_max -># hot_threshold), so M = V/A diverges without bound. `hot_regions` marks such regions# "sub_resolution": True; `feeder_recommendations` skips them (logging the# count once); `macro_shrinkage` still lists them (volume/severity remain# meaningful, only the modulus diverges).# --------------------------------------------------------------------------- #def _single_isolated_hot_node_mesh(): """A 7x7x7 grid mesh with exactly ONE hot node (fully interior, no hot neighbors) -- the minimal fixture for a 1-node `hot_regions` component.""" nx = ny = nz = 7 pos, tets = _grid_mesh(nx, ny, nz) idx = _node_idx(nx, ny) n_nodes = pos.shape[0] t_s = np.zeros(n_nodes) hot_node = idx(3, 3, 3) t_s[hot_node] = 100.0 top_frac = 1.0 / n_nodes surface_nodes = _surface_nodes(nx, ny, nz) return pos, tets, t_s, top_frac, surface_nodes, hot_node
def test_hot_regions_marks_sub_resolution_for_regions_under_4_nodes(): pos, tets, t_s, top_frac, surface_nodes, hot_node = _single_isolated_hot_node_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert len(regions) == 1 assert regions[0]["nodes"].tolist() == [hot_node] assert regions[0]["sub_resolution"] is True
def test_hot_regions_does_not_mark_well_resolved_regions_sub_resolution(): # the boss (8 nodes) and band (4 nodes) fixture -- both >= the 4-node floor. pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert len(regions) == 2 for r in regions: assert r["sub_resolution"] is False
def test_feeder_recommendations_skips_sub_resolution_region_and_logs_count(caplog): """A 1-node region must get NO feeder recommendation at all, and the skip must be logged (once, with the count) rather than silent.""" import logging as _logging pos, tets, t_s, top_frac, surface_nodes, hot_node = _single_isolated_hot_node_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert regions[0]["sub_resolution"] is True
with caplog.at_level(_logging.INFO, logger="src.shrinkage"): recs = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s)
assert recs == [] assert any("skipped 1 sub-resolution region" in rec.message for rec in caplog.records)
def test_feeder_recommendations_mixed_regions_skips_only_sub_resolution_ones(caplog): """A regions list mixing well-resolved regions (get a feeder rec each) and a sub-resolution one (skipped, not just de-prioritized) -- the well-resolved regions' recs must be unaffected by the mix.""" import logging as _logging pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert all(not r["sub_resolution"] for r in regions)
sub_region = { "nodes": np.array([0]), "centroid": pos[0], "volume_mm3": 1.0, "t_max": float(t_s.max()), "region_id": 99, "hot_threshold": regions[0]["hot_threshold"], "sub_resolution": True, } mixed_regions = regions + [sub_region]
with caplog.at_level(_logging.INFO, logger="src.shrinkage"): recs = feeder_recommendations(mixed_regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s)
assert len(recs) == len(regions) assert {r["region_id"] for r in recs} == {r["region_id"] for r in regions} assert any("skipped 1 sub-resolution region" in rec.message for rec in caplog.records)
# --------------------------------------------------------------------------- ## the mesh's boundary-face structure is# region-independent and hoisted out of `_region_surface_area`'s per-call# work into a standalone `_boundary_faces(tets)` helper, computed once by# `feeder_recommendations` and shared across every region. A direct check# of the helper on a hand-countable 2-tet mesh (one shared interior face).# --------------------------------------------------------------------------- #def test_boundary_faces_excludes_shared_interior_face(): # two tets sharing face (0,1,2) -- a triangular bipyramid. tets = np.array([[0, 1, 2, 3], [0, 1, 2, 4]], dtype=np.int64) bf = _boundary_faces(tets) assert bf.shape == (6, 3) boundary_keys = {tuple(sorted(row.tolist())) for row in bf} assert (0, 1, 2) not in boundary_keys # the shared interior face is excluded expected = {(0, 1, 3), (0, 2, 3), (1, 2, 3), (0, 1, 4), (0, 2, 4), (1, 2, 4)} assert boundary_keys == expected
def test_boundary_faces_empty_tets_gives_empty_array(): bf = _boundary_faces(np.zeros((0, 4), dtype=np.int64)) assert bf.shape == (0, 3)
def test_hot_regions_top_frac_out_of_range_raises(): pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() with pytest.raises(ValueError): hot_regions(pos, tets, t_s, top_frac=0.0) with pytest.raises(ValueError): hot_regions(pos, tets, t_s, top_frac=1.5)
# ---------------------------------------------------------------------------# (a2) is_fed corridor semantics: a warm corridor (t within `corridor_frac` of the region's own# t_max) bridges the region to a feed node several hops away, NOT required# to be part of the region's own hot-node set. This is the# REQUIRED test: it must fail both under a `return False` stub (variant 1# expects True) and under a naive "touch test" that only checks direct# region-to-feed_node adjacency or membership (variant 1's feed node is 6# hops from the region, connected only via the intermediate warm corridor).# ---------------------------------------------------------------------------
def _corridor_chain_mesh(): """8x2x2 lattice (32 nodes): an x-adjacent chain of nodes (i,0,0), i=0..7 (verified consecutively tet-adjacent). Node 6 will be the sole hot region (t_max=100); nodes 0-5 are the candidate corridor (0 doubles as the feed node); node 7 is the "far cold side" used as a decoy feed node in variant 3. Every other mesh node stays at background 0 and never participates (present only so this is a valid tet mesh).""" nx, ny, nz = 8, 2, 2 pos, tets = _grid_mesh(nx, ny, nz) idx = _node_idx(nx, ny) chain = [idx(i, 0, 0) for i in range(nx)] n_nodes = pos.shape[0] return pos, tets, n_nodes, chain
def test_is_fed_warm_corridor_bridges_region_to_distant_feed_node(): pos, tets, n_nodes, chain = _corridor_chain_mesh() t_s = np.zeros(n_nodes) t_s[chain[6]] = 100.0 # region peak t_s[chain[0:6]] = 96.0 # corridor >= 0.95*100 = 95 -- stays warm region = {"nodes": np.array([chain[6]]), "t_max": 100.0} assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[0]])) is True
def test_is_fed_false_when_corridor_cools_below_corridor_frac(): pos, tets, n_nodes, chain = _corridor_chain_mesh() t_s = np.zeros(n_nodes) t_s[chain[6]] = 100.0 t_s[chain[0:6]] = 90.0 # < 95 -- corridor no longer warm enough region = {"nodes": np.array([chain[6]]), "t_max": 100.0} assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[0]])) is False
def test_is_fed_false_when_feed_node_is_on_far_cold_side(): pos, tets, n_nodes, chain = _corridor_chain_mesh() t_s = np.zeros(n_nodes) t_s[chain[6]] = 100.0 t_s[chain[0:6]] = 96.0 # corridor stays warm... region = {"nodes": np.array([chain[6]]), "t_max": 100.0} # ...but feed_nodes points to the far (cold, disconnected) side instead. assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[7]])) is False
def test_is_fed_region_t_max_zero_is_unfed_not_vacuously_true(): """a region t_max <= 0 would make the corridor threshold (corridor_frac * t_max) <= 0, vacuously satisfied by every non-negative t_s -- i.e. the whole (connected) mesh would count as "warm", trivially fed via any non-empty feed_nodes regardless of real connectivity. Guarded to report unfed instead.""" pos, tets, n_nodes, chain = _corridor_chain_mesh() t_s = np.zeros(n_nodes) # every node, including all feed candidates, is 0 region = {"nodes": np.array([chain[6]]), "t_max": 0.0} # without the guard, corridor threshold = 0.95*0 = 0 <= every t_s -> the # whole mesh (one connected component) would trivially "fed" this region. assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[0]])) is False
# ---------------------------------------------------------------------------# (b) macro_shrinkage -- severity = pct/100 * volume, hand-checked; grey_iron# (pct=0) still reports the region with zero severity; fed regions excluded.# ---------------------------------------------------------------------------
def _interior_cube_block_mesh(): """9x6x5 lattice with a fully-interior 3x3x3 node block (a 2x2x2 mm solid cube of 8 sub-cells). Under the fraction-weighted volume rule, volume_mm3 = 27.0 exactly: each of the 27 hot nodes is fully interior with a complete 8-cube neighborhood, so its lumped nodal volume (sum of tet_volume/4 over incident tets) is exactly 1 mm^3 on this unit-spacing lattice -- hand-verified numerically (independently confirmed: fraction-weighted volume == hot-node COUNT here, since summing volume*n_hot/4 over all tets is algebraically identical to summing each hot node's own lumped volume). Boundary area is now `_region_surface_area`'s co-area/domain-boundary formula -- see that function's docstring -- which for this fixture comes to ~49.31 mm^2 (M = V/A ~= 0.5475, within 15% of the idealized "3x3x3 mm dilated cube" reference of A=54/M=0.5 derived by hand; an exact closed-form match isn't expected for a graded/partial-tet field -- see `test_feeder_recommendations_modulus_exact` and the mesh-refinement drift test below for the actual acceptance checks). The block is exactly 27/270 = 10% of nodes, matching hot_regions'/macro_shrinkage's default top_frac.""" nx, ny, nz = 9, 6, 5 pos, tets = _grid_mesh(nx, ny, nz) idx = _node_idx(nx, ny) n_nodes = pos.shape[0] t_s = np.zeros(n_nodes) block_nodes = [idx(i, j, k) for i in (3, 4, 5) for j in (1, 2, 3) for k in (1, 2, 3)] t_s[block_nodes] = 100.0 surface_nodes = _surface_nodes(nx, ny, nz) assert len(block_nodes) / n_nodes == pytest.approx(0.10) assert not any(n in set(surface_nodes.tolist()) for n in block_nodes) return pos, tets, t_s, surface_nodes, set(block_nodes)
def test_macro_shrinkage_severity_hand_checked(): pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() # bare-casting convention: no risers -> empty feed_nodes -> conservative # (this fully-interior block is unfed regardless, since it never reaches # the domain surface anyway -- see is_fed's docstring). no_feed = np.array([], dtype=np.int64) regions = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=2.5) assert len(regions) == 1 r = regions[0] assert set(r["nodes"].tolist()) == block_nodes assert r["volume_mm3"] == pytest.approx(27.0) assert r["severity"] == pytest.approx(2.5 / 100.0 * 27.0)
def test_macro_shrinkage_grey_iron_zero_severity_still_reported(): pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() no_feed = np.array([], dtype=np.int64) regions = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=SHRINKAGE_PCT["grey_iron"]) assert len(regions) == 1 assert regions[0]["severity"] == pytest.approx(0.0) assert regions[0]["volume_mm3"] == pytest.approx(27.0) # region still fully reported
def _unfed_boss_and_fed_band_10pct_mesh(): """10x5x4 lattice (200 nodes) with an interior unit-cube boss (8 nodes, t_max=100, unfed) and a corner block band (12 nodes, t_max=150, touching x=0/y=0/z=0 boundary faces) -- 20/200 = exactly 10%, matching macro_shrinkage's (un-parametrized) default top_frac so BOTH regions are picked up by its internal hot_regions() call. `feed_nodes=surface_nodes` is used by the tests below as a stand-in "this domain boundary carries risers" convention: the band's own boundary-touching nodes are literally IN `surface_nodes`, so it self-connects trivially (fed); the boss's warm corridor (0.95*its own t_max=100 -> threshold 95) never leaves its own 8 nodes (all neighbors are background 0), so it cannot reach the boundary (unfed) -- hand-verified via the boss/band-touches-surface assertions below. Band's t_max is deliberately HIGHER than boss's so hot_regions sorts band first (region_id=0) and boss second (region_id=1) -- this exposes a positional-reindex bug (region_id coherence) that a same-valued t_max tie would hide.""" nx, ny, nz = 10, 5, 4 pos, tets = _grid_mesh(nx, ny, nz) idx = _node_idx(nx, ny) n_nodes = pos.shape[0] t_s = np.zeros(n_nodes)
boss_nodes = [idx(i, j, k) for i in (4, 5) for j in (1, 2) for k in (1, 2)] band_nodes = [idx(i, j, k) for i in (0, 1) for j in (0, 1) for k in (0, 1, 2)] t_s[boss_nodes] = 100.0 t_s[band_nodes] = 150.0 assert (len(boss_nodes) + len(band_nodes)) / n_nodes == pytest.approx(0.10)
surface_nodes = _surface_nodes(nx, ny, nz) surface_set = set(surface_nodes.tolist()) assert not any(n in surface_set for n in boss_nodes) assert any(n in surface_set for n in band_nodes) return pos, tets, t_s, surface_nodes, set(boss_nodes), set(band_nodes)
def test_macro_shrinkage_excludes_fed_regions(): pos, tets, t_s, surface_nodes, boss_nodes, band_nodes = _unfed_boss_and_fed_band_10pct_mesh() regions = macro_shrinkage(pos, tets, t_s, feed_nodes=surface_nodes, shrinkage_pct=2.5) assert len(regions) == 1 assert set(regions[0]["nodes"].tolist()) == boss_nodes
def test_region_id_coherence_across_pipeline(): """region_id must be the STABLE hot_regions index, propagated (not positionally re-derived) through macro_shrinkage's filtering and further through top_sinks/feeder_recommendations.""" pos, tets, t_s, surface_nodes, boss_nodes, band_nodes = _unfed_boss_and_fed_band_10pct_mesh()
raw_regions = hot_regions(pos, tets, t_s) assert len(raw_regions) == 2 boss_raw = next(r for r in raw_regions if set(r["nodes"].tolist()) == boss_nodes) band_raw = next(r for r in raw_regions if set(r["nodes"].tolist()) == band_nodes) # band's t_max (150) > boss's (100) -> band sorts first. assert band_raw["region_id"] == 0 assert boss_raw["region_id"] == 1
macro = macro_shrinkage(pos, tets, t_s, feed_nodes=surface_nodes, shrinkage_pct=2.5) assert len(macro) == 1 # band filtered out (fed); a naive positional # re-index would mislabel the sole survivor as region_id 0. assert macro[0]["region_id"] == 1
sinks = top_sinks(macro, pos, surface_nodes, gravity_vec=(0, 0, -1)) feeders = feeder_recommendations(macro, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) assert all(f["region_id"] == 1 for f in feeders) assert all(s["region_id"] == 1 for s in sinks)
def test_macro_shrinkage_verdict_flips_via_genuine_external_corridor(): """an end-to-end (not just is_fed-level) demonstration that a region's fed/unfed verdict can flip because of a node that is NOT part of the region (hot_regions' own top-10% cut excludes it) and NOT the feed node itself, but sits between `0.95*t_max` and the hot cut and bridges to a feed node -- i.e. a genuine warm-corridor effect, not the trivial "feed node happens to be inside the region" case exercised by `test_macro_shrinkage_excludes_ fed_regions`. Peak (node 1), bridge (node 3), and feed (node 2) are chosen so the feed node is NOT itself tet-adjacent to the region peak (hand-verified: nodes 1 and 2 share no tet in this mesh's Kuhn decomposition) -- the bridge node is structurally required to connect them, unlike a single-hop setup where a direct peak-feed edge could make the test pass for the wrong reason. A single unit-cube mesh (N=8) is used because hot_regions' un-parametrized default top_frac=0.10 only isolates a lone peak node cleanly at small N (verified: at N=12+ the corridor value gets pulled into the "hot" selection itself by percentile interpolation, defeating the "external, not region-touching" setup).""" pos, tets = _grid_mesh(2, 2, 2) n_nodes = pos.shape[0] t_s = np.zeros(n_nodes) t_s[1] = 100.0 # sole region peak t_s[3] = 96.0 # bridge node: >= 0.95*100=95, but < the 97.2 hot cut t_s[2] = 96.0 # feed node: same band; NOT tet-adjacent to node 1 directly
regions = hot_regions(pos, tets, t_s) # default top_frac=0.10 assert len(regions) == 1 assert regions[0]["nodes"].tolist() == [1] # bridge/feed excluded from the region itself
fed_via_corridor = macro_shrinkage(pos, tets, t_s, feed_nodes=np.array([2]), shrinkage_pct=2.5) assert fed_via_corridor == [] # fed -> not reported as macro-shrinkage
unfed_without_corridor = macro_shrinkage(pos, tets, t_s, feed_nodes=np.array([], dtype=np.int64), shrinkage_pct=2.5) assert len(unfed_without_corridor) == 1 assert unfed_without_corridor[0]["nodes"].tolist() == [1]
# cooling the bridge/feed band below 0.95*t_max flips the verdict back # to unfed even with the SAME feed_nodes -- confirms the flip is driven # by the corridor threshold, not merely feed_nodes' presence. t_s_cold_corridor = t_s.copy() t_s_cold_corridor[[2, 3]] = 90.0 cooled = macro_shrinkage(pos, tets, t_s_cold_corridor, feed_nodes=np.array([2]), shrinkage_pct=2.5) assert len(cooled) == 1
def test_shrinkage_pct_table(): assert SHRINKAGE_PCT == { "steel": 2.5, "low_alloy_steel": 2.5, "ductile_iron": 0.75, "grey_iron": 0.0, }
# ---------------------------------------------------------------------------# (c) top_sinks -- gravity -z -> sink on the top (z-max) face; rotating# gravity to -x/-y relocates the sink to the +x/+y face. Single 3x3x3 mesh,# one hot region spanning a top-face node, an interior bridge node, an# x-face node, and a y-face node (all connected via tet adjacency through# the bridge) -- also reused by feeder_recommendations' rotation tests below#.# ---------------------------------------------------------------------------
def _rotatable_sink_mesh(): nx = ny = nz = 3 pos, tets = _grid_mesh(nx, ny, nz) idx = _node_idx(nx, ny) n_nodes = pos.shape[0] t_s = np.zeros(n_nodes)
node_top = idx(1, 1, 2) # z=2 -> top (z-max) surface face node_bridge = idx(1, 1, 1) # interior node_xface = idx(2, 1, 1) # x=2 -> +x surface face node_yface = idx(1, 2, 1) # y=2 -> +y surface face
hot = [node_top, node_bridge, node_xface, node_yface] t_s[hot] = 100.0 top_frac = len(hot) / n_nodes surface_nodes = _surface_nodes(nx, ny, nz) regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert len(regions) == 1 return pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface
def test_top_sinks_default_gravity_hits_top_face(): pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface = _rotatable_sink_mesh() sinks = top_sinks(regions, pos, surface_nodes, gravity_vec=(0, 0, -1)) assert len(sinks) == 1 np.testing.assert_allclose(sinks[0]["location"], pos[node_top])
def test_top_sinks_rotated_gravity_relocates_to_x_face(): pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface = _rotatable_sink_mesh() sinks = top_sinks(regions, pos, surface_nodes, gravity_vec=(-1, 0, 0)) assert len(sinks) == 1 np.testing.assert_allclose(sinks[0]["location"], pos[node_xface])
# ---------------------------------------------------------------------------# (d) feeder_recommendations -- min_modulus == 1.2*(V/A); location on the# top surface above the region's centroid; ValueError on empty surface_nodes;# a degenerate (zero-volume/area) region logs a warning instead of a silent 0.## `_region_surface_area` now runs marching tetrahedra on the# CONTINUOUS `t_s` field cut at the region's own `hot_threshold`, replacing# round 2's co-area formula on a BINARIZED indicator -- the binarized version# always crosses each tet edge at its midpoint regardless of where the real# field crosses its OWN selection threshold, which is an exact calculus# identity for the (artificial) binary step but measures the anisotropic# discrete perimeter of that step, not the true field's level-surface area:# it plateaus ~24-29% high on curved/diagonal boundaries (only looking exact# on an axis-aligned cut, where a midpoint crossing happens to coincide with# the true one). `feeder_recommendations` gained a required `t_s` parameter# in this round since the marching-tetrahedra computation needs the# continuous field, not just region-node membership.# ---------------------------------------------------------------------------
def _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold): """Independent reimplementation of the marching-tetrahedra + domain- boundary-face area formula (mirrors, but does not call, `src.shrinkage._region_surface_area` -- a genuine hand-check against the same algorithm, not a tautological re-invocation of the code under test).""" n_nodes = pos.shape[0] is_member = np.zeros(n_nodes, dtype=bool) is_member[np.asarray(nodes, dtype=np.int64)] = True hot_mask = t_s >= threshold
area = 0.0 member_per_tet = hot_mask[tets] n_above = member_per_tet.sum(axis=1) for ti in np.flatnonzero((n_above >= 1) & (n_above <= 3)): tet = tets[ti] if not is_member[tet].any(): continue verts = pos[tet] vals = t_s[tet] above = member_per_tet[ti] k = int(n_above[ti]) if k in (1, 3): odd = int(np.flatnonzero(above)[0]) if k == 1 else int(np.flatnonzero(~above)[0]) others = [i for i in range(4) if i != odd] pts = [] for o in others: frac = (threshold - vals[odd]) / (vals[o] - vals[odd]) pts.append(verts[odd] + frac * (verts[o] - verts[odd])) area += 0.5 * np.linalg.norm(np.cross(pts[1] - pts[0], pts[2] - pts[0])) else: hi = np.flatnonzero(above) lo = np.flatnonzero(~above)
def _cp(h, c, verts=verts, vals=vals): frac = (threshold - vals[h]) / (vals[c] - vals[h]) return verts[h] + frac * (verts[c] - verts[h])
a_pt, b_pt = _cp(hi[0], lo[0]), _cp(hi[0], lo[1]) c_pt, d_pt = _cp(hi[1], lo[1]), _cp(hi[1], lo[0]) area += 0.5 * np.linalg.norm(np.cross(c_pt - a_pt, d_pt - b_pt))
face_count = {} for tet in tets: for f in [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]: key = tuple(sorted(tet[list(f)].tolist())) face_count[key] = face_count.get(key, 0) + 1 for key, cnt in face_count.items(): if cnt == 1: v = np.array(key) frac = is_member[v].sum() / 3.0 if frac > 0: q0, q1, q2 = pos[v[0]], pos[v[1]], pos[v[2]] area += frac * 0.5 * np.linalg.norm(np.cross(q1 - q0, q2 - q0)) return area
def _interior_chebyshev_cube_mesh(): """9x6x5 lattice (same domain as `_interior_cube_block_mesh`) with a CONTINUOUS Chebyshev-distance field `t_s = -max(|x-cx|,|y-cy|,|z-cz|)` centered at (4,2,2) -- the level sets of this field are EXACT axis- aligned cubes at any threshold (unlike the binary 0/100 step used elsewhere in this file, whose arbitrary node-count-derived threshold has no meaningful relationship to a genuine half-integer offset). At threshold=-1.5 (exactly bisecting the "distance 1" hot shell and the "distance 2" next shell), `t_s >= -1.5` selects the SAME 27-node block as `_interior_cube_block_mesh` (hand-verified) -- reusing `hot_regions` with top_frac=27/270 reproduces this node set and the correct volume/ centroid/t_max/region_id, but its OWN `hot_threshold` lands at -1.9 (a percentile-interpolation artifact of this exact node-count split, not a physically meaningful cut) -- overridden to the analytically clean -1.5 for this specific hand-check, isolating the area ALGORITHM's behavior at a genuinely representative threshold position from `hot_regions`' own (separately tested) node-selection quirks.""" nx, ny, nz = 9, 6, 5 pos, tets = _grid_mesh(nx, ny, nz) center = np.array([4.0, 2.0, 2.0]) t_s = -np.max(np.abs(pos - center), axis=1) surface_nodes = _surface_nodes(nx, ny, nz)
regions = hot_regions(pos, tets, t_s, top_frac=27.0 / 270.0) assert len(regions) == 1 region = dict(regions[0]) assert region["volume_mm3"] == pytest.approx(27.0) region["hot_threshold"] = -1.5 # see docstring: the clean, symmetric cut return pos, tets, t_s, surface_nodes, region
def test_feeder_recommendations_modulus_level_set_consistent(): """V and A must measure the same body via a genuine continuous-field level set (not an artificially-thresholded binary block). On this fixture the true level set is an exact 3x3x3mm cube (M = side/6 = 0.5 by the Chvorinov identity for any cube); marching tetrahedra on a real linear field still chamfers cube corners/edges (hand-verified: the same chamfering appears in an independent marching- tets reimplementation, not just the shipped code), so M lands near but not exactly at 0.5 -- within the stated 15% band.""" pos, tets, t_s, surface_nodes, region = _interior_chebyshev_cube_mesh() recs = feeder_recommendations([region], pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) assert len(recs) == 1
expected_area = _reference_region_area_marching_tets(pos, tets, region["nodes"], t_s, region["hot_threshold"]) expected_modulus = region["volume_mm3"] / expected_area assert recs[0]["min_modulus_mm"] == pytest.approx(1.2 * expected_modulus, rel=1e-9) assert recs[0]["region_id"] == region["region_id"]
M = recs[0]["min_modulus_mm"] / 1.2 assert abs(M - 0.5) / 0.5 < 0.15, f"M={M} not within 15% of the Chvorinov M=0.5 cube reference"
def test_feeder_recommendations_location_on_top_surface_above_centroid(): pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() regions = hot_regions(pos, tets, t_s) recs = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) loc = recs[0]["location"] centroid = regions[0]["centroid"]
# the recommended point must itself be a surface node... surface_pos = pos[surface_nodes] assert np.any(np.all(np.isclose(surface_pos, loc), axis=1)) # ...directly above the centroid (matching x,y; z at the domain's top face) np.testing.assert_allclose(loc[:2], centroid[:2]) assert loc[2] == pos[:, 2].max()
def test_feeder_recommendations_gravity_rotation_relocates_location(): pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface = _rotatable_sink_mesh()
recs_z = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) np.testing.assert_allclose(recs_z[0]["location"], pos[node_top])
recs_x = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(-1, 0, 0), t_s=t_s) np.testing.assert_allclose(recs_x[0]["location"], pos[node_xface])
recs_y = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, -1, 0), t_s=t_s) np.testing.assert_allclose(recs_y[0]["location"], pos[node_yface])
def test_feeder_recommendations_empty_surface_nodes_raises_value_error(): pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() regions = hot_regions(pos, tets, t_s) with pytest.raises(ValueError): feeder_recommendations(regions, pos, tets, np.array([], dtype=np.int64), gravity_vec=(0, 0, -1), t_s=t_s)
def test_feeder_recommendations_degenerate_region_warns_instead_of_silent_zero(caplog): import logging as _logging pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() # a hand-built region touching no tet at all (an isolated single node # from the fixture's background, never part of any hot cluster) has # volume_mm3 == 0 and boundary area == 0 -> degenerate modulus. degenerate_region = { "nodes": np.array([0]), "centroid": pos[0], "volume_mm3": 0.0, "t_max": 0.0, "region_id": 0, "hot_threshold": t_s.max() + 1.0, # nothing in the mesh qualifies as "hot" } with caplog.at_level(_logging.WARNING, logger="src.shrinkage"): recs = feeder_recommendations([degenerate_region], pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) assert recs[0]["min_modulus_mm"] == 0.0 assert any("degenerate" in rec.message for rec in caplog.records)
def test_feeder_recommendations_region_touching_mesh_skin_exercises_boundary_term(caplog): """a dedicated, in-suite exercise of the domain-boundary term (a region whose own boundary coincides with the mesh's outer surface, so `_region_surface_area`'s "no other side to integrate across" correction path actually fires) -- the gravity- rotation tests above already use a skin-touching region but only assert `location`, never `min_modulus_mm`. Reuses the boss+band fixture (task 2 round 1): the band directly touches 3 domain-boundary faces.""" pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh() regions = hot_regions(pos, tets, t_s, top_frac=top_frac) band_region = next(r for r in regions if set(r["nodes"].tolist()) == band_nodes)
with caplog.at_level("WARNING", logger="src.shrinkage"): recs = feeder_recommendations([band_region], pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) assert not any("degenerate" in rec.message for rec in caplog.records) assert recs[0]["min_modulus_mm"] > 0.0 assert np.isfinite(recs[0]["min_modulus_mm"])
# independent hand-check: the reference reimplementation must agree. expected_area = _reference_region_area_marching_tets( pos, tets, band_region["nodes"], t_s, band_region["hot_threshold"]) expected_modulus = band_region["volume_mm3"] / expected_area assert recs[0]["min_modulus_mm"] == pytest.approx(1.2 * expected_modulus, rel=1e-9)
def _smooth_blob_mesh(spacing, extent=10.0, top_frac=0.05, center_offset=(0.13, 0.29, 0.07)): """A cubic domain of side `extent` mm with a smooth (non-binary-block) field `t_s = -|x - center|^2` -- hottest at the center, smoothly falling off outward, so the top-`top_frac` hot selection is a roughly spherical blob whose boundary genuinely straddles many partial tets at every mesh density (unlike the axis-aligned block fixtures elsewhere in this file, which are deliberately clean/hand-checkable but not representative of a "smooth field" mesh-convergence scenario). `center_offset` is a deliberately non-grid-aligned (sub-cell) shift.""" n = int(round(extent / spacing)) + 1 pos, tets = _grid_mesh(n, n, n, spacing=spacing) center = np.array([extent / 2.0] * 3) + np.array(center_offset) t_s = -((pos - center) ** 2).sum(axis=1) surface_nodes = _surface_nodes(n, n, n) return pos, tets, t_s, top_frac, surface_nodes
def test_feeder_recommendations_modulus_refinement_drift_improves_nonaxis(caplog): """moved from an exact-grid-centered blob to an off-grid-centered spherical blob -- a genuinely NON-axis- aligned fixture, since the round-2 co-area formula's axis-aligned cuts were "the one exact case" and could mask residual anisotropy even on a nominally spherical shape if its center happened to sit on a favorable grid position at both tested densities. Under the OLD (round-1-shipped) all-4-vertices-hot area rule, M = V/A drifted ~-29% between a coarse and 2x-refined mesh of a smooth field (worse than the pre-fix-round-1 baseline of -17%). The marching-tetrahedra area (this round) must keep drift well under the 15% bound.""" import logging as _logging
def modulus_at(spacing): pos, tets, t_s, top_frac, surface_nodes = _smooth_blob_mesh(spacing) regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert len(regions) == 1 with caplog.at_level(_logging.WARNING, logger="src.shrinkage"): recs = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) return recs[0]["min_modulus_mm"] / 1.2
m_coarse = modulus_at(1.0) m_fine = modulus_at(0.5) drift = abs(m_fine - m_coarse) / m_coarse assert drift < 0.15, f"M drift {drift:.1%} exceeds the 15% bound (coarse={m_coarse}, fine={m_fine})"
# ---------------------------------------------------------------------------# (g) Acceptance suite: marching-tets area vs. the ANALYTIC# true value on shapes the old (binarized co-area) formula got badly wrong --# a sphere (curved, converging with refinement, not plateauing), a diagonal# plane cut through a box (exact via a convex-hull oracle), and an# orientation sweep (axis/face-diagonal/space-diagonal/generic normals)# showing the error stays small and roughly ORIENTATION-INDEPENDENT.# ---------------------------------------------------------------------------
def _sphere_region(spacing, extent=12.0, top_frac=0.03, center_offset=(0.13, 0.29, 0.07)): """A spherical hot blob (off-grid center, see `_smooth_blob_mesh`) with its ANALYTIC area/radius derived directly from the threshold `hot_ regions` actually used (R = sqrt(-threshold) exactly, since the continuous field t_s = -|pos-center|^2 has a perfectly spherical level set at every threshold, independent of mesh discretization).""" n = int(round(extent / spacing)) + 1 pos, tets = _grid_mesh(n, n, n, spacing=spacing) center = np.array([extent / 2.0] * 3) + np.array(center_offset) t_s = -((pos - center) ** 2).sum(axis=1) threshold = np.percentile(t_s, 100 * (1 - top_frac)) nodes = np.flatnonzero(t_s >= threshold) radius = np.sqrt(-threshold) true_area = 4.0 * np.pi * radius ** 2 return pos, tets, nodes, t_s, threshold, true_area
def test_region_area_sphere_converges_not_plateaus(): """sphere-field area must converge toward the analytic 4*pi*R^2 as the mesh refines (error DECREASING), not plateau at the ~24-29% measured for the binarized co-area formula.""" errors = [] for spacing in (1.0, 0.5, 0.25): pos, tets, nodes, t_s, threshold, true_area = _sphere_region(spacing) area = _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold) errors.append(abs(area - true_area) / true_area)
assert errors[0] < 0.10, f"coarsest-mesh sphere error too high: {errors[0]:.1%}" assert errors[-1] < errors[0], f"error did not decrease with refinement: {errors}" assert errors[-1] < 0.02, f"finest-mesh sphere error too high: {errors[-1]:.1%}"
def _halfspace_box_total_area(box_extent, normal, offset): """Analytic total boundary area of `box ∩ {p : normal.p <= offset}` for an axis-aligned box `[0,box_extent]^3` -- exact via `scipy.spatial. ConvexHull` on the (convex) polytope's vertices: the box corners already inside the half-space, plus the half-space plane's intersection points with each of the box's 12 edges. Serves as the analytic reference for the diagonal-cut and orientation-sweep tests below (hand-verified against known closed forms: an axis-aligned cut of a 10mm cube at x=5 gives exactly 400mm^2 = surface area of a 5x10x10 box; a cut through the center along the space diagonal gives 300 [half the original 600mm^2 surface, split evenly by symmetry] + 3*sqrt(3)/4*10^2 [=129.90, the well-known hexagonal cross-section area of a cube bisected perpendicular to its space diagonal] = 429.90).""" from scipy.spatial import ConvexHull
normal = np.asarray(normal, dtype=np.float64) normal = normal / np.linalg.norm(normal) lo, hi = 0.0, float(box_extent) corners = np.array([[x, y, z] for x in (lo, hi) for y in (lo, hi) for z in (lo, hi)]) edges = [] for xi in range(2): for yi in range(2): for zi in range(2): idx0 = 4 * xi + 2 * yi + zi if xi == 0: edges.append((idx0, 4 * 1 + 2 * yi + zi)) if yi == 0: edges.append((idx0, 4 * xi + 2 * 1 + zi)) if zi == 0: edges.append((idx0, 4 * xi + 2 * yi + 1))
pts = [c for c in corners if normal @ c - offset <= 1e-9] for i, j in edges: vi, vj = corners[i], corners[j] si, sj = normal @ vi - offset, normal @ vj - offset if si * sj < 0: t = si / (si - sj) pts.append(vi + t * (vj - vi)) return ConvexHull(np.array(pts)).area
def _diagonal_cut_region(spacing, normal, extent=10.0, top_frac=0.3): pos, tets = _grid_mesh(int(round(extent / spacing)) + 1, int(round(extent / spacing)) + 1, int(round(extent / spacing)) + 1, spacing=spacing) normal = np.asarray(normal, dtype=np.float64) normal = normal / np.linalg.norm(normal) t_s = -(pos @ normal) threshold = np.percentile(t_s, 100 * (1 - top_frac)) nodes = np.flatnonzero(t_s >= threshold) true_area = _halfspace_box_total_area(extent, normal, offset=-threshold) return pos, tets, nodes, t_s, threshold, true_area
def test_region_area_diagonal_plane_cut_error_far_below_old_bias(): """a half-space region cut by a plane along the space diagonal (1,1,1) -- normal not aligned with any mesh axis. Error must be far below the reported +36% for the prior (binarized co-area) formula.""" for spacing in (1.0, 0.5): pos, tets, nodes, t_s, threshold, true_area = _diagonal_cut_region(spacing, (1, 1, 1)) area = _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold) err = abs(area - true_area) / true_area assert err < 0.10, f"spacing={spacing}: diagonal-cut error {err:.1%} too high"
# ---------------------------------------------------------------------------# (f) hot_regions volume -- fraction-weighted rule:# each tet contributes tet_volume * n_hot_vertices/4, replacing an earlier# all-4-vertices-hot rule that discarded (undercounted) every boundary tet.# ---------------------------------------------------------------------------
def test_hot_regions_volume_fraction_weighted_partial_tets_hand_checked(): """An isolated single unit-cube mesh (2x2x2 nodes, spacing 1mm, no neighboring cubes -- nothing outside this mesh to contaminate the count): corner 7 (the (1,1,1) corner) is background/cold, the other 7 corners are hot. Every one of the cube's 6 Kuhn tets contains corner 7 (hand-checked from the tet list), so every tet has exactly 3 of its 4 vertices hot; each tet has volume 1/6 mm^3 (regular unit cube / 6). Total fraction-weighted volume = 6 * (1/6) * (3/4) = 0.75 mm^3 exactly. Under the old all-4-vertices rule this region would score 0.0 mm^3 (no tet has all 4 vertices hot) -- the undercount this fix targets.""" pos, tets = _grid_mesh(2, 2, 2) t_s = np.full(8, 100.0) t_s[7] = 0.0 top_frac = 7.0 / 8.0 regions = hot_regions(pos, tets, t_s, top_frac=top_frac) assert len(regions) == 1 assert set(regions[0]["nodes"].tolist()) == {0, 1, 2, 3, 4, 5, 6} assert regions[0]["volume_mm3"] == pytest.approx(0.75)
def test_hot_regions_volume_full_mesh_matches_analytic_total(): """Sanity/regression check: when EVERY node is hot (top_frac=1.0), no tet straddles the region boundary (n_hot_vertices == 4 everywhere), so the fraction-weighted rule reduces to the plain tet-volume sum, which for a unit-spacing (nx-1)x(ny-1)x(nz-1) lattice equals that product exactly.""" nx, ny, nz = 4, 3, 3 pos, tets = _grid_mesh(nx, ny, nz) t_s = np.ones(pos.shape[0]) # uniform -> every node is "hot" at top_frac=1.0 regions = hot_regions(pos, tets, t_s, top_frac=1.0) assert len(regions) == 1 assert regions[0]["volume_mm3"] == pytest.approx((nx - 1) * (ny - 1) * (nz - 1))
# ---------------------------------------------------------------------------# (e) determinism -- two runs on the same inputs produce identical results.# ---------------------------------------------------------------------------
def test_determinism_hot_regions_and_downstream(): pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() no_feed = np.array([], dtype=np.int64)
regions1 = hot_regions(pos, tets, t_s) regions2 = hot_regions(pos, tets, t_s) assert len(regions1) == len(regions2) == 1 np.testing.assert_array_equal(regions1[0]["nodes"], regions2[0]["nodes"]) np.testing.assert_allclose(regions1[0]["centroid"], regions2[0]["centroid"]) assert regions1[0]["volume_mm3"] == regions2[0]["volume_mm3"] assert regions1[0]["t_max"] == regions2[0]["t_max"] assert regions1[0]["region_id"] == regions2[0]["region_id"]
macro1 = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=2.5) macro2 = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=2.5) assert macro1[0]["severity"] == macro2[0]["severity"]
feeders1 = feeder_recommendations(regions1, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) feeders2 = feeder_recommendations(regions2, pos, tets, surface_nodes, gravity_vec=(0, 0, -1), t_s=t_s) assert feeders1[0]["min_modulus_mm"] == feeders2[0]["min_modulus_mm"] np.testing.assert_array_equal(feeders1[0]["location"], feeders2[0]["location"])
# ---------------------------------------------------------------------------# screen_casting: one call combining the Niyama proxy, macro-shrinkage, top# sinks and feeder recommendations. `feed_nodes` (adiabatic-face nodes) is# separate from `surface_nodes` (the whole free surface, used for sink and# feeder placement); None means no feed source, so every region is unfed.# ---------------------------------------------------------------------------
def test_screen_casting_proxy_niyama_when_fields_omitted(): nx = ny = nz = 4 pos, tets = _grid_mesh(nx, ny, nz) t_s = pos[:, 0].copy() + 1.0 surface_nodes = _surface_nodes(nx, ny, nz) TL, TS = 1400.0, 1100.0
result = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "grey_iron")
assert result["niyama_source"] == "proxy" expected_ny = niyama_proxy(pos, tets, t_s, TL, TS) np.testing.assert_allclose(result["niyama"], expected_ny) expected_risk = porosity_risk(expected_ny) np.testing.assert_array_equal(result["porosity_risk"], expected_risk) assert result["material"] == {"alloy_family": "grey_iron", "shrinkage_pct": 0.0}
def test_screen_casting_unknown_alloy_family_raises_loud_error_naming_known_families(): pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh() with pytest.raises(KeyError) as exc_info: screen_casting(pos, tets, surface_nodes, t_s, 1400.0, 1100.0, "unobtainium") msg = str(exc_info.value) assert "unobtainium" in msg for family in SHRINKAGE_PCT: assert family in msg
def test_screen_casting_feed_nodes_default_is_empty_bare_casting_convention(): pos, tets, t_s, surface_nodes, boss_nodes, band_nodes = _unfed_boss_and_fed_band_10pct_mesh() TL, TS = 1400.0, 1100.0
default_call = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "steel") explicit_empty = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "steel", feed_nodes=np.array([], dtype=np.int64)) assert len(default_call["macro_shrinkage"]) == len(explicit_empty["macro_shrinkage"]) == 2
fed_call = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "steel", feed_nodes=surface_nodes) assert len(fed_call["macro_shrinkage"]) == 1 # band fed away via feed_nodes=surface_nodes
def test_region_area_orientation_sweep_spread_far_below_old_bias(): """The SAME half-space-cut construction at several normals (axis-aligned, face-diagonal, space- diagonal, and a generic non-symmetric direction) -- the spread of relative errors across orientations must be far below the ~29% orientation sensitivity of a binarized co-area estimate.""" orientations = { "axis-x": (1, 0, 0), "face-diag": (1, 1, 0), "space-diag": (1, 1, 1), "generic": (2, 1, 0.3), } errors = {} for name, normal in orientations.items(): pos, tets, nodes, t_s, threshold, true_area = _diagonal_cut_region(0.5, normal) area = _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold) errors[name] = abs(area - true_area) / true_area
spread = max(errors.values()) - min(errors.values()) assert spread < 0.10, f"orientation-sweep spread {spread:.1%} too high: {errors}" assert all(e < 0.10 for e in errors.values()), f"an orientation exceeded 10% error: {errors}"1234e1dd5d9227a9495af51177f52f78bd28507134c19e1a82d9341fbf49733a820a gnn_v5.1.safetensors0a0b9caa7f1ebcea94e220dd4704ef63309c5f1619fbc20427f90ae1e6727b83 gbm_total_v3.skopsbd4469c06490c4eb8b3d90b24144b2fd7059ae8faab7012e78b12cfaaf25239a gbm_std_v2.skops5c24d0c99064ea264e17b44c9c419f73e6793e509215b7099cf5a5902c9a12ae ood_ranges.json.gitattributes+2
.gitignoreDeleted-10
README.md+31-33
config.jsonAdded+38
data/properties/README.mdDeleted-25
data/properties/materials.csvDeleted-3
data/properties/molds.csvDeleted-2
weights/gbm_std_v2.skops → gbm_std_v2.skopsRenamed
weights/gbm_total_v3.skops → gbm_total_v3.skopsRenamed
weights/gnn_v5.1.safetensors → gnn_v5.1.safetensorsRenamed
weights/ood_ranges.json → ood_ranges.jsonRenamed
requirements.txtDeleted-20
src/features.pyDeleted-109
src/gbm_heads.pyDeleted-69
src/geometry.pyDeleted-128
src/hybrid.pyDeleted-287
src/inference_props.pyDeleted-170
src/mesh_cache.pyDeleted-128
src/meshing.pyDeleted-368
src/model_api.pyDeleted-80
src/model_gnn.pyDeleted-136
src/msh_parse.pyDeleted-67
src/ood.pyDeleted-23
src/predict_casting.pyDeleted-283
src/release_io.pyDeleted-47
src/shrinkage.pyDeleted-498
src/viz.pyDeleted-90
src/webapp.pyDeleted-561
tests/__init__.pyDeleted
tests/conftest.pyDeleted-49
tests/test_features.pyDeleted-55
tests/test_gbm_heads.pyDeleted-55
tests/test_geometry.pyDeleted-36
tests/test_hybrid.pyDeleted-336
tests/test_hybrid_max_anchor.pyDeleted-86
tests/test_inference_props.pyDeleted-102
tests/test_local_modulus.pyDeleted-63
tests/test_mesh_cache.pyDeleted-176
tests/test_meshing.pyDeleted-443
tests/test_model_api.pyDeleted-25
tests/test_model_gnn.pyDeleted-66
tests/test_msh_parse.pyDeleted-22
tests/test_ood.pyDeleted-19
tests/test_predict_casting.pyDeleted-106
tests/test_release_io.pyDeleted-55
tests/test_shrinkage.pyDeleted-1186
weights/SHA256SUMSDeleted-4