Metadata-Version: 2.4
Name: nudisxs-py
Version: 2.0.0
Summary: Neutrino-nucleon deep inelastic charged/neutral current cross sections: numba port of the Fortran code by Vadim A. Naumov and Konstantin Kuzmin.
Author: Vadim A. Naumov and K. Kuzmin
Maintainer-email: "Dmitry V. Naumov" <dmitryvnaumov@gmail.com>
License: MIT License
        
        Copyright (c) 2022-present U.N. Owen <void@some.where>
        
        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:
        
        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        
        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.
        
Project-URL: Fortran original (nudisxs 1.x), https://git.jinr.ru/dnaumov/nudisxs
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: Implementation :: CPython
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: numpy<2.6,>=1.24
Requires-Dist: numba>=0.68
Requires-Dist: vegas
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Dynamic: license-file

# nudisxs-py

Neutrino–nucleon deep inelastic scattering (DIS) cross sections, charged and neutral
current: the model of V. A. Naumov and K. S. Kuzmin, originally written in Fortran.

Version 2 is a pure Python package: the Fortran code has been ported to
[numba](https://numba.pydata.org/), with the same Python interface as 1.x.  PDFs still
come from [LHAPDF](https://lhapdf.hepforge.org/) — any set can be used — and are
evaluated in the hot loop by a numba re-implementation of LHAPDF's own grid
interpolation.

- no compilation at install time (no Fortran, CMake, f2py);
- faster than the Fortran code on one core, 7–10× faster on all cores, and ~40× faster
  for cross-section tables that 1.x filled with Python loops (see *Performance*);
- several independent configurations (targets, neutrinos, PDF sets) in one process;
- VEGAS integration as before, plus an optional deterministic quadrature.

## Requirements

- Python ≥ 3.10, `numpy`, `numba` ≥ 0.68, `vegas`;
- LHAPDF with its Python bindings (module `lhapdf`), and the PDF sets you want to use
  (`lhapdf install CT10nlo`).  LHAPDF is not on PyPI; follow its
  [installation](https://lhapdf.hepforge.org/install.html) instructions.  For a custom
  prefix `/foo/lhapdf`:

```console
export PATH=$PATH:/foo/lhapdf/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/foo/lhapdf/lib
export PYTHONPATH=$PYTHONPATH:/foo/lhapdf/lib/pythonX.Y/site-packages
```

## Installation

The package is published on PyPI as **`nudisxs-py`** and is imported as **`nudisxs`**, like the Fortran
package `nudisxs` 1.x it replaces.  Both install the same `nudisxs` directory, so remove the old package
first:

```console
pip uninstall nudisxs        # Fortran 1.x, if installed
pip install nudisxs-py
```

From a source checkout: `pip install .` in the repository root.

The numba kernels are compiled on first use (20–40 s once) and cached next to the
sources; later imports take well under a second.

## Usage

```python
import numpy as np
from nudisxs.disxs import disxs

dis = disxs()                     # defaults: nu_mu, proton, CT10nlo, Naumov–Kuzmin model
dis.init_current('cc')

dis.xs_cc(100.0, 0.2, 0.5)        # d2sigma/dxdy [cm^2] at E=100 GeV, x=0.2, y=0.5
dis.xs_cc_as_array(np.array([10., 100.]), np.linspace(0, 1, 50), np.linspace(0, 1, 50))
# another process without re-configuring the instance (current 'cc'/'nc', PDG codes):
dis.xs_as_array([10., 100.], x, y, current='nc', neutrino=-14, target='neutron')
dis.xs_cc_as_array([10., 100.], x, y, neutrino=-14)      # likewise xs_nc_as_array, xs_points
dis.calculate_total(100.0)                       # sigma(E), VEGAS (as in 1.x)
dis.calculate_total(100.0, integrator='quad')    # deterministic quadrature
dis.total_xs(np.logspace(1, 6, 100))             # sigma(E) table (quadrature, parallel)
dis.dxs_dx([100.], np.logspace(-4, 0, 50))       # dsigma/dx;  dis.dxs_dy(...) likewise
```

### Initialization

- most used: `init_neutrino(pdg)`, `init_target('proton' | 'neutron' | 2212 | 2112)`,
  `init_pdf(name, member=0)`, `init_current('cc' | 'nc')`;
- for experts: `init_structure_functions`, `init_r_function`, `init_fl_function`,
  `init_qc`, `init_bend_factor`, `init_abc`, `init_q2_min`, `init_final_hadron_mass`,
  `init_polarization` (new: final-lepton polarisation of the legacy code).

Switch values that the legacy code cannot evaluate (Bodek–Yang model 2, which needs
GRV98 through CERN PDFLIB; the QCD `F_L`/`R` models that need the never-built `FQCD_L`
tables) raise `UnsupportedModelError` instead of stopping or returning garbage.

### PDFs

`init_pdf` accepts an LHAPDF set name (`'CT18NLO'`, or the 1.x style `'CT10nlo.LHgrid'`),
an LHAPDF ID, an `lhapdf.PDF` object or a `NumbaPDF`.  The numba interpolation can be
used on its own as well:

```python
from nudisxs.pdf import NumbaPDF, interp
pdf = NumbaPDF.from_lhapdf('CT10nlo', member=0)
pdf.xfxQ2(2, x_array, q2_array)   # like lhapdf.xfxQ2, vectorised and multi-threaded
pdf.validate()                    # comparison with LHAPDF itself
# inside your own @njit code:  interp.xfxq2(pdf.grid, pid, x, q2)
```

For `lhagrid1` sets with LHAPDF's `logcubic`/`log` interpolators (practically all sets)
the values agree with LHAPDF to ~1e-16 inside the grid, including subgrids and all
extrapolation modes.  Other PDFs are tabulated through LHAPDF (`mode='tabulate'`,
typically ~1e-6 accurate; `validate()` reports the accuracy).

### Integrators

`calculate_total` uses VEGAS by default, exactly as 1.x (`self.integrator`, `nitn=10`);
`integrator='quad'` selects a Gauss–Legendre quadrature over the exact physical
region with breakpoints at the discontinuities of the integrand (charm thresholds,
edges of the resonance region, `Q2 = Q2_DIS`).  Its default accuracy is ~2e-5, against
the 1e-3 statistical error of the default VEGAS setup.  `integrand_1dx/1dy/2d` keep VEGAS
and accept `integrator='quad'` in `calculate_as_array`.

`nudisxs.disxs.set_num_threads(n)` limits the number of threads.

## Performance

Apple M5 (10 cores), CT10nlo, `python benchmarks/bench_vs_fortran.py`.  Every row
compares the same quantity on the same points.

**d2sigma/dxdy at random (x, y) in the unit square** (CC, default model), time per point:

| E | Fortran 1.x | Fortran `-O2` | numba, 1 thread | numba, 10 threads |
|---|---|---|---|---|
| 10 GeV | 705 ns | 790 ns | 455 ns | 48 ns |
| 1e6 GeV | 360 ns | 471 ns | 475 ns | 50 ns |

**`xs_cc_as_array` / `xs_nc_as_array`**, grid E = 10, 30, 100 GeV × y × x, time per point
(1.x looped over scalar Fortran calls in Python; "Fortran array" is the best the old
extension allows: its array routine called once per energy):

| grid | | Fortran 1.x loop | Fortran array | numba, 10 threads |
|---|---|---|---|---|
| 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) |
| | NC ν p / ν̄ n | 0.55 µs | 0.33 µs | 29 ns (0.9 ms) |
| 3×316×316 = 3·10⁵ | CC ν p / ν̄ p / ν n | – | 0.99 µs | 48–51 ns (15 ms) |
| | NC ν p / ν̄ n | – | 0.31 µs | 26–28 ns (8 ms) |

The time in parentheses is the wall-clock time of the whole call (all points of the
grid, the multiplication by `normfactor` included); "per point" is that time divided by
the number of points.  With 10 threads the points are computed concurrently, so the CPU
time spent per point is ~10 times larger (~0.4–0.5 µs, as on one thread: 1 thread takes
11.6 ms for 3·10⁴ points, 116 ms for 3·10⁵).  A call also has a fixed cost of ~0.1 ms
(dispatch, waking the threads), negligible from ~10³ points on.

**Threads**: 4·10⁵ points, E = 1 TeV: 1 / 2 / 4 / 6 / 8 / 10 threads take 434 / 219 /
110 / 76 / 61 / 51 ns per point (×8.5 on the 4 performance + 6 efficiency cores).

**Small calls**: starting the threads of a parallel region costs ~0.1 ms on macOS,
because idle worker threads sleep.  Calls with fewer than ~300 points therefore use a
serial kernel (break-even measured at ~270 points).  Workloads made of many small
parallel calls (VEGAS batches) can use the OpenMP threading layer with spinning threads,
which cuts that cost to ~5 µs, if `libomp` is installed (macOS: `brew install libomp`):

```console
export DYLD_FALLBACK_LIBRARY_PATH=$(brew --prefix libomp)/lib   # macOS only
export NUMBA_THREADING_LAYER=omp KMP_BLOCKTIME=200
```

**JIT compilation**: the first use after installation compiles the kernels (~27 s);
they are cached, after which import and first calls take ~0.7 s.

**Total cross section sigma(E), 100 energies 10 GeV – 1 PeV**, total time:

| VEGAS + Fortran 1.x | VEGAS + numba | numba quadrature |
|---|---|---|
| 564 ms (stat. error ~4e-3) | 303 ms (same VEGAS setup); 214 ms with the OpenMP settings above | 74 ms (error ~1e-5) |

## Validation

`pytest` compares the port with the original Fortran sources (`legacy/fortran`, compiled
with consistent double precision: `bash tests/oracle/build_oracle.sh`; the results are
stored in `tests/data/golden.npz`): 212 switch configurations, the structure functions,
all R models and the kinematic limits agree to 1e-12 (to ~1e-15 apart from
cancellations), with identical kinematic cuts.  The same holds with CT18NLO and with
MSHT20nlo_as118, whose grid is split into subgrids at Q = 1.4 and 4.75 GeV: all 212
configurations agree to 6e-12, also with Q2 exactly on the subgrid boundaries, and
`NumbaPDF` matches LHAPDF for their members to ~2e-13 relative to the PDF scale
(~1e-16 inside the grid, ~1e-14 around the subgrid boundaries).  The PDF tests on these
sets are skipped when the sets are not installed (`lhapdf install CT18NLO MSHT20nlo_as118`).  See [MIGRATION.md](MIGRATION.md) for
the differences with the results of the 1.x builds.

## License

`nudisxs` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html)
license.
