erer-can commited on
Commit
256b4e9
·
verified ·
1 Parent(s): 3046edb

Release STAR-XPC model, inference code and model card

Browse files
Files changed (6) hide show
  1. README.md +187 -0
  2. config.json +121 -0
  3. embeddings.safetensors +3 -0
  4. model.safetensors +3 -0
  5. requirements.txt +8 -0
  6. star_xpc.py +527 -0
README.md CHANGED
@@ -1,3 +1,190 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ library_name: pytorch
4
+ pipeline_tag: tabular-regression
5
+ tags:
6
+ - set-transformer
7
+ - chemberta
8
+ - radiation-shielding
9
+ - x-ray
10
+ - materials-science
11
+ - monte-carlo-surrogate
12
  ---
13
+
14
+ # STAR-XPC
15
+
16
+ STAR-XPC predicts how much of an X-ray beam passes through a polymer composite
17
+ shield. You give it a polyethylene slab loaded with fillers, a slab thickness
18
+ and a tube voltage. It returns the transmission ratio **I/I₀** in milliseconds.
19
+ The penEasy (PENELOPE) Monte Carlo simulations it was trained to replace take
20
+ hours per point.
21
+
22
+ The composite is treated as a *set* of ingredients. Each ingredient is described
23
+ by a ChemBERTa embedding of its SMILES and its weight fraction, and a Set
24
+ Transformer maps the set plus four physics features to I/I₀. Because the
25
+ chemistry enters through SMILES, you can also register materials the model was
26
+ not trained on.
27
+
28
+ ## Quickstart
29
+
30
+ ```bash
31
+ pip install torch numpy safetensors huggingface_hub
32
+ ```
33
+
34
+ ```python
35
+ import sys
36
+ from huggingface_hub import snapshot_download
37
+
38
+ repo = snapshot_download("cmpe-netlab41/STAR-XPC")
39
+ sys.path.insert(0, repo)
40
+ from star_xpc import STARXPC
41
+
42
+ model = STARXPC.from_pretrained(repo)
43
+
44
+ # 40 wt% Bi + 30 wt% W in polyethylene (the remaining 30 wt%), 80 kVp beam
45
+ y = model.predict({"Bi": 0.40, "W": 0.30}, thickness_mm=[0.25, 0.5, 1.0, 1.5], kvp=80)
46
+ print(y) # I/I0 at each thickness
47
+ ```
48
+
49
+ `predict` works out the composite's density and mean excitation energy from the
50
+ composition, so the composition, thickness and voltage are all you need.
51
+
52
+ ## Inputs
53
+
54
+ | Argument | Meaning | Unit |
55
+ |---|---|---|
56
+ | `fillers` | Filler weight fractions of the **whole** composite, e.g. `{"Bi2O3": 0.4, "BaSO4": 0.4}`. Up to 10 fillers | fraction (0.4 = 40 wt%) |
57
+ | `thickness_mm` | Slab thickness, scalar or array | mm |
58
+ | `kvp` | X-ray tube voltage, scalar or array (broadcast with thickness) | kVp |
59
+ | `polymer_fraction` | Polyethylene weight fraction. Defaults to `1 - sum(fillers)` | fraction |
60
+ | `mass_den` | Composite density. Computed if omitted | g/cm³ |
61
+ | `mean_excit` | Composite mean excitation energy. Computed if omitted | eV |
62
+
63
+ ## Materials
64
+
65
+ The model ships with the materials it was trained on:
66
+
67
+ - **Fillers:** B, B4C, BN, Ba, BaSO4, Bi, Bi2O3, Cu, Sb, Sn, W, WO3
68
+ - **Matrix:** polyethylene (C2H4)
69
+
70
+ ### Registering a new material
71
+
72
+ Any other filler can be registered from its SMILES. It is embedded with ChemBERTa
73
+ (`seyonec/ChemBERTa-zinc-base-v1`, pinned revision) using exactly the recipe the
74
+ training materials went through. For example, lead and gadolinium, which are not
75
+ in the training data:
76
+
77
+ ```python
78
+ # pip install transformers
79
+ model.add_material("Pb", smiles="[Pb]", density=11.34)
80
+ model.add_material("Gd", smiles="[Gd]", density=7.90)
81
+
82
+ model.predict({"Pb": 0.70}, thickness_mm=[0.3, 0.6, 1.2], kvp=100)
83
+ model.predict({"Gd": 0.40, "W": 0.30}, thickness_mm=1.0, kvp=120)
84
+ ```
85
+
86
+ Registered this way, Pb and Gd reach NMSE % 0.14 and 0.16 against penEasy at
87
+ 100 kVp. That is in line with the held-out sets of trained materials (see
88
+ [results](#held-out-test-results)).
89
+
90
+ - **Formula:** read from the name when the name is a chemical formula (`"Pb"`,
91
+ `"Gd2O3"`). Otherwise pass `formula="..."`.
92
+ - **Density:** in g/cm³, used to compute the composite density. Without a
93
+ formula or density, pass `mass_den=` and `mean_excit=` to `predict` instead.
94
+ - **Style:** write SMILES the way the training materials were written. Use pure
95
+ elements as bracket atoms (`[Pb]`), oxides as covalent structures
96
+ (`O=[Gd]O[Gd]=O`, `O=[W](=O)=O`), and salts as ions
97
+ (`[Ba++].[O-]S(=O)(=O)[O-]`). Keep SMILES under 64 tokens, since longer ones
98
+ are truncated and you get a warning.
99
+ - **Unregistered names:** using one raises an error that shows the
100
+ `add_material` call to make.
101
+ - **Accuracy:** `predict` warns once for each material that is not in the
102
+ training data. Treat those predictions as estimates and confirm important
103
+ ones with Monte Carlo.
104
+
105
+ ## Physics features
106
+
107
+ - **Mean excitation energy:** the Bragg additivity rule with PENELOPE's elemental
108
+ I-values for Z = 1–99, so it also works for registered materials. This is what
109
+ PENELOPE's `material` program does, and it matches the training data to within
110
+ 10⁻⁴.
111
+ - **Density:** the inverse rule of mixtures. It uses the training densities for
112
+ the bundled materials and the density you pass for registered ones.
113
+ - **If you know better:** some boron-containing training samples used a slightly
114
+ different boron density. If you have the exact values from PENELOPE, pass
115
+ `mass_den=` and `mean_excit=`.
116
+
117
+ ## Batch prediction from a table
118
+
119
+ `predict_frame` takes a pandas DataFrame in the training-data schema:
120
+ `molecule_1..10`, `ratio_1..10` (filler wt%), `polymer`, `polymer_ratio`
121
+ (fraction), `geo_number_mm` (**in units of 0.01 mm**, so 100 = 1 mm), `spc`
122
+ (kVp), `mass_den` and `mean_excit`.
123
+
124
+ ```python
125
+ import pandas as pd
126
+ y = model.predict_frame(pd.read_csv("my_samples.csv"))
127
+ ```
128
+
129
+ ## Training domain and limitations
130
+
131
+ - **Target:** the energy deposited in an air detector behind the slab, divided
132
+ by the same quantity with the slab replaced by air. It comes from penEasy
133
+ simulations of a fixed slab-and-detector geometry.
134
+ - **Beams:** four spectra. 30 kVp is ISO N-30, 80 kVp is IEC RQR6, 100 kVp is
135
+ IEC RQR8 and 120 kVp is IEC RQR9. Other voltages are interpolation between
136
+ those spectra and are untested.
137
+ - **Thickness:** 0.15–2.5 mm.
138
+ - **Composition:** polyethylene at 20–40 wt%, with one to several fillers making
139
+ up the remaining 60–80 wt%.
140
+ - **Output range:** the output layer is unbounded, so predictions near 0 or 1
141
+ can land slightly outside that range.
142
+ - **Warnings:** `predict` warns when an input falls outside the training domain.
143
+
144
+ ## Held-out test results
145
+
146
+ None of these test sets were used in training. Each has 10 thicknesses.
147
+
148
+ | Test set | NMSE % | RMSE | MAPE (10 % trimmed) |
149
+ |---|---:|---:|---:|
150
+ | Bi–W, 80 kVp | 0.153 | 0.0119 | 7.59 % |
151
+ | W–Cu–B, 100 kVp | 0.022 | 0.0074 | 1.04 % |
152
+ | Bi–Sb, 120 kVp | 0.051 | 0.0111 | 2.85 % |
153
+ | Bi₂O₃–BaSO₄, 80 kVp | 0.209 | 0.0147 | 5.15 % |
154
+ | BaSO₄–WO₃, 100 kVp | 0.023 | 0.0076 | 1.98 % |
155
+ | Bi₂O₃, 120 kVp | 0.013 | 0.0058 | 1.09 % |
156
+ | **Pb** 70 wt% (registered), 100 kVp | 0.141 | 0.0143 | 4.93 % |
157
+ | **Gd** 70 wt% (registered), 100 kVp | 0.163 | 0.0177 | 4.28 % |
158
+
159
+ NMSE % = 100 · MSE / mean(y²).
160
+
161
+ ## How it works
162
+
163
+ Each composite becomes a set of 11 slots (up to 10 fillers plus the polymer,
164
+ zero-padded). Each slot is a 773-d vector:
165
+
166
+ - the ingredient's 768-d ChemBERTa embedding, which is the mean of the last 4
167
+ hidden layers, masked-mean-pooled over tokens and L2-normalised;
168
+ - its share of the composition;
169
+ - four z-scored global features: tube voltage, composite density, thickness and
170
+ mean excitation energy.
171
+
172
+ A Set Transformer (2 ISAB blocks with 64 inducing points, PMA with 8 seeds and a
173
+ SAB; width 256, 32 heads) turns the set into a single output.
174
+
175
+ In the training data, filler amounts were stored in wt% and the polymer amount
176
+ as a fraction, and the two were renormalised together. `star_xpc.py`
177
+ reproduces that encoding, so give `predict` ordinary weight fractions.
178
+
179
+ ## Files
180
+
181
+ | File | Contents |
182
+ |---|---|
183
+ | `star_xpc.py` | Model definition and the `STARXPC` predictor |
184
+ | `model.safetensors` | Set Transformer weights |
185
+ | `embeddings.safetensors` | ChemBERTa embeddings of the 13 training materials |
186
+ | `config.json` | Architecture, feature normalisation statistics, material table, training domain |
187
+
188
+ ## Citation
189
+
190
+ <!-- TODO: add the paper's BibTeX once it is available -->
config.json ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "STAR-XPC",
3
+ "architecture": {
4
+ "in_dimension": 773,
5
+ "out_dimension": 1,
6
+ "d": 256,
7
+ "m": 64,
8
+ "h": 32,
9
+ "k": 8,
10
+ "num_isabs": 2,
11
+ "num_rff_layers": 3
12
+ },
13
+ "max_slots": 11,
14
+ "embedding": {
15
+ "model_id": "seyonec/ChemBERTa-zinc-base-v1",
16
+ "revision": "761d6a18cf99db371e0b43baf3e2d21b3e865a20",
17
+ "dim": 768,
18
+ "max_length": 64
19
+ },
20
+ "polymer": "C2H4",
21
+ "thickness_unit_mm": 0.01,
22
+ "global_features": [
23
+ "spc",
24
+ "mass_den",
25
+ "geo_number_mm",
26
+ "mean_excit"
27
+ ],
28
+ "normalization": {
29
+ "spc_mean": 89.3144560357675,
30
+ "spc_std": 29.071914051102166,
31
+ "mass_den_mean": 2.2529541424398554,
32
+ "mass_den_std": 0.5317519959220683,
33
+ "thick_mean": 92.31850117096019,
34
+ "thick_std": 58.83530258224455,
35
+ "mean_excit_mean": 180.05545585669574,
36
+ "mean_excit_std": 75.43978864260697
37
+ },
38
+ "training_domain": {
39
+ "kvp": [
40
+ 30,
41
+ 80,
42
+ 100,
43
+ 120
44
+ ],
45
+ "thickness_mm": [
46
+ 0.15,
47
+ 2.5
48
+ ],
49
+ "polymer_fraction": [
50
+ 0.2,
51
+ 0.4
52
+ ]
53
+ },
54
+ "materials": {
55
+ "B": {
56
+ "smiles": "[B]",
57
+ "formula": "B",
58
+ "density": 2.37
59
+ },
60
+ "B4C": {
61
+ "smiles": "B12B3C14B2B43",
62
+ "formula": "B4C",
63
+ "density": 2.52
64
+ },
65
+ "BN": {
66
+ "smiles": "B#N",
67
+ "formula": "BN",
68
+ "density": 2.1
69
+ },
70
+ "Ba": {
71
+ "smiles": "[Ba]",
72
+ "formula": "Ba",
73
+ "density": 3.59
74
+ },
75
+ "BaSO4": {
76
+ "smiles": "[Ba++].[O-]S(=O)(=O)[O-]",
77
+ "formula": "BaSO4",
78
+ "density": 4.48
79
+ },
80
+ "Bi": {
81
+ "smiles": "[Bi]",
82
+ "formula": "Bi",
83
+ "density": 9.747
84
+ },
85
+ "Bi2O3": {
86
+ "smiles": "O=[Bi]O[Bi]=O",
87
+ "formula": "Bi2O3",
88
+ "density": 8.9018
89
+ },
90
+ "C2H4": {
91
+ "smiles": "C=C",
92
+ "formula": "C2H4",
93
+ "density": 0.95
94
+ },
95
+ "Cu": {
96
+ "smiles": "[Cu]",
97
+ "formula": "Cu",
98
+ "density": 8.96
99
+ },
100
+ "Sb": {
101
+ "smiles": "[Sb]",
102
+ "formula": "Sb",
103
+ "density": 6.697
104
+ },
105
+ "Sn": {
106
+ "smiles": "[Sn]",
107
+ "formula": "Sn",
108
+ "density": 7.265
109
+ },
110
+ "W": {
111
+ "smiles": "[W]",
112
+ "formula": "W",
113
+ "density": 19.254
114
+ },
115
+ "WO3": {
116
+ "smiles": "O=[W](=O)=O",
117
+ "formula": "WO3",
118
+ "density": 7.1596
119
+ }
120
+ }
121
+ }
embeddings.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1695dc7a6b6711814aa7f9d07b0f9a7a82c1c5dfaa3b02f1996f640929f3606
3
+ size 40776
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb8d7c4f6bbf706ec592a85bbf4aeb635ee8de6dade1ef82b468e588cb8a2e8b
3
+ size 12029436
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ numpy
3
+ safetensors
4
+ huggingface_hub
5
+ # optional: only for model.add_material() with a new SMILES
6
+ transformers
7
+ # optional: only for model.predict_frame()
8
+ pandas
star_xpc.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """STAR-XPC: Set-Transformer estimator of X-ray transmission through filled polymer composites.
2
+
3
+ Self-contained inference code for the Hugging Face release. Needs ``torch``,
4
+ ``numpy`` and ``safetensors``; ``huggingface_hub`` to download from the Hub, and
5
+ ``transformers`` only to register a material that was not in training.
6
+
7
+ from star_xpc import STARXPC
8
+
9
+ model = STARXPC.from_pretrained("path/or/repo-id")
10
+ model.predict({"Bi": 0.40, "W": 0.30}, thickness_mm=[0.5, 1.0, 2.0], kvp=80)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ import re
18
+ import warnings
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn as nn
24
+ from safetensors.torch import load_file
25
+
26
+ __all__ = ["STARXPC", "SetTransformer", "ChemBERTaEmbedder", "UnknownMaterialError", "parse_formula"]
27
+
28
+
29
+ # Set Transformer
30
+
31
+ class Attention(nn.Module):
32
+ """Scaled dot-product attention."""
33
+
34
+ def __init__(self, temperature):
35
+ super().__init__()
36
+ self.temperature = temperature
37
+ self.softmax = nn.Softmax(dim=2)
38
+
39
+ def forward(self, queries, keys, values):
40
+ attention = self.softmax(torch.bmm(queries, keys.transpose(1, 2)) / self.temperature)
41
+ return torch.bmm(attention, values)
42
+
43
+
44
+ class MultiheadAttention(nn.Module):
45
+ def __init__(self, d, h):
46
+ super().__init__()
47
+ assert d % h == 0
48
+ self.h = h
49
+ self.project_queries = nn.Linear(d, d)
50
+ self.project_keys = nn.Linear(d, d)
51
+ self.project_values = nn.Linear(d, d)
52
+ self.concatenation = nn.Linear(d, d)
53
+ self.attention = Attention(temperature=(d // h) ** 0.5)
54
+
55
+ def forward(self, queries, keys, values):
56
+ h = self.h
57
+ b, n, d = queries.size()
58
+ m = keys.size(1)
59
+ p = d // h
60
+
61
+ q = self.project_queries(queries).view(b, n, h, p).permute(2, 0, 1, 3).contiguous().view(h * b, n, p)
62
+ k = self.project_keys(keys).view(b, m, h, p).permute(2, 0, 1, 3).contiguous().view(h * b, m, p)
63
+ v = self.project_values(values).view(b, m, h, p).permute(2, 0, 1, 3).contiguous().view(h * b, m, p)
64
+
65
+ out = self.attention(q, k, v) # [hb, n, p]
66
+ out = out.view(h, b, n, p).permute(1, 2, 0, 3).contiguous().view(b, n, d) # [b, n, d]
67
+ return self.concatenation(out)
68
+
69
+
70
+ class RFF(nn.Module):
71
+ """Row-wise feed-forward network."""
72
+
73
+ def __init__(self, d, num_layers=2):
74
+ super().__init__()
75
+ layers = []
76
+ for _ in range(num_layers):
77
+ layers.extend([nn.Linear(d, d), nn.ReLU(inplace=True)])
78
+ self.layers = nn.Sequential(*layers)
79
+
80
+ def forward(self, x):
81
+ return self.layers(x)
82
+
83
+
84
+ class MultiheadAttentionBlock(nn.Module):
85
+ def __init__(self, d, h, rff):
86
+ super().__init__()
87
+ self.multihead = MultiheadAttention(d, h)
88
+ self.layer_norm1 = nn.LayerNorm(d)
89
+ self.layer_norm2 = nn.LayerNorm(d)
90
+ self.rff = rff
91
+
92
+ def forward(self, x, y):
93
+ h_ = self.layer_norm1(x + self.multihead(x, y, y))
94
+ return self.layer_norm2(h_ + self.rff(h_))
95
+
96
+
97
+ class SetAttentionBlock(nn.Module):
98
+ def __init__(self, d, h, rff):
99
+ super().__init__()
100
+ self.mab = MultiheadAttentionBlock(d, h, rff)
101
+
102
+ def forward(self, x):
103
+ return self.mab(x, x)
104
+
105
+
106
+ class InducedSetAttentionBlock(nn.Module):
107
+ def __init__(self, d, m, h, rff1, rff2):
108
+ super().__init__()
109
+ self.mab1 = MultiheadAttentionBlock(d, h, rff1)
110
+ self.mab2 = MultiheadAttentionBlock(d, h, rff2)
111
+ self.inducing_points = nn.Parameter(torch.zeros(1, m, d))
112
+
113
+ def forward(self, x):
114
+ p = self.inducing_points.repeat(x.size(0), 1, 1)
115
+ return self.mab2(x, self.mab1(p, x))
116
+
117
+
118
+ class PoolingMultiheadAttention(nn.Module):
119
+ def __init__(self, d, k, h, rff):
120
+ super().__init__()
121
+ self.mab = MultiheadAttentionBlock(d, h, rff)
122
+ self.seed_vectors = nn.Parameter(torch.zeros(1, k, d))
123
+
124
+ def forward(self, z):
125
+ s = self.seed_vectors.repeat(z.size(0), 1, 1)
126
+ return self.mab(s, z)
127
+
128
+
129
+ class SetTransformer(nn.Module):
130
+ def __init__(self, in_dimension, out_dimension, d=128, m=16, h=4, k=4,
131
+ num_isabs=2, num_rff_layers=3):
132
+ super().__init__()
133
+ self.embed = nn.Sequential(nn.Linear(in_dimension, d), nn.ReLU(inplace=True))
134
+ self.encoder = nn.ModuleList([
135
+ InducedSetAttentionBlock(d, m, h, RFF(d, num_rff_layers), RFF(d, num_rff_layers))
136
+ for _ in range(num_isabs)
137
+ ])
138
+ self.pma = PoolingMultiheadAttention(d, k, h, RFF(d, num_rff_layers))
139
+ self.sab = SetAttentionBlock(d, h, RFF(d, num_rff_layers))
140
+ self.predictor = nn.Linear(k * d, out_dimension)
141
+
142
+ def forward(self, x):
143
+ """x: [b, n, in_dimension] -> [b, out_dimension]"""
144
+ x = self.embed(x)
145
+ for blk in self.encoder:
146
+ x = blk(x)
147
+ x = self.sab(self.pma(x))
148
+ b, k, d = x.shape
149
+ return self.predictor(x.view(b, k * d))
150
+
151
+
152
+ # ChemBERTa embeddings
153
+
154
+ class ChemBERTaEmbedder:
155
+ """768-d SMILES embedding: mean of the last 4 hidden layers, attention-masked
156
+ mean over tokens, then L2-normalised."""
157
+
158
+ def __init__(self, model_id="seyonec/ChemBERTa-zinc-base-v1", revision=None,
159
+ max_length=64, device="cpu"):
160
+ from transformers import AutoModel, AutoTokenizer
161
+
162
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
163
+ self.model = AutoModel.from_pretrained(model_id, revision=revision).to(device).eval()
164
+ self.max_length = max_length
165
+ self.device = device
166
+
167
+ @torch.no_grad()
168
+ def __call__(self, smiles: str) -> torch.Tensor:
169
+ n_tokens = len(self.tokenizer(smiles)["input_ids"])
170
+ if n_tokens > self.max_length:
171
+ warnings.warn(f"SMILES {smiles!r} is {n_tokens} tokens; only the first "
172
+ f"{self.max_length} are embedded (as in training).", stacklevel=2)
173
+ enc = self.tokenizer(smiles, return_tensors="pt", padding=True, truncation=True,
174
+ max_length=self.max_length).to(self.device)
175
+ hidden = self.model(**enc, output_hidden_states=True).hidden_states[-4:]
176
+ layers = torch.stack(hidden, dim=0).mean(dim=0) # [1, seq, 768]
177
+ mask = enc["attention_mask"].unsqueeze(-1) # [1, seq, 1]
178
+ emb = ((layers * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)).squeeze(0).cpu()
179
+ norm = emb.norm(p=2)
180
+ if norm.item() == 0:
181
+ raise ValueError(f"Zero-norm embedding for SMILES {smiles!r}")
182
+ return emb / norm
183
+
184
+
185
+ # Composite physics features
186
+
187
+ # symbol: (Z, atomic weight [g/mol], mean excitation energy I [eV]).
188
+ _ELEMENTS = {
189
+ "H": (1, 1.00794, 19.2), "He": (2, 4.002602, 41.8), "Li": (3, 6.94, 40),
190
+ "Be": (4, 9.0121831, 63.7), "B": (5, 10.81, 76), "C": (6, 12.0107, 81),
191
+ "N": (7, 14.0067, 82), "O": (8, 15.999, 95), "F": (9, 18.998403163, 115),
192
+ "Ne": (10, 20.1797, 137), "Na": (11, 22.98976928, 149), "Mg": (12, 24.305, 156),
193
+ "Al": (13, 26.9815385, 166), "Si": (14, 28.085, 173), "P": (15, 30.973761998, 173),
194
+ "S": (16, 32.065, 180), "Cl": (17, 35.45, 174), "Ar": (18, 39.948, 188),
195
+ "K": (19, 39.0983, 190), "Ca": (20, 40.078, 191), "Sc": (21, 44.955908, 216),
196
+ "Ti": (22, 47.867, 233), "V": (23, 50.9415, 245), "Cr": (24, 51.9961, 257),
197
+ "Mn": (25, 54.938044, 272), "Fe": (26, 55.845, 286), "Co": (27, 58.933194, 297),
198
+ "Ni": (28, 58.6934, 311), "Cu": (29, 63.546, 322), "Zn": (30, 65.38, 330),
199
+ "Ga": (31, 69.723, 334), "Ge": (32, 72.63, 350), "As": (33, 74.921595, 347),
200
+ "Se": (34, 78.971, 348), "Br": (35, 79.904, 343), "Kr": (36, 83.798, 352),
201
+ "Rb": (37, 85.4678, 363), "Sr": (38, 87.62, 366), "Y": (39, 88.90584, 379),
202
+ "Zr": (40, 91.224, 393), "Nb": (41, 92.90637, 417), "Mo": (42, 95.95, 424),
203
+ "Tc": (43, 98.0, 428), "Ru": (44, 101.07, 441), "Rh": (45, 102.9055, 449),
204
+ "Pd": (46, 106.42, 470), "Ag": (47, 107.8682, 470), "Cd": (48, 112.414, 469),
205
+ "In": (49, 114.818, 488), "Sn": (50, 118.71, 488), "Sb": (51, 121.76, 487),
206
+ "Te": (52, 127.6, 485), "I": (53, 126.90447, 491), "Xe": (54, 131.293, 482),
207
+ "Cs": (55, 132.90545196, 488), "Ba": (56, 137.327, 491), "La": (57, 138.90547, 501),
208
+ "Ce": (58, 140.116, 523), "Pr": (59, 140.90766, 535), "Nd": (60, 144.242, 546),
209
+ "Pm": (61, 145.0, 560), "Sm": (62, 150.36, 574), "Eu": (63, 151.964, 580),
210
+ "Gd": (64, 157.25, 591), "Tb": (65, 158.92535, 614), "Dy": (66, 162.5, 628),
211
+ "Ho": (67, 164.93033, 650), "Er": (68, 167.259, 658), "Tm": (69, 168.93422, 674),
212
+ "Yb": (70, 173.045, 684), "Lu": (71, 174.9668, 694), "Hf": (72, 178.49, 705),
213
+ "Ta": (73, 180.94788, 718), "W": (74, 183.84, 727), "Re": (75, 186.207, 736),
214
+ "Os": (76, 190.23, 746), "Ir": (77, 192.217, 757), "Pt": (78, 195.084, 790),
215
+ "Au": (79, 196.966569, 790), "Hg": (80, 200.592, 800), "Tl": (81, 204.38, 810),
216
+ "Pb": (82, 207.231, 823), "Bi": (83, 208.9804, 823), "Po": (84, 209.0, 830),
217
+ "At": (85, 210.0, 825), "Rn": (86, 222.0, 794), "Fr": (87, 223.0, 827),
218
+ "Ra": (88, 226.0, 826), "Ac": (89, 227.0, 841), "Th": (90, 232.0377, 847),
219
+ "Pa": (91, 231.03588, 878), "U": (92, 238.02891, 890), "Np": (93, 237.0, 902),
220
+ "Pu": (94, 244.0, 921), "Am": (95, 243.0, 934), "Cm": (96, 247.0, 939),
221
+ "Bk": (97, 247.0, 952), "Cf": (98, 251.0, 966), "Es": (99, 252.0, 980),
222
+ }
223
+
224
+ _FORMULA_TOKEN = re.compile(r"([A-Z][a-z]?|\(|\)|\d+(?:\.\d+)?)")
225
+
226
+
227
+ def parse_formula(formula: str) -> dict[str, float]:
228
+ """``"Gd2O3"`` -> ``{"Gd": 2, "O": 3}``. Understands parentheses
229
+ (``"Mg(OH)2"``) and fractional counts; raises ValueError otherwise."""
230
+ tokens = _FORMULA_TOKEN.findall(formula)
231
+ if not formula or "".join(tokens) != formula:
232
+ raise ValueError(f"Cannot parse chemical formula {formula!r}")
233
+ stack, i = [{}], 0
234
+ while i < len(tokens):
235
+ tok = tokens[i]
236
+ i += 1
237
+ if tok == "(":
238
+ stack.append({})
239
+ continue
240
+ if tok[0].isdigit():
241
+ raise ValueError(f"Unexpected number in formula {formula!r}")
242
+ mult = 1.0
243
+ if i < len(tokens) and tokens[i][0].isdigit():
244
+ mult = float(tokens[i])
245
+ i += 1
246
+ if tok == ")":
247
+ if len(stack) == 1:
248
+ raise ValueError(f"Unbalanced ')' in formula {formula!r}")
249
+ for el, c in stack.pop().items():
250
+ stack[-1][el] = stack[-1].get(el, 0.0) + c * mult
251
+ else:
252
+ if tok not in _ELEMENTS:
253
+ raise ValueError(f"Unknown element {tok!r} in formula {formula!r}")
254
+ stack[-1][tok] = stack[-1].get(tok, 0.0) + mult
255
+ if len(stack) != 1:
256
+ raise ValueError(f"Unbalanced '(' in formula {formula!r}")
257
+ return stack[0]
258
+
259
+
260
+ _INVALID = {"-1", "-1.0", "", "nan", "None"}
261
+
262
+
263
+ def _is_missing(v) -> bool:
264
+ return v is None or (isinstance(v, float) and math.isnan(v)) or str(v).strip() in _INVALID
265
+
266
+
267
+ class UnknownMaterialError(KeyError):
268
+ def __str__(self):
269
+ return self.args[0]
270
+
271
+
272
+ # Public predictor
273
+
274
+ class STARXPC:
275
+ """Predicts the transmission ratio I/I0 of a filler + polyethylene composite slab."""
276
+
277
+ def __init__(self, model: SetTransformer, embeddings: dict, config: dict, device="cpu"):
278
+ self.device = torch.device(device)
279
+ self.model = model.to(self.device).eval()
280
+ self.config = config
281
+ self.embeddings = {k: v.float() for k, v in embeddings.items()}
282
+ self.materials = {k: dict(v) for k, v in config["materials"].items()}
283
+ self._embedder = None
284
+ self._warned = set()
285
+
286
+ @classmethod
287
+ def from_pretrained(cls, path_or_repo_id, revision=None, device="cpu") -> "STARXPC":
288
+ """Load from a local folder or a Hugging Face repo id."""
289
+ path = Path(path_or_repo_id)
290
+ if not path.is_dir():
291
+ from huggingface_hub import snapshot_download
292
+ path = Path(snapshot_download(str(path_or_repo_id), revision=revision))
293
+
294
+ config = json.loads((path / "config.json").read_text())
295
+ model = SetTransformer(**config["architecture"])
296
+ model.load_state_dict(load_file(path / "model.safetensors"), strict=True)
297
+ embeddings = load_file(path / "embeddings.safetensors")
298
+ return cls(model, embeddings, config, device=device)
299
+
300
+ # materials
301
+
302
+ @property
303
+ def available_materials(self) -> list[str]:
304
+ """Trained materials plus any registered with :meth:`add_material`."""
305
+ return sorted(self.embeddings)
306
+
307
+ def add_material(self, name: str, smiles: str, density: float | None = None,
308
+ formula: str | dict | None = None, overwrite: bool = False) -> torch.Tensor:
309
+ """Register a new material from its SMILES (requires ``transformers``).
310
+
311
+ The SMILES is embedded with ChemBERTa exactly as the training materials
312
+ were. ``density`` (g/cm3) and ``formula`` (read from ``name`` when it is a
313
+ chemical formula, e.g. ``"Pb"`` or ``"Bi2O3"``) let :meth:`predict`
314
+ compute mass_den and mean_excit; without them, pass those to
315
+ :meth:`predict` yourself.
316
+ """
317
+ if name in self.embeddings and not overwrite:
318
+ raise ValueError(f"{name!r} already exists; pass overwrite=True to replace it.")
319
+ if formula is None:
320
+ try:
321
+ parse_formula(name)
322
+ formula = name
323
+ except ValueError:
324
+ formula = None
325
+ elif isinstance(formula, str):
326
+ parse_formula(formula) # validate early
327
+ if self._embedder is None:
328
+ cfg = self.config["embedding"]
329
+ self._embedder = ChemBERTaEmbedder(cfg["model_id"], cfg.get("revision"),
330
+ cfg["max_length"], device=self.device)
331
+ self.embeddings[name] = self._embedder(smiles)
332
+ self.materials[name] = {"smiles": smiles, "formula": formula, "density": density}
333
+ return self.embeddings[name]
334
+
335
+ def _resolve(self, name) -> str:
336
+ name = str(name).strip()
337
+ if name in self.embeddings:
338
+ return name
339
+ matches = [k for k in self.embeddings if k.lower() == name.lower()]
340
+ if len(matches) == 1:
341
+ return matches[0]
342
+ raise UnknownMaterialError(
343
+ f"{name!r} is not a trained or registered material. Register it from its SMILES "
344
+ "(needs `pip install transformers`):\n\n"
345
+ f" model.add_material({name!r}, smiles=\"...\", density=...) # density in g/cm3\n\n"
346
+ "A pure element is a bracket atom, e.g. model.add_material(\"Pb\", smiles=\"[Pb]\", "
347
+ "density=11.34).\nTrained materials: " + ", ".join(sorted(self.config["materials"]))
348
+ )
349
+
350
+ def _counts(self, name: str) -> dict:
351
+ formula = self.materials[name].get("formula")
352
+ if not formula:
353
+ raise ValueError(f"{name!r} has no chemical formula: pass formula= to add_material(), "
354
+ "or mean_excit= to predict().")
355
+ return dict(formula) if isinstance(formula, dict) else parse_formula(formula)
356
+
357
+ def _density(self, name: str) -> float:
358
+ rho = self.materials[name].get("density")
359
+ if not rho:
360
+ raise ValueError(f"{name!r} has no density: pass density= to add_material(), "
361
+ "or mass_den= to predict().")
362
+ return float(rho)
363
+
364
+ def mass_density(self, mixture: dict) -> float:
365
+ """Composite density (g/cm3), inverse rule of mixtures over weight fractions."""
366
+ return 1.0 / sum(w / self._density(self._resolve(n)) for n, w in mixture.items())
367
+
368
+ def mean_excitation(self, mixture: dict) -> float:
369
+ """Composite mean excitation energy (eV), Bragg additivity rule as in PENELOPE."""
370
+ el_w = {}
371
+ for name, w in mixture.items():
372
+ counts = self._counts(self._resolve(name))
373
+ molar = sum(_ELEMENTS[e][1] * c for e, c in counts.items())
374
+ for e, c in counts.items():
375
+ el_w[e] = el_w.get(e, 0.0) + w * _ELEMENTS[e][1] * c / molar
376
+ z_over_a = {e: w * _ELEMENTS[e][0] / _ELEMENTS[e][1] for e, w in el_w.items()}
377
+ return math.exp(sum(za * math.log(_ELEMENTS[e][2]) for e, za in z_over_a.items())
378
+ / sum(z_over_a.values()))
379
+
380
+ def composite_properties(self, fillers: dict, polymer_fraction: float) -> tuple[float, float]:
381
+ """(mass_den [g/cm3], mean_excit [eV]) of fillers + polyethylene."""
382
+ mixture = self._mixture(fillers, polymer_fraction)
383
+ return self.mass_density(mixture), self.mean_excitation(mixture)
384
+
385
+ def _mixture(self, fillers, polymer_fraction):
386
+ mixture = {self._resolve(k): float(v) for k, v in fillers.items()}
387
+ if polymer_fraction > 0:
388
+ poly = self.config["polymer"]
389
+ mixture[poly] = mixture.get(poly, 0.0) + polymer_fraction
390
+ return mixture
391
+
392
+ def _warn_untrained(self, names):
393
+ for name in names:
394
+ if name not in self.config["materials"] and name not in self._warned:
395
+ self._warned.add(name)
396
+ warnings.warn(
397
+ f"{name!r} is not in the training data; its prediction relies on how well its "
398
+ "ChemBERTa embedding generalises. Treat it as an estimate.", stacklevel=3)
399
+
400
+ # prediction
401
+
402
+ def predict(self, fillers: dict, thickness_mm, kvp, polymer_fraction: float | None = None,
403
+ mass_den: float | None = None, mean_excit: float | None = None):
404
+ """Transmission ratio I/I0 for one composite.
405
+
406
+ fillers: weight fractions of the whole composite, e.g. {"Bi": 0.40, "W": 0.30}.
407
+ thickness_mm: slab thickness in mm (scalar or array).
408
+ kvp: X-ray tube voltage in kVp (scalar or array, broadcast with thickness).
409
+ polymer_fraction: polyethylene weight fraction; defaults to 1 - sum(fillers).
410
+ mass_den, mean_excit: g/cm3 and eV; computed from the composition when omitted.
411
+
412
+ Returns a float for scalar inputs, otherwise a numpy array.
413
+ """
414
+ resolved = {}
415
+ for k, v in fillers.items():
416
+ if float(v) > 0:
417
+ key = self._resolve(k)
418
+ resolved[key] = resolved.get(key, 0.0) + float(v)
419
+ fillers = resolved
420
+ if not fillers:
421
+ raise ValueError("At least one filler with a positive weight fraction is required.")
422
+ if len(fillers) > self.config["max_slots"] - 1:
423
+ raise ValueError(f"At most {self.config['max_slots'] - 1} fillers are supported.")
424
+ total = sum(fillers.values())
425
+ if total > 1.0 + 1e-6:
426
+ raise ValueError(f"Filler fractions sum to {total:.3f}; give weight fractions "
427
+ "(0.40 for 40 wt%), not percentages.")
428
+ if polymer_fraction is None:
429
+ polymer_fraction = max(0.0, 1.0 - total)
430
+ if abs(total + polymer_fraction - 1.0) > 1e-3:
431
+ raise ValueError(f"Fillers ({total:.3f}) + polymer ({polymer_fraction:.3f}) must sum to 1.")
432
+
433
+ mixture = self._mixture(fillers, polymer_fraction)
434
+ mass_den = self.mass_density(mixture) if mass_den is None else mass_den
435
+ mean_excit = self.mean_excitation(mixture) if mean_excit is None else mean_excit
436
+
437
+ t, v = np.broadcast_arrays(np.asarray(thickness_mm, dtype=float), np.asarray(kvp, dtype=float))
438
+ shape = t.shape
439
+ t, v = t.ravel(), v.ravel()
440
+ self._check_domain(t, v, polymer_fraction)
441
+ self._warn_untrained(fillers)
442
+
443
+ pairs = [(name, 100.0 * w) for name, w in fillers.items()]
444
+ if polymer_fraction > 0:
445
+ pairs.append((self.config["polymer"], polymer_fraction))
446
+
447
+ y = self._forward(
448
+ [pairs] * len(t),
449
+ spc=v,
450
+ mass_den=np.full(len(t), float(mass_den)),
451
+ geo=t / self.config["thickness_unit_mm"],
452
+ mean_excit=np.full(len(t), float(mean_excit)),
453
+ )
454
+ return float(y[0]) if shape == () else y.reshape(shape)
455
+
456
+ def predict_frame(self, df) -> np.ndarray:
457
+ """Predict for a pandas DataFrame in the training-CSV schema
458
+ (molecule_1..10, ratio_1..10, polymer, polymer_ratio, geo_number_mm,
459
+ spc, mass_den, mean_excit)."""
460
+ slots = self.config["max_slots"]
461
+ mol_cols = [f"molecule_{j}" for j in range(1, slots)] + ["polymer"]
462
+ rat_cols = [f"ratio_{j}" for j in range(1, slots)] + ["polymer_ratio"]
463
+
464
+ sets, used = [], set()
465
+ for row in df.to_dict("records"):
466
+ pairs = []
467
+ for mcol, rcol in zip(mol_cols, rat_cols):
468
+ m, r = row.get(mcol), row.get(rcol)
469
+ if _is_missing(m) or _is_missing(r):
470
+ continue
471
+ try:
472
+ r = float(r)
473
+ except (TypeError, ValueError):
474
+ continue
475
+ if r > 0:
476
+ name = self._resolve(m)
477
+ pairs.append((name, r))
478
+ used.add(name)
479
+ sets.append(pairs)
480
+ self._warn_untrained(sorted(used))
481
+
482
+ col = lambda c: df[c].to_numpy(dtype=float)
483
+ return self._forward(sets, col("spc"), col("mass_den"), col("geo_number_mm"), col("mean_excit"))
484
+
485
+ def _forward(self, sets, spc, mass_den, geo, mean_excit, batch_size=1024) -> np.ndarray:
486
+ n = self.config["normalization"]
487
+ slots = self.config["max_slots"]
488
+ dim = self.config["embedding"]["dim"]
489
+
490
+ gf = np.stack([
491
+ (spc - n["spc_mean"]) / n["spc_std"],
492
+ (mass_den - n["mass_den_mean"]) / n["mass_den_std"],
493
+ (geo - n["thick_mean"]) / n["thick_std"],
494
+ (mean_excit - n["mean_excit_mean"]) / n["mean_excit_std"],
495
+ ], axis=1)
496
+
497
+ out = []
498
+ for start in range(0, len(sets), batch_size):
499
+ chunk = sets[start:start + batch_size]
500
+ emb = torch.zeros(len(chunk), slots, dim)
501
+ rat = torch.zeros(len(chunk), slots, 1)
502
+ for b, pairs in enumerate(chunk):
503
+ total = sum(r for _, r in pairs)
504
+ if not pairs or total <= 0:
505
+ raise ValueError(f"Row {start + b} has no material with a positive ratio.")
506
+ for s, (name, r) in enumerate(pairs[:slots]):
507
+ emb[b, s] = self.embeddings[name]
508
+ rat[b, s, 0] = r / total
509
+ g = torch.tensor(gf[start:start + len(chunk)], dtype=torch.float32)
510
+ x = torch.cat([emb, rat, g.unsqueeze(1).expand(-1, slots, -1)], dim=-1).to(self.device)
511
+ with torch.no_grad():
512
+ out.append(self.model(x).squeeze(-1).cpu().numpy())
513
+ return np.concatenate(out) if out else np.empty(0, dtype=np.float32)
514
+
515
+ def _check_domain(self, thickness_mm, kvp, polymer_fraction):
516
+ dom = self.config.get("training_domain", {})
517
+ if "kvp" in dom and not np.isin(kvp, dom["kvp"]).all():
518
+ warnings.warn(f"Model was trained only at {dom['kvp']} kVp; other voltages are interpolation.",
519
+ stacklevel=3)
520
+ if "thickness_mm" in dom:
521
+ lo, hi = dom["thickness_mm"]
522
+ if (thickness_mm < lo).any() or (thickness_mm > hi).any():
523
+ warnings.warn(f"Thickness outside the training range {lo}-{hi} mm.", stacklevel=3)
524
+ if "polymer_fraction" in dom:
525
+ lo, hi = dom["polymer_fraction"]
526
+ if not lo - 1e-9 <= polymer_fraction <= hi + 1e-9:
527
+ warnings.warn(f"Polymer fraction outside the training range {lo}-{hi}.", stacklevel=3)