LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ctmc_reward.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_SOLVERS_CTMC_SOLVER_CTMC_REWARD_H
6#define LINE_SOLVERS_CTMC_SOLVER_CTMC_REWARD_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_ctmc_reward.m` and the `@@SolverCTMC` reward surface
12 * (`runRewardAnalyzer`, `getAvgReward`, `getTranReward`, `getAccReward`).
13 *
14 * TWO DIFFERENT QUANTITIES SHARE THE WORD "REWARD", and conflating them is the
15 * trap this file exists to avoid:
16 *
17 * steady state E[r] = sum_s pi(s) r(s), a RATE -- the long-run average
18 * reward earned per unit time.
19 * value function V^k(s), the reward ACCUMULATED over k uniformized steps
20 * starting from s. It grows without bound in a recurrent chain,
21 * because it is a total and not an average.
22 *
23 * `V` is therefore not "the transient version of E[r]" and does not converge to
24 * it; its SLOPE does. The reference reports both and so does this port.
25 *
26 * UNIFORMIZATION IS WHAT MAKES THE VALUE ITERATION A CTMC ANSWER. The embedded
27 * chain P = Q/q + I with q = max|diag(Q)| has the same stationary law as Q and
28 * a uniform step of mean duration 1/q, so iteration index k maps to time k/q.
29 * Any q at least as large as the maximum exit rate is valid; taking the maximum
30 * is the tightest, hence the fastest-mixing, choice.
31 */
32
33#include <cmath>
34#include <cstddef>
35#include <string>
36#include <vector>
37
42#include "line/util/error.h"
43#include "line/util/matrix.h"
44
45namespace line {
46namespace ctmc {
47
48/** What the reward analyzer produces, per declared reward. */
49template <class T>
50struct CtmcReward {
51 std::vector<std::string> names;
52 std::vector<T> steady_state; ///< E[r] per reward
53 std::vector<Matrix<T>> V; ///< V[r] is (Tmax+1 x nstates)
54 std::vector<T> t; ///< iteration index / q
55 Matrix<T> state_space_aggr; ///< the rows the reward saw
57};
58
59/**
60 * Port of `solver_ctmc_reward.m`.
61 *
62 * @param tmax number of value-iteration steps; the reference's default is 1000
63 * @param sn the refreshed network struct, carrying the reward definitions
64 * @param opt CTMC options (state-space cutoff, tolerances, method)
65 */
66template <class T>
68 std::size_t tmax = 1000) {
69 if (sn.reward.empty())
70 throw InputError(
71 "solver_ctmc_reward: no rewards are defined; declare one with set_reward(name, fn) "
72 "before asking for a reward analysis");
73
74 CtmcReward<T> out;
76 const std::size_t n = out.chain.chain.space.size();
77 const std::size_t nr = sn.reward.size();
78 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
79
80 out.state_space_aggr = ctmc_state_space_aggr(out.chain.solved_sn ? *out.chain.solved_sn : sn,
81 out.chain.chain.space);
82
83 // The reward vector of each declaration, evaluated once per state on the
84 // aggregate row -- the same row `RewardState` wraps in the reference.
85 Matrix<T> R(nr, n, zero);
86 out.names.resize(nr);
87 for (std::size_t r = 0; r < nr; ++r) {
88 out.names[r] = sn.reward[r].name;
89 for (std::size_t s = 0; s < n; ++s) {
90 std::vector<T> row(out.state_space_aggr.cols());
91 for (std::size_t c = 0; c < row.size(); ++c) row[c] = out.state_space_aggr(s, c);
92 R(r, s) = sn.reward[r].fn(row);
93 }
94 }
95
96 out.steady_state.assign(nr, zero);
97 for (std::size_t r = 0; r < nr; ++r)
98 for (std::size_t s = 0; s < n; ++s)
99 out.steady_state[r] += T(out.chain.pi[s] * R(r, s));
100
101 // Uniformization rate: the largest exit rate. A generator with none -- every
102 // state absorbing -- would divide by zero, so it falls back to 1, which
103 // leaves P = I and a value function that simply accumulates r(s).
104 double q = 0;
105 for (std::size_t s = 0; s < n; ++s)
106 q = std::max(q, std::fabs(num_traits<T>::to_double(out.chain.chain.Q(s, s))));
107 if (q == 0) q = 1.0;
108 const T qq = num_traits<T>::from_double(q);
109
110 Matrix<T> P(n, n, zero);
111 for (std::size_t a = 0; a < n; ++a)
112 for (std::size_t b = 0; b < n; ++b)
113 P(a, b) = a == b ? T(out.chain.chain.Q(a, b) / qq + one)
114 : T(out.chain.chain.Q(a, b) / qq);
115
116 out.V.assign(nr, Matrix<T>(tmax + 1, n, zero));
117 for (std::size_t r = 0; r < nr; ++r) {
118 std::vector<T> prev(n, zero);
119 for (std::size_t k = 1; k <= tmax; ++k) {
120 std::vector<T> next(n, zero);
121 // V^{k+1}(s) = r(s) + sum_s' P(s,s') V^k(s'), the reference's
122 // `R(r,:) + v_prev*P'` -- note the TRANSPOSE, which makes it a
123 // forward expectation over the successor rather than a backward
124 // one over the predecessor.
125 for (std::size_t s = 0; s < n; ++s) {
126 T acc = R(r, s);
127 for (std::size_t sp = 0; sp < n; ++sp) acc += T(P(s, sp) * prev[sp]);
128 next[s] = acc;
129 }
130 for (std::size_t s = 0; s < n; ++s) out.V[r](k, s) = next[s];
131 prev.swap(next);
132 }
133 }
134
135 out.t.resize(tmax + 1);
136 for (std::size_t k = 0; k <= tmax; ++k)
137 out.t[k] = T(num_traits<T>::from_double(static_cast<double>(k)) / qq);
138 return out;
139}
140
141/**
142 * Port of `@@SolverCTMC/getTranReward`: E[r(X(t))] = sum_s pi_t(s) r(s).
143 *
144 * NOT THE VALUE FUNCTION `V` above. This is the expected reward RATE at time t,
145 * which converges to the steady-state E[r]; `V` is the reward accumulated over
146 * k uniformized steps and diverges. The two are related by V being roughly the
147 * integral of this, and confusing them is the easiest mistake to make here.
148 *
149 * @param t0,t1 the timespan; an infinite one has no transient to report
150 * @param sn the refreshed network struct, carrying the reward definitions
151 * @param opt CTMC options (state-space cutoff, tolerances, method)
152 * @param tout optional out-parameter receiving the integration time points
153 * @param names optional out-parameter receiving the reward names, in result order
154 * @return `out[r][i]` is reward r at time `t[i]`
155 */
156template <class T>
157std::vector<std::vector<T>> solver_ctmc_tran_reward(const NetworkStruct<T>& sn,
158 const CtmcOptions& opt, const T& t0,
159 const T& t1, std::vector<T>* tout = nullptr,
160 std::vector<std::string>* names = nullptr) {
162 "solver_ctmc_tran_reward integrates the forward equation, which needs "
163 "transcendental arithmetic; use --arith double or real");
164 if (sn.reward.empty())
165 throw InputError(
166 "solver_ctmc_tran_reward: no rewards are defined; declare one with "
167 "set_reward(name, fn) before asking for a transient reward");
168 if (!std::isfinite(num_traits<T>::to_double(t1)))
169 throw InputError(
170 "solver_ctmc_tran_reward: a finite timespan is required; an unbounded one has no "
171 "transient to report, so ask for the steady-state reward instead");
172
174 const Matrix<T> A = ctmc_state_space_aggr(sn, tr.chain.chain.space);
175 const std::size_t n = tr.chain.chain.space.size(), nr = sn.reward.size(), nt = tr.t.size();
176 const T zero = num_traits<T>::from_int(0);
177
178 // The reward vector is state-dependent only, so it is evaluated ONCE per
179 // state rather than once per (state, time): r does not depend on t, and
180 // re-evaluating a user callback nt times would be the dominant cost.
181 Matrix<T> R(nr, n, zero);
182 if (names) names->clear();
183 for (std::size_t r = 0; r < nr; ++r) {
184 if (names) names->push_back(sn.reward[r].name);
185 for (std::size_t s = 0; s < n; ++s) {
186 std::vector<T> row(A.cols());
187 for (std::size_t c = 0; c < row.size(); ++c) row[c] = A(s, c);
188 R(r, s) = sn.reward[r].fn(row);
189 }
190 }
191
192 std::vector<std::vector<T>> out(nr, std::vector<T>(nt, zero));
193 for (std::size_t r = 0; r < nr; ++r)
194 for (std::size_t i = 0; i < nt; ++i)
195 for (std::size_t s = 0; s < n; ++s) out[r][i] += T(tr.pit(i, s) * R(r, s));
196 if (tout) *tout = tr.t;
197 return out;
198}
199
200/** What `solver_ctmc_acc_reward` produces. */
201template <class T>
203 std::vector<std::string> names;
204 std::vector<T> t; ///< absolute time points, t[0] = t0
205 std::vector<std::vector<T>> metric; ///< metric[r][i] = E[int_{t0}^{t_i} r(X(s)) ds]
206 std::vector<std::vector<T>> avg; ///< metric / (t_i - t0); E[r(X(t0))] at t_i = t0
207};
208
209/**
210 * Port of `@@SolverCTMC/getAccReward`: the reward ACCUMULATED over [t0, t],
211 * E[int_{t0}^t r(X(s)) ds] = L(t - t0) r with L(h) = int_0^h pi0 exp(Q s) ds
212 * computed by uniformisation (mc::ctmc_accumulated; Haverkort 1998, 15.2.4),
213 * and its time average over the interval. The chain starts at t0 from the
214 * model's initial distribution, as for `solver_ctmc_tran_reward`.
215 *
216 * Unlike the value function `V` of `solver_ctmc_reward`, which counts
217 * uniformised STEPS, this is a continuous-time integral: its time average
218 * converges to the steady-state E[r] as t grows.
219 *
220 * The time grid follows the reference: `opt.timestep > 0` gives
221 * t0, t0 + ts, ... up to t1 with t1 appended if it is not on the grid;
222 * otherwise 51 equally spaced points.
223 */
224template <class T>
226 const T& t0, const T& t1) {
228 "solver_ctmc_acc_reward uses Poisson weights exp(-q t); use --arith double or real");
229 if (sn_arg.reward.empty())
230 throw InputError(
231 "solver_ctmc_acc_reward: no rewards are defined; declare one with "
232 "set_reward(name, fn) before asking for an accumulated reward");
233 const double t0d = num_traits<T>::to_double(t0), t1d = num_traits<T>::to_double(t1);
234 if (!std::isfinite(t0d) || !std::isfinite(t1d) || t1d < t0d)
235 throw InputError(
236 "solver_ctmc_acc_reward: a finite timespan [t0, t1] with t1 >= t0 is required");
237
238 const CtmcSolution<T> chain = solver_ctmc_analyzer(sn_arg, opt);
239 const NetworkStruct<T>& sn = chain.solved_sn ? *chain.solved_sn : sn_arg;
240 std::vector<T> pi0;
241 if (!analyzer_detail::init_state_distribution(sn, chain.chain.space, pi0))
242 throw InputError(
243 "solver_ctmc_acc_reward: the initial state is not contained in the state space");
244
246 if (opt.timestep > 0.0) {
247 const long K = static_cast<long>(std::floor((t1d - t0d) / opt.timestep + 1e-9));
248 for (long i = 0; i <= K; ++i) {
249 const T ti = T(t0 + num_traits<T>::from_double(opt.timestep * static_cast<double>(i)));
250 if (ti <= t1) out.t.push_back(ti);
251 }
252 if (out.t.empty() || out.t.back() < t1) out.t.push_back(t1);
253 } else {
254 for (long i = 0; i <= 50; ++i)
255 out.t.push_back(T(t0 + (t1 - t0) * num_traits<T>::from_int(i) / num_traits<T>::from_int(50)));
256 out.t.back() = t1;
257 }
258 std::vector<T> h(out.t.size());
259 for (std::size_t i = 0; i < h.size(); ++i) h[i] = T(out.t[i] - t0);
260 const mc::AccumulatedResult<T> acc = mc::ctmc_accumulated(pi0, chain.chain.Q, h);
261
262 const Matrix<T> A = ctmc_state_space_aggr(sn, chain.chain.space);
263 const std::size_t n = chain.chain.space.size(), nr = sn_arg.reward.size(), nt = out.t.size();
264 const T zero = num_traits<T>::from_int(0);
265 out.metric.assign(nr, std::vector<T>(nt, zero));
266 out.avg.assign(nr, std::vector<T>(nt, zero));
267 for (std::size_t r = 0; r < nr; ++r) {
268 out.names.push_back(sn_arg.reward[r].name);
269 std::vector<T> R(n);
270 T r0 = zero;
271 for (std::size_t s = 0; s < n; ++s) {
272 std::vector<T> row(A.cols());
273 for (std::size_t c = 0; c < row.size(); ++c) row[c] = A(s, c);
274 R[s] = sn_arg.reward[r].fn(row);
275 r0 += T(pi0[s] * R[s]);
276 }
277 for (std::size_t i = 0; i < nt; ++i) {
278 T m = zero;
279 for (std::size_t s = 0; s < n; ++s) m += T(acc.L(i, s) * R[s]);
280 out.metric[r][i] = m;
281 out.avg[r][i] = h[i] > zero ? T(m / h[i]) : r0;
282 }
283 }
284 return out;
285}
286
287/** Port of `@@SolverCTMC/getAvgReward`: the steady-state expected rewards. */
288template <class T>
290 std::vector<std::string>* names = nullptr) {
292 if (names) *names = r.names;
293 return r.steady_state;
294}
295
296} // namespace ctmc
297} // namespace line
298
299#endif // LINE_SOLVERS_CTMC_SOLVER_CTMC_REWARD_H
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
A network plus its refreshed NetworkStruct.
std::vector< Reward > reward
Accumulated state probabilities L(t) = int_0^t pi(s) ds of a CTMC by uniformisation (Reibman and Triv...
The exception types the port throws.
Dense matrix and non-owning view.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
std::vector< T > solver_ctmc_avg_reward(const NetworkStruct< T > &sn, const CtmcOptions &opt, std::vector< std::string > *names=nullptr)
Port of @@SolverCTMC/getAvgReward: the steady-state expected rewards.
CtmcTransient< T > solver_ctmc_transient_analyzer(const NetworkStruct< T > &sn_arg, const CtmcOptions &opt, const T &t0, const T &t1, const std::vector< T > &grid=std::vector< T >())
Port of solver_ctmc_transient_analyzer.m.
CtmcAccReward< T > solver_ctmc_acc_reward(const NetworkStruct< T > &sn_arg, const CtmcOptions &opt, const T &t0, const T &t1)
Port of @@SolverCTMC/getAccReward: the reward ACCUMULATED over [t0, t], E[int_{t0}...
Matrix< T > ctmc_state_space_aggr(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
Port of StateSpaceAggr: the per-(station, class) job counts of every state, as an (nstates x nstation...
std::vector< std::vector< T > > solver_ctmc_tran_reward(const NetworkStruct< T > &sn, const CtmcOptions &opt, const T &t0, const T &t1, std::vector< T > *tout=nullptr, std::vector< std::string > *names=nullptr)
Port of @@SolverCTMC/getTranReward: E[r(X(t))] = sum_s pi_t(s) r(s).
CtmcReward< T > solver_ctmc_reward(const NetworkStruct< T > &sn, const CtmcOptions &opt, std::size_t tmax=1000)
Port of solver_ctmc_reward.m.
AccumulatedResult< T > ctmc_accumulated(const std::vector< T > &pi0, const Matrix< T > &Q, const std::vector< T > &t, double tol=1e-12, long maxiter=-1)
Accumulated state probabilities int_0^t pi(s) ds at each time point.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Port of solver_ctmc_transient_analyzer.m: the time-dependent counterpart of solver_ctmc_analyzer,...
What solver_ctmc_acc_reward produces.
std::vector< T > t
absolute time points, t[0] = t0
std::vector< std::string > names
std::vector< std::vector< T > > metric
metric[r][i] = E[int_{t0}^{t_i} r(X(s)) ds]
std::vector< std::vector< T > > avg
metric / (t_i - t0); E[r(X(t0))] at t_i = t0
The SolverCTMC knobs this port honours.
What the reward analyzer produces, per declared reward.
std::vector< T > steady_state
E[r] per reward.
std::vector< Matrix< T > > V
V[r] is (Tmax+1 x nstates).
std::vector< T > t
iteration index / q
Matrix< T > state_space_aggr
the rows the reward saw
std::vector< std::string > names
Everything one CTMC solve produces.
std::shared_ptr< const NetworkStruct< T > > solved_sn
The struct the chain was built on, when it differs from the caller's in its state LAYOUT: set when he...
What one transient CTMC solve produces.
Matrix< T > L
row k is int_0^{t_k} pi(s) ds