5#ifndef LINE_API_MC_CTMC_COSIMLA_H
6#define LINE_API_MC_CTMC_COSIMLA_H
53 std::vector<std::vector<double>>
states;
61using CosimlaReward = std::function<std::vector<double>(
const std::vector<double>&)>;
74 std::vector<std::vector<double>>
ci;
78 std::vector<double>
piK;
80 std::vector<std::vector<double>>
D;
89inline std::string cosimla_str(
const std::vector<double>& x) {
90 std::ostringstream os;
92 for (std::size_t i = 0; i < x.size(); ++i) os << (i ?
" " :
"") << x[i];
97inline std::vector<double> cosimla_key(
const std::vector<double>& x) {
98 std::vector<double> k(x);
99 for (
double& v : k) v += 0.0;
104 std::vector<std::vector<double>> Y;
105 std::vector<double> p, w, cum, r;
109inline std::vector<double> cosimla_reward(
const CosimlaReward& reward,
const std::vector<double>& x,
110 const std::string& caller) {
111 std::vector<double> rx = reward(x);
112 bool ok = !rx.empty();
113 for (
double v : rx) ok = ok && std::isfinite(v);
116 caller +
": the reward function returned an empty or non-finite value at state " +
117 cosimla_str(x) +
".");
121inline CosimlaStep cosimla_step(
const CosimlaTransition& trans,
const std::vector<double>& x,
bool isctmc,
122 const std::string& caller) {
123 const CosimlaSuccessors s =
trans(x);
124 if (s.states.size() != s.weights.size())
125 throw InputError(ErrorKind{
"Argument"}, caller +
": the transition function must return one successor row of width " +
126 std::to_string(x.size()) +
" per weight.");
127 const std::vector<double> kx = cosimla_key(x);
130 for (std::size_t j = 0; j < s.weights.size(); ++j) {
131 if (s.states[j].size() != x.size())
132 throw InputError(ErrorKind{
"Argument"}, caller +
": the transition function must return one successor row of width " +
133 std::to_string(x.size()) +
" per weight.");
134 const double w = s.weights[j];
135 if (!(w >= 0.0) || !std::isfinite(w))
136 throw InputError(ErrorKind{
"Argument"}, caller +
": the transition function returned a negative or non-finite weight at state " +
137 cosimla_str(x) +
".");
138 if (w > 0.0 && !(isctmc && cosimla_key(s.states[j]) == kx)) {
139 st.Y.push_back(s.states[j]);
144 const std::size_t m = st.w.size();
148 throw InputError(ErrorKind{
"Argument"}, caller +
": state " + cosimla_str(x) +
149 " is absorbing (zero total outgoing rate): the chain is not irreducible.");
150 for (std::size_t j = 0; j < m; ++j) st.p[j] = st.w[j] / q;
153 if (std::fabs(q - 1.0) > 1e-8) {
154 std::ostringstream os;
155 os << caller <<
": the transition probabilities out of state " << cosimla_str(x) <<
" sum to " << q <<
", not 1.";
156 throw InputError(ErrorKind{
"Argument"}, os.str());
163 for (std::size_t j = 0; j < m; ++j) {
170inline CosimlaResult cosimla_core(
const std::vector<std::vector<double>>& A,
const std::vector<std::size_t>& K,
172 const CosimlaOptions& options,
bool isctmc,
const std::string& caller) {
173 using clock = std::chrono::steady_clock;
174 const std::size_t n = options.nsamples;
176 throw InputError(ErrorKind{
"Option"}, caller +
": options.nsamples must be an integer >= 2 (it sets the variance estimate of every boundary state).");
177 if (!(options.conflevel > 0.0 && options.conflevel < 1.0))
178 throw InputError(ErrorKind{
"Option"}, caller +
": options.conflevel must lie in (0,1).");
179 if (!(options.maxsteps >= 1.0))
180 throw InputError(ErrorKind{
"Option"}, caller +
": options.maxsteps must be a positive number.");
182 throw InputError(ErrorKind{
"Argument"}, caller +
": the center set A must be non-empty, one state per row.");
183 const std::size_t nA = A.size(), dim = A[0].size();
185 throw InputError(ErrorKind{
"Argument"}, caller +
": the regeneration set K must be a non-empty set of row indices of A.");
186 std::vector<char> isK(nA, 0);
187 for (std::size_t k : K) {
189 throw InputError(ErrorKind{
"Argument"}, caller +
": the regeneration set K must be a non-empty set of row indices of A.");
192 std::vector<std::size_t> kList, apList;
193 std::vector<std::size_t> posK(nA, 0);
194 for (std::size_t i = 0; i < nA; ++i) {
196 posK[i] = kList.size();
202 const std::size_t nK = kList.size(), nAp = apList.size();
204 std::map<std::vector<double>, std::size_t> Amap;
205 for (std::size_t i = 0; i < nA; ++i) {
206 if (A[i].size() != dim)
207 throw InputError(ErrorKind{
"Argument"}, caller +
": every state of the center set A must have the same width.");
208 if (!Amap.emplace(cosimla_key(A[i]), i).second)
209 throw InputError(ErrorKind{
"Argument"}, caller +
": the center set A contains the state " + cosimla_str(A[i]) +
" twice.");
213 const auto tla = clock::now();
214 std::map<std::vector<double>, std::size_t> Dmap;
215 std::vector<std::vector<double>> Dlist;
217 std::vector<std::vector<double>> rA(nA), rrA(nA);
218 std::vector<double> hA(nA);
219 struct Arc { std::size_t i, j;
double p, w; };
220 std::vector<Arc> aa, ad;
221 for (std::size_t i = 0; i < nA; ++i) {
222 const CosimlaStep st = cosimla_step(trans, A[i], isctmc, caller);
223 const std::vector<double> rx = cosimla_reward(reward, A[i], caller);
224 if (i == 0) R = rx.size();
225 else if (rx.size() != R)
226 throw InputError(ErrorKind{
"Argument"}, caller +
": the reward function must return the same number of rewards in every state.");
229 for (std::size_t k = 0; k < R; ++k) rrA[i][k] = rx[k] * st.h;
231 for (std::size_t j = 0; j < st.Y.size(); ++j) {
232 const std::vector<double> key = cosimla_key(st.Y[j]);
233 auto ia = Amap.find(key);
234 if (ia != Amap.end()) {
235 aa.push_back({i, ia->second, st.p[j], st.w[j]});
237 auto d = Dmap.find(key);
239 if (d == Dmap.end()) {
241 Dmap.emplace(key, di);
242 Dlist.push_back(st.Y[j]);
246 ad.push_back({i, di, st.p[j], st.w[j]});
250 const std::size_t nD = Dlist.size();
251 Matrix<double> PAA(nA, nA, 0.0), WAA(nA, nA, 0.0), PAD(nA, nD ? nD : 1, 0.0);
252 for (
const Arc& a : aa) {
253 PAA(a.i, a.j) += a.p;
254 WAA(a.i, a.j) += a.w;
256 for (
const Arc& a : ad) PAD(a.i, a.j) += a.p;
259 Matrix<double> ar(nK, R, 0.0), Atil(nK, nK, 0.0), F(nK, nD ? nD : 1, 0.0);
260 std::vector<double> ae(nK, 0.0);
261 for (std::size_t a = 0; a < nK; ++a) {
262 const std::size_t i = kList[a];
263 for (std::size_t k = 0; k < R; ++k) ar(a, k) = rrA[i][k];
265 for (std::size_t b = 0; b < nK; ++b) Atil(a, b) = PAA(i, kList[b]);
266 for (std::size_t d = 0; d < nD; ++d) F(a, d) = PAD(i, d);
269 const std::size_t ncol = R + 1 + nK + nD;
270 Matrix<double> M(nAp, nAp, 0.0);
271 for (std::size_t a = 0; a < nAp; ++a) {
273 for (std::size_t b = 0; b < nAp; ++b) M(a, b) -= PAA(apList[a], apList[b]);
275 const std::vector<std::size_t> piv =
lu_factor(M);
276 Matrix<double> X(nAp, ncol, 0.0);
277 std::vector<double> col(nAp);
278 for (std::size_t c = 0; c < ncol; ++c) {
279 for (std::size_t a = 0; a < nAp; ++a) {
280 const std::size_t i = apList[a];
281 if (c < R) col[a] = rrA[i][c];
282 else if (c == R) col[a] = hA[i];
283 else if (c < R + 1 + nK) col[a] = PAA(i, kList[c - R - 1]);
284 else col[a] = PAD(i, c - R - 1 - nK);
287 for (std::size_t a = 0; a < nAp; ++a) X(a, c) = col[a];
289 for (std::size_t a = 0; a < nK; ++a) {
290 const std::size_t i = kList[a];
291 for (std::size_t c = 0; c < nAp; ++c) {
292 const double p12 = PAA(i, apList[c]);
293 if (p12 == 0.0)
continue;
294 for (std::size_t k = 0; k < R; ++k) ar(a, k) += p12 * X(c, k);
295 ae[a] += p12 * X(c, R);
296 for (std::size_t b = 0; b < nK; ++b) Atil(a, b) += p12 * X(c, R + 1 + b);
297 for (std::size_t d = 0; d < nD; ++d) F(a, d) += p12 * X(c, R + 1 + nK + d);
301 const double latime = std::chrono::duration<double>(clock::now() - tla).count();
304 const auto tsim = clock::now();
305 std::mt19937 mt(options.seed);
306 const auto res53 = [&mt]() ->
double {
307 const double a =
static_cast<double>(mt() >> 5);
308 const double b =
static_cast<double>(mt() >> 6);
309 return (a * 67108864.0 + b) / 9007199254740992.0;
311 Matrix<double> wr(nD ? nD : 1, R, 0.0), Hn(nD ? nD : 1, nK, 0.0);
312 std::vector<double> we(nD, 0.0);
313 std::vector<double> pathR(nD * n * R), pathE(nD * n);
314 std::vector<std::size_t> pathHit(nD * n);
315 std::map<std::vector<double>, CosimlaStep> cache;
316 std::size_t totsteps = 0;
317 for (std::size_t d = 0; d < nD; ++d) {
318 for (std::size_t s = 0; s < n; ++s) {
319 std::vector<double> key = cosimla_key(Dlist[d]);
320 std::vector<double> Rsum(R, 0.0);
325 auto it = cache.find(key);
326 if (it == cache.end()) {
327 CosimlaStep c = cosimla_step(trans, key, isctmc, caller);
328 const std::vector<double> rc = cosimla_reward(reward, key, caller);
330 throw InputError(ErrorKind{
"Argument"}, caller +
": the reward function must return the same number of rewards in every state.");
332 for (std::size_t k = 0; k < R; ++k) c.r[k] = rc[k] * c.h;
333 it = cache.emplace(key, std::move(c)).first;
335 const CosimlaStep& c = it->second;
336 for (std::size_t k = 0; k < R; ++k) Rsum[k] += c.r[k];
338 const double target = res53() * c.cum.back();
339 std::size_t j = c.cum.size() - 1;
340 for (std::size_t t = 0; t < c.cum.size(); ++t)
341 if (c.cum[t] > target) {
345 key = cosimla_key(c.Y[j]);
347 auto hit = Amap.find(key);
348 if (hit != Amap.end() && isK[hit->second]) {
352 if (steps >= options.maxsteps) {
353 std::ostringstream os;
354 os << caller <<
": an excursion from boundary state " << cosimla_str(Dlist[d])
355 <<
" did not return to the regeneration set within options.maxsteps = " << options.maxsteps
356 <<
" steps; the chain may not be positive recurrent, or K should be enlarged.";
357 throw NumericError(ErrorKind{
"NonConvergence"}, os.str());
360 totsteps +=
static_cast<std::size_t
>(steps);
361 for (std::size_t k = 0; k < R; ++k) pathR[(d * n + s) * R + k] = Rsum[k];
362 pathE[d * n + s] = Esum;
363 pathHit[d * n + s] = posK[ia];
365 for (std::size_t s = 0; s < n; ++s) {
366 for (std::size_t k = 0; k < R; ++k) wr(d, k) += pathR[(d * n + s) * R + k];
367 we[d] += pathE[d * n + s];
368 Hn(d, pathHit[d * n + s]) += 1.0;
370 for (std::size_t k = 0; k < R; ++k) wr(d, k) /=
static_cast<double>(n);
371 we[d] /=
static_cast<double>(n);
372 for (std::size_t b = 0; b < nK; ++b) Hn(d, b) /=
static_cast<double>(n);
374 const double simtime = std::chrono::duration<double>(clock::now() - tsim).count();
377 Matrix<double> PK(nK, nK, 0.0);
378 for (std::size_t a = 0; a < nK; ++a)
379 for (std::size_t b = 0; b < nK; ++b) {
380 double v = Atil(a, b);
381 for (std::size_t d = 0; d < nD; ++d) v += F(a, d) * Hn(d, b);
386 for (
double v : piK)
tot += v;
387 for (
double& v : piK) v /=
tot;
388 std::vector<double> num(R, 0.0);
390 for (std::size_t a = 0; a < nK; ++a) {
392 for (std::size_t d = 0; d < nD; ++d) e += F(a, d) * we[d];
394 for (std::size_t k = 0; k < R; ++k) {
396 for (std::size_t d = 0; d < nD; ++d) v += F(a, d) * wr(d, k);
397 num[k] += piK[a] * v;
400 std::vector<double> alpha(R);
401 for (std::size_t k = 0; k < R; ++k) alpha[k] = num[k] / den;
405 std::vector<double> se(R, 0.0);
407 Matrix<double> Gin(nK, nK, 0.0);
408 for (std::size_t a = 0; a < nK; ++a)
409 for (std::size_t b = 0; b < nK; ++b) Gin(a, b) = (a == b ? 1.0 : 0.0) - PK(a, b) + piK[b];
410 const std::vector<std::size_t> gpiv =
lu_factor(Gin);
411 std::vector<double> f(nD, 0.0);
412 for (std::size_t d = 0; d < nD; ++d)
413 for (std::size_t a = 0; a < nK; ++a) f[d] += piK[a] * F(a, d);
414 for (std::size_t k = 0; k < R; ++k) {
415 std::vector<double> cv(nK, 0.0);
416 for (std::size_t a = 0; a < nK; ++a) {
417 double v = ar(a, k) - alpha[k] * ae[a];
418 for (std::size_t d = 0; d < nD; ++d) v += F(a, d) * (wr(d, k) - alpha[k] * we[d]);
423 std::vector<double> Z(n);
424 for (std::size_t d = 0; d < nD; ++d) {
426 for (std::size_t s = 0; s < n; ++s) {
427 Z[s] = pathR[(d * n + s) * R + k] - alpha[k] * pathE[d * n + s] + cv[pathHit[d * n + s]];
430 mean /=
static_cast<double>(n);
432 for (std::size_t s = 0; s < n; ++s) ss += (Z[s] - mean) * (Z[s] - mean);
433 var += f[d] * f[d] * (ss /
static_cast<double>(n - 1)) /
static_cast<double>(n);
435 se[k] = std::sqrt(var) / den;
440 std::vector<double> piT;
442 Matrix<double> QA(nA, nA, 0.0);
443 for (std::size_t i = 0; i < nA; ++i) {
445 for (std::size_t j = 0; j < nA; ++j) {
446 QA(i, j) = WAA(i, j);
453 Matrix<double> PT(nA, nA, 0.0);
454 for (std::size_t i = 0; i < nA; ++i) {
456 for (std::size_t d = 0; d < nD; ++d) lost += PAD(i, d);
457 for (std::size_t j = 0; j < nA; ++j) PT(i, j) = PAA(i, j);
466 res.halfwidth.resize(R);
467 res.ci.assign(R, std::vector<double>(2));
468 for (std::size_t k = 0; k < R; ++k) {
469 res.halfwidth[k] =
z * se[k];
470 res.ci[k][0] = alpha[k] - res.halfwidth[k];
471 res.ci[k][1] = alpha[k] + res.halfwidth[k];
473 res.alphaTrunc.assign(R, 0.0);
474 for (std::size_t i = 0; i < nA; ++i)
475 for (std::size_t k = 0; k < R; ++k) res.alphaTrunc[k] += piT[i] * rA[i][k];
476 res.conflevel = options.conflevel;
484 res.steps = totsteps;
486 res.simtime = simtime;
509 return detail::cosimla_core(A, K, trans, reward, options,
false,
"dtmc_cosimla");
521 return detail::cosimla_core(A, K, trans, reward, options,
true,
"ctmc_cosimla");
NumericError(const std::string &what)
Steady-state distribution of a continuous-time Markov chain.
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
The exception types the port throws.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
double tot(const std::vector< double > &pops)
double var(const std::vector< double > &x)
Sample variance with the n - 1 denominator.
std::vector< T > ctmc_solve(const Matrix< T > &Qin, const std::string &linsolver=std::string())
Steady-state distribution of a continuous-time Markov chain.
CosimlaResult dtmc_cosimla(const std::vector< std::vector< double > > &A, const std::vector< std::size_t > &K, const CosimlaTransition &trans, const CosimlaReward &reward, const CosimlaOptions &options=CosimlaOptions())
COSIMLA estimate of a stationary expectation of a DTMC.
CosimlaResult ctmc_cosimla(const std::vector< std::vector< double > > &A, const std::vector< std::size_t > &K, const CosimlaTransition &trans, const CosimlaReward &reward, const CosimlaOptions &options=CosimlaOptions())
COSIMLA estimate of a stationary expectation of a CTMC, through its embedded jump chain; trans return...
std::function< std::vector< double >(const std::vector< double > &)> CosimlaReward
Reward function returning one or more rewards per state.
std::vector< T > dtmc_solve(const Matrix< T > &P)
Stationary distribution of a stochastic matrix P.
std::function< CosimlaSuccessors(const std::vector< double > &)> CosimlaTransition
One-step transition function; it must accept any state the chain can reach.
double sim_norminv(double p)
Standard normal quantile function.
Matrix< double > trans(const Matrix< double > &A)
Conservation laws of a layered queueing network, enumerated from its structure.
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.
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Normal and Student t quantiles used by the output-analysis routines.
Options, with the MATLAB defaults.
double conflevel
confidence level of the interval
std::size_t nsamples
paths per boundary state (at least 2)
double maxsteps
cap on one excursion; reaching it is an error
unsigned seed
seed of the MT19937 stream
Estimate, confidence interval and diagnostics.
std::vector< double > piK
stationary law of the chain watched on K
std::vector< double > alpha
estimate of pi*r, one entry per reward
std::vector< double > alphaTrunc
plain truncation on the same center
std::vector< std::vector< double > > ci
R rows of [lower, upper].
Matrix< double > PK
estimated transition matrix on K
std::vector< double > stderr_
standard error (trailing _ avoids the stdio macro)
std::vector< double > halfwidth
std::size_t steps
simulated transitions in total
std::vector< std::vector< double > > D
boundary states, in discovery order
Successor states and their weights (probabilities for a DTMC, rates for a CTMC).
std::vector< std::vector< double > > states
std::vector< double > weights