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/Parallel.py ADDED
@@ -0,0 +1,92 @@
1
+ """
2
+ Achieve parallel computing to increase processing speed.
3
+ On Windows every worker re-imports numpy/scipy, so the default is moderate.
4
+ Users can override it with Spec.max_workers.
5
+ """
6
+
7
+ import logging
8
+ import os
9
+ from concurrent.futures import ProcessPoolExecutor
10
+
11
+ DEFAULT_MAX_WORKERS = min(os.cpu_count() or 4, 8)
12
+ def _total_ram_mb():
13
+ """Return total physical memory in MB, or None if it cannot be read."""
14
+ try:
15
+ if os.name == 'nt':
16
+ import ctypes
17
+ class MEMORYSTATUSEX(ctypes.Structure):
18
+ _fields_ = [
19
+ ('dwLength', ctypes.c_ulong),
20
+ ('dwMemoryLoad', ctypes.c_ulong),
21
+ ('ullTotalPhys', ctypes.c_ulonglong),
22
+ ('ullAvailPhys', ctypes.c_ulonglong),
23
+ ('ullTotalPageFile', ctypes.c_ulonglong),
24
+ ('ullAvailPageFile', ctypes.c_ulonglong),
25
+ ('ullTotalVirtual', ctypes.c_ulonglong),
26
+ ('ullAvailVirtual', ctypes.c_ulonglong),
27
+ ('ullAvailExtendedVirtual', ctypes.c_ulonglong),
28
+ ]
29
+ stat = MEMORYSTATUSEX()
30
+ stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
31
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
32
+ return int(stat.ullTotalPhys // (1024 * 1024))
33
+ else:
34
+ return int(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') // (1024 * 1024))
35
+ except Exception:
36
+ return None
37
+
38
+
39
+ def check_worker_count(n):
40
+ """Validate a worker count.
41
+
42
+ Raise ``ValueError`` for non-positive or non-integer values and emit a
43
+ warning when the count exceeds the logical core count or the estimated
44
+ memory use.
45
+ """
46
+ try:
47
+ n = int(n)
48
+ except (TypeError, ValueError):
49
+ raise ValueError(f'worker count must be an integer, got {n!r}')
50
+ if n <= 0:
51
+ raise ValueError(f'worker count must be a positive integer, got {n}')
52
+
53
+ logical = os.cpu_count() or 1
54
+ if n > logical:
55
+ logging.warning(f'worker count {n} exceeds the {logical} logical cores; oversubscription may be slower.')
56
+
57
+ # Rough estimate: each worker re-imports numpy/scipy, about 250 MB.
58
+ total_mb = _total_ram_mb()
59
+ if total_mb is not None and n * 250 > total_mb * 0.8:
60
+ logging.warning(
61
+ f'worker count {n} is estimated to need about {n * 250} MB, '
62
+ f'close to 80% of total memory ({total_mb} MB); paging may occur.'
63
+ )
64
+ return n
65
+
66
+
67
+ def resolve_workers(spec_max):
68
+ """Return the default worker count when ``spec_max`` is None."""
69
+ if spec_max is None:
70
+ return DEFAULT_MAX_WORKERS
71
+ return check_worker_count(spec_max)
72
+
73
+
74
+ def set_blas_threads_one():
75
+ # Limit BLAS/OpenMP threads so workers do not compete for cores.
76
+ # Set them in the parent process so spawned workers inherit them.
77
+ os.environ['OMP_NUM_THREADS'] = '1'
78
+ os.environ['OPENBLAS_NUM_THREADS'] = '1'
79
+ os.environ['MKL_NUM_THREADS'] = '1'
80
+
81
+
82
+ def parallel_map(func, iterable, initializer=None, initargs=None, max_workers=None):
83
+ """Process-pool map as a lazy generator.
84
+
85
+ The BLAS thread limit is applied inside workers, and results are produced
86
+ in input order. ``max_workers=None`` uses ``DEFAULT_MAX_WORKERS``;
87
+ otherwise the value is validated with :func:`check_worker_count`.
88
+ """
89
+ set_blas_threads_one()
90
+ n = resolve_workers(max_workers)
91
+ with ProcessPoolExecutor(max_workers=n, initializer=initializer, initargs=initargs) as pool:
92
+ yield from pool.map(func, iterable)
@@ -0,0 +1,17 @@
1
+ """Estimate the number of field points needed for a spectrum."""
2
+
3
+
4
+ def get_points_spectrum(fieldRange, lw_lorentzian, lw_gaussian):
5
+ """Return a point count giving roughly five samples per linewidth."""
6
+ # Use the smaller nonzero linewidth as the resolution scale.
7
+ if lw_lorentzian != 0 and lw_gaussian != 0:
8
+ lw = min(lw_lorentzian, lw_gaussian)
9
+ elif lw_lorentzian != 0:
10
+ lw = lw_lorentzian
11
+ elif lw_gaussian != 0:
12
+ lw = lw_gaussian
13
+ else:
14
+ lw = 1.0
15
+
16
+ width = fieldRange[-1] - fieldRange[0]
17
+ return max(int(5 * width / lw), 100)
dimspin/Powder.py ADDED
@@ -0,0 +1,118 @@
1
+ """Powder spectra: average over crystallite orientations.
2
+
3
+ Orientations are sampled on a Fibonacci sphere. Each orientation is computed
4
+ without line broadening, and all transitions are broadened once at the end,
5
+ which is equivalent to broadening every orientation separately because the
6
+ convolution is linear.
7
+
8
+ For an electric-field modulated spectrum each sampled orientation is
9
+ evaluated together with its electric-field-reversed partner, obtained by a
10
+ half turn about an axis perpendicular to the electric field. When the
11
+ electric field is zero there is no partner and only the sampled orientations
12
+ are used.
13
+ """
14
+
15
+ import math
16
+
17
+ import numpy as np
18
+
19
+ from .Fibonacci_Orientation import fibonacci_orientation
20
+ from .Orientation_Switch import orientation_switch
21
+ from .Parallel import parallel_map
22
+ from .Rodrigues_Rotation import rotation_matrix
23
+ from .Spec_Oneside import broaden_transitions, spec_transitions
24
+
25
+ _worker_spins = None
26
+ _worker_spec = None
27
+ _worker_Rrot_average = None
28
+
29
+
30
+ def _init_worker(spins, spec, Rrot_average):
31
+ global _worker_spins, _worker_spec, _worker_Rrot_average
32
+ _worker_spins = spins
33
+ _worker_spec = spec
34
+ _worker_Rrot_average = Rrot_average
35
+
36
+
37
+ def _orientation_task(spin_Rrot):
38
+ spin_idx, Rrot = spin_Rrot
39
+ return _one_orientation(_worker_spins[spin_idx], _worker_spec, Rrot, _worker_Rrot_average)
40
+
41
+
42
+ def _one_orientation(spin, spec, Rrot, Rrot_average):
43
+ """
44
+ Inputs: Spin and Spec objects; orientation rotation; optional partner
45
+ rotation (None when the electric field is zero).
46
+
47
+ Returns: (positions, intensities) accumulated over the sampled orientation
48
+ and, when present, its partner.
49
+
50
+ Notes: spin is copied so that parallel workers never share mutable state.
51
+ """
52
+ spin = spin.clone()
53
+ spin.R_tf2lf_rotated = Rrot @ spin.R_tf2lf
54
+ spin.R_etf2lf_rotated = Rrot @ spin.R_etf2lf
55
+ pos1, int1 = spec_transitions(spin, spec)
56
+ if Rrot_average is None:
57
+ return pos1, int1
58
+
59
+ spin.R_tf2lf_rotated = Rrot_average @ (Rrot @ spin.R_tf2lf)
60
+ spin.R_etf2lf_rotated = Rrot_average @ (Rrot @ spin.R_etf2lf)
61
+ pos2, int2 = spec_transitions(spin, spec)
62
+
63
+ return np.concatenate([pos1, pos2]), np.concatenate([int1, int2])
64
+
65
+
66
+ def powder(spins, spec, parallel=True):
67
+ """
68
+ Inputs: list of Spin objects; Spec object; whether to use a process pool.
69
+
70
+ Returns: an array of shape (len(spins), specpoints).
71
+
72
+ Notes: tasks are (spin index, orientation) pairs. Each orientation only
73
+ produces transitions; the main process accumulates them per spin and
74
+ broadens once.
75
+ """
76
+ n_spins = len(spins)
77
+ oreientations = fibonacci_orientation(spec.npowder)
78
+
79
+ if np.all(spec.Edirection == 0):
80
+ Rrot_average = None
81
+ else:
82
+ averageaxis = np.array([-spec.Edirection[1], spec.Edirection[0], 0])
83
+ if averageaxis[0] == 0 and averageaxis[1] == 0:
84
+ averageaxis = np.array([0, -spec.Edirection[2], spec.Edirection[1]])
85
+ Rrot_average = rotation_matrix(averageaxis, math.pi)
86
+ for Ri in range(0, 3):
87
+ for Rj in range(0, 3):
88
+ if abs(Rrot_average[Ri][Rj]) < 1e-8:
89
+ Rrot_average[Ri][Rj] = 0
90
+
91
+ Rrot_list = []
92
+ for i in range(spec.npowder):
93
+ if i == 0:
94
+ Rrot = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
95
+ else:
96
+ Rrot = orientation_switch(np.array(oreientations[i]), np.array(oreientations[0]))
97
+ Rrot_list.append(Rrot)
98
+
99
+ tasks = [(si, Rrot) for si in range(n_spins) for Rrot in Rrot_list]
100
+ if parallel:
101
+ partials = parallel_map(_orientation_task, tasks, initializer=_init_worker,
102
+ initargs=(spins, spec, Rrot_average), max_workers=spec.max_workers)
103
+ else:
104
+ partials = (_one_orientation(spins[si], spec, Rrot, Rrot_average) for si, Rrot in tasks)
105
+
106
+ pos_buckets = [[] for _ in range(n_spins)]
107
+ int_buckets = [[] for _ in range(n_spins)]
108
+ for (si, _), (pos, inten) in zip(tasks, partials):
109
+ pos_buckets[si].append(pos)
110
+ int_buckets[si].append(inten)
111
+
112
+ spectra = np.zeros((n_spins, spec.specpoints))
113
+ for si in range(n_spins):
114
+ if pos_buckets[si]:
115
+ positions = np.concatenate(pos_buckets[si])
116
+ intensities = np.concatenate(int_buckets[si])
117
+ spectra[si] = broaden_transitions(spec, positions, intensities)
118
+ return spectra
@@ -0,0 +1,11 @@
1
+ """Rotation matrices built with the Rodrigues formula."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def rotation_matrix(axis, angle):
7
+ """Return the rotation matrix around ``axis`` by ``angle`` radians."""
8
+ u = np.asarray(axis, dtype=float)
9
+ u = u / np.linalg.norm(u)
10
+ K = np.array([[0, -u[2], u[1]], [u[2], 0, -u[0]], [-u[1], u[0], 0]])
11
+ return np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * (K @ K)
dimspin/Root_Finder.py ADDED
@@ -0,0 +1,220 @@
1
+ """Resonance-field root finding and transition intensities.
2
+
3
+ Public entry points: find_root_Bmod, find_root_Emod and find_root_param, plus
4
+ transition_probability and population_difference for line intensities. The
5
+ module is shared by the high-field, adaptive-grid and eigenfield methods.
6
+
7
+ Energies are in MHz and fields in G.
8
+ """
9
+
10
+ import numpy as np
11
+
12
+ from .Spin_Operators import Sx_get, Sy_get, Sz_get
13
+
14
+
15
+ def transition_probability(S, I, g, eigvecs, jj, kk):
16
+ """
17
+ Inputs: electron and nuclear spins; 3x3 g tensor; eigenvectors at the
18
+ resonance field; level indices jj and kk.
19
+
20
+ Returns: the squared matrix element ``|<kk|H1|jj>|^2``, with
21
+ H1 = g[0, :] . S the microwave coupling.
22
+
23
+ Notes: the first row of ``g`` is used because the microwave field is taken
24
+ along the laboratory x axis.
25
+ """
26
+ Sx = Sx_get(S, I)
27
+ Sy = Sy_get(S, I)
28
+ Sz = Sz_get(S, I)
29
+ H1 = g[0][0] * Sx + g[0][1] * Sy + g[0][2] * Sz
30
+ element = np.dot(np.dot(eigvecs[:, kk].T.conjugate(), H1), eigvecs[:, jj])
31
+ return np.absolute(element) ** 2
32
+
33
+
34
+ def population_difference(eigvals, jj, kk, Temperature):
35
+ """
36
+ Inputs: eigenvalues at the resonance field (MHz); level indices jj and kk;
37
+ temperature (K).
38
+
39
+ Returns: the normalized Boltzmann population difference between jj and kk.
40
+
41
+ Notes: ``h / k_B`` is applied per MHz.
42
+ """
43
+ k_B = 1.380649e-23
44
+ h_per_mhz = 6.626e-28
45
+ beta = h_per_mhz / (k_B * Temperature)
46
+ factors = np.exp(-(np.asarray(eigvals, dtype=float) - np.min(eigvals)) * beta)
47
+ return (factors[jj] - factors[kk]) / factors.sum()
48
+
49
+
50
+ def _brentq(f, a, b, xtol, rtol, maxiter=100):
51
+ """
52
+ Inputs: bracketing function f; endpoints a and b with residuals of opposite
53
+ sign; absolute and relative tolerances; iteration limit.
54
+
55
+ Returns: a root of f in [a, b].
56
+
57
+ Notes: self-contained Brent implementation; it avoids importing scipy.optimize
58
+ inside worker processes,thereby significantly improving computational efficiency.
59
+ """
60
+ xpre = a * 1.0
61
+ xcur = b * 1.0
62
+ fpre = f(xpre)
63
+ fcur = f(xcur)
64
+ if fpre * fcur > 0:
65
+ raise ValueError("f(a) and f(b) must have different signs")
66
+ if fpre == 0:
67
+ return xpre
68
+ if fcur == 0:
69
+ return xcur
70
+
71
+ xblk = 0.0
72
+ fblk = 0.0
73
+ spre = 0.0
74
+ scur = 0.0
75
+
76
+ for _ in range(maxiter):
77
+ if fpre * fcur < 0:
78
+ xblk = xpre
79
+ fblk = fpre
80
+ spre = scur = xcur - xpre
81
+ if abs(fblk) < abs(fcur):
82
+ xpre = xcur
83
+ xcur = xblk
84
+ xblk = xpre
85
+ fpre = fcur
86
+ fcur = fblk
87
+ fblk = fpre
88
+
89
+ delta = (xtol + rtol * abs(xcur)) / 2
90
+ sbis = (xblk - xcur) / 2
91
+ if fcur == 0 or abs(sbis) < delta:
92
+ return xcur
93
+
94
+ if abs(spre) > delta and abs(fcur) < abs(fpre):
95
+ if xpre == xblk:
96
+ stry = -fcur * (xcur - xpre) / (fcur - fpre)
97
+ else:
98
+ dpre = (fpre - fcur) / (xpre - xcur)
99
+ dblk = (fblk - fcur) / (xblk - xcur)
100
+ stry = -fcur * (fblk * dblk - fpre * dpre) / (dblk * dpre * (fblk - fpre))
101
+ if 2 * abs(stry) < min(abs(spre), 3 * abs(sbis) - delta):
102
+ spre = scur
103
+ scur = stry
104
+ else:
105
+ spre = sbis
106
+ scur = sbis
107
+ else:
108
+ spre = sbis
109
+ scur = sbis
110
+
111
+ xpre = xcur
112
+ fpre = fcur
113
+ if abs(scur) > delta:
114
+ xcur += scur
115
+ else:
116
+ xcur += (delta if sbis > 0 else -delta)
117
+ fcur = f(xcur)
118
+
119
+ return xcur
120
+
121
+
122
+ def _find_root(func, field_left, field_right, fa, fb, xtol, rtol):
123
+ """
124
+ Inputs: residual function; bracket endpoints; precomputed endpoint
125
+ residuals fa and fb, which may be None; tolerances.
126
+
127
+ Returns: the root found by :func:`_brentq`.
128
+
129
+ Notes: fa/fb are computed by the caller from the end eigenvalues,
130
+ so the bracket ends are not diagonalized again.
131
+ """
132
+ def f(x):
133
+ if fa is not None and x == field_left:
134
+ return fa
135
+ if fb is not None and x == field_right:
136
+ return fb
137
+ return func(x)
138
+ return _brentq(f, field_left, field_right, xtol, rtol)
139
+
140
+
141
+ def _root_record(spin, mwFreq, set_field, field_left, field_right, jj, kk,
142
+ Temperature, fa, fb, xtol):
143
+ """
144
+ Inputs: Spin object; microwave frequency (MHz); callable that sets the
145
+ field-dependent Hamiltonian; bracket endpoints; level indices jj and kk;
146
+ temperature (K); endpoint residuals; absolute tolerance.
147
+
148
+ Returns: (field, jj, kk, intensity), or None when the transition
149
+ probability is zero.
150
+ """
151
+ def residual(x):
152
+ set_field(x)
153
+ eigvals = np.linalg.eigvalsh(spin.H_total)
154
+ return np.abs(eigvals[kk] - eigvals[jj]) - mwFreq
155
+
156
+ field = _find_root(residual, field_left, field_right, fa, fb, xtol=xtol, rtol=1e-6)
157
+ set_field(field)
158
+ eigvals, eigvecs = np.linalg.eigh(spin.H_total)
159
+ probability = transition_probability(spin.S, spin.I, spin.g1, eigvecs, jj, kk)
160
+ if probability > 0.0:
161
+ difference = population_difference(eigvals, jj, kk, Temperature)
162
+ return (field, jj, kk, probability * difference)
163
+ return None
164
+
165
+
166
+ def find_root_Emod(spin, mwFreq, EF, field_left, field_right, jj, kk,
167
+ modulation_symbol, Temperature, fa=None, fb=None):
168
+ """
169
+ Inputs: Spin object; microwave frequency (MHz); electric-field vector EF;
170
+ bracket endpoints; level indices jj and kk; modulation_symbol ("positive"
171
+ or "negative"); temperature (K); optional endpoint residuals.
172
+
173
+ Returns: (field, jj, kk, intensity), or None when the transition
174
+ probability is zero.
175
+
176
+ Notes: the absolute tolerance is 0.01 G, well below the field resolution.
177
+ """
178
+ return _root_record(
179
+ spin, mwFreq,
180
+ lambda x: spin.modulate_E_T(x, EF, modulation_symbol),
181
+ field_left, field_right, jj, kk, Temperature, fa, fb, xtol=0.01,
182
+ )
183
+
184
+
185
+ def find_root_Bmod(spin, mwFreq, Bmod, field_left, field_right, jj, kk,
186
+ modulation_symbol, Temperature, fa=None, fb=None):
187
+ """
188
+ Inputs: Spin object; microwave frequency (MHz); modulated field Bmod (G);
189
+ bracket endpoints; level indices jj and kk; modulation_symbol ("positive"
190
+ or "negative"); temperature (K); optional endpoint residuals.
191
+
192
+ Returns: (field, jj, kk, intensity), or None when the transition
193
+ probability is zero.
194
+
195
+ Notes: the absolute tolerance is 0.05 G, about 0.14 MHz.
196
+ """
197
+ return _root_record(
198
+ spin, mwFreq,
199
+ lambda x: spin.modulate_B(x, Bmod, modulation_symbol),
200
+ field_left, field_right, jj, kk, Temperature, fa, fb, xtol=0.05,
201
+ )
202
+
203
+
204
+ def find_root_param(spin, mwFreq, field_left, field_right, jj, kk,
205
+ modulation_symbol, Temperature, fa=None, fb=None):
206
+ """
207
+ Inputs: Spin object; microwave frequency (MHz); bracket endpoints; level
208
+ indices jj and kk; modulation_symbol ("positive" or "negative");
209
+ temperature (K); optional endpoint residuals.
210
+
211
+ Returns: (field, jj, kk, intensity), or None when the transition
212
+ probability is zero.
213
+
214
+ Notes: the absolute tolerance is 0.01 G, well below the field resolution.
215
+ """
216
+ return _root_record(
217
+ spin, mwFreq,
218
+ lambda x: spin.modulate_param(x, modulation_symbol),
219
+ field_left, field_right, jj, kk, Temperature, fa, fb, xtol=0.01,
220
+ )
@@ -0,0 +1,48 @@
1
+ """Plotting helpers for simulated spectra.
2
+
3
+ Both functions draw on a matplotlib axes and call ``plt.show()``. The
4
+ AutoSim entry point uses them when ``show=True``; they can also be called
5
+ directly with an existing axes.
6
+ """
7
+
8
+ import numpy as np
9
+
10
+
11
+ def show_spectrum(spec, spectrum, ax=None):
12
+ """
13
+ Inputs: Spec object; one-dimensional spectrum; optional axes.
14
+
15
+ Returns: the axes used, after showing the figure.
16
+
17
+ Notes: matplotlib is imported only when this function is called.
18
+ """
19
+ import matplotlib.pyplot as plt
20
+ if ax is None:
21
+ _, ax = plt.subplots()
22
+ ax.plot(spec.fieldrange, spectrum, color=spec.linecolor, linewidth=0.5)
23
+ ax.set_xlabel('Magnetic field (G)')
24
+ ax.set_ylabel('Intensity (arb. units)')
25
+ plt.show()
26
+ return ax
27
+
28
+
29
+ def show_rotation(spec, spectra, ax=None):
30
+ """
31
+ Inputs: Spec object; (angle, field) spectrum array; optional axes.
32
+
33
+ Returns: the axes used, after showing the figure.
34
+
35
+ Notes: the map is drawn with the field on the horizontal axis and the
36
+ rotation angle on the vertical axis; matplotlib is imported only when this
37
+ function is called.
38
+ """
39
+ import matplotlib.pyplot as plt
40
+ if ax is None:
41
+ _, ax = plt.subplots()
42
+ angles = np.linspace(spec.anglerange[0], spec.anglerange[1], spectra.shape[0])
43
+ mesh = ax.pcolormesh(spec.fieldrange, angles, spectra, shading='auto', cmap='viridis')
44
+ ax.set_xlabel('Magnetic field (G)')
45
+ ax.set_ylabel('Angle (deg)')
46
+ ax.figure.colorbar(mesh, ax=ax)
47
+ plt.show()
48
+ return ax