LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
eig.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_UTIL_EIG_H
6#define LINE_UTIL_EIG_H
7
8/**
9 * @file
10 * @ingroup line_util
11 * Eigenvalues and singular values, backed by LAPACK.
12 *
13 * LAPACK is BSD-3, so it is the one external numerical dependency that costs
14 * the port nothing in licensing terms: it links cleanly into a BSD-licensed
15 * binary and, unlike GMP or MPFR, imposes no relinking obligation. It is
16 * requested through the Fortran symbols (`dgeev_`, `dgesvd_`) rather than
17 * through LAPACKE, because the reference distribution ships the library without
18 * the C headers, and reached through `line::lapack` (lapack.h), which by default
19 * loads the library at run time instead of linking it.
20 *
21 * DOUBLE ONLY, and deliberately so. Eigenvalues of a rational matrix are
22 * algebraic numbers, not rationals: there is no exact instantiation to offer,
23 * and a high-precision one would need a multiprecision QR iteration that
24 * LAPACK cannot provide. Both entry points therefore take Matrix<double>,
25 * and callers templated on T must convert and document the precision loss at
26 * that point rather than pretending otherwise.
27 *
28 * When the build is configured without LAPACK the entry points throw
29 * UnsupportedError naming the missing dependency, which is the same
30 * refuse-by-name policy the CLI uses for unported features: a caller learns
31 * what is missing instead of receiving a silently substituted answer.
32 */
33
34#include <complex>
35#include <cstddef>
36#include <vector>
37
38#include "line/util/error.h"
39#include "line/util/matrix.h"
40
41#include "line/util/lapack.h"
42
43namespace line {
44
45/** Eigenvalues of a general real square matrix, in LAPACK's order. */
46inline std::vector<std::complex<double>> eig_values(const Matrix<double>& A) {
47#ifndef LINE_MP_HAVE_LAPACK
48 (void)A;
49 throw ExternalError(ErrorKind{"LAPACK"},
50 "eig_values requires LAPACK: reconfigure with -DLINE_MP_USE_LAPACK=ON and liblapack "
51 "available");
52#else
53 const std::size_t n = A.rows();
54 if (A.cols() != n) throw InputError("eig_values: matrix is not square");
55 if (n == 0) return {};
56
57 // LAPACK is column-major; the input is row-major, so transpose on the way in.
58 std::vector<double> a(n * n);
59 for (std::size_t i = 0; i < n; ++i)
60 for (std::size_t j = 0; j < n; ++j) a[j * n + i] = A(i, j);
61
62 const int ni = static_cast<int>(n);
63 std::vector<double> wr(n), wi(n);
64 double vdummy = 0.0;
65 int info = 0, lwork = -1;
66 double wopt = 0.0;
67 const int one = 1;
68 lapack::dgeev("N", "N", &ni, a.data(), &ni, wr.data(), wi.data(), &vdummy, &one, &vdummy, &one, &wopt,
69 &lwork, &info);
70 if (info != 0) throw NumericError(ErrorKind{"Lapack"}, "eig_values: LAPACK workspace query failed");
71 lwork = static_cast<int>(wopt);
72 std::vector<double> work(static_cast<std::size_t>(lwork));
73 lapack::dgeev("N", "N", &ni, a.data(), &ni, wr.data(), wi.data(), &vdummy, &one, &vdummy, &one,
74 work.data(), &lwork, &info);
75 if (info != 0) throw NumericError(ErrorKind{"NonConvergence"}, "eig_values: LAPACK dgeev failed to converge");
76
77 std::vector<std::complex<double>> out(n);
78 for (std::size_t i = 0; i < n; ++i) out[i] = std::complex<double>(wr[i], wi[i]);
79 return out;
80#endif
81}
82
83/** Largest modulus over the spectrum, i.e. the spectral radius. */
84inline double spectral_radius(const Matrix<double>& A) {
85 double r = 0.0;
86 for (const std::complex<double>& z : eig_values(A)) {
87 const double m = std::abs(z);
88 if (m > r) r = m;
89 }
90 return r;
91}
92
93/**
94 * Second largest modulus over the spectrum. This is the quantity the NCD
95 * machinery needs (ctmc_courtois's epsMAX is built from the subdominant
96 * eigenvalue of each diagonal block); returns 0 when the matrix is 1 x 1.
97 */
98inline double subdominant_modulus(const Matrix<double>& A) {
99 std::vector<std::complex<double>> e = eig_values(A);
100 if (e.size() < 2) return 0.0;
101 double first = 0.0, second = 0.0;
102 for (const std::complex<double>& z : e) {
103 const double m = std::abs(z);
104 if (m > first) {
105 second = first;
106 first = m;
107 } else if (m > second) {
108 second = m;
109 }
110 }
111 return second;
112}
113
114/** Singular values in descending order. */
115inline std::vector<double> svd_values(const Matrix<double>& A) {
116#ifndef LINE_MP_HAVE_LAPACK
117 (void)A;
118 throw ExternalError(ErrorKind{"LAPACK"},
119 "svd_values requires LAPACK: reconfigure with -DLINE_MP_USE_LAPACK=ON and liblapack "
120 "available");
121#else
122 const std::size_t m = A.rows(), n = A.cols();
123 if (m == 0 || n == 0) return {};
124 std::vector<double> a(m * n);
125 for (std::size_t i = 0; i < m; ++i)
126 for (std::size_t j = 0; j < n; ++j) a[j * m + i] = A(i, j);
127
128 const int mi = static_cast<int>(m), nj = static_cast<int>(n);
129 const std::size_t k = m < n ? m : n;
130 std::vector<double> s(k);
131 double udummy = 0.0, vtdummy = 0.0;
132 int info = 0, lwork = -1;
133 double wopt = 0.0;
134 const int one = 1;
135 lapack::dgesvd("N", "N", &mi, &nj, a.data(), &mi, s.data(), &udummy, &one, &vtdummy, &one, &wopt,
136 &lwork, &info);
137 if (info != 0) throw NumericError(ErrorKind{"Lapack"}, "svd_values: LAPACK workspace query failed");
138 lwork = static_cast<int>(wopt);
139 std::vector<double> work(static_cast<std::size_t>(lwork));
140 lapack::dgesvd("N", "N", &mi, &nj, a.data(), &mi, s.data(), &udummy, &one, &vtdummy, &one, work.data(),
141 &lwork, &info);
142 if (info != 0) throw NumericError(ErrorKind{"NonConvergence"}, "svd_values: LAPACK dgesvd failed to converge");
143 return s; // dgesvd returns them descending
144#endif
145}
146
147// ---------------------------------------------------------------------------
148// Real Schur form, and reordering its diagonal blocks
149// ---------------------------------------------------------------------------
150
151/**
152 * Real Schur factorization A = Z T Z^T, with Z orthogonal and T upper
153 * quasi-triangular: 1 x 1 diagonal blocks for real eigenvalues and 2 x 2 blocks
154 * for complex conjugate pairs.
155 */
156struct RealSchur {
157 Matrix<double> Z; ///< orthogonal Schur vectors
158 Matrix<double> T; ///< upper quasi-triangular factor
159};
160
161/**
162 * Real Schur factorization of a general square matrix (LAPACK dgees, unsorted).
163 *
164 * The Schur form is the right basis for splitting a spectrum into invariant
165 * subspaces, which is what a multi-regime fluid queue needs: the eigenvector
166 * basis exists only for a diagonalizable matrix and is complex whenever the
167 * spectrum is, while Z is orthogonal and real for every real A.
168 */
170#ifndef LINE_MP_HAVE_LAPACK
171 (void)A;
172 throw ExternalError(ErrorKind{"LAPACK"},
173 "schur_decomposition requires LAPACK: reconfigure with -DLINE_MP_USE_LAPACK=ON and "
174 "liblapack available");
175#else
176 const std::size_t n = A.rows();
177 if (A.cols() != n) throw InputError("schur_decomposition: matrix is not square");
178 RealSchur out;
179 out.Z = Matrix<double>(n, n, 0.0);
180 out.T = Matrix<double>(n, n, 0.0);
181 if (n == 0) return out;
182
183 std::vector<double> a(n * n);
184 for (std::size_t i = 0; i < n; ++i)
185 for (std::size_t j = 0; j < n; ++j) a[j * n + i] = A(i, j);
186
187 const int ni = static_cast<int>(n);
188 std::vector<double> wr(n), wi(n), vs(n * n);
189 int sdim = 0, info = 0, lwork = -1;
190 double wopt = 0.0;
191 lapack::dgees("V", "N", nullptr, &ni, a.data(), &ni, &sdim, wr.data(), wi.data(), vs.data(), &ni,
192 &wopt, &lwork, nullptr, &info);
193 if (info != 0) throw NumericError(ErrorKind{"Lapack"}, "schur_decomposition: LAPACK workspace query failed");
194 lwork = static_cast<int>(wopt);
195 std::vector<double> work(static_cast<std::size_t>(lwork));
196 lapack::dgees("V", "N", nullptr, &ni, a.data(), &ni, &sdim, wr.data(), wi.data(), vs.data(), &ni,
197 work.data(), &lwork, nullptr, &info);
198 if (info != 0) throw NumericError(ErrorKind{"NonConvergence"}, "schur_decomposition: LAPACK dgees failed to converge");
199
200 for (std::size_t i = 0; i < n; ++i)
201 for (std::size_t j = 0; j < n; ++j) {
202 out.T(i, j) = a[j * n + i];
203 out.Z(i, j) = vs[j * n + i];
204 }
205 return out;
206#endif
207}
208
209/**
210 * Reorder the diagonal blocks of a real Schur form into DESCENDING key order,
211 * stably, updating Z so that A = Z T Z^T still holds.
212 *
213 * This is MATLAB's ordschur with a CLUSTER-NUMBER select vector, whose
214 * documented behaviour is that clusters appear in descending order of the
215 * cluster number. The key is given per diagonal ENTRY; for a 2 x 2 block the
216 * key of its first row is used and the second is ignored, which is the same
217 * requirement MATLAB imposes (a select vector must be constant on a block, and
218 * a caller that splits one is asking for a factorization that does not exist
219 * over the reals).
220 *
221 * WHY dtrexc AND NOT dtrsen. dtrsen splits a spectrum into TWO clusters, the
222 * selected one and the rest, so an ordering into three or more classes needs it
223 * applied recursively to trailing submatrices, with the accumulated Q and the
224 * shifting block boundaries tracked by hand at every level. dtrexc moves ONE
225 * diagonal block from position ifst to position ilst and updates Q itself, so
226 * an arbitrary key ordering is a stable selection sort over blocks with no
227 * submatrix bookkeeping at all. It also refuses to split a 2 x 2 block rather
228 * than silently producing a complex pair astride a boundary, which is the
229 * failure that would otherwise be discovered downstream as a complex "real"
230 * subspace.
231 *
232 * @param s a real Schur factorization, typically from schur_decomposition
233 * @param key one value per diagonal entry; blocks are sorted descending by it
234 */
235inline RealSchur schur_reorder(const RealSchur& s, const std::vector<double>& key) {
236#ifndef LINE_MP_HAVE_LAPACK
237 (void)s;
238 (void)key;
239 throw ExternalError(ErrorKind{"LAPACK"},
240 "schur_reorder requires LAPACK: reconfigure with -DLINE_MP_USE_LAPACK=ON and liblapack "
241 "available");
242#else
243 const std::size_t n = s.T.rows();
244 if (s.T.cols() != n || s.Z.rows() != n || s.Z.cols() != n)
245 throw InputError("schur_reorder: the factors are not square or not conformable");
246 if (key.size() != n) throw InputError("schur_reorder: one key per diagonal entry is required");
247 RealSchur out;
248 out.T = s.T;
249 out.Z = s.Z;
250 if (n <= 1) return out;
251
252 // Column-major working copies for LAPACK.
253 std::vector<double> t(n * n), q(n * n);
254 for (std::size_t i = 0; i < n; ++i)
255 for (std::size_t j = 0; j < n; ++j) {
256 t[j * n + i] = s.T(i, j);
257 q[j * n + i] = s.Z(i, j);
258 }
259 // The key travels with its block, so it is permuted alongside T.
260 std::vector<double> k = key;
261
262 const int ni = static_cast<int>(n);
263 std::vector<double> work(n);
264 const double tiny = 0.0; // dgees leaves an exact zero below a 1 x 1 block
265
266 // Stable selection sort over blocks. pos is the first row of the region
267 // still to be ordered.
268 std::size_t pos = 0;
269 while (pos < n) {
270 // Enumerate the blocks of the remaining region and find the first one
271 // carrying the largest key; "first" keeps the sort stable.
272 std::size_t best = pos;
273 double bestkey = k[pos];
274 std::size_t i = pos;
275 while (i < n) {
276 const std::size_t sz = (i + 1 < n && t[i * n + (i + 1)] != tiny) ? 2u : 1u;
277 if (k[i] > bestkey) {
278 bestkey = k[i];
279 best = i;
280 }
281 i += sz;
282 }
283 const std::size_t bsz =
284 (best + 1 < n && t[best * n + (best + 1)] != tiny) ? 2u : 1u;
285 if (best != pos) {
286 int ifst = static_cast<int>(best) + 1; // LAPACK is 1-based
287 int ilst = static_cast<int>(pos) + 1;
288 int info = 0;
289 lapack::dtrexc("V", &ni, t.data(), &ni, q.data(), &ni, &ifst, &ilst, work.data(), &info);
290 if (info == 1)
291 throw NumericError(ErrorKind{"Singular"},
292 "schur_reorder: dtrexc could not separate two eigenvalues that are too close; "
293 "the requested ordering splits a 2 x 2 block");
294 if (info != 0) throw NumericError(ErrorKind{"Lapack"}, "schur_reorder: LAPACK dtrexc failed");
295 // Move the key with the block: erase it from its old position and
296 // reinsert it at the new one, exactly as dtrexc permuted the rows.
297 const std::vector<double> moved(k.begin() + static_cast<long>(best),
298 k.begin() + static_cast<long>(best + bsz));
299 k.erase(k.begin() + static_cast<long>(best),
300 k.begin() + static_cast<long>(best + bsz));
301 k.insert(k.begin() + static_cast<long>(pos), moved.begin(), moved.end());
302 }
303 pos += bsz;
304 }
305
306 for (std::size_t i = 0; i < n; ++i)
307 for (std::size_t j = 0; j < n; ++j) {
308 out.T(i, j) = t[j * n + i];
309 out.Z(i, j) = q[j * n + i];
310 }
311 return out;
312#endif
313}
314
315/** Numerical rank at the standard max(m,n) eps sigma_1 threshold. */
316inline std::size_t matrix_rank(const Matrix<double>& A) {
317 const std::vector<double> s = svd_values(A);
318 if (s.empty()) return 0;
319 const std::size_t dim = A.rows() > A.cols() ? A.rows() : A.cols();
320 const double tol = static_cast<double>(dim) * 2.220446049250313e-16 * s[0];
321 std::size_t r = 0;
322 for (double v : s)
323 if (v > tol) ++r;
324 return r;
325}
326
327} // namespace line
328
329#endif // LINE_UTIL_EIG_H
ExternalError(const std::string &what)
Definition error.h:126
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
The exception types the port throws.
The five LAPACK routines the port calls, behind one indirection.
Dense matrix and non-owning view.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
double subdominant_modulus(const Matrix< double > &A)
Second largest modulus over the spectrum.
Definition eig.h:98
double spectral_radius(const Matrix< double > &A)
Largest modulus over the spectrum, i.e.
Definition eig.h:84
RealSchur schur_reorder(const RealSchur &s, const std::vector< double > &key)
Reorder the diagonal blocks of a real Schur form into DESCENDING key order, stably,...
Definition eig.h:235
std::vector< std::complex< double > > eig_values(const Matrix< double > &A)
Eigenvalues of a general real square matrix, in LAPACK's order.
Definition eig.h:46
std::size_t matrix_rank(const Matrix< double > &A)
Numerical rank at the standard max(m,n) eps sigma_1 threshold.
Definition eig.h:316
std::vector< double > svd_values(const Matrix< double > &A)
Singular values in descending order.
Definition eig.h:115
RealSchur schur_decomposition(const Matrix< double > &A)
Real Schur factorization of a general square matrix (LAPACK dgees, unsorted).
Definition eig.h:169
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Real Schur factorization A = Z T Z^T, with Z orthogonal and T upper quasi-triangular: 1 x 1 diagonal ...
Definition eig.h:156
Matrix< double > Z
orthogonal Schur vectors
Definition eig.h:157
Matrix< double > T
upper quasi-triangular factor
Definition eig.h:158