Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
Circulant.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// This Source Code Form is subject to the terms of the Mozilla
5// Public License v. 2.0. If a copy of the MPL was not distributed
6// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
7// SPDX-FileCopyrightText: The Eigen Authors
8// SPDX-License-Identifier: MPL-2.0
9
10// References:
11// [1] P. J. Davis, "Circulant Matrices", Wiley, 1979. Diagonalization of a
12// circulant matrix by the DFT and the closed-form eigenstructure used by
13// eigenvalues()/eigenvectors(); the SVD and pseudo-inverse below follow
14// from it by taking moduli/phases of the eigenvalues.
15// [2] R. M. Gray, "Toeplitz and Circulant Matrices: A Review", Foundations and
16// Trends in Communications and Information Theory, 2(3), 2006.
17// [3] G. H. Golub and C. F. Van Loan, "Matrix Computations", 4th ed., Johns
18// Hopkins University Press, 2013, chapter 4.8 (circulant systems and
19// FFT-based products) and chapter 5.4 (numerical rank conventions).
20// [4] J. J. Dongarra, J. R. Bunch, C. B. Moler and G. W. Stewart, "LINPACK
21// Users' Guide", SIAM, 1979. determinant()'s balanced accumulation follows
22// the convention of its xGEDI routines, which return determinants as a
23// (fraction, exponent) pair to avoid spurious overflow/underflow.
24// [5] P. H. Sterbenz, "Floating-Point Computation", Prentice-Hall, 1974.
25// Scaling by a power of two is exact, the property the balanced
26// accumulation relies on.
27
28#ifndef EIGEN_STRUCTURED_CIRCULANT_H
29#define EIGEN_STRUCTURED_CIRCULANT_H
30
31// IWYU pragma: private
32#include "./InternalHeaderCheck.h"
33
34namespace Eigen {
35
36template <typename Scalar_, int Size_ = Dynamic>
37class Circulant;
38
39namespace internal {
40
41template <typename Scalar_, int Size_>
42struct traits<Circulant<Scalar_, Size_>> {
43 using Scalar = Scalar_;
44 using StorageKind = Dense;
45 using XprKind = MatrixXpr;
46 using StorageIndex = int;
47 static constexpr int RowsAtCompileTime = Size_;
48 static constexpr int ColsAtCompileTime = Size_;
49 static constexpr int MaxRowsAtCompileTime = Size_;
50 static constexpr int MaxColsAtCompileTime = Size_;
51 // Deliberately no NestByRefBit: transpose(), conjugate() and adjoint() return
52 // owning temporaries, so Product must nest the operator by value for a
53 // delayed-evaluated product expression to keep its left factor alive. The copy
54 // is O(n), negligible against the O(n log n) product evaluation.
55 static constexpr int Flags = 0;
56};
57
58template <typename Scalar_, int Size_>
59struct evaluator_traits<Circulant<Scalar_, Size_>> {
60 using Kind = IndexBased;
61 using Shape = StructuredShape;
62};
63
64} // namespace internal
65
102template <typename Scalar_, int Size_>
103class Circulant : public EigenBase<Circulant<Scalar_, Size_>> {
104 public:
105 using Scalar = Scalar_;
106 using RealScalar = typename NumTraits<Scalar>::Real;
107 using StorageIndex = int;
108 using Complex = std::complex<RealScalar>;
109 using GeneratorType = Matrix<Scalar, Size_, 1>;
110 using ComplexVector = Matrix<Complex, Dynamic, 1>;
111 using RealVector = Matrix<RealScalar, Size_, 1>;
112 using ComplexMatrix = Matrix<Complex, Size_, Size_>;
113
114 static constexpr int RowsAtCompileTime = Size_;
115 static constexpr int ColsAtCompileTime = Size_;
116 static constexpr int MaxRowsAtCompileTime = Size_;
117 static constexpr int MaxColsAtCompileTime = Size_;
118 static constexpr int SizeAtCompileTime = internal::size_at_compile_time(Size_, Size_);
119 static constexpr int MaxSizeAtCompileTime = SizeAtCompileTime;
120 static constexpr bool IsRowMajor = false;
121 // Deliberately no IsVectorAtCompileTime: Ref<const Circulant>'s default StrideType
122 // argument reads it, so its absence makes internal::is_ref_compatible SFINAE to
123 // false and keeps the iterative solvers on their matrix-free path.
124
130 template <typename Derived>
131 explicit Circulant(const MatrixBase<Derived>& col) : m_col(col) {
132 EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
133 EIGEN_INTERNAL_ASSERT_NONEMPTY_MSG(m_col, "Circulant generator must be non-empty");
134 if (m_col.size() > internal::structured_direct_threshold()) {
135 m_symbol = computeSymbol();
136 m_prodSymbol = computeProdSymbol(m_col);
137 }
138 }
139
140 EIGEN_DEVICE_FUNC Index rows() const { return m_col.size(); }
141 EIGEN_DEVICE_FUNC Index cols() const { return m_col.size(); }
142
144 const GeneratorType& column() const { return m_col; }
145
150 ComplexVector symbol() const { return m_symbol.size() > 0 ? m_symbol : computeSymbol(); }
151
153 Scalar coeff(Index row, Index col) const {
154 Index k = row - col;
155 if (k < 0) k += rows();
156 return m_col.coeff(k);
157 }
158
164 const Index n = rows();
165 GeneratorType col(n);
166 col[0] = m_col[0];
167 if (n > 1) col.tail(n - 1) = m_col.tail(n - 1).reverse();
168 return Circulant(col, internal::structured_reverse_symbol(m_symbol),
169 internal::structured_reverse_symbol(m_prodSymbol));
170 }
171
176 return Circulant(m_col.conjugate(), internal::structured_reverse_symbol(m_symbol).conjugate(),
177 internal::structured_reverse_symbol(m_prodSymbol).conjugate());
178 }
179
185 const Index n = rows();
186 GeneratorType col(n);
187 col[0] = numext::conj(m_col[0]);
188 if (n > 1) col.tail(n - 1) = m_col.tail(n - 1).reverse().conjugate();
189 return Circulant(col, m_symbol.conjugate(), m_prodSymbol.conjugate());
190 }
191
195 template <typename Dest>
196 void evalTo(Dest& dst) const {
197 const Index n = rows();
198 EIGEN_IF_CONSTEXPR (Dest::IsRowMajor) {
199 for (Index i = 0; i < n; ++i) {
200 dst.row(i).head(i + 1) = m_col.head(i + 1).reverse().transpose();
201 dst.row(i).tail(n - i - 1) = m_col.tail(n - i - 1).reverse().transpose();
202 }
203 return;
204 }
205 for (Index j = 0; j < n; ++j) {
206 dst.col(j).head(j) = m_col.tail(j);
207 dst.col(j).tail(n - j) = m_col.head(n - j);
208 }
209 }
210
212 template <typename Dest>
213 void addTo(Dest& dst) const {
214 const Index n = rows();
215 EIGEN_IF_CONSTEXPR (Dest::IsRowMajor) {
216 for (Index i = 0; i < n; ++i) {
217 dst.row(i).head(i + 1) += m_col.head(i + 1).reverse().transpose();
218 dst.row(i).tail(n - i - 1) += m_col.tail(n - i - 1).reverse().transpose();
219 }
220 return;
221 }
222 for (Index j = 0; j < n; ++j) {
223 dst.col(j).head(j) += m_col.tail(j);
224 dst.col(j).tail(n - j) += m_col.head(n - j);
225 }
226 }
227
229 template <typename Dest>
230 void subTo(Dest& dst) const {
231 const Index n = rows();
232 EIGEN_IF_CONSTEXPR (Dest::IsRowMajor) {
233 for (Index i = 0; i < n; ++i) {
234 dst.row(i).head(i + 1) -= m_col.head(i + 1).reverse().transpose();
235 dst.row(i).tail(n - i - 1) -= m_col.tail(n - i - 1).reverse().transpose();
236 }
237 return;
238 }
239 for (Index j = 0; j < n; ++j) {
240 dst.col(j).head(j) -= m_col.tail(j);
241 dst.col(j).tail(n - j) -= m_col.head(n - j);
242 }
243 }
244
249 template <typename Rhs>
251 return Product<Circulant, Rhs>(*this, x.derived());
252 }
253
262 template <typename Rhs>
264 const MatrixBase<Rhs>& b) const {
266 EIGEN_INTERNAL_ASSERT_SOLVER_RHS_MSG(*this, b, false, "right-hand side has the wrong number of rows");
267 const Index n = rows();
268 const ComplexVector s = symbol();
269 const RealVector mods = s.cwiseAbs();
270 const ComplexVector sinv = internal::structured_pinv_symbol(s, mods, internal::structured_rank_threshold(s, mods));
272 x.setZero();
273 internal::structured_fft_apply(x, sinv, n, b.derived(), ResultScalar(1));
274 return x;
275 }
276
283 Index rank() const {
284 const ComplexVector s = symbol();
285 const RealVector mods = s.cwiseAbs();
286 return (!(mods.array() < internal::structured_rank_threshold(s, mods))).count(); // NaN entries count as non-zero
287 }
288
294 const Index n = rows();
295 const ComplexVector sinv = symbol().cwiseInverse();
296 GeneratorType col(n);
297 if (n == 1) {
298 col = internal::structured_scalar_part_impl<Scalar>::run(sinv);
299 } else {
300 auto&& fft = internal::structured_fft_engine<RealScalar>();
301 ComplexVector ct(n);
302 fft.inv(ct, sinv, n);
303 col = internal::structured_scalar_part_impl<Scalar>::run(ct);
304 }
305 return Circulant(col, n > internal::structured_direct_threshold() ? sinv : ComplexVector(),
306 n > internal::structured_direct_threshold() ? computeProdSymbol(col) : ComplexVector());
307 }
308
317 Scalar determinant() const {
318 const ComplexVector s = symbol();
319 Complex det(1);
320 Index exponent = 0;
321 for (Index k = 0; k < s.size(); ++k)
322 det = internal::balance_exponent(Complex(det * internal::balance_exponent(s[k], exponent)), exponent);
323 return internal::structured_scalar_part_impl<Scalar>::run_scalar(internal::apply_exponent(det, exponent));
324 }
325
330 ComplexVector eigenvalues() const { return symbol(); }
331
336 ComplexMatrix eigenvectors() const {
337 const Index n = rows();
338 const ComplexVector roots = fourierRoots();
339 ComplexMatrix F(n, n);
340 for (Index k = 0; k < n; ++k) fourierColumn(F, roots, k, k);
341 return F;
342 }
343
349 RealVector singularValues() const {
350 ComplexVector s;
351 RealVector mods;
352 const std::vector<Index> perm = svdOrdering(s, mods);
353 RealVector sv(s.size());
354 for (Index t = 0; t < s.size(); ++t) sv[t] = mods[perm[t]];
355 return sv;
356 }
357
361 ComplexMatrix matrixU() const {
362 const Index n = rows();
363 ComplexVector s;
364 RealVector mods;
365 const std::vector<Index> perm = svdOrdering(s, mods);
366 const ComplexVector roots = fourierRoots();
367 ComplexMatrix U(n, n);
368 for (Index t = 0; t < n; ++t) {
369 fourierColumn(U, roots, perm[t], t);
370 const RealScalar a = mods[perm[t]];
371 if (a > RealScalar(0)) U.col(t) *= s[perm[t]] / a;
372 }
373 return U;
374 }
375
379 ComplexMatrix matrixV() const {
380 const Index n = rows();
381 ComplexVector s;
382 RealVector mods;
383 const std::vector<Index> perm = svdOrdering(s, mods);
384 const ComplexVector roots = fourierRoots();
385 ComplexMatrix V(n, n);
386 for (Index t = 0; t < n; ++t) fourierColumn(V, roots, perm[t], t);
387 return V;
388 }
389
393 template <typename Dest, typename Rhs, typename ProductScalar>
394 void addProduct(Dest& dst, const Rhs& rhs, const ProductScalar& alpha) const {
395 const Index n = rows();
396 EIGEN_INTERNAL_ASSERT_PRODUCT_SHAPE_MSG(*this, rhs, "invalid product: dimensions do not match");
397 if (n <= internal::structured_direct_threshold()) {
398 directProduct(dst, rhs, alpha);
399 return;
400 }
401 // Products use the padded embedding symbol when the operator size is not
402 // 5-smooth (see computeProdSymbol()); the exact-size transform of such a
403 // size runs through kissfft's quadratic generic butterfly.
404 const ComplexVector& s = m_prodSymbol.size() > 0 ? m_prodSymbol : m_symbol;
405 internal::structured_fft_apply(dst, s, n, rhs, alpha);
406 }
407
408 private:
414 Circulant(const GeneratorType& col, const ComplexVector& symbol, const ComplexVector& prodSymbol)
415 : m_col(col), m_symbol(symbol), m_prodSymbol(prodSymbol) {}
416
427 static ComplexVector computeProdSymbol(const GeneratorType& col) {
428 const Index n = col.size();
429 if (internal::fft_next_good_size(n) == n) return ComplexVector();
430 const Index p = internal::fft_next_good_size(2 * n - 1);
431 ComplexVector embedding = ComplexVector::Zero(p);
432 embedding.head(n) = col.template cast<Complex>();
433 embedding.tail(n - 1) = col.tail(n - 1).template cast<Complex>();
434 ComplexVector symbol(p);
435 auto&& fft = internal::structured_fft_engine<RealScalar>();
436 fft.fwd(symbol, embedding, p);
437 return symbol;
438 }
439
443 template <typename Dest, typename Rhs, typename ProductScalar>
444 void directProductColumn(Dest& dst, const Rhs& rhs, Index k, const ProductScalar& alpha) const {
445 const Index n = rows();
446 // A unit alpha must not multiply: even the identity complex scalar (1,0)
447 // pollutes an (Inf,0) value with NaN through the 0*Inf cross term.
448 const bool unitAlpha = alpha == ProductScalar(1);
449 if (n <= internal::structured_scalar_threshold()) {
450 // Tiny sizes: a plain scalar loop beats the segment-based path below, whose
451 // per-segment setup dominates when segments hold only a few entries.
452 for (Index i = 0; i < n; ++i) {
453 ProductScalar acc(0);
454 for (Index j = 0; j < n; ++j) acc += coeff(i, j) * rhs.coeff(j, k);
455 dst.coeffRef(i, k) += unitAlpha ? acc : ProductScalar(alpha * acc);
456 }
457 return;
458 }
459
460 // Column j is c rotated downward by j; split it into two contiguous segments.
461 auto dstCol = dst.col(k);
462 for (Index j = 0; j < n; ++j) {
463 const ProductScalar xj = unitAlpha ? ProductScalar(rhs.coeff(j, k)) : ProductScalar(alpha * rhs.coeff(j, k));
464 dstCol.head(j) += xj * m_col.tail(j);
465 dstCol.tail(n - j) += xj * m_col.head(n - j);
466 }
467 }
468
471 template <typename Dest, typename Rhs, typename ProductScalar>
472 void directProduct(Dest& dst, const Rhs& rhs, const ProductScalar& alpha) const {
473 for (Index k = 0; k < rhs.cols(); ++k) directProductColumn(dst, rhs, k, alpha);
474 }
475
492 std::vector<Index> svdOrdering(ComplexVector& s, RealVector& mods) const {
493 const Index n = rows();
494 s = symbol();
495 EIGEN_IF_CONSTEXPR (!NumTraits<Scalar>::IsComplex) {
496 const Index pairs = (n - 1) / 2;
497 mods.resize(n);
498 mods.head(n - pairs) = s.head(n - pairs).cwiseAbs();
499 mods.tail(pairs) = mods.segment(1, pairs).reverse();
500 } else {
501 mods = s.cwiseAbs();
502 }
503 return internal::structured_svd_permutation(mods);
504 }
505
506 // Cache the n distinct roots once per Fourier matrix, preserving polar()'s
507 // bounded arguments and rounding while avoiding n^2 trigonometric evaluations.
508 ComplexVector fourierRoots() const {
509 const Index n = rows();
510 const RealScalar scale = RealScalar(1) / numext::sqrt(RealScalar(n));
511 ComplexVector roots(n);
512 for (Index j = 0; j < n; ++j)
513 roots[j] = std::polar(scale, RealScalar(2 * EIGEN_PI) * RealScalar(j) / RealScalar(n));
514 return roots;
515 }
516
517 // Column k uses roots[j*k mod n]; incremental modular indexing avoids j*k overflow.
518 void fourierColumn(ComplexMatrix& F, const ComplexVector& roots, Index k, Index dstCol) const {
519 const Index n = rows();
520 Index jk = 0;
521 for (Index j = 0; j < n; ++j) {
522 F(j, dstCol) = roots[jk];
523 jk += k;
524 if (jk >= n) jk -= n;
525 }
526 }
527
529 ComplexVector computeSymbol() const {
530 const Index n = m_col.size();
531 const ComplexVector cc = m_col.template cast<Complex>();
532 if (n == 1) return cc; // the DFT of a single sample is the identity
533 ComplexVector symbol(n);
534 auto&& fft = internal::structured_fft_engine<RealScalar>();
535 fft.fwd(symbol, cc, n);
536 return symbol;
537 }
538
539 GeneratorType m_col;
540 ComplexVector m_symbol;
541 // The padded embedding symbol products use when the size is not 5-smooth;
542 // empty otherwise. See computeProdSymbol().
543 ComplexVector m_prodSymbol;
544};
545
549template <typename Derived>
553
554namespace internal {
555
556// StructuredShape avoids ambiguity with the stock dense product specializations.
557template <typename Scalar_, int Size_, typename Rhs, int ProductTag>
558struct generic_product_impl<Circulant<Scalar_, Size_>, Rhs, StructuredShape, DenseShape, ProductTag>
559 : structured_product_impl<Circulant<Scalar_, Size_>, Rhs> {};
560
561} // namespace internal
562
563#if EIGEN_COMP_CXXVER < 17
564template <typename Scalar_, int Size_>
565constexpr int Circulant<Scalar_, Size_>::RowsAtCompileTime;
566template <typename Scalar_, int Size_>
567constexpr int Circulant<Scalar_, Size_>::ColsAtCompileTime;
568template <typename Scalar_, int Size_>
569constexpr int Circulant<Scalar_, Size_>::MaxRowsAtCompileTime;
570template <typename Scalar_, int Size_>
571constexpr int Circulant<Scalar_, Size_>::MaxColsAtCompileTime;
572template <typename Scalar_, int Size_>
573constexpr int Circulant<Scalar_, Size_>::SizeAtCompileTime;
574template <typename Scalar_, int Size_>
575constexpr int Circulant<Scalar_, Size_>::MaxSizeAtCompileTime;
576template <typename Scalar_, int Size_>
577constexpr bool Circulant<Scalar_, Size_>::IsRowMajor;
578#endif
579
580} // namespace Eigen
581
582#endif // EIGEN_STRUCTURED_CIRCULANT_H
An n x n circulant matrix represented by its first column.
Definition Circulant.h:103
Matrix< typename ScalarBinaryOpTraits< Scalar, typename Rhs::Scalar >::ReturnType, Size_, Rhs::ColsAtCompileTime > solve(const MatrixBase< Rhs > &b) const
Definition Circulant.h:263
Circulant(const MatrixBase< Derived > &col)
Definition Circulant.h:131
ComplexVector eigenvalues() const
Definition Circulant.h:330
const GeneratorType & column() const
Definition Circulant.h:144
Circulant transpose() const
Definition Circulant.h:163
ComplexMatrix matrixV() const
Definition Circulant.h:379
Index rank() const
Definition Circulant.h:283
Circulant conjugate() const
Definition Circulant.h:175
Circulant inverse() const
Definition Circulant.h:293
ComplexVector symbol() const
Definition Circulant.h:150
Circulant adjoint() const
Definition Circulant.h:184
Scalar coeff(Index row, Index col) const
Definition Circulant.h:153
ComplexMatrix eigenvectors() const
Definition Circulant.h:336
ComplexMatrix matrixU() const
Definition Circulant.h:361
Scalar determinant() const
Definition Circulant.h:317
Product< Circulant, Rhs > operator*(const MatrixBase< Rhs > &x) const
Definition Circulant.h:250
RealVector singularValues() const
Definition Circulant.h:349
Derived & setZero(Index rows, Index cols)
Circulant< typename Derived::Scalar, Derived::SizeAtCompileTime > makeCirculant(const MatrixBase< Derived > &col)
Definition Circulant.h:550
Namespace containing all symbols from the Eigen library.