Metadata-Version: 2.4
Name: rescalculator
Version: 2.0.2
Summary: Triple-Axis Spectrometer Resolution Calculator with Numba/PyTorch acceleration
Author-email: William Ratcliff <william.ratcliff@nist.gov>
Maintainer-email: William Ratcliff <william.ratcliff@nist.gov>
License: MIT License
        
        Copyright (c) 2026 rescalculator contributors
        
        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: Homepage, https://github.com/scattering/rescalculator
Project-URL: Repository, https://github.com/scattering/rescalculator
Project-URL: Issues, https://github.com/scattering/rescalculator/issues
Keywords: neutron scattering,triple-axis spectrometer,resolution,TAS,Cooper-Nathans,pyspinw
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20
Requires-Dist: scipy>=1.7
Requires-Dist: icp-lattice-calculator>=0.1.1
Provides-Extra: fast
Requires-Dist: numba>=0.57; extra == "fast"
Provides-Extra: gpu
Requires-Dist: torch>=2.0; extra == "gpu"
Provides-Extra: all
Requires-Dist: numba>=0.57; extra == "all"
Requires-Dist: torch>=2.0; extra == "all"
Requires-Dist: pyspinw; extra == "all"
Requires-Dist: matplotlib; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: isort; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: numba>=0.57; extra == "dev"
Dynamic: license-file

# Resolution Calculator for Triple-Axis Spectrometers

[![PyPI version](https://badge.fury.io/py/rescalculator.svg)](https://pypi.org/project/rescalculator/)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A Python library for computing resolution matrices and performing S(Q,w) convolutions for Triple-Axis Spectrometer (TAS) experiments. Cooper–Nathans calculations support Numba JIT acceleration; geometry-aware Popovici calculations use a shared NumPy implementation.

Based on ResLib by Andrei Zheludev.

## Features

- **Cooper-Nathans and Popovici resolution formalisms**, selected explicitly with `method=0` or `method=1`
- **Numba JIT acceleration** for Cooper–Nathans resolution calculations
- **Multiple array backends**: NumPy, Numba and optional PyTorch tensor outputs
- **Automatic backend selection**: Prefers Numba when available; Popovici uses the NumPy calculation path
- **S(Q,w) convolution**: Integrate scattering cross-sections with resolution function
- **Batched operations**: Efficient computation for 100,000+ Q-points

## Experimental QMC resolution integration

`qmc_resolution.py` provides a small Sobol/QMC helper for numerical convolution
with a Gaussian TAS resolution kernel. It exposes normalized and unnormalized
Gaussian conventions explicitly so consumers can audit how the instrument `R0`
prefactor is applied.

See `docs/qmc_resolution_integration.md` for usage notes and current
normalization caveats.

## Installation

### From PyPI (Recommended)

```bash
# Include Numba acceleration for Cooper–Nathans calculations
pip install rescalculator[fast]

# Basic version (NumPy only)
pip install rescalculator

# With PyTorch GPU support
pip install rescalculator[gpu]

# Everything (Numba + PyTorch + pyspinw + matplotlib)
pip install rescalculator[all]
```

### From Source

```bash
git clone https://github.com/scattering/rescalculator.git
cd rescalculator
pip install -e .[fast]
```

### Using Conda

```bash
conda create -n resolution python=3.11 numba numpy scipy matplotlib -c conda-forge
conda activate resolution
pip install rescalculator
```

## Quick Start

### Basic Resolution Calculation

```python
import numpy as np
from rescalculator import TASResolution
from lattice_calculator import Lattice, modvec

# Define crystal lattice
lattice = Lattice(
    a=5.0, b=5.0, c=5.0,
    alpha=90, beta=90, gamma=90,
    orient1=np.array([[1, 0, 0]]),
    orient2=np.array([[0, 1, 0]])
)

# Define experiment configuration
EXP = {
    'efixed': 14.7,              # Fixed energy (meV)
    'infin': -1,                 # -1 for fixed Ef, +1 for fixed Ei
    'dir1': 1,                   # Monochromator scattering direction
    'dir2': 1,                   # Analyzer scattering direction
    'hcol': np.array([40, 40, 40, 40]),  # Horizontal collimations (arcmin)
    'vcol': np.array([120, 120, 120, 120]),  # Vertical collimations (arcmin)
    'mono': {'tau': 'pg(002)', 'mosaic': 30},  # Monochromator
    'ana': {'tau': 'pg(002)', 'mosaic': 30},   # Analyzer
    'sample': {'mosaic': 30},                   # Sample mosaic
    'arms': [200, 200, 150, 150, 100],         # L0, L1, L2, L3, Lmono-monitor (cm)
    'horifoc': -1,               # Horizontal focusing (-1 = no focusing)
    'moncor': 1,                 # Monitor correction
}

# Create resolution calculator
res = TASResolution(lattice, backend='numpy')

# Define scan points
H = np.array([1.0, 1.05, 1.1])
K = np.zeros(3)
L = np.zeros(3)
W = np.array([5.0, 5.0, 5.0])  # Energy transfer (meV)
lattice.npts = len(H)

# Calculate resolution matrices
R0, RMS = res.ResMatS(H, K, L, W, [EXP] * len(H))

# R0: Prefactors (normalization)
# RMS: Resolution matrices in sample coordinates, shape (4, 4, npts)
print(f"Resolution matrix at first point:\n{RMS[:,:,0]}")
```

### S(Q,w) Convolution with Spin Waves

```python
import numpy as np
from rescalculator import TASResolution, ConvolutionCalculator
from lattice_calculator import Lattice
from pyspinw import SpinW

# Set up spin wave model using pyspinw
model = SpinW()
model.genlattice(lat_const=[3.0, 3.0, 3.0], angled=[90, 90, 90])
model.addatom(r=[0, 0, 0], S=1, label='Fe')
model.gencoupling(max_distance=4.0)
model.addmatrix(label='J', value=1.0)
model.addcoupling(bond=0, mat_labels='J')
model.genmagstr(mode='direct', S=[[0], [0], [1]])

# Create S(Q,w) function
def sqw_function(h, k, l, w):
    """Spin wave S(Q,w) at given (h,k,l,w)."""
    spec = model.spinwave([[h], [k], [l]], use_surface_integrals=True)
    # ... process spectrum ...
    return intensity

# Set up convolution
lattice = Lattice(a=3.0, b=3.0, c=3.0, alpha=90, beta=90, gamma=90,
                  orient1=np.array([[1,0,0]]), orient2=np.array([[0,1,0]]))

conv = ConvolutionCalculator(
    resolution=TASResolution(lattice, backend='numpy'),
    sqw_function=sqw_function,
    lattice=lattice
)

# Calculate convoluted intensity
H_scan = np.linspace(0.1, 0.9, 50)
K_scan = np.zeros(50)
L_scan = np.zeros(50)
W_scan = np.full(50, 5.0)

intensity = conv.convolve(H_scan, K_scan, L_scan, W_scan, EXP_list)
```

## Performance Notes

`backend='auto'` prefers Numba for Cooper–Nathans calculations when it is installed.
Warm timings depend on scan size, thread count, model and quadrature; the first call
also includes JIT initialization. Benchmark the workload you intend to use.

Popovici currently calculates in NumPy on the CPU with float64 precision, including
when `backend='numba'` or `'pytorch'` is requested. PyTorch results are converted to
the requested device and dtype after calculation (MPS uses float32). This fallback
does not provide PyTorch autograd through the Popovici calculation. The calculator's
`last_calculation_backend` records the backend that performed the calculation;
`last_resolution_method` records the method. The adapter reports these as
`backend_used` and `method_used`, separately from `backend_requested`.

## API Reference

### TASResolution

```python
class TASResolution(lattice, backend='auto')
```

Main resolution calculator class.

**Parameters:**
- `lattice`: Lattice instance from lattice-calculator
- `backend`: 'auto', 'numba', 'numpy', or 'pytorch'

**Methods:**
- `ResMatS(H, K, L, W, EXP)`: Compute resolution matrices in sample coordinates
- `ResMat_vectorized(Q, W, EXP)`: Compute resolution matrices for Q magnitude array
- `set_backend(backend_type)`: Change computational backend

### BatchedTASResolution

```python
class BatchedTASResolution(lattice, device='auto')
```

Resolution calculator with batched PyTorch operations for Cooper–Nathans.
Popovici uses the same CPU NumPy calculation as `TASResolution`, then converts
results to the requested tensor device and dtype.

**Parameters:**
- `lattice`: Lattice instance
- `device`: 'auto', 'cuda', 'mps', or 'cpu'

**Methods:**
- `ResMat_batched(Q, W, EXP)`: Batched resolution calculation returning tensors
- `ResMatS(H, K, L, W, EXP)`: Resolution matrices in sample coordinates

### ConvolutionCalculator

```python
class ConvolutionCalculator(resolution, sqw_function, lattice)
```

Convolves S(Q,w) with resolution function.

**Parameters:**
- `resolution`: TASResolution instance
- `sqw_function`: Function `f(h, k, l, w) -> intensity`
- `lattice`: Lattice instance

### Experiment Configuration (EXP)

The EXP dictionary contains all spectrometer parameters:

```python
EXP = {
    'efixed': 14.7,       # Fixed energy (meV)
    'infin': -1,          # -1 = fixed Ef, +1 = fixed Ei
    'dir1': 1,            # Monochromator scattering direction (+1 or -1)
    'dir2': 1,            # Analyzer scattering direction (+1 or -1)
    'hcol': [40, 40, 40, 40],      # Horizontal collimations (arcmin)
    'vcol': [120, 120, 120, 120],  # Vertical collimations (arcmin)
    'mono': {
        'tau': 'pg(002)',   # Monochromator crystal
        'mosaic': 30,       # Mosaic spread (arcmin)
        'rh': 1e6,          # Horizontal radius (cm), 1e6 = flat
        'rv': 1e6,          # Vertical radius (cm)
    },
    'ana': {
        'tau': 'pg(002)',   # Analyzer crystal
        'mosaic': 30,
        'rh': 1e6,
        'rv': 1e6,
    },
    'sample': {
        'mosaic': 30,       # Sample mosaic (arcmin)
        'vmosaic': 30,      # Vertical sample mosaic (arcmin)
    },
    'arms': [200, 200, 150, 150, 100],  # L0, L1, L2, L3, optional Lmono-monitor (cm)
    'horifoc': -1,          # Horizontal focusing (-1 = off)
    'moncor': 1,            # Monitor correction (0 or 1)
    'method': 0,            # 0 = Cooper-Nathans, 1 = Popovici
}
```

### Popovici geometry and conventions

Set `method=1` to include finite source, crystal, sample, detector and monitor
geometry, plus monochromator/analyzer curvature. Unsupported method values raise
an error rather than returning a different approximation.

- `arms` is `[L0, L1, L2, L3]`, optionally followed by `Lmono-monitor`, all in cm.
  The four main distances are source→monochromator→sample→analyzer→detector.
  With four entries, the monitor distance defaults to `L1`.
- `beam`, `monitor` and `detector` accept `width` and `height`; `mono` and `ana`
  additionally accept `depth`. These are **RMS dimensions in cm**, following
  ResLib's convention. For a uniform rectangular dimension of full size `d`,
  supply `d / sqrt(12)`, not `d`.
- `mono.rh`, `mono.rv`, `ana.rh`, `ana.rv` are signed curvature radii in cm.
- `sample.shape` is a symmetric positive-definite spatial covariance in cm².
  For `ResMatS`, express it in the sample Cartesian `(X,Y,Z)` frame: `X` is along
  `orient1`, `Y` is the in-plane orthogonal component of `orient2`, and `Z` completes
  the orthonormal frame. For direct `ResMat_vectorized`, supply it in the Q-aligned
  Cartesian frame. Inputs are copied before rotation.
- Output resolution matrices retain axis order **`[X,Y,E,Z]`**, with spatial
  offsets in inverse Å and energy in meV. NIST/ICP motor-angle conventions are
  preserved; this geometry support does not change motor zeros or signs.
- Set actual dimensions, distances and curvatures for your instrument. ResLib's
  default geometry is a numerical default, not an instrument calibration.

For example, extend the quick-start configuration with explicit geometry:

```python
from copy import deepcopy

pop = deepcopy(EXP)
pop['method'] = 1
pop['beam'] = {'width': 1.0 / np.sqrt(12), 'height': 2.0 / np.sqrt(12)}
pop['monitor'] = {'width': 2.0 / np.sqrt(12), 'height': 2.0 / np.sqrt(12)}
pop['detector'] = {'width': 2.0 / np.sqrt(12), 'height': 3.0 / np.sqrt(12)}
for name in ('mono', 'ana'):
    pop[name].update(width=2.0 / np.sqrt(12), height=3.0 / np.sqrt(12),
                     depth=0.2 / np.sqrt(12), rh=1e6, rv=1e6)
pop['sample']['shape'] = np.diag(np.square([1.0, 0.5, 0.2]) / 12)
R0, RMS = res.ResMatS(H, K, L, W, [pop] * len(H))
```

The tascopilot adapter accepts the same nested dictionaries in `experiment`.
Nested `instrument_config` component dictionaries can supply defaults;
`experiment` fields override them. Established flat fields such as
`mono_mosaic`, `sample_mosaic` and `sample_vmosaic` override their nested mosaic
counterparts. For compatibility, a flat-only `sample_mosaic` call still defaults
vertical sample mosaic to 30 arcmin; nested `sample.mosaic` defaults `vmosaic`
to its horizontal value when omitted.

Use the maintained `TASResolution`/`BatchedTASResolution` entry points. The old
Python-2-era `rescalc.py`, `respython.py` and `reslattice.py` files are historical
source, not supported runtime alternatives. This implementation follows the
[author's MATLAB ResLib 3.4c](https://neutron.phys.ethz.ch/Methods/reslib.html)
matrix expressions and corrected sample-shape rotation. Sample-mosaic broadening
uses determinant normalization to conserve the integrated Gaussian weight,
including unequal horizontal and vertical mosaics.
Monitor normalization uses the horizontal and vertical monitor dimensions
independently, including propagation to the finite vertical aperture. This
corrects the original monitor indexing, so monitor-normalized prefactors can
differ from uncorrected upstream ResLib values.

Adapter results explicitly identify the sample Cartesian frame and axis order
`[X,Y,E,Z]`. The reported `fwhm` values are Gaussian **section widths**, holding
the other offsets at zero: spatial axes use `1/angstrom` and the energy axis
uses `meV`. They are not projected widths or reciprocal-lattice-unit widths.

Available monochromator/analyzer crystals:
- `'pg(002)'`: PG(002), tau = 1.873 A^-1
- `'pg(004)'`: PG(004), tau = 3.746 A^-1
- `'ge(111)'`: Ge(111), tau = 1.924 A^-1
- `'ge(220)'`: Ge(220), tau = 3.141 A^-1
- `'ge(311)'`: Ge(311), tau = 3.684 A^-1
- `'be(002)'`: Be(002), tau = 3.507 A^-1

## Examples

See the `examples/` directory for complete working examples:

- `spinwave_convolution.py`: Ferromagnetic chain convolution with pyspinw
- `benchmark.py`: Performance comparison between backends

## Dependencies

- [lattice-calculator](https://github.com/scattering/lattice-calculator): Crystal lattice calculations
- [pyspinw](https://github.com/scattering/pyspinw): Spin wave calculations (optional, for S(Q,w))

## References

1. Cooper, M. J. & Nathans, R. (1967). Acta Cryst. 23, 357-367.
2. Popovici, M. (1975). Acta Cryst. A31, 507-513.
3. Chesser, N. J. & Axe, J. D. (1973). Acta Cryst. A29, 160-169.
4. Zheludev, A. ResLib (MATLAB version)

## License

[MIT License](LICENSE).

## Authors

William Ratcliff (NIST Center for Neutron Research)
