DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
WDF.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
79#include "DspMath.h"
80
81#include <algorithm>
82#include <array>
83#include <bit>
84#include <cassert>
85#include <cmath>
86#include <cstddef>
87#include <cstdint>
88#include <limits>
89#include <numbers>
90#include <tuple>
91#include <utility>
92
93// Keeps the cold solver paths (large diode constants, extreme drive) out of
94// the per-sample root, so the hot path inlines into the caller's loop.
95// Locally defined and guarded, as in Core/Biquad.h.
96#ifndef DSPARK_NOINLINE
97 #if defined(_MSC_VER)
98 #define DSPARK_NOINLINE __declspec(noinline)
99 #elif defined(__GNUC__) || defined(__clang__)
100 #define DSPARK_NOINLINE __attribute__((noinline))
101 #else
102 #define DSPARK_NOINLINE
103 #endif
104#endif
105
106// Forces the kernel of the local expansions into the root that reads a
107// cell: it has several callers, and with them a compiler may leave it out
108// of line (MSVC did for the pair once the single diode read cells too, 1 ns
109// per sample there). Forcing the table and series paths as well was
110// measured and is not done: no gain with GCC, a loss with Clang and MSVC.
111#ifndef DSPARK_WDF_INLINE
112 #if defined(_MSC_VER) && !defined(__clang__)
113 #define DSPARK_WDF_INLINE __forceinline
114 #elif defined(__GNUC__) || defined(__clang__)
115 #define DSPARK_WDF_INLINE inline __attribute__((always_inline))
116 #else
117 #define DSPARK_WDF_INLINE inline
118 #endif
119#endif
120
121namespace dspark {
122namespace wdf {
123
124// ============================================================================
125// One-port leaf elements
126// ============================================================================
127
129template <FloatType T>
131{
132public:
133 explicit Resistor(T resistanceOhms) noexcept : value_(resistanceOhms) {}
134
135 void setResistance(T ohms) noexcept { value_ = std::max(ohms, T(1e-9)); }
136
138 [[nodiscard]] T getResistance() const noexcept { return value_; }
139
140 void prepare(double) noexcept {}
141 void updatePorts() noexcept { R_ = static_cast<double>(value_); }
142 void reset() noexcept { a_ = 0; }
143
144 [[nodiscard]] double portResistance() const noexcept { return R_; }
145 [[nodiscard]] T reflected() noexcept { return T(0); }
146 void incident(T a) noexcept { a_ = a; }
147
149 [[nodiscard]] T getVoltage() const noexcept { return a_ * T(0.5); }
151 [[nodiscard]] T getCurrent() const noexcept
152 {
153 return static_cast<T>(static_cast<double>(a_) * 0.5 / R_);
154 }
155
156private:
157 T value_;
158 double R_ = 1.0;
159 T a_ = 0;
160};
161
163template <FloatType T>
165{
166public:
167 explicit Capacitor(T farads) noexcept : value_(farads) {}
168
169 void setCapacitance(T farads) noexcept { value_ = std::max(farads, T(1e-18)); }
170
172 [[nodiscard]] T getCapacitance() const noexcept { return value_; }
173
174 void prepare(double sampleRate) noexcept { fs_ = sampleRate; }
175 void updatePorts() noexcept { R_ = 1.0 / (2.0 * fs_ * static_cast<double>(value_)); }
176 void reset() noexcept { state_ = 0; a_ = 0; b_ = 0; }
177
181 void offsetVoltage(T offset) noexcept
182 {
183 state_ += offset;
184 a_ += offset;
185 b_ += offset;
186 }
187
188 [[nodiscard]] double portResistance() const noexcept { return R_; }
189 [[nodiscard]] T reflected() noexcept { b_ = state_; return b_; }
190 void incident(T a) noexcept { a_ = a; state_ = a; }
191
192 [[nodiscard]] T getVoltage() const noexcept { return (a_ + b_) * T(0.5); }
193 [[nodiscard]] T getCurrent() const noexcept
194 {
195 return static_cast<T>(static_cast<double>(a_ - b_) * 0.5 / R_);
196 }
197
198private:
199 T value_;
200 double fs_ = 48000.0;
201 double R_ = 1.0;
202 T state_ = 0, a_ = 0, b_ = 0;
203};
204
206template <FloatType T>
208{
209public:
210 explicit Inductor(T henries) noexcept : value_(henries) {}
211
212 void setInductance(T henries) noexcept { value_ = std::max(henries, T(1e-12)); }
213
214 void prepare(double sampleRate) noexcept { fs_ = sampleRate; }
215 void updatePorts() noexcept { R_ = 2.0 * fs_ * static_cast<double>(value_); }
216 void reset() noexcept { state_ = 0; a_ = 0; b_ = 0; }
217
218 [[nodiscard]] double portResistance() const noexcept { return R_; }
219 [[nodiscard]] T reflected() noexcept { b_ = -state_; return b_; }
220 void incident(T a) noexcept { a_ = a; state_ = a; }
221
222 [[nodiscard]] T getVoltage() const noexcept { return (a_ + b_) * T(0.5); }
223 [[nodiscard]] T getCurrent() const noexcept
224 {
225 return static_cast<T>(static_cast<double>(a_ - b_) * 0.5 / R_);
226 }
227
228private:
229 T value_;
230 double fs_ = 48000.0;
231 double R_ = 1.0;
232 T state_ = 0, a_ = 0, b_ = 0;
233};
234
241template <FloatType T>
243{
244public:
245 explicit ResistiveVoltageSource(T seriesResistanceOhms) noexcept
246 : value_(seriesResistanceOhms) {}
247
248 void setResistance(T ohms) noexcept { value_ = std::max(ohms, T(1e-9)); }
249 void setVoltage(T volts) noexcept { vs_ = volts; }
250
251 void prepare(double) noexcept {}
252 void updatePorts() noexcept { R_ = static_cast<double>(value_); }
253 void reset() noexcept { a_ = 0; }
254
255 [[nodiscard]] double portResistance() const noexcept { return R_; }
256 [[nodiscard]] T reflected() noexcept { return vs_; }
257 void incident(T a) noexcept { a_ = a; }
258
260 [[nodiscard]] T getVoltage() const noexcept { return (a_ + vs_) * T(0.5); }
261
262private:
263 T value_;
264 double R_ = 1.0;
265 T vs_ = 0, a_ = 0;
266};
267
268// ============================================================================
269// Connectors
270// ============================================================================
271
286template <FloatType T, typename Child1, typename Child2>
288{
289public:
290 Series(Child1& c1, Child2& c2) noexcept : c1_(c1), c2_(c2) {}
291
292 void prepare(double sampleRate) noexcept
293 {
294 c1_.prepare(sampleRate);
295 c2_.prepare(sampleRate);
296 }
297 void updatePorts() noexcept
298 {
299 c1_.updatePorts();
300 c2_.updatePorts();
301 const double r1 = c1_.portResistance();
302 const double r2 = c2_.portResistance();
303 R_ = r1 + r2;
304 gamma1_ = static_cast<T>(r1 / R_);
305 }
306 void reset() noexcept { c1_.reset(); c2_.reset(); a1_ = 0; a2_ = 0; }
307
308 [[nodiscard]] double portResistance() const noexcept { return R_; }
309
310 [[nodiscard]] T reflected() noexcept
311 {
312 a1_ = c1_.reflected();
313 a2_ = c2_.reflected();
314 return a1_ + a2_; // -(a1+a2) with the up-port inversion folded in
315 }
316
317 void incident(T a3) noexcept
318 {
319 // b_k = a_k - gamma_k * (a1 + a2 + a3'), a3' = -a3 (folded inversion),
320 // with gamma1 + gamma2 = 1 on the adapted port.
321 const T sum = a1_ + a2_ - a3;
322 c1_.incident(a1_ - gamma1_ * sum);
323 c2_.incident(a2_ - (sum - gamma1_ * sum)); // a2 - gamma2 * sum
324 }
325
326private:
327 Child1& c1_;
328 Child2& c2_;
329 double R_ = 2.0;
330 T gamma1_ = T(0.5);
331 T a1_ = 0, a2_ = 0;
332};
333
340template <FloatType T, typename Child1, typename Child2>
342{
343public:
344 Parallel(Child1& c1, Child2& c2) noexcept : c1_(c1), c2_(c2) {}
345
346 void prepare(double sampleRate) noexcept
347 {
348 c1_.prepare(sampleRate);
349 c2_.prepare(sampleRate);
350 }
351 void updatePorts() noexcept
352 {
353 c1_.updatePorts();
354 c2_.updatePorts();
355 const double g1 = 1.0 / c1_.portResistance();
356 const double g2 = 1.0 / c2_.portResistance();
357 R_ = 1.0 / (g1 + g2);
358 d1_ = static_cast<T>(g1 / (g1 + g2));
359 }
360 void reset() noexcept { c1_.reset(); c2_.reset(); a1_ = 0; a2_ = 0; bUp_ = 0; }
361
362 [[nodiscard]] double portResistance() const noexcept { return R_; }
363
364 [[nodiscard]] T reflected() noexcept
365 {
366 a1_ = c1_.reflected();
367 a2_ = c2_.reflected();
368 bUp_ = d1_ * a1_ + (T(1) - d1_) * a2_; // weighted node wave
369 return bUp_;
370 }
371
372 void incident(T a3) noexcept
373 {
374 // Common node wave: bNode = bUp + a3; then b_k = bNode - a_k.
375 const T bNode = bUp_ + a3;
376 c1_.incident(bNode - a1_);
377 c2_.incident(bNode - a2_);
378 }
379
380private:
381 Child1& c1_;
382 Child2& c2_;
383 double R_ = 0.5;
384 T d1_ = T(0.5);
385 T a1_ = 0, a2_ = 0, bUp_ = 0;
386};
387
389template <FloatType T, typename Child>
391{
392public:
393 explicit Inverter(Child& c) noexcept : c_(c) {}
394
395 void prepare(double sampleRate) noexcept { c_.prepare(sampleRate); }
396 void updatePorts() noexcept { c_.updatePorts(); }
397 void reset() noexcept { c_.reset(); }
398
399 [[nodiscard]] double portResistance() const noexcept { return c_.portResistance(); }
400 [[nodiscard]] T reflected() noexcept { return -c_.reflected(); }
401 void incident(T a) noexcept { c_.incident(-a); }
402
403private:
404 Child& c_;
405};
406
407// ============================================================================
408// Roots
409// ============================================================================
410
417template <FloatType T, typename Tree>
419{
420public:
421 explicit IdealVoltageSourceRoot(Tree& tree) noexcept : tree_(tree) {}
422
423 void setVoltage(T volts) noexcept { vs_ = volts; }
424
425 void prepare(double sampleRate) noexcept
426 {
427 tree_.prepare(sampleRate);
428 tree_.updatePorts();
429 tree_.reset();
430 }
431 void reset() noexcept { tree_.reset(); }
432
433 void process() noexcept
434 {
435 const T a = tree_.reflected();
436 // A non-finite source or wave would stay in the reactive states for
437 // good: clear the tree instead, so the next finite input recovers.
438 if (!std::isfinite(a) || !std::isfinite(vs_)) [[unlikely]]
439 {
440 tree_.reset();
441 return;
442 }
443 tree_.incident(T(2) * vs_ - a);
444 }
445
446private:
447 Tree& tree_;
448 T vs_ = 0;
449};
450
451template <FloatType T, typename Tree> class DiodePairRoot;
452template <FloatType T, typename Tree> class DiodeRoot;
453
454namespace detail {
455
467template <typename F>
468[[nodiscard]] inline double solveMonotonic(double a, double seed, F&& evaluate) noexcept
469{
470 double lo = std::min(0.0, a);
471 double hi = std::max(0.0, a);
472 double v = std::clamp(seed, lo, hi);
473 double prevAbsF = 1e300;
474
475 for (int it = 0; it < 48; ++it)
476 {
477 double f = 0.0, fp = 1.0;
478 evaluate(v, f, fp);
479
480 const double absF = std::abs(f);
481 if (absF < 1e-10)
482 break;
483 if (f > 0.0) hi = v;
484 else lo = v;
485
486 // Accept the Newton step only while it makes real progress. Deep in
487 // the exponential region Newton crawls at ~nVt per step (the classic
488 // diode pathology), so a stalled |f| switches to bisection, which
489 // halves the bracket unconditionally. Quadratic near the root,
490 // bisection-guaranteed everywhere.
491 const double vn = v - f / fp;
492 if (vn > lo && vn < hi && absF < 0.7 * prevAbsF)
493 v = vn;
494 else
495 v = 0.5 * (lo + hi);
496 prevAbsF = absF;
497 }
498 return v;
499}
500
522class WrightOmega
523{
524public:
525 [[nodiscard]] static const WrightOmega& instance() noexcept
526 {
527 static const WrightOmega table;
528 return table;
529 }
530
531 [[nodiscard]] double operator()(double z) const noexcept
532 {
533 if (z < kUniformMax)
534 {
535 if (!(z > kUniformMin)) return 0.0;
536 // p + 1.5 * 2^52 rounds p to the nearest integer, which then
537 // sits in the low mantissa bits: no float-to-integer conversion.
538 constexpr double kRound = 6755399441055744.0;
539 const double p = (z - kUniformMin) * kInvStep;
540 const double rounded = p + kRound;
541 const double t = p - (rounded - kRound); // [-0.5, 0.5]
542 const auto& k = taylor_[static_cast<size_t>(std::bit_cast<std::uint64_t>(rounded) & 0x1FFu)];
543 const double t2 = t * t;
544 return (k[0] + k[1] * t) + t2 * ((k[2] + k[3] * t) + t2 * k[4]);
545 }
546 if (z < kOctaveMax)
547 {
548 // Cell = exponent and top four mantissa bits: 16 equal cells per
549 // octave from 32 upward, each expanded about its midpoint. The
550 // inverse width 2^(4 - e) comes from the exponent bits.
551 const auto bits = std::bit_cast<std::uint64_t>(z);
552 const auto& k = upper_[static_cast<size_t>((bits >> 48) - kFirstCellBits)];
553 const double t = (z - k[5]) * std::bit_cast<double>(kInverseSixteenth - (bits & kExponentMask));
554 const double t2 = t * t;
555 return (k[0] + k[1] * t) + t2 * ((k[2] + k[3] * t) + t2 * k[4]);
556 }
557 return farField(z);
558 }
559
560private:
561 static constexpr double kUniformMin = -32.0, kUniformMax = 32.0, kStep = 0.25, kInvStep = 4.0;
562 static constexpr int kUniformNodes = 257;
563 static constexpr int kOctaves = 15; // 32 .. 2^20
564 static constexpr int kUpperCells = 16 * kOctaves;
565 static constexpr double kOctaveMax = 1048576.0;
566 static constexpr std::uint64_t kFirstCellBits = 0x4040u; // bits(32.0) >> 48
567 static constexpr std::uint64_t kExponentMask = 0x7FF0000000000000ull;
568 static constexpr std::uint64_t kInverseSixteenth = std::uint64_t(2050) << 52; // 2^(4 - e)
569
571 static std::array<double, 5> expansion(double z, double h) noexcept
572 {
573 const double y = solve(z);
574 // omega' = w/(1+w), omega'' = w/(1+w)^3, omega''' = w(1-2w)/(1+w)^5,
575 // omega'''' = w(1-8w+6w^2)/(1+w)^7.
576 const double u = 1.0 / (1.0 + y), u2 = u * u;
577 const double d1 = y * u, d2 = d1 * u2, d3 = d2 * (1.0 - 2.0 * y) * u2;
578 const double d4 = d1 * (1.0 - 8.0 * y + 6.0 * y * y) * u2 * u2 * u2;
579 return { y, d1 * h, d2 * h * h / 2.0, d3 * h * h * h / 6.0, d4 * h * h * h * h / 24.0 };
580 }
581
583 DSPARK_NOINLINE static double farField(double z) noexcept
584 {
585 double y = z - std::log(z);
586 for (int it = 0; it < 2; ++it)
587 y -= (y + std::log(y) - z) * y / (1.0 + y);
588 return y;
589 }
590
591 static double solve(double z) noexcept
592 {
593 double y = z < 1.0 ? std::exp(z) : z - std::log(z);
594 for (int it = 0; it < 64; ++it)
595 {
596 const double step = (y + std::log(y) - z) * y / (1.0 + y);
597 y -= step;
598 if (!(std::abs(step) > 1e-17 * y)) break;
599 }
600 return y;
601 }
602
603 WrightOmega() noexcept
604 {
605 for (int i = 0; i < kUniformNodes; ++i)
606 taylor_[static_cast<size_t>(i)] = expansion(kUniformMin + kStep * i, kStep);
607 for (int c = 0; c < kUpperCells; ++c)
608 {
609 const double width = std::ldexp(1.0, 1 + c / 16); // 2^e / 16, e = 5 + c/16
610 const double mid = std::ldexp(1.0 + (c % 16) / 16.0, 5 + c / 16) + 0.5 * width;
611 const auto e = expansion(mid, width);
612 upper_[static_cast<size_t>(c)] = { e[0], e[1], e[2], e[3], e[4], mid };
613 }
614 }
615
616 std::array<std::array<double, 5>, kUniformNodes> taylor_ {};
617 std::array<std::array<double, 6>, kUpperCells> upper_ {};
618};
619
626inline void expTwice(double a, double& hi, double& lo) noexcept
627{
628 constexpr double kLn2Hi = 0.6931471805599453, kLn2Lo = 2.3190468138462996e-17;
629 const double k = std::nearbyint(a * 1.4426950408889634);
630 const double product = k * kLn2Hi;
631 const double productLow = std::fma(k, kLn2Hi, -product) + k * kLn2Lo;
632 const double first = a - product;
633 const double firstPart = first - a;
634 const double tail = ((a - (first - firstPart)) - (product + firstPart)) - productLow;
635 const double rh = first + tail;
636 const double rPart = rh - first;
637 const double rl = (first - (rh - rPart)) + (tail - rPart);
638 // 1 + r (1 + r / 2 (1 + r / 3 (...))): |r| < 0.35, so 22 terms pass 1e-31.
639 double sh = 1.0, sl = 0.0;
640 for (int n = 22; n >= 1; --n)
641 {
642 const double p = sh * rh;
643 const double pl = std::fma(sh, rh, -p) + (sh * rl + sl * rh);
644 const double q = p / n;
645 const double ql = (std::fma(-q, static_cast<double>(n), p) + pl) / n;
646 const double t = 1.0 + q;
647 const double tl = (q - (t - 1.0)) + ql;
648 sh = t + tl;
649 sl = tl - (sh - t);
650 }
651 const int e = static_cast<int>(k);
652 hi = std::ldexp(sh, e);
653 lo = std::ldexp(sl, e);
654}
655
692class DiodeOmegaTable
693{
694public:
695 static constexpr double kLo = -40.0, kHi = 32.0;
696 static constexpr int kNodes = 289;
697 static constexpr int kFirstLogNode = 160;
698 static constexpr double kOctaveMax = 1048576.0;
699 static constexpr int kCells = 16 * 15;
700
701 struct Node { double p[10]; double r[10]; double h[7]; };
702 struct Cell { double mid; double p[10]; double r[8]; };
703
704 [[nodiscard]] static const DiodeOmegaTable& instance() noexcept
705 {
706 static const DiodeOmegaTable table;
707 return table;
708 }
709
711 [[nodiscard]] static double poly9Rest(const double* c, double t) noexcept
712 {
713 const double t2 = t * t, t4 = t2 * t2;
714 const double a = (c[1] * t) + t2 * (c[2] + c[3] * t);
715 const double b = (c[4] + c[5] * t) + t2 * (c[6] + c[7] * t);
716 return (a + t4 * b) + (t4 * t4) * (c[8] + c[9] * t);
717 }
718
719private:
720 // The lookups return references into the table, which is immutable after
721 // construction; only the two diode roots read them.
722 template <FloatType U, typename Tr> friend class wdf::DiodePairRoot;
723 template <FloatType U, typename Tr> friend class wdf::DiodeRoot;
724
732 [[nodiscard]] const Node& node(double z4, double& t, int& index) const noexcept
733 {
734 constexpr double kRound = 6755399441055744.0 + kFirstLogNode;
735 const double rounded = z4 + kRound;
736 index = static_cast<int>(std::bit_cast<std::uint64_t>(rounded) & 0x1FFu);
737 t = z4 - (rounded - kRound);
738 return nodes_[static_cast<size_t>(index)];
739 }
740
742 [[nodiscard]] const Cell& cell(double z, double& t) const noexcept
743 {
744 const auto bits = std::bit_cast<std::uint64_t>(z);
745 const Cell& c = cells_[static_cast<size_t>((bits >> 48) - kFirstCellBits)];
746 t = (z - c.mid) * std::bit_cast<double>(kInverseSixteenth - (bits & kExponentMask));
747 return c;
748 }
749
752 [[nodiscard]] const Cell& cell(double z, double& t, double& scale, double& low) const noexcept
753 {
754 const auto bits = std::bit_cast<std::uint64_t>(z);
755 const auto index = static_cast<size_t>((bits >> 48) - kFirstCellBits);
756 const Cell& c = cells_[index];
757 scale = std::bit_cast<double>(kInverseSixteenth - (bits & kExponentMask));
758 t = (z - c.mid) * scale;
759 low = cellLow_[index];
760 return c;
761 }
762
764 [[nodiscard]] double nodeLow(int index) const noexcept { return nodeLow_[static_cast<size_t>(index)]; }
765
766public:
768 [[nodiscard]] static double poly7(const double* c, double t) noexcept
769 {
770 const double t2 = t * t;
771 const double a = (c[0] + c[1] * t) + t2 * (c[2] + c[3] * t);
772 const double b = (c[4] + c[5] * t) + t2 * (c[6] + c[7] * t);
773 return a + (t2 * t2) * b;
774 }
775
776private:
777 static constexpr std::uint64_t kFirstCellBits = 0x4040u; // bits(32.0) >> 48
778 static constexpr std::uint64_t kExponentMask = 0x7FF0000000000000ull;
779 static constexpr std::uint64_t kInverseSixteenth = std::uint64_t(2050) << 52; // 2^(4 - e)
780 static constexpr int kOrder = 14;
781 static constexpr int kFolded = 13;
782
791 static void economise(double* q, int from, int to, double& constant) noexcept
792 {
793 double cheb[kOrder + 1][kOrder + 1] {}; // T_n in powers of u = 2 t
794 cheb[0][0] = 1.0;
795 cheb[1][1] = 1.0;
796 for (int n = 1; n < from; ++n)
797 for (int j = 0; j <= n + 1; ++j)
798 cheb[n + 1][j] = (j > 0 ? 2.0 * cheb[n][j - 1] : 0.0) - cheb[n - 1][j];
799 for (int n = from; n > to; --n)
800 {
801 // t^n = u^n / 2^n, and u^n = (T_n(u) - its lower powers) / 2^(n - 1).
802 const double factor = -q[n] * std::ldexp(1.0, 1 - 2 * n);
803 for (int j = n - 2; j >= 0; j -= 2)
804 {
805 const double change = factor * cheb[n][j] * std::ldexp(1.0, j);
806 if (j == 0) constant += change;
807 else q[j] += change;
808 }
809 q[n] = 0.0;
810 }
811 }
812
813 static double solve(double z) noexcept
814 {
815 double y = z < 1.0 ? std::exp(z) : z - std::log(z);
816 for (int it = 0; it < 64; ++it)
817 {
818 const double step = (y + std::log(y) - z) * y / (1.0 + y);
819 y -= step;
820 if (!(std::abs(step) > 1e-17 * y)) break;
821 }
822 return y;
823 }
824
834 static void series(double z, double* w, double* l, double* r, double* h = nullptr,
835 double* low = nullptr) noexcept
836 {
837 const double y = solve(z);
838 if (low)
839 {
840 // What the doubles y and ln y leave out of omega and ln(omega)
841 // (low[0], low[1]): ln y to twice the precision from e^(ln y),
842 // then one Newton step of y + ln y = z with that residual.
843 const double lh = std::log(y);
844 double eh = 0.0, el = 0.0;
845 expTwice(lh, eh, el);
846 const double ll = ((y - eh) - el) / eh;
847 const double sum = y + lh;
848 const double part = sum - y;
849 const double sumLow = (y - (sum - part)) + (lh - part);
850 const double dy = -(((sum - z) + sumLow) + ll) * y / (1.0 + y);
851 low[0] = dy;
852 low[1] = ll + dy / y;
853 }
854 double p[kOrder + 1], q[kOrder + 1], pp[kOrder + 1], rp[kOrder + 1];
855 p[0] = 1.0 / (1.0 + y);
856 q[0] = y * p[0]; // 1 - P
857 r[0] = p[0] / y;
858 for (int n = 0; n < kOrder; ++n)
859 {
860 double s = 0.0;
861 for (int j = 0; j <= n; ++j) s += p[j] * p[n - j];
862 pp[n] = s; // [P^2]_n
863 s = 0.0;
864 for (int j = 0; j <= n; ++j) s += pp[j] * q[n - j];
865 p[n + 1] = -s / (n + 1);
866 q[n + 1] = -p[n + 1];
867 s = 0.0;
868 for (int j = 0; j <= n; ++j) s += r[j] * p[n - j];
869 rp[n] = s; // [R P]_n
870 s = rp[n];
871 for (int j = 0; j <= n; ++j) s += rp[j] * q[n - j];
872 r[n + 1] = -s / (n + 1);
873 }
874 if (h)
875 for (int n = 0; n < kOrder; ++n) h[n] = pp[n];
876 w[0] = y;
877 l[0] = std::log(y);
878 for (int n = 0; n < kOrder; ++n)
879 {
880 w[n + 1] = q[n] / (n + 1);
881 l[n + 1] = p[n] / (n + 1);
882 }
883 }
884
885 DiodeOmegaTable() noexcept
886 {
887 double w[kOrder + 1], l[kOrder + 1], r[kOrder + 1], hh[kOrder + 1], low[2], q[kOrder + 1];
888 for (int i = 0; i < kNodes; ++i)
889 {
890 series(kLo + 0.25 * i, w, l, r, hh, low);
891 Node& n = nodes_[static_cast<size_t>(i)];
892 // -omega or ln(omega) in t = 4 (z - z_k), with the powers 10 to
893 // 13 folded into the nine kept: cut at degree 9, the series
894 // would leave up to 4e-16 at the edges of the nodes nearest the
895 // branch points of omega (z = -1 +- i pi).
896 double scale = 1.0;
897 for (int k = 0; k <= kFolded; ++k, scale *= 0.25)
898 q[k] = (i < kFirstLogNode ? -w[k] : l[k]) * scale;
899 double shift = 0.0;
900 economise(q, kFolded, 9, shift);
901 for (int k = 0; k < 10; ++k) n.p[k] = q[k];
902 nodeLow_[static_cast<size_t>(i)] = (i < kFirstLogNode ? -low[0] : low[1]) + shift;
903 scale = 1.0;
904 for (int k = 0; k < 10; ++k, scale *= 0.25) n.r[k] = r[k] * scale;
905 const double u = 1.0 / (1.0 + w[0]);
906 n.h[0] = u * u;
907 n.h[1] = -2.0 * w[0] * u * u * u * u * 0.25;
908 scale = 0.0625;
909 for (int k = 2; k < 7; ++k, scale *= 0.25) n.h[k] = hh[k] * scale;
910 }
911 for (int c = 0; c < kCells; ++c)
912 {
913 const double width = std::ldexp(1.0, 1 + c / 16); // 2^e / 16, e = 5 + c/16
914 const double mid = std::ldexp(1.0 + (c % 16) / 16.0, 5 + c / 16) + 0.5 * width;
915 series(mid, w, l, r, nullptr, low);
916 cellLow_[static_cast<size_t>(c)] = low[1];
917 Cell& cl = cells_[static_cast<size_t>(c)];
918 cl.mid = mid;
919 double scale = 1.0;
920 for (int k = 0; k < 10; ++k, scale *= width) cl.p[k] = l[k] * scale;
921 scale = 1.0;
922 for (int k = 0; k < 8; ++k, scale *= width) cl.r[k] = r[k] * scale;
923 }
924 }
925
926 std::array<Node, kNodes> nodes_ {};
927 std::array<Cell, kCells> cells_ {};
928 std::array<double, kNodes> nodeLow_ {};
929 std::array<double, kCells> cellLow_ {};
930};
931
953struct DiodeSeries
954{
958 static constexpr double kPairCoefficients[190] = {
959 -0.16666666666666666, -0.008333333333333333, 0.08333333333333333,
960 -0.0001984126984126984, 0.011111111111111112, -0.05555555555555555,
961 -2.7557319223985893e-06, 0.000677910052910053, -0.01273148148148148,
962 0.04243827160493827, -2.505210838544172e-08, 2.535273368606702e-05,
963 -0.0013326719576719577, 0.01404320987654321, -0.03510802469135803,
964 -1.6059043836821613e-10, 6.555301694190583e-07, -8.616255144032922e-05,
965 0.0021347736625514403, -0.015303497942386831, 0.030606995884773662,
966 -7.647163731819816e-13, 1.2516877596242676e-08, -3.901925528909656e-06,
967 0.00020154810895551636, -0.003085684891240447, 0.01661522633744856,
968 -0.0276920438957476, -2.8114572543455206e-15, 1.8420105639020982e-10,
969 -1.3265171685310574e-07, 1.3412058788629556e-05, -0.00038840127743484227,
970 0.004199620627572016, -0.01803037122770919, 0.025757673182441702,
971 -8.22063524662433e-18, 2.154825793386156e-12, -3.537694774007972e-09,
972 6.748958893377618e-07, -3.461694730904479e-05, 0.0006657831313824112,
973 -0.005497982872275568, 0.019581856805365037, -0.024477321006706295,
974 -1.9572941063391263e-20, 2.052328564378316e-14, -7.63054132550079e-11,
975 2.6857233826151793e-08, -2.3437074499064687e-06, 7.502594069606581e-05,
976 -0.0010560215634321858, 0.007007507328205631, -0.021295269275834475,
977 0.023661410306482753, -3.868170170630684e-23, 1.6224188783272867e-16,
978 -1.3615508265959045e-12, 8.718744862893881e-10, -1.2608500024975103e-07,
979 6.444848572066936e-06, -0.00014466849341383163, 0.0015856217815772857,
980 -0.008759798795847214, 0.02319379350200681, -0.02319379350200681,
981 -6.446950284384474e-26, 1.0816170984167235e-18, -2.0454899596721922e-14,
982 2.3622256014636148e-11, -5.560999346458007e-09, 4.4139111094536364e-07,
983 -1.5151959626692243e-05, 0.0002566754712713968, -0.0022861625245067354,
984 0.010791464659987286, -0.025300563078439094, 0.023000511889490084,
985 -9.183689863795546e-29, 6.163067369443176e-21, -2.624379797399636e-16,
986 5.435863409317769e-13, -2.0576040831492097e-10, 2.486734120772481e-08,
987 -1.2686390623297178e-06, 3.18473810836589e-05, -0.0004280069091063092,
988 0.0031952644376229754, -0.013144553833792228, 0.02763993138172911,
989 -0.023033276151440924, -1.1309962886447716e-31, 3.0359947054677823e-23,
990 -2.90983516988768e-18, 1.0773119729318394e-14, -6.500516401322334e-12,
991 1.1793526431273427e-09, -8.760273119582742e-08, 3.166099301127302e-06,
992 -6.155872734178536e-05, 0.0006803442075780342, -0.004357681886385206,
993 0.01586718791319178, -0.03023826647467491, 0.023260204980519162,
994 -1.216125041553518e-34, 1.305804281413749e-25, -2.8164494022894016e-20,
995 1.8598856226380004e-16, -1.7781683941160714e-13, 4.792391011366623e-11,
996 -5.105092927875956e-09, 2.6013585118536054e-07, -7.1081371288621065e-06,
997 0.00011151636823255261, -0.0010411731217924711, 0.005826556292754563,
998 -0.019014342187516006, 0.033124532770107074, -0.02366038055007648,
999 -1.151633562077195e-37, 4.946228446941997e-28, -2.400577152778124e-22,
1000 2.823876221983734e-18, -4.259542492017361e-15, 1.692153810932095e-12,
1001 -2.555530089128816e-10, 1.8074100859420624e-08, -6.795666888993754e-07,
1002 1.4701125115609984e-05, -0.0001918618460532977, 0.0015450912017424953,
1003 -0.0076648654207181945, 0.022648764847580313, -0.03633078320260323,
1004 0.024220522135068822, -9.67759295863189e-41, 1.6625978069690206e-30,
1005 -1.815631965979403e-24, 3.80152886681811e-20, -9.020063567411856e-17,
1006 5.251035194309445e-14, -1.1143997834640651e-11, 1.0808330297892926e-09,
1007 -5.503300371729764e-08, 1.6071863715423982e-06, -2.848117077960185e-05,
1008 0.0003165434147228053, -0.002235380660678097, 0.009947103846933474,
1009 -0.026842037472040975, 0.039892624693054525, -0.02493289043315908,
1010 -7.265460179153071e-44, 4.992786214815564e-33, -1.2268004484704633e-26,
1011 4.569781510266617e-22, -1.7020604798406413e-18, 1.4456351083934227e-15,
1012 -4.281836851327378e-13, 5.641424476816121e-11, -3.842042611039085e-09,
1013 1.490510231519924e-07, -3.511190846188237e-06, 5.231861394876127e-05,
1014 -0.0005044424531680884, 0.0031658955995590354, -0.012761233058852326,
1015 0.03167578795742484, -0.04384969153807692, 0.02579393619886878,
1016 -4.902469756513544e-47, 1.3475806253306053e-35, -7.45026815204885e-29,
1017 4.9358060995432006e-24, -2.88161452928429e-20, 3.5590142851266987e-17,
1018 -1.463339766188361e-14, 2.599510558910379e-12, -2.3448394274072986e-10,
1019 1.1933073304746268e-08, -3.6768172678110105e-07, 7.190746000583771e-06,
1020 -9.19608815095438e-05, 0.0007807836711677919, -0.004403321514323129,
1021 0.016210944378911955, -0.03724307230981259, 0.04824614786994889,
1022 -0.02680341548330494
1023 };
1025 static constexpr double kSingleCoefficients[136] = {
1026 -0.5, -0.16666666666666666, 0.5, -0.041666666666666664, 0.4166666666666667, -0.625,
1027 -0.008333333333333333, 0.20833333333333334, -0.875, 0.875, -0.001388888888888889,
1028 0.07777777777777778, -0.6805555555555556, 1.75, -1.3125, -0.0001984126984126984,
1029 0.02361111111111111, -0.38055555555555554, 1.875, -3.4375, 2.0625,
1030 -2.48015873015873e-05, 0.006101190476190476, -0.16927083333333334, 1.4131944444444444,
1031 -4.7265625, 6.703125, -3.3515625, -2.7557319223985893e-06, 0.0013806216931216931,
1032 -0.06320271164021164, 0.8349729938271605, -4.510127314814815, 11.296006944444445,
1033 -13.033854166666666, 5.5859375, -2.755731922398589e-07, 0.0002788800705467372,
1034 -0.020479497354497354, 0.4098324514991182, -3.340528549382716, 13.091782407407408,
1035 -26.067708333333332, 25.322916666666668, -9.49609375, -2.505210838544172e-08,
1036 5.09810405643739e-05, -0.005889550264550265, 0.173233024691358, -2.0400270061728394,
1037 11.696238425925927, -35.63113425925926, 58.703125, -49.20703125, 16.40234375,
1038 -2.08767569878681e-09, 8.521892202447758e-06, -0.001527617026748971,
1039 0.06461548353909465, -1.066552533436214, 8.568155221193416, -37.354499421296296,
1040 92.58211805555555, -129.85188802083334, 95.68033854166667, -28.7041015625,
1041 -1.6059043836821613e-10, 1.3131480145369033e-06, -0.0003617044285447063,
1042 0.02164432227366255, -0.4897392618312757, 5.3492557227366255, -31.97756076388889,
1043 111.56864872685185, -232.33148871527777, 283.3610026041667, -186.20865885416666,
1044 50.7841796875, -1.1470745597729725e-11, 1.8775316394364013e-07, -7.891503613229804e-05,
1045 0.006597468567954679, -0.20118927055776015, 2.9222029320987652, -23.24848457708701,
1046 109.43574322089947, -316.70893012152777, 567.4930555555555, -611.8284505208334,
1047 362.744140625, -90.68603515625, -7.647163731819816e-13, 2.5045225938083082e-08,
1048 -1.598327726799949e-05, 0.0018487619924045188, -0.07498005246746567,
1049 1.4237209155460024, -14.74556337877229, 90.91360812573487, -350.53111479690256,
1050 863.9490632233797, -1356.6630859375, 1309.909396701389, -707.35107421875,
1051 163.23486328125, -4.779477332387385e-14, 3.131417958633567e-09,
1052 -3.0234750403091175e-06, 0.0004801716850276291, -0.025626671262063385,
1053 0.627620408914083, -8.319817679867006, 65.73195370867933, -327.86206375400155,
1054 1065.7648367099662, -2282.6262828685617, 3187.009562174479, -2785.194854736328,
1055 1380.6948852539062, -295.8631896972656, -2.8114572543455206e-15,
1056 3.6844990755374353e-10, -5.368700378931033e-07, 0.00011636075093390529,
1057 -0.008102164118286442, 0.2531695617639899, -4.238021926775227, 42.188908018022104,
1058 -266.3720860467246, 1109.0705859382176, -3106.9867568243117, 5875.001434326172,
1059 -7379.047108968099, 5888.257598876953, -2697.576141357422, 539.5152282714844
1060 };
1061
1062 static constexpr double kTolerance = 1e-17;
1063 static constexpr double kMaxKappa = 0.04;
1064 static constexpr double kMaxY = 6.0;
1065
1067 static double pair(double kappa, double* b) noexcept
1068 {
1069 if (!(kappa > 0.0 && kappa <= kMaxKappa)) return 0.0;
1070 double tail[2] {};
1071 int offset = 0;
1072 for (int i = 0; i < 9; ++i)
1073 {
1074 const int degree = i + 1;
1075 double v = 0.0;
1076 for (int j = degree - 1; j >= 0; --j) v = v * kappa + kPairCoefficients[offset + j];
1077 offset += degree;
1078 if (i < 7) b[i] = v * kappa;
1079 else tail[i - 7] = v * kappa;
1080 }
1081 return limit(tail, 17);
1082 }
1083
1087 static double pairLong(double kappa, double* b) noexcept
1088 {
1089 if (!(kappa > 0.0 && kappa <= kMaxKappa)) return 0.0;
1090 double tail[2] {};
1091 int offset = 0;
1092 for (int i = 0; i < 19; ++i)
1093 {
1094 const int degree = i + 1;
1095 double v = 0.0;
1096 for (int j = degree - 1; j >= 0; --j) v = v * kappa + kPairCoefficients[offset + j];
1097 offset += degree;
1098 if (i < 17) b[i] = v * kappa;
1099 else tail[i - 17] = v * kappa;
1100 }
1101 return limit(tail, 37);
1102 }
1103
1105 static double single(double kappa, double* d) noexcept
1106 {
1107 if (!(kappa > 0.0 && kappa <= kMaxKappa)) return 0.0;
1108 double tail[2] {};
1109 int offset = 0;
1110 for (int i = 0; i < 16; ++i)
1111 {
1112 const int degree = i + 1;
1113 double v = 0.0;
1114 for (int j = degree - 1; j >= 0; --j) v = v * kappa + kSingleCoefficients[offset + j];
1115 offset += degree;
1116 if (i < 14) d[i] = v * kappa;
1117 else tail[i - 14] = v * kappa;
1118 }
1119 return limit(tail, 16);
1120 }
1121
1122private:
1125 static double limit(const double* tail, int firstPower) noexcept
1126 {
1127 const int step = (firstPower & 1) != 0 ? 2 : 1; // the pair has odd powers only
1128 double y = kMaxY;
1129 for (int i = 0; i < 2; ++i)
1130 {
1131 const double t = std::abs(tail[i]);
1132 if (t > 0.0)
1133 y = std::min(y, std::pow(kTolerance / t, 1.0 / (firstPower + step * i - 1)));
1134 }
1135 return y;
1136 }
1137};
1138
1177struct DiodeLocal
1178{
1179 static constexpr int kTerms = 32;
1180 static constexpr int kCellTerms = 16;
1181 static constexpr int kMaxCells = 56;
1182 static constexpr int kCentreCount = 24;
1183 static constexpr double kTolerance = 1e-17;
1187 static constexpr double kOffset = 1.5;
1188 static constexpr int kKeyShift = 49;
1189
1191 struct Centre { double s, sinhHi, sinhLo, cosh; };
1192 static constexpr Centre kCentres[kCentreCount] = {
1193 { 0.25, 0.2526123168081683, -5.550352555023456e-18, 1.0314130998795732 },
1194 { 0.5, 0.5210953054937474, -2.3328183476404597e-17, 1.1276259652063807 },
1195 { 0.75, 0.82231673193583, -1.1335882233129953e-17, 1.2946832846768448 },
1196 { 1.0, 1.1752011936438014, 7.849672142285669e-17, 1.5430806348152437 },
1197 { 1.25, 1.6019190803008256, 4.943508499611119e-19, 1.8884238771610158 },
1198 { 1.5, 2.1292794550948173, 1.8859829935660394e-16, 2.352409615243247 },
1199 { 1.75, 2.7904143662776426, 4.462297999014824e-17, 2.9641883097280877 },
1200 { 2.0, 3.6268604078470186, 1.9291196578353674e-16, 3.7621956910836314 },
1201 { 2.25, 4.691168305898331, -2.0060583610320798e-16, 4.796567530460195 },
1202 { 2.5, 6.0502044810397875, -1.5266669624477375e-16, 6.132289479663686 },
1203 { 2.75, 7.789352011490732, 4.362551404194279e-17, 7.853279872697439 },
1204 { 3.0, 10.017874927409903, -6.97789774734877e-16, 10.067661995777765 },
1205 { 3.25, 12.87578285468067, -2.578015334190764e-16, 12.914557062512392 },
1206 { 3.5, 16.542627287634996, 1.388991286007725e-15, 16.572824671057315 },
1207 { 3.75, 21.248782127103386, 1.0986521939233124e-15, 21.272299872959398 },
1208 { 4.0, 27.289917197127753, -7.633630011960991e-16, 27.308232836016487 },
1209 { 4.25, 35.04557405638943, 2.7362100014654743e-15, 35.05983829029843 },
1210 { 4.5, 45.003011151991785, 3.6708731211657254e-16, 45.014120148530026 },
1211 { 4.75, 57.78781641599227, 1.1560809076983308e-15, 57.79646811119539 },
1212 { 5.0, 74.20321057778875, 6.687957117824193e-15, 74.20994852478785 },
1213 { 5.25, 95.2805104701154, 5.1967560907177715e-15, 95.28575798851459 },
1214 { 5.5, 122.34392274639096, 3.0463153468293817e-15, 122.34800951782942 },
1215 { 5.75, 157.09373875244884, 1.3507577081271248e-15, 157.09692153324536 },
1216 { 6.0, 201.71315737027922, 8.575934656268528e-15, 201.7156361224559 },
1217 };
1218
1219 static constexpr int kSingleCentreCount = 18;
1223 static constexpr int kSingleMaxCells = 32;
1226 struct ExpCentre { double s, expHi, expLo; };
1227 static constexpr ExpCentre kSingleCentres[kSingleCentreCount] = {
1228 { -2.0, 0.1353352832366127, -1.042381423288669e-17 },
1229 { -1.75, 0.17377394345044514, -1.2999409968044821e-17 },
1230 { -1.5, 0.22313016014842982, 1.0887723699042263e-17 },
1231 { -1.25, 0.2865047968601901, 8.479830077607644e-18 },
1232 { -1.0, 0.36787944117144233, -1.2428753672788363e-17 },
1233 { -0.75, 0.4723665527410147, 1.7984004434373214e-17 },
1234 { -0.5, 0.6065306597126334, -6.593178415491414e-19 },
1235 { -0.25, 0.7788007830714049, -1.0231869534531498e-17 },
1236 { 0.25, 1.2840254166877414, 8.968972781793724e-17 },
1237 { 0.5, 1.6487212707001282, -4.731568479435833e-17 },
1238 { 0.75, 2.117000016612675, -1.1571006249440234e-16 },
1239 { 1.0, 2.718281828459045, 1.4456468917292502e-16 },
1240 { 1.25, 3.4903429574618414, -4.604261945372796e-17 },
1241 { 1.5, 4.4816890703380645, 3.0481759556536343e-16 },
1242 { 1.75, 5.754602676005731, -2.8457593299092424e-16 },
1243 { 2.0, 7.38905609893065, -1.7971139497839148e-16 },
1244 { 2.25, 9.487735836358526, -5.218563277933494e-16 },
1245 { 2.5, 12.182493960703473, 2.0334002173348147e-16 },
1246 };
1247
1248 struct Cell
1249 {
1250 double centre = 0.0;
1251 double rootHi = 0.0, rootLo = 0.0;
1252 double a[kCellTerms] {};
1253 };
1254
1255private:
1257 struct Expansion
1258 {
1259 double xHi = 0.0, xLo = 0.0;
1260 double width = 0.0;
1261 double s = 0.0;
1262 double a[kTerms + 1] {};
1263 };
1264
1265public:
1267 [[nodiscard]] static DSPARK_WDF_INLINE std::uint64_t key(double shifted) noexcept
1268 {
1269 return std::bit_cast<std::uint64_t>(shifted) >> kKeyShift;
1270 }
1271
1273 [[nodiscard]] static DSPARK_WDF_INLINE double evaluate(const Cell& cell, double x) noexcept
1274 {
1275 const double d = x - cell.centre;
1276 const double* a = cell.a;
1277 const double d2 = d * d, d4 = d2 * d2;
1278 const double q0 = (a[0] + a[1] * d) + d2 * (a[2] + a[3] * d);
1279 const double q1 = (a[4] + a[5] * d) + d2 * (a[6] + a[7] * d);
1280 const double q2 = (a[8] + a[9] * d) + d2 * (a[10] + a[11] * d);
1281 const double q3 = (a[12] + a[13] * d) + d2 * (a[14] + a[15] * d);
1282 return cell.rootHi + (cell.rootLo + d * ((q0 + d4 * q1) + (d4 * d4) * (q2 + d4 * q3)));
1283 }
1284
1291 static double origin(double kappa, double* b) noexcept
1292 {
1293 double g[kMaxOrder] {};
1294 series(1.0, -kappa, 1.0, 0.0, 39, g);
1295 for (int i = 0; i < 17; ++i) b[i] = g[2 * i + 2];
1296 double y = 6.0;
1297 for (int k = 37; k <= 39; k += 2)
1298 {
1299 const double tail = std::abs(g[k - 1]);
1300 if (tail > 0.0) y = std::min(y, std::pow(kTolerance / tail, 1.0 / (k - 1)));
1301 }
1302 return y;
1303 }
1304
1311 struct Builder
1312 {
1313 double offset = 0.0;
1314 std::uint64_t firstKey = 0;
1315 int count = 0;
1316 bool done = true;
1317 double twoC = 0.0, from = 0.0, to = 0.0;
1318 double c = 0.0;
1319 bool single = false;
1320 bool clipTop = false;
1321 int capacity = kMaxCells;
1322 int nearest = 0;
1323 int anchorCentre[2] = { -1, -1 };
1324 double anchorWidth[2] = { 0.0, 0.0 };
1325 Expansion anchor[2];
1326 };
1327
1329 static void start(Builder& b, double c, double from, double to) noexcept
1330 {
1331 b.count = 0;
1332 b.nearest = 0;
1333 b.anchorCentre[0] = b.anchorCentre[1] = -1;
1334 b.twoC = 2.0 * c;
1335 b.c = c;
1336 b.single = false;
1337 b.clipTop = false;
1338 b.capacity = kMaxCells;
1339 b.from = from;
1340 b.to = to;
1341 // Branch point nearest the positive real axis: the image of
1342 // acosh(1 / 2c) + i pi for c < 1/2, of i acos(-1 / 2c) beyond.
1343 double branchRe = 0.0, branchIm = std::numbers::pi;
1344 if (c < 0.5)
1345 {
1346 const double root = std::sqrt(1.0 - 4.0 * c * c);
1347 branchRe = std::log((1.0 + root) / b.twoC) - root;
1348 }
1349 else
1350 {
1351 branchIm = std::acos(-0.5 / c) + std::sqrt(4.0 * c * c - 1.0);
1352 }
1353 // x + offset stays positive, at least a quarter of x.
1354 b.offset = std::max(kOffset * branchIm - branchRe, -0.75 * from);
1355 b.firstKey = 0;
1356 b.done = !(to > from) || !(from + b.offset > 0.0);
1357 if (!b.done) b.firstKey = key(from + b.offset);
1358 }
1359
1367 static bool step(Builder& b, Cell* cells, double& end) noexcept
1368 {
1369 if (b.done) return false;
1370 b.done = true;
1371 const std::uint64_t bits = (b.firstKey + static_cast<std::uint64_t>(b.count)) << kKeyShift;
1372 const double low = std::bit_cast<double>(bits);
1373 const double high = std::bit_cast<double>(bits + (std::uint64_t(1) << kKeyShift));
1374 if (!(low - b.offset < b.to)) return false;
1375 // The part of the cell the root uses: the first one starts at
1376 // `from`, and its series is about the middle of that part.
1377 const double lowX = std::max(low - b.offset, b.from);
1378 const double highX = b.clipTop ? std::min(high - b.offset, b.to) : high - b.offset;
1379 const double half = 0.5 * (highX - lowX);
1380 const double centre = lowX + half;
1381 const int centres = b.single ? kSingleCentreCount : kCentreCount;
1382 // Nearest anchor in x (their x grows with s), then the one of it
1383 // and its upper neighbour that leaves more room around the cell.
1384 while (b.nearest + 1 < centres
1385 && std::abs(centreX(b, b.nearest + 1) - centre) < std::abs(centreX(b, b.nearest) - centre))
1386 ++b.nearest;
1387 int slot = anchorOf(b, b.nearest);
1388 double room = b.anchorWidth[slot] - std::abs(centre - b.anchor[slot].xHi);
1389 if (room < 2.0 * half && b.nearest + 1 < centres)
1390 {
1391 const int upper = anchorOf(b, b.nearest + 1);
1392 const double upperRoom = b.anchorWidth[upper] - std::abs(centre - b.anchor[upper].xHi);
1393 slot = anchorOf(b, b.nearest); // still held: only the lower centre is replaced
1394 if (upperRoom > room) { slot = upper; room = upperRoom; }
1395 }
1396 if (!(room >= 1.001 * half)) return false;
1397 if (!shift(b.anchor[slot], centre, half, cells[b.count])) return false;
1398 ++b.count;
1399 // Just below the cell's upper edge, so that the rounded sum of a
1400 // drive under it and the offset stays inside the cell.
1401 end = b.clipTop && !(high - b.offset < b.to) ? b.to : high * (1.0 - 0x1p-40) - b.offset;
1402 b.done = b.count >= b.capacity;
1403 return true;
1404 }
1405
1412 static int cells(double c, double from, double to, Cell* cells, double& offset,
1413 std::uint64_t& firstKey, double& end) noexcept
1414 {
1415 Builder b;
1416 start(b, c, from, to);
1417 end = -1.0;
1418 while (step(b, cells, end)) {}
1419 offset = b.offset;
1420 firstKey = b.firstKey;
1421 return b.count;
1422 }
1423
1424 // ---- Single diode: s + c (e^s - 1) = x, either sign --------------------
1425
1432 static double originSingle(double kappa, double* q) noexcept
1433 {
1434 double g[kMaxOrder] {};
1435 seriesSingle(1.0, -kappa, 1.0, 35, g);
1436 for (int i = 0; i < 32; ++i) q[i] = g[i + 1];
1437 double y = 6.0;
1438 for (int k = 34; k <= 35; ++k)
1439 {
1440 const double tail = std::abs(g[k - 1]);
1441 if (tail > 0.0) y = std::min(y, std::pow(kTolerance / tail, 1.0 / (k - 1)));
1442 }
1443 return y;
1444 }
1445
1448 static constexpr double kSingleTableReverse = -1.0, kSingleTableForward = 1.5;
1449
1457 static void singleTableDrives(double c, double& reverse, double& forward) noexcept
1458 {
1459 reverse = kSingleTableReverse + c * std::expm1(kSingleTableReverse);
1460 forward = kSingleTableForward + c * std::expm1(kSingleTableForward);
1461 }
1462
1465 [[nodiscard]] static double singleOffset(double c) noexcept
1466 {
1467 return kOffset * std::numbers::pi + (std::log(c) + 1.0 + c);
1468 }
1469
1476 static void startSingle(Builder& b, double c, double from, double to, double offset,
1477 bool clipTop, int capacity) noexcept
1478 {
1479 b.count = 0;
1480 b.nearest = 0;
1481 b.anchorCentre[0] = b.anchorCentre[1] = -1;
1482 b.twoC = 2.0 * c;
1483 b.c = c;
1484 b.single = true;
1485 b.clipTop = clipTop;
1486 b.capacity = capacity;
1487 b.from = from;
1488 b.to = to;
1489 b.offset = offset;
1490 b.firstKey = 0;
1491 b.done = !(to > from) || !(from + offset > 0.0) || capacity <= 0;
1492 if (!b.done) b.firstKey = key(from + offset);
1493 }
1494
1495private:
1496 static constexpr int kMaxOrder = 40;
1497
1500 static int anchorOf(Builder& b, int m) noexcept
1501 {
1502 for (int i = 0; i < 2; ++i)
1503 if (b.anchorCentre[i] == m) return i;
1504 const int slot = b.anchorCentre[0] <= b.anchorCentre[1] ? 0 : 1;
1505 b.anchorWidth[slot] = b.single ? buildSingle(b.c, kSingleCentres[m], b.anchor[slot])
1506 : build(b.twoC, kCentres[m], b.anchor[slot]);
1507 b.anchorCentre[slot] = m;
1508 return slot;
1509 }
1510
1511 [[nodiscard]] static double centreX(const Builder& b, int m) noexcept
1512 {
1513 return b.single ? kSingleCentres[m].s + b.c * (kSingleCentres[m].expHi - 1.0)
1514 : kCentres[m].s + b.twoC * kCentres[m].sinhHi;
1515 }
1516
1523 static void series(double invD, double feedback, double cosh0, double sinh0, int order, double* g) noexcept
1524 {
1525 double p[kMaxOrder] {}, C[kMaxOrder] {}, S[kMaxOrder] {}; // g' = sum p_n d^n, cosh g, sinh g
1526 C[0] = cosh0;
1527 S[0] = sinh0;
1528 p[0] = invD;
1529 for (int n = 0; n + 1 < order; ++n)
1530 {
1531 double fromS = 0.0, fromC = 0.0;
1532 for (int j = 0; j <= n; ++j)
1533 {
1534 fromS += S[j] * p[n - j];
1535 fromC += C[j] * p[n - j];
1536 }
1537 const double inv = 1.0 / (n + 1);
1538 C[n + 1] = fromS * inv;
1539 S[n + 1] = fromC * inv;
1540 double sum = 0.0;
1541 for (int j = 1; j <= n + 1; ++j) sum += C[j] * p[n + 1 - j];
1542 p[n + 1] = feedback * sum;
1543 }
1544 for (int k = 1; k <= order; ++k) g[k - 1] = p[k - 1] / k;
1545 }
1546
1548 static double build(double twoC, const Centre& m, Expansion& e) noexcept
1549 {
1550 double g[kMaxOrder] {};
1551 const double invD = 1.0 / (1.0 + twoC * m.cosh);
1552 series(invD, -twoC * invD, m.cosh, m.sinhHi, kTerms + 2, g);
1553 // x_m = s_m + 2c (sinh hi + sinh lo): the product and the sum with
1554 // their rounding errors.
1555 const double product = twoC * m.sinhHi;
1556 const double productLow = std::fma(twoC, m.sinhHi, -product) + twoC * m.sinhLo;
1557 const double sum = m.s + product;
1558 const double part = sum - m.s;
1559 const double sumLow = (m.s - (sum - part)) + (product - part);
1560 e.xHi = sum;
1561 e.xLo = sumLow + productLow;
1562 e.s = m.s;
1563 // No further than x_m / 2 and than the root s_m / 2 (to first order).
1564 double width = 0.5 * std::min(sum, m.s / g[0]);
1565 const double reference = kTolerance * 0.5 * m.s;
1566 for (int k = kTerms + 1; k <= kTerms + 2; ++k)
1567 {
1568 const double tail = std::abs(g[k - 1]);
1569 if (tail > 0.0) width = std::min(width, std::pow(reference / tail, 1.0 / k));
1570 }
1571 e.width = width;
1572 e.a[0] = 0.0;
1573 double power = width;
1574 for (int k = 1; k <= kTerms; ++k, power *= width) e.a[k] = g[k - 1] * power;
1575 return width;
1576 }
1577
1584 static void seriesSingle(double invD, double feedback, double exp0, int order, double* g) noexcept
1585 {
1586 double p[kMaxOrder] {}, E[kMaxOrder] {};
1587 E[0] = exp0;
1588 p[0] = invD;
1589 for (int n = 0; n + 1 < order; ++n)
1590 {
1591 double fromE = 0.0;
1592 for (int j = 0; j <= n; ++j) fromE += E[j] * p[n - j];
1593 E[n + 1] = fromE / (n + 1);
1594 double sum = 0.0;
1595 for (int j = 1; j <= n + 1; ++j) sum += E[j] * p[n + 1 - j];
1596 p[n + 1] = feedback * sum;
1597 }
1598 for (int k = 1; k <= order; ++k) g[k - 1] = p[k - 1] / k;
1599 }
1600
1603 static double buildSingle(double c, const ExpCentre& m, Expansion& e) noexcept
1604 {
1605 double g[kMaxOrder] {};
1606 const double invD = 1.0 / (1.0 + c * m.expHi);
1607 seriesSingle(invD, -c * invD, m.expHi, kTerms + 2, g);
1608 // x_m = s_m + c (e^s - 1): the product, the difference and the sum
1609 // with their rounding errors.
1610 const double product = c * m.expHi;
1611 const double productLow = std::fma(c, m.expHi, -product) + c * m.expLo;
1612 const double excess = product - c;
1613 const double excessPart = excess - product;
1614 const double excessLow = (product - (excess - excessPart)) + (-c - excessPart);
1615 const double sum = m.s + excess;
1616 const double part = sum - m.s;
1617 const double sumLow = (m.s - (sum - part)) + (excess - part);
1618 e.xHi = sum;
1619 e.xLo = (sumLow + excessLow) + productLow;
1620 e.s = m.s;
1621 // No further than |x_m| / 2 and than the root s_m / 2 (to first order).
1622 double width = 0.5 * std::min(std::abs(sum), std::abs(m.s) / g[0]);
1623 const double reference = kTolerance * 0.5 * std::abs(m.s);
1624 for (int k = kTerms + 1; k <= kTerms + 2; ++k)
1625 {
1626 const double tail = std::abs(g[k - 1]);
1627 if (tail > 0.0) width = std::min(width, std::pow(reference / tail, 1.0 / k));
1628 }
1629 e.width = width;
1630 e.a[0] = 0.0;
1631 double power = width;
1632 for (int k = 1; k <= kTerms; ++k, power *= width) e.a[k] = g[k - 1] * power;
1633 return width;
1634 }
1635
1641 static bool shift(const Expansion& e, double centre, double half, Cell& cell) noexcept
1642 {
1643 const double invWidth = 1.0 / e.width;
1644 const double tau = ((centre - e.xHi) - e.xLo) * invWidth;
1645 double work[kTerms + 1];
1646 for (int k = 0; k <= kTerms; ++k) work[k] = e.a[k];
1647 // Repeated synthetic division: after pass j, work[j] is the
1648 // coefficient of the power j about tau.
1649 for (int j = 0; j <= kCellTerms + 2; ++j)
1650 for (int i = kTerms - 1; i >= j; --i) work[i] += tau * work[i + 1];
1651 // Root at the centre: s_m plus the linear term with its rounding
1652 // error plus the rest, summed without losing the low part.
1653 const double linear = e.a[1] * tau;
1654 double rest = e.a[kTerms];
1655 for (int k = kTerms - 1; k >= 2; --k) rest = rest * tau + e.a[k];
1656 rest = rest * (tau * tau) + std::fma(e.a[1], tau, -linear);
1657 const double sum = e.s + linear;
1658 const double part = sum - e.s;
1659 const double low = ((e.s - (sum - part)) + (linear - part)) + rest;
1660 cell.centre = centre;
1661 cell.rootHi = sum + low;
1662 cell.rootLo = low - (cell.rootHi - sum);
1663 double power = invWidth;
1664 for (int j = 1; j <= kCellTerms; ++j, power *= invWidth) cell.a[j - 1] = work[j] * power;
1665 const double reach = half * invWidth, reference = kTolerance * 0.5 * std::abs(cell.rootHi);
1666 double term = 1.0;
1667 for (int j = 0; j <= kCellTerms; ++j) term *= reach; // reach to the 17
1668 return std::abs(work[kCellTerms + 1]) * term <= reference
1669 && std::abs(work[kCellTerms + 2]) * (term * reach) <= reference;
1670 }
1671};
1672
1673} // namespace detail
1674
1737template <FloatType T, typename Tree>
1739{
1740public:
1741 explicit DiodePairRoot(Tree& tree, T saturationCurrent = T(2.52e-9),
1742 T idealityTimesVt = T(1.752 * 0.02585)) noexcept
1743 : tree_(tree), is_(saturationCurrent), nvt_(idealityTimesVt),
1744 omega_(&detail::WrightOmega::instance()), exact_(&detail::DiodeOmegaTable::instance()) {}
1745
1746 void setSaturationCurrent(T amps) noexcept { is_ = std::max(amps, T(1e-15)); }
1747 void setIdealityTimesVt(T volts) noexcept { nvt_ = std::max(volts, T(1e-4)); }
1748
1749 void prepare(double sampleRate) noexcept
1750 {
1751 tree_.prepare(sampleRate);
1752 tree_.updatePorts();
1753 tree_.reset();
1754 v_ = 0.0;
1755 // The constants of the circuit as it stands, with their local
1756 // expansions, so that the first sample already finds them.
1757 const double k = 2.0 * tree_.portResistance() * static_cast<double>(is_);
1758 const double nvt = static_cast<double>(nvt_);
1759 if (k != kCached_ || nvt != nvtCached_) updateConstants(k, nvt);
1760 while (localPending_) stepLocal();
1761 }
1762 void reset() noexcept { tree_.reset(); v_ = 0.0; }
1763
1764 void process() noexcept
1765 {
1766 const double a = static_cast<double>(tree_.reflected());
1767 // Non-finite wave (a NaN/Inf source): clear the tree rather than
1768 // leave it in the capacitor states forever.
1769 if (!(std::abs(a) <= kMaxFinite)) [[unlikely]]
1770 {
1771 tree_.reset();
1772 v_ = 0.0;
1773 return;
1774 }
1775 const double k = 2.0 * tree_.portResistance() * static_cast<double>(is_);
1776 const double nvt = static_cast<double>(nvt_);
1777 if (k != kCached_ || nvt != nvtCached_) [[unlikely]]
1778 updateConstants(k, nvt);
1779 else if (localPending_) [[unlikely]]
1780 {
1781 // Constants changed while running: the local expansions wait
1782 // until they have held for kSettle samples, so that a circuit
1783 // whose values move every sample never pays for them, and are
1784 // then built one cell per sample.
1785 if (settle_ < kSettle) ++settle_;
1786 else stepLocal();
1787 }
1788
1789 const double magnitude = std::abs(a);
1790 const double x = magnitude * invNvt_;
1791 if (x < seriesLimit_)
1792 {
1793 // Low drive: the exact reversion series (detail::DiodeSeries).
1794 const double y = x * invBeta_, u = y * y, u2 = u * u, u4 = u2 * u2;
1795 const double p = ((series_[0] + series_[1] * u) + u2 * (series_[2] + series_[3] * u))
1796 + u4 * ((series_[4] + series_[5] * u) + u2 * series_[6]);
1797 const double s = y + (y * u) * p;
1798 tree_.incident(static_cast<T>(std::copysign(s * (2.0 * nvt), a) - a));
1799 v_ = std::copysign(s * nvt, a);
1800 return;
1801 }
1802 if (x < series2Limit_)
1803 {
1804 // Just above it, for c > 1e-4 (where the omega table's
1805 // correction takes many terms or does not reach): the same
1806 // series to y^35, from the tabulated polynomials up to c = 0.02
1807 // and from detail::DiodeLocal::origin() beyond.
1808 const double y = x * invBeta_, u = y * y, u2 = u * u, u4 = u2 * u2, u8 = u4 * u4;
1809 const double* b = series2_;
1810 const double p = ((((b[0] + b[1] * u) + u2 * (b[2] + b[3] * u)) + u4 * ((b[4] + b[5] * u) + u2 * (b[6] + b[7] * u)))
1811 + u8 * (((b[8] + b[9] * u) + u2 * (b[10] + b[11] * u)) + u4 * ((b[12] + b[13] * u) + u2 * (b[14] + b[15] * u))))
1812 + (u8 * u8) * b[16];
1813 const double s = y + (y * u) * p;
1814 tree_.incident(static_cast<T>(std::copysign(s * (2.0 * nvt), a) - a));
1815 v_ = std::copysign(s * nvt, a);
1816 return;
1817 }
1818 if (x < localTo_)
1819 {
1820 // Between the series and the table's short correction: the cell
1821 // that holds x (detail::DiodeLocal), found from the bits of x
1822 // plus the grid's offset.
1823 const auto cell = static_cast<std::size_t>(detail::DiodeLocal::key(x + localOffset_) - localFirstKey_);
1824 const double s = detail::DiodeLocal::evaluate(local_[cell], x);
1825 tree_.incident(static_cast<T>(std::copysign(s * (2.0 * nvt), a) - a));
1826 v_ = std::copysign(s * nvt, a);
1827 return;
1828 }
1829 if (x < kClosedFormLimit) [[likely]]
1830 {
1831 const double s = solveNormalised(x, magnitude);
1832 tree_.incident(static_cast<T>(std::copysign(s * (2.0 * nvt), a) - a));
1833 v_ = std::copysign(s * nvt, a);
1834 return;
1835 }
1836 v_ = solveFarField(a, k, nvt);
1837 tree_.incident(static_cast<T>(2.0 * v_ - a));
1838 }
1839
1841 [[nodiscard]] T getVoltage() const noexcept { return static_cast<T>(v_); }
1842
1843private:
1846 static constexpr double kClosedFormLimit = 1e12;
1848 static constexpr double kMaxFinite = std::numeric_limits<double>::max();
1849
1850 DSPARK_NOINLINE void updateConstants(double k, double nvt) noexcept
1851 {
1852 kCached_ = k;
1853 nvtCached_ = nvt;
1854 invNvt_ = 1.0 / nvt;
1855 invNvt4_ = 4.0 * invNvt_;
1856 c_ = 0.5 * k * invNvt_;
1857 logC_ = std::log(c_);
1858 logC4_ = 4.0 * logC_;
1859 bound_ = 1.0 / (1.0 + 2.0 * c_);
1860 cPlus_ = 1.0 + 2.0 * c_;
1861 mode_ = c_ <= 1e-4 ? Mode::Newton : (c_ <= 0.02 ? Mode::Halley : Mode::Iterate);
1862 c2_ = c_ * c_;
1863 halfC2_ = 0.5 * c2_;
1864 // First node of solveTableWide() whose whole cell has q <= kShortQ,
1865 // r <= kShortR and a root above 1.25 (R and H fall with z): with
1866 // omega(1 + omega) >= c^2 / kShortQ, 1 + omega >= c / sqrt(kShortR)
1867 // and x = z - ln c >= 1.25 there, the omitted terms (largest
1868 // (8/3) q^4 and (27/8) r q^3) total under 1.1e-17.
1869 shortFrom_ = std::numeric_limits<int>::max();
1870 if (mode_ == Mode::Halley)
1871 {
1872 const double wq = 0.5 * (std::sqrt(1.0 + 4.0 * c2_ / kShortQ) - 1.0);
1873 const double wr = c_ / std::sqrt(kShortR) - 1.0;
1874 const double w = std::max({wq, wr, 1e-300});
1875 const double z = std::max(w + std::log(w), 1.25 + logC_);
1876 const double from = std::ceil((z + 0.125 - detail::DiodeOmegaTable::kLo) * 4.0);
1877 shortFrom_ = static_cast<int>(std::clamp(from, 0.0, double(detail::DiodeOmegaTable::kNodes)));
1878 }
1879 // ln c = logC_ + ln(c e^-logC_): the residual, to about 1e-16.
1880 logCLow_ = std::fma(c_, std::exp(-logC_), -1.0);
1881 invBeta_ = bound_;
1882 seriesLimit_ = cPlus_ * detail::DiodeSeries::pair(2.0 * c_ * bound_, series_);
1883 // The table root holds where q = c^2 / (omega (1 + omega)) <= kTableQ:
1884 // above the series limit for c <= 1e-4; from omega(1 + omega) =
1885 // c^2 / kWideTableQ up to c = 0.02, with the correction series of
1886 // solveTableWide() scaled by powers of c^2. In that range the longer
1887 // series takes every drive it reaches above the short one: it costs
1888 // less than the table root with its full correction, and for
1889 // c > 0.0062, where the table starts above the short series, it
1890 // covers the drives between (at c = 0.02 it reaches 1.764 against
1891 // 1.748 nVt). The omega estimate with its correction step would
1892 // cover any remaining gap.
1893 series2Limit_ = seriesLimit_;
1894 tableFrom_ = seriesLimit_;
1895 if (mode_ == Mode::Halley)
1896 {
1897 const double w = 0.5 * (std::sqrt(1.0 + 4.0 * c2_ / kWideTableQ) - 1.0);
1898 const double wideStart = w + std::log(w) - logC_;
1899 series2Limit_ = std::max(seriesLimit_, cPlus_ * detail::DiodeSeries::pairLong(2.0 * c_ * bound_, series2_));
1900 tableFrom_ = std::max(series2Limit_, wideStart);
1901 int o = 0;
1902 for (int j = 0; j < 5; ++j)
1903 {
1904 double scale = 1.0;
1905 for (int m = 0; m <= j; ++m) scale *= c2_;
1906 for (int m = 0; m < 7 - j; ++m, scale *= c2_)
1907 wide_[o++] = kWideCoefficients[j][m] * scale;
1908 }
1909 }
1910 else if (mode_ == Mode::Iterate)
1911 tableFrom_ = std::numeric_limits<double>::infinity();
1912
1913 // Local expansions (detail::DiodeLocal), built in prepare() or once
1914 // these constants have held for kSettle samples. Up to c = 0.02 they
1915 // run from the longer series to the first node with the short
1916 // correction, in place of the table root with its full correction.
1917 // Beyond, from the low-drive series of that constant (built with
1918 // them) to the drive from which the reverse diode's correction is
1919 // short (q <= kShortQ and r <= kShortR), where the table root takes
1920 // over on every node and cell; until they are built the repeated
1921 // Halley steps answer below that drive.
1922 localTo_ = -1.0;
1923 settle_ = 0;
1924 localPending_ = false;
1925 localStarted_ = false;
1926 if (mode_ == Mode::Halley)
1927 {
1928 localFrom_ = series2Limit_;
1929 localGoal_ = (detail::DiodeOmegaTable::kLo + 0.25 * shortFrom_ - 0.125) - logC_;
1930 localPending_ = shortFrom_ < detail::DiodeOmegaTable::kNodes && localGoal_ > localFrom_;
1931 }
1932 else if (mode_ == Mode::Iterate && c_ <= kLocalMaxC)
1933 {
1934 const double wq = 0.5 * (std::sqrt(1.0 + 4.0 * c2_ / kShortQ) - 1.0);
1935 const double wr = c_ / std::sqrt(kShortR) - 1.0;
1936 const double w = std::max(wq, wr);
1937 localFrom_ = 0.0;
1938 localGoal_ = (w + std::log(w)) - logC_;
1939 tableFrom_ = localGoal_;
1940 shortFrom_ = 0;
1941 localPending_ = true;
1942 }
1943 }
1944
1951 DSPARK_NOINLINE void stepLocal() noexcept
1952 {
1953 if (!localStarted_)
1954 {
1955 localStarted_ = true;
1956 if (mode_ == Mode::Iterate)
1957 {
1958 // The low-drive series of this constant, which the tabulated
1959 // polynomials of DiodeSeries do not cover.
1960 series2Limit_ = std::max(seriesLimit_, cPlus_ * detail::DiodeLocal::origin(2.0 * c_ * bound_, series2_));
1961 localFrom_ = series2Limit_;
1962 }
1963 detail::DiodeLocal::start(localBuild_, c_, localFrom_, localGoal_);
1964 localOffset_ = localBuild_.offset;
1965 localFirstKey_ = localBuild_.firstKey;
1966 localPending_ = !localBuild_.done;
1967 return;
1968 }
1969 double end = localTo_;
1970 const bool added = detail::DiodeLocal::step(localBuild_, local_, end);
1971 localTo_ = end;
1972 localPending_ = added && !localBuild_.done;
1973 }
1974
1980 [[nodiscard]] static double byForm(int index, double logValue, double linearValue) noexcept
1981 {
1982 const std::uint64_t mask = std::uint64_t(0)
1983 - static_cast<std::uint64_t>(index >= detail::DiodeOmegaTable::kFirstLogNode);
1984 return std::bit_cast<double>((std::bit_cast<std::uint64_t>(logValue) & mask)
1985 | (std::bit_cast<std::uint64_t>(linearValue) & ~mask));
1986 }
1987
1989 [[nodiscard]] double solveNormalised(double x, double magnitude) const noexcept
1990 {
1991 if (x >= tableFrom_) [[likely]]
1992 {
1993 // 4 (ln c + x) with one rounding. The product is 4 x exactly (the
1994 // factor 4 only moves the exponent), formed from the wave so that
1995 // the table index does not wait for x.
1996 const double z4 = magnitude * invNvt4_ + logC4_;
1997 if (z4 < 4.0 * detail::DiodeOmegaTable::kOctaveMax) [[likely]]
1998 return mode_ == Mode::Newton ? solveTable(x, z4) : solveTableWide(x, z4);
1999 }
2000 const auto& omega = *omega_;
2001 // Both diodes' closed forms.
2002 const double s = (x + omega(logC_ - x)) - omega(logC_ + x);
2003 if (mode_ == Mode::Newton) [[likely]]
2004 {
2005 // One expm1 and one division. With u = e^s, g and g' share the
2006 // factor 1/u, which cancels in the step, and u^2 - 1 = m (2 + m)
2007 // keeps small s free of cancellation.
2008 const double m = std::expm1(s);
2009 const double sh = c_ * (m * (2.0 + m)); // c (u^2 - 1)
2010 const double g = (s - x) * (1.0 + m) + sh; // u g
2011 const double g1 = (cPlus_ + m) + sh; // u g' = u + c (u^2 + 1)
2012 return s - g / g1;
2013 }
2014 return refineHalley(s, x);
2015 }
2016
2026 [[nodiscard]] double solveTable(double x, double z4) const noexcept
2027 {
2028 using Table = detail::DiodeOmegaTable;
2029 if (z4 < 4.0 * Table::kHi)
2030 {
2031 if (!(z4 >= 4.0 * Table::kLo)) return x;
2032 double t = 0.0;
2033 int index = 0;
2034 const auto& n = exact_->node(z4, t, index);
2035 const double rest = Table::poly9Rest(n.p, t);
2036 // q = c^2 R with c^2 applied to the two Estrin halves of R (one
2037 // multiply less on the path), and d = q (1 - h) - q^2 + 1.5 q^3.
2038 const double t2 = t * t;
2039 const double* r = n.r;
2040 const double ra = (r[0] + r[1] * t) + t2 * (r[2] + r[3] * t);
2041 const double rb = (r[4] + r[5] * t) + t2 * (r[6] + r[7] * t);
2042 const double q = c2_ * ra + (c2_ * (t2 * t2)) * rb;
2043 const double h = halfC2_ * (n.h[0] + n.h[1] * t);
2044 const double q2 = q * q;
2045 const double d = (q * (1.0 - h) - q2) + (1.5 * q) * q2;
2046 // Root = base + p0 + rest + d, with the large base + p0 summed
2047 // exactly (|base| > |p0|) so that only the final add rounds.
2048 const double base = byForm(index, -logC_, x);
2049 const double s0 = base + n.p[0];
2050 const double e0 = n.p[0] - (s0 - base);
2051 return s0 + (((rest + e0) - byForm(index, logCLow_, 0.0)) + d);
2052 }
2053 // Above z = 32, q < c^2 / 818: q^2 is below 1e-24 of the root.
2054 double t = 0.0;
2055 const auto& cl = exact_->cell(0.25 * z4, t);
2056 const double r = Table::poly7(cl.r, t);
2057 const double rest = Table::poly9Rest(cl.p, t);
2058 const double s0 = cl.p[0] - logC_;
2059 const double v = s0 - cl.p[0];
2060 const double e0 = (cl.p[0] - (s0 - v)) - (logC_ + v); // two-sum error
2061 return s0 + (((rest + e0) - logCLow_) + c2_ * r);
2062 }
2063
2078 [[nodiscard]] double solveTableWide(double x, double z4) const noexcept
2079 {
2080 using Table = detail::DiodeOmegaTable;
2081 if (z4 < 4.0 * Table::kHi)
2082 {
2083 if (!(z4 >= 4.0 * Table::kLo)) return x;
2084 double t = 0.0;
2085 int index = 0;
2086 const auto& n = exact_->node(z4, t, index);
2087 const double rest = Table::poly9Rest(n.p, t);
2088 const double R = n.r[0] + Table::poly9Rest(n.r, t);
2089 const double t2 = t * t, t4 = t2 * t2;
2090 const double H = ((n.h[0] + n.h[1] * t) + t2 * (n.h[2] + n.h[3] * t))
2091 + t4 * ((n.h[4] + n.h[5] * t) + t2 * n.h[6]);
2092 const double base = byForm(index, -logC_, x);
2093 const double s0 = base + n.p[0];
2094 const double e0 = n.p[0] - (s0 - base);
2095 const double tail = (rest + e0) - byForm(index, logCLow_, 0.0);
2096 if (index >= shortFrom_)
2097 {
2098 // q <= kShortQ and r <= kShortR on this node (see
2099 // updateConstants()): every term past q^3, r q^2 and r^2 q
2100 // stays below 9e-18 of the root, and the correction is three
2101 // multiply-adds deep after R instead of seven.
2102 const double q = c2_ * R, r = c2_ * H;
2103 return s0 + (tail + q * (((1.0 - q) + 1.5 * (q * q)) + r * ((-0.5 + (4.0 / 3.0) * q) + 0.5 * r)));
2104 }
2105 {
2106 const double* a = wide_;
2107 const double R2 = R * R, R4 = R2 * R2, H2 = H * H;
2108 const double B0 = ((a[0] + a[1] * R) + R2 * (a[2] + a[3] * R)) + R4 * ((a[4] + a[5] * R) + R2 * a[6]);
2109 const double B1 = ((a[7] + a[8] * R) + R2 * (a[9] + a[10] * R)) + R4 * (a[11] + a[12] * R);
2110 const double B2 = ((a[13] + a[14] * R) + R2 * (a[15] + a[16] * R)) + R4 * a[17];
2111 const double B3 = (a[18] + a[19] * R) + R2 * (a[20] + a[21] * R);
2112 const double B4 = (a[22] + a[23] * R) + R2 * a[24];
2113 return s0 + (tail + R * ((B0 + H * B1) + H2 * ((B2 + H * B3) + H2 * B4)));
2114 }
2115 }
2116 double t = 0.0;
2117 const auto& cl = exact_->cell(0.25 * z4, t);
2118 const double R = Table::poly7(cl.r, t);
2119 const double rest = Table::poly9Rest(cl.p, t);
2120 const double w = 1.0 - (0.25 * z4 - (cl.p[0] + rest)) * R;
2121 const double q = c2_ * R;
2122 const double s0 = cl.p[0] - logC_;
2123 const double v = s0 - cl.p[0];
2124 const double e0 = (cl.p[0] - (s0 - v)) - (logC_ + v); // two-sum error
2125 if (mode_ == Mode::Iterate)
2126 {
2127 // c > 0.02: q is bounded by kShortQ here, not by c^2 / 818, and
2128 // the short correction is needed in full (r = q w).
2129 const double r = q * w;
2130 const double lead = q - (q * q) * (1.0 - 1.5 * q);
2131 const double cross = (-0.5 + (4.0 / 3.0) * q) + 0.5 * r;
2132 return s0 + (((rest + e0) - logCLow_) + (lead + (q * r) * cross));
2133 }
2134 return s0 + (((rest + e0) - logCLow_) + (q - (q * q) * (1.0 + 0.5 * w)));
2135 }
2136
2140 [[nodiscard]] DSPARK_NOINLINE double refineHalley(double s, double x) const noexcept
2141 {
2142 if (mode_ == Mode::Iterate) s = std::clamp(s, 0.0, x * bound_);
2143 for (int it = 0; it < 32; ++it)
2144 {
2145 const double m = std::expm1(s);
2146 const double sh = c_ * (m * (2.0 + m));
2147 const double g = (s - x) * (1.0 + m) + sh;
2148 const double g1 = (cPlus_ + m) + sh;
2149 const double step = (2.0 * g) * g1 / ((2.0 * g1) * g1 - g * sh);
2150 s -= step;
2151 if (mode_ == Mode::Halley || !(std::abs(step) > 1e-6 * std::abs(s))) break;
2152 }
2153 return s;
2154 }
2155
2157 [[nodiscard]] DSPARK_NOINLINE static double solveFarField(double a, double k, double nvt) noexcept
2158 {
2159 return detail::solveMonotonic(a, nvt * std::asinh(a / k),
2160 [k, nvt, a](double v, double& f, double& fp)
2161 {
2162 // cosh overflows around |x| > 710 in double, far outside any
2163 // solution the bracket allows anyway.
2164 const double x = std::clamp(v / nvt, -700.0, 700.0);
2165 f = v + k * std::sinh(x) - a;
2166 fp = 1.0 + (k / nvt) * std::cosh(x);
2167 });
2168 }
2169
2170 Tree& tree_;
2171 T is_, nvt_;
2172 const detail::WrightOmega* omega_;
2173 const detail::DiodeOmegaTable* exact_;
2174 double v_ = 0.0;
2175 double kCached_ = -1.0, nvtCached_ = -1.0;
2176 double c2_ = 1.0, halfC2_ = 0.5;
2177 double logCLow_ = 0.0;
2178 double logC4_ = 0.0;
2179 double tableFrom_ = 0.0;
2180 static constexpr double kTableQ = 3e-5;
2181 static constexpr double kWideTableQ = 3.5e-3;
2183 static constexpr double kWideCoefficients[5][7] = {
2184 {1.0, -1.0, 1.5, -8.0 / 3.0, 125.0 / 24.0, -54.0 / 5.0, 16807.0 / 720.0},
2185 {-0.5, 4.0 / 3.0, -27.0 / 8.0, 128.0 / 15.0, -3125.0 / 144.0, 1944.0 / 35.0, 0.0},
2186 {0.5, -25.0 / 12.0, 85.0 / 12.0, -8057.0 / 360.0, 5451.0 / 80.0, 0.0, 0.0},
2187 {-0.625, 3.5, -1057.0 / 72.0, 4927.0 / 90.0, 0.0, 0.0, 0.0},
2188 {0.875, -6.125, 485.0 / 16.0, 0.0, 0.0, 0.0, 0.0}};
2189 double wide_[25] {};
2192 static constexpr double kShortQ = 4.05e-5, kShortR = 1.47e-5;
2193 int shortFrom_ = std::numeric_limits<int>::max();
2194 enum class Mode { Newton, Halley, Iterate };
2195 double invNvt_ = 1.0, c_ = 1.0, logC_ = 0.0, bound_ = 1.0, cPlus_ = 3.0;
2196 double invNvt4_ = 4.0;
2197 double invBeta_ = 1.0, seriesLimit_ = -1.0;
2198 double series_[7] {};
2199 double series2Limit_ = -1.0;
2200 double series2_[17] {};
2201 Mode mode_ = Mode::Iterate;
2204 static constexpr double kLocalMaxC = 1e6;
2205 static constexpr int kSettle = 256;
2206 double localTo_ = -1.0;
2207 double localFrom_ = 0.0, localGoal_ = 0.0;
2208 int settle_ = 0;
2209 bool localPending_ = false;
2210 bool localStarted_ = false;
2211 detail::DiodeLocal::Builder localBuild_;
2212 double localOffset_ = 0.0;
2213 std::uint64_t localFirstKey_ = 0;
2214 detail::DiodeLocal::Cell local_[detail::DiodeLocal::kMaxCells];
2215};
2216
2269template <FloatType T, typename Tree>
2271{
2272public:
2273 explicit DiodeRoot(Tree& tree, T saturationCurrent = T(2.52e-9),
2274 T idealityTimesVt = T(1.752 * 0.02585)) noexcept
2275 : tree_(tree), is_(saturationCurrent), nvt_(idealityTimesVt),
2276 omega_(&detail::WrightOmega::instance()), exact_(&detail::DiodeOmegaTable::instance()) {}
2277
2278 void setSaturationCurrent(T amps) noexcept { is_ = std::max(amps, T(1e-15)); }
2279 void setIdealityTimesVt(T volts) noexcept { nvt_ = std::max(volts, T(1e-4)); }
2280
2281 void prepare(double sampleRate) noexcept
2282 {
2283 tree_.prepare(sampleRate);
2284 tree_.updatePorts();
2285 tree_.reset();
2286 v_ = 0.0;
2287 // The constants of the circuit as it stands, with their local
2288 // expansions, so that the first sample already finds them.
2289 const double k = tree_.portResistance() * static_cast<double>(is_);
2290 const double nvt = static_cast<double>(nvt_);
2291 if (k != kCached_ || nvt != nvtCached_) updateConstants(k, nvt);
2292 while (localPending_) stepLocal();
2293 }
2294 void reset() noexcept { tree_.reset(); v_ = 0.0; }
2295
2296 void process() noexcept
2297 {
2298 const double a = static_cast<double>(tree_.reflected());
2299 if (!std::isfinite(a)) [[unlikely]]
2300 {
2301 tree_.reset();
2302 v_ = 0.0;
2303 return;
2304 }
2305 const double k = tree_.portResistance() * static_cast<double>(is_);
2306 const double nvt = static_cast<double>(nvt_);
2307 if (k != kCached_ || nvt != nvtCached_) [[unlikely]]
2308 updateConstants(k, nvt);
2309 else if (localPending_) [[unlikely]]
2310 {
2311 // Constants changed while running: the local expansions wait
2312 // until they have held for kSettle samples, so that a circuit
2313 // whose values move every sample never pays for them, and are
2314 // then built one cell per sample.
2315 if (settle_ < kSettle) ++settle_;
2316 else stepLocal();
2317 }
2318
2319 const double x = a * invNvt_;
2320 if (std::abs(x) < seriesLimit_)
2321 {
2322 // Low drive: the exact reversion series (detail::DiodeSeries).
2323 const double y = x * invBeta_, y2 = y * y, y4 = y2 * y2, y8 = y4 * y4;
2324 const double* d = series_;
2325 const double q = (((d[0] + d[1] * y) + y2 * (d[2] + d[3] * y))
2326 + y4 * ((d[4] + d[5] * y) + y2 * (d[6] + d[7] * y)))
2327 + y8 * (((d[8] + d[9] * y) + y2 * (d[10] + d[11] * y))
2328 + y4 * (d[12] + d[13] * y));
2329 v_ = (y + y2 * q) * nvt;
2330 }
2331 else if (seriesLimit_ > 0.0 && x * 4.0 + logCc4_ < 4.0 * detail::DiodeOmegaTable::kOctaveMax) [[likely]]
2332 {
2333 v_ = solveTable(x, x * 4.0 + logCc4_) * nvt;
2334 }
2335 else if (std::abs(x) < 1e12)
2336 {
2337 // 4 (ln c + c + x) with one rounding, formed from the wave so
2338 // that the table index does not wait for x.
2339 v_ = (large_ ? solveLarge(x, a * invNvt4_ + logCc4_) : solveIterate(x)) * nvt;
2340 }
2341 else
2342 {
2343 v_ = solveFarField(a, k, nvt);
2344 }
2345
2346 tree_.incident(static_cast<T>(2.0 * v_ - a));
2347 }
2348
2350 [[nodiscard]] T getVoltage() const noexcept { return static_cast<T>(v_); }
2351
2352private:
2353 DSPARK_NOINLINE void updateConstants(double k, double nvt) noexcept
2354 {
2355 kCached_ = k;
2356 nvtCached_ = nvt;
2357 invNvt_ = 1.0 / nvt;
2358 c_ = k * invNvt_;
2359 logC_ = std::log(c_);
2360 steps_ = c_ <= 1e-4 ? 0 : (c_ <= 10.0 ? 1 : 32);
2361 logCc4_ = 4.0 * (logC_ + c_);
2362 logCLow_ = std::fma(c_, std::exp(-logC_), -1.0);
2363 invNvt4_ = 4.0 * invNvt_;
2364 invBeta_ = 1.0 / (1.0 + c_);
2365 seriesLimit_ = (1.0 + c_) * detail::DiodeSeries::single(c_ * invBeta_, series_);
2366
2367 // Beyond the constants the tabulated series cover (c above 0.0417)
2368 // the table root answers outside two drives that depend on the
2369 // constant (detail::DiodeLocal::singleTableDrives()), and up to
2370 // kLocalMaxC a low-drive series and cells built for the constant
2371 // (detail::DiodeLocal) answer between them: in prepare(), or once
2372 // these constants have held for kSettle samples.
2373 large_ = !(seriesLimit_ > 0.0) && c_ <= kTableMaxC;
2374 longLimit_ = 0.0;
2375 forwardTo_ = -1.0;
2376 reverseFrom_ = std::numeric_limits<double>::infinity();
2377 reverseTo_ = -std::numeric_limits<double>::infinity();
2378 reverseCount_ = 0;
2379 settle_ = 0;
2380 localPhase_ = 0;
2381 localPending_ = large_ && c_ <= kLocalMaxC;
2382 if (large_)
2383 {
2384 // ln c to twice the precision, and what logCc4_ leaves out of
2385 // 4 (ln c + c).
2386 double eh = 0.0, el = 0.0;
2387 detail::expTwice(logC_, eh, el);
2388 logCLow_ = ((c_ - eh) - el) / eh;
2389 const double sum = logC_ + c_;
2390 const double part = sum - logC_;
2391 logCcLow4_ = 4.0 * (((logC_ - (sum - part)) + (c_ - part)) + logCLow_);
2392 detail::DiodeLocal::singleTableDrives(c_, tableReverse_, tableForward_);
2393 }
2394 }
2395
2402 DSPARK_NOINLINE void stepLocal() noexcept
2403 {
2404 using Local = detail::DiodeLocal;
2405 if (localPhase_ == 0)
2406 {
2407 const double limit = (1.0 + c_) * Local::originSingle(c_ * invBeta_, long_);
2408 localOffset_ = Local::singleOffset(c_);
2409 Local::startSingle(localBuild_, c_, tableReverse_, -limit, localOffset_, true, Local::kSingleMaxCells);
2410 reverseFirstKey_ = localBuild_.firstKey;
2411 longLimit_ = limit;
2412 localPhase_ = 1;
2413 return;
2414 }
2415 if (localPhase_ == 1)
2416 {
2417 double end = reverseTo_;
2418 if (Local::step(localBuild_, local_, end))
2419 {
2420 reverseFrom_ = tableReverse_;
2421 reverseTo_ = end;
2422 reverseCount_ = localBuild_.count;
2423 if (!localBuild_.done) return;
2424 }
2425 // Below the origin is done: above it, in the room that is left.
2426 Local::startSingle(localBuild_, c_, longLimit_, tableForward_, localOffset_, false,
2427 Local::kSingleMaxCells - reverseCount_);
2428 forwardFirstKey_ = localBuild_.firstKey;
2429 localPhase_ = 2;
2430 localPending_ = !localBuild_.done;
2431 return;
2432 }
2433 double end = forwardTo_;
2434 const bool added = Local::step(localBuild_, local_ + reverseCount_, end);
2435 forwardTo_ = end;
2436 localPending_ = added && !localBuild_.done;
2437 }
2438
2442 [[nodiscard]] double solveLarge(double x, double z4) const noexcept
2443 {
2444 using Local = detail::DiodeLocal;
2445 if (std::abs(x) < longLimit_)
2446 {
2447 // s = y + y^2 (q_0 + q_1 y + ... + q_31 y^31).
2448 const double y = x * invBeta_;
2449 const double* q = long_;
2450 const double y2 = y * y, y4 = y2 * y2, y8 = y4 * y4;
2451 const double q0 = (q[0] + q[1] * y) + y2 * (q[2] + q[3] * y);
2452 const double q1 = (q[4] + q[5] * y) + y2 * (q[6] + q[7] * y);
2453 const double q2 = (q[8] + q[9] * y) + y2 * (q[10] + q[11] * y);
2454 const double q3 = (q[12] + q[13] * y) + y2 * (q[14] + q[15] * y);
2455 const double q4 = (q[16] + q[17] * y) + y2 * (q[18] + q[19] * y);
2456 const double q5 = (q[20] + q[21] * y) + y2 * (q[22] + q[23] * y);
2457 const double q6 = (q[24] + q[25] * y) + y2 * (q[26] + q[27] * y);
2458 const double q7 = (q[28] + q[29] * y) + y2 * (q[30] + q[31] * y);
2459 const double low = (q0 + y4 * q1) + y8 * (q2 + y4 * q3);
2460 const double high = (q4 + y4 * q5) + y8 * (q6 + y4 * q7);
2461 return y + y2 * (low + (y8 * y8) * high);
2462 }
2463 if (x > 0.0)
2464 {
2465 if (x < forwardTo_)
2466 {
2467 const auto cell = static_cast<std::size_t>(Local::key(x + localOffset_) - forwardFirstKey_);
2468 return Local::evaluate(local_[static_cast<std::size_t>(reverseCount_) + cell], x);
2469 }
2470 if (x >= tableForward_) return solveTableLarge(x, z4);
2471 }
2472 else
2473 {
2474 if (x >= reverseFrom_ && x < reverseTo_)
2475 {
2476 const auto cell = static_cast<std::size_t>(Local::key(x + localOffset_) - reverseFirstKey_);
2477 return Local::evaluate(local_[cell], x);
2478 }
2479 if (x <= tableReverse_) return solveTableLarge(x, z4);
2480 }
2481 return solveIterate(x);
2482 }
2483
2487 [[nodiscard]] DSPARK_NOINLINE static double solveFarField(double a, double k, double nvt) noexcept
2488 {
2489 const double seed = (a > 0.0) ? nvt * std::log1p(a / k) : a;
2490 return detail::solveMonotonic(a, seed, [k, nvt, a](double v, double& f, double& fp)
2491 {
2492 const double xx = std::clamp(v / nvt, -700.0, 700.0);
2493 f = v + k * std::expm1(xx) - a;
2494 fp = 1.0 + (k / nvt) * std::exp(xx);
2495 });
2496 }
2497
2501 [[nodiscard]] DSPARK_NOINLINE double solveIterate(double x) const noexcept
2502 {
2503 double s = x + c_ - (*omega_)(logC_ + x + c_);
2504 // x + c with its rounding error, for the residual below s = -0.7.
2505 const double sum = x + c_;
2506 const double part = sum - x;
2507 const double sumLow = (x - (sum - part)) + (c_ - part);
2508 for (int it = 0; it <= steps_; ++it)
2509 {
2510 double e = 0.0, g = 0.0; // c e^s = g' - 1 = g'', residual
2511 if (s < -0.7)
2512 {
2513 // s + c e^s - (x + c): c (e^s - 1) would lose what c e^s
2514 // holds below the last place of c.
2515 e = c_ * std::exp(s);
2516 g = ((s - sum) - sumLow) + e;
2517 }
2518 else
2519 {
2520 const double m = std::expm1(s);
2521 e = c_ * (1.0 + m);
2522 g = (s - x) + c_ * m;
2523 }
2524 const double g1 = 1.0 + e;
2525 if (steps_ == 0)
2526 {
2527 s -= g / g1;
2528 break;
2529 }
2530 const double step = (2.0 * g) * g1 / ((2.0 * g1) * g1 - g * e);
2531 s -= step;
2532 if (steps_ == 1 || !(std::abs(step) > 1e-6 * std::abs(s))) break;
2533 }
2534 return s;
2535 }
2536
2549 [[nodiscard]] double solveTableLarge(double x, double z4) const noexcept
2550 {
2551 using Table = detail::DiodeOmegaTable;
2552 if (!(z4 < 4.0 * Table::kOctaveMax)) return solveIterate(x);
2553 const double x4 = 4.0 * x;
2554 const double part = z4 - x4;
2555 const double dz = ((x4 - (z4 - part)) + (logCc4_ - part)) + logCcLow4_;
2556 if (z4 < 4.0 * Table::kHi)
2557 {
2558 if (!(z4 >= 4.0 * Table::kLo)) return x + c_;
2559 double t = 0.0;
2560 int index = 0;
2561 const auto& n = exact_->node(z4, t, index);
2562 // The small terms are gathered apart, so that only the
2563 // polynomial and two sums follow the node.
2564 const double extra = dz * (n.p[1] + n.p[2] * (2.0 * t + dz)) + exact_->nodeLow(index);
2565 const double rest = Table::poly9Rest(n.p, t);
2566 if (index < Table::kFirstLogNode)
2567 {
2568 const double sum = x + c_; // |x| > c wherever z < 0
2569 const double low = c_ - (sum - x);
2570 const double s0 = sum + n.p[0];
2571 const double v = s0 - sum;
2572 const double e0 = (sum - (s0 - v)) + (n.p[0] - v);
2573 return s0 + (rest + ((e0 + low) + extra));
2574 }
2575 const double s0 = n.p[0] - logC_;
2576 const double v = s0 - n.p[0];
2577 const double e0 = (n.p[0] - (s0 - v)) - (logC_ + v);
2578 return s0 + (rest + ((e0 - logCLow_) + extra));
2579 }
2580 double t = 0.0, scale = 0.0, p0Low = 0.0;
2581 const auto& cl = exact_->cell(0.25 * z4, t, scale, p0Low);
2582 const double dt = (0.25 * dz) * scale;
2583 const double extra = dt * (cl.p[1] + cl.p[2] * (2.0 * t + dt)) + p0Low;
2584 const double rest = Table::poly9Rest(cl.p, t);
2585 const double s0 = cl.p[0] - logC_;
2586 const double v = s0 - cl.p[0];
2587 const double e0 = (cl.p[0] - (s0 - v)) - (logC_ + v);
2588 return s0 + (rest + ((e0 - logCLow_) + extra));
2589 }
2590
2598 [[nodiscard]] double solveTable(double x, double z4) const noexcept
2599 {
2600 using Table = detail::DiodeOmegaTable;
2601 if (z4 < 4.0 * Table::kHi)
2602 {
2603 if (!(z4 >= 4.0 * Table::kLo)) return x + c_;
2604 double t = 0.0;
2605 int index = 0;
2606 const auto& n = exact_->node(z4, t, index);
2607 const double rest = Table::poly9Rest(n.p, t);
2608 if (index < Table::kFirstLogNode)
2609 {
2610 const double s0 = x + n.p[0]; // |x| > omega
2611 const double e0 = n.p[0] - (s0 - x);
2612 return s0 + ((rest + e0) + c_);
2613 }
2614 const double s0 = n.p[0] - logC_; // -ln c > |ln omega|
2615 const double e0 = n.p[0] - (s0 + logC_);
2616 return s0 + ((rest + e0) - logCLow_);
2617 }
2618 double t = 0.0;
2619 const auto& cl = exact_->cell(0.25 * z4, t);
2620 const double rest = Table::poly9Rest(cl.p, t);
2621 const double s0 = cl.p[0] - logC_;
2622 const double v = s0 - cl.p[0];
2623 const double e0 = (cl.p[0] - (s0 - v)) - (logC_ + v); // two-sum error
2624 return s0 + ((rest + e0) - logCLow_);
2625 }
2626
2627 Tree& tree_;
2628 T is_, nvt_;
2629 const detail::WrightOmega* omega_;
2630 const detail::DiodeOmegaTable* exact_;
2631 double v_ = 0.0;
2632 double kCached_ = -1.0, nvtCached_ = -1.0;
2633 double invNvt_ = 1.0, c_ = 1.0, logC_ = 0.0;
2634 double logCc4_ = 0.0, logCLow_ = 0.0;
2635 double invNvt4_ = 4.0, logCcLow4_ = 0.0;
2636 double invBeta_ = 1.0, seriesLimit_ = -1.0;
2637 double series_[14] {};
2638 int steps_ = 1;
2644 static constexpr double kTableMaxC = 1e7;
2645 static constexpr double kLocalMaxC = 1e5;
2646 static constexpr int kSettle = 256;
2647 bool large_ = false;
2648 bool localPending_ = false;
2649 int localPhase_ = 0;
2650 int settle_ = 0;
2651 int reverseCount_ = 0;
2652 double longLimit_ = 0.0;
2653 double tableForward_ = 0.0, tableReverse_ = 0.0;
2654 double forwardTo_ = -1.0;
2655 double reverseFrom_ = std::numeric_limits<double>::infinity();
2656 double reverseTo_ = -std::numeric_limits<double>::infinity();
2657 double localOffset_ = 0.0;
2658 std::uint64_t forwardFirstKey_ = 0, reverseFirstKey_ = 0;
2659 double long_[32] {};
2660 detail::DiodeLocal::Builder localBuild_;
2661 detail::DiodeLocal::Cell local_[detail::DiodeLocal::kSingleMaxCells];
2662};
2663
2664// ============================================================================
2665// R-type adaptor (arbitrary topologies)
2666// ============================================================================
2667
2683template <FloatType T, typename... Children>
2685{
2686 template <FloatType> friend class ToneStackFMV;
2687public:
2688 static constexpr int kNumPorts = static_cast<int>(sizeof...(Children)) + 1;
2689 static constexpr int kMaxNodes = 12;
2690 static_assert(sizeof...(Children) >= 1, "RType needs at least one child");
2691
2697 RType(const std::array<std::pair<int, int>, static_cast<size_t>(kNumPorts)>& portNodes,
2698 int numNodes, Children&... children) noexcept
2699 : children_(children...), portNodes_(portNodes),
2700 numNodes_(std::clamp(numNodes, 1, kMaxNodes))
2701 {
2702 assert(numNodes >= 1 && numNodes <= kMaxNodes);
2703 // Release-safe node sanitising: an out-of-range node index would
2704 // stamp the conductance/RHS arrays out of bounds. Clamp into
2705 // [-1, numNodes_-1] (-1 = ground); a clamped topology is wrong but
2706 // cannot corrupt memory.
2707 for (auto& [p, m] : portNodes_)
2708 {
2709 assert(p >= -1 && p < numNodes_ && m >= -1 && m < numNodes_);
2710 p = std::clamp(p, -1, numNodes_ - 1);
2711 m = std::clamp(m, -1, numNodes_ - 1);
2712 }
2713 }
2714
2715 void prepare(double sampleRate) noexcept
2716 {
2717 std::apply([&](auto&... ch) { (ch.prepare(sampleRate), ...); }, children_);
2718 }
2719
2720 void updatePorts() noexcept
2721 {
2722 std::apply([&](auto&... ch) { (ch.updatePorts(), ...); }, children_);
2723
2724 // Gather child port resistances (port 0 resolved by adaptation).
2725 {
2726 int i = 1;
2727 std::apply([&](auto&... ch)
2728 { ((portR_[static_cast<size_t>(i++)] = ch.portResistance()), ...); },
2729 children_);
2730 }
2731
2732 // 1) Thevenin resistance looking into the network from port 0:
2733 // assemble MNA without port 0, inject 1 A across its nodes.
2734 assembleConductance(false);
2735 factor();
2736 double rhs[kMaxNodes] = {};
2737 stampCurrent(rhs, 0, 1.0);
2738 solve(rhs);
2739 double rth = portVoltage(rhs, 0);
2740 portR_[0] = std::clamp(rth, 1e-6, 1e12);
2741
2742 // 2) Full MNA with every port loaded; S = 2M - I where column j of M
2743 // is the port-voltage response to a_j = 1 (Norton: 1/R_j).
2744 assembleConductance(true);
2745 factor();
2746 for (int j = 0; j < kNumPorts; ++j)
2747 {
2748 double v[kMaxNodes] = {};
2749 stampCurrent(v, j, 1.0 / portR_[static_cast<size_t>(j)]);
2750 solve(v);
2751 for (int i = 0; i < kNumPorts; ++i)
2752 {
2753 const double m = portVoltage(v, i);
2754 s_[static_cast<size_t>(i)][static_cast<size_t>(j)] =
2755 2.0 * m - (i == j ? 1.0 : 0.0);
2756 }
2757 }
2758 // Adaptation leaves no instantaneous reflection at the up port.
2759 s_[0][0] = 0.0;
2760 }
2761
2762 void reset() noexcept
2763 {
2764 std::apply([&](auto&... ch) { (ch.reset(), ...); }, children_);
2765 a_.fill(0.0);
2766 }
2767
2768 [[nodiscard]] double portResistance() const noexcept { return portR_[0]; }
2769
2770 [[nodiscard]] T reflected() noexcept
2771 {
2772 int i = 1;
2773 std::apply([&](auto&... ch)
2774 { ((a_[static_cast<size_t>(i++)] = static_cast<double>(ch.reflected())), ...); },
2775 children_);
2776 double b0 = 0.0;
2777 for (int j = 1; j < kNumPorts; ++j)
2778 b0 += s_[0][static_cast<size_t>(j)] * a_[static_cast<size_t>(j)];
2779 return static_cast<T>(b0);
2780 }
2781
2782 void incident(T aUp) noexcept
2783 {
2784 a_[0] = static_cast<double>(aUp);
2785 int i = 1;
2786 std::apply([&](auto&... ch)
2787 {
2788 ((ch.incident(static_cast<T>(rowDot(i))), ++i), ...);
2789 },
2790 children_);
2791 }
2792
2793private:
2794 // Preserve a topology-proven zero-current voltage mode after the nodal
2795 // solve: S*v = v. For the FMV network the source and three coupling
2796 // capacitors share a common DC voltage; every resistor has zero voltage.
2797 // Correcting only the final nonzero column removes factorization roundoff
2798 // in this identity without adding arithmetic to sample processing.
2799 void preserveDcMode(const std::array<double, static_cast<size_t>(kNumPorts)>& mode) noexcept
2800 {
2801 int pivot = kNumPorts - 1;
2802 while (pivot > 0 && mode[static_cast<size_t>(pivot)] == 0.0) --pivot;
2803 if (pivot == 0) return; // Keep the adapted up-port reflection at zero.
2804 for (int i = 0; i < kNumPorts; ++i)
2805 {
2806 double remainder = 0.0;
2807 for (int j = 0; j < kNumPorts; ++j)
2808 if (j != pivot)
2809 remainder += s_[static_cast<size_t>(i)][static_cast<size_t>(j)]
2810 * mode[static_cast<size_t>(j)];
2811 s_[static_cast<size_t>(i)][static_cast<size_t>(pivot)] =
2812 (mode[static_cast<size_t>(i)] - remainder) / mode[static_cast<size_t>(pivot)];
2813 }
2814 }
2815
2816 [[nodiscard]] double rowDot(int row) const noexcept
2817 {
2818 double acc = 0.0;
2819 for (int j = 0; j < kNumPorts; ++j)
2820 acc += s_[static_cast<size_t>(row)][static_cast<size_t>(j)] * a_[static_cast<size_t>(j)];
2821 return acc;
2822 }
2823
2824 void assembleConductance(bool includePort0) noexcept
2825 {
2826 for (auto& row : g_) row.fill(0.0);
2827 for (int j = includePort0 ? 0 : 1; j < kNumPorts; ++j)
2828 {
2829 const double g = 1.0 / portR_[static_cast<size_t>(j)];
2830 const int p = portNodes_[static_cast<size_t>(j)].first;
2831 const int m = portNodes_[static_cast<size_t>(j)].second;
2832 if (p >= 0) g_[static_cast<size_t>(p)][static_cast<size_t>(p)] += g;
2833 if (m >= 0) g_[static_cast<size_t>(m)][static_cast<size_t>(m)] += g;
2834 if (p >= 0 && m >= 0)
2835 {
2836 g_[static_cast<size_t>(p)][static_cast<size_t>(m)] -= g;
2837 g_[static_cast<size_t>(m)][static_cast<size_t>(p)] -= g;
2838 }
2839 }
2840 }
2841
2842 void stampCurrent(double* rhs, int port, double amps) const noexcept
2843 {
2844 const int p = portNodes_[static_cast<size_t>(port)].first;
2845 const int m = portNodes_[static_cast<size_t>(port)].second;
2846 if (p >= 0) rhs[p] += amps;
2847 if (m >= 0) rhs[m] -= amps;
2848 }
2849
2850 [[nodiscard]] double portVoltage(const double* v, int port) const noexcept
2851 {
2852 const int p = portNodes_[static_cast<size_t>(port)].first;
2853 const int m = portNodes_[static_cast<size_t>(port)].second;
2854 return (p >= 0 ? v[p] : 0.0) - (m >= 0 ? v[m] : 0.0);
2855 }
2856
2858 void factor() noexcept
2859 {
2860 const int n = numNodes_;
2861 for (int i = 0; i < n; ++i)
2862 {
2863 for (int j = 0; j < n; ++j)
2864 lu_[static_cast<size_t>(i)][static_cast<size_t>(j)] =
2865 g_[static_cast<size_t>(i)][static_cast<size_t>(j)];
2866 piv_[static_cast<size_t>(i)] = i;
2867 }
2868 for (int k = 0; k < n; ++k)
2869 {
2870 int p = k;
2871 for (int i = k + 1; i < n; ++i)
2872 if (std::abs(lu_[static_cast<size_t>(i)][static_cast<size_t>(k)])
2873 > std::abs(lu_[static_cast<size_t>(p)][static_cast<size_t>(k)]))
2874 p = i;
2875 if (p != k)
2876 {
2877 std::swap(lu_[static_cast<size_t>(p)], lu_[static_cast<size_t>(k)]);
2878 std::swap(piv_[static_cast<size_t>(p)], piv_[static_cast<size_t>(k)]);
2879 }
2880 double d = lu_[static_cast<size_t>(k)][static_cast<size_t>(k)];
2881 if (std::abs(d) < 1e-300)
2882 d = (d >= 0.0 ? 1e-300 : -1e-300);
2883 const double invD = 1.0 / d;
2884 for (int i = k + 1; i < n; ++i)
2885 {
2886 const double f = lu_[static_cast<size_t>(i)][static_cast<size_t>(k)] * invD;
2887 lu_[static_cast<size_t>(i)][static_cast<size_t>(k)] = f;
2888 for (int j = k + 1; j < n; ++j)
2889 lu_[static_cast<size_t>(i)][static_cast<size_t>(j)]
2890 -= f * lu_[static_cast<size_t>(k)][static_cast<size_t>(j)];
2891 }
2892 }
2893 }
2894
2896 void solve(double* rhs) const noexcept
2897 {
2898 const int n = numNodes_;
2899 double y[kMaxNodes];
2900 for (int i = 0; i < n; ++i)
2901 y[i] = rhs[piv_[static_cast<size_t>(i)]];
2902 for (int i = 0; i < n; ++i)
2903 for (int j = 0; j < i; ++j)
2904 y[i] -= lu_[static_cast<size_t>(i)][static_cast<size_t>(j)] * y[j];
2905 for (int i = n - 1; i >= 0; --i)
2906 {
2907 for (int j = i + 1; j < n; ++j)
2908 y[i] -= lu_[static_cast<size_t>(i)][static_cast<size_t>(j)] * y[j];
2909 double d = lu_[static_cast<size_t>(i)][static_cast<size_t>(i)];
2910 if (std::abs(d) < 1e-300)
2911 d = (d >= 0.0 ? 1e-300 : -1e-300);
2912 y[i] /= d;
2913 }
2914 for (int i = 0; i < n; ++i)
2915 rhs[i] = y[i];
2916 }
2917
2918 std::tuple<Children&...> children_;
2919 std::array<std::pair<int, int>, static_cast<size_t>(kNumPorts)> portNodes_;
2920 int numNodes_;
2921
2922 std::array<double, static_cast<size_t>(kNumPorts)> portR_ {};
2923 std::array<double, static_cast<size_t>(kNumPorts)> a_ {};
2924 std::array<std::array<double, static_cast<size_t>(kNumPorts)>,
2925 static_cast<size_t>(kNumPorts)> s_ {};
2926
2927 std::array<std::array<double, kMaxNodes>, kMaxNodes> g_ {};
2928 std::array<std::array<double, kMaxNodes>, kMaxNodes> lu_ {};
2929 std::array<int, kMaxNodes> piv_ {};
2930};
2931
2932// ============================================================================
2933// Fender '59 Bassman FMV tone stack (reference R-type circuit)
2934// ============================================================================
2935
2951template <FloatType T>
2953{
2954public:
2959 explicit ToneStackFMV(double sourceResistance = 1e3, double loadResistance = 1e6)
2960 : rOut_(static_cast<T>(sourceResistance)), c1_(T(0.25e-9)),
2961 r1Top_(T(125e3)), r1Bot_(T(125e3)), r4_(T(56e3)), c2_(T(20e-9)),
2962 r2_(T(500e3)), c3_(T(20e-9)), r3Top_(T(12.5e3)), r3Bot_(T(12.5e3)),
2963 rLoad_(static_cast<T>(loadResistance)),
2964 rtype_({ { { kSrc, -1 }, // port 0: ideal source root
2965 { kSrc, kVi }, // rOut
2966 { kVi, kA }, // C1
2967 { kA, kVo }, // (1-t) R1
2968 { kVo, kB }, // t R1
2969 { kVi, kS }, // R4
2970 { kS, kB }, // C2
2971 { kB, kC }, // l R2 (rheostat)
2972 { kS, kW }, // C3 to the middle wiper
2973 { kC, kW }, // (1-m) R3
2974 { kW, -1 }, // m R3 to ground
2975 { kVo, -1 } } }, // grid load
2976 kNumNodes,
2977 rOut_, c1_, r1Top_, r1Bot_, r4_, c2_, r2_, c3_, r3Top_, r3Bot_, rLoad_),
2978 root_(rtype_)
2979 {
2980 }
2981
2983 void prepare(double sampleRate) noexcept
2984 {
2985 root_.prepare(sampleRate);
2986 setControls(treble_, bass_, middle_);
2987 }
2988
2990 void reset() noexcept { root_.reset(); }
2991
3001 void copyStateFrom(const ToneStackFMV& source, T inputOffset = T(0)) noexcept
3002 {
3003 c1_ = source.c1_;
3004 c2_ = source.c2_;
3005 c3_ = source.c3_;
3006 if (inputOffset != T(0))
3007 {
3008 c1_.offsetVoltage(inputOffset);
3009 c2_.offsetVoltage(inputOffset);
3010 c3_.offsetVoltage(inputOffset);
3011 }
3012 }
3013
3020 void setControls(T treble, T bass, T middle) noexcept
3021 {
3022 treble_ = std::clamp(treble, T(0), T(1));
3023 bass_ = std::clamp(bass, T(0), T(1));
3024 middle_ = std::clamp(middle, T(0), T(1));
3025
3026 const double t = static_cast<double>(treble_);
3027 const double l = static_cast<double>(bass_) * static_cast<double>(bass_);
3028 const double m = static_cast<double>(middle_);
3029 constexpr double kRmin = 0.5; // keeps the node matrix well-posed
3030
3031 r1Top_.setResistance(static_cast<T>((1.0 - t) * 250e3 + kRmin));
3032 r1Bot_.setResistance(static_cast<T>(t * 250e3 + kRmin));
3033 r2_.setResistance(static_cast<T>(l * 1e6 + kRmin));
3034 r3Top_.setResistance(static_cast<T>((1.0 - m) * 25e3 + kRmin));
3035 r3Bot_.setResistance(static_cast<T>(m * 25e3 + kRmin));
3036 rtype_.updatePorts(); // rebuild scattering, keep states
3037 rtype_.preserveDcMode({1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0});
3038 }
3039
3041 [[nodiscard]] T processSample(T input) noexcept
3042 {
3043 root_.setVoltage(input);
3044 root_.process();
3045 return rLoad_.getVoltage();
3046 }
3047
3061 {
3062 double a[3][3];
3063 double b[3];
3064 double c[3];
3065 double d;
3066 double capacitance[3];
3067 };
3068
3069 [[nodiscard]] AnalogStateSpace analogStateSpace() const noexcept
3070 {
3071 // Unknowns: node voltages kVi..kW (7) then the three capacitor currents.
3072 constexpr int kN = 10;
3073 struct Element { int p, m; double value; bool capacitor; };
3074 const Element elements[] = {
3075 { kSrc, kVi, static_cast<double>(rOut_.getResistance()), false },
3076 { kVi, kA, static_cast<double>(c1_.getCapacitance()), true },
3077 { kA, kVo, static_cast<double>(r1Top_.getResistance()), false },
3078 { kVo, kB, static_cast<double>(r1Bot_.getResistance()), false },
3079 { kVi, kS, static_cast<double>(r4_.getResistance()), false },
3080 { kS, kB, static_cast<double>(c2_.getCapacitance()), true },
3081 { kB, kC, static_cast<double>(r2_.getResistance()), false },
3082 { kS, kW, static_cast<double>(c3_.getCapacitance()), true },
3083 { kC, kW, static_cast<double>(r3Top_.getResistance()), false },
3084 { kW, -1, static_cast<double>(r3Bot_.getResistance()), false },
3085 { kVo, -1, static_cast<double>(rLoad_.getResistance()), false } };
3086 double m[kN][kN] {};
3087 double rhs[kN][4] {}; // columns: unit C1, C2, C3 voltages, unit source
3088 int capIndex = 0;
3089 AnalogStateSpace out {};
3090 for (const auto& e : elements)
3091 {
3092 const int p = e.p - 1, q = e.m < 0 ? -1 : e.m - 1; // kSrc maps to -1
3093 if (e.capacitor)
3094 {
3095 const int row = 7 + capIndex;
3096 if (p >= 0) { m[p][row] += 1.0; m[row][p] += 1.0; }
3097 if (q >= 0) { m[q][row] -= 1.0; m[row][q] -= 1.0; }
3098 rhs[row][capIndex] = 1.0;
3099 out.capacitance[capIndex] = e.value;
3100 ++capIndex;
3101 continue;
3102 }
3103 const double g = 1.0 / e.value;
3104 if (e.p == kSrc)
3105 {
3106 // Source node is driven: its conductance stamps the RHS.
3107 m[q][q] += g;
3108 rhs[q][3] += g;
3109 continue;
3110 }
3111 if (p >= 0) m[p][p] += g;
3112 if (q >= 0) m[q][q] += g;
3113 if (p >= 0 && q >= 0) { m[p][q] -= g; m[q][p] -= g; }
3114 }
3115 // Gaussian elimination with partial pivoting, four right-hand sides.
3116 for (int k = 0; k < kN; ++k)
3117 {
3118 int piv = k;
3119 for (int i = k + 1; i < kN; ++i)
3120 if (std::abs(m[i][k]) > std::abs(m[piv][k])) piv = i;
3121 if (piv != k)
3122 for (int j = 0; j < kN; ++j) std::swap(m[piv][j], m[k][j]);
3123 if (piv != k)
3124 for (int j = 0; j < 4; ++j) std::swap(rhs[piv][j], rhs[k][j]);
3125 for (int i = k + 1; i < kN; ++i)
3126 {
3127 const double f = m[i][k] / m[k][k];
3128 if (f == 0.0) continue;
3129 for (int j = k; j < kN; ++j) m[i][j] -= f * m[k][j];
3130 for (int j = 0; j < 4; ++j) rhs[i][j] -= f * rhs[k][j];
3131 }
3132 }
3133 for (int i = kN - 1; i >= 0; --i)
3134 for (int j = 0; j < 4; ++j)
3135 {
3136 double v = rhs[i][j];
3137 for (int k = i + 1; k < kN; ++k) v -= m[i][k] * rhs[k][j];
3138 rhs[i][j] = v / m[i][i];
3139 }
3140 // Capacitor current flows from its first node to its second node.
3141 for (int j = 0; j < 4; ++j)
3142 {
3143 for (int k = 0; k < 3; ++k)
3144 {
3145 const double dv = rhs[7 + k][j] / out.capacitance[k];
3146 if (j < 3) out.a[k][j] = dv;
3147 else out.b[k] = dv;
3148 }
3149 if (j < 3) out.c[j] = rhs[kVo - 1][j];
3150 else out.d = rhs[kVo - 1][j];
3151 }
3152 return out;
3153 }
3154
3155private:
3156 static constexpr int kSrc = 0, kVi = 1, kA = 2, kVo = 3,
3157 kB = 4, kS = 5, kC = 6, kW = 7;
3158 static constexpr int kNumNodes = 8;
3159
3160 Resistor<T> rOut_;
3161 Capacitor<T> c1_;
3162 Resistor<T> r1Top_, r1Bot_, r4_;
3163 Capacitor<T> c2_;
3164 Resistor<T> r2_;
3165 Capacitor<T> c3_;
3166 Resistor<T> r3Top_, r3Bot_, rLoad_;
3167
3171 StackRType rtype_;
3173
3174 T treble_ = T(0.5), bass_ = T(0.5), middle_ = T(0.5);
3175};
3176
3177} // namespace wdf
3178} // namespace dspark
Capacitor, bilinear discretization: b[n] = a[n-1], Rp = 1/(2 fs C).
Definition WDF.h:165
double portResistance() const noexcept
Definition WDF.h:188
void incident(T a) noexcept
Definition WDF.h:190
void setCapacitance(T farads) noexcept
Definition WDF.h:169
void prepare(double sampleRate) noexcept
Definition WDF.h:174
void reset() noexcept
Definition WDF.h:176
T getCurrent() const noexcept
Definition WDF.h:193
T reflected() noexcept
Definition WDF.h:189
T getVoltage() const noexcept
Definition WDF.h:192
T getCapacitance() const noexcept
Current capacitance in farads.
Definition WDF.h:172
void offsetVoltage(T offset) noexcept
Shifts the voltage reference without changing capacitor current. Stream-owner only; the finite offset...
Definition WDF.h:181
Capacitor(T farads) noexcept
Definition WDF.h:167
void updatePorts() noexcept
Definition WDF.h:175
Antiparallel diode pair root (the classic clipper nonlinearity).
Definition WDF.h:1739
DiodePairRoot(Tree &tree, T saturationCurrent=T(2.52e-9), T idealityTimesVt=T(1.752 *0.02585)) noexcept
Definition WDF.h:1741
void process() noexcept
Definition WDF.h:1764
void setIdealityTimesVt(T volts) noexcept
Definition WDF.h:1747
T getVoltage() const noexcept
Voltage across the pair (the clipper output).
Definition WDF.h:1841
void prepare(double sampleRate) noexcept
Definition WDF.h:1749
void reset() noexcept
Definition WDF.h:1762
void setSaturationCurrent(T amps) noexcept
Definition WDF.h:1746
Single Shockley diode root: i(v) = Is (e^{v/(n Vt)} - 1).
Definition WDF.h:2271
DiodeRoot(Tree &tree, T saturationCurrent=T(2.52e-9), T idealityTimesVt=T(1.752 *0.02585)) noexcept
Definition WDF.h:2273
void setIdealityTimesVt(T volts) noexcept
Definition WDF.h:2279
void setSaturationCurrent(T amps) noexcept
Definition WDF.h:2278
T getVoltage() const noexcept
Voltage across the diode.
Definition WDF.h:2350
void prepare(double sampleRate) noexcept
Definition WDF.h:2281
void reset() noexcept
Definition WDF.h:2294
void process() noexcept
Definition WDF.h:2296
Ideal voltage source closing a linear tree: b = 2 Vs - a.
Definition WDF.h:419
void setVoltage(T volts) noexcept
Definition WDF.h:423
IdealVoltageSourceRoot(Tree &tree) noexcept
Definition WDF.h:421
void prepare(double sampleRate) noexcept
Definition WDF.h:425
Inductor, bilinear discretization: b[n] = -a[n-1], Rp = 2 fs L.
Definition WDF.h:208
T getVoltage() const noexcept
Definition WDF.h:222
Inductor(T henries) noexcept
Definition WDF.h:210
void updatePorts() noexcept
Definition WDF.h:215
void setInductance(T henries) noexcept
Definition WDF.h:212
void reset() noexcept
Definition WDF.h:216
void incident(T a) noexcept
Definition WDF.h:220
void prepare(double sampleRate) noexcept
Definition WDF.h:214
T reflected() noexcept
Definition WDF.h:219
double portResistance() const noexcept
Definition WDF.h:218
T getCurrent() const noexcept
Definition WDF.h:223
Two-port polarity inverter (flips the connected subtree's polarity).
Definition WDF.h:391
void updatePorts() noexcept
Definition WDF.h:396
Inverter(Child &c) noexcept
Definition WDF.h:393
void incident(T a) noexcept
Definition WDF.h:401
void prepare(double sampleRate) noexcept
Definition WDF.h:395
T reflected() noexcept
Definition WDF.h:400
void reset() noexcept
Definition WDF.h:397
double portResistance() const noexcept
Definition WDF.h:399
Adapted three-port parallel connector.
Definition WDF.h:342
void incident(T a3) noexcept
Definition WDF.h:372
Parallel(Child1 &c1, Child2 &c2) noexcept
Definition WDF.h:344
void prepare(double sampleRate) noexcept
Definition WDF.h:346
T reflected() noexcept
Definition WDF.h:364
double portResistance() const noexcept
Definition WDF.h:362
void updatePorts() noexcept
Definition WDF.h:351
void reset() noexcept
Definition WDF.h:360
N-port R-type adaptor for non-series/parallel interconnections.
Definition WDF.h:2685
void reset() noexcept
Definition WDF.h:2762
void updatePorts() noexcept
Definition WDF.h:2720
RType(const std::array< std::pair< int, int >, static_cast< size_t >(kNumPorts)> &portNodes, int numNodes, Children &... children) noexcept
Definition WDF.h:2697
static constexpr int kNumPorts
Definition WDF.h:2688
static constexpr int kMaxNodes
Definition WDF.h:2689
void prepare(double sampleRate) noexcept
Definition WDF.h:2715
T reflected() noexcept
Definition WDF.h:2770
double portResistance() const noexcept
Definition WDF.h:2768
void incident(T aUp) noexcept
Definition WDF.h:2782
Voltage source with series resistance (Thevenin leaf): b = Vs.
Definition WDF.h:243
void setVoltage(T volts) noexcept
Definition WDF.h:249
double portResistance() const noexcept
Definition WDF.h:255
void setResistance(T ohms) noexcept
Definition WDF.h:248
void prepare(double) noexcept
Definition WDF.h:251
T getVoltage() const noexcept
Voltage at the source terminals (after the series resistance).
Definition WDF.h:260
void incident(T a) noexcept
Definition WDF.h:257
ResistiveVoltageSource(T seriesResistanceOhms) noexcept
Definition WDF.h:245
void updatePorts() noexcept
Definition WDF.h:252
Ideal resistor. Absorbs its incident wave (b = 0).
Definition WDF.h:131
void setResistance(T ohms) noexcept
Definition WDF.h:135
void reset() noexcept
Definition WDF.h:142
double portResistance() const noexcept
Definition WDF.h:144
void updatePorts() noexcept
Definition WDF.h:141
Resistor(T resistanceOhms) noexcept
Definition WDF.h:133
void prepare(double) noexcept
Definition WDF.h:140
void incident(T a) noexcept
Definition WDF.h:146
T reflected() noexcept
Definition WDF.h:145
T getCurrent() const noexcept
Current through the resistor.
Definition WDF.h:151
T getResistance() const noexcept
Current resistance in ohms.
Definition WDF.h:138
T getVoltage() const noexcept
Voltage across the resistor (valid after the root scattered).
Definition WDF.h:149
Adapted three-port series connector.
Definition WDF.h:288
void reset() noexcept
Definition WDF.h:306
double portResistance() const noexcept
Definition WDF.h:308
void updatePorts() noexcept
Definition WDF.h:297
void prepare(double sampleRate) noexcept
Definition WDF.h:292
T reflected() noexcept
Definition WDF.h:310
void incident(T a3) noexcept
Definition WDF.h:317
Series(Child1 &c1, Child2 &c2) noexcept
Definition WDF.h:290
Exact Fender '59 Bassman treble/bass/middle tone stack.
Definition WDF.h:2953
void reset() noexcept
Clears capacitor states. RT-safe.
Definition WDF.h:2990
void setControls(T treble, T bass, T middle) noexcept
Sets the three controls, [0, 1] each.
Definition WDF.h:3020
AnalogStateSpace analogStateSpace() const noexcept
Definition WDF.h:3069
ToneStackFMV(double sourceResistance=1e3, double loadResistance=1e6)
Definition WDF.h:2959
void copyStateFrom(const ToneStackFMV &source, T inputOffset=T(0)) noexcept
Copies the capacitor history from an identically prepared stack.
Definition WDF.h:3001
void prepare(double sampleRate) noexcept
Prepares the network (allocates nothing).
Definition WDF.h:2983
T processSample(T input) noexcept
Processes one sample (input volts -> wiper volts).
Definition WDF.h:3041
Main namespace for the DSPark framework.
Continuous-time state space of the same network.
Definition WDF.h:3061
int anchorCentre[2]
Centres of the two anchors held.
Definition WDF.h:1323
bool done
Nothing left to build.
Definition WDF.h:1316
bool clipTop
The last cell ends at to.
Definition WDF.h:1320
int capacity
Cells the caller has room for.
Definition WDF.h:1321
int count
Cells built so far.
Definition WDF.h:1315
double c
Constant of the single diode.
Definition WDF.h:1318
int nearest
Anchor nearest the last cell.
Definition WDF.h:1322
bool single
Single diode instead of the pair.
Definition WDF.h:1319
std::uint64_t firstKey
Key of the first cell.
Definition WDF.h:1314
double offset
Offset of the cell grid.
Definition WDF.h:1313
double rootLo
Root there, to twice the precision.
Definition WDF.h:1251
double a[kCellTerms]
Coefficients of the powers 1 .. 16 of x - centre.
Definition WDF.h:1252
double centre
x the cell's series is about.
Definition WDF.h:1250
s, sinh(s) as a double and its remainder, cosh(s).
Definition WDF.h:1191
Scaled to t in [-0.5, 0.5].
Definition WDF.h:701