rescalculator 2.0.0__py3-none-any.whl

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,292 @@
1
+ # Resolution Calculator for Triple-Axis Spectrometers
2
+
3
+ A Python library for computing resolution matrices and performing S(Q,w) convolutions for Triple-Axis Spectrometer (TAS) experiments. This package provides both NumPy (CPU) and PyTorch backends for flexible deployment.
4
+
5
+ Based on ResLib by Andrei Zheludev.
6
+
7
+ ## Features
8
+
9
+ - **Cooper-Nathans resolution formalism** with optional Popovici method
10
+ - **Dual backend support**: NumPy for CPU, PyTorch for GPU acceleration
11
+ - **Automatic device detection**: CUDA, MPS (Apple Silicon), or CPU
12
+ - **S(Q,w) convolution**: Integrate scattering cross-sections with resolution function
13
+ - **Batched operations**: Efficient computation for thousands of Q-points simultaneously
14
+
15
+ ## Installation
16
+
17
+ ### Requirements
18
+
19
+ - Python >= 3.9
20
+ - NumPy
21
+ - SciPy
22
+ - PyTorch (optional, for GPU acceleration)
23
+ - lattice-calculator
24
+
25
+ ### Install from PyPI
26
+
27
+ ```bash
28
+ pip install rescalculator
29
+ ```
30
+
31
+ ### Install from source
32
+
33
+ ```bash
34
+ git clone https://github.com/scattering/rescalculator.git
35
+ cd rescalculator
36
+ pip install -e .
37
+ ```
38
+
39
+ ### Setting up a conda environment
40
+
41
+ ```bash
42
+ conda create -n resolution python=3.11 pytorch numpy scipy matplotlib -c pytorch
43
+ conda activate resolution
44
+ pip install lattice-calculator
45
+ pip install -e .
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ### Basic Resolution Calculation
51
+
52
+ ```python
53
+ import numpy as np
54
+ from rescalculator import TASResolution
55
+ from lattice_calculator import Lattice, modvec
56
+
57
+ # Define crystal lattice
58
+ lattice = Lattice(
59
+ a=5.0, b=5.0, c=5.0,
60
+ alpha=90, beta=90, gamma=90,
61
+ orient1=np.array([[1, 0, 0]]),
62
+ orient2=np.array([[0, 1, 0]])
63
+ )
64
+
65
+ # Define experiment configuration
66
+ EXP = {
67
+ 'efixed': 14.7, # Fixed energy (meV)
68
+ 'infin': -1, # -1 for fixed Ef, +1 for fixed Ei
69
+ 'dir1': 1, # Monochromator scattering direction
70
+ 'dir2': 1, # Analyzer scattering direction
71
+ 'hcol': np.array([40, 40, 40, 40]), # Horizontal collimations (arcmin)
72
+ 'vcol': np.array([120, 120, 120, 120]), # Vertical collimations (arcmin)
73
+ 'mono': {'tau': 'pg(002)', 'mosaic': 30}, # Monochromator
74
+ 'ana': {'tau': 'pg(002)', 'mosaic': 30}, # Analyzer
75
+ 'sample': {'mosaic': 30}, # Sample mosaic
76
+ 'arms': [200, 200, 150, 150, 100], # Spectrometer arms (cm)
77
+ 'horifoc': -1, # Horizontal focusing (-1 = no focusing)
78
+ 'moncor': 1, # Monitor correction
79
+ }
80
+
81
+ # Create resolution calculator
82
+ res = TASResolution(lattice, backend='numpy')
83
+
84
+ # Define scan points
85
+ H = np.array([1.0, 1.05, 1.1])
86
+ K = np.zeros(3)
87
+ L = np.zeros(3)
88
+ W = np.array([5.0, 5.0, 5.0]) # Energy transfer (meV)
89
+ lattice.npts = len(H)
90
+
91
+ # Calculate resolution matrices
92
+ R0, RMS = res.ResMatS(H, K, L, W, [EXP] * len(H))
93
+
94
+ # R0: Prefactors (normalization)
95
+ # RMS: Resolution matrices in sample coordinates, shape (4, 4, npts)
96
+ print(f"Resolution matrix at first point:\n{RMS[:,:,0]}")
97
+ ```
98
+
99
+ ### S(Q,w) Convolution with Spin Waves
100
+
101
+ ```python
102
+ import numpy as np
103
+ from rescalculator import TASResolution, ConvolutionCalculator
104
+ from lattice_calculator import Lattice
105
+ from pyspinw import SpinW
106
+
107
+ # Set up spin wave model using pyspinw
108
+ model = SpinW()
109
+ model.genlattice(lat_const=[3.0, 3.0, 3.0], angled=[90, 90, 90])
110
+ model.addatom(r=[0, 0, 0], S=1, label='Fe')
111
+ model.gencoupling(max_distance=4.0)
112
+ model.addmatrix(label='J', value=1.0)
113
+ model.addcoupling(bond=0, mat_labels='J')
114
+ model.genmagstr(mode='direct', S=[[0], [0], [1]])
115
+
116
+ # Create S(Q,w) function
117
+ def sqw_function(h, k, l, w):
118
+ """Spin wave S(Q,w) at given (h,k,l,w)."""
119
+ spec = model.spinwave([[h], [k], [l]], use_surface_integrals=True)
120
+ # ... process spectrum ...
121
+ return intensity
122
+
123
+ # Set up convolution
124
+ lattice = Lattice(a=3.0, b=3.0, c=3.0, alpha=90, beta=90, gamma=90,
125
+ orient1=np.array([[1,0,0]]), orient2=np.array([[0,1,0]]))
126
+
127
+ conv = ConvolutionCalculator(
128
+ resolution=TASResolution(lattice, backend='numpy'),
129
+ sqw_function=sqw_function,
130
+ lattice=lattice
131
+ )
132
+
133
+ # Calculate convoluted intensity
134
+ H_scan = np.linspace(0.1, 0.9, 50)
135
+ K_scan = np.zeros(50)
136
+ L_scan = np.zeros(50)
137
+ W_scan = np.full(50, 5.0)
138
+
139
+ intensity = conv.convolve(H_scan, K_scan, L_scan, W_scan, EXP_list)
140
+ ```
141
+
142
+ ## Performance Notes
143
+
144
+ ### Backend Comparison
145
+
146
+ This library supports multiple backends with dramatically different performance:
147
+
148
+ | Backend | 1,000 pts | 10,000 pts | 100,000 pts | Speedup |
149
+ |---------|-----------|------------|-------------|---------|
150
+ | **Numba (CPU)** | 4 ms | 39 ms | 395 ms | **26x** |
151
+ | NumPy (CPU) | 105 ms | 998 ms | 10,288 ms | 1x |
152
+ | PyTorch (MPS) | 1,580 ms | 13,552 ms | OOM | 0.08x |
153
+
154
+ **Key findings:**
155
+
156
+ 1. **Numba is fastest** - JIT compilation with parallel execution gives ~26x speedup
157
+ 2. **Small matrices don't benefit from GPU**: Resolution calculations involve thousands of small (4x4 to 8x8) matrix operations, which don't parallelize efficiently on GPU
158
+ 3. **GPU overhead dominates**: Data transfer and kernel launch overhead exceeds computation time for small matrices
159
+ 4. **More points don't help GPU**: GPU performance actually degrades with more points due to memory pressure
160
+
161
+ **Recommendation:** Install with `pip install rescalculator[fast]` to get Numba acceleration. The default `backend='auto'` will automatically use Numba if available.
162
+
163
+ ### When to use each backend
164
+
165
+ - **Numba** (recommended): Best performance for all use cases
166
+ - **NumPy**: Fallback when Numba not available, always works
167
+ - **PyTorch**: Only for gradient computation or integration with PyTorch models
168
+
169
+ ### Memory Efficiency
170
+
171
+ The library handles large numbers of points efficiently:
172
+ - Numba/NumPy: Tested with 100,000+ points
173
+ - Memory scales linearly with point count
174
+ - Each point requires approximately 1-2 KB of memory
175
+
176
+ ## API Reference
177
+
178
+ ### TASResolution
179
+
180
+ ```python
181
+ class TASResolution(lattice, backend='auto')
182
+ ```
183
+
184
+ Main resolution calculator class.
185
+
186
+ **Parameters:**
187
+ - `lattice`: Lattice instance from lattice-calculator
188
+ - `backend`: 'auto', 'numba', 'numpy', or 'pytorch'
189
+
190
+ **Methods:**
191
+ - `ResMatS(H, K, L, W, EXP)`: Compute resolution matrices in sample coordinates
192
+ - `ResMat_vectorized(Q, W, EXP)`: Compute resolution matrices for Q magnitude array
193
+ - `set_backend(backend_type)`: Change computational backend
194
+
195
+ ### BatchedTASResolution
196
+
197
+ ```python
198
+ class BatchedTASResolution(lattice, device='auto')
199
+ ```
200
+
201
+ Fully batched resolution calculator using PyTorch tensor operations.
202
+
203
+ **Parameters:**
204
+ - `lattice`: Lattice instance
205
+ - `device`: 'auto', 'cuda', 'mps', or 'cpu'
206
+
207
+ **Methods:**
208
+ - `ResMat_batched(Q, W, EXP)`: Batched resolution calculation returning tensors
209
+ - `ResMatS(H, K, L, W, EXP)`: Resolution matrices in sample coordinates
210
+
211
+ ### ConvolutionCalculator
212
+
213
+ ```python
214
+ class ConvolutionCalculator(resolution, sqw_function, lattice)
215
+ ```
216
+
217
+ Convolves S(Q,w) with resolution function.
218
+
219
+ **Parameters:**
220
+ - `resolution`: TASResolution instance
221
+ - `sqw_function`: Function `f(h, k, l, w) -> intensity`
222
+ - `lattice`: Lattice instance
223
+
224
+ ### Experiment Configuration (EXP)
225
+
226
+ The EXP dictionary contains all spectrometer parameters:
227
+
228
+ ```python
229
+ EXP = {
230
+ 'efixed': 14.7, # Fixed energy (meV)
231
+ 'infin': -1, # -1 = fixed Ef, +1 = fixed Ei
232
+ 'dir1': 1, # Monochromator scattering direction (+1 or -1)
233
+ 'dir2': 1, # Analyzer scattering direction (+1 or -1)
234
+ 'hcol': [40, 40, 40, 40], # Horizontal collimations (arcmin)
235
+ 'vcol': [120, 120, 120, 120], # Vertical collimations (arcmin)
236
+ 'mono': {
237
+ 'tau': 'pg(002)', # Monochromator crystal
238
+ 'mosaic': 30, # Mosaic spread (arcmin)
239
+ 'rh': 1e6, # Horizontal radius (cm), 1e6 = flat
240
+ 'rv': 1e6, # Vertical radius (cm)
241
+ },
242
+ 'ana': {
243
+ 'tau': 'pg(002)', # Analyzer crystal
244
+ 'mosaic': 30,
245
+ 'rh': 1e6,
246
+ 'rv': 1e6,
247
+ },
248
+ 'sample': {
249
+ 'mosaic': 30, # Sample mosaic (arcmin)
250
+ 'vmosaic': 30, # Vertical sample mosaic (arcmin)
251
+ },
252
+ 'arms': [200, 200, 150, 150, 100], # L0, L1p, L1, L2, L3 (cm)
253
+ 'horifoc': -1, # Horizontal focusing (-1 = off)
254
+ 'moncor': 1, # Monitor correction (0 or 1)
255
+ 'method': 0, # 0 = Cooper-Nathans, 1 = Popovici
256
+ }
257
+ ```
258
+
259
+ Available monochromator/analyzer crystals:
260
+ - `'pg(002)'`: PG(002), tau = 1.873 A^-1
261
+ - `'pg(004)'`: PG(004), tau = 3.746 A^-1
262
+ - `'ge(111)'`: Ge(111), tau = 1.924 A^-1
263
+ - `'ge(220)'`: Ge(220), tau = 3.141 A^-1
264
+ - `'ge(311)'`: Ge(311), tau = 3.684 A^-1
265
+ - `'be(002)'`: Be(002), tau = 3.507 A^-1
266
+
267
+ ## Examples
268
+
269
+ See the `examples/` directory for complete working examples:
270
+
271
+ - `spinwave_convolution.py`: Ferromagnetic chain convolution with pyspinw
272
+ - `benchmark.py`: Performance comparison between backends
273
+
274
+ ## Dependencies
275
+
276
+ - [lattice-calculator](https://github.com/scattering/lattice-calculator): Crystal lattice calculations
277
+ - [pyspinw](https://github.com/scattering/pyspinw): Spin wave calculations (optional, for S(Q,w))
278
+
279
+ ## References
280
+
281
+ 1. Cooper, M. J. & Nathans, R. (1967). Acta Cryst. 23, 357-367.
282
+ 2. Popovici, M. (1975). Acta Cryst. A31, 507-513.
283
+ 3. Chesser, N. J. & Axe, J. D. (1973). Acta Cryst. A29, 160-169.
284
+ 4. Zheludev, A. ResLib (MATLAB version)
285
+
286
+ ## License
287
+
288
+ MIT License
289
+
290
+ ## Authors
291
+
292
+ William Ratcliff (NIST Center for Neutron Research)
@@ -0,0 +1,42 @@
1
+ """
2
+ Resolution Calculator for Triple Axis Spectrometer
3
+
4
+ This package provides GPU-accelerated resolution calculations using PyTorch.
5
+ It supports both NumPy (CPU) and PyTorch (GPU) backends for flexible deployment.
6
+
7
+ Key components:
8
+ - TASResolution: Resolution matrix calculator with GPU support
9
+ - ConvolutionCalculator: S(Q,w) convolution with resolution function
10
+ - Backends: NumPy and PyTorch computational backends
11
+
12
+ Example usage:
13
+ from rescalculator_pytorch import TASResolution, get_backend
14
+ from lattice_calculator import Lattice, Orientation
15
+
16
+ # Initialize backend (auto-detects GPU)
17
+ backend = get_backend('auto')
18
+
19
+ # Set up lattice
20
+ lattice = Lattice(a=5.0, b=5.0, c=5.0, ...)
21
+
22
+ # Create resolution calculator
23
+ res = TASResolution(lattice, backend='pytorch')
24
+
25
+ # Calculate resolution matrices
26
+ R0, RMS = res.ResMatS(H, K, L, W, EXP)
27
+ """
28
+
29
+ __author__ = 'William Ratcliff'
30
+ __version__ = '2.0.0'
31
+
32
+ from .backends import get_backend, current_backend
33
+ from .rescalc_torch import TASResolution, ConvolutionCalculator
34
+ from .rescalc_batched import BatchedTASResolution
35
+
36
+ __all__ = [
37
+ 'TASResolution',
38
+ 'BatchedTASResolution',
39
+ 'ConvolutionCalculator',
40
+ 'get_backend',
41
+ 'current_backend',
42
+ ]
@@ -0,0 +1,71 @@
1
+ """
2
+ Backend abstraction for resolution calculator.
3
+
4
+ Supports multiple backends:
5
+ - NumPy (CPU): Pure NumPy, always available
6
+ - Numba (CPU): JIT-compiled parallel, ~25x faster than NumPy (recommended)
7
+ - PyTorch (GPU): For GPU acceleration and gradient computation
8
+
9
+ Performance comparison (typical):
10
+ - NumPy: ~10,000 pts/sec
11
+ - Numba: ~250,000 pts/sec (25x faster)
12
+ - PyTorch MPS: ~300 pts/sec (slower due to small matrix overhead)
13
+ - PyTorch CUDA: Depends on GPU, may be faster for very large batches
14
+ """
15
+
16
+ from .base import BaseBackend
17
+ from .numpy_backend import NumpyBackend
18
+
19
+ _current_backend = None
20
+
21
+
22
+ def get_backend(backend_type='auto'):
23
+ """Get a computational backend.
24
+
25
+ Parameters
26
+ ----------
27
+ backend_type : str
28
+ 'numpy' for pure NumPy (CPU)
29
+ 'numba' for JIT-compiled parallel (CPU, fastest)
30
+ 'pytorch' for PyTorch (GPU/CPU)
31
+ 'auto' to detect best available (prefers Numba > NumPy)
32
+
33
+ Returns
34
+ -------
35
+ BaseBackend or NumbaBackend
36
+ The computational backend instance
37
+ """
38
+ global _current_backend
39
+
40
+ if backend_type == 'auto':
41
+ # Prefer Numba (fastest), then NumPy
42
+ # Note: PyTorch/GPU is not preferred for auto due to small matrix overhead
43
+ try:
44
+ from .numba_backend import NumbaBackend
45
+ _current_backend = NumbaBackend()
46
+ except ImportError:
47
+ _current_backend = NumpyBackend()
48
+ elif backend_type == 'numba':
49
+ from .numba_backend import NumbaBackend
50
+ _current_backend = NumbaBackend()
51
+ elif backend_type == 'pytorch':
52
+ from .pytorch_backend import PyTorchBackend
53
+ _current_backend = PyTorchBackend()
54
+ elif backend_type == 'numpy':
55
+ _current_backend = NumpyBackend()
56
+ else:
57
+ raise ValueError(f"Unknown backend type: {backend_type}. "
58
+ f"Available: 'auto', 'numpy', 'numba', 'pytorch'")
59
+
60
+ return _current_backend
61
+
62
+
63
+ def current_backend():
64
+ """Get the current backend, initializing if needed."""
65
+ global _current_backend
66
+ if _current_backend is None:
67
+ _current_backend = get_backend('auto')
68
+ return _current_backend
69
+
70
+
71
+ __all__ = ['get_backend', 'current_backend', 'BaseBackend', 'NumpyBackend']
@@ -0,0 +1,176 @@
1
+ """
2
+ Abstract base class for computational backends.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+
8
+ class BaseBackend(ABC):
9
+ """Abstract base class for computational backends."""
10
+
11
+ @property
12
+ @abstractmethod
13
+ def name(self):
14
+ """Return backend name."""
15
+ pass
16
+
17
+ @property
18
+ @abstractmethod
19
+ def device(self):
20
+ """Return current device (cpu, cuda, mps)."""
21
+ pass
22
+
23
+ @abstractmethod
24
+ def to_array(self, data, dtype=None):
25
+ """Convert data to backend array type."""
26
+ pass
27
+
28
+ @abstractmethod
29
+ def to_numpy(self, data):
30
+ """Convert backend array to numpy."""
31
+ pass
32
+
33
+ @abstractmethod
34
+ def zeros(self, shape, dtype=None):
35
+ """Create array of zeros."""
36
+ pass
37
+
38
+ @abstractmethod
39
+ def ones(self, shape, dtype=None):
40
+ """Create array of ones."""
41
+ pass
42
+
43
+ @abstractmethod
44
+ def eye(self, n, dtype=None):
45
+ """Create identity matrix."""
46
+ pass
47
+
48
+ @abstractmethod
49
+ def diag(self, v):
50
+ """Create diagonal matrix or extract diagonal."""
51
+ pass
52
+
53
+ @abstractmethod
54
+ def dot(self, a, b):
55
+ """Matrix multiplication."""
56
+ pass
57
+
58
+ @abstractmethod
59
+ def matmul(self, a, b):
60
+ """Batch matrix multiplication."""
61
+ pass
62
+
63
+ @abstractmethod
64
+ def inv(self, a):
65
+ """Matrix inverse."""
66
+ pass
67
+
68
+ @abstractmethod
69
+ def det(self, a):
70
+ """Matrix determinant."""
71
+ pass
72
+
73
+ @abstractmethod
74
+ def eig(self, a):
75
+ """Eigenvalue decomposition."""
76
+ pass
77
+
78
+ @abstractmethod
79
+ def sqrt(self, x):
80
+ """Element-wise square root."""
81
+ pass
82
+
83
+ @abstractmethod
84
+ def exp(self, x):
85
+ """Element-wise exponential."""
86
+ pass
87
+
88
+ @abstractmethod
89
+ def sin(self, x):
90
+ """Element-wise sine."""
91
+ pass
92
+
93
+ @abstractmethod
94
+ def cos(self, x):
95
+ """Element-wise cosine."""
96
+ pass
97
+
98
+ @abstractmethod
99
+ def tan(self, x):
100
+ """Element-wise tangent."""
101
+ pass
102
+
103
+ @abstractmethod
104
+ def arcsin(self, x):
105
+ """Element-wise arcsine."""
106
+ pass
107
+
108
+ @abstractmethod
109
+ def arccos(self, x):
110
+ """Element-wise arccosine."""
111
+ pass
112
+
113
+ @abstractmethod
114
+ def arctan2(self, y, x):
115
+ """Element-wise arctan2."""
116
+ pass
117
+
118
+ @abstractmethod
119
+ def abs(self, x):
120
+ """Element-wise absolute value."""
121
+ pass
122
+
123
+ @abstractmethod
124
+ def log(self, x):
125
+ """Element-wise natural log."""
126
+ pass
127
+
128
+ @abstractmethod
129
+ def sum(self, x, axis=None):
130
+ """Sum over axis."""
131
+ pass
132
+
133
+ @abstractmethod
134
+ def stack(self, arrays, axis=0):
135
+ """Stack arrays along axis."""
136
+ pass
137
+
138
+ @abstractmethod
139
+ def concatenate(self, arrays, axis=0):
140
+ """Concatenate arrays along axis."""
141
+ pass
142
+
143
+ @abstractmethod
144
+ def transpose(self, a, axes=None):
145
+ """Transpose array."""
146
+ pass
147
+
148
+ @abstractmethod
149
+ def reshape(self, a, shape):
150
+ """Reshape array."""
151
+ pass
152
+
153
+ @abstractmethod
154
+ def linspace(self, start, stop, num):
155
+ """Create evenly spaced array."""
156
+ pass
157
+
158
+ @abstractmethod
159
+ def arange(self, start, stop=None, step=1):
160
+ """Create array with given range."""
161
+ pass
162
+
163
+ @abstractmethod
164
+ def meshgrid(self, *xi, indexing='xy'):
165
+ """Create meshgrid from coordinate arrays."""
166
+ pass
167
+
168
+ @abstractmethod
169
+ def einsum(self, subscripts, *operands):
170
+ """Einstein summation."""
171
+ pass
172
+
173
+ @abstractmethod
174
+ def block_diag(self, *matrices):
175
+ """Create block diagonal matrix."""
176
+ pass