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.
@@ -0,0 +1,212 @@
1
+ """Adaptive-grid resonance search with Hermite cubic spline roots.
2
+
3
+ Public entry point: :func:`adaptive_grid_method`. The energy-level diagram is
4
+ refined adaptively until a cubic Hermite spline reproduces the levels to a
5
+ given tolerance; the roots of each level-gap spline are then solved
6
+ analytically and backfilled with transition intensities. This follows the
7
+ same approach as EasySpin: the spline roots are trusted as returned,
8
+ without an iterative refinement step.
9
+
10
+ The method makes no high-field assumption: it evaluates all level pairs that
11
+ can cross the microwave frequency and therefore keeps forbidden and
12
+ level-crossing transitions.
13
+
14
+ Reference: S. Stoll and A. Schweiger, EasySpin, a comprehensive software
15
+ package for spectral simulation and analysis in EPR, J. Magn. Reson. 178
16
+ (2006) 42-55, doi:10.1016/j.jmr.2005.08.013.
17
+ """
18
+
19
+ import numpy as np
20
+
21
+
22
+ def _feynman_derivatives(eigvecs, H1):
23
+ """
24
+ Inputs: eigenvectors at one field; field-gradient matrix H1 = dH/dB.
25
+
26
+ Returns: the level derivatives dE_u/dB = <u|H1|u>, one per level.
27
+
28
+ """
29
+ return np.sum(eigvecs.conj() * (H1 @ eigvecs), axis=0).real
30
+
31
+
32
+ def _cubic_roots_t(dL, dR, dLp, dRp):
33
+ """
34
+ Inputs: Hermite endpoint values dL and dR of the level gap minus the
35
+ microwave frequency, and endpoint derivatives dLp and dRp with respect to
36
+ the normalized parameter t.
37
+
38
+ Returns: the real roots in [0, 1] of the cubic Hermite polynomial.
39
+
40
+ Notes: the roots inherit the cubic interpolation error; the caller uses
41
+ them directly.
42
+ """
43
+ a3 = 2.0 * (dL - dR) + dLp + dRp
44
+ a2 = 3.0 * (dR - dL) - 2.0 * dLp - dRp
45
+ a1 = dLp
46
+ a0 = dL
47
+ roots = np.roots([a3, a2, a1, a0])
48
+ ts = []
49
+ for r in roots:
50
+ if abs(r.imag) < 1e-8 and -1e-9 <= r.real <= 1.0 + 1e-9:
51
+ ts.append(float(r.real))
52
+ return ts
53
+
54
+
55
+ def _adaptive_level_diagram(H0, H1, field_lo, field_hi, tol=0.5, max_depth=20,
56
+ min_width=1.0):
57
+ """
58
+ Inputs: field-independent Hamiltonian H0 and gradient H1, so that
59
+ H(B) = H0 + B * H1; field range; spline tolerance (MHz); maximum
60
+ subdivision depth; minimum segment width (G).
61
+
62
+ Returns: a list of segments (B_L, B_R, E_L, E_R, Ep_L, Ep_R), each holding
63
+ the endpoint fields, sorted eigenvalues and level derivatives.
64
+
65
+ Notes: a segment splits while the Hermite midpoint prediction differs from
66
+ the exact eigenvalues by more than ``tol``. Near level crossings the
67
+ sorted eigenvalues have a discontinuous derivative, so subdivision stops
68
+ at ``max_depth`` or at ``min_width``; the endpoint eigenvalues are always
69
+ exact, so the spline accuracy is not needed by the final roots.
70
+ """
71
+ segments = []
72
+
73
+ def eig_at(B):
74
+ vals, vecs = np.linalg.eigh(H0 + B * H1)
75
+ return vals, _feynman_derivatives(vecs, H1)
76
+
77
+ E_lo, Ep_lo = eig_at(field_lo)
78
+ E_hi, Ep_hi = eig_at(field_hi)
79
+
80
+ def subdivide(B_L, B_R, E_L, E_R, Ep_L, Ep_R, depth):
81
+ if depth >= max_depth or (B_R - B_L) <= min_width:
82
+ segments.append((B_L, B_R, E_L, E_R, Ep_L, Ep_R))
83
+ return
84
+ B_M = 0.5 * (B_L + B_R)
85
+ E_pred = 0.5 * (E_L + E_R) + 0.125 * (B_R - B_L) * (Ep_L - Ep_R)
86
+ E_M, vecs_M = np.linalg.eigh(H0 + B_M * H1)
87
+ if float(np.max(np.abs(E_M - E_pred))) <= tol:
88
+ segments.append((B_L, B_R, E_L, E_R, Ep_L, Ep_R))
89
+ return
90
+ Ep_M = _feynman_derivatives(vecs_M, H1)
91
+ subdivide(B_L, B_M, E_L, E_M, Ep_L, Ep_M, depth + 1)
92
+ subdivide(B_M, B_R, E_M, E_R, Ep_M, Ep_R, depth + 1)
93
+
94
+ subdivide(field_lo, field_hi, E_lo, E_hi, Ep_lo, Ep_hi, 0)
95
+ return segments
96
+
97
+
98
+ def _resonating_pairs(segments, mwfreq, N):
99
+ """
100
+ Inputs: spline segments; microwave frequency (MHz); number of levels.
101
+
102
+ Returns: the (u, v) pairs whose gap lies between the global minimum and
103
+ maximum of E_v - E_u over all segment endpoints.
104
+
105
+ Notes: the gap is continuous in the field, so a resonance is accompanied
106
+ by a segment endpoint whose gap crosses ``mwfreq``; only a gap that
107
+ crosses the frequency twice inside one segment can be missed, which the
108
+ adaptive subdivision avoids in practice.
109
+ """
110
+ gap_min = np.full((N, N), np.inf)
111
+ gap_max = np.full((N, N), -np.inf)
112
+ for _, _, E_L, E_R, _, _ in segments:
113
+ for E in (E_L, E_R):
114
+ G = E[:, None] - E[None, :]
115
+ np.minimum(gap_min, G, out=gap_min)
116
+ np.maximum(gap_max, G, out=gap_max)
117
+ return [(u, v) for u in range(N - 1) for v in range(u + 1, N)
118
+ if gap_min[v, u] <= mwfreq <= gap_max[v, u]]
119
+
120
+
121
+ def _dedup_roots(roots, tol=0.05):
122
+ """
123
+ Inputs: roots as (field, u, v); merge tolerance in G.
124
+
125
+ Returns: the roots with repeats of the same (u, v) closer than ``tol``
126
+ merged, keeping one.
127
+
128
+ Notes: only repeats of the same pair are merged; degenerate resonances of
129
+ different pairs at the same field are distinct transitions and are kept.
130
+ """
131
+ if not roots:
132
+ return []
133
+ roots.sort(key=lambda r: (r[1], r[2], r[0]))
134
+ out = []
135
+ for B, u, v in roots:
136
+ if out and out[-1][1] == u and out[-1][2] == v and (B - out[-1][0]) <= tol:
137
+ continue
138
+ out.append((B, u, v))
139
+ return out
140
+
141
+
142
+ def _backfill(H0, H1, mwfreq, spin, spec, roots, tol_freq=0.5):
143
+ """
144
+ Inputs: Hamiltonian constants; microwave frequency (MHz); Spin and Spec
145
+ objects; roots as (field, u, v); gap tolerance (MHz).
146
+
147
+ Returns: transitions (field, u, v, intensity) with intensity equal to the
148
+ transition probability times the population difference.
149
+
150
+ Notes: each root field is diagonalized once. A root whose actual gap
151
+ differs from ``mwfreq`` by more than ``tol_freq`` is discarded; this only
152
+ happens when the pair indices are misassigned at a level crossing.
153
+ """
154
+ from .Root_Finder import population_difference, transition_probability
155
+ transitions = []
156
+ for B, u, v in roots:
157
+ eigvals, eigvecs = np.linalg.eigh(H0 + B * H1)
158
+ if abs(abs(eigvals[v] - eigvals[u]) - mwfreq) > tol_freq:
159
+ continue
160
+ p = transition_probability(spin.S, spin.I, spin.g1, eigvecs, u, v)
161
+ if p > 0.0:
162
+ pd = population_difference(eigvals, u, v, spec.Temperature)
163
+ transitions.append((B, u, v, p * pd))
164
+ return transitions
165
+
166
+
167
+ def _spline_roots(segments, mwfreq, pairs):
168
+ """
169
+ Inputs: spline segments; microwave frequency (MHz); level pairs.
170
+
171
+ Returns: roots (field, u, v) from the analytic cubic roots on each segment.
172
+
173
+ Notes: no refinement is applied to the analytic roots.
174
+ """
175
+ roots = []
176
+ for B_L, B_R, E_L, E_R, Ep_L, Ep_R in segments:
177
+ delta = B_R - B_L
178
+ if delta == 0:
179
+ continue
180
+ for u, v in pairs:
181
+ dL = (E_L[v] - E_L[u]) - mwfreq
182
+ dR = (E_R[v] - E_R[u]) - mwfreq
183
+ if dL * dR > 0.0:
184
+ continue
185
+ dLp = (Ep_L[v] - Ep_L[u]) * delta
186
+ dRp = (Ep_R[v] - Ep_R[u]) * delta
187
+ for t in _cubic_roots_t(dL, dR, dLp, dRp):
188
+ roots.append((B_L + t * delta, u, v))
189
+ return roots
190
+
191
+
192
+ def adaptive_grid_method(spin, spec, modulation_symbol, tol=0.1, max_depth=20,
193
+ tol_freq=0.5):
194
+ """
195
+ Inputs: Spin and Spec objects; modulation_symbol ("positive" or
196
+ "negative"); spline tolerance (MHz); maximum subdivision depth; gap
197
+ tolerance for the intensity backfill (MHz).
198
+
199
+ Returns: transitions (field, u, v, intensity), with intensity equal to the
200
+ transition probability times the population difference.
201
+
202
+ Notes: all resonating level pairs are used, without a high-field label
203
+ selection, so forbidden and level-crossing transitions are included.
204
+ """
205
+ from .Eigenfield_Method import _build_H0_H1
206
+ H0, H1 = _build_H0_H1(spin, spec, modulation_symbol)
207
+
208
+ segments = _adaptive_level_diagram(H0, H1, spec.fieldrange[0], spec.fieldrange[-1],
209
+ tol=tol, max_depth=max_depth)
210
+ pairs = _resonating_pairs(segments, spec.mwfreq, H0.shape[0])
211
+ roots = _dedup_roots(_spline_roots(segments, spec.mwfreq, pairs))
212
+ return _backfill(H0, H1, spec.mwfreq, spin, spec, roots, tol_freq=tol_freq)
dimspin/AutoSim.py ADDED
@@ -0,0 +1,113 @@
1
+ """Single entry point for spectrum simulations.
2
+
3
+ ``autosim`` takes one or more Spin objects and one Spec object and returns
4
+ the spectrum: a one-dimensional array for the ``Crystal_Oneside`` and
5
+ ``Powder`` samples, and a two-dimensional (angle, field) array for
6
+ ``Crystal_Rotation``. Plotting is opt-in through ``show=True`` and is done by
7
+ the helpers in Show_Spectra.
8
+ """
9
+
10
+ import numpy as np
11
+
12
+ from .Class_Spec import Spec
13
+ from .Class_Spin import Spin
14
+
15
+
16
+ def autosim(*class_name, show=True, parallel=True):
17
+ """
18
+ Inputs: one or more Spin objects followed by one Spec object; whether to
19
+ plot the result; whether to use a process pool.
20
+
21
+ Returns: the spectrum array (see the module docstring for its shape).
22
+
23
+ Notes: when ``Spec.group_number`` is set, each Spin is expanded into the
24
+ magnetically inequivalent orientations of the space group and the spectra
25
+ are summed with their multiplicities. Parameter checks and the field grid
26
+ expansion are done by ``Spec.check_simpara``. With ``show=True`` all three
27
+ sample types are drawn: a line for one-side and powder, an angle-field map
28
+ for rotation.
29
+ """
30
+ if len(class_name) < 2:
31
+ raise ValueError("Autosim requires at least one Spin and one Spec to be entered as parameters")
32
+ spec = class_name[-1]
33
+ if not isinstance(spec, Spec):
34
+ raise ValueError("The last parameter must be a Spec class!")
35
+ spec.check_simpara()
36
+
37
+ spins = []
38
+ multiplicity = []
39
+ for item in class_name[:-1]:
40
+ if isinstance(item, Spec):
41
+ raise ValueError("Cannot accept two independent experimental conditions! "
42
+ "You can only transfer one 'Spec' class to autosim!")
43
+ if not isinstance(item, Spin):
44
+ raise ValueError("Cannot accept other classes! You can only transfer "
45
+ "'Spin' and 'Spec' classes to autosim!")
46
+ if spec.group_number is not None:
47
+ from .Space_Group_Expand import build_space_group_orientations
48
+ orientations, multiplicities = build_space_group_orientations(
49
+ item, spec.group_number, spec.frac_pos)
50
+ for R_cart, m in zip(orientations, multiplicities):
51
+ sj = item.clone()
52
+ sj.identity_tensor(spec.crystal_orientation, R_cart)
53
+ spins.append(sj)
54
+ multiplicity.append(m)
55
+ else:
56
+ sj = item.clone()
57
+ sj.identity_tensor(spec.crystal_orientation, np.eye(3))
58
+ spins.append(sj)
59
+ multiplicity.append(1)
60
+
61
+ if spec.sample == 'Crystal_Oneside':
62
+ spectrum = _oneside(spins, multiplicity, spec, parallel)
63
+ if show:
64
+ from .Show_Spectra import show_spectrum
65
+ show_spectrum(spec, spectrum)
66
+ return spectrum
67
+
68
+ if spec.sample == 'Crystal_Rotation':
69
+ from .Crystal_Rotation import crystal_rotation
70
+ angnum = int((spec.anglerange[1] - spec.anglerange[0]) / spec.anglerange[2]) + 1
71
+ spectra = crystal_rotation(spins, spec, angnum, parallel=parallel)
72
+ result = np.zeros((angnum, spec.specpoints))
73
+ for i in range(len(spins)):
74
+ result = result + multiplicity[i] * spectra[i]
75
+ if show:
76
+ from .Show_Spectra import show_rotation
77
+ show_rotation(spec, result)
78
+ return result
79
+
80
+ if spec.sample == 'Powder':
81
+ from .Powder import powder
82
+ spectra = powder(spins, spec, parallel=parallel)
83
+ result = np.zeros(spec.specpoints)
84
+ for i in range(len(spins)):
85
+ result = result + multiplicity[i] * spectra[i]
86
+ if show:
87
+ from .Show_Spectra import show_spectrum
88
+ show_spectrum(spec, result)
89
+ return result
90
+
91
+
92
+ def _oneside(spins, multiplicity, spec, parallel):
93
+ """
94
+ Inputs: expanded Spin list; multiplicities; Spec object; parallel flag.
95
+
96
+ Returns: the multiplicity-weighted sum of the one-side spectra.
97
+ """
98
+ from .Spec_Oneside import spec_oneside
99
+ if len(spins) == 1:
100
+ return multiplicity[0] * spec_oneside(spins[0], spec)
101
+
102
+ from functools import partial
103
+
104
+ from .Parallel import parallel_map
105
+ if parallel:
106
+ results = parallel_map(partial(spec_oneside, spec=spec), spins, max_workers=spec.max_workers)
107
+ else:
108
+ results = (spec_oneside(spin, spec) for spin in spins)
109
+ spectrum = np.zeros(spec.specpoints)
110
+ for i, res in enumerate(results):
111
+ spectrum = spectrum + multiplicity[i] * res
112
+ return spectrum
113
+
dimspin/Class_Spec.py ADDED
@@ -0,0 +1,270 @@
1
+ """Experimental parameters for a spectrum simulation.
2
+
3
+ Spec stores the method, modulation type, sample mode, field grid, linewidths
4
+ and the settings for the crystal-rotation and powder modes.
5
+ :meth:`Spec.check_simpara` validates the settings and expands the field range
6
+ and the electric-field vector into their usable forms.
7
+ """
8
+
9
+ import logging
10
+
11
+ import numpy as np
12
+
13
+
14
+ class Spec:
15
+ """Experimental parameters for one simulation."""
16
+
17
+ def __init__(self):
18
+ self.name = 'Spec'
19
+ self.method = 'High_Field_Method'
20
+ self.modtype = 'Bmod'
21
+ self.sample = 'Crystal_Oneside'
22
+
23
+ self.mwfreq = 9560.000
24
+
25
+ self.lw = np.zeros(2)
26
+ self.lw_lorentzian = 1
27
+ self.lw_gaussian = 0
28
+ self.lw_type = ''
29
+
30
+ self.fieldrange = np.zeros(2)
31
+ self.Bmod = 0
32
+ self.Emod = 0
33
+ self.Edirection = np.zeros(3)
34
+ self.E1 = np.zeros(3)
35
+ self.Temperature = 298
36
+ self.specpoints = 0
37
+
38
+ self.anglerange = [0, 180, 1]
39
+ self.rotaxis = np.array([0, 0, 0])
40
+ self.crystal_orientation = None
41
+ self.group_number = None
42
+ self.frac_pos = None
43
+
44
+ self.npowder = 2000
45
+ self.max_workers = None
46
+ self.linecolor = 'red'
47
+
48
+ def clone(self):
49
+ """
50
+ Inputs: none.
51
+
52
+ Returns: a deep copy, used by parallel tasks to isolate mutable state.
53
+ """
54
+ from copy import deepcopy
55
+ return deepcopy(self)
56
+
57
+ def check_simpara(self):
58
+ """
59
+ Inputs: none; the parameters are read from the instance.
60
+
61
+ Returns: nothing; ``modtype``, ``E1``, ``lw_type``, ``specpoints`` and
62
+ the expanded ``fieldrange`` are set in place.
63
+
64
+ Notes: the modulation type is detected from Bmod/Emod unless
65
+ ``modtype`` is explicitly 'param'; giving both fields at once is
66
+ rejected. The method must be 'High_Field_Method' or
67
+ 'Adaptive_Grid_Method'. A field range given as two values is expanded
68
+ to ``specpoints`` points; an already expanded axis must be uniformly
69
+ spaced, and it sets ``specpoints`` when that is zero. The method is
70
+ idempotent. ``rotaxis`` is deprecated and unused: the rotation mode
71
+ turns the crystal about the laboratory x axis, and the initial
72
+ orientation comes from ``crystal_orientation``.
73
+ """
74
+ self.mwfreq = _positive_number(self.mwfreq, 'mwfreq')
75
+ self.Temperature = _positive_number(self.Temperature, 'Temperature')
76
+
77
+ if self.group_number is not None:
78
+ try:
79
+ number = int(self.group_number)
80
+ except (TypeError, ValueError):
81
+ raise ValueError("'group_number' must be an integer between 1 and 230.")
82
+ if number != self.group_number or not 1 <= number <= 230:
83
+ raise ValueError("'group_number' must be an integer between 1 and 230.")
84
+ self.group_number = number
85
+ if self.frac_pos is not None:
86
+ self.frac_pos = np.asarray(self.frac_pos, dtype=float)
87
+ if self.frac_pos.shape != (3,):
88
+ raise ValueError("'frac_pos' must be a three-dimensional fractional coordinate.")
89
+ if not np.all(np.isfinite(self.frac_pos)):
90
+ raise ValueError("'frac_pos' must contain finite values.")
91
+
92
+ self.Bmod = _number(self.Bmod, 'Bmod')
93
+ self.Emod = _number(self.Emod, 'Emod')
94
+ self.Edirection = np.asarray(self.Edirection, dtype=float)
95
+ if self.Edirection.shape != (3,):
96
+ raise ValueError("'Edirection' must be a three-dimensional vector.")
97
+ if not np.all(np.isfinite(self.Edirection)):
98
+ raise ValueError("'Edirection' must contain finite values.")
99
+
100
+ if self.modtype != 'param':
101
+ if self.Bmod != 0 and self.Emod != 0:
102
+ raise ValueError('Both Bmod and Emod are nonzero; please give only one modulation field.')
103
+ if self.Bmod != 0:
104
+ self.modtype = 'Bmod'
105
+ logging.warning('Magnetic field modulation is recognized.')
106
+ if self.Emod != 0:
107
+ self.modtype = 'Emod'
108
+ logging.warning('Electric field modulation is recognized.')
109
+
110
+ if self.modtype == 'Bmod' and self.Bmod == 0:
111
+ raise ValueError('Magnetic field modulation is selected, but modulating magnetic field is not given')
112
+ elif self.modtype == 'Emod' and (self.Emod == 0 or np.all(self.Edirection == 0)):
113
+ raise ValueError('Electric field modulation is selected, but modulating electric field is not given')
114
+ elif self.modtype == 'param':
115
+ logging.warning('Parameter modulation (Delta g/Delta D/Delta A) is recognized.')
116
+ if self.modtype not in ('Bmod', 'Emod', 'param'):
117
+ raise ValueError("Can't recognize modtype, please check it again."
118
+ "(Only 'Bmod', 'Emod' or 'param' is allowed)")
119
+ self.E1 = self.Emod * self.Edirection
120
+
121
+ self.lw_lorentzian = _number(self.lw_lorentzian, 'lw_lorentzian')
122
+ self.lw_gaussian = _number(self.lw_gaussian, 'lw_gaussian')
123
+ self.lw = np.asarray(self.lw, dtype=float)
124
+ if self.lw.size not in (0, 2):
125
+ raise ValueError("'lw' must contain two elements (Lorentzian, Gaussian).")
126
+ if self.lw.any():
127
+ if self.lw_lorentzian == 0 and self.lw_gaussian == 0:
128
+ self.lw_lorentzian = float(self.lw[0])
129
+ self.lw_gaussian = float(self.lw[1])
130
+ self.lw = np.zeros(2)
131
+ else:
132
+ raise ValueError('The linewidth has been entered twice, please double check and delete one of them.')
133
+ elif self.lw_lorentzian == 0 and self.lw_gaussian == 0:
134
+ raise ValueError('Lorentzian and Gaussian linewidths cannot be zero at the same time.')
135
+ self.lw_lorentzian = _nonnegative_number(self.lw_lorentzian, 'lw_lorentzian')
136
+ self.lw_gaussian = _nonnegative_number(self.lw_gaussian, 'lw_gaussian')
137
+ if self.lw_lorentzian == 0 and self.lw_gaussian != 0:
138
+ logging.warning('The spectrogram will be broadened using Gaussian linewidth.')
139
+ self.lw_type = 'Gaussian'
140
+ if self.lw_lorentzian != 0 and self.lw_gaussian == 0:
141
+ logging.warning('The spectrogram will be broadened using lorentzian linewidth.')
142
+ self.lw_type = 'Lorentzian'
143
+ if self.lw_lorentzian != 0 and self.lw_gaussian != 0:
144
+ logging.warning('The spectrogram will be broadened using both Lorentzian and Gaussian linewidths.')
145
+ self.lw_type = 'Voigt'
146
+
147
+ if self.sample not in ('Crystal_Oneside', 'Crystal_Rotation', 'Powder'):
148
+ raise ValueError("Only 'Crystal_Oneside', 'Crystal_Rotation' or 'Powder' is allowed for 'sample'.")
149
+
150
+ if self.sample == 'Crystal_Rotation':
151
+ self.rotaxis = np.asarray(self.rotaxis, dtype=float)
152
+ if self.rotaxis.shape != (3,):
153
+ raise ValueError("'rotaxis' must be a three-dimensional vector")
154
+ if not np.all(np.isfinite(self.rotaxis)):
155
+ raise ValueError("'rotaxis' must contain finite values")
156
+ if self.rotaxis.any():
157
+ from .Vec_normalize import vec_normalize
158
+ self.rotaxis = vec_normalize(self.rotaxis)
159
+ self.anglerange = np.asarray(self.anglerange, dtype=float)
160
+ if self.anglerange.shape == (2,):
161
+ self.anglerange = np.array([self.anglerange[0], self.anglerange[1], 1.0])
162
+ elif self.anglerange.shape != (3,):
163
+ raise ValueError("Incorrect initial and ending angles for the given rotation!")
164
+ if not np.all(np.isfinite(self.anglerange)):
165
+ raise ValueError("'anglerange' must contain finite values")
166
+ if self.anglerange[2] <= 0:
167
+ raise ValueError("The angle step must be positive.")
168
+ if self.anglerange[1] < self.anglerange[0]:
169
+ raise ValueError("The ending angle must not be smaller than the initial angle.")
170
+
171
+ if self.sample == 'Powder':
172
+ try:
173
+ count = int(self.npowder)
174
+ except (TypeError, ValueError):
175
+ raise ValueError("'npowder' must be a positive integer.")
176
+ if count != self.npowder or count <= 0:
177
+ raise ValueError("'npowder' must be a positive integer.")
178
+ self.npowder = count
179
+
180
+ if self.method not in ('High_Field_Method', 'Adaptive_Grid_Method'):
181
+ raise ValueError("Only 'High_Field_Method' or 'Adaptive_Grid_Method' is allowed.")
182
+
183
+ self.fieldrange = np.asarray(self.fieldrange, dtype=float)
184
+ if self.fieldrange.ndim != 1 or self.fieldrange.size < 2:
185
+ raise ValueError("Please enter an interval for legal magnetic field range in 'fieldrange'")
186
+ if not np.all(np.isfinite(self.fieldrange)):
187
+ raise ValueError("'fieldrange' must contain finite values")
188
+ if self.fieldrange.size == 2:
189
+ if self.fieldrange[0] >= self.fieldrange[1]:
190
+ raise ValueError("Please enter an interval for legal magnetic field range in 'fieldrange'")
191
+ else:
192
+ steps = np.diff(self.fieldrange)
193
+ if not np.all(steps > 0):
194
+ raise ValueError("Please enter an interval for legal magnetic field range in 'fieldrange'")
195
+ if not np.allclose(steps, steps[0], rtol=1e-6, atol=1e-12):
196
+ raise ValueError("An expanded 'fieldrange' must be uniformly spaced.")
197
+
198
+ if self.fieldrange.size > 2:
199
+ if self.specpoints == 0:
200
+ self.specpoints = int(self.fieldrange.size)
201
+ else:
202
+ self.specpoints = _positive_int(self.specpoints, 'specpoints')
203
+ if self.specpoints != self.fieldrange.size:
204
+ raise ValueError("The length of 'fieldrange' does not match 'specpoints'")
205
+ elif self.specpoints == 0:
206
+ from .Pointsnum_Optimise import get_points_spectrum
207
+ self.specpoints = get_points_spectrum(self.fieldrange, self.lw_lorentzian, self.lw_gaussian)
208
+ else:
209
+ self.specpoints = _positive_int(self.specpoints, 'specpoints')
210
+
211
+ if self.fieldrange.size == 2:
212
+ self.fieldrange = np.linspace(self.fieldrange[0], self.fieldrange[1], self.specpoints)
213
+
214
+
215
+ def _number(value, name):
216
+ """
217
+ Inputs: value; parameter name.
218
+
219
+ Returns: the value as a finite float.
220
+
221
+ Notes: a non-numeric or non-finite value raises ValueError.
222
+ """
223
+ try:
224
+ result = float(value)
225
+ except (TypeError, ValueError):
226
+ raise ValueError(f"'{name}' must be a number.")
227
+ if not np.isfinite(result):
228
+ raise ValueError(f"'{name}' must be finite.")
229
+ return result
230
+
231
+
232
+ def _positive_number(value, name):
233
+ """
234
+ Inputs: value; parameter name.
235
+
236
+ Returns: the value as a positive finite float.
237
+ """
238
+ result = _number(value, name)
239
+ if result <= 0:
240
+ raise ValueError(f"'{name}' must be positive.")
241
+ return result
242
+
243
+
244
+ def _nonnegative_number(value, name):
245
+ """
246
+ Inputs: value; parameter name.
247
+
248
+ Returns: the value as a non-negative finite float.
249
+ """
250
+ result = _number(value, name)
251
+ if result < 0:
252
+ raise ValueError(f"'{name}' cannot be negative.")
253
+ return result
254
+
255
+
256
+ def _positive_int(value, name):
257
+ """
258
+ Inputs: value; parameter name.
259
+
260
+ Returns: the value as a positive int.
261
+
262
+ Notes: a non-integer or non-positive value raises ValueError.
263
+ """
264
+ try:
265
+ result = int(value)
266
+ except (TypeError, ValueError):
267
+ raise ValueError(f"'{name}' must be a positive integer.")
268
+ if float(value) != result or result <= 0:
269
+ raise ValueError(f"'{name}' must be a positive integer.")
270
+ return result