nudisxs-py 2.0.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.
Files changed (39) hide show
  1. nudisxs_py-2.0.0/LICENSE.txt +9 -0
  2. nudisxs_py-2.0.0/MANIFEST.in +2 -0
  3. nudisxs_py-2.0.0/MIGRATION.md +54 -0
  4. nudisxs_py-2.0.0/PKG-INFO +213 -0
  5. nudisxs_py-2.0.0/README.md +180 -0
  6. nudisxs_py-2.0.0/nudisxs/__about__.py +2 -0
  7. nudisxs_py-2.0.0/nudisxs/__init__.py +13 -0
  8. nudisxs_py-2.0.0/nudisxs/config.py +91 -0
  9. nudisxs_py-2.0.0/nudisxs/constants.py +103 -0
  10. nudisxs_py-2.0.0/nudisxs/disxs.py +383 -0
  11. nudisxs_py-2.0.0/nudisxs/integrand_1dx.py +76 -0
  12. nudisxs_py-2.0.0/nudisxs/integrand_1dy.py +76 -0
  13. nudisxs_py-2.0.0/nudisxs/integrand_2d.py +46 -0
  14. nudisxs_py-2.0.0/nudisxs/integrate/__init__.py +1 -0
  15. nudisxs_py-2.0.0/nudisxs/integrate/quadrature.py +342 -0
  16. nudisxs_py-2.0.0/nudisxs/pdf/__init__.py +5 -0
  17. nudisxs_py-2.0.0/nudisxs/pdf/interp.py +572 -0
  18. nudisxs_py-2.0.0/nudisxs/pdf/lhagrid.py +73 -0
  19. nudisxs_py-2.0.0/nudisxs/pdf/numba_pdf.py +411 -0
  20. nudisxs_py-2.0.0/nudisxs/physics/__init__.py +1 -0
  21. nudisxs_py-2.0.0/nudisxs/physics/kinematics.py +54 -0
  22. nudisxs_py-2.0.0/nudisxs/physics/rfunctions.py +177 -0
  23. nudisxs_py-2.0.0/nudisxs/physics/structure.py +281 -0
  24. nudisxs_py-2.0.0/nudisxs/physics/xsec.py +171 -0
  25. nudisxs_py-2.0.0/nudisxs/tests/__init__.py +3 -0
  26. nudisxs_py-2.0.0/nudisxs/tests/test_dis.py +64 -0
  27. nudisxs_py-2.0.0/nudisxs/tests/test_dis_kinematics.py +21 -0
  28. nudisxs_py-2.0.0/nudisxs/tests/test_dis_total.py +32 -0
  29. nudisxs_py-2.0.0/nudisxs_py.egg-info/PKG-INFO +213 -0
  30. nudisxs_py-2.0.0/nudisxs_py.egg-info/SOURCES.txt +37 -0
  31. nudisxs_py-2.0.0/nudisxs_py.egg-info/dependency_links.txt +1 -0
  32. nudisxs_py-2.0.0/nudisxs_py.egg-info/requires.txt +6 -0
  33. nudisxs_py-2.0.0/nudisxs_py.egg-info/top_level.txt +1 -0
  34. nudisxs_py-2.0.0/pyproject.toml +49 -0
  35. nudisxs_py-2.0.0/setup.cfg +4 -0
  36. nudisxs_py-2.0.0/tests/test_api.py +101 -0
  37. nudisxs_py-2.0.0/tests/test_pdf.py +170 -0
  38. nudisxs_py-2.0.0/tests/test_physics_parity.py +164 -0
  39. nudisxs_py-2.0.0/tests/test_quadrature.py +59 -0
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present U.N. Owen <void@some.where>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include pyproject.toml README.md LICENSE.txt MIGRATION.md
2
+ recursive-include nudisxs *.py
@@ -0,0 +1,54 @@
1
+ # Migrating from nudisxs 1.x (Fortran/f2py) to 2.0 (numba)
2
+
3
+ ## What stays the same
4
+
5
+ - The `disxs` class and its methods (`init_*`, `xs_cc`, `xs_nc`, `xs_cc_as_array`,
6
+ `xs_nc_as_array`, `calculate_total`, `dis_kinematics`, `__call__` as a VEGAS batch
7
+ integrand, `xsdis_as_array(E, x, y, f, n)` filling `f` in place), the units
8
+ (`normfactor = 1.678e-38`) and the default model.
9
+ - VEGAS is the default integrator of `calculate_total` and of the `integrand_*` classes.
10
+ - PDFs come from LHAPDF; any set can be selected with `init_pdf`.
11
+
12
+ ## What is new
13
+
14
+ - `init_pdf(name, member=0)`; LHAPDF IDs, `lhapdf.PDF` objects and `NumbaPDF` accepted.
15
+ - `init_polarization(n_lp)` (COMMON `/n_LP/` of the Fortran code, unreachable from 1.x).
16
+ - `init_target` accepts PDG codes 2212/2112.
17
+ - `total_xs`, `dxs_dx`, `dxs_dy` and `integrator='quad'`: numba quadrature.
18
+ - `xs_points(E, x, y)`: d2sigma/dxdy at arbitrary points, vectorised.
19
+ - `nudisxs.pdf.NumbaPDF`: numba evaluation of any LHAPDF PDF, usable on its own.
20
+ - Independent instances: the Fortran COMMON blocks were process-global.
21
+
22
+ ## Differences of the results
23
+
24
+ The reference for 2.0 is the Fortran code of 1.1.3 (upstream 8fa0973e), compiled with
25
+ consistent double precision. Against it the port agrees to 1e-12 (see README,
26
+ *Validation*). The results of the 1.x *builds* differ from that reference because of
27
+ build problems of the old package:
28
+
29
+ | Issue | Effect in 1.x | 2.0 |
30
+ |---|---|---|
31
+ | **B. Mixed precision.** `libDISxs` was compiled without `-freal-4-real-8` (and without `-O`), while `R_Liang.f` declares its variables and result as `REAL` (4 bytes) and is called as `REAL*8`. | In the 1.1.3 build `R_Liang` returns ~0 (a single-precision bit pattern read as a double), so F_L ≈ 0 for the default `n_RT_DIS=2`; the charm part receives garbage. d2sigma/dxdy differs from the reference by up to ~25% at individual points (median 0.15%). | Double precision throughout: R = R_E143 outside the resonance region, as written. |
32
+ | **A. Liang spline never initialised.** `Rset_Liang`, which tabulates the Liang resonance model, is only called from `FQCD_L_set`, which is never called. | `R_Liang` returns 0 inside the resonance region (1 ≤ W² ≤ 4 GeV², 0.3 ≤ Q² ≤ 5 GeV²). | **Kept** (decision of the port): R = 0 there, exactly as the Fortran code computes it. A switch `r_liang_mode` is reserved for restoring the Liang model later. |
33
+ | 1.1.2 used LHAPDF `x·f` as `f` | F2 too small by a factor x | 1.1.3 behaviour (division by x). |
34
+ | `dis_kinematics(E, x, y)` with N = 1 | failed with numpy ≥ 2 | works |
35
+
36
+ ## Fortran issues and how the port handles them
37
+
38
+ | Fortran | Port |
39
+ |---|---|
40
+ | `R_WBA` with JLab modification (R models 5, 8, 11) evaluates the reference model at an uninitialised `x_0` | evaluated at `x` (as `R_E143` does with the same modification); the only deliberate deviation from the Fortran text |
41
+ | `n_AG_DIS=2` (Bodek–Yang) needs GRV98 from CERN PDFLIB (`NGROUP=5`), stops otherwise | `UnsupportedModelError` |
42
+ | `n_AG_DIS=5`, `n_FL_DIS=1`, `n_RT_DIS=1` need the `FQCD_L` tables that are never built (`FQCD_L_set` writes to `D:/FORTRANout/...`) | `UnsupportedModelError` |
43
+ | `SFNC` defines only models 0 and 1; other switches leave stale values | `UnsupportedModelError` |
44
+ | `BendFactor` defines only types 1, 2, 4 | `UnsupportedModelError` |
45
+ | The legacy `INITPDF` subroutine shadows LHAGLUE's `initpdf_(member)`: only member 0 could be used | `init_pdf(name, member)` |
46
+ | Structure functions were evaluated before the kinematic cuts and discarded outside | evaluated only inside the physical region (same results, fewer PDF calls) |
47
+
48
+ ## Numerical notes
49
+
50
+ - PDF values agree with LHAPDF 6.5 to ~1 ulp inside the grid; the remaining last-bit
51
+ differences come from fused multiply-adds in the compiled LHAPDF and depend on how
52
+ LHAPDF was built. Extrapolation far outside the grid amplifies them (≤ 3e-13).
53
+ - Antineutrino cross sections near y → 1 and F3/F4 at small x are cancellations of
54
+ much larger terms; there the relative agreement is limited by those ulp differences.
@@ -0,0 +1,213 @@
1
+ Metadata-Version: 2.4
2
+ Name: nudisxs-py
3
+ Version: 2.0.0
4
+ Summary: Neutrino-nucleon deep inelastic charged/neutral current cross sections: numba port of the Fortran code by Vadim A. Naumov and Konstantin Kuzmin.
5
+ Author: Vadim A. Naumov and K. Kuzmin
6
+ Maintainer-email: "Dmitry V. Naumov" <dmitryvnaumov@gmail.com>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2022-present U.N. Owen <void@some.where>
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16
+
17
+ Project-URL: Fortran original (nudisxs 1.x), https://git.jinr.ru/dnaumov/nudisxs
18
+ Classifier: Development Status :: 4 - Beta
19
+ Classifier: Intended Audience :: Science/Research
20
+ Classifier: Topic :: Scientific/Engineering :: Physics
21
+ Classifier: Programming Language :: Python
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE.txt
27
+ Requires-Dist: numpy<2.6,>=1.24
28
+ Requires-Dist: numba>=0.68
29
+ Requires-Dist: vegas
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # nudisxs-py
35
+
36
+ Neutrino–nucleon deep inelastic scattering (DIS) cross sections, charged and neutral
37
+ current: the model of V. A. Naumov and K. S. Kuzmin, originally written in Fortran.
38
+
39
+ Version 2 is a pure Python package: the Fortran code has been ported to
40
+ [numba](https://numba.pydata.org/), with the same Python interface as 1.x. PDFs still
41
+ come from [LHAPDF](https://lhapdf.hepforge.org/) — any set can be used — and are
42
+ evaluated in the hot loop by a numba re-implementation of LHAPDF's own grid
43
+ interpolation.
44
+
45
+ - no compilation at install time (no Fortran, CMake, f2py);
46
+ - faster than the Fortran code on one core, 7–10× faster on all cores, and ~40× faster
47
+ for cross-section tables that 1.x filled with Python loops (see *Performance*);
48
+ - several independent configurations (targets, neutrinos, PDF sets) in one process;
49
+ - VEGAS integration as before, plus an optional deterministic quadrature.
50
+
51
+ ## Requirements
52
+
53
+ - Python ≥ 3.10, `numpy`, `numba` ≥ 0.68, `vegas`;
54
+ - LHAPDF with its Python bindings (module `lhapdf`), and the PDF sets you want to use
55
+ (`lhapdf install CT10nlo`). LHAPDF is not on PyPI; follow its
56
+ [installation](https://lhapdf.hepforge.org/install.html) instructions. For a custom
57
+ prefix `/foo/lhapdf`:
58
+
59
+ ```console
60
+ export PATH=$PATH:/foo/lhapdf/bin
61
+ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/foo/lhapdf/lib
62
+ export PYTHONPATH=$PYTHONPATH:/foo/lhapdf/lib/pythonX.Y/site-packages
63
+ ```
64
+
65
+ ## Installation
66
+
67
+ The package is published on PyPI as **`nudisxs-py`** and is imported as **`nudisxs`**, like the Fortran
68
+ package `nudisxs` 1.x it replaces. Both install the same `nudisxs` directory, so remove the old package
69
+ first:
70
+
71
+ ```console
72
+ pip uninstall nudisxs # Fortran 1.x, if installed
73
+ pip install nudisxs-py
74
+ ```
75
+
76
+ From a source checkout: `pip install .` in the repository root.
77
+
78
+ The numba kernels are compiled on first use (20–40 s once) and cached next to the
79
+ sources; later imports take well under a second.
80
+
81
+ ## Usage
82
+
83
+ ```python
84
+ import numpy as np
85
+ from nudisxs.disxs import disxs
86
+
87
+ dis = disxs() # defaults: nu_mu, proton, CT10nlo, Naumov–Kuzmin model
88
+ dis.init_current('cc')
89
+
90
+ dis.xs_cc(100.0, 0.2, 0.5) # d2sigma/dxdy [cm^2] at E=100 GeV, x=0.2, y=0.5
91
+ dis.xs_cc_as_array(np.array([10., 100.]), np.linspace(0, 1, 50), np.linspace(0, 1, 50))
92
+ # another process without re-configuring the instance (current 'cc'/'nc', PDG codes):
93
+ dis.xs_as_array([10., 100.], x, y, current='nc', neutrino=-14, target='neutron')
94
+ dis.xs_cc_as_array([10., 100.], x, y, neutrino=-14) # likewise xs_nc_as_array, xs_points
95
+ dis.calculate_total(100.0) # sigma(E), VEGAS (as in 1.x)
96
+ dis.calculate_total(100.0, integrator='quad') # deterministic quadrature
97
+ dis.total_xs(np.logspace(1, 6, 100)) # sigma(E) table (quadrature, parallel)
98
+ dis.dxs_dx([100.], np.logspace(-4, 0, 50)) # dsigma/dx; dis.dxs_dy(...) likewise
99
+ ```
100
+
101
+ ### Initialization
102
+
103
+ - most used: `init_neutrino(pdg)`, `init_target('proton' | 'neutron' | 2212 | 2112)`,
104
+ `init_pdf(name, member=0)`, `init_current('cc' | 'nc')`;
105
+ - for experts: `init_structure_functions`, `init_r_function`, `init_fl_function`,
106
+ `init_qc`, `init_bend_factor`, `init_abc`, `init_q2_min`, `init_final_hadron_mass`,
107
+ `init_polarization` (new: final-lepton polarisation of the legacy code).
108
+
109
+ Switch values that the legacy code cannot evaluate (Bodek–Yang model 2, which needs
110
+ GRV98 through CERN PDFLIB; the QCD `F_L`/`R` models that need the never-built `FQCD_L`
111
+ tables) raise `UnsupportedModelError` instead of stopping or returning garbage.
112
+
113
+ ### PDFs
114
+
115
+ `init_pdf` accepts an LHAPDF set name (`'CT18NLO'`, or the 1.x style `'CT10nlo.LHgrid'`),
116
+ an LHAPDF ID, an `lhapdf.PDF` object or a `NumbaPDF`. The numba interpolation can be
117
+ used on its own as well:
118
+
119
+ ```python
120
+ from nudisxs.pdf import NumbaPDF, interp
121
+ pdf = NumbaPDF.from_lhapdf('CT10nlo', member=0)
122
+ pdf.xfxQ2(2, x_array, q2_array) # like lhapdf.xfxQ2, vectorised and multi-threaded
123
+ pdf.validate() # comparison with LHAPDF itself
124
+ # inside your own @njit code: interp.xfxq2(pdf.grid, pid, x, q2)
125
+ ```
126
+
127
+ For `lhagrid1` sets with LHAPDF's `logcubic`/`log` interpolators (practically all sets)
128
+ the values agree with LHAPDF to ~1e-16 inside the grid, including subgrids and all
129
+ extrapolation modes. Other PDFs are tabulated through LHAPDF (`mode='tabulate'`,
130
+ typically ~1e-6 accurate; `validate()` reports the accuracy).
131
+
132
+ ### Integrators
133
+
134
+ `calculate_total` uses VEGAS by default, exactly as 1.x (`self.integrator`, `nitn=10`);
135
+ `integrator='quad'` selects a Gauss–Legendre quadrature over the exact physical
136
+ region with breakpoints at the discontinuities of the integrand (charm thresholds,
137
+ edges of the resonance region, `Q2 = Q2_DIS`). Its default accuracy is ~2e-5, against
138
+ the 1e-3 statistical error of the default VEGAS setup. `integrand_1dx/1dy/2d` keep VEGAS
139
+ and accept `integrator='quad'` in `calculate_as_array`.
140
+
141
+ `nudisxs.disxs.set_num_threads(n)` limits the number of threads.
142
+
143
+ ## Performance
144
+
145
+ Apple M5 (10 cores), CT10nlo, `python benchmarks/bench_vs_fortran.py`. Every row
146
+ compares the same quantity on the same points.
147
+
148
+ **d2sigma/dxdy at random (x, y) in the unit square** (CC, default model), time per point:
149
+
150
+ | E | Fortran 1.x | Fortran `-O2` | numba, 1 thread | numba, 10 threads |
151
+ |---|---|---|---|---|
152
+ | 10 GeV | 705 ns | 790 ns | 455 ns | 48 ns |
153
+ | 1e6 GeV | 360 ns | 471 ns | 475 ns | 50 ns |
154
+
155
+ **`xs_cc_as_array` / `xs_nc_as_array`**, grid E = 10, 30, 100 GeV × y × x, time per point
156
+ (1.x looped over scalar Fortran calls in Python; "Fortran array" is the best the old
157
+ extension allows: its array routine called once per energy):
158
+
159
+ | grid | | Fortran 1.x loop | Fortran array | numba, 10 threads |
160
+ |---|---|---|---|---|
161
+ | 3×100×100 = 3·10⁴ | CC ν p / ν̄ p / ν n | 2.1–2.3 µs | 1.9–2.0 µs | 53–57 ns (1.6 ms in all) |
162
+ | | NC ν p / ν̄ n | 0.55 µs | 0.33 µs | 29 ns (0.9 ms) |
163
+ | 3×316×316 = 3·10⁵ | CC ν p / ν̄ p / ν n | – | 0.99 µs | 48–51 ns (15 ms) |
164
+ | | NC ν p / ν̄ n | – | 0.31 µs | 26–28 ns (8 ms) |
165
+
166
+ The time in parentheses is the wall-clock time of the whole call (all points of the
167
+ grid, the multiplication by `normfactor` included); "per point" is that time divided by
168
+ the number of points. With 10 threads the points are computed concurrently, so the CPU
169
+ time spent per point is ~10 times larger (~0.4–0.5 µs, as on one thread: 1 thread takes
170
+ 11.6 ms for 3·10⁴ points, 116 ms for 3·10⁵). A call also has a fixed cost of ~0.1 ms
171
+ (dispatch, waking the threads), negligible from ~10³ points on.
172
+
173
+ **Threads**: 4·10⁵ points, E = 1 TeV: 1 / 2 / 4 / 6 / 8 / 10 threads take 434 / 219 /
174
+ 110 / 76 / 61 / 51 ns per point (×8.5 on the 4 performance + 6 efficiency cores).
175
+
176
+ **Small calls**: starting the threads of a parallel region costs ~0.1 ms on macOS,
177
+ because idle worker threads sleep. Calls with fewer than ~300 points therefore use a
178
+ serial kernel (break-even measured at ~270 points). Workloads made of many small
179
+ parallel calls (VEGAS batches) can use the OpenMP threading layer with spinning threads,
180
+ which cuts that cost to ~5 µs, if `libomp` is installed (macOS: `brew install libomp`):
181
+
182
+ ```console
183
+ export DYLD_FALLBACK_LIBRARY_PATH=$(brew --prefix libomp)/lib # macOS only
184
+ export NUMBA_THREADING_LAYER=omp KMP_BLOCKTIME=200
185
+ ```
186
+
187
+ **JIT compilation**: the first use after installation compiles the kernels (~27 s);
188
+ they are cached, after which import and first calls take ~0.7 s.
189
+
190
+ **Total cross section sigma(E), 100 energies 10 GeV – 1 PeV**, total time:
191
+
192
+ | VEGAS + Fortran 1.x | VEGAS + numba | numba quadrature |
193
+ |---|---|---|
194
+ | 564 ms (stat. error ~4e-3) | 303 ms (same VEGAS setup); 214 ms with the OpenMP settings above | 74 ms (error ~1e-5) |
195
+
196
+ ## Validation
197
+
198
+ `pytest` compares the port with the original Fortran sources (`legacy/fortran`, compiled
199
+ with consistent double precision: `bash tests/oracle/build_oracle.sh`; the results are
200
+ stored in `tests/data/golden.npz`): 212 switch configurations, the structure functions,
201
+ all R models and the kinematic limits agree to 1e-12 (to ~1e-15 apart from
202
+ cancellations), with identical kinematic cuts. The same holds with CT18NLO and with
203
+ MSHT20nlo_as118, whose grid is split into subgrids at Q = 1.4 and 4.75 GeV: all 212
204
+ configurations agree to 6e-12, also with Q2 exactly on the subgrid boundaries, and
205
+ `NumbaPDF` matches LHAPDF for their members to ~2e-13 relative to the PDF scale
206
+ (~1e-16 inside the grid, ~1e-14 around the subgrid boundaries). The PDF tests on these
207
+ sets are skipped when the sets are not installed (`lhapdf install CT18NLO MSHT20nlo_as118`). See [MIGRATION.md](MIGRATION.md) for
208
+ the differences with the results of the 1.x builds.
209
+
210
+ ## License
211
+
212
+ `nudisxs` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html)
213
+ license.
@@ -0,0 +1,180 @@
1
+ # nudisxs-py
2
+
3
+ Neutrino–nucleon deep inelastic scattering (DIS) cross sections, charged and neutral
4
+ current: the model of V. A. Naumov and K. S. Kuzmin, originally written in Fortran.
5
+
6
+ Version 2 is a pure Python package: the Fortran code has been ported to
7
+ [numba](https://numba.pydata.org/), with the same Python interface as 1.x. PDFs still
8
+ come from [LHAPDF](https://lhapdf.hepforge.org/) — any set can be used — and are
9
+ evaluated in the hot loop by a numba re-implementation of LHAPDF's own grid
10
+ interpolation.
11
+
12
+ - no compilation at install time (no Fortran, CMake, f2py);
13
+ - faster than the Fortran code on one core, 7–10× faster on all cores, and ~40× faster
14
+ for cross-section tables that 1.x filled with Python loops (see *Performance*);
15
+ - several independent configurations (targets, neutrinos, PDF sets) in one process;
16
+ - VEGAS integration as before, plus an optional deterministic quadrature.
17
+
18
+ ## Requirements
19
+
20
+ - Python ≥ 3.10, `numpy`, `numba` ≥ 0.68, `vegas`;
21
+ - LHAPDF with its Python bindings (module `lhapdf`), and the PDF sets you want to use
22
+ (`lhapdf install CT10nlo`). LHAPDF is not on PyPI; follow its
23
+ [installation](https://lhapdf.hepforge.org/install.html) instructions. For a custom
24
+ prefix `/foo/lhapdf`:
25
+
26
+ ```console
27
+ export PATH=$PATH:/foo/lhapdf/bin
28
+ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/foo/lhapdf/lib
29
+ export PYTHONPATH=$PYTHONPATH:/foo/lhapdf/lib/pythonX.Y/site-packages
30
+ ```
31
+
32
+ ## Installation
33
+
34
+ The package is published on PyPI as **`nudisxs-py`** and is imported as **`nudisxs`**, like the Fortran
35
+ package `nudisxs` 1.x it replaces. Both install the same `nudisxs` directory, so remove the old package
36
+ first:
37
+
38
+ ```console
39
+ pip uninstall nudisxs # Fortran 1.x, if installed
40
+ pip install nudisxs-py
41
+ ```
42
+
43
+ From a source checkout: `pip install .` in the repository root.
44
+
45
+ The numba kernels are compiled on first use (20–40 s once) and cached next to the
46
+ sources; later imports take well under a second.
47
+
48
+ ## Usage
49
+
50
+ ```python
51
+ import numpy as np
52
+ from nudisxs.disxs import disxs
53
+
54
+ dis = disxs() # defaults: nu_mu, proton, CT10nlo, Naumov–Kuzmin model
55
+ dis.init_current('cc')
56
+
57
+ dis.xs_cc(100.0, 0.2, 0.5) # d2sigma/dxdy [cm^2] at E=100 GeV, x=0.2, y=0.5
58
+ dis.xs_cc_as_array(np.array([10., 100.]), np.linspace(0, 1, 50), np.linspace(0, 1, 50))
59
+ # another process without re-configuring the instance (current 'cc'/'nc', PDG codes):
60
+ dis.xs_as_array([10., 100.], x, y, current='nc', neutrino=-14, target='neutron')
61
+ dis.xs_cc_as_array([10., 100.], x, y, neutrino=-14) # likewise xs_nc_as_array, xs_points
62
+ dis.calculate_total(100.0) # sigma(E), VEGAS (as in 1.x)
63
+ dis.calculate_total(100.0, integrator='quad') # deterministic quadrature
64
+ dis.total_xs(np.logspace(1, 6, 100)) # sigma(E) table (quadrature, parallel)
65
+ dis.dxs_dx([100.], np.logspace(-4, 0, 50)) # dsigma/dx; dis.dxs_dy(...) likewise
66
+ ```
67
+
68
+ ### Initialization
69
+
70
+ - most used: `init_neutrino(pdg)`, `init_target('proton' | 'neutron' | 2212 | 2112)`,
71
+ `init_pdf(name, member=0)`, `init_current('cc' | 'nc')`;
72
+ - for experts: `init_structure_functions`, `init_r_function`, `init_fl_function`,
73
+ `init_qc`, `init_bend_factor`, `init_abc`, `init_q2_min`, `init_final_hadron_mass`,
74
+ `init_polarization` (new: final-lepton polarisation of the legacy code).
75
+
76
+ Switch values that the legacy code cannot evaluate (Bodek–Yang model 2, which needs
77
+ GRV98 through CERN PDFLIB; the QCD `F_L`/`R` models that need the never-built `FQCD_L`
78
+ tables) raise `UnsupportedModelError` instead of stopping or returning garbage.
79
+
80
+ ### PDFs
81
+
82
+ `init_pdf` accepts an LHAPDF set name (`'CT18NLO'`, or the 1.x style `'CT10nlo.LHgrid'`),
83
+ an LHAPDF ID, an `lhapdf.PDF` object or a `NumbaPDF`. The numba interpolation can be
84
+ used on its own as well:
85
+
86
+ ```python
87
+ from nudisxs.pdf import NumbaPDF, interp
88
+ pdf = NumbaPDF.from_lhapdf('CT10nlo', member=0)
89
+ pdf.xfxQ2(2, x_array, q2_array) # like lhapdf.xfxQ2, vectorised and multi-threaded
90
+ pdf.validate() # comparison with LHAPDF itself
91
+ # inside your own @njit code: interp.xfxq2(pdf.grid, pid, x, q2)
92
+ ```
93
+
94
+ For `lhagrid1` sets with LHAPDF's `logcubic`/`log` interpolators (practically all sets)
95
+ the values agree with LHAPDF to ~1e-16 inside the grid, including subgrids and all
96
+ extrapolation modes. Other PDFs are tabulated through LHAPDF (`mode='tabulate'`,
97
+ typically ~1e-6 accurate; `validate()` reports the accuracy).
98
+
99
+ ### Integrators
100
+
101
+ `calculate_total` uses VEGAS by default, exactly as 1.x (`self.integrator`, `nitn=10`);
102
+ `integrator='quad'` selects a Gauss–Legendre quadrature over the exact physical
103
+ region with breakpoints at the discontinuities of the integrand (charm thresholds,
104
+ edges of the resonance region, `Q2 = Q2_DIS`). Its default accuracy is ~2e-5, against
105
+ the 1e-3 statistical error of the default VEGAS setup. `integrand_1dx/1dy/2d` keep VEGAS
106
+ and accept `integrator='quad'` in `calculate_as_array`.
107
+
108
+ `nudisxs.disxs.set_num_threads(n)` limits the number of threads.
109
+
110
+ ## Performance
111
+
112
+ Apple M5 (10 cores), CT10nlo, `python benchmarks/bench_vs_fortran.py`. Every row
113
+ compares the same quantity on the same points.
114
+
115
+ **d2sigma/dxdy at random (x, y) in the unit square** (CC, default model), time per point:
116
+
117
+ | E | Fortran 1.x | Fortran `-O2` | numba, 1 thread | numba, 10 threads |
118
+ |---|---|---|---|---|
119
+ | 10 GeV | 705 ns | 790 ns | 455 ns | 48 ns |
120
+ | 1e6 GeV | 360 ns | 471 ns | 475 ns | 50 ns |
121
+
122
+ **`xs_cc_as_array` / `xs_nc_as_array`**, grid E = 10, 30, 100 GeV × y × x, time per point
123
+ (1.x looped over scalar Fortran calls in Python; "Fortran array" is the best the old
124
+ extension allows: its array routine called once per energy):
125
+
126
+ | grid | | Fortran 1.x loop | Fortran array | numba, 10 threads |
127
+ |---|---|---|---|---|
128
+ | 3×100×100 = 3·10⁴ | CC ν p / ν̄ p / ν n | 2.1–2.3 µs | 1.9–2.0 µs | 53–57 ns (1.6 ms in all) |
129
+ | | NC ν p / ν̄ n | 0.55 µs | 0.33 µs | 29 ns (0.9 ms) |
130
+ | 3×316×316 = 3·10⁵ | CC ν p / ν̄ p / ν n | – | 0.99 µs | 48–51 ns (15 ms) |
131
+ | | NC ν p / ν̄ n | – | 0.31 µs | 26–28 ns (8 ms) |
132
+
133
+ The time in parentheses is the wall-clock time of the whole call (all points of the
134
+ grid, the multiplication by `normfactor` included); "per point" is that time divided by
135
+ the number of points. With 10 threads the points are computed concurrently, so the CPU
136
+ time spent per point is ~10 times larger (~0.4–0.5 µs, as on one thread: 1 thread takes
137
+ 11.6 ms for 3·10⁴ points, 116 ms for 3·10⁵). A call also has a fixed cost of ~0.1 ms
138
+ (dispatch, waking the threads), negligible from ~10³ points on.
139
+
140
+ **Threads**: 4·10⁵ points, E = 1 TeV: 1 / 2 / 4 / 6 / 8 / 10 threads take 434 / 219 /
141
+ 110 / 76 / 61 / 51 ns per point (×8.5 on the 4 performance + 6 efficiency cores).
142
+
143
+ **Small calls**: starting the threads of a parallel region costs ~0.1 ms on macOS,
144
+ because idle worker threads sleep. Calls with fewer than ~300 points therefore use a
145
+ serial kernel (break-even measured at ~270 points). Workloads made of many small
146
+ parallel calls (VEGAS batches) can use the OpenMP threading layer with spinning threads,
147
+ which cuts that cost to ~5 µs, if `libomp` is installed (macOS: `brew install libomp`):
148
+
149
+ ```console
150
+ export DYLD_FALLBACK_LIBRARY_PATH=$(brew --prefix libomp)/lib # macOS only
151
+ export NUMBA_THREADING_LAYER=omp KMP_BLOCKTIME=200
152
+ ```
153
+
154
+ **JIT compilation**: the first use after installation compiles the kernels (~27 s);
155
+ they are cached, after which import and first calls take ~0.7 s.
156
+
157
+ **Total cross section sigma(E), 100 energies 10 GeV – 1 PeV**, total time:
158
+
159
+ | VEGAS + Fortran 1.x | VEGAS + numba | numba quadrature |
160
+ |---|---|---|
161
+ | 564 ms (stat. error ~4e-3) | 303 ms (same VEGAS setup); 214 ms with the OpenMP settings above | 74 ms (error ~1e-5) |
162
+
163
+ ## Validation
164
+
165
+ `pytest` compares the port with the original Fortran sources (`legacy/fortran`, compiled
166
+ with consistent double precision: `bash tests/oracle/build_oracle.sh`; the results are
167
+ stored in `tests/data/golden.npz`): 212 switch configurations, the structure functions,
168
+ all R models and the kinematic limits agree to 1e-12 (to ~1e-15 apart from
169
+ cancellations), with identical kinematic cuts. The same holds with CT18NLO and with
170
+ MSHT20nlo_as118, whose grid is split into subgrids at Q = 1.4 and 4.75 GeV: all 212
171
+ configurations agree to 6e-12, also with Q2 exactly on the subgrid boundaries, and
172
+ `NumbaPDF` matches LHAPDF for their members to ~2e-13 relative to the PDF scale
173
+ (~1e-16 inside the grid, ~1e-14 around the subgrid boundaries). The PDF tests on these
174
+ sets are skipped when the sets are not installed (`lhapdf install CT18NLO MSHT20nlo_as118`). See [MIGRATION.md](MIGRATION.md) for
175
+ the differences with the results of the 1.x builds.
176
+
177
+ ## License
178
+
179
+ `nudisxs` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html)
180
+ license.
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: MIT
2
+ __version__ = '2.0.0'
@@ -0,0 +1,13 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """nudisxs: neutrino-nucleon DIS cross sections (numba port of the Naumov-Kuzmin code)."""
3
+ from .__about__ import __version__
4
+ from .pdf import NumbaPDF
5
+
6
+ __all__ = ["__version__", "NumbaPDF", "disxs"]
7
+
8
+
9
+ def __getattr__(name): # lazy: importing disxs configures logging, as in 1.x
10
+ if name == "disxs":
11
+ from .disxs import disxs
12
+ return disxs
13
+ raise AttributeError(name)
@@ -0,0 +1,91 @@
1
+ """Model configuration: the replacement of the legacy COMMON blocks.
2
+
3
+ :class:`DISParams` is an immutable NamedTuple of plain numbers that the numba kernels
4
+ receive as an argument, so several independent configurations can coexist (and be used
5
+ from several threads), unlike the global COMMON blocks of the Fortran code.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import NamedTuple
10
+
11
+ from . import constants as C
12
+
13
+
14
+ class DISParams(NamedTuple):
15
+ n_NT: int = 1 # +1 neutrino, -1 antineutrino (COMMON /n_NT/)
16
+ n_TT: int = 1 # 1 proton, 2 neutron (/n_TT/)
17
+ n_LP: int = 0 # lepton polarisation: 0 none, +-1 (/n_LP/)
18
+ n_AG: int = 1 # structure-function model (/n_AG_DIS/)
19
+ n_FL: int = 2 # F_L model (/n_FL_DIS/)
20
+ n_RT: int = 2 # R = sigma_L/sigma_T model (/n_RT_DIS/)
21
+ n_Rc: int = 1 # modification of R for charm (/n_Rc_DIS/)
22
+ n_Qc: int = 0 # PDF limitation: 0 -> x rescaling below Q2_DIS (/n_Qc_DIS/)
23
+ n_BF: int = 1 # "bend factor" type (/n_BF_DIS/)
24
+ m_ini: float = C.PY_M_P
25
+ mm_ini: float = C.PY_M_P ** 2
26
+ m_lep: float = C.PY_M_MU
27
+ mm_lep: float = C.PY_M_MU ** 2
28
+ m_fin: float = 1.2
29
+ mm_fin: float = 1.2 ** 2
30
+ Q2_DIS: float = 1.0
31
+ A0: float = 0.0
32
+ B0: float = 0.0
33
+ C0: float = 0.0
34
+
35
+
36
+ R_LIANG_MODES = ("fortran",)
37
+
38
+ _CC_MODELS = {0: "Paschos-Yu", 1: "Naumov-Kuzmin", 3: "Naumov '1-2' scheme", 4: "Yang",
39
+ 6: "Naumov test scheme"}
40
+ _NC_MODELS = {0: "Paschos-Yu", 1: "Naumov-Kuzmin"}
41
+
42
+
43
+ class UnsupportedModelError(ValueError):
44
+ """A switch combination that the legacy code cannot evaluate meaningfully."""
45
+
46
+
47
+ def validate(p: DISParams, current: str = "cc") -> None:
48
+ """Raise :class:`UnsupportedModelError` for switch values that are broken in the
49
+ legacy code; only switches actually used by the selected model are checked."""
50
+ if p.n_NT not in (1, -1):
51
+ raise UnsupportedModelError(f"n_NT must be +1 or -1, got {p.n_NT}")
52
+ if p.n_TT not in (1, 2):
53
+ raise UnsupportedModelError(f"n_TT must be 1 (proton) or 2 (neutron), got {p.n_TT}")
54
+ if current == "nc":
55
+ if p.n_AG not in _NC_MODELS:
56
+ raise UnsupportedModelError(
57
+ f"neutral current: structure-function model {p.n_AG} is not defined in the legacy "
58
+ f"code (SFNC implements models {sorted(_NC_MODELS)})")
59
+ return
60
+ if current != "cc":
61
+ raise ValueError(f"unknown current {current!r}")
62
+ if p.n_LP not in (0, 1, -1):
63
+ raise UnsupportedModelError(f"n_LP must be 0, +1 or -1, got {p.n_LP}")
64
+ if p.n_AG == 2:
65
+ raise UnsupportedModelError(
66
+ "n_AG_DIS=2 (Bodek-Yang) needs the GRV98 PDF through CERN PDFLIB (NGROUP=5); "
67
+ "the legacy code stops with 'CASE FOR GRV 98 PDF ONLY'")
68
+ if p.n_AG == 5:
69
+ raise UnsupportedModelError(
70
+ "n_AG_DIS=5 needs the FQCD_L tables, which the package never builds (FQCD_L_set is dead code)")
71
+ if p.n_AG not in _CC_MODELS:
72
+ raise UnsupportedModelError(f"unknown structure-function model n_AG_DIS={p.n_AG}")
73
+ uses_fl = p.n_AG == 1
74
+ uses_r = p.n_AG in (3, 4, 6) or (uses_fl and p.n_FL == 2)
75
+ uses_rc = p.n_AG in (1, 3, 4, 6)
76
+ if uses_fl:
77
+ if p.n_FL == 1:
78
+ raise UnsupportedModelError(
79
+ "n_FL_DIS=1 (QCD F_L) needs the FQCD_L tables, which the package never builds")
80
+ if p.n_FL not in (0, 2):
81
+ raise UnsupportedModelError(f"unknown F_L model n_FL_DIS={p.n_FL}")
82
+ if p.n_BF not in (1, 2, 4):
83
+ raise UnsupportedModelError(f"n_BF_DIS must be 1, 2 or 4, got {p.n_BF}")
84
+ if uses_r:
85
+ if p.n_RT == 1:
86
+ raise UnsupportedModelError(
87
+ "n_RT_DIS=1 (QCD R) needs the FQCD_L tables, which the package never builds")
88
+ if not (p.n_RT == 0 or 2 <= p.n_RT <= 19):
89
+ raise UnsupportedModelError(f"unknown R model n_RT_DIS={p.n_RT}")
90
+ if uses_rc and p.n_Rc not in (0, 1):
91
+ raise UnsupportedModelError(f"n_Rc_DIS must be 0 or 1, got {p.n_Rc}")