73# include <string_view>
74# include <type_traits>
77# if (defined(__GNUC__) or defined(__clang__)) \
78 and (defined(__x86_64__) or defined(__i386__) \
79 or defined(_M_X64) or defined(_M_IX86)) \
84# include <immintrin.h>
85# define ALEPH_FFT_HAS_X86_AVX2_DISPATCH 1
86# define ALEPH_FFT_AVX2_TARGET __attribute__((target("avx2")))
88# define ALEPH_FFT_HAS_X86_AVX2_DISPATCH 0
91# if (defined(__GNUC__) or defined(__clang__)) \
92 and (defined(__aarch64__) or defined(__arm__) or defined(_M_ARM64) \
94# if defined(__ARM_NEON) or defined(__ARM_NEON__)
96# define ALEPH_FFT_HAS_ARM_NEON_DISPATCH 1
98# define ALEPH_FFT_HAS_ARM_NEON_DISPATCH 0
101# define ALEPH_FFT_HAS_ARM_NEON_DISPATCH 0
104# if ALEPH_FFT_HAS_ARM_NEON_DISPATCH and defined(__aarch64__)
105# define ALEPH_FFT_HAS_ARM_NEON_DOUBLE 1
107# define ALEPH_FFT_HAS_ARM_NEON_DOUBLE 0
110# if ALEPH_FFT_HAS_ARM_NEON_DISPATCH and defined(__linux__)
111# include <sys/auxv.h>
112# include <asm/hwcap.h>
157 template <std::
floating_po
int Real =
double>
252 Real
radians = std::numeric_limits<Real>::infinity();
253 Real
degrees = std::numeric_limits<Real>::infinity();
261 Real
ratio = std::numeric_limits<Real>::infinity();
262 Real
decibels = std::numeric_limits<Real>::infinity();
272 Real
distance = std::numeric_limits<Real>::infinity();
356 template <
typename T>
360 template <
typename T>
364 template <
typename Container>
372 template <
typename Container>
377 requires std::convertible_to<
decltype(*std::begin(c)), Real>;
381 template <
typename Container>
386 requires std::convertible_to<std::remove_cvref_t<
decltype(*std::begin(c))>,
390 template <
typename Container>
404 return std::polar(Real(1), angle *
static_cast<Real
>(index));
408 [[nodiscard]]
static Real
411 return std::max(Real(1),
412 std::log2(
static_cast<Real
>(std::max(n,
size_t(2)))));
418 [[nodiscard]]
static Real
421 const Real scale = std::abs(
value.real()) + std::abs(
value.imag()) + Real(1);
423 * std::numeric_limits<Real>::epsilon() * scale;
429 [[nodiscard]]
static Real
431 const size_t n)
noexcept
433 const Real scale = std::abs(lhs.real()) + std::abs(lhs.imag())
434 + std::abs(rhs.real()) + std::abs(rhs.imag())
437 * std::numeric_limits<Real>::epsilon() * scale;
446 const size_t n = input.
size();
448 << ctx <<
": input must be non-empty";
452 << ctx <<
": coefficient 0 has non-negligible imaginary part "
458 const size_t half = n / 2;
463 << ctx <<
": coefficient " << half
464 <<
" has non-negligible imaginary part " << input[half].imag();
467 const size_t limit = (n & 1) == 0 ? half : half + 1;
468 for (
size_t k = 1;
k < limit; ++
k)
473 << ctx <<
": spectrum is not Hermitian at k=" <<
k;
480 const Real a1 = Real(0),
481 const Real a2 = Real(0))
491 const Real denom =
static_cast<Real
>(n - 1);
492 for (
size_t i = 0; i < n; ++i)
494 const Real phase = Real(2) * std::numbers::pi_v<Real>
495 *
static_cast<Real
>(i) / denom;
496 const Real
value = a0 - a1 * std::cos(phase)
497 + a2 * std::cos(Real(2) * phase);
505 template <
typename T>
511 for (
size_t i = input.
size(); i > 0; --i)
512 output.append(input[i - 1]);
517 template <
typename T>
522 <<
"FFT::prefix_copy: length " << length
523 <<
" exceeds input size " << input.
size();
527 for (
size_t i = 0; i < length; ++i)
533 template <
typename T>
540 <<
"FFT::slice_copy: offset " <<
offset <<
" exceeds input size " << input.
size();
542 <<
"FFT::slice_copy: length " << length <<
" exceeds slice capacity " << (input.
size() -
offset);
546 for (
size_t i = 0; i < length; ++i)
552 [[nodiscard]]
static size_t
554 const size_t coeff_size)
noexcept
556 if (signal_size <= 1 or coeff_size <= 1)
559 const size_t taps_minus_one = coeff_size - 1;
560 const size_t suggested = taps_minus_one
561 > std::numeric_limits<size_t>::max() / 3 ?
562 std::numeric_limits<size_t>::max() :
564 return std::min(suggested, signal_size - 1);
577 <<
"FFT::reflect_pad_signal: signal size must be >= 2 when pad_len > 0";
579 <<
"FFT::reflect_pad_signal: pad length " << pad_len
580 <<
" must be smaller than signal size " << signal.
size();
585 for (
size_t i = 0; i < pad_len; ++i)
586 output.append(signal[pad_len - i]);
588 for (
size_t i = 0; i < signal.
size(); ++i)
591 for (
size_t i = 0; i < pad_len; ++i)
600 const size_t left_pad,
601 const size_t right_pad)
606 for (
size_t i = 0; i < left_pad; ++i)
608 for (
size_t i = 0; i < signal.
size(); ++i)
610 for (
size_t i = 0; i < right_pad; ++i)
622 const size_t hop_size,
626 << ctx <<
": analysis window must be non-empty";
628 << ctx <<
": synthesis window must be non-empty";
630 << ctx <<
": analysis window size " << analysis_window.
size()
631 <<
" does not match synthesis window size "
632 << synthesis_window.
size();
636 for (
size_t i = 0; i < hop_size; ++i)
637 profile(i) = Real(0);
639 for (
size_t i = 0; i < analysis_window.
size(); ++i)
640 profile(i % hop_size) += analysis_window[i] * synthesis_window[i];
648 [[nodiscard]]
static bool
652 * Real(128) * std::numeric_limits<Real>::epsilon();
653 for (
size_t i = 0; i < profile.size(); ++i)
654 if (std::abs(profile[i]) <= tol)
662 [[nodiscard]]
static bool
665 if (profile.is_empty())
668 const Real
mean = profile[0];
670 * Real(256) * std::numeric_limits<Real>::epsilon();
671 for (
size_t i = 0; i < profile.size(); ++i)
672 if (std::abs(profile[i] -
mean) > tol)
681 const size_t hop_size,
682 const bool validate_nola,
683 const bool validate_cola,
686 if (not validate_nola
and not validate_cola)
697 << ctx <<
": window pair does not satisfy NOLA for hop size "
704 << ctx <<
": window pair does not satisfy COLA for hop size "
712 const size_t frame_size,
713 const size_t hop_size,
721 if (signal_size == 0)
726 if (
const size_t length = std::min(frame_size, signal_size -
offset); not pad_end
and length < frame_size)
731 if (not pad_end
and offset + frame_size >= signal_size)
739 [[nodiscard]]
static Real
743 for (
size_t i = 0; i < input.size(); ++i)
749 [[nodiscard]]
static Real
752 Real total = Real(0);
753 for (
size_t i = 0; i < input.size(); ++i)
759 [[nodiscard]]
static Real
762 Real total = Real(0);
763 for (
size_t i = 0; i < input.size(); ++i)
764 total += input[i] * input[i];
777 for (
size_t i = 0; i < input.
size(); ++i)
785 const Real sample_rate,
790 << ctx <<
": sample rate " << sample_rate <<
" must be strictly positive";
793 for (
size_t k = 0;
k < frequency.
size(); ++
k)
794 frequency(
k) =
static_cast<Real
>(
k) * sample_rate
795 /
static_cast<Real
>(fft_size);
800 [[nodiscard]]
static bool
802 const size_t fft_size)
noexcept
806 if (fft_size % 2 == 0
and bin == fft_size / 2)
812 [[nodiscard]]
static size_t
814 const size_t frame_size,
817 const size_t hop_size =
818 options.hop_size == 0 ? std::max(
static_cast<size_t>(1), frame_size / 2) :
options.hop_size;
824 [[nodiscard]]
static size_t
826 const size_t frame_size,
829 const size_t fft_size =
832 << ctx <<
": FFT size " << fft_size <<
" is smaller than frame size " << frame_size;
852 << ctx <<
": framing produced no analysis frames";
854 for (
size_t i = 0; i < frames.
size(); ++i)
865 template <
typename Density>
869 const size_t fft_size)
noexcept
876 [[nodiscard]]
static size_t
879 if (input.is_empty())
883 * Real(64) * std::numeric_limits<Real>::epsilon();
884 size_t n = input.size();
885 while (n > 1
and std::abs(input[n - 1]) <= tol)
895 for (
size_t i = 0; i < input.
size(); ++i)
896 output(i) = input[i] * factor;
922 [[nodiscard]]
static Real
924 const Real multiplier = Real(256)) noexcept
926 return (std::abs(reference) + Real(1))
927 * multiplier * std::numeric_limits<Real>::epsilon();
930 [[nodiscard]]
static Real
932 const Real multiplier = Real(256)) noexcept
935 *
static_cast<Real
>(coeff_count + 1)
936 * std::numeric_limits<Real>::epsilon();
939 [[nodiscard]]
static IIRCoefficients
948 << ctx <<
": numerator must be non-empty";
950 << ctx <<
": denominator must be non-empty";
952 const Real a0 = denominator[0];
954 * Real(64) * std::numeric_limits<Real>::epsilon();
956 << ctx <<
": leading denominator coefficient must be non-zero";
958 const size_t order = std::max(num_length, den_length) - 1;
963 for (
size_t i = 0; i <= order; ++i)
969 for (
size_t i = 0; i < num_length; ++i)
971 for (
size_t i = 0; i < den_length; ++i)
988 << ctx <<
": matrix size " << matrix.
size()
989 <<
" does not match a dense " << n <<
"x" << n <<
" system";
991 << ctx <<
": rhs size " << rhs.
size() <<
" does not match system size " << n;
993 Real max_entry = Real(0);
994 for (
size_t i = 0; i < matrix.
size(); ++i)
995 max_entry = std::max(max_entry, std::abs(matrix[i]));
996 for (
size_t i = 0; i < rhs.
size(); ++i)
997 max_entry = std::max(max_entry, std::abs(rhs[i]));
999 const Real pivot_tol = (max_entry + Real(1))
1000 * Real(128) * std::numeric_limits<Real>::epsilon();
1002 auto coeff = [&matrix, n](
const size_t row,
const size_t col) -> Real &
1004 return matrix(
row * n +
col);
1009 size_t pivot_row =
col;
1010 Real pivot_abs = std::abs(coeff(
col,
col));
1013 const Real candidate = std::abs(coeff(
row,
col));
1014 if (candidate > pivot_abs)
1016 pivot_abs = candidate;
1022 << ctx <<
": singular or ill-conditioned linear system";
1024 if (pivot_row !=
col)
1026 for (
size_t k =
col;
k < n; ++
k)
1027 std::swap(coeff(
col,
k), coeff(pivot_row,
k));
1028 std::swap(rhs(
col), rhs(pivot_row));
1031 const Real pivot = coeff(
col,
col);
1034 const Real factor = coeff(
row,
col) / pivot;
1035 if (std::abs(factor) <= pivot_tol)
1037 coeff(
row,
col) = Real(0);
1041 coeff(
row,
col) = Real(0);
1042 for (
size_t k =
col + 1;
k < n; ++
k)
1043 coeff(
row,
k) -= factor * coeff(
col,
k);
1044 rhs(
row) -= factor * rhs[
col];
1049 for (
size_t i = 0; i < n; ++i)
1050 solution(i) = Real(0);
1054 const size_t i =
row - 1;
1056 for (
size_t col = i + 1;
col < n; ++
col)
1059 const Real pivot = coeff(i, i);
1061 << ctx <<
": singular or ill-conditioned linear system";
1062 solution(i) =
sum / pivot;
1074 << ctx <<
": numerator size " << numerator.
size()
1075 <<
" does not match denominator size " << denominator.
size();
1077 const size_t order = denominator.
size() - 1;
1082 for (
size_t i = 0; i < system.
size(); ++i)
1083 system(i) = Real(0);
1085 auto coeff = [&system, order](
const size_t row,
const size_t col) -> Real &
1087 return system(
row * order +
col);
1090 for (
size_t i = 0; i < order; ++i)
1091 coeff(i, i) = Real(1);
1093 for (
size_t i = 0; i < order; ++i)
1095 coeff(i, 0) += denominator[i + 1];
1097 coeff(i, i + 1) -= Real(1);
1101 for (
size_t i = 0; i < order; ++i)
1102 rhs(i) = numerator[i + 1] - denominator[i + 1] * numerator[0];
1116 << ctx <<
": numerator size " << numerator.
size()
1117 <<
" does not match denominator size " << denominator.
size();
1119 const size_t order = denominator.
size() - 1;
1121 and initial_state.
size() != order)
1122 << ctx <<
": initial state size " << initial_state.
size()
1123 <<
" does not match filter order " << order;
1131 for (
size_t i = 0; i < signal.
size(); ++i)
1132 output(i) = numerator[0] * signal[i];
1137 for (
size_t i = 0; i < order; ++i)
1138 state(i) = initial_state.
is_empty() ? Real(0) : initial_state[i];
1140 for (
size_t n = 0; n < signal.
size(); ++n)
1142 const Real x = signal[n];
1143 const Real
y = numerator[0] * x + state[0];
1146 for (
size_t i = 0; i + 1 < order; ++i)
1147 state(i) = state[i + 1] + numerator[i + 1] * x
1148 - denominator[i + 1] *
y;
1149 state(order - 1) = numerator[order] * x - denominator[order] *
y;
1152 if (final_state !=
nullptr)
1153 *final_state = state;
1174 for (
size_t i = 0; i < signal.
size(); ++i)
1175 output(i) = signal[i] * gain;
1212 size_t total_order = 0;
1213 for (
size_t i = 0; i < sections.
size(); ++i)
1217 sections[i].denominator(),
1220 normalized_sections.
append(coeffs);
1223 if (total_order == 0)
1226 for (
size_t i = 0; i < normalized_sections.
size(); ++i)
1228 const Real gain = normalized_sections[i].numerator[0]
1229 * normalized_sections[i].numerator[0];
1230 for (
size_t j = 0; j <
output.size(); ++j)
1240 for (
size_t i = 0; i < normalized_sections.
size(); ++i)
1242 const auto & coeffs = normalized_sections[i];
1255 for (
size_t i = 0; i < normalized_sections.
size(); ++i)
1257 const auto & coeffs = normalized_sections[i];
1271 template <
typename T>
1276 for (
size_t i = 0; i < src.
size(); ++i)
1280 template <
typename T>
1285 <<
"FFT::drop_prefix: count " <<
count <<
" exceeds input size " << input.
size();
1298 for (
size_t i =
count; i < input.
size(); ++i)
1299 trimmed.
append(input[i]);
1300 input = std::move(trimmed);
1303 [[nodiscard]]
static constexpr size_t
1306 return lhs == 0 or rhs == 0 ?
1308 lhs > std::numeric_limits<size_t>::max() / rhs ?
1309 std::numeric_limits<size_t>::max() :
1313 [[nodiscard]]
static bool
1315 const size_t batch_size,
1316 const size_t transform_size,
1317 const size_t min_work = 8192) noexcept
1319 return pool !=
nullptr
1325 [[nodiscard]]
static size_t
1329 for (
size_t i = 0; i < batch.size(); ++i)
1330 if (not batch[i].is_empty())
1335 [[nodiscard]]
static size_t
1337 const size_t batch_size,
1340 constexpr size_t target_bytes = 32 * 1024;
1341 const size_t bytes_per_item = std::max(
sizeof(
Complex),
sizeof(Real))
1342 * std::max<size_t>(1, transform_size);
1343 size_t tile = std::max<size_t>(1, target_bytes / bytes_per_item);
1344 tile = std::max<size_t>(4, tile);
1345 tile = std::min(tile, std::max<size_t>(
static_cast<size_t>(1), batch_size));
1346 if (pool !=
nullptr and pool->num_threads() > 1)
1347 tile = std::max(tile, pool->num_threads() * 2);
1348 return std::min(tile, std::max<size_t>(
static_cast<size_t>(1), batch_size));
1353 const size_t frame_size)
1356 for (
size_t i = 0; i < frame_size; ++i)
1359 const size_t length = std::min(frame_size, input.
size());
1360 for (
size_t i = 0; i < length; ++i)
1361 frame(i) = input[i];
1366 [[nodiscard]]
static size_t
1376 << ctx <<
": FFT size " << fft_size <<
" is smaller than window size " << window.
size();
1390 const size_t fft_size)
1398 const size_t fft_size,
1401 const size_t chunk_size)
1403 if (frames.is_empty())
1406 const bool prefer_batch_simd =
1407 pool ==
nullptr or pool->
num_threads() <= 1 or fft_size >= 256;
1408 const size_t tile_size =
1414 const size_t count = std::min(tile_size, frames.size() -
offset);
1416 const bool parallelize_preparation =
1419 auto prepare_one = [&frames, &window, fft_size,
offset, &tile](
const size_t i)
1424 if (parallelize_preparation)
1427 for (
size_t i = 0; i <
count; ++i)
1430 const bool parallelize_transforms =
1432 if (parallelize_transforms)
1437 for (
size_t i = 0; i <
count; ++i)
1449 const size_t chunk_size = 0)
1454 const size_t fft_size =
1457 const size_t center_pad =
options.centered ? window.
size() / 2 : 0;
1464 if (frames.is_empty())
1467 const Plan plan(fft_size);
1488 const Real den_tol =
1491 << ctx <<
": transfer response is singular at omega=" << omega;
1497 [[nodiscard]]
static FrequencyResponse
1500 const size_t num_points,
1505 << ctx <<
": number of frequency samples must be positive";
1511 const Real max_omega = whole ? Real(2) * std::numbers::pi_v<Real> : std::numbers::pi_v<Real>;
1512 const Real denom = whole ?
static_cast<Real
>(num_points) :
static_cast<Real
>(std::max(
size_t(1), num_points - 1));
1514 for (
size_t i = 0; i < num_points; ++i)
1516 const Real omega = num_points == 1 ? Real(0) : max_omega *
static_cast<Real
>(i) / denom;
1527 [[nodiscard]]
static SeriesEvaluation
1534 << ctx <<
": coefficient series must be non-empty";
1537 const Real inv_scale = scale > std::numeric_limits<Real>::min() ? Real(1) / scale : Real(1);
1538 const Complex z = std::polar(Real(1), -omega);
1539 Complex value(coefficients[n - 1] * inv_scale, Real(0));
1540 Complex derivative_poly(Real(0), Real(0));
1542 for (
size_t idx = n - 1; idx-- > 0;)
1544 derivative_poly = derivative_poly * z +
value;
1550 output.derivative =
Complex(Real(0), Real(-1)) * z * derivative_poly;
1551 output.coefficient_scale = scale > std::numeric_limits<Real>::min() ? scale : Real(1);
1557 [[nodiscard]]
static PolynomialEvaluation
1564 for (
size_t i = 1; i < n; ++i)
1572 [[nodiscard]]
static PolynomialEvaluation
1587 [[nodiscard]]
static PolynomialEvaluation
1593 [[nodiscard]]
static std::pair<Array<Real>, Real>
1602 quotient(0) = coefficients[0];
1603 for (
size_t i = 1; i + 1 < n; ++i)
1604 quotient(i) = coefficients[i] +
root * quotient[i - 1];
1606 const Real
remainder = coefficients[n - 1] +
root * quotient[n - 2];
1607 return {std::move(quotient),
remainder};
1616 bool changed =
true;
1620 const Real coeff_tol =
1623 for (
const Real
root: {Real(1), Real(-1)})
1629 if (std::abs(eval.
value) > coeff_tol)
1644 return {std::move(reduced), std::move(extracted)};
1647 [[nodiscard]]
static Real
1650 Real bound = Real(1);
1651 const Real leading = std::max(std::abs(monic[0]),
1652 std::numeric_limits<Real>::min());
1653 for (
size_t i = 1; i < monic.size(); ++i)
1654 bound = std::max(bound, Real(1) + std::abs(monic[i]) / leading);
1658 [[nodiscard]]
static Real
1661 if (monic.size() <= 1)
1664 const Real constant = std::abs(monic[monic.size() - 1]);
1668 Real inverse_bound = Real(1);
1669 for (
size_t i = 0; i + 1 < monic.size(); ++i)
1670 inverse_bound = std::max(inverse_bound,
1671 Real(1) + std::abs(monic[i]) / constant);
1672 return Real(1) / inverse_bound;
1675 [[nodiscard]]
static BalancedPolynomial
1681 << ctx <<
": polynomial degree must be at least one";
1683 const Real leading = coefficients[0];
1687 << ctx <<
": leading polynomial coefficient must be non-zero";
1691 for (
size_t i = 0; i < n; ++i)
1692 output.monic(i) = coefficients[i] / leading;
1696 Real root_scale = Real(1);
1697 if (lower > tol
and std::isfinite(lower)
and std::isfinite(upper))
1698 root_scale = std::sqrt(lower * upper);
1699 else if (upper > Real(1)
and std::isfinite(upper))
1702 if (not std::isfinite(root_scale)
1703 or root_scale <= std::numeric_limits<Real>::min())
1704 root_scale = Real(1);
1707 output.balanced(0) = Real(1);
1708 Real inv_power = Real(1);
1709 const Real inv_scale = Real(1) / root_scale;
1710 for (
size_t i = 1; i < n; ++i)
1712 inv_power *= inv_scale;
1716 output.root_scale = root_scale;
1729 const size_t degree = coefficients.
size() - 1;
1734 Real base_radius = Real(1);
1735 if (lower > Real(0)
and std::isfinite(lower)
and std::isfinite(upper))
1736 base_radius = std::sqrt(lower * upper);
1737 else if (std::isfinite(upper)
and upper > Real(0))
1738 base_radius = upper;
1740 if (not std::isfinite(base_radius)
1741 or base_radius <= std::numeric_limits<Real>::min())
1742 base_radius = Real(1);
1744 for (
size_t i = 0; i < degree; ++i)
1747 Real(2) * std::numbers::pi_v<Real>
1748 * (
static_cast<Real
>(i) + Real(0.5))
1749 /
static_cast<Real
>(degree);
1753 + Real(0.2) *
static_cast<Real
>(i + 1)
1754 /
static_cast<Real
>(degree + 1));
1755 roots(i) = std::polar(radius, angle);
1765 const size_t max_iterations = 192) noexcept
1767 const size_t degree = roots.
size();
1768 for (
size_t iter = 0; iter < max_iterations; ++iter)
1770 bool converged =
true;
1771 for (
size_t i = 0; i < degree; ++i)
1775 Complex correction(Real(0), Real(0));
1776 for (
size_t j = 0; j < degree; ++j)
1779 const Complex delta = roots[i] - roots[j];
1780 if (std::abs(delta) > tol)
1781 correction +=
Complex(Real(1), Real(0)) / delta;
1785 if (std::abs(denom) <= tol)
1789 const Real nudge = tol * (Real(4) + std::abs(roots[i]));
1790 roots(i) += std::polar(nudge,
1792 * std::numbers::pi_v<Real>
1793 *
static_cast<Real
>(iter + i + 1)
1794 /
static_cast<Real
>(degree + 1));
1803 if (std::abs(step) > tol * (Real(1) + std::abs(roots[i])))
1818 const size_t max_iterations = 192) noexcept
1820 const size_t degree = roots.
size();
1821 for (
size_t iter = 0; iter < max_iterations; ++iter)
1823 bool converged =
true;
1824 for (
size_t i = 0; i < degree; ++i)
1828 Complex denom(Real(1), Real(0));
1829 for (
size_t j = 0; j < degree; ++j)
1832 const Complex delta = roots[i] - roots[j];
1833 if (std::abs(delta) <= tol)
1835 const Real nudge = tol * (Real(4) + std::abs(roots[i]));
1836 roots(i) += std::polar(nudge,
1838 * std::numbers::pi_v<Real>
1839 *
static_cast<Real
>(iter + i + 1)
1840 /
static_cast<Real
>(degree + 1));
1841 denom =
Complex(Real(0), Real(0));
1847 if (std::abs(denom) <= tol)
1855 if (std::abs(step) > tol * (Real(1) + std::abs(roots[i])))
1870 const size_t iterations)
noexcept
1872 for (
size_t i = 0; i < roots.size(); ++i)
1873 for (
size_t iter = 0; iter < iterations; ++iter)
1882 if (std::abs(step) <= tol * (Real(1) + std::abs(roots[i])))
1889 const Real tol)
noexcept
1892 for (
size_t i = 0; i < roots.size(); ++i)
1897 if (std::abs(roots[i].imag()) <= tol * (Real(8) + std::abs(roots[i])))
1899 roots(i) =
Complex(roots[i].real(), Real(0));
1904 const Complex target = std::conj(roots[i]);
1905 size_t best = roots.size();
1906 Real best_error = std::numeric_limits<Real>::infinity();
1907 for (
size_t j = i + 1; j < roots.size(); ++j)
1911 const Real
error = std::abs(roots[j] - target);
1912 if (
error < best_error)
1919 if (best == roots.size()
1920 or best_error > tol * (Real(16) + std::abs(roots[i])))
1923 const Complex center = (roots[i] + std::conj(roots[best])) / Real(2);
1924 const Real imag = std::abs(center.imag());
1925 roots(i) =
Complex(center.real(),
1926 roots[i].imag() >= Real(0) ? imag : -imag);
1927 roots(best) = std::conj(roots[i]);
1933 [[nodiscard]]
static bool
1936 const Real tol)
noexcept
1938 for (
size_t i = 0; i < roots.size(); ++i)
1942 Real bound = Real(0);
1943 const Real radius = std::abs(roots[i]);
1944 for (
size_t k = 0;
k < coefficients.size(); ++
k)
1945 bound = bound * radius + std::abs(coefficients[
k]);
1947 if (std::abs(eval.
value) > tol * (bound + Real(1)))
1959 const size_t n = coefficients.size();
1960 const size_t degree = n - 1;
1963 for (
size_t i = 0; i < n; ++i)
1964 deflated(i) =
Complex(coefficients[i], Real(0));
1966 for (
size_t k = 0;
k < degree; ++
k)
1968 const size_t m = degree -
k;
1969 const Real m_r =
static_cast<Real
>(
m);
1970 Complex z = std::polar(Real(0.8) + Real(0.4)
1971 *
static_cast<Real
>(
k)
1972 /
static_cast<Real
>(degree + 1),
1973 Real(2) * std::numbers::pi_v<Real>
1974 * (
static_cast<Real
>(
k) + Real(0.5))
1975 /
static_cast<Real
>(degree));
1978 for (
size_t iter = 0; iter < 512; ++iter)
1982 Complex d2p(Real(0), Real(0));
1983 for (
size_t i = 1; i <=
m; ++i)
1987 p = z * p + deflated[i];
1989 d2p *=
Complex(Real(2), Real(0));
1991 if (std::abs(p) <= tol)
2000 std::sqrt(
Complex(m_r - Real(1), Real(0))
2006 std::abs(denom1) >= std::abs(denom2) ?
2011 if (std::abs(best_denom) > tol)
2012 step =
Complex(m_r, Real(0)) / best_denom;
2014 step = (Real(1) + std::abs(z))
2015 * std::polar(Real(1),
2016 Real(2) * std::numbers::pi_v<Real>
2017 *
static_cast<Real
>(iter * 2 + 1)
2021 if (std::abs(step) <= tol * (Real(1) + std::abs(z)))
2034 reduced(0) = deflated[0];
2035 for (
size_t i = 1; i <
m; ++i)
2036 reduced(i) = deflated[i] + z * reduced[i - 1];
2038 deflated = std::move(reduced);
2057 const Real leading = coefficients[0];
2060 << ctx <<
": leading polynomial coefficient must be non-zero";
2062 const size_t degree = n - 1;
2066 roots(0) =
Complex(-coefficients[1] / coefficients[0], Real(0));
2072 const Real a = coefficients[0];
2073 const Real b = coefficients[1];
2074 const Real c = coefficients[2];
2076 std::sqrt(
Complex(b * b - Real(4) * a * c, Real(0)));
2077 const Complex signed_disc = b >= Real(0) ? disc : -disc;
2079 * (
Complex(b, Real(0)) + signed_disc);
2081 if (std::abs(q) <= tol)
2106 problem.
tol * Real(4),
2113 problem.
tol * Real(4),
2119 for (
size_t i = 0; i < roots.
size(); ++i)
2129 << ctx <<
": root solver residual check failed";
2140 if (input.is_empty())
2144 while (first < input.size()
and input[first] == Real(0))
2147 if (first == input.size())
2151 trimmed.
reserve(input.size() - first);
2152 for (
size_t i = first; i < input.size(); ++i)
2153 trimmed.
append(input[i]);
2187 const Real den_tol =
2190 << ctx <<
": transfer response is singular at omega=" << omega;
2202 const size_t num_points,
2207 freqz_impl(numerator, denominator, num_points, whole, ctx);
2212 * Real(256) * std::numeric_limits<Real>::epsilon();
2214 for (
size_t i = 0; i < num_points; ++i)
2222 delay(i) = numeric_fallback[i];
2239 << ctx <<
": at least one biquad section is required";
2243 for (
size_t i = 0; i < response.
omega.
size(); ++i)
2245 Real total = Real(0);
2246 bool analytic =
true;
2247 for (
size_t j = 0; j < sections.
size(); ++j)
2251 sections[j].denominator(),
2254 const Real num_tol =
2256 if (std::abs(terms.
numerator) <= num_tol)
2266 delay(i) = analytic ? total : numeric_fallback[i];
2276 const size_t num_points,
2281 freqz_impl(numerator, denominator, num_points, whole, ctx);
2286 const Real tol = (response.
omega[response.
omega.
size() - 1] + Real(1))
2287 * Real(128) * std::numeric_limits<Real>::epsilon();
2289 for (
size_t i = 0; i < num_points; ++i)
2290 delay(i) = std::abs(response.
omega[i]) <= tol ? group[i] : -phase[i] / response.
omega[i];
2296 [[nodiscard]]
static Real
2299 Real radius = Real(0);
2300 for (
size_t i = 0; i < roots.size(); ++i)
2301 radius = std::max(radius,
static_cast<Real
>(std::abs(roots[i])));
2320 size_t best_zero = 0;
2321 size_t best_pole = 0;
2322 Real best_distance = std::numeric_limits<Real>::infinity();
2324 for (
size_t i = 0; i <
zeros.
size(); ++i)
2329 for (
size_t j = 0; j <
poles.
size(); ++j)
2334 const Real distance = std::abs(
zeros[i] -
poles[j]);
2335 if (distance < best_distance)
2337 best_distance = distance;
2351 pair.distance = best_distance;
2352 pair.has_zero =
true;
2353 pair.has_pole =
true;
2355 zero_used[best_zero] =
true;
2356 pole_used[best_pole] =
true;
2359 for (
size_t i = 0; i <
zeros.
size(); ++i)
2360 if (not zero_used[i])
2364 pair.has_zero =
true;
2368 for (
size_t i = 0; i <
poles.
size(); ++i)
2369 if (not pole_used[i])
2373 pair.has_pole =
true;
2383 [[nodiscard]]
static Real
2386 Real best = std::numeric_limits<Real>::infinity();
2387 for (
size_t i = 0; i < pairs.size(); ++i)
2388 if (pairs[i].has_zero
and pairs[i].has_pole)
2389 best = std::min(best, pairs[i].distance);
2427 template <
typename T>
2435 for (
size_t i = 0; i <
output.size(); ++i)
2438 for (
size_t i = 0; i < lhs.
size(); ++i)
2439 for (
size_t j = 0; j < rhs.
size(); ++j)
2440 output(i + j) += lhs[i] * rhs[j];
2446 template <
typename T>
2453 <<
"FFT::add_scaled_polynomial: destination size "
2454 << dst.
size() <<
" is smaller than source size " << src.
size();
2456 for (
size_t i = 0; i < src.
size(); ++i)
2457 dst(i) += src[i] * scale;
2461 [[nodiscard]]
static Real
2464 Real result = Real(1);
2465 for (
size_t i = 0; i < exponent; ++i)
2475 coeffs(0) = Real(1);
2476 for (
size_t k = 1;
k <= power; ++
k)
2477 coeffs(
k) = coeffs[
k - 1]
2478 *
static_cast<Real
>(power -
k + 1)
2479 /
static_cast<Real
>(
k)
2490 const Real sample_rate,
2494 << ctx <<
": analog polynomial must be non-empty";
2496 << ctx <<
": sample rate " << sample_rate <<
" must be positive";
2498 const size_t degree = analog.
size() - 1;
2500 << ctx <<
": analog degree " << degree <<
" exceeds requested bilinear order " << order;
2503 for (
size_t i = 0; i <
output.size(); ++i)
2506 const Real fs2 = Real(2) * sample_rate;
2507 for (
size_t i = 0; i < analog.
size(); ++i)
2509 const size_t power = degree - i;
2526 coeffs(0) =
Complex(Real(1), Real(0));
2528 for (
size_t i = 0; i < roots.
size(); ++i)
2531 for (
size_t j = 0; j <
next.size(); ++j)
2534 for (
size_t j = 0; j < coeffs.
size(); ++j)
2536 next(j) += coeffs[j];
2537 next(j + 1) -= coeffs[j] * roots[i];
2540 coeffs = std::move(
next);
2559 const size_t exponent,
2565 for (
size_t i = 0; i < exponent; ++i)
2582 << ctx <<
": polynomial must be non-empty";
2584 << ctx <<
": rational substitution polynomials must be non-empty";
2586 const size_t order = degree - 1;
2589 numerator_powers(0) = {Real(1)};
2590 denominator_powers(0) = {Real(1)};
2591 for (
size_t i = 1; i <= order; ++i)
2593 numerator_powers(i) =
2595 denominator_powers(i) =
2600 for (
size_t i = 0; i <= order; ++i)
2604 denominator_powers[i]);
2608 for (
size_t j = 0; j < grown.
size(); ++j)
2610 for (
size_t j = 0; j <
output.size(); ++j)
2612 output = std::move(grown);
2616 for (
size_t j = 0; j < aligned.
size(); ++j)
2617 aligned(j) = Real(0);
2618 for (
size_t j = 0; j < term.
size(); ++j)
2619 aligned(j + (aligned.
size() - term.
size())) = term[j];
2620 for (
size_t j = 0; j <
output.size(); ++j)
2621 output(j) += poly[i] * aligned[j];
2631 [[nodiscard]]
static IIRCoefficients
2651 if (den_degree > num_degree)
2652 transformed_numerator =
2655 den_degree - num_degree,
2657 else if (num_degree > den_degree)
2658 transformed_denominator =
2661 num_degree - den_degree,
2668 const Real a0 = compact_denominator[0];
2671 << ctx <<
": transformed analog denominator leading coefficient "
2672 << a0 <<
" is too small";
2673 for (
size_t i = 0; i < compact_numerator.
size(); ++i)
2674 compact_numerator(i) /= a0;
2675 for (
size_t i = 0; i < compact_denominator.
size(); ++i)
2676 compact_denominator(i) /= a0;
2679 coeffs.
numerator = std::move(compact_numerator);
2680 coeffs.
denominator = std::move(compact_denominator);
2692 Real max_coeff = Real(0);
2693 for (
size_t i = 0; i < coeffs.
size(); ++i)
2694 max_coeff = std::max(max_coeff,
2695 static_cast<Real
>(std::abs(coeffs[i])));
2697 const Real tol = (max_coeff + Real(1))
2698 * Real(1024) * std::numeric_limits<Real>::epsilon();
2700 for (
size_t i = 0; i < coeffs.
size(); ++i)
2703 << ctx <<
": root set does not generate a real polynomial";
2704 real_coeffs(i) = coeffs[i].real();
2715 return Complex(Real(0), Real(0));
2717 Complex center(Real(0), Real(0));
2718 for (
size_t i = 0; i < roots.
size(); ++i)
2720 return center /
static_cast<Real
>(roots.
size());
2731 * Real(2048) * std::numeric_limits<Real>::epsilon();
2735 for (
size_t i = 0; i < result.
size(); ++i)
2737 if (paired[i] or std::abs(result[i].imag()) <= tol)
2740 size_t best = result.
size();
2741 Real best_error = std::numeric_limits<Real>::infinity();
2742 const Complex target = std::conj(result[i]);
2743 for (
size_t j = i + 1; j < result.
size(); ++j)
2747 const Real
error = std::abs(result[j] - target);
2748 if (
error < best_error)
2755 if (best < result.
size())
2758 (result[i].real() + result[best].real()) / Real(2);
2760 (std::abs(result[i].imag())
2761 + std::abs(result[best].imag())) / Real(2);
2762 result(i) =
Complex(avg_re, avg_im);
2763 result(best) =
Complex(avg_re, -avg_im);
2765 paired[best] =
true;
2785 * Real(2048) * std::numeric_limits<Real>::epsilon();
2789 for (
size_t i = 0; i < roots.
size(); ++i)
2791 if (used[i] or std::abs(roots[i].imag()) <= tol)
2794 size_t best = roots.
size();
2795 Real best_error = std::numeric_limits<Real>::infinity();
2796 const Complex target = std::conj(roots[i]);
2797 for (
size_t j = i + 1; j < roots.
size(); ++j)
2802 const Real
error = std::abs(roots[j] - target);
2803 if (
error < best_error)
2811 or best_error > tol * (Real(16)
2812 + std::abs(roots[i])))
2813 << ctx <<
": complex root " << roots[i] <<
" does not have a matching conjugate";
2816 group.
roots = {roots[i], roots[best]};
2824 for (
size_t i = 0; i < roots.
size(); ++i)
2830 << ctx <<
": root " << roots[i] <<
" was not paired into a real section";
2837 size_t first = real_roots.
size();
2838 for (
size_t i = 0; i < real_roots.
size(); ++i)
2839 if (not real_used[i])
2845 if (first == real_roots.
size())
2848 size_t second = real_roots.
size();
2849 Real best_distance = std::numeric_limits<Real>::infinity();
2850 for (
size_t j = first + 1; j < real_roots.
size(); ++j)
2855 const Real distance = std::abs(real_roots[first] - real_roots[j]);
2856 if (distance < best_distance)
2858 best_distance = distance;
2865 real_used[first] =
true;
2866 if (second != real_roots.
size())
2869 real_used[second] =
true;
2881 [[nodiscard]]
static BiquadSection
2889 << ctx <<
": section denominator order " << (coeffs.
denominator.
size() - 1)
2890 <<
" exceeds second order";
2895 for (
size_t i = 0; i < 3; ++i)
2916 [[nodiscard]]
static IIRCoefficients
2919 const Real sample_rate,
2923 << ctx <<
": analog numerator must be non-empty";
2925 << ctx <<
": analog denominator must be non-empty";
2927 const size_t order =
2928 std::max(analog_numerator.
size(), analog_denominator.
size()) - 1;
2940 digital_denominator,
2947 [[nodiscard]]
static Real
2949 const Real sample_rate,
2953 << ctx <<
": sample rate " << sample_rate <<
" must be positive";
2955 << ctx <<
": cutoff frequency " << cutoff_frequency
2956 <<
" must be positive";
2958 << ctx <<
": cutoff frequency " << cutoff_frequency
2959 <<
" must be smaller than Nyquist " << (sample_rate / Real(2));
2961 return Real(2) * sample_rate
2962 * std::tan(std::numbers::pi_v<Real>
2963 * cutoff_frequency / sample_rate);
2976# if defined(__GLIBCXX__) or defined(_MSVC_STL_VERSION)
2978 [[nodiscard]]
static Real
2981 return std::ellint_1(
k, phi);
2984 [[nodiscard]]
static Real
2987 return std::comp_ellint_1(
k);
2992 [[nodiscard]]
static Real
2997 Real b = std::sqrt(std::max(Real(0), Real(1) -
k *
k));
2998 for (
size_t i = 0; i < 64
and std::abs(a - b) >
2999 std::numeric_limits<Real>::epsilon() * a; ++i)
3001 const Real next_a = (a + b) / Real(2);
3002 b = std::sqrt(a * b);
3005 return std::numbers::pi_v<Real> / (Real(2) * a);
3008 [[nodiscard]]
static Real
3015 std::pow(std::numeric_limits<Real>::epsilon() / Real(3),
3017 for (
size_t i = 0; i < 64; ++i)
3019 const Real mu = (x +
y + z) / Real(3);
3020 const Real dx = Real(1) - x / mu;
3021 const Real dy = Real(1) -
y / mu;
3022 const Real dz = Real(1) - z / mu;
3023 if (std::max({std::abs(dx), std::abs(dy), std::abs(dz)})
3026 const Real e2 = dx * dy - dz * dz;
3027 const Real e3 = dx * dy * dz;
3028 return (Real(1) - e2 / Real(10) + e3 / Real(14)
3029 + e2 * e2 / Real(24)
3030 - Real(3) * e2 * e3 / Real(44))
3033 const Real lam = std::sqrt(x *
y) + std::sqrt(x * z)
3035 x = (x + lam) / Real(4);
3036 y = (
y + lam) / Real(4);
3037 z = (z + lam) / Real(4);
3039 return Real(1) / std::sqrt((x +
y + z) / Real(3));
3042 [[nodiscard]]
static Real
3048 const Real half_pi = std::numbers::pi_v<Real> / Real(2);
3049 if (std::abs(phi - half_pi) <=
3050 std::numeric_limits<Real>::epsilon() * Real(4))
3053 if (std::abs(phi) <=
3054 std::numeric_limits<Real>::epsilon() * Real(4))
3057 const Real s = std::sin(phi);
3058 const Real c = std::cos(phi);
3061 Real(1) -
k *
k * s * s),
3070 [[nodiscard]]
static Real
3075 << ctx <<
": elliptic modulus " <<
modulus <<
" must lie in [0, 1)";
3082 [[nodiscard]]
static JacobiValues
3088 << ctx <<
": elliptic modulus " <<
modulus <<
" must lie in [0, 1)";
3093 const bool negative = argument < Real(0);
3094 const Real u = std::abs(argument);
3098 values.
sn = std::sin(u);
3099 values.
cn = std::cos(u);
3100 values.
dn = Real(1);
3102 values.
sn = -values.
sn;
3108 if (std::abs(u - K) <= endpoint_tol)
3111 values.
sn = Real(1);
3112 values.
cn = Real(0);
3113 values.
dn = std::sqrt(std::max(Real(0),
3116 values.
sn = -values.
sn;
3121 << ctx <<
": Jacobi argument " << u
3122 <<
" exceeds the supported quarter period " << K;
3124 Real lower = Real(0);
3125 Real upper = std::numbers::pi_v<Real> / Real(2);
3126 Real phi = upper * (u / K);
3127 phi = std::clamp(phi,
3128 std::numeric_limits<Real>::epsilon(),
3129 upper - std::numeric_limits<Real>::epsilon());
3131 for (
size_t iter = 0; iter < 96; ++iter)
3134 const Real residual =
value - u;
3138 if (residual > Real(0))
3143 const Real sin_phi = std::sin(phi);
3144 const Real derivative =
3145 Real(1) / std::sqrt(std::max(Real(0),
3148 * sin_phi * sin_phi));
3149 Real candidate = phi - residual / derivative;
3150 if (candidate <= lower or candidate >= upper
3151 or not std::isfinite(candidate))
3152 candidate = (lower + upper) / Real(2);
3157 values.
sn = std::sin(phi);
3158 values.
cn = std::cos(phi);
3159 values.
dn = std::sqrt(std::max(Real(0),
3162 * values.
sn * values.
sn));
3164 values.
sn = -values.
sn;
3168 [[nodiscard]]
static Real
3174 << ctx <<
": inverse Jacobi sc value " <<
value
3175 <<
" must be non-negative";
3177 << ctx <<
": elliptic modulus " <<
modulus
3178 <<
" must lie in [0, 1)";
3182 [[nodiscard]]
static Real
3188 << ctx <<
": order must be positive";
3190 << ctx <<
": selectivity modulus " << k1
3191 <<
" must lie in (0, 1)";
3193 const Real k1_complement =
3194 std::sqrt(std::max(Real(0), Real(1) - k1 * k1));
3197 / (
static_cast<Real
>(order)
3200 Real lower = Real(0);
3201 Real upper = Real(1) - std::sqrt(std::numeric_limits<Real>::epsilon());
3202 for (
size_t iter = 0; iter < 128; ++iter)
3204 const Real mid = (lower + upper) / Real(2);
3205 const Real mid_complement =
3206 std::sqrt(std::max(Real(0), Real(1) - mid * mid));
3216 return (lower + upper) / Real(2);
3226 const Real complement =
3234 << ctx <<
": elliptic cd denominator vanished";
3238 [[nodiscard]]
static AnalogPrototype
3243 << ctx <<
": order must be positive";
3247 prototype.
gain = Real(1);
3248 for (
size_t k = 0;
k < order; ++
k)
3251 std::numbers::pi_v<Real>
3252 * (Real(2) *
static_cast<Real
>(
k)
3254 +
static_cast<Real
>(order))
3255 / (Real(2) *
static_cast<Real
>(order));
3256 prototype.
poles(
k) = std::polar(Real(1), angle);
3262 [[nodiscard]]
static AnalogPrototype
3264 const Real ripple_db,
3268 << ctx <<
": order must be positive";
3270 << ctx <<
": passband ripple " << ripple_db
3271 <<
" must be positive in decibels";
3273 const Real epsilon =
3274 std::sqrt(std::pow(Real(10), ripple_db / Real(10)) - Real(1));
3275 const Real mu = std::asinh(Real(1) / epsilon)
3276 /
static_cast<Real
>(order);
3280 for (
size_t k = 0;
k < order; ++
k)
3283 std::numbers::pi_v<Real>
3284 * (Real(2) *
static_cast<Real
>(
k)
3286 / (Real(2) *
static_cast<Real
>(order));
3288 Complex(-std::sinh(mu) * std::sin(theta),
3289 std::cosh(mu) * std::cos(theta));
3294 prototype.
gain = denominator[denominator.
size() - 1];
3296 prototype.
gain /= std::sqrt(Real(1) + epsilon * epsilon);
3301 [[nodiscard]]
static AnalogPrototype
3303 const Real attenuation_db,
3307 << ctx <<
": order must be positive";
3309 << ctx <<
": stopband attenuation " << attenuation_db
3310 <<
" must be positive in decibels";
3312 const Real epsilon =
3313 Real(1) / std::sqrt(std::pow(Real(10), attenuation_db / Real(10))
3315 const Real mu = std::asinh(Real(1) / epsilon)
3316 /
static_cast<Real
>(order);
3321 for (
size_t k = 0;
k < order; ++
k)
3324 std::numbers::pi_v<Real>
3325 * (Real(2) *
static_cast<Real
>(
k) + Real(1))
3326 / (Real(2) *
static_cast<Real
>(order));
3327 const Complex inverse_pole(-std::sinh(mu) * std::sin(theta),
3328 std::cosh(mu) * std::cos(theta));
3329 prototype.
poles(
k) =
Complex(Real(1), Real(0)) / inverse_pole;
3332 for (
size_t k = 0;
k < order / 2; ++
k)
3335 std::numbers::pi_v<Real>
3336 * (Real(2) *
static_cast<Real
>(
k) + Real(1))
3337 / (Real(2) *
static_cast<Real
>(order));
3338 const Real imag = Real(1) / std::cos(theta);
3349 denominator[denominator.
size() - 1] / numerator[numerator.
size() - 1];
3353 [[nodiscard]]
static AnalogPrototype
3355 const Real ripple_db,
3356 const Real attenuation_db,
3360 << ctx <<
": order must be positive";
3362 << ctx <<
": passband ripple " << ripple_db
3363 <<
" must be positive in decibels";
3365 << ctx <<
": stopband attenuation " << attenuation_db
3366 <<
" must exceed passband ripple " << ripple_db;
3368 const Real epsilon =
3369 std::sqrt(std::pow(Real(10), ripple_db / Real(10)) - Real(1));
3370 const Real stop_term =
3371 std::pow(Real(10), attenuation_db / Real(10)) - Real(1);
3373 << ctx <<
": stopband attenuation produced a non-positive stop term";
3375 const Real k1 = epsilon / std::sqrt(stop_term);
3387 const Real k1_complement =
3388 std::sqrt(std::max(Real(0), Real(1) - k1 * k1));
3393 K *
r / (
static_cast<Real
>(order) * K1);
3399 const size_t pair_count = order / 2;
3400 for (
size_t i = 0; i < pair_count; ++i)
3403 (Real(2) *
static_cast<Real
>(i) + Real(1)) * K
3404 /
static_cast<Real
>(order);
3406 const Real zero_scale =
modulus * values.
sn;
3409 << ctx <<
": elliptic prototype zero scale vanished";
3410 const Real zero_imag = Real(1) / zero_scale;
3417 if (pole.real() > Real(0))
3419 if (pole.imag() < Real(0))
3420 pole = std::conj(pole);
3426 if ((order & 1) != 0)
3428 const Real complement =
3433 << ctx <<
": elliptic prototype real pole denominator vanished";
3442 const Real target_gain =
3444 Real(1) / std::sqrt(Real(1) + epsilon * epsilon) :
3447 target_gain * denominator[denominator.
size() - 1]
3448 / numerator[numerator.
size() - 1];
3453 [[nodiscard]]
static Real
3470 << ctx <<
": analog transfer response is singular at omega="
3472 return std::abs(num_eval.
value / den_eval.
value);
3483 << ctx <<
": order must be positive";
3486 for (
size_t k = 0;
k <= order; ++
k)
3488 const long double numerator =
3489 std::tgamma(
static_cast<long double>(2 * order -
k + 1));
3490 const long double denominator =
3491 std::pow(2.0L,
static_cast<long double>(order -
k))
3492 * std::tgamma(
static_cast<long double>(order -
k + 1))
3493 * std::tgamma(
static_cast<long double>(
k + 1));
3495 static_cast<Real
>(numerator / denominator);
3501 [[nodiscard]]
static AnalogPrototype
3507 const Real base_gain =
3508 base_denominator[base_denominator.
size() - 1];
3509 const Real target = Real(1) / std::sqrt(Real(2));
3511 Real upper = Real(1);
3519 << ctx <<
": could not bracket the -3 dB normalization point";
3522 Real lower = Real(0);
3523 for (
size_t iter = 0; iter < 96; ++iter)
3525 const Real mid = (lower + upper) / Real(2);
3526 const Real magnitude =
3531 if (magnitude > target)
3537 const Real scale = upper;
3539 for (
size_t i = 0; i <
poles.
size(); ++i)
3546 prototype.
gain = scaled_denominator[scaled_denominator.
size() - 1];
3553 const Real cutoff_frequency,
3554 const Real sample_rate,
3555 const bool highpass,
3558 const Real warped_cutoff =
3570 const Real cutoff_frequency,
3571 const Real sample_rate,
3572 const bool highpass,
3576 << ctx <<
": prototype order " << prototype.
poles.
size()
3577 <<
" does not match requested order " << order;
3579 const Real warped_cutoff =
3583 const Real prototype_constant =
3584 prototype_denominator[prototype_denominator.
size() - 1];
3585 const Real first_section_gain = highpass ?
3586 prototype.
gain / prototype_constant :
3590 for (
size_t i = 0; i < order; ++i)
3591 transformed_poles(i) = highpass ?
3599 for (
size_t i = 0; i < pole_groups.
size(); ++i)
3601 const size_t degree = pole_groups[i].roots.
size();
3605 for (
size_t j = 0; j < analog_numerator.
size(); ++j)
3606 analog_numerator(j) = Real(0);
3609 analog_numerator(0) = i == 0 ? first_section_gain : Real(1);
3611 analog_numerator(degree) = i == 0 ? first_section_gain : Real(1);
3627 [[nodiscard]]
static std::pair<Real, Real>
3629 const Real high_cutoff_frequency,
3630 const Real sample_rate,
3634 << ctx <<
": low cutoff " << low_cutoff_frequency
3635 <<
" must be positive";
3637 << ctx <<
": high cutoff " << high_cutoff_frequency
3638 <<
" must be greater than low cutoff " << low_cutoff_frequency;
3640 << ctx <<
": high cutoff " << high_cutoff_frequency
3641 <<
" must be smaller than Nyquist " << (sample_rate / Real(2));
3663 for (
size_t i = 0; i < pole_groups.
size(); ++i)
3665 size_t best = zero_groups.
size();
3666 Real best_cost = std::numeric_limits<Real>::infinity();
3667 for (
size_t j = 0; j < zero_groups.
size(); ++j)
3670 or zero_groups[j].roots.
size() > pole_groups[i].roots.
size())
3673 const Real size_penalty =
3674 zero_groups[j].roots.
size() == pole_groups[i].roots.
size() ? Real(0) : Real(16);
3676 std::abs(zero_groups[j].center - pole_groups[i].center)
3678 if (cost < best_cost)
3686 if (best != zero_groups.
size())
3690 zero_used(best) =
true;
3696 for (
size_t k = 0;
k < section_numerator.
size(); ++
k)
3700 section_denominator,
3704 for (
size_t i = 0; i < zero_groups.
size(); ++i)
3706 << ctx <<
": could not assign finite-zero group " << i
3707 <<
" to any SOS section";
3730 const Real low_cutoff_frequency,
3731 const Real high_cutoff_frequency,
3732 const Real sample_rate,
3736 << ctx <<
": specialized band-stop path expects prototypes without zeros";
3738 const auto [warped_low, warped_high] =
3740 high_cutoff_frequency,
3743 const Real bandwidth = warped_high - warped_low;
3744 const Real center = std::sqrt(warped_low * warped_high);
3749 prototype_denominator,
3750 {bandwidth, Real(0)},
3751 {Real(1), Real(0), center * center},
3759 const Complex analog_zero(Real(0), center);
3761 (
Complex(Real(2) * sample_rate, Real(0)) - analog_zero)
3762 / (
Complex(Real(2) * sample_rate, Real(0)) + analog_zero);
3766 for (
size_t i = 0; i < order; ++i)
3769 group.
roots = {digital_zero, std::conj(digital_zero)};
3771 zero_groups.
append(std::move(group));
3782 const Real sample_rate,
3788 prototype_numerator =
3790 for (
size_t i = 0; i < prototype_numerator.
size(); ++i)
3791 prototype_numerator(i) *= prototype.
gain;
3797 prototype_denominator,
3812 [[nodiscard]]
static Real
3815 const Real half_x = x / Real(2);
3816 const Real half_x_sq = half_x * half_x;
3818 Real term = Real(1);
3819 for (
size_t k = 1;
k < 80; ++
k)
3822 / (
static_cast<Real
>(
k) *
static_cast<Real
>(
k));
3824 if (std::abs(term) <= std::numeric_limits<Real>::epsilon() *
sum)
3831 [[nodiscard]]
static Real
3834 const Real pix = std::numbers::pi_v<Real> * x;
3835 if (std::abs(pix) <= std::numeric_limits<Real>::epsilon())
3837 return std::sin(pix) / pix;
3841 [[nodiscard]]
static Real
3861 << ctx <<
": FIR gain vanished at normalization omega=" << omega;
3862 for (
size_t i = 0; i < coeffs.
size(); ++i)
3869 const Real cutoff_frequency,
3870 const Real sample_rate,
3875 << ctx <<
": num_taps must be positive";
3877 << ctx <<
": window size " << window.
size()
3878 <<
" does not match num_taps " << num_taps;
3880 << ctx <<
": sample rate " << sample_rate <<
" must be positive";
3882 << ctx <<
": cutoff frequency " << cutoff_frequency
3883 <<
" must be positive";
3885 << ctx <<
": cutoff frequency " << cutoff_frequency
3886 <<
" must be smaller than Nyquist " << (sample_rate / Real(2));
3888 const Real normalized_cutoff = cutoff_frequency / sample_rate;
3889 const Real center =
static_cast<Real
>(num_taps - 1) / Real(2);
3891 for (
size_t n = 0; n < num_taps; ++n)
3893 const Real
m =
static_cast<Real
>(n) - center;
3895 Real(2) * normalized_cutoff
3897 coeffs(n) = ideal * window[n];
3905 [[nodiscard]]
static Real
3907 const Real omega_hi,
3908 const size_t harmonic)
noexcept
3911 return omega_hi - omega_lo;
3913 const Real
k =
static_cast<Real
>(harmonic);
3914 return (std::sin(
k * omega_hi) - std::sin(
k * omega_lo)) /
k;
3918 [[nodiscard]]
static Real
3920 const Real omega_hi,
3921 const size_t lhs_harmonic,
3922 const size_t rhs_harmonic)
noexcept
3924 const size_t delta = lhs_harmonic >= rhs_harmonic ? lhs_harmonic - rhs_harmonic : rhs_harmonic - lhs_harmonic;
3928 lhs_harmonic + rhs_harmonic));
3932 [[nodiscard]]
static Real
3934 const Real omega_hi,
3935 const size_t harmonic)
noexcept
3937 const Real width = omega_hi - omega_lo;
3939 return Real(0.5) * width * width;
3941 const Real
k =
static_cast<Real
>(harmonic);
3942 return width * std::sin(
k * omega_hi) /
k
3943 + (std::cos(
k * omega_hi) - std::cos(
k * omega_lo)) / (
k *
k);
3947 [[nodiscard]]
static Real
3949 const Real omega_hi,
3950 const Real desired_lo,
3951 const Real desired_hi,
3952 const size_t harmonic)
noexcept
3954 const Real width = omega_hi - omega_lo;
3955 if (width <= Real(0))
3958 const Real slope = (desired_hi - desired_lo) / width;
3970 const Real sample_rate,
3975 << ctx <<
": num_taps must be positive";
3977 << ctx <<
": num_taps must be odd for a Type-I linear-phase design";
3979 << ctx <<
": sample rate " << sample_rate <<
" must be positive";
3981 << ctx <<
": bands must contain an even number of band edges";
3983 << ctx <<
": desired size " << desired.
size()
3984 <<
" does not match band edge count " << bands.
size();
3986 const size_t band_count = bands.
size() / 2;
3988 << ctx <<
": weights size " << weights.
size()
3989 <<
" does not match band count " << band_count;
3991 const Real nyquist = sample_rate / Real(2);
3995 << ctx <<
": first band edge " << bands[0] <<
" must start at 0";
3997 << ctx <<
": last band edge " << bands[bands.
size() - 1]
3998 <<
" must reach Nyquist " << nyquist;
4001 normalized_weights.
reserve(band_count);
4003 for (
size_t i = 0; i < band_count; ++i)
4004 normalized_weights.
append(Real(1));
4006 for (
size_t i = 0; i < band_count; ++i)
4009 << ctx <<
": weight " << weights[i]
4010 <<
" at band " << i <<
" must be positive";
4011 normalized_weights.
append(weights[i]);
4015 Real previous_edge = Real(0);
4016 for (
size_t i = 0; i < bands.
size(); ++i)
4018 const Real edge = i == 0 ? Real(0) : (i + 1 == bands.
size() ? nyquist : bands[i]);
4020 << ctx <<
": band edge " << edge <<
" lies outside [0, Nyquist]";
4022 << ctx <<
": band edges must be non-decreasing";
4026 << ctx <<
": band " << (i / 2)
4027 <<
" has non-positive width";
4030 omega(i) = Real(2) * std::numbers::pi_v<Real> * edge / sample_rate;
4031 previous_edge = edge;
4034 const size_t order = (num_taps - 1) / 2;
4035 const size_t dimension = order + 1;
4038 for (
size_t i = 0; i < system.
size(); ++i)
4039 system(i) = Real(0);
4040 for (
size_t i = 0; i < rhs.
size(); ++i)
4043 for (
size_t band = 0; band < band_count; ++band)
4045 const Real omega_lo = omega[band * 2];
4046 const Real omega_hi = omega[band * 2 + 1];
4047 const Real desired_lo = desired[band * 2];
4048 const Real desired_hi = desired[band * 2 + 1];
4049 const Real weight = normalized_weights[band];
4051 for (
size_t row = 0;
row < dimension; ++
row)
4060 const Real contribution =
4065 system(
row * dimension +
col) += contribution;
4067 system(
col * dimension +
row) += contribution;
4075 for (
size_t i = 0; i < coeffs.
size(); ++i)
4076 coeffs(i) = Real(0);
4078 const size_t center = order;
4079 coeffs(center) = cosine_series[0];
4080 for (
size_t k = 1;
k < cosine_series.
size(); ++
k)
4082 const Real tap = cosine_series[
k] / Real(2);
4083 coeffs(center -
k) = tap;
4084 coeffs(center +
k) = tap;
4090 [[nodiscard]]
static WeightedFrequencyGrid
4094 const Real sample_rate,
4096 const size_t grid_density,
4100 << ctx <<
": num_taps must be positive";
4102 << ctx <<
": num_taps must be odd for a Type-I linear-phase design";
4104 << ctx <<
": sample rate " << sample_rate <<
" must be positive";
4106 << ctx <<
": grid density " << grid_density
4107 <<
" must be at least 8";
4109 << ctx <<
": bands must contain an even number of band edges";
4111 << ctx <<
": desired size " << desired.
size()
4112 <<
" does not match band edge count " << bands.
size();
4114 const size_t band_count = bands.
size() / 2;
4116 << ctx <<
": weights size " << weights.
size()
4117 <<
" does not match band count " << band_count;
4119 const Real nyquist = sample_rate / Real(2);
4122 << ctx <<
": first band edge " << bands[0] <<
" must start at 0";
4124 << ctx <<
": last band edge " << bands[bands.
size() - 1]
4125 <<
" must reach Nyquist " << nyquist;
4128 const size_t half_order = (num_taps - 1) / 2;
4129 const size_t target_points = grid_density * (half_order + 2);
4131 Real previous_edge = Real(0);
4132 for (
size_t band = 0; band < band_count; ++band)
4134 const Real
low = bands[band * 2];
4135 const Real high = bands[band * 2 + 1];
4137 << ctx <<
": band edges must lie in [0, Nyquist]";
4139 << ctx <<
": band edges must be non-decreasing";
4141 << ctx <<
": band " << band <<
" has non-positive width";
4143 const Real desired_low = desired[band * 2];
4144 const Real desired_high = desired[band * 2 + 1];
4145 const Real weight = weights.
is_empty() ? Real(1) : weights[band];
4147 << ctx <<
": weight " << weight <<
" at band " << band
4148 <<
" must be positive";
4150 const Real omega_low =
4151 Real(2) * std::numbers::pi_v<Real> *
low / sample_rate;
4152 const Real omega_high =
4153 Real(2) * std::numbers::pi_v<Real> * high / sample_rate;
4154 const Real omega_width = omega_high - omega_low;
4155 size_t sample_count =
4156 static_cast<size_t>(std::ceil(target_points
4158 / std::numbers::pi_v<Real>));
4159 sample_count = std::max<size_t>(sample_count, 2);
4161 for (
size_t i = 0; i < sample_count; ++i)
4163 if (band > 0
and i == 0)
4169 static_cast<Real
>(i)
4170 /
static_cast<Real
>(sample_count - 1);
4171 const Real omega = omega_low + t * omega_width;
4172 const Real desired_value =
4173 desired_low + t * (desired_high - desired_low);
4179 previous_edge = high;
4183 << ctx <<
": weighted frequency grid is too small";
4187 [[nodiscard]]
static Real
4189 const Real omega)
noexcept
4191 Real
value = Real(0);
4192 for (
size_t k = 0;
k < coefficients.size(); ++
k)
4193 value += coefficients[
k] * std::cos(
static_cast<Real
>(
k) * omega);
4199 const size_t extremal_count)
4202 extrema.
reserve(extremal_count);
4203 for (
size_t i = 0; i < extremal_count; ++i)
4205 const Real position =
4206 extremal_count == 1 ?
4208 static_cast<Real
>(i)
4209 *
static_cast<Real
>(grid_size - 1)
4210 /
static_cast<Real
>(extremal_count - 1);
4211 extrema.
append(
static_cast<size_t>(std::llround(position)));
4218 const size_t required_count,
4222 << ctx <<
": weighted error grid has only " << weighted_error.
size()
4223 <<
" points for " << required_count <<
" required extrema";
4228 Real magnitude = Real(0);
4234 for (
size_t i = 0; i < weighted_error.
size(); ++i)
4236 const Real current = weighted_error[i];
4237 const Real current_abs = std::abs(current);
4241 const Real left_abs =
4242 i == 0 ? Real(-1) : std::abs(weighted_error[i - 1]);
4243 const Real right_abs =
4244 i + 1 == weighted_error.
size() ? Real(-1) : std::abs(weighted_error[i + 1]);
4249 Candidate candidate;
4250 candidate.index = i;
4251 candidate.magnitude = current_abs;
4252 candidate.sign = current >= Real(0) ? 1 : -1;
4253 candidates.
append(candidate);
4256 if (candidates.
size() < required_count)
4260 compressed.reserve(candidates.
size());
4261 compressed.append(candidates[0]);
4262 for (
size_t i = 1; i < candidates.
size(); ++i)
4264 if (candidates[i].sign == compressed[compressed.size() - 1].sign)
4266 if (candidates[i].magnitude > compressed[compressed.size() - 1].magnitude)
4267 compressed(compressed.size() - 1) = candidates[i];
4270 compressed.append(candidates[i]);
4273 if (compressed.size() < required_count)
4275 if (compressed.size() == required_count)
4278 extrema.
reserve(required_count);
4279 for (
size_t i = 0; i < compressed.size(); ++i)
4280 extrema.
append(compressed[i].index);
4284 size_t best_start = 0;
4285 Real best_floor = Real(-1);
4286 Real best_sum = Real(-1);
4287 for (
size_t start = 0; start + required_count <= compressed.size(); ++start)
4289 Real
floor = std::numeric_limits<Real>::infinity();
4291 for (
size_t i = 0; i < required_count; ++i)
4293 floor = std::min(
floor, compressed[start + i].magnitude);
4294 sum += compressed[start + i].magnitude;
4297 if (
floor > best_floor
4298 or (std::abs(
floor - best_floor)
4309 extrema.
reserve(required_count);
4310 for (
size_t i = 0; i < required_count; ++i)
4311 extrema.
append(compressed[best_start + i].index);
4320 const size_t half_order,
4323 const size_t dimension = half_order + 2;
4325 << ctx <<
": expected " << dimension <<
" extrema but got "
4330 for (
size_t i = 0; i < matrix.
size(); ++i)
4331 matrix(i) = Real(0);
4332 for (
size_t i = 0; i < rhs.
size(); ++i)
4335 for (
size_t row = 0;
row < dimension; ++
row)
4337 const size_t index = extrema[
row];
4338 for (
size_t col = 0;
col <= half_order; ++
col)
4339 matrix(
row * dimension +
col) =
4340 std::cos(
static_cast<Real
>(
col) * omega[index]);
4341 matrix(
row * dimension + half_order + 1) =
4342 ((
row & 1) == 0 ? Real(1) : Real(-1)) / weight[index];
4343 rhs(
row) = desired[index];
4353 const Real sample_rate,
4355 const size_t grid_density,
4356 const size_t max_iterations,
4360 << ctx <<
": max_iterations must be positive";
4370 const size_t half_order = (num_taps - 1) / 2;
4371 const size_t required_extrema = half_order + 2;
4376 for (
size_t i = 0; i < cosine.
size(); ++i)
4377 cosine(i) = Real(0);
4379 for (
size_t iter = 0; iter < max_iterations; ++iter)
4388 for (
size_t i = 0; i < cosine.
size(); ++i)
4389 cosine(i) = solution[i];
4392 for (
size_t i = 0; i < grid.
omega.
size(); ++i)
4404 bool unchanged = next_extrema.
size() == extrema.
size();
4405 for (
size_t i = 0; unchanged
and i < extrema.
size(); ++i)
4406 unchanged = next_extrema[i] == extrema[i];
4407 extrema = next_extrema;
4413 for (
size_t i = 0; i < coeffs.
size(); ++i)
4414 coeffs(i) = Real(0);
4416 const size_t center = half_order;
4417 coeffs(center) = cosine[0];
4418 for (
size_t k = 1;
k < cosine.
size(); ++
k)
4420 const Real tap = cosine[
k] / Real(2);
4421 coeffs(center -
k) = tap;
4422 coeffs(center +
k) = tap;
4428 [[nodiscard]]
static Real
4433 const Real target)
noexcept
4435 const Real dy =
y1 -
y0;
4436 if (std::abs(dy) <= std::numeric_limits<Real>::epsilon())
4438 const Real t = (target -
y0) / dy;
4439 return x0 + t * (x1 - x0);
4442 [[nodiscard]]
static Real
4447 const Real x)
noexcept
4449 const Real dx = x1 - x0;
4450 if (std::abs(dx) <= std::numeric_limits<Real>::epsilon())
4452 const Real t = (x - x0) / dx;
4453 return y0 + t * (
y1 -
y0);
4456 [[nodiscard]]
static Real
4458 const Real reference_phase)
noexcept
4461 std::round((reference_phase - raw_phase)
4462 / (Real(2) * std::numbers::pi_v<Real>));
4463 return raw_phase + turns * Real(2) * std::numbers::pi_v<Real>;
4466 template <
typename Evaluator>
4467 [[nodiscard]]
static Real
4477 Real left_y =
y0 - target;
4478 Real right_y =
y1 - target;
4480 if (std::abs(left_y) <= std::numeric_limits<Real>::epsilon())
4482 if (std::abs(right_y) <= std::numeric_limits<Real>::epsilon())
4484 if ((left_y < Real(0)
and right_y < Real(0))
4485 or (left_y > Real(0)
and right_y > Real(0)))
4490 for (
size_t iter = 0; iter < 64; ++iter)
4492 const Real mid_x = (left_x + right_x) / Real(2);
4493 const Real mid_y = evaluator(mid_x) - target;
4494 if (std::abs(mid_y) <= std::numeric_limits<Real>::epsilon()
4495 or std::abs(right_x - left_x) <= xtol)
4498 if ((left_y < Real(0)
and mid_y < Real(0))
4499 or (left_y > Real(0)
and mid_y > Real(0)))
4511 return (left_x + right_x) / Real(2);
4520 << ctx <<
": at least one biquad section is required";
4522 Complex response(Real(1), Real(0));
4523 for (
size_t i = 0; i < sections.
size(); ++i)
4525 sections[i].denominator(),
4531 [[nodiscard]]
static PhaseMarginInfo
4535 <<
"FFT::phase_margin: omega size " << response.
omega.
size()
4536 <<
" does not match response size " << response.
response.
size();
4545 Real best_margin = std::numeric_limits<Real>::infinity();
4546 Real best_omega = std::numeric_limits<Real>::quiet_NaN();
4548 for (
size_t i = 1; i < response.
omega.
size(); ++i)
4550 const Real left = magnitude[i - 1] - Real(1);
4551 const Real right = magnitude[i] - Real(1);
4552 if ((left < Real(0)
and right < Real(0))
4553 or (left > Real(0)
and right > Real(0)))
4566 const Real margin = std::numbers::pi_v<Real> + phi;
4567 if (not found or margin < best_margin)
4569 best_margin = margin;
4578 info.
degrees = best_margin * Real(180) / std::numbers::pi_v<Real>;
4587 [[nodiscard]]
static GainMarginInfo
4591 <<
"FFT::gain_margin: omega size " << response.
omega.
size()
4592 <<
" does not match response size " << response.
response.
size();
4601 Real best_ratio = std::numeric_limits<Real>::infinity();
4602 Real best_omega = std::numeric_limits<Real>::quiet_NaN();
4604 for (
size_t i = 1; i < response.
omega.
size(); ++i)
4606 const Real p0 = phase[i - 1];
4607 const Real p1 = phase[i];
4608 const Real lower = std::min(p0, p1);
4609 const Real upper = std::max(p0, p1);
4610 const auto first_target =
4611 static_cast<long long>(std::ceil((-upper - std::numbers::pi_v<Real>)
4613 * std::numbers::pi_v<Real>)));
4614 const auto last_target =
4615 static_cast<long long>(std::floor((-lower - std::numbers::pi_v<Real>)
4617 * std::numbers::pi_v<Real>)));
4619 for (
long long m = first_target;
m <= last_target; ++
m)
4622 -(Real(2) *
static_cast<Real
>(
m) + Real(1))
4623 * std::numbers::pi_v<Real>;
4634 const Real ratio = std::abs(mag) <= std::numeric_limits<Real>::epsilon() ?
4635 std::numeric_limits<Real>::infinity() :
4636 Real(1) / std::abs(mag);
4637 if (not found or ratio < best_ratio)
4648 info.
ratio = best_ratio;
4649 info.
decibels = std::isinf(best_ratio) ?
4650 std::numeric_limits<Real>::infinity() :
4651 Real(20) * std::log10(best_ratio);
4660 template <
typename Evaluator>
4661 [[nodiscard]]
static PhaseMarginInfo
4663 const Evaluator & evaluator)
4666 <<
"FFT::phase_margin: omega size " << response.
omega.
size()
4667 <<
" does not match response size " << response.
response.
size();
4676 Real best_margin = std::numeric_limits<Real>::infinity();
4677 Real best_omega = std::numeric_limits<Real>::quiet_NaN();
4679 for (
size_t i = 1; i < response.
omega.
size(); ++i)
4681 const Real left = magnitude[i - 1] - Real(1);
4682 const Real right = magnitude[i] - Real(1);
4683 if ((left < Real(0)
and right < Real(0))
4684 or (left > Real(0)
and right > Real(0)))
4690 return std::abs(evaluator(
w));
4692 response.
omega[i - 1],
4697 const Real phase_ref =
4705 const Real margin = std::numbers::pi_v<Real> + phi;
4706 if (not found or margin < best_margin)
4708 best_margin = margin;
4717 info.
degrees = best_margin * Real(180) / std::numbers::pi_v<Real>;
4726 template <
typename Evaluator>
4727 [[nodiscard]]
static GainMarginInfo
4729 const Evaluator & evaluator)
4732 <<
"FFT::gain_margin: omega size " << response.
omega.
size()
4733 <<
" does not match response size " << response.
response.
size();
4742 Real best_ratio = std::numeric_limits<Real>::infinity();
4743 Real best_omega = std::numeric_limits<Real>::quiet_NaN();
4745 for (
size_t i = 1; i < response.
omega.
size(); ++i)
4747 const Real p0 = phase[i - 1];
4748 const Real p1 = phase[i];
4749 const Real lower = std::min(p0, p1);
4750 const Real upper = std::max(p0, p1);
4751 const auto first_target =
4752 static_cast<long long>(std::ceil((-upper - std::numbers::pi_v<Real>)
4754 * std::numbers::pi_v<Real>)));
4755 const auto last_target =
4756 static_cast<long long>(std::floor((-lower - std::numbers::pi_v<Real>)
4758 * std::numbers::pi_v<Real>)));
4760 for (
long long m = first_target;
m <= last_target; ++
m)
4763 -(Real(2) *
static_cast<Real
>(
m) + Real(1))
4764 * std::numbers::pi_v<Real>;
4768 const Real reference =
4777 response.
omega[i - 1],
4782 const Real mag = std::abs(evaluator(omega));
4784 std::abs(mag) <= std::numeric_limits<Real>::epsilon() ?
4785 std::numeric_limits<Real>::infinity() :
4786 Real(1) / std::abs(mag);
4787 if (not found or ratio < best_ratio)
4798 info.
ratio = best_ratio;
4799 info.
decibels = std::isinf(best_ratio) ?
4800 std::numeric_limits<Real>::infinity() :
4801 Real(20) * std::log10(best_ratio);
4819 for (
size_t i = 1; i < phase.
size(); ++i)
4821 const Real delta = phase[i] - phase[i - 1];
4822 if (delta > std::numbers::pi_v<Real>)
4823 offset -= Real(2) * std::numbers::pi_v<Real>;
4824 else if (delta < -std::numbers::pi_v<Real>)
4825 offset += Real(2) * std::numbers::pi_v<Real>;
4836 <<
"FFT::group_delay: omega size " << response.
omega.
size()
4837 <<
" does not match response size " << response.
response.
size();
4850 for (
size_t i = 0; i < response.
omega.
size(); ++i)
4852 const size_t left = i == 0 ? 0 : i - 1;
4853 const size_t right = i + 1 == response.
omega.
size() ? i : i + 1;
4854 const Real domega = response.
omega[right] - response.
omega[left];
4855 if (std::abs(domega) <= std::numeric_limits<Real>::epsilon())
4858 delay(i) = -(phase[right] - phase[left]) / domega;
4869 <<
"FFT::phase_delay: omega size " << response.
omega.
size()
4870 <<
" does not match response size " << response.
response.
size();
4878 const Real tol = (response.
omega[response.
omega.
size() - 1] + Real(1))
4879 * Real(128) * std::numeric_limits<Real>::epsilon();
4881 for (
size_t i = 0; i < response.
omega.
size(); ++i)
4882 delay(i) = std::abs(response.
omega[i]) <= tol ? group[i] : -phase[i] / response.
omega[i];
4893 const size_t fft_size,
4898 << ctx <<
": analysis window must be non-empty";
4900 << ctx <<
": synthesis window must be non-empty";
4902 << ctx <<
": analysis window size " << analysis_window.
size()
4903 <<
" does not match synthesis window size "
4904 << synthesis_window.
size();
4906 << ctx <<
": hop size must be positive";
4908 << ctx <<
": FFT size must be positive";
4910 << ctx <<
": frame FFT size " << fft_size
4911 <<
" is smaller than window size " << analysis_window.
size();
4928 const size_t chunk_size)
4930 if (spectrogram.is_empty())
4933 const size_t fft_size = spectrogram[0].
size();
4940 for (
size_t i = 1; i < spectrogram.size(); ++i)
4942 <<
"FFT::istft: frame " << i <<
" has size "
4943 << spectrogram[i].size() <<
" but expected " << fft_size;
4945 const size_t raw_length = (spectrogram.size() - 1) *
options.hop_size
4946 + analysis_window.
size();
4947 const size_t center_pad =
options.centered ? analysis_window.
size() / 2 : 0;
4948 const size_t output_length =
options.signal_length == 0 ?
4949 (
options.centered
and raw_length >= 2 * center_pad ?
4950 raw_length - 2 * center_pad :
4954 <<
"FFT::istft: requested signal length " << output_length
4955 <<
" exceeds overlap-add length " << raw_length
4956 <<
" after centered trimming";
4958 Plan plan(fft_size);
4961 for (
size_t i = 0; i < raw_length; ++i)
4964 normalization(i) = Real(0);
4967 for (
size_t frame_idx = 0; frame_idx < spectrogram.size(); ++frame_idx)
4974 for (
size_t i = 0; i < analysis_window.
size(); ++i)
4977 normalization(
offset + i) += analysis_window[i] * synthesis_window[i];
4982 * Real(256) * std::numeric_limits<Real>::epsilon();
4984 for (
size_t i = 0; i < raw_length; ++i)
4986 if (std::abs(normalization[i]) <= tol)
4989 <<
"FFT::istft: overlap-add normalization vanished at sample " << i;
4990 normalized(i) = Real(0);
4993 normalized(i) =
output[i] / normalization[i];
4997 slice_copy(normalized, center_pad, output_length) :
5006 <<
"FFT::zero_padded_copy: target size " << n
5007 <<
" is smaller than input size " << input.
size();
5011 for (
size_t i = 0; i < input.
size(); ++i)
5013 for (
size_t i = input.
size(); i < n; ++i)
5023 <<
"FFT::zero_padded_copy: target size " << n
5024 <<
" is smaller than input size " << input.
size();
5028 for (
size_t i = 0; i < input.
size(); ++i)
5030 for (
size_t i = input.
size(); i < n; ++i)
5040 <<
"FFT::trim_to_size: target size " << n
5041 <<
" exceeds input size " << input.
size();
5043 while (input.
size() > n)
5047 template <
typename T,
typename Container>
5052 requires std::convertible_to<
decltype(*std::begin(c)),
T>;
5059 if constexpr (
requires { input.size(); })
5062 for (
auto it = std::begin(input); it != std::end(input); ++it)
5063 output.append(
static_cast<T>(*it));
5068 template <
typename Container>
5069 requires Is_Complex_Container<Container>
5073 return to_array<Complex>(input);
5076 template <
typename Container>
5077 requires Is_Real_Container<Container>
5081 return to_array<Real>(input);
5084 [[nodiscard]]
static size_t
5089 << ctx <<
": tensor shape must be non-empty";
5092 for (
size_t i = 0; i < shape.
size(); ++i)
5095 << ctx <<
": shape dimension " << i <<
" must be positive";
5108 for (
size_t i = shape.
size(); i > 0; --i)
5110 strides(i - 1) = stride;
5116 [[nodiscard]]
static size_t
5122 << ctx <<
": shape rank " << shape.
size()
5123 <<
" does not match strides rank " << strides.
size();
5125 size_t max_offset = 0;
5126 for (
size_t i = 0; i < shape.
size(); ++i)
5129 << ctx <<
": shape dimension " << i <<
" must be positive";
5139 [[nodiscard]]
static TensorLayout
5147 << ctx <<
": tensor shape must be non-empty";
5154 << ctx <<
": flat data size " << data.
size()
5155 <<
" does not match row-major tensor size " << logical_size;
5161 << ctx <<
": strides rank " << normalized.
strides.
size()
5162 <<
" does not match shape rank " << normalized.
shape.
size();
5164 const size_t max_offset =
5167 << ctx <<
": tensor layout touches offset " << max_offset
5168 <<
" but flat buffer size is " << data.
size();
5181 << ctx <<
": at least one axis is required";
5186 for (
size_t i = 0; i < axes.
size(); ++i)
5189 << ctx <<
": axis " << axes[i] <<
" is out of range for rank "
5192 << ctx <<
": axis " << axes[i] <<
" appears more than once";
5193 used(axes[i]) =
true;
5194 normalized.
append(axes[i]);
5210 size_t slice_count = 1;
5211 for (
size_t i = 0; i < shape.
size(); ++i)
5227 for (
size_t i = 0; i < counters.
size(); ++i)
5234 for (
size_t i = 0; i < other_dims.
size(); ++i)
5235 offset += counters[i] * strides[other_dims[i]];
5238 for (
size_t rev = other_dims.
size(); rev > 0; --rev)
5240 const size_t idx = rev - 1;
5242 if (counters[idx] < shape[other_dims[idx]])
5259 const size_t base_offset,
5260 const size_t axis_length,
5261 const size_t axis_stride)
5264 for (
size_t i = 0; i < axis_length; ++i)
5265 slice(i) = data[base_offset + i * axis_stride];
5274 const size_t base_offset,
5275 const size_t axis_stride,
5278 for (
size_t i = 0; i < slice.
size(); ++i)
5279 data(base_offset + i * axis_stride) = slice[i];
5291 const size_t chunk_size = 0)
5298 "FFT::transform_axis");
5299 const size_t axis_index = axes[0];
5300 const size_t axis_length = normalized.
shape[axis_index];
5301 const size_t axis_stride = normalized.
strides[axis_index];
5304 Plan plan(axis_length);
5306 if (offsets.
size() == 1)
5310 if (pool !=
nullptr and pool->num_threads() > 1)
5311 plan.
ptransform(*pool, slice, invert, chunk_size);
5318 auto transform_one =
5319 [&data, &offsets, axis_length, axis_stride, invert, &plan](
const size_t i)
5328 and pool->num_threads() > 1
5332 for (
size_t i = 0; i < offsets.
size(); ++i)
5345 const size_t chunk_size = 0)
5351 for (
size_t i = 0; i < normalized_axes.
size(); ++i)
5370 const size_t cols = input[0].size();
5373 for (
size_t i = 1; i <
rows; ++i)
5375 << ctx <<
": row " << i <<
" has size " << input[i].size()
5376 <<
" but expected " <<
cols;
5388 flat.
reserve(shape[0] * shape[1]);
5389 for (
size_t row = 0;
row < shape[0]; ++
row)
5390 for (
size_t col = 0;
col < shape[1]; ++
col)
5403 << ctx <<
": matrix shape must be positive";
5405 << ctx <<
": flat size " << input.
size()
5406 <<
" does not match matrix shape " <<
rows <<
"x" <<
cols;
5426 << ctx <<
": tensor must be non-empty";
5427 const size_t dim0 = input.
size();
5428 const size_t dim1 = input[0].size();
5430 << ctx <<
": tensor middle dimension must be positive";
5431 const size_t dim2 = input[0][0].size();
5433 << ctx <<
": tensor innermost dimension must be positive";
5435 for (
size_t i = 0; i < dim0; ++i)
5438 << ctx <<
": slab " << i <<
" has size " << input[i].size()
5439 <<
" but expected " << dim1;
5440 for (
size_t j = 0; j < dim1; ++j)
5442 << ctx <<
": slab " << i <<
", row " << j
5443 <<
" has size " << input[i][j].size()
5444 <<
" but expected " << dim2;
5447 return {dim0, dim1, dim2};
5457 flat.
reserve(shape[0] * shape[1] * shape[2]);
5458 for (
size_t i = 0; i < shape[0]; ++i)
5459 for (
size_t j = 0; j < shape[1]; ++j)
5460 for (
size_t k = 0;
k < shape[2]; ++
k)
5474 << ctx <<
": tensor shape must be positive";
5476 << ctx <<
": flat size " << input.
size()
5477 <<
" does not match tensor shape";
5481 for (
size_t i = 0; i < dim0; ++i)
5484 for (
size_t j = 0; j < dim1; ++j)
5487 for (
size_t k = 0;
k < dim2; ++
k, ++index)
5488 output(i)(j)(
k) = input[index];
5503 if (source == target or input.is_empty())
5508 const size_t channels = input.size();
5509 const size_t frames = input[0].size();
5511 frames == 0 ? 0 : input[0][0].size();
5513 for (
size_t ch = 0; ch < channels; ++ch)
5516 << ctx <<
": channel " << ch <<
" has " << input[ch].size()
5517 <<
" frames but expected " << frames;
5518 for (
size_t frame = 0; frame < frames; ++frame)
5520 << ctx <<
": channel " << ch <<
", frame " << frame
5521 <<
" has " << input[ch][frame].size()
5522 <<
" bins but expected " << bins;
5526 for (
size_t frame = 0; frame < frames; ++frame)
5529 for (
size_t ch = 0; ch < channels; ++ch)
5530 output(frame)(ch) = input[ch][frame];
5535 const size_t frames = input.
size();
5536 const size_t channels = input[0].size();
5537 const size_t bins = channels == 0 ? 0 : input[0][0].size();
5538 for (
size_t frame = 0; frame < frames; ++frame)
5541 << ctx <<
": frame " << frame <<
" has " << input[frame].size()
5542 <<
" channels but expected " << channels;
5543 for (
size_t ch = 0; ch < channels; ++ch)
5545 << ctx <<
": frame " << frame <<
", channel " << ch
5546 <<
" has " << input[frame][ch].size()
5547 <<
" bins but expected " << bins;
5551 for (
size_t ch = 0; ch < channels; ++ch)
5554 for (
size_t frame = 0; frame < frames; ++frame)
5555 output(ch)(frame) = input[frame][ch];
5571 return to_array<Complex>(input);
5581 const size_t chunk_size = 0)
5583 const size_t n = input.
size();
5585 <<
"FFT::transform: input must be non-empty";
5588 return {
Complex(input[0], Real(0))};
5597 const size_t half = n / 2;
5600 for (
size_t i = 0; i < half; ++i)
5606 const Complex half_i(Real(0), Real(-0.5));
5607 const Real base_angle = -Real(2) * std::numbers::pi_v<Real>
5608 /
static_cast<Real
>(n);
5609 auto recombine = [&packed, &
spectrum, half_i, half, base_angle](
const size_t k)
5611 const size_t mirror = (half -
k) % half;
5613 const Complex zmk = std::conj(packed[mirror]);
5614 const Complex even = (zk + zmk) * Real(0.5);
5615 const Complex odd = half_i * (zk - zmk);
5618 spectrum(
k + half) = even - twiddle * odd;
5621 if (pool !=
nullptr and pool->num_threads() > 1
and half > 1)
5624 for (
size_t k = 0;
k < half; ++
k)
5634 template <
typename InversePackedTransform>
5639 const size_t chunk_size,
5640 InversePackedTransform inverse_packed)
5642 const size_t n = input.
size();
5644 << ctx <<
": input must be non-empty";
5649 return {input[0].real()};
5653 << ctx <<
": input size " << n <<
" must be a power of two";
5657 const size_t half = n / 2;
5659 const Real base_angle = -Real(2) * std::numbers::pi_v<Real>
5660 /
static_cast<Real
>(n);
5662 auto build_packed_spectrum = [&input, &packed_spectrum, half, base_angle]
5665 const Complex even = (input[
k] + input[
k + half]) * Real(0.5);
5666 const Complex odd = (input[
k] - input[
k + half])
5669 packed_spectrum(
k) = even +
Complex(-odd.imag(), odd.real());
5675 for (
size_t k = 0;
k < half; ++
k)
5676 build_packed_spectrum(
k);
5678 inverse_packed(packed_spectrum, pool, chunk_size);
5681 auto unpack_output = [&packed_spectrum, &
output](
const size_t i)
5683 output(2 * i) = packed_spectrum[i].real();
5684 output(2 * i + 1) = packed_spectrum[i].imag();
5690 for (
size_t i = 0; i < half; ++i)
5703 const size_t chunk_size = 0)
5709 <<
"FFT::multiply: product size exceeds size_t capacity";
5711 const size_t required = a.
size() + b.
size() - 1;
5718 for (
size_t i = 0; i < n; ++i)
5724 const Complex half_i(Real(0), Real(-0.5));
5725 auto build_product = [&packed, &packed_spectrum, half_i, n](
const size_t k)
5727 const size_t mirror = (n -
k) % n;
5728 const Complex pk = packed_spectrum[
k];
5729 const Complex pm = std::conj(packed_spectrum[mirror]);
5730 const Complex fa = (pk + pm) * Real(0.5);
5731 const Complex fb = half_i * (pk - pm);
5732 packed(
k) = fa * fb;
5735 if (pool !=
nullptr and pool->num_threads() > 1
and n > 1)
5738 for (
size_t k = 0;
k < n; ++
k)
5750 const size_t chunk_size = 0)
5756 <<
"FFT::multiply: product size exceeds size_t capacity";
5758 const size_t required = a.
size() + b.
size() - 1;
5767 auto pointwise_product = [&fa, &fb](
const size_t i)
5772 if (pool !=
nullptr and pool->num_threads() > 1
and n > 1)
5775 for (
size_t i = 0; i < n; ++i)
5776 pointwise_product(i);
5802 for (
size_t i = 0; i < input.
size(); ++i)
5804 const Real imag = std::abs(input[i].imag());
5805 const Real scale = std::abs(input[i].real()) + std::abs(input[i].imag()) + Real(1);
5806 const Real tolerance = Real(128) * stages
5807 * std::numeric_limits<Real>::epsilon() * scale;
5810 << ctx <<
": coefficient " << i
5811 <<
" has non-negligible imaginary part " << input[i].imag();
5830 const size_t n = a.size();
5831 for (
size_t i = 1, j = 0; i < n; ++i)
5833 size_t bit = n >> 1;
5834 for (; j & bit; bit >>= 1)
5838 std::swap(a(i), a(j));
5850 [[nodiscard]]
static size_t
5854 <<
"FFT::next_power_of_two: input size must be positive";
5860 <<
"FFT::next_power_of_two: size overflow for input " << n;
5871 const size_t chunk_size = 0)
5873 const size_t n = a.
size();
5875 <<
"FFT::transform: input must be non-empty";
5881 <<
"FFT::transform: input size " << n <<
" must be a power of two";
5886 for (
size_t tmp = n; tmp > 1; tmp >>= 1)
5889 size_t r4_start_len;
5895 const size_t blocks = n >> 1;
5896 auto r2_block = [&a](
const size_t block)
5898 const size_t base = block << 1;
5900 const Complex v = a[base + 1];
5902 a(base + 1) = u - v;
5905 if (pool !=
nullptr and pool->num_threads() > 1
and blocks > 1)
5908 for (
size_t block = 0; block < blocks; ++block)
5918 for (
size_t len = r4_start_len; len <= n; len <<= 2)
5920 const size_t quarter = len >> 2;
5921 const size_t blocks = n / len;
5922 const Real angle = (invert ? Real(2) : Real(-2))
5923 * std::numbers::pi_v<Real>
5924 /
static_cast<Real
>(len);
5925 const Complex w_step = std::polar(Real(1), angle);
5927 auto r4_block = [&a, quarter, angle, w_step, invert]
5928 (
const size_t block)
5930 const size_t base = block * (quarter << 2);
5932 for (
size_t j = 0; j < quarter; ++j)
5937 const size_t i0 = base + j;
5938 const size_t i1 = i0 + quarter;
5939 const size_t i2 = i1 + quarter;
5940 const size_t i3 = i2 + quarter;
5943 const Complex a1 = a[i1] * w2;
5944 const Complex a2 = a[i2] * w1;
5945 const Complex a3 = a[i3] * w3;
5960 if (j + 1 < quarter)
5962 const size_t next_j = j + 1;
5971 if (pool !=
nullptr and pool->num_threads() > 1
and blocks > 1)
5974 for (
size_t block = 0; block < blocks; ++block)
5980 const Real inv_n = Real(1) /
static_cast<Real
>(n);
5981 for (
size_t i = 0; i < n; ++i)
5998 else if (n % 5 == 0)
6000 else if (n % 3 == 0)
6002 else if (n % 2 == 0)
6023 [[nodiscard]]
static constexpr bool
6026 return n > 0
and (n & (n - 1)) == 0;
6030 [[nodiscard]]
static constexpr const char *
6046 [[nodiscard]]
static constexpr const char *
6064 [[nodiscard]]
static constexpr bool
6067# if ALEPH_FFT_HAS_X86_AVX2_DISPATCH
6068 return std::same_as<Real, double>;
6075 [[nodiscard]]
static constexpr bool
6078# if ALEPH_FFT_HAS_ARM_NEON_DISPATCH
6079 if constexpr (std::same_as<Real, float>)
6081# if ALEPH_FFT_HAS_ARM_NEON_DOUBLE
6082 if constexpr (std::same_as<Real, double>)
6092 [[nodiscard]]
static bool
6095# if ALEPH_FFT_HAS_X86_AVX2_DISPATCH
6096 if constexpr (std::same_as<Real, double>)
6098 static const bool available = []()
noexcept
6100 __builtin_cpu_init();
6101 return static_cast<bool>(__builtin_cpu_supports(
"avx2"));
6112 [[nodiscard]]
static bool
6115# if ALEPH_FFT_HAS_ARM_NEON_DISPATCH
6116 if constexpr (std::same_as<Real, float>)
6121# if defined(__linux__)
6122 static const bool available = []()
noexcept
6127# if defined(__aarch64__) and defined(HWCAP_ASIMD)
6128 return (getauxval(AT_HWCAP) & HWCAP_ASIMD) != 0;
6129# elif defined(__arm__) and defined(HWCAP_NEON)
6130 return (getauxval(AT_HWCAP) & HWCAP_NEON) != 0;
6141# if ALEPH_FFT_HAS_ARM_NEON_DOUBLE
6142 if constexpr (std::same_as<Real, double>)
6147# if defined(__linux__) and defined(HWCAP_ASIMD)
6148 static const bool available = []()
noexcept
6150 return (getauxval(AT_HWCAP) & HWCAP_ASIMD) != 0;
6176 [[nodiscard]]
static const char *
6193 const char *disabled = std::getenv(
"ALEPH_FFT_DISABLE_AVX2");
6194 if (disabled !=
nullptr and disabled[0] !=
'\0' and disabled[0] !=
'0')
6197 if (
const char *
mode = std::getenv(
"ALEPH_FFT_SIMD");
6201 if (
value ==
"scalar")
6203 if (
value ==
"avx2")
6205 if (
value ==
"neon")
6210 const char *enabled = std::getenv(
"ALEPH_FFT_ENABLE_AVX2");
6211 if (enabled !=
nullptr and enabled[0] !=
'\0' and enabled[0] !=
'0')
6239 [[nodiscard]]
static const char *
6270 [[nodiscard]]
static const char *
6277 [[nodiscard]]
static const char *
6284 [[nodiscard]]
static bool
6291 [[nodiscard]]
static bool
6347 for (
size_t tmp =
n_; tmp > 1; tmp >>= 1)
6352 for (
size_t i = 1, j = 0; i <
n_; ++i)
6354 size_t bit =
n_ >> 1;
6355 for (; j & bit; bit >>= 1)
6362 for (
size_t stage = 0; stage <
log_n_; ++stage)
6364 const size_t half =
static_cast<size_t>(1) << stage;
6365 const size_t len = half << 1;
6366 const Real angle = Real(-2) * std::numbers::pi_v<Real>
6367 /
static_cast<Real
>(len);
6368 const size_t offset = half - 1;
6369 for (
size_t j = 0; j < half; ++j)
6371 angle *
static_cast<Real
>(j));
6382 for (
size_t i = 0; i <
n_; ++i)
6383 roots_(i) = std::polar(Real(1),
6384 Real(-2) * std::numbers::pi_v<Real>
6385 *
static_cast<Real
>(i)
6386 /
static_cast<Real
>(
n_));
6397 for (
size_t i = 0; i <
n_; ++i)
6399 const Real
value =
static_cast<Real
>(i);
6400 const Real phase = std::numbers::pi_v<Real> *
value *
value
6401 /
static_cast<Real
>(
n_);
6409 forward_kernel(i) =
Complex(Real(0), Real(0));
6410 inverse_kernel(i) =
Complex(Real(0), Real(0));
6413 forward_kernel(0) =
Complex(Real(1), Real(0));
6414 inverse_kernel(0) =
Complex(Real(1), Real(0));
6415 for (
size_t i = 1; i <
n_; ++i)
6432 for (
size_t i = 0; i <
n_; ++i)
6437# if ALEPH_FFT_HAS_X86_AVX2_DISPATCH
6438 static ALEPH_FFT_AVX2_TARGET __m256d
6439 avx2_load_complex_pair(
const Complex *ptr)
requires std::same_as<Real, double>
6441 static_assert(
sizeof(
Complex) ==
sizeof(
double) * 2);
6442 return _mm256_loadu_pd(
reinterpret_cast<const double *
>(ptr));
6445 static ALEPH_FFT_AVX2_TARGET
void
6446 avx2_store_complex_pair(
Complex *ptr,
6447 const __m256d
value)
requires std::same_as<Real, double>
6449 static_assert(
sizeof(
Complex) ==
sizeof(
double) * 2);
6450 _mm256_storeu_pd(
reinterpret_cast<double *
>(ptr),
value);
6453 [[nodiscard]]
static ALEPH_FFT_AVX2_TARGET __m256d
6454 avx2_conjugate_pair(
const __m256d
value)
requires std::same_as<Real, double>
6456 const __m256d mask = _mm256_set_pd(-0.0, 0.0, -0.0, 0.0);
6457 return _mm256_xor_pd(
value, mask);
6460 [[nodiscard]]
static ALEPH_FFT_AVX2_TARGET __m256d
6461 avx2_complex_mul_pair(
const __m256d lhs,
6462 const __m256d rhs)
requires std::same_as<Real, double>
6464 const __m256d rhs_real = _mm256_movedup_pd(rhs);
6465 const __m256d rhs_imag = _mm256_permute_pd(rhs, 0xF);
6466 const __m256d lhs_swapped = _mm256_permute_pd(lhs, 0x5);
6467 return _mm256_addsub_pd(_mm256_mul_pd(lhs, rhs_real),
6468 _mm256_mul_pd(lhs_swapped, rhs_imag));
6471 [[nodiscard]]
static ALEPH_FFT_AVX2_TARGET __m256d
6472 avx2_rotate_js_pair(
const __m256d
value,
6473 const bool invert)
requires std::same_as<Real, double>
6475 const __m256d swapped = _mm256_permute_pd(
value, 0x5);
6476 const __m256d forward_mask = _mm256_set_pd(-0.0, 0.0, -0.0, 0.0);
6477 const __m256d inverse_mask = _mm256_set_pd(0.0, -0.0, 0.0, -0.0);
6478 return _mm256_xor_pd(swapped, invert ? inverse_mask : forward_mask);
6481 static ALEPH_FFT_AVX2_TARGET
void
6483 requires std::same_as<Real, double>
6485 const __m256d uv = avx2_load_complex_pair(&a[base]);
6486 const __m128d u = _mm256_castpd256_pd128(uv);
6487 const __m128d v = _mm256_extractf128_pd(uv, 1);
6488 const __m128d
sum = _mm_add_pd(u, v);
6489 const __m128d
diff = _mm_sub_pd(u, v);
6490 avx2_store_complex_pair(&a[base], _mm256_set_m128d(
diff, sum));
6493 static ALEPH_FFT_AVX2_TARGET
void
6495 requires std::same_as<Real, double>
6497 for (
size_t block = 0;
block < blocks; ++
block)
6498 avx2_apply_r2_block(a, block << 1);
6501 ALEPH_FFT_AVX2_TARGET
void
6503 const size_t quarter,
6504 const size_t tw_w1_off,
6505 const size_t tw_w2_off,
6507 const size_t block)
const
6508 requires std::same_as<Real, double>
6510 const size_t base =
block * (quarter << 2);
6512 for (; j + 1 < quarter; j += 2)
6514 __m256d w1 = avx2_load_complex_pair(&
twiddles_[tw_w1_off + j]);
6515 __m256d w2 = avx2_load_complex_pair(&
twiddles_[tw_w2_off + j]);
6518 w1 = avx2_conjugate_pair(w1);
6519 w2 = avx2_conjugate_pair(w2);
6521 const __m256d w3 = avx2_complex_mul_pair(w1, w2);
6523 const size_t i0 = base + j;
6524 const size_t i1 = i0 + quarter;
6525 const size_t i2 = i1 + quarter;
6526 const size_t i3 = i2 + quarter;
6528 const __m256d a0 = avx2_load_complex_pair(&a[i0]);
6529 const __m256d a1 = avx2_complex_mul_pair(avx2_load_complex_pair(&a[i1]), w2);
6530 const __m256d a2 = avx2_complex_mul_pair(avx2_load_complex_pair(&a[i2]), w1);
6531 const __m256d a3 = avx2_complex_mul_pair(avx2_load_complex_pair(&a[i3]), w3);
6533 const __m256d p = _mm256_add_pd(a0, a1);
6534 const __m256d q = _mm256_sub_pd(a0, a1);
6535 const __m256d
r = _mm256_add_pd(a2, a3);
6536 const __m256d s = _mm256_sub_pd(a2, a3);
6537 const __m256d js = avx2_rotate_js_pair(s, invert);
6539 avx2_store_complex_pair(&a[i0], _mm256_add_pd(p,
r));
6540 avx2_store_complex_pair(&a[i1], _mm256_add_pd(q, js));
6541 avx2_store_complex_pair(&a[i2], _mm256_sub_pd(p,
r));
6542 avx2_store_complex_pair(&a[i3], _mm256_sub_pd(q, js));
6545 for (; j < quarter; ++j)
6553 const size_t i0 = base + j;
6554 const size_t i1 = i0 + quarter;
6555 const size_t i2 = i1 + quarter;
6556 const size_t i3 = i2 + quarter;
6559 const Complex a1 = a[i1] * w2;
6560 const Complex a2 = a[i2] * w1;
6561 const Complex a3 = a[i3] * w3;
6577 static ALEPH_FFT_AVX2_TARGET
void
6579 const Real inv_n)
requires std::same_as<Real, double>
6581 const __m256d scale = _mm256_set1_pd(inv_n);
6583 for (; i + 1 < a.size(); i += 2)
6584 avx2_store_complex_pair(&a[i],
6585 _mm256_mul_pd(avx2_load_complex_pair(&a[i]), scale));
6586 for (; i < a.size(); ++i)
6590 ALEPH_FFT_AVX2_TARGET
void
6592 const size_t quarter,
6593 const size_t blocks,
6594 const size_t tw_w1_off,
6595 const size_t tw_w2_off,
6596 const bool invert)
const
6597 requires std::same_as<Real, double>
6599 for (
size_t block = 0;
block < blocks; ++
block)
6600 avx2_apply_r4_block(a, quarter, tw_w1_off, tw_w2_off, invert, block);
6604# if ALEPH_FFT_HAS_ARM_NEON_DISPATCH
6605 struct NeonComplexPairFloat
6611# if ALEPH_FFT_HAS_ARM_NEON_DOUBLE
6612 struct NeonComplexPairDouble
6619 [[nodiscard]]
static NeonComplexPairFloat
6620 neon_load_complex_pair(
const Complex *ptr)
requires std::same_as<Real, float>
6622 static_assert(
sizeof(
Complex) ==
sizeof(
float) * 2);
6623 const float32x2x2_t interleaved =
6624 vld2_f32(
reinterpret_cast<const float *
>(ptr));
6625 return {interleaved.val[0], interleaved.val[1]};
6629 neon_store_complex_pair(
Complex *ptr,
6630 const NeonComplexPairFloat
value)
requires std::same_as<Real, float>
6632 static_assert(
sizeof(
Complex) ==
sizeof(
float) * 2);
6633 const float32x2x2_t interleaved = {
value.re,
value.im};
6634 vst2_f32(
reinterpret_cast<float *
>(ptr), interleaved);
6637 [[nodiscard]]
static NeonComplexPairFloat
6638 neon_conjugate_pair(
const NeonComplexPairFloat
value)
requires std::same_as<Real, float>
6643 [[nodiscard]]
static NeonComplexPairFloat
6644 neon_complex_mul_pair(
const NeonComplexPairFloat lhs,
6645 const NeonComplexPairFloat rhs)
requires std::same_as<Real, float>
6648 vsub_f32(vmul_f32(lhs.re, rhs.re), vmul_f32(lhs.im, rhs.im)),
6649 vadd_f32(vmul_f32(lhs.re, rhs.im), vmul_f32(lhs.im, rhs.re))
6653 [[nodiscard]]
static NeonComplexPairFloat
6654 neon_add_pair(
const NeonComplexPairFloat lhs,
6655 const NeonComplexPairFloat rhs)
requires std::same_as<Real, float>
6657 return {vadd_f32(lhs.re, rhs.re), vadd_f32(lhs.im, rhs.im)};
6660 [[nodiscard]]
static NeonComplexPairFloat
6661 neon_sub_pair(
const NeonComplexPairFloat lhs,
6662 const NeonComplexPairFloat rhs)
requires std::same_as<Real, float>
6664 return {vsub_f32(lhs.re, rhs.re), vsub_f32(lhs.im, rhs.im)};
6667 [[nodiscard]]
static NeonComplexPairFloat
6668 neon_rotate_js_pair(
const NeonComplexPairFloat
value,
6669 const bool invert)
requires std::same_as<Real, float>
6672 NeonComplexPairFloat{vneg_f32(
value.im),
value.re} :
6673 NeonComplexPairFloat{
value.im, vneg_f32(
value.re)};
6676# if ALEPH_FFT_HAS_ARM_NEON_DOUBLE
6677 [[nodiscard]]
static NeonComplexPairDouble
6678 neon_load_complex_pair(
const Complex *ptr)
requires std::same_as<Real, double>
6680 static_assert(
sizeof(
Complex) ==
sizeof(
double) * 2);
6681 const float64x2x2_t interleaved =
6682 vld2q_f64(
reinterpret_cast<const double *
>(ptr));
6683 return {interleaved.val[0], interleaved.val[1]};
6687 neon_store_complex_pair(
Complex *ptr,
6688 const NeonComplexPairDouble
value)
requires std::same_as<Real, double>
6690 static_assert(
sizeof(
Complex) ==
sizeof(
double) * 2);
6691 const float64x2x2_t interleaved = {
value.re,
value.im};
6692 vst2q_f64(
reinterpret_cast<double *
>(ptr), interleaved);
6695 [[nodiscard]]
static NeonComplexPairDouble
6696 neon_conjugate_pair(
const NeonComplexPairDouble
value)
requires std::same_as<Real, double>
6701 [[nodiscard]]
static NeonComplexPairDouble
6702 neon_complex_mul_pair(
const NeonComplexPairDouble lhs,
6703 const NeonComplexPairDouble rhs)
requires std::same_as<Real, double>
6706 vsubq_f64(vmulq_f64(lhs.re, rhs.re), vmulq_f64(lhs.im, rhs.im)),
6707 vaddq_f64(vmulq_f64(lhs.re, rhs.im), vmulq_f64(lhs.im, rhs.re))
6711 [[nodiscard]]
static NeonComplexPairDouble
6712 neon_add_pair(
const NeonComplexPairDouble lhs,
6713 const NeonComplexPairDouble rhs)
requires std::same_as<Real, double>
6715 return {vaddq_f64(lhs.re, rhs.re), vaddq_f64(lhs.im, rhs.im)};
6718 [[nodiscard]]
static NeonComplexPairDouble
6719 neon_sub_pair(
const NeonComplexPairDouble lhs,
6720 const NeonComplexPairDouble rhs)
requires std::same_as<Real, double>
6722 return {vsubq_f64(lhs.re, rhs.re), vsubq_f64(lhs.im, rhs.im)};
6725 [[nodiscard]]
static NeonComplexPairDouble
6726 neon_rotate_js_pair(
const NeonComplexPairDouble
value,
6727 const bool invert)
requires std::same_as<Real, double>
6730 NeonComplexPairDouble{vnegq_f64(
value.im),
value.re} :
6731 NeonComplexPairDouble{
value.im, vnegq_f64(
value.re)};
6737 const size_t quarter,
6738 const size_t tw_w1_off,
6739 const size_t tw_w2_off,
6741 const size_t block)
const
6743 const size_t base =
block * (quarter << 2);
6745 for (; j + 1 < quarter; j += 2)
6747 auto w1 = neon_load_complex_pair(&
twiddles_[tw_w1_off + j]);
6748 auto w2 = neon_load_complex_pair(&
twiddles_[tw_w2_off + j]);
6751 w1 = neon_conjugate_pair(w1);
6752 w2 = neon_conjugate_pair(w2);
6754 const auto w3 = neon_complex_mul_pair(w1, w2);
6756 const size_t i0 = base + j;
6757 const size_t i1 = i0 + quarter;
6758 const size_t i2 = i1 + quarter;
6759 const size_t i3 = i2 + quarter;
6761 const auto a0 = neon_load_complex_pair(&a[i0]);
6762 const auto a1 = neon_complex_mul_pair(neon_load_complex_pair(&a[i1]), w2);
6763 const auto a2 = neon_complex_mul_pair(neon_load_complex_pair(&a[i2]), w1);
6764 const auto a3 = neon_complex_mul_pair(neon_load_complex_pair(&a[i3]), w3);
6766 const auto p = neon_add_pair(a0, a1);
6767 const auto q = neon_sub_pair(a0, a1);
6768 const auto r = neon_add_pair(a2, a3);
6769 const auto s = neon_sub_pair(a2, a3);
6770 const auto js = neon_rotate_js_pair(s, invert);
6772 neon_store_complex_pair(&a[i0], neon_add_pair(p,
r));
6773 neon_store_complex_pair(&a[i1], neon_add_pair(q, js));
6774 neon_store_complex_pair(&a[i2], neon_sub_pair(p,
r));
6775 neon_store_complex_pair(&a[i3], neon_sub_pair(q, js));
6778 for (; j < quarter; ++j)
6786 const size_t i0 = base + j;
6787 const size_t i1 = i0 + quarter;
6788 const size_t i2 = i1 + quarter;
6789 const size_t i3 = i2 + quarter;
6792 const Complex a1 = a[i1] * w2;
6793 const Complex a2 = a[i2] * w1;
6794 const Complex a3 = a[i3] * w3;
6814 if constexpr (std::same_as<Real, float>)
6816 const float32x2_t scale = vdup_n_f32(inv_n);
6817 for (; i + 1 < a.
size(); i += 2)
6819 auto pair = neon_load_complex_pair(&a[i]);
6820 pair.re = vmul_f32(
pair.re, scale);
6821 pair.im = vmul_f32(
pair.im, scale);
6822 neon_store_complex_pair(&a[i],
pair);
6825# if ALEPH_FFT_HAS_ARM_NEON_DOUBLE
6826 else if constexpr (std::same_as<Real, double>)
6828 const float64x2_t scale = vdupq_n_f64(inv_n);
6829 for (; i + 1 < a.
size(); i += 2)
6831 auto pair = neon_load_complex_pair(&a[i]);
6832 pair.re = vmulq_f64(
pair.re, scale);
6833 pair.im = vmulq_f64(
pair.im, scale);
6834 neon_store_complex_pair(&a[i],
pair);
6838 for (; i<a.
size();++i)
6844 const size_t quarter,
6845 const size_t blocks,
6846 const size_t tw_w1_off,
6847 const size_t tw_w2_off,
6848 const bool invert)
const
6850 for (
size_t block = 0;
block < blocks; ++
block)
6851 neon_apply_r4_block(a, quarter, tw_w1_off, tw_w2_off, invert, block);
6858 return batch_size >= 4
6866 const bool prefer_simd)
const noexcept
6868 if constexpr (not std::same_as<Real, double>)
6874 if (pool !=
nullptr and pool->num_threads() > 1)
6895 const bool prefer_simd)
const noexcept
6899 if constexpr (not (std::same_as<Real, double> or std::same_as<Real, float>))
6905 if (pool !=
nullptr and pool->num_threads() > 1)
6926 const size_t chunk_size,
6927 const bool prefer_simd)
const
6929 [[maybe_unused]]
const bool use_avx2 =
should_use_avx2(pool, prefer_simd);
6930 [[maybe_unused]]
const bool use_neon =
should_use_neon(pool, prefer_simd);
6932# if ALEPH_FFT_HAS_X86_AVX2_DISPATCH
6933 if constexpr (std::same_as<Real, double>)
6940 avx2_apply_r2_stage(a,
n_ >> 1);
6944 while (stage + 1 <
log_n_)
6946 const size_t s_low = stage;
6947 const size_t s_high = stage + 1;
6948 const size_t quarter =
static_cast<size_t>(1) << s_low;
6949 const size_t blocks =
n_ >> (s_high + 1);
6950 const size_t tw_w1_off = (
static_cast<size_t>(1) << s_high) - 1;
6951 const size_t tw_w2_off = quarter - 1;
6952 avx2_apply_r4_stage(a, quarter, blocks,
6953 tw_w1_off, tw_w2_off, invert);
6958 avx2_scale_output(a, Real(1) /
static_cast<Real
>(
n_));
6963# if ALEPH_FFT_HAS_ARM_NEON_DISPATCH
6970 if constexpr (std::same_as<Real, double> or std::same_as<Real, float>)
6977 const size_t blocks =
n_ >> 1;
6978 for (
size_t block = 0; block < blocks; ++block)
6980 const size_t base = block << 1;
6982 const Complex v = a[base + 1];
6984 a(base + 1) = u - v;
6989 while (stage + 1 <
log_n_)
6991 const size_t s_low = stage;
6992 const size_t s_high = stage + 1;
6993 const size_t quarter = size_t(1) << s_low;
6994 const size_t blocks =
n_ >> (s_high + 1);
6995 const size_t tw_w1_off = (size_t(1) << s_high) - 1;
6996 const size_t tw_w2_off = quarter - 1;
6997 neon_apply_r4_stage(a, quarter, blocks,
6998 tw_w1_off, tw_w2_off, invert);
7003 neon_scale_output(a, Real(1) /
static_cast<Real
>(
n_));
7013 const size_t blocks =
n_ >> 1;
7014 auto r2_block = [&a](
const size_t block)
7016 const size_t base = block << 1;
7018 const Complex v = a[base + 1];
7020 a(base + 1) = u - v;
7026 for (
size_t block = 0; block < blocks; ++block)
7035 while (stage + 1 <
log_n_)
7037 const size_t s_low = stage;
7038 const size_t s_high = stage + 1;
7039 const size_t quarter =
static_cast<size_t>(1) << s_low;
7040 const size_t blocks =
n_ >> (s_high + 1);
7041 const size_t tw_w1_off = (
static_cast<size_t>(1) << s_high) - 1;
7042 const size_t tw_w2_off = quarter - 1;
7044 auto r4_block = [
this, &a, quarter, tw_w1_off, tw_w2_off, invert]
7045 (
const size_t block)
7047 const size_t base = block * (quarter << 2);
7048 for (
size_t j = 0; j < quarter; ++j)
7052 const Complex w1 = invert ? std::conj(tw1) : tw1;
7053 const Complex w2 = invert ? std::conj(tw2) : tw2;
7056 const size_t i0 = base + j;
7057 const size_t i1 = i0 + quarter;
7058 const size_t i2 = i1 + quarter;
7059 const size_t i3 = i2 + quarter;
7062 const Complex a1 = a[i1] * w2;
7063 const Complex a2 = a[i2] * w1;
7064 const Complex a3 = a[i3] * w3;
7083 for (
size_t block = 0; block < blocks; ++block)
7091 const Real inv_n = Real(1) /
static_cast<Real
>(
n_);
7092 for (
size_t i = 0; i <
n_; ++i)
7101 const size_t chunk_size,
7102 const bool prefer_simd)
const
7105 <<
"FFT::Plan::transform: input size " << a.
size()
7106 <<
" does not match plan size " <<
n_;
7130 const size_t exponent,
7131 const bool invert)
const
7134 return Complex(Real(1), Real(0));
7136 const size_t stride =
n_ / length;
7137 const size_t index = ((exponent % length) * stride) %
n_;
7139 return invert ? std::conj(
root) :
root;
7144 const size_t factor_index,
7145 const size_t current_size,
7146 const bool invert)
const
7148 if (current_size <= 1)
7151 const size_t factor =
factors_[factor_index];
7152 const size_t sub_size = current_size / factor;
7155 subtransforms.
reserve(factor);
7156 for (
size_t q = 0; q < factor; ++q)
7159 subsequence.
reserve(sub_size);
7160 for (
size_t t = 0; t < sub_size; ++t)
7161 subsequence.
append(input[factor * t + q]);
7169 for (
size_t k1 = 0; k1 < sub_size; ++k1)
7170 for (
size_t p = 0; p < factor; ++p)
7173 const size_t target = k1 + sub_size * p;
7174 for (
size_t q = 0; q < factor; ++q)
7175 sum += subtransforms[q][k1]
7189 const Real inv_n = Real(1) /
static_cast<Real
>(
n_);
7190 for (
size_t i = 0; i <
n_; ++i)
7200 const size_t chunk_size)
const
7204 auto initialize = [
this, &a, &work, invert](
const size_t i)
7208 work(i) =
Complex(Real(0), Real(0));
7213 work(i) = a[i] * chirp;
7222 if (pool !=
nullptr)
7229 auto pointwise = [&work, &kernel](
const size_t i)
7231 work(i) *= kernel[i];
7240 if (pool !=
nullptr)
7245 auto finalize = [
this, &a, &work, invert](
const size_t i)
7248 a(i) = work[i] * chirp;
7250 a(i) /=
static_cast<Real
>(
n_);
7256 for (
size_t i = 0; i <
n_; ++i)
7283 <<
"FFT::Plan: size must be positive";
7323 :
n_(std::exchange(other.n_, 0)),
7325 log_n_(std::exchange(other.log_n_, 0)),
7326 bit_rev_(std::move(other.bit_rev_)),
7329 factors_(std::move(other.factors_)),
7330 roots_(std::move(other.roots_)),
7362 std::swap(
n_, other.n_);
7364 std::swap(
log_n_, other.log_n_);
7378 [[nodiscard]]
size_t size() const noexcept {
return n_; }
7399 const bool invert =
false)
const
7422 <<
"FFT::Plan::inverse_transform_real: input size " << input.
size()
7423 <<
" does not match plan size " <<
n_;
7430 input,
"FFT::Plan::inverse_transform_real",
nullptr, 0,
7445 const size_t chunk_size = 0)
const
7448 <<
"FFT::Plan::pinverse_transform_real: input size "
7449 << input.
size() <<
" does not match plan size " <<
n_;
7456 input,
"FFT::Plan::inverse_transform_real", &pool,
7459 const size_t inner_chunk_size)
7461 if (inner_pool !=
nullptr)
7462 half_plan_->ptransform(*inner_pool, packed,
true,
7483 const size_t chunk_size = 0)
const
7491 const bool invert =
false,
7492 const size_t chunk_size = 0)
const
7502 const size_t chunk_size = 0)
const
7511 const bool prefer_simd =
true)
const
7513 const bool effective_prefer_simd =
7515 for (
size_t i = 0; i < batch.size(); ++i)
7518 <<
"FFT::Plan::transform_batch: batch item " << i
7519 <<
" has size " << batch[i].size()
7520 <<
" but plan size is " <<
n_;
7535 const size_t chunk_size = 0,
7536 const bool prefer_simd =
true)
const
7538 const bool effective_prefer_simd =
7540 for (
size_t i = 0; i < batch.size(); ++i)
7542 <<
"FFT::Plan::ptransform_batch: batch item " << i
7543 <<
" has size " << batch[i].size()
7544 <<
" but plan size is " <<
n_;
7546 if (batch.is_empty())
7551 for (
size_t i = 0; i < batch.size(); ++i)
7556 effective_prefer_simd);
7560 auto transform_one = [
this, &batch, invert, effective_prefer_simd](
const size_t i)
7570 const bool invert =
false,
7571 const bool prefer_simd =
true)
const
7582 const bool invert =
false,
7583 const size_t chunk_size = 0,
7584 const bool prefer_simd =
true)
const
7602 const size_t chunk_size = 0,
7603 const bool prefer_simd =
true)
const
7615 for (
size_t i = 0; i < input.size(); ++i)
7618 <<
"FFT::Plan::inverse_transform_real_batch: batch item " << i
7619 <<
" has size " << input[i].size()
7620 <<
" but plan size is " <<
n_;
7632 const size_t chunk_size = 0,
7633 const bool prefer_simd [[maybe_unused]] =
true)
const
7635 for (
size_t i = 0; i < input.size(); ++i)
7637 <<
"FFT::Plan::pinverse_transform_real_batch: batch item " << i
7638 <<
" has size " << input[i].size()
7639 <<
" but plan size is " <<
n_;
7641 if (input.is_empty())
7647 for (
size_t i = 0; i < input.size(); ++i)
7652 auto inverse_one = [
this, &input, &
output](
const size_t i)
7671 <<
"FFT::Plan::rfft: input size " << input.
size()
7672 <<
" does not match plan size " <<
n_;
7679 const size_t chunk_size = 0)
const
7682 <<
"FFT::Plan::prfft: input size " << input.
size()
7683 <<
" does not match plan size " <<
n_;
7700 "FFT::Plan::irfft"));
7706 const size_t chunk_size = 0)
const
7711 "FFT::Plan::pirfft"),
7727 const size_t chunk_size = 0)
const
7738 spectra,
n_,
"FFT::Plan::irfft_batch"));
7745 const size_t chunk_size = 0)
const
7751 "FFT::Plan::pirfft_batch"),
7761 const size_t chunk_size = 0)
7764 if (pool !=
nullptr)
7765 plan.
ptransform(*pool, lifted,
false, chunk_size);
7775 const size_t chunk_size = 0)
7779 for (
size_t i = 0; i < input.size(); ++i)
7782 if (pool !=
nullptr)
7793 <<
"FFT::compact_real_spectrum: spectrum must be non-empty";
7797 for (
size_t i = 0; i <= full_spectrum.
size() / 2; ++i)
7798 compact.
append(full_spectrum[i]);
7806 compact.
reserve(full_spectra.size());
7807 for (
size_t i = 0; i < full_spectra.size(); ++i)
7812 [[nodiscard]]
static size_t
7814 const size_t signal_size,
7818 << ctx <<
": compact spectrum must be non-empty";
7820 if (signal_size != 0)
7823 << ctx <<
": compact spectrum size " <<
spectrum.
size()
7824 <<
" does not match signal size " << signal_size;
7832 > std::numeric_limits<size_t>::max() / 2)
7833 << ctx <<
": inferred signal size overflows size_t";
7839 const size_t signal_size,
7843 const size_t half = n / 2;
7846 for (
size_t i = 0; i < n; ++i)
7847 full(i) =
Complex(Real(0), Real(0));
7849 for (
size_t i = 0; i <= half; ++i)
7851 for (
size_t i = half + 1; i < n; ++i)
7852 full(i) = std::conj(full[n - i]);
7859 const size_t signal_size,
7864 for (
size_t i = 0; i < spectra.size(); ++i)
7875 for (
size_t i = 0; i < input.size(); ++i)
7884 const size_t chunk_size = 0)
7886 const size_t n = a.
size();
7899 if (pool !=
nullptr)
7900 plan.
ptransform(*pool, a, invert, chunk_size);
7909 const size_t chunk_size)
7952 const size_t chunk_size = 0)
7990 const bool invert =
false,
const size_t chunk_size = 0)
8001 if (batch.is_empty())
8013 const size_t chunk_size = 0)
8015 if (batch.is_empty())
8025 const bool invert =
false)
8036 const bool invert =
false,
8037 const size_t chunk_size = 0)
8055 const size_t chunk_size = 0)
8064 if (input.is_empty())
8075 const size_t chunk_size = 0)
8077 if (input.is_empty())
8087 const size_t signal_size)
8089 if (spectra.is_empty())
8092 Plan plan(signal_size);
8100 const size_t signal_size,
8101 const size_t chunk_size = 0)
8103 if (spectra.is_empty())
8106 Plan plan(signal_size);
8111 [[nodiscard]]
static TensorLayout
8115 layout.
shape = shape;
8137 const size_t chunk_size = 0)
8159 const size_t chunk_size = 0)
8169 const bool invert =
false)
8182 const bool invert =
false,
8183 const size_t chunk_size = 0)
8193 const bool invert =
false)
8201 "FFT::transformed2d");
8208 const bool invert =
false,
8209 const size_t chunk_size = 0)
8222 "FFT::ptransformed2d");
8236 const size_t chunk_size = 0)
8244 const bool invert =
false)
8248 "FFT::transformed2d_batch");
8254 "FFT::transformed2d_batch");
8261 const bool invert =
false,
8262 const size_t chunk_size = 0)
8266 "FFT::ptransformed2d_batch");
8277 "FFT::ptransformed2d_batch");
8283 const bool invert =
false)
8295 "FFT::transformed3d");
8302 const bool invert =
false,
8303 const size_t chunk_size = 0)
8317 "FFT::ptransformed3d");
8331 const size_t chunk_size = 0)
8347 "FFT::transpose_spectrogram_layout");
8377 const size_t chunk_size = 0)
8423 const size_t chunk_size = 0)
8450 const size_t chunk_size = 0)
8471 template <
typename Container>
8472 requires Is_Complex_Container<Container>
8489 template <
typename Container>
8490 requires Is_Complex_Container<Container>
8493 const size_t chunk_size = 0)
8511 template <
typename Container>
8512 requires Is_Complex_Container<Container>
8530 template <
typename Container>
8531 requires Is_Complex_Container<Container>
8534 const bool invert =
false,
const size_t chunk_size = 0)
8568 const size_t chunk_size = 0)
8588 const size_t chunk_size = 0)
8603 const size_t chunk_size = 0)
8610 template <
typename Container>
8611 requires Is_Complex_Container<Container>
8619 template <
typename Container>
8620 requires Is_Complex_Container<Container>
8623 const size_t chunk_size = 0)
8629 template <
typename Container>
8630 requires Is_Real_Container<Container>
8638 template <
typename Container>
8639 requires Is_Real_Container<Container>
8642 const size_t chunk_size = 0)
8648 template <
typename Container>
8649 requires Is_Real_Container<Container>
8657 template <
typename Container>
8658 requires Is_Real_Container<Container>
8661 const size_t chunk_size = 0)
8667 template <
typename Container>
8668 requires Is_Real_Container<Container>
8676 template <
typename Container>
8677 requires Is_Real_Container<Container>
8680 const size_t chunk_size = 0)
8695 const size_t chunk_size = 0)
8710 const size_t chunk_size = 0)
8716 template <
typename Container>
8717 requires Is_Complex_Container<Container>
8725 template <
typename Container>
8726 requires Is_Complex_Container<Container>
8729 const size_t chunk_size = 0)
8735 template <
typename Container>
8736 requires Is_Real_Container<Container>
8744 template <
typename Container>
8745 requires Is_Real_Container<Container>
8748 const size_t chunk_size = 0)
8772 const size_t chunk_size = 0)
8778 template <
typename Container>
8779 requires Is_Complex_Container<Container>
8787 template <
typename Container>
8788 requires Is_Complex_Container<Container>
8791 const size_t chunk_size = 0)
8812 "FFT::inverse_transform_real",
nullptr, 0,
8814 const size_t inner_chunk_size)
8819 "FFT::inverse_transform_real",
8827 const size_t chunk_size = 0)
8831 "FFT::inverse_transform_real", &pool, chunk_size,
8833 const size_t inner_chunk_size)
8838 "FFT::inverse_transform_real",
8861 const size_t signal_size = 0,
8862 const size_t chunk_size = 0)
8872 template <
typename Container>
8873 requires Is_Complex_Container<Container>
8881 template <
typename Container>
8882 requires Is_Complex_Container<Container>
8885 const size_t chunk_size = 0)
8891 template <
typename Container>
8892 requires Is_Complex_Container<Container>
8900 template <
typename Container>
8901 requires Is_Complex_Container<Container>
8905 const size_t signal_size = 0,
8906 const size_t chunk_size = 0)
8920 for (
size_t i = 0; i < input.
size(); ++i)
8921 output.append(std::abs(input[i]));
8926 template <
typename Container>
8927 requires Is_Complex_Container<Container>
8940 for (
size_t i = 0; i < input.
size(); ++i)
8941 output.append(std::norm(input[i]));
8945 template <
typename Container>
8946 requires Is_Complex_Container<Container>
8959 for (
size_t i = 0; i < input.
size(); ++i)
8960 output.append(std::arg(input[i]));
8964 template <
typename Container>
8965 requires Is_Complex_Container<Container>
8994 [[nodiscard]]
static Real
8998 <<
"FFT::kaiser_beta: attenuation " << attenuation_db
8999 <<
" must be non-negative";
9001 if (attenuation_db > Real(50))
9002 return Real(0.1102) * (attenuation_db - Real(8.7));
9003 if (attenuation_db >= Real(21))
9004 return Real(0.5842) * std::pow(attenuation_db - Real(21), Real(0.4))
9005 + Real(0.07886) * (attenuation_db - Real(21));
9015 <<
"FFT::kaiser_window: beta " << beta <<
" must be non-negative";
9023 const Real half =
static_cast<Real
>(n - 1) / Real(2);
9026 for (
size_t i = 0; i < n; ++i)
9028 const Real x = (
static_cast<Real
>(i) - half) / half;
9029 const Real arg = beta * std::sqrt(std::max(Real(0), Real(1) - x * x));
9040 <<
"FFT::apply_window: signal size " << signal.
size()
9041 <<
" does not match window size " << window.
size();
9044 for (
size_t i = 0; i < signal.
size(); ++i)
9045 output(i) = signal[i] * window[i];
9054 <<
"FFT::apply_window: signal size " << signal.
size()
9055 <<
" does not match window size " << window.
size();
9058 for (
size_t i = 0; i < signal.
size(); ++i)
9059 output(i) = signal[i] * window[i];
9063 template <
typename SignalContainer,
typename WindowContainer>
9064 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
9066 apply_window(
const SignalContainer & signal,
const WindowContainer & window)
9071 template <
typename SignalContainer,
typename WindowContainer>
9072 requires Is_Complex_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
9074 apply_window(
const SignalContainer & signal,
const WindowContainer & window)
9124 const Real cutoff_frequency,
9125 const Real sample_rate,
9132 "FFT::firwin_lowpass");
9138 const Real cutoff_frequency,
9139 const Real sample_rate,
9140 const Real attenuation_db)
9151 const Real cutoff_frequency,
9152 const Real sample_rate,
9160 "FFT::firwin_highpass");
9161 const size_t center = (num_taps - 1) / 2;
9162 for (
size_t i = 0; i < coeffs.
size(); ++i)
9163 coeffs(i) = -coeffs[i];
9164 coeffs(center) += Real(1);
9166 std::numbers::pi_v<Real>,
9167 "FFT::firwin_highpass");
9174 const Real cutoff_frequency,
9175 const Real sample_rate,
9176 const Real attenuation_db)
9187 const Real low_cutoff_frequency,
9188 const Real high_cutoff_frequency,
9189 const Real sample_rate,
9193 <<
"FFT::firwin_bandpass: low cutoff " << low_cutoff_frequency
9194 <<
" must be positive";
9196 <<
"FFT::firwin_bandpass: high cutoff " << high_cutoff_frequency
9197 <<
" must be greater than low cutoff " << low_cutoff_frequency;
9199 <<
"FFT::firwin_bandpass: high cutoff " << high_cutoff_frequency
9200 <<
" must be smaller than Nyquist " << (sample_rate / Real(2));
9204 high_cutoff_frequency,
9207 "FFT::firwin_bandpass");
9210 low_cutoff_frequency,
9213 "FFT::firwin_bandpass");
9215 for (
size_t i = 0; i < num_taps; ++i)
9216 coeffs(i) =
low[i] - high[i];
9218 const Real center_frequency = (low_cutoff_frequency + high_cutoff_frequency)
9219 / (Real(2) * sample_rate);
9221 Real(2) * std::numbers::pi_v<Real> * center_frequency,
9222 "FFT::firwin_bandpass");
9229 const Real low_cutoff_frequency,
9230 const Real high_cutoff_frequency,
9231 const Real sample_rate,
9232 const Real attenuation_db)
9235 low_cutoff_frequency,
9236 high_cutoff_frequency,
9244 const Real low_cutoff_frequency,
9245 const Real high_cutoff_frequency,
9246 const Real sample_rate,
9251 low_cutoff_frequency,
9252 high_cutoff_frequency,
9255 const size_t center = (num_taps - 1) / 2;
9256 for (
size_t i = 0; i < coeffs.
size(); ++i)
9257 coeffs(i) = -coeffs[i];
9258 coeffs(center) += Real(1);
9266 const Real low_cutoff_frequency,
9267 const Real high_cutoff_frequency,
9268 const Real sample_rate,
9269 const Real attenuation_db)
9272 low_cutoff_frequency,
9273 high_cutoff_frequency,
9283 const Real sample_rate,
9294 template <
typename BandContainer,
typename DesiredContainer>
9295 requires Is_Real_Container<BandContainer>
9296 and Is_Real_Container<DesiredContainer>
9299 const BandContainer & bands,
9300 const DesiredContainer & desired,
9301 const Real sample_rate)
9303 return firls(num_taps,
9310 template <
typename BandContainer,
typename DesiredContainer,
9311 typename WeightContainer>
9312 requires Is_Real_Container<BandContainer>
9313 and Is_Real_Container<DesiredContainer>
9314 and Is_Real_Container<WeightContainer>
9317 const BandContainer & bands,
9318 const DesiredContainer & desired,
9319 const Real sample_rate,
9320 const WeightContainer & weights)
9322 return firls(num_taps,
9334 const Real sample_rate,
9336 const size_t grid_density = 32,
9337 const size_t max_iterations = 64)
9349 template <
typename BandContainer,
typename DesiredContainer>
9350 requires Is_Real_Container<BandContainer>
9351 and Is_Real_Container<DesiredContainer>
9354 const BandContainer & bands,
9355 const DesiredContainer & desired,
9356 const Real sample_rate)
9358 return remez(num_taps,
9365 template <
typename BandContainer,
typename DesiredContainer,
9366 typename WeightContainer>
9367 requires Is_Real_Container<BandContainer>
9368 and Is_Real_Container<DesiredContainer>
9369 and Is_Real_Container<WeightContainer>
9372 const BandContainer & bands,
9373 const DesiredContainer & desired,
9374 const Real sample_rate,
9375 const WeightContainer & weights,
9376 const size_t grid_density = 32,
9377 const size_t max_iterations = 64)
9379 return remez(num_taps,
9392 const size_t up = 1,
9393 const size_t down = 1)
9396 <<
"FFT::upfirdn: up factor must be positive";
9398 <<
"FFT::upfirdn: down factor must be positive";
9400 <<
"FFT::upfirdn: FIR coefficients must be non-empty";
9405 <<
"FFT::upfirdn: upsampled signal length overflows size_t";
9406 const size_t convolved_length = signal.
size() * up + coeffs.
size() - 1;
9407 const size_t output_size = (convolved_length + down - 1) / down;
9410 for (
size_t i = 0; i < convolved_length; ++i)
9411 filtered(i) = Real(0);
9413 for (
size_t n = 0; n < signal.
size(); ++n)
9415 const size_t base = n * up;
9416 for (
size_t k = 0;
k < coeffs.
size(); ++
k)
9417 filtered(base +
k) += signal[n] * coeffs[
k];
9421 for (
size_t i = 0; i < output_size; ++i)
9422 output(i) = filtered[i * down];
9426 template <
typename SignalContainer,
typename CoeffContainer>
9427 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<CoeffContainer>
9430 const CoeffContainer & coeffs,
9431 const size_t up = 1,
9432 const size_t down = 1)
9448 <<
"FFT::resample_poly: up factor must be positive";
9450 <<
"FFT::resample_poly: down factor must be positive";
9452 <<
"FFT::resample_poly: FIR coefficients must be non-empty";
9456 const size_t gcd = std::gcd(up, down);
9457 const size_t reduced_up = up / gcd;
9458 const size_t reduced_down = down / gcd;
9462 const size_t start = (half_len + reduced_down - 1) / reduced_down;
9463 const size_t expected_size =
9464 (signal.
size() * reduced_up + reduced_down - 1) / reduced_down;
9467 <<
"FFT::resample_poly: internal trim offset exceeds raw output";
9469 const size_t available = raw.
size() - start;
9470 const size_t trimmed_size = std::min(expected_size, available);
9472 if (
output.size() == expected_size)
9476 for (
size_t i = 0; i < expected_size; ++i)
9489 <<
"FFT::resample_poly: taps_per_phase must be positive";
9491 <<
"FFT::resample_poly: attenuation " <<
options.attenuation_db
9492 <<
" must be strictly positive";
9496 const size_t gcd = std::gcd(up, down);
9497 const size_t reduced_up = up / gcd;
9498 const size_t reduced_down = down / gcd;
9499 const size_t rate = std::max(reduced_up, reduced_down);
9500 const size_t num_taps = 2 *
options.taps_per_phase * rate + 1;
9501 const Real effective_rate =
static_cast<Real
>(reduced_up);
9502 const Real cutoff = effective_rate / (Real(2) *
static_cast<Real
>(rate));
9509 for (
size_t i = 0; i < coeffs.
size(); ++i)
9510 coeffs(i) *=
static_cast<Real
>(reduced_up);
9512 return resample_poly(signal, reduced_up, reduced_down, coeffs);
9515 template <
typename SignalContainer,
typename CoeffContainer>
9516 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<CoeffContainer>
9521 const CoeffContainer & coeffs)
9529 template <
typename SignalContainer>
9530 requires Is_Real_Container<SignalContainer>
9540 template <
typename Container>
9541 requires Is_Real_Container<Container>
9548 template <
typename Container>
9549 requires Is_Real_Container<Container>
9556 template <
typename Container>
9557 requires Is_Real_Container<Container>
9564 template <
typename Container>
9565 requires Is_Complex_Container<Container>
9572 template <
typename Container>
9573 requires Is_Complex_Container<Container>
9580 template <
typename Container>
9581 requires Is_Complex_Container<Container>
9602 template <
typename SignalContainer,
typename WindowContainer>
9603 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
9606 const WindowContainer & window)
9611 template <
typename SignalContainer,
typename WindowContainer>
9612 requires Is_Complex_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
9615 const WindowContainer & window)
9621 [[nodiscard]]
static Real
9629 [[nodiscard]]
static Real
9633 <<
"FFT::window_coherent_gain: window must be non-empty";
9638 [[nodiscard]]
static Real
9642 <<
"FFT::window_enbw: window must be non-empty";
9643 const Real coherent_sum =
sum_values(window);
9645 <<
"FFT::window_enbw: coherent gain is zero";
9647 / (coherent_sum * coherent_sum);
9650 template <
typename Container>
9651 requires Is_Real_Container<Container>
9652 [[nodiscard]]
static Real
9658 template <
typename Container>
9659 requires Is_Real_Container<Container>
9660 [[nodiscard]]
static Real
9666 template <
typename Container>
9667 requires Is_Real_Container<Container>
9668 [[nodiscard]]
static Real
9677 const size_t frame_size,
9678 const size_t hop_size,
9679 const bool pad_end =
true)
9685 "FFT::frame_offsets");
9691 const size_t hop_size,
9692 const size_t signal_length = 0)
9695 <<
"FFT::overlap_add_frames: hop size must be positive";
9696 if (frames.is_empty())
9699 const size_t frame_size = frames[0].
size();
9701 <<
"FFT::overlap_add_frames: frames must be non-empty";
9702 for (
size_t i = 1; i < frames.size(); ++i)
9704 <<
"FFT::overlap_add_frames: frame " << i
9705 <<
" has size " << frames[i].size()
9706 <<
" but expected " << frame_size;
9708 const size_t total_length = hop_size * (frames.size() - 1) + frame_size;
9710 <<
"FFT::overlap_add_frames: requested signal length "
9711 << signal_length <<
" exceeds overlap-add extent " << total_length;
9714 for (
size_t i = 0; i < total_length; ++i)
9717 for (
size_t frame = 0; frame < frames.size(); ++frame)
9719 const size_t offset = frame * hop_size;
9720 for (
size_t i = 0; i < frame_size; ++i)
9724 return signal_length == 0 ?
9730 [[nodiscard]]
static PowerSpectralDensity
9733 const Real sample_rate,
9736 const char *ctx =
"FFT::welch";
9741 << ctx <<
": window energy must be strictly positive";
9743 Plan plan(fft_size);
9745 for (
size_t k = 0;
k < density.size(); ++
k)
9746 density(
k) = Real(0);
9748 for (
size_t i = 0; i < frames.
size(); ++i)
9760 const Real scale = Real(1)
9763 *
static_cast<Real
>(frames.
size()));
9771 [[nodiscard]]
static PowerSpectralDensity
9773 const size_t frame_size,
9774 const Real sample_rate,
9781 [[nodiscard]]
static CrossSpectralDensity
9785 const Real sample_rate,
9788 const auto ctx =
"FFT::csd";
9790 << ctx <<
": signal sizes " << x.
size()
9791 <<
" and " <<
y.size() <<
" do not match";
9797 << ctx <<
": frame count mismatch after preparation";
9801 << ctx <<
": window energy must be strictly positive";
9803 Plan plan(fft_size);
9805 for (
size_t k = 0;
k < density.size(); ++
k)
9806 density(
k) =
Complex(Real(0), Real(0));
9808 for (
size_t i = 0; i < x_frames.
size(); ++i)
9812 for (
size_t k = 0;
k < density.size(); ++
k)
9820 const Real scale = Real(1)
9823 *
static_cast<Real
>(x_frames.
size()));
9831 [[nodiscard]]
static CrossSpectralDensity
9834 const size_t frame_size,
9835 const Real sample_rate,
9842 [[nodiscard]]
static CoherenceEstimate
9846 const Real sample_rate,
9849 const CrossSpectralDensity pxy =
csd(x,
y, window, sample_rate,
options);
9850 const PowerSpectralDensity pxx =
welch(x, window, sample_rate,
options);
9851 const PowerSpectralDensity pyy =
welch(
y, window, sample_rate,
options);
9854 or pxy.density.size() != pyy.density.size())
9855 <<
"FFT::coherence: inconsistent spectrum sizes";
9857 CoherenceEstimate
output;
9858 output.frequency = pxy.frequency;
9860 const Real tol = Real(1024) * std::numeric_limits<Real>::epsilon();
9861 for (
size_t k = 0;
k < pxy.density.size(); ++
k)
9863 const Real denom = pxx.density[
k] * pyy.density[
k];
9865 denom <= tol ? Real(0) :
std::norm(pxy.density[
k]) / denom;
9871 [[nodiscard]]
static CoherenceEstimate
9874 const size_t frame_size,
9875 const Real sample_rate,
9881 template <
typename SignalContainer,
typename WindowContainer>
9882 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
9883 [[nodiscard]]
static PowerSpectralDensity
9885 const WindowContainer & window,
9886 const Real sample_rate,
9895 template <
typename ContainerX,
typename ContainerY,
typename WindowContainer>
9896 requires Is_Real_Container<ContainerX>
9897 and Is_Real_Container<ContainerY>
9898 and Is_Real_Container<WindowContainer>
9899 [[nodiscard]]
static CrossSpectralDensity
9901 const ContainerY &
y,
9902 const WindowContainer & window,
9903 const Real sample_rate,
9913 template <
typename ContainerX,
typename ContainerY,
typename WindowContainer>
9914 requires Is_Real_Container<ContainerX>
9915 and Is_Real_Container<ContainerY>
9916 and Is_Real_Container<WindowContainer>
9917 [[nodiscard]]
static CoherenceEstimate
9919 const ContainerY &
y,
9920 const WindowContainer & window,
9921 const Real sample_rate,
9935 const size_t hop_size)
9940 "FFT::window_overlap_profile");
9944 [[nodiscard]]
static bool
9947 const size_t hop_size)
9955 [[nodiscard]]
static bool
9958 const size_t hop_size)
9966 [[nodiscard]]
static bool
9973 [[nodiscard]]
static bool
9986 const size_t frame_size,
9987 const size_t hop_size,
9988 const bool pad_end =
true)
9999 "FFT::frame_signal");
10001 for (
size_t item = 0; item < offsets.
size(); ++item)
10003 const size_t offset = offsets[item];
10004 const size_t length = std::min(frame_size, signal.
size() -
offset);
10007 for (
size_t i = 0; i < frame_size; ++i)
10008 frame(i) = Real(0);
10009 for (
size_t i = 0; i < length; ++i)
10010 frame(i) = signal[
offset + i];
10018 template <
typename Container>
10019 requires Is_Real_Container<Container>
10022 const size_t frame_size,
10023 const size_t hop_size,
10024 const bool pad_end =
true)
10037 const size_t hop_size,
10038 const bool pad_end =
true)
10049 const size_t frame_size,
10050 const size_t hop_size,
10051 const bool pad_end =
true)
10056 template <
typename SignalContainer,
typename WindowContainer>
10057 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
10060 const WindowContainer & window,
10061 const size_t hop_size,
10062 const bool pad_end =
true)
10067 template <
typename Container>
10068 requires Is_Real_Container<Container>
10071 const size_t frame_size,
10072 const size_t hop_size,
10073 const bool pad_end =
true)
10093 const size_t chunk_size = 0)
10101 const size_t frame_size,
10111 const size_t frame_size,
10113 const size_t chunk_size = 0)
10118 template <
typename SignalContainer,
typename WindowContainer>
10119 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
10122 const WindowContainer & window,
10128 template <
typename SignalContainer,
typename WindowContainer>
10129 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<WindowContainer>
10132 const SignalContainer & signal,
10133 const WindowContainer & window,
10135 const size_t chunk_size = 0)
10144 template <
typename Container>
10145 requires Is_Real_Container<Container>
10148 const size_t frame_size,
10154 template <
typename Container>
10155 requires Is_Real_Container<Container>
10159 const size_t frame_size,
10161 const size_t chunk_size = 0)
10177 const size_t hop_size,
10178 const size_t signal_length = 0)
10182 options.signal_length = signal_length;
10197 const size_t hop_size,
10198 const size_t signal_length = 0)
10200 return istft(spectrogram, window, window, hop_size, signal_length);
10206 const size_t frame_size,
10207 const size_t hop_size,
10208 const size_t signal_length = 0)
10211 return istft(spectrogram, window, window, hop_size, signal_length);
10220 const size_t hop_size,
10221 const size_t signal_length = 0,
10222 const size_t chunk_size = 0)
10226 options.signal_length = signal_length;
10240 const size_t hop_size,
10241 const size_t signal_length = 0,
10242 const size_t chunk_size = 0)
10257 const size_t frame_size,
10258 const size_t hop_size,
10259 const size_t signal_length = 0,
10260 const size_t chunk_size = 0)
10299 const size_t frame_size,
10313 const size_t chunk_size = 0)
10329 const size_t chunk_size = 0)
10331 return pistft(pool, spectrogram, window, window,
options, chunk_size);
10338 const size_t frame_size,
10340 const size_t chunk_size = 0)
10343 return pistft(pool, spectrogram, window, window,
options, chunk_size);
10378 > std::numeric_limits<size_t>::max() - block.size())
10379 <<
"FFT::STFTProcessor::process_block: pending buffer overflow";
10385 const size_t chunk_size,
10386 const bool allow_partial_frames)
10422 "FFT::STFTProcessor")),
10446 template <
typename WindowContainer>
10447 requires Is_Real_Container<WindowContainer>
10472 :
window_(std::move(other.window_)),
10474 fft_size_(std::exchange(other.fft_size_, 0)),
10475 center_pad_(std::exchange(other.center_pad_, 0)),
10476 plan_(std::move(other.plan_)),
10477 pending_(std::move(other.pending_)),
10478 configured_(std::exchange(other.configured_,
false)),
10480 finalized_(std::exchange(other.finalized_,
false))
10509 std::swap(
options_, other.options_);
10572 <<
"FFT::STFTProcessor::process_block: processor already flushed";
10574 if (block.is_empty())
10585 const size_t chunk_size = 0)
10589 <<
"FFT::STFTProcessor::process_block: processor already flushed";
10591 if (block.is_empty())
10617 right_pad(i) = Real(0);
10645 right_pad(i) = Real(0);
10655 template <
typename Container>
10656 requires Is_Real_Container<Container>
10663 template <
typename Container>
10664 requires Is_Real_Container<Container>
10668 const size_t chunk_size = 0)
10697 << ctx <<
": processor is not configured";
10733 > std::numeric_limits<size_t>::max()
10735 <<
"FFT::ISTFTProcessor::process_frame: frame offset overflow";
10739 <<
"FFT::ISTFTProcessor::process_frame: invalid overlap-add state";
10757 <<
"FFT::ISTFTProcessor::normalize_prefix: count " <<
count
10764 * Real(256) * std::numeric_limits<Real>::epsilon();
10766 for (
size_t i = 0; i <
count; ++i)
10771 <<
"FFT::ISTFTProcessor: overlap-add normalization vanished at sample "
10773 normalized(i) = Real(0);
10787 const bool final_flush)
10794 size_t end = normalized.
size();
10802 size_t available = end - start;
10808 available = std::min(available,
10814 for (
size_t i = 0; i < available; ++i)
10815 emitted.
append(normalized[start + i]);
10823 size_t ready_raw = 0;
10830 <<
"FFT::ISTFTProcessor: invalid finalized-sample accounting";
10832 const size_t right_hold =
10834 ready_raw = ready_raw > right_hold ? ready_raw - right_hold : 0;
10843 const size_t chunk_size)
10847 <<
"FFT::ISTFTProcessor::process_frame: processor already flushed";
10849 <<
"FFT::ISTFTProcessor::process_frame: frame size " <<
spectrum.
size()
10850 <<
" does not match configured FFT size " <<
fft_size_;
10887 "FFT::ISTFTProcessor");
10927 template <
typename AnalysisContainer,
typename SynthesisContainer>
10928 requires Is_Real_Container<AnalysisContainer>
10929 and Is_Real_Container<SynthesisContainer>
10931 const AnalysisContainer & analysis_window,
10932 const SynthesisContainer & synthesis_window,
10962 fft_size_(std::exchange(other.fft_size_, 0)),
10963 center_pad_(std::exchange(other.center_pad_, 0)),
10964 plan_(std::move(other.plan_)),
10971 configured_(std::exchange(other.configured_,
false)),
10973 finalized_(std::exchange(other.finalized_,
false))
11003 std::swap(
options_, other.options_);
11063 const size_t chunk_size = 0)
11072 for (
size_t i = 0; i < spectrogram_block.size(); ++i)
11080 const size_t chunk_size = 0)
11083 for (
size_t i = 0; i < spectrogram_block.size(); ++i)
11117 template <
typename Container>
11118 requires Is_Complex_Container<Container>
11125 template <
typename Container>
11126 requires Is_Complex_Container<Container>
11130 const size_t chunk_size = 0)
11145 << ctx <<
": batch size " <<
size
11146 <<
" does not match configured channel count " <<
processors_.size();
11155 <<
"FFT::BatchedSTFTProcessor: at least one channel is required";
11162 const size_t frame_size,
11167 template <
typename WindowContainer>
11168 requires Is_Real_Container<WindowContainer>
11170 const WindowContainer & window,
11186 <<
"FFT::BatchedSTFTProcessor::channel: index " << index
11187 <<
" out of range for " <<
processors_.size() <<
" channels";
11195 <<
"FFT::BatchedSTFTProcessor::channel: index " << index
11196 <<
" out of range for " <<
processors_.size() <<
" channels";
11220 const size_t chunk_size = 0)
11223 "FFT::BatchedSTFTProcessor::pprocess_block");
11229 [
this, &block, &pool, chunk_size, &
output](
const size_t i)
11232 processors_[i].pprocess_block(pool,
11258 [
this, &pool, chunk_size, &
output](
const size_t i)
11260 output(i) = processors_[i].pflush(pool, chunk_size);
11275 const size_t index)
11278 if (not signal_lengths.
is_empty())
11279 channel.signal_length = signal_lengths[index];
11287 << ctx <<
": batch size " <<
size
11288 <<
" does not match configured channel count " <<
processors_.size();
11293 const size_t fft_size,
11306 const size_t fft_size,
11313 <<
"FFT::BatchedISTFTProcessor: at least one channel is required";
11316 <<
"FFT::BatchedISTFTProcessor: signal length count "
11317 << signal_lengths.
size()
11330 const size_t fft_size,
11342 const size_t fft_size,
11355 const size_t fft_size,
11356 const size_t frame_size,
11367 const size_t fft_size,
11368 const size_t frame_size,
11379 template <
typename AnalysisContainer,
typename SynthesisContainer>
11380 requires Is_Real_Container<AnalysisContainer>
11381 and Is_Real_Container<SynthesisContainer>
11383 const size_t fft_size,
11384 const AnalysisContainer & analysis_window,
11385 const SynthesisContainer & synthesis_window,
11395 template <
typename AnalysisContainer,
typename SynthesisContainer>
11396 requires Is_Real_Container<AnalysisContainer>
11397 and Is_Real_Container<SynthesisContainer>
11399 const size_t fft_size,
11400 const AnalysisContainer & analysis_window,
11401 const SynthesisContainer & synthesis_window,
11421 <<
"FFT::BatchedISTFTProcessor::channel: index " << index
11422 <<
" out of range for " <<
processors_.size() <<
" channels";
11430 <<
"FFT::BatchedISTFTProcessor::channel: index " << index
11431 <<
" out of range for " <<
processors_.size() <<
" channels";
11445 "FFT::BatchedISTFTProcessor::process_block");
11455 const size_t chunk_size = 0)
11458 "FFT::BatchedISTFTProcessor::pprocess_block");
11463 [
this, &block, &pool, chunk_size, &
output](
const size_t i)
11466 processors_[i].pprocess_block(pool,
11490 [
this, &pool, chunk_size, &
output](
const size_t i)
11492 output(i) = processors_[i].pflush(pool, chunk_size);
11505 if (signals.is_empty())
11509 for (
size_t i = 0; i < signals.size(); ++i)
11520 const size_t chunk_size = 0)
11522 if (signals.is_empty())
11526 const bool parallelize = pool.
num_threads() > 1
and signals.size() > 1;
11527 auto transform_one = [&signals, &window, &
options, &
output](
const size_t i)
11535 for (
size_t i = 0; i < signals.size(); ++i)
11544 const size_t frame_size,
11554 const size_t frame_size,
11556 const size_t chunk_size = 0)
11573 if (spectrograms.is_empty())
11577 and signal_lengths.
size() != spectrograms.size())
11578 <<
"FFT::batched_istft: signal_lengths size "
11579 << signal_lengths.
size()
11580 <<
" does not match batch size " << spectrograms.size();
11583 for (
size_t i = 0; i < spectrograms.size(); ++i)
11585 ISTFTOptions local_options =
options;
11586 if (not signal_lengths.
is_empty())
11587 local_options.signal_length = signal_lengths[i];
11606 const size_t chunk_size = 0)
11608 if (spectrograms.is_empty())
11612 and signal_lengths.
size() != spectrograms.size())
11613 <<
"FFT::pbatched_istft: signal_lengths size "
11614 << signal_lengths.
size()
11615 <<
" does not match batch size " << spectrograms.size();
11618 const bool parallelize = pool.
num_threads() > 1
and spectrograms.size() > 1;
11619 auto reconstruct_one =
11620 [&spectrograms, &analysis_window, &synthesis_window, &
options,
11621 &signal_lengths, &
output](
const size_t i)
11623 ISTFTOptions local_options =
options;
11624 if (not signal_lengths.is_empty())
11625 local_options.signal_length = signal_lengths[i];
11637 for (
size_t i = 0; i < spectrograms.size(); ++i)
11639 ISTFTOptions local_options =
options;
11640 if (not signal_lengths.is_empty())
11641 local_options.signal_length = signal_lengths[i];
11674 const size_t chunk_size = 0)
11688 const size_t frame_size,
11700 const size_t frame_size,
11703 const size_t chunk_size = 0)
11726 << ctx <<
": filter is not configured";
11734 for (
size_t i = 0; i <
order; ++i)
11762 :
LFilter(coeffs.numerator, coeffs.denominator)
11778 template <
typename NumContainer,
typename DenContainer>
11779 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
11781 const DenContainer & denominator)
11802 :
coeffs_(std::move(other.coeffs_)),
11803 state_(std::move(other.state_)),
11804 configured_(std::exchange(other.configured_,
false))
11875 <<
"FFT::LFilter::set_state: state size " << new_state.
size()
11876 <<
" does not match filter order " <<
state_.
size();
11889 "FFT::LFilter::filter",
11894 template <
typename Container>
11895 requires Is_Real_Container<Container>
11915 << ctx <<
": filter is not configured";
11923 for (
size_t i = 0; i <
coeffs_.size(); ++i)
11926 for (
size_t j = 0; j <
state.
size(); ++j)
11927 state(j) = Real(0);
11943 <<
"FFT::SOSFilter: at least one biquad section is required";
11946 for (
size_t i = 0; i <
sections_.size(); ++i)
11949 "FFT::SOSFilter"));
11956 template <
typename SectionsContainer>
11957 requires Is_Biquad_Container<SectionsContainer>
11979 :
sections_(std::move(other.sections_)),
11980 coeffs_(std::move(other.coeffs_)),
11981 states_(std::move(other.states_)),
11982 configured_(std::exchange(other.configured_,
false))
12033 <<
"FFT::SOSFilter::state: index " << index
12034 <<
" out of range for " <<
states_.
size() <<
" sections";
12042 for (
size_t i = 0; i <
states_.size(); ++i)
12043 for (
size_t j = 0; j <
states_[i].size(); ++j)
12053 for (
size_t i = 0; i <
coeffs_.size(); ++i)
12060 "FFT::SOSFilter::filter",
12068 template <
typename Container>
12069 requires Is_Real_Container<Container>
12087 << ctx <<
": batch size " <<
count
12088 <<
" does not match configured channel count " <<
filters_.size();
12097 <<
"FFT::LFilterBank: at least one channel is required";
12113 template <
typename NumContainer,
typename DenContainer>
12114 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
12116 const NumContainer & numerator,
12117 const DenContainer & denominator)
12132 <<
"FFT::LFilterBank::channel: index " << index
12133 <<
" out of range for " <<
filters_.size() <<
" channels";
12137 [[nodiscard]]
const LFilter &
12141 <<
"FFT::LFilterBank::channel: index " << index
12142 <<
" out of range for " <<
filters_.size() <<
" channels";
12148 for (
size_t i = 0; i <
filters_.size(); ++i)
12159 template <
typename Container>
12160 requires Is_Real_Container<Container>
12173 for (
size_t i = 0; i <
filters_.size(); ++i)
12181 const size_t chunk_size = 0)
12188 [
this, &signals, &
output](
const size_t i)
12190 output(i) = filters_[i].filter(signals[i]);
12207 << ctx <<
": batch size " <<
count
12208 <<
" does not match configured channel count " <<
filters_.size();
12216 <<
"FFT::SOSFilterBank: at least one channel is required";
12222 template <
typename SectionsContainer>
12223 requires Is_Biquad_Container<SectionsContainer>
12225 const SectionsContainer & sections)
12238 <<
"FFT::SOSFilterBank::channel: index " << index
12239 <<
" out of range for " <<
filters_.size() <<
" channels";
12247 <<
"FFT::SOSFilterBank::channel: index " << index
12248 <<
" out of range for " <<
filters_.size() <<
" channels";
12254 for (
size_t i = 0; i <
filters_.size(); ++i)
12265 template <
typename Container>
12266 requires Is_Real_Container<Container>
12279 for (
size_t i = 0; i <
filters_.size(); ++i)
12287 const size_t chunk_size = 0)
12294 [
this, &signals, &
output](
const size_t i)
12296 output(i) = filters_[i].filter(signals[i]);
12310 const IIRCoefficients coeffs =
12314 coeffs.denominator,
12335 template <
typename SignalContainer,
typename NumContainer,
typename DenContainer>
12336 requires Is_Real_Container<SignalContainer>
12337 and Is_Real_Container<NumContainer>
12338 and Is_Real_Container<DenContainer>
12341 const NumContainer & numerator,
12342 const DenContainer & denominator,
12358 if (signals.is_empty())
12361 const IIRCoefficients coeffs =
12364 and initial_states.size() != signals.size())
12365 <<
"FFT::batched_lfilter: initial state count "
12366 << initial_states.size()
12367 <<
" does not match channel count " << signals.size();
12370 for (
size_t i = 0; i < signals.size(); ++i)
12373 coeffs.denominator,
12374 initial_states.is_empty() ?
Array<Real>() : initial_states[i],
12375 "FFT::batched_lfilter");
12385 const size_t chunk_size = 0)
12387 if (signals.is_empty())
12390 const IIRCoefficients coeffs =
12393 and initial_states.size() != signals.size())
12394 <<
"FFT::pbatched_lfilter: initial state count "
12395 << initial_states.size()
12396 <<
" does not match channel count " << signals.size();
12402 [&signals, &coeffs, &initial_states, &
output](
const size_t i)
12404 output(i) = iir_filter_impl(signals[i],
12406 coeffs.denominator,
12407 initial_states.is_empty() ? Array<Real>() : initial_states[i],
12408 "FFT::pbatched_lfilter");
12414 template <
typename SignalsContainer,
typename NumContainer,
typename DenContainer>
12415 requires Is_Real_Batch_Container<SignalsContainer>
12416 and Is_Real_Container<NumContainer>
12417 and Is_Real_Container<DenContainer>
12420 const NumContainer & numerator,
12421 const DenContainer & denominator,
12425 for (
const auto & signal: signals)
12441 template <
typename SignalContainer,
typename SectionsContainer>
12442 requires Is_Real_Container<SignalContainer>
12443 and Is_Biquad_Container<SectionsContainer>
12446 const SectionsContainer & sections)
12456 if (signals.is_empty())
12460 for (
size_t i = 0; i < signals.size(); ++i)
12469 const size_t chunk_size = 0)
12471 if (signals.is_empty())
12478 [&signals, §ions, &
output](
const size_t i)
12480 output(i) = sosfilt(signals[i], sections);
12486 template <
typename SignalsContainer,
typename SectionsContainer>
12487 requires Is_Real_Batch_Container<SignalsContainer>
12488 and Is_Biquad_Container<SectionsContainer>
12491 const SectionsContainer & sections)
12494 for (
const auto & signal: signals)
12500 [[nodiscard]]
static FrequencyResponse
12503 const size_t num_points = 512,
12504 const bool whole =
false)
12506 return freqz_impl(numerator, denominator, num_points, whole,
"FFT::freqz");
12510 [[nodiscard]]
static FrequencyResponse
12512 const size_t num_points = 512,
12513 const bool whole =
false)
12518 [[nodiscard]]
static FrequencyResponse
12520 const size_t num_points = 512,
12521 const bool whole =
false)
12526 [[nodiscard]]
static FrequencyResponse
12528 const size_t num_points = 512,
12529 const bool whole =
false)
12534 [[nodiscard]]
static FrequencyResponse
12536 const size_t num_points = 512,
12537 const bool whole =
false)
12540 <<
"FFT::freqz: at least one biquad section is required";
12542 <<
"FFT::freqz: number of frequency samples must be positive";
12548 const Real max_omega = whole ? Real(2) * std::numbers::pi_v<Real> : std::numbers::pi_v<Real>;
12549 const Real denom = whole ?
static_cast<Real
>(num_points) :
static_cast<Real
>(std::max(
size_t(1), num_points - 1));
12551 for (
size_t i = 0; i < num_points; ++i)
12553 const Real omega = num_points == 1 ? Real(0) : max_omega *
static_cast<Real
>(i) / denom;
12554 Complex response(Real(1), Real(0));
12555 for (
size_t j = 0; j < sections.
size(); ++j)
12557 sections[j].denominator(),
12559 "FFT::freqz(SOS)");
12560 output.omega(i) = omega;
12561 output.response(i) = response;
12567 template <
typename NumContainer,
typename DenContainer>
12568 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
12569 [[nodiscard]]
static FrequencyResponse
12571 const DenContainer & denominator,
12572 const size_t num_points = 512,
12573 const bool whole =
false)
12581 template <
typename SectionsContainer>
12582 requires Is_Biquad_Container<SectionsContainer>
12583 [[nodiscard]]
static FrequencyResponse
12585 const size_t num_points = 512,
12586 const bool whole =
false)
12588 return freqz(to_array<BiquadSection>(sections), num_points, whole);
12598 const auto [deflated, extracted_roots] =
12645 for (
size_t i = 0; i < sections.
size(); ++i)
12654 for (
size_t i = 0; i < sections.
size(); ++i)
12659 template <
typename Container>
12660 requires Is_Real_Container<Container>
12667 template <
typename Container>
12668 requires Is_Real_Container<Container>
12675 template <
typename SectionsContainer>
12676 requires Is_Biquad_Container<SectionsContainer>
12680 return zeros(to_array<BiquadSection>(sections));
12683 template <
typename SectionsContainer>
12684 requires Is_Biquad_Container<SectionsContainer>
12688 return poles(to_array<BiquadSection>(sections));
12724 template <
typename NumContainer,
typename DenContainer>
12725 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
12728 const DenContainer & denominator)
12734 template <
typename SectionsContainer>
12735 requires Is_Biquad_Container<SectionsContainer>
12743 [[nodiscard]]
static Real
12750 [[nodiscard]]
static Real
12757 [[nodiscard]]
static Real
12763 [[nodiscard]]
static Real
12769 [[nodiscard]]
static Real
12775 template <
typename NumContainer,
typename DenContainer>
12776 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
12777 [[nodiscard]]
static Real
12779 const DenContainer & denominator)
12785 template <
typename SectionsContainer>
12786 requires Is_Biquad_Container<SectionsContainer>
12787 [[nodiscard]]
static Real
12794 [[nodiscard]]
static Real
12800 [[nodiscard]]
static Real
12806 [[nodiscard]]
static Real
12812 [[nodiscard]]
static Real
12818 Real margin = std::numeric_limits<Real>::infinity();
12819 for (
size_t i = 0; i < sections.
size(); ++i)
12824 template <
typename Container>
12825 requires Is_Real_Container<Container>
12826 [[nodiscard]]
static Real
12832 template <
typename SectionsContainer>
12833 requires Is_Biquad_Container<SectionsContainer>
12834 [[nodiscard]]
static Real
12841 [[nodiscard]]
static bool
12844 const Real tol = Real(1024) * std::numeric_limits<Real>::epsilon();
12848 [[nodiscard]]
static bool
12854 [[nodiscard]]
static bool
12860 [[nodiscard]]
static bool
12863 for (
size_t i = 0; i < sections.
size(); ++i)
12869 template <
typename Container>
12870 requires Is_Real_Container<Container>
12871 [[nodiscard]]
static bool
12877 template <
typename SectionsContainer>
12878 requires Is_Biquad_Container<SectionsContainer>
12879 [[nodiscard]]
static bool
12882 return is_stable(to_array<BiquadSection>(sections));
12886 [[nodiscard]]
static bool
12889 const Real tolerance)
12892 for (
size_t i = 0; i < pairs.
size(); ++i)
12893 if (pairs[i].is_cancellation(tolerance))
12898 [[nodiscard]]
static bool
12901 const Real tolerance)
12904 poles(denominator),
12908 [[nodiscard]]
static bool
12910 const Real tolerance)
12917 [[nodiscard]]
static bool
12919 const Real tolerance)
12926 [[nodiscard]]
static bool
12928 const Real tolerance)
12935 template <
typename NumContainer,
typename DenContainer>
12936 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
12937 [[nodiscard]]
static bool
12939 const DenContainer & denominator,
12940 const Real tolerance)
12947 template <
typename SectionsContainer>
12948 requires Is_Biquad_Container<SectionsContainer>
12949 [[nodiscard]]
static bool
12951 const Real tolerance)
12960 const Real tol = Real(1024) * std::numeric_limits<Real>::epsilon();
12964 <<
"FFT::validate_stable: stability margin " << margin
12965 <<
" is not strictly positive";
12966 for (
size_t i = 0; i < roots.
size(); ++i)
12968 <<
"FFT::validate_stable: unstable pole at " << roots[i]
12969 <<
" with magnitude " << std::abs(roots[i]);
12987 for (
size_t i = 0; i < sections.
size(); ++i)
12991 template <
typename Container>
12992 requires Is_Real_Container<Container>
12999 template <
typename SectionsContainer>
13000 requires Is_Biquad_Container<SectionsContainer>
13009 const Real min_margin)
13013 <<
"FFT::validate_stable: stability margin " << margin
13014 <<
" is smaller than required margin " << min_margin;
13020 const Real min_margin)
13027 const Real min_margin)
13034 const Real min_margin)
13038 <<
"FFT::validate_stable: SOS stability margin "
13040 <<
" is smaller than required margin " << min_margin;
13044 template <
typename Container>
13045 requires Is_Real_Container<Container>
13048 const Real min_margin)
13053 template <
typename SectionsContainer>
13054 requires Is_Biquad_Container<SectionsContainer>
13057 const Real min_margin)
13065 const Real tolerance)
13068 for (
size_t i = 0; i < pairs.
size(); ++i)
13069 if (pairs[i].is_cancellation(tolerance))
13072 <<
"FFT::validate_no_near_pole_zero_cancellation: zero "
13073 << pairs[i].zero <<
" and pole " << pairs[i].pole
13074 <<
" are only " << pairs[i].distance <<
" apart";
13081 const Real tolerance)
13084 poles(denominator),
13090 const Real tolerance)
13099 const Real tolerance)
13108 const Real tolerance)
13115 template <
typename NumContainer,
typename DenContainer>
13116 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
13119 const DenContainer & denominator,
13120 const Real tolerance)
13127 template <
typename SectionsContainer>
13128 requires Is_Biquad_Container<SectionsContainer>
13131 const Real tolerance)
13154 const size_t num_points = 512,
13155 const bool whole =
false)
13161 "FFT::group_delay");
13167 const size_t num_points = 512,
13168 const bool whole =
false)
13174 "FFT::phase_delay");
13179 const size_t num_points = 512,
13180 const bool whole =
false)
13186 "FFT::group_delay");
13191 const size_t num_points = 512,
13192 const bool whole =
false)
13198 "FFT::phase_delay");
13203 const size_t num_points = 512,
13204 const bool whole =
false)
13211 const size_t num_points = 512,
13212 const bool whole =
false)
13219 const size_t num_points = 512,
13220 const bool whole =
false)
13230 const size_t num_points = 512,
13231 const bool whole =
false)
13241 const size_t num_points = 512,
13242 const bool whole =
false)
13247 "FFT::group_delay(SOS)");
13252 const size_t num_points = 512,
13253 const bool whole =
false)
13260 "FFT::phase_delay(SOS)");
13262 const Real tol = (response.
omega[response.
omega.
size() - 1] + Real(1))
13263 * Real(128) * std::numeric_limits<Real>::epsilon();
13265 for (
size_t i = 0; i < response.
omega.
size(); ++i)
13266 delay(i) = std::abs(response.
omega[i]) <= tol ? group[i] : -phase[i] / response.
omega[i];
13271 template <
typename NumContainer,
typename DenContainer>
13272 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
13275 const DenContainer & denominator,
13276 const size_t num_points = 512,
13277 const bool whole =
false)
13285 template <
typename NumContainer,
typename DenContainer>
13286 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
13289 const DenContainer & denominator,
13290 const size_t num_points = 512,
13291 const bool whole =
false)
13299 template <
typename Container>
13300 requires Is_Real_Container<Container>
13303 const size_t num_points = 512,
13304 const bool whole =
false)
13309 template <
typename Container>
13310 requires Is_Real_Container<Container>
13313 const size_t num_points = 512,
13314 const bool whole =
false)
13319 template <
typename SectionsContainer>
13320 requires Is_Biquad_Container<SectionsContainer>
13323 const size_t num_points = 512,
13324 const bool whole =
false)
13326 return group_delay(to_array<BiquadSection>(sections), num_points, whole);
13329 template <
typename SectionsContainer>
13330 requires Is_Biquad_Container<SectionsContainer>
13333 const size_t num_points = 512,
13334 const bool whole =
false)
13336 return phase_delay(to_array<BiquadSection>(sections), num_points, whole);
13340 [[nodiscard]]
static PhaseMarginInfo
13347 [[nodiscard]]
static GainMarginInfo
13353 [[nodiscard]]
static PhaseMarginInfo
13356 const size_t num_points = 1024,
13357 const bool whole =
false)
13359 const size_t seed_points = std::max(num_points,
size_t(4097));
13365 [&](
const Real omega)
13370 "FFT::phase_margin");
13374 [[nodiscard]]
static GainMarginInfo
13377 const size_t num_points = 1024,
13378 const bool whole =
false)
13380 const size_t seed_points = std::max(num_points,
size_t(4097));
13386 [&](
const Real omega)
13391 "FFT::gain_margin");
13395 [[nodiscard]]
static PhaseMarginInfo
13397 const size_t num_points = 1024,
13398 const bool whole =
false)
13403 [[nodiscard]]
static GainMarginInfo
13405 const size_t num_points = 1024,
13406 const bool whole =
false)
13411 [[nodiscard]]
static PhaseMarginInfo
13413 const size_t num_points = 1024,
13414 const bool whole =
false)
13422 [[nodiscard]]
static GainMarginInfo
13424 const size_t num_points = 1024,
13425 const bool whole =
false)
13433 [[nodiscard]]
static PhaseMarginInfo
13435 const size_t num_points = 1024,
13436 const bool whole =
false)
13438 const size_t seed_points = std::max(num_points,
size_t(4097));
13441 [&](
const Real omega)
13445 "FFT::phase_margin(SOS)");
13449 [[nodiscard]]
static GainMarginInfo
13451 const size_t num_points = 1024,
13452 const bool whole =
false)
13454 const size_t seed_points = std::max(num_points,
size_t(4097));
13457 [&](
const Real omega)
13461 "FFT::gain_margin(SOS)");
13465 template <
typename NumContainer,
typename DenContainer>
13466 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
13467 [[nodiscard]]
static PhaseMarginInfo
13469 const DenContainer & denominator,
13470 const size_t num_points = 1024,
13471 const bool whole =
false)
13479 template <
typename NumContainer,
typename DenContainer>
13480 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
13481 [[nodiscard]]
static GainMarginInfo
13483 const DenContainer & denominator,
13484 const size_t num_points = 1024,
13485 const bool whole =
false)
13493 template <
typename SectionsContainer>
13494 requires Is_Biquad_Container<SectionsContainer>
13495 [[nodiscard]]
static PhaseMarginInfo
13497 const size_t num_points = 1024,
13498 const bool whole =
false)
13500 return phase_margin(to_array<BiquadSection>(sections), num_points, whole);
13503 template <
typename SectionsContainer>
13504 requires Is_Biquad_Container<SectionsContainer>
13505 [[nodiscard]]
static GainMarginInfo
13507 const size_t num_points = 1024,
13508 const bool whole =
false)
13510 return gain_margin(to_array<BiquadSection>(sections), num_points, whole);
13514 [[nodiscard]]
static IIRCoefficients
13517 const Real sample_rate)
13520 analog_denominator,
13522 "FFT::bilinear_transform");
13525 template <
typename NumContainer,
typename DenContainer>
13526 requires Is_Real_Container<NumContainer>
and Is_Real_Container<DenContainer>
13527 [[nodiscard]]
static IIRCoefficients
13529 const DenContainer & analog_denominator,
13530 const Real sample_rate)
13540 const Real cutoff_frequency,
13541 const Real sample_rate)
13544 "FFT::butterworth_lowpass"),
13549 "FFT::butterworth_lowpass");
13555 const Real cutoff_frequency,
13556 const Real sample_rate)
13559 "FFT::butterworth_highpass"),
13564 "FFT::butterworth_highpass");
13570 const Real low_cutoff_frequency,
13571 const Real high_cutoff_frequency,
13572 const Real sample_rate)
13574 const auto [warped_low, warped_high] =
13576 high_cutoff_frequency,
13578 "FFT::butterworth_bandpass");
13579 const Real bandwidth = warped_high - warped_low;
13580 const Real center = std::sqrt(warped_low * warped_high);
13582 "FFT::butterworth_bandpass"),
13583 {Real(1), Real(0), center * center},
13584 {bandwidth, Real(0)},
13586 "FFT::butterworth_bandpass");
13592 const Real low_cutoff_frequency,
13593 const Real high_cutoff_frequency,
13594 const Real sample_rate)
13598 low_cutoff_frequency,
13599 high_cutoff_frequency,
13601 "FFT::butterworth_bandstop");
13607 const Real ripple_db,
13608 const Real cutoff_frequency,
13609 const Real sample_rate)
13613 "FFT::chebyshev1_lowpass"),
13618 "FFT::chebyshev1_lowpass");
13624 const Real ripple_db,
13625 const Real cutoff_frequency,
13626 const Real sample_rate)
13630 "FFT::chebyshev1_highpass"),
13635 "FFT::chebyshev1_highpass");
13641 const Real ripple_db,
13642 const Real low_cutoff_frequency,
13643 const Real high_cutoff_frequency,
13644 const Real sample_rate)
13646 const auto [warped_low, warped_high] =
13648 high_cutoff_frequency,
13650 "FFT::chebyshev1_bandpass");
13651 const Real bandwidth = warped_high - warped_low;
13652 const Real center = std::sqrt(warped_low * warped_high);
13655 "FFT::chebyshev1_bandpass"),
13656 {Real(1), Real(0), center * center},
13657 {bandwidth, Real(0)},
13659 "FFT::chebyshev1_bandpass");
13665 const Real ripple_db,
13666 const Real low_cutoff_frequency,
13667 const Real high_cutoff_frequency,
13668 const Real sample_rate)
13673 "FFT::chebyshev1_bandstop"),
13675 low_cutoff_frequency,
13676 high_cutoff_frequency,
13678 "FFT::chebyshev1_bandstop");
13684 const Real attenuation_db,
13685 const Real cutoff_frequency,
13686 const Real sample_rate)
13690 "FFT::chebyshev2_lowpass"),
13694 "FFT::chebyshev2_lowpass");
13700 const Real attenuation_db,
13701 const Real cutoff_frequency,
13702 const Real sample_rate)
13706 "FFT::chebyshev2_highpass"),
13710 "FFT::chebyshev2_highpass");
13716 const Real attenuation_db,
13717 const Real low_cutoff_frequency,
13718 const Real high_cutoff_frequency,
13719 const Real sample_rate)
13721 const auto [warped_low, warped_high] =
13723 high_cutoff_frequency,
13725 "FFT::chebyshev2_bandpass");
13726 const Real bandwidth = warped_high - warped_low;
13727 const Real center = std::sqrt(warped_low * warped_high);
13730 "FFT::chebyshev2_bandpass"),
13731 {Real(1), Real(0), center * center},
13732 {bandwidth, Real(0)},
13734 "FFT::chebyshev2_bandpass");
13740 const Real attenuation_db,
13741 const Real low_cutoff_frequency,
13742 const Real high_cutoff_frequency,
13743 const Real sample_rate)
13745 const auto [warped_low, warped_high] =
13747 high_cutoff_frequency,
13749 "FFT::chebyshev2_bandstop");
13750 const Real bandwidth = warped_high - warped_low;
13751 const Real center = std::sqrt(warped_low * warped_high);
13754 "FFT::chebyshev2_bandstop"),
13755 {bandwidth, Real(0)},
13756 {Real(1), Real(0), center * center},
13758 "FFT::chebyshev2_bandstop");
13768 const Real cutoff_frequency,
13769 const Real sample_rate)
13772 "FFT::bessel_lowpass"),
13776 "FFT::bessel_lowpass");
13782 const Real cutoff_frequency,
13783 const Real sample_rate)
13786 "FFT::bessel_highpass"),
13790 "FFT::bessel_highpass");
13796 const Real low_cutoff_frequency,
13797 const Real high_cutoff_frequency,
13798 const Real sample_rate)
13800 const auto [warped_low, warped_high] =
13802 high_cutoff_frequency,
13804 "FFT::bessel_bandpass");
13805 const Real bandwidth = warped_high - warped_low;
13806 const Real center = std::sqrt(warped_low * warped_high);
13808 "FFT::bessel_bandpass"),
13809 {Real(1), Real(0), center * center},
13810 {bandwidth, Real(0)},
13812 "FFT::bessel_bandpass");
13818 const Real low_cutoff_frequency,
13819 const Real high_cutoff_frequency,
13820 const Real sample_rate)
13824 low_cutoff_frequency,
13825 high_cutoff_frequency,
13827 "FFT::bessel_bandstop");
13833 const Real ripple_db,
13834 const Real attenuation_db,
13835 const Real cutoff_frequency,
13836 const Real sample_rate)
13841 "FFT::elliptic_lowpass"),
13845 "FFT::elliptic_lowpass");
13851 const Real ripple_db,
13852 const Real attenuation_db,
13853 const Real cutoff_frequency,
13854 const Real sample_rate)
13859 "FFT::elliptic_highpass"),
13863 "FFT::elliptic_highpass");
13869 const Real ripple_db,
13870 const Real attenuation_db,
13871 const Real low_cutoff_frequency,
13872 const Real high_cutoff_frequency,
13873 const Real sample_rate)
13875 const auto [warped_low, warped_high] =
13877 high_cutoff_frequency,
13879 "FFT::elliptic_bandpass");
13880 const Real bandwidth = warped_high - warped_low;
13881 const Real center = std::sqrt(warped_low * warped_high);
13885 "FFT::elliptic_bandpass"),
13886 {Real(1), Real(0), center * center},
13887 {bandwidth, Real(0)},
13889 "FFT::elliptic_bandpass");
13895 const Real ripple_db,
13896 const Real attenuation_db,
13897 const Real low_cutoff_frequency,
13898 const Real high_cutoff_frequency,
13899 const Real sample_rate)
13901 const auto [warped_low, warped_high] =
13903 high_cutoff_frequency,
13905 "FFT::elliptic_bandstop");
13906 const Real bandwidth = warped_high - warped_low;
13907 const Real center = std::sqrt(warped_low * warped_high);
13911 "FFT::elliptic_bandstop"),
13912 {bandwidth, Real(0)},
13913 {Real(1), Real(0), center * center},
13915 "FFT::elliptic_bandstop");
13927 const size_t block_size = 0)
13932 if (coeffs.
size() == 1)
13935 const Real gain = coeffs[0] * coeffs[0];
13936 for (
size_t i = 0; i < signal.
size(); ++i)
13937 output(i) = signal[i] * gain;
13943 const OverlapAdd convolver(coeffs, block_size);
13958 const size_t block_size = 0,
13959 const size_t chunk_size = 0)
13964 if (coeffs.
size() == 1)
13967 const Real gain = coeffs[0] * coeffs[0];
13968 for (
size_t i = 0; i < signal.
size(); ++i)
13969 output(i) = signal[i] * gain;
13975 const OverlapAdd convolver(coeffs, block_size);
13987 template <
typename SignalContainer,
typename CoeffContainer>
13988 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<CoeffContainer>
13991 const CoeffContainer & coeffs,
13992 const size_t block_size = 0)
13997 template <
typename SignalContainer,
typename CoeffContainer>
13998 requires Is_Real_Container<SignalContainer>
and Is_Real_Container<CoeffContainer>
14001 const SignalContainer & signal,
14002 const CoeffContainer & coeffs,
14003 const size_t block_size = 0,
14004 const size_t chunk_size = 0)
14028 "FFT::filtfilt(IIR)");
14055 template <
typename SignalContainer,
typename NumContainer,
typename DenContainer>
14056 requires Is_Real_Container<SignalContainer>
14057 and Is_Real_Container<NumContainer>
14058 and Is_Real_Container<DenContainer>
14061 const NumContainer & numerator,
14062 const DenContainer & denominator)
14069 template <
typename SignalContainer>
14070 requires Is_Real_Container<SignalContainer>
14078 template <
typename SignalContainer>
14079 requires Is_Real_Container<SignalContainer>
14087 template <
typename SignalContainer,
typename SectionsContainer>
14088 requires Is_Real_Container<SignalContainer>
14089 and Is_Biquad_Container<SectionsContainer>
14092 const SectionsContainer & sections)
14095 to_array<BiquadSection>(sections));
14114 [[nodiscard]]
static size_t
14118 <<
"FFT::OverlapAdd: kernel size must be positive";
14129 const size_t length)
const
14133 block(i) =
Complex(Real(0), Real(0));
14135 for (
size_t i = 0; i < length; ++i)
14147 const size_t chunk_size)
const
14149 auto pointwise = [
this, &
spectrum](
const size_t i)
14180 const size_t chunk_size)
14182 if (block.is_empty())
14186 <<
"FFT::OverlapAdd::process_block: block size " << block.size()
14187 <<
" exceeds configured block size " <<
block_size_;
14191 if (pool !=
nullptr)
14198 const Array<Real> convolved = (pool !=
nullptr) ?
14203 for (
size_t i = 0; i < block.size(); ++i)
14206 emitted(i) = convolved[i] + overlap;
14214 const size_t src = block.size() + i;
14215 const Real from_current = src < convolved.
size() ? convolved[src] : Real(0);
14217 next_overlap(i) = from_current + from_previous;
14230 const size_t chunk_size)
const
14236 > std::numeric_limits<size_t>::max()
14238 <<
"FFT::OverlapAdd::convolve: product size exceeds size_t capacity";
14241 for (
size_t i = 0; i <
output.size(); ++i)
14249 if (pool !=
nullptr)
14260 const size_t valid = length +
kernel_.
size() - 1;
14261 for (
size_t i = 0; i < valid; ++i)
14274 <<
"FFT::OverlapAdd: kernel must be non-empty";
14278 <<
"FFT::OverlapAdd: block size must be positive";
14281 > std::numeric_limits<size_t>::max()
14283 <<
"FFT::OverlapAdd: FFT size overflow";
14292 padded_kernel(i) =
Complex(Real(0), Real(0));
14319 :
kernel_(std::move(other.kernel_)),
14320 block_size_(std::exchange(other.block_size_, 0)),
14321 fft_size_(std::exchange(other.fft_size_, 0)),
14322 plan_(std::move(other.plan_)),
14324 overlap_(std::move(other.overlap_)),
14387 <<
"FFT::OverlapAdd::convolve: convolver is empty (it was moved from)";
14405 const size_t chunk_size = 0)
const
14408 <<
"FFT::OverlapAdd::pconvolve: convolver is empty (it was moved from)";
14426 <<
"FFT::OverlapAdd::process_block: convolver is empty (it was moved from)";
14427 if (block.is_empty())
14431 emitted.
reserve(block.size());
14437 for (
size_t i = 0; i < length; ++i)
14441 for (
size_t i = 0; i < partial.
size(); ++i)
14442 emitted.
append(partial[i]);
14459 const size_t chunk_size = 0)
14462 <<
"FFT::OverlapAdd::pprocess_block: convolver is empty (it was moved from)";
14463 if (block.is_empty())
14467 emitted.
reserve(block.size());
14473 for (
size_t i = 0; i < length; ++i)
14477 for (
size_t i = 0; i < partial.
size(); ++i)
14478 emitted.
append(partial[i]);
14505 template <
typename Container>
14506 requires Is_Real_Container<Container>
14523 template <
typename Container>
14524 requires Is_Real_Container<Container>
14527 const size_t chunk_size = 0)
const
14539 template <
typename Container>
14540 requires Is_Real_Container<Container>
14557 template <
typename Container>
14558 requires Is_Real_Container<Container>
14561 const size_t chunk_size = 0)
14586 [[nodiscard]]
static size_t
14590 <<
"FFT::OverlapAddBank: kernel size must be positive";
14599 << ctx <<
": batch size " <<
count
14600 <<
" does not match configured channel count " <<
overlaps_.size();
14605 [[nodiscard]]
static size_t
14609 for (
size_t i = 0; i < signals.size(); ++i)
14610 length = std::max(length, signals[i].
size());
14618 const size_t length)
14622 for (
size_t i = 0; i < length; ++i)
14630 const size_t offset = 0,
14631 const size_t length = std::numeric_limits<size_t>::max())
const
14634 <<
"FFT::OverlapAddBank::build_signal_block: offset " <<
offset
14635 <<
" exceeds signal size " << signal.
size();
14636 const size_t effective_length =
14639 <<
"FFT::OverlapAddBank::build_signal_block: block size "
14640 << effective_length <<
" exceeds configured block size " <<
block_size_;
14644 block(i) =
Complex(Real(0), Real(0));
14645 for (
size_t i = 0; i < effective_length; ++i)
14655 for (
size_t channel = 0; channel < block.size(); ++channel)
14665 const size_t offset = 0)
const
14668 for (
size_t item = 0; item < channels.
size(); ++item)
14681 const size_t chunk_size)
const
14683 auto multiply_one = [
this, &spectra](
const size_t channel)
14685 for (
size_t bin = 0; bin <
fft_size_; ++bin)
14692 for (
size_t channel = 0; channel < spectra.size(); ++channel)
14693 multiply_one(channel);
14700 for (
size_t i = 0; i <
overlaps_[channel].size(); ++i)
14708 for (
size_t channel = 0; channel <
overlaps_.size(); ++channel)
14715 const size_t chunk_size)
14722 active_channels.
reserve(active_count);
14723 active_lengths.
reserve(active_count);
14724 for (
size_t channel = 0; channel < block.size(); ++channel)
14725 if (not block[channel].is_empty())
14727 active_channels.
append(channel);
14728 active_lengths.
append(block[channel].
size());
14738 const bool parallelize_fft =
14740 if (parallelize_fft)
14751 for (
size_t item = 0; item < active_channels.
size(); ++item)
14753 const size_t channel = active_channels[item];
14755 for (
size_t i = 0; i < active_lengths[item]; ++i)
14757 const Real overlap = i <
overlaps_[channel].size() ?
overlaps_[channel][i] : Real(0);
14758 emitted(channel)(i) = convolved[item][i] + overlap;
14764 for (
size_t i = 0; i <
overlaps_[channel].size(); ++i)
14766 const size_t src = active_lengths[item] + i;
14767 const Real from_current = src < convolved[item].size() ? convolved[item][src] : Real(0);
14768 const Real from_previous = src <
overlaps_[channel].size() ?
overlaps_[channel][src] : Real(0);
14769 next_overlap(i) = from_current + from_previous;
14783 const size_t chunk_size)
const
14785 if (signals.is_empty())
14789 for (
size_t channel = 0; channel < signals.size(); ++channel)
14791 if (signals[channel].is_empty())
14795 for (
size_t i = 0; i <
output[channel].size(); ++i)
14796 output(channel)(i) = Real(0);
14804 active_channels.
reserve(signals.size());
14805 active_lengths.
reserve(signals.size());
14806 for (
size_t channel = 0; channel < signals.size(); ++channel)
14811 const size_t length =
14813 active_channels.
append(channel);
14814 active_lengths.
append(length);
14820 const bool parallelize_fft =
14826 if (parallelize_fft)
14832 parallelize_fft ? pool :
nullptr,
14839 for (
size_t item = 0; item < active_channels.
size(); ++item)
14841 const size_t channel = active_channels[item];
14842 const size_t valid = active_lengths[item] +
kernel_.
size() - 1;
14843 for (
size_t i = 0; i < valid; ++i)
14858 <<
"FFT::OverlapAddBank: at least one channel is required";
14860 <<
"FFT::OverlapAddBank: kernel must be non-empty";
14864 <<
"FFT::OverlapAddBank: block size must be positive";
14866 > std::numeric_limits<size_t>::max()
14868 <<
"FFT::OverlapAddBank: FFT size overflow";
14875 for (
size_t channel = 0; channel <
num_channels; ++channel)
14884 padded_kernel(i) =
Complex(Real(0), Real(0));
14911 :
kernel_(std::move(other.kernel_)),
14912 block_size_(std::exchange(other.block_size_, 0)),
14913 fft_size_(std::exchange(other.fft_size_, 0)),
14914 plan_(std::move(other.plan_)),
14989 <<
"FFT::OverlapAddBank::convolve: bank is empty (it was moved from)";
15007 const size_t chunk_size = 0)
const
15010 <<
"FFT::OverlapAddBank::pconvolve: bank is empty (it was moved from)";
15027 <<
"FFT::OverlapAddBank::process_block: bank is empty (it was moved from)";
15031 for (
size_t channel = 0; channel < emitted.
size(); ++channel)
15036 bool any_pending =
false;
15037 for (
size_t channel = 0; channel < block.size(); ++channel)
15041 const size_t length =
15044 any_pending =
true;
15047 if (not any_pending)
15052 for (
size_t channel = 0; channel < emitted.
size(); ++channel)
15053 for (
size_t i = 0; i < partial[channel].
size(); ++i)
15054 emitted(channel).
append(partial[channel][i]);
15073 const size_t chunk_size = 0)
15076 <<
"FFT::OverlapAddBank::pprocess_block: bank is empty (it was moved from)";
15080 for (
size_t channel = 0; channel < emitted.
size(); ++channel)
15085 bool any_pending =
false;
15086 for (
size_t channel = 0; channel < block.size(); ++channel)
15090 const size_t length =
15093 any_pending =
true;
15096 if (not any_pending)
15101 for (
size_t channel = 0; channel < emitted.
size(); ++channel)
15102 for (
size_t i = 0; i < partial[channel].
size(); ++i)
15103 emitted(channel).
append(partial[channel][i]);
15113 for (
size_t channel = 0; channel <
overlaps_.size(); ++channel)
15126 auto flush_one = [
this, &tail](
const size_t channel)
15136 for (
size_t channel = 0; channel <
overlaps_.size(); ++channel)
15137 flush_one(channel);
15163 [[nodiscard]]
static size_t
15167 <<
"FFT::OverlapSave: kernel size must be positive";
15195 history_(i) = padded_chunk[start + i];
15201 for (
size_t i = 0; i < preserved; ++i)
15203 for (
size_t i = 0; i < padded_chunk.
size(); ++i)
15204 next_history(preserved + i) = padded_chunk[i];
15215 <<
"FFT::OverlapSave::process_block: block size " << chunk.
size()
15216 <<
" exceeds configured block size " <<
block_size_;
15220 padded_chunk(i) = i < chunk.
size() ? chunk[i] : Real(0);
15224 segment(i) =
Complex(Real(0), Real(0));
15227 for (
size_t i = 0; i < padded_chunk.
size(); ++i)
15238 padded_chunk(i) = i < chunk.
size() ? chunk[i] : Real(0);
15239 return padded_chunk;
15259 segment(i) =
Complex(Real(0), Real(0));
15262 for (
size_t i = 0; i < padded_chunk.
size(); ++i)
15281 <<
"FFT::OverlapSave: kernel must be non-empty";
15285 <<
"FFT::OverlapSave: block size must be positive";
15287 > std::numeric_limits<size_t>::max()
15289 <<
"FFT::OverlapSave: FFT size overflow";
15298 padded_kernel(i) =
Complex(Real(0), Real(0));
15324 :
kernel_(std::move(other.kernel_)),
15325 block_size_(std::exchange(other.block_size_, 0)),
15326 fft_size_(std::exchange(other.fft_size_, 0)),
15327 plan_(std::move(other.plan_)),
15329 history_(std::move(other.history_)),
15330 pending_(std::move(other.pending_)),
15407 <<
"FFT::OverlapSave::process_block: convolver is empty (it was moved from)";
15408 if (block.is_empty())
15457 zeros(i) = Real(0);
15461 const size_t required = target_output_size - emitted_before;
15478 <<
"FFT::OverlapSave::convolve: convolver is empty (it was moved from)";
15492 template <
typename Container>
15493 requires Is_Real_Container<Container>
15507 template <
typename Container>
15508 requires Is_Real_Container<Container>
15538 [[nodiscard]]
static size_t
15542 <<
"FFT::PartitionedConvolver: kernel size must be positive";
15578 padded(i) = i < chunk.
size() ? chunk[i] : Real(0);
15597 for (
size_t i = 0; i < padded.
size(); ++i)
15598 input(i) =
Complex(padded[i], Real(0));
15605 const size_t history_index =
15607 for (
size_t bin = 0; bin <
fft_size_; ++bin)
15615 emitted(i) = convolved[i] +
overlap_[i];
15630 <<
"FFT::PartitionedConvolver: kernel must be non-empty";
15635 <<
"FFT::PartitionedConvolver: partition size must be positive";
15643 const size_t num_partitions =
15647 for (
size_t part = 0; part < num_partitions; ++part)
15651 const size_t length =
15653 for (
size_t i = 0; i < length; ++i)
15683 :
kernel_(std::move(other.kernel_)),
15685 fft_size_(std::exchange(other.fft_size_, 0)),
15686 plan_(std::move(other.plan_)),
15689 head_(std::exchange(other.head_, 0)),
15690 overlap_(std::move(other.overlap_)),
15691 pending_(std::move(other.pending_)),
15727 std::swap(
head_, other.head_);
15766 <<
"FFT::PartitionedConvolver::process_block: convolver is empty"
15767 <<
" (it was moved from)";
15768 if (block.is_empty())
15810 zeros(i) = Real(0);
15814 const size_t required = target_output_size - emitted_before;
15831 <<
"FFT::PartitionedConvolver::convolve: convolver is empty"
15832 <<
" (it was moved from)";
15846 template <
typename Container>
15847 requires Is_Real_Container<Container>
15861 template <
typename Container>
15862 requires Is_Real_Container<Container>
15874 const size_t block_size = 0)
15887 const size_t block_size = 0,
15888 const size_t chunk_size = 0)
15899 const size_t block_size = 0)
15901 if (signals.is_empty() or kernel.
is_empty())
15911 const size_t block_size = 0,
15912 const size_t chunk_size = 0)
15914 if (signals.is_empty() or kernel.
is_empty())
15924 const size_t block_size = 0)
15935 const size_t partition_size = 0)
15943 template <
typename Container1,
typename Container2>
15944 requires Is_Real_Container<Container1>
and Is_Real_Container<Container2>
15947 const Container2 & kernel,
15948 const size_t block_size = 0)
15956 template <
typename Container1,
typename Container2>
15957 requires Is_Real_Container<Container1>
and Is_Real_Container<Container2>
15960 const Container1 & signal,
15961 const Container2 & kernel,
15962 const size_t block_size = 0,
15963 const size_t chunk_size = 0)
15973 template <
typename Container1,
typename Container2>
15974 requires Is_Real_Container<Container1>
and Is_Real_Container<Container2>
15977 const Container2 & kernel,
15978 const size_t block_size = 0)
15986 template <
typename Container1,
typename Container2>
15987 requires Is_Real_Container<Container1>
and Is_Real_Container<Container2>
15990 const Container2 & kernel,
15991 const size_t partition_size = 0)
16026 const size_t chunk_size = 0)
16032 template <
typename Container1,
typename Container2>
16033 requires Is_Complex_Container<Container1>
and Is_Complex_Container<Container2>
16041 template <
typename Container1,
typename Container2>
16042 requires Is_Complex_Container<Container1>
and Is_Complex_Container<Container2>
16045 const size_t chunk_size = 0)
16072 const size_t chunk_size = 0)
16078 template <
typename Container1,
typename Container2>
16079 requires Is_Real_Container<Container1>
and Is_Real_Container<Container2>
16087 template <
typename Container1,
typename Container2>
16088 requires Is_Real_Container<Container1>
and Is_Real_Container<Container2>
16091 const size_t chunk_size = 0)
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
size_t size_t int32_t value
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void empty() noexcept
Empties the container.
constexpr bool is_empty() const noexcept
Checks if the container is empty.
void swap(Array &s) noexcept
Swap this with s
static Array create(const size_t n)
Create an array with n logical elements.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
Stateful multichannel ISTFT processor with one synthesizer per channel.
ISTFTProcessor & channel(const size_t index)
void validate_batch_size(const size_t size, const char *ctx) const
BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const size_t frame_size, const ISTFTOptions &options)
BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const Array< Real > &window, const ISTFTOptions &options)
size_t num_channels() const noexcept
static ISTFTOptions channel_options(const ISTFTOptions &options, const Array< size_t > &signal_lengths, const size_t index)
BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const Array< Real > &window, const ISTFTOptions &options, const Array< size_t > &signal_lengths)
and Is_Real_Container< SynthesisContainer > BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const AnalysisContainer &analysis_window, const SynthesisContainer &synthesis_window, const ISTFTOptions &options, const Array< size_t > &signal_lengths)
Array< Array< Real > > pprocess_block(ThreadPool &pool, const Array< Array< Array< Complex > > > &block, const size_t chunk_size=0)
const ISTFTProcessor & channel(const size_t index) const
BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const size_t frame_size, const ISTFTOptions &options, const Array< size_t > &signal_lengths)
Array< Array< Real > > flush()
and Is_Real_Container< SynthesisContainer > BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const AnalysisContainer &analysis_window, const SynthesisContainer &synthesis_window, const ISTFTOptions &options)
BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options)
Array< Array< Real > > pflush(ThreadPool &pool, const size_t chunk_size=0)
Array< ISTFTProcessor > processors_
Array< Array< Real > > process_block(const Array< Array< Array< Complex > > > &block)
BatchedISTFTProcessor(const size_t num_channels, const size_t fft_size, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options, const Array< size_t > &signal_lengths)
Stateful multichannel STFT processor with one analyzer per channel.
Array< Array< Array< Complex > > > pflush(ThreadPool &pool, const size_t chunk_size=0)
BatchedSTFTProcessor(const size_t num_channels, const size_t frame_size, const STFTOptions &options)
Array< STFTProcessor > processors_
Array< Array< Array< Complex > > > process_block(const Array< Array< Real > > &block)
const STFTProcessor & channel(const size_t index) const
size_t num_channels() const noexcept
Array< Array< Array< Complex > > > flush()
STFTProcessor & channel(const size_t index)
void validate_batch_size(const size_t size, const char *ctx) const
Array< Array< Array< Complex > > > pprocess_block(ThreadPool &pool, const Array< Array< Real > > &block, const size_t chunk_size=0)
BatchedSTFTProcessor(const size_t num_channels, const Array< Real > &window, const STFTOptions &options)
BatchedSTFTProcessor(const size_t num_channels, const WindowContainer &window, const STFTOptions &options)
Stateful ISTFT processor for chunked frame-by-frame synthesis.
Array< Real > analysis_window_
ISTFTProcessor(const size_t fft_size, const size_t frame_size, const ISTFTOptions &options)
Construct an inverse STFT processor with a Hann window.
Array< Real > synthesis_window_
bool centered() const noexcept
size_t left_trim_remaining_
void swap(ISTFTProcessor &other) noexcept
Exchange in O(1) the state of this processor and another.
Array< Real > pprocess_frame(ThreadPool &pool, const Container &spectrum, const size_t chunk_size=0)
Array< Real > pprocess_block(ThreadPool &pool, const Array< Array< Complex > > &spectrogram_block, const size_t chunk_size=0)
size_t fft_size() const noexcept
Array< Real > drain_ready_samples(const bool final_flush)
size_t hop_size() const noexcept
Array< Real > process_frame_impl(const Array< Complex > &spectrum, ThreadPool *pool, const size_t chunk_size)
ISTFTProcessor(ISTFTProcessor &&other) noexcept
Take the configuration and the pending samples of another processor, which is left unconfigured,...
Array< Real > process_frame(const Array< Complex > &spectrum)
and Is_Real_Container< SynthesisContainer > ISTFTProcessor(const size_t fft_size, const AnalysisContainer &analysis_window, const SynthesisContainer &synthesis_window, const ISTFTOptions &options)
Construct an inverse STFT processor from any real containers.
Array< Real > emit_samples(const Array< Real > &normalized, const bool final_flush)
Array< Real > pprocess_frame(ThreadPool &pool, const Array< Complex > &spectrum, const size_t chunk_size=0)
void require_configured(const char *ctx) const
ISTFTProcessor & operator=(const ISTFTProcessor &other)=default
Copy the configuration and the pending samples of another processor.
Array< Real > pflush(ThreadPool &, const size_t=0)
Array< Real > process_block(const Array< Array< Complex > > &spectrogram_block)
Array< Real > pending_norm_
Array< Real > pending_output_
void accumulate_frame(const Array< Real > &frame)
ISTFTProcessor(const size_t fft_size, const Array< Real > &window, const ISTFTOptions &options)
Construct an inverse STFT processor with a single window.
Array< Real > process_frame(const Container &spectrum)
ISTFTProcessor(const size_t fft_size, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options)
Construct an inverse STFT processor with custom windows.
size_t emitted_raw_samples_
ISTFTProcessor()=default
Default constructor for an unconfigured inverse processor.
void ensure_pending_size(const size_t size)
bool finalized() const noexcept
Array< Real > normalize_prefix(const size_t count)
ISTFTProcessor(const ISTFTProcessor &other)=default
Copy the configuration and the pending samples of another processor.
size_t frame_size() const noexcept
size_t emitted_signal_samples_
bool configured() const noexcept
Stateful bank of direct-form II transposed IIR filters.
LFilterBank(const size_t num_channels, const IIRCoefficients &coeffs)
void validate_channel_count(const size_t count, const char *ctx) const
Rationale: Internal safety guard.
LFilter & channel(const size_t index)
size_t num_channels() const noexcept
Array< Real > filter_channel(const size_t index, const Array< Real > &signal)
Array< LFilter > filters_
and Is_Real_Container< DenContainer > LFilterBank(const size_t num_channels, const NumContainer &numerator, const DenContainer &denominator)
LFilterBank(const size_t num_channels, const Array< Real > &numerator, const Array< Real > &denominator)
Array< Array< Real > > pfilter(ThreadPool &pool, const Array< Array< Real > > &signals, const size_t chunk_size=0)
Array< Array< Real > > filter(const Array< Array< Real > > &signals)
LFilterBank(const size_t num_channels, const BiquadSection §ion)
const LFilter & channel(const size_t index) const
Array< Real > filter_channel(const size_t index, const Container &signal)
Stateful direct-form II transposed IIR filter.
LFilter(const IIRCoefficients &coeffs)
Construct a linear filter from IIRCoefficients.
bool configured() const noexcept
Returns whether the filter has been initialized with coefficients.
and Is_Real_Container< DenContainer > LFilter(const NumContainer &numerator, const DenContainer &denominator)
Construct a linear filter from any real containers.
void require_configured(const char *ctx) const
const Array< Real > & state() const noexcept
Returns the current internal delay-line state.
const IIRCoefficients & coefficients() const noexcept
Returns the active normalized filter coefficients.
void reset()
Resets the delay-line state to zero.
LFilter(const Array< Real > &numerator, const Array< Real > &denominator)
Construct a linear filter from numerator and denominator arrays.
LFilter(const LFilter &other)=default
Copy the coefficients and the state of another filter.
Array< Real > filter(const Container &signal)
Processes a real-valued container through the stateful filter.
void set_state(const Array< Real > &new_state)
Manually overrides the delay-line state.
LFilter(LFilter &&other) noexcept
Take the coefficients and the state of another filter, which is left unconfigured,...
LFilter(const BiquadSection §ion)
Construct a linear filter from a single BiquadSection.
LFilter & operator=(const LFilter &other)=default
Copy the coefficients and the state of another filter.
size_t order() const noexcept
Returns the filter order (number of feedback coefficients - 1).
void swap(LFilter &other) noexcept
Exchange in O(1) the coefficients and the state of this filter and another.
LFilter()=default
Default constructor for an unconfigured LFilter.
Array< Real > filter(const Array< Real > &signal)
Processes a signal block through the stateful filter.
Multichannel overlap-add convolver with one shared kernel FFT.
Array< bool > has_pending_tail_
void validate_channel_count(const size_t count, const char *ctx) const
Rationale: Internal safety guard.
Array< Array< Real > > convolve(const Array< Array< Real > > &signals) const
Convolve a whole signal per channel with the kernel.
void swap(OverlapAddBank &other) noexcept
Exchange in O(1) the state of this bank and another.
OverlapAddBank(const OverlapAddBank &other)=default
Copy the kernel, the plan and the pending tails of another bank.
const Array< Real > & kernel() const noexcept
Array< Array< Real > > convolve_impl(const Array< Array< Real > > &signals, ThreadPool *pool, const size_t chunk_size) const
static Array< Real > slice_chunk(const Array< Real > &input, const size_t offset, const size_t length)
Returns a contiguous slice of input.
Array< Array< Real > > pflush(ThreadPool &pool, const size_t chunk_size=0)
Array< Array< Real > > process_chunk_batch_impl(const Array< Array< Real > > &block, ThreadPool *pool, const size_t chunk_size)
Array< Array< Real > > process_block(const Array< Array< Real > > &block)
Convolve the next samples of a stream per channel.
Array< Array< Real > > overlaps_
static size_t max_batch_length(const Array< Array< Real > > &signals) noexcept
Returns the maximum signal length in a batch.
size_t block_size() const noexcept
OverlapAddBank(OverlapAddBank &&other) noexcept
Take the state of another bank, which is left empty.
size_t overlap_size() const noexcept
Returns the size of the tail of each channel.
Array< Array< Real > > pconvolve(ThreadPool &pool, const Array< Array< Real > > &signals, const size_t chunk_size=0) const
convolve() with parallel transforms.
Array< Complex > kernel_spectrum_
void pointwise_multiply_batch(Array< Array< Complex > > &spectra, ThreadPool *pool, const size_t chunk_size) const
Rationale: Parallel pointwise multiplication of multiple signal spectra with the shared kernel spectr...
Array< Array< Real > > pprocess_block(ThreadPool &pool, const Array< Array< Real > > &block, const size_t chunk_size=0)
process_block() with parallel transforms.
void clear_channel_overlap(const size_t channel)
Rationale: Resets the overlap buffer for a single channel.
static size_t default_block_size(const size_t kernel_size)
Rationale: Selects a block size that is at least as large as the kernel to ensure efficient FFT proce...
Array< Array< Complex > > build_signal_batch(const Array< Array< Real > > &source, const Array< size_t > &channels, const Array< size_t > &lengths, const size_t offset=0) const
implementation helper for preparing a subset of signal blocks.
OverlapAddBank(const size_t num_channels, const Array< Real > &kernel, const size_t block_size=0)
size_t fft_size() const noexcept
size_t num_channels() const noexcept
Array< Complex > build_signal_block(const Array< Real > &signal, const size_t offset=0, const size_t length=std::numeric_limits< size_t >::max()) const
implementation helper for preparing a signal block for FFT.
Array< Array< Complex > > build_signal_batch(const Array< Array< Real > > &block) const
implementation helper for preparing a batch of signal blocks.
Array< Array< Real > > flush()
OverlapAddBank & operator=(const OverlapAddBank &other)=default
Copy the kernel, the plan and the pending tails of another bank.
Reusable overlap-add convolver for long real sequences.
Array< Real > convolve(const Container &signal) const
convolve() of the samples of a real container.
OverlapAdd & operator=(const OverlapAdd &other)=default
Copy the kernel, the plan and the pending tail of another convolver.
void clear_overlap()
Rationale: Resets the overlap buffer between independent convolution runs.
OverlapAdd(const OverlapAdd &other)=default
Copy the kernel, the plan and the pending tail of another convolver.
Array< Real > convolve_impl(const Array< Real > &signal, ThreadPool *pool, const size_t chunk_size) const
implementation of one-shot linear convolution.
OverlapAdd(OverlapAdd &&other) noexcept
Take the state of another convolver, which is left empty.
Array< Complex > kernel_spectrum_
void swap(OverlapAdd &other) noexcept
Exchange in O(1) the state of this convolver and another.
Array< Real > process_block(const Array< Real > &block)
Convolve the next samples of a stream; the tail of each block is added to the next ones,...
size_t block_size() const noexcept
const Array< Real > & kernel() const noexcept
Array< Real > pprocess_block(ThreadPool &pool, const Array< Real > &block, const size_t chunk_size=0)
process_block() with parallel transforms.
Array< Real > process_chunk_impl(const Array< Real > &block, ThreadPool *pool, const size_t chunk_size)
Rationale: Implements the core Overlap-Add logic for a single block:
Array< Real > pprocess_block(ThreadPool &pool, const Container &block, const size_t chunk_size=0)
pprocess_block() of the samples of a real container.
OverlapAdd(const Array< Real > &kernel, const size_t block_size=0)
Array< Real > pconvolve(ThreadPool &pool, const Container &signal, const size_t chunk_size=0) const
pconvolve() of the samples of a real container.
Array< Real > convolve(const Array< Real > &signal) const
Convolve a whole signal with the kernel.
size_t overlap_size() const noexcept
Array< Real > process_block(const Container &block)
process_block() of the samples of a real container.
size_t fft_size() const noexcept
static size_t default_block_size(const size_t kernel_size)
Array< Real > pconvolve(ThreadPool &pool, const Array< Real > &signal, const size_t chunk_size=0) const
Convolve a whole signal with the kernel, with parallel transforms.
void pointwise_multiply(Array< Complex > &spectrum, ThreadPool *pool, const size_t chunk_size) const
Rationale: Applies the precomputed FIR kernel in the frequency domain via element-wise multiplication...
Array< Complex > build_signal_block(const Array< Real > &signal, const size_t offset, const size_t length) const
Rationale: Prepares a chunk of signal for FFT by zero-padding it to the internal fft_size().
Reusable overlap-save convolver for streaming real FIR filtering.
Array< Real > process_block(const Array< Real > &block)
Processes an input block and returns the corresponding filtered output.
OverlapSave(OverlapSave &&other) noexcept
Take the state of another convolver, which is left empty.
void update_history(const Array< Real > &padded_chunk)
Rationale: Maintains the sliding window of historical samples required to correctly compute the linea...
size_t fft_size() const noexcept
Returns the FFT size used internally (block_size + kernel_size - 1 padded to power of 2).
OverlapSave & operator=(const OverlapSave &other)=default
Copy the kernel, the plan and the pending samples of another convolver.
Array< Real > process_block(const Container &block)
Processes an input block from a real-valued container.
OverlapSave(const OverlapSave &other)=default
Copy the kernel, the plan and the pending samples of another convolver.
void clear_history()
Rationale: Resets the state for a new filtering process.
Array< Complex > kernel_spectrum_
void reset()
Resets the internal filter state and history.
static size_t default_block_size(const size_t kernel_size)
Rationale: Heuristic for choosing a block size that provides a good balance between algorithmic laten...
void swap(OverlapSave &other) noexcept
Exchange in O(1) the state of this convolver and another.
Array< Real > process_chunk_impl(const Array< Real > &chunk)
Rationale: Implements the core Overlap-Save logic for one block:
Array< Complex > build_segment_spectrum(const Array< Real > &chunk) const
Rationale: Prepares a frequency-domain segment by combining historical samples with the current signa...
Array< Real > flush()
Flushes all buffered samples and returns the final tail of the convolution.
const Array< Real > & kernel() const noexcept
Returns the current FIR kernel.
size_t overlap_size() const noexcept
Returns the internal overlap history size.
size_t block_size() const noexcept
Returns the processing block size (the hop size).
Array< Real > convolve(const Container &signal)
Convolves an input signal from a real-valued container.
size_t emitted_output_size_
OverlapSave(const Array< Real > &kernel, const size_t block_size=0)
Array< Real > convolve(const Array< Real > &signal)
Convolves the input signal with the kernel (one-shot convenience).
Array< Real > padded_chunk_copy(const Array< Real > &chunk) const
Internal helper for zero-padding chunks.
Uniform partitioned FIR convolver for low-latency streaming.
Array< Real > convolve(const Container &signal)
convolve() of the samples of a real container.
Array< Real > process_block(const Container &block)
process_block() of the samples of a real container.
size_t fft_size() const noexcept
const Array< Real > & kernel() const noexcept
void clear_state()
Rationale: Resets all delay-line history and overlap buffers.
PartitionedConvolver(const Array< Real > &kernel, const size_t partition_size=0)
void swap(PartitionedConvolver &other) noexcept
Exchange in O(1) the state of this convolver and another.
Array< Array< Complex > > input_history_
Array< Real > padded_partition(const Array< Real > &chunk) const
implementation helper for preparing a padded partition.
Array< Real > process_partition_impl(const Array< Real > &chunk)
Rationale: Implements the core frequency-domain partitioned convolution logic:
Array< Real > convolve(const Array< Real > &signal)
Convolve a whole signal with the kernel.
Array< Real > process_block(const Array< Real > &block)
Convolve the next samples of a stream, a partition at a time.
PartitionedConvolver(PartitionedConvolver &&other) noexcept
Take the state of another convolver, which is left empty.
size_t emitted_output_size_
static size_t default_partition_size(const size_t kernel_size)
Rationale: Selects a partition size that minimizes latency while maintaining FFT efficiency (capped a...
PartitionedConvolver(const PartitionedConvolver &other)=default
Copy the kernel partitions, the plan and the state of another convolver.
size_t partition_size() const noexcept
Array< Complex > zero_spectrum() const
implementation helper for creating zero-filled complex spectra.
Array< Array< Complex > > kernel_partitions_
PartitionedConvolver & operator=(const PartitionedConvolver &other)=default
Copy the kernel partitions, the plan and the state of another convolver.
Precomputed FFT plan for repeated transforms of the same size.
Array< Complex > rfft(const Array< Real > &input) const
Computes the Real-to-Complex FFT (RFFT).
std::shared_ptr< const Plan > half_plan_
void initialize_mixed_radix_plan()
void apply_bit_reversal(Array< Complex > &a) const noexcept
Array< Array< Complex > > ptransformed_batch(ThreadPool &pool, const Array< Array< Complex > > &input, const bool invert=false, const size_t chunk_size=0, const bool prefer_simd=true) const
Returns the parallel batch FFT/IFFT as a new array of arrays.
Array< Complex > ptransformed(ThreadPool &pool, const Array< Complex > &input, const bool invert=false, const size_t chunk_size=0) const
Parallel transform returning a new array.
void transform_batch(Array< Array< Complex > > &batch, const bool invert, const bool prefer_simd=true) const
In-place batch transform for equal-length complex inputs.
Array< Real > inverse_transform_real(const Array< Complex > &input) const
Returns the IFFT projected back to real values.
void initialize_power_of_two_plan()
void initialize_bluestein_plan()
void swap(Plan &other) noexcept
Exchange in O(1) the tables of this plan and another.
Plan(const size_t n)
Constructs a plan for transforms of size n.
Array< Complex > prfft(ThreadPool &pool, const Array< Real > &input, const size_t chunk_size=0) const
Parallel Real-to-Complex FFT (RFFT).
Array< Real > pirfft(ThreadPool &pool, const Array< Complex > &spectrum, const size_t chunk_size=0) const
Parallel Complex-to-Real Inverse FFT (IRFFT).
Complex root_for_length(const size_t length, const size_t exponent, const bool invert) const
void transform(Array< Complex > &a, const bool invert) const
Computes the FFT or IFFT in-place using precomputed tables.
void apply_bluestein_transform(Array< Complex > &a, const bool invert, ThreadPool *pool, const size_t chunk_size) const
size_t size() const noexcept
Returns the transform size this plan was built for.
void apply_transform(Array< Complex > &a, const bool invert, ThreadPool *pool, const size_t chunk_size, const bool prefer_simd) const
bool should_use_neon(ThreadPool *pool, const bool prefer_simd) const noexcept
Plan(const Plan &other)=default
Copy the tables of another plan.
Plan & operator=(const Plan &other)=default
Copy the tables of another plan.
Array< Array< Real > > irfft_batch(const Array< Array< Complex > > &spectra) const
Computes a batch of Complex-to-Real Inverse FFTs.
Array< Array< Complex > > prfft_batch(ThreadPool &pool, const Array< Array< Real > > &input, const size_t chunk_size=0) const
Computes a parallel batch of Real-to-Complex FFTs.
Array< Complex > bluestein_kernel_forward_
void apply_mixed_radix_transform(Array< Complex > &a, const bool invert) const
std::shared_ptr< const Plan > bluestein_plan_
Array< Real > pinverse_transform_real(ThreadPool &pool, const Array< Complex > &input, const size_t chunk_size=0) const
Parallel IFFT projected back to real values.
Array< Complex > bluestein_kernel_inverse_
void apply_butterflies(Array< Complex > &a, const bool invert, ThreadPool *pool, const size_t chunk_size, const bool prefer_simd) const
Array< Complex > transformed(const Array< Complex > &input, const bool invert=false) const
Computes the FFT or IFFT returning a new array.
Array< Complex > inverse_transform(const Array< Complex > &input) const
Returns the inverse transform as a new array.
bool automatic_batch_simd_candidate(const size_t batch_size) const noexcept
Plan(Plan &&other) noexcept
Take the tables of another plan, which is left empty (size 0).
Array< Array< Real > > pinverse_transform_real_batch(ThreadPool &pool, const Array< Array< Complex > > &input, const size_t chunk_size=0, const bool prefer_simd=true) const
Returns the parallel inverse batch transform projected back to real values.
bool supports_power_of_two_real_optimization() const noexcept
Array< Complex > pinverse_transform(ThreadPool &pool, const Array< Complex > &input, const size_t chunk_size=0) const
Parallel inverse transform returning a new array.
Array< Array< Real > > pirfft_batch(ThreadPool &pool, const Array< Array< Complex > > &spectra, const size_t chunk_size=0) const
Computes a parallel batch of Complex-to-Real Inverse FFTs.
Array< Complex > mixed_radix_transform_recursive(const Array< Complex > &input, const size_t factor_index, const size_t current_size, const bool invert) const
Array< Array< Complex > > inverse_transform_batch(const Array< Array< Complex > > &input) const
Returns the inverse batch transform as a new array of arrays.
bool should_use_avx2(ThreadPool *pool, const bool prefer_simd) const noexcept
Array< Complex > twiddles_
void ptransform_batch(ThreadPool &pool, Array< Array< Complex > > &batch, const bool invert, const size_t chunk_size=0, const bool prefer_simd=true) const
Parallel batch transform for equal-length complex inputs.
Array< Real > irfft(const Array< Complex > &spectrum) const
Computes the Complex-to-Real Inverse FFT (IRFFT).
Array< Array< Complex > > transformed_batch(const Array< Array< Complex > > &input, const bool invert=false, const bool prefer_simd=true) const
Returns the batch FFT/IFFT as a new array of arrays.
Array< Array< Complex > > pinverse_transform_batch(ThreadPool &pool, const Array< Array< Complex > > &input, const size_t chunk_size=0, const bool prefer_simd=true) const
Returns the parallel inverse batch transform.
Array< Array< Complex > > rfft_batch(const Array< Array< Real > > &input) const
Computes a batch of Real-to-Complex FFTs.
Array< Array< Real > > inverse_transform_real_batch(const Array< Array< Complex > > &input) const
Returns the inverse batch transform projected back to real values.
Array< Complex > bluestein_chirp_
void ptransform(ThreadPool &pool, Array< Complex > &a, const bool invert, const size_t chunk_size=0) const
Parallel in-place transform using a thread pool.
Plan()=default
Constructs an empty plan (size 0).
Stateful bank of SOS cascades, one per channel.
SOSFilter & channel(const size_t index)
SOSFilterBank(const size_t num_channels, const SectionsContainer §ions)
Array< Array< Real > > filter(const Array< Array< Real > > &signals)
Array< Real > filter_channel(const size_t index, const Container &signal)
const SOSFilter & channel(const size_t index) const
Array< Array< Real > > pfilter(ThreadPool &pool, const Array< Array< Real > > &signals, const size_t chunk_size=0)
Array< Real > filter_channel(const size_t index, const Array< Real > &signal)
Array< SOSFilter > filters_
size_t num_channels() const noexcept
void validate_channel_count(const size_t count, const char *ctx) const
Rationale: Internal safety guard.
SOSFilterBank(const size_t num_channels, const Array< BiquadSection > §ions)
Stateful cascade of second-order sections.
SOSFilter(const SOSFilter &other)=default
Copy the sections and the states of another cascade.
Array< Array< Real > > states_
size_t num_sections() const noexcept
Returns the number of sections in the cascade.
SOSFilter(const SectionsContainer §ions)
Construct a cascade of SOS from any biquad container.
SOSFilter(const Array< BiquadSection > §ions)
Construct a cascade of second-order sections (SOS).
bool configured() const noexcept
Returns whether the filter has been configured.
void swap(SOSFilter &other) noexcept
Exchange in O(1) the sections and the states of this cascade and another.
SOSFilter()=default
Default constructor for an unconfigured SOSFilter.
const Array< Real > & state(const size_t index) const
Returns the current delay-line state of section index.
Array< BiquadSection > sections_
Array< IIRCoefficients > coeffs_
Array< Real > filter(const Array< Real > &signal)
Processes a signal block through the stateful SOS cascade.
Array< Real > filter(const Container &signal)
Processes a real-valued container through the stateful SOS cascade.
void reset()
Resets all internal delay lines to zero.
SOSFilter & operator=(const SOSFilter &other)=default
Copy the sections and the states of another cascade.
SOSFilter(SOSFilter &&other) noexcept
Take the sections and the states of another cascade, which is left unconfigured, as built by default.
void require_configured(const char *ctx) const
Stateful STFT processor for chunked real-time analysis.
Array< Array< Complex > > pflush(ThreadPool &pool, const size_t chunk_size=0)
size_t frame_size() const noexcept
void initialize_pending()
STFTProcessor(STFTProcessor &&other) noexcept
Take the configuration and the pending samples of another processor, which is left unconfigured,...
void append_samples(const Array< Real > &block)
size_t fft_size() const noexcept
bool centered() const noexcept
STFTProcessor(const Array< Real > &window, const STFTOptions &options)
Construct an STFT processor with a fixed analysis window.
bool finalized() const noexcept
Array< Array< Complex > > pprocess_block(ThreadPool &pool, const Container &block, const size_t chunk_size=0)
Array< Array< Complex > > flush()
Array< Array< Complex > > process_block(const Container &block)
STFTProcessor(const STFTProcessor &other)=default
Copy the configuration and the pending samples of another processor.
void require_configured(const char *ctx) const
STFTProcessor & operator=(const STFTProcessor &other)=default
Copy the configuration and the pending samples of another processor.
STFTProcessor(const size_t frame_size, const STFTOptions &options)
Construct an STFT processor using a Hann window.
Array< Array< Complex > > process_block(const Array< Real > &block)
const Array< Real > & window() const noexcept
void swap(STFTProcessor &other) noexcept
Exchange in O(1) the state of this processor and another.
Array< Array< Complex > > emit_ready_frames(ThreadPool *pool, const size_t chunk_size, const bool allow_partial_frames)
Array< Array< Complex > > pprocess_block(ThreadPool &pool, const Array< Real > &block, const size_t chunk_size=0)
STFTProcessor(const WindowContainer &window, const STFTOptions &options)
Construct an STFT processor from any real container.
size_t hop_size() const noexcept
STFTProcessor()=default
Default constructor for an unconfigured processor.
bool pad_end() const noexcept
bool configured() const noexcept
Fast Fourier Transform (FFT) and DSP Toolkit.
static Array< Array< Array< Complex > > > inverse_transform3d(const Array< Array< Array< Complex > > > &input)
Functional inverse 3-D FFT wrapper.
static Array< Array< Complex > > rfft_batch(const Array< Array< Real > > &input)
Functional compact real FFT for equal-length real batches.
static Array< Real > group_delay(const SectionsContainer §ions, const size_t num_points=512, const bool whole=false)
static Array< Complex > spectrum(const Container &input)
DSP alias for complex-valued container forward FFT.
static Array< Real > istft(const Array< Array< Complex > > &spectrogram, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options)
Reconstructs a real signal using explicit ISTFT options.
static Array< Real > signed_binomial(const size_t power, const Real sign)
Rationale: Computes (1 + sign*x)^power coefficients.
static Array< Complex > transform_padded(const Container &input)
Forward FFT with padding for real-valued containers.
static void validate_real_spectrum(const Array< Complex > &input, const char *ctx)
Rationale: Ensures a complex spectrum has the Hermitian symmetry (X[k] = X[N-k]*) required to be the ...
static Array< BiquadSection > bessel_bandstop(const size_t order, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Bessel band-stop design returned as SOS.
static bool has_near_pole_zero_cancellation(const Array< Real > &numerator, const Array< Real > &denominator, const Real tolerance)
static Array< Array< Complex > > stft(const Array< Real > &signal, const Array< Real > &window, const size_t hop_size, const bool pad_end=true)
Computes a basic STFT for a real signal using a custom window.
static WeightedFrequencyGrid build_weighted_frequency_grid(const size_t num_taps, const Array< Real > &bands, const Array< Real > &desired, const Real sample_rate, const Array< Real > &weights, const size_t grid_density, const char *ctx)
static Real hermitian_tolerance(const Complex &lhs, const Complex &rhs, const size_t n) noexcept
Rationale: Numerical tolerance for Hermitian symmetry checks.
static Array< Array< Real > > frame_signal(const Array< Real > &signal, const size_t frame_size, const size_t hop_size, const bool pad_end=true)
Splits a real signal into frames using a fixed hop size.
static Array< Real > apply_blackman_window(const Array< Real > &signal)
Applies a Blackman window of matching size to a real signal.
static Array< Real > phase_delay(const Array< Real > &numerator, const size_t num_points=512, const bool whole=false)
static Array< Array< Real > > pbatched_sosfilt(ThreadPool &pool, const Array< Array< Real > > &signals, const Array< BiquadSection > §ions, const size_t chunk_size=0)
and static Is_Real_Container< Container2 > Array< Real > overlap_save_convolution(const Container1 &signal, const Container2 &kernel, const size_t block_size=0)
Overlap-save convolution for real-valued containers.
static Array< Real > trim_leading_zeros_copy(const Array< Real > &input) noexcept
Rationale: Copy utility that removes leading zero coefficients, effectively normalizing the polynomia...
static Array< Real > hamming_window(const size_t n)
Returns a Hamming window of length n.
and Is_Real_Container< DesiredContainer > and static Is_Real_Container< WeightContainer > Array< Real > remez(const size_t num_taps, const BandContainer &bands, const DesiredContainer &desired, const Real sample_rate, const WeightContainer &weights, const size_t grid_density=32, const size_t max_iterations=64)
SimdBackend
SIMD hardware acceleration backends.
@ scalar
Generic implementation.
static Array< size_t > frame_offsets(const size_t signal_size, const size_t frame_size, const size_t hop_size, const bool pad_end=true)
Returns the frame start offsets used by frame_signal.
static std::pair< Real, Real > prewarp_band_edges(const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate, const char *ctx)
Prewarps a pair of band edges for bilinear transform.
static Array< Real > sos_filtfilt_impl(const Array< Real > &signal, const Array< BiquadSection > §ions, const char *ctx)
static void validate_no_near_pole_zero_cancellation(const Array< BiquadSection > §ions, const Real tolerance)
static Array< Array< Complex > > compact_real_batch_spectra(const Array< Array< Complex > > &full_spectra)
static Array< Real > project_real_output(const Array< Complex > &input, const char *ctx)
Projects a complex-valued output array back to the real domain.
static Array< Complex > build_complex_input(const Container &input)
static Array< Real > phase_delay(const BiquadSection §ion, const size_t num_points=512, const bool whole=false)
static Array< Complex > ptransformed(ThreadPool &pool, const Array< Complex > &input, const bool invert=false, const size_t chunk_size=0)
Parallel FFT/IFFT that returns a new array.
and static Is_Real_Container< DenContainer > GainMarginInfo gain_margin(const NumContainer &numerator, const DenContainer &denominator, const size_t num_points=1024, const bool whole=false)
static Array< Real > lfilter(const Array< Real > &signal, const Array< Real > &numerator, const Array< Real > &denominator, const Array< Real > &initial_state={})
One-shot causal IIR filtering.
and static Is_Real_Container< DenContainer > Real minimum_pole_zero_distance(const NumContainer &numerator, const DenContainer &denominator)
static constexpr const char * simd_preference_name(const SimdPreference preference) noexcept
Returns the human-readable name of a SIMD preference.
static Array< Array< Complex > > stft(const Array< Real > &signal, const Array< Real > &window, const STFTOptions &options)
Computes an STFT with explicit analysis options.
static FrequencyResponse freqz_impl(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points, const bool whole, const char *ctx)
static Array< Real > apply_blackman_window(const Container &signal)
SimdPreference
User-selected SIMD dispatch preference.
@ scalar_only
Force the portable scalar implementation.
@ automatic
Use the fastest available hardware.
@ neon_only
Force NEON (must be supported by CPU).
@ avx2_only
Force AVX2 (must be supported by CPU).
static Array< Real > phase_delay_impl(const FrequencyResponse &response)
implementation of numeric phase delay calculation.
static PhaseMarginInfo phase_margin(const BiquadSection §ion, const size_t num_points=1024, const bool whole=false)
and static Is_Real_Container< Container2 > Array< Real > multiply(const Container1 &a, const Container2 &b)
Multiplication for real-valued containers.
static Real modified_bessel_i0(const Real x) noexcept
Standard Zeroth-order Modified Bessel function of the first kind.
static Array< Complex > rfft(const Container &input)
Compact real FFT for real-valued containers.
static constexpr size_t saturating_product(const size_t lhs, const size_t rhs) noexcept
static PolynomialEvaluation evaluate_whole_polynomial(const Array< Real > &coefficients, const Complex &x) noexcept
static Array< BiquadSection > butterworth_highpass(const size_t order, const Real cutoff_frequency, const Real sample_rate)
Digital Butterworth high-pass design returned as SOS.
static PhaseMarginInfo phase_margin(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points=1024, const bool whole=false)
static size_t resolve_irfft_signal_size(const Array< Complex > &spectrum, const size_t signal_size, const char *ctx)
static Array< Real > filtfilt(const Array< Real > &signal, const BiquadSection §ion)
Zero-phase filtering of one biquad section.
static Array< Real > analytic_phase_delay_impl(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points, const bool whole, const char *ctx)
implementation of analytic phase delay calculation.
static Real evaluate_cosine_series(const Array< Real > &coefficients, const Real omega) noexcept
static Array< BiquadSection > bessel_lowpass(const size_t order, const Real cutoff_frequency, const Real sample_rate)
Digital Bessel low-pass design returned as SOS.
static Array< Complex > pspectrum(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of spectrum(const Container&).
static Array< Complex > poles(const IIRCoefficients &coeffs)
static void validate_stable(const Array< Real > &denominator, const Real min_margin)
and static Is_Real_Container< WindowContainer > PowerSpectralDensity welch(const SignalContainer &signal, const WindowContainer &window, const Real sample_rate, const WelchOptions &options={})
static Array< Complex > apply_hann_window(const Array< Complex > &signal)
Applies a Hann window of matching size to a complex signal.
and Is_Real_Container< ContainerY > and static Is_Real_Container< WindowContainer > CoherenceEstimate coherence(const ContainerX &x, const ContainerY &y, const WindowContainer &window, const Real sample_rate, const WelchOptions &options={})
static Array< Real > solve_dense_system(Array< Real > matrix, Array< Real > rhs, const size_t n, const char *ctx)
static Array< Real > filtfilt(const Array< Real > &signal, const IIRCoefficients &coeffs)
Zero-phase IIR filtering with explicit coefficient groups.
static void validate_no_near_pole_zero_cancellation(const IIRCoefficients &coeffs, const Real tolerance)
static BiquadSection section_from_coefficients(const Array< Real > &numerator, const Array< Real > &denominator, const char *ctx)
Rationale: Converts generic IIR coefficients into a stabilized BiquadSection structure,...
static bool roots_pass_residual_check(const Array< Real > &coefficients, const Array< Complex > &roots, const Real tol) noexcept
static Array< Real > firwin_bandstop(const size_t num_taps, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate, const Array< Real > &window)
FIR band-stop design via the window method.
static Array< Real > solve_remez_cosine_series(const Array< Real > &omega, const Array< Real > &desired, const Array< Real > &weight, const Array< size_t > &extrema, const size_t half_order, const char *ctx)
static Array< Real > pistft(ThreadPool &pool, const Array< Array< Complex > > &spectrogram, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size, const size_t signal_length=0, const size_t chunk_size=0)
Parallel STFT inversion using a thread pool.
static Array< Array< Real > > overlap_add_convolution_batch(const Array< Array< Real > > &signals, const Array< Real > &kernel, const size_t block_size=0)
Multichannel overlap-add convolution with a shared kernel FFT.
static void validate_no_near_pole_zero_cancellation(const BiquadSection §ion, const Real tolerance)
static Array< Complex > apply_window(const Array< Complex > &signal, const Array< Real > &window)
Applies a real window sample-by-sample to a complex signal.
static Real stability_margin(const SectionsContainer §ions)
static Array< Real > lfilter(const Array< Real > &signal, const IIRCoefficients &coeffs, const Array< Real > &initial_state={})
static bool has_near_pole_zero_cancellation(const Array< Complex > &zeros, const Array< Complex > &poles, const Real tolerance)
Detects near pole/zero cancellations under a tolerance.
static Array< Real > overlap_save_convolution(const Array< Real > &signal, const Array< Real > &kernel, const size_t block_size=0)
Convenience wrapper for overlap-save real convolution.
static Array< Complex > zeros(const BiquadSection §ion)
static Array< Real > phase_spectrum(const Container &input)
static constexpr bool is_power_of_two(const size_t n) noexcept
Checks if a given number is a power of two.
static Array< BiquadSection > chebyshev2_lowpass(const size_t order, const Real attenuation_db, const Real cutoff_frequency, const Real sample_rate)
Digital Chebyshev-II low-pass design returned as SOS.
static void validate_stable(const SectionsContainer §ions)
static void append_all(Array< T > &dst, const Array< T > &src)
static SeriesEvaluation evaluate_series_at_unit_circle(const Array< Real > &coefficients, const Real omega, const char *ctx)
static void ptransform(ThreadPool &pool, Array< Complex > &a, const bool invert, const size_t chunk_size=0)
Parallel in-place FFT/IFFT using a thread pool.
static Array< Array< Complex > > pstft(ThreadPool &pool, const Array< Real > &signal, const size_t frame_size, const STFTOptions &options, const size_t chunk_size=0)
Parallel Hann-window STFT with explicit analysis options.
static Array< Real > firwin_bandpass(const size_t num_taps, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate, const Real attenuation_db)
FIR band-pass design using a Kaiser window.
static bool try_durand_kerner_roots(const Array< Real > &coefficients, const Real tol, Array< Complex > &roots, const size_t max_iterations=192) noexcept
static bool try_aberth_ehrlich_roots(const Array< Real > &coefficients, const Real tol, Array< Complex > &roots, const size_t max_iterations=192) noexcept
static Array< Complex > zeros(const Array< Real > &numerator)
Returns the finite zeros of a transfer numerator.
static Array< Array< Array< Complex > > > batched_stft(const Array< Array< Real > > &signals, const size_t frame_size, const STFTOptions &options)
Hann-window batched STFT.
and static Is_Real_Container< WindowContainer > Array< Array< Complex > > stft(const SignalContainer &signal, const WindowContainer &window, const STFTOptions &options)
static IIRCoefficients apply_analog_rational_transform(const Array< Real > &numerator, const Array< Real > &denominator, const Array< Real > &map_numerator, const Array< Real > &map_denominator, const char *ctx)
Rationale: Transforms an analog transfer function H(s) via rational substitution s = N(z)/D(z),...
static Real refine_scalar_crossing(const Evaluator &evaluator, const Real x0, const Real y0, const Real x1, const Real y1, const Real target)
static Array< BiquadSection > transfer_function_to_sections(const IIRCoefficients &coeffs, const Array< RootGroup > &zero_groups, const char *ctx)
Rationale: Decomposes a general IIR transfer function into a cascade of Second-Order Sections (SOS) b...
static Array< Real > multiply_real_optimized(const Array< Real > &a, const Array< Real > &b, ThreadPool *pool=nullptr, const size_t chunk_size=0)
Rationale: Efficiently multiplies two real sequences using a single N-point complex FFT by packing on...
static GainMarginInfo gain_margin(const FrequencyResponse &response)
Estimates gain margin around the -pi phase crossover.
static Real comp_ellint_1_impl(const Real k)
static Array< Array< Complex > > stft(const Array< Real > &signal, const size_t frame_size, const size_t hop_size, const bool pad_end=true)
Computes a basic STFT for a real signal using a Hann window.
static Array< Real > phase_delay(const FrequencyResponse &response)
Estimates phase delay from a sampled frequency response.
static void validate_overlap_constraints(const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size, const bool validate_nola, const bool validate_cola, const char *ctx)
Rationale: Internal validator for STFT/ISTFT windowing parameters.
static Real stability_margin(const Array< Real > &denominator)
Signed stability margin relative to the unit circle.
static Array< Real > firwin_lowpass(const size_t num_taps, const Real cutoff_frequency, const Real sample_rate, const Real attenuation_db)
FIR low-pass design via the window method using a Kaiser window.
static Array< Real > istft_impl(const Array< Array< Complex > > &spectrogram, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options, ThreadPool *pool, const size_t chunk_size)
implementation of the Inverse Short-Time Fourier Transform.
static Real minimum_pole_zero_distance(const Array< Complex > &zeros, const Array< Complex > &poles)
Returns the minimum pole/zero distance in a greedy pairing.
static Array< Complex > zeros(const IIRCoefficients &coeffs)
static Real window_enbw(const Container &window)
static Real align_phase_near_reference(const Real raw_phase, const Real reference_phase) noexcept
static Array< Real > pistft(ThreadPool &pool, const Array< Array< Complex > > &spectrogram, const size_t frame_size, const size_t hop_size, const size_t signal_length=0, const size_t chunk_size=0)
Parallel STFT inversion using a Hann window pair.
static Array< Complex > apply_hamming_window(const Array< Complex > &signal)
Applies a Hamming window of matching size to a complex signal.
static PhaseMarginInfo phase_margin_impl(const FrequencyResponse &response)
static Array< Real > inverse_transform_real_general_impl(const Array< Complex > &input, const char *ctx, ThreadPool *pool, const size_t chunk_size)
static Array< Real > build_real_input(const Container &input)
static Array< Real > firls_impl(const size_t num_taps, const Array< Real > &bands, const Array< Real > &desired, const Real sample_rate, const Array< Real > &weights, const char *ctx)
implementation of Least-Squares FIR design.
static Array< Real > filtfilt(const Array< Real > &signal, const Array< BiquadSection > §ions)
Zero-phase filtering of a cascade of biquad sections.
and static Is_Real_Container< Container2 > Array< Real > poverlap_add_convolution(ThreadPool &pool, const Container1 &signal, const Container2 &kernel, const size_t block_size=0, const size_t chunk_size=0)
Parallel version of overlap_add_convolution(const Container1&, const Container2&, size_t).
static FrequencyResponse freqz(const BiquadSection §ion, const size_t num_points=512, const bool whole=false)
static Array< Real > analytic_group_delay_impl(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points, const bool whole, const char *ctx)
Rationale: Analytic calculation of group delay (-dphi/domega) using the complex derivative of the tra...
static Array< Real > pirfft(ThreadPool &pool, const Array< Complex > &spectrum, const size_t signal_size=0, const size_t chunk_size=0)
Parallel version of irfft(const Array<Complex>&, size_t).
static Array< Complex > zeros(const Container &numerator)
static CoherenceEstimate coherence(const Array< Real > &x, const Array< Real > &y, const Array< Real > &window, const Real sample_rate, const WelchOptions &options={})
Magnitude-squared coherence estimate using Welch averages.
static Array< Real > unwrap_phase(const Array< Real > &phase)
implementation of phase unwrapping (removes +/- 2*pi jumps).
static Array< Real > polynomial_power(const Array< Real > &poly, const size_t exponent, const char *ctx)
implementation of P(x)^n via successive multiplication.
static bool is_stable(const Container &denominator)
static constexpr bool Is_Real_Batch_Container
static Array< Real > phase_delay(const Array< BiquadSection > §ions, const size_t num_points=512, const bool whole=false)
static bool neon_dispatch_available() noexcept
Returns whether the runtime CPU can execute the NEON kernel when it has been compiled in.
static Array< Real > build_padded_frame_from_prefix(const Array< Real > &input, const size_t frame_size)
static Array< Array< Complex > > ptransformed2d(ThreadPool &pool, const Array< Array< Complex > > &input, const bool invert=false, const size_t chunk_size=0)
Parallel functional 2-D FFT/IFFT wrapper for matrices.
static void scatter_axis_slice(Array< Complex > &data, const size_t base_offset, const size_t axis_stride, const Array< Complex > &slice)
Rationale: Writes back a transformed contiguous slice into its original (potentially non-contiguous) ...
static Array< Array< Real > > pbatched_lfilter(ThreadPool &pool, const Array< Array< Real > > &signals, const Array< Real > &numerator, const Array< Real > &denominator, const Array< Array< Real > > &initial_states={}, const size_t chunk_size=0)
static constexpr const char * simd_backend_name(const SimdBackend backend) noexcept
Returns the human-readable name of a SIMD backend.
and static Is_Real_Container< WindowContainer > Array< Array< Complex > > stft(const SignalContainer &signal, const WindowContainer &window, const size_t hop_size, const bool pad_end=true)
static Array< Complex > poles(const Array< BiquadSection > §ions)
static Array< Array< Real > > pbatched_istft(ThreadPool &pool, const Array< Array< Array< Complex > > > &spectrograms, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options, const Array< size_t > &signal_lengths={}, const size_t chunk_size=0)
Parallel batched ISTFT across signals.
static Array< Array< Complex > > pinverse_transform2d(ThreadPool &pool, const Array< Array< Complex > > &input, const size_t chunk_size=0)
Parallel functional inverse 2-D FFT wrapper.
static Array< BiquadSection > chebyshev2_highpass(const size_t order, const Real attenuation_db, const Real cutoff_frequency, const Real sample_rate)
Digital Chebyshev-II high-pass design returned as SOS.
static Array< Real > irfft(const Array< Complex > &spectrum, const size_t signal_size=0)
Reconstructs a real signal from a compact rfft() spectrum.
static Array< BiquadSection > design_transformed_sections(const AnalogPrototype &prototype, const Array< Real > &map_numerator, const Array< Real > &map_denominator, const Real sample_rate, const char *ctx)
Generic implementation for designing transformed SOS cascades.
static size_t resolve_welch_fft_size(const WelchOptions &options, const size_t frame_size, const char *ctx)
Default FFT size for Welch analysis (zero-padded to power of 2).
static Array< BiquadSection > butterworth_lowpass(const size_t order, const Real cutoff_frequency, const Real sample_rate)
Digital Butterworth low-pass design returned as SOS.
static Array< Array< Array< Complex > > > pbatched_stft(ThreadPool &pool, const Array< Array< Real > > &signals, const size_t frame_size, const STFTOptions &options, const size_t chunk_size=0)
Parallel Hann-window batched STFT.
static bool is_stable(const Array< Real > &denominator)
Checks BIBO stability from denominator roots.
static Array< Array< Complex > > prfft_batch(ThreadPool &pool, const Array< Array< Real > > &input, const size_t chunk_size=0)
Parallel compact real FFT for equal-length real batches.
static Array< Real > group_delay(const Array< Real > &numerator, const size_t num_points=512, const bool whole=false)
static BalancedPolynomial balance_polynomial_for_roots(const Array< Real > &coefficients, const char *ctx)
static Array< Complex > polynomial_roots_impl(const Array< Real > &coefficients, const char *ctx)
Rationale: Master implementation for polynomial root-finding.
static Real minimum_cancellation_distance_impl(const Array< PoleZeroPair > &pairs) noexcept
Rationale: Estimates the minimum distance between any matched pole and zero to identify potential can...
static Array< Real > phase_delay(const SectionsContainer §ions, const size_t num_points=512, const bool whole=false)
static Array< Array< Real > > pmultichannel_istft(ThreadPool &pool, const Array< Array< Array< Complex > > > &spectrograms, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options={}, const Array< size_t > &signal_lengths={}, const SpectrogramLayout layout=SpectrogramLayout::channel_frame_bin, const size_t chunk_size=0)
Parallel multichannel ISTFT from either supported layout.
static TensorLayout row_major_layout(const Array< size_t > &shape)
Builds a default row-major tensor layout for a flat buffer.
static constexpr size_t twiddle_refresh_period
static Array< Real > hann_window(const size_t n)
Returns a Hann window of length n.
static Array< Complex > rfft(const Array< Real > &input)
Computes the compact real FFT of size floor(N/2) + 1.
static Real integrate_offset_cos_basis(const Real omega_lo, const Real omega_hi, const size_t harmonic) noexcept
implementation helper for firls slope integration.
static Array< Real > remez(const size_t num_taps, const Array< Real > &bands, const Array< Real > &desired, const Real sample_rate, const Array< Real > &weights={}, const size_t grid_density=32, const size_t max_iterations=64)
FIR equiripple design via a dense-grid Remez exchange.
static Array< Array< Array< Complex > > > pinverse_transform3d(ThreadPool &pool, const Array< Array< Array< Complex > > > &input, const size_t chunk_size=0)
Parallel functional inverse 3-D FFT wrapper.
static Array< Complex > pspectrum(ThreadPool &pool, const Array< Complex > &input, const size_t chunk_size=0)
Parallel version of spectrum(const Array<Complex>&).
static Array< Real > pistft(ThreadPool &pool, const Array< Array< Complex > > &spectrogram, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options, const size_t chunk_size=0)
Parallel ISTFT with explicit options.
static Real minimum_pole_zero_distance(const Array< BiquadSection > §ions)
static Array< Real > analytic_sos_group_delay_impl(const Array< BiquadSection > §ions, const FrequencyResponse &response, const char *ctx)
implementation of analytic group delay for SOS cascades.
static Array< size_t > evenly_spaced_extrema(const size_t grid_size, const size_t extremal_count)
static Array< Real > trim_polynomial_leading_zeros(const Array< Real > &input, const char *ctx)
Validation wrapper for trim_leading_zeros_copy.
static Array< Real > power_spectrum(const Container &input)
static Real stability_margin(const Array< BiquadSection > §ions)
static Array< Complex > pinverse_transform(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of inverse_transform(const Container&).
and static Is_Real_Container< CoeffContainer > Array< Real > resample_poly(const SignalContainer &signal, const size_t up, const size_t down, const CoeffContainer &coeffs)
static Array< Array< Real > > project_real_batch_output(const Array< Array< Complex > > &input, const char *ctx)
static Real evaluate_fir_response_magnitude(const Array< Real > &coeffs, const Real omega, const char *ctx)
implementation helper for FIR frequency response magnitude.
and static Is_Real_Container< DesiredContainer > Array< Real > remez(const size_t num_taps, const BandContainer &bands, const DesiredContainer &desired, const Real sample_rate)
static Array< Real > irfft(const Container &spectrum, const size_t signal_size=0)
Inverse real transform (compact) for complex-valued containers.
static Array< Array< Array< Complex > > > ptransformed2d_batch(ThreadPool &pool, const Array< Array< Array< Complex > > > &input, const bool invert=false, const size_t chunk_size=0)
Parallel functional 2-D batched FFT/IFFT wrapper.
and static Is_Real_Container< Container2 > Array< Real > pmultiply(ThreadPool &pool, const Container1 &a, const Container2 &b, const size_t chunk_size=0)
Parallel version of multiply(const Container1&, const Container2&).
static AnalogPrototype butterworth_prototype(const size_t order, const char *ctx)
static Array< Real > overlap_profile(const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size, const char *ctx)
Rationale: Computes the effective window product for a windowed overlap-add process to validate recon...
static Array< Array< Real > > batched_istft(const Array< Array< Array< Complex > > > &spectrograms, const Array< Real > &window, const ISTFTOptions &options, const Array< size_t > &signal_lengths={})
Batched ISTFT using a shared analysis/synthesis window.
static Real max_root_radius(const Array< Complex > &roots) noexcept
Returns the magnitude of the largest root in the set.
static Array< Array< Array< Complex > > > ptransformed3d(ThreadPool &pool, const Array< Array< Array< Complex > > > &input, const bool invert=false, const size_t chunk_size=0)
Parallel functional 3-D FFT/IFFT wrapper for tensors.
static Array< Complex > prfft(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of rfft(const Container&).
static SimdBackend simd_backend() noexcept
Returns the default SIMD backend used by standalone plan transforms for this precision.
static Array< Array< Real > > poverlap_add_convolution_batch(ThreadPool &pool, const Array< Array< Real > > &signals, const Array< Real > &kernel, const size_t block_size=0, const size_t chunk_size=0)
Parallel version of overlap_add_convolution_batch.
static Real normalized_sinc(const Real x) noexcept
Standard normalized sinc function sin(pi*x)/(pi*x).
static Real ellint_1_impl(const Real k, const Real phi)
static Array< Real > demean_copy(const Array< Real > &input)
Returns a copy with DC offset removed.
static Array< Array< Real > > frame_signal(const Container &signal, const size_t frame_size, const size_t hop_size, const bool pad_end=true)
static const char * detected_simd_backend_name() noexcept
Returns the detected hardware SIMD backend name.
static Array< Array< Complex > > expand_real_batch_spectra(const Array< Array< Complex > > &spectra, const size_t signal_size, const char *ctx)
static Array< Real > inverse_transform_real_optimized_impl(const Array< Complex > &input, const char *ctx, ThreadPool *pool, const size_t chunk_size, InversePackedTransform inverse_packed)
Rationale: Optimized Inverse FFT for real signals of size N (power-of-two).
static Array< Real > resample_poly(const SignalContainer &signal, const size_t up, const size_t down, const ResamplePolyOptions &options={})
static Array< Real > lfilter(const Array< Real > &signal, const BiquadSection §ion, const Array< Real > &initial_state={})
static Array< Real > istft(const Array< Array< Complex > > &spectrogram, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size, const size_t signal_length=0)
Reconstructs a real signal from an STFT using overlap-add.
static Array< PoleZeroPair > pair_poles_and_zeros(const Array< BiquadSection > §ions)
static Array< Real > pinverse_transform_real(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of inverse_transform_real(const Container&).
static Real stability_margin(const Container &denominator)
static CrossSpectralDensity csd(const Array< Real > &x, const Array< Real > &y, const Array< Real > &window, const Real sample_rate, const WelchOptions &options={})
One-sided cross-spectral density estimate using a custom window.
static Array< Complex > zeros(const SectionsContainer §ions)
static Array< Array< Real > > prepare_welch_frames(const Array< Real > &signal, const Array< Real > &window, const WelchOptions &options, const char *ctx)
Rationale: Encapsulates frame extraction, detrending and windowing common to Welch and other spectral...
static Complex evaluate_transfer_at(const Array< Real > &numerator, const Array< Real > &denominator, const Real omega, const char *ctx)
static Array< BiquadSection > elliptic_bandstop(const size_t order, const Real ripple_db, const Real attenuation_db, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital elliptic/Cauer band-stop design returned as SOS.
static bool is_stable(const SectionsContainer §ions)
static Array< Real > one_sided_frequency_grid(const size_t fft_size, const Real sample_rate, const char *ctx)
Maps bin indices to frequency in Hz.
static Array< Complex > lift_real_input(const Array< Real > &input)
Lifts a real-valued input array to the complex domain.
static Array< Real > pfiltfilt(ThreadPool &pool, const Array< Real > &signal, const Array< Real > &coeffs, const size_t block_size=0, const size_t chunk_size=0)
Parallel zero-phase FIR filtering via forward-backward convolution.
static constexpr bool Is_Biquad_Container
static Array< Array< Real > > batched_istft(const Array< Array< Array< Complex > > > &spectrograms, const size_t frame_size, const ISTFTOptions &options, const Array< size_t > &signal_lengths={})
Hann-window batched ISTFT.
static Array< PoleZeroPair > pair_poles_and_zeros(const Array< Real > &numerator, const Array< Real > &denominator)
static Array< Array< Real > > pbatched_istft(ThreadPool &pool, const Array< Array< Array< Complex > > > &spectrograms, const size_t frame_size, const ISTFTOptions &options, const Array< size_t > &signal_lengths={}, const size_t chunk_size=0)
Parallel Hann-window batched ISTFT.
static size_t validate_stft_options(const Array< Real > &window, const STFTOptions &options, const char *ctx)
static CoherenceEstimate coherence(const Array< Real > &x, const Array< Real > &y, const size_t frame_size, const Real sample_rate, const WelchOptions &options={})
Magnitude-squared coherence estimate using a Hann window.
static Array< BiquadSection > elliptic_highpass(const size_t order, const Real ripple_db, const Real attenuation_db, const Real cutoff_frequency, const Real sample_rate)
Digital elliptic/Cauer high-pass design returned as SOS.
static void bit_reverse(Array< Complex > &a) noexcept
Performs bit-reversal permutation in-place.
static Complex evaluate_sos_transfer_at(const Array< BiquadSection > §ions, const Real omega, const char *ctx)
static Array< BiquadSection > bessel_highpass(const size_t order, const Real cutoff_frequency, const Real sample_rate)
Digital Bessel high-pass design returned as SOS.
static Array< Array< Complex > > pstft(ThreadPool &pool, const Container &signal, const size_t frame_size, const STFTOptions &options, const size_t chunk_size=0)
static GainMarginInfo gain_margin(const SectionsContainer §ions, const size_t num_points=1024, const bool whole=false)
static Array< Real > apply_hann_window(const Array< Real > &signal)
Applies a Hann window of matching size to a real signal.
static Array< Array< Array< Complex > > > transpose_spectrogram_layout_impl(const Array< Array< Array< Complex > > > &input, const SpectrogramLayout source, const SpectrogramLayout target, const char *ctx)
Rationale: Internal implementation for transposing between multichannel spectrogram layouts (e....
static Array< Array< Complex > > pstft(ThreadPool &pool, const Array< Real > &signal, const Array< Real > &window, const STFTOptions &options, const size_t chunk_size=0)
Parallel STFT using explicit analysis options.
static void normalize_fir_at_omega(Array< Real > &coeffs, const Real omega, const char *ctx)
Normalizes FIR coefficients to have unit gain at frequency omega.
static Array< Complex > spectrum(const Array< Complex > &input)
DSP alias for the forward FFT.
static Array< Real > group_delay(const Array< BiquadSection > §ions, const size_t num_points=512, const bool whole=false)
static Real stability_margin(const IIRCoefficients &coeffs)
static Real interpolate_crossing(const Real x0, const Real y0, const Real x1, const Real y1, const Real target) noexcept
static Array< Real > pirfft(ThreadPool &pool, const Container &spectrum, const size_t signal_size=0, const size_t chunk_size=0)
Parallel version of irfft(const Container&, size_t).
static Array< Real > apply_hamming_window(const Container &signal)
static Array< Array< Complex > > stft(const Container &signal, const size_t frame_size, const STFTOptions &options)
static Array< Real > sosfilt(const Array< Real > &signal, const Array< BiquadSection > §ions)
One-shot causal filtering of a cascade of second-order sections.
static Array< Complex > transform(const Container &input)
Forward FFT for complex-valued containers.
static Array< Real > upfirdn(const Array< Real > &signal, const Array< Real > &coeffs, const size_t up=1, const size_t down=1)
Polyphase upsample-filter-downsample for real signals.
static void transform_axes_impl(Array< Complex > &data, const TensorLayout &layout, const Array< size_t > &axes, const bool invert, ThreadPool *pool=nullptr, const size_t chunk_size=0)
Rationale: Internal implementation of a multi-axis tensor transform.
static SimdBackend detected_simd_backend() noexcept
Returns the best SIMD backend supported by the current hardware among the kernels compiled for this p...
static Array< BiquadSection > butterworth_bandpass(const size_t order, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Butterworth band-pass design returned as SOS.
static Array< Complex > inverse_transform(const Container &input)
Forward IFFT for complex-valued containers.
static Array< Complex > ptransformed_axes(ThreadPool &pool, const Array< Complex > &input, const TensorLayout &layout, const Array< size_t > &axes, const bool invert=false, const size_t chunk_size=0)
Parallel functional tensor FFT/IFFT wrapper for flat buffers.
static Array< T > prefix_copy(const Array< T > &input, const size_t length)
Functional prefix extraction.
static Array< Array< Real > > batched_lfilter(const Array< Array< Real > > &signals, const Array< Real > &numerator, const Array< Real > &denominator, const Array< Array< Real > > &initial_states={})
One-shot batched causal IIR filtering across real channels.
and static Is_Real_Container< WindowContainer > Array< Complex > windowed_spectrum(const SignalContainer &signal, const WindowContainer &window)
static Real window_energy(const Container &window)
static Array< Array< Real > > multichannel_istft(const Array< Array< Array< Complex > > > &spectrograms, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options={}, const Array< size_t > &signal_lengths={}, const SpectrogramLayout layout=SpectrogramLayout::channel_frame_bin)
Multichannel ISTFT from either channel-major or frame-major spectrogram layouts.
static constexpr bool avx2_kernel_compiled() noexcept
Returns whether the AVX2 kernel was compiled for this precision.
static Array< Real > group_delay(const FrequencyResponse &response)
Estimates group delay from a sampled frequency response.
static FrequencyResponse freqz(const Array< BiquadSection > §ions, const size_t num_points=512, const bool whole=false)
static Real interpolate_value_at(const Real x0, const Real y0, const Real x1, const Real y1, const Real x) noexcept
static Complex group_center(const Array< Complex > &roots) noexcept
Geometric center of a root set.
static Array< Real > istft(const Array< Array< Complex > > &spectrogram, const Array< Real > &window, const ISTFTOptions &options)
Reconstructs a real signal using one shared analysis/synthesis window.
and Is_Real_Container< ContainerY > and static Is_Real_Container< WindowContainer > CrossSpectralDensity csd(const ContainerX &x, const ContainerY &y, const WindowContainer &window, const Real sample_rate, const WelchOptions &options={})
static Array< Complex > apply_blackman_window(const Array< Complex > &signal)
Applies a Blackman window of matching size to a complex signal.
static Array< Real > firwin_highpass(const size_t num_taps, const Real cutoff_frequency, const Real sample_rate, const Real attenuation_db)
FIR high-pass design using a Kaiser window.
static void validate_stable(const Array< BiquadSection > §ions)
static constexpr bool neon_kernel_compiled() noexcept
Returns whether the NEON kernel was compiled for this precision.
static FrequencyResponse freqz(const IIRCoefficients &coeffs, const size_t num_points=512, const bool whole=false)
static void validate_stable(const IIRCoefficients &coeffs, const Real min_margin)
static Array< BiquadSection > elliptic_bandpass(const size_t order, const Real ripple_db, const Real attenuation_db, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital elliptic/Cauer band-pass design returned as SOS.
static GainMarginInfo gain_margin(const BiquadSection §ion, const size_t num_points=1024, const bool whole=false)
and static Is_Real_Container< CoeffContainer > Array< Real > pfiltfilt(ThreadPool &pool, const SignalContainer &signal, const CoeffContainer &coeffs, const size_t block_size=0, const size_t chunk_size=0)
static bool avx2_runtime_available() noexcept
Returns whether AVX2 dispatch is supported at runtime.
static bool avx2_dispatch_available() noexcept
Returns whether the runtime CPU can execute the AVX2 double kernel when it has been compiled in.
static SimdBackend batched_plan_simd_backend() noexcept
Returns the SIMD backend selected for throughput-oriented batch plan paths under the current runtime ...
static Array< Real > filtfilt(const SignalContainer &signal, const BiquadSection §ion)
static Real window_coherent_gain(const Container &window)
static Array< Complex > multiply(const Array< Complex > &a, const Array< Complex > &b)
Multiplies two complex-valued sequences using convolution.
static std::pair< Array< Real >, Real > divide_polynomial_by_linear_root(const Array< Real > &coefficients, const Real root, const char *ctx)
and Is_Real_Container< NumContainer > and static Is_Real_Container< DenContainer > Array< Real > lfilter(const SignalContainer &signal, const NumContainer &numerator, const DenContainer &denominator, const Array< Real > &initial_state={})
static Array< Complex > prepare_stft_frame_input(const Array< Real > &frame, const Array< Real > &window, const size_t fft_size)
static Array< Array< Array< Complex > > > pbatched_stft(ThreadPool &pool, const Array< Array< Real > > &signals, const Array< Real > &window, const STFTOptions &options, const size_t chunk_size=0)
Parallel batched STFT across signals.
static Array< Array< Complex > > stft(const Container &signal, const size_t frame_size, const size_t hop_size, const bool pad_end=true)
static Array< Real > filtfilt(const Array< Real > &signal, const Array< Real > &coeffs, const size_t block_size=0)
Zero-phase FIR filtering via forward-backward convolution.
static Array< T > to_array(const Container &input)
static Array< Complex > compact_real_spectrum(const Array< Complex > &full_spectrum)
static Array< size_t > axis_base_offsets(const Array< size_t > &shape, const Array< size_t > &strides, const size_t axis)
Rationale: Generates the base memory offsets for all 1D slices along a specific axis in a multidimens...
static Real kaiser_beta(const Real attenuation_db)
Returns the Kaiser beta that corresponds to an attenuation goal.
static Array< PoleZeroPair > pair_poles_and_zeros(const BiquadSection §ion)
static Array< Complex > pspectrum(ThreadPool &pool, const Array< Real > &input, const size_t chunk_size=0)
Parallel version of spectrum(const Array<Real>&).
static Array< T > slice_copy(const Array< T > &input, const size_t offset, const size_t length)
Functional slice extraction.
static Array< PoleZeroPair > pair_poles_and_zeros(const Array< Complex > &zeros, const Array< Complex > &poles)
Greedily pairs zeros and poles by nearest distance.
static void transform_axes(Array< Complex > &data, const TensorLayout &layout, const Array< size_t > &axes, const bool invert)
In-place FFT/IFFT along multiple tensor axes of a flat buffer.
static Array< size_t > tensor3_shape(const Array< Array< Array< Complex > > > &input, const char *ctx)
Rationale: Validates that a nested Array represents a 3D tensor and returns its {d0,...
and static Is_Real_Container< CoeffContainer > Array< Real > filtfilt(const SignalContainer &signal, const CoeffContainer &coeffs, const size_t block_size=0)
and static Is_Biquad_Container< SectionsContainer > Array< Array< Real > > batched_sosfilt(const SignalsContainer &signals, const SectionsContainer §ions)
static Array< BiquadSection > transfer_function_to_sections(const Array< Real > &numerator, const Array< Real > &denominator, const char *ctx)
overload of transfer_function_to_sections using raw coefficients.
static Array< Array< Real > > batched_sosfilt(const Array< Array< Real > > &signals, const Array< BiquadSection > §ions)
One-shot batched causal SOS filtering across real channels.
static const char * simd_backend_name() noexcept
Returns the active default SIMD backend name for this precision.
static Array< Array< Real > > pirfft_batch(ThreadPool &pool, const Array< Array< Complex > > &spectra, const size_t signal_size, const size_t chunk_size=0)
Parallel compact real inverse FFT for equal-length batches.
static Array< Real > magnitude_spectrum(const Array< Complex > &input)
Returns |X[k]| for each frequency bin in an FFT output.
static Array< Complex > initialize_root_guesses(const Array< Real > &coefficients)
static Array< Real > phase_delay(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points=512, const bool whole=false)
static FrequencyResponse freqz(const SectionsContainer §ions, const size_t num_points=512, const bool whole=false)
static Array< Complex > polynomial_from_roots_complex(const Array< Complex > &roots)
Rationale: Polynomial expansion (z-r1)(z-r2)...
static Array< Real > multiply(const Array< Real > &a, const Array< Real > &b)
Multiplies two real-valued sequences using convolution.
and static Is_Complex_Container< Container2 > Array< Complex > multiply(const Container1 &a, const Container2 &b)
Multiplication for complex-valued containers.
static void validate_stable(const IIRCoefficients &coeffs)
and static Is_Real_Container< DenContainer > void validate_no_near_pole_zero_cancellation(const NumContainer &numerator, const DenContainer &denominator, const Real tolerance)
static AnalogPrototype chebyshev2_prototype(const size_t order, const Real attenuation_db, const char *ctx)
static Array< Complex > transform(const Array< Real > &input)
Computes the FFT of a real-valued input sequence.
and Is_Real_Container< NumContainer > and static Is_Real_Container< DenContainer > Array< Array< Real > > batched_lfilter(const SignalsContainer &signals, const NumContainer &numerator, const DenContainer &denominator, const Array< Array< Real > > &initial_states={})
static Array< Complex > ptransform_padded(ThreadPool &pool, const Array< Complex > &input, const size_t chunk_size=0)
static Array< RootGroup > root_groups_impl(const Array< Complex > &raw_roots, const char *ctx)
Rationale: Partitions a set of roots into real sections and conjugate pairs to facilitate SOS decompo...
static Array< Array< Complex > > project_to_plan_batch_spectra(const Plan &plan, const Array< Array< Real > > &input, ThreadPool *pool=nullptr, const size_t chunk_size=0)
static AnalogPrototype bessel_prototype(const size_t order, const char *ctx)
implementation of the Bessel filter analog prototype.
static size_t next_power_of_two(const size_t n)
Calculates the smallest power of two greater than or equal to n.
static Array< BiquadSection > elliptic_lowpass(const size_t order, const Real ripple_db, const Real attenuation_db, const Real cutoff_frequency, const Real sample_rate)
Digital elliptic/Cauer low-pass design returned as SOS.
static PhaseMarginInfo phase_margin(const Array< BiquadSection > §ions, const size_t num_points=1024, const bool whole=false)
static Array< Real > pistft(ThreadPool &pool, const Array< Array< Complex > > &spectrogram, const Array< Real > &window, const ISTFTOptions &options, const size_t chunk_size=0)
Parallel ISTFT using a shared analysis/synthesis window.
static Array< Array< Complex > > stft_impl(const Array< Real > &signal, const Array< Real > &window, const STFTOptions &options, ThreadPool *pool=nullptr, const size_t chunk_size=0)
static Array< Real > real_polynomial_from_roots(const Array< Complex > &roots, const char *ctx)
Rationale: Constructs a real-coefficient polynomial from a set of complex roots, verifying that roots...
static const char * batched_plan_simd_backend_name() noexcept
Returns the active batch-plan SIMD backend name.
static Array< Complex > ptransform_padded(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of transform_padded(const Container&).
static bool has_near_pole_zero_cancellation(const SectionsContainer §ions, const Real tolerance)
static Array< Real > kaiser_window(const size_t n, const Real beta)
Returns a Kaiser window of length n.
static Array< Real > group_delay(const IIRCoefficients &coeffs, const size_t num_points=512, const bool whole=false)
static Array< T > polynomial_multiply(const Array< T > &lhs, const Array< T > &rhs)
Rationale: Standard polynomial multiplication (O(N*M)).
static Array< Real > power_spectrum(const Array< Complex > &input)
Returns |X[k]|^2 for each frequency bin in an FFT output.
static Array< Array< Complex > > inverse_transform_batch(const Array< Array< Complex > > &input)
Functional batch IFFT wrapper.
static Array< size_t > factor_small_radices(size_t n)
Rationale: Factors a number into small primes (2, 3, 4, 5) to determine if a composite FFT kernel is ...
static void transform_axis_impl(Array< Complex > &data, const TensorLayout &layout, const size_t axis, const bool invert, ThreadPool *pool=nullptr, const size_t chunk_size=0)
Rationale: Internal implementation of a 1D FFT along a single tensor axis.
static Array< Complex > poles(const BiquadSection §ion)
static Array< Real > resample_poly(const Array< Real > &signal, const size_t up, const size_t down, const ResamplePolyOptions &options={})
Polyphase resampling with an internally designed Kaiser FIR.
static Array< Complex > poles(const Container &denominator)
static PolynomialEvaluation evaluate_polynomial_and_derivative(const Array< Real > &coefficients, const Complex &x, const char *ctx)
static Array< Real > iir_filtfilt_impl(const Array< Real > &signal, const Array< Real > &numerator, const Array< Real > &denominator, const char *ctx)
static Array< Complex > pspectrum(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of spectrum(const Container&).
static Array< PoleZeroPair > pair_poles_and_zeros(const IIRCoefficients &coeffs)
and static Is_Real_Container< DenContainer > Array< Real > group_delay(const NumContainer &numerator, const DenContainer &denominator, const size_t num_points=512, const bool whole=false)
static Real transform_stages(const size_t n) noexcept
Returns log2(N) stages, used for numerical error scaling.
static Array< PoleZeroPair > pole_zero_pairs_impl(const Array< Complex > &zeros, const Array< Complex > &poles)
Rationale: Matches zeros and poles into pairs by minimizing Euclidean distance, aiding in SOS decompo...
static Array< Real > firwin_lowpass(const size_t num_taps, const Real cutoff_frequency, const Real sample_rate, const Array< Real > &window)
FIR low-pass design via the window method.
static Real window_coherent_gain(const Array< Real > &window)
Returns the average window gain.
static void drop_prefix(Array< T > &input, const size_t count)
and static Is_Real_Container< DenContainer > Array< PoleZeroPair > pair_poles_and_zeros(const NumContainer &numerator, const DenContainer &denominator)
static Array< Real > istft(const Array< Array< Complex > > &spectrogram, const size_t frame_size, const size_t hop_size, const size_t signal_length=0)
Reconstructs a real signal using a Hann window pair.
static Array< Real > firwin_bandpass(const size_t num_taps, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate, const Array< Real > &window)
FIR band-pass design via the window method.
static size_t count_non_empty_real_batch(const Array< Array< Real > > &batch) noexcept
static Real solve_elliptic_selectivity_modulus(const Real k1, const size_t order, const char *ctx)
static bool should_parallelize_batch_work(ThreadPool *pool, const size_t batch_size, const size_t transform_size, const size_t min_work=8192) noexcept
static Real carlson_rf_impl(Real x, Real y, Real z)
static bool satisfies_nola(const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size)
Returns true when the window pair satisfies NOLA.
static std::pair< Array< Real >, Array< Complex > > extract_repeated_unit_roots(const Array< Real > &coefficients, const char *ctx)
static const char * simd_preference_name() noexcept
Returns the requested SIMD policy name.
static PowerSpectralDensity welch(const Array< Real > &signal, const Array< Real > &window, const Real sample_rate, const WelchOptions &options={})
Welch one-sided PSD estimate using a custom window.
static Array< Real > iir_steady_state(const Array< Real > &numerator, const Array< Real > &denominator, const char *ctx)
static Array< BiquadSection > chebyshev2_bandpass(const size_t order, const Real attenuation_db, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Chebyshev-II band-pass design returned as SOS.
static Array< Complex > apply_hamming_window(const Container &signal)
and static Is_Real_Container< WindowContainer > Array< Real > apply_window(const SignalContainer &signal, const WindowContainer &window)
static Real window_energy(const Array< Real > &window)
Returns the sum of squared window samples.
and static Is_Real_Container< Container2 > Array< Real > partitioned_convolution(const Container1 &signal, const Container2 &kernel, const size_t partition_size=0)
Partitioned convolution for real-valued containers.
static GainMarginInfo gain_margin(const Array< BiquadSection > §ions, const size_t num_points=1024, const bool whole=false)
static Complex elliptic_cd_minus_imaginary(const Real u, const Real v, const Real modulus, const char *ctx)
static Real scaled_tolerance(const Real reference, const Real multiplier=Real(256)) noexcept
static size_t tensor_element_count(const Array< size_t > &shape, const char *ctx)
static Array< Complex > spectrum(const Array< Real > &input)
DSP alias for the real forward FFT.
static PhaseMarginInfo phase_margin(const IIRCoefficients &coeffs, const size_t num_points=1024, const bool whole=false)
and Is_Real_Container< DesiredContainer > and static Is_Real_Container< WeightContainer > Array< Real > firls(const size_t num_taps, const BandContainer &bands, const DesiredContainer &desired, const Real sample_rate, const WeightContainer &weights)
static Real minimum_pole_zero_distance(const IIRCoefficients &coeffs)
static GainMarginInfo gain_margin_impl(const FrequencyResponse &response)
implementation helper for Gain Margin calculation.
static Array< Complex > flatten_tensor3_row_major(const Array< Array< Array< Complex > > > &input, const char *ctx)
Rationale: Flattens a 3D tensor into a 1D row-major array.
static bool is_one_sided_interior_bin(const size_t bin, const size_t fft_size) noexcept
Identifies non-redundant spectrum bins (excluding DC and Nyquist).
and static Is_Complex_Container< Container2 > Array< Complex > pmultiply(ThreadPool &pool, const Container1 &a, const Container2 &b, const size_t chunk_size=0)
Parallel version of multiply(const Container1&, const Container2&).
static Array< T > reverse_copy(const Array< T > &input)
Functional reverse.
static Array< Complex > transform(const Container &input)
Forward FFT for real-valued containers.
static void enforce_real_polynomial_symmetry(Array< Complex > &roots, const Real tol) noexcept
static Array< Real > group_delay_impl(const FrequencyResponse &response)
implementation of numeric group delay calculation.
static Real minimum_pole_zero_distance(const SectionsContainer §ions)
static Array< Real > blackman_window(const size_t n)
Returns a Blackman window of length n.
static size_t default_filtfilt_pad_length(const size_t signal_size, const size_t coeff_size) noexcept
Rationale: Rule-of-thumb for filtfilt padding to allow transients to decay.
and static Is_Real_Container< DenContainer > bool has_near_pole_zero_cancellation(const NumContainer &numerator, const DenContainer &denominator, const Real tolerance)
static Array< Complex > inverse_transform(const Array< Complex > &input)
Computes the Inverse Fast Fourier Transform (IFFT).
static void polish_roots_with_newton(const Array< Real > &coefficients, Array< Complex > &roots, const Real tol, const size_t iterations) noexcept
static Array< Complex > spectrum(const Container &input)
DSP alias for real-valued container forward FFT.
static AnalogPrototype elliptic_prototype(const size_t order, const Real ripple_db, const Real attenuation_db, const char *ctx)
static Real sum_squares(const Array< Real > &input) noexcept
L2 norm squared.
static void ptransform_batch(ThreadPool &pool, Array< Array< Complex > > &batch, const bool invert, const size_t chunk_size=0)
Parallel in-place batch transform for equal-length inputs.
static Array< Real > zero_padded_copy(const Array< Real > &input, const size_t n)
Returns a copy of input zero-padded to size n.
static void validate_no_near_pole_zero_cancellation(const Array< Complex > &zeros, const Array< Complex > &poles, const Real tolerance)
static PhaseMarginInfo phase_margin(const FrequencyResponse &response)
Estimates phase margin around the unity-gain crossover.
static Array< Complex > transform_real_optimized(const Array< Real > &input, ThreadPool *pool=nullptr, const size_t chunk_size=0)
Rationale: Optimized FFT for real signals of size N (power-of-two).
and static Is_Real_Container< Container2 > Array< Real > overlap_add_convolution(const Container1 &signal, const Container2 &kernel, const size_t block_size=0)
Overlap-add convolution for real-valued containers.
static Real minimum_pole_zero_distance(const Array< Real > &numerator, const Array< Real > &denominator)
static Array< BiquadSection > chebyshev1_bandpass(const size_t order, const Real ripple_db, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Chebyshev-I band-pass design returned as SOS.
static Real series_zero_tolerance(const size_t coeff_count, const Real multiplier=Real(256)) noexcept
static Array< Complex > transformed(const Array< Complex > &input, const bool invert=false)
Computes the FFT or IFFT and returns a new array.
static constexpr bool Is_Real_Container
static bool overlap_profile_has_nola(const Array< Real > &profile) noexcept
Rationale: Non-zero Overlap-Add (NOLA) ensures the signal can be reconstructed (it's never multiplied...
static Real integrate_linear_cos_basis(const Real omega_lo, const Real omega_hi, const Real desired_lo, const Real desired_hi, const size_t harmonic) noexcept
implementation helper for firls linear band integration.
static bool has_near_pole_zero_cancellation(const IIRCoefficients &coeffs, const Real tolerance)
static IIRCoefficients normalize_iir_coefficients(const Array< Real > &numerator, const Array< Real > &denominator, const char *ctx)
static Array< Array< Complex > > transformed_batch(const Array< Array< Complex > > &input, const bool invert=false)
Functional batch FFT/IFFT wrapper.
static Array< Real > istft(const Array< Array< Complex > > &spectrogram, const size_t frame_size, const ISTFTOptions &options)
Reconstructs a Hann-window STFT with explicit options.
static bool try_laguerre_roots(const Array< Real > &coefficients, const Real tol, Array< Complex > &roots) noexcept
static Array< BiquadSection > design_prototype_sections(const AnalogPrototype &prototype, const size_t order, const Real cutoff_frequency, const Real sample_rate, const bool highpass, const char *ctx)
static FrequencyResponse freqz(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points=512, const bool whole=false)
Samples the discrete-time transfer response on the unit circle.
static Real max_abs_value(const Array< Real > &input) noexcept
L-infinity norm.
static Array< Real > bilinear_substitute_polynomial(const Array< Real > &analog, const size_t order, const Real sample_rate, const char *ctx)
Rationale: Performs the bilinear substitution mapping from the S-plane to the Z-domain: H(z) = H(s)|s...
static Array< Complex > zero_padded_copy(const Array< Complex > &input, const size_t n)
Returns a copy of input zero-padded to size n.
static bool has_near_pole_zero_cancellation(const BiquadSection §ion, const Real tolerance)
static Real integrate_cos_basis(const Real omega_lo, const Real omega_hi, const size_t harmonic) noexcept
Rationale: Evaluates integral of cos(k*w) from omega_lo to omega_hi.
static void validate_no_near_pole_zero_cancellation(const Array< Real > &numerator, const Array< Real > &denominator, const Real tolerance)
static Array< BiquadSection > design_low_high_sections(const AnalogPrototype &prototype, const Real cutoff_frequency, const Real sample_rate, const bool highpass, const char *ctx)
internal helper for designing standard lowpass/highpass SOS filters.
static Array< BiquadSection > chebyshev1_highpass(const size_t order, const Real ripple_db, const Real cutoff_frequency, const Real sample_rate)
Digital Chebyshev-I high-pass design returned as SOS.
and static Is_Real_Container< DesiredContainer > Array< Real > firls(const size_t num_taps, const BandContainer &bands, const DesiredContainer &desired, const Real sample_rate)
static CrossSpectralDensity csd(const Array< Real > &x, const Array< Real > &y, const size_t frame_size, const Real sample_rate, const WelchOptions &options={})
One-sided cross-spectral density estimate using a Hann window.
static Array< Real > firwin_lowpass_impl(const size_t num_taps, const Real cutoff_frequency, const Real sample_rate, const Array< Real > &window, const char *ctx)
implementation of the window-method FIR design.
and static Is_Real_Container< WindowContainer > Array< Complex > apply_window(const SignalContainer &signal, const WindowContainer &window)
static void apply_one_sided_density_scaling(Density &value, const size_t bin, const size_t fft_size) noexcept
Rationale: Multiplies spectral densities by 2 for interior bins to account for energy in the omitted ...
static Array< Real > pmultiply(ThreadPool &pool, const Array< Real > &a, const Array< Real > &b, const size_t chunk_size=0)
Parallel version of multiply(const Array<Real>&, const Array<Real>&).
static Array< Complex > ptransform_padded(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel zero-pad and forward-FFT for a generic complex iterable.
static Array< Array< Array< Complex > > > multichannel_stft(const Array< Array< Real > > &signals, const Array< Real > &window, const STFTOptions &options={}, const SpectrogramLayout layout=SpectrogramLayout::channel_frame_bin)
Multichannel STFT with explicit channel-major or frame-major output layout.
static Real minimum_pole_zero_distance(const BiquadSection §ion)
static bool satisfies_cola(const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size)
Returns true when the window pair satisfies COLA.
static void validate_no_near_pole_zero_cancellation(const SectionsContainer §ions, const Real tolerance)
and static Is_Real_Container< DenContainer > FrequencyResponse freqz(const NumContainer &numerator, const DenContainer &denominator, const size_t num_points=512, const bool whole=false)
static bool neon_runtime_available() noexcept
Returns whether NEON dispatch is supported at runtime.
and static Is_Real_Container< WindowContainer > Array< Complex > windowed_spectrum(const SignalContainer &signal, const WindowContainer &window)
static Array< Real > substitute_rational_polynomial(const Array< Real > &poly, const Array< Real > &numerator, const Array< Real > &denominator, const char *ctx)
Rationale: Evaluates P(N(z)/D(z)) by scaling by the common denominator D(z)^degree and evaluating the...
static TransferTerms evaluate_transfer_terms_at(const Array< Real > &numerator, const Array< Real > &denominator, const Real omega, const char *ctx)
implementation helper for evaluating H(z) and its derivatives on the unit circle.
static AnalogPrototype chebyshev1_prototype(const size_t order, const Real ripple_db, const char *ctx)
static Array< Complex > ptransform(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of transform(const Container&).
static Array< Real > iir_filter_impl(const Array< Real > &signal, const Array< Real > &numerator, const Array< Real > &denominator, const Array< Real > &initial_state, const char *ctx, Array< Real > *final_state=nullptr)
static void validate_stable(const BiquadSection §ion)
static Array< Complex > windowed_spectrum(const Array< Real > &signal, const Array< Real > &window)
Returns the FFT of a real signal after applying a window.
static Array< size_t > choose_remez_extrema(const Array< Real > &weighted_error, const size_t required_count, const char *ctx)
static Array< Complex > transformed_axes(const Array< Complex > &input, const TensorLayout &layout, const Array< size_t > &axes, const bool invert=false)
Functional tensor FFT/IFFT wrapper for flat buffers.
static Array< Complex > ptransform_padded(ThreadPool &pool, const Array< Real > &input, const size_t chunk_size=0)
Parallel version of transform_padded(const Array<Real>&).
and static Is_Real_Container< DenContainer > PhaseMarginInfo phase_margin(const NumContainer &numerator, const DenContainer &denominator, const size_t num_points=1024, const bool whole=false)
static GainMarginInfo gain_margin(const IIRCoefficients &coeffs, const size_t num_points=1024, const bool whole=false)
static void validate_istft_configuration(const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t fft_size, const ISTFTOptions &options, const char *ctx)
Rationale: Validates and normalizes ISTFT parameters, checking window constraints and FFT size.
static Array< Real > firwin_highpass(const size_t num_taps, const Real cutoff_frequency, const Real sample_rate, const Array< Real > &window)
FIR high-pass design via spectral inversion of a low-pass design.
static GainMarginInfo gain_margin(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points=1024, const bool whole=false)
and static Is_Real_Container< DenContainer > IIRCoefficients bilinear_transform(const NumContainer &analog_numerator, const DenContainer &analog_denominator, const Real sample_rate)
static Array< Real > group_delay(const Container &numerator, const size_t num_points=512, const bool whole=false)
static Array< Complex > enforce_conjugate_symmetry(const Array< Complex > &roots)
Enforce conjugate symmetry on roots of a real-coefficient polynomial.
static Real real_projection_tolerance(const Complex &value, const size_t n) noexcept
Rationale: Estimates the maximum expected numerical noise for a value after an N-point transform,...
static Array< Complex > prfft(ThreadPool &pool, const Array< Real > &input, const size_t chunk_size=0)
Parallel version of rfft(const Array<Real>&).
static Array< Array< Complex > > reshape_matrix_row_major(const Array< Complex > &input, const size_t rows, const size_t cols, const char *ctx)
Rationale: Reshapes a 1D row-major array back into a 2D matrix.
static void ptransform_axis(ThreadPool &pool, Array< Complex > &data, const TensorLayout &layout, const size_t axis, const bool invert, const size_t chunk_size=0)
Parallel in-place 1-D FFT/IFFT along one tensor axis.
static Array< Complex > poles(const SectionsContainer §ions)
and Is_Real_Container< NumContainer > and static Is_Real_Container< DenContainer > Array< Real > filtfilt(const SignalContainer &signal, const NumContainer &numerator, const DenContainer &denominator)
static void transform_impl(Array< Complex > &a, const bool invert, ThreadPool *pool=nullptr, const size_t chunk_size=0)
implementation of the power-of-two iterative FFT using mixed radix-2/4.
static Array< BiquadSection > chebyshev2_bandstop(const size_t order, const Real attenuation_db, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Chebyshev-II band-stop design returned as SOS.
static bool is_stable(const BiquadSection §ion)
static Array< Real > pinverse_transform_real(ThreadPool &pool, const Array< Complex > &input, const size_t chunk_size=0)
Parallel version of inverse_transform_real(const Array<Complex>&).
static Array< Complex > ptransform(ThreadPool &pool, const Array< Real > &input, const size_t chunk_size=0)
Parallel real-input FFT.
static Real sum_values(const Array< Real > &input) noexcept
Sum reduction.
static FrequencyResponse freqz(const Array< Real > &numerator, const size_t num_points=512, const bool whole=false)
FIR frequency response.
static Array< Real > cosine_sum_window(const size_t n, const Real a0, const Real a1=Real(0), const Real a2=Real(0))
Internal generator for generalized cosine windows (Hann, Hamming, Blackman).
static void validate_stable(const Array< BiquadSection > §ions, const Real min_margin)
static void transform_batch(Array< Array< Complex > > &batch, const bool invert)
In-place batch transform for equal-length complex inputs.
static void transform_axis(Array< Complex > &data, const TensorLayout &layout, const size_t axis, const bool invert)
In-place 1-D FFT/IFFT along one tensor axis of a flat buffer.
static Array< Array< Array< Complex > > > pmultichannel_stft(ThreadPool &pool, const Array< Array< Real > > &signals, const Array< Real > &window, const STFTOptions &options={}, const SpectrogramLayout layout=SpectrogramLayout::channel_frame_bin, const size_t chunk_size=0)
Parallel multichannel STFT with selectable output layout.
static bool satisfies_cola(const Array< Real > &window, const size_t hop_size)
Returns true when one window satisfies COLA by itself.
static GainMarginInfo gain_margin_refined_impl(const FrequencyResponse &response, const Evaluator &evaluator)
implementation of refined Gain Margin calculation using analytic evaluation.
static bool has_near_pole_zero_cancellation(const Array< BiquadSection > §ions, const Real tolerance)
static void validate_stable(const SectionsContainer §ions, const Real min_margin)
static void validate_stable(const Array< Real > &denominator)
static Array< Complex > ptransform(ThreadPool &pool, const Container &input, const size_t chunk_size=0)
Parallel version of transform(const Container&).
static Array< Real > apply_window(const Array< Real > &signal, const Array< Real > &window)
Applies a real window sample-by-sample to a real signal.
static Real complete_elliptic_first_kind(const Real modulus, const char *ctx)
Rationale: Complete elliptic integral K(k) using the modulus convention required by elliptic filter d...
static PowerSpectralDensity welch(const Array< Real > &signal, const size_t frame_size, const Real sample_rate, const WelchOptions &options={})
Welch one-sided PSD estimate using a Hann window.
static Real integer_power(const Real base, const size_t exponent) noexcept
Fast integer power utility.
static Array< Real > group_delay(const Array< Real > &numerator, const Array< Real > &denominator, const size_t num_points=512, const bool whole=false)
static Array< BiquadSection > chebyshev1_bandstop(const size_t order, const Real ripple_db, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Chebyshev-I band-stop design returned as SOS.
static Array< Array< Real > > batched_istft(const Array< Array< Array< Complex > > > &spectrograms, const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const ISTFTOptions &options, const Array< size_t > &signal_lengths={})
Batched ISTFT with optional per-signal output lengths.
static size_t tensor_max_offset(const Array< size_t > &shape, const Array< size_t > &strides, const char *ctx)
static Array< Real > poverlap_add_convolution(ThreadPool &pool, const Array< Real > &signal, const Array< Real > &kernel, const size_t block_size=0, const size_t chunk_size=0)
Parallel convenience wrapper for overlap-add convolution.
and static Is_Real_Container< DenContainer > Array< Real > phase_delay(const NumContainer &numerator, const DenContainer &denominator, const size_t num_points=512, const bool whole=false)
static PhaseMarginInfo phase_margin(const SectionsContainer §ions, const size_t num_points=1024, const bool whole=false)
static Array< Real > remez_impl(const size_t num_taps, const Array< Real > &bands, const Array< Real > &desired, const Real sample_rate, const Array< Real > &weights, const size_t grid_density, const size_t max_iterations, const char *ctx)
static Array< Complex > ptransformed(ThreadPool &pool, const Container &input, const bool invert=false, const size_t chunk_size=0)
Parallel FFT/IFFT for a generic complex iterable.
static bool is_stable(const IIRCoefficients &coeffs)
static Array< BiquadSection > bessel_bandpass(const size_t order, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Bessel band-pass design returned as SOS.
static void validate_stable(const Container &denominator, const Real min_margin)
static Array< Real > apply_hann_window(const Container &signal)
static IIRCoefficients bilinear_transform_impl(const Array< Real > &analog_numerator, const Array< Real > &analog_denominator, const Real sample_rate, const char *ctx)
implementation helper for the bilinear transform.
static Array< BiquadSection > design_bandstop_sections_without_numerator_roots(const AnalogPrototype &prototype, const size_t order, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate, const char *ctx)
Specialization for band-stop designs to handle zeros explicitly.
and static Is_Real_Container< WindowContainer > Array< Array< Complex > > pstft(ThreadPool &pool, const SignalContainer &signal, const WindowContainer &window, const STFTOptions &options, const size_t chunk_size=0)
static Array< size_t > row_major_strides(const Array< size_t > &shape, const char *ctx)
SpectrogramLayout
Logical layout for multichannel spectrograms.
static Array< Real > phase_delay(const Container &numerator, const size_t num_points=512, const bool whole=false)
static Array< Complex > transformed(const Container &input, const bool invert=false)
FFT/IFFT for a generic complex iterable.
static Array< Complex > transform_padded(const Array< Real > &input)
Computes the FFT after zero-padding the input to the next power of two.
static void transform(Array< Complex > &a, const bool invert)
Computes the Fast Fourier Transform (FFT) in-place.
static Real window_enbw(const Array< Real > &window)
Returns the equivalent noise bandwidth of a window in bins.
static Array< Array< Complex > > ptransformed_batch(ThreadPool &pool, const Array< Array< Complex > > &input, const bool invert=false, const size_t chunk_size=0)
Parallel functional batch FFT/IFFT wrapper.
static Array< Real > phase_delay(const IIRCoefficients &coeffs, const size_t num_points=512, const bool whole=false)
static Array< Complex > project_to_plan_spectrum(const Plan &plan, const Array< Real > &input, ThreadPool *pool=nullptr, const size_t chunk_size=0)
static Real prewarp_frequency(const Real cutoff_frequency, const Real sample_rate, const char *ctx)
Rationale: Prewarps an analog cutoff frequency to compensate for the non-linear frequency mapping of ...
static Array< Real > apply_hamming_window(const Array< Real > &signal)
Applies a Hamming window of matching size to a real signal.
static JacobiValues jacobi_sn_cn_dn(const Real argument, const Real modulus, const char *ctx)
Rationale: Simultanous calculation of Jacobi sn, cn, dn functions using the descending Landen transfo...
static Array< size_t > matrix_shape(const Array< Array< Complex > > &input, const char *ctx)
Rationale: Validates that an Array of Arrays represents a rectangular matrix and returns its {rows,...
static Array< Complex > flatten_matrix_row_major(const Array< Array< Complex > > &input, const char *ctx)
Rationale: Flattens a 2D matrix into a 1D row-major array.
static Array< Real > partitioned_convolution(const Array< Real > &signal, const Array< Real > &kernel, const size_t partition_size=0)
Convenience wrapper for low-latency partitioned convolution.
static Array< Array< Array< Complex > > > transpose_spectrogram_layout(const Array< Array< Array< Complex > > > &input, const SpectrogramLayout source, const SpectrogramLayout target)
Converts multichannel spectrograms between channel-major and frame-major layouts.
static Array< Real > filtfilt(const Array< Real > &signal, const Array< Real > &numerator, const Array< Real > &denominator)
Zero-phase IIR filtering using transfer-function coefficients.
static Array< Complex > expand_real_spectrum(const Array< Complex > &spectrum, const size_t signal_size, const char *ctx)
static void transform_any_size_impl(Array< Complex > &a, const bool invert, ThreadPool *pool=nullptr, const size_t chunk_size=0)
static Array< Array< Complex > > transformed2d(const Array< Array< Complex > > &input, const bool invert=false)
Functional 2-D FFT/IFFT wrapper for rectangular complex matrices.
static Array< Real > pistft(ThreadPool &pool, const Array< Array< Complex > > &spectrogram, const Array< Real > &window, const size_t hop_size, const size_t signal_length=0, const size_t chunk_size=0)
Parallel STFT inversion using a shared analysis/synthesis window.
static Array< Real > inverse_transform_real(const Array< Complex > &input)
Computes the IFFT and projects the result back to real values.
static Array< Complex > pmultiply(ThreadPool &pool, const Array< Complex > &a, const Array< Complex > &b, const size_t chunk_size=0)
Parallel version of multiply(const Array<Complex>&, const Array<Complex>&).
static constexpr bool Is_Complex_Container
static Array< Real > scaled_copy(const Array< Real > &input, const Real factor)
Scalar scaling.
static Array< Complex > gather_axis_slice(const Array< Complex > &data, const size_t base_offset, const size_t axis_length, const size_t axis_stride)
Rationale: Extracts a non-contiguous slice of data along a tensor axis into a contiguous array for FF...
static Array< Real > istft(const Array< Array< Complex > > &spectrogram, const Array< Real > &window, const size_t hop_size, const size_t signal_length=0)
Reconstructs a real signal using the same window for analysis and synthesis.
static Array< Array< Array< Complex > > > transformed3d(const Array< Array< Array< Complex > > > &input, const bool invert=false)
Functional 3-D FFT/IFFT wrapper for rectangular complex tensors.
static size_t recommended_cache_tile_size(const size_t transform_size, const size_t batch_size, ThreadPool *pool) noexcept
static Array< Complex > pinverse_transform(ThreadPool &pool, const Array< Complex > &input, const size_t chunk_size=0)
Parallel version of inverse_transform(const Array<Complex>&).
static IIRCoefficients bilinear_transform(const Array< Real > &analog_numerator, const Array< Real > &analog_denominator, const Real sample_rate)
Bilinear transform of an analog transfer function.
static size_t resolve_welch_hop_size(const WelchOptions &options, const size_t frame_size, const char *ctx)
Default hop size for Welch analysis (50% overlap).
and static Is_Real_Container< CoeffContainer > Array< Real > upfirdn(const SignalContainer &signal, const CoeffContainer &coeffs, const size_t up=1, const size_t down=1)
static SimdPreference simd_preference() noexcept
Returns the runtime SIMD preference requested via environment.
static PolynomialEvaluation evaluate_polynomial_prefix(const Array< Real > &coefficients, const size_t n, const Complex &x) noexcept
static Array< Complex > apply_hann_window(const Container &signal)
static void trim_to_size(Array< Complex > &input, const size_t n)
Trims input to size n.
static void validate_stable(const BiquadSection §ion, const Real min_margin)
static Real polynomial_root_lower_bound(const Array< Real > &monic) noexcept
and static Is_Biquad_Container< SectionsContainer > Array< Real > filtfilt(const SignalContainer &signal, const SectionsContainer §ions)
static Array< Array< Array< Complex > > > reshape_tensor3_row_major(const Array< Complex > &input, const size_t dim0, const size_t dim1, const size_t dim2, const char *ctx)
Rationale: Reshapes a 1D row-major array back into a 3D tensor.
static Real stability_margin(const BiquadSection §ion)
static Array< BiquadSection > butterworth_bandstop(const size_t order, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate)
Digital Butterworth band-stop design returned as SOS.
static PhaseMarginInfo phase_margin_refined_impl(const FrequencyResponse &response, const Evaluator &evaluator)
implementation of refined Phase Margin calculation using analytic evaluation.
static Array< Real > firls(const size_t num_taps, const Array< Real > &bands, const Array< Real > &desired, const Real sample_rate, const Array< Real > &weights={})
FIR design by weighted least squares over piecewise-linear bands.
static Array< Array< Complex > > inverse_transform2d(const Array< Array< Complex > > &input)
Functional inverse 2-D FFT wrapper.
static Array< Array< Real > > pbatched_istft(ThreadPool &pool, const Array< Array< Array< Complex > > > &spectrograms, const Array< Real > &window, const ISTFTOptions &options, const Array< size_t > &signal_lengths={}, const size_t chunk_size=0)
Parallel batched ISTFT using a shared analysis/synthesis window.
static Array< Array< Real > > irfft_batch(const Array< Array< Complex > > &spectra, const size_t signal_size)
Functional compact real inverse FFT for equal-length batches.
static Array< size_t > frame_offsets_impl(const size_t signal_size, const size_t frame_size, const size_t hop_size, const bool pad_end, const char *ctx)
Computes framing offsets.
and static Is_Biquad_Container< SectionsContainer > Array< Real > sosfilt(const SignalContainer &signal, const SectionsContainer §ions)
static Array< Real > zero_pad_edges(const Array< Real > &signal, const size_t left_pad, const size_t right_pad)
functional zero-padding at both ends.
static Real polynomial_root_upper_bound(const Array< Real > &monic) noexcept
static Array< PoleZeroPair > pair_poles_and_zeros(const SectionsContainer §ions)
static Array< Array< Complex > > pinverse_transform_batch(ThreadPool &pool, const Array< Array< Complex > > &input, const size_t chunk_size=0)
Parallel functional batch IFFT wrapper.
static Real integrate_cos_product(const Real omega_lo, const Real omega_hi, const size_t lhs_harmonic, const size_t rhs_harmonic) noexcept
Rationale: Evaluates integral of cos(m*w)*cos(n*w).
static Array< Real > reverse_bessel_polynomial(const size_t order, const char *ctx)
Rationale: Generates coefficients for the Reverse Bessel Polynomial used in Bessel filter prototypes.
static Array< Real > phase_spectrum(const Array< Complex > &input)
Returns arg(X[k]) for each frequency bin in an FFT output.
static Array< Real > magnitude_spectrum(const Container &input)
Magnitude spectrum for complex-valued containers.
static void ptransform_axes(ThreadPool &pool, Array< Complex > &data, const TensorLayout &layout, const Array< size_t > &axes, const bool invert, const size_t chunk_size=0)
Parallel in-place FFT/IFFT along multiple tensor axes.
static Array< size_t > normalize_axes(const Array< size_t > &axes, const size_t rank, const char *ctx)
Rationale: Validates axis indices against the tensor rank and ensures no axis is specified more than ...
static Array< Real > window_overlap_profile(const Array< Real > &analysis_window, const Array< Real > &synthesis_window, const size_t hop_size)
Returns the overlap-add normalization profile for one hop period.
static TensorLayout normalize_tensor_layout(const Array< Complex > &data, const TensorLayout &layout, const char *ctx)
Rationale: Validates a tensor layout and infers row-major strides if they are not provided.
static Array< Array< Complex > > transform_stft_frames(const Array< Array< Real > > &frames, const Array< Real > &window, const size_t fft_size, const Plan &plan, ThreadPool *pool, const size_t chunk_size)
static Array< Complex > transform_padded(const Container &input)
Zero-pad and forward-FFT a generic complex iterable.
static void validate_stable(const Container &denominator)
static Array< BiquadSection > chebyshev1_lowpass(const size_t order, const Real ripple_db, const Real cutoff_frequency, const Real sample_rate)
Digital Chebyshev-I low-pass design returned as SOS.
static Array< Array< Complex > > stft(const Array< Real > &signal, const size_t frame_size, const STFTOptions &options)
Computes a Hann-window STFT with explicit analysis options.
static Array< Array< Array< Complex > > > batched_stft(const Array< Array< Real > > &signals, const Array< Real > &window, const STFTOptions &options)
Batched STFT over a collection of real signals.
static Array< Real > filtfilt(const SignalContainer &signal, const IIRCoefficients &coeffs)
static Real inverse_jacobi_sc(const Real value, const Real modulus, const char *ctx)
static Array< Real > inverse_transform_real(const Container &input)
Inverse real transform for complex-valued containers.
static Array< Array< Array< Complex > > > transformed2d_batch(const Array< Array< Array< Complex > > > &input, const bool invert=false)
Functional 2-D batched FFT/IFFT wrapper over a matrix stack.
static Array< Complex > zeros(const Array< BiquadSection > §ions)
static Array< Real > group_delay(const BiquadSection §ion, const size_t num_points=512, const bool whole=false)
static Complex twiddle_at(const Real angle, const size_t index)
Computes a single twiddle factor exp(j * angle * index).
static Array< Real > reflect_pad_signal(const Array< Real > &signal, const size_t pad_len)
Rationale: Applies reflection padding at signal edges to reduce boundary artifacts during filtering.
std::complex< Real > Complex
static Array< Complex > apply_blackman_window(const Container &signal)
static Real evaluate_analog_transfer_magnitude(const Array< Real > &numerator, const Array< Real > &denominator, const Real omega, const char *ctx)
Rationale: Direct evaluation of |H(j*omega)| for an analog transfer function.
static Array< Real > overlap_add_frames(const Array< Array< Real > > &frames, const size_t hop_size, const size_t signal_length=0)
Overlap-adds a frame sequence with a fixed hop size.
static Array< Complex > transform_padded(const Array< Complex > &input)
static Array< Real > overlap_add_convolution(const Array< Real > &signal, const Array< Real > &kernel, const size_t block_size=0)
Convenience wrapper for long real convolution via overlap-add.
static Array< Complex > poles(const Array< Real > &denominator)
Returns the poles of a transfer denominator.
static bool satisfies_nola(const Array< Real > &window, const size_t hop_size)
Returns true when one window satisfies NOLA by itself.
static Array< Real > pistft(ThreadPool &pool, const Array< Array< Complex > > &spectrogram, const size_t frame_size, const ISTFTOptions &options, const size_t chunk_size=0)
Parallel Hann-window ISTFT with explicit options.
static bool is_stable(const Array< BiquadSection > §ions)
static bool overlap_profile_has_cola(const Array< Real > &profile) noexcept
Rationale: Constant Overlap-Add (COLA) ensures that OLA reconstruction has no amplitude modulation ar...
static Array< Real > firwin_bandstop(const size_t num_taps, const Real low_cutoff_frequency, const Real high_cutoff_frequency, const Real sample_rate, const Real attenuation_db)
FIR band-stop design using a Kaiser window.
static Array< Real > resample_poly(const Array< Real > &signal, const size_t up, const size_t down, const Array< Real > &coeffs)
Polyphase resampling with explicit FIR coefficients.
static void add_scaled_polynomial(Array< T > &dst, const Array< T > &src, const T scale)
Rationale: In-place addition of a scaled polynomial.
static Array< Complex > windowed_spectrum(const Array< Complex > &signal, const Array< Real > &window)
Returns the FFT of a complex signal after applying a window.
static size_t effective_coeff_length(const Array< Real > &input) noexcept
Returns length excluding trailing insignificant zeros.
static Array< Complex > multiply_complex_impl(const Array< Complex > &a, const Array< Complex > &b, ThreadPool *pool=nullptr, const size_t chunk_size=0)
Rationale: Linear convolution of two complex sequences via FFT.
Graph implemented with double-linked adjacency lists.
A reusable thread pool for efficient parallel task execution.
size_t num_threads() const noexcept
Get the number of worker threads.
Minimal std::expected-style result type for C++20.
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_y1_function > > y1(const __gmp_expr< T, U > &expr)
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_floor_function > > floor(const __gmp_expr< T, U > &expr)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_remainder_function > > remainder(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_y0_function > > y0(const __gmp_expr< T, U > &expr)
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
const long double offset[]
Offset values indexed by symbol string length (bounded by MAX_OFFSET_INDEX)
constexpr State invert(const State &s) noexcept
Toggle a cell value between its zero and a non-zero counterpart.
double density(const Lattice &lat, const typename Lattice::state_type &s)
Compiler_SSA_Block & block(Compiler_SSA_Function &function, const Compiler_SSA_Block_Id id)
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::pair< TgtContainer< typename SrcContainer::Item_Type >, TgtContainer< typename SrcContainer::Item_Type > > partition(const SrcContainer &c, std::function< bool(const typename SrcContainer::Item_Type &)> operation)
Partition a container into two based on a predicate.
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
DynList< T > repeated(const Container< T > &c)
Return elements that appear more than once in the container.
void parallel_for_index(ThreadPool &pool, size_t start, size_t end, F &&f, size_t chunk_size=0)
Apply a function to each element in parallel (index-based).
std::decay_t< typename HeadC::Item_Type > T
and
Check uniqueness with explicit hash + equality functors.
auto mean(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute the arithmetic mean.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
void next()
Advance all underlying iterators (bounds-checked).
auto mode(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute the mode (most frequent value).
auto max_value(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute maximum value.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
static struct argp_option options[]
static void section(const string &title)
Parameters for an analog filter prototype (S-domain).
A stable Second-Order Section (SOS) building block.
Array< Real > denominator() const
Array< Real > numerator() const
Magnitude-squared coherence sampled in Hertz.
Array< Real > magnitude_squared
One-sided cross-spectral density estimate sampled in Hertz.
Discrete frequency response sampled on a fixed angular grid.
Array< Complex > response
Array< Real > power() const
Array< Real > magnitude() const
Array< Real > phase() const
Gain-margin estimate around a phase crossover.
Coefficients for an Infinite Impulse Response (IIR) filter.
Array< Real > denominator
Feed-backward coefficients (a).
Array< Real > numerator
Feed-forward coefficients (b).
Options for ISTFT reconstruction.
Value triplet for Jacobi elliptic functions (sn, cn, dn).
Phase-margin estimate around a gain crossover.
Greedy nearest-neighbor pole/zero pairing entry.
bool is_cancellation(const Real tolerance) const noexcept
One-sided power spectral density estimate sampled in Hertz.
Options for default polyphase resampling filter design.
Rationale: Group of one or more roots (typically a conjugate pair) sharing a common geometric center.
Options for STFT analysis.
Layout descriptor for a flat tensor buffer.
Internal storage for complex transfer function evaluation terms.
Complex numerator_derivative
Complex denominator_derivative
Frequency-domain grid with target values and importance weights.
Options for Welch PSD, CSD, and coherence estimation.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
A modern, efficient thread pool for parallel task execution.
Dynamic array container with automatic resizing.