Skip to main content

Resolution Calculator for Triple-Axis Spectrometers

PyPI version Python 3.9+ License: 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

# 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

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

Using Conda

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

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

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

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

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

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:

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:

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 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

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.

Authors

William Ratcliff (NIST Center for Neutron Research)

Metadata

Release files for rescalculator 2.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rescalculator 2.0.2
File Size Uploaded Provenance Actions
rescalculator-2.0.2.tar.gz 143.2 kB Without provenance Details for rescalculator-2.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rescalculator 2.0.2
File Interpreter ABI Platform Actions
rescalculator-2.0.2-py3-none-any.whl Python 3 none any Details for rescalculator-2.0.2-py3-none-any.whl

Total release size: 291.0 kB

Release files / rescalculator-2.0.2.tar.gz

Download URL rescalculator-2.0.2.tar.gz
Size 143.2 kB
Tags Source
SHA-256 checksum
How to use checksums
997f0070a365c8af3c15308f7b5646b29cc63135d8cfac61966ec20c0f60fdc2
BLAKE2b-256 checksum
How to use checksums
97252b7c3fc982187aac74a39b7e0d6e34f2e096833925c602e1f9f981d26b3e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Release files / rescalculator-2.0.2-py3-none-any.whl

Download URL rescalculator-2.0.2-py3-none-any.whl
Size 147.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d69b43904d68d913c6b3caa1553b17e0e044a80581340763e6f2ac15d22212b3
BLAKE2b-256 checksum
How to use checksums
7e8676d75eb261762fe6dc4ac385b091a24691a81bae38fc937d12718cbbcc71
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Security for rescalculator 2.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page