Coverage for ase/utils/xrdebye.py: 82.40%
125 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Definition of the XrDebye class.
3This module defines the XrDebye class for calculation
4of X-ray scattering properties from atomic cluster
5using Debye formula.
6Also contains routine for calculation of atomic form factors and
7X-ray wavelength dict.
8"""
10from math import acos, cos, exp, pi, sin, sqrt
12import numpy as np
14from ase.data import atomic_numbers
16# Table (1) of
17# D. WAASMAIER AND A. KIRFEL, Acta Cryst. (1995). A51, 416-431
18waasmaier = {
19 # a1 b1 a2 b2 a3 b3 a4 b4 a5 b5 c
20 'C': [
21 2.657506,
22 14.780758,
23 1.078079,
24 0.776775,
25 1.490909,
26 42.086843,
27 -4.241070,
28 -0.000294,
29 0.713791,
30 0.239535,
31 4.297983,
32 ],
33 'N': [
34 11.893780,
35 0.000158,
36 3.277479,
37 10.232723,
38 1.858092,
39 30.344690,
40 0.858927,
41 0.656065,
42 0.912985,
43 0.217287,
44 -11.804902,
45 ],
46 'O': [
47 2.960427,
48 14.182259,
49 2.5088111,
50 5.936858,
51 0.637053,
52 0.112726,
53 0.722838,
54 34.958481,
55 1.142756,
56 0.390240,
57 0.027014,
58 ],
59 'P': [
60 1.950541,
61 0.908139,
62 4.146930,
63 27.044953,
64 1.494560,
65 0.071280,
66 1.522042,
67 67.520190,
68 5.729711,
69 1.981173,
70 0.155233,
71 ],
72 'S': [
73 6.372157,
74 1.514347,
75 5.154568,
76 22.092528,
77 1.473732,
78 0.061373,
79 1.635073,
80 55.445176,
81 1.209372,
82 0.646925,
83 0.154722,
84 ],
85 'Cl': [
86 1.446071,
87 0.052357,
88 6.870609,
89 1.193165,
90 6.151801,
91 18.343416,
92 1.750347,
93 46.398394,
94 0.634168,
95 0.401005,
96 0.146773,
97 ],
98 'Ni': [
99 13.521865,
100 4.077277,
101 6.947285,
102 0.286763,
103 3.866028,
104 14.622634,
105 2.135900,
106 71.966078,
107 4.284731,
108 0.004437,
109 -2.762697,
110 ],
111 'Cu': [
112 14.014192,
113 3.738280,
114 4.784577,
115 0.003744,
116 5.056806,
117 13.034982,
118 1.457971,
119 72.554793,
120 6.932996,
121 0.265666,
122 -3.774477,
123 ],
124 'Pd': [
125 6.121511,
126 0.062549,
127 4.784063,
128 0.784031,
129 16.631683,
130 8.751391,
131 4.318258,
132 34.489983,
133 13.246773,
134 0.784031,
135 0.883099,
136 ],
137 'Ag': [
138 6.073874,
139 0.055333,
140 17.155437,
141 7.896512,
142 4.173344,
143 28.443739,
144 0.852238,
145 110.376108,
146 17.988685,
147 0.716809,
148 0.756603,
149 ],
150 'Pt': [
151 31.273891,
152 1.316992,
153 18.445441,
154 8.797154,
155 17.063745,
156 0.124741,
157 5.555933,
158 40.177994,
159 1.575270,
160 1.316997,
161 4.050394,
162 ],
163 'Au': [
164 16.777389,
165 0.122737,
166 19.317156,
167 8.621570,
168 32.979682,
169 1.256902,
170 5.595453,
171 38.008821,
172 10.576854,
173 0.000601,
174 -6.279078,
175 ],
176}
178wavelengths = {
179 'CuKa1': 1.5405981,
180 'CuKa2': 1.54443,
181 'CuKb1': 1.39225,
182 'WLa1': 1.47642,
183 'WLa2': 1.48748,
184}
187class XrDebye:
188 """
189 Class for calculation of XRD or SAXS patterns.
190 """
192 def __init__(
193 self,
194 atoms,
195 wavelength,
196 damping=0.04,
197 method='Iwasa',
198 alpha=1.01,
199 warn=True,
200 ):
201 """
202 Initilize the calculation of X-ray diffraction patterns
204 Parameters
205 ----------
207 atoms: ase.Atoms
208 atoms object for which calculation will be performed.
210 wavelength: float, Angstrom
211 X-ray wavelength in Angstrom. Used for XRD and to setup dumpings.
213 damping : float, Angstrom**2
214 thermal damping factor parameter (B-factor).
216 method: {'Iwasa'}
217 method of calculation (damping and atomic factors affected).
219 If set to 'Iwasa' than angular damping and q-dependence of
220 atomic factors are used.
222 For any other string there will be only thermal damping
223 and constant atomic factors (`f_a(q) = Z_a`).
225 alpha: float
226 parameter for angular damping of scattering intensity.
227 Close to 1.0 for unplorized beam.
229 warn: boolean
230 flag to show warning if atomic factor can't be calculated
231 """
232 self.wavelength = wavelength
233 self.damping = damping
234 self.mode = ''
235 self.method = method
236 self.alpha = alpha
237 self.warn = warn
239 self.twotheta_list = []
240 self.q_list = []
241 self.intensity_list = []
243 self.atoms = atoms
244 # TODO: setup atomic form factors if method != 'Iwasa'
246 def set_damping(self, damping):
247 """set B-factor for thermal damping"""
248 self.damping = damping
250 def get(self, s):
251 r"""Get the powder x-ray (XRD) scattering intensity
252 using the Debye-Formula at single point.
254 Parameters
255 ----------
257 s: float, in inverse Angstrom
258 scattering vector value (`s = q / 2\pi`).
260 Returns
261 -------
262 Intensity at given scattering vector `s`.
263 """
265 pre = exp(-self.damping * s**2 / 2)
267 if self.method == 'Iwasa':
268 sinth = self.wavelength * s / 2.0
269 positive = 1.0 - sinth**2
270 if positive < 0:
271 positive = 0
272 costh = sqrt(positive)
273 cos2th = cos(2.0 * acos(costh))
274 pre *= costh / (1.0 + self.alpha * cos2th**2)
276 f = {}
278 def atomic(symbol):
279 """
280 get atomic factor, using cache.
281 """
282 if symbol not in f:
283 if self.method == 'Iwasa':
284 f[symbol] = self.get_waasmaier(symbol, s)
285 else:
286 f[symbol] = atomic_numbers[symbol]
287 return f[symbol]
289 I = 0.0
290 fa = [] # atomic factors list
291 for a in self.atoms:
292 fa.append(atomic(a.symbol))
294 pos = self.atoms.get_positions() # positions of atoms
295 fa = np.array(fa) # atomic factors array
297 for i in range(len(self.atoms)):
298 vr = pos - pos[i]
299 I += np.sum(
300 fa[i] * fa * np.sinc(2 * s * np.sqrt(np.sum(vr * vr, axis=1)))
301 )
303 return pre * I
305 def get_waasmaier(self, symbol, s):
306 r"""Scattering factor for free atoms.
308 Parameters
309 ----------
311 symbol: string
312 atom element symbol.
314 s: float, in inverse Angstrom
315 scattering vector value (`s = q / 2\pi`).
317 Returns
318 -------
319 Intensity at given scattering vector `s`.
321 Note:
322 for hydrogen will be returned zero value."""
323 if symbol == 'H':
324 # XXXX implement analytical H
325 return 0
326 elif symbol in waasmaier:
327 abc = waasmaier[symbol]
328 f = abc[10]
329 s2 = s * s
330 for i in range(5):
331 f += abc[2 * i] * exp(-abc[2 * i + 1] * s2)
332 return f
333 if self.warn:
334 print('<xrdebye::get_atomic> Element', symbol, 'not available')
335 return 0
337 def calc_pattern(self, x=None, mode='XRD', verbose=False):
338 r"""
339 Calculate X-ray diffraction pattern or
340 small angle X-ray scattering pattern.
342 Parameters
343 ----------
345 x: float array
346 points where intensity will be calculated.
347 XRD - 2theta values, in degrees;
348 SAXS - q values in 1/A
349 (`q = 2 \pi \cdot s = 4 \pi \sin( \theta) / \lambda`).
350 If ``x`` is ``None`` then default values will be used.
352 mode: {'XRD', 'SAXS'}
353 the mode of calculation: X-ray diffraction (XRD) or
354 small-angle scattering (SAXS).
356 Returns
357 -------
358 list of intensities calculated for values given in ``x``.
359 """
360 self.mode = mode.upper()
361 assert mode in ['XRD', 'SAXS']
363 result = []
364 if mode == 'XRD':
365 if x is None:
366 self.twotheta_list = np.linspace(15, 55, 100)
367 else:
368 self.twotheta_list = x
369 self.q_list = []
370 if verbose:
371 print('#2theta\tIntensity')
372 for twotheta in self.twotheta_list:
373 s = 2 * sin(twotheta * pi / 180 / 2.0) / self.wavelength
374 result.append(self.get(s))
375 if verbose:
376 print(f'{twotheta:.3f}\t{result[-1]:f}')
377 elif mode == 'SAXS':
378 if x is None:
379 self.twotheta_list = np.logspace(-3, -0.3, 100)
380 else:
381 self.q_list = x
382 self.twotheta_list = []
383 if verbose:
384 print('#q\tIntensity')
385 for q in self.q_list:
386 s = q / (2 * pi)
387 result.append(self.get(s))
388 if verbose:
389 print(f'{q:.4f}\t{result[-1]:f}')
390 self.intensity_list = np.array(result)
391 return self.intensity_list
393 def write_pattern(self, filename):
394 """Save calculated data to file specified by ``filename`` string."""
395 with open(filename, 'w') as fd:
396 self._write_pattern(fd)
398 def _write_pattern(self, fd):
399 fd.write('# Wavelength = %f\n' % self.wavelength)
400 if self.mode == 'XRD':
401 x, y = self.twotheta_list, self.intensity_list
402 fd.write('# 2theta \t Intesity\n')
403 elif self.mode == 'SAXS':
404 x, y = self.q_list, self.intensity_list
405 fd.write('# q(1/A)\tIntesity\n')
406 else:
407 raise Exception('No data available, call calc_pattern() first.')
409 for i in range(len(x)):
410 fd.write(f' {x[i]:f}\t{y[i]:f}\n')
412 def plot_pattern(self, filename=None, show=False, ax=None):
413 """Plot XRD or SAXS depending on filled data
415 Uses Matplotlib to plot pattern. Use *show=True* to
416 show the figure and *filename='abc.png'* or
417 *filename='abc.eps'* to save the figure to a file.
419 Returns
420 -------
421 ``matplotlib.axes.Axes`` object."""
423 import matplotlib.pyplot as plt
425 if ax is None:
426 plt.clf() # clear figure
427 ax = plt.gca()
429 if self.mode == 'XRD':
430 x, y = np.array(self.twotheta_list), np.array(self.intensity_list)
431 ax.plot(x, y / np.max(y), '.-')
432 ax.set_xlabel('2$\\theta$')
433 ax.set_ylabel('Intensity')
434 elif self.mode == 'SAXS':
435 x, y = np.array(self.q_list), np.array(self.intensity_list)
436 ax.loglog(x, y / np.max(y), '.-')
437 ax.set_xlabel('q, 1/Angstr.')
438 ax.set_ylabel('Intensity')
439 else:
440 raise Exception('No data available, call calc_pattern() first')
442 if show:
443 plt.show()
444 if filename is not None:
445 fig = ax.get_figure()
446 fig.savefig(filename)
448 return ax