hklforge 0.0.1__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.
- hklforge/__init__.py +6 -0
- hklforge/draw.py +252 -0
- hklforge/geometries/__init__.py +0 -0
- hklforge/geometries/fourcv.yml +15 -0
- hklforge/geometries/psic.yml +18 -0
- hklforge/geometry.py +220 -0
- hklforge/lattice.py +33 -0
- hklforge/rotation.py +196 -0
- hklforge/solve.py +609 -0
- hklforge/virtual.py +114 -0
- hklforge-0.0.1.dist-info/METADATA +84 -0
- hklforge-0.0.1.dist-info/RECORD +15 -0
- hklforge-0.0.1.dist-info/WHEEL +5 -0
- hklforge-0.0.1.dist-info/licenses/LICENSE +28 -0
- hklforge-0.0.1.dist-info/top_level.txt +1 -0
hklforge/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""hklforge - diffractometer angle solvers generated exactly from a declared geometry."""
|
|
2
|
+
from .geometry import Circle, Geometry, wavevector
|
|
3
|
+
from .rotation import Degenerate
|
|
4
|
+
from .solve import Diffractometer, ModeError, Plan, plan
|
|
5
|
+
|
|
6
|
+
__all__ = ["Circle", "Geometry", "wavevector", "Diffractometer", "ModeError", "Degenerate", "Plan", "plan"]
|
hklforge/draw.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""3D drawings of a position and its virtual angles (matplotlib, optional).
|
|
2
|
+
|
|
3
|
+
``draw(d, angles, show=...)`` puts the lab vectors of one position into a 3D
|
|
4
|
+
axes - beam b, outgoing beam k', Q, surface normal, reference vector, the
|
|
5
|
+
bisect circle's axis - and draws each requested virtual angle as a labelled
|
|
6
|
+
arc, using the definitions of :mod:`hklforge.virtual`. ``draw_circles``
|
|
7
|
+
draws the geometry itself: every circle as a ring about its current axis.
|
|
8
|
+
|
|
9
|
+
The plot is oriented so that the geometry's "vertical" lab axis (from its
|
|
10
|
+
``labels``, e.g. psic x) points up and the beam runs left to right.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .rotation import rot, unit
|
|
17
|
+
from .virtual import bisect_axis, scattering_frame, virtual_angles
|
|
18
|
+
|
|
19
|
+
COLORS = {"beam": "#1f77b4", "kout": "#d62728", "Q": "#2ca02c", "surface": "#8c564b",
|
|
20
|
+
"reference": "#9467bd", "bisect": "#ff7f0e", "frame": "#7f7f7f", "p": "#17becf"}
|
|
21
|
+
ALL = ("ttheta", "qaz", "naz", "alpha", "beta", "betain", "betaout", "tau", "psi", "omega")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _perp(v):
|
|
25
|
+
v = unit(v)
|
|
26
|
+
return unit(np.cross(v, [1.0, 0, 0] if abs(v[0]) < 0.9 else [0, 1.0, 0]))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def view_basis(geometry) -> np.ndarray:
|
|
30
|
+
"""Rows: plot x (beam), plot y (across), plot z (up), as lab vectors."""
|
|
31
|
+
b = np.asarray(geometry.beam)
|
|
32
|
+
up = None
|
|
33
|
+
for axis, label in geometry.labels.items():
|
|
34
|
+
if str(label).lower() == "vertical":
|
|
35
|
+
up = np.eye(3)["xyz".index(axis)]
|
|
36
|
+
if up is None:
|
|
37
|
+
up = geometry.azimuth_frame()[1]
|
|
38
|
+
up = unit(up - b * (b @ up))
|
|
39
|
+
return np.array([b, np.cross(up, b), up])
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _Scene:
|
|
43
|
+
def __init__(self, ax, basis):
|
|
44
|
+
self.ax, self.B = ax, basis
|
|
45
|
+
|
|
46
|
+
def p(self, v):
|
|
47
|
+
return self.B @ np.asarray(v, float)
|
|
48
|
+
|
|
49
|
+
def arrow(self, vec, color, label=None, origin=(0, 0, 0), lw=2.0, ls="-"):
|
|
50
|
+
o, v = self.p(origin), self.p(vec)
|
|
51
|
+
self.ax.quiver(*o, *v, color=color, lw=lw, arrow_length_ratio=0.08, linestyle=ls)
|
|
52
|
+
if label:
|
|
53
|
+
t = o + 1.08 * v
|
|
54
|
+
self.ax.text(*t, label, color=color, fontsize=11, ha="center", va="center")
|
|
55
|
+
|
|
56
|
+
def line(self, pts, color, lw=1.0, ls="-"):
|
|
57
|
+
P = np.array([self.p(x) for x in pts])
|
|
58
|
+
self.ax.plot(P[:, 0], P[:, 1], P[:, 2], color=color, lw=lw, ls=ls)
|
|
59
|
+
|
|
60
|
+
def arc(self, v1, v2, radius, color, label, axis=None):
|
|
61
|
+
"""Arc from direction v1 to v2 (about their common normal, or about ``axis``)."""
|
|
62
|
+
v1 = unit(v1)
|
|
63
|
+
if axis is None:
|
|
64
|
+
axis = np.cross(v1, unit(v2))
|
|
65
|
+
if np.linalg.norm(axis) < 1e-9:
|
|
66
|
+
return
|
|
67
|
+
axis = unit(axis)
|
|
68
|
+
v1p = unit(v1 - axis * (axis @ v1))
|
|
69
|
+
v2p = unit(v2 - axis * (axis @ v2))
|
|
70
|
+
ang = np.arctan2(axis @ np.cross(v1p, v2p), v1p @ v2p)
|
|
71
|
+
ts = np.linspace(0, ang, 40)
|
|
72
|
+
pts = [radius * rot(axis, t) @ v1p for t in ts]
|
|
73
|
+
self.line(pts, color, lw=1.6)
|
|
74
|
+
mid = (radius + 0.12) * rot(axis, ang / 2) @ v1p
|
|
75
|
+
self.ax.text(*self.p(mid), label, color=color, fontsize=11, ha="center", va="center")
|
|
76
|
+
|
|
77
|
+
def plane(self, e1, e2, color, size=1.0, alpha=0.08):
|
|
78
|
+
e1, e2 = unit(e1), unit(e2)
|
|
79
|
+
corners = [size * (s1 * e1 + s2 * e2) for s1, s2 in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
|
|
80
|
+
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
|
|
81
|
+
self.ax.add_collection3d(Poly3DCollection([[self.p(c) for c in corners]],
|
|
82
|
+
facecolor=color, alpha=alpha, edgecolor="none"))
|
|
83
|
+
|
|
84
|
+
def finish(self, lim=1.25, title=None):
|
|
85
|
+
ax = self.ax
|
|
86
|
+
for setter in (ax.set_xlim, ax.set_ylim, ax.set_zlim):
|
|
87
|
+
setter(-lim, lim)
|
|
88
|
+
ax.set_box_aspect((1, 1, 1))
|
|
89
|
+
ax.set_axis_off()
|
|
90
|
+
if title:
|
|
91
|
+
ax.set_title(title)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _ax(ax):
|
|
95
|
+
import matplotlib.pyplot as plt
|
|
96
|
+
if ax is None:
|
|
97
|
+
fig = plt.figure(figsize=(6.5, 6))
|
|
98
|
+
ax = fig.add_subplot(projection="3d")
|
|
99
|
+
ax.view_init(elev=18, azim=-62)
|
|
100
|
+
return ax
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _lab_axes(sc, geometry):
|
|
104
|
+
"""A small lab x, y, z triad in a corner of the plot."""
|
|
105
|
+
origin = sc.B.T @ np.array([-1.0, -1.05, -1.0])
|
|
106
|
+
for i, name in enumerate("xyz"):
|
|
107
|
+
e = np.eye(3)[i]
|
|
108
|
+
label = geometry.labels.get(name, "")
|
|
109
|
+
sc.arrow(0.28 * e, COLORS["frame"], None, origin=origin, lw=0.8)
|
|
110
|
+
sc.ax.text(*sc.p(origin + 0.42 * e), f"{name}" + (f" ({label})" if label else ""),
|
|
111
|
+
color=COLORS["frame"], fontsize=8, ha="center", va="center")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _look_from(sc, direction):
|
|
115
|
+
"""Point the camera from lab ``direction`` towards the origin, from the
|
|
116
|
+
side that keeps the beam running left to right."""
|
|
117
|
+
v = sc.p(unit(direction))
|
|
118
|
+
if v[1] > 0:
|
|
119
|
+
v = v * np.array([1, -1, 1]) if abs(v[0]) > 0.9 else -v * np.array([1, 1, -1])
|
|
120
|
+
sc.ax.view_init(elev=float(np.degrees(np.arcsin(np.clip(v[2], -1, 1)))),
|
|
121
|
+
azim=float(np.degrees(np.arctan2(v[1], v[0]))))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def draw(d, angles: dict, show=("ttheta",), ax=None, title=None, lab_axes=True, view=None,
|
|
125
|
+
hkls=()):
|
|
126
|
+
"""Draw one position of Diffractometer ``d`` with the virtual angles in ``show``.
|
|
127
|
+
|
|
128
|
+
``show``: any of "ttheta", "qaz", "naz", "alpha", "beta", "betain",
|
|
129
|
+
"betaout", "tau", "psi", "omega", or "all". ``view``: None (default
|
|
130
|
+
oblique view), "beam" (look downstream along the beam - azimuths in
|
|
131
|
+
true size), "Q" (look down Q - psi in true size), "plane" (normal to the
|
|
132
|
+
scattering plane - 2theta, omega), "Qn" (normal to Q and n - tau) or a
|
|
133
|
+
lab vector to look from. ``hkls``: further reflections whose outgoing
|
|
134
|
+
beams b + R UB h / |k| are drawn too (double diffraction). Vectors are
|
|
135
|
+
unit length; returns the matplotlib 3D axes.
|
|
136
|
+
"""
|
|
137
|
+
g = d.geometry
|
|
138
|
+
ax = _ax(ax)
|
|
139
|
+
sc = _Scene(ax, view_basis(g))
|
|
140
|
+
show = ALL if show == "all" else tuple(show)
|
|
141
|
+
b = np.asarray(g.beam)
|
|
142
|
+
kout = g.k_out(angles)
|
|
143
|
+
R = g.sample_matrix(angles)
|
|
144
|
+
Q = kout - b
|
|
145
|
+
Qh, p, s = scattering_frame(b, Q)
|
|
146
|
+
va = virtual_angles(g, angles, d.surface, d.reference)
|
|
147
|
+
r, u = g.azimuth_frame()
|
|
148
|
+
|
|
149
|
+
if isinstance(view, str):
|
|
150
|
+
n_lab = None if d.reference is None else R @ d.reference
|
|
151
|
+
view = {"beam": -b + 0.15 * sc.B[2], "Q": Qh + 0.25 * s,
|
|
152
|
+
"plane": np.cross(b, Qh) + 0.3 * sc.B[2],
|
|
153
|
+
"Qn": None if n_lab is None else np.cross(Qh, n_lab) + 0.2 * sc.B[2]}[view]
|
|
154
|
+
if view is not None:
|
|
155
|
+
_look_from(sc, view)
|
|
156
|
+
if lab_axes:
|
|
157
|
+
_lab_axes(sc, g)
|
|
158
|
+
sc.arrow(b, COLORS["beam"], None, origin=-b, lw=2.2) # incoming, ends at the sample
|
|
159
|
+
sc.ax.text(*sc.p(-1.1 * b), "k (beam b)", color=COLORS["beam"], fontsize=11)
|
|
160
|
+
sc.arrow(kout, COLORS["kout"], "k' (detector)" if hkls else "k'")
|
|
161
|
+
sc.arrow(Qh, COLORS["Q"], "Q")
|
|
162
|
+
for i, h in enumerate(hkls):
|
|
163
|
+
ki = unit(b + R @ d.ub @ np.asarray(h, float) / d.k)
|
|
164
|
+
sc.arrow(ki, "#e377c2", f"k'{i + 1} {tuple(int(x) if float(x).is_integer() else x for x in h)}",
|
|
165
|
+
lw=1.5, ls="--")
|
|
166
|
+
sc.plane(b, Qh, COLORS["Q"], size=1.0, alpha=0.06) # scattering plane
|
|
167
|
+
|
|
168
|
+
n = None if d.reference is None else R @ d.reference
|
|
169
|
+
sv = None if d.surface is None else R @ d.surface
|
|
170
|
+
if n is not None and set(show) & {"naz", "alpha", "beta", "tau", "psi"}:
|
|
171
|
+
sc.arrow(n, COLORS["reference"], "n (reference)")
|
|
172
|
+
if set(show) & {"alpha", "beta"}: # the plane alpha/beta refer to
|
|
173
|
+
sc.plane(_perp(n), np.cross(n, _perp(n)), COLORS["reference"], size=0.8, alpha=0.10)
|
|
174
|
+
if sv is not None and set(show) & {"betain", "betaout"}:
|
|
175
|
+
sc.arrow(sv, COLORS["surface"], "surface normal")
|
|
176
|
+
sc.plane(_perp(sv), np.cross(sv, _perp(sv)), COLORS["surface"], size=0.8, alpha=0.10)
|
|
177
|
+
|
|
178
|
+
if "ttheta" in show:
|
|
179
|
+
sc.arc(b, kout, 0.5, COLORS["kout"], f"2θ={va['ttheta']:.1f}°")
|
|
180
|
+
sc.line([np.zeros(3), 0.9 * b], COLORS["beam"], ls=":") # beam continued
|
|
181
|
+
if {"qaz", "naz"} & set(show):
|
|
182
|
+
sc.arrow(0.8 * r, COLORS["frame"], "r (az. 0)", lw=1.0, ls="--")
|
|
183
|
+
sc.arrow(0.8 * u, COLORS["frame"], "u (az. 90)", lw=1.0, ls="--")
|
|
184
|
+
sc.plane(r, u, COLORS["frame"], size=0.9, alpha=0.05)
|
|
185
|
+
if "qaz" in show:
|
|
186
|
+
kp = kout - b * (b @ kout)
|
|
187
|
+
sc.line([np.zeros(3), kp], COLORS["kout"], ls=":")
|
|
188
|
+
sc.arc(r, kp, 0.4, COLORS["kout"], f"qaz={va['qaz']:.1f}°", axis=b)
|
|
189
|
+
if "naz" in show and n is not None:
|
|
190
|
+
np_ = n - b * (b @ n)
|
|
191
|
+
sc.line([np.zeros(3), np_], COLORS["reference"], ls=":")
|
|
192
|
+
sc.arc(r, np_, 0.75, COLORS["reference"], f"naz={va['naz']:.1f}°", axis=b)
|
|
193
|
+
for name, vec, beam_vec, sign in (("alpha", n, -b, 1), ("beta", n, kout, 1),
|
|
194
|
+
("betain", sv, -b, 1), ("betaout", sv, kout, 1)):
|
|
195
|
+
if name in show and vec is not None:
|
|
196
|
+
proj = beam_vec - vec * (vec @ beam_vec) # the beam's shadow on the plane
|
|
197
|
+
col = COLORS["reference"] if name in ("alpha", "beta") else COLORS["surface"]
|
|
198
|
+
sc.line([np.zeros(3), unit(proj) * 0.9], col, ls=":")
|
|
199
|
+
radius = 0.75 if name in ("alpha", "betain") else 0.55
|
|
200
|
+
sc.arc(proj, beam_vec, radius, col, f"{name}={va[name]:.1f}°")
|
|
201
|
+
if "tau" in show and n is not None:
|
|
202
|
+
sc.arc(Qh, n, 0.35, COLORS["reference"], f"τ={va['tau']:.1f}°")
|
|
203
|
+
if "psi" in show and n is not None:
|
|
204
|
+
sc.arrow(0.7 * p, COLORS["p"], "p", lw=1.2)
|
|
205
|
+
npp = n - Qh * (Qh @ n)
|
|
206
|
+
sc.line([np.zeros(3), unit(npp) * 0.7], COLORS["reference"], ls=":")
|
|
207
|
+
sc.arc(p, npp, 0.5, COLORS["reference"], f"ψ={va['psi']:.1f}°", axis=Qh)
|
|
208
|
+
if "omega" in show and g.bisect_circle is not None:
|
|
209
|
+
e = bisect_axis(g, angles)
|
|
210
|
+
sc.arrow(e, COLORS["bisect"], f"{g.bisect_circle} axis")
|
|
211
|
+
sc.arrow(0.7 * p, COLORS["p"], "p", lw=1.2)
|
|
212
|
+
sc.arc(p, e, 0.6, COLORS["bisect"], f"ω={va['omega']:.1f}°")
|
|
213
|
+
sc.finish(title=title)
|
|
214
|
+
return ax
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def draw_circles(geometry, angles: dict | None = None, ax=None, title=None):
|
|
218
|
+
"""Every circle of ``geometry`` as a ring about its current lab axis.
|
|
219
|
+
|
|
220
|
+
Sample circles are nested (outermost = largest ring), detector circles
|
|
221
|
+
drawn on the right; the rotation sense is marked by an arrow head.
|
|
222
|
+
"""
|
|
223
|
+
angles = angles or {}
|
|
224
|
+
ax = _ax(ax)
|
|
225
|
+
sc = _Scene(ax, view_basis(geometry))
|
|
226
|
+
_lab_axes(sc, geometry)
|
|
227
|
+
b = np.asarray(geometry.beam)
|
|
228
|
+
sc.arrow(b, COLORS["beam"], None, origin=-b, lw=2.2)
|
|
229
|
+
sc.ax.text(*sc.p(-1.15 * b), "beam", color=COLORS["beam"], fontsize=11)
|
|
230
|
+
|
|
231
|
+
def ring(axis, radius, color, label, centre=np.zeros(3)):
|
|
232
|
+
a = unit(axis)
|
|
233
|
+
v = unit(np.cross(a, [1.0, 0, 0] if abs(a[0]) < 0.9 else [0, 1.0, 0]))
|
|
234
|
+
pts = [centre + radius * rot(a, t) @ v for t in np.linspace(0, 2 * np.pi * 0.92, 60)]
|
|
235
|
+
sc.line(pts, color, lw=2.0)
|
|
236
|
+
tip, tail = pts[-1], pts[-4]
|
|
237
|
+
sc.arrow(tip - tail, color, None, origin=tail, lw=2.0) # rotation sense
|
|
238
|
+
sc.line([centre - 0.3 * radius * a, centre + 1.25 * radius * a], color, lw=0.8, ls="--")
|
|
239
|
+
sc.ax.text(*sc.p(centre + 1.35 * radius * a), label, color=color, fontsize=11)
|
|
240
|
+
|
|
241
|
+
M = np.eye(3)
|
|
242
|
+
n = len(geometry.sample)
|
|
243
|
+
for i, c in enumerate(geometry.sample):
|
|
244
|
+
ring(M @ np.asarray(c.axis), 1.0 - 0.6 * i / max(n, 1), "#444444", c.name)
|
|
245
|
+
M = M @ c.matrix(angles.get(c.name, 0.0))
|
|
246
|
+
D = np.eye(3)
|
|
247
|
+
for i, c in enumerate(geometry.detector):
|
|
248
|
+
ring(D @ np.asarray(c.axis), 0.45 - 0.15 * i, COLORS["kout"], c.name)
|
|
249
|
+
D = D @ c.matrix(angles.get(c.name, 0.0))
|
|
250
|
+
sc.arrow(geometry.k_out(angles), COLORS["kout"], "k' (detector)")
|
|
251
|
+
sc.finish(title=title or geometry.name)
|
|
252
|
+
return ax
|
|
File without changes
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
name: fourcv
|
|
2
|
+
description: |
|
|
3
|
+
Eulerian four-circle, vertical scattering plane (Busing & Levy 1967).
|
|
4
|
+
The psic geometry with mu = nu = 0: omega is psic's eta, tth its delta.
|
|
5
|
+
Lab frame: x vertical, y along the beam, z transverse.
|
|
6
|
+
labels: {x: vertical, y: beam, z: transverse}
|
|
7
|
+
beam: y+
|
|
8
|
+
azimuth_zero: z+ # qaz = naz = 0 along z, 90 deg along x (vertical)
|
|
9
|
+
bisect_circle: chi
|
|
10
|
+
sample:
|
|
11
|
+
- {name: omega, axis: z-}
|
|
12
|
+
- {name: chi, axis: y+}
|
|
13
|
+
- {name: phi, axis: z-}
|
|
14
|
+
detector:
|
|
15
|
+
- {name: tth, axis: z-}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
name: psic
|
|
2
|
+
description: |
|
|
3
|
+
You (1999) "4S+2D" six-circle diffractometer, as used by diffcalc-core
|
|
4
|
+
(and libhkl's E6C, where eta is called omega and nu gamma).
|
|
5
|
+
Lab frame: x vertical, y along the beam, z transverse.
|
|
6
|
+
At SwissFEL Bernina the out-of-plane detector circle nu is called gamma.
|
|
7
|
+
labels: {x: vertical, y: beam, z: transverse}
|
|
8
|
+
beam: y+
|
|
9
|
+
azimuth_zero: z+ # qaz = naz = 0 along z, 90 deg along x (vertical)
|
|
10
|
+
bisect_circle: chi
|
|
11
|
+
sample: # outermost first
|
|
12
|
+
- {name: mu, axis: x+}
|
|
13
|
+
- {name: eta, axis: z-}
|
|
14
|
+
- {name: chi, axis: y+}
|
|
15
|
+
- {name: phi, axis: z-}
|
|
16
|
+
detector:
|
|
17
|
+
- {name: nu, axis: x+}
|
|
18
|
+
- {name: delta, axis: z-}
|
hklforge/geometry.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""A diffractometer as data: rotation axes, how they stack, and the beam.
|
|
2
|
+
|
|
3
|
+
A geometry is two stacks of circles, each listed outermost (closest to the
|
|
4
|
+
floor) first:
|
|
5
|
+
|
|
6
|
+
- the **sample** stack, whose product R = R_1 R_2 ... R_n turns the sample
|
|
7
|
+
(phi) frame into the lab frame;
|
|
8
|
+
- the **detector** stack, whose product D turns the incoming beam direction
|
|
9
|
+
into the outgoing one, k' = D k_in.
|
|
10
|
+
|
|
11
|
+
Each circle is a right-handed rotation about a fixed lab axis given at all
|
|
12
|
+
angles zero. That is the whole model; everything else (the forward map
|
|
13
|
+
angles -> hkl and the generated inverse solvers) follows from it.
|
|
14
|
+
|
|
15
|
+
Two ways to write one down:
|
|
16
|
+
|
|
17
|
+
- YAML (``Geometry.from_yaml``), or a dict with the same keys;
|
|
18
|
+
- xrayutilities' axis strings (``Geometry.from_xrayutilities``), e.g.
|
|
19
|
+
``sample=['x+', 'z-', 'y+', 'z-'], detector=['x+', 'z-'], r_i=(0, 1, 0)``.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from importlib import resources
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
import yaml
|
|
29
|
+
|
|
30
|
+
from .rotation import rot, unit
|
|
31
|
+
|
|
32
|
+
# hc in eV * angstrom, same value (CODATA 2018) as scipy.constants
|
|
33
|
+
HC_EV_ANGSTROM = 12398.419843320026
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Circle:
|
|
38
|
+
name: str
|
|
39
|
+
axis: tuple[float, float, float] # unit vector, lab frame, all angles zero
|
|
40
|
+
|
|
41
|
+
def matrix(self, angle_deg: float) -> np.ndarray:
|
|
42
|
+
return rot(self.axis, np.radians(angle_deg))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Geometry:
|
|
47
|
+
name: str
|
|
48
|
+
sample: list[Circle]
|
|
49
|
+
detector: list[Circle]
|
|
50
|
+
beam: tuple[float, float, float] = (0.0, 1.0, 0.0)
|
|
51
|
+
description: str = ""
|
|
52
|
+
labels: dict = field(default_factory=dict) # e.g. {"x": "vertical"} for docs
|
|
53
|
+
azimuth_zero: tuple | None = None # lab direction where qaz / naz = 0 (default: see azimuth_frame)
|
|
54
|
+
bisect_circle: str | None = None # the circle whose axis 'bisect' / 'omega' refer to (psic: chi)
|
|
55
|
+
|
|
56
|
+
def __post_init__(self):
|
|
57
|
+
self.beam = tuple(unit(self.beam))
|
|
58
|
+
names = [c.name for c in self.sample + self.detector]
|
|
59
|
+
if len(set(names)) != len(names):
|
|
60
|
+
raise ValueError(f"circle names must be unique, got {names}")
|
|
61
|
+
if self.bisect_circle is not None and self.bisect_circle not in self.sample_names:
|
|
62
|
+
raise ValueError(f"bisect_circle {self.bisect_circle!r} is not a sample circle")
|
|
63
|
+
if self.azimuth_zero is not None:
|
|
64
|
+
r = np.asarray(_axis(self.azimuth_zero), float)
|
|
65
|
+
b = np.asarray(self.beam)
|
|
66
|
+
r = r - b * (b @ r)
|
|
67
|
+
self.azimuth_zero = tuple(unit(r))
|
|
68
|
+
|
|
69
|
+
# --- construction -------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def from_dict(cls, d: dict) -> "Geometry":
|
|
73
|
+
def circles(items):
|
|
74
|
+
return [Circle(c["name"], tuple(unit(_axis(c["axis"])))) for c in items]
|
|
75
|
+
return cls(
|
|
76
|
+
name=d["name"],
|
|
77
|
+
sample=circles(d["sample"]),
|
|
78
|
+
detector=circles(d["detector"]),
|
|
79
|
+
beam=tuple(_axis(d.get("beam", (0, 1, 0)))),
|
|
80
|
+
description=d.get("description", ""),
|
|
81
|
+
labels=d.get("labels", {}),
|
|
82
|
+
azimuth_zero=d.get("azimuth_zero"),
|
|
83
|
+
bisect_circle=d.get("bisect_circle"),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def from_yaml(cls, path_or_text) -> "Geometry":
|
|
88
|
+
text = Path(path_or_text).read_text() if _is_path(path_or_text) else path_or_text
|
|
89
|
+
return cls.from_dict(yaml.safe_load(text))
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_xrayutilities(
|
|
93
|
+
cls,
|
|
94
|
+
sample: list[str],
|
|
95
|
+
detector: list[str],
|
|
96
|
+
r_i=(0, 1, 0),
|
|
97
|
+
sample_names: list[str] | None = None,
|
|
98
|
+
detector_names: list[str] | None = None,
|
|
99
|
+
name: str = "custom",
|
|
100
|
+
) -> "Geometry":
|
|
101
|
+
"""Build from xrayutilities ``QConversion`` axis strings.
|
|
102
|
+
|
|
103
|
+
``'x+'`` is a right-handed rotation about +x, ``'z-'`` about -z, as in
|
|
104
|
+
xrayutilities; circles are listed outermost first, also as there.
|
|
105
|
+
``r_i`` is the primary-beam direction.
|
|
106
|
+
"""
|
|
107
|
+
sn = sample_names or [f"s{i + 1}" for i in range(len(sample))]
|
|
108
|
+
dn = detector_names or [f"d{i + 1}" for i in range(len(detector))]
|
|
109
|
+
if len(sn) != len(sample) or len(dn) != len(detector):
|
|
110
|
+
raise ValueError("one name per circle")
|
|
111
|
+
return cls(
|
|
112
|
+
name=name,
|
|
113
|
+
sample=[Circle(n, tuple(_axis(a))) for n, a in zip(sn, sample)],
|
|
114
|
+
detector=[Circle(n, tuple(_axis(a))) for n, a in zip(dn, detector)],
|
|
115
|
+
beam=tuple(unit(r_i)),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def builtin(cls, name: str) -> "Geometry":
|
|
120
|
+
return cls.from_yaml(resources.files("hklforge.geometries").joinpath(f"{name}.yml").read_text())
|
|
121
|
+
|
|
122
|
+
# --- introspection ------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def sample_names(self) -> list[str]:
|
|
126
|
+
return [c.name for c in self.sample]
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def detector_names(self) -> list[str]:
|
|
130
|
+
return [c.name for c in self.detector]
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def names(self) -> list[str]:
|
|
134
|
+
return self.sample_names + self.detector_names
|
|
135
|
+
|
|
136
|
+
def azimuth_frame(self) -> tuple[np.ndarray, np.ndarray]:
|
|
137
|
+
"""(r, u): azimuths about the beam (qaz, naz) are atan2(v.u, v.r).
|
|
138
|
+
|
|
139
|
+
r is ``azimuth_zero`` or, by default, the lab axis after the beam's in
|
|
140
|
+
cyclic order (beam y -> r = z); u = beam x r (beam y -> u = x). For psic
|
|
141
|
+
that is diffcalc's qaz = atan2(Q_x, Q_z): 90 deg = vertical scattering.
|
|
142
|
+
"""
|
|
143
|
+
b = np.asarray(self.beam)
|
|
144
|
+
if self.azimuth_zero is not None:
|
|
145
|
+
r = np.asarray(self.azimuth_zero)
|
|
146
|
+
else:
|
|
147
|
+
i = int(np.argmax(np.abs(b)))
|
|
148
|
+
r = np.eye(3)[(i + 1) % 3]
|
|
149
|
+
r = unit(r - b * (b @ r))
|
|
150
|
+
return r, np.cross(b, r)
|
|
151
|
+
|
|
152
|
+
def circle(self, name: str) -> Circle:
|
|
153
|
+
for c in self.sample + self.detector:
|
|
154
|
+
if c.name == name:
|
|
155
|
+
return c
|
|
156
|
+
raise KeyError(name)
|
|
157
|
+
|
|
158
|
+
def __repr__(self):
|
|
159
|
+
s = ", ".join(f"{c.name}{_axis_str(c.axis)}" for c in self.sample)
|
|
160
|
+
d = ", ".join(f"{c.name}{_axis_str(c.axis)}" for c in self.detector)
|
|
161
|
+
return f"Geometry({self.name!r}: sample [{s}] | detector [{d}] | beam {_axis_str(self.beam)})"
|
|
162
|
+
|
|
163
|
+
# --- forward model ------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def sample_matrix(self, angles: dict) -> np.ndarray:
|
|
166
|
+
"""R: phi (sample) frame -> lab frame."""
|
|
167
|
+
R = np.eye(3)
|
|
168
|
+
for c in self.sample:
|
|
169
|
+
R = R @ c.matrix(angles.get(c.name, 0.0))
|
|
170
|
+
return R
|
|
171
|
+
|
|
172
|
+
def detector_matrix(self, angles: dict) -> np.ndarray:
|
|
173
|
+
"""D: incoming beam direction -> outgoing beam direction."""
|
|
174
|
+
D = np.eye(3)
|
|
175
|
+
for c in self.detector:
|
|
176
|
+
D = D @ c.matrix(angles.get(c.name, 0.0))
|
|
177
|
+
return D
|
|
178
|
+
|
|
179
|
+
def k_out(self, angles: dict) -> np.ndarray:
|
|
180
|
+
return self.detector_matrix(angles) @ np.asarray(self.beam)
|
|
181
|
+
|
|
182
|
+
def q_lab(self, angles: dict, k: float) -> np.ndarray:
|
|
183
|
+
"""Scattering vector Q = k' - k in the lab frame, |k| = ``k``."""
|
|
184
|
+
b = np.asarray(self.beam)
|
|
185
|
+
return k * (self.k_out(angles) - b)
|
|
186
|
+
|
|
187
|
+
def q_phi(self, angles: dict, k: float) -> np.ndarray:
|
|
188
|
+
"""Q in the sample (phi) frame."""
|
|
189
|
+
return self.sample_matrix(angles).T @ self.q_lab(angles, k)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def wavevector(energy_eV: float) -> float:
|
|
193
|
+
"""|k| = 2 pi / lambda in 1/angstrom (the 2 pi convention, as diffcalc/libhkl)."""
|
|
194
|
+
return 2 * np.pi * energy_eV / HC_EV_ANGSTROM
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _is_path(x) -> bool:
|
|
198
|
+
return isinstance(x, Path) or (isinstance(x, str) and "\n" not in x and x.endswith((".yml", ".yaml")))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _axis(a) -> np.ndarray:
|
|
202
|
+
"""'x+', '-y', '+z' or a 3-vector -> unit vector."""
|
|
203
|
+
if isinstance(a, str):
|
|
204
|
+
s = a.strip().lower()
|
|
205
|
+
letter = s.strip("+-")
|
|
206
|
+
sign = -1.0 if "-" in s else 1.0
|
|
207
|
+
if letter not in ("x", "y", "z") or len(letter) != 1:
|
|
208
|
+
raise ValueError(f"axis {a!r}: use x/y/z with a sign, e.g. 'z-'")
|
|
209
|
+
v = np.zeros(3)
|
|
210
|
+
v["xyz".index(letter)] = sign
|
|
211
|
+
return v
|
|
212
|
+
return unit(a)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _axis_str(v) -> str:
|
|
216
|
+
v = np.asarray(v)
|
|
217
|
+
i = int(np.argmax(np.abs(v)))
|
|
218
|
+
if np.isclose(abs(v[i]), 1.0):
|
|
219
|
+
return f"({'xyz'[i]}{'+' if v[i] > 0 else '-'})"
|
|
220
|
+
return f"({v[0]:.3g},{v[1]:.3g},{v[2]:.3g})"
|
hklforge/lattice.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Crystal lattice -> B matrix (Busing & Levy 1967), 2 pi convention.
|
|
2
|
+
|
|
3
|
+
``ub = u @ b_matrix(a, b, c, alpha, beta, gamma)`` gives q = UB h with
|
|
4
|
+
|q| = 2 pi / d, the convention of the rest of hklforge (and of diffcalc and
|
|
5
|
+
libhkl). Lengths in angstrom, angles in degrees.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def b_matrix(a: float, b: float, c: float, alpha: float = 90.0, beta: float = 90.0,
|
|
13
|
+
gamma: float = 90.0) -> np.ndarray:
|
|
14
|
+
al, be, ga = np.radians([alpha, beta, gamma])
|
|
15
|
+
# real-space metric -> reciprocal lattice (with 2 pi)
|
|
16
|
+
A = np.array([[a, b * np.cos(ga), c * np.cos(be)],
|
|
17
|
+
[0, b * np.sin(ga), c * (np.cos(al) - np.cos(be) * np.cos(ga)) / np.sin(ga)],
|
|
18
|
+
[0, 0, 0]])
|
|
19
|
+
A[2, 2] = np.sqrt(c * c - A[0, 2] ** 2 - A[1, 2] ** 2)
|
|
20
|
+
rec = 2 * np.pi * np.linalg.inv(A).T # columns a*, b*, c*
|
|
21
|
+
G = rec.T @ rec # reciprocal metric
|
|
22
|
+
ast, bst, cst = np.sqrt(np.diag(G))
|
|
23
|
+
cos_al_st = G[1, 2] / (bst * cst)
|
|
24
|
+
cos_be_st = G[0, 2] / (ast * cst)
|
|
25
|
+
cos_ga_st = G[0, 1] / (ast * bst)
|
|
26
|
+
sin_be_st, sin_ga_st = np.sqrt(1 - cos_be_st ** 2), np.sqrt(1 - cos_ga_st ** 2)
|
|
27
|
+
return np.array([[ast, bst * cos_ga_st, cst * cos_be_st],
|
|
28
|
+
[0, bst * sin_ga_st, -cst * sin_be_st * np.cos(al)],
|
|
29
|
+
[0, 0, 2 * np.pi / c]])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def d_spacing(b: np.ndarray, hkl) -> float:
|
|
33
|
+
return 2 * np.pi / np.linalg.norm(b @ np.asarray(hkl, float))
|