DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Hysteresis.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
56#include "DspMath.h"
57
58#include <algorithm>
59#include <array>
60#include <cmath>
61#include <cstddef>
62
63namespace dspark {
64
71template <FloatType T>
73{
74public:
78 void prepare(double sampleRate)
79 {
80 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return;
81 invFs2_ = 0.5 / sampleRate;
82 fs2_ = 2.0 * sampleRate;
83 reset();
84 }
85
87 void reset() noexcept
88 {
89 m_ = 0.0;
90 hPrev_ = 0.0;
91 hDotPrev_ = 0.0;
92 wPrev_ = 0.0;
93 past_.fill(0.0);
94 pastAt_ = 0;
95 pastCount_ = 0;
96 }
97
112 void setParameters(double ms, double a, double alpha, double k, double c) noexcept
113 {
114 if (!std::isfinite(ms) || !std::isfinite(a) || !std::isfinite(alpha)
115 || !std::isfinite(k) || !std::isfinite(c))
116 return;
117 ms_ = std::max(ms, 1.0);
118 a_ = std::max(a, 1.0);
119 alpha_ = std::max(alpha, 0.0);
120 k_ = std::max(k, 1.0);
121 c_ = std::clamp(c, 0.0, 0.999);
122 chi_ = ms_ / a_;
123 }
124
136 void setTolerance(double relative) noexcept
137 {
138 if (!(relative > 0.0) || !std::isfinite(relative)) return;
139 tolerance_ = std::clamp(relative, 1e-12, 1e-3);
140 bySlope_ = tolerance_ > 1e-9;
141 }
142
152 void setPredictorPeriod(int period) noexcept
153 {
154 if (period < 0 || period > kMaxPeriod || period == period_) return;
155 period_ = period;
156 pastCount_ = 0;
157 }
159 [[nodiscard]] int getPredictorPeriod() const noexcept { return period_; }
160
162 [[nodiscard]] double getSaturation() const noexcept { return ms_; }
163
170 [[nodiscard]] double getSmallSignalSusceptibility() const noexcept
171 {
172 const double chiAn = ms_ / (3.0 * a_);
173 return c_ * chiAn / (1.0 - c_ * alpha_ * chiAn);
174 }
175
180 [[nodiscard]] T processSample(T fieldH) noexcept
181 {
182 // Non-finite guard: a single NaN/Inf field would poison m_/hPrev_/
183 // hDotPrev_/wPrev_ permanently (the recursive JA state never clears it,
184 // and inf-inf on the next sample becomes a sticky NaN). Ignore the bad
185 // sample and hold the last magnetization, so a transient upstream
186 // glitch cannot kill the core for the rest of the stream.
187 if (!std::isfinite(fieldH)) return static_cast<T>(m_);
188
189 const double h = static_cast<double>(fieldH);
190 const double hDot = (1.0 + kAlpha) * 0.5 * fs2_ * (h - hPrev_) - kAlpha * hDotPrev_;
191
192 // Explicit predictor, then the matching alpha-transform corrector
193 // with Newton steps.
194 constexpr double kGain = 1.0 / (1.0 + kAlpha);
195 const double step = 2.0 * invFs2_ * kGain; // T / (1 + a)
196 const double rhs = m_ + step * kAlpha * wPrev_;
197 double m = m_ + 2.0 * invFs2_ * wPrev_;
198 if (period_ > 0 && pastCount_ >= 2 * period_)
199 {
200 // W at this phase a period and two periods ago, carried on: the
201 // corrector's own equation then gives the M it implies.
202 const double one = past_[static_cast<std::size_t>((pastAt_ + kRing - period_) & (kRing - 1))];
203 const double two = past_[static_cast<std::size_t>((pastAt_ + kRing - 2 * period_) & (kRing - 1))];
204 m = rhs + step * (2.0 * one - two);
205 }
206
207 double w = 0.0, dwdm = 0.0;
208 bool settled = false;
209 const double stop = tolerance_ * ms_;
210 double before = 0.0;
211 for (int it = 0; it < 4; ++it)
212 {
213 evaluate(m, h, hDot, w, dwdm);
214 const double g = m - rhs - step * w;
215 const double gp = 1.0 - step * dwdm;
216 const double dm = g / gp;
217 m -= dm;
218 const double size = std::abs(dm);
219 // Loose: the steps shrinking as Newton's do (each under half the
220 // last), what is left is about step^3 / last^2.
221 const bool shrunk = bySlope_ && it > 0 && size < 0.5 * before && size * size * size < stop * before * before;
222 before = size;
223 if (size < stop || shrunk)
224 {
225 if (bySlope_)
226 {
227 w -= dwdm * dm;
228 settled = true;
229 }
230 break;
231 }
232 }
233 if (!settled || std::abs(m) > ms_)
234 {
235 // Physical clamp: |M| cannot exceed the saturation magnetization.
236 m = std::clamp(m, -ms_, ms_);
237 evaluate(m, h, hDot, w, dwdm);
238 }
239 wPrev_ = w;
240 if (period_ > 0)
241 {
242 past_[static_cast<std::size_t>(pastAt_)] = w;
243 pastAt_ = (pastAt_ + 1) & (kRing - 1);
244 if (pastCount_ < 2 * period_) ++pastCount_;
245 }
246 hPrev_ = h;
247 hDotPrev_ = hDot;
248 m_ = m;
249 return static_cast<T>(m);
250 }
251
252private:
254 static void langevin(double x, double& l, double& lp, double& lpp) noexcept
255 {
256 const double ax = std::abs(x);
257 if (ax < 1e-3)
258 {
259 // Taylor: L = x/3 - x^3/45, L' = 1/3 - x^2/15, L'' = -2x/15
260 const double x2 = x * x;
261 l = x * (1.0 / 3.0 - x2 / 45.0);
262 lp = 1.0 / 3.0 - x2 / 15.0;
263 lpp = -2.0 * x / 15.0;
264 }
265 else if (ax > 30.0)
266 {
267 // csch^2 underflows to 0 well before this point.
268 l = (x > 0.0 ? 1.0 : -1.0) - 1.0 / x;
269 lp = 1.0 / (x * x);
270 lpp = -2.0 / (x * x * x);
271 }
272 else
273 {
274 // With u = e^(2x) - 1: coth = 1 + 2/u and csch^2 = 4 (u + 1)/u^2,
275 // one exponential and one division (expm1 keeps u whole for a
276 // small x, where e^(2x) - 1 would lose its digits).
277 const double u = std::expm1(2.0 * x);
278 const double r = 1.0 / u;
279 const double coth = 1.0 + 2.0 * r;
280 const double csch2 = 4.0 * (u + 1.0) * r * r;
281 const double ix = 1.0 / x;
282 l = coth - ix;
283 lp = ix * ix - csch2;
284 lpp = 2.0 * (csch2 * coth - ix * ix * ix);
285 }
286 }
287
289 void evaluate(double m, double h, double hDot, double& w, double& dwdm) const noexcept
290 {
291 if (hDot == 0.0)
292 {
293 w = 0.0;
294 dwdm = 0.0;
295 return;
296 }
297
298 const double q = (h + alpha_ * m) / a_;
299 double l = 0.0, lp = 0.0, lpp = 0.0;
300 langevin(q, l, lp, lpp);
301
302 const double mAn = ms_ * l;
303 const double dM = mAn - m;
304 const double delta = (hDot > 0.0) ? 1.0 : -1.0;
305 const double deltaM = (dM * delta > 0.0) ? 1.0 : 0.0; // gate reversal
306
307 // Guard the JA denominator singularity (can cross zero at hard drive).
308 const double oneMc = 1.0 - c_;
309 double d1 = oneMc * delta * k_ - alpha_ * dM;
310 const double d1Min = 0.01 * oneMc * k_;
311 if (std::abs(d1) < d1Min)
312 d1 = (d1 >= 0.0) ? d1Min : -d1Min;
313
314 const double invD1 = 1.0 / d1;
315 const double phi1 = oneMc * deltaM * dM * invD1;
316 const double cChiLp = c_ * chi_ * lp;
317
318 const double num = phi1 + cChiLp;
319 // Guard the reversible-branch denominator too: physical JA parameter
320 // sets satisfy c*alpha*Ms/(3a) < 1 so den stays near 1, but an extreme
321 // user set makes it sweep through zero as Q moves, spiking dM/dt (and
322 // wPrev_, which has no physical clamp) by orders of magnitude for a
323 // sample. The M clamp recovers afterwards; this bounds the spike.
324 double den = 1.0 - alpha_ * cChiLp;
325 if (std::abs(den) < 0.01)
326 den = (den >= 0.0) ? 0.01 : -0.01;
327 const double invDen = 1.0 / den;
328 w = hDot * num * invDen;
329
330 // Analytic dW/dM for the Newton step.
331 const double alphaOverA = alpha_ / a_;
332 const double dmAn = ms_ * lp * alphaOverA - 1.0; // d(M_an - M)/dM
333 const double dPhi1 = oneMc * deltaM * dmAn * (oneMc * delta * k_) * (invD1 * invD1);
334 const double dLp = lpp * alphaOverA;
335 const double dNum = dPhi1 + c_ * chi_ * dLp;
336 const double dDen = -alpha_ * c_ * chi_ * dLp;
337 dwdm = hDot * (dNum * den - num * dDen) * (invDen * invDen);
338 }
339
342 static constexpr double kAlpha = 0.9;
343
344public:
345 static constexpr int kMaxPeriod = 8;
346
347private:
348 static constexpr int kRing = 16;
349
350 // -- Members ----------------------------------------------------------------
351 double ms_ = 3.5e5, a_ = 2.2e4, alpha_ = 1.6e-3, k_ = 2.7e4, c_ = 1.7e-1;
352 double chi_ = 3.5e5 / 2.2e4;
353 double tolerance_ = 1e-9;
354 bool bySlope_ = false;
355
356 double invFs2_ = 0.5 / 48000.0;
357 double fs2_ = 2.0 * 48000.0;
358
359 double m_ = 0.0;
360 double hPrev_ = 0.0;
361 double hDotPrev_ = 0.0;
362 double wPrev_ = 0.0;
363 std::array<double, kRing> past_ {};
364 int pastAt_ = 0, pastCount_ = 0, period_ = 0;
365};
366
367} // namespace dspark
Per-channel Jiles-Atherton hysteresis processor (field in, M out).
Definition Hysteresis.h:73
T processSample(T fieldH) noexcept
Processes one sample of applied field H, returns magnetization M.
Definition Hysteresis.h:180
static constexpr int kMaxPeriod
The longest period the predictor follows.
Definition Hysteresis.h:345
double getSaturation() const noexcept
Saturation magnetization Ms (A/m).
Definition Hysteresis.h:162
double getSmallSignalSusceptibility() const noexcept
Small-signal susceptibility dM/dH around the demagnetized state.
Definition Hysteresis.h:170
int getPredictorPeriod() const noexcept
Definition Hysteresis.h:159
void setParameters(double ms, double a, double alpha, double k, double c) noexcept
Sets the Jiles-Atherton parameters.
Definition Hysteresis.h:112
void setTolerance(double relative) noexcept
Where the solver stops: a Newton step under this share of Ms.
Definition Hysteresis.h:136
void reset() noexcept
Clears magnetization and integrator state. RT-safe.
Definition Hysteresis.h:87
void setPredictorPeriod(int period) noexcept
The period of the field in samples, for the predictor (0, the default, for none). With a field that r...
Definition Hysteresis.h:152
void prepare(double sampleRate)
Prepares the integrator for the given sample rate. A non-positive or non-finite rate is ignored (NaN ...
Definition Hysteresis.h:78
Main namespace for the DSPark framework.