LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ctmc_solve.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_API_MC_CTMC_SOLVE_H
6#define LINE_API_MC_CTMC_SOLVE_H
7
8/**
9 * @file
10 * @ingroup api_mc
11 * Steady-state distribution of a continuous-time Markov chain.
12 *
13 * Templated port of matlab/lib/kpctoolbox/mc/ctmc_solve.m (the numeric branch)
14 * and jar/src/main/java/jline/api/mc/Ctmc_solve.java. Solves pi Q = 0 with
15 * sum(pi) = 1 by replacing the last column of the generator with ones and
16 * solving Q' x = e_n, exactly as MATLAB's `Qnnz' \ bnnz` does.
17 *
18 * Every step is a field operation, so the exact instantiation returns pi as a
19 * vector of rationals: for a generator with rational rates that is the true
20 * stationary distribution with no rounding whatsoever, which is what makes the
21 * exact backend worth its cost here (the double path of the JAR needs 50.9 s
22 * at n=800 where this LU needs tens of ms, see _kb/14-cpp-multiprecision).
23 *
24 * Reducible generators are handled as MATLAB does: the weakly connected
25 * components are solved separately and renormalized. States that are ISOLATED
26 * (no transition in and none out) are trimmed first -- an absorbing state is NOT
27 * isolated and is kept, being where the stationary mass ends up -- and a
28 * generator that trims to nothing is an error rather than a plausible-looking
29 * uniform vector.
30 *
31 * ABOVE GMRES_MIN_STATES THE LU IS ABANDONED FOR THE KRYLOV PATH, as in the
32 * other three codebases: restarted GMRES first, BiCGSTAB if it reports a nonzero
33 * flag, and the direct solve only if both do. The gate is compile-time as well
34 * as size-based -- an exact instantiation always takes the LU, because the
35 * iteration stops on a residual tolerance and normalizes by a Euclidean norm, so
36 * there is nothing exact for it to converge to.
37 */
38
39#include <algorithm>
40#include <cstddef>
41#include <string>
42#include <vector>
43
48#include "line/num/number.h"
49#include "line/util/error.h"
50#include "line/util/lu.h"
51#include "line/util/matrix.h"
52
53namespace line {
54namespace mc {
55
56/**
57 * Set the diagonal so that every row sums to zero (ctmc_makeinfgen).
58 * Any pre-existing diagonal entry is discarded, as in MATLAB.
59 */
60template <class T>
62 const std::size_t n = Q.rows();
63 if (Q.cols() != n) throw InputError("ctmc_makeinfgen: generator is not square");
64 Matrix<T> R = Q;
65 const T zero = num_traits<T>::from_int(0);
66 for (std::size_t i = 0; i < n; ++i) {
67 R(i, i) = zero;
68 T s = zero;
69 for (std::size_t j = 0; j < n; ++j) s += R(i, j);
70 R(i, i) = -s;
71 }
72 return R;
73}
74
75namespace detail {
76
77/** Weakly connected components of the graph of |Q + Q'| > 0. */
78template <class T>
79std::vector<std::vector<std::size_t>> weak_components(const Matrix<T>& Q) {
80 const std::size_t n = Q.rows();
81 const T zero = num_traits<T>::from_int(0);
82 std::vector<int> comp(n, -1);
83 std::vector<std::vector<std::size_t>> out;
84 for (std::size_t s = 0; s < n; ++s) {
85 if (comp[s] >= 0) continue;
86 std::vector<std::size_t> stack{s}, members;
87 comp[s] = static_cast<int>(out.size());
88 while (!stack.empty()) {
89 const std::size_t u = stack.back();
90 stack.pop_back();
91 members.push_back(u);
92 for (std::size_t v = 0; v < n; ++v) {
93 if (v == u || comp[v] >= 0) continue;
94 if (Q(u, v) != zero || Q(v, u) != zero) {
95 comp[v] = comp[u];
96 stack.push_back(v);
97 }
98 }
99 }
100 std::sort(members.begin(), members.end());
101 out.push_back(members);
102 }
103 return out;
104}
105
106/** Submatrix on the given index set, re-normalized as a generator. */
107template <class T>
108Matrix<T> submatrix(const Matrix<T>& Q, const std::vector<std::size_t>& idx) {
109 Matrix<T> S(idx.size(), idx.size());
110 for (std::size_t a = 0; a < idx.size(); ++a)
111 for (std::size_t b = 0; b < idx.size(); ++b) S(a, b) = Q(idx[a], idx[b]);
112 return S;
113}
114
115} // namespace detail
116
117/**
118 * @brief Steady-state distribution of a continuous-time Markov chain.
119 *
120 * @param Qin generator; the diagonal is recomputed, so an off-diagonal rate
121 * matrix is accepted directly
122 * @param linsolver optional method name, as options.config.linsolver /
123 * options.method in the other codebases: "power", "jacobi",
124 * "gaussseidel" or "sor" run that classical iteration
125 * (ctmc_classical.h) on the trimmed generator and keep its result
126 * only when it converges (flag 0); any other value, or a classical
127 * iteration that fails, takes the default path below; "gth" runs
128 * GTH elimination (ctmc_gth.h), at every arithmetic. The exact
129 * instantiation ignores the classical names and solves directly.
130 * @return stationary distribution as a row vector of length n, summing to one
131 */
132template <class T>
133std::vector<T> ctmc_solve(const Matrix<T>& Qin, const std::string& linsolver = std::string()) {
134 const std::size_t n = Qin.rows();
135 if (Qin.cols() != n) throw InputError("ctmc_solve: generator is not square");
136 const T zero = num_traits<T>::from_int(0);
137 const T one = num_traits<T>::from_int(1);
138
139 if (n == 0) throw InputError("ctmc_solve: empty generator");
140 if (n == 1) return std::vector<T>{one};
141
142 const Matrix<T> Q = ctmc_makeinfgen(Qin);
143
144 bool allZero = true;
145 for (std::size_t i = 0; i < n && allZero; ++i)
146 for (std::size_t j = 0; j < n; ++j)
147 if (Q(i, j) != zero) {
148 allZero = false;
149 break;
150 }
151 if (allZero) {
152 // No transitions at all: every distribution satisfies pi Q = 0, so the
153 // stationary distribution is not unique and uniform is as good as any.
154 return std::vector<T>(n, one / num_traits<T>::from_int(static_cast<long>(n)));
155 }
156
157 // Reducible: solve each weakly connected component and renormalize.
158 const std::vector<std::vector<std::size_t>> comps = detail::weak_components(Q);
159 if (comps.size() > 1) {
160 std::vector<T> pi(n, zero);
161 for (const std::vector<std::size_t>& c : comps) {
162 const std::vector<T> pc = ctmc_solve(ctmc_makeinfgen(detail::submatrix(Q, c)), linsolver);
163 for (std::size_t k = 0; k < c.size(); ++k) pi[c[k]] = pc[k];
164 }
165 T s = zero;
166 for (const T& v : pi) s += v;
167 if (s == zero) throw NumericError(ErrorKind{"Degenerate"}, "ctmc_solve: components sum to zero");
168 for (T& v : pi) v /= s;
169 return pi;
170 }
171
172 // Trim ISOLATED states -- no transition in and none out -- repeatedly.
173 //
174 // AN ABSORBING STATE IS NOT ISOLATED AND IS KEPT. Its column carries the flow that
175 // reaches it, and it is where the stationary mass ends up; the trim used to also
176 // require a nonzero ROW, which dropped exactly that state, left its feeders with
177 // nothing to flow into, and cascaded through them until the generator was empty and
178 // this function refused a chain whose distribution is unique (Q = [0 0; 1 -1] has
179 // pi = [1 0]). The MATLAB and JAR twins carried the same rule and are fixed with
180 // this one; see _kb/06-solver-catalog.md, where it cost SolverMAM a host-dependent
181 // answer. The test here scans stored entries rather than a summed row, so it stays
182 // exact and needs no tolerance -- which also keeps it correct at T = Rational.
183 std::vector<std::size_t> keep(n);
184 for (std::size_t i = 0; i < n; ++i) keep[i] = i;
185 Matrix<T> Qk = Q;
186 for (;;) {
187 const std::size_t m = Qk.rows();
188 std::vector<std::size_t> active;
189 for (std::size_t i = 0; i < m; ++i) {
190 bool colNz = false;
191 for (std::size_t j = 0; j < m; ++j) {
192 if (Qk(j, i) != zero) { colNz = true; break; }
193 }
194 if (colNz) active.push_back(i);
195 }
196 if (active.empty())
197 throw NumericError(ErrorKind{"Infeasible"},
198 "ctmc_solve: the generator has no connected state, every state was eliminated as "
199 "isolated; it admits no unique stationary distribution");
200 if (active.size() == m) break;
201 std::vector<std::size_t> keep2(active.size());
202 for (std::size_t k = 0; k < active.size(); ++k) keep2[k] = keep[active[k]];
203 keep = keep2;
204 Qk = ctmc_makeinfgen(detail::submatrix(Qk, active));
205 }
206
207 // GTH elimination (Grassmann, Taksar, Heyman 1985): subtraction-free, so
208 // every probability keeps small relative error; exact at T = Rational. With
209 // several closed classes in the trimmed chain it defers to the default path.
210 if (linsolver == "gth") {
211 const GthResult<T> g = ctmc_gth_flag(Qk);
212 if (g.flag == 0) {
213 std::vector<T> pi(n, zero);
214 for (std::size_t k = 0; k < Qk.rows(); ++k) pi[keep[k]] = g.p[k];
215 return pi;
216 }
217 }
218
219 // Classical stationary iterations (Stewart 1994; Haverkort 1998, 15.1.3),
220 // on the trimmed generator before the normalisation column replaces its
221 // last column, exactly where MATLAB, the JAR and Python run them.
222 if constexpr (num_traits<T>::has_transcendental) {
223 if (is_classical_linsolver(linsolver)) {
224 const ClassicalResult<T> c = ctmc_classical_by_name(linsolver, Qk);
225 if (c.flag == 0) {
226 std::vector<T> pi(n, zero);
227 for (std::size_t k = 0; k < Qk.rows(); ++k) pi[keep[k]] = c.p[k];
228 return pi;
229 }
230 }
231 }
232
233 // Replace the last column with ones and solve the transposed system.
234 const std::size_t m = Qk.rows();
235 Matrix<T> A(m, m);
236 for (std::size_t i = 0; i < m; ++i)
237 for (std::size_t j = 0; j < m; ++j) A(i, j) = (i == m - 1) ? one : Qk(j, i);
238 std::vector<T> b(m, zero);
239 b[m - 1] = one;
240
241 // The iterative path. Its accuracy is a residual tolerance of 1e-12, tighter
242 // than any fixed-point tolerance a caller sets, so switching to it cannot
243 // move a reported metric; its failure modes are reported through the flag
244 // rather than thrown, which is what makes the fallback chain possible.
245 std::vector<T> x;
246 if constexpr (num_traits<T>::has_transcendental) {
247 if (m > GMRES_MIN_STATES) {
248 const GmresResult<T> g = ctmc_gmres(A, b);
249 if (g.flag == 0) {
250 x = g.x;
251 } else {
252 const BicgstabResult<T> bs = ctmc_bicgstab(A, b);
253 if (bs.flag == 0) x = bs.x;
254 }
255 }
256 }
257 if (x.empty()) x = solve(A, b);
258
259 std::vector<T> pi(n, zero);
260 for (std::size_t k = 0; k < m; ++k) pi[keep[k]] = x[k];
261 return pi;
262}
263
264} // namespace mc
265} // namespace line
266
267#endif // LINE_API_MC_CTMC_SOLVE_H
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
Preconditioned stabilized biconjugate gradients, for the linear systems a generator produces.
Classical stationary iterative solvers for pi Q = 0, sum(pi) = 1: the power method on the uniformised...
Restarted GMRES with an ILUT preconditioner, for the linear systems a generator produces.
Grassmann-Taksar-Heyman (GTH) elimination for the stationary vector, and the limit matrix J = lim exp...
The exception types the port throws.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
std::vector< T > ctmc_solve(const Matrix< T > &Qin, const std::string &linsolver=std::string())
Steady-state distribution of a continuous-time Markov chain.
Definition ctmc_solve.h:133
bool is_classical_linsolver(const std::string &name)
Whether a linsolver name selects one of the classical solvers, as accepted by ctmc_solve in all four ...
BicgstabResult< T > ctmc_bicgstab(const Matrix< T > &A, const std::vector< T > &b, double tol=1e-12, long maxit=0, const std::vector< T > &x0=std::vector< T >())
Preconditioned stabilized biconjugate gradients, for the linear systems a generator produces.
Matrix< T > ctmc_makeinfgen(const Matrix< T > &Q)
Set the diagonal so that every row sums to zero (ctmc_makeinfgen).
Definition ctmc_solve.h:61
constexpr std::size_t GMRES_MIN_STATES
Order above which the direct sparse factorization is abandoned in favour of the Krylov path.
Definition ctmc_gmres.h:75
GthResult< T > ctmc_gth_flag(const Matrix< T > &Q)
Stationary vector of a CTMC by GTH elimination, with a flag.
Definition ctmc_gth.h:135
ClassicalResult< T > ctmc_classical_by_name(const std::string &name, const Matrix< T > &Q)
Run the classical solver named by is_classical_linsolver with defaults.
GmresResult< T > ctmc_gmres(const Matrix< T > &A, const std::vector< T > &b, double tol=1e-12, long restart=0, long maxit=0, const std::vector< T > &x0=std::vector< T >())
Restarted GMRES with an ILUT preconditioner, for the linear systems a generator produces.
Definition ctmc_gmres.h:653
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
Definition lu.h:158
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
std::vector< T > x
solution
int flag
0 converged, 1 iteration limit, 3 stagnation, 4 breakdown
int flag
0 converged, 1 iteration cap, 2 zero diagonal, 4 breakdown
std::vector< T > p
stationary distribution estimate, sums to one
int flag
0 converged, 1 iteration limit, 3 stagnation/divergence
Definition ctmc_gmres.h:80
std::vector< T > x
solution
Definition ctmc_gmres.h:79
int flag
0 success, 1 several closed classes (not unique)
Definition ctmc_gth.h:53
std::vector< T > p
stationary vector (empty when flag == 1)
Definition ctmc_gth.h:52