LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
sylvester.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_SYLVESTER_H
6#define LINE_UTIL_SYLVESTER_H
7
8/**
9 * @file
10 * @ingroup line_util
11 * The Sylvester equation A X + X B = C, and MATLAB's `lyap(A,B,C)`.
12 *
13 * Solved in the Kronecker form (I_m kron A + B^T kron I_n) vec(X) = vec(C) with
14 * `vec` column-major, so the whole thing is one LU solve of order n*m in `T`.
15 * That is the ONLY formulation available at every arithmetic the port offers:
16 * Bartels-Stewart needs a real Schur factorization, `util/eig.h` is
17 * deliberately double-only (eigenvalues of a rational matrix are algebraic, not
18 * rational), so a Schur-based solver would silently pin every caller to double.
19 * The cost is O((n m)^3) against Bartels-Stewart's O(n^3 + m^3); the callers in
20 * this port pass phase-space matrices whose order is the product of an arrival
21 * MMAP order and a total service-PH order, both small, and the whole point of
22 * the header is that `Rational` and `Real<D>` get an answer at all.
23 *
24 * SO A DOUBLE-ONLY CALLER TAKES `sylvester_schur`/`lyap_schur` BELOW, not these,
25 * and `SylvesterFactor<double>` itself takes the Schur arm whenever LAPACK is
26 * present (see its comment for the `dec.mmap` hang that forced it).
27 * The Kronecker arm exists for the arithmetics Schur cannot reach, and the two
28 * linear-noise covariances -- `fluid_lyapunov` and `cache_rmf_lna` -- are double
29 * by construction, since each decides stability with `eig_values` first. Both
30 * once took this arm, and both grew a d^2-by-d^2 LU out of a d-by-d covariance:
31 * an Erlang(64) service made the fluid one 4096-square and it stopped finishing.
32 *
33 * `mfq_multiregime.h` carries the identical Kronecker construction for
34 * `Matrix<double>`; it predates this header and stays where it is because it is
35 * used only from double-only code and moving it would churn two large files
36 * that no test covers at another arithmetic.
37 */
38
39#include <cstddef>
40#include <memory>
41#include <type_traits>
42#include <vector>
43
44#include "line/num/number.h"
45#include "line/util/eig.h"
46#include "line/util/error.h"
47#include "line/util/linalg.h"
48#include "line/util/lu.h"
49#include "line/util/matrix.h"
50
51#include "line/util/lapack.h"
52
53namespace line {
54
55/**
56 * A X + X B = C by Bartels-Stewart, at double.
57 *
58 * WHY THIS EXISTS BESIDE THE KRONECKER SOLVER ABOVE. The Kronecker form is the
59 * only one available in an arbitrary field, and its O((n m)^3) cost is
60 * acceptable for the phase-space matrices the MMAP queue recursion passes. The
61 * FJ_codes fork-join engine passes matrices of order (C + 1) * m^2 * ma with C
62 * defaulting to 100, i.e. n and m in the hundreds to low thousands: the
63 * Kronecker operator of an 800 x 800 pair is 640000 square, which is 3 TB of
64 * LU. Bartels-Stewart is O(n^3 + m^3) and factorizes the same problem in
65 * fractions of a second, at the price of a real Schur factorization -- LAPACK,
66 * hence double only, exactly as `util/eig.h` is.
67 *
68 * A X + X B = C is solved as Ta Y + Y Tb = Za' C Zb with A = Za Ta Za' and
69 * B = Zb Tb Zb' real Schur, the quasi-triangular core done by dtrsyl, and
70 * X = Za Y Zb'. dtrsyl's `scale` guards against overflow when the two spectra
71 * nearly collide; it is divided out here, and a scale of zero means the
72 * equation has no solution, which is reported by name rather than returned as
73 * an infinity.
74 *
75 * The Schur pair is computed ONCE in the constructor and every `solve` reuses
76 * it, so a chain of right-hand sides against a fixed (A,B) costs one dgees per
77 * coefficient plus a dtrsyl per right-hand side, as `SylvesterFactor` needs.
78 */
80public:
82 : n_(A.rows()), m_(B.rows()) {
83#ifndef LINE_MP_HAVE_LAPACK
84 throw ExternalError(ErrorKind{"LAPACK"},
85 "sylvester_schur requires LAPACK: reconfigure with -DLINE_MP_USE_LAPACK=ON and "
86 "liblapack available");
87#else
88 if (A.cols() != n_ || B.cols() != m_)
89 throw InputError("sylvester_schur: A and B must be square");
90 if (n_ == 0 || m_ == 0) return;
91 const RealSchur sa = schur_decomposition(A);
92 const RealSchur sb = schur_decomposition(B);
93 Za_ = sa.Z;
94 Zb_ = sb.Z;
95 ta_.resize(n_ * n_);
96 tb_.resize(m_ * m_);
97 for (std::size_t i = 0; i < n_; ++i)
98 for (std::size_t j = 0; j < n_; ++j) ta_[j * n_ + i] = sa.T(i, j);
99 for (std::size_t i = 0; i < m_; ++i)
100 for (std::size_t j = 0; j < m_; ++j) tb_[j * m_ + i] = sb.T(i, j);
101#endif
102 }
103
104 /** Solve A X + X B = C. */
106#ifndef LINE_MP_HAVE_LAPACK
107 (void)C;
108 throw ExternalError(ErrorKind{"LAPACK"}, "sylvester_schur requires LAPACK");
109#else
110 if (C.rows() != n_ || C.cols() != m_)
111 throw InputError("sylvester_schur: the right-hand side is not conformable");
112 Matrix<double> X(n_, m_, 0.0);
113 if (n_ == 0 || m_ == 0) return X;
114 // Ct = Za' C Zb, column-major for LAPACK.
115 const Matrix<double> Ct = matmul(matmul(Za_.transpose(), C), Zb_);
116 std::vector<double> ta = ta_, tb = tb_, c(n_ * m_);
117 for (std::size_t i = 0; i < n_; ++i)
118 for (std::size_t j = 0; j < m_; ++j) c[j * n_ + i] = Ct(i, j);
119
120 const int ni = static_cast<int>(n_), mi = static_cast<int>(m_), isgn = 1;
121 double scale = 0.0;
122 int info = 0;
123 lapack::dtrsyl("N", "N", &isgn, &ni, &mi, ta.data(), &ni, tb.data(), &mi, c.data(), &ni,
124 &scale, &info);
125 if (info < 0) throw InputError("sylvester_schur: LAPACK dtrsyl rejected an argument");
126 if (info == 1)
127 throw NumericError(ErrorKind{"Singular"},
128 "sylvester_schur: A and -B have common or very close eigenvalues, so the "
129 "Sylvester equation is singular or nearly so and its solution is not determined");
130 if (scale == 0.0)
131 throw NumericError(ErrorKind{"Degenerate"},
132 "sylvester_schur: LAPACK dtrsyl returned a zero scale factor");
133
134 Matrix<double> Y(n_, m_, 0.0);
135 for (std::size_t i = 0; i < n_; ++i)
136 for (std::size_t j = 0; j < m_; ++j) Y(i, j) = c[j * n_ + i] / scale;
137 return matmul(matmul(Za_, Y), Zb_.transpose());
138#endif
139 }
140
141private:
142 std::size_t n_, m_;
143 Matrix<double> Za_, Zb_;
144 std::vector<double> ta_, tb_; ///< the quasi-triangular factors, column-major
145};
146
147/** A X + X B = C by Bartels-Stewart, at double; see SchurSylvesterFactor. */
149 const Matrix<double>& C) {
150 if (A.cols() != A.rows() || B.cols() != B.rows())
151 throw InputError("sylvester_schur: A and B must be square");
152 if (C.rows() != A.rows() || C.cols() != B.rows())
153 throw InputError("sylvester_schur: the right-hand side is not conformable");
154 return SchurSylvesterFactor(A, B).solve(C);
155}
156
157/**
158 * The Kronecker operator of a FIXED (A,B) pair, factorized once.
159 *
160 * The MMAP[K]/PH[K]/1 queue-length recursion solves a chain of Sylvester
161 * equations that share A and B and differ only in the right-hand side, one per
162 * queue-length level. Refactorizing per level would make the recursion cubic in
163 * the level count for no reason.
164 *
165 * AT DOUBLE WITH LAPACK IT IS BARTELS-STEWART, NOT THE KRONECKER FORM. The
166 * Kronecker operator of an n x n by m x m pair is (n m)^2 entries, and the MMAP
167 * queue recursion's A and B are both (arrival order) x (service order): a
168 * departure process ETAQA-truncated at level 8 is a 90-state MMAP, which against
169 * an Erlang-3 service made A and B 270 x 270 and the operator 72900 square,
170 * 42 GB of LU and ~10^14 flops. `dec.mmap` sat in that allocation
171 * indefinitely on an Erl/Erl/1 tandem the JAR (`Matrix.lyap`, Schur-based)
172 * solves in 0.02 s. So the double arm factors the pair once with
173 * `SchurSylvesterFactor` and reuses it per right-hand side; the Kronecker LU
174 * stays for the arithmetics a Schur factorization cannot reach.
175 */
176template <class T>
178public:
179 SylvesterFactor(const Matrix<T>& A, const Matrix<T>& B) : n_(A.rows()), m_(B.rows()) {
180 const T zero = num_traits<T>::from_int(0);
181 if (A.cols() != n_ || B.cols() != m_)
182 throw InputError("SylvesterFactor: A and B must be square");
183 if (n_ == 0 || m_ == 0) return;
184#ifdef LINE_MP_HAVE_LAPACK
185 if constexpr (std::is_same<T, double>::value) {
186 schur_ = std::make_shared<const SchurSylvesterFactor>(A, B);
187 return;
188 }
189#endif
190 LU_ = Matrix<T>(n_ * m_, n_ * m_, zero);
191 for (std::size_t j = 0; j < m_; ++j)
192 for (std::size_t i = 0; i < n_; ++i) {
193 const std::size_t row = j * n_ + i;
194 for (std::size_t k = 0; k < n_; ++k) LU_(row, j * n_ + k) += A(i, k);
195 for (std::size_t k = 0; k < m_; ++k) LU_(row, k * n_ + i) += B(k, j);
196 }
197 piv_ = lu_factor(LU_);
198 }
199
200 /** Solve A X + X B = C. */
202 const T zero = num_traits<T>::from_int(0);
203 Matrix<T> X(n_, m_, zero);
204 if (n_ == 0 || m_ == 0) return X;
205 if (C.rows() != n_ || C.cols() != m_)
206 throw InputError("SylvesterFactor: the right-hand side is not conformable");
207#ifdef LINE_MP_HAVE_LAPACK
208 if constexpr (std::is_same<T, double>::value) return schur_->solve(C);
209#endif
210 std::vector<T> rhs(n_ * m_, zero);
211 for (std::size_t j = 0; j < m_; ++j)
212 for (std::size_t i = 0; i < n_; ++i) rhs[j * n_ + i] = C(i, j);
213 lu_solve(LU_, piv_, rhs);
214 for (std::size_t j = 0; j < m_; ++j)
215 for (std::size_t i = 0; i < n_; ++i) X(i, j) = rhs[j * n_ + i];
216 return X;
217 }
218
219 /** Solve A X + X B + C = 0, MATLAB's lyap(A,B,C). */
221 Matrix<T> negC(C.rows(), C.cols());
222 for (std::size_t i = 0; i < C.rows(); ++i)
223 for (std::size_t j = 0; j < C.cols(); ++j) negC(i, j) = -C(i, j);
224 return solve_sylvester(negC);
225 }
226
227private:
228 std::size_t n_, m_;
229 Matrix<T> LU_;
230 std::vector<std::size_t> piv_;
231 std::shared_ptr<const SchurSylvesterFactor> schur_; ///< the double arm, see above
232};
233
234/**
235 * Solve A X + X B = C for X.
236 *
237 * @param A n x n
238 * @param B m x m
239 * @param C n x m
240 */
241template <class T>
243 if (C.rows() != A.rows() || C.cols() != B.rows())
244 throw InputError("sylvester_solve: the blocks are not conformable");
245 return SylvesterFactor<T>(A, B).solve_sylvester(C);
246}
247
248/** MATLAB `lyap(A,B,C)` solves A X + X B + C = 0, i.e. sylvester_solve(A, B, -C). */
249template <class T>
250Matrix<T> lyap_solve(const Matrix<T>& A, const Matrix<T>& B, const Matrix<T>& C) {
251 if (C.rows() != A.rows() || C.cols() != B.rows())
252 throw InputError("lyap_solve: the blocks are not conformable");
253 return SylvesterFactor<T>(A, B).solve_lyap(C);
254}
255
256/** MATLAB `lyap(A,B,C)` at double via Bartels-Stewart: A X + X B + C = 0. */
258 const Matrix<double>& C) {
259 Matrix<double> negC(C.rows(), C.cols());
260 for (std::size_t i = 0; i < C.rows(); ++i)
261 for (std::size_t j = 0; j < C.cols(); ++j) negC(i, j) = -C(i, j);
262 return sylvester_schur(A, B, negC);
263}
264
265} // namespace line
266
267#endif // LINE_UTIL_SYLVESTER_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
Matrix< double > solve(const Matrix< double > &C) const
Solve A X + X B = C.
Definition sylvester.h:105
SchurSylvesterFactor(const Matrix< double > &A, const Matrix< double > &B)
Definition sylvester.h:81
SylvesterFactor(const Matrix< T > &A, const Matrix< T > &B)
Definition sylvester.h:179
Matrix< T > solve_lyap(const Matrix< T > &C) const
Solve A X + X B + C = 0, MATLAB's lyap(A,B,C).
Definition sylvester.h:220
Matrix< T > solve_sylvester(const Matrix< T > &C) const
Solve A X + X B = C.
Definition sylvester.h:201
Eigenvalues and singular values, backed by LAPACK.
The exception types the port throws.
The five LAPACK routines the port calls, behind one indirection.
Dense linear algebra over the templated number type: products, identity, inverse, and powers.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
void lu_solve(const Matrix< T > &LU, const std::vector< std::size_t > &piv, std::vector< T > &b)
Solve LUx = Pb in place on b, using the factors from lu_factor.
Definition lu.h:94
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Definition lu.h:48
Matrix< T > lyap_solve(const Matrix< T > &A, const Matrix< T > &B, const Matrix< T > &C)
MATLAB lyap(A,B,C) solves A X + X B + C = 0, i.e.
Definition sylvester.h:250
Matrix< T > matmul(const Matrix< T > &A, const Matrix< T > &B)
Matrix product A B.
Definition linalg.h:36
Matrix< double > sylvester_schur(const Matrix< double > &A, const Matrix< double > &B, const Matrix< double > &C)
A X + X B = C by Bartels-Stewart, at double; see SchurSylvesterFactor.
Definition sylvester.h:148
Matrix< T > sylvester_solve(const Matrix< T > &A, const Matrix< T > &B, const Matrix< T > &C)
Solve A X + X B = C for X.
Definition sylvester.h:242
RealSchur schur_decomposition(const Matrix< double > &A)
Real Schur factorization of a general square matrix (LAPACK dgees, unsorted).
Definition eig.h:169
Matrix< double > lyap_schur(const Matrix< double > &A, const Matrix< double > &B, const Matrix< double > &C)
MATLAB lyap(A,B,C) at double via Bartels-Stewart: A X + X B + C = 0.
Definition sylvester.h:257
Number-type abstraction for the templated API port.
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