nuclide 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nuclide/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Unit-aware nuclear data and single-parent radioactive decay."""
2
+
3
+ from ._nuclide import DataUnavailableError, Nuclide, nuclides
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["DataUnavailableError", "Nuclide", "nuclides"]
nuclide/_data.py ADDED
@@ -0,0 +1,36 @@
1
+ """Load the bundled evaluation once, without network access."""
2
+
3
+ import json
4
+ from functools import cache
5
+ from importlib.resources import files
6
+ from typing import TypedDict
7
+
8
+
9
+ class Record(TypedDict):
10
+ name: str
11
+ Z: int
12
+ A: int
13
+ state: str
14
+ mass_excess_kev: float | None
15
+ mass_excess_uncertainty_kev: float | None
16
+ mass_excess_estimated: bool
17
+ half_life_seconds: float | None
18
+ half_life_status: str
19
+ half_life_raw: str
20
+ half_life_uncertainty_raw: str
21
+ decay_modes_raw: str
22
+ spin_parity: str
23
+ excitation_energy_kev: float | None
24
+ raw_line: str
25
+
26
+
27
+ @cache
28
+ def records() -> dict[str, Record]:
29
+ text = files("nuclide").joinpath("data/nubase2020.json").read_text(encoding="utf-8")
30
+ data: dict[str, Record] = json.loads(text)["nuclides"]
31
+ return dict(
32
+ sorted(
33
+ data.items(),
34
+ key=lambda item: (item[1]["A"], item[1]["Z"], item[1]["state"]),
35
+ )
36
+ )
nuclide/_nuclide.py ADDED
@@ -0,0 +1,300 @@
1
+ """Nuclear identities, evaluated properties, and single-parent calculations."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from math import inf, isfinite, log
6
+ from numbers import Real
7
+
8
+ from unitx import Quantity, Unit
9
+ from unitx import math as umath
10
+ from unitx.si import SI, si
11
+
12
+ from ._data import Record, records
13
+
14
+
15
+ class DataUnavailableError(ValueError):
16
+ """The evaluation does not provide a usable value for this calculation."""
17
+
18
+
19
+ def _canonical_name(name: str) -> str:
20
+ if not isinstance(name, str):
21
+ raise TypeError("Nuclide requires a name such as 'Rn222' or 'Tc99m'.")
22
+ text = name.strip()
23
+ if match := re.fullmatch(r"([A-Za-z]{1,3})-?([1-9][0-9]*)(m[12]?|n)?", text):
24
+ element, mass, state = match.groups()
25
+ elif match := re.fullmatch(r"([1-9][0-9]*)(m[12]?|n)?-?([A-Za-z]{1,3})", text):
26
+ mass, state, element = match.groups()
27
+ else:
28
+ raise ValueError(
29
+ f"Invalid nuclide name {name!r}; use 'Rn222', 'Rn-222', or '222Rn'."
30
+ )
31
+ # The source uses m/n for the first/second isomer, respectively.
32
+ state = {None: "", "m1": "m", "m2": "n"}.get(state, state)
33
+ symbol = "n" if element.lower() == "n" and mass == "1" else element.capitalize()
34
+ return f"{symbol}-{mass}{state}"
35
+
36
+
37
+ def _nonnegative(value: float, label: str) -> float:
38
+ if isinstance(value, bool) or not isinstance(value, Real):
39
+ raise TypeError(f"{label} must be a real scalar.")
40
+ if not isfinite(value) or value < 0:
41
+ raise ValueError(f"{label} must be finite and nonnegative.")
42
+ return value
43
+
44
+
45
+ def _quantity_value(value: Quantity[float], unit: Unit, label: str) -> float:
46
+ if not isinstance(value, Quantity):
47
+ raise TypeError(f"{label} must carry units; for example, 1 * si.{unit}.")
48
+ return _nonnegative(value.value_in(unit), label)
49
+
50
+
51
+ @dataclass(frozen=True, slots=True, repr=False)
52
+ class Nuclide:
53
+ """An immutable nuclear identity with NUBASE2020 evaluated properties.
54
+
55
+ Names such as ``Rn222``, ``Rn-222`` and ``222Rn`` describe the same
56
+ ground state. ``Tc99m`` is distinct from ``Tc99``. Numeric calculations
57
+ use central values; source qualifiers remain available as properties.
58
+ """
59
+
60
+ name: str
61
+
62
+ def __post_init__(self) -> None:
63
+ name = _canonical_name(self.name)
64
+ if name not in records():
65
+ raise ValueError(
66
+ f"Nuclide {self.name!r} is not in the bundled NUBASE2020 data. "
67
+ "Supported states are ground states and the first two isomers (m/n)."
68
+ )
69
+ object.__setattr__(self, "name", name)
70
+
71
+ def __str__(self) -> str:
72
+ return self.name
73
+
74
+ def __repr__(self) -> str:
75
+ return f"Nuclide({self.name!r})"
76
+
77
+ @property
78
+ def _record(self) -> Record:
79
+ return records()[self.name]
80
+
81
+ @property
82
+ def Z(self) -> int:
83
+ """Number of protons."""
84
+ return self._record["Z"]
85
+
86
+ @property
87
+ def A(self) -> int:
88
+ """Mass number (protons + neutrons)."""
89
+ return self._record["A"]
90
+
91
+ @property
92
+ def N(self) -> int:
93
+ """Number of neutrons."""
94
+ return self.A - self.Z
95
+
96
+ @property
97
+ def element(self) -> str:
98
+ """Element symbol, or ``n`` for the free neutron."""
99
+ return self.name.split("-")[0]
100
+
101
+ @property
102
+ def state(self) -> str:
103
+ """Empty string for the ground state; ``m`` or ``n`` for an isomer."""
104
+ return self._record["state"]
105
+
106
+ @property
107
+ def is_stable(self) -> bool:
108
+ """Whether NUBASE2020 explicitly classifies this state as stable."""
109
+ return self.half_life_status == "stable"
110
+
111
+ @property
112
+ def half_life_status(self) -> str:
113
+ """Source classification: measured, estimated, approximate, stable, etc."""
114
+ return self._record["half_life_status"]
115
+
116
+ @property
117
+ def half_life_text(self) -> str:
118
+ """Original half-life value and unit, preserving limits and qualifiers."""
119
+ return self._record["half_life_raw"]
120
+
121
+ @property
122
+ def half_life_uncertainty_text(self) -> str:
123
+ """Original uncertainty field; not a propagated numerical uncertainty."""
124
+ return self._record["half_life_uncertainty_raw"]
125
+
126
+ @property
127
+ def half_life(self) -> Quantity[float]:
128
+ """Half-life as a time quantity; infinity for an explicitly stable state.
129
+
130
+ Limits, unknown half-lives and particle-unstable states without a
131
+ lifetime raise DataUnavailableError. Estimated and approximate central
132
+ values are usable, with their status retained in half_life_status.
133
+ """
134
+ if self.is_stable:
135
+ return inf * si.s
136
+ seconds = self._record["half_life_seconds"]
137
+ if seconds is None or self.half_life_status not in {
138
+ "measured",
139
+ "estimated",
140
+ "approximate",
141
+ }:
142
+ raise DataUnavailableError(
143
+ f"{self.name} has no usable half-life: {self.half_life_text!r} "
144
+ f"({self.half_life_status}). A limit is not an exact lifetime."
145
+ )
146
+ return seconds * si.s
147
+
148
+ @property
149
+ def decay_constant(self) -> Quantity[float]:
150
+ """Parent loss rate ln(2) / half_life, in inverse seconds."""
151
+ return (log(2) / self.half_life).to(si.s**-1)
152
+
153
+ @property
154
+ def mean_lifetime(self) -> Quantity[float]:
155
+ """Mean lifetime half_life / ln(2)."""
156
+ return self.half_life / log(2)
157
+
158
+ @property
159
+ def mass_excess(self) -> Quantity[float]:
160
+ """Atomic mass excess (M - A u)c²; this can be negative."""
161
+ value = self._record["mass_excess_kev"]
162
+ if value is None:
163
+ raise DataUnavailableError(f"{self.name} has no evaluated mass excess.")
164
+ return value * si.keV
165
+
166
+ @property
167
+ def mass_excess_uncertainty(self) -> Quantity[float]:
168
+ """Tabulated mass-excess uncertainty, without propagation."""
169
+ value = self._record["mass_excess_uncertainty_kev"]
170
+ if value is None:
171
+ raise DataUnavailableError(f"{self.name} has no mass-excess uncertainty.")
172
+ return value * si.keV
173
+
174
+ @property
175
+ def mass_is_estimated(self) -> bool:
176
+ """Whether the mass was estimated from systematics (source '#')."""
177
+ return self._record["mass_excess_estimated"]
178
+
179
+ @property
180
+ def atomic_mass(self) -> Quantity[float]:
181
+ """Neutral atomic mass A u + mass_excess/c² (free mass for n-1)."""
182
+ return (self.A * si.u + self.mass_excess / SI.c**2).to(si.u)
183
+
184
+ @property
185
+ def molar_mass(self) -> Quantity[float]:
186
+ """Atomic mass times the Avogadro constant."""
187
+ return (self.atomic_mass * SI.NA).to(si.g / si.mol)
188
+
189
+ @property
190
+ def excitation_energy(self) -> Quantity[float]:
191
+ """Excitation energy of the nuclear state; zero for ground states."""
192
+ if not self.state:
193
+ return 0.0 * si.keV
194
+ value = self._record["excitation_energy_kev"]
195
+ if value is None:
196
+ raise DataUnavailableError(f"{self.name} has no excitation energy value.")
197
+ return value * si.keV
198
+
199
+ @property
200
+ def spin_parity(self) -> str:
201
+ """Evaluated spin/parity text, retaining source qualifiers."""
202
+ return self._record["spin_parity"]
203
+
204
+ @property
205
+ def decay_modes(self) -> tuple[str, ...]:
206
+ """Source decay descriptions (percent), excluding isotopic abundance.
207
+
208
+ These may overlap and are not daughter-state-resolved branching
209
+ probabilities. For example, beta-delayed neutron decay is included
210
+ in the total beta decay rate.
211
+ """
212
+ return tuple(
213
+ part.strip()
214
+ for part in self._record["decay_modes_raw"].split(";")
215
+ if part.strip() and not part.strip().startswith("IS")
216
+ )
217
+
218
+ @property
219
+ def specific_activity(self) -> Quantity[float]:
220
+ """Activity per mass of this pure isotope, in Bq/g."""
221
+ return (self.decay_constant / self.atomic_mass).to(si.Bq / si.g)
222
+
223
+ def survival_fraction(self, time: Quantity[float]) -> float:
224
+ """Fraction of the original parent nuclei remaining after time.
225
+
226
+ Assumes an isolated population with no production or removal other
227
+ than radioactive decay. Does not include daughter growth.
228
+ """
229
+ seconds = _quantity_value(time, si.s, "time")
230
+ return umath.exp(-self.decay_constant * (seconds * si.s)).n
231
+
232
+ def activity(
233
+ self, *, atoms: float | None = None, mass: Quantity[float] | None = None
234
+ ) -> Quantity[float]:
235
+ """Activity of a pure sample, specifying either atom count or mass."""
236
+ if (atoms is None) == (mass is None):
237
+ raise TypeError("Specify exactly one of atoms= or mass=.")
238
+ if mass is not None:
239
+ count = self.atoms(mass=mass)
240
+ else:
241
+ assert atoms is not None
242
+ count = _nonnegative(atoms, "atoms")
243
+ return (count * self.decay_constant).to(si.Bq)
244
+
245
+ def atoms(
246
+ self,
247
+ *,
248
+ mass: Quantity[float] | None = None,
249
+ activity: Quantity[float] | None = None,
250
+ ) -> float:
251
+ """Atom count from a pure sample's mass or activity.
252
+
253
+ Counts may be fractional expected populations. Stable nuclides have
254
+ zero activity at every mass, so activity cannot determine their count.
255
+ """
256
+ if (mass is None) == (activity is None):
257
+ raise TypeError("Specify exactly one of mass= or activity=.")
258
+ if mass is not None:
259
+ grams = _quantity_value(mass, si.g, "mass")
260
+ return ((grams * si.g) / self.atomic_mass).n
261
+ assert activity is not None
262
+ becquerels = _quantity_value(activity, si.Bq, "activity")
263
+ if self.is_stable:
264
+ raise ValueError(
265
+ f"Activity cannot determine the amount of stable {self.name}."
266
+ )
267
+ return ((becquerels * si.Bq) / self.decay_constant).n
268
+
269
+ def mass(
270
+ self, *, atoms: float | None = None, activity: Quantity[float] | None = None
271
+ ) -> Quantity[float]:
272
+ """Mass of a pure sample, specifying either atom count or activity."""
273
+ if (atoms is None) == (activity is None):
274
+ raise TypeError("Specify exactly one of atoms= or activity=.")
275
+ if activity is not None:
276
+ count = self.atoms(activity=activity)
277
+ else:
278
+ assert atoms is not None
279
+ count = _nonnegative(atoms, "atoms")
280
+ return (count * self.atomic_mass).to(si.g)
281
+
282
+
283
+ def nuclides(element: str | None = None) -> tuple[Nuclide, ...]:
284
+ """List supported nuclear states, optionally for an element symbol.
285
+
286
+ Results follow the evaluation's mass-number/proton-number/state order.
287
+ Lowercase ``n`` selects the free neutron; ``N`` selects nitrogen.
288
+ """
289
+ if element is not None:
290
+ if not isinstance(element, str):
291
+ raise TypeError("element must be a symbol such as 'Rn'.")
292
+ element = element.strip()
293
+ element = element if element == "n" else element.capitalize()
294
+ if element not in {name.split("-")[0] for name in records()}:
295
+ raise ValueError(f"Unknown element symbol {element!r}.")
296
+ return tuple(
297
+ Nuclide(name)
298
+ for name in records()
299
+ if element is None or name.split("-")[0] == element
300
+ )
nuclide/data/NOTICE.md ADDED
@@ -0,0 +1,33 @@
1
+ # NUBASE2020 data attribution
2
+
3
+ The bundled nuclear data are adapted from:
4
+
5
+ F.G. Kondev, M. Wang, W.J. Huang, S. Naimi, and G. Audi,
6
+ **The NUBASE2020 evaluation of nuclear physics properties**,
7
+ Chinese Physics C **45**, 030001 (2021).
8
+ DOI: <https://doi.org/10.1088/1674-1137/abddae>.
9
+
10
+ The evaluation is published under the
11
+ [Creative Commons Attribution 3.0 license](https://creativecommons.org/licenses/by/3.0/).
12
+ See the [publisher's reuse policy](https://csnsdoc.ihep.ac.cn/article/doi/10.1088/1674-1137/abddae)
13
+ and the [final published article hosted by AMDC](https://amdc.impcas.ac.cn/masstables/Ame2020/Kondev_2021_Chinese_Phys._C_45_030001.pdf).
14
+ This attribution and the data license are separate from nuclide's software license.
15
+ The authors, AMDC, and IAEA do not endorse this package.
16
+
17
+ Source: <https://nds.iaea.org/amdc/ame2020/nubase_4.mas20.txt>
18
+
19
+ Retrieved: 2026-11-16.
20
+
21
+ SHA-256 of the uncompressed source:
22
+ `1585a5eea86c5e17e90307c7e6e786d060049c4039e392a261ff6db977df9859`.
23
+
24
+ Changes made by nuclide: selected ground states and the first two isomer labels
25
+ (`m`, `n`); omitted entries marked as reported nonexistent or existence uncertain;
26
+ normalized names and numeric fields; converted time units to seconds using the
27
+ evaluation's tropical year (31,556,926 seconds); preserved source qualifiers and
28
+ original rows. Decay-mode strings are retained without inferring daughter states
29
+ or a branching network. Uncertainties are not propagated.
30
+
31
+ `nubase_4.mas20.txt.gz` is a lossless compressed copy of the source.
32
+ `nubase2020.json` is generated by `tools/import_nubase.py` in the source repository.
33
+ The JSON metadata includes counts, excluded entries, and source provenance.