hklforge 0.0.1__tar.gz

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-0.0.1/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Henrik Lemke
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.4
2
+ Name: hklforge
3
+ Version: 0.0.1
4
+ Summary: Diffractometer angle solvers generated exactly from a declared geometry
5
+ Author: Henrik Lemke
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/swissfel/hklforge
8
+ Project-URL: Documentation, https://github.com/swissfel/hklforge/tree/main/docs
9
+ Keywords: diffraction,diffractometer,crystallography,x-ray,hkl,synchrotron,XFEL
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Physics
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy
18
+ Requires-Dist: pyyaml
19
+ Provides-Extra: draw
20
+ Requires-Dist: matplotlib; extra == "draw"
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest; extra == "test"
23
+ Requires-Dist: scipy; extra == "test"
24
+ Requires-Dist: diffcalc-core; extra == "test"
25
+ Requires-Dist: xrayutilities; extra == "test"
26
+ Requires-Dist: matplotlib; extra == "test"
27
+ Requires-Dist: pandas; extra == "test"
28
+ Provides-Extra: examples
29
+ Requires-Dist: matplotlib; extra == "examples"
30
+ Requires-Dist: pandas; extra == "examples"
31
+ Requires-Dist: jupyter; extra == "examples"
32
+ Requires-Dist: diffcalc-core; extra == "examples"
33
+ Requires-Dist: xrayutilities; extra == "examples"
34
+ Dynamic: license-file
35
+
36
+ # hklforge
37
+
38
+ Diffractometer angle calculations for **any** geometry, with solvers that are
39
+ **generated exactly** from the geometry rather than hand-written for one
40
+ instrument (diffcalc) or found by numerical search (libhkl, ad_hoc_diffractometer).
41
+
42
+ Status: the geometry model, the exact sub-problems, the planner (geometry +
43
+ mode -> all solutions) and all of diffcalc's virtual angles (psi, naz, qaz,
44
+ alpha/beta, betain/betaout, omega/bisect, ...) exist and are tested against
45
+ diffcalc (all 194 modes), libhkl (all 13 E6C modes), xrayutilities and the
46
+ Bernina two-reflection solver.
47
+
48
+ Documentation: [docs/](docs/README.md) - [virtual angles](docs/virtual_angles.md)
49
+ with 3D figures, [modes](docs/modes.md), [verification](docs/verification.md).
50
+ Example notebooks: [examples/](examples/). Design notes and roadmap: `CLAUDE.md`.
51
+
52
+ ```python
53
+ from hklforge import Geometry
54
+
55
+ psic = Geometry.builtin("psic") # You (1999) six-circle, as diffcalc
56
+ custom = Geometry.from_xrayutilities( # xrayutilities' QConversion syntax
57
+ sample=["x+", "z-", "y+", "z-"], detector=["x+", "z-"], r_i=(0, 1, 0))
58
+ psic.q_phi({"mu": 0, "eta": 10, "chi": 0, "phi": 0, "nu": 0, "delta": 20}, k=4.5)
59
+
60
+ from hklforge import Diffractometer
61
+ from hklforge.lattice import b_matrix
62
+ ub = b_matrix(5.431, 5.431, 5.431) # phi frame, q = UB h (U = 1)
63
+ d = Diffractometer(psic, ub, energy=9000, surface_hkl=(0, 0, 1), reference_hkl=(0, 0, 1))
64
+ d.solve((1, 1, 2), {"eta": 0, "chi": 0, "phi": 0}) # every branch, as dicts of degrees
65
+ d.solve((1, 1, 2), {"chi": 10, "phi": 20, "betain": 5})
66
+ d.solve((1, 1, 1), {"mu": 0, "nu": 0, "h2": (2, 2, 0)}) # double diffraction, detector on h1
67
+ d.solve((1, 1, 1), {"eta": 0, "chi": 0, "h2": (2, 2, 0)}, detector="between")
68
+ d.solve((1, 1, 2), {"mu": 0, "nu": 0, "psi": 30}) # needs reference= / reference_hkl=
69
+ d.solve((1, 1, 2), {"nu": 0, "bisect": True, "omega": 0}) # bisecting
70
+ print(d.plan({"chi": 10, "phi": 20, "betain": 5}).describe())
71
+ angles = d.solve((1, 1, 2), {"mu": 0, "nu": 0, "betain": 2})[0]
72
+ d.pseudo(angles) # all virtual angles of a position
73
+
74
+ from hklforge.draw import draw # 3D drawing (matplotlib)
75
+ draw(d, angles, show=("ttheta", "psi"))
76
+ ```
77
+
78
+ Tests (`pytest`) compare against diffcalc-core and xrayutilities.
79
+
80
+ ## License
81
+
82
+ BSD 3-Clause, see [LICENSE](LICENSE). The software is provided "as is",
83
+ without warranty of any kind. Check computed angles against your
84
+ instrument's limits before moving motors.
@@ -0,0 +1,49 @@
1
+ # hklforge
2
+
3
+ Diffractometer angle calculations for **any** geometry, with solvers that are
4
+ **generated exactly** from the geometry rather than hand-written for one
5
+ instrument (diffcalc) or found by numerical search (libhkl, ad_hoc_diffractometer).
6
+
7
+ Status: the geometry model, the exact sub-problems, the planner (geometry +
8
+ mode -> all solutions) and all of diffcalc's virtual angles (psi, naz, qaz,
9
+ alpha/beta, betain/betaout, omega/bisect, ...) exist and are tested against
10
+ diffcalc (all 194 modes), libhkl (all 13 E6C modes), xrayutilities and the
11
+ Bernina two-reflection solver.
12
+
13
+ Documentation: [docs/](docs/README.md) - [virtual angles](docs/virtual_angles.md)
14
+ with 3D figures, [modes](docs/modes.md), [verification](docs/verification.md).
15
+ Example notebooks: [examples/](examples/). Design notes and roadmap: `CLAUDE.md`.
16
+
17
+ ```python
18
+ from hklforge import Geometry
19
+
20
+ psic = Geometry.builtin("psic") # You (1999) six-circle, as diffcalc
21
+ custom = Geometry.from_xrayutilities( # xrayutilities' QConversion syntax
22
+ sample=["x+", "z-", "y+", "z-"], detector=["x+", "z-"], r_i=(0, 1, 0))
23
+ psic.q_phi({"mu": 0, "eta": 10, "chi": 0, "phi": 0, "nu": 0, "delta": 20}, k=4.5)
24
+
25
+ from hklforge import Diffractometer
26
+ from hklforge.lattice import b_matrix
27
+ ub = b_matrix(5.431, 5.431, 5.431) # phi frame, q = UB h (U = 1)
28
+ d = Diffractometer(psic, ub, energy=9000, surface_hkl=(0, 0, 1), reference_hkl=(0, 0, 1))
29
+ d.solve((1, 1, 2), {"eta": 0, "chi": 0, "phi": 0}) # every branch, as dicts of degrees
30
+ d.solve((1, 1, 2), {"chi": 10, "phi": 20, "betain": 5})
31
+ d.solve((1, 1, 1), {"mu": 0, "nu": 0, "h2": (2, 2, 0)}) # double diffraction, detector on h1
32
+ d.solve((1, 1, 1), {"eta": 0, "chi": 0, "h2": (2, 2, 0)}, detector="between")
33
+ d.solve((1, 1, 2), {"mu": 0, "nu": 0, "psi": 30}) # needs reference= / reference_hkl=
34
+ d.solve((1, 1, 2), {"nu": 0, "bisect": True, "omega": 0}) # bisecting
35
+ print(d.plan({"chi": 10, "phi": 20, "betain": 5}).describe())
36
+ angles = d.solve((1, 1, 2), {"mu": 0, "nu": 0, "betain": 2})[0]
37
+ d.pseudo(angles) # all virtual angles of a position
38
+
39
+ from hklforge.draw import draw # 3D drawing (matplotlib)
40
+ draw(d, angles, show=("ttheta", "psi"))
41
+ ```
42
+
43
+ Tests (`pytest`) compare against diffcalc-core and xrayutilities.
44
+
45
+ ## License
46
+
47
+ BSD 3-Clause, see [LICENSE](LICENSE). The software is provided "as is",
48
+ without warranty of any kind. Check computed angles against your
49
+ instrument's limits before moving motors.
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hklforge"
7
+ version = "0.0.1"
8
+ description = "Diffractometer angle solvers generated exactly from a declared geometry"
9
+ requires-python = ">=3.10"
10
+ license = "BSD-3-Clause"
11
+ license-files = ["LICENSE"]
12
+ authors = [{name = "Henrik Lemke"}]
13
+ readme = "README.md"
14
+ keywords = ["diffraction", "diffractometer", "crystallography", "x-ray", "hkl", "synchrotron", "XFEL"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Scientific/Engineering :: Physics",
18
+ "Intended Audience :: Science/Research",
19
+ "Development Status :: 3 - Alpha",
20
+ ]
21
+ dependencies = ["numpy", "pyyaml"]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/swissfel/hklforge"
25
+ Documentation = "https://github.com/swissfel/hklforge/tree/main/docs"
26
+
27
+ [project.optional-dependencies]
28
+ draw = ["matplotlib"]
29
+ # reference implementations the tests compare against
30
+ test = ["pytest", "scipy", "diffcalc-core", "xrayutilities", "matplotlib", "pandas"]
31
+ examples = ["matplotlib", "pandas", "jupyter", "diffcalc-core", "xrayutilities"]
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.setuptools.package-data]
37
+ "hklforge.geometries" = ["*.yml"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
41
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"]
@@ -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-}