213 const std::size_t E = envObj.nstages();
218 for (it = 1; it <= opt.iter_max; ++it) {
219 for (std::size_t e = 0; e < E; ++e) analyze(e);
233 mam_backend = (
opt.stage_solver ==
"mam");
234 if (!mam_backend &&
opt.stage_solver !=
"ctmc")
236 "SolverENV statevec: stage solver '" +
opt.stage_solver +
237 "' is not available; the state-vector coupling needs an EXPLICIT generator over a "
238 "state space it can propagate a distribution across, which SolverCTMC exposes by "
239 "enumeration and SolverMAM by flattening its level-dependent QBD blocks");
240 if (
opt.sojourn !=
"stochastic" &&
opt.sojourn !=
"deterministic")
241 throw InputError(
"SolverENV statevec: unknown sojourn '" +
opt.sojourn +
"'");
249 envObj.reject_lqn_stages(
250 "SolverENV statevec",
251 "the state-vector coupling propagates a joint distribution over ONE stage "
252 "generator, which a layered model does not have -- it decomposes into a network "
255 const std::size_t E = envObj.nstages();
256 M = envObj.stage(0).model.nstations;
257 K = envObj.stage(0).model.nclasses;
258 for (std::size_t e = 1; e < E; ++e)
259 if (envObj.stage(e).model.nstations != M || envObj.stage(e).model.nclasses != K)
261 "SolverENV statevec: every stage must have the same stations and classes; the "
262 "metrics are blended entrywise across them");
266 tspan_end.assign(E,
opt.timespan_end);
267 for (std::size_t e = 0; e < E; ++e) {
268 if (e <
opt.stage_timespan_end.size()) tspan_end[e] =
opt.stage_timespan_end[e];
269 if (!std::isfinite(tspan_end[e]) || !(tspan_end[e] >
opt.timespan_start))
271 "SolverENV statevec: the statevec analyzer requires a finite inner-solver "
272 "timespan for stage " +
273 std::to_string(e + 1) +
", e.g. CTMC(model,'timespan',[0,T])");
276 det_sojourn = (
opt.sojourn ==
"deterministic");
280 pi_enter.assign(E, std::vector<T>());
281 pi_enter_prev.assign(E, std::vector<T>());
282 pi_exit.assign(E, std::vector<std::vector<T>>());
283 pi_timeavg.assign(E, std::vector<T>());
284 dvals.assign(E, 0.0);
286 for (std::size_t e = 0; e < E; ++e)
287 dvals[e] = std::max(
mam::map_mean(envObj.hold_time[e].map()),
288 std::numeric_limits<double>::epsilon());
304 const std::size_t E = envObj.nstages();
305 for (std::size_t e = 0; e < E; ++e) {
313 mo.method =
"default";
314 mo.cutoff = opt.mam_cutoff;
321 seed_entry_distributions();
322 pi_enter_prev = pi_enter;
347 void seed_entry_distributions() {
348 const std::size_t E = envObj.nstages();
357 std::vector<std::vector<T>> own(E);
358 for (std::size_t e = 0; e < E; ++e) {
362 : normalized(stages[e].pi);
365 bool sameSpace = E > 1;
366 for (std::size_t e = 1; e < E && sameSpace; ++e)
367 sameSpace = (state_count(e) == state_count(0));
369 std::vector<T> shared;
371 std::vector<double> w(E, 1.0 /
static_cast<double>(E));
373 bool usable = envObj.prob_env.size() == E;
374 for (std::size_t e = 0; e < E && usable; ++e) {
375 if (!std::isfinite(envObj.prob_env[e]) || envObj.prob_env[e] < 0.0) usable =
false;
376 else wsum += envObj.prob_env[e];
379 if (usable && wsum > 0.0)
380 for (std::size_t e = 0; e < E; ++e) w[e] = envObj.prob_env[e] / wsum;
382 const std::size_t n = state_count(0);
383 Matrix<T> Qbar(n, n, num_traits<T>::from_double(0.0));
384 for (std::size_t e = 0; e < E; ++e) {
385 const Matrix<T>& Qe = gen(e);
386 const T we = num_traits<T>::from_double(w[e]);
387 for (std::size_t i = 0; i < n; ++i)
388 for (std::size_t j = 0; j < n; ++j) Qbar(i, j) += we * Qe(i, j);
395 std::vector<T> pi0(n, num_traits<T>::from_double(0.0));
396 for (std::size_t e = 0; e < E; ++e) {
397 const T we = num_traits<T>::from_double(w[e]);
398 for (std::size_t i = 0; i < n; ++i) pi0[i] += we * own[e][i];
403 for (std::size_t e = 0; e < E; ++e) {
404 pi_enter[e] = shared.empty() ? own[e] : shared;
409 const Matrix<T>& gen(std::size_t e)
const {
410 return mam_backend ? mam_flat[e].Q : stages[e].chain.Q;
414 std::size_t state_count(std::size_t e)
const {
415 return mam_backend ? mam_flat[e].levelOf.size() : stages[e].chain.space.size();
422 void analyze(std::size_t e) {
423 const std::size_t E = envObj.nstages();
424 const Matrix<T>& Q = gen(e);
425 const std::vector<T> pi0 = pi_enter[e];
433 std::vector<T> avg, ex;
434 time_average(pi0, Q, dvals[e], avg, ex);
435 pi_exit[e].assign(E, std::vector<T>());
436 for (std::size_t h = 0; h < E; ++h)
437 if (envObj.arc(e, h).enabled) pi_exit[e][h] = ex;
443 if (exp_sojourn(e, s_e)) {
448 const std::vector<T> res = resolvent(pi0, Q, s_e);
449 pi_exit[e].assign(E, std::vector<T>());
450 for (std::size_t h = 0; h < E; ++h)
451 if (envObj.arc(e, h).enabled) pi_exit[e][h] = res;
458 if constexpr (!num_traits<T>::has_transcendental) {
460 "SolverENV statevec: a non-exponential environment sojourn needs the transient "
461 "pi0 exp(Qt) from ctmc_transient, which is an adaptive approximation governed by "
462 "a tolerance and has no exact value in rational arithmetic; rerun with "
463 "--arith double, or use exponential transitions, whose resolvent is exact");
465 const mc::TransientResult<T> tr =
467 num_traits<T>::from_double(tspan_end[e]));
468 std::vector<double> t(tr.t.size());
469 for (std::size_t j = 0; j < tr.t.size(); ++j) t[j] = num_traits<T>::to_double(tr.t[j]);
471 pi_exit[e].assign(E, std::vector<T>());
472 for (std::size_t h = 0; h < E; ++h)
473 pi_exit[e][h] = stieltjes(tr.pi, cdf_weights(envObj.proc[e][h].map(), t));
475 const std::vector<T> avg =
476 stieltjes(tr.pi, cdf_weights(envObj.hold_time[e].map(), t));
482 const std::size_t last = tr.pi.rows() - 1, n = tr.pi.cols();
483 std::vector<T> tail(n);
484 for (std::size_t j = 0; j < n; ++j) tail[j] = tr.pi(last, j);
485 pi_timeavg[e] = tail;
495 const std::size_t E = envObj.nstages();
496 pi_enter_prev = pi_enter;
497 std::vector<std::vector<T>> next(E);
499 for (std::size_t e = 0; e < E; ++e) {
500 const std::size_t n = state_count(e);
501 std::vector<T> acc(n, num_traits<T>::from_int(0));
503 for (std::size_t h = 0; h < E; ++h) {
504 const double po = envObj.prob_orig(h, e);
505 if (!(po > 0.0))
continue;
506 if (pi_exit[h].size() <= e || pi_exit[h][e].empty())
continue;
507 const std::vector<T> pex = reset_apply(h, e, pi_exit[h][e]);
510 "SolverENV statevec: reset_state[" + std::to_string(h) +
"][" +
511 std::to_string(e) +
"] returned a " + std::to_string(pex.size()) +
512 "-element vector but stage " + std::to_string(e + 1) +
" has " +
514 " states; supply a reset that maps the state space of stage " +
515 std::to_string(h + 1) +
" onto that of stage " + std::to_string(e + 1));
516 const T w = num_traits<T>::from_double(po);
517 for (std::size_t s = 0; s < n; ++s) acc[s] += T(w * pex[s]);
521 const T w = num_traits<T>::from_double(wsum);
522 for (std::size_t s = 0; s < n; ++s) acc[s] = T(acc[s] / w);
526 next[e] = normalized(acc);
536 bool converged()
const {
537 const std::size_t E = envObj.nstages();
539 for (std::size_t e = 0; e < E; ++e) {
540 const std::vector<T>& a = pi_enter[e];
541 const std::vector<T>& b = pi_enter_prev[e];
542 if (a.empty() || b.empty() || a.size() != b.size())
return false;
544 for (std::size_t s = 0; s < a.size(); ++s)
545 d += std::fabs(num_traits<T>::to_double(a[s]) - num_traits<T>::to_double(b[s]));
546 l1 = std::max(l1, d);
548 if (!std::isfinite(l1))
return false;
549 return l1 < opt.iter_tol;
556 void finish(EnvStatevecSolution<T>& out) {
557 const std::size_t E = envObj.nstages();
558 const T zero = num_traits<T>::from_int(0);
562 out.QStage.assign(E, Matrix<T>(M, K, zero));
563 out.UStage.assign(E, Matrix<T>(M, K, zero));
564 out.TStage.assign(E, Matrix<T>(M, K, zero));
566 for (std::size_t e = 0; e < E; ++e) {
567 if (pi_timeavg[e].empty())
continue;
568 Matrix<T> QNe, UNe, TNe;
572 const mam::LdqbdAvg<T> a =
582 envObj.stage(e).model, stages[e].chain, pi_timeavg[e],
false);
590 const T p = num_traits<T>::from_double(envObj.prob_env[e]);
591 for (std::size_t i = 0; i < M; ++i)
592 for (std::size_t r = 0; r < K && r < QNe.cols(); ++r) {
593 out.QN(i, r) += T(p * QNe(i, r));
594 out.UN(i, r) += T(p * UNe(i, r));
595 out.TN(i, r) += T(p * TNe(i, r));
598 out.pi_enter = pi_enter;
599 out.pi_timeavg = pi_timeavg;
612 void cache_blend(EnvStatevecSolution<T>& out)
const {
617 if (mam_backend)
return;
618 const std::size_t E = envObj.nstages();
619 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
620 const T zero = num_traits<T>::from_int(0);
623 std::vector<T>(), std::vector<T>(), Matrix<T>(),
624 Matrix<T>(), std::vector<T>());
625 for (std::size_t c = 0; c < out.cache.caches.size(); ++c) {
626 const std::size_t ind = out.cache.caches[c].node;
627 const std::size_t isf = sn1.stateful_index(ind);
628 if (isf == 0)
continue;
629 std::vector<T> hitT(K, zero), missT(K, zero);
630 for (std::size_t e = 0; e < E; ++e) {
631 if (pi_timeavg[e].empty())
continue;
632 const std::vector<T> pv = normalized(pi_timeavg[e]);
633 const qn::NetworkStruct<T>& sne = envObj.stage(e).model;
634 const auto it = sne.nodeparam.find(ind);
635 if (it == sne.nodeparam.end())
continue;
636 const qn::CacheParam<T>& np = it->second;
637 const T w = num_traits<T>::from_double(envObj.prob_env[e]);
638 const auto& dr = stages[e].chain.dep_rates;
639 for (std::size_t k = 0; k < K && k < np.hitclass.size(); ++k) {
640 const std::size_t hc = np.hitclass[k];
641 const std::size_t mc = k < np.missclass.size() ? np.missclass[k] : 0;
642 if (hc == 0 || mc == 0)
continue;
643 for (std::size_t s = 0; s < pv.size(); ++s) {
644 hitT[k] += T(w * pv[s] * dr[s][isf - 1][hc - 1]);
645 missT[k] += T(w * pv[s] * dr[s][isf - 1][mc - 1]);
649 const T nan = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
650 std::vector<T> hp(K, nan), mp(K, nan);
651 for (std::size_t k = 0; k < K; ++k) {
652 const T tot = T(hitT[k] + missT[k]);
653 if (num_traits<T>::to_double(tot) > 0) {
654 hp[k] = T(hitT[k] / tot);
655 mp[k] = T(missT[k] / tot);
658 out.cache.caches[c].hitprob = hp;
659 out.cache.caches[c].missprob = mp;
666 bool exp_sojourn(std::size_t e,
double& s)
const {
667 const std::size_t E = envObj.nstages();
670 for (std::size_t h = 0; h < E; ++h) {
671 const EnvArc<T>& a = envObj.arc(e, h);
672 if (!a.enabled)
continue;
674 s += num_traits<T>::to_double(a.dist.D1(0, 0));
677 return any && s > 0.0;
681 static std::vector<T> resolvent(
const std::vector<T>& pi0,
const Matrix<T>& Q,
double s) {
682 const std::size_t n = Q.rows();
683 const T sT = num_traits<T>::from_double(s);
684 Matrix<T> A(n, n, num_traits<T>::from_int(0));
685 for (std::size_t i = 0; i < n; ++i)
686 for (std::size_t j = 0; j < n; ++j)
687 A(j, i) = T((i == j ? sT : num_traits<T>::from_int(0)) - Q(i, j));
689 for (std::size_t i = 0; i < n; ++i) b[i] = T(sT * pi0[i]);
694 static void time_average(
const std::vector<T>& pi0,
const Matrix<T>& Q,
double d,
695 std::vector<T>& avg, std::vector<T>& ex) {
696 if constexpr (!num_traits<T>::has_transcendental) {
698 "SolverENV statevec: a deterministic sojourn needs ctmc_timeaverage, whose "
699 "uniformization carries Poisson weights exp(-qt) that are not rational; rerun "
700 "with --arith double");
702 const mc::TimeAverageResult<T> r =
717 static std::vector<double> cdf_weights(
const mam::Map<double>& m,
718 const std::vector<double>& t) {
719 std::vector<double> w(t.size(), 0.0);
720 if (t.size() < 2)
return w;
722 bool all_zero =
true;
723 for (std::size_t a = 0; a < m.D1.rows() && all_zero; ++a)
724 for (std::size_t b = 0; b < m.D1.cols() && all_zero; ++b)
725 if (m.D1(a, b) != 0.0) all_zero =
false;
726 if (all_zero)
return w;
728 for (std::size_t j = 1; j < t.size(); ++j) w[j] = F[j] - F[j - 1];
733 static std::vector<T> stieltjes(
const Matrix<T>& pit,
const std::vector<double>& w) {
736 if (std::isnan(v))
return std::vector<T>();
739 if (!(sw > 0.0))
return std::vector<T>();
740 const std::size_t n = pit.cols();
741 std::vector<T> out(n, num_traits<T>::from_int(0));
742 for (std::size_t j = 0; j < w.size() && j < pit.rows(); ++j) {
743 if (w[j] == 0.0)
continue;
744 const T wj = num_traits<T>::from_double(w[j] / sw);
745 for (std::size_t s = 0; s < n; ++s) out[s] += T(wj * pit(j, s));
752 std::vector<T> reset_apply(std::size_t h, std::size_t e,
const std::vector<T>& p)
const {
753 if (h < opt.reset_state.size() && e < opt.reset_state[h].size() && opt.reset_state[h][e])
754 return opt.reset_state[h][e](p);
759 static std::vector<T> normalized(
const std::vector<T>& p) {
760 const T zero = num_traits<T>::from_int(0);
761 std::vector<T> q = p;
763 for (std::size_t s = 0; s < q.size(); ++s) {
764 if (num_traits<T>::to_double(q[s]) < 0) q[s] = zero;
767 if (num_traits<T>::to_double(tot) > 0)
768 for (std::size_t s = 0; s < q.size(); ++s) q[s] = T(q[s] / tot);
772 Environment<T>& envObj;
773 EnvStatevecOptions<T> opt;
774 std::size_t M = 0, K = 0;
775 bool det_sojourn =
false;
776 std::vector<double> dvals, tspan_end;
777 std::vector<ctmc::CtmcSolution<T>> stages;
778 bool mam_backend =
false;
779 std::vector<mam::LdqbdBlocks<T>> mam_ld;
780 std::vector<mam::LdqbdFlat<T>> mam_flat;
781 std::vector<std::vector<T>> pi_enter, pi_enter_prev, pi_timeavg;
782 std::vector<std::vector<std::vector<T>>> pi_exit;