DimSpin 0.1.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.
- dimspin/Adaptive_Grid_Method.py +212 -0
- dimspin/AutoSim.py +113 -0
- dimspin/Class_Spec.py +270 -0
- dimspin/Class_Spin.py +462 -0
- dimspin/Crystal_Rotation.py +74 -0
- dimspin/ETeam_Hyperfine.py +25 -0
- dimspin/ETeam_ZFS.py +24 -0
- dimspin/ETeam_Zeeman.py +27 -0
- dimspin/Eigenfield_Method.py +114 -0
- dimspin/Eular2Rot.py +52 -0
- dimspin/Fibonacci_Orientation.py +19 -0
- dimspin/High_Field_Method.py +133 -0
- dimspin/Levels_Plot.py +119 -0
- dimspin/Line_Broadening.py +178 -0
- dimspin/Orientation_Switch.py +27 -0
- dimspin/Parallel.py +92 -0
- dimspin/Pointsnum_Optimise.py +17 -0
- dimspin/Powder.py +118 -0
- dimspin/Rodrigues_Rotation.py +11 -0
- dimspin/Root_Finder.py +220 -0
- dimspin/Show_Spectra.py +48 -0
- dimspin/Space_Group.py +6451 -0
- dimspin/Space_Group_Expand.py +140 -0
- dimspin/Space_Group_L.py +135 -0
- dimspin/Spec_Oneside.py +68 -0
- dimspin/Spin_Operators.py +89 -0
- dimspin/Steven_Operator.py +161 -0
- dimspin/Team_Hyperfine.py +23 -0
- dimspin/Team_ZFS.py +24 -0
- dimspin/Team_ZFS_HighOrder.py +48 -0
- dimspin/Team_Zeeman.py +22 -0
- dimspin/Tensor.py +71 -0
- dimspin/Truncate_Observable.py +34 -0
- dimspin/Vec_normalize.py +9 -0
- dimspin/__init__.py +28 -0
- dimspin-0.1.0.dist-info/METADATA +142 -0
- dimspin-0.1.0.dist-info/RECORD +40 -0
- dimspin-0.1.0.dist-info/WHEEL +5 -0
- dimspin-0.1.0.dist-info/licenses/LICENSE +21 -0
- dimspin-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Resonance fields from the generalized eigenvalue problem.
|
|
2
|
+
|
|
3
|
+
The spin Hamiltonian is linear in the field, H(B) = H0 + B * H1. The
|
|
4
|
+
eigenvalues of the commutator superoperator L = I (x) H - H (x) H are all
|
|
5
|
+
level differences, so the resonance condition E_j - E_i = mwfreq is the
|
|
6
|
+
generalized eigenvalue problem (mwfreq * I - L0) v = B * L1 v.
|
|
7
|
+
|
|
8
|
+
Public entry point: :func:`eigenfield_method`. It returns every resonance in
|
|
9
|
+
the field window at once, including forbidden and level-crossing
|
|
10
|
+
transitions, without labeling or bracketing. The cost grows as the square of
|
|
11
|
+
the level count, so it serves as an independent reference for the iterative
|
|
12
|
+
methods rather than a production path.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from scipy.linalg import eigvals
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _build_H0_H1(spin, spec, modulation_symbol):
|
|
20
|
+
"""
|
|
21
|
+
Inputs: Spin and Spec objects; modulation_symbol ("positive" or
|
|
22
|
+
"negative").
|
|
23
|
+
|
|
24
|
+
Returns: the constant matrices H0 and H1 with H(B) = H0 + B * H1.
|
|
25
|
+
|
|
26
|
+
Notes: the Spin must already have its field-independent terms and field
|
|
27
|
+
gradients prepared. Electric-field terms are built here from the Spec.
|
|
28
|
+
"""
|
|
29
|
+
if modulation_symbol not in ('positive', 'negative'):
|
|
30
|
+
raise ValueError("modulation_symbol must be 'positive' or 'negative'.")
|
|
31
|
+
sign = 1 if modulation_symbol == 'positive' else -1
|
|
32
|
+
|
|
33
|
+
if spec.modtype == 'Bmod':
|
|
34
|
+
H0 = spin.H_initial + sign * spec.Bmod * spin.H_g_grad
|
|
35
|
+
H1 = spin.H_g_grad
|
|
36
|
+
elif spec.modtype == 'Emod':
|
|
37
|
+
spin.update_Etensor(spec.E1)
|
|
38
|
+
spin.modulate_E_initial(spec.E1)
|
|
39
|
+
H0 = spin.H_initial + sign * spin.H_Einitial
|
|
40
|
+
H1 = spin.H_g_grad + sign * spin.H_T_grad
|
|
41
|
+
else:
|
|
42
|
+
if not (spin.dg1.any() or spin.dD1.any() or spin.dA1.any()):
|
|
43
|
+
raise ValueError('Parameter modulation is selected, but no '
|
|
44
|
+
'Delta g / Delta D / Delta A is given on the Spin.')
|
|
45
|
+
H0 = spin.H_initial + sign * spin.H_delta_const
|
|
46
|
+
H1 = spin.H_g_grad + sign * spin.H_dg_grad
|
|
47
|
+
return H0, H1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _resonance_fields(H0, H1, mwfreq, field_lo, field_hi):
|
|
51
|
+
"""
|
|
52
|
+
Inputs: Hamiltonian constants; microwave frequency (MHz); field window.
|
|
53
|
+
|
|
54
|
+
Returns: the resonance fields inside the window, sorted and deduplicated.
|
|
55
|
+
|
|
56
|
+
Notes: the superoperator matrices have dimension N^2 with N the number of
|
|
57
|
+
levels, so the dense QZ solve is much slower than the iterative methods.
|
|
58
|
+
L1 is singular, hence non-finite eigenvalues are filtered out.
|
|
59
|
+
"""
|
|
60
|
+
N = H0.shape[0]
|
|
61
|
+
I = np.eye(N)
|
|
62
|
+
L0 = np.kron(I, H0) - np.kron(H0, I)
|
|
63
|
+
L1 = np.kron(I, H1) - np.kron(H1, I)
|
|
64
|
+
A = mwfreq * np.eye(N * N) - L0
|
|
65
|
+
C = L1
|
|
66
|
+
w = eigvals(A, C)
|
|
67
|
+
tol = 1e-6
|
|
68
|
+
real = np.real(w)
|
|
69
|
+
mask = (np.isfinite(w)
|
|
70
|
+
& (np.abs(np.imag(w)) <= tol * (1.0 + np.abs(real)))
|
|
71
|
+
& (real >= field_lo - tol) & (real <= field_hi + tol))
|
|
72
|
+
fields = np.sort(real[mask])
|
|
73
|
+
if fields.size:
|
|
74
|
+
keep = [fields[0]]
|
|
75
|
+
for f in fields[1:]:
|
|
76
|
+
if f - keep[-1] > 1e-3:
|
|
77
|
+
keep.append(f)
|
|
78
|
+
fields = np.array(keep)
|
|
79
|
+
return fields
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def eigenfield_method(spin, spec, modulation_symbol):
|
|
83
|
+
"""
|
|
84
|
+
Inputs: Spin and Spec objects; modulation_symbol ("positive" or
|
|
85
|
+
"negative").
|
|
86
|
+
|
|
87
|
+
Returns: transitions (field, jj, kk, intensity) for every resonance in the
|
|
88
|
+
field window, with intensity equal to the transition probability times the
|
|
89
|
+
population difference.
|
|
90
|
+
|
|
91
|
+
Notes: the intensities are backfilled by diagonalizing H(B) once per
|
|
92
|
+
resonance field, so they match the other methods. The field tolerance for
|
|
93
|
+
matching a gap to mwfreq is 1e-2 MHz.
|
|
94
|
+
"""
|
|
95
|
+
H0, H1 = _build_H0_H1(spin, spec, modulation_symbol)
|
|
96
|
+
|
|
97
|
+
fields = _resonance_fields(H0, H1, spec.mwfreq,
|
|
98
|
+
spec.fieldrange[0], spec.fieldrange[-1])
|
|
99
|
+
|
|
100
|
+
from .Root_Finder import population_difference, transition_probability
|
|
101
|
+
|
|
102
|
+
tol_freq = 1e-2
|
|
103
|
+
transitions = []
|
|
104
|
+
for B in fields:
|
|
105
|
+
eigvals, eigvecs = np.linalg.eigh(H0 + B * H1)
|
|
106
|
+
for jj in range(spin.total_Level):
|
|
107
|
+
for kk in range(jj + 1, spin.total_Level):
|
|
108
|
+
if abs(abs(eigvals[kk] - eigvals[jj]) - spec.mwfreq) > tol_freq:
|
|
109
|
+
continue
|
|
110
|
+
p = transition_probability(spin.S, spin.I, spin.g1, eigvecs, jj, kk)
|
|
111
|
+
if p > 0.0:
|
|
112
|
+
pd = population_difference(eigvals, jj, kk, spec.Temperature)
|
|
113
|
+
transitions.append((B, jj, kk, p * pd))
|
|
114
|
+
return transitions
|
dimspin/Eular2Rot.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Euler-angle and orientation helpers.
|
|
2
|
+
|
|
3
|
+
Euler angles use the zyz convention and are expressed in radians.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def sin(a):
|
|
10
|
+
return np.sin(a)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def cos(a):
|
|
14
|
+
return np.cos(a)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def eular2rotzyz(alpha, beta, gamma):
|
|
18
|
+
"""Return the zyz rotation matrix for angles in radians."""
|
|
19
|
+
Rz = np.array([[cos(alpha), sin(alpha), 0], [-sin(alpha), cos(alpha), 0], [0, 0, 1]])
|
|
20
|
+
Ry = np.array([[cos(beta), 0, -sin(beta)], [0, 1, 0], [sin(beta), 0, cos(beta)]])
|
|
21
|
+
Rz1 = np.array([[cos(gamma), sin(gamma), 0], [-sin(gamma), cos(gamma), 0], [0, 0, 1]])
|
|
22
|
+
return Rz1 @ Ry @ Rz
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def resolve_orientation(ori):
|
|
26
|
+
"""Normalize an orientation to a 3x3 orthogonal matrix.
|
|
27
|
+
|
|
28
|
+
Accepts a 3x3 matrix or three Euler angles in the zyz convention (radians).
|
|
29
|
+
``None`` or a zero vector gives the identity matrix.
|
|
30
|
+
|
|
31
|
+
The determinant may be +1 for a proper rotation or -1 for an improper
|
|
32
|
+
operation such as inversion or a mirror. Second-order tensors transform as
|
|
33
|
+
``R @ T @ R.T`` for either sign.
|
|
34
|
+
|
|
35
|
+
High-order zero-field terms rotate the spin operators with ``R``
|
|
36
|
+
(``S_tensor = R @ S_lab``). The implemented ranks k = 2, 4, 6 are even,
|
|
37
|
+
so det(R) = -1 is acceptable.
|
|
38
|
+
"""
|
|
39
|
+
if ori is None:
|
|
40
|
+
return np.eye(3)
|
|
41
|
+
ori = np.array(ori)
|
|
42
|
+
if ori.shape == (3, 3):
|
|
43
|
+
R = ori
|
|
44
|
+
elif ori.shape == (3,) or ori.size == 3:
|
|
45
|
+
R = eular2rotzyz(ori[0], ori[1], ori[2])
|
|
46
|
+
else:
|
|
47
|
+
raise ValueError('Orientation must be a 3x3 matrix or 3 Euler angles, got %s' % (ori.shape,))
|
|
48
|
+
if not np.allclose(R @ R.T, np.eye(3), atol=1e-6):
|
|
49
|
+
raise ValueError('Orientation matrix is not orthogonal.')
|
|
50
|
+
if not np.isclose(abs(np.linalg.det(R)), 1.0, atol=1e-6):
|
|
51
|
+
raise ValueError('Orientation must be an orthogonal matrix with det=±1.')
|
|
52
|
+
return R
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Fibonacci-sphere sampling of crystallite orientations."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def fibonacci_orientation(n):
|
|
9
|
+
"""Return ``n`` approximately uniform unit vectors on the sphere."""
|
|
10
|
+
data = np.zeros((n, 3))
|
|
11
|
+
pi = math.pi
|
|
12
|
+
phi = (np.sqrt(5) - 1) / 2
|
|
13
|
+
for i in range(0, n):
|
|
14
|
+
data[i][2] = (2 * i + 1) / n - 1
|
|
15
|
+
item1 = np.sqrt(1 - data[i][2] * data[i][2])
|
|
16
|
+
item2 = 2 * pi * (i + 1) * phi
|
|
17
|
+
data[i][0] = item1 * math.cos(item2)
|
|
18
|
+
data[i][1] = item1 * math.sin(item2)
|
|
19
|
+
return data
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""High-field method: label transitions by matrix elements and solve the roots.
|
|
2
|
+
|
|
3
|
+
Public entry point: :func:`high_field_method`. Candidate (jj, kk) pairs are
|
|
4
|
+
chosen from the microwave transition matrix at the high-field end of the
|
|
5
|
+
sweep; the resonance field of each pair is then bracketed by the eigenvalue
|
|
6
|
+
gaps at both ends and solved with the Brent routine from Root_Finder.
|
|
7
|
+
Note that this method may miss spectral peaks when energy level crossings or
|
|
8
|
+
avoided crossings occur.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _transition_matrix(spin, eigvecs):
|
|
15
|
+
"""
|
|
16
|
+
Inputs: Spin object; eigenvectors at the high-field end.
|
|
17
|
+
|
|
18
|
+
Returns: M = U^dagger H1 U, with H1 = g1[0, :] . S the microwave coupling.
|
|
19
|
+
|
|
20
|
+
Notes: |M[kk, jj]|^2 is the transition probability used by
|
|
21
|
+
Root_Finder.transition_probability.
|
|
22
|
+
"""
|
|
23
|
+
from .Spin_Operators import Sx_get, Sy_get, Sz_get
|
|
24
|
+
Sx = Sx_get(spin.S, spin.I)
|
|
25
|
+
Sy = Sy_get(spin.S, spin.I)
|
|
26
|
+
Sz = Sz_get(spin.S, spin.I)
|
|
27
|
+
H1 = spin.g1[0][0] * Sx + spin.g1[0][1] * Sy + spin.g1[0][2] * Sz
|
|
28
|
+
return eigvecs.T.conj() @ H1 @ eigvecs
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _select_transition_pairs(spin, eigvecs, epsilon=1e-2):
|
|
32
|
+
"""
|
|
33
|
+
Inputs: Spin object; eigenvectors at the high-field end; relative threshold
|
|
34
|
+
epsilon.
|
|
35
|
+
|
|
36
|
+
Returns: the (jj, kk) pairs with |<kk|H1|jj>|^2 above epsilon times the
|
|
37
|
+
largest matrix element.
|
|
38
|
+
|
|
39
|
+
Notes: the threshold is insensitive to anisotropy, large E or A, and
|
|
40
|
+
Delta m_s >= 2 transitions from high-order ZFS, because all of these enter
|
|
41
|
+
through the matrix elements. The default 1e-2 sits in the gap between
|
|
42
|
+
allowed and forbidden intensities.
|
|
43
|
+
"""
|
|
44
|
+
M = _transition_matrix(spin, eigvecs)
|
|
45
|
+
N = spin.total_Level
|
|
46
|
+
p = np.abs(M) ** 2
|
|
47
|
+
pmax = float(p.max())
|
|
48
|
+
pairs = []
|
|
49
|
+
for jj in range(N - 1):
|
|
50
|
+
for kk in range(jj + 1, N):
|
|
51
|
+
if p[kk, jj] > epsilon * pmax:
|
|
52
|
+
pairs.append((jj, kk))
|
|
53
|
+
return pairs
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _find_transitions(spin, spec, field_left, field_right, eigvals1, eigvals2,
|
|
57
|
+
pairs, modulation_symbol, find_root, root_args):
|
|
58
|
+
"""
|
|
59
|
+
Inputs: Spin and Spec objects; bracket endpoints; eigenvalues at both ends;
|
|
60
|
+
candidate pairs; modulation_symbol; root-finder function for the modulation
|
|
61
|
+
type and its extra positional arguments.
|
|
62
|
+
|
|
63
|
+
Returns: the list of transitions whose gap crosses mwFreq between the ends.
|
|
64
|
+
|
|
65
|
+
Notes: only pairs whose gap crosses mwFreq are passed to the root finder;
|
|
66
|
+
both endpoint residuals are supplied so the ends are not diagonalized
|
|
67
|
+
again.
|
|
68
|
+
"""
|
|
69
|
+
transitions = []
|
|
70
|
+
for jj, kk in pairs:
|
|
71
|
+
left = eigvals1[kk] - eigvals1[jj]
|
|
72
|
+
right = eigvals2[kk] - eigvals2[jj]
|
|
73
|
+
if (left < spec.mwfreq and right > spec.mwfreq) or (left > spec.mwfreq and right < spec.mwfreq):
|
|
74
|
+
transition = find_root(spin, spec.mwfreq, *root_args, field_left, field_right,
|
|
75
|
+
jj, kk, modulation_symbol, spec.Temperature,
|
|
76
|
+
fa=abs(left) - spec.mwfreq, fb=abs(right) - spec.mwfreq)
|
|
77
|
+
if transition is not None:
|
|
78
|
+
transitions.append(transition)
|
|
79
|
+
return transitions
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def high_field_method(spin, spec, modulation_symbol):
|
|
83
|
+
"""
|
|
84
|
+
Inputs: Spin and Spec objects; modulation_symbol ("positive" or
|
|
85
|
+
"negative").
|
|
86
|
+
|
|
87
|
+
Returns: a list of (field, jj, kk, intensity) transitions.
|
|
88
|
+
|
|
89
|
+
Notes: pairs are selected from the microwave transition matrix at the
|
|
90
|
+
high-field end; if fewer than 80% of them yield a root, all pairs are
|
|
91
|
+
retried so that transitions interrupted by level crossings are recovered.
|
|
92
|
+
"""
|
|
93
|
+
field_left = spec.fieldrange[0]
|
|
94
|
+
field_right = spec.fieldrange[-1]
|
|
95
|
+
|
|
96
|
+
if spec.modtype == 'Bmod':
|
|
97
|
+
from .Root_Finder import find_root_Bmod
|
|
98
|
+
spin.modulate_B(field_left, spec.Bmod, modulation_symbol)
|
|
99
|
+
eigvals1 = np.linalg.eigvalsh(spin.H_total)
|
|
100
|
+
spin.modulate_B(field_right, spec.Bmod, modulation_symbol)
|
|
101
|
+
eigvals2, eigvecs2 = np.linalg.eigh(spin.H_total)
|
|
102
|
+
find_root, root_args = find_root_Bmod, (spec.Bmod,)
|
|
103
|
+
elif spec.modtype == 'Emod':
|
|
104
|
+
from .Root_Finder import find_root_Emod
|
|
105
|
+
spin.update_Etensor(spec.E1)
|
|
106
|
+
spin.modulate_E_initial(spec.E1)
|
|
107
|
+
spin.modulate_E_T(field_left, spec.E1, modulation_symbol)
|
|
108
|
+
eigvals1 = np.linalg.eigvalsh(spin.H_total)
|
|
109
|
+
spin.modulate_E_T(field_right, spec.E1, modulation_symbol)
|
|
110
|
+
eigvals2, eigvecs2 = np.linalg.eigh(spin.H_total)
|
|
111
|
+
find_root, root_args = find_root_Emod, (spec.E1,)
|
|
112
|
+
else:
|
|
113
|
+
from .Root_Finder import find_root_param
|
|
114
|
+
if not (spin.dg1.any() or spin.dD1.any() or spin.dA1.any()):
|
|
115
|
+
raise ValueError('Parameter modulation is selected, but no '
|
|
116
|
+
'Delta g / Delta D / Delta A is given on the Spin.')
|
|
117
|
+
spin.modulate_param(field_left, modulation_symbol)
|
|
118
|
+
eigvals1 = np.linalg.eigvalsh(spin.H_total)
|
|
119
|
+
spin.modulate_param(field_right, modulation_symbol)
|
|
120
|
+
eigvals2, eigvecs2 = np.linalg.eigh(spin.H_total)
|
|
121
|
+
find_root, root_args = find_root_param, ()
|
|
122
|
+
|
|
123
|
+
fast_pairs = _select_transition_pairs(spin, eigvecs2)
|
|
124
|
+
transitions = _find_transitions(spin, spec, field_left, field_right, eigvals1, eigvals2,
|
|
125
|
+
fast_pairs, modulation_symbol, find_root, root_args)
|
|
126
|
+
|
|
127
|
+
if len(transitions) < 0.8 * len(fast_pairs):
|
|
128
|
+
full_pairs = [(jj, kk) for jj in range(spin.total_Level - 1)
|
|
129
|
+
for kk in range(jj + 1, spin.total_Level)]
|
|
130
|
+
transitions = _find_transitions(spin, spec, field_left, field_right, eigvals1, eigvals2,
|
|
131
|
+
full_pairs, modulation_symbol, find_root, root_args)
|
|
132
|
+
|
|
133
|
+
return transitions
|
dimspin/Levels_Plot.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Energy-level diagrams for a single crystal orientation.
|
|
2
|
+
|
|
3
|
+
Levels are drawn as E_i(B) versus B, with a vertical double arrow at every
|
|
4
|
+
resonance field connecting the two levels involved. The module is separate
|
|
5
|
+
from the spectrum calculation; it only supports ``spec.sample ==
|
|
6
|
+
'Crystal_Oneside'`` because a rotation or powder sweep has no single
|
|
7
|
+
energy-level diagram.
|
|
8
|
+
|
|
9
|
+
The same H(B) = H0 + B * H1 construction as the root finders is used, and the
|
|
10
|
+
resonance arrows come from the selected method, so they match the spectrum.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _prepare(spin, spec):
|
|
17
|
+
"""
|
|
18
|
+
Inputs: Spin and Spec objects.
|
|
19
|
+
|
|
20
|
+
Returns: a prepared copy of the spin.
|
|
21
|
+
|
|
22
|
+
Notes: the Spec parameters are checked and the tensor orientations,
|
|
23
|
+
field gradients and field-independent Hamiltonian are prepared.
|
|
24
|
+
"""
|
|
25
|
+
from copy import deepcopy
|
|
26
|
+
spec.check_simpara()
|
|
27
|
+
prepared = deepcopy(spin)
|
|
28
|
+
prepared.identity_tensor(spec.crystal_orientation, np.eye(3))
|
|
29
|
+
prepared.update_Btensor()
|
|
30
|
+
prepared.update_H_initial()
|
|
31
|
+
return prepared
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _level_curves(H0, H1, fieldrange, npoints):
|
|
35
|
+
"""
|
|
36
|
+
Inputs: Hamiltonian constants; field range; number of points.
|
|
37
|
+
|
|
38
|
+
Returns: (field grid, E) with E[i, :] the i-th level along the grid.
|
|
39
|
+
"""
|
|
40
|
+
B = np.linspace(fieldrange[0], fieldrange[-1], npoints)
|
|
41
|
+
E = np.array([np.linalg.eigvalsh(H0 + b * H1) for b in B]).T
|
|
42
|
+
return B, E
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _resonance_pairs(spin, spec, modulation_symbol, method, truncate):
|
|
46
|
+
"""
|
|
47
|
+
Inputs: prepared Spin; Spec object; modulation_symbol; method name;
|
|
48
|
+
whether to apply the spectrum truncation.
|
|
49
|
+
|
|
50
|
+
Returns: a list of (field, u, v) resonance pairs, with the intensity
|
|
51
|
+
dropped.
|
|
52
|
+
|
|
53
|
+
Notes: truncate=True applies the same observable-transition selection as
|
|
54
|
+
Spec_Oneside, so the arrows match the spectrum; False keeps every
|
|
55
|
+
transition returned by the method.
|
|
56
|
+
"""
|
|
57
|
+
num_allowed = int(2 * spin.S * (2 * spin.I + 1))
|
|
58
|
+
if method == 'High_Field_Method':
|
|
59
|
+
from .High_Field_Method import high_field_method
|
|
60
|
+
transitions = high_field_method(spin, spec, modulation_symbol)
|
|
61
|
+
elif method == 'Adaptive_Grid_Method':
|
|
62
|
+
from .Adaptive_Grid_Method import adaptive_grid_method
|
|
63
|
+
transitions = adaptive_grid_method(spin, spec, modulation_symbol)
|
|
64
|
+
else:
|
|
65
|
+
raise ValueError(f"unknown method {method!r}")
|
|
66
|
+
if truncate:
|
|
67
|
+
from .Truncate_Observable import truncate_observable
|
|
68
|
+
transitions = truncate_observable(transitions, num_allowed)
|
|
69
|
+
return [(t[0], t[1], t[2]) for t in transitions]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def plot_energy_levels(spin, spec, modulation_symbol='positive', method=None,
|
|
73
|
+
npoints=2000, show_resonances=True, truncate=True,
|
|
74
|
+
ax=None, **kwargs):
|
|
75
|
+
"""
|
|
76
|
+
Inputs: Spin and Spec objects; modulation_symbol ("positive" or
|
|
77
|
+
"negative"); method name (defaults to ``spec.method``); number of points
|
|
78
|
+
on the level curves; whether to draw resonance arrows; whether to apply
|
|
79
|
+
the spectrum truncation; optional axes; extra line keywords.
|
|
80
|
+
|
|
81
|
+
Returns: the axes used.
|
|
82
|
+
|
|
83
|
+
Notes: only ``spec.sample == 'Crystal_Oneside'`` is supported. The arrows
|
|
84
|
+
use the same method and modulation sign as the spectrum, so they stay
|
|
85
|
+
consistent with the simulated peaks. With High_Field_Method the sorted
|
|
86
|
+
level indices can be followed incorrectly at strong level crossings; this
|
|
87
|
+
is a known limitation of the method itself.
|
|
88
|
+
"""
|
|
89
|
+
import matplotlib.pyplot as plt
|
|
90
|
+
|
|
91
|
+
if spec.sample != 'Crystal_Oneside':
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"plot_energy_levels only supports a single orientation "
|
|
94
|
+
f"(spec.sample == 'Crystal_Oneside'); got {spec.sample!r}. "
|
|
95
|
+
"A rotation/powder sweep has no single energy-level diagram.")
|
|
96
|
+
|
|
97
|
+
if method is None:
|
|
98
|
+
method = spec.method
|
|
99
|
+
|
|
100
|
+
prepared = _prepare(spin, spec)
|
|
101
|
+
from .Eigenfield_Method import _build_H0_H1
|
|
102
|
+
H0, H1 = _build_H0_H1(prepared, spec, modulation_symbol)
|
|
103
|
+
|
|
104
|
+
B, E = _level_curves(H0, H1, spec.fieldrange, npoints)
|
|
105
|
+
|
|
106
|
+
if ax is None:
|
|
107
|
+
ax = plt.gca()
|
|
108
|
+
for i in range(E.shape[0]):
|
|
109
|
+
ax.plot(B, E[i], lw=0.8, **kwargs)
|
|
110
|
+
|
|
111
|
+
if show_resonances:
|
|
112
|
+
for Bk, u, v in _resonance_pairs(prepared, spec, modulation_symbol, method, truncate):
|
|
113
|
+
ev = np.linalg.eigvalsh(H0 + Bk * H1)
|
|
114
|
+
ax.annotate('', xy=(Bk, ev[v]), xytext=(Bk, ev[u]),
|
|
115
|
+
arrowprops=dict(arrowstyle='<->', color='red', lw=0.8))
|
|
116
|
+
|
|
117
|
+
ax.set_xlabel('Magnetic field (G)')
|
|
118
|
+
ax.set_ylabel('Energy (MHz)')
|
|
119
|
+
return ax
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Line-shape profiles and spectrum broadening.
|
|
2
|
+
|
|
3
|
+
Public entry point: :func:`broaden`. Two evaluation paths are available:
|
|
4
|
+
direct summation (exact for any grid) and FFT convolution (uniform grid, fast
|
|
5
|
+
for many transitions). The FFT path adds out-of-grid transitions by direct
|
|
6
|
+
evaluation, so their tails inside the grid are retained.
|
|
7
|
+
|
|
8
|
+
All widths use the same units as the field grid.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from scipy.special import wofz
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _line_values(x, sigma_l, sigma_g):
|
|
18
|
+
"""Return the area-normalized line profile at offsets ``x``."""
|
|
19
|
+
sqrt2 = np.sqrt(2.0)
|
|
20
|
+
if sigma_g == 0:
|
|
21
|
+
return (sigma_l / np.pi) / (x * x + sigma_l * sigma_l)
|
|
22
|
+
z = (x + 1j * sigma_l) / (sigma_g * sqrt2)
|
|
23
|
+
return np.real(wofz(z)) / (sigma_g * np.sqrt(2.0 * np.pi))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def line_shape(fieldrange, position, intensity, sigma_l, sigma_g):
|
|
27
|
+
"""Return one area-normalized line.
|
|
28
|
+
|
|
29
|
+
Inputs: field grid, center, integrated intensity, Lorentzian half-width,
|
|
30
|
+
Gaussian standard deviation. At least one width must be nonzero.
|
|
31
|
+
|
|
32
|
+
Returns the line values; their integral over the grid equals ``intensity``.
|
|
33
|
+
``sigma_g = 0`` gives a Lorentzian; ``sigma_l = 0`` gives a Gaussian.
|
|
34
|
+
"""
|
|
35
|
+
fieldrange = np.asarray(fieldrange, dtype=float)
|
|
36
|
+
return intensity * _line_values(fieldrange - position, sigma_l, sigma_g)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def broaden_direct(fieldrange, positions, intensities, sigma_l, sigma_g):
|
|
40
|
+
"""Sum line shapes directly.
|
|
41
|
+
|
|
42
|
+
Inputs: field grid, positions, intensities, Lorentzian half-width, Gaussian
|
|
43
|
+
standard deviation.
|
|
44
|
+
|
|
45
|
+
Returns the summed spectrum. Exact for any grid; positions outside the grid
|
|
46
|
+
contribute their tails inside it. Cost is O(M * N).
|
|
47
|
+
"""
|
|
48
|
+
fieldrange = np.asarray(fieldrange, dtype=float)
|
|
49
|
+
positions = np.asarray(positions, dtype=float).ravel()
|
|
50
|
+
intensities = np.asarray(intensities, dtype=float).ravel()
|
|
51
|
+
if positions.size != intensities.size:
|
|
52
|
+
raise ValueError("positions and intensities must have the same length")
|
|
53
|
+
if positions.size == 0:
|
|
54
|
+
return np.zeros(fieldrange.size)
|
|
55
|
+
|
|
56
|
+
x = fieldrange[None, :] - positions[:, None]
|
|
57
|
+
y = _line_values(x, sigma_l, sigma_g)
|
|
58
|
+
return (y * intensities[:, None]).sum(axis=0)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@lru_cache(maxsize=None)
|
|
62
|
+
def _kernel_fft(spacing, N, sigma_l, sigma_g, oversample):
|
|
63
|
+
"""Return the cached FFT of a line-shape kernel for a uniform grid."""
|
|
64
|
+
Nf = N * oversample
|
|
65
|
+
spacing_f = spacing / oversample
|
|
66
|
+
Mf = 2 * Nf
|
|
67
|
+
offsets = (np.arange(Mf) - Nf) * spacing_f
|
|
68
|
+
return np.fft.fft(_line_values(offsets, sigma_l, sigma_g))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _voigt_kernel_fft(fieldrange, sigma_l, sigma_g, oversample=1):
|
|
72
|
+
"""Return the kernel FFT for ``fieldrange`` and the given widths."""
|
|
73
|
+
fieldrange = np.asarray(fieldrange, dtype=float)
|
|
74
|
+
N = fieldrange.size
|
|
75
|
+
spacing = fieldrange[1] - fieldrange[0]
|
|
76
|
+
return _kernel_fft(spacing, N, sigma_l, sigma_g, oversample)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _fft_inside(fieldrange, positions, intensities, sigma_l, sigma_g,
|
|
80
|
+
kernel_fft=None, oversample=1):
|
|
81
|
+
"""FFT convolution for transitions inside the field grid."""
|
|
82
|
+
fieldrange = np.asarray(fieldrange, dtype=float)
|
|
83
|
+
N = fieldrange.size
|
|
84
|
+
spacing = fieldrange[1] - fieldrange[0]
|
|
85
|
+
lo = fieldrange[0]
|
|
86
|
+
|
|
87
|
+
if kernel_fft is None:
|
|
88
|
+
kernel_fft = _voigt_kernel_fft(fieldrange, sigma_l, sigma_g, oversample)
|
|
89
|
+
Nf = kernel_fft.shape[0] // 2
|
|
90
|
+
spacing_f = spacing * N / Nf
|
|
91
|
+
|
|
92
|
+
idx = (positions - lo) / spacing_f
|
|
93
|
+
i0 = np.floor(idx).astype(int)
|
|
94
|
+
frac = idx - i0
|
|
95
|
+
valid = (i0 >= 0) & (i0 <= Nf - 1)
|
|
96
|
+
i0 = i0[valid]
|
|
97
|
+
frac = frac[valid]
|
|
98
|
+
inten = intensities[valid]
|
|
99
|
+
if i0.size == 0:
|
|
100
|
+
return np.zeros(N)
|
|
101
|
+
|
|
102
|
+
stick = np.zeros(Nf)
|
|
103
|
+
np.add.at(stick, i0, inten * (1.0 - frac))
|
|
104
|
+
np.add.at(stick, np.minimum(i0 + 1, Nf - 1), inten * frac)
|
|
105
|
+
|
|
106
|
+
Mf = 2 * Nf
|
|
107
|
+
stick_pad = np.zeros(Mf)
|
|
108
|
+
stick_pad[:Nf] = stick
|
|
109
|
+
full = np.fft.ifft(np.fft.fft(stick_pad) * kernel_fft).real
|
|
110
|
+
return full[Nf:Nf + Nf][::(Nf // N)]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def broaden_fft(fieldrange, positions, intensities, sigma_l, sigma_g,
|
|
114
|
+
kernel_fft=None, oversample=1):
|
|
115
|
+
"""Sum line shapes by FFT convolution, including out-of-grid tails.
|
|
116
|
+
|
|
117
|
+
Inputs: uniform field grid, positions (may lie outside the grid),
|
|
118
|
+
intensities, Lorentzian half-width, Gaussian standard deviation.
|
|
119
|
+
``kernel_fft`` may be supplied for repeated calls; ``oversample`` refines
|
|
120
|
+
the internal grid.
|
|
121
|
+
|
|
122
|
+
Returns the summed spectrum. Inside transitions use FFT; outside
|
|
123
|
+
transitions are added by direct evaluation. Sub-grid error is about 0.3%
|
|
124
|
+
of the peak at ``oversample=1`` and scales as 1/F^2.
|
|
125
|
+
"""
|
|
126
|
+
fieldrange = np.asarray(fieldrange, dtype=float)
|
|
127
|
+
N = fieldrange.size
|
|
128
|
+
if N < 2:
|
|
129
|
+
raise ValueError("fieldrange must contain at least two points")
|
|
130
|
+
spacing = fieldrange[1] - fieldrange[0]
|
|
131
|
+
if not np.allclose(np.diff(fieldrange), spacing, rtol=1e-6, atol=1e-12):
|
|
132
|
+
raise ValueError("broaden_fft requires a uniformly spaced field grid")
|
|
133
|
+
|
|
134
|
+
positions = np.asarray(positions, dtype=float).ravel()
|
|
135
|
+
intensities = np.asarray(intensities, dtype=float).ravel()
|
|
136
|
+
if positions.size != intensities.size:
|
|
137
|
+
raise ValueError("positions and intensities must have the same length")
|
|
138
|
+
if positions.size == 0:
|
|
139
|
+
return np.zeros(N)
|
|
140
|
+
|
|
141
|
+
lo = fieldrange[0]
|
|
142
|
+
hi = fieldrange[-1]
|
|
143
|
+
inside = (positions >= lo) & (positions <= hi)
|
|
144
|
+
spectrum = np.zeros(N)
|
|
145
|
+
if np.any(inside):
|
|
146
|
+
spectrum += _fft_inside(
|
|
147
|
+
fieldrange, positions[inside], intensities[inside],
|
|
148
|
+
sigma_l, sigma_g, kernel_fft, oversample,
|
|
149
|
+
)
|
|
150
|
+
if np.any(~inside):
|
|
151
|
+
spectrum += broaden_direct(
|
|
152
|
+
fieldrange, positions[~inside], intensities[~inside],
|
|
153
|
+
sigma_l, sigma_g,
|
|
154
|
+
)
|
|
155
|
+
return spectrum
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def broaden(fieldrange, positions, intensities, sigma_l, sigma_g,
|
|
159
|
+
method="auto", oversample=1, threshold=2):
|
|
160
|
+
"""Broaden all transitions and return the summed spectrum.
|
|
161
|
+
|
|
162
|
+
Inputs: field grid, positions, intensities, Lorentzian half-width, Gaussian
|
|
163
|
+
standard deviation. ``method`` is "auto", "direct" or "fft"; "auto" uses
|
|
164
|
+
direct summation for at most ``threshold`` transitions and FFT otherwise.
|
|
165
|
+
|
|
166
|
+
Returns the summed spectrum. Lines are area-normalized, so its integral
|
|
167
|
+
equals the sum of the intensities.
|
|
168
|
+
"""
|
|
169
|
+
if method not in ("auto", "direct", "fft"):
|
|
170
|
+
raise ValueError("method must be 'auto', 'direct' or 'fft'")
|
|
171
|
+
|
|
172
|
+
count = np.asarray(positions).size
|
|
173
|
+
if method == "direct" or (method == "auto" and count <= threshold):
|
|
174
|
+
return broaden_direct(fieldrange, positions, intensities, sigma_l, sigma_g)
|
|
175
|
+
return broaden_fft(
|
|
176
|
+
fieldrange, positions, intensities, sigma_l, sigma_g,
|
|
177
|
+
oversample=oversample,
|
|
178
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Rotation that carries one orientation direction onto another."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .Rodrigues_Rotation import rotation_matrix
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def orientation_switch(ori, iniori):
|
|
11
|
+
"""Return the rotation matrix that maps ``iniori`` onto ``ori``."""
|
|
12
|
+
ori = np.asarray(ori, dtype=float)
|
|
13
|
+
iniori = np.asarray(iniori, dtype=float)
|
|
14
|
+
|
|
15
|
+
rotaxis1 = np.cross(iniori, ori)
|
|
16
|
+
cos_angle = np.dot(ori, iniori) / np.sqrt(np.dot(ori, ori) * np.dot(iniori, iniori))
|
|
17
|
+
rotang1 = math.acos(float(np.clip(cos_angle, -1.0, 1.0)))
|
|
18
|
+
|
|
19
|
+
if np.linalg.norm(rotaxis1) < 1e-12:
|
|
20
|
+
if cos_angle >= 0.0:
|
|
21
|
+
return np.eye(3)
|
|
22
|
+
helper = np.array([1.0, 0.0, 0.0])
|
|
23
|
+
if abs(np.dot(helper, iniori)) > 0.9 * np.linalg.norm(iniori):
|
|
24
|
+
helper = np.array([0.0, 1.0, 0.0])
|
|
25
|
+
return rotation_matrix(np.cross(iniori, helper), math.pi)
|
|
26
|
+
|
|
27
|
+
return rotation_matrix(rotaxis1, rotang1)
|