214 const std::size_t E = envObj.nstages();
219 for (it = 1; it <= opt.iter_max; ++it) {
220 for (std::size_t e = 0; e < E; ++e) analyze(e);
234 mam_backend = (
opt.stage_solver ==
"mam");
235 if (!mam_backend &&
opt.stage_solver !=
"ctmc")
237 "SolverENV statevec: stage solver '" +
opt.stage_solver +
238 "' is not available; the state-vector coupling needs an EXPLICIT generator over a "
239 "state space it can propagate a distribution across, which SolverCTMC exposes by "
240 "enumeration and SolverMAM by flattening its level-dependent QBD blocks");
241 if (
opt.sojourn !=
"stochastic" &&
opt.sojourn !=
"deterministic")
242 throw InputError(
"SolverENV statevec: unknown sojourn '" +
opt.sojourn +
"'");
250 envObj.reject_lqn_stages(
251 "SolverENV statevec",
252 "the state-vector coupling propagates a joint distribution over ONE stage "
253 "generator, which a layered model does not have -- it decomposes into a network "
256 const std::size_t E = envObj.nstages();
257 M = envObj.stage(0).model.nstations;
258 K = envObj.stage(0).model.nclasses;
259 for (std::size_t e = 1; e < E; ++e)
260 if (envObj.stage(e).model.nstations != M || envObj.stage(e).model.nclasses != K)
262 "SolverENV statevec: every stage must have the same stations and classes; the "
263 "metrics are blended entrywise across them");
267 tspan_end.assign(E,
opt.timespan_end);
268 for (std::size_t e = 0; e < E; ++e) {
269 if (e <
opt.stage_timespan_end.size()) tspan_end[e] =
opt.stage_timespan_end[e];
270 if (!std::isfinite(tspan_end[e]) || !(tspan_end[e] >
opt.timespan_start))
272 "SolverENV statevec: the statevec analyzer requires a finite inner-solver "
273 "timespan for stage " +
274 std::to_string(e + 1) +
", e.g. CTMC(model,'timespan',[0,T])");
277 det_sojourn = (
opt.sojourn ==
"deterministic");
281 pi_enter.assign(E, std::vector<T>());
282 pi_enter_prev.assign(E, std::vector<T>());
283 pi_exit.assign(E, std::vector<std::vector<T>>());
284 pi_timeavg.assign(E, std::vector<T>());
285 dvals.assign(E, 0.0);
287 for (std::size_t e = 0; e < E; ++e)
288 dvals[e] = std::max(
mam::map_mean(envObj.hold_time[e].map()),
289 std::numeric_limits<double>::epsilon());
305 const std::size_t E = envObj.nstages();
306 for (std::size_t e = 0; e < E; ++e) {
314 mo.method =
"default";
315 mo.cutoff = opt.mam_cutoff;
322 seed_entry_distributions();
323 pi_enter_prev = pi_enter;
348 void seed_entry_distributions() {
349 const std::size_t E = envObj.nstages();
358 std::vector<std::vector<T>> own(E);
359 for (std::size_t e = 0; e < E; ++e) {
363 : normalized(stages[e].pi);
366 bool sameSpace = E > 1;
367 for (std::size_t e = 1; e < E && sameSpace; ++e)
368 sameSpace = (state_count(e) == state_count(0));
370 std::vector<T> shared;
372 std::vector<double> w(E, 1.0 /
static_cast<double>(E));
374 bool usable = envObj.prob_env.size() == E;
375 for (std::size_t e = 0; e < E && usable; ++e) {
376 if (!std::isfinite(envObj.prob_env[e]) || envObj.prob_env[e] < 0.0) usable =
false;
377 else wsum += envObj.prob_env[e];
380 if (usable && wsum > 0.0)
381 for (std::size_t e = 0; e < E; ++e) w[e] = envObj.prob_env[e] / wsum;
383 const std::size_t n = state_count(0);
384 Matrix<T> Qbar(n, n, num_traits<T>::from_double(0.0));
385 for (std::size_t e = 0; e < E; ++e) {
386 const Matrix<T>& Qe = gen(e);
387 const T we = num_traits<T>::from_double(w[e]);
388 for (std::size_t i = 0; i < n; ++i)
389 for (std::size_t j = 0; j < n; ++j) Qbar(i, j) += we * Qe(i, j);
396 std::vector<T> pi0(n, num_traits<T>::from_double(0.0));
397 for (std::size_t e = 0; e < E; ++e) {
398 const T we = num_traits<T>::from_double(w[e]);
399 for (std::size_t i = 0; i < n; ++i) pi0[i] += we * own[e][i];
404 for (std::size_t e = 0; e < E; ++e) {
405 pi_enter[e] = shared.empty() ? own[e] : shared;
410 const Matrix<T>& gen(std::size_t e)
const {
411 return mam_backend ? mam_flat[e].Q : stages[e].chain.Q;
415 std::size_t state_count(std::size_t e)
const {
416 return mam_backend ? mam_flat[e].levelOf.size() : stages[e].chain.space.size();
423 void analyze(std::size_t e) {
424 const std::size_t E = envObj.nstages();
425 const Matrix<T>& Q = gen(e);
426 const std::vector<T> pi0 = pi_enter[e];
434 std::vector<T> avg, ex;
435 time_average(pi0, Q, dvals[e], avg, ex);
436 pi_exit[e].assign(E, std::vector<T>());
437 for (std::size_t h = 0; h < E; ++h)
438 if (envObj.arc(e, h).enabled) pi_exit[e][h] = ex;
444 if (exp_sojourn(e, s_e)) {
449 const std::vector<T> res = resolvent(pi0, Q, s_e);
450 pi_exit[e].assign(E, std::vector<T>());
451 for (std::size_t h = 0; h < E; ++h)
452 if (envObj.arc(e, h).enabled) pi_exit[e][h] = res;
459 if constexpr (!num_traits<T>::has_transcendental) {
461 "SolverENV statevec: a non-exponential environment sojourn needs the transient "
462 "pi0 exp(Qt) from ctmc_transient, which is an adaptive approximation governed by "
463 "a tolerance and has no exact value in rational arithmetic; rerun with "
464 "--arith double, or use exponential transitions, whose resolvent is exact");
466 const mc::TransientResult<T> tr =
468 num_traits<T>::from_double(tspan_end[e]));
469 std::vector<double> t(tr.t.size());
470 for (std::size_t j = 0; j < tr.t.size(); ++j) t[j] = num_traits<T>::to_double(tr.t[j]);
472 pi_exit[e].assign(E, std::vector<T>());
473 for (std::size_t h = 0; h < E; ++h)
474 pi_exit[e][h] = stieltjes(tr.pi, cdf_weights(envObj.proc[e][h].map(), t));
476 const std::vector<T> avg =
477 stieltjes(tr.pi, cdf_weights(envObj.hold_time[e].map(), t));
483 const std::size_t last = tr.pi.rows() - 1, n = tr.pi.cols();
484 std::vector<T> tail(n);
485 for (std::size_t j = 0; j < n; ++j) tail[j] = tr.pi(last, j);
486 pi_timeavg[e] = tail;
496 const std::size_t E = envObj.nstages();
497 pi_enter_prev = pi_enter;
498 std::vector<std::vector<T>> next(E);
500 for (std::size_t e = 0; e < E; ++e) {
501 const std::size_t n = state_count(e);
502 std::vector<T> acc(n, num_traits<T>::from_int(0));
504 for (std::size_t h = 0; h < E; ++h) {
505 const double po = envObj.prob_orig(h, e);
506 if (!(po > 0.0))
continue;
507 if (pi_exit[h].size() <= e || pi_exit[h][e].empty())
continue;
508 const std::vector<T> pex = reset_apply(h, e, pi_exit[h][e]);
511 "SolverENV statevec: reset_state[" + std::to_string(h) +
"][" +
512 std::to_string(e) +
"] returned a " + std::to_string(pex.size()) +
513 "-element vector but stage " + std::to_string(e + 1) +
" has " +
515 " states; supply a reset that maps the state space of stage " +
516 std::to_string(h + 1) +
" onto that of stage " + std::to_string(e + 1));
517 const T w = num_traits<T>::from_double(po);
518 for (std::size_t s = 0; s < n; ++s) acc[s] += T(w * pex[s]);
522 const T w = num_traits<T>::from_double(wsum);
523 for (std::size_t s = 0; s < n; ++s) acc[s] = T(acc[s] / w);
527 next[e] = normalized(acc);
537 bool converged()
const {
538 const std::size_t E = envObj.nstages();
540 for (std::size_t e = 0; e < E; ++e) {
541 const std::vector<T>& a = pi_enter[e];
542 const std::vector<T>& b = pi_enter_prev[e];
543 if (a.empty() || b.empty() || a.size() != b.size())
return false;
545 for (std::size_t s = 0; s < a.size(); ++s)
546 d += std::fabs(num_traits<T>::to_double(a[s]) - num_traits<T>::to_double(b[s]));
547 l1 = std::max(l1, d);
549 if (!std::isfinite(l1))
return false;
550 return l1 < opt.iter_tol;
557 void finish(EnvStatevecSolution<T>& out) {
558 const std::size_t E = envObj.nstages();
559 const T zero = num_traits<T>::from_int(0);
563 out.QStage.assign(E, Matrix<T>(M, K, zero));
564 out.UStage.assign(E, Matrix<T>(M, K, zero));
565 out.TStage.assign(E, Matrix<T>(M, K, zero));
567 for (std::size_t e = 0; e < E; ++e) {
568 if (pi_timeavg[e].empty())
continue;
569 Matrix<T> QNe, UNe, TNe;
573 const mam::LdqbdAvg<T> a =
583 envObj.stage(e).model, stages[e].chain, pi_timeavg[e],
false);
591 const T p = num_traits<T>::from_double(envObj.prob_env[e]);
592 for (std::size_t i = 0; i < M; ++i)
593 for (std::size_t r = 0; r < K && r < QNe.cols(); ++r) {
594 out.QN(i, r) += T(p * QNe(i, r));
595 out.UN(i, r) += T(p * UNe(i, r));
596 out.TN(i, r) += T(p * TNe(i, r));
599 out.pi_enter = pi_enter;
600 out.pi_timeavg = pi_timeavg;
613 void cache_blend(EnvStatevecSolution<T>& out)
const {
618 if (mam_backend)
return;
619 const std::size_t E = envObj.nstages();
620 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
621 const T zero = num_traits<T>::from_int(0);
624 std::vector<T>(), std::vector<T>(), Matrix<T>(),
625 Matrix<T>(), std::vector<T>());
626 for (std::size_t c = 0; c < out.cache.caches.size(); ++c) {
627 const std::size_t ind = out.cache.caches[c].node;
628 const std::size_t isf = sn1.stateful_index(ind);
629 if (isf == 0)
continue;
630 std::vector<T> hitT(K, zero), missT(K, zero), dhitT(K, zero);
631 bool any_delayed =
false;
632 for (std::size_t e = 0; e < E; ++e) {
633 if (pi_timeavg[e].empty())
continue;
634 const std::vector<T> pv = normalized(pi_timeavg[e]);
635 const qn::NetworkStruct<T>& sne = envObj.stage(e).model;
636 const auto it = sne.nodeparam.find(ind);
637 if (it == sne.nodeparam.end())
continue;
638 const qn::CacheParam<T>& np = it->second;
639 const T w = num_traits<T>::from_double(envObj.prob_env[e]);
640 const auto& dr = stages[e].chain.dep_rates;
643 const std::vector<double> drate =
644 ctmc::analyzer_detail::cache_delayed_hit_rate(sne, ind, stages[e].chain, pv);
645 for (std::size_t k = 0; k < K && k < np.hitclass.size(); ++k) {
646 const std::size_t hc = np.hitclass[k];
647 const std::size_t mc = k < np.missclass.size() ? np.missclass[k] : 0;
648 if (hc == 0 || mc == 0)
continue;
649 T hit_rate = zero, miss_rate = zero;
650 for (std::size_t s = 0; s < pv.size(); ++s) {
651 hit_rate += T(pv[s] * dr[s][isf - 1][hc - 1]);
652 miss_rate += T(pv[s] * dr[s][isf - 1][mc - 1]);
655 if (k < drate.size())
656 dk = num_traits<T>::from_double(
657 std::min(drate[k], num_traits<T>::to_double(hit_rate)));
658 if (num_traits<T>::to_double(dk) > 0) any_delayed =
true;
659 hitT[k] += T(w * T(hit_rate - dk));
660 dhitT[k] += T(w * dk);
661 missT[k] += T(w * miss_rate);
664 const T nan = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
665 std::vector<T> hp(K, nan), mp(K, nan), dp(K, nan);
666 for (std::size_t k = 0; k < K; ++k) {
667 const T tot = T(hitT[k] + missT[k] + dhitT[k]);
668 if (num_traits<T>::to_double(tot) > 0) {
669 hp[k] = T(hitT[k] / tot);
670 mp[k] = T(missT[k] / tot);
671 dp[k] = T(dhitT[k] / tot);
674 out.cache.caches[c].hitprob = hp;
675 out.cache.caches[c].missprob = mp;
676 if (any_delayed) out.cache.caches[c].delayedprob = dp;
683 bool exp_sojourn(std::size_t e,
double& s)
const {
684 const std::size_t E = envObj.nstages();
687 for (std::size_t h = 0; h < E; ++h) {
688 const EnvArc<T>& a = envObj.arc(e, h);
689 if (!a.enabled)
continue;
691 s += num_traits<T>::to_double(a.dist.D1(0, 0));
694 return any && s > 0.0;
698 static std::vector<T> resolvent(
const std::vector<T>& pi0,
const Matrix<T>& Q,
double s) {
699 const std::size_t n = Q.rows();
700 const T sT = num_traits<T>::from_double(s);
701 Matrix<T> A(n, n, num_traits<T>::from_int(0));
702 for (std::size_t i = 0; i < n; ++i)
703 for (std::size_t j = 0; j < n; ++j)
704 A(j, i) = T((i == j ? sT : num_traits<T>::from_int(0)) - Q(i, j));
706 for (std::size_t i = 0; i < n; ++i) b[i] = T(sT * pi0[i]);
711 static void time_average(
const std::vector<T>& pi0,
const Matrix<T>& Q,
double d,
712 std::vector<T>& avg, std::vector<T>& ex) {
713 if constexpr (!num_traits<T>::has_transcendental) {
715 "SolverENV statevec: a deterministic sojourn needs ctmc_timeaverage, whose "
716 "uniformization carries Poisson weights exp(-qt) that are not rational; rerun "
717 "with --arith double");
719 const mc::TimeAverageResult<T> r =
734 static std::vector<double> cdf_weights(
const mam::Map<double>& m,
735 const std::vector<double>& t) {
736 std::vector<double> w(t.size(), 0.0);
737 if (t.size() < 2)
return w;
739 bool all_zero =
true;
740 for (std::size_t a = 0; a < m.D1.rows() && all_zero; ++a)
741 for (std::size_t b = 0; b < m.D1.cols() && all_zero; ++b)
742 if (m.D1(a, b) != 0.0) all_zero =
false;
743 if (all_zero)
return w;
745 for (std::size_t j = 1; j < t.size(); ++j) w[j] = F[j] - F[j - 1];
750 static std::vector<T> stieltjes(
const Matrix<T>& pit,
const std::vector<double>& w) {
753 if (std::isnan(v))
return std::vector<T>();
756 if (!(sw > 0.0))
return std::vector<T>();
757 const std::size_t n = pit.cols();
758 std::vector<T> out(n, num_traits<T>::from_int(0));
759 for (std::size_t j = 0; j < w.size() && j < pit.rows(); ++j) {
760 if (w[j] == 0.0)
continue;
761 const T wj = num_traits<T>::from_double(w[j] / sw);
762 for (std::size_t s = 0; s < n; ++s) out[s] += T(wj * pit(j, s));
769 std::vector<T> reset_apply(std::size_t h, std::size_t e,
const std::vector<T>& p)
const {
770 if (h < opt.reset_state.size() && e < opt.reset_state[h].size() && opt.reset_state[h][e])
771 return opt.reset_state[h][e](p);
776 static std::vector<T> normalized(
const std::vector<T>& p) {
777 const T zero = num_traits<T>::from_int(0);
778 std::vector<T> q = p;
780 for (std::size_t s = 0; s < q.size(); ++s) {
781 if (num_traits<T>::to_double(q[s]) < 0) q[s] = zero;
784 if (num_traits<T>::to_double(tot) > 0)
785 for (std::size_t s = 0; s < q.size(); ++s) q[s] = T(q[s] / tot);
789 Environment<T>& envObj;
790 EnvStatevecOptions<T> opt;
791 std::size_t M = 0, K = 0;
792 bool det_sojourn =
false;
793 std::vector<double> dvals, tspan_end;
794 std::vector<ctmc::CtmcSolution<T>> stages;
795 bool mam_backend =
false;
796 std::vector<mam::LdqbdBlocks<T>> mam_ld;
797 std::vector<mam::LdqbdFlat<T>> mam_flat;
798 std::vector<std::vector<T>> pi_enter, pi_enter_prev, pi_timeavg;
799 std::vector<std::vector<std::vector<T>>> pi_exit;