braggcalculator 0.1.0__tar.gz

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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: braggcalculator
3
+ Version: 0.1.0
4
+ Summary: Fast, validated and differentiable Bragg powder diffraction
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: crystallography,diffraction,PXRD,neutron,PyTorch
8
+ Author: Frederik Lizak Johansen
9
+ Author-email: fupjohansen@gmail.com
10
+ Requires-Python: >=3.12,<3.14
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Provides-Extra: all
20
+ Provides-Extra: ase
21
+ Provides-Extra: torch
22
+ Requires-Dist: ase (>=3.23,<4) ; extra == "ase" or extra == "all"
23
+ Requires-Dist: numpy (>=2.3.2,<3.0.0)
24
+ Requires-Dist: pymatgen (>=2025.6.14,<2027)
25
+ Requires-Dist: spglib (>=2.6.0,<3.0.0)
26
+ Requires-Dist: torch (>=2.2,<3) ; extra == "torch" or extra == "all"
27
+ Project-URL: Documentation, https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/docs/api.md
28
+ Project-URL: Issues, https://github.com/FrederikLizakJohansen/BraggCalculator/issues
29
+ Project-URL: Repository, https://github.com/FrederikLizakJohansen/BraggCalculator
30
+ Description-Content-Type: text/markdown
31
+
32
+ <p align="center">
33
+ <img src="https://raw.githubusercontent.com/FrederikLizakJohansen/BraggCalculator/main/assets/braggcalculator-logo.png" width="650" alt="BraggCalculator logo">
34
+ </p>
35
+
36
+ # BraggCalculator
37
+
38
+ BraggCalculator is a fast, validated powder X-ray and neutron diffraction
39
+ engine for ideal periodic crystals. It evaluates reciprocal-space Bragg
40
+ diffraction with NumPy or optional PyTorch kernels.
41
+
42
+ The current scientific scope is monochromatic, kinematic powder diffraction.
43
+ It includes neutral-atom X-ray form factors, coherent elemental neutron
44
+ scattering lengths, occupancies, isotropic Debye-Waller factors, the standard
45
+ powder Lorentz or Lorentz-polarization correction, and area-normalized Gaussian
46
+ profiles. It does not model diffuse scattering, finite-particle shape, preferred
47
+ orientation, microstrain, absorption, background, anomalous X-ray terms, or
48
+ instrumental wavelength distributions.
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ python -m pip install braggcalculator
54
+ python -m pip install "braggcalculator[torch]" # Torch/autograd/CUDA backend
55
+ python -m pip install "braggcalculator[ase]" # ASE structure input
56
+ ```
57
+
58
+ Python 3.12 and 3.13 are supported. To work from a source checkout, use
59
+ `python -m pip install -e ".[all]"`.
60
+
61
+ The [API reference](https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/docs/api.md)
62
+ documents the public configuration, methods, and result conventions.
63
+
64
+ ## Quick start
65
+
66
+ ```python
67
+ from braggcalculator import BraggCalculator
68
+
69
+ calculator = BraggCalculator(mode="xray", wavelength="CuKa1")
70
+ calculator.load("structure.cif")
71
+
72
+ two_theta, integrated_intensity = calculator.line_pattern(scaled=True)
73
+ grid, profile = calculator.pattern()
74
+ ```
75
+
76
+ `line_pattern()` returns the conventional merged powder lines. `pattern()`
77
+ returns an area-normalized Gaussian profile on a regular grid.
78
+ `reflection_table()` provides the corresponding HKLs, d-spacings, Q values,
79
+ scattering angles, structure factors, and corrected intensities. The
80
+ [API reference](https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/docs/api.md)
81
+ documents lower-level reciprocal-point output and the rules for differentiable
82
+ lattice changes.
83
+
84
+ The Q-space API uses inverse angstroms:
85
+
86
+ ```python
87
+ q, intensity = calculator.line_pattern(domain="q")
88
+ q_grid, profile_q = calculator.pattern(domain="q")
89
+ ```
90
+
91
+ ## Torch and autograd
92
+
93
+ Symmetry detection and HKL enumeration are discrete preprocessing operations.
94
+ Autograd therefore operates on a fixed reflection topology. Rebuild the
95
+ calculator if a lattice change is large enough that reflections can enter or
96
+ leave the configured Q range.
97
+
98
+ ```python
99
+ from braggcalculator import BraggCalculator
100
+ from braggcalculator.backends import TorchBackend
101
+
102
+ calculator = BraggCalculator(backend=TorchBackend(device="cpu")).load(
103
+ "structure.cif"
104
+ )
105
+ parameters = calculator.tensor_parameters(
106
+ requires_grad=["lattice", "frac_coords", "occupancies", "b_iso"]
107
+ )
108
+ grid, profile = calculator.pattern(parameters=parameters)
109
+ loss = profile.square().sum()
110
+ loss.backward()
111
+ ```
112
+
113
+ Use `TorchBackend(device="cuda")` with a CUDA-enabled PyTorch installation to
114
+ run the continuous diffraction and profile kernels on a GPU.
115
+
116
+ Species identities and reflection indices are intentionally not differentiable.
117
+ Isotope-specific neutron samples can select a tabulated isotope through
118
+ `neutron_scattering_lengths={"H": "2H"}` (or supply a measured/custom length)
119
+ because pymatgen structures do not retain isotope identity.
120
+
121
+ By default, `qmax` is derived from the requested 2-theta and Q ranges and the
122
+ physical Ewald limit. An explicit `qmax` that would truncate either output range
123
+ is rejected instead of silently dropping reflections.
124
+
125
+ ## Scientific conventions
126
+
127
+ - Direct lattice vectors are rows in angstroms.
128
+ - `g = 1 / d`, `Q = 2 pi / d`, and `s = sin(theta) / wavelength = g / 2`.
129
+ - Isotropic displacement amplitudes use `exp(-B s^2)`.
130
+ - Line intensities are `|F|^2` times the powder Lorentz-polarization factor.
131
+ - Gaussian profile amplitudes are integrated areas, not peak heights.
132
+ - Every reciprocal point is evaluated explicitly. This makes systematic
133
+ absences emerge from the full structure factor and avoids multiplicity
134
+ double-counting.
135
+
136
+ X-ray coefficients, radiation wavelengths, and coherent elemental neutron
137
+ lengths are read from the required pymatgen dependency. This keeps the source
138
+ of physical values explicit and versioned rather than duplicating an
139
+ unmaintained local table.
140
+
141
+ ## Validation and performance
142
+
143
+ BraggCalculator evaluates the same kinematic equations as pymatgen and does
144
+ not prune the reciprocal set. In pymatgen 2026.5.4, each pattern rebuilds the
145
+ reciprocal points and flattened site arrays, then a Python loop processes one
146
+ reflection at a time; the site sum inside that reflection is vectorized.
147
+ BraggCalculator reduces the primitive cell and constructs the exact reflection
148
+ topology during `load()`. Its numerical kernel processes reflection-by-site
149
+ chunks and merges equal-spacing lines with indexed reductions. Repeated calls
150
+ reuse the topology, and reducible supercells perform numerical work on the
151
+ primitive sites. These two savings are reported separately as cached and
152
+ end-to-end timings.
153
+
154
+ Run the unit and analytical test suite:
155
+
156
+ ```bash
157
+ python -m pytest -q
158
+ ```
159
+
160
+ Validate X-ray and neutron peak positions and normalized intensities against
161
+ pymatgen across cubic, diamond, perovskite, triclinic, disordered, and 40-atom
162
+ P1 cells:
163
+
164
+ ```bash
165
+ python scripts/validate_against_pymatgen.py
166
+ ```
167
+
168
+ Run the reproducible performance comparison. The command fails if either the
169
+ cached or end-to-end calculation is not faster for every case:
170
+
171
+ ```bash
172
+ python benchmarks/benchmark_against_pymatgen.py \
173
+ --number 20 --repeat 7 --require-speedup 1 --json benchmark.json
174
+ ```
175
+
176
+ Performance is machine- and dependency-version-specific, so benchmark JSON
177
+ records the exact environment and all timing samples. The versioned scaling
178
+ data, plotting commands, and CPU/CUDA protocol are documented in
179
+ [the paper README](https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/paper/README.md).
180
+
181
+ ## Demonstration
182
+
183
+ The [NaCl demonstration](https://github.com/FrederikLizakJohansen/BraggCalculator/tree/main/demo)
184
+ loads a CIF, verifies the calculated powder lines against pymatgen, and writes
185
+ an overlay with a residual panel:
186
+
187
+ ```bash
188
+ python -m pip install -e . matplotlib
189
+ python demo/compare_with_pymatgen.py
190
+ ```
191
+
192
+ The script stops if either implementation departs from the stated numerical
193
+ tolerances.
194
+
195
+ ## Data and model references
196
+
197
+ - P. A. Doyle and P. S. Turner, *Acta Crystallographica A* **24**, 390–397
198
+ (1968), DOI: [10.1107/S0567739468000756](https://doi.org/10.1107/S0567739468000756).
199
+ - V. F. Sears, *Neutron News* **3**(3), 26–37 (1992), DOI:
200
+ [10.1080/10448639208218770](https://doi.org/10.1080/10448639208218770).
201
+ - The [pymatgen diffraction documentation](https://pymatgen.org/pymatgen.analysis.diffraction.html)
202
+ describes the independent oracle implementation used in validation.
203
+
204
+ ## License
205
+
206
+ Apache License 2.0. See `LICENSE`.
207
+
@@ -0,0 +1,175 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/FrederikLizakJohansen/BraggCalculator/main/assets/braggcalculator-logo.png" width="650" alt="BraggCalculator logo">
3
+ </p>
4
+
5
+ # BraggCalculator
6
+
7
+ BraggCalculator is a fast, validated powder X-ray and neutron diffraction
8
+ engine for ideal periodic crystals. It evaluates reciprocal-space Bragg
9
+ diffraction with NumPy or optional PyTorch kernels.
10
+
11
+ The current scientific scope is monochromatic, kinematic powder diffraction.
12
+ It includes neutral-atom X-ray form factors, coherent elemental neutron
13
+ scattering lengths, occupancies, isotropic Debye-Waller factors, the standard
14
+ powder Lorentz or Lorentz-polarization correction, and area-normalized Gaussian
15
+ profiles. It does not model diffuse scattering, finite-particle shape, preferred
16
+ orientation, microstrain, absorption, background, anomalous X-ray terms, or
17
+ instrumental wavelength distributions.
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ python -m pip install braggcalculator
23
+ python -m pip install "braggcalculator[torch]" # Torch/autograd/CUDA backend
24
+ python -m pip install "braggcalculator[ase]" # ASE structure input
25
+ ```
26
+
27
+ Python 3.12 and 3.13 are supported. To work from a source checkout, use
28
+ `python -m pip install -e ".[all]"`.
29
+
30
+ The [API reference](https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/docs/api.md)
31
+ documents the public configuration, methods, and result conventions.
32
+
33
+ ## Quick start
34
+
35
+ ```python
36
+ from braggcalculator import BraggCalculator
37
+
38
+ calculator = BraggCalculator(mode="xray", wavelength="CuKa1")
39
+ calculator.load("structure.cif")
40
+
41
+ two_theta, integrated_intensity = calculator.line_pattern(scaled=True)
42
+ grid, profile = calculator.pattern()
43
+ ```
44
+
45
+ `line_pattern()` returns the conventional merged powder lines. `pattern()`
46
+ returns an area-normalized Gaussian profile on a regular grid.
47
+ `reflection_table()` provides the corresponding HKLs, d-spacings, Q values,
48
+ scattering angles, structure factors, and corrected intensities. The
49
+ [API reference](https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/docs/api.md)
50
+ documents lower-level reciprocal-point output and the rules for differentiable
51
+ lattice changes.
52
+
53
+ The Q-space API uses inverse angstroms:
54
+
55
+ ```python
56
+ q, intensity = calculator.line_pattern(domain="q")
57
+ q_grid, profile_q = calculator.pattern(domain="q")
58
+ ```
59
+
60
+ ## Torch and autograd
61
+
62
+ Symmetry detection and HKL enumeration are discrete preprocessing operations.
63
+ Autograd therefore operates on a fixed reflection topology. Rebuild the
64
+ calculator if a lattice change is large enough that reflections can enter or
65
+ leave the configured Q range.
66
+
67
+ ```python
68
+ from braggcalculator import BraggCalculator
69
+ from braggcalculator.backends import TorchBackend
70
+
71
+ calculator = BraggCalculator(backend=TorchBackend(device="cpu")).load(
72
+ "structure.cif"
73
+ )
74
+ parameters = calculator.tensor_parameters(
75
+ requires_grad=["lattice", "frac_coords", "occupancies", "b_iso"]
76
+ )
77
+ grid, profile = calculator.pattern(parameters=parameters)
78
+ loss = profile.square().sum()
79
+ loss.backward()
80
+ ```
81
+
82
+ Use `TorchBackend(device="cuda")` with a CUDA-enabled PyTorch installation to
83
+ run the continuous diffraction and profile kernels on a GPU.
84
+
85
+ Species identities and reflection indices are intentionally not differentiable.
86
+ Isotope-specific neutron samples can select a tabulated isotope through
87
+ `neutron_scattering_lengths={"H": "2H"}` (or supply a measured/custom length)
88
+ because pymatgen structures do not retain isotope identity.
89
+
90
+ By default, `qmax` is derived from the requested 2-theta and Q ranges and the
91
+ physical Ewald limit. An explicit `qmax` that would truncate either output range
92
+ is rejected instead of silently dropping reflections.
93
+
94
+ ## Scientific conventions
95
+
96
+ - Direct lattice vectors are rows in angstroms.
97
+ - `g = 1 / d`, `Q = 2 pi / d`, and `s = sin(theta) / wavelength = g / 2`.
98
+ - Isotropic displacement amplitudes use `exp(-B s^2)`.
99
+ - Line intensities are `|F|^2` times the powder Lorentz-polarization factor.
100
+ - Gaussian profile amplitudes are integrated areas, not peak heights.
101
+ - Every reciprocal point is evaluated explicitly. This makes systematic
102
+ absences emerge from the full structure factor and avoids multiplicity
103
+ double-counting.
104
+
105
+ X-ray coefficients, radiation wavelengths, and coherent elemental neutron
106
+ lengths are read from the required pymatgen dependency. This keeps the source
107
+ of physical values explicit and versioned rather than duplicating an
108
+ unmaintained local table.
109
+
110
+ ## Validation and performance
111
+
112
+ BraggCalculator evaluates the same kinematic equations as pymatgen and does
113
+ not prune the reciprocal set. In pymatgen 2026.5.4, each pattern rebuilds the
114
+ reciprocal points and flattened site arrays, then a Python loop processes one
115
+ reflection at a time; the site sum inside that reflection is vectorized.
116
+ BraggCalculator reduces the primitive cell and constructs the exact reflection
117
+ topology during `load()`. Its numerical kernel processes reflection-by-site
118
+ chunks and merges equal-spacing lines with indexed reductions. Repeated calls
119
+ reuse the topology, and reducible supercells perform numerical work on the
120
+ primitive sites. These two savings are reported separately as cached and
121
+ end-to-end timings.
122
+
123
+ Run the unit and analytical test suite:
124
+
125
+ ```bash
126
+ python -m pytest -q
127
+ ```
128
+
129
+ Validate X-ray and neutron peak positions and normalized intensities against
130
+ pymatgen across cubic, diamond, perovskite, triclinic, disordered, and 40-atom
131
+ P1 cells:
132
+
133
+ ```bash
134
+ python scripts/validate_against_pymatgen.py
135
+ ```
136
+
137
+ Run the reproducible performance comparison. The command fails if either the
138
+ cached or end-to-end calculation is not faster for every case:
139
+
140
+ ```bash
141
+ python benchmarks/benchmark_against_pymatgen.py \
142
+ --number 20 --repeat 7 --require-speedup 1 --json benchmark.json
143
+ ```
144
+
145
+ Performance is machine- and dependency-version-specific, so benchmark JSON
146
+ records the exact environment and all timing samples. The versioned scaling
147
+ data, plotting commands, and CPU/CUDA protocol are documented in
148
+ [the paper README](https://github.com/FrederikLizakJohansen/BraggCalculator/blob/main/paper/README.md).
149
+
150
+ ## Demonstration
151
+
152
+ The [NaCl demonstration](https://github.com/FrederikLizakJohansen/BraggCalculator/tree/main/demo)
153
+ loads a CIF, verifies the calculated powder lines against pymatgen, and writes
154
+ an overlay with a residual panel:
155
+
156
+ ```bash
157
+ python -m pip install -e . matplotlib
158
+ python demo/compare_with_pymatgen.py
159
+ ```
160
+
161
+ The script stops if either implementation departs from the stated numerical
162
+ tolerances.
163
+
164
+ ## Data and model references
165
+
166
+ - P. A. Doyle and P. S. Turner, *Acta Crystallographica A* **24**, 390–397
167
+ (1968), DOI: [10.1107/S0567739468000756](https://doi.org/10.1107/S0567739468000756).
168
+ - V. F. Sears, *Neutron News* **3**(3), 26–37 (1992), DOI:
169
+ [10.1080/10448639208218770](https://doi.org/10.1080/10448639208218770).
170
+ - The [pymatgen diffraction documentation](https://pymatgen.org/pymatgen.analysis.diffraction.html)
171
+ describes the independent oracle implementation used in validation.
172
+
173
+ ## License
174
+
175
+ Apache License 2.0. See `LICENSE`.
@@ -0,0 +1,5 @@
1
+ from .core import BraggCalculator
2
+ from .results import ReflectionTable
3
+ from ._version import __version__
4
+
5
+ __all__ = ["BraggCalculator", "ReflectionTable", "__version__"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,8 @@
1
+ from .numpy_backend import NumpyBackend
2
+
3
+ try:
4
+ from .torch_backend import TorchBackend
5
+ except ImportError: # pragma: no cover
6
+ TorchBackend = None
7
+
8
+ __all__ = ["NumpyBackend", "TorchBackend"]