eugenmik commited on
Commit
8299b46
·
verified ·
1 Parent(s): 20d2438

Model-only repository: weights, config.json and model card; code lives on GitHub

Browse files
.gitattributes CHANGED
@@ -38,3 +38,5 @@ assets/mesh.png filter=lfs diff=lfs merge=lfs -text
38
  assets/solidification.gif filter=lfs diff=lfs merge=lfs -text
39
  weights/gbm_std_v2.skops filter=lfs diff=lfs merge=lfs -text
40
  weights/gbm_total_v3.skops filter=lfs diff=lfs merge=lfs -text
 
 
 
38
  assets/solidification.gif filter=lfs diff=lfs merge=lfs -text
39
  weights/gbm_std_v2.skops filter=lfs diff=lfs merge=lfs -text
40
  weights/gbm_total_v3.skops filter=lfs diff=lfs merge=lfs -text
41
+ gbm_std_v2.skops filter=lfs diff=lfs merge=lfs -text
42
+ gbm_total_v3.skops filter=lfs diff=lfs merge=lfs -text
.gitignore DELETED
@@ -1,10 +0,0 @@
1
- # Data stays out of the repository except the property tables.
2
- data/*
3
- !data/properties/
4
- !data/properties/*
5
- # Prediction output and the mesh cache
6
- runs/
7
- # Python
8
- __pycache__/
9
- *.pyc
10
- .pytest_cache/
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -51,7 +51,7 @@ shrinkage-risk indicator, not a porosity label.
51
  | Parameters | about 1.85 M (GNN) plus two `HistGradientBoostingRegressor` heads |
52
  | Training data | FEniCSx enthalpy-method conduction simulations: about 9.7k primitive cases, 4.7k multi-alloy cases, 500 real-part cases |
53
  | License | Apache-2.0 for code and weights |
54
- | Pipeline | STEP import, meshing and result export are documented on [GitHub](https://github.com/eugenmik/castsolid-gnn) |
55
  | Author | Eugen Miknevic, independent foundry engineer |
56
 
57
  ## Contents
@@ -71,27 +71,29 @@ shrinkage-risk indicator, not a porosity label.
71
 
72
  The model reads one casting at a time.
73
 
74
- **Mesh.** A tetrahedral volume mesh in millimetres, in gmsh 2.2 ASCII format (`.msh`). Surface
75
  triangles that cool into the mold belong to a physical group named `Cooling`; in this release
76
  that is the whole outer surface. The model was trained on meshes of roughly 7,500 to 10,000
77
  nodes, and that is the density it should be given. It does not use node numbering or absolute
78
  coordinates: node inputs are distances, flags and volume-type quantities in millimetres, and
79
  edges carry only relative displacements between neighbouring nodes.
80
 
81
- **Alloy and mold.** Eight numbers describe the material and the mold: thermal conductivity,
82
- density, specific heat, latent heat, liquidus, solidus, pouring temperature and mold effusivity.
83
- Two alloys are tabulated in `data/properties/`, `EN-GJS-400-15` (ductile iron, the default) and
84
- `G20Mn5` (cast steel), together with one mold, green sand. You can also pass your own eight
85
- values.
86
 
87
- **Output.** One number per node: the time in seconds at which that node cools through the
88
  solidus. The maximum over all nodes is the total solidification time, and the 10% of nodes with
89
  the largest times are the hot spots.
90
 
91
  ## How to use
92
 
 
 
 
93
  ```bash
94
- hf download eugenmik/castsolid-gnn --local-dir castsolid-gnn
95
  cd castsolid-gnn
96
  python -m venv .venv && source .venv/bin/activate
97
  pip install "torch==2.3.0" --index-url https://download.pytorch.org/whl/cpu
@@ -105,7 +107,7 @@ in both URLs. Then, from the repository root:
105
  ```python
106
  from src.model_api import CastSolidModel
107
 
108
- model = CastSolidModel() # loads the three weight files once
109
  t = model.predict("part.msh") # EN-GJS-400-15 in green sand
110
  t_steel = model.predict("part.msh", alloy="G20Mn5")
111
 
@@ -113,20 +115,19 @@ t.max() # total solidification time, s
113
  hot = CastSolidModel.hotspots(t) # boolean mask, top 10% of nodes
114
  ```
115
 
116
- `predict` returns a NumPy array in the node order of the `.msh` file. To use another alloy,
117
- pass `props_json="my_alloy.json"` with exactly these keys (SI units, temperatures in °C;
118
- 1018 is the green-sand effusivity):
 
119
 
120
  ```json
121
  {"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0,
122
  "TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1018.0}
123
  ```
124
 
125
- If you start from a STEP file, the
126
- [GitHub repository](https://github.com/eugenmik/castsolid-gnn) has the pipeline that heals the
127
- CAD, builds a mesh at the right density, runs this model and writes the result for ParaView.
128
- The same code is included here, so `python -m src.predict_casting part.step` works in this
129
- repository too.
130
 
131
  ## Model architecture
132
 
@@ -211,21 +212,17 @@ spread is not monotone in `a`, so the solver brackets the smallest root explicit
211
 
212
  | File | Size | Content |
213
  |---|---:|---|
214
- | `weights/gnn_v5.1.safetensors` | 7.4 MB | GNN weights, feature and target normalization, and the architecture config (in the safetensors metadata) |
215
- | `weights/gbm_total_v3.skops` | 0.6 MB | Total-time head |
216
- | `weights/gbm_std_v2.skops` | 0.8 MB | Spread head |
217
- | `weights/ood_ranges.json` | <1 KB | Training envelope (part volume, size, distance to cooling) for out-of-distribution warnings |
218
- | `weights/SHA256SUMS` | <1 KB | Checksums |
219
- | `src/model_api.py` | | `CastSolidModel`, the mesh-in, field-out interface shown above |
220
- | `src/features.py`, `src/model_gnn.py`, `src/gbm_heads.py`, `src/hybrid.py` | | The model: node features, graph network, gradient-boosted heads, recomposition |
221
- | `data/properties/` | | Alloy and mold tables ([README](data/properties/README.md)) |
222
 
223
  None of the weight files can execute code when loaded. The GNN is stored as
224
  [safetensors](https://github.com/huggingface/safetensors) and the heads as
225
- [skops](https://skops.readthedocs.io/); before loading a skops file, `src/release_io.py` checks
226
- every type it names against an allowlist of scikit-learn and NumPy types. The rest of `src/`
227
- (meshing a STEP file, shrinkage screening, result export, a browser viewer) and `tests/` are the
228
- supporting pipeline, described on GitHub. Training code is not part of this release.
229
 
230
  ## Training data
231
 
@@ -328,7 +325,7 @@ Known limitations:
328
  3. Meshes much coarser or finer than the training density (about 7,500 to 10,000 nodes) are
329
  outside what the model has seen. At that density, large thin-walled parts can be
330
  under-resolved.
331
- 4. The training envelope in `weights/ood_ranges.json` only covers part size and distance to
332
  cooling. It is not a calibrated uncertainty estimate.
333
 
334
  Treat each prediction as a screening hypothesis: where should an engineer look first, and is
@@ -346,7 +343,7 @@ them:
346
  | `gbm_total_v3.skops` | `hgb_v3.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range |
347
  | `gbm_std_v2.skops` | `hgb_std_v2.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range |
348
 
349
- The code in this repository was also run side by side with the internal pipeline on five
350
  production parts (two of them with both alloys), plus a fixed-size mesh with a custom property
351
  set: every output field matched exactly. The heads were trained with scikit-learn 1.5.2, and other versions may refuse to load them or change
352
  their output. Other versions used: Python 3.11, PyTorch 2.3.0, PyTorch Geometric 2.7.0,
@@ -355,7 +352,8 @@ NumPy 2.x.
355
  ## License and citation
356
 
357
  Code and weights are released under the [Apache License 2.0](LICENSE). The tables in
358
- `data/properties/` are modelling inputs, not certified material specifications.
 
359
 
360
  ```bibtex
361
  @software{miknevic_casting_gnn_2026,
 
51
  | Parameters | about 1.85 M (GNN) plus two `HistGradientBoostingRegressor` heads |
52
  | Training data | FEniCSx enthalpy-method conduction simulations: about 9.7k primitive cases, 4.7k multi-alloy cases, 500 real-part cases |
53
  | License | Apache-2.0 for code and weights |
54
+ | Code | [github.com/eugenmik/castsolid-gnn](https://github.com/eugenmik/castsolid-gnn): loading, inference, and the STEP-to-result pipeline |
55
  | Author | Eugen Miknevic, independent foundry engineer |
56
 
57
  ## Contents
 
71
 
72
  The model reads one casting at a time.
73
 
74
+ The mesh is a tetrahedral volume mesh in millimetres, in gmsh 2.2 ASCII format (`.msh`). Surface
75
  triangles that cool into the mold belong to a physical group named `Cooling`; in this release
76
  that is the whole outer surface. The model was trained on meshes of roughly 7,500 to 10,000
77
  nodes, and that is the density it should be given. It does not use node numbering or absolute
78
  coordinates: node inputs are distances, flags and volume-type quantities in millimetres, and
79
  edges carry only relative displacements between neighbouring nodes.
80
 
81
+ Eight numbers describe the alloy and the mold: thermal conductivity, density, specific heat,
82
+ latent heat, liquidus, solidus, pouring temperature and mold effusivity. The code ships two
83
+ tabulated alloys, `EN-GJS-400-15` (ductile iron, the default) and `G20Mn5` (cast steel), and one
84
+ mold, green sand. You can also pass your own eight values.
 
85
 
86
+ The output is one number per node: the time in seconds at which that node cools through the
87
  solidus. The maximum over all nodes is the total solidification time, and the 10% of nodes with
88
  the largest times are the hot spots.
89
 
90
  ## How to use
91
 
92
+ This repository holds the weights and this card. The code that loads and runs them is on
93
+ [GitHub](https://github.com/eugenmik/castsolid-gnn):
94
+
95
  ```bash
96
+ git clone https://github.com/eugenmik/castsolid-gnn
97
  cd castsolid-gnn
98
  python -m venv .venv && source .venv/bin/activate
99
  pip install "torch==2.3.0" --index-url https://download.pytorch.org/whl/cpu
 
107
  ```python
108
  from src.model_api import CastSolidModel
109
 
110
+ model = CastSolidModel.from_pretrained() # downloads this repository's files once
111
  t = model.predict("part.msh") # EN-GJS-400-15 in green sand
112
  t_steel = model.predict("part.msh", alloy="G20Mn5")
113
 
 
115
  hot = CastSolidModel.hotspots(t) # boolean mask, top 10% of nodes
116
  ```
117
 
118
+ `from_pretrained()` fetches `config.json` and the files it lists into the local Hugging Face
119
+ cache, pinned to the `v5.1` tag; later calls run offline. `predict` returns a NumPy array in the
120
+ node order of the `.msh` file. To use another alloy, pass `props_json="my_alloy.json"` with
121
+ exactly these keys (SI units, temperatures in °C; 1018 is the green-sand effusivity):
122
 
123
  ```json
124
  {"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0,
125
  "TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1018.0}
126
  ```
127
 
128
+ To start from a STEP file instead of a mesh, run `python -m src.predict_casting part.step` in
129
+ the GitHub repository. It heals the CAD, builds a mesh at the right density, runs the model and
130
+ writes the result for ParaView.
 
 
131
 
132
  ## Model architecture
133
 
 
212
 
213
  | File | Size | Content |
214
  |---|---:|---|
215
+ | `config.json` | 1 KB | Model version, file list, architecture summary, recomposition weights and input description |
216
+ | `gnn_v5.1.safetensors` | 7.4 MB | GNN weights, feature and target normalization, and the architecture config (in the safetensors metadata) |
217
+ | `gbm_total_v3.skops` | 0.6 MB | Total-time head |
218
+ | `gbm_std_v2.skops` | 0.8 MB | Spread head |
219
+ | `ood_ranges.json` | <1 KB | Training envelope (part volume, size, distance to cooling) used for out-of-distribution warnings |
 
 
 
220
 
221
  None of the weight files can execute code when loaded. The GNN is stored as
222
  [safetensors](https://github.com/huggingface/safetensors) and the heads as
223
+ [skops](https://skops.readthedocs.io/). Before it opens a skops file, the loader on GitHub checks
224
+ every type the file names against an allowlist of scikit-learn and NumPy types. Training code is
225
+ not published.
 
226
 
227
  ## Training data
228
 
 
325
  3. Meshes much coarser or finer than the training density (about 7,500 to 10,000 nodes) are
326
  outside what the model has seen. At that density, large thin-walled parts can be
327
  under-resolved.
328
+ 4. The training envelope in `ood_ranges.json` only covers part size and distance to
329
  cooling. It is not a calibrated uncertainty estimate.
330
 
331
  Treat each prediction as a screening hypothesis: where should an engineer look first, and is
 
343
  | `gbm_total_v3.skops` | `hgb_v3.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range |
344
  | `gbm_std_v2.skops` | `hgb_std_v2.joblib` | Identical predictions on 10,002 probe rows spanning each feature's training split range |
345
 
346
+ The published inference code was also run side by side with the internal pipeline on five
347
  production parts (two of them with both alloys), plus a fixed-size mesh with a custom property
348
  set: every output field matched exactly. The heads were trained with scikit-learn 1.5.2, and other versions may refuse to load them or change
349
  their output. Other versions used: Python 3.11, PyTorch 2.3.0, PyTorch Geometric 2.7.0,
 
352
  ## License and citation
353
 
354
  Code and weights are released under the [Apache License 2.0](LICENSE). The tables in
355
+ `data/properties/` of the GitHub repository are modelling inputs, not certified material
356
+ specifications.
357
 
358
  ```bibtex
359
  @software{miknevic_casting_gnn_2026,
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "casting-solidification-gnn",
3
+ "version": "v5.1",
4
+ "code": "https://github.com/eugenmik/castsolid-gnn",
5
+ "files": {
6
+ "gnn": "gnn_v5.1.safetensors",
7
+ "total_head": "gbm_total_v3.skops",
8
+ "spread_head": "gbm_std_v2.skops",
9
+ "ood_ranges": "ood_ranges.json"
10
+ },
11
+ "gnn": {
12
+ "architecture": "MeshGraphNet-style encode-process-decode with FiLM conditioning",
13
+ "node_features": 15,
14
+ "edge_features": 5,
15
+ "conditioning_features": 5,
16
+ "hidden": 128,
17
+ "message_passing_blocks": 12,
18
+ "knn_neighbours": 16,
19
+ "graph": "tetrahedral mesh edges union k-nearest neighbours"
20
+ },
21
+ "heads": {
22
+ "total_head_features": 16,
23
+ "spread_head_features": 17,
24
+ "sklearn_version": "1.5.2"
25
+ },
26
+ "recomposition": {
27
+ "method": "soft_anchor",
28
+ "quantile": 0.995,
29
+ "w_total": 1.0,
30
+ "w_std": 4.0
31
+ },
32
+ "input": {
33
+ "mesh": "gmsh 2.2 ASCII tetrahedral mesh in mm, cooling surface tagged 'Cooling'",
34
+ "mesh_nodes_trained": [7500, 10000],
35
+ "properties": ["k", "rho", "cp", "L_kJ_kg", "TL", "TS", "Tpour", "mold_effusivity"]
36
+ },
37
+ "output": "solidification time in seconds per mesh node"
38
+ }
data/properties/README.md DELETED
@@ -1,25 +0,0 @@
1
- # Property tables
2
-
3
- These two CSV files hold the material and mold rows that inference reads.
4
-
5
- - `materials.csv` has two grades: `EN-GJS-400-15` (ductile iron, the default) and `G20Mn5`
6
- (cast steel). Columns: thermal conductivity `k_W_mK`, density `rho_kg_m3`, specific heat
7
- `cp_J_kgK`, latent heat `L_kJ_kg`, liquidus `TL_C`, solidus `TS_C` and the pouring
8
- temperature range `Tpour_lo_C`/`Tpour_hi_C`. The prediction uses the midpoint of that range.
9
- - `molds.csv` has one mold system, `green_sand`. The model reads its thermal effusivity
10
- (`effusivity_W_s05_m2K`), which is the square root of the product of the conductivity,
11
- density and specific heat in the same row.
12
-
13
- The values come from handbook data. They are modelling inputs, not certified material
14
- specifications. Check them against your actual alloy and process, and keep the exact row you
15
- used with every result.
16
-
17
- To try an alloy that is not listed, pass the properties directly instead of editing the table:
18
-
19
- ```bash
20
- python -m src.predict_casting part.step --props my_alloy.json
21
- ```
22
-
23
- `my_alloy.json` needs exactly these keys: `k`, `rho`, `cp`, `L_kJ_kg`, `TL`, `TS`, `Tpour`,
24
- `mold_effusivity`. The model was trained on iron and steel grades in sand molds; properties far
25
- from that range are extrapolation.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data/properties/materials.csv DELETED
@@ -1,3 +0,0 @@
1
- material_id,family,k_W_mK,rho_kg_m3,cp_J_kgK,L_kJ_kg,TL_C,TS_C,Tpour_lo_C,Tpour_hi_C
2
- EN-GJS-400-15,ductile_iron,32.9,6800,515,220,1160,1120,1250,1270
3
- G20Mn5,low_alloy_steel,48.4,7800,590,260,1530,1495,1620,1640
 
 
 
 
data/properties/molds.csv DELETED
@@ -1,2 +0,0 @@
1
- mold_system,k_W_mK,rho_kg_m3,cp_J_kgK,effusivity_W_s05_m2K
2
- green_sand,0.607,1520,1123,1018
 
 
 
weights/gbm_std_v2.skops → gbm_std_v2.skops RENAMED
File without changes
weights/gbm_total_v3.skops → gbm_total_v3.skops RENAMED
File without changes
weights/gnn_v5.1.safetensors → gnn_v5.1.safetensors RENAMED
File without changes
weights/ood_ranges.json → ood_ranges.json RENAMED
File without changes
requirements.txt DELETED
@@ -1,20 +0,0 @@
1
- # Install PyTorch 2.3 for your platform first, plus the matching torch-cluster
2
- # wheel, for example on CPU:
3
- # pip install "torch==2.3.0" --index-url https://download.pytorch.org/whl/cpu
4
- # pip install torch-cluster -f https://data.pyg.org/whl/torch-2.3.0+cpu.html
5
- numpy>=2.0
6
- scipy>=1.11
7
- scikit-learn==1.5.2
8
- skops>=0.10
9
- safetensors>=0.4
10
- torch-geometric==2.7.0
11
- gmsh>=4.13
12
- meshio>=5.3
13
- pytest>=8.3
14
- # Optional: local browser viewer (python -m src.webapp)
15
- pyvista>=0.44
16
- trame>=3.6
17
- trame-vtk>=2.8
18
- trame-vuetify>=2.7
19
- trame-pyvista>=0.1
20
- imageio>=2.34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/features.py DELETED
@@ -1,109 +0,0 @@
1
- """Node features and the alloy/mold conditioning vector.
2
-
3
- Every feature comes from the mesh and its surface tags ("Cooling", optionally
4
- "Adiabatic"), in millimetres. Nothing depends on node numbering, file names or
5
- absolute position.
6
- """
7
- import numpy as np
8
-
9
- from src.geometry import (total_area, mesh_volume, nearest_distance, boundary_node_mask,
10
- edges_from_tets, geodesic_distance, local_modulus)
11
-
12
- FEATURE_NAMES = [
13
- "geodesic_d_cool", "d_surf", "d_adiab",
14
- "is_cooling", "is_adiabatic", "is_interior",
15
- "volume_mm3", "surface_area_mm2", "cooling_area_frac",
16
- "geodesic_d_adiab",
17
- "local_modulus_r5", "local_modulus_r15", "local_modulus_r40",
18
- "boundary_extraction", "boundary_heat_input",
19
- ]
20
- LOCAL_MODULUS_RADII = (5.0, 15.0, 40.0)
21
-
22
- # Alloy/mold conditioning vector (raw, not standardized).
23
- G_VECTOR_NAMES = ["Ste", "dTf_norm", "alpha_ratio", "superheat_norm", "mold_eff_norm"]
24
- T_REF = 1000.0 # deg C, normalizes temperature differences
25
- ALPHA_REF = 1e-5 # m^2/s, typical alloy thermal diffusivity
26
- MOLD_EFF_REF = 1250.0 # W*s^0.5/(m^2*K), reference mold effusivity
27
-
28
-
29
- def alloy_g_vector(props: dict) -> np.ndarray:
30
- """Five dimensionless numbers describing alloy and mold.
31
-
32
- `props` keys: k, rho, cp, L_kJ_kg, TL, TS, Tpour, mold_effusivity."""
33
- k = float(props["k"]); rho = float(props["rho"]); cp = float(props["cp"])
34
- L = float(props["L_kJ_kg"]); TL = float(props["TL"]); TS = float(props["TS"])
35
- Tpour = float(props["Tpour"]); b_mold = float(props["mold_effusivity"])
36
-
37
- Ste = cp * (Tpour - TS) / (L * 1000.0)
38
- dTf_norm = (TL - TS) / T_REF
39
- alpha_ratio = (k / (rho * cp)) / ALPHA_REF
40
- superheat_norm = (Tpour - TL) / T_REF
41
- mold_eff_norm = b_mold / MOLD_EFF_REF
42
- return np.array([Ste, dTf_norm, alpha_ratio, superheat_norm, mold_eff_norm],
43
- dtype=np.float64)
44
-
45
-
46
- def node_features(mesh, mold_effusivity: float) -> dict:
47
- """The (N, 15) float32 feature matrix `X`, node positions `pos` (mm) and
48
- the unique tetrahedral mesh edges `mesh_edges` for one casting."""
49
- xyz = mesh.node_xyz
50
- N = xyz.shape[0]
51
- cool_tri = mesh.tris.get("Cooling", np.empty((0, 3), np.int64))
52
- adiab_tri = mesh.tris.get("Adiabatic", np.empty((0, 3), np.int64))
53
-
54
- cool_mask = boundary_node_mask(N, cool_tri)
55
- adiab_mask = boundary_node_mask(N, adiab_tri)
56
- adiab_only = adiab_mask & ~cool_mask
57
- surf_mask = cool_mask | adiab_mask
58
- interior_mask = ~surf_mask
59
-
60
- bbox = xyz.max(0) - xyz.min(0)
61
- bbox_diag = float(np.linalg.norm(bbox))
62
-
63
- edges = edges_from_tets(mesh.tets)
64
- edge_len = np.linalg.norm(xyz[edges[:, 0]] - xyz[edges[:, 1]], axis=1) if edges.shape[0] else np.empty(0)
65
- src = np.flatnonzero(cool_mask)
66
- g_cool = geodesic_distance(N, edges, edge_len, src)
67
- eucl_cool = nearest_distance(xyz, xyz[cool_mask])
68
- eucl_cool = np.where(np.isinf(eucl_cool), bbox_diag, eucl_cool)
69
- g_cool = np.where(np.isinf(g_cool), eucl_cool, g_cool)
70
-
71
- d_surf = nearest_distance(xyz, xyz[surf_mask])
72
- d_adiab = nearest_distance(xyz, xyz[adiab_mask])
73
- d_surf = np.where(np.isinf(d_surf), bbox_diag, d_surf)
74
- d_adiab = np.where(np.isinf(d_adiab), bbox_diag, d_adiab)
75
-
76
- area_cool = total_area(xyz, cool_tri)
77
- area_total = area_cool + total_area(xyz, adiab_tri)
78
- cool_frac = area_cool / area_total if area_total > 0 else 0.0
79
- volume = mesh_volume(xyz, mesh.tets)
80
-
81
- g_adiab = geodesic_distance(N, edges, edge_len, np.flatnonzero(adiab_mask))
82
- g_adiab = np.where(np.isinf(g_adiab), d_adiab, g_adiab)
83
- lm = local_modulus(xyz, mesh.tets, cool_tri, edges, edge_len, LOCAL_MODULUS_RADII)
84
-
85
- # Boundary channels. Surface nodes carry the mold effusivity (how fast the
86
- # mold draws heat); interior nodes carry 0. The heat-input channel is for
87
- # heat sources on the boundary, and a plain sand-mold surface has none.
88
- boundary_extraction = np.zeros(N, dtype=np.float32)
89
- boundary_extraction[cool_mask] = mold_effusivity
90
- boundary_extraction[adiab_only] = mold_effusivity
91
- boundary_heat_input = np.zeros(N, dtype=np.float32)
92
-
93
- cols = {
94
- "geodesic_d_cool": g_cool, "d_surf": d_surf, "d_adiab": d_adiab,
95
- "is_cooling": cool_mask.astype(np.float32),
96
- "is_adiabatic": adiab_only.astype(np.float32),
97
- "is_interior": interior_mask.astype(np.float32),
98
- "volume_mm3": np.full(N, volume),
99
- "surface_area_mm2": np.full(N, area_total),
100
- "cooling_area_frac": np.full(N, cool_frac),
101
- "geodesic_d_adiab": g_adiab,
102
- "local_modulus_r5": lm[:, 0],
103
- "local_modulus_r15": lm[:, 1],
104
- "local_modulus_r40": lm[:, 2],
105
- "boundary_extraction": boundary_extraction,
106
- "boundary_heat_input": boundary_heat_input,
107
- }
108
- X = np.stack([cols[n] for n in FEATURE_NAMES], axis=1).astype(np.float32)
109
- return {"X": X, "pos": xyz.astype(np.float32), "mesh_edges": edges.astype(np.int64)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/gbm_heads.py DELETED
@@ -1,69 +0,0 @@
1
- """The two gradient-boosted heads: total solidification time and field spread.
2
-
3
- Both are scikit-learn HistGradientBoostingRegressor models that see one row
4
- per part and predict log1p of their target in seconds.
5
-
6
- Row layout (16 columns for the total head, 17 for the spread head):
7
- 0-6 alloy: k, rho, cp, L_kJ_kg, TL, TS, Tpour
8
- 7 part volume / surface area (mm)
9
- 8 mold effusivity
10
- 9-15 boundary-condition descriptors from training. A casting that cools
11
- into the sand mold over its whole surface is the regime encoded as
12
- [1, 0, 0, 0, 0, 0, 0]; this release always uses it.
13
- 16 (spread head only) fraction of surface nodes tagged adiabatic
14
- """
15
- import numpy as np
16
-
17
- from src.features import FEATURE_NAMES
18
-
19
- _IS_COOLING_IDX = FEATURE_NAMES.index("is_cooling")
20
- _IS_ADIABATIC_IDX = FEATURE_NAMES.index("is_adiabatic")
21
- _VOL_IDX = FEATURE_NAMES.index("volume_mm3")
22
- _AREA_IDX = FEATURE_NAMES.index("surface_area_mm2")
23
-
24
- _SAND_MOLD_BOUNDARY = (1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
25
- N_TOTAL_FEATURES = 16
26
- N_SPREAD_FEATURES = 17
27
-
28
-
29
- def total_row(props: dict, X: np.ndarray) -> np.ndarray:
30
- """The 16-column row for the total-time head."""
31
- v_over_a = float(X[0, _VOL_IDX]) / float(X[0, _AREA_IDX])
32
- return np.array([
33
- props["k"], props["rho"], props["cp"], props["L_kJ_kg"],
34
- props["TL"], props["TS"], props["Tpour"],
35
- float(v_over_a), props["mold_effusivity"],
36
- *_SAND_MOLD_BOUNDARY,
37
- ], dtype=np.float64)
38
-
39
-
40
- def adiabatic_node_fraction(X: np.ndarray) -> float:
41
- """Adiabatic surface nodes / (adiabatic + cooling surface nodes)."""
42
- n_adiabatic = float(np.sum(X[:, _IS_ADIABATIC_IDX]))
43
- n_cooling = float(np.sum(X[:, _IS_COOLING_IDX]))
44
- return n_adiabatic / max(n_adiabatic + n_cooling, 1.0)
45
-
46
-
47
- def spread_row(row_total: np.ndarray, X: np.ndarray) -> np.ndarray:
48
- """The 17-column row for the spread head."""
49
- return np.concatenate([row_total, [adiabatic_node_fraction(X)]])
50
-
51
-
52
- def predict_total_seconds(model, row: np.ndarray) -> float:
53
- total = float(np.expm1(float(model.predict(row.reshape(1, -1))[0])))
54
- if total <= 0:
55
- raise ValueError(f"total-time head returned a non-positive total ({total!r})")
56
- return total
57
-
58
-
59
- def predict_spread_seconds(model, row: np.ndarray) -> float:
60
- x = np.asarray(row, dtype=np.float64).reshape(1, -1)
61
- log_pred = float(model.predict(x)[0])
62
- return max(0.0, float(np.expm1(log_pred)))
63
-
64
-
65
- def check_head(model, n_features: int, name: str) -> None:
66
- n = getattr(model, "n_features_in_", None)
67
- if n is not None and int(n) != n_features:
68
- raise ValueError(f"{name} head expects {n} input columns, this code builds "
69
- f"{n_features}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/geometry.py DELETED
@@ -1,128 +0,0 @@
1
- """Pure-geometry helpers: triangle areas, tet volumes, nearest-surface
2
- distances (via KD-tree), and boundary-node masks. All lengths in mm."""
3
- import numpy as np
4
- from scipy.spatial import cKDTree
5
- from scipy.sparse import coo_matrix
6
- from scipy.sparse.csgraph import dijkstra
7
-
8
-
9
- def triangle_areas(node_xyz: np.ndarray, tri: np.ndarray) -> np.ndarray:
10
- if tri.shape[0] == 0:
11
- return np.zeros(0)
12
- a = node_xyz[tri[:, 0]]
13
- b = node_xyz[tri[:, 1]]
14
- c = node_xyz[tri[:, 2]]
15
- cross = np.cross(b - a, c - a)
16
- return 0.5 * np.linalg.norm(cross, axis=1)
17
-
18
-
19
- def total_area(node_xyz: np.ndarray, tri: np.ndarray) -> float:
20
- return float(triangle_areas(node_xyz, tri).sum())
21
-
22
-
23
- def tet_volumes(node_xyz: np.ndarray, tets: np.ndarray) -> np.ndarray:
24
- if tets.shape[0] == 0:
25
- return np.zeros(0)
26
- a = node_xyz[tets[:, 0]]
27
- b = node_xyz[tets[:, 1]]
28
- c = node_xyz[tets[:, 2]]
29
- d = node_xyz[tets[:, 3]]
30
- return np.abs(np.einsum('ij,ij->i', b - a, np.cross(c - a, d - a))) / 6.0
31
-
32
-
33
- def mesh_volume(node_xyz: np.ndarray, tets: np.ndarray) -> float:
34
- if tets.shape[0] == 0:
35
- return 0.0
36
- return float(tet_volumes(node_xyz, tets).sum())
37
-
38
-
39
- def nearest_distance(points: np.ndarray, targets: np.ndarray) -> np.ndarray:
40
- """Euclidean distance from each point to the nearest target point.
41
- Returns +inf for every point when there are no targets."""
42
- if targets.shape[0] == 0:
43
- return np.full(points.shape[0], np.inf)
44
- tree = cKDTree(targets)
45
- d, _ = tree.query(points, k=1)
46
- return d
47
-
48
-
49
- def boundary_node_mask(n_nodes: int, tri: np.ndarray) -> np.ndarray:
50
- mask = np.zeros(n_nodes, dtype=bool)
51
- if tri.shape[0]:
52
- mask[np.unique(tri.reshape(-1))] = True
53
- return mask
54
-
55
-
56
- _TET_EDGE_PAIRS = ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3))
57
-
58
-
59
- def edges_from_tets(tets: np.ndarray) -> np.ndarray:
60
- if tets.shape[0] == 0:
61
- return np.empty((0, 2), dtype=np.int64)
62
- e = np.concatenate([tets[:, [a, b]] for a, b in _TET_EDGE_PAIRS], axis=0)
63
- e = np.sort(e, axis=1)
64
- return np.unique(e, axis=0).astype(np.int64)
65
-
66
-
67
- def _edge_csr(n_nodes: int, edges: np.ndarray, edge_len: np.ndarray):
68
- r = np.concatenate([edges[:, 0], edges[:, 1]])
69
- c = np.concatenate([edges[:, 1], edges[:, 0]])
70
- w = np.concatenate([edge_len, edge_len])
71
- return coo_matrix((w, (r, c)), shape=(n_nodes, n_nodes)).tocsr()
72
-
73
-
74
- def geodesic_distance(n_nodes: int, edges: np.ndarray, edge_len: np.ndarray,
75
- source_idx: np.ndarray) -> np.ndarray:
76
- if source_idx.shape[0] == 0 or edges.shape[0] == 0:
77
- return np.full(n_nodes, np.inf)
78
- g = _edge_csr(n_nodes, edges, edge_len)
79
- d = dijkstra(g, directed=False, indices=source_idx, min_only=True)
80
- return d
81
-
82
-
83
-
84
-
85
- def _local_modulus_for_query(tets: np.ndarray, cool_tri: np.ndarray, radii: np.ndarray,
86
- chunk: int, query_idx: np.ndarray, g, tvol: np.ndarray,
87
- tarea: np.ndarray, bbox_diag: float) -> np.ndarray:
88
- """Exact V/A geodesic-ball modulus, computed only for the nodes in
89
- `query_idx` (as Dijkstra sources). Returns (len(query_idx), len(radii))."""
90
- rmax = float(radii.max())
91
- vals = np.full((query_idx.shape[0], len(radii)), bbox_diag, dtype=np.float64)
92
- for start in range(0, query_idx.shape[0], chunk):
93
- sel = query_idx[start:start + chunk]
94
- dmat = dijkstra(g, directed=False, indices=sel, limit=rmax) # (c, N)
95
- for j, r in enumerate(radii):
96
- in_ball = dmat <= r # (c, N)
97
- vol = in_ball[:, tets].all(axis=2) @ tvol # (c,)
98
- area = (in_ball[:, cool_tri].all(axis=2) @ tarea
99
- if cool_tri.shape[0] else np.zeros(len(sel)))
100
- vals[start:start + len(sel), j] = np.where(
101
- area > 0, vol / np.maximum(area, 1e-12), bbox_diag)
102
- return vals
103
-
104
-
105
-
106
-
107
- def local_modulus(node_xyz: np.ndarray, tets: np.ndarray, cool_tri: np.ndarray,
108
- edges: np.ndarray, edge_len: np.ndarray, radii,
109
- chunk: int = 128) -> np.ndarray:
110
- """Local cooling modulus per node: V/A over geodesic balls (mm).
111
-
112
- For each node and radius r: (sum of volumes of tets whose 4 nodes all lie
113
- within geodesic distance r of the node) / (area of cooling triangles whose
114
- 3 nodes all lie within r). Balls with no cooling area get the bbox-diagonal
115
- sentinel (consistent with the other distance sentinels)."""
116
- N = node_xyz.shape[0]
117
- radii = np.asarray(radii, dtype=float)
118
- bbox_diag = float(np.linalg.norm(node_xyz.max(0) - node_xyz.min(0)))
119
- out = np.full((N, len(radii)), bbox_diag, dtype=np.float64)
120
- if edges.shape[0] == 0 or tets.shape[0] == 0:
121
- return out.astype(np.float32)
122
- tvol = tet_volumes(node_xyz, tets)
123
- tarea = triangle_areas(node_xyz, cool_tri)
124
- g = _edge_csr(N, edges, edge_len)
125
- query_idx = np.arange(N, dtype=np.int64)
126
- out[query_idx] = _local_modulus_for_query(tets, cool_tri, radii, chunk, query_idx, g,
127
- tvol, tarea, bbox_diag)
128
- return out.astype(np.float32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/hybrid.py DELETED
@@ -1,287 +0,0 @@
1
- """Recomposition: combine the GNN field shape with the two heads' targets.
2
-
3
- The GNN predicts the spatial pattern of the field well but is less reliable
4
- about its absolute level and spread. The heads predict the part's total time
5
- (used as the 99.5% quantile of the field) and the standard deviation of the
6
- field. `hybrid_field_soft` maps the GNN field affinely,
7
-
8
- pred(a, m) = clip(a * (gnn - mean(gnn)) + m, 0, None)
9
-
10
- and picks (a, m) to minimize
11
-
12
- J = w_total * r_total**2 + w_std * r_std**2,
13
- r_total = (quantile(pred, q) - total) / total
14
- r_std = (std(pred) - std_target) / std_target.
15
- """
16
- import logging
17
-
18
- import numpy as np
19
-
20
- logger = logging.getLogger(__name__)
21
-
22
-
23
- def hybrid_field_max_anchor(gnn_seconds: np.ndarray, total_seconds: float,
24
- q: float = 0.995) -> np.ndarray:
25
- """Shift the GNN field so its q-quantile equals `total_seconds`, clip at 0."""
26
- g = np.asarray(gnn_seconds, dtype=np.float64)
27
- anchor = np.quantile(g, q)
28
- out = g - anchor + float(total_seconds)
29
- return np.clip(out, 0.0, None)
30
-
31
-
32
- def hybrid_field_affine(gnn_seconds: np.ndarray, total_seconds: float,
33
- std_seconds: float, q: float = 0.995,
34
- a_clamp: tuple = (0.3, 5.0)) -> tuple:
35
- """Hard two-target fit: the q-quantile is anchored exactly at
36
- `total_seconds` and the scale `a` is solved so that the clipped field's
37
- standard deviation matches `std_seconds`.
38
-
39
- Anchoring the quantile gives raw(a) = a * d + total with d fixed by the
40
- GNN field. Below a_clipstart nothing is clipped and a = std/std(gnn) in
41
- closed form. Past it, the post-clip spread is not monotone in a (it rises
42
- to an interior peak and then falls), so the smallest root is found by a
43
- coarse scan followed by bisection; if no root exists the closest scanned
44
- point is used and `a_clamped` is set. Returns (field, info)."""
45
- g = np.asarray(gnn_seconds, dtype=np.float64)
46
- s = float(np.std(g))
47
- if s < 1e-9:
48
- logger.warning("hybrid_field_affine: degenerate flat GNN field (std=%.3g) -- "
49
- "falling back to quantile-anchor recomposition", s)
50
- pred = hybrid_field_max_anchor(g, total_seconds, q=q)
51
- return pred, {"a": 1.0, "a_clamped": False, "degenerate_fallback": True,
52
- "clip_frac": float((pred == 0.0).mean()),
53
- "std_target_effective": float(std_seconds)}
54
-
55
- std_target = float(std_seconds)
56
- lo, hi = float(a_clamp[0]), float(a_clamp[1])
57
- total = float(total_seconds)
58
-
59
- c = g - g.mean()
60
- shift = float(np.quantile(c, q))
61
- d = c - shift
62
- eps = 1e-9
63
- a_clipstart = total / max(-float(d.min()), eps)
64
-
65
- def _raw_for_a(a):
66
- return a * d + total
67
-
68
- def _post_clip_std(a):
69
- return float(np.std(np.clip(_raw_for_a(a), 0.0, None)))
70
-
71
- a_raw = std_target / s
72
-
73
- if a_raw <= a_clipstart:
74
- # Nothing is clipped at a_raw, so the closed form is exact. The clamp
75
- # to `lo` can still clip when the total is small next to the spread.
76
- a = float(np.clip(a_raw, lo, hi))
77
- a_clamped = bool(a != a_raw)
78
- raw = _raw_for_a(a)
79
- else:
80
- lo_search = max(a_clipstart, lo)
81
- if lo_search >= hi:
82
- a, a_clamped = hi, True
83
- raw = _raw_for_a(a)
84
- else:
85
- n_scan = 64
86
- scan_a = np.linspace(lo_search, hi, n_scan)
87
- scan_f = np.array([_post_clip_std(x) for x in scan_a])
88
- diffs = scan_f - std_target
89
- crossing = None
90
- for i in range(1, n_scan):
91
- if diffs[i - 1] == 0.0 or diffs[i - 1] * diffs[i] <= 0.0:
92
- crossing = i
93
- break
94
- if crossing is not None:
95
- blo, bhi = float(scan_a[crossing - 1]), float(scan_a[crossing])
96
- flo = float(diffs[crossing - 1])
97
- if flo == 0.0:
98
- a = blo
99
- else:
100
- for _ in range(50):
101
- mid = 0.5 * (blo + bhi)
102
- fm = _post_clip_std(mid) - std_target
103
- if (fm > 0.0) == (flo > 0.0):
104
- blo, flo = mid, fm
105
- else:
106
- bhi = mid
107
- if (bhi - blo) <= 1e-9 * max(abs(bhi), 1e-12):
108
- break
109
- a = 0.5 * (blo + bhi)
110
- a_clamped = False
111
- raw = _raw_for_a(a)
112
- else:
113
- # The target exceeds the reachable spread: take the closest
114
- # scanned point instead of the upper clamp.
115
- best_idx = int(np.argmin(np.abs(diffs)))
116
- a = float(scan_a[best_idx])
117
- a_clamped = True
118
- raw = _raw_for_a(a)
119
-
120
- clip_frac = float((raw < 0.0).mean())
121
- if clip_frac > 0.5:
122
- logger.warning("hybrid_field_affine: majority of field clipped "
123
- "(clip_frac=%.3f) -- GBM total/std may be inconsistent "
124
- "with the GNN shape", clip_frac)
125
- return np.clip(raw, 0.0, None), {"a": a, "a_clamped": a_clamped,
126
- "degenerate_fallback": False, "clip_frac": clip_frac,
127
- "std_target_effective": std_target}
128
-
129
-
130
- def hybrid_field_soft(gnn_seconds: np.ndarray, total_seconds: float, std_seconds: float,
131
- q: float = 0.995, a_clamp: tuple = (0.3, 5.0),
132
- w_total: float = 1.0, w_std: float = 1.0) -> tuple:
133
- """Soft two-target fit (see the module docstring for J).
134
-
135
- Seeded by `hybrid_field_affine`. When the seed already meets both
136
- targets it is returned unchanged; otherwise a 64 x 33 grid over (a, m),
137
- a 9 x 9 refinement around the best point and an exact re-check decide
138
- whether letting the total move buys a better spread match. Returns
139
- (field, info) with info keys a, m, target_unreachable,
140
- degenerate_fallback, clip_frac, total_deviation_frac, j_total_resid,
141
- j_std_resid, std_target_effective."""
142
- g = np.asarray(gnn_seconds, dtype=np.float64)
143
- total = float(total_seconds)
144
- q = float(q)
145
- w_total = float(w_total)
146
- w_std = float(w_std)
147
-
148
- if w_total < 0.0 or w_std < 0.0:
149
- raise ValueError(
150
- f"hybrid_field_soft: w_total/w_std must be >= 0 (got "
151
- f"w_total={w_total!r}, w_std={w_std!r})")
152
- if w_total == 0.0 and w_std == 0.0:
153
- raise ValueError("hybrid_field_soft: w_total and w_std cannot both be 0")
154
- if float(a_clamp[0]) <= 0.0:
155
- raise ValueError(f"hybrid_field_soft: a_clamp[0] must be > 0 (got {a_clamp[0]!r}) "
156
- "-- the a-grid is log-spaced")
157
-
158
- pred_seed, info_affine = hybrid_field_affine(g, total, std_seconds, q=q, a_clamp=a_clamp)
159
-
160
- # For every branch of the affine solve, m(a) = total - a * quantile(c, q).
161
- c = g - g.mean()
162
- shift = float(np.quantile(c, q))
163
- a_seed = float(info_affine["a"])
164
- m_seed = total - a_seed * shift
165
- std_target_eff = float(info_affine["std_target_effective"])
166
-
167
- denom_total = total if abs(total) > 1e-9 else (1e-9 if total >= 0.0 else -1e-9)
168
- denom_std = std_target_eff if abs(std_target_eff) > 1e-9 else 1e-9
169
-
170
- def _residuals(pred):
171
- r_total = (float(np.quantile(pred, q)) - total) / denom_total
172
- r_std = (float(np.std(pred)) - std_target_eff) / denom_std
173
- return r_total, r_std
174
-
175
- def _build_info(final_a, final_m, final_rt, final_rs, clip_frac, target_unreachable):
176
- if clip_frac > 0.5:
177
- logger.warning("hybrid_field_soft: majority of the accepted soft-anchor "
178
- "field clipped (clip_frac=%.3f) -- GBM total/std may be "
179
- "inconsistent with the GNN shape", clip_frac)
180
- return {
181
- "a": final_a, "m": final_m, "target_unreachable": target_unreachable,
182
- "degenerate_fallback": False, "clip_frac": clip_frac,
183
- "total_deviation_frac": final_rt,
184
- "j_total_resid": float(w_total * final_rt ** 2),
185
- "j_std_resid": float(w_std * final_rs ** 2),
186
- "std_target_effective": std_target_eff,
187
- }
188
-
189
- r_total_seed, r_std_seed = _residuals(pred_seed)
190
- j_seed = w_total * r_total_seed ** 2 + w_std * r_std_seed ** 2
191
-
192
- if info_affine["degenerate_fallback"]:
193
- return pred_seed, {
194
- "a": a_seed, "m": m_seed, "target_unreachable": False,
195
- "degenerate_fallback": True, "clip_frac": info_affine["clip_frac"],
196
- "total_deviation_frac": r_total_seed,
197
- "j_total_resid": float(w_total * r_total_seed ** 2),
198
- "j_std_resid": float(w_std * r_std_seed ** 2),
199
- "std_target_effective": std_target_eff,
200
- }
201
-
202
- target_unreachable = bool(info_affine["a_clamped"])
203
- seed_clip_frac = float((c * a_seed + m_seed < 0.0).mean())
204
-
205
- # Both targets already met: no search needed (the common case).
206
- if j_seed < 1e-12:
207
- return pred_seed, _build_info(a_seed, m_seed, r_total_seed, r_std_seed,
208
- seed_clip_frac, target_unreachable)
209
-
210
- lo, hi = float(a_clamp[0]), float(a_clamp[1])
211
- n_a, n_m = 64, 33
212
- a_grid = np.logspace(np.log10(lo), np.log10(hi), n_a)
213
- # The m-window is centred on the seed.
214
- m_lo, m_hi = sorted((m_seed - 0.3 * total, m_seed + 0.3 * total))
215
- m_grid = np.linspace(m_lo, m_hi, n_m)
216
-
217
- # raw(a, m) = a*c + m is order-preserving and clipping only touches the
218
- # low tail, so quantile(clip(raw), q) == a*shift + m in closed form as
219
- # long as fewer than ~q of the nodes are clipped. Where that fails (all
220
- # nodes clipped) J is over-estimated, so such a point is never selected.
221
- # The winning candidate is re-scored exactly below.
222
- def _grid_eval(a_vals, m_vals):
223
- n_av, n_mv = len(a_vals), len(m_vals)
224
- J = np.empty((n_av, n_mv))
225
- Rt = np.empty((n_av, n_mv))
226
- Rs = np.empty((n_av, n_mv))
227
- for i, av in enumerate(a_vals):
228
- raw = m_vals[:, None] + av * c[None, :] # (n_mv, n_nodes)
229
- clipped = np.clip(raw, 0.0, None)
230
- qv = av * shift + m_vals
231
- sv = np.std(clipped, axis=-1)
232
- rt = (qv - total) / denom_total
233
- rs = (sv - std_target_eff) / denom_std
234
- J[i] = w_total * rt ** 2 + w_std * rs ** 2
235
- Rt[i] = rt
236
- Rs[i] = rs
237
- return J, Rt, Rs
238
-
239
- J_coarse, Rt_coarse, Rs_coarse = _grid_eval(a_grid, m_grid)
240
- idx = np.unravel_index(int(np.argmin(J_coarse)), J_coarse.shape)
241
- best_a, best_m = float(a_grid[idx[0]]), float(m_grid[idx[1]])
242
- best_J = float(J_coarse[idx])
243
- best_rt, best_rs = float(Rt_coarse[idx]), float(Rs_coarse[idx])
244
-
245
- if j_seed < best_J:
246
- best_a, best_m, best_J = a_seed, m_seed, j_seed
247
- best_rt, best_rs = r_total_seed, r_std_seed
248
-
249
- # One refinement pass on a 9 x 9 sub-grid about one coarse cell wide
250
- # around the best point so far (log-spaced in a, linear in m).
251
- log_lo, log_hi = np.log10(lo), np.log10(hi)
252
- a_step = (log_hi - log_lo) / max(n_a - 1, 1)
253
- log_best_a = np.log10(best_a)
254
- ref_log_a = np.clip(np.linspace(log_best_a - a_step, log_best_a + a_step, 9),
255
- log_lo, log_hi)
256
- ref_a = 10.0 ** ref_log_a
257
-
258
- m_step = (m_hi - m_lo) / max(n_m - 1, 1)
259
- ref_m = np.clip(np.linspace(best_m - m_step, best_m + m_step, 9), m_lo, m_hi)
260
-
261
- J_ref, Rt_ref, Rs_ref = _grid_eval(ref_a, ref_m)
262
- idx_r = np.unravel_index(int(np.argmin(J_ref)), J_ref.shape)
263
- if float(J_ref[idx_r]) < best_J:
264
- best_a, best_m = float(ref_a[idx_r[0]]), float(ref_m[idx_r[1]])
265
- best_J = float(J_ref[idx_r])
266
- best_rt, best_rs = float(Rt_ref[idx_r]), float(Rs_ref[idx_r])
267
-
268
- # Exact re-check of the winner before accepting it over the seed.
269
- if (best_a, best_m) != (a_seed, m_seed):
270
- best_pred = np.clip(best_a * c + best_m, 0.0, None)
271
- best_rt, best_rs = _residuals(best_pred)
272
- best_J = w_total * best_rt ** 2 + w_std * best_rs ** 2
273
-
274
- if best_J < j_seed - 1e-12:
275
- final_a, final_m = best_a, best_m
276
- final_raw = final_a * c + final_m
277
- final_pred = np.clip(final_raw, 0.0, None)
278
- final_rt, final_rs = best_rt, best_rs
279
- else:
280
- final_a, final_m = a_seed, m_seed
281
- final_raw = final_a * c + final_m
282
- final_pred = pred_seed
283
- final_rt, final_rs = r_total_seed, r_std_seed
284
-
285
- clip_frac = float((final_raw < 0.0).mean())
286
- return final_pred, _build_info(final_a, final_m, final_rt, final_rs, clip_frac,
287
- target_unreachable)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/inference_props.py DELETED
@@ -1,170 +0,0 @@
1
- """Alloy and mold properties.
2
-
3
- Turns a named alloy and mold (rows of `data/properties/materials.csv` and
4
- `molds.csv`), or a JSON file with raw values, into the 8-key dict the model
5
- reads:
6
-
7
- {k, rho, cp, L_kJ_kg, TL, TS, Tpour, mold_effusivity}
8
-
9
- Units: W/(m K), kg/m^3, J/(kg K), kJ/kg, deg C, W s^0.5/(m^2 K). The pouring
10
- temperature of a named alloy is the midpoint of its tabulated range.
11
- """
12
- from __future__ import annotations
13
-
14
- import csv
15
- import json
16
- from dataclasses import dataclass
17
- from pathlib import Path
18
-
19
- DEFAULT_ALLOY = "EN-GJS-400-15"
20
- DEFAULT_MOLD = "green_sand"
21
-
22
- _REQUIRED_KEYS = ("k", "rho", "cp", "L_kJ_kg", "TL", "TS", "Tpour", "mold_effusivity")
23
-
24
- _MATERIALS_PATH = "data/properties/materials.csv"
25
- _MOLDS_PATH = "data/properties/molds.csv"
26
-
27
- # Family used for shrinkage severity when the alloy family is unknown (a raw
28
- # property file has no grade). Steel has the largest shrinkage, so this errs
29
- # on the side of flagging.
30
- _UNKNOWN_ALLOY_FAMILY_FALLBACK = "steel"
31
-
32
-
33
- @dataclass(frozen=True)
34
- class Material:
35
- material_id: str
36
- alloy_family: str
37
- k: float
38
- rho: float
39
- cp: float
40
- L: float
41
- TL: float
42
- TS: float
43
- Tpour: float
44
-
45
-
46
- def load_materials(path: str = _MATERIALS_PATH) -> list[Material]:
47
- """Rows of the materials table; rejects rows that are not TS < TL < Tpour."""
48
- materials: list[Material] = []
49
- with Path(path).open(newline="") as handle:
50
- for row in csv.DictReader(handle):
51
- material_id = row["material_id"]
52
- TL = float(row["TL_C"])
53
- TS = float(row["TS_C"])
54
- tpour = 0.5 * (float(row["Tpour_lo_C"]) + float(row["Tpour_hi_C"]))
55
- if not TS < TL < tpour:
56
- raise ValueError(
57
- f"material {material_id!r}: expected TS < TL < Tpour, "
58
- f"got {TS}, {TL}, {tpour}")
59
- materials.append(Material(
60
- material_id=material_id,
61
- alloy_family=row["family"],
62
- k=float(row["k_W_mK"]),
63
- rho=float(row["rho_kg_m3"]),
64
- cp=float(row["cp_J_kgK"]),
65
- L=float(row["L_kJ_kg"]),
66
- TL=TL,
67
- TS=TS,
68
- Tpour=tpour,
69
- ))
70
- return materials
71
-
72
-
73
- def load_molds(path: str = _MOLDS_PATH) -> dict[str, float]:
74
- """{mold_system: effusivity} from the molds table."""
75
- with Path(path).open(newline="") as f:
76
- return {row["mold_system"]: float(row["effusivity_W_s05_m2K"])
77
- for row in csv.DictReader(f)}
78
-
79
-
80
- _materials_cache: dict[str, Material] | None = None
81
- _molds_cache: dict[str, float] | None = None
82
-
83
-
84
- def _materials() -> dict[str, Material]:
85
- global _materials_cache
86
- if _materials_cache is None:
87
- _materials_cache = {m.material_id: m for m in load_materials()}
88
- return _materials_cache
89
-
90
-
91
- def _molds() -> dict[str, float]:
92
- global _molds_cache
93
- if _molds_cache is None:
94
- _molds_cache = load_molds()
95
- return _molds_cache
96
-
97
-
98
- def list_alloys() -> list[str]:
99
- return list(_materials().keys())
100
-
101
-
102
- def list_molds() -> list[str]:
103
- return list(_molds().keys())
104
-
105
-
106
- def _validate_tl_ts(props: dict, source: str) -> None:
107
- """An inverted or equal liquidus/solidus pair would make the Niyama proxy
108
- zero everywhere and flag every node, so it is rejected up front."""
109
- TL, TS = props["TL"], props["TS"]
110
- if TL <= TS:
111
- raise ValueError(
112
- f"resolve_props ({source}): TL ({TL!r}) must be strictly greater than "
113
- f"TS ({TS!r})")
114
-
115
-
116
- def resolve_props(alloy: str | None = None, mold: str = DEFAULT_MOLD,
117
- props_json: str | None = None) -> dict:
118
- """The 8-key property dict.
119
-
120
- `props_json` replaces `alloy` and `mold`; the file must hold all 8 keys.
121
- Otherwise `alloy` (default `DEFAULT_ALLOY`) and `mold` are looked up in
122
- the tables, and unknown names raise ValueError listing the options."""
123
- if props_json is not None:
124
- with open(props_json) as f:
125
- data = json.load(f)
126
- missing = [k for k in _REQUIRED_KEYS if k not in data]
127
- if missing:
128
- raise ValueError(
129
- f"props_json '{props_json}' is missing required key(s): {missing} "
130
- f"(required: {list(_REQUIRED_KEYS)})")
131
- props = {k: float(data[k]) for k in _REQUIRED_KEYS}
132
- _validate_tl_ts(props, f"props_json={props_json!r}")
133
- return props
134
-
135
- alloy_id = alloy if alloy is not None else DEFAULT_ALLOY
136
- materials = _materials()
137
- if alloy_id not in materials:
138
- raise ValueError(
139
- f"unknown alloy '{alloy_id}'; available alloys: {sorted(materials.keys())}")
140
- material = materials[alloy_id]
141
-
142
- molds = _molds()
143
- if mold not in molds:
144
- raise ValueError(
145
- f"unknown mold system '{mold}'; available mold systems: {sorted(molds.keys())}")
146
-
147
- props = {
148
- "k": float(material.k),
149
- "rho": float(material.rho),
150
- "cp": float(material.cp),
151
- "L_kJ_kg": float(material.L),
152
- "TL": float(material.TL),
153
- "TS": float(material.TS),
154
- "Tpour": float(material.Tpour),
155
- "mold_effusivity": float(molds[mold]),
156
- }
157
- _validate_tl_ts(props, f"alloy={alloy_id!r}")
158
- return props
159
-
160
-
161
- def resolve_alloy_family(alloy: str | None, props_json: str | None = None) -> tuple[str, bool]:
162
- """(family, assumed) for shrinkage severity. The family comes from the
163
- materials table; `assumed` is True when it had to fall back to steel
164
- (a raw property file, or an alloy that is not in the table)."""
165
- if props_json is not None:
166
- return _UNKNOWN_ALLOY_FAMILY_FALLBACK, True
167
- material = _materials().get(alloy if alloy is not None else DEFAULT_ALLOY)
168
- if material is None:
169
- return _UNKNOWN_ALLOY_FAMILY_FALLBACK, True
170
- return material.alloy_family, False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/mesh_cache.py DELETED
@@ -1,128 +0,0 @@
1
- """Content-addressed on-disk cache for `src.meshing.heal_and_mesh`.
2
-
3
- The key is sha256(STEP bytes) + target node count + `MESH_PIPELINE_VERSION`,
4
- so a byte-identical STEP file is meshed once. Each entry is a pair
5
- `<key>.msh` / `<key>.json` (the mesh and its meta dict), written through a
6
- per-writer temporary file and `os.replace`, so concurrent writers never leave
7
- a half-written entry. Failed meshes are not cached.
8
- """
9
- from __future__ import annotations
10
-
11
- import hashlib
12
- import json
13
- import os
14
- import shutil
15
- import time
16
- import uuid
17
-
18
- # MESH_PIPELINE_VERSION and heal_and_mesh are read through globals() so tests
19
- # can monkeypatch them.
20
- from src.meshing import DEFAULT_TARGET_NODES, MESH_PIPELINE_VERSION, heal_and_mesh # noqa: F401
21
-
22
- _HASH_CHUNK_SIZE = 1 << 20 # 1 MiB
23
- # STEP files above this size get the defeaturing attempt first. Changing it
24
- # changes which mesh a file resolves to, so bump MESH_PIPELINE_VERSION too.
25
- _BIG_FILE_THRESHOLD_BYTES = 8 * 1024 * 1024 # 8 MiB
26
-
27
-
28
- def _sha256_file(path: str) -> str:
29
- h = hashlib.sha256()
30
- with open(path, "rb") as f:
31
- while True:
32
- chunk = f.read(_HASH_CHUNK_SIZE)
33
- if not chunk:
34
- break
35
- h.update(chunk)
36
- return h.hexdigest()
37
-
38
-
39
- def mesh_cache_key(step_path: str, target_nodes: int = DEFAULT_TARGET_NODES) -> str:
40
- """sha256 over the file digest, `target_nodes` and the pipeline version.
41
- The version is read from module globals so tests can monkeypatch it."""
42
- digest = _sha256_file(step_path)
43
- pipeline_version = globals()["MESH_PIPELINE_VERSION"]
44
- key_input = f"{digest}:{int(target_nodes)}:{int(pipeline_version)}".encode("utf-8")
45
- return hashlib.sha256(key_input).hexdigest()
46
-
47
-
48
- def _unique_tmp_path(final_path: str) -> str:
49
- return f"{final_path}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
50
-
51
-
52
- def _paths(cache_dir: str, key: str) -> tuple[str, str]:
53
- return (
54
- os.path.join(cache_dir, f"{key}.msh"),
55
- os.path.join(cache_dir, f"{key}.json"),
56
- )
57
-
58
-
59
- def get_or_mesh(step_path: str, out_msh: str, target_nodes: int = DEFAULT_TARGET_NODES,
60
- cache_dir: str = "runs/mesh_cache") -> dict:
61
- """`heal_and_mesh`'s meta dict for `step_path`, plus a `"cache"` key.
62
-
63
- On a hit the cached mesh is copied to `out_msh` (`"cache": "hit"`). On a
64
- miss the part is meshed; a successful mesh is stored and returned with
65
- `"cache": "miss"`, a failed one is returned unchanged and not stored.
66
- Small files try a plain pass first and retry once with defeaturing; files
67
- above 8 MiB try the defeatured pass first and retry once without it.
68
- """
69
- os.makedirs(cache_dir, exist_ok=True)
70
- key = mesh_cache_key(step_path, target_nodes)
71
- msh_path, json_path = _paths(cache_dir, key)
72
-
73
- if os.path.exists(msh_path) and os.path.exists(json_path):
74
- with open(json_path) as f:
75
- meta = json.load(f)
76
- shutil.copyfile(msh_path, out_msh)
77
- result = dict(meta)
78
- result["cache"] = "hit"
79
- return result
80
-
81
- heal_and_mesh_fn = globals()["heal_and_mesh"]
82
- t0 = time.time()
83
- big_file = os.path.getsize(step_path) > _BIG_FILE_THRESHOLD_BYTES
84
- if big_file:
85
- meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=True)
86
- defeature_used, retry = True, False
87
- if not meta.get("ok"):
88
- meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=False)
89
- defeature_used, retry = False, True
90
- else:
91
- meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=False)
92
- defeature_used, retry = False, False
93
- if not meta.get("ok"):
94
- meta = heal_and_mesh_fn(step_path, out_msh, target_nodes=target_nodes, defeature=True)
95
- defeature_used, retry = True, True
96
- wall_s = time.time() - t0
97
-
98
- if not meta.get("ok"):
99
- result = dict(meta)
100
- result["cache"] = "miss"
101
- result["defeature"] = defeature_used
102
- result["retry"] = retry
103
- return result
104
-
105
- stored_meta = dict(meta)
106
- stored_meta["mesh_wall_s"] = wall_s
107
- stored_meta["pipeline_version"] = globals()["MESH_PIPELINE_VERSION"]
108
- stored_meta["source_path"] = os.path.abspath(step_path)
109
- stored_meta["created_at"] = time.time()
110
- stored_meta["defeature"] = defeature_used
111
- stored_meta["retry"] = retry
112
-
113
- msh_tmp = _unique_tmp_path(msh_path)
114
- json_tmp = _unique_tmp_path(json_path)
115
- shutil.copyfile(out_msh, msh_tmp)
116
- os.replace(msh_tmp, msh_path)
117
- with open(json_tmp, "w") as f:
118
- json.dump(stored_meta, f)
119
- os.replace(json_tmp, json_path)
120
-
121
- result = dict(stored_meta)
122
- result["cache"] = "miss"
123
- return result
124
-
125
-
126
- def clear_mesh_cache(cache_dir: str = "runs/mesh_cache") -> None:
127
- """Remove the entire cache directory, if present."""
128
- shutil.rmtree(cache_dir, ignore_errors=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/meshing.py DELETED
@@ -1,368 +0,0 @@
1
- """STEP to tetrahedral mesh with Gmsh (OpenCASCADE kernel).
2
-
3
- `heal_and_mesh` is the default path: import the STEP file, keep the largest
4
- solid, tag every surface "Cooling" and the volume "Volume", and search the
5
- element size until the mesh lands near `target_nodes` (the density the model
6
- was trained on). If the unhealed geometry cannot be meshed, a second pass heals
7
- it and retries. `mesh_step` meshes at one fixed element size instead.
8
-
9
- Both write gmsh 2.2 ASCII meshes, the format `src.msh_parse` reads. All
10
- lengths are in millimetres.
11
- """
12
- from __future__ import annotations
13
-
14
- import numpy as np
15
-
16
- DEFAULT_TARGET_NODES = 8500
17
- # Part of the mesh-cache key (src/mesh_cache.py): bump it whenever a change
18
- # here would produce a different mesh for the same STEP file.
19
- MESH_PIPELINE_VERSION = 3
20
-
21
- # Element-size seed: sqrt(K_SURF * surface_area / target_nodes), calibrated so
22
- # the first guess usually lands within the density search's tolerance.
23
- K_SURF = 2.5
24
-
25
- # Physical-group tags are pinned (not auto-assigned) so that repeated meshing
26
- # attempts in one Gmsh session keep the "Volume"/"Cooling" names bound.
27
- _VOLUME_PHYS_TAG = 1
28
- _COOLING_PHYS_TAG = 2
29
-
30
-
31
- def _reduce_to_largest_solid():
32
- """Keep only the largest solid of the imported OCC model.
33
-
34
- Returns (n_solids_in, kept_tag, kept_volume_mm3)."""
35
- import gmsh
36
-
37
- vols = [t for (d, t) in gmsh.model.occ.getEntities(3)]
38
- n_in = len(vols)
39
- if n_in == 0:
40
- raise ValueError("no 3D solids found in STEP import")
41
- masses = [(t, gmsh.model.occ.getMass(3, t)) for t in vols]
42
- kept_tag, kept_vol = max(masses, key=lambda tv: tv[1])
43
- if n_in > 1:
44
- drop = [(3, t) for (t, _v) in masses if t != kept_tag]
45
- gmsh.model.occ.remove(drop, recursive=True)
46
- gmsh.model.occ.synchronize()
47
- return n_in, kept_tag, float(kept_vol)
48
-
49
-
50
- def _import_and_reduce(step_path: str) -> tuple[int, float, str | None]:
51
- """Import `step_path` into the current Gmsh session and keep its largest
52
- solid. Returns (n_solids_in, kept_volume_mm3, error_or_None)."""
53
- import gmsh
54
-
55
- try:
56
- gmsh.model.occ.importShapes(step_path)
57
- gmsh.model.occ.synchronize()
58
- except Exception as e:
59
- return 0, 0.0, f"import failed: {e}"
60
- try:
61
- n_solids, _kept_tag, volume_mm3 = _reduce_to_largest_solid()
62
- except Exception as e:
63
- return 0, 0.0, f"largest-solid reduction failed: {e}"
64
- return n_solids, volume_mm3, None
65
-
66
-
67
- def _elem_size(bbox_diag_mm: float) -> float:
68
- """Fallback element-size seed: bounding-box diagonal / 28."""
69
- return bbox_diag_mm / 28.0
70
-
71
-
72
- def _elem_size_from_area(area_mm2: float, target_nodes: int) -> float:
73
- """Element-size seed from the total surface area of the model."""
74
- return float(np.sqrt(K_SURF * area_mm2 / target_nodes))
75
-
76
-
77
- def _total_surface_area_mm2() -> float:
78
- """Total area of all surface entities of the current OCC model."""
79
- import gmsh
80
-
81
- surfs = [t for (d, t) in gmsh.model.occ.getEntities(2)]
82
- return float(sum(gmsh.model.occ.getMass(2, t) for t in surfs))
83
-
84
-
85
- def _first_guess_elem_size(bbox_diag_mm: float, target_nodes: int) -> float:
86
- """Surface-area seed, or the bounding-box seed if the area query fails."""
87
- try:
88
- area_mm2 = _total_surface_area_mm2()
89
- except Exception as e:
90
- print(f"[meshing] WARNING: OCC surface-area query failed ({e}); "
91
- f"falling back to bbox_diag/28 seed", flush=True)
92
- return _elem_size(bbox_diag_mm)
93
- if area_mm2 <= 0:
94
- print(f"[meshing] WARNING: OCC surface-area query returned "
95
- f"{area_mm2!r} (<=0); falling back to bbox_diag/28 seed", flush=True)
96
- return _elem_size(bbox_diag_mm)
97
- return _elem_size_from_area(area_mm2, target_nodes)
98
-
99
-
100
- def _search_elem_size(build_fn, out_msh: str, target_nodes: int,
101
- max_iter: int = 3) -> tuple[int, float]:
102
- """Refine the element size assuming the node count scales as h^-3."""
103
- n_nodes, elem_size = build_fn(out_msh, None)
104
- for _ in range(max_iter - 1):
105
- if n_nodes <= 0:
106
- break
107
- elem_size = elem_size * (n_nodes / target_nodes) ** (1.0 / 3.0)
108
- n_nodes, elem_size = build_fn(out_msh, elem_size)
109
- return n_nodes, elem_size
110
-
111
-
112
- def _search_target_nodes(build_fn, out_msh: str, target_nodes: int,
113
- tol: float = 0.35, max_iter: int = 3) -> tuple[int, float, int]:
114
- """Density search towards `target_nodes`.
115
-
116
- `build_fn(out_msh, elem_size) -> (n_nodes, elem_size_used)`, with
117
- `elem_size=None` meaning "use the seed" and `n_nodes == 0` meaning the
118
- mesh failed outright. Stops after the first attempt if it is already
119
- within `tol` of the target (or failed); otherwise refines for up to
120
- `max_iter` attempts. Returns (n_nodes, elem_size_used, attempts)."""
121
- calls = {"n": 0}
122
-
123
- def counted_build_fn(msh_path, elem_size):
124
- calls["n"] += 1
125
- return build_fn(msh_path, elem_size)
126
-
127
- n0, es0 = counted_build_fn(out_msh, None)
128
- if n0 <= 0 or abs(n0 - target_nodes) <= tol * target_nodes:
129
- return n0, es0, calls["n"]
130
- n, es = _search_elem_size(counted_build_fn, out_msh, target_nodes, max_iter=max_iter)
131
- return n, es, calls["n"]
132
-
133
-
134
- def _tag_and_mesh(size: float, out_msh: str) -> tuple[bool, int, str]:
135
- """Tag the current model ("Volume" + every surface as "Cooling") and mesh
136
- it at element size `size`. Returns (ok, n_nodes, note).
137
-
138
- The tag numbers are pinned: Gmsh keeps a removed group's *name* bound to
139
- its old tag, so auto-assigned tags on a second attempt in the same
140
- session would leave the written mesh with unnamed groups."""
141
- import gmsh
142
-
143
- gmsh.model.mesh.clear()
144
- gmsh.model.removePhysicalGroups()
145
- vols = [t for (d, t) in gmsh.model.getEntities(3)]
146
- surfs = [t for (d, t) in gmsh.model.getEntities(2)]
147
- if not vols:
148
- return False, 0, "no volume entities to mesh"
149
- pv = gmsh.model.addPhysicalGroup(3, vols, tag=_VOLUME_PHYS_TAG)
150
- gmsh.model.setPhysicalName(3, pv, "Volume")
151
- pc = gmsh.model.addPhysicalGroup(2, surfs, tag=_COOLING_PHYS_TAG)
152
- gmsh.model.setPhysicalName(2, pc, "Cooling")
153
- # The mesh reader matches elements by group name, so an unnamed group
154
- # would silently look like a mesh without boundary. Fail loudly instead.
155
- if (gmsh.model.getPhysicalName(3, pv) != "Volume"
156
- or gmsh.model.getPhysicalName(2, pc) != "Cooling"):
157
- return False, 0, ("physical-group tagging did not register "
158
- "(Volume/Cooling name binding missing)")
159
- gmsh.option.setNumber("Mesh.MeshSizeMin", size)
160
- gmsh.option.setNumber("Mesh.MeshSizeMax", size)
161
- try:
162
- gmsh.model.mesh.generate(3)
163
- node_tags, _, _ = gmsh.model.mesh.getNodes()
164
- try:
165
- tet_tags = gmsh.model.mesh.getElementsByType(4)[0]
166
- except Exception:
167
- tet_tags = []
168
- if len(node_tags) > 0 and len(tet_tags) > 0:
169
- gmsh.option.setNumber("Mesh.MshFileVersion", 2.2)
170
- gmsh.write(out_msh)
171
- return True, len(node_tags), ""
172
- return False, 0, f"empty mesh at size={size:.2f}mm"
173
- except Exception as e:
174
- return False, 0, f"mesh generate failed at size={size:.2f}mm: {e}"
175
-
176
-
177
- def _apply_heal() -> tuple[bool, str]:
178
- """Run OCC shape healing. `healShapes()` can finish without raising and
179
- still leave no solid, so a heal only counts if a volume survives.
180
- Returns (effective, note)."""
181
- import gmsh
182
-
183
- try:
184
- gmsh.model.occ.healShapes()
185
- gmsh.model.occ.synchronize()
186
- except Exception as e:
187
- return False, f"healShapes raised: {e}"
188
- n_vols = len(gmsh.model.getEntities(3))
189
- if n_vols == 0:
190
- return False, ("healShapes ran but yielded 0 volume entities (solid could not be "
191
- "reconstructed -- likely a self-intersecting B-rep)")
192
- return True, ""
193
-
194
-
195
- def _apply_defeature() -> tuple[bool, str]:
196
- """Merge literally duplicate OCC entities (`removeAllDuplicates`), a
197
- cheap clean-up for CAD exports. Returns (ok, note); not ok if the call
198
- raises or the solid is lost."""
199
- import gmsh
200
-
201
- n_vols_before = len(gmsh.model.getEntities(3))
202
- try:
203
- gmsh.model.occ.removeAllDuplicates()
204
- gmsh.model.occ.synchronize()
205
- except Exception as e:
206
- return False, f"defeature (removeAllDuplicates) raised: {e}"
207
- n_vols_after = len(gmsh.model.getEntities(3))
208
- if n_vols_before > 0 and n_vols_after == 0:
209
- return False, "defeature (removeAllDuplicates) yielded 0 volume entities (solid lost)"
210
- return True, ""
211
-
212
-
213
- def heal_and_mesh(step_path: str, out_msh: str, target_nodes: int = DEFAULT_TARGET_NODES,
214
- defeature: bool = False) -> dict:
215
- """Mesh the largest solid of `step_path` near `target_nodes` nodes.
216
-
217
- Pass 1 meshes the geometry as imported (healing can destroy a solid
218
- that would have meshed fine, so it is not applied by default). Only if
219
- pass 1 fails outright does pass 2, in a fresh Gmsh session, heal the
220
- geometry and retry the same density search. `defeature=True` runs
221
- `_apply_defeature` before meshing in both passes.
222
-
223
- Returns {n_solids, volume_mm3, bbox_diag_mm, n_nodes, ok, healed, notes,
224
- attempts}; `notes` collects human-readable diagnostics.
225
- """
226
- import gmsh
227
-
228
- notes: list[str] = []
229
-
230
- # ---- Pass 1: unhealed ----
231
- gmsh.initialize()
232
- try:
233
- gmsh.option.setNumber("General.Terminal", 0)
234
- gmsh.model.add("part")
235
- n_solids, volume_mm3, err = _import_and_reduce(step_path)
236
- if err is not None:
237
- notes.append(err)
238
- return dict(n_solids=0, volume_mm3=0.0, bbox_diag_mm=0.0, n_nodes=0,
239
- ok=False, healed=False, notes="; ".join(notes), attempts=0)
240
- if n_solids > 1:
241
- notes.append(f"multi-body: kept largest of {n_solids} solids (vol={volume_mm3:.1f} mm3)")
242
-
243
- if defeature:
244
- defeature_ok, defeature_note = _apply_defeature()
245
- if defeature_note:
246
- notes.append(defeature_note)
247
- if not defeature_ok:
248
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=0.0,
249
- n_nodes=0, ok=False, healed=False, notes="; ".join(notes),
250
- attempts=0)
251
-
252
- xmin, ymin, zmin, xmax, ymax, zmax = gmsh.model.getBoundingBox(-1, -1)
253
- bbox_diag_mm = float(np.linalg.norm([xmax - xmin, ymax - ymin, zmax - zmin]))
254
- base_size = _first_guess_elem_size(bbox_diag_mm, target_nodes)
255
-
256
- fail_notes: list[str] = []
257
-
258
- def build_fn(msh_path, elem_size):
259
- size = elem_size if elem_size is not None else base_size
260
- ok_, n_nodes_, note_ = _tag_and_mesh(size, msh_path)
261
- if not ok_:
262
- fail_notes.append(note_)
263
- return (n_nodes_ if ok_ else 0), size
264
-
265
- n_nodes, _used_size, attempts = _search_target_nodes(build_fn, out_msh, target_nodes)
266
- if n_nodes > 0:
267
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm,
268
- n_nodes=n_nodes, ok=True, healed=False, notes="; ".join(notes),
269
- attempts=attempts)
270
- notes.append(f"unhealed mesh attempt failed: {fail_notes[-1] if fail_notes else 'unknown'}")
271
- finally:
272
- gmsh.finalize()
273
-
274
- # ---- Pass 2: heal + density-searched retry (fresh session) ----
275
- healed = False
276
- gmsh.initialize()
277
- try:
278
- gmsh.option.setNumber("General.Terminal", 0)
279
- gmsh.model.add("part_healed")
280
- n_solids2, volume_mm32, err2 = _import_and_reduce(step_path)
281
- if err2 is not None:
282
- notes.append(f"pass-2 {err2}")
283
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm,
284
- n_nodes=0, ok=False, healed=False, notes="; ".join(notes),
285
- attempts=attempts)
286
-
287
- if defeature:
288
- defeature_ok2, defeature_note2 = _apply_defeature()
289
- if defeature_note2:
290
- notes.append(defeature_note2)
291
- if not defeature_ok2:
292
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm,
293
- n_nodes=0, ok=False, healed=False, notes="; ".join(notes),
294
- attempts=attempts)
295
-
296
- heal_ok, heal_note = _apply_heal()
297
- if heal_note:
298
- notes.append(heal_note)
299
- if not heal_ok:
300
- notes.append("meshing failed after heal attempt")
301
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm,
302
- n_nodes=0, ok=False, healed=False, notes="; ".join(notes),
303
- attempts=attempts)
304
- healed = True
305
-
306
- fail_notes2: list[str] = []
307
-
308
- def build_fn2(msh_path, elem_size):
309
- size = elem_size if elem_size is not None else base_size
310
- ok_, n_nodes_, note_ = _tag_and_mesh(size, msh_path)
311
- if not ok_:
312
- fail_notes2.append(note_)
313
- return (n_nodes_ if ok_ else 0), size
314
-
315
- n_nodes2, _used_size2, attempts2 = _search_target_nodes(build_fn2, out_msh, target_nodes)
316
- if n_nodes2 > 0:
317
- notes.append("meshed after heal")
318
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm,
319
- n_nodes=n_nodes2, ok=True, healed=True, notes="; ".join(notes),
320
- attempts=attempts + attempts2)
321
- notes.append(f"post-heal mesh attempt failed: {fail_notes2[-1] if fail_notes2 else 'unknown'}")
322
- notes.append("meshing failed after heal attempt")
323
- return dict(n_solids=n_solids, volume_mm3=volume_mm3, bbox_diag_mm=bbox_diag_mm,
324
- n_nodes=0, ok=False, healed=healed, notes="; ".join(notes),
325
- attempts=attempts + attempts2)
326
- finally:
327
- gmsh.finalize()
328
-
329
-
330
- def auto_elem_size(bbox_diag: float) -> float:
331
- """Default fixed element size for `mesh_step`: bounding-box diagonal / 60."""
332
- return bbox_diag / 60.0
333
-
334
-
335
- def mesh_step(step_path: str, out_msh: str, elem_size: float | None = None) -> dict:
336
- """Mesh the whole STEP model at one fixed element size (no healing, no
337
- density search). Every surface is tagged "Cooling"."""
338
- import gmsh
339
-
340
- gmsh.initialize()
341
- try:
342
- gmsh.option.setNumber("General.Terminal", 0)
343
- gmsh.model.add("casting")
344
- gmsh.model.occ.importShapes(step_path)
345
- gmsh.model.occ.synchronize()
346
-
347
- xmin, ymin, zmin, xmax, ymax, zmax = gmsh.model.getBoundingBox(-1, -1)
348
- bbox = (xmax - xmin, ymax - ymin, zmax - zmin)
349
- diag = float(np.linalg.norm(bbox))
350
- size = float(elem_size) if elem_size is not None else auto_elem_size(diag)
351
- gmsh.option.setNumber("Mesh.MeshSizeMin", size)
352
- gmsh.option.setNumber("Mesh.MeshSizeMax", size)
353
-
354
- vols = [t for (d, t) in gmsh.model.getEntities(3)]
355
- surfs = [t for (d, t) in gmsh.model.getEntities(2)]
356
- pv = gmsh.model.addPhysicalGroup(3, vols); gmsh.model.setPhysicalName(3, pv, "Volume")
357
- pc = gmsh.model.addPhysicalGroup(2, surfs); gmsh.model.setPhysicalName(2, pc, "Cooling")
358
-
359
- gmsh.model.mesh.generate(3)
360
- gmsh.option.setNumber("Mesh.MshFileVersion", 2.2)
361
- gmsh.write(out_msh)
362
-
363
- node_tags, _, _ = gmsh.model.mesh.getNodes()
364
- tet_tags = gmsh.model.mesh.getElementsByType(4)[0]
365
- return {"n_nodes": len(node_tags), "n_tets": len(tet_tags),
366
- "bbox_mm": bbox, "elem_size": size}
367
- finally:
368
- gmsh.finalize()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/model_api.py DELETED
@@ -1,80 +0,0 @@
1
- """Mesh in, solidification-time field out.
2
-
3
- from src.model_api import CastSolidModel
4
- model = CastSolidModel() # loads weights/ once
5
- seconds = model.predict("part.msh", alloy="G20Mn5")
6
-
7
- `predict` takes a gmsh 2.2 ASCII tetrahedral mesh (a path or a parsed
8
- `src.msh_parse.Mesh`) whose cooling surface is tagged "Cooling", and returns
9
- the solidification time in seconds for every node, in the mesh's node order.
10
- """
11
- from __future__ import annotations
12
-
13
- import os
14
-
15
- import numpy as np
16
- import torch
17
-
18
- from src import gbm_heads
19
- from src.features import alloy_g_vector, node_features
20
- from src.hybrid import hybrid_field_soft
21
- from src.inference_props import DEFAULT_MOLD, resolve_props
22
- from src.model_gnn import load_gnn, predict_graph_seconds
23
- from src.msh_parse import Mesh, parse_msh
24
- from src.release_io import load_gbm, load_gnn_state
25
-
26
- # Recomposition weights of the published model (see src/hybrid.py).
27
- W_TOTAL = 1.0
28
- W_STD = 4.0
29
-
30
- GNN_FILE = "gnn_v5.1.safetensors"
31
- TOTAL_HEAD_FILE = "gbm_total_v3.skops"
32
- SPREAD_HEAD_FILE = "gbm_std_v2.skops"
33
-
34
-
35
- class CastSolidModel:
36
- def __init__(self, weights_dir: str = "weights", device: str | None = None):
37
- self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
38
- state = load_gnn_state(os.path.join(weights_dir, GNN_FILE), self.device)
39
- self.gnn, self.cfg, self.norm = load_gnn(state, self.device)
40
- self.total_head = load_gbm(os.path.join(weights_dir, TOTAL_HEAD_FILE))
41
- self.spread_head = load_gbm(os.path.join(weights_dir, SPREAD_HEAD_FILE))
42
- gbm_heads.check_head(self.total_head, gbm_heads.N_TOTAL_FEATURES, "total-time")
43
- gbm_heads.check_head(self.spread_head, gbm_heads.N_SPREAD_FEATURES, "spread")
44
-
45
- def predict(self, mesh: str | Mesh, alloy: str | None = None, mold: str = DEFAULT_MOLD,
46
- props_json: str | None = None) -> np.ndarray:
47
- """Per-node solidification time (s).
48
-
49
- `alloy`/`mold` name rows of `data/properties/` (default EN-GJS-400-15
50
- in green sand); `props_json` replaces both with your own values."""
51
- props = resolve_props(alloy=alloy, mold=mold, props_json=props_json)
52
- return self.predict_with_props(mesh, props)[0]
53
-
54
- def predict_with_props(self, mesh: str | Mesh, props: dict) -> tuple[np.ndarray, dict]:
55
- """(seconds, details) for an already-resolved property dict.
56
-
57
- `details` holds the node feature matrix `X`, the heads' `total_s` and
58
- `spread_s`, and the recomposition diagnostics `recomposition`."""
59
- if not isinstance(mesh, Mesh):
60
- mesh = parse_msh(os.fspath(mesh))
61
- feat = node_features(mesh, props["mold_effusivity"])
62
- X = feat["X"]
63
- gnn_seconds = predict_graph_seconds(self.gnn, self.cfg, self.norm, X, feat["pos"],
64
- feat["mesh_edges"], alloy_g_vector(props),
65
- device=self.device)
66
- row = gbm_heads.total_row(props, X)
67
- total = gbm_heads.predict_total_seconds(self.total_head, row)
68
- spread = gbm_heads.predict_spread_seconds(self.spread_head,
69
- gbm_heads.spread_row(row, X))
70
- seconds, info = hybrid_field_soft(gnn_seconds, total, spread,
71
- w_total=W_TOTAL, w_std=W_STD)
72
- return seconds, {"X": X, "total_s": total, "spread_s": spread,
73
- "recomposition": info}
74
-
75
- @staticmethod
76
- def hotspots(seconds: np.ndarray, top_frac: float = 0.1) -> np.ndarray:
77
- """Boolean mask of the `top_frac` latest-solidifying nodes."""
78
- seconds = np.asarray(seconds, dtype=np.float32)
79
- k = max(1, int(round(seconds.shape[0] * top_frac)))
80
- return seconds >= np.sort(seconds)[-k]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/model_gnn.py DELETED
@@ -1,136 +0,0 @@
1
- """The graph network: an encode-process-decode GNN in the style of
2
- MeshGraphNets, conditioned on the alloy/mold vector through FiLM.
3
-
4
- It predicts the standardized log1p solidification time of every node. The
5
- graph is the union of the tetrahedral mesh edges and each node's k nearest
6
- neighbours; an edge carries its displacement vector (mm), its length and a
7
- flag telling whether it is a mesh edge.
8
- """
9
- import numpy as np
10
- import torch
11
- import torch.nn as nn
12
- from torch_geometric.nn import knn_graph
13
- from torch_geometric.utils import scatter, to_undirected
14
-
15
-
16
- def _mlp(i, h, o):
17
- return nn.Sequential(nn.Linear(i, h), nn.ReLU(), nn.Linear(h, o))
18
-
19
-
20
- class ProcessorBlock(nn.Module):
21
- """One message-passing step with residual edge and node updates."""
22
-
23
- def __init__(self, h):
24
- super().__init__()
25
- self.edge_mlp = _mlp(3 * h, h, h)
26
- self.edge_norm = nn.LayerNorm(h)
27
- self.node_mlp = _mlp(2 * h, h, h)
28
- self.node_norm = nn.LayerNorm(h)
29
-
30
- def forward(self, hnode, edge_index, e):
31
- src, dst = edge_index
32
- e_new = self.edge_norm(self.edge_mlp(torch.cat([hnode[src], hnode[dst], e], dim=-1)) + e)
33
- agg = scatter(e_new, dst, dim=0, dim_size=hnode.shape[0], reduce="mean")
34
- h_new = self.node_norm(self.node_mlp(torch.cat([hnode, agg], dim=-1)) + hnode)
35
- return h_new, e_new
36
-
37
-
38
- class FiLM(nn.Module):
39
- """g -> per-channel (gamma, beta); applied as h * (1 + gamma) + beta."""
40
-
41
- def __init__(self, g_dim, hidden):
42
- super().__init__()
43
- self.net = nn.Sequential(nn.Linear(g_dim, hidden), nn.SiLU(),
44
- nn.Linear(hidden, 2 * hidden))
45
-
46
- def forward(self, h, g_nodes):
47
- gamma, beta = self.net(g_nodes).chunk(2, dim=-1)
48
- return h * (1.0 + gamma) + beta
49
-
50
-
51
- class SolidGNN(nn.Module):
52
- """12 processor blocks (hidden width 128 in the published model), FiLM
53
- after each block, and a two-head decoder: a per-node deviation head and
54
- a graph-level scale head on the mean node embedding."""
55
-
56
- def __init__(self, node_in=15, edge_in=5, hidden=128, n_blocks=12, g_dim=5):
57
- super().__init__()
58
- self.node_encoder = nn.Sequential(_mlp(node_in, hidden, hidden), nn.LayerNorm(hidden))
59
- self.edge_encoder = nn.Sequential(_mlp(edge_in, hidden, hidden), nn.LayerNorm(hidden))
60
- self.blocks = nn.ModuleList([ProcessorBlock(hidden) for _ in range(n_blocks)])
61
- self.decoder = _mlp(hidden, hidden // 2, 1)
62
- self.scale_head = _mlp(hidden, hidden // 2, 1)
63
- self.films = nn.ModuleList([FiLM(g_dim, hidden) for _ in range(n_blocks)])
64
-
65
- def forward(self, x, edge_index, edge_attr, batch, g):
66
- h = self.node_encoder(x)
67
- e = self.edge_encoder(edge_attr)
68
- g_nodes = g[batch]
69
- for i, blk in enumerate(self.blocks):
70
- h, e = blk(h, edge_index, e)
71
- h = self.films[i](h, g_nodes)
72
- y_nodal = self.decoder(h).squeeze(-1)
73
- dev = y_nodal - scatter(y_nodal, batch, dim=0, reduce="mean")[batch]
74
- scale = self.scale_head(scatter(h, batch, dim=0, reduce="mean")).squeeze(-1)
75
- return dev + scale[batch]
76
-
77
-
78
- def knn_edge_index(pos: torch.Tensor, k: int = 16) -> torch.Tensor:
79
- ei = knn_graph(pos, k=k, loop=False) # directed k-nearest
80
- return to_undirected(ei) # symmetric
81
-
82
-
83
- def union_edge_index(pos: torch.Tensor, mesh_edges: torch.Tensor, k: int = 16):
84
- """Undirected union of the mesh edges and kNN edges, deduplicated.
85
-
86
- mesh_edges: (M, 2) long tensor of unique node pairs (any orientation).
87
- Returns (edge_index (2, E) long, is_mesh (E,) float32 flag)."""
88
- n = pos.shape[0]
89
- knn = knn_edge_index(pos, k=k).to(torch.long)
90
- me = mesh_edges.t().to(torch.long)
91
- me = torch.cat([me, me.flip(0)], dim=1) # both directions
92
- mesh_key = me[0] * n + me[1]
93
- keys = torch.unique(torch.cat([mesh_key, knn[0] * n + knn[1]]))
94
- ei = torch.stack([keys // n, keys % n])
95
- is_mesh = torch.isin(keys, mesh_key).to(torch.float32)
96
- return ei, is_mesh
97
-
98
-
99
- def union_edge_attr(pos: torch.Tensor, edge_index: torch.Tensor,
100
- is_mesh: torch.Tensor) -> torch.Tensor:
101
- """(E, 5): displacement (3), length, mesh-edge flag."""
102
- src, dst = edge_index
103
- d = pos[dst] - pos[src]
104
- return torch.cat([d, d.norm(dim=1, keepdim=True), is_mesh.unsqueeze(1)], dim=1)
105
-
106
-
107
- def load_gnn(state: dict, device):
108
- """Build a `SolidGNN` from a `{model, norm, cfg}` dict (see
109
- `src.release_io.load_gnn_state`). Returns (model, cfg, norm)."""
110
- cfg, norm = state["cfg"], state["norm"]
111
- model = SolidGNN(node_in=cfg["node_in"], edge_in=cfg["edge_in"], hidden=cfg["hidden"],
112
- n_blocks=cfg["n_blocks"], g_dim=cfg.get("g_dim", 5)).to(device)
113
- model.load_state_dict(state["model"])
114
- model.eval()
115
- return model, cfg, norm
116
-
117
-
118
- def predict_graph_seconds(model, cfg, norm, X, pos_np, mesh_edges, g_vec,
119
- device="cpu") -> np.ndarray:
120
- """Per-node solidification time (s) predicted by the GNN alone.
121
-
122
- `X` is the raw (N, 15) feature matrix, `g_vec` the raw (5,) alloy/mold
123
- vector; standardization uses the statistics stored with the weights."""
124
- fmean = torch.tensor(norm["feat_mean"], dtype=torch.float32)
125
- fstd = torch.tensor(norm["feat_std"], dtype=torch.float32)
126
- x = (torch.tensor(X, dtype=torch.float32) - fmean) / fstd
127
- pos = torch.tensor(pos_np, dtype=torch.float32)
128
- me = torch.tensor(mesh_edges, dtype=torch.long)
129
- ei, is_mesh = union_edge_index(pos, me, k=cfg["k"])
130
- ea = union_edge_attr(pos, ei, is_mesh)
131
- zeros = torch.zeros(x.shape[0], dtype=torch.long, device=device)
132
- g = torch.tensor(np.asarray(g_vec), dtype=torch.float32).reshape(1, -1).to(device)
133
- with torch.no_grad():
134
- yn = model(x.to(device), ei.to(device), ea.to(device), zeros, g)
135
- pred_log = yn.cpu().numpy() * norm["y_log_std"] + norm["y_log_mean"]
136
- return np.clip(np.expm1(pred_log), 0.0, None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/msh_parse.py DELETED
@@ -1,67 +0,0 @@
1
- """Reader for gmsh 2.2 ASCII meshes.
2
-
3
- Extracts node coordinates (mm, in the file's node order), surface triangles
4
- grouped by physical name ("Cooling", optionally "Adiabatic") and volume
5
- tetrahedra. Connectivity is remapped to 0-based node indices.
6
- """
7
- from dataclasses import dataclass
8
- import numpy as np
9
-
10
- _TRI_TYPE = 2 # 3-node triangle
11
- _TET_TYPE = 4 # 4-node tetrahedron
12
-
13
-
14
- @dataclass
15
- class Mesh:
16
- node_xyz: np.ndarray # (N, 3) float64, mm
17
- tris: dict # name -> (M, 3) int64, 0-based
18
- tets: np.ndarray # (K, 4) int64, 0-based
19
-
20
-
21
- def parse_msh(path: str) -> Mesh:
22
- lines = open(path).read().splitlines()
23
- i, n = 0, len(lines)
24
- phys = {} # physical tag -> name
25
- node_ids = [] # id order
26
- coords = [] # xyz in that order
27
- tri_by_name = {} # name -> list of [i,j,k]
28
- tets = []
29
-
30
- while i < n:
31
- s = lines[i].strip()
32
- if s == "$PhysicalNames":
33
- cnt = int(lines[i + 1])
34
- for k in range(cnt):
35
- dim, tag, name = lines[i + 2 + k].split(maxsplit=2)
36
- phys[int(tag)] = name.strip().strip('"')
37
- i += 2 + cnt
38
- continue
39
- if s == "$Nodes":
40
- cnt = int(lines[i + 1])
41
- for k in range(cnt):
42
- p = lines[i + 2 + k].split()
43
- node_ids.append(int(p[0]))
44
- coords.append((float(p[1]), float(p[2]), float(p[3])))
45
- i += 2 + cnt
46
- continue
47
- if s == "$Elements":
48
- cnt = int(lines[i + 1])
49
- id2idx = {nid: idx for idx, nid in enumerate(node_ids)}
50
- for k in range(cnt):
51
- p = [int(x) for x in lines[i + 2 + k].split()]
52
- etype, ntags = p[1], p[2]
53
- tags = p[3:3 + ntags]
54
- conn = [id2idx[v] for v in p[3 + ntags:]]
55
- name = phys.get(tags[0]) if ntags else None
56
- if etype == _TRI_TYPE and name is not None:
57
- tri_by_name.setdefault(name, []).append(conn)
58
- elif etype == _TET_TYPE:
59
- tets.append(conn)
60
- i += 2 + cnt
61
- continue
62
- i += 1
63
-
64
- node_xyz = np.asarray(coords, dtype=np.float64)
65
- tris = {name: np.asarray(v, dtype=np.int64) for name, v in tri_by_name.items()}
66
- tets_arr = np.asarray(tets, dtype=np.int64) if tets else np.empty((0, 4), np.int64)
67
- return Mesh(node_xyz=node_xyz, tris=tris, tets=tets_arr)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/ood.py DELETED
@@ -1,23 +0,0 @@
1
- """Out-of-distribution size check: compare a casting's volume, bounding-box
2
- diagonal and largest distance to cooling with the training maxima
3
- (`weights/ood_ranges.json`) and warn when any of them is exceeded."""
4
- import json
5
-
6
-
7
- def load_ranges(path: str) -> dict:
8
- with open(path) as f:
9
- return json.load(f)
10
-
11
-
12
- def ood_flags(volume_mm3, bbox_diag, geodesic_d_cool_max, ranges, tol=1.05) -> list:
13
- w = []
14
- if volume_mm3 > ranges["volume_mm3_max"] * tol:
15
- w.append(f"casting volume {volume_mm3:.0f} mm^3 exceeds training max "
16
- f"{ranges['volume_mm3_max']:.0f} mm^3 — prediction unreliable")
17
- if bbox_diag > ranges["bbox_diag_max"] * tol:
18
- w.append(f"bounding-box diagonal {bbox_diag:.0f} mm exceeds training max "
19
- f"{ranges['bbox_diag_max']:.0f} mm — prediction unreliable")
20
- if geodesic_d_cool_max > ranges["geodesic_d_cool_max"] * tol:
21
- w.append(f"max distance-to-cooling {geodesic_d_cool_max:.1f} mm exceeds training max "
22
- f"{ranges['geodesic_d_cool_max']:.1f} mm — prediction unreliable")
23
- return w
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/predict_casting.py DELETED
@@ -1,283 +0,0 @@
1
- """STEP file in, solidification field out.
2
-
3
- python -m src.predict_casting part.step --out-dir out [--alloy G20Mn5]
4
-
5
- Steps: mesh the STEP file (healed, density-searched and cached, or at a fixed
6
- element size with --elem-size), run the model, check the training envelope,
7
- screen for shrinkage, and write `<name>.vtu`, `<name>_summary.txt` and the
8
- mesh `<name>.msh` to the output directory.
9
- """
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import logging
14
- import os
15
- import os.path as osp
16
-
17
- import numpy as np
18
-
19
- from src import ood as _ood
20
- from src.features import FEATURE_NAMES
21
- from src.inference_props import DEFAULT_ALLOY, DEFAULT_MOLD, resolve_alloy_family, resolve_props
22
- from src.mesh_cache import get_or_mesh
23
- from src.meshing import DEFAULT_TARGET_NODES, mesh_step
24
- from src.model_api import CastSolidModel
25
- from src.msh_parse import parse_msh
26
- from src.shrinkage import screen_casting
27
-
28
- logger = logging.getLogger(__name__)
29
-
30
- MODEL_VERSION = "v5.1"
31
- _VOL_IDX = FEATURE_NAMES.index("volume_mm3")
32
- _GCOOL_IDX = FEATURE_NAMES.index("geodesic_d_cool")
33
-
34
-
35
- def write_vtu(out_path, node_xyz, tets, seconds, top_frac=0.1, extra_point_data=None):
36
- """Write the mesh with `solidification_time` (s) and `hotspot` (the
37
- `top_frac` latest-solidifying nodes) point fields, plus any extras."""
38
- import meshio
39
- seconds = np.asarray(seconds, dtype=np.float32)
40
- n = seconds.shape[0]
41
- k = max(1, int(round(n * top_frac)))
42
- thresh = np.sort(seconds)[-k]
43
- hotspot = (seconds >= thresh).astype(np.int32)
44
- point_data = {"solidification_time": seconds, "hotspot": hotspot}
45
- if extra_point_data:
46
- point_data.update(extra_point_data)
47
- m = meshio.Mesh(points=np.asarray(node_xyz, dtype=np.float64),
48
- cells=[("tetra", np.asarray(tets))],
49
- point_data=point_data)
50
- m.write(out_path)
51
-
52
-
53
- def _surface_and_feed_nodes(mesh):
54
- """All tagged surface nodes, and the adiabatic-tagged ones that can feed
55
- a shrinkage region (none on a STEP meshed by this pipeline)."""
56
- tri_arrays = [tri for tri in mesh.tris.values() if tri.size]
57
- surface_nodes = (np.unique(np.concatenate(tri_arrays, axis=0).reshape(-1))
58
- if tri_arrays else np.zeros(0, dtype=np.int64))
59
- adiab_tri = mesh.tris.get("Adiabatic")
60
- feed_nodes = (np.unique(adiab_tri.reshape(-1))
61
- if adiab_tri is not None and adiab_tri.size else np.zeros(0, dtype=np.int64))
62
- return surface_nodes.astype(np.int64), feed_nodes.astype(np.int64)
63
-
64
-
65
- def _shrinkage_result_for_return(screen: dict) -> dict:
66
- """The screening result without its per-node arrays, plus counts."""
67
- result = {k: v for k, v in screen.items() if k not in ("niyama", "porosity_risk")}
68
- risk = screen["porosity_risk"]
69
- result["flagged_frac"] = float(np.mean(risk)) if risk.size else 0.0
70
- result["n_macro_regions"] = len(screen["macro_shrinkage"])
71
- result["n_sinks"] = len(screen["top_sinks"])
72
- result["n_feeders"] = len(screen["feeders"])
73
- return result
74
-
75
-
76
- def _shrinkage_point_data(mesh, screen: dict) -> dict:
77
- n_nodes = mesh.node_xyz.shape[0]
78
- macro_region_id = np.full(n_nodes, -1, dtype=np.int64)
79
- for region in screen["macro_shrinkage"]:
80
- macro_region_id[np.asarray(region["nodes"], dtype=np.int64)] = region["region_id"]
81
- return {
82
- "niyama": np.asarray(screen["niyama"], dtype=np.float32),
83
- "porosity_risk": np.asarray(screen["porosity_risk"], dtype=np.uint8),
84
- "macro_region_id": macro_region_id,
85
- }
86
-
87
-
88
- def _write_shrinkage_summary(f, shrinkage) -> None:
89
- if shrinkage is None:
90
- f.write("shrinkage screening: disabled\n")
91
- return
92
- f.write("shrinkage screening:\n")
93
- f.write(f" niyama_source: {shrinkage['niyama_source']}\n")
94
- # The risk mask is the lowest Niyama decile of the part, so this
95
- # percentage is fixed by construction, not a measured severity.
96
- f.write(f" flagged nodes: {shrinkage['flagged_frac'] * 100.0:.1f}%"
97
- f" (bottom decile by construction)\n")
98
- macro = shrinkage["macro_shrinkage"]
99
- if macro:
100
- # Regions under 4 nodes are listed but get no feeder suggestion.
101
- n_sub_resolution = sum(1 for r in macro if r.get("sub_resolution"))
102
- region_count = str(len(macro))
103
- if n_sub_resolution:
104
- region_count += f" (+{n_sub_resolution} sub-resolution)"
105
- worst = max(macro, key=lambda r: r["severity"])
106
- c = worst["centroid"]
107
- f.write(f" macro shrinkage regions: {region_count} "
108
- f"(worst severity={worst['severity']:.4g} mm^3 @ "
109
- f"({c[0]:.1f},{c[1]:.1f},{c[2]:.1f}))\n")
110
- else:
111
- f.write(" macro shrinkage regions: 0\n")
112
- f.write(f" sinks: {len(shrinkage['top_sinks'])}\n")
113
- feeders = shrinkage["feeders"]
114
- if feeders:
115
- f.write(" feeder recommendations:\n")
116
- for feeder in feeders:
117
- loc = feeder["location"]
118
- f.write(f" - location=({loc[0]:.1f},{loc[1]:.1f},{loc[2]:.1f}) mm "
119
- f"min_modulus_mm={feeder['min_modulus_mm']:.4f}\n")
120
- else:
121
- f.write(" feeder recommendations: none\n")
122
- if shrinkage.get("alloy_family_assumed"):
123
- f.write(f" alloy_family_assumed: {shrinkage['material']['alloy_family']} "
124
- f"(alloy not in the materials table -- conservative fallback)\n")
125
-
126
-
127
- def _mesh(step_path, out_msh, elem_size, target_nodes, cache_dir):
128
- if elem_size is not None:
129
- info = mesh_step(step_path, out_msh, elem_size)
130
- mesh = parse_msh(out_msh)
131
- return mesh, {"mode": "fixed", "n_nodes": info["n_nodes"], "n_tets": info["n_tets"],
132
- "elem_size": info["elem_size"], "cache": "n/a"}
133
- info = get_or_mesh(step_path, out_msh, target_nodes=target_nodes, cache_dir=cache_dir)
134
- if not info.get("ok", False):
135
- raise RuntimeError(f"meshing failed for {step_path!r}: {info.get('notes', '(no notes)')}")
136
- mesh = parse_msh(out_msh)
137
- return mesh, {"mode": "density-searched", "n_nodes": info["n_nodes"],
138
- "n_tets": int(mesh.tets.shape[0]), "elem_size": None,
139
- "cache": info.get("cache", "unknown")}
140
-
141
-
142
- def predict_casting(step_path, out_dir="runs/castings", alloy=None, mold=DEFAULT_MOLD,
143
- props_json=None, elem_size=None,
144
- target_nodes: int = DEFAULT_TARGET_NODES,
145
- screen_shrinkage: bool = True, gravity: tuple = (0, 0, -1),
146
- model: CastSolidModel | None = None, weights_dir: str = "weights",
147
- ood_json: str | None = None, cache_dir: str = "runs/mesh_cache",
148
- device: str | None = None) -> dict:
149
- """Mesh `step_path`, predict, and write the result files.
150
-
151
- `alloy`/`mold` name rows of `data/properties/` (default EN-GJS-400-15 in
152
- green sand); `props_json` replaces both. `elem_size` (mm) meshes at a
153
- fixed size instead of searching for `target_nodes`. Pass a loaded
154
- `model` to reuse it across calls.
155
-
156
- Returns {name, vtu, summary, msh, total_time_s, hotspot_xyz (5 x 3 mm),
157
- ood_warnings, n_nodes, mesh_mode, elem_size, cache, recomposition_info,
158
- shrinkage}."""
159
- if elem_size is not None and target_nodes != DEFAULT_TARGET_NODES:
160
- raise ValueError("predict_casting: give either elem_size or target_nodes, not both")
161
- os.makedirs(out_dir, exist_ok=True)
162
- name = osp.splitext(osp.basename(step_path))[0]
163
- out_msh = osp.join(out_dir, f"{name}.msh")
164
-
165
- # Resolve properties before meshing so a bad alloy name fails fast.
166
- props = resolve_props(alloy=alloy, mold=mold, props_json=props_json)
167
- model = model or CastSolidModel(weights_dir=weights_dir, device=device)
168
-
169
- mesh, minfo = _mesh(step_path, out_msh, elem_size, target_nodes, cache_dir)
170
- seconds, details = model.predict_with_props(mesh, props)
171
- X = details["X"]
172
-
173
- warnings = []
174
- ood_json = ood_json or osp.join(weights_dir, "ood_ranges.json")
175
- if osp.exists(ood_json):
176
- diag = float(np.linalg.norm(mesh.node_xyz.max(0) - mesh.node_xyz.min(0)))
177
- warnings = _ood.ood_flags(float(X[0, _VOL_IDX]), diag, float(X[:, _GCOOL_IDX].max()),
178
- _ood.load_ranges(ood_json))
179
-
180
- shrinkage = None
181
- point_data = None
182
- if screen_shrinkage:
183
- surface_nodes, feed_nodes = _surface_and_feed_nodes(mesh)
184
- if surface_nodes.size == 0:
185
- logger.warning("predict_casting: no surface nodes on the mesh -- "
186
- "shrinkage screening skipped")
187
- else:
188
- alloy_family, assumed = resolve_alloy_family(alloy, props_json)
189
- screen = screen_casting(pos=mesh.node_xyz, tets=mesh.tets,
190
- surface_nodes=surface_nodes, t_s=seconds,
191
- TL=props["TL"], TS=props["TS"],
192
- alloy_family=alloy_family, gravity_vec=gravity,
193
- feed_nodes=feed_nodes)
194
- shrinkage = _shrinkage_result_for_return(screen)
195
- if assumed:
196
- shrinkage["alloy_family_assumed"] = True
197
- point_data = _shrinkage_point_data(mesh, screen)
198
-
199
- vtu = osp.join(out_dir, f"{name}.vtu")
200
- write_vtu(vtu, mesh.node_xyz, mesh.tets, seconds, extra_point_data=point_data)
201
-
202
- order = np.argsort(seconds)[::-1][:5]
203
- hot_xyz = mesh.node_xyz[order]
204
- total = float(seconds.max())
205
- info = details["recomposition"]
206
- summary = osp.join(out_dir, f"{name}_summary.txt")
207
- alloy_label = (f"custom ({props_json})" if props_json is not None
208
- else alloy if alloy is not None else DEFAULT_ALLOY)
209
- mold_label = mold if props_json is None else "n/a (props_json)"
210
- bbox_mm = tuple(round(float(v), 1) for v in mesh.node_xyz.max(0) - mesh.node_xyz.min(0))
211
- elem_label = (f"{minfo['elem_size']:.2f} mm" if minfo["elem_size"] is not None
212
- else "n/a (density-searched)")
213
- with open(summary, "w") as f:
214
- f.write(f"casting: {name}\n")
215
- f.write(f"total solidification time: {total:.1f} s\n")
216
- f.write(f"alloy: {alloy_label} mold: {mold_label} model: {MODEL_VERSION}\n")
217
- f.write(f"mesh: {minfo['mode']} cache: {minfo['cache']} nodes: {minfo['n_nodes']} "
218
- f"tets: {minfo['n_tets']} elem_size: {elem_label} bbox_mm: {bbox_mm}\n")
219
- line = (f"recomposition: a={info['a']:.4f}, m={info['m']:.4f}, "
220
- f"target_unreachable={info['target_unreachable']}, "
221
- f"clip_frac={info['clip_frac']:.4f}")
222
- if abs(info.get("total_deviation_frac", 0.0)) > 0.001:
223
- line += f", total_dev={info['total_deviation_frac'] * 100.0:+.1f}%"
224
- f.write(line + "\n")
225
- if screen_shrinkage:
226
- _write_shrinkage_summary(f, shrinkage)
227
- f.write("top hot spots (x,y,z mm : t_solidus s):\n")
228
- for xyz_i, i in zip(hot_xyz, order):
229
- f.write(f" ({xyz_i[0]:.1f},{xyz_i[1]:.1f},{xyz_i[2]:.1f}) : {seconds[i]:.1f}\n")
230
- if warnings:
231
- f.write("WARNINGS:\n")
232
- for w in warnings:
233
- f.write(f" - {w}\n")
234
-
235
- return {"name": name, "vtu": vtu, "summary": summary, "msh": out_msh,
236
- "total_time_s": total, "hotspot_xyz": hot_xyz, "ood_warnings": warnings,
237
- "n_nodes": minfo["n_nodes"], "mesh_mode": minfo["mode"],
238
- "elem_size": minfo["elem_size"], "cache": minfo["cache"],
239
- "recomposition_info": info, "shrinkage": shrinkage}
240
-
241
-
242
- def _parse_gravity(s: str) -> tuple:
243
- parts = [p.strip() for p in s.split(",")]
244
- if len(parts) != 3:
245
- raise ValueError(f"--gravity must be 'x,y,z' (3 comma-separated numbers), got {s!r}")
246
- vec = tuple(float(p) for p in parts)
247
- if all(v == 0.0 for v in vec):
248
- raise ValueError(f"--gravity must not be the zero vector (got {s!r})")
249
- return vec
250
-
251
-
252
- def main(argv=None):
253
- ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
254
- ap.add_argument("step_path")
255
- ap.add_argument("--out-dir", default="runs/castings")
256
- ap.add_argument("--alloy", default=None,
257
- help=f"alloy from data/properties/materials.csv (default {DEFAULT_ALLOY})")
258
- ap.add_argument("--mold", default=DEFAULT_MOLD,
259
- help=f"mold from data/properties/molds.csv (default {DEFAULT_MOLD})")
260
- ap.add_argument("--props", dest="props_json", default=None,
261
- help="JSON file with k, rho, cp, L_kJ_kg, TL, TS, Tpour, mold_effusivity "
262
- "(replaces --alloy and --mold)")
263
- ap.add_argument("--elem-size", type=float, default=None,
264
- help="mesh at this fixed element size in mm instead of searching for "
265
- f"about {DEFAULT_TARGET_NODES} nodes")
266
- ap.add_argument("--gravity", type=_parse_gravity, default=(0, 0, -1),
267
- help="gravity direction 'x,y,z' for sinks and feeder placement "
268
- "(default 0,0,-1)")
269
- ap.add_argument("--no-shrinkage", dest="screen_shrinkage", action="store_false",
270
- help="skip the shrinkage screening")
271
- ap.add_argument("--weights-dir", default="weights")
272
- a = ap.parse_args(argv)
273
- r = predict_casting(a.step_path, out_dir=a.out_dir, alloy=a.alloy, mold=a.mold,
274
- props_json=a.props_json, elem_size=a.elem_size,
275
- screen_shrinkage=a.screen_shrinkage, gravity=a.gravity,
276
- weights_dir=a.weights_dir)
277
- print(f"{r['name']}: total {r['total_time_s']:.1f}s nodes {r['n_nodes']} -> {r['vtu']}")
278
- for w in r["ood_warnings"]:
279
- print("WARNING:", w)
280
-
281
-
282
- if __name__ == "__main__":
283
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/release_io.py DELETED
@@ -1,47 +0,0 @@
1
- """Loading the published weight files.
2
-
3
- - GNN: one safetensors file with tensors `model.<state_dict key>` and
4
- `norm.<key>`; the architecture config (`cfg`) and the container type of
5
- each normalization entry are JSON strings in the safetensors metadata.
6
- - Gradient-boosted heads: skops files. Before loading, every type a file
7
- names is checked against an allowlist (scikit-learn and NumPy only).
8
-
9
- Neither format runs code when loaded.
10
- """
11
- from __future__ import annotations
12
-
13
- import json
14
- import os
15
-
16
- GNN_FORMAT = "foundry-gnn-release/1"
17
-
18
- _SKOPS_ALLOWED_PREFIXES = ("sklearn.", "numpy.")
19
-
20
-
21
- def load_gnn_state(path: str, device="cpu") -> dict:
22
- """The `{model, norm, cfg}` dict stored in a GNN safetensors file."""
23
- from safetensors import safe_open
24
- with safe_open(path, framework="pt", device="cpu") as f:
25
- meta = f.metadata() or {}
26
- if meta.get("format") != GNN_FORMAT:
27
- raise ValueError(f"{path}: not a {GNN_FORMAT} file "
28
- f"(format={meta.get('format')!r})")
29
- tensors = {k: f.get_tensor(k) for k in f.keys()}
30
- norm_kinds = json.loads(meta["norm_kinds"])
31
- model = {k[len("model."):]: v.to(device) for k, v in tensors.items()
32
- if k.startswith("model.")}
33
- norm = dict(json.loads(meta["norm_scalars"]))
34
- for k, kind in norm_kinds.items():
35
- t = tensors[f"norm.{k}"]
36
- norm[k] = t.numpy() if kind == "numpy" else t
37
- return {"model": model, "norm": norm, "cfg": json.loads(meta["cfg"])}
38
-
39
-
40
- def load_gbm(path):
41
- """A gradient-boosted head from a skops file, after the type check."""
42
- import skops.io as sio
43
- untrusted = sio.get_untrusted_types(file=os.fspath(path))
44
- bad = [t for t in untrusted if not t.startswith(_SKOPS_ALLOWED_PREFIXES)]
45
- if bad:
46
- raise ValueError(f"{path}: refusing to load unexpected types {bad}")
47
- return sio.load(os.fspath(path), trusted=untrusted)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/shrinkage.py DELETED
@@ -1,498 +0,0 @@
1
- """Shrinkage screening on a predicted solidification-time field.
2
-
3
- Pure numpy/scipy, working on node positions `pos` (mm), tetrahedra `tets` and
4
- the per-node solidification time `t_s` (s). Four outputs:
5
-
6
- - A Niyama-style criterion. With only `t_s` available, the identity
7
- grad(T) = -Tdot * grad(t_s) gives Ny = sqrt(|Tdot|) * |grad(t_s)|, and the
8
- cooling rate is approximated by the freezing-interval rate
9
- (TL - TS) / t_s. The result is a relative ranking within one part, so the
10
- risk mask flags its lowest decile rather than applying absolute
11
- literature thresholds.
12
- - Macro-shrinkage regions: connected groups of the latest-solidifying nodes
13
- that no feed source can reach through metal that is still liquid.
14
- - Sinks: regions whose highest point (against gravity) is on the free
15
- surface, which would draw the surface in rather than void internally.
16
- - Feeder suggestions: a surface point above each region and the minimum
17
- feeder modulus (1.2 x the region's V/A, Chvorinov's rule).
18
- """
19
- import logging
20
-
21
- import numpy as np
22
- from scipy.sparse import csr_matrix
23
- from scipy.sparse.csgraph import connected_components
24
-
25
- logger = logging.getLogger(__name__)
26
-
27
- # Volumetric solidification shrinkage per alloy family, in percent. Severity
28
- # of a region = shrinkage_pct / 100 * region volume. Grey iron's graphite
29
- # expansion offsets its shrinkage, hence 0 (regions are still reported).
30
- SHRINKAGE_PCT = {
31
- "steel": 2.5,
32
- "low_alloy_steel": 2.5,
33
- "ductile_iron": 0.75,
34
- "grey_iron": 0.0,
35
- }
36
-
37
- # Guards divisions and square roots without moving any physical value.
38
- _EPS = 1e-9
39
-
40
-
41
- def node_gradient(pos: np.ndarray, tets: np.ndarray, field: np.ndarray) -> np.ndarray:
42
- """(N, 3) nodal gradient of a P1 field on a tet mesh, in [field units]/mm.
43
-
44
- The gradient is constant per tet (solve J g = df with J the tet's edge
45
- vectors from vertex 0), then averaged onto the nodes weighted by tet
46
- volume. Degenerate tets contribute nothing; isolated nodes get zero."""
47
- pos = np.asarray(pos, dtype=np.float64)
48
- tets = np.asarray(tets, dtype=np.int64)
49
- field = np.asarray(field, dtype=np.float64)
50
- n_nodes = pos.shape[0]
51
-
52
- if tets.shape[0] == 0:
53
- return np.zeros((n_nodes, 3))
54
-
55
- p0 = pos[tets[:, 0]]
56
- p1 = pos[tets[:, 1]]
57
- p2 = pos[tets[:, 2]]
58
- p3 = pos[tets[:, 3]]
59
- f0 = field[tets[:, 0]]
60
- f1 = field[tets[:, 1]]
61
- f2 = field[tets[:, 2]]
62
- f3 = field[tets[:, 3]]
63
-
64
- e1 = p1 - p0
65
- e2 = p2 - p0
66
- e3 = p3 - p0
67
-
68
- jac = np.stack([e1, e2, e3], axis=1) # (M,3,3), rows = edge vectors
69
- rhs = np.stack([f1 - f0, f2 - f0, f3 - f0], axis=1) # (M,3)
70
-
71
- vol = np.abs(np.einsum('ij,ij->i', e1, np.cross(e2, e3))) / 6.0 # (M,)
72
-
73
- grad_tet = np.zeros_like(rhs)
74
- nondeg = vol > 0
75
- if nondeg.any():
76
- grad_tet[nondeg] = np.linalg.solve(jac[nondeg], rhs[nondeg, :, None])[..., 0]
77
-
78
- node_grad_sum = np.zeros((n_nodes, 3))
79
- node_vol_sum = np.zeros(n_nodes)
80
- weighted = grad_tet * vol[:, None]
81
- for k in range(4):
82
- idx = tets[:, k]
83
- np.add.at(node_grad_sum, idx, weighted)
84
- np.add.at(node_vol_sum, idx, vol)
85
-
86
- return node_grad_sum / np.maximum(node_vol_sum, _EPS)[:, None]
87
-
88
-
89
- def niyama_proxy(pos: np.ndarray, tets: np.ndarray, t_s: np.ndarray,
90
- TL: float, TS: float) -> np.ndarray:
91
- """sqrt((TL - TS) / max(t_s, eps)) * |grad(t_s)|, per node.
92
-
93
- `TL`, `TS` in deg C, `t_s` in s, `pos` in mm. A relative ranking within
94
- one part; see the module docstring."""
95
- t_s = np.asarray(t_s, dtype=np.float64)
96
- grad = node_gradient(pos, tets, t_s)
97
- grad_mag = np.linalg.norm(grad, axis=1)
98
-
99
- t_safe = np.maximum(t_s, _EPS)
100
- tdot_proxy = (TL - TS) / t_safe
101
- return np.sqrt(np.maximum(tdot_proxy, 0.0)) * grad_mag
102
-
103
-
104
- def porosity_risk(ny: np.ndarray, pct: float = 10.0) -> np.ndarray:
105
- """Boolean mask of the within-part lowest `pct`% Niyama values
106
- (`ny <= percentile(ny, pct)`; ties at the threshold are all flagged)."""
107
- ny = np.asarray(ny, dtype=np.float64)
108
- threshold = np.percentile(ny, pct)
109
- return ny <= threshold
110
-
111
-
112
- # Local vertex-index pairs/triples of a tetrahedron.
113
- _TET_EDGE_PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
114
- _TET_FACES = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
115
-
116
-
117
- def _tet_volumes(pos: np.ndarray, tets: np.ndarray) -> np.ndarray:
118
- """(M,) unsigned tet volumes in mm^3."""
119
- if tets.shape[0] == 0:
120
- return np.zeros(0)
121
- p0, p1, p2, p3 = pos[tets[:, 0]], pos[tets[:, 1]], pos[tets[:, 2]], pos[tets[:, 3]]
122
- e1, e2, e3 = p1 - p0, p2 - p0, p3 - p0
123
- return np.abs(np.einsum('ij,ij->i', e1, np.cross(e2, e3))) / 6.0
124
-
125
-
126
- def _induced_components(n_nodes: int, tets: np.ndarray, mask: np.ndarray):
127
- """Connected components of the tet-adjacency graph restricted to `mask`.
128
-
129
- Returns (n_comp, labels) with labels of shape (n_nodes,): the component
130
- id for masked nodes, -1 elsewhere."""
131
- idx = np.flatnonzero(mask)
132
- labels_full = np.full(n_nodes, -1, dtype=np.int64)
133
- if idx.size == 0:
134
- return 0, labels_full
135
-
136
- local_of = -np.ones(n_nodes, dtype=np.int64)
137
- local_of[idx] = np.arange(idx.size)
138
-
139
- rows_list, cols_list = [], []
140
- for a, b in _TET_EDGE_PAIRS:
141
- va, vb = tets[:, a], tets[:, b]
142
- both = mask[va] & mask[vb]
143
- if both.any():
144
- rows_list.append(local_of[va[both]])
145
- cols_list.append(local_of[vb[both]])
146
- n_local = idx.size
147
- if rows_list:
148
- rows = np.concatenate(rows_list)
149
- cols = np.concatenate(cols_list)
150
- data = np.ones(rows.shape[0])
151
- graph = csr_matrix((data, (rows, cols)), shape=(n_local, n_local))
152
- else:
153
- graph = csr_matrix((n_local, n_local))
154
- n_comp, labels_local = connected_components(graph, directed=False)
155
- labels_full[idx] = labels_local
156
- return n_comp, labels_full
157
-
158
-
159
- def _boundary_faces(tets: np.ndarray) -> np.ndarray:
160
- """(F, 3) vertex triples of the mesh's outer faces: faces that belong to
161
- exactly one tet, in their original per-tet vertex order."""
162
- tets = np.asarray(tets, dtype=np.int64)
163
- if tets.shape[0] == 0:
164
- return np.zeros((0, 3), dtype=np.int64)
165
- face_idx = np.asarray(_TET_FACES, dtype=np.int64) # (4, 3)
166
- all_faces = tets[:, face_idx].reshape(-1, 3) # (4*M, 3), original order
167
- sorted_faces = np.sort(all_faces, axis=1)
168
- _, first_idx, counts = np.unique(sorted_faces, axis=0, return_index=True,
169
- return_counts=True)
170
- boundary = counts == 1
171
- return all_faces[first_idx[boundary]]
172
-
173
-
174
- def _region_surface_area(pos: np.ndarray, tets: np.ndarray, nodes: np.ndarray,
175
- t_s: np.ndarray, threshold: float,
176
- boundary_faces: np.ndarray = None) -> float:
177
- """Surface area (mm^2) of a hot region, for its V/A modulus.
178
-
179
- The interior part is the iso-surface `t_s == threshold` (the cut that
180
- selected the region), built by marching tetrahedra on the continuous
181
- field: a tet with 1 or 3 vertices above the threshold contributes a
182
- triangle, one with 2 contributes a planar quadrilateral, and crossing
183
- points sit at their interpolated position on each edge. A tet counts for
184
- this region if any of its vertices is in `nodes`. Outer faces of the
185
- mesh are added separately, weighted by the fraction of their 3 vertices
186
- in the region. `boundary_faces` can be passed in to avoid recomputing
187
- `_boundary_faces(tets)` for every region."""
188
- n_nodes = pos.shape[0]
189
- is_member = np.zeros(n_nodes, dtype=bool)
190
- is_member[np.asarray(nodes, dtype=np.int64)] = True
191
- t_s = np.asarray(t_s, dtype=np.float64)
192
- threshold = float(threshold)
193
-
194
- area = 0.0
195
- if tets.shape[0] > 0:
196
- hot_mask = t_s >= threshold
197
- member_per_tet = hot_mask[tets]
198
- n_above = member_per_tet.sum(axis=1)
199
- mixed = np.flatnonzero((n_above >= 1) & (n_above <= 3))
200
- for ti in mixed:
201
- tet = tets[ti]
202
- if not is_member[tet].any():
203
- continue # this crossing belongs to a different region
204
- verts = pos[tet]
205
- vals = t_s[tet]
206
- above_local = member_per_tet[ti]
207
- k = int(n_above[ti])
208
- if k in (1, 3):
209
- odd = int(np.flatnonzero(above_local)[0]) if k == 1 else \
210
- int(np.flatnonzero(~above_local)[0])
211
- others = [i for i in range(4) if i != odd]
212
- pts = []
213
- for o in others:
214
- frac = (threshold - vals[odd]) / (vals[o] - vals[odd])
215
- pts.append(verts[odd] + frac * (verts[o] - verts[odd]))
216
- area += 0.5 * float(np.linalg.norm(np.cross(pts[1] - pts[0], pts[2] - pts[0])))
217
- else: # k == 2
218
- hi = np.flatnonzero(above_local)
219
- lo = np.flatnonzero(~above_local)
220
-
221
- def _cross_point(h, c, verts=verts, vals=vals):
222
- frac = (threshold - vals[h]) / (vals[c] - vals[h])
223
- return verts[h] + frac * (verts[c] - verts[h])
224
-
225
- a_pt = _cross_point(hi[0], lo[0])
226
- b_pt = _cross_point(hi[0], lo[1])
227
- c_pt = _cross_point(hi[1], lo[1])
228
- d_pt = _cross_point(hi[1], lo[0])
229
- area += 0.5 * float(np.linalg.norm(np.cross(c_pt - a_pt, d_pt - b_pt)))
230
-
231
- if boundary_faces is None:
232
- boundary_faces = _boundary_faces(tets)
233
- if boundary_faces.shape[0] > 0:
234
- # Each outer face counts with the fraction of its 3 vertices in
235
- # the region.
236
- member_counts = is_member[boundary_faces].sum(axis=1).astype(np.float64) # (F,)
237
- frac = member_counts / 3.0
238
- nonzero = frac > 0
239
- if nonzero.any():
240
- v = boundary_faces[nonzero]
241
- p0f, p1f, p2f = pos[v[:, 0]], pos[v[:, 1]], pos[v[:, 2]]
242
- tri_areas = 0.5 * np.linalg.norm(np.cross(p1f - p0f, p2f - p0f), axis=1)
243
- area += float(np.sum(frac[nonzero] * tri_areas))
244
- return area
245
-
246
-
247
- def hot_regions(pos: np.ndarray, tets: np.ndarray, t_s: np.ndarray,
248
- top_frac: float = 0.10) -> list:
249
- """Connected groups (via tet adjacency) of the top-`top_frac` latest-
250
- solidifying nodes, sorted by `t_max` descending.
251
-
252
- Each region is a dict: `nodes` (sorted indices), `centroid` (mm),
253
- `volume_mm3`, `t_max`, `region_id` (its index in this list),
254
- `hot_threshold` (the percentile cut used) and `sub_resolution` (fewer
255
- than 4 nodes, too small for a meaningful V/A modulus). The volume sums,
256
- over all tets touching the region, tet volume times the fraction of its
257
- vertices that are hot, which converges with mesh refinement."""
258
- top_frac = float(top_frac)
259
- if not (0.0 < top_frac <= 1.0):
260
- raise ValueError(f"hot_regions: top_frac must be in (0, 1], got {top_frac!r}")
261
-
262
- pos = np.asarray(pos, dtype=np.float64)
263
- tets = np.asarray(tets, dtype=np.int64)
264
- t_s = np.asarray(t_s, dtype=np.float64)
265
- n_nodes = pos.shape[0]
266
-
267
- if n_nodes == 0 or tets.shape[0] == 0:
268
- return []
269
-
270
- threshold = np.percentile(t_s, 100.0 * (1.0 - top_frac))
271
- hot_mask = t_s >= threshold
272
- if not hot_mask.any():
273
- return []
274
-
275
- n_comp, labels = _induced_components(n_nodes, tets, hot_mask)
276
-
277
- vol = _tet_volumes(pos, tets)
278
- n_hot_per_tet = hot_mask[tets].sum(axis=1)
279
- has_hot = n_hot_per_tet > 0
280
- region_vol = np.zeros(n_comp)
281
- if has_hot.any():
282
- # any one hot vertex identifies the tet's (unique) component.
283
- first_hot_col = np.argmax(hot_mask[tets], axis=1)
284
- first_hot_node = tets[np.arange(tets.shape[0]), first_hot_col]
285
- comp_of_tet = labels[first_hot_node]
286
- weight = vol * (n_hot_per_tet / 4.0)
287
- np.add.at(region_vol, comp_of_tet[has_hot], weight[has_hot])
288
-
289
- regions = []
290
- for c in range(n_comp):
291
- nodes = np.sort(np.flatnonzero(labels == c))
292
- regions.append({
293
- "nodes": nodes,
294
- "centroid": pos[nodes].mean(axis=0),
295
- "volume_mm3": float(region_vol[c]),
296
- "t_max": float(t_s[nodes].max()),
297
- })
298
- regions.sort(key=lambda r: r["t_max"], reverse=True)
299
- for i, r in enumerate(regions):
300
- r["region_id"] = i
301
- r["hot_threshold"] = float(threshold)
302
- # Below 4 nodes the iso-surface area and the lumped volume no longer
303
- # agree, so the V/A modulus is not meaningful.
304
- r["sub_resolution"] = len(r["nodes"]) < 4
305
- return regions
306
-
307
-
308
- def is_fed(region: dict, t_s: np.ndarray, tets: np.ndarray,
309
- feed_nodes: np.ndarray, corridor_frac: float = 0.95) -> bool:
310
- """Whether a feed source can still reach the region through liquid metal.
311
-
312
- True iff some region node and some `feed_nodes` node are connected
313
- through nodes with `t_s >= corridor_frac * region["t_max"]` (a corridor
314
- that stays liquid until the region itself is nearly solid). Feed nodes
315
- are adiabatic-tagged surface nodes, for example a riser face. With no
316
- feed nodes every region is unfed, which is the conservative answer. A
317
- region with t_max <= 0 is reported unfed."""
318
- t_s = np.asarray(t_s, dtype=np.float64)
319
- tets = np.asarray(tets, dtype=np.int64)
320
- feed_nodes = np.asarray(feed_nodes, dtype=np.int64)
321
- region_nodes = np.asarray(region["nodes"], dtype=np.int64)
322
-
323
- if feed_nodes.size == 0:
324
- return False
325
- if tets.shape[0] == 0:
326
- return False
327
- region_t_max = float(region["t_max"])
328
- if region_t_max <= 0:
329
- logger.debug(
330
- "is_fed: region t_max=%.6g <= 0 -- corridor threshold would be "
331
- "vacuous (every non-negative t_s qualifies); reporting unfed.",
332
- region_t_max)
333
- return False
334
-
335
- n_nodes = t_s.shape[0]
336
- threshold = corridor_frac * region_t_max
337
- warm_mask = t_s >= threshold
338
-
339
- _, labels = _induced_components(n_nodes, tets, warm_mask)
340
-
341
- region_labels = set(int(l) for l in labels[region_nodes] if l >= 0)
342
- if not region_labels:
343
- return False
344
- feed_labels = set(int(l) for l in labels[feed_nodes] if l >= 0)
345
- return len(region_labels & feed_labels) > 0
346
-
347
-
348
- def macro_shrinkage(pos: np.ndarray, tets: np.ndarray, t_s: np.ndarray,
349
- feed_nodes: np.ndarray, shrinkage_pct: float) -> list:
350
- """The hot regions that are not fed, each with `severity = shrinkage_pct /
351
- 100 * volume_mm3`. `region_id` keeps its value from `hot_regions`."""
352
- regions = hot_regions(pos, tets, t_s)
353
- out = []
354
- for r in regions:
355
- if is_fed(r, t_s, tets, feed_nodes):
356
- continue
357
- severity = shrinkage_pct / 100.0 * r["volume_mm3"]
358
- out.append({**r, "severity": severity})
359
- return out
360
-
361
-
362
- def top_sinks(regions: list, pos: np.ndarray, surface_nodes: np.ndarray,
363
- gravity_vec) -> list:
364
- """Regions whose highest node along -gravity is a surface node. Returns
365
- `{"region_id", "location" (mm), "volume_mm3"}` for each."""
366
- pos = np.asarray(pos, dtype=np.float64)
367
- gravity_vec = np.asarray(gravity_vec, dtype=np.float64)
368
- up = -gravity_vec
369
- norm = np.linalg.norm(up)
370
- if norm > 0:
371
- up = up / norm
372
- surface_set = set(np.asarray(surface_nodes, dtype=np.int64).tolist())
373
-
374
- sinks = []
375
- for r in regions:
376
- nodes = np.asarray(r["nodes"], dtype=np.int64)
377
- proj = pos[nodes] @ up
378
- top_node = int(nodes[np.argmax(proj)])
379
- if top_node in surface_set:
380
- sinks.append({
381
- "region_id": r["region_id"],
382
- "location": pos[top_node].copy(),
383
- "volume_mm3": r["volume_mm3"],
384
- })
385
- return sinks
386
-
387
-
388
- def feeder_recommendations(regions: list, pos: np.ndarray, tets: np.ndarray,
389
- surface_nodes: np.ndarray, gravity_vec, t_s: np.ndarray) -> list:
390
- """Per region: a feeder `location` and `min_modulus_mm = 1.2 * V/A`.
391
-
392
- The location is the surface node closest to the vertical line (along
393
- -gravity) through the region's centroid, among surface nodes at or above
394
- the centroid (all surface nodes if none are). Sub-resolution regions are
395
- skipped. A region with zero volume or area gets a warning and
396
- `min_modulus_mm = 0.0`. Raises ValueError if `surface_nodes` is empty."""
397
- pos = np.asarray(pos, dtype=np.float64)
398
- tets = np.asarray(tets, dtype=np.int64)
399
- t_s = np.asarray(t_s, dtype=np.float64)
400
- gravity_vec = np.asarray(gravity_vec, dtype=np.float64)
401
- up = -gravity_vec
402
- norm = np.linalg.norm(up)
403
- if norm > 0:
404
- up = up / norm
405
- surface_nodes = np.asarray(surface_nodes, dtype=np.int64)
406
- if surface_nodes.size == 0:
407
- raise ValueError(
408
- "feeder_recommendations: surface_nodes is empty -- no candidate "
409
- "feeder location exists (a mesh with no free surface is not a "
410
- "valid casting)")
411
- surface_pos = pos[surface_nodes]
412
- boundary_faces = _boundary_faces(tets) # shared by every region
413
-
414
- recs = []
415
- n_skipped_sub_resolution = 0
416
- for r in regions:
417
- if r.get("sub_resolution", False):
418
- n_skipped_sub_resolution += 1
419
- continue
420
- nodes = np.asarray(r["nodes"], dtype=np.int64)
421
- volume = r["volume_mm3"]
422
- threshold = r["hot_threshold"]
423
- area = _region_surface_area(pos, tets, nodes, t_s, threshold,
424
- boundary_faces=boundary_faces)
425
- if area > 0 and volume > 0:
426
- region_modulus = volume / area
427
- else:
428
- logger.warning(
429
- "feeder_recommendations: region_id=%s has degenerate "
430
- "volume/area (V=%.6g mm^3, A=%.6g mm^2) -- min_modulus_mm is "
431
- "not meaningful and is reported as 0.0",
432
- r.get("region_id"), volume, area)
433
- region_modulus = 0.0
434
-
435
- centroid = np.asarray(r["centroid"], dtype=np.float64)
436
- rel = surface_pos - centroid
437
- axis_comp = rel @ up
438
- perp = rel - np.outer(axis_comp, up)
439
- perp_dist = np.linalg.norm(perp, axis=1)
440
-
441
- above = np.flatnonzero(axis_comp >= 0)
442
- candidates = above if above.size > 0 else np.arange(surface_pos.shape[0])
443
- best = candidates[np.argmin(perp_dist[candidates])]
444
-
445
- recs.append({
446
- "location": surface_pos[best].copy(),
447
- "min_modulus_mm": 1.2 * region_modulus,
448
- "region_id": r["region_id"],
449
- })
450
- if n_skipped_sub_resolution:
451
- logger.info(
452
- "feeder_recommendations: skipped %d sub-resolution region(s) (<4 "
453
- "nodes) -- V/A modulus is not meaningful at this resolution",
454
- n_skipped_sub_resolution)
455
- return recs
456
-
457
-
458
- def screen_casting(pos: np.ndarray, tets: np.ndarray, surface_nodes: np.ndarray,
459
- t_s: np.ndarray, TL: float, TS: float, alloy_family: str,
460
- gravity_vec=(0, 0, -1), feed_nodes: np.ndarray = None) -> dict:
461
- """All four screening outputs for one part.
462
-
463
- `alloy_family` must be a key of `SHRINKAGE_PCT`. `surface_nodes` are all
464
- surface nodes (for sinks and feeder placement); `feed_nodes` are the
465
- nodes that can feed a region (None means none).
466
-
467
- Returns {"niyama", "porosity_risk", "niyama_source": "proxy",
468
- "macro_shrinkage", "top_sinks", "feeders", "material"}."""
469
- if alloy_family not in SHRINKAGE_PCT:
470
- raise KeyError(
471
- f"screen_casting: unknown alloy_family {alloy_family!r} -- known "
472
- f"families: {sorted(SHRINKAGE_PCT)}"
473
- )
474
-
475
- pos = np.asarray(pos, dtype=np.float64)
476
- tets = np.asarray(tets, dtype=np.int64)
477
- surface_nodes = np.asarray(surface_nodes, dtype=np.int64)
478
- t_s = np.asarray(t_s, dtype=np.float64)
479
- feed_nodes_arr = (np.zeros(0, dtype=np.int64) if feed_nodes is None
480
- else np.asarray(feed_nodes, dtype=np.int64))
481
-
482
- ny = niyama_proxy(pos, tets, t_s, TL, TS)
483
- risk = porosity_risk(ny)
484
-
485
- shrinkage_pct = SHRINKAGE_PCT[alloy_family]
486
- macro = macro_shrinkage(pos, tets, t_s, feed_nodes_arr, shrinkage_pct)
487
- sinks = top_sinks(macro, pos, surface_nodes, gravity_vec)
488
- feeders = feeder_recommendations(macro, pos, tets, surface_nodes, gravity_vec, t_s)
489
-
490
- return {
491
- "niyama": ny,
492
- "porosity_risk": risk,
493
- "niyama_source": "proxy",
494
- "macro_shrinkage": macro,
495
- "top_sinks": sinks,
496
- "feeders": feeders,
497
- "material": {"alloy_family": alloy_family, "shrinkage_pct": shrinkage_pct},
498
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/viz.py DELETED
@@ -1,90 +0,0 @@
1
- """PyVista helpers for the solidification viewer. Pure/testable: load a
2
- prediction VTU and derive the ghost mesh, the still-liquid region above a time
3
- threshold, and the hot-spot points."""
4
- import os
5
-
6
- import numpy as np
7
- import pyvista as pv
8
-
9
-
10
- def load_prediction(vtu_path: str) -> pv.UnstructuredGrid:
11
- grid = pv.read(vtu_path)
12
- for name in ("solidification_time", "hotspot"):
13
- if name not in grid.point_data:
14
- raise ValueError(f"VTU missing point array '{name}'")
15
- return grid
16
-
17
-
18
- def time_range(grid):
19
- t = np.asarray(grid.point_data["solidification_time"])
20
- return float(t.min()), float(t.max())
21
-
22
-
23
- def liquid_region(grid, tau: float):
24
- # cells still liquid at time tau (solidification_time >= tau)
25
- return grid.threshold(tau, scalars="solidification_time")
26
-
27
-
28
- def hotspot_points(grid):
29
- mask = np.asarray(grid.point_data["hotspot"]) > 0.5
30
- return pv.PolyData(np.asarray(grid.points)[mask])
31
-
32
-
33
- def points_above_time(grid, t: float) -> pv.PolyData:
34
- """Points whose solidification_time is >= t. Used to thin out the hot-spot
35
- cloud with a user-controlled cutoff/threshold slider."""
36
- times = np.asarray(grid.point_data["solidification_time"])
37
- mask = times >= t
38
- pts = pv.PolyData(np.asarray(grid.points)[mask])
39
- pts.point_data["solidification_time"] = times[mask]
40
- return pts
41
-
42
-
43
- def solidification_animation(grid, out_path, *, n_frames=40, fps=10,
44
- cmap="turbo_r", ghost_opacity=0.15,
45
- scalar_bar_args=None, bg="#f7f7f5",
46
- window_size=(1280, 720), camera_position=None):
47
- """Render an animated GIF of progressive solidification: tau sweeps from
48
- tmin to tmax; already-solidified material (t < tau) shows as a low-opacity
49
- ghost of the full body, still-liquid material (t >= tau) is opaque and
50
- colored by solidification time. Each frame shows the color legend and the
51
- current time. Returns out_path. Off-screen; independent of any live view,
52
- except that when `camera_position` is given (e.g. captured from a live
53
- plotter) it is used verbatim so the GIF renders from that exact viewpoint;
54
- otherwise the camera is auto-framed via reset_camera()."""
55
- import pyvista as pv
56
- tmin, tmax = time_range(grid)
57
- taus = np.linspace(tmin, tmax, int(n_frames))
58
- p = pv.Plotter(off_screen=True, window_size=list(window_size))
59
- p.set_background(bg)
60
- try:
61
- # permanent ghost of the full body (owns the one legend)
62
- p.add_mesh(grid, scalars="solidification_time", opacity=ghost_opacity,
63
- cmap=cmap, clim=[tmin, tmax], smooth_shading=True,
64
- show_scalar_bar=True, scalar_bar_args=dict(scalar_bar_args or {}))
65
- p.add_mesh(liquid_region(grid, tmin), scalars="solidification_time",
66
- cmap=cmap, clim=[tmin, tmax], smooth_shading=True,
67
- name="liquid", show_scalar_bar=False)
68
- if camera_position is not None:
69
- p.camera_position = camera_position
70
- else:
71
- p.reset_camera()
72
- p.open_gif(out_path, fps=int(fps))
73
- for tau in taus:
74
- liq = liquid_region(grid, float(tau))
75
- if liq.n_cells > 0:
76
- p.add_mesh(liq, scalars="solidification_time", cmap=cmap,
77
- clim=[tmin, tmax], smooth_shading=True,
78
- name="liquid", show_scalar_bar=False)
79
- else:
80
- p.remove_actor("liquid") # fully solidified -> only the ghost
81
- p.add_text(f"t = {float(tau):6.1f} s", name="tlabel",
82
- position="upper_left", font_size=14, color="black")
83
- p.write_frame()
84
- except Exception:
85
- if os.path.exists(out_path):
86
- os.unlink(out_path) # don't leave a truncated/corrupt gif behind
87
- raise
88
- finally:
89
- p.close()
90
- return out_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/webapp.py DELETED
@@ -1,561 +0,0 @@
1
- """Local trame + PyVista web app: upload a STEP casting, run the prediction,
2
- and view the solidification field with a time slider (solidified =
3
- ghost, liquid = opaque) and a hot-spot toggle. Run: python -m src.webapp
4
-
5
- A multi-solid STEP is meshed through the same prep pipeline as the CLI, which
6
- keeps the largest solid as the casting."""
7
- import os
8
- import os.path as osp
9
-
10
- import numpy as np
11
- import pyvista as pv
12
- from trame.app import get_server
13
- from trame.ui.vuetify3 import SinglePageWithDrawerLayout
14
- from trame.widgets import html, vuetify3
15
- from pyvista.trame.ui import plotter_ui
16
-
17
- from src import viz
18
- from src.inference_props import DEFAULT_ALLOY, list_alloys, list_molds
19
- from src.predict_casting import predict_casting
20
-
21
- DEFAULT_MOLD = "green_sand"
22
-
23
- pv.OFF_SCREEN = True
24
-
25
- GHOST_OPACITY = 0.15
26
- DEFAULT_HOTSPOT_SIZE = 12.0
27
- HOTSPOT_CUTOFF_PERCENTILE = 90.0
28
-
29
- # --- visual identity -------------------------------------------------------
30
- # "Neuralcast" = a neural-network surrogate for a foundry casting process, so
31
- # the palette stays in the same molten-metal family as before but is rebuilt
32
- # for a light, legible workbench: warm parchment chrome, white control
33
- # surfaces, and a near-white VTK stage so the inferno field is what draws the
34
- # eye. The one recurring accent is a deeper burnt-orange (readable at text
35
- # contrast on white, unlike the original pale version). Wired into vuetify's
36
- # theme system so every stock control (slider, checkbox, buttons) inherits it.
37
- # The app bar is a deliberate exception: a dark charcoal strip (independent of
38
- # the light theme) so the header reads as instrument-panel chrome holding just
39
- # the title and a status line, not another content surface.
40
- BG_APP = "#f4f2ee" # app chrome background (warm parchment)
41
- SURFACE = "#ffffff" # drawer / card surfaces
42
- BORDER = "#ddd8cf" # hairline dividers
43
- VTK_BG = "#f7f7f5" # 3D viewport background -- near-white so the
44
- # colored field is the highest-contrast thing on screen
45
- ACCENT_MOLTEN = "#c1440e" # burnt-orange -- the one recurring accent (readable on white)
46
- TEXT_PRIMARY = "#23262b"
47
- TEXT_MUTED = "#6b7078"
48
- HEADER_BG = "#1c1a17" # dark charcoal app-bar -- deliberately dark in the light theme
49
- HEADER_TEXT = "#f4f2ee"
50
- HEADER_TEXT_MUTED = "#b6afa1"
51
- FIELD_CMAP = "turbo_r" # reversed turbo (red -> blue): wide, high-contrast gradient
52
- # with far more distinguishable steps than a single-hue map,
53
- # so small time differences across the field stay legible
54
- HOTSPOT_COLOR = "#0092b8" # deep cyan/teal marker: falls in the middle of turbo's
55
- # range but is rendered as small spheres (not a field
56
- # color), so it still reads as an overlay/alert
57
-
58
- _MONO_STACK = ('"JetBrains Mono", ui-monospace, "SFMono-Regular", '
59
- "Menlo, Consolas, monospace")
60
- _COND_STACK = '"Roboto Condensed", "Arial Narrow", sans-serif'
61
-
62
- # Scalar bar (legend) for the solidification-time color field: a vertical bar
63
- # pinned to the right edge of the viewport, with generous title/label padding
64
- # so the title never collides with the tick numbers, and integer tick labels
65
- # (fractional seconds add no information at casting scale).
66
- SCALAR_BAR_ARGS = dict(
67
- title="Solidification Time, s",
68
- fmt="%.0f",
69
- color="black",
70
- bold=True,
71
- font_family="arial",
72
- vertical=True,
73
- position_x=0.91,
74
- position_y=0.06,
75
- width=0.055,
76
- height=0.80,
77
- title_font_size=20,
78
- label_font_size=16,
79
- n_labels=6,
80
- )
81
-
82
- _CUSTOM_CSS = f"""
83
- .neuralcast-title {{
84
- display: flex;
85
- align-items: center;
86
- gap: 10px;
87
- }}
88
- .neuralcast-title-text {{
89
- font-family: {_COND_STACK};
90
- font-weight: 700;
91
- letter-spacing: .04em;
92
- text-transform: uppercase;
93
- font-size: 1.05rem;
94
- color: {HEADER_TEXT};
95
- }}
96
- .neuralcast-status {{
97
- font-family: {_COND_STACK};
98
- letter-spacing: .08em;
99
- text-transform: uppercase;
100
- font-size: .7rem;
101
- color: {HEADER_TEXT_MUTED};
102
- white-space: nowrap;
103
- }}
104
- .neuralcast-drawer-content {{
105
- overflow-y: auto;
106
- }}
107
- .neuralcast-section-label {{
108
- font-family: {_COND_STACK};
109
- letter-spacing: .12em;
110
- text-transform: uppercase;
111
- font-size: .7rem;
112
- color: {TEXT_MUTED};
113
- margin-bottom: 10px;
114
- flex: none;
115
- }}
116
- .neuralcast-section {{
117
- margin-bottom: 4px;
118
- }}
119
- .neuralcast-section + .neuralcast-section {{
120
- border-top: 1px solid {BORDER};
121
- padding-top: 20px;
122
- margin-top: 20px;
123
- }}
124
- .neuralcast-tau-badge {{
125
- display: inline-block;
126
- font-family: {_MONO_STACK};
127
- font-size: .75rem;
128
- color: {ACCENT_MOLTEN};
129
- background: {BG_APP};
130
- border: 1px solid {BORDER};
131
- border-radius: 4px;
132
- padding: 3px 10px;
133
- white-space: nowrap;
134
- }}
135
- .neuralcast-summary-box {{
136
- min-height: 0;
137
- }}
138
- .neuralcast-summary-box .v-input {{
139
- flex: 1 1 auto;
140
- min-height: 0;
141
- }}
142
- .neuralcast-summary-box .v-field__input,
143
- .neuralcast-summary-box textarea {{
144
- font-family: {_MONO_STACK} !important;
145
- font-size: .78rem;
146
- line-height: 1.5;
147
- color: {TEXT_PRIMARY};
148
- }}
149
- .neuralcast-footer-text {{
150
- width: 100%;
151
- text-align: center;
152
- font-family: {_COND_STACK};
153
- letter-spacing: .06em;
154
- font-size: .72rem;
155
- color: {TEXT_MUTED};
156
- }}
157
- """
158
-
159
-
160
- def summary_text(result: dict, alloy: str = None, mold: str = None) -> str:
161
- lines = [f"casting: {result['name']}",
162
- f"total solidification time: {result['total_time_s']:.1f} s",
163
- f"nodes: {result['n_nodes']}"]
164
- if alloy is not None or mold is not None:
165
- cond_parts = []
166
- if alloy is not None:
167
- cond_parts.append(f"alloy: {alloy}")
168
- if mold is not None:
169
- cond_parts.append(f"mold: {mold}")
170
- lines.append(" " + ", ".join(cond_parts))
171
- lines.append("top hot spots (x,y,z mm):")
172
- for xyz in result["hotspot_xyz"]:
173
- lines.append(f" ({xyz[0]:.1f}, {xyz[1]:.1f}, {xyz[2]:.1f})")
174
- if result.get("ood_warnings"):
175
- lines.append("WARNINGS:")
176
- lines += [f" - {w}" for w in result["ood_warnings"]]
177
- return "\n".join(lines)
178
-
179
-
180
- INITIAL_SUMMARY = "(upload a STEP file)"
181
-
182
-
183
- def _run_prediction(step_path, out_dir, alloy, mold):
184
- """Thin wrapper around `predict_casting` forwarding alloy/mold conditioning.
185
-
186
- Extracted so the upload handler's predict call is unit-testable without
187
- driving the full trame upload flow (module-level lookup of
188
- `predict_casting` so tests can monkeypatch `src.webapp.predict_casting`).
189
- """
190
- return predict_casting(step_path, out_dir=out_dir, alloy=alloy, mold=mold)
191
-
192
-
193
- def _rebuild_hotspots(app):
194
- """(Re)build the hot-spot point actor from the current cutoff/size state.
195
- Called on load and whenever the size or cutoff slider moves."""
196
- plotter, server = app["plotter"], app["server"]
197
- state, ctrl = server.state, server.controller
198
- if app["grid"] is None:
199
- return
200
- pts = viz.points_above_time(app["grid"], float(state.hotspot_cutoff))
201
- actor = plotter.add_mesh(pts, color=HOTSPOT_COLOR, point_size=float(state.hotspot_size),
202
- name="hotspots", render_points_as_spheres=True)
203
- actor.SetVisibility(bool(state.show_hotspots))
204
- app["hotspot_actor"] = actor
205
- ctrl.view_update()
206
-
207
-
208
- def _remove_scalar_bar(plotter):
209
- """Drop any existing scalar bar(s), regardless of how many are present.
210
- Guarded because pyvista raises if none exist (or if a title is required
211
- with more than one) -- callers just want a clean slate either way."""
212
- try:
213
- plotter.remove_scalar_bar()
214
- except Exception:
215
- pass
216
- # Belt-and-suspenders: clear() takes the whole registry in one shot, in
217
- # case remove_scalar_bar() above only got one of several.
218
- try:
219
- plotter.scalar_bars.clear()
220
- except Exception:
221
- pass
222
-
223
-
224
- def _process_upload(app, step_path, alloy, mold):
225
- """Core upload logic, extracted from the `uploaded_file` state-change
226
- handler so it is testable without a browser/file-upload round trip:
227
- run the prediction and render it, keeping the UI alive on failure."""
228
- server = app["server"]
229
- state = server.state
230
- plotter = app["plotter"]
231
- out_dir = "runs/castings"
232
- try:
233
- result = _run_prediction(step_path, out_dir, alloy, mold)
234
- grid = viz.load_prediction(result["vtu"])
235
- app["name"] = result["name"]
236
- render_prediction(app, grid, summary_text(result, alloy=alloy, mold=mold))
237
- except Exception as e: # keep the UI alive on bad/unmeshable STEP
238
- plotter.clear_actors()
239
- _remove_scalar_bar(plotter)
240
- app["grid"] = None
241
- app["hotspot_actor"] = None
242
- state.loaded = False
243
- state.summary = f"Prediction failed for {osp.basename(step_path)}:\n{e}"
244
-
245
-
246
- def render_prediction(app, grid, summary):
247
- plotter, server = app["plotter"], app["server"]
248
- state, ctrl = server.state, server.controller
249
- plotter.clear_actors()
250
- _remove_scalar_bar(plotter)
251
- tmin, tmax = viz.time_range(grid)
252
- app["grid"] = grid
253
- # The "ghost" actor is the single, permanent owner of the scalar bar/legend:
254
- # it is added once here and never touched again by the tau slider, so the
255
- # legend persists across playback without being re-added or dropped. The
256
- # "liquid" actor (re-added on every tau change) must NEVER own a scalar bar,
257
- # or scrubbing the slider would repeatedly add/replace it.
258
- plotter.add_mesh(grid, scalars="solidification_time", opacity=GHOST_OPACITY,
259
- cmap=FIELD_CMAP, name="ghost", clim=[tmin, tmax],
260
- smooth_shading=True, show_scalar_bar=True,
261
- scalar_bar_args=SCALAR_BAR_ARGS)
262
- plotter.add_mesh(viz.liquid_region(grid, tmin), scalars="solidification_time",
263
- cmap=FIELD_CMAP, name="liquid", clim=[tmin, tmax],
264
- smooth_shading=True, show_scalar_bar=False)
265
- state.tmin, state.tmax, state.tau = tmin, tmax, tmin
266
- times = np.asarray(grid.point_data["solidification_time"])
267
- state.hotspot_cutoff = float(np.percentile(times, HOTSPOT_CUTOFF_PERCENTILE))
268
- _rebuild_hotspots(app)
269
- state.anim_ready = False
270
- state.anim_uri = ""
271
- state.summary, state.loaded = summary, True
272
- plotter.reset_camera()
273
- ctrl.view_update()
274
-
275
-
276
- def build_app(server=None):
277
- if server is None:
278
- server = get_server(client_type="vue3")
279
- state, ctrl = server.state, server.controller
280
- plotter = pv.Plotter()
281
- plotter.set_background(VTK_BG)
282
- app = {"server": server, "plotter": plotter, "grid": None, "hotspot_actor": None,
283
- "name": "casting"}
284
- server.app = app # exposes the app dict for tests / headless callers that
285
- # need render_prediction()/clear_casting() without the UI
286
-
287
- state.trame__title = "Neuralcast Viewer"
288
-
289
- # Custom light vuetify theme (molten-metal accent) applied through
290
- # Vuetify's own theme system, so every stock control (slider, checkbox,
291
- # buttons) picks up the palette automatically instead of one-off color
292
- # props.
293
- vuetify_config = {
294
- "theme": {
295
- "defaultTheme": "neuralcastLight",
296
- "themes": {
297
- "neuralcastLight": {
298
- "dark": False,
299
- "colors": {
300
- "background": BG_APP,
301
- "surface": SURFACE,
302
- "primary": ACCENT_MOLTEN,
303
- "secondary": TEXT_MUTED,
304
- "on-background": TEXT_PRIMARY,
305
- "on-surface": TEXT_PRIMARY,
306
- },
307
- },
308
- },
309
- },
310
- }
311
- for k, v in dict(tau=0.0, tmin=0.0, tmax=1.0, show_hotspots=False,
312
- summary=INITIAL_SUMMARY, loaded=False, uploaded_file=None,
313
- loading=False, hotspot_size=DEFAULT_HOTSPOT_SIZE,
314
- hotspot_cutoff=0.0, animating=False, anim_ready=False,
315
- anim_uri="", anim_name="solidification.gif",
316
- alloy=DEFAULT_ALLOY, mold=DEFAULT_MOLD,
317
- alloy_options=list_alloys(), mold_options=list_molds(),
318
- ).items():
319
- state.setdefault(k, v)
320
-
321
- @state.change("tau")
322
- def _on_tau(tau, **kwargs):
323
- if app["grid"] is None:
324
- return
325
- # show_scalar_bar=False: the "ghost" actor owns the one legend (see
326
- # render_prediction); re-adding it here would duplicate/replace it on
327
- # every slider tick.
328
- liq = viz.liquid_region(app["grid"], tau)
329
- if liq.n_cells > 0:
330
- plotter.add_mesh(liq, scalars="solidification_time",
331
- cmap=FIELD_CMAP, name="liquid", smooth_shading=True,
332
- clim=[state.tmin, state.tmax], show_scalar_bar=False)
333
- else:
334
- plotter.remove_actor("liquid")
335
- ctrl.view_update()
336
-
337
- @state.change("show_hotspots")
338
- def _on_hot(show_hotspots, **kwargs):
339
- if app["hotspot_actor"] is not None:
340
- app["hotspot_actor"].SetVisibility(bool(show_hotspots))
341
- ctrl.view_update()
342
-
343
- @state.change("hotspot_cutoff", "hotspot_size")
344
- def _on_hotspot_controls(**kwargs):
345
- _rebuild_hotspots(app)
346
-
347
- @state.change("uploaded_file")
348
- def _on_upload(uploaded_file, **kwargs):
349
- if not uploaded_file:
350
- return
351
- f = uploaded_file[0] if isinstance(uploaded_file, list) else uploaded_file
352
- out_dir = "runs/castings"
353
- os.makedirs(out_dir, exist_ok=True)
354
- step_path = osp.join(out_dir, f.get("name", "part.step"))
355
- with open(step_path, "wb") as fh:
356
- fh.write(f["content"])
357
- state.loading = True
358
- state.flush()
359
- try:
360
- _process_upload(app, step_path, state.alloy, state.mold)
361
- finally:
362
- state.loading = False
363
- ctrl.view_update()
364
-
365
- def clear_casting():
366
- """Drop the loaded casting and return to a ready-for-upload state."""
367
- plotter.clear_actors()
368
- _remove_scalar_bar(plotter)
369
- app["grid"] = None
370
- app["hotspot_actor"] = None
371
- state.loaded = False
372
- state.summary = INITIAL_SUMMARY
373
- state.uploaded_file = None
374
- state.tau, state.tmin, state.tmax = 0.0, 0.0, 1.0
375
- state.show_hotspots = False
376
- state.anim_ready = False
377
- state.anim_uri = ""
378
- state.animating = False
379
- ctrl.view_update()
380
-
381
- # Exposed on the controller so tests (and any future non-UI caller) can
382
- # invoke the same clear logic the "Clear" button uses.
383
- ctrl.clear_casting = clear_casting
384
-
385
- def generate_animation():
386
- """Render the solidification GIF for the loaded casting and expose it
387
- to the browser as a base64 data URI (preview + download). Blocking, like
388
- the upload prediction -- fine for this local single-user app."""
389
- if app["grid"] is None:
390
- return
391
- state.animating = True
392
- state.flush()
393
- try:
394
- out_dir = "runs/castings"
395
- os.makedirs(out_dir, exist_ok=True)
396
- gif_path = osp.join(out_dir, f"{app['name']}_solidification.gif")
397
- viz.solidification_animation(app["grid"], gif_path,
398
- cmap=FIELD_CMAP, ghost_opacity=GHOST_OPACITY,
399
- scalar_bar_args=SCALAR_BAR_ARGS, bg=VTK_BG,
400
- camera_position=plotter.camera_position)
401
- import base64
402
- with open(gif_path, "rb") as fh:
403
- b64 = base64.b64encode(fh.read()).decode("ascii")
404
- state.anim_uri = f"data:image/gif;base64,{b64}"
405
- state.anim_name = f"{app['name']}_solidification.gif"
406
- state.anim_ready = True
407
- except Exception as e:
408
- state.anim_ready = False
409
- state.summary = f"Animation failed:\n{e}"
410
- finally:
411
- state.animating = False
412
- ctrl.view_update()
413
- ctrl.generate_animation = generate_animation
414
-
415
- with SinglePageWithDrawerLayout(server, vuetify_config=vuetify_config,
416
- width=360) as layout:
417
- html.Style(_CUSTOM_CSS)
418
-
419
- # The nav-icon toggles the drawer, but the drawer is `permanent` (it
420
- # stays open as the fixed left control panel), so the toggle has no
421
- # visible effect -- hide it rather than show a button that does nothing.
422
- layout.icon.hide()
423
-
424
- # Dark, compact app-bar: it holds only the title and a status line, so
425
- # it is styled as an instrument-panel strip distinct from the light
426
- # control surfaces below it, and kept slim since it carries no controls.
427
- layout.toolbar.color = HEADER_BG
428
- layout.toolbar.density = "compact"
429
- layout.toolbar.flat = True
430
-
431
- layout.title.set_text(
432
- '<div class="neuralcast-title">'
433
- '<span class="neuralcast-title-text">Neuralcast Viewer</span>'
434
- "</div>"
435
- )
436
- with layout.toolbar:
437
- vuetify3.VSpacer()
438
- html.Div(
439
- "{{ loading ? 'Predicting…' : (loaded ? 'Prediction loaded' "
440
- ": 'Awaiting upload') }}",
441
- classes="neuralcast-status mr-2",
442
- )
443
- # Thin indeterminate progress bar pinned to the bottom edge of the
444
- # header -- visible only while a prediction is running, so the user
445
- # can see the model is working during the blocking STEP -> VTU call.
446
- vuetify3.VProgressLinear(
447
- indeterminate=True, absolute=True, location="bottom",
448
- height=3, color=ACCENT_MOLTEN, v_show=("loading",),
449
- )
450
-
451
- with layout.drawer:
452
- with html.Div(classes="d-flex flex-column fill-height pa-4 "
453
- "neuralcast-drawer-content"):
454
- with html.Div(classes="neuralcast-section"):
455
- html.Div("Upload", classes="neuralcast-section-label")
456
- vuetify3.VSelect(v_model=("alloy",), items=("alloy_options",),
457
- label="Alloy", density="compact",
458
- variant="outlined", hide_details=True,
459
- classes="mb-2")
460
- vuetify3.VSelect(v_model=("mold",), items=("mold_options",),
461
- label="Mold system", density="compact",
462
- variant="outlined", hide_details=True,
463
- classes="mb-2")
464
- vuetify3.VFileInput(v_model=("uploaded_file", None), label="STEP file",
465
- prepend_inner_icon="mdi-file-upload-outline",
466
- accept=".step,.stp,.STEP,.STP", density="compact",
467
- variant="outlined", hide_details=True)
468
- vuetify3.VBtn("Clear", click=clear_casting, variant="text",
469
- size="small", color="secondary", disabled=("!loaded",),
470
- classes="mt-2", block=True)
471
-
472
- with html.Div(classes="neuralcast-section"):
473
- html.Div("Playback", classes="neuralcast-section-label")
474
- vuetify3.VSlider(v_model=("tau",), min=("tmin",), max=("tmax",),
475
- label="time (s)",
476
- hide_details=True, disabled=("!loaded",),
477
- thumb_label=True)
478
- html.Div(
479
- "{{ Number(tau).toFixed(1) }} / {{ Number(tmax).toFixed(1) }} s",
480
- classes="neuralcast-tau-badge mt-1",
481
- )
482
-
483
- with html.Div(classes="neuralcast-section"):
484
- html.Div("Hot Spots", classes="neuralcast-section-label")
485
- vuetify3.VCheckbox(v_model=("show_hotspots",), label="show hot spots",
486
- hide_details=True, disabled=("!loaded",))
487
- vuetify3.VSlider(v_model=("hotspot_size",), min=2, max=40, step=1,
488
- label="size", hide_details=True,
489
- disabled=("!loaded",), thumb_label=True,
490
- classes="mt-4")
491
- vuetify3.VSlider(v_model=("hotspot_cutoff",), min=("tmin",),
492
- max=("tmax",), label="cutoff (s)", hide_details=True,
493
- disabled=("!loaded",), thumb_label=True,
494
- classes="mt-2")
495
-
496
- with html.Div(classes="neuralcast-section"):
497
- html.Div("Animation", classes="neuralcast-section-label")
498
- vuetify3.VBtn("Generate GIF", click=generate_animation,
499
- variant="tonal", size="small", color="primary",
500
- disabled=("!loaded || animating",), block=True,
501
- loading=("animating",))
502
- vuetify3.VProgressLinear(indeterminate=True, height=3,
503
- color=ACCENT_MOLTEN, v_show=("animating",),
504
- classes="mt-2")
505
- html.Img(src=("anim_uri",), v_show=("anim_ready",),
506
- style="max-width:100%; margin-top:10px; "
507
- f"border:1px solid {BORDER}; border-radius:4px;")
508
- html.A("Download GIF", href=("anim_uri",), download=("anim_name",),
509
- v_show=("anim_ready",),
510
- style=f"display:block; margin-top:8px; color:{ACCENT_MOLTEN}; "
511
- "font-size:.8rem; text-decoration:underline;")
512
-
513
- with html.Div(classes="neuralcast-section flex-grow-1 d-flex "
514
- "flex-column neuralcast-summary-box"):
515
- html.Div("Summary", classes="neuralcast-section-label")
516
- vuetify3.VTextarea(v_model=("summary",), readonly=True,
517
- variant="outlined", density="compact",
518
- hide_details=True, no_resize=True,
519
- classes="flex-grow-1")
520
-
521
- with layout.content:
522
- with vuetify3.VContainer(fluid=True, classes="fill-height pa-0"):
523
- # add_menu=True: keep pyvista's default view-toolbar overlay --
524
- # it gives reset-camera / view-axis / screenshot controls that
525
- # users want when inspecting the casting.
526
- # mode="server": render server-side (VTK on the Python process,
527
- # frames streamed to the browser) rather than client-side
528
- # (geometry shipped to the browser and rendered there). This
529
- # keeps the server-side VTK camera in sync with the user's
530
- # mouse rotations/pans/zooms, so generate_animation() below can
531
- # read plotter.camera_position and reuse the exact view for
532
- # the GIF -- with client-side rendering the server-side camera
533
- # would stay frozen regardless of what the user sees.
534
- view = plotter_ui(plotter, add_menu=True, mode="server")
535
- ctrl.view_update = view.update
536
-
537
- # Replace trame's default footer ("Powered by trame" / Kitware credit)
538
- # with our own.
539
- layout.footer.clear()
540
- with layout.footer:
541
- html.Div("© 2026 Eugen Miknevic", classes="neuralcast-footer-text")
542
-
543
- # NOTE (deviation from brief): trame's `state.to_dict()` only reflects state
544
- # that has been *flushed*, and flushing is a no-op until the state is marked
545
- # `ready()` (normally done when a client connects, i.e. inside `.start()`).
546
- # Since `build_app()` must be unit-constructible without starting the server,
547
- # we mark the state ready here so the initial `setdefault(...)` values are
548
- # visible via `to_dict()`/attribute access immediately after construction.
549
- # This performs no networking (no client is connected yet) and is idempotent
550
- # (a later real `.start()` calling `ready()` again is a no-op).
551
- state.ready()
552
-
553
- return server
554
-
555
-
556
- def main():
557
- build_app().start(port=8080)
558
-
559
-
560
- if __name__ == "__main__":
561
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/__init__.py DELETED
File without changes
tests/conftest.py DELETED
@@ -1,49 +0,0 @@
1
- """Shared pytest fixtures: a minimal gmsh-2.2 mesh for unit tests.
2
-
3
- The mesh is a unit-ish tetrahedron-based shape with 5 nodes:
4
- - one internal-ish apex, 4 base nodes forming two tets
5
- - two boundary triangles tagged 'Cooling', one tagged 'Adiabatic'
6
- Coordinates are in mm.
7
- """
8
- import textwrap
9
- import pytest
10
-
11
- # node ids 1..5 ; coords in mm
12
- MINI_MSH = textwrap.dedent("""\
13
- $MeshFormat
14
- 2.2 0 8
15
- $EndMeshFormat
16
- $PhysicalNames
17
- 3
18
- 2 1 "Adiabatic"
19
- 2 2 "Cooling"
20
- 3 3 "Volume"
21
- $EndPhysicalNames
22
- $Nodes
23
- 5
24
- 1 0 0 0
25
- 2 10 0 0
26
- 3 0 10 0
27
- 4 0 0 10
28
- 5 3 3 3
29
- $EndNodes
30
- $Elements
31
- 4
32
- 1 2 2 2 1 1 2 3
33
- 2 2 2 2 1 1 2 4
34
- 3 2 2 1 1 2 3 4
35
- 4 4 2 3 1 1 2 3 4
36
- $EndElements
37
- """)
38
- # Element lines: "id type ntags phys geom n1 n2 n3[ n4]"
39
- # el1: triangle (type 2), phys 2 = Cooling, nodes 1,2,3
40
- # el2: triangle, phys 2 = Cooling, nodes 1,2,4
41
- # el3: triangle, phys 1 = Adiabatic, nodes 2,3,4
42
- # el4: tetrahedron (type 4), phys 3 = Volume, nodes 1,2,3,4
43
-
44
-
45
- @pytest.fixture
46
- def mini_msh_file(tmp_path):
47
- p = tmp_path / "MINI_00.msh"
48
- p.write_text(MINI_MSH)
49
- return str(p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_features.py DELETED
@@ -1,55 +0,0 @@
1
- import numpy as np
2
- import pytest
3
-
4
- from src.features import FEATURE_NAMES, alloy_g_vector, node_features
5
- from src.msh_parse import parse_msh
6
-
7
- MOLD_EFF = 1018.0
8
-
9
-
10
- def test_shapes_and_order(mini_msh_file):
11
- mesh = parse_msh(mini_msh_file)
12
- f = node_features(mesh, MOLD_EFF)
13
- assert f["X"].shape == (5, len(FEATURE_NAMES)) == (5, 15)
14
- assert f["X"].dtype == np.float32
15
- assert f["pos"].shape == (5, 3)
16
- assert f["mesh_edges"].shape == (6, 2) # one tet -> 6 edges
17
-
18
-
19
- def test_flags_and_boundary_channels(mini_msh_file):
20
- X = node_features(parse_msh(mini_msh_file), MOLD_EFF)["X"]
21
- col = {n: X[:, i] for i, n in enumerate(FEATURE_NAMES)}
22
- # nodes 0..3 lie on the tagged surface, node 4 (index 4) is not in any tet
23
- assert col["is_cooling"][:4].tolist() == [1, 1, 1, 1]
24
- assert col["is_adiabatic"].sum() == 0 # adiabatic nodes are also cooling here
25
- assert col["is_interior"][4] == 1
26
- np.testing.assert_allclose(col["boundary_extraction"][:4], MOLD_EFF)
27
- assert col["boundary_extraction"][4] == 0
28
- assert np.all(col["boundary_heat_input"] == 0)
29
-
30
-
31
- def test_global_columns_are_constant(mini_msh_file):
32
- X = node_features(parse_msh(mini_msh_file), MOLD_EFF)["X"]
33
- for name in ("volume_mm3", "surface_area_mm2", "cooling_area_frac"):
34
- c = X[:, FEATURE_NAMES.index(name)]
35
- assert np.all(c == c[0])
36
- assert X[0, FEATURE_NAMES.index("volume_mm3")] == pytest.approx(1000.0 / 6.0)
37
-
38
-
39
- def test_translation_invariance(mini_msh_file):
40
- mesh = parse_msh(mini_msh_file)
41
- a = node_features(mesh, MOLD_EFF)["X"]
42
- mesh.node_xyz = mesh.node_xyz + np.array([100.0, -50.0, 7.0])
43
- b = node_features(mesh, MOLD_EFF)["X"]
44
- np.testing.assert_allclose(a, b, rtol=1e-5, atol=1e-4)
45
-
46
-
47
- def test_g_vector():
48
- props = {"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0,
49
- "TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1250.0}
50
- g = alloy_g_vector(props)
51
- assert g.shape == (5,)
52
- assert g[0] == pytest.approx(515.0 * 140.0 / 220000.0) # Stefan number
53
- assert g[1] == pytest.approx(0.04) and g[3] == pytest.approx(0.1)
54
- assert g[2] == pytest.approx(32.9 / (6800.0 * 515.0) / 1e-5)
55
- assert g[4] == pytest.approx(1.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_gbm_heads.py DELETED
@@ -1,55 +0,0 @@
1
- import numpy as np
2
- import pytest
3
-
4
- from src import gbm_heads
5
- from src.features import FEATURE_NAMES
6
-
7
- PROPS = {"k": 32.9, "rho": 6800.0, "cp": 515.0, "L_kJ_kg": 220.0,
8
- "TL": 1160.0, "TS": 1120.0, "Tpour": 1260.0, "mold_effusivity": 1018.0}
9
-
10
-
11
- def _X(n=10, vol=8000.0, area=2400.0, n_adiab=0):
12
- X = np.zeros((n, len(FEATURE_NAMES)), np.float32)
13
- X[:, FEATURE_NAMES.index("volume_mm3")] = vol
14
- X[:, FEATURE_NAMES.index("surface_area_mm2")] = area
15
- X[:6, FEATURE_NAMES.index("is_cooling")] = 1
16
- X[6:6 + n_adiab, FEATURE_NAMES.index("is_adiabatic")] = 1
17
- return X
18
-
19
-
20
- def test_total_row_layout():
21
- row = gbm_heads.total_row(PROPS, _X())
22
- assert row.shape == (gbm_heads.N_TOTAL_FEATURES,)
23
- assert row[:7].tolist() == [32.9, 6800.0, 515.0, 220.0, 1160.0, 1120.0, 1260.0]
24
- assert row[7] == pytest.approx(8000.0 / 2400.0)
25
- assert row[8] == 1018.0
26
- assert row[9:].tolist() == [1, 0, 0, 0, 0, 0, 0]
27
-
28
-
29
- def test_spread_row_appends_adiabatic_fraction():
30
- X = _X(n_adiab=2)
31
- row = gbm_heads.spread_row(gbm_heads.total_row(PROPS, X), X)
32
- assert row.shape == (gbm_heads.N_SPREAD_FEATURES,)
33
- assert row[-1] == pytest.approx(2 / 8)
34
-
35
-
36
- class _Stub:
37
- def __init__(self, value, n):
38
- self.value, self.n_features_in_ = value, n
39
-
40
- def predict(self, x):
41
- return np.full(len(x), self.value)
42
-
43
-
44
- def test_predictions_are_expm1_of_log_output():
45
- row = np.zeros(16)
46
- assert gbm_heads.predict_total_seconds(_Stub(np.log1p(500.0), 16), row) == pytest.approx(500.0)
47
- assert gbm_heads.predict_spread_seconds(_Stub(-5.0, 17), np.zeros(17)) == 0.0
48
- with pytest.raises(ValueError):
49
- gbm_heads.predict_total_seconds(_Stub(-1.0, 16), row)
50
-
51
-
52
- def test_check_head_rejects_wrong_width():
53
- gbm_heads.check_head(_Stub(0.0, 16), 16, "total-time")
54
- with pytest.raises(ValueError):
55
- gbm_heads.check_head(_Stub(0.0, 9), 16, "total-time")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_geometry.py DELETED
@@ -1,36 +0,0 @@
1
- import numpy as np
2
- from src.geometry import (triangle_areas, total_area, mesh_volume,
3
- nearest_distance, boundary_node_mask)
4
-
5
-
6
- def test_triangle_area_right_triangle():
7
- xyz = np.array([[0, 0, 0], [4, 0, 0], [0, 3, 0]], float)
8
- tri = np.array([[0, 1, 2]])
9
- np.testing.assert_allclose(triangle_areas(xyz, tri), [6.0]) # 0.5*4*3
10
- np.testing.assert_allclose(total_area(xyz, tri), 6.0)
11
-
12
-
13
- def test_tet_volume_unit():
14
- # tetrahedron with legs 3,3,3 along axes from origin -> vol = 3^3/6 = 4.5
15
- xyz = np.array([[0, 0, 0], [3, 0, 0], [0, 3, 0], [0, 0, 3]], float)
16
- tets = np.array([[0, 1, 2, 3]])
17
- np.testing.assert_allclose(mesh_volume(xyz, tets), 4.5)
18
-
19
-
20
- def test_nearest_distance():
21
- pts = np.array([[0, 0, 0], [10, 0, 0]], float)
22
- tgt = np.array([[0, 0, 0], [1, 0, 0]], float)
23
- np.testing.assert_allclose(nearest_distance(pts, tgt), [0.0, 9.0])
24
-
25
-
26
- def test_nearest_distance_empty_targets():
27
- pts = np.array([[0, 0, 0]], float)
28
- tgt = np.empty((0, 3), float)
29
- d = nearest_distance(pts, tgt)
30
- assert np.isinf(d).all()
31
-
32
-
33
- def test_boundary_node_mask():
34
- tri = np.array([[0, 1, 2], [1, 2, 3]])
35
- m = boundary_node_mask(5, tri)
36
- np.testing.assert_array_equal(m, [True, True, True, True, False])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_hybrid.py DELETED
@@ -1,336 +0,0 @@
1
- import logging
2
-
3
- import numpy as np
4
- import pytest
5
- from src.hybrid import hybrid_field_affine, hybrid_field_max_anchor, hybrid_field_soft
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
- def test_hybrid_affine_spread_match():
15
- # gnn std is exactly 10 (two points, mean 10, deviations -+10)
16
- gnn = np.array([0.0, 20.0])
17
- total = 1000.0 # large enough that nothing clips
18
- pred, info = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995)
19
- assert info["a"] == 2.0
20
- np.testing.assert_allclose(np.std(pred), 20.0, atol=1e-9)
21
- assert info["clip_frac"] == 0.0
22
-
23
-
24
- def test_hybrid_affine_total_anchor():
25
- gnn = np.array([0.0, 20.0])
26
- total = 1000.0 # large enough that nothing clips
27
- pred, info = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995)
28
- assert np.quantile(pred, 0.995) == pytest.approx(total, abs=1e-9)
29
- assert info["clip_frac"] == 0.0
30
-
31
-
32
- def test_hybrid_affine_preserves_ranking():
33
- gnn = np.array([3.0, 1.0, 9.0, 5.0])
34
- total = 1000.0
35
- pred, info = hybrid_field_affine(gnn, total, std_seconds=5.0)
36
- assert info["a"] > 0.0
37
- assert list(np.argsort(pred)) == list(np.argsort(gnn))
38
-
39
-
40
- def test_hybrid_affine_clamp_high():
41
- # gnn std is 10; std_seconds=100 -> a_raw=10.0, clamped down to the a_clamp
42
- # ceiling 5.0. No clipping occurs at a=5.0 here (total=1000 is large), so
43
- # this exercises the closed-form path's own clamp handling.
44
- gnn = np.array([0.0, 20.0])
45
- total = 1000.0
46
- pred, info = hybrid_field_affine(gnn, total, std_seconds=100.0)
47
- assert info["a"] == 5.0
48
- assert info["a_clamped"] is True
49
-
50
-
51
- def test_hybrid_affine_degenerate_fallback(caplog):
52
- gnn = np.array([5.0, 5.0, 5.0])
53
- total = 100.0
54
- with caplog.at_level(logging.WARNING):
55
- pred, info = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995)
56
- expected = hybrid_field_max_anchor(gnn, total, q=0.995)
57
- np.testing.assert_allclose(pred, expected)
58
- assert info["degenerate_fallback"] is True
59
- assert any("degenerate" in rec.message.lower() for rec in caplog.records)
60
-
61
-
62
- def test_hybrid_affine_clip_negative():
63
- # gnn std is 50; the naive (pre-amendment) closed form a=std_seconds/s=1.0
64
- # already clips the low node (raw would be [-89.5, 10.5]), so the
65
- # clip-aware solver kicks in. With only 2 nodes the post-clip std is capped
66
- # well below 50 everywhere in the clamp range (max achievable is at
67
- # a=5.0), so this lands on the a_clamp ceiling.
68
- gnn = np.array([0.0, 100.0])
69
- total = 10.0
70
- pred, info = hybrid_field_affine(gnn, total, std_seconds=50.0)
71
- np.testing.assert_allclose(pred, [0.0, 12.5])
72
- assert info["a"] == 5.0
73
- assert info["a_clamped"] is True
74
- assert info["clip_frac"] == pytest.approx(0.5)
75
-
76
-
77
- def test_hybrid_affine_heavy_clip_achievable():
78
- # Real fields sometimes need heavy scaling to hit the spread head's
79
- # target; a closed form that ignores clipping
80
- # entirely, so its implied `a` can leave the delivered std far short of
81
- # the target. Construct such a case (right-skewed field; the naive
82
- # closed-form `a` clips ~30% of nodes) and confirm the clip-aware solve
83
- # still lands on-target.
84
- g = np.random.default_rng(1).exponential(5.0, size=200)
85
- s = np.std(g)
86
- total = 8.0
87
- target = 0.3 * s
88
-
89
- # sanity: the pre-amendment closed form (a = target/s, unclamped) clips
90
- # ~30% of nodes here -- this is the regime the amendment targets.
91
- a_naive = target / s
92
- centered_naive = a_naive * (g - g.mean())
93
- m_naive = total - np.quantile(centered_naive, 0.995)
94
- naive_clip_frac = float((centered_naive + m_naive < 0.0).mean())
95
- assert 0.25 <= naive_clip_frac <= 0.35
96
-
97
- pred, info = hybrid_field_affine(g, total, target)
98
- assert info["a_clamped"] is False
99
- assert np.std(pred) == pytest.approx(target, rel=1e-3)
100
-
101
-
102
- def test_hybrid_affine_unachievable_due_to_clipping():
103
- # std_seconds=8.0 exceeds this field's interior PEAK (f rises past
104
- # a_clipstart to a peak around a~1.78, std~3.82, then falls -- it never
105
- # reaches 8.0 anywhere in the clamp range). The unreachable case must pick the scanned point CLOSEST to
106
- # the target (here, at/near the peak) rather than blindly clamping to
107
- # a_clamp[1]=5.0 -- clamping to 5.0 would give a worse fit (std~3.45,
108
- # clip_frac 0.7) than the peak (std~3.82, clip_frac 0.4).
109
- gnn = np.arange(10.0)
110
- total = 10.5
111
- pred, info = hybrid_field_affine(gnn, total, std_seconds=8.0)
112
- assert info["a"] != 5.0 # must NOT blindly clamp to the ceiling
113
- assert info["a_clamped"] is True
114
- achieved = np.std(pred)
115
- assert achieved == pytest.approx(3.816200508029165, rel=1e-6)
116
- assert achieved < 8.0
117
- # the peak (this test's outcome) beats the naive hi=5.0 clamp on fit:
118
- at_hi = np.clip(5.0 * (gnn - gnn.mean() - np.quantile(gnn - gnn.mean(), 0.995)) + total,
119
- 0.0, None)
120
- assert abs(achieved - 8.0) < abs(np.std(at_hi) - 8.0)
121
-
122
-
123
-
124
-
125
- def test_hybrid_affine_no_clip_matches_pre_amendment_closed_form():
126
- # Invariant: when nothing clips at the closed-form solution, the amended
127
- # (clip-aware) function must reproduce the pre-amendment closed form
128
- # exactly (it takes it as a fast path; bisection is never invoked).
129
- def pre_amendment_closed_form(gnn_seconds, total_seconds, std_seconds,
130
- q=0.995, a_clamp=(0.3, 5.0)):
131
- g = np.asarray(gnn_seconds, dtype=np.float64)
132
- s = float(np.std(g))
133
- a_raw = float(std_seconds) / s
134
- a = float(np.clip(a_raw, a_clamp[0], a_clamp[1]))
135
- centered = a * (g - g.mean())
136
- m = float(total_seconds) - float(np.quantile(centered, q))
137
- out = centered + m
138
- return np.clip(out, 0.0, None), a
139
-
140
- gnn = np.array([3.0, 1.0, 9.0, 5.0])
141
- total = 1000.0
142
- std_seconds = 5.0
143
- pred_new, info_new = hybrid_field_affine(gnn, total, std_seconds)
144
- pred_old, a_old = pre_amendment_closed_form(gnn, total, std_seconds)
145
- assert info_new["a_clamped"] is False
146
- assert info_new["a"] == pytest.approx(a_old, rel=1e-6)
147
- np.testing.assert_allclose(pred_new, pred_old, rtol=1e-6)
148
-
149
-
150
-
151
-
152
-
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
- # --------------------------------------------------------------------------- #
161
- # hybrid_field_soft: weighted two-target soft recomposition
162
- # --------------------------------------------------------------------------- #
163
- def _squeezed_case():
164
- # A field with a small (3%) group of low-value outlier nodes and a tight
165
- # high-value cluster: the affine solve's hard quantile-anchor pins the
166
- # top near `total`, so scaling enough to hit a large `std_seconds` clips
167
- # the low outliers hard -- `a_clamped` fires (the two-target problem is
168
- # unreachable via a pure affine map). Verified interactively: at these
169
- # exact parameters the affine solve lands short of the std target
170
- # (std ~169.8 vs target ~330.1, clip_frac 0.03, a_clamped True) while the
171
- # soft solve's default-weight optimum (~203.2) is strictly closer, by
172
- # trading a ~20% total-anchor deviation for less clipping.
173
- rng = np.random.default_rng(7)
174
- n = 200
175
- n_low = int(0.03 * n)
176
- n_high = n - n_low
177
- high_vals = 1000.0 + rng.normal(0.0, 2.0, n_high)
178
- low_vals = rng.uniform(0.0, 50.0, n_low)
179
- g = np.concatenate([high_vals, low_vals])
180
- total = 1000.0
181
- target = 2.0 * float(np.std(g))
182
- return g, total, target
183
-
184
-
185
- def test_hybrid_soft_exact_degeneration_matches_affine():
186
- # No-clip case (from test_hybrid_affine_spread_match/total_anchor): the
187
- # affine solve already hits both targets essentially exactly, so the soft
188
- # solve must return that seed unchanged.
189
- gnn = np.array([0.0, 20.0])
190
- total = 1000.0
191
- pred_affine, info_affine = hybrid_field_affine(gnn, total, std_seconds=20.0, q=0.995)
192
- pred_soft, info_soft = hybrid_field_soft(gnn, total, std_seconds=20.0, q=0.995)
193
- np.testing.assert_allclose(pred_soft, pred_affine, rtol=1e-9)
194
- assert abs(info_soft["total_deviation_frac"]) < 1e-6
195
- assert info_soft["degenerate_fallback"] is False
196
-
197
-
198
- def test_hybrid_soft_trade_off_engages_on_squeezed_case():
199
- g, total, target = _squeezed_case()
200
- pred_affine, info_affine = hybrid_field_affine(g, total, target)
201
- assert info_affine["a_clamped"] is True # affine truly cannot reach std_t
202
-
203
- pred_soft, info_soft = hybrid_field_soft(g, total, target)
204
- d_affine = abs(np.std(pred_affine) - target)
205
- d_soft = abs(np.std(pred_soft) - target)
206
- assert d_soft < d_affine # soft's std is strictly closer to the target
207
- assert info_soft["total_deviation_frac"] > 0 # the top rose above total
208
-
209
-
210
- def test_hybrid_soft_weight_monotonicity_on_squeezed_case():
211
- g, total, target = _squeezed_case()
212
- pred_hi, info_hi = hybrid_field_soft(g, total, target, w_total=100.0, w_std=1.0)
213
- pred_lo, info_lo = hybrid_field_soft(g, total, target, w_total=0.01, w_std=1.0)
214
- assert abs(info_hi["total_deviation_frac"]) <= abs(info_lo["total_deviation_frac"])
215
- assert np.std(pred_lo) >= np.std(pred_hi)
216
-
217
-
218
- def test_hybrid_soft_determinism():
219
- g, total, target = _squeezed_case()
220
- pred1, info1 = hybrid_field_soft(g, total, target)
221
- pred2, info2 = hybrid_field_soft(g, total, target)
222
- np.testing.assert_array_equal(pred1, pred2)
223
- assert info1 == info2
224
-
225
-
226
- def test_hybrid_soft_degenerate_flat_field_falls_back(caplog):
227
- gnn = np.array([5.0, 5.0, 5.0])
228
- total = 100.0
229
- with caplog.at_level(logging.WARNING):
230
- pred, info = hybrid_field_soft(gnn, total, std_seconds=20.0, q=0.995)
231
- expected = hybrid_field_max_anchor(gnn, total, q=0.995)
232
- np.testing.assert_allclose(pred, expected)
233
- assert info["degenerate_fallback"] is True
234
- assert any("degenerate" in rec.message.lower() for rec in caplog.records)
235
-
236
-
237
-
238
-
239
-
240
-
241
- # --------------------------------------------------------------------------- #
242
- # Edge cases: the a_clamp[0] <= 0 guard and degeneration to the affine solve
243
- # at a realistic scale.
244
- # --------------------------------------------------------------------------- #
245
-
246
-
247
-
248
-
249
- def test_hybrid_soft_realistic_scale_exact_degeneration_matches_affine():
250
- # The exact-degeneration test above uses a 2-node toy field;
251
- # this adds a realistic-scale (n=5000), right-skewed synthetic field with
252
- # an EASILY achievable std target (no clipping needed at all), so the
253
- # affine seed hits both targets and the soft solve must reduce to it
254
- # exactly (via the j_seed < 1e-12 early return, not by chance).
255
- rng = np.random.default_rng(11)
256
- g = rng.lognormal(mean=5.0, sigma=0.4, size=5000)
257
- total = 5000.0 # large relative to g's own scale -> no clipping at a~1
258
- target = 0.8 * float(np.std(g)) # well within reach, a_raw < 1 < a_clamp[1]
259
-
260
- pred_affine, info_affine = hybrid_field_affine(g, total, target)
261
- assert info_affine["a_clamped"] is False
262
- pred_soft, info_soft = hybrid_field_soft(g, total, target)
263
-
264
- np.testing.assert_allclose(pred_soft, pred_affine, rtol=1e-9)
265
- assert info_soft["target_unreachable"] is False
266
- assert abs(info_soft["total_deviation_frac"]) < 1e-6
267
-
268
-
269
- def test_hybrid_soft_a_clamp_lo_nonpositive_raises():
270
- gnn = np.array([1.0, 2.0, 3.0])
271
- with pytest.raises(ValueError, match="a_clamp"):
272
- hybrid_field_soft(gnn, 10.0, 1.0, a_clamp=(0.0, 5.0))
273
- with pytest.raises(ValueError, match="a_clamp"):
274
- hybrid_field_soft(gnn, 10.0, 1.0, a_clamp=(-1.0, 5.0))
275
-
276
-
277
- def test_hybrid_soft_negative_weight_raises():
278
- # LOW: a negative weight rewards moving AWAY from that
279
- # target (minimizing J then maximizes the residual's square) -- must
280
- # raise loudly rather than silently drive a to a nonsensical optimum.
281
- gnn = np.array([1.0, 2.0, 3.0])
282
- with pytest.raises(ValueError, match="w_total|w_std"):
283
- hybrid_field_soft(gnn, 10.0, 1.0, w_total=-1.0)
284
- with pytest.raises(ValueError, match="w_total|w_std"):
285
- hybrid_field_soft(gnn, 10.0, 1.0, w_std=-1.0)
286
-
287
-
288
- def test_hybrid_soft_both_weights_zero_raises():
289
- # LOW: w_total == w_std == 0 makes J identically zero
290
- # everywhere -- no signal for the search to optimize against.
291
- gnn = np.array([1.0, 2.0, 3.0])
292
- with pytest.raises(ValueError, match="w_total|w_std"):
293
- hybrid_field_soft(gnn, 10.0, 1.0, w_total=0.0, w_std=0.0)
294
-
295
-
296
- def test_hybrid_soft_one_weight_zero_is_allowed():
297
- # Sanity: only BOTH-zero is forbidden -- a single zero weight (pure
298
- # single-target optimization) is a legitimate, deliberate use case.
299
- gnn = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
300
- pred, info = hybrid_field_soft(gnn, 10.0, 1.0, w_total=0.0, w_std=1.0)
301
- assert np.all(np.isfinite(pred))
302
- pred, info = hybrid_field_soft(gnn, 10.0, 1.0, w_total=1.0, w_std=0.0)
303
- assert np.all(np.isfinite(pred))
304
-
305
-
306
- def test_hybrid_soft_accepted_optimum_majority_clipped_warns(caplog):
307
- # The affine path already warns when ITS OWN clip_frac > 0.5; the
308
- # soft path must emit the analogous warning when the ACCEPTED soft
309
- # optimum (which can differ from the affine seed) itself clips a
310
- # majority of the field.
311
- rng = np.random.default_rng(3)
312
- g = rng.exponential(1.0, size=500) ** 2
313
- g = g - g.min()
314
- total = 3.0
315
- target = 3.0 * float(np.std(g))
316
- with caplog.at_level(logging.WARNING):
317
- pred, info = hybrid_field_soft(g, total, target, w_total=0.1, w_std=10.0)
318
- assert info["clip_frac"] > 0.5
319
- assert any("hybrid_field_soft" in rec.message and "majority" in rec.message.lower()
320
- for rec in caplog.records)
321
-
322
-
323
-
324
-
325
- def test_hybrid_soft_info_dict_carries_all_keys():
326
- g, total, target = _squeezed_case()
327
- pred, info = hybrid_field_soft(g, total, target)
328
- expected_keys = {"a", "m", "target_unreachable", "degenerate_fallback", "clip_frac",
329
- "total_deviation_frac", "j_total_resid", "j_std_resid",
330
- "std_target_effective"}
331
- assert expected_keys <= set(info.keys())
332
- # clip_frac must be measured on the FINAL (returned) field.
333
- a, m = info["a"], info["m"]
334
- c = g - g.mean()
335
- final_raw = a * c + m
336
- assert info["clip_frac"] == pytest.approx(float((final_raw < 0.0).mean()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_hybrid_max_anchor.py DELETED
@@ -1,86 +0,0 @@
1
- """max/quantile-anchor hybrid recomposition, in src/hybrid.py.
2
-
3
- The exact-max anchor is fragile to a handful of outlier nodes (one
4
- inflated GNN log-space prediction can drag the entire rest of the field
5
- below the zero clip). The anchor moved to a high quantile
6
- (`np.quantile(gnn, q)`, default `q=0.995`); `q=1.0` reproduces the old
7
- exact-max behavior bit-for-bit (`np.quantile(x, 1.0) == x.max()`).
8
- """
9
- import numpy as np
10
-
11
- from src.hybrid import hybrid_field_max_anchor
12
-
13
-
14
- def test_max_anchor_q1_sets_exact_max_and_preserves_shape():
15
- """q=1.0 regression pin: reproduces the earlier exact-max behavior."""
16
- g = np.array([1.0, 4.0, 2.5])
17
- out = hybrid_field_max_anchor(g, 10.0, q=1.0)
18
- assert out.max() == 10.0
19
- assert np.allclose(np.diff(out), np.diff(g)) # additive shift only
20
-
21
-
22
- def test_max_anchor_default_q_preserves_shape_and_meets_or_exceeds_total():
23
- """Default q<1: still an additive shift; max(out) >= total (not ==)."""
24
- g = np.array([1.0, 4.0, 2.5])
25
- out = hybrid_field_max_anchor(g, 10.0)
26
- assert out.max() >= 10.0
27
- assert out.shape == g.shape
28
- assert np.allclose(np.diff(out), np.diff(g)) # additive shift only
29
-
30
-
31
- def test_max_anchor_clips_at_zero():
32
- assert hybrid_field_max_anchor(np.array([0.0, 100.0]), 10.0)[0] == 0.0
33
-
34
-
35
-
36
-
37
- def test_max_anchor_q1_reproduces_old_exact_max_on_random_vector():
38
- """Regression pin: q=1.0 bit-for-bit equals the earlier formula
39
- `clip(g - g.max() + total, 0, None)` on an arbitrary random vector."""
40
- rng = np.random.default_rng(42)
41
- g = rng.normal(loc=50.0, scale=20.0, size=200)
42
- total = 37.5
43
-
44
- out = hybrid_field_max_anchor(g, total, q=1.0)
45
- expected = np.clip(g - g.max() + total, 0.0, None)
46
-
47
- assert np.array_equal(out, expected)
48
-
49
-
50
- def test_max_anchor_default_q_is_robust_to_a_single_outlier_node():
51
- """The failure mode the promotion gate exposed: one wildly-inflated
52
- GNN prediction anchored to the exact max drags ~all other nodes below
53
- the zero clip. With the default quantile anchor (q=0.995), >=99% of a
54
- 1000-node field stays > 0 for the same outlier + total."""
55
- rng = np.random.default_rng(0)
56
- bulk = rng.uniform(0.0, 100.0, size=1000)
57
- g = np.concatenate([bulk, [1e6]]) # one extreme outlier node
58
- total = 500.0
59
-
60
- out_exact = hybrid_field_max_anchor(g, total, q=1.0)
61
- out_default = hybrid_field_max_anchor(g, total)
62
-
63
- # Old exact-max behavior: the outlier alone sets the anchor, dragging
64
- # essentially the whole bulk to the zero clip.
65
- assert (out_exact[:-1] > 0).mean() < 0.01
66
-
67
- # New default-q behavior: the bulk survives the clip.
68
- assert (out_default[:-1] > 0).mean() >= 0.99
69
- assert out_default.shape == g.shape
70
-
71
-
72
- def test_max_anchor_argsort_unchanged_between_q1_and_default_q():
73
- """Hot-spot ranking must be unaffected by the anchor choice: both are
74
- per-graph additive shifts of the same field, so (absent clipping
75
- collisions) node order is identical regardless of q."""
76
- rng = np.random.default_rng(7)
77
- g = rng.uniform(10.0, 200.0, size=500)
78
- # total large enough that neither anchor choice clips any node at zero
79
- # (min(g) - anchor + total > 0 for anchor <= max(g)): isolates ordering
80
- # from the (expected, separately-tested) clipping behavior.
81
- total = 300.0
82
-
83
- out_q1 = hybrid_field_max_anchor(g, total, q=1.0)
84
- out_default = hybrid_field_max_anchor(g, total)
85
-
86
- assert np.array_equal(np.argsort(out_q1), np.argsort(out_default))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_inference_props.py DELETED
@@ -1,102 +0,0 @@
1
- import json, pytest
2
- from src.inference_props import resolve_props, list_alloys, list_molds, DEFAULT_ALLOY, \
3
- resolve_alloy_family
4
- from src.shrinkage import SHRINKAGE_PCT
5
-
6
- REQ = {"k", "rho", "cp", "L_kJ_kg", "TL", "TS", "Tpour", "mold_effusivity"}
7
-
8
- def test_default_is_gjs400_green_sand():
9
- p = resolve_props()
10
- assert set(p) == REQ and all(isinstance(v, float) for v in p.values())
11
- assert p["TL"] == 1160.0 and p["TS"] == 1120.0 # EN-GJS-400-15 row
12
- assert p["Tpour"] == pytest.approx((1250 + 1270) / 2) # midpoint rule
13
- assert p["mold_effusivity"] == pytest.approx(1018.0) # molds.csv, NOT 1250
14
-
15
- def test_named_alloy_and_lists():
16
- assert DEFAULT_ALLOY in list_alloys()
17
- assert list_alloys() == ["EN-GJS-400-15", "G20Mn5"]
18
- assert list_molds() == ["green_sand"]
19
- p = resolve_props(alloy="G20Mn5")
20
- assert p["TS"] == 1495.0
21
-
22
- def test_unknown_names_raise_listing_options():
23
- with pytest.raises(ValueError, match="EN-GJS-400-15"):
24
- resolve_props(alloy="unobtainium")
25
- with pytest.raises(ValueError, match="green_sand"):
26
- resolve_props(mold="vacuum")
27
-
28
- def test_props_json_override_and_missing_keys(tmp_path):
29
- full = dict(k=30.0, rho=7000.0, cp=500.0, L_kJ_kg=220.0, TL=1200.0, TS=1120.0,
30
- Tpour=1350.0, mold_effusivity=900.0)
31
- f = tmp_path / "p.json"; f.write_text(json.dumps(full))
32
- assert resolve_props(props_json=str(f)) == full
33
- f2 = tmp_path / "p2.json"; f2.write_text(json.dumps({"k": 30.0}))
34
- with pytest.raises(ValueError, match="L_kJ_kg"):
35
- resolve_props(props_json=str(f2))
36
-
37
-
38
- # --------------------------------------------------------------------------- #
39
- # A `--props` custom-JSON override with TL <= TS was previously unvalidated -- silently
40
- # collapsing src.shrinkage.niyama_proxy to 0 everywhere (100% flagged).
41
- # --------------------------------------------------------------------------- #
42
- def test_props_json_tl_less_equal_ts_raises(tmp_path):
43
- inverted = dict(k=30.0, rho=7000.0, cp=500.0, L_kJ_kg=220.0, TL=1100.0, TS=1200.0,
44
- Tpour=1350.0, mold_effusivity=900.0)
45
- f = tmp_path / "inverted.json"; f.write_text(json.dumps(inverted))
46
- with pytest.raises(ValueError, match=r"TL.*1100.*TS.*1200|TL.*must be strictly greater"):
47
- resolve_props(props_json=str(f))
48
-
49
-
50
- def test_props_json_tl_equal_ts_raises(tmp_path):
51
- # degenerate (TL == TS), not just inverted -- niyama_proxy's tdot_proxy
52
- # would be exactly (TL-TS)/t_s == 0 for every node either way.
53
- degenerate = dict(k=30.0, rho=7000.0, cp=500.0, L_kJ_kg=220.0, TL=1150.0, TS=1150.0,
54
- Tpour=1350.0, mold_effusivity=900.0)
55
- f = tmp_path / "degenerate.json"; f.write_text(json.dumps(degenerate))
56
- with pytest.raises(ValueError, match="TL"):
57
- resolve_props(props_json=str(f))
58
-
59
-
60
- def test_named_alloy_tl_ts_still_valid_after_i2_guard():
61
- # sanity: the new guard must not break any real named grade (already
62
- # validated by tools.doe.load_properties.load_materials's own TS<TL<Tpour
63
- # check at CSV-load time -- this just proves resolve_props's OWN check
64
- # doesn't double-reject a legitimately-ordered grade).
65
- for grade in list_alloys():
66
- p = resolve_props(alloy=grade)
67
- assert p["TL"] > p["TS"]
68
-
69
-
70
-
71
-
72
- def test_resolve_alloy_family_default_alloy_when_none():
73
- # None -> DEFAULT_ALLOY (EN-GJS-400-15) -> ductile_iron, not assumed.
74
- assert resolve_alloy_family(None) == ("ductile_iron", False)
75
-
76
-
77
- def test_resolve_alloy_family_unknown_prefix_falls_back_loud():
78
- family, assumed = resolve_alloy_family("some_unknown_grade")
79
- assert family == "steel" and assumed is True
80
-
81
-
82
-
83
-
84
-
85
-
86
- def test_resolve_alloy_family_covers_every_catalog_grade_exactly():
87
- """a data-driven guard over the REAL property
88
- DB (`data/properties/materials.csv` via `list_alloys()`) -- every grade
89
- actually on file today must be an EXACT prefix match (`assumed is
90
- False`), not a fallback. This is the loud-failure trip-wire for a
91
- FUTURE grade added to the catalog under a name none of
92
- `_ALLOY_FAMILY_PREFIXES` recognizes: that grade would otherwise silently
93
- default to "steel" (a plausible-looking but wrong family for, say, a new
94
- aluminum or a differently-prefixed steel grade) with no test ever
95
- catching it."""
96
- for grade in list_alloys():
97
- family, assumed = resolve_alloy_family(grade)
98
- assert assumed is False, (
99
- f"catalog grade {grade!r} fell back to the 'assumed' family map "
100
- f"(resolved family={family!r}) -- add a matching prefix to "
101
- f"src.inference_props._ALLOY_FAMILY_PREFIXES")
102
- assert family in SHRINKAGE_PCT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_local_modulus.py DELETED
@@ -1,63 +0,0 @@
1
- import numpy as np
2
- from scipy.spatial import Delaunay
3
-
4
- from src.geometry import (local_modulus, tet_volumes, edges_from_tets,
5
- mesh_volume, total_area)
6
-
7
-
8
- def _cube(a=10.0):
9
- pts = np.array([[x, y, z] for x in (0, a) for y in (0, a) for z in (0, a)], float)
10
- dt = Delaunay(pts)
11
- tets = dt.simplices.astype(np.int64)
12
- cool = dt.convex_hull.astype(np.int64) # all 12 boundary triangles
13
- edges = edges_from_tets(tets)
14
- elen = np.linalg.norm(pts[edges[:, 0]] - pts[edges[:, 1]], axis=1)
15
- return pts, tets, cool, edges, elen
16
-
17
-
18
- def _box_grid(n=4, a=10.0):
19
- """A structured grid of n^3 points spanning a cube of side `a`, Delaunay
20
- tetrahedralized, with the convex-hull triangles as the cooling surface.
21
- Denser than `_cube` (n=2) -> stands in for a training-density mesh."""
22
- lin = np.linspace(0.0, a, n)
23
- pts = np.array([[x, y, z] for x in lin for y in lin for z in lin], float)
24
- dt = Delaunay(pts)
25
- tets = dt.simplices.astype(np.int64)
26
- cool = dt.convex_hull.astype(np.int64)
27
- edges = edges_from_tets(tets)
28
- elen = np.linalg.norm(pts[edges[:, 0]] - pts[edges[:, 1]], axis=1)
29
- return pts, tets, cool, edges, elen
30
-
31
-
32
- def test_tet_volumes_sum_to_mesh_volume():
33
- xyz, tets, _, _, _ = _cube()
34
- assert np.isclose(tet_volumes(xyz, tets).sum(), mesh_volume(xyz, tets))
35
- assert np.isclose(mesh_volume(xyz, tets), 1000.0)
36
-
37
-
38
- def test_large_radius_equals_global_v_over_a():
39
- xyz, tets, cool, edges, elen = _cube()
40
- m = local_modulus(xyz, tets, cool, edges, elen, radii=[1e6])
41
- expected = mesh_volume(xyz, tets) / total_area(xyz, cool) # 1000/600
42
- assert m.shape == (8, 1) and np.allclose(m[:, 0], expected, rtol=1e-6)
43
-
44
-
45
- def test_no_cooling_gives_bbox_sentinel():
46
- xyz, tets, _, edges, elen = _cube()
47
- m = local_modulus(xyz, tets, np.empty((0, 3), np.int64), edges, elen, radii=[1e6])
48
- assert np.allclose(m[:, 0], np.linalg.norm(xyz.max(0) - xyz.min(0)))
49
-
50
-
51
- def test_tiny_radius_gives_sentinel():
52
- # ball = the node itself: no complete tet, no complete cooling tri -> sentinel
53
- xyz, tets, cool, edges, elen = _cube()
54
- m = local_modulus(xyz, tets, cool, edges, elen, radii=[0.1])
55
- assert np.allclose(m[:, 0], np.linalg.norm(xyz.max(0) - xyz.min(0)))
56
-
57
-
58
- def test_multiple_radii_columns_ordered():
59
- xyz, tets, cool, edges, elen = _cube()
60
- m = local_modulus(xyz, tets, cool, edges, elen, radii=[0.1, 1e6])
61
- assert m.shape == (8, 2)
62
-
63
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_mesh_cache.py DELETED
@@ -1,176 +0,0 @@
1
- import src.mesh_cache as mc
2
-
3
- def _fake_heal(calls, ok=True, n_nodes=5000):
4
- def fake(step_path, out_msh, target_nodes=8500, **kw):
5
- calls.append((step_path, target_nodes))
6
- if ok:
7
- with open(out_msh, "w") as f:
8
- f.write("MESH " + str(n_nodes))
9
- return {"ok": ok, "n_nodes": n_nodes if ok else 0, "notes": "" if ok else "boom"}
10
- return fake
11
-
12
-
13
- def _recording_heal(calls, results):
14
- """A monkeypatch fake that records the `defeature` kwarg passed on each
15
- call (`calls` accumulates dicts `{"defeature": bool}`) and returns
16
- `results[i]` for the i-th call (clamped to the last entry once
17
- exhausted) -- lets a single fake script a "fails plain, succeeds on
18
- defeature retry" sequence for the trigger-policy tests below."""
19
- def fake(step_path, out_msh, target_nodes=8500, defeature=False, **kw):
20
- idx = min(len(calls), len(results) - 1)
21
- calls.append({"defeature": defeature})
22
- r = results[idx]
23
- if r["ok"]:
24
- with open(out_msh, "w") as f:
25
- f.write("MESH " + str(r["n_nodes"]))
26
- return dict(r)
27
- return fake
28
-
29
- def test_miss_then_hit(tmp_path, monkeypatch):
30
- step = tmp_path / "part.step"; step.write_bytes(b"solid-bytes-1")
31
- calls = []
32
- monkeypatch.setattr(mc, "heal_and_mesh", _fake_heal(calls))
33
- r1 = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
34
- r2 = mc.get_or_mesh(str(step), str(tmp_path / "b.msh"), 8500, cache_dir=str(tmp_path / "c"))
35
- assert r1["cache"] == "miss" and r2["cache"] == "hit"
36
- assert len(calls) == 1 # second call never meshed
37
- assert open(tmp_path / "b.msh").read() == open(tmp_path / "a.msh").read()
38
- assert r2["n_nodes"] == 5000 and r2["pipeline_version"] == mc.MESH_PIPELINE_VERSION
39
-
40
- def test_key_changes_with_content_target_and_version(tmp_path, monkeypatch):
41
- step = tmp_path / "p.step"; step.write_bytes(b"AAA")
42
- k1 = mc.mesh_cache_key(str(step), 8500)
43
- step.write_bytes(b"BBB")
44
- k2 = mc.mesh_cache_key(str(step), 8500)
45
- k3 = mc.mesh_cache_key(str(step), 5000)
46
- monkeypatch.setattr(mc, "MESH_PIPELINE_VERSION", mc.MESH_PIPELINE_VERSION + 1)
47
- k4 = mc.mesh_cache_key(str(step), 8500)
48
- assert len({k1, k2, k3, k4}) == 4
49
-
50
- def test_failure_not_cached(tmp_path, monkeypatch):
51
- step = tmp_path / "p.step"; step.write_bytes(b"X")
52
- calls = []
53
- monkeypatch.setattr(mc, "heal_and_mesh", _fake_heal(calls, ok=False))
54
- r1 = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
55
- r2 = mc.get_or_mesh(str(step), str(tmp_path / "b.msh"), 8500, cache_dir=str(tmp_path / "c"))
56
- # `_fake_heal` (ok=False) always fails, so each of the 2 `get_or_mesh`
57
- # calls tries twice (plain, then defeature=True): 4 calls in total.
58
- assert r1["ok"] is False and r2["cache"] == "miss" and len(calls) == 4
59
-
60
- # --------------------------------------------------------------------------
61
- # size/failure auto-trigger policy for `defeature=`. Big STEP files
62
- # (>8 MiB) try defeature=True first; smaller files try plain first and retry ONCE with
63
- # defeature=True only if the plain attempt fails outright. Either way the
64
- # returned meta records which `defeature` value actually produced the
65
- # result and whether a retry happened, and the cache key is untouched by
66
- # any of this (the policy is a deterministic function of the input file,
67
- # so a given STEP always resolves to the same `defeature` choice).
68
- # --------------------------------------------------------------------------
69
- _BIG_FILE_THRESHOLD_BYTES = 8 * 1024 * 1024
70
-
71
-
72
- def test_trigger_policy_big_file_single_defeature_call(tmp_path, monkeypatch):
73
- step = tmp_path / "big.step"
74
- step.write_bytes(b"x" * (_BIG_FILE_THRESHOLD_BYTES + 1))
75
- calls = []
76
- monkeypatch.setattr(mc, "heal_and_mesh",
77
- _recording_heal(calls, [{"ok": True, "n_nodes": 999, "notes": ""}]))
78
- r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
79
- assert len(calls) == 1
80
- assert calls[0]["defeature"] is True
81
- assert r["ok"] is True and r["defeature"] is True and r["retry"] is False
82
-
83
-
84
- def test_trigger_policy_small_file_ok_plain_no_retry(tmp_path, monkeypatch):
85
- step = tmp_path / "small.step"
86
- step.write_bytes(b"tiny")
87
- calls = []
88
- monkeypatch.setattr(mc, "heal_and_mesh",
89
- _recording_heal(calls, [{"ok": True, "n_nodes": 111, "notes": ""}]))
90
- r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
91
- assert len(calls) == 1
92
- assert calls[0]["defeature"] is False
93
- assert r["ok"] is True and r["defeature"] is False and r["retry"] is False
94
-
95
-
96
- def test_trigger_policy_small_file_retries_with_defeature_on_failure(tmp_path, monkeypatch):
97
- step = tmp_path / "small.step"
98
- step.write_bytes(b"tiny")
99
- calls = []
100
- monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [
101
- {"ok": False, "n_nodes": 0, "notes": "boom"},
102
- {"ok": True, "n_nodes": 777, "notes": ""},
103
- ]))
104
- r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
105
- assert len(calls) == 2
106
- assert calls[0]["defeature"] is False
107
- assert calls[1]["defeature"] is True
108
- assert r["ok"] is True and r["defeature"] is True and r["retry"] is True
109
- assert r["n_nodes"] == 777
110
-
111
-
112
- def test_trigger_policy_big_file_defeature_fails_plain_retry_succeeds(tmp_path, monkeypatch):
113
- """Symmetric with the small-file retry: a big file's first (defeature=True)
114
- attempt can also fail outright, and must then retry ONCE with
115
- defeature=False -- not be left with a single, permanently-failed attempt.
116
- This must fail on pre-fix code (which had no big-file fallback at all)."""
117
- step = tmp_path / "big.step"
118
- step.write_bytes(b"x" * (_BIG_FILE_THRESHOLD_BYTES + 1))
119
- calls = []
120
- monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [
121
- {"ok": False, "n_nodes": 0, "notes": "boom"},
122
- {"ok": True, "n_nodes": 321, "notes": ""},
123
- ]))
124
- r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
125
- assert len(calls) == 2
126
- assert calls[0]["defeature"] is True
127
- assert calls[1]["defeature"] is False
128
- assert r["ok"] is True and r["defeature"] is False and r["retry"] is True
129
- assert r["n_nodes"] == 321
130
- assert r["cache"] == "miss"
131
- # And now it must be cached: a second call must hit, with no further heal_and_mesh calls.
132
- r2 = mc.get_or_mesh(str(step), str(tmp_path / "b.msh"), 8500, cache_dir=str(tmp_path / "c"))
133
- assert r2["cache"] == "hit" and len(calls) == 2
134
- assert r2["defeature"] is False and r2["retry"] is True
135
-
136
-
137
- def test_trigger_policy_small_file_fails_both_attempts_no_extra_retry(tmp_path, monkeypatch):
138
- """Even if the defeature retry also fails, `get_or_mesh` must not retry
139
- a third time -- exactly one retry, ever."""
140
- step = tmp_path / "small.step"
141
- step.write_bytes(b"tiny")
142
- calls = []
143
- monkeypatch.setattr(mc, "heal_and_mesh", _recording_heal(calls, [
144
- {"ok": False, "n_nodes": 0, "notes": "boom1"},
145
- {"ok": False, "n_nodes": 0, "notes": "boom2"},
146
- ]))
147
- r = mc.get_or_mesh(str(step), str(tmp_path / "a.msh"), 8500, cache_dir=str(tmp_path / "c"))
148
- assert len(calls) == 2
149
- assert r["ok"] is False and r["defeature"] is True and r["retry"] is True
150
- assert r["cache"] == "miss"
151
-
152
-
153
- def test_tmp_names_are_unique_per_writer(tmp_path):
154
- # Two concurrent workers racing on the SAME cache miss must never derive
155
- # the same tmp path from the same final path -- otherwise their writes
156
- # could interleave on one inode before either os.replace runs, and
157
- # os.replace would then install a corrupted mesh for every later hit.
158
- final = str(tmp_path / "c" / "somekey.msh")
159
- tmp_a = mc._unique_tmp_path(final)
160
- tmp_b = mc._unique_tmp_path(final)
161
- assert tmp_a != tmp_b
162
- assert tmp_a != final + ".tmp" and tmp_b != final + ".tmp" # no fixed shared name
163
-
164
-
165
- def test_pipeline_version_pinned_to_3():
166
- assert mc.MESH_PIPELINE_VERSION == 3
167
-
168
-
169
-
170
-
171
-
172
-
173
-
174
-
175
-
176
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_meshing.py DELETED
@@ -1,443 +0,0 @@
1
- from pathlib import Path
2
-
3
- import numpy as np
4
- import pytest
5
-
6
- import src.meshing as pp
7
- from src.meshing import (
8
- heal_and_mesh, _elem_size_from_area, _elem_size,
9
- _first_guess_elem_size, K_SURF,
10
- )
11
- from src.msh_parse import parse_msh
12
-
13
-
14
- def _make_one_box_step(path, dx=30.0, dy=20.0, dz=10.0):
15
- import gmsh
16
- gmsh.initialize()
17
- try:
18
- gmsh.option.setNumber("General.Terminal", 0)
19
- gmsh.model.add("box")
20
- gmsh.model.occ.addBox(0, 0, 0, dx, dy, dz)
21
- gmsh.model.occ.synchronize()
22
- gmsh.write(str(path))
23
- finally:
24
- gmsh.finalize()
25
-
26
-
27
- def _make_two_box_step(path, big=40.0, small=10.0):
28
- """A synthetic 2-solid STEP: one `big`^3 box and one `small`^3 box,
29
- positioned so they don't touch (kept as two separate OCC solids)."""
30
- import gmsh
31
- gmsh.initialize()
32
- try:
33
- gmsh.option.setNumber("General.Terminal", 0)
34
- gmsh.model.add("two_box")
35
- gmsh.model.occ.addBox(0, 0, 0, big, big, big)
36
- gmsh.model.occ.addBox(big + 100, 0, 0, small, small, small)
37
- gmsh.model.occ.synchronize()
38
- gmsh.write(str(path))
39
- finally:
40
- gmsh.finalize()
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
- # --------------------------------------------------------------------------
54
- # Surface-area density-search seed: the first element size comes from the
55
- # OCC surface area of the imported model (`_elem_size_from_area`, via
56
- # `_first_guess_elem_size`), with bbox_diag/28 as the fallback.
57
- # --------------------------------------------------------------------------
58
- def test_elem_size_from_area_matches_formula():
59
- area_mm2, target_nodes = 2200.0, 500
60
- expected = np.sqrt(K_SURF * area_mm2 / target_nodes)
61
- assert _elem_size_from_area(area_mm2, target_nodes) == pytest.approx(expected)
62
-
63
-
64
- def test_heal_and_mesh_area_seed_converges_on_first_attempt(tmp_path):
65
- """The calibrated K_SURF must make the 30x20x10mm box @ target_nodes=500
66
- converge within the +-35% band on the FIRST density-search attempt (no
67
- refinement rounds needed) -- this is the whole point of seeding from
68
- the OCC surface area instead of bbox_diag/28, which missed this same
69
- fixture badly (see the multi-round test below, forced via a bad
70
- monkeypatched K_SURF)."""
71
- step = tmp_path / "box.step"
72
- _make_one_box_step(step, 30, 20, 10)
73
-
74
- out_msh = tmp_path / "box.msh"
75
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
76
-
77
- assert result["ok"] is True
78
- assert result["attempts"] == 1
79
- assert 500 * 0.65 <= result["n_nodes"] <= 500 * 1.35
80
-
81
-
82
- def test_first_guess_elem_size_falls_back_when_area_query_raises(monkeypatch):
83
- """If the OCC surface-area query raises, `_first_guess_elem_size` must
84
- fall back to the bbox_diag/28 heuristic rather than propagating the
85
- exception."""
86
- def _boom():
87
- raise RuntimeError("simulated gmsh area-query failure")
88
-
89
- monkeypatch.setattr(pp, "_total_surface_area_mm2", _boom)
90
-
91
- bbox_diag_mm = 37.4
92
- assert _first_guess_elem_size(bbox_diag_mm, 500) == pytest.approx(_elem_size(bbox_diag_mm))
93
-
94
-
95
- def test_first_guess_elem_size_falls_back_when_area_nonpositive(monkeypatch):
96
- """If the OCC surface-area query returns <= 0 (no exception, just a
97
- degenerate/empty answer), `_first_guess_elem_size` must fall back to
98
- the bbox_diag/28 heuristic rather than dividing by (or sqrt-ing) a
99
- non-positive area."""
100
- monkeypatch.setattr(pp, "_total_surface_area_mm2", lambda: 0.0)
101
-
102
- bbox_diag_mm = 37.4
103
- assert _first_guess_elem_size(bbox_diag_mm, 500) == pytest.approx(_elem_size(bbox_diag_mm))
104
-
105
-
106
- # --------------------------------------------------------------------------
107
- # Heal-only-as-fallback regression tests (guards the bug fixed in 5220dbc:
108
- # `healShapes()` can run without raising and still silently destroy the
109
- # solid -- monkeypatched, deterministic, no real-part meshing).
110
- # --------------------------------------------------------------------------
111
- def test_heal_and_mesh_clean_part_never_calls_heal(tmp_path, monkeypatch):
112
- """A part that meshes fine on pass 1 must never invoke `_apply_heal` --
113
- this is the exact regression found in commit 5220dbc, where
114
- `healShapes()` was called unconditionally and silently reduced a
115
- perfectly meshable solid to 0 volume entities."""
116
- step = tmp_path / "box.step"
117
- _make_one_box_step(step, 30, 20, 10)
118
-
119
- def _boom():
120
- raise AssertionError("_apply_heal must not be called when pass 1 succeeds")
121
-
122
- monkeypatch.setattr(pp, "_apply_heal", _boom)
123
-
124
- out_msh = tmp_path / "box.msh"
125
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
126
- assert result["ok"] is True
127
- assert result["healed"] is False
128
-
129
-
130
- def test_heal_and_mesh_ineffective_heal_reported_as_failed(tmp_path, monkeypatch):
131
- """If pass 1's mesh attempt fails and the pass-2 heal runs but does NOT
132
- yield a volume (the historical bug: `healShapes()` silently zeroing out
133
- the solid), `heal_and_mesh` must (a) actually attempt the heal, and
134
- (b) report ok=False / healed=False -- never silently accept a heal
135
- that produced no usable geometry."""
136
- step = tmp_path / "box.step"
137
- _make_one_box_step(step, 30, 20, 10)
138
-
139
- monkeypatch.setattr(pp, "_tag_and_mesh",
140
- lambda size, out_msh: (False, 0, "simulated mesh failure"))
141
-
142
- heal_calls = []
143
-
144
- def _fake_heal():
145
- heal_calls.append(1)
146
- return False, "simulated heal ineffective (0 volumes)"
147
-
148
- monkeypatch.setattr(pp, "_apply_heal", _fake_heal)
149
-
150
- out_msh = tmp_path / "box.msh"
151
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
152
-
153
- assert len(heal_calls) == 1 # (a) heal WAS attempted after pass-1 failure
154
- assert result["ok"] is False # (b) not silently accepted
155
- assert result["healed"] is False
156
- assert "simulated heal ineffective" in result["notes"]
157
- assert not out_msh.exists()
158
-
159
-
160
- def test_heal_and_mesh_effective_heal_then_succeeds(tmp_path, monkeypatch):
161
- """If pass 1 fails but the pass-2 heal IS effective, pass 2 should
162
- retry meshing and succeed (ok=True, healed=True)."""
163
- step = tmp_path / "box.step"
164
- _make_one_box_step(step, 30, 20, 10)
165
-
166
- calls = {"n": 0}
167
-
168
- def _fake_tag_and_mesh(size, out_msh):
169
- calls["n"] += 1
170
- if calls["n"] == 1:
171
- return False, 0, "simulated pass-1 failure"
172
- Path(out_msh).write_text("fake mesh")
173
- return True, 777, ""
174
-
175
- monkeypatch.setattr(pp, "_tag_and_mesh", _fake_tag_and_mesh)
176
- monkeypatch.setattr(pp, "_apply_heal", lambda: (True, ""))
177
-
178
- out_msh = tmp_path / "box.msh"
179
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=777)
180
-
181
- assert calls["n"] >= 2
182
- assert result["ok"] is True
183
- assert result["healed"] is True
184
- assert result["n_nodes"] == 777
185
-
186
-
187
- # --------------------------------------------------------------------------
188
- # Untagged-mesh regression: `_tag_and_mesh` can run more than once within a single gmsh session (density-search
189
- # retries) -- `removePhysicalGroups()` frees the *tag number* but not the
190
- # *name registration*, so on the 2nd+ call an auto-assigned new tag number
191
- # silently fails to bind "Volume"/"Cooling" again. The fix pins explicit
192
- # tag numbers (`_VOLUME_PHYS_TAG`/`_COOLING_PHYS_TAG`) across every call in
193
- # a session, plus a loud-fail guard in case the binding fails for any other
194
- # reason.
195
- # --------------------------------------------------------------------------
196
- def test_heal_and_mesh_multi_round_density_search_keeps_tags(tmp_path, monkeypatch):
197
- """A part whose first-attempt guess misses `target_nodes` by more than
198
- the 35% early-exit tolerance forces `_search_target_nodes` into
199
- `_search_elem_size`'s multi-round refinement -- i.e. `_tag_and_mesh` runs
200
- MORE THAN ONCE in the same gmsh session (verified during triage:
201
- without the tag-pinning fix, this reliably ends with an untagged mesh
202
- -- `parse_msh(...).tris == {}` -- because only the FIRST round's
203
- physical names actually bind). This test's purpose is that TAG
204
- behavior, not seed quality -- since the calibrated K_SURF now makes
205
- this exact 30x20x10 @ target_nodes=500 fixture converge in ONE attempt
206
- (see `test_heal_and_mesh_area_seed_converges_on_first_attempt` above),
207
- K_SURF is monkeypatched to a deliberately bad value (50.0, which misses
208
- this fixture by >90%) purely to force the
209
- multi-round path back open. Regardless of how many rounds ran, the
210
- final written mesh must have a nonempty "Cooling" surface group and a
211
- nonempty tet volume."""
212
- step = tmp_path / "box.step"
213
- _make_one_box_step(step, 30, 20, 10)
214
-
215
- monkeypatch.setattr(pp, "K_SURF", 50.0)
216
-
217
- calls = []
218
- orig_tag_and_mesh = pp._tag_and_mesh
219
-
220
- def _counting(size, out_msh):
221
- calls.append(size)
222
- return orig_tag_and_mesh(size, out_msh)
223
-
224
- monkeypatch.setattr(pp, "_tag_and_mesh", _counting)
225
-
226
- out_msh = tmp_path / "box.msh"
227
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
228
-
229
- assert len(calls) >= 2, "test setup must force a multi-round density search"
230
- assert result["ok"] is True
231
-
232
- mesh = parse_msh(str(out_msh))
233
- assert "Cooling" in mesh.tris
234
- assert mesh.tris["Cooling"].shape[0] > 0
235
- assert mesh.tets.shape[0] > 0
236
-
237
-
238
-
239
-
240
-
241
-
242
- def test_fast_options_not_applied_in_plain_session():
243
- """A plain fresh gmsh session (nothing fast-related called) must show
244
- gmsh's own, un-touched default for Mesh.Algorithm3D -- never HXT (10).
245
- Read BEFORE any fast call so this session can't have been polluted by
246
- another test in the same process."""
247
- import gmsh
248
-
249
- gmsh.initialize()
250
- try:
251
- gmsh.option.setNumber("General.Terminal", 0)
252
- algo = gmsh.option.getNumber("Mesh.Algorithm3D")
253
- assert algo != 10
254
- assert algo == 1 # gmsh's documented default (classical Delaunay)
255
- finally:
256
- gmsh.finalize()
257
-
258
-
259
-
260
-
261
- # --------------------------------------------------------------------------
262
- # Defeaturing pass: `removeAllDuplicates()`, enabled via `defeature=` and
263
- # off by default.
264
- # --------------------------------------------------------------------------
265
- def test_heal_and_mesh_defeature_true_synthetic_box(tmp_path):
266
- """defeature=True on a clean box must still succeed with a nonempty
267
- "Cooling" surface group and tet volume -- defeaturing a clean part must
268
- not break the Volume/Cooling tag guarantee."""
269
- step = tmp_path / "box.step"
270
- _make_one_box_step(step, 30, 20, 10)
271
-
272
- out_msh = tmp_path / "box.msh"
273
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500, defeature=True)
274
-
275
- assert result["ok"] is True
276
- assert result["n_nodes"] > 0
277
-
278
- mesh = parse_msh(str(out_msh))
279
- assert "Cooling" in mesh.tris
280
- assert mesh.tris["Cooling"].shape[0] > 0
281
- assert mesh.tets.shape[0] > 0
282
-
283
-
284
- def test_heal_and_mesh_defeature_true_calls_apply_defeature(tmp_path, monkeypatch):
285
- """defeature=True must actually invoke `_apply_defeature` (in pass 1)."""
286
- step = tmp_path / "box.step"
287
- _make_one_box_step(step, 30, 20, 10)
288
-
289
- calls = []
290
- orig = pp._apply_defeature
291
-
292
- def _wrap():
293
- calls.append(1)
294
- return orig()
295
-
296
- monkeypatch.setattr(pp, "_apply_defeature", _wrap)
297
-
298
- out_msh = tmp_path / "box.msh"
299
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500, defeature=True)
300
-
301
- assert len(calls) >= 1
302
- assert result["ok"] is True
303
-
304
-
305
- def test_heal_and_mesh_destructive_defeature_returns_ok_false_not_a_crash(tmp_path, monkeypatch):
306
- """If `_apply_defeature`
307
- reports the solid was lost (ok=False), `heal_and_mesh` must branch on
308
- that and return a clean `ok=False` dict with the solid-loss note --
309
- NOT fall through to `gmsh.model.getBoundingBox(-1, -1)` on an empty
310
- model, which raises an uncaught `Exception: Empty bounding box`."""
311
- step = tmp_path / "box.step"
312
- _make_one_box_step(step, 30, 20, 10)
313
-
314
- monkeypatch.setattr(pp, "_apply_defeature",
315
- lambda: (False, "defeature (removeAllDuplicates) yielded 0 volume entities"))
316
-
317
- out_msh = tmp_path / "box.msh"
318
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500, defeature=True)
319
-
320
- assert result["ok"] is False
321
- assert "0 volume entities" in result["notes"]
322
- assert not out_msh.exists()
323
-
324
-
325
- def test_heal_and_mesh_defeature_default_never_calls_apply_defeature(tmp_path, monkeypatch):
326
- """`defeature` defaults to False -- `heal_and_mesh` must not invoke
327
- `_apply_defeature` at all in that case (zero behavior change from
328
- before this flag existed)."""
329
- step = tmp_path / "box.step"
330
- _make_one_box_step(step, 30, 20, 10)
331
-
332
- def _boom():
333
- raise AssertionError("_apply_defeature must not be called when defeature=False (default)")
334
-
335
- monkeypatch.setattr(pp, "_apply_defeature", _boom)
336
-
337
- out_msh = tmp_path / "box.msh"
338
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
339
- assert result["ok"] is True
340
-
341
-
342
- def test_apply_defeature_removes_duplicates_without_losing_solid():
343
- """Direct test of `_apply_defeature()` inside an initialized gmsh
344
- session: runs cleanly on a plain box and does not destroy the solid."""
345
- import gmsh
346
-
347
- gmsh.initialize()
348
- try:
349
- gmsh.option.setNumber("General.Terminal", 0)
350
- gmsh.model.add("box")
351
- gmsh.model.occ.addBox(0, 0, 0, 30, 20, 10)
352
- gmsh.model.occ.synchronize()
353
- ok, note = pp._apply_defeature()
354
- assert ok is True
355
- assert note == ""
356
- assert len(gmsh.model.getEntities(3)) == 1
357
- finally:
358
- gmsh.finalize()
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
-
370
-
371
- def test_tag_and_mesh_fails_loudly_when_name_binding_missing(tmp_path, monkeypatch):
372
- """Direct regression test for the loud-fail guard itself: if gmsh ever
373
- fails to bind the "Volume"/"Cooling" physical-group names (the exact
374
- silent failure that once produced an untagged mesh), `_tag_and_mesh`
375
- must return ok=False and must NOT write `out_msh` -- never silently
376
- hand back an untagged mesh."""
377
- import gmsh
378
-
379
- step = tmp_path / "box.step"
380
- _make_one_box_step(step, 30, 20, 10)
381
-
382
- gmsh.initialize()
383
- try:
384
- gmsh.option.setNumber("General.Terminal", 0)
385
- gmsh.model.add("box")
386
- gmsh.model.occ.importShapes(str(step))
387
- gmsh.model.occ.synchronize()
388
-
389
- monkeypatch.setattr(gmsh.model, "getPhysicalName", lambda dim, tag: "")
390
-
391
- out_msh = tmp_path / "box.msh"
392
- ok, n_nodes, note = pp._tag_and_mesh(2.0, str(out_msh))
393
-
394
- assert ok is False
395
- assert n_nodes == 0
396
- assert "name binding missing" in note
397
- assert not out_msh.exists()
398
- finally:
399
- gmsh.finalize()
400
-
401
-
402
-
403
- def test_heal_and_mesh_synthetic_box(tmp_path):
404
- """A small synthetic box runs the import + mesh + tag pipeline end to end."""
405
- step = tmp_path / "box.step"
406
- _make_one_box_step(step)
407
- out_msh = tmp_path / "box.msh"
408
- result = heal_and_mesh(str(step), str(out_msh), target_nodes=500)
409
-
410
- assert result["ok"] is True
411
- assert result["n_solids"] == 1
412
- assert result["n_nodes"] > 0
413
- assert result["volume_mm3"] == pytest.approx(30 * 20 * 10, rel=1e-2)
414
- assert np.isfinite(result["bbox_diag_mm"]) and result["bbox_diag_mm"] > 0
415
- mesh = parse_msh(str(out_msh))
416
- assert set(mesh.tris) == {"Cooling"} and mesh.tets.shape[0] > 0
417
-
418
-
419
- def test_heal_and_mesh_keeps_largest_of_two_solids(tmp_path):
420
- step = tmp_path / "two.step"
421
- import gmsh
422
- gmsh.initialize()
423
- try:
424
- gmsh.option.setNumber("General.Terminal", 0)
425
- gmsh.model.add("two_box")
426
- gmsh.model.occ.addBox(0, 0, 0, 40, 40, 40)
427
- gmsh.model.occ.addBox(140, 0, 0, 10, 10, 10)
428
- gmsh.model.occ.synchronize()
429
- gmsh.write(str(step))
430
- finally:
431
- gmsh.finalize()
432
- result = heal_and_mesh(str(step), str(tmp_path / "two.msh"), target_nodes=500)
433
- assert result["ok"] is True and result["n_solids"] == 2
434
- assert result["volume_mm3"] == pytest.approx(40 ** 3, rel=1e-2)
435
- assert "kept largest of 2 solids" in result["notes"]
436
-
437
-
438
- def test_mesh_step_fixed_size(tmp_path):
439
- step = tmp_path / "box.step"
440
- _make_one_box_step(step)
441
- info = pp.mesh_step(str(step), str(tmp_path / "fixed.msh"), elem_size=5.0)
442
- assert info["elem_size"] == 5.0 and info["n_nodes"] > 0 and info["n_tets"] > 0
443
- assert set(parse_msh(str(tmp_path / "fixed.msh")).tris) == {"Cooling"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_model_api.py DELETED
@@ -1,25 +0,0 @@
1
- """CastSolidModel: mesh in, per-node seconds out (needs the published weights)."""
2
- import os
3
-
4
- import numpy as np
5
- import pytest
6
-
7
- from src.model_api import CastSolidModel
8
-
9
- WEIGHTS = "weights/gnn_v5.1.safetensors"
10
-
11
-
12
- def test_hotspots_matches_top_fraction():
13
- t = np.arange(100, dtype=np.float32)
14
- mask = CastSolidModel.hotspots(t)
15
- assert mask.sum() == 10 and mask[-10:].all()
16
-
17
-
18
- @pytest.mark.skipif(not os.path.exists(WEIGHTS), reason="published weights not present")
19
- def test_predict_on_mesh(mini_msh_file):
20
- model = CastSolidModel(device="cpu")
21
- t_iron = model.predict(mini_msh_file)
22
- t_steel = model.predict(mini_msh_file, alloy="G20Mn5")
23
- assert t_iron.shape == t_steel.shape and t_iron.ndim == 1
24
- assert np.all(np.isfinite(t_iron)) and np.all(t_iron >= 0)
25
- assert not np.allclose(t_iron, t_steel)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_model_gnn.py DELETED
@@ -1,66 +0,0 @@
1
- import numpy as np
2
- import torch
3
-
4
- from src.model_gnn import (SolidGNN, knn_edge_index, load_gnn, predict_graph_seconds,
5
- union_edge_attr, union_edge_index)
6
-
7
- CFG = {"node_in": 15, "edge_in": 5, "hidden": 16, "n_blocks": 2, "g_dim": 5, "k": 4}
8
-
9
-
10
- def _norm():
11
- return {"feat_mean": np.zeros(15, np.float32), "feat_std": np.ones(15, np.float32),
12
- "y_log_mean": 3.0, "y_log_std": 0.5}
13
-
14
-
15
- def _state(seed=0):
16
- torch.manual_seed(seed)
17
- model = SolidGNN(node_in=15, edge_in=5, hidden=16, n_blocks=2)
18
- return {"model": model.state_dict(), "norm": _norm(), "cfg": CFG}
19
-
20
-
21
- def test_knn_edges_are_symmetric():
22
- pos = torch.rand(30, 3)
23
- ei = knn_edge_index(pos, k=4)
24
- pairs = set(map(tuple, ei.t().tolist()))
25
- assert all((b, a) in pairs for a, b in pairs)
26
-
27
-
28
- def test_union_graph_contains_mesh_edges_and_flags_them():
29
- pos = torch.rand(20, 3)
30
- mesh_edges = torch.tensor([[0, 19], [3, 7]])
31
- ei, is_mesh = union_edge_index(pos, mesh_edges, k=3)
32
- pairs = {tuple(p): f for p, f in zip(ei.t().tolist(), is_mesh.tolist())}
33
- for a, b in [(0, 19), (19, 0), (3, 7), (7, 3)]:
34
- assert pairs[(a, b)] == 1.0
35
- assert len(pairs) == ei.shape[1] # no duplicates
36
- ea = union_edge_attr(pos, ei, is_mesh)
37
- assert ea.shape == (ei.shape[1], 5)
38
- src, dst = ei
39
- np.testing.assert_allclose(ea[:, 3], (pos[dst] - pos[src]).norm(dim=1), rtol=1e-6)
40
-
41
-
42
- def test_film_conditioning_changes_output():
43
- model, cfg, norm = load_gnn(_state(), "cpu")
44
- with torch.no_grad():
45
- for film in model.films: # make FiLM non-trivial
46
- film.net[-1].weight.normal_(0, 0.5)
47
- rng = np.random.default_rng(0)
48
- X, pos = rng.normal(size=(25, 15)), rng.uniform(0, 50, size=(25, 3))
49
- edges = np.array([[0, 1], [1, 2], [2, 3]])
50
- a = predict_graph_seconds(model, cfg, norm, X, pos, edges, np.zeros(5))
51
- b = predict_graph_seconds(model, cfg, norm, X, pos, edges, np.ones(5))
52
- assert a.shape == (25,) and np.all(a >= 0)
53
- assert not np.allclose(a, b)
54
-
55
-
56
- def test_prediction_ignores_node_order():
57
- model, cfg, norm = load_gnn(_state(1), "cpu")
58
- rng = np.random.default_rng(1)
59
- X, pos = rng.normal(size=(25, 15)), rng.uniform(0, 50, size=(25, 3))
60
- edges = np.array([[0, 1], [1, 2], [5, 9]])
61
- g = rng.normal(size=5)
62
- a = predict_graph_seconds(model, cfg, norm, X, pos, edges, g)
63
- perm = rng.permutation(25)
64
- inv = np.argsort(perm)
65
- b = predict_graph_seconds(model, cfg, norm, X[perm], pos[perm], inv[edges], g)
66
- np.testing.assert_allclose(a[perm], b, rtol=1e-4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_msh_parse.py DELETED
@@ -1,22 +0,0 @@
1
- import numpy as np
2
- from src.msh_parse import parse_msh
3
-
4
-
5
- def test_parse_mini(mini_msh_file):
6
- mesh = parse_msh(mini_msh_file)
7
-
8
- # 5 nodes, in id order, in mm
9
- assert mesh.node_xyz.shape == (5, 3)
10
- np.testing.assert_allclose(mesh.node_xyz[0], [0, 0, 0])
11
- np.testing.assert_allclose(mesh.node_xyz[4], [3, 3, 3])
12
-
13
- # physical groups present, 0-based indices
14
- assert set(mesh.tris.keys()) == {"Cooling", "Adiabatic"}
15
- assert mesh.tris["Cooling"].shape == (2, 3)
16
- assert mesh.tris["Adiabatic"].shape == (1, 3)
17
- # cooling triangle 1 = nodes 1,2,3 (ids) -> indices 0,1,2
18
- np.testing.assert_array_equal(sorted(mesh.tris["Cooling"][0]), [0, 1, 2])
19
-
20
- # one tetrahedron, 0-based
21
- assert mesh.tets.shape == (1, 4)
22
- np.testing.assert_array_equal(sorted(mesh.tets[0]), [0, 1, 2, 3])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_ood.py DELETED
@@ -1,19 +0,0 @@
1
- import json
2
-
3
- from src.ood import load_ranges, ood_flags
4
-
5
- RANGES = {"volume_mm3_max": 400.0, "bbox_diag_max": 69.3, "geodesic_d_cool_max": 9.0}
6
-
7
-
8
- def test_load_ranges(tmp_path):
9
- p = tmp_path / "ood.json"
10
- p.write_text(json.dumps(RANGES))
11
- assert load_ranges(str(p)) == RANGES
12
-
13
-
14
- def test_flags_only_beyond_tolerance():
15
- assert ood_flags(400.0, 69.3, 9.0, RANGES) == []
16
- assert ood_flags(410.0, 70.0, 9.3, RANGES) == [] # within the 5% tolerance
17
- w = ood_flags(1000.0, 200.0, 30.0, RANGES)
18
- assert len(w) == 3
19
- assert "volume" in w[0] and "bounding-box" in w[1] and "distance-to-cooling" in w[2]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_predict_casting.py DELETED
@@ -1,106 +0,0 @@
1
- """predict_casting orchestration with meshing and the model replaced by fakes,
2
- plus an end-to-end run on a synthetic STEP when the weights are present."""
3
- import os
4
- import shutil
5
-
6
- import meshio
7
- import numpy as np
8
- import pytest
9
-
10
- import src.predict_casting as pc
11
- from src.features import FEATURE_NAMES
12
- from src.msh_parse import parse_msh
13
-
14
-
15
- class _FakeModel:
16
- def predict_with_props(self, mesh, props):
17
- n = mesh.node_xyz.shape[0]
18
- X = np.zeros((n, len(FEATURE_NAMES)), np.float32)
19
- X[:, FEATURE_NAMES.index("volume_mm3")] = 1000.0 / 6.0
20
- seconds = np.arange(n, dtype=np.float64) + 1.0
21
- info = {"a": 1.0, "m": 0.0, "target_unreachable": False, "clip_frac": 0.0,
22
- "total_deviation_frac": 0.0}
23
- return seconds, {"X": X, "total_s": float(n), "spread_s": 1.0, "recomposition": info}
24
-
25
-
26
- def _fake_get_or_mesh(mini_msh_file, calls):
27
- def _fn(step_path, out_msh, target_nodes=None, cache_dir=None):
28
- calls.append(target_nodes)
29
- shutil.copy(mini_msh_file, out_msh)
30
- return {"ok": True, "n_nodes": 5, "cache": "miss"}
31
- return _fn
32
-
33
-
34
- def test_writes_vtu_and_summary(monkeypatch, mini_msh_file, tmp_path):
35
- calls = []
36
- monkeypatch.setattr(pc, "get_or_mesh", _fake_get_or_mesh(mini_msh_file, calls))
37
- r = pc.predict_casting("part.step", out_dir=str(tmp_path), model=_FakeModel(),
38
- ood_json="missing.json")
39
- assert calls == [pc.DEFAULT_TARGET_NODES]
40
- assert r["total_time_s"] == 5.0 and r["n_nodes"] == 5
41
- assert r["hotspot_xyz"].shape == (5, 3)
42
- vtu = meshio.read(r["vtu"])
43
- assert {"solidification_time", "hotspot", "niyama", "porosity_risk",
44
- "macro_region_id"} <= set(vtu.point_data)
45
- text = open(r["summary"]).read()
46
- assert "total solidification time: 5.0 s" in text
47
- assert "alloy: EN-GJS-400-15 mold: green_sand model: v5.1" in text
48
- assert "shrinkage screening:" in text
49
- assert r["shrinkage"]["niyama_source"] == "proxy"
50
-
51
-
52
- def test_bad_alloy_fails_before_meshing(monkeypatch, tmp_path):
53
- def boom(*a, **k):
54
- raise AssertionError("meshing must not run")
55
- monkeypatch.setattr(pc, "get_or_mesh", boom)
56
- with pytest.raises(ValueError, match="unknown alloy"):
57
- pc.predict_casting("part.step", out_dir=str(tmp_path), alloy="nope",
58
- model=_FakeModel())
59
-
60
-
61
- def test_no_shrinkage_and_ood_warning(monkeypatch, mini_msh_file, tmp_path):
62
- monkeypatch.setattr(pc, "get_or_mesh", _fake_get_or_mesh(mini_msh_file, []))
63
- ood = tmp_path / "ood.json"
64
- ood.write_text('{"volume_mm3_max": 1.0, "bbox_diag_max": 1000.0, '
65
- '"geodesic_d_cool_max": 1000.0}')
66
- r = pc.predict_casting("part.step", out_dir=str(tmp_path), model=_FakeModel(),
67
- screen_shrinkage=False, ood_json=str(ood))
68
- assert r["shrinkage"] is None
69
- assert len(r["ood_warnings"]) == 1 and "volume" in r["ood_warnings"][0]
70
- assert "porosity_risk" not in meshio.read(r["vtu"]).point_data
71
-
72
-
73
- def test_elem_size_and_target_nodes_are_exclusive(tmp_path):
74
- with pytest.raises(ValueError):
75
- pc.predict_casting("part.step", out_dir=str(tmp_path), elem_size=4.0,
76
- target_nodes=9000, model=_FakeModel())
77
-
78
-
79
- def test_parse_gravity():
80
- assert pc._parse_gravity("0, 0, -1") == (0.0, 0.0, -1.0)
81
- for bad in ("1,2", "0,0,0", "a,b,c"):
82
- with pytest.raises(ValueError):
83
- pc._parse_gravity(bad)
84
-
85
-
86
- @pytest.mark.skipif(not os.path.exists("weights/gnn_v5.1.safetensors"),
87
- reason="published weights not present")
88
- def test_end_to_end_on_a_box(tmp_path):
89
- import gmsh
90
- step = tmp_path / "box.step"
91
- gmsh.initialize()
92
- try:
93
- gmsh.option.setNumber("General.Terminal", 0)
94
- gmsh.model.add("box")
95
- gmsh.model.occ.addBox(0, 0, 0, 120, 80, 40)
96
- gmsh.model.occ.synchronize()
97
- gmsh.write(str(step))
98
- finally:
99
- gmsh.finalize()
100
- r = pc.predict_casting(str(step), out_dir=str(tmp_path / "out"),
101
- cache_dir=str(tmp_path / "cache"), device="cpu")
102
- t = meshio.read(r["vtu"]).point_data["solidification_time"]
103
- assert np.all(np.isfinite(t)) and t.min() >= 0 and r["total_time_s"] > 0
104
- assert set(parse_msh(r["msh"]).tris) == {"Cooling"}
105
- # the hottest point of a box sits near its centre
106
- assert np.linalg.norm(r["hotspot_xyz"][0] - np.array([60, 40, 20])) < 25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_release_io.py DELETED
@@ -1,55 +0,0 @@
1
- import collections
2
- import json
3
-
4
- import numpy as np
5
- import pytest
6
- import torch
7
- from safetensors.torch import save_file
8
-
9
- from src import release_io as rio
10
-
11
-
12
- def _write_gnn(path, fmt=rio.GNN_FORMAT):
13
- tensors = {"model.w": torch.arange(6, dtype=torch.float32).reshape(2, 3),
14
- "norm.feat_mean": torch.from_numpy(np.arange(3, dtype=np.float32))}
15
- meta = {"format": fmt, "cfg": json.dumps({"hidden": 16, "k": 4}),
16
- "norm_kinds": json.dumps({"feat_mean": "numpy"}),
17
- "norm_scalars": json.dumps({"y_log_mean": 3.5})}
18
- save_file(tensors, str(path), metadata=meta)
19
-
20
-
21
- def test_load_gnn_state(tmp_path):
22
- p = tmp_path / "gnn.safetensors"
23
- _write_gnn(p)
24
- state = rio.load_gnn_state(str(p))
25
- assert state["cfg"] == {"hidden": 16, "k": 4}
26
- assert torch.equal(state["model"]["w"], torch.arange(6, dtype=torch.float32).reshape(2, 3))
27
- assert isinstance(state["norm"]["feat_mean"], np.ndarray)
28
- assert state["norm"]["feat_mean"].dtype == np.float32
29
- assert state["norm"]["y_log_mean"] == 3.5
30
-
31
-
32
- def test_load_gnn_state_rejects_other_files(tmp_path):
33
- p = tmp_path / "other.safetensors"
34
- _write_gnn(p, fmt="something-else")
35
- with pytest.raises(ValueError, match="not a"):
36
- rio.load_gnn_state(str(p))
37
-
38
-
39
- def test_load_gbm_roundtrip(tmp_path):
40
- skops = pytest.importorskip("skops.io")
41
- from sklearn.ensemble import HistGradientBoostingRegressor
42
- rng = np.random.default_rng(0)
43
- X, y = rng.normal(size=(200, 4)), rng.normal(size=200)
44
- m = HistGradientBoostingRegressor(max_iter=20).fit(X, y)
45
- p = tmp_path / "gbm.skops"
46
- skops.dump(m, str(p))
47
- np.testing.assert_array_equal(rio.load_gbm(p).predict(X), m.predict(X))
48
-
49
-
50
- def test_load_gbm_refuses_foreign_types(tmp_path):
51
- skops = pytest.importorskip("skops.io")
52
- p = tmp_path / "bad.skops"
53
- skops.dump({"c": collections.Counter(a=1)}, str(p))
54
- with pytest.raises(ValueError, match="unexpected types"):
55
- rio.load_gbm(p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_shrinkage.py DELETED
@@ -1,1186 +0,0 @@
1
- import numpy as np
2
- import pytest
3
-
4
- from src.shrinkage import (
5
- node_gradient, niyama_proxy, porosity_risk,
6
- hot_regions, is_fed, macro_shrinkage, top_sinks, feeder_recommendations,
7
- SHRINKAGE_PCT, screen_casting, _boundary_faces,
8
- )
9
-
10
-
11
- # ---------------------------------------------------------------------------
12
- # Structured tet-grid helpers -- a Kuhn/Freudenthal 6-tet-per-cube
13
- # decomposition of a regular nx*ny*nz node lattice (unit spacing unless
14
- # overridden). This is a conforming triangulation (verified numerically: tet
15
- # volumes sum exactly to the lattice bounding volume, and internal faces
16
- # between adjacent cubes cancel out of the boundary-surface-area count),
17
- # reused across the region/sink/feeder tests below.
18
- # ---------------------------------------------------------------------------
19
-
20
- _KUHN_TETS = [(0, 1, 3, 7), (0, 1, 5, 7), (0, 4, 5, 7),
21
- (0, 2, 3, 7), (0, 2, 6, 7), (0, 4, 6, 7)]
22
-
23
-
24
- def _node_idx(nx, ny):
25
- return lambda i, j, k: i + j * nx + k * nx * ny
26
-
27
-
28
- def _grid_mesh(nx, ny, nz, spacing=1.0):
29
- idx = _node_idx(nx, ny)
30
- pos = np.zeros((nx * ny * nz, 3))
31
- for k in range(nz):
32
- for j in range(ny):
33
- for i in range(nx):
34
- pos[idx(i, j, k)] = [i * spacing, j * spacing, k * spacing]
35
-
36
- def local(i, j, k, bit):
37
- dx, dy, dz = bit & 1, (bit >> 1) & 1, (bit >> 2) & 1
38
- return idx(i + dx, j + dy, k + dz)
39
-
40
- tets = []
41
- for k in range(nz - 1):
42
- for j in range(ny - 1):
43
- for i in range(nx - 1):
44
- for t in _KUHN_TETS:
45
- tets.append([local(i, j, k, b) for b in t])
46
- return pos, np.array(tets, dtype=np.int64)
47
-
48
-
49
- def _surface_nodes(nx, ny, nz):
50
- idx = _node_idx(nx, ny)
51
- nodes = []
52
- for k in range(nz):
53
- for j in range(ny):
54
- for i in range(nx):
55
- if i in (0, nx - 1) or j in (0, ny - 1) or k in (0, nz - 1):
56
- nodes.append(idx(i, j, k))
57
- return np.array(sorted(nodes), dtype=np.int64)
58
-
59
-
60
- # ---------------------------------------------------------------------------
61
- # (a) node_gradient
62
- # ---------------------------------------------------------------------------
63
-
64
- def test_node_gradient_single_regular_tet():
65
- # unit tet at the origin: (0,0,0), (1,0,0), (0,1,0), (0,0,1)
66
- pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], float)
67
- tets = np.array([[0, 1, 2, 3]])
68
- field = 2.0 * pos[:, 0] # f = 2x -> grad = (2, 0, 0) everywhere
69
- g = node_gradient(pos, tets, field)
70
- assert g.shape == (4, 3)
71
- np.testing.assert_allclose(g, np.tile([2.0, 0.0, 0.0], (4, 1)), atol=1e-10)
72
-
73
-
74
- def test_node_gradient_two_tet_bipyramid():
75
- # two tets sharing triangular face ABC, apexes D (above) and E (below)
76
- # A, B, C, D, E -> indices 0..4
77
- pos = np.array([
78
- [0, 0, 0], # A
79
- [1, 0, 0], # B
80
- [0, 1, 0], # C
81
- [0, 0, 1], # D (apex above)
82
- [0, 0, -1], # E (apex below)
83
- ], float)
84
- tets = np.array([
85
- [0, 1, 2, 3], # A B C D
86
- [0, 1, 2, 4], # A B C E
87
- ])
88
- field = pos[:, 0] + pos[:, 1] # f = x + y -> grad = (1, 1, 0) everywhere (exact, linear)
89
- g = node_gradient(pos, tets, field)
90
- assert g.shape == (5, 3)
91
- np.testing.assert_allclose(g, np.tile([1.0, 1.0, 0.0], (5, 1)), atol=1e-10)
92
-
93
-
94
- def test_node_gradient_no_tets_returns_zeros():
95
- pos = np.zeros((3, 3))
96
- tets = np.empty((0, 4), dtype=np.int64)
97
- field = np.zeros(3)
98
- g = node_gradient(pos, tets, field)
99
- np.testing.assert_allclose(g, np.zeros((3, 3)))
100
-
101
-
102
- # ---------------------------------------------------------------------------
103
- # (b) niyama_exact
104
- # ---------------------------------------------------------------------------
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
- # ---------------------------------------------------------------------------
113
- # (c) niyama_proxy
114
- # ---------------------------------------------------------------------------
115
-
116
- def test_niyama_proxy_linear_slab_hand_computed():
117
- # single regular tet, t_s = 2 + 2x (linear ramp along x) -> |grad t_s| = 2 exactly
118
- pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], float)
119
- tets = np.array([[0, 1, 2, 3]])
120
- 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
121
- TL, TS = 1400.0, 1100.0 # TL - TS = 300
122
-
123
- ny = niyama_proxy(pos, tets, t_s, TL, TS)
124
- assert ny.shape == (4,)
125
-
126
- # hand computation: sqrt((TL-TS)/t_s) * |grad t_s|, |grad t_s| = 2 at every node
127
- expected_node0 = np.sqrt(300.0 / 2.0) * 2.0 # ~24.494897...
128
- expected_node1 = np.sqrt(300.0 / 4.0) * 2.0 # ~17.320508...
129
- np.testing.assert_allclose(ny[0], expected_node0, rtol=1e-10)
130
- np.testing.assert_allclose(ny[1], expected_node1, rtol=1e-10)
131
-
132
-
133
- def test_niyama_proxy_eps_guarded_at_zero_t_s():
134
- pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], float)
135
- tets = np.array([[0, 1, 2, 3]])
136
- t_s = np.array([0.0, 2.0, 0.0, 0.0])
137
- ny = niyama_proxy(pos, tets, t_s, 1400.0, 1100.0)
138
- assert np.isfinite(ny).all()
139
-
140
-
141
- # ---------------------------------------------------------------------------
142
- # (d) porosity_risk -- absolute mode
143
- # ---------------------------------------------------------------------------
144
-
145
-
146
-
147
-
148
-
149
-
150
-
151
-
152
-
153
-
154
-
155
- # ---------------------------------------------------------------------------
156
- # (e) porosity_risk -- percentile mode
157
- # ---------------------------------------------------------------------------
158
-
159
- def test_porosity_risk_percentile_exact_bottom_10pct():
160
- ny = np.arange(20, dtype=float) # 0..19, no ties
161
- mask = porosity_risk(ny, pct=10.0)
162
- assert mask.sum() == 2 # exactly bottom 10% of 20 = 2
163
- np.testing.assert_array_equal(np.where(mask)[0], [0, 1])
164
-
165
-
166
- def test_porosity_risk_percentile_exact_bottom_10pct_n10():
167
- ny = np.arange(10, dtype=float) # 0..9
168
- mask = porosity_risk(ny, pct=10.0)
169
- assert mask.sum() == 1
170
- np.testing.assert_array_equal(np.where(mask)[0], [0])
171
-
172
-
173
- def test_porosity_risk_percentile_tie_handling_documented():
174
- # duplicate values straddling the percentile threshold: both ties are
175
- # flagged (mask is defined as ny <= percentile(ny, pct), so a tie AT the
176
- # threshold is always included) -- this can flag slightly MORE than the
177
- # nominal pct% when duplicates sit at the boundary. Documented behavior,
178
- # not a bug: deterministic and order-independent.
179
- ny = np.array([0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
180
- mask = porosity_risk(ny, pct=10.0)
181
- assert mask.sum() == 2
182
- np.testing.assert_array_equal(np.where(mask)[0], [0, 1])
183
-
184
-
185
-
186
-
187
- # ---------------------------------------------------------------------------
188
- # (a) hot_regions + is_fed -- isolated boss (unfed) vs. surface-connected
189
- # band (fed), on one 7x7x7 mesh with two disjoint elevated node clusters.
190
- # ---------------------------------------------------------------------------
191
-
192
- def _boss_and_band_mesh():
193
- nx = ny = nz = 7
194
- pos, tets = _grid_mesh(nx, ny, nz)
195
- idx = _node_idx(nx, ny)
196
- n_nodes = pos.shape[0]
197
- t_s = np.zeros(n_nodes)
198
-
199
- # boss: a fully-interior unit cube {2,3}x{2,3}x{2,3} -- 8 nodes, none on
200
- # the (0 or 6) domain boundary, and not adjacent to the band below.
201
- boss_nodes = [idx(i, j, k) for i in (2, 3) for j in (2, 3) for k in (2, 3)]
202
- # band: a column at x=5,y=5, z=3..6 -- z=6 sits on the top boundary face,
203
- # so the band directly touches a free surface.
204
- band_nodes = [idx(5, 5, z) for z in (3, 4, 5, 6)]
205
-
206
- t_s[boss_nodes] = 100.0
207
- t_s[band_nodes] = 100.0
208
- n_hot = len(boss_nodes) + len(band_nodes)
209
- top_frac = n_hot / n_nodes # sized so the percentile cut lands exactly on {0, 100}
210
-
211
- surface_nodes = _surface_nodes(nx, ny, nz)
212
- return pos, tets, t_s, top_frac, surface_nodes, set(boss_nodes), set(band_nodes)
213
-
214
-
215
- def test_hot_regions_finds_boss_and_band_as_separate_components():
216
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
217
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
218
- assert len(regions) == 2
219
- node_sets = [set(r["nodes"].tolist()) for r in regions]
220
- assert boss_nodes in node_sets
221
- assert band_nodes in node_sets
222
- for r in regions:
223
- assert r["t_max"] == 100.0
224
- np.testing.assert_allclose(r["centroid"], pos[np.array(sorted(r["nodes"]))].mean(axis=0))
225
-
226
-
227
- def test_hot_regions_sorted_by_t_max_desc():
228
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
229
- # bump one region's peak so the sort order is unambiguous.
230
- idx = _node_idx(7, 7)
231
- t_s = t_s.copy()
232
- t_s[idx(5, 5, 6)] = 150.0
233
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
234
- t_maxes = [r["t_max"] for r in regions]
235
- assert t_maxes == sorted(t_maxes, reverse=True)
236
- assert t_maxes[0] == 150.0
237
-
238
-
239
- def test_is_fed_isolated_boss_is_false():
240
- # feed_nodes = surface_nodes here (this mesh's domain boundary stands in
241
- # for a riser/feed location) -- the boss never reaches the corridor
242
- # threshold (0.95*t_max) outside its own 8 nodes, so it can't connect.
243
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
244
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
245
- boss_region = next(r for r in regions if set(r["nodes"].tolist()) == boss_nodes)
246
- assert is_fed(boss_region, t_s, tets, feed_nodes=surface_nodes) is False
247
-
248
-
249
- def test_is_fed_surface_connected_band_is_true():
250
- # the band's own top node (z=6) is itself in feed_nodes=surface_nodes,
251
- # so the region trivially self-connects to a feed node.
252
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
253
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
254
- band_region = next(r for r in regions if set(r["nodes"].tolist()) == band_nodes)
255
- assert is_fed(band_region, t_s, tets, feed_nodes=surface_nodes) is True
256
-
257
-
258
- def test_is_fed_empty_feed_nodes_is_always_false():
259
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
260
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
261
- band_region = next(r for r in regions if set(r["nodes"].tolist()) == band_nodes)
262
- # bare sand casting convention: no risers -> empty feed_nodes -> unfed,
263
- # even for a region that DOES touch the domain surface.
264
- assert is_fed(band_region, t_s, tets, feed_nodes=np.array([], dtype=np.int64)) is False
265
-
266
-
267
- # --------------------------------------------------------------------------- #
268
- # Marginal ("sub-resolution", <4 nodes) hot regions mix a lumped-nodal V
269
- # (stays O(h^3)) with a true iso-surface A (shrinks toward zero as t_max ->
270
- # hot_threshold), so M = V/A diverges without bound. `hot_regions` marks such regions
271
- # "sub_resolution": True; `feeder_recommendations` skips them (logging the
272
- # count once); `macro_shrinkage` still lists them (volume/severity remain
273
- # meaningful, only the modulus diverges).
274
- # --------------------------------------------------------------------------- #
275
- def _single_isolated_hot_node_mesh():
276
- """A 7x7x7 grid mesh with exactly ONE hot node (fully interior, no hot
277
- neighbors) -- the minimal fixture for a 1-node `hot_regions` component."""
278
- nx = ny = nz = 7
279
- pos, tets = _grid_mesh(nx, ny, nz)
280
- idx = _node_idx(nx, ny)
281
- n_nodes = pos.shape[0]
282
- t_s = np.zeros(n_nodes)
283
- hot_node = idx(3, 3, 3)
284
- t_s[hot_node] = 100.0
285
- top_frac = 1.0 / n_nodes
286
- surface_nodes = _surface_nodes(nx, ny, nz)
287
- return pos, tets, t_s, top_frac, surface_nodes, hot_node
288
-
289
-
290
- def test_hot_regions_marks_sub_resolution_for_regions_under_4_nodes():
291
- pos, tets, t_s, top_frac, surface_nodes, hot_node = _single_isolated_hot_node_mesh()
292
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
293
- assert len(regions) == 1
294
- assert regions[0]["nodes"].tolist() == [hot_node]
295
- assert regions[0]["sub_resolution"] is True
296
-
297
-
298
- def test_hot_regions_does_not_mark_well_resolved_regions_sub_resolution():
299
- # the boss (8 nodes) and band (4 nodes) fixture -- both >= the 4-node floor.
300
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
301
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
302
- assert len(regions) == 2
303
- for r in regions:
304
- assert r["sub_resolution"] is False
305
-
306
-
307
- def test_feeder_recommendations_skips_sub_resolution_region_and_logs_count(caplog):
308
- """A 1-node region must get NO feeder recommendation at all, and the
309
- skip must be logged (once, with the count) rather than silent."""
310
- import logging as _logging
311
- pos, tets, t_s, top_frac, surface_nodes, hot_node = _single_isolated_hot_node_mesh()
312
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
313
- assert regions[0]["sub_resolution"] is True
314
-
315
- with caplog.at_level(_logging.INFO, logger="src.shrinkage"):
316
- recs = feeder_recommendations(regions, pos, tets, surface_nodes,
317
- gravity_vec=(0, 0, -1), t_s=t_s)
318
-
319
- assert recs == []
320
- assert any("skipped 1 sub-resolution region" in rec.message for rec in caplog.records)
321
-
322
-
323
- def test_feeder_recommendations_mixed_regions_skips_only_sub_resolution_ones(caplog):
324
- """A regions list mixing well-resolved regions (get a feeder rec each)
325
- and a sub-resolution one (skipped, not just de-prioritized) -- the
326
- well-resolved regions' recs must be unaffected by the mix."""
327
- import logging as _logging
328
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
329
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
330
- assert all(not r["sub_resolution"] for r in regions)
331
-
332
- sub_region = {
333
- "nodes": np.array([0]), "centroid": pos[0], "volume_mm3": 1.0,
334
- "t_max": float(t_s.max()), "region_id": 99,
335
- "hot_threshold": regions[0]["hot_threshold"], "sub_resolution": True,
336
- }
337
- mixed_regions = regions + [sub_region]
338
-
339
- with caplog.at_level(_logging.INFO, logger="src.shrinkage"):
340
- recs = feeder_recommendations(mixed_regions, pos, tets, surface_nodes,
341
- gravity_vec=(0, 0, -1), t_s=t_s)
342
-
343
- assert len(recs) == len(regions)
344
- assert {r["region_id"] for r in recs} == {r["region_id"] for r in regions}
345
- assert any("skipped 1 sub-resolution region" in rec.message for rec in caplog.records)
346
-
347
-
348
- # --------------------------------------------------------------------------- #
349
- # the mesh's boundary-face structure is
350
- # region-independent and hoisted out of `_region_surface_area`'s per-call
351
- # work into a standalone `_boundary_faces(tets)` helper, computed once by
352
- # `feeder_recommendations` and shared across every region. A direct check
353
- # of the helper on a hand-countable 2-tet mesh (one shared interior face).
354
- # --------------------------------------------------------------------------- #
355
- def test_boundary_faces_excludes_shared_interior_face():
356
- # two tets sharing face (0,1,2) -- a triangular bipyramid.
357
- tets = np.array([[0, 1, 2, 3], [0, 1, 2, 4]], dtype=np.int64)
358
- bf = _boundary_faces(tets)
359
- assert bf.shape == (6, 3)
360
- boundary_keys = {tuple(sorted(row.tolist())) for row in bf}
361
- assert (0, 1, 2) not in boundary_keys # the shared interior face is excluded
362
- expected = {(0, 1, 3), (0, 2, 3), (1, 2, 3),
363
- (0, 1, 4), (0, 2, 4), (1, 2, 4)}
364
- assert boundary_keys == expected
365
-
366
-
367
- def test_boundary_faces_empty_tets_gives_empty_array():
368
- bf = _boundary_faces(np.zeros((0, 4), dtype=np.int64))
369
- assert bf.shape == (0, 3)
370
-
371
-
372
- def test_hot_regions_top_frac_out_of_range_raises():
373
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
374
- with pytest.raises(ValueError):
375
- hot_regions(pos, tets, t_s, top_frac=0.0)
376
- with pytest.raises(ValueError):
377
- hot_regions(pos, tets, t_s, top_frac=1.5)
378
-
379
-
380
- # ---------------------------------------------------------------------------
381
- # (a2) is_fed corridor semantics: a warm corridor (t within `corridor_frac` of the region's own
382
- # t_max) bridges the region to a feed node several hops away, NOT required
383
- # to be part of the region's own hot-node set. This is the
384
- # REQUIRED test: it must fail both under a `return False` stub (variant 1
385
- # expects True) and under a naive "touch test" that only checks direct
386
- # region-to-feed_node adjacency or membership (variant 1's feed node is 6
387
- # hops from the region, connected only via the intermediate warm corridor).
388
- # ---------------------------------------------------------------------------
389
-
390
- def _corridor_chain_mesh():
391
- """8x2x2 lattice (32 nodes): an x-adjacent chain of nodes (i,0,0),
392
- i=0..7 (verified consecutively tet-adjacent). Node 6 will be the sole
393
- hot region (t_max=100); nodes 0-5 are the candidate corridor (0 doubles
394
- as the feed node); node 7 is the "far cold side" used as a decoy feed
395
- node in variant 3. Every other mesh node stays at background 0 and
396
- never participates (present only so this is a valid tet mesh)."""
397
- nx, ny, nz = 8, 2, 2
398
- pos, tets = _grid_mesh(nx, ny, nz)
399
- idx = _node_idx(nx, ny)
400
- chain = [idx(i, 0, 0) for i in range(nx)]
401
- n_nodes = pos.shape[0]
402
- return pos, tets, n_nodes, chain
403
-
404
-
405
- def test_is_fed_warm_corridor_bridges_region_to_distant_feed_node():
406
- pos, tets, n_nodes, chain = _corridor_chain_mesh()
407
- t_s = np.zeros(n_nodes)
408
- t_s[chain[6]] = 100.0 # region peak
409
- t_s[chain[0:6]] = 96.0 # corridor >= 0.95*100 = 95 -- stays warm
410
- region = {"nodes": np.array([chain[6]]), "t_max": 100.0}
411
- assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[0]])) is True
412
-
413
-
414
- def test_is_fed_false_when_corridor_cools_below_corridor_frac():
415
- pos, tets, n_nodes, chain = _corridor_chain_mesh()
416
- t_s = np.zeros(n_nodes)
417
- t_s[chain[6]] = 100.0
418
- t_s[chain[0:6]] = 90.0 # < 95 -- corridor no longer warm enough
419
- region = {"nodes": np.array([chain[6]]), "t_max": 100.0}
420
- assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[0]])) is False
421
-
422
-
423
- def test_is_fed_false_when_feed_node_is_on_far_cold_side():
424
- pos, tets, n_nodes, chain = _corridor_chain_mesh()
425
- t_s = np.zeros(n_nodes)
426
- t_s[chain[6]] = 100.0
427
- t_s[chain[0:6]] = 96.0 # corridor stays warm...
428
- region = {"nodes": np.array([chain[6]]), "t_max": 100.0}
429
- # ...but feed_nodes points to the far (cold, disconnected) side instead.
430
- assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[7]])) is False
431
-
432
-
433
- def test_is_fed_region_t_max_zero_is_unfed_not_vacuously_true():
434
- """a region t_max <= 0 would make the
435
- corridor threshold (corridor_frac * t_max) <= 0, vacuously satisfied by
436
- every non-negative t_s -- i.e. the whole (connected) mesh would count as
437
- "warm", trivially fed via any non-empty feed_nodes regardless of real
438
- connectivity. Guarded to report unfed instead."""
439
- pos, tets, n_nodes, chain = _corridor_chain_mesh()
440
- t_s = np.zeros(n_nodes) # every node, including all feed candidates, is 0
441
- region = {"nodes": np.array([chain[6]]), "t_max": 0.0}
442
- # without the guard, corridor threshold = 0.95*0 = 0 <= every t_s -> the
443
- # whole mesh (one connected component) would trivially "fed" this region.
444
- assert is_fed(region, t_s, tets, feed_nodes=np.array([chain[0]])) is False
445
-
446
-
447
- # ---------------------------------------------------------------------------
448
- # (b) macro_shrinkage -- severity = pct/100 * volume, hand-checked; grey_iron
449
- # (pct=0) still reports the region with zero severity; fed regions excluded.
450
- # ---------------------------------------------------------------------------
451
-
452
- def _interior_cube_block_mesh():
453
- """9x6x5 lattice with a fully-interior 3x3x3 node block (a 2x2x2 mm solid
454
- cube of 8 sub-cells). Under the fraction-weighted volume rule, volume_mm3 = 27.0 exactly: each of the 27 hot nodes
455
- is fully interior with a complete 8-cube neighborhood, so its lumped
456
- nodal volume (sum of tet_volume/4 over incident tets) is exactly 1 mm^3
457
- on this unit-spacing lattice -- hand-verified numerically (independently
458
- confirmed: fraction-weighted volume == hot-node COUNT here, since
459
- summing volume*n_hot/4 over all tets is algebraically identical to
460
- summing each hot node's own lumped volume). Boundary area is now `_region_surface_area`'s co-area/domain-boundary
461
- formula -- see that function's docstring -- which for this fixture comes
462
- to ~49.31 mm^2 (M = V/A ~= 0.5475, within 15% of the idealized "3x3x3 mm
463
- dilated cube" reference of A=54/M=0.5 derived by hand; an
464
- exact closed-form match isn't expected for a graded/partial-tet field --
465
- see `test_feeder_recommendations_modulus_exact` and the mesh-refinement
466
- drift test below for the actual acceptance checks). The block is exactly
467
- 27/270 = 10% of nodes, matching hot_regions'/macro_shrinkage's default
468
- top_frac."""
469
- nx, ny, nz = 9, 6, 5
470
- pos, tets = _grid_mesh(nx, ny, nz)
471
- idx = _node_idx(nx, ny)
472
- n_nodes = pos.shape[0]
473
- t_s = np.zeros(n_nodes)
474
- block_nodes = [idx(i, j, k) for i in (3, 4, 5) for j in (1, 2, 3) for k in (1, 2, 3)]
475
- t_s[block_nodes] = 100.0
476
- surface_nodes = _surface_nodes(nx, ny, nz)
477
- assert len(block_nodes) / n_nodes == pytest.approx(0.10)
478
- assert not any(n in set(surface_nodes.tolist()) for n in block_nodes)
479
- return pos, tets, t_s, surface_nodes, set(block_nodes)
480
-
481
-
482
- def test_macro_shrinkage_severity_hand_checked():
483
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
484
- # bare-casting convention: no risers -> empty feed_nodes -> conservative
485
- # (this fully-interior block is unfed regardless, since it never reaches
486
- # the domain surface anyway -- see is_fed's docstring).
487
- no_feed = np.array([], dtype=np.int64)
488
- regions = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=2.5)
489
- assert len(regions) == 1
490
- r = regions[0]
491
- assert set(r["nodes"].tolist()) == block_nodes
492
- assert r["volume_mm3"] == pytest.approx(27.0)
493
- assert r["severity"] == pytest.approx(2.5 / 100.0 * 27.0)
494
-
495
-
496
- def test_macro_shrinkage_grey_iron_zero_severity_still_reported():
497
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
498
- no_feed = np.array([], dtype=np.int64)
499
- regions = macro_shrinkage(pos, tets, t_s, no_feed,
500
- shrinkage_pct=SHRINKAGE_PCT["grey_iron"])
501
- assert len(regions) == 1
502
- assert regions[0]["severity"] == pytest.approx(0.0)
503
- assert regions[0]["volume_mm3"] == pytest.approx(27.0) # region still fully reported
504
-
505
-
506
- def _unfed_boss_and_fed_band_10pct_mesh():
507
- """10x5x4 lattice (200 nodes) with an interior unit-cube boss (8 nodes,
508
- t_max=100, unfed) and a corner block band (12 nodes, t_max=150, touching
509
- x=0/y=0/z=0 boundary faces) -- 20/200 = exactly 10%, matching
510
- macro_shrinkage's (un-parametrized) default top_frac so BOTH regions are
511
- picked up by its internal hot_regions() call. `feed_nodes=surface_nodes`
512
- is used by the tests below as a stand-in "this domain boundary carries
513
- risers" convention: the band's own boundary-touching nodes are literally
514
- IN `surface_nodes`, so it self-connects trivially (fed); the boss's
515
- warm corridor (0.95*its own t_max=100 -> threshold 95) never leaves its
516
- own 8 nodes (all neighbors are background 0), so it cannot reach the
517
- boundary (unfed) -- hand-verified via the boss/band-touches-surface
518
- assertions below. Band's t_max is deliberately HIGHER than boss's so
519
- hot_regions sorts band first (region_id=0) and boss second (region_id=1)
520
- -- this exposes a positional-reindex bug (region_id coherence) that a
521
- same-valued t_max tie would hide."""
522
- nx, ny, nz = 10, 5, 4
523
- pos, tets = _grid_mesh(nx, ny, nz)
524
- idx = _node_idx(nx, ny)
525
- n_nodes = pos.shape[0]
526
- t_s = np.zeros(n_nodes)
527
-
528
- boss_nodes = [idx(i, j, k) for i in (4, 5) for j in (1, 2) for k in (1, 2)]
529
- band_nodes = [idx(i, j, k) for i in (0, 1) for j in (0, 1) for k in (0, 1, 2)]
530
- t_s[boss_nodes] = 100.0
531
- t_s[band_nodes] = 150.0
532
- assert (len(boss_nodes) + len(band_nodes)) / n_nodes == pytest.approx(0.10)
533
-
534
- surface_nodes = _surface_nodes(nx, ny, nz)
535
- surface_set = set(surface_nodes.tolist())
536
- assert not any(n in surface_set for n in boss_nodes)
537
- assert any(n in surface_set for n in band_nodes)
538
- return pos, tets, t_s, surface_nodes, set(boss_nodes), set(band_nodes)
539
-
540
-
541
- def test_macro_shrinkage_excludes_fed_regions():
542
- pos, tets, t_s, surface_nodes, boss_nodes, band_nodes = _unfed_boss_and_fed_band_10pct_mesh()
543
- regions = macro_shrinkage(pos, tets, t_s, feed_nodes=surface_nodes, shrinkage_pct=2.5)
544
- assert len(regions) == 1
545
- assert set(regions[0]["nodes"].tolist()) == boss_nodes
546
-
547
-
548
- def test_region_id_coherence_across_pipeline():
549
- """region_id must be the STABLE hot_regions index, propagated (not
550
- positionally re-derived) through macro_shrinkage's filtering and further
551
- through top_sinks/feeder_recommendations."""
552
- pos, tets, t_s, surface_nodes, boss_nodes, band_nodes = _unfed_boss_and_fed_band_10pct_mesh()
553
-
554
- raw_regions = hot_regions(pos, tets, t_s)
555
- assert len(raw_regions) == 2
556
- boss_raw = next(r for r in raw_regions if set(r["nodes"].tolist()) == boss_nodes)
557
- band_raw = next(r for r in raw_regions if set(r["nodes"].tolist()) == band_nodes)
558
- # band's t_max (150) > boss's (100) -> band sorts first.
559
- assert band_raw["region_id"] == 0
560
- assert boss_raw["region_id"] == 1
561
-
562
- macro = macro_shrinkage(pos, tets, t_s, feed_nodes=surface_nodes, shrinkage_pct=2.5)
563
- assert len(macro) == 1 # band filtered out (fed); a naive positional
564
- # re-index would mislabel the sole survivor as region_id 0.
565
- assert macro[0]["region_id"] == 1
566
-
567
- sinks = top_sinks(macro, pos, surface_nodes, gravity_vec=(0, 0, -1))
568
- feeders = feeder_recommendations(macro, pos, tets, surface_nodes, gravity_vec=(0, 0, -1),
569
- t_s=t_s)
570
- assert all(f["region_id"] == 1 for f in feeders)
571
- assert all(s["region_id"] == 1 for s in sinks)
572
-
573
-
574
- def test_macro_shrinkage_verdict_flips_via_genuine_external_corridor():
575
- """an end-to-end (not just is_fed-level)
576
- demonstration that a region's fed/unfed verdict can flip because of a
577
- node that is NOT part of the region (hot_regions' own top-10% cut
578
- excludes it) and NOT the feed node itself, but sits between
579
- `0.95*t_max` and the hot cut and bridges to a feed node -- i.e. a
580
- genuine warm-corridor effect, not the trivial "feed node happens to be
581
- inside the region" case exercised by `test_macro_shrinkage_excludes_
582
- fed_regions`. Peak (node 1), bridge (node 3), and feed (node 2) are
583
- chosen so the feed node is NOT itself tet-adjacent to the region peak
584
- (hand-verified: nodes 1 and 2 share no tet in this mesh's Kuhn
585
- decomposition) -- the bridge node is structurally required to connect
586
- them, unlike a single-hop setup where a direct peak-feed edge could
587
- make the test pass for the wrong reason. A single unit-cube mesh (N=8)
588
- is used because hot_regions' un-parametrized default top_frac=0.10 only
589
- isolates a lone peak node cleanly at small N (verified: at N=12+ the
590
- corridor value gets pulled into the "hot" selection itself by
591
- percentile interpolation, defeating the "external, not region-touching"
592
- setup)."""
593
- pos, tets = _grid_mesh(2, 2, 2)
594
- n_nodes = pos.shape[0]
595
- t_s = np.zeros(n_nodes)
596
- t_s[1] = 100.0 # sole region peak
597
- t_s[3] = 96.0 # bridge node: >= 0.95*100=95, but < the 97.2 hot cut
598
- t_s[2] = 96.0 # feed node: same band; NOT tet-adjacent to node 1 directly
599
-
600
- regions = hot_regions(pos, tets, t_s) # default top_frac=0.10
601
- assert len(regions) == 1
602
- assert regions[0]["nodes"].tolist() == [1] # bridge/feed excluded from the region itself
603
-
604
- fed_via_corridor = macro_shrinkage(pos, tets, t_s, feed_nodes=np.array([2]),
605
- shrinkage_pct=2.5)
606
- assert fed_via_corridor == [] # fed -> not reported as macro-shrinkage
607
-
608
- unfed_without_corridor = macro_shrinkage(pos, tets, t_s, feed_nodes=np.array([], dtype=np.int64),
609
- shrinkage_pct=2.5)
610
- assert len(unfed_without_corridor) == 1
611
- assert unfed_without_corridor[0]["nodes"].tolist() == [1]
612
-
613
- # cooling the bridge/feed band below 0.95*t_max flips the verdict back
614
- # to unfed even with the SAME feed_nodes -- confirms the flip is driven
615
- # by the corridor threshold, not merely feed_nodes' presence.
616
- t_s_cold_corridor = t_s.copy()
617
- t_s_cold_corridor[[2, 3]] = 90.0
618
- cooled = macro_shrinkage(pos, tets, t_s_cold_corridor, feed_nodes=np.array([2]),
619
- shrinkage_pct=2.5)
620
- assert len(cooled) == 1
621
-
622
-
623
- def test_shrinkage_pct_table():
624
- assert SHRINKAGE_PCT == {
625
- "steel": 2.5, "low_alloy_steel": 2.5, "ductile_iron": 0.75, "grey_iron": 0.0,
626
- }
627
-
628
-
629
- # ---------------------------------------------------------------------------
630
- # (c) top_sinks -- gravity -z -> sink on the top (z-max) face; rotating
631
- # gravity to -x/-y relocates the sink to the +x/+y face. Single 3x3x3 mesh,
632
- # one hot region spanning a top-face node, an interior bridge node, an
633
- # x-face node, and a y-face node (all connected via tet adjacency through
634
- # the bridge) -- also reused by feeder_recommendations' rotation tests below
635
- #.
636
- # ---------------------------------------------------------------------------
637
-
638
- def _rotatable_sink_mesh():
639
- nx = ny = nz = 3
640
- pos, tets = _grid_mesh(nx, ny, nz)
641
- idx = _node_idx(nx, ny)
642
- n_nodes = pos.shape[0]
643
- t_s = np.zeros(n_nodes)
644
-
645
- node_top = idx(1, 1, 2) # z=2 -> top (z-max) surface face
646
- node_bridge = idx(1, 1, 1) # interior
647
- node_xface = idx(2, 1, 1) # x=2 -> +x surface face
648
- node_yface = idx(1, 2, 1) # y=2 -> +y surface face
649
-
650
- hot = [node_top, node_bridge, node_xface, node_yface]
651
- t_s[hot] = 100.0
652
- top_frac = len(hot) / n_nodes
653
- surface_nodes = _surface_nodes(nx, ny, nz)
654
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
655
- assert len(regions) == 1
656
- return pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface
657
-
658
-
659
- def test_top_sinks_default_gravity_hits_top_face():
660
- pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface = _rotatable_sink_mesh()
661
- sinks = top_sinks(regions, pos, surface_nodes, gravity_vec=(0, 0, -1))
662
- assert len(sinks) == 1
663
- np.testing.assert_allclose(sinks[0]["location"], pos[node_top])
664
-
665
-
666
- def test_top_sinks_rotated_gravity_relocates_to_x_face():
667
- pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface = _rotatable_sink_mesh()
668
- sinks = top_sinks(regions, pos, surface_nodes, gravity_vec=(-1, 0, 0))
669
- assert len(sinks) == 1
670
- np.testing.assert_allclose(sinks[0]["location"], pos[node_xface])
671
-
672
-
673
- # ---------------------------------------------------------------------------
674
- # (d) feeder_recommendations -- min_modulus == 1.2*(V/A); location on the
675
- # top surface above the region's centroid; ValueError on empty surface_nodes;
676
- # a degenerate (zero-volume/area) region logs a warning instead of a silent 0.
677
- #
678
- # `_region_surface_area` now runs marching tetrahedra on the
679
- # CONTINUOUS `t_s` field cut at the region's own `hot_threshold`, replacing
680
- # round 2's co-area formula on a BINARIZED indicator -- the binarized version
681
- # always crosses each tet edge at its midpoint regardless of where the real
682
- # field crosses its OWN selection threshold, which is an exact calculus
683
- # identity for the (artificial) binary step but measures the anisotropic
684
- # discrete perimeter of that step, not the true field's level-surface area:
685
- # it plateaus ~24-29% high on curved/diagonal boundaries (only looking exact
686
- # on an axis-aligned cut, where a midpoint crossing happens to coincide with
687
- # the true one). `feeder_recommendations` gained a required `t_s` parameter
688
- # in this round since the marching-tetrahedra computation needs the
689
- # continuous field, not just region-node membership.
690
- # ---------------------------------------------------------------------------
691
-
692
- def _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold):
693
- """Independent reimplementation of the marching-tetrahedra + domain-
694
- boundary-face area formula (mirrors, but does not call,
695
- `src.shrinkage._region_surface_area` -- a genuine hand-check against the
696
- same algorithm, not a tautological re-invocation of the code under
697
- test)."""
698
- n_nodes = pos.shape[0]
699
- is_member = np.zeros(n_nodes, dtype=bool)
700
- is_member[np.asarray(nodes, dtype=np.int64)] = True
701
- hot_mask = t_s >= threshold
702
-
703
- area = 0.0
704
- member_per_tet = hot_mask[tets]
705
- n_above = member_per_tet.sum(axis=1)
706
- for ti in np.flatnonzero((n_above >= 1) & (n_above <= 3)):
707
- tet = tets[ti]
708
- if not is_member[tet].any():
709
- continue
710
- verts = pos[tet]
711
- vals = t_s[tet]
712
- above = member_per_tet[ti]
713
- k = int(n_above[ti])
714
- if k in (1, 3):
715
- odd = int(np.flatnonzero(above)[0]) if k == 1 else int(np.flatnonzero(~above)[0])
716
- others = [i for i in range(4) if i != odd]
717
- pts = []
718
- for o in others:
719
- frac = (threshold - vals[odd]) / (vals[o] - vals[odd])
720
- pts.append(verts[odd] + frac * (verts[o] - verts[odd]))
721
- area += 0.5 * np.linalg.norm(np.cross(pts[1] - pts[0], pts[2] - pts[0]))
722
- else:
723
- hi = np.flatnonzero(above)
724
- lo = np.flatnonzero(~above)
725
-
726
- def _cp(h, c, verts=verts, vals=vals):
727
- frac = (threshold - vals[h]) / (vals[c] - vals[h])
728
- return verts[h] + frac * (verts[c] - verts[h])
729
-
730
- a_pt, b_pt = _cp(hi[0], lo[0]), _cp(hi[0], lo[1])
731
- c_pt, d_pt = _cp(hi[1], lo[1]), _cp(hi[1], lo[0])
732
- area += 0.5 * np.linalg.norm(np.cross(c_pt - a_pt, d_pt - b_pt))
733
-
734
- face_count = {}
735
- for tet in tets:
736
- for f in [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]:
737
- key = tuple(sorted(tet[list(f)].tolist()))
738
- face_count[key] = face_count.get(key, 0) + 1
739
- for key, cnt in face_count.items():
740
- if cnt == 1:
741
- v = np.array(key)
742
- frac = is_member[v].sum() / 3.0
743
- if frac > 0:
744
- q0, q1, q2 = pos[v[0]], pos[v[1]], pos[v[2]]
745
- area += frac * 0.5 * np.linalg.norm(np.cross(q1 - q0, q2 - q0))
746
- return area
747
-
748
-
749
- def _interior_chebyshev_cube_mesh():
750
- """9x6x5 lattice (same domain as `_interior_cube_block_mesh`) with a
751
- CONTINUOUS Chebyshev-distance field `t_s = -max(|x-cx|,|y-cy|,|z-cz|)`
752
- centered at (4,2,2) -- the level sets of this field are EXACT axis-
753
- aligned cubes at any threshold (unlike the binary 0/100 step used
754
- elsewhere in this file, whose arbitrary node-count-derived threshold
755
- has no meaningful relationship to a genuine half-integer offset). At
756
- threshold=-1.5 (exactly bisecting the "distance 1" hot shell and the
757
- "distance 2" next shell), `t_s >= -1.5` selects the SAME 27-node block
758
- as `_interior_cube_block_mesh` (hand-verified) -- reusing `hot_regions`
759
- with top_frac=27/270 reproduces this node set and the correct volume/
760
- centroid/t_max/region_id, but its OWN `hot_threshold` lands at -1.9 (a
761
- percentile-interpolation artifact of this exact node-count split, not a
762
- physically meaningful cut) -- overridden to the analytically clean -1.5
763
- for this specific hand-check, isolating the area ALGORITHM's behavior at
764
- a genuinely representative threshold position from `hot_regions`' own
765
- (separately tested) node-selection quirks."""
766
- nx, ny, nz = 9, 6, 5
767
- pos, tets = _grid_mesh(nx, ny, nz)
768
- center = np.array([4.0, 2.0, 2.0])
769
- t_s = -np.max(np.abs(pos - center), axis=1)
770
- surface_nodes = _surface_nodes(nx, ny, nz)
771
-
772
- regions = hot_regions(pos, tets, t_s, top_frac=27.0 / 270.0)
773
- assert len(regions) == 1
774
- region = dict(regions[0])
775
- assert region["volume_mm3"] == pytest.approx(27.0)
776
- region["hot_threshold"] = -1.5 # see docstring: the clean, symmetric cut
777
- return pos, tets, t_s, surface_nodes, region
778
-
779
-
780
- def test_feeder_recommendations_modulus_level_set_consistent():
781
- """V and A must measure the same body via a genuine
782
- continuous-field level set (not an artificially-thresholded binary
783
- block). On this fixture the true level set is an exact 3x3x3mm cube
784
- (M = side/6 = 0.5 by the Chvorinov identity for any cube); marching
785
- tetrahedra on a real linear field still chamfers cube corners/edges
786
- (hand-verified: the same chamfering appears in an independent marching-
787
- tets reimplementation, not just the shipped code), so M lands near but
788
- not exactly at 0.5 -- within the stated 15% band."""
789
- pos, tets, t_s, surface_nodes, region = _interior_chebyshev_cube_mesh()
790
- recs = feeder_recommendations([region], pos, tets, surface_nodes, gravity_vec=(0, 0, -1),
791
- t_s=t_s)
792
- assert len(recs) == 1
793
-
794
- expected_area = _reference_region_area_marching_tets(pos, tets, region["nodes"], t_s,
795
- region["hot_threshold"])
796
- expected_modulus = region["volume_mm3"] / expected_area
797
- assert recs[0]["min_modulus_mm"] == pytest.approx(1.2 * expected_modulus, rel=1e-9)
798
- assert recs[0]["region_id"] == region["region_id"]
799
-
800
- M = recs[0]["min_modulus_mm"] / 1.2
801
- assert abs(M - 0.5) / 0.5 < 0.15, f"M={M} not within 15% of the Chvorinov M=0.5 cube reference"
802
-
803
-
804
- def test_feeder_recommendations_location_on_top_surface_above_centroid():
805
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
806
- regions = hot_regions(pos, tets, t_s)
807
- recs = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1),
808
- t_s=t_s)
809
- loc = recs[0]["location"]
810
- centroid = regions[0]["centroid"]
811
-
812
- # the recommended point must itself be a surface node...
813
- surface_pos = pos[surface_nodes]
814
- assert np.any(np.all(np.isclose(surface_pos, loc), axis=1))
815
- # ...directly above the centroid (matching x,y; z at the domain's top face)
816
- np.testing.assert_allclose(loc[:2], centroid[:2])
817
- assert loc[2] == pos[:, 2].max()
818
-
819
-
820
- def test_feeder_recommendations_gravity_rotation_relocates_location():
821
- pos, tets, t_s, regions, surface_nodes, node_top, node_xface, node_yface = _rotatable_sink_mesh()
822
-
823
- recs_z = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, 0, -1),
824
- t_s=t_s)
825
- np.testing.assert_allclose(recs_z[0]["location"], pos[node_top])
826
-
827
- recs_x = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(-1, 0, 0),
828
- t_s=t_s)
829
- np.testing.assert_allclose(recs_x[0]["location"], pos[node_xface])
830
-
831
- recs_y = feeder_recommendations(regions, pos, tets, surface_nodes, gravity_vec=(0, -1, 0),
832
- t_s=t_s)
833
- np.testing.assert_allclose(recs_y[0]["location"], pos[node_yface])
834
-
835
-
836
- def test_feeder_recommendations_empty_surface_nodes_raises_value_error():
837
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
838
- regions = hot_regions(pos, tets, t_s)
839
- with pytest.raises(ValueError):
840
- feeder_recommendations(regions, pos, tets, np.array([], dtype=np.int64),
841
- gravity_vec=(0, 0, -1), t_s=t_s)
842
-
843
-
844
- def test_feeder_recommendations_degenerate_region_warns_instead_of_silent_zero(caplog):
845
- import logging as _logging
846
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
847
- # a hand-built region touching no tet at all (an isolated single node
848
- # from the fixture's background, never part of any hot cluster) has
849
- # volume_mm3 == 0 and boundary area == 0 -> degenerate modulus.
850
- degenerate_region = {
851
- "nodes": np.array([0]),
852
- "centroid": pos[0],
853
- "volume_mm3": 0.0,
854
- "t_max": 0.0,
855
- "region_id": 0,
856
- "hot_threshold": t_s.max() + 1.0, # nothing in the mesh qualifies as "hot"
857
- }
858
- with caplog.at_level(_logging.WARNING, logger="src.shrinkage"):
859
- recs = feeder_recommendations([degenerate_region], pos, tets, surface_nodes,
860
- gravity_vec=(0, 0, -1), t_s=t_s)
861
- assert recs[0]["min_modulus_mm"] == 0.0
862
- assert any("degenerate" in rec.message for rec in caplog.records)
863
-
864
-
865
- def test_feeder_recommendations_region_touching_mesh_skin_exercises_boundary_term(caplog):
866
- """a dedicated, in-suite exercise of the
867
- domain-boundary term (a region whose own boundary coincides with the
868
- mesh's outer surface, so `_region_surface_area`'s "no other side to
869
- integrate across" correction path actually fires) -- the gravity-
870
- rotation tests above already use a skin-touching region but only assert
871
- `location`, never `min_modulus_mm`. Reuses the boss+band fixture (task 2
872
- round 1): the band directly touches 3 domain-boundary faces."""
873
- pos, tets, t_s, top_frac, surface_nodes, boss_nodes, band_nodes = _boss_and_band_mesh()
874
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
875
- band_region = next(r for r in regions if set(r["nodes"].tolist()) == band_nodes)
876
-
877
- with caplog.at_level("WARNING", logger="src.shrinkage"):
878
- recs = feeder_recommendations([band_region], pos, tets, surface_nodes,
879
- gravity_vec=(0, 0, -1), t_s=t_s)
880
- assert not any("degenerate" in rec.message for rec in caplog.records)
881
- assert recs[0]["min_modulus_mm"] > 0.0
882
- assert np.isfinite(recs[0]["min_modulus_mm"])
883
-
884
- # independent hand-check: the reference reimplementation must agree.
885
- expected_area = _reference_region_area_marching_tets(
886
- pos, tets, band_region["nodes"], t_s, band_region["hot_threshold"])
887
- expected_modulus = band_region["volume_mm3"] / expected_area
888
- assert recs[0]["min_modulus_mm"] == pytest.approx(1.2 * expected_modulus, rel=1e-9)
889
-
890
-
891
- def _smooth_blob_mesh(spacing, extent=10.0, top_frac=0.05, center_offset=(0.13, 0.29, 0.07)):
892
- """A cubic domain of side `extent` mm with a smooth (non-binary-block)
893
- field `t_s = -|x - center|^2` -- hottest at the center, smoothly falling
894
- off outward, so the top-`top_frac` hot selection is a roughly spherical
895
- blob whose boundary genuinely straddles many partial tets at every mesh
896
- density (unlike the axis-aligned block fixtures elsewhere in this file,
897
- which are deliberately clean/hand-checkable but not representative of a
898
- "smooth field" mesh-convergence scenario). `center_offset` is a
899
- deliberately non-grid-aligned (sub-cell) shift."""
900
- n = int(round(extent / spacing)) + 1
901
- pos, tets = _grid_mesh(n, n, n, spacing=spacing)
902
- center = np.array([extent / 2.0] * 3) + np.array(center_offset)
903
- t_s = -((pos - center) ** 2).sum(axis=1)
904
- surface_nodes = _surface_nodes(n, n, n)
905
- return pos, tets, t_s, top_frac, surface_nodes
906
-
907
-
908
- def test_feeder_recommendations_modulus_refinement_drift_improves_nonaxis(caplog):
909
- """moved from an exact-grid-centered blob to an off-grid-centered spherical blob -- a genuinely NON-axis-
910
- aligned fixture, since the round-2 co-area formula's axis-aligned cuts
911
- were "the one exact case" and could mask residual anisotropy even on a
912
- nominally spherical shape if its center happened to sit on a favorable
913
- grid position at both tested densities. Under the OLD (round-1-shipped)
914
- all-4-vertices-hot area rule, M = V/A drifted ~-29% between a coarse and
915
- 2x-refined mesh of a smooth field (worse than the pre-fix-round-1
916
- baseline of -17%). The marching-tetrahedra area (this round) must keep
917
- drift well under the 15% bound."""
918
- import logging as _logging
919
-
920
- def modulus_at(spacing):
921
- pos, tets, t_s, top_frac, surface_nodes = _smooth_blob_mesh(spacing)
922
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
923
- assert len(regions) == 1
924
- with caplog.at_level(_logging.WARNING, logger="src.shrinkage"):
925
- recs = feeder_recommendations(regions, pos, tets, surface_nodes,
926
- gravity_vec=(0, 0, -1), t_s=t_s)
927
- return recs[0]["min_modulus_mm"] / 1.2
928
-
929
- m_coarse = modulus_at(1.0)
930
- m_fine = modulus_at(0.5)
931
- drift = abs(m_fine - m_coarse) / m_coarse
932
- assert drift < 0.15, f"M drift {drift:.1%} exceeds the 15% bound (coarse={m_coarse}, fine={m_fine})"
933
-
934
-
935
- # ---------------------------------------------------------------------------
936
- # (g) Acceptance suite: marching-tets area vs. the ANALYTIC
937
- # true value on shapes the old (binarized co-area) formula got badly wrong --
938
- # a sphere (curved, converging with refinement, not plateauing), a diagonal
939
- # plane cut through a box (exact via a convex-hull oracle), and an
940
- # orientation sweep (axis/face-diagonal/space-diagonal/generic normals)
941
- # showing the error stays small and roughly ORIENTATION-INDEPENDENT.
942
- # ---------------------------------------------------------------------------
943
-
944
- def _sphere_region(spacing, extent=12.0, top_frac=0.03, center_offset=(0.13, 0.29, 0.07)):
945
- """A spherical hot blob (off-grid center, see `_smooth_blob_mesh`) with
946
- its ANALYTIC area/radius derived directly from the threshold `hot_
947
- regions` actually used (R = sqrt(-threshold) exactly, since the
948
- continuous field t_s = -|pos-center|^2 has a perfectly spherical level
949
- set at every threshold, independent of mesh discretization)."""
950
- n = int(round(extent / spacing)) + 1
951
- pos, tets = _grid_mesh(n, n, n, spacing=spacing)
952
- center = np.array([extent / 2.0] * 3) + np.array(center_offset)
953
- t_s = -((pos - center) ** 2).sum(axis=1)
954
- threshold = np.percentile(t_s, 100 * (1 - top_frac))
955
- nodes = np.flatnonzero(t_s >= threshold)
956
- radius = np.sqrt(-threshold)
957
- true_area = 4.0 * np.pi * radius ** 2
958
- return pos, tets, nodes, t_s, threshold, true_area
959
-
960
-
961
- def test_region_area_sphere_converges_not_plateaus():
962
- """sphere-field area must converge
963
- toward the analytic 4*pi*R^2 as the mesh refines (error DECREASING),
964
- not plateau at the ~24-29% measured for the binarized
965
- co-area formula."""
966
- errors = []
967
- for spacing in (1.0, 0.5, 0.25):
968
- pos, tets, nodes, t_s, threshold, true_area = _sphere_region(spacing)
969
- area = _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold)
970
- errors.append(abs(area - true_area) / true_area)
971
-
972
- assert errors[0] < 0.10, f"coarsest-mesh sphere error too high: {errors[0]:.1%}"
973
- assert errors[-1] < errors[0], f"error did not decrease with refinement: {errors}"
974
- assert errors[-1] < 0.02, f"finest-mesh sphere error too high: {errors[-1]:.1%}"
975
-
976
-
977
- def _halfspace_box_total_area(box_extent, normal, offset):
978
- """Analytic total boundary area of `box ∩ {p : normal.p <= offset}` for
979
- an axis-aligned box `[0,box_extent]^3` -- exact via `scipy.spatial.
980
- ConvexHull` on the (convex) polytope's vertices: the box corners already
981
- inside the half-space, plus the half-space plane's intersection points
982
- with each of the box's 12 edges. Serves as the analytic reference for
983
- the diagonal-cut and orientation-sweep tests below (hand-verified
984
- against known closed forms: an axis-aligned cut of a 10mm cube at x=5
985
- gives exactly 400mm^2 = surface area of a 5x10x10 box; a cut through the
986
- center along the space diagonal gives 300 [half the original 600mm^2
987
- surface, split evenly by symmetry] + 3*sqrt(3)/4*10^2 [=129.90, the
988
- well-known hexagonal cross-section area of a cube bisected
989
- perpendicular to its space diagonal] = 429.90)."""
990
- from scipy.spatial import ConvexHull
991
-
992
- normal = np.asarray(normal, dtype=np.float64)
993
- normal = normal / np.linalg.norm(normal)
994
- lo, hi = 0.0, float(box_extent)
995
- corners = np.array([[x, y, z] for x in (lo, hi) for y in (lo, hi) for z in (lo, hi)])
996
- edges = []
997
- for xi in range(2):
998
- for yi in range(2):
999
- for zi in range(2):
1000
- idx0 = 4 * xi + 2 * yi + zi
1001
- if xi == 0:
1002
- edges.append((idx0, 4 * 1 + 2 * yi + zi))
1003
- if yi == 0:
1004
- edges.append((idx0, 4 * xi + 2 * 1 + zi))
1005
- if zi == 0:
1006
- edges.append((idx0, 4 * xi + 2 * yi + 1))
1007
-
1008
- pts = [c for c in corners if normal @ c - offset <= 1e-9]
1009
- for i, j in edges:
1010
- vi, vj = corners[i], corners[j]
1011
- si, sj = normal @ vi - offset, normal @ vj - offset
1012
- if si * sj < 0:
1013
- t = si / (si - sj)
1014
- pts.append(vi + t * (vj - vi))
1015
- return ConvexHull(np.array(pts)).area
1016
-
1017
-
1018
- def _diagonal_cut_region(spacing, normal, extent=10.0, top_frac=0.3):
1019
- pos, tets = _grid_mesh(int(round(extent / spacing)) + 1,
1020
- int(round(extent / spacing)) + 1,
1021
- int(round(extent / spacing)) + 1, spacing=spacing)
1022
- normal = np.asarray(normal, dtype=np.float64)
1023
- normal = normal / np.linalg.norm(normal)
1024
- t_s = -(pos @ normal)
1025
- threshold = np.percentile(t_s, 100 * (1 - top_frac))
1026
- nodes = np.flatnonzero(t_s >= threshold)
1027
- true_area = _halfspace_box_total_area(extent, normal, offset=-threshold)
1028
- return pos, tets, nodes, t_s, threshold, true_area
1029
-
1030
-
1031
- def test_region_area_diagonal_plane_cut_error_far_below_old_bias():
1032
- """a half-space region cut by a
1033
- plane along the space diagonal (1,1,1) -- normal not aligned with any
1034
- mesh axis. Error must be far below the reported +36% for the
1035
- prior (binarized co-area) formula."""
1036
- for spacing in (1.0, 0.5):
1037
- pos, tets, nodes, t_s, threshold, true_area = _diagonal_cut_region(spacing, (1, 1, 1))
1038
- area = _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold)
1039
- err = abs(area - true_area) / true_area
1040
- assert err < 0.10, f"spacing={spacing}: diagonal-cut error {err:.1%} too high"
1041
-
1042
-
1043
-
1044
-
1045
- # ---------------------------------------------------------------------------
1046
- # (f) hot_regions volume -- fraction-weighted rule:
1047
- # each tet contributes tet_volume * n_hot_vertices/4, replacing an earlier
1048
- # all-4-vertices-hot rule that discarded (undercounted) every boundary tet.
1049
- # ---------------------------------------------------------------------------
1050
-
1051
- def test_hot_regions_volume_fraction_weighted_partial_tets_hand_checked():
1052
- """An isolated single unit-cube mesh (2x2x2 nodes, spacing 1mm, no
1053
- neighboring cubes -- nothing outside this mesh to contaminate the
1054
- count): corner 7 (the (1,1,1) corner) is background/cold, the other 7
1055
- corners are hot. Every one of the cube's 6 Kuhn tets contains corner 7
1056
- (hand-checked from the tet list), so every tet has exactly 3 of its 4
1057
- vertices hot; each tet has volume 1/6 mm^3 (regular unit cube / 6). Total
1058
- fraction-weighted volume = 6 * (1/6) * (3/4) = 0.75 mm^3 exactly. Under
1059
- the old all-4-vertices rule this region would score 0.0 mm^3 (no tet has
1060
- all 4 vertices hot) -- the undercount this fix targets."""
1061
- pos, tets = _grid_mesh(2, 2, 2)
1062
- t_s = np.full(8, 100.0)
1063
- t_s[7] = 0.0
1064
- top_frac = 7.0 / 8.0
1065
- regions = hot_regions(pos, tets, t_s, top_frac=top_frac)
1066
- assert len(regions) == 1
1067
- assert set(regions[0]["nodes"].tolist()) == {0, 1, 2, 3, 4, 5, 6}
1068
- assert regions[0]["volume_mm3"] == pytest.approx(0.75)
1069
-
1070
-
1071
- def test_hot_regions_volume_full_mesh_matches_analytic_total():
1072
- """Sanity/regression check: when EVERY node is hot (top_frac=1.0), no
1073
- tet straddles the region boundary (n_hot_vertices == 4 everywhere), so
1074
- the fraction-weighted rule reduces to the plain tet-volume sum, which
1075
- for a unit-spacing (nx-1)x(ny-1)x(nz-1) lattice equals that product
1076
- exactly."""
1077
- nx, ny, nz = 4, 3, 3
1078
- pos, tets = _grid_mesh(nx, ny, nz)
1079
- t_s = np.ones(pos.shape[0]) # uniform -> every node is "hot" at top_frac=1.0
1080
- regions = hot_regions(pos, tets, t_s, top_frac=1.0)
1081
- assert len(regions) == 1
1082
- assert regions[0]["volume_mm3"] == pytest.approx((nx - 1) * (ny - 1) * (nz - 1))
1083
-
1084
-
1085
- # ---------------------------------------------------------------------------
1086
- # (e) determinism -- two runs on the same inputs produce identical results.
1087
- # ---------------------------------------------------------------------------
1088
-
1089
- def test_determinism_hot_regions_and_downstream():
1090
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
1091
- no_feed = np.array([], dtype=np.int64)
1092
-
1093
- regions1 = hot_regions(pos, tets, t_s)
1094
- regions2 = hot_regions(pos, tets, t_s)
1095
- assert len(regions1) == len(regions2) == 1
1096
- np.testing.assert_array_equal(regions1[0]["nodes"], regions2[0]["nodes"])
1097
- np.testing.assert_allclose(regions1[0]["centroid"], regions2[0]["centroid"])
1098
- assert regions1[0]["volume_mm3"] == regions2[0]["volume_mm3"]
1099
- assert regions1[0]["t_max"] == regions2[0]["t_max"]
1100
- assert regions1[0]["region_id"] == regions2[0]["region_id"]
1101
-
1102
- macro1 = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=2.5)
1103
- macro2 = macro_shrinkage(pos, tets, t_s, no_feed, shrinkage_pct=2.5)
1104
- assert macro1[0]["severity"] == macro2[0]["severity"]
1105
-
1106
- feeders1 = feeder_recommendations(regions1, pos, tets, surface_nodes, gravity_vec=(0, 0, -1),
1107
- t_s=t_s)
1108
- feeders2 = feeder_recommendations(regions2, pos, tets, surface_nodes, gravity_vec=(0, 0, -1),
1109
- t_s=t_s)
1110
- assert feeders1[0]["min_modulus_mm"] == feeders2[0]["min_modulus_mm"]
1111
- np.testing.assert_array_equal(feeders1[0]["location"], feeders2[0]["location"])
1112
-
1113
-
1114
- # ---------------------------------------------------------------------------
1115
- # screen_casting: one call combining the Niyama proxy, macro-shrinkage, top
1116
- # sinks and feeder recommendations. `feed_nodes` (adiabatic-face nodes) is
1117
- # separate from `surface_nodes` (the whole free surface, used for sink and
1118
- # feeder placement); None means no feed source, so every region is unfed.
1119
- # ---------------------------------------------------------------------------
1120
-
1121
-
1122
-
1123
- def test_screen_casting_proxy_niyama_when_fields_omitted():
1124
- nx = ny = nz = 4
1125
- pos, tets = _grid_mesh(nx, ny, nz)
1126
- t_s = pos[:, 0].copy() + 1.0
1127
- surface_nodes = _surface_nodes(nx, ny, nz)
1128
- TL, TS = 1400.0, 1100.0
1129
-
1130
- result = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "grey_iron")
1131
-
1132
- assert result["niyama_source"] == "proxy"
1133
- expected_ny = niyama_proxy(pos, tets, t_s, TL, TS)
1134
- np.testing.assert_allclose(result["niyama"], expected_ny)
1135
- expected_risk = porosity_risk(expected_ny)
1136
- np.testing.assert_array_equal(result["porosity_risk"], expected_risk)
1137
- assert result["material"] == {"alloy_family": "grey_iron", "shrinkage_pct": 0.0}
1138
-
1139
-
1140
-
1141
-
1142
- def test_screen_casting_unknown_alloy_family_raises_loud_error_naming_known_families():
1143
- pos, tets, t_s, surface_nodes, block_nodes = _interior_cube_block_mesh()
1144
- with pytest.raises(KeyError) as exc_info:
1145
- screen_casting(pos, tets, surface_nodes, t_s, 1400.0, 1100.0, "unobtainium")
1146
- msg = str(exc_info.value)
1147
- assert "unobtainium" in msg
1148
- for family in SHRINKAGE_PCT:
1149
- assert family in msg
1150
-
1151
-
1152
- def test_screen_casting_feed_nodes_default_is_empty_bare_casting_convention():
1153
- pos, tets, t_s, surface_nodes, boss_nodes, band_nodes = _unfed_boss_and_fed_band_10pct_mesh()
1154
- TL, TS = 1400.0, 1100.0
1155
-
1156
- default_call = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "steel")
1157
- explicit_empty = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "steel",
1158
- feed_nodes=np.array([], dtype=np.int64))
1159
- assert len(default_call["macro_shrinkage"]) == len(explicit_empty["macro_shrinkage"]) == 2
1160
-
1161
- fed_call = screen_casting(pos, tets, surface_nodes, t_s, TL, TS, "steel",
1162
- feed_nodes=surface_nodes)
1163
- assert len(fed_call["macro_shrinkage"]) == 1 # band fed away via feed_nodes=surface_nodes
1164
-
1165
-
1166
- def test_region_area_orientation_sweep_spread_far_below_old_bias():
1167
- """The SAME half-space-cut
1168
- construction at several normals (axis-aligned, face-diagonal, space-
1169
- diagonal, and a generic non-symmetric direction) -- the spread of
1170
- relative errors across orientations must be far below the ~29% orientation
1171
- sensitivity of a binarized co-area estimate."""
1172
- orientations = {
1173
- "axis-x": (1, 0, 0),
1174
- "face-diag": (1, 1, 0),
1175
- "space-diag": (1, 1, 1),
1176
- "generic": (2, 1, 0.3),
1177
- }
1178
- errors = {}
1179
- for name, normal in orientations.items():
1180
- pos, tets, nodes, t_s, threshold, true_area = _diagonal_cut_region(0.5, normal)
1181
- area = _reference_region_area_marching_tets(pos, tets, nodes, t_s, threshold)
1182
- errors[name] = abs(area - true_area) / true_area
1183
-
1184
- spread = max(errors.values()) - min(errors.values())
1185
- assert spread < 0.10, f"orientation-sweep spread {spread:.1%} too high: {errors}"
1186
- assert all(e < 0.10 for e in errors.values()), f"an orientation exceeded 10% error: {errors}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
weights/SHA256SUMS DELETED
@@ -1,4 +0,0 @@
1
- e1dd5d9227a9495af51177f52f78bd28507134c19e1a82d9341fbf49733a820a gnn_v5.1.safetensors
2
- 0a0b9caa7f1ebcea94e220dd4704ef63309c5f1619fbc20427f90ae1e6727b83 gbm_total_v3.skops
3
- bd4469c06490c4eb8b3d90b24144b2fd7059ae8faab7012e78b12cfaaf25239a gbm_std_v2.skops
4
- 5c24d0c99064ea264e17b44c9c419f73e6793e509215b7099cf5a5902c9a12ae ood_ranges.json