207 const std::size_t E = envObj.nstages();
212 for (it = 1; it <= opt.iter_max; ++it) {
213 for (std::size_t e = 0; e < E; ++e) analyze(e);
227 mam_backend = (
opt.stage_solver ==
"mam");
228 if (!mam_backend &&
opt.stage_solver !=
"ctmc")
230 "SolverENV statevec: stage solver '" +
opt.stage_solver +
231 "' is not available; the state-vector coupling needs an EXPLICIT generator over a "
232 "state space it can propagate a distribution across, which SolverCTMC exposes by "
233 "enumeration and SolverMAM by flattening its level-dependent QBD blocks");
234 if (
opt.sojourn !=
"stochastic" &&
opt.sojourn !=
"deterministic")
235 throw InputError(
"SolverENV statevec: unknown sojourn '" +
opt.sojourn +
"'");
243 envObj.reject_lqn_stages(
244 "SolverENV statevec",
245 "the state-vector coupling propagates a joint distribution over ONE stage "
246 "generator, which a layered model does not have -- it decomposes into a network "
249 const std::size_t E = envObj.nstages();
250 M = envObj.stage(0).model.nstations;
251 K = envObj.stage(0).model.nclasses;
252 for (std::size_t e = 1; e < E; ++e)
253 if (envObj.stage(e).model.nstations != M || envObj.stage(e).model.nclasses != K)
255 "SolverENV statevec: every stage must have the same stations and classes; the "
256 "metrics are blended entrywise across them");
260 tspan_end.assign(E,
opt.timespan_end);
261 for (std::size_t e = 0; e < E; ++e) {
262 if (e <
opt.stage_timespan_end.size()) tspan_end[e] =
opt.stage_timespan_end[e];
263 if (!std::isfinite(tspan_end[e]) || !(tspan_end[e] >
opt.timespan_start))
265 "SolverENV statevec: the statevec analyzer requires a finite inner-solver "
266 "timespan for stage " +
267 std::to_string(e + 1) +
", e.g. CTMC(model,'timespan',[0,T])");
270 det_sojourn = (
opt.sojourn ==
"deterministic");
274 pi_enter.assign(E, std::vector<T>());
275 pi_enter_prev.assign(E, std::vector<T>());
276 pi_exit.assign(E, std::vector<std::vector<T>>());
277 pi_timeavg.assign(E, std::vector<T>());
278 dvals.assign(E, 0.0);
280 for (std::size_t e = 0; e < E; ++e)
281 dvals[e] = std::max(
mam::map_mean(envObj.hold_time[e].map()),
282 std::numeric_limits<double>::epsilon());
298 const std::size_t E = envObj.nstages();
299 for (std::size_t e = 0; e < E; ++e) {
307 mo.method =
"default";
308 mo.cutoff = opt.mam_cutoff;
315 seed_entry_distributions();
316 pi_enter_prev = pi_enter;
341 void seed_entry_distributions() {
342 const std::size_t E = envObj.nstages();
351 std::vector<std::vector<T>> own(E);
352 for (std::size_t e = 0; e < E; ++e) {
356 : normalized(stages[e].pi);
359 bool sameSpace = E > 1;
360 for (std::size_t e = 1; e < E && sameSpace; ++e)
361 sameSpace = (state_count(e) == state_count(0));
363 std::vector<T> shared;
365 std::vector<double> w(E, 1.0 /
static_cast<double>(E));
367 bool usable = envObj.prob_env.size() == E;
368 for (std::size_t e = 0; e < E && usable; ++e) {
369 if (!std::isfinite(envObj.prob_env[e]) || envObj.prob_env[e] < 0.0) usable =
false;
370 else wsum += envObj.prob_env[e];
373 if (usable && wsum > 0.0)
374 for (std::size_t e = 0; e < E; ++e) w[e] = envObj.prob_env[e] / wsum;
376 const std::size_t n = state_count(0);
377 Matrix<T> Qbar(n, n, num_traits<T>::from_double(0.0));
378 for (std::size_t e = 0; e < E; ++e) {
379 const Matrix<T>& Qe = gen(e);
380 const T we = num_traits<T>::from_double(w[e]);
381 for (std::size_t i = 0; i < n; ++i)
382 for (std::size_t j = 0; j < n; ++j) Qbar(i, j) += we * Qe(i, j);
389 std::vector<T> pi0(n, num_traits<T>::from_double(0.0));
390 for (std::size_t e = 0; e < E; ++e) {
391 const T we = num_traits<T>::from_double(w[e]);
392 for (std::size_t i = 0; i < n; ++i) pi0[i] += we * own[e][i];
397 for (std::size_t e = 0; e < E; ++e) {
398 pi_enter[e] = shared.empty() ? own[e] : shared;
403 const Matrix<T>& gen(std::size_t e)
const {
404 return mam_backend ? mam_flat[e].Q : stages[e].chain.Q;
408 std::size_t state_count(std::size_t e)
const {
409 return mam_backend ? mam_flat[e].levelOf.size() : stages[e].chain.space.size();
416 void analyze(std::size_t e) {
417 const std::size_t E = envObj.nstages();
418 const Matrix<T>& Q = gen(e);
419 const std::vector<T> pi0 = pi_enter[e];
427 std::vector<T> avg, ex;
428 time_average(pi0, Q, dvals[e], avg, ex);
429 pi_exit[e].assign(E, std::vector<T>());
430 for (std::size_t h = 0; h < E; ++h)
431 if (envObj.arc(e, h).enabled) pi_exit[e][h] = ex;
437 if (exp_sojourn(e, s_e)) {
442 const std::vector<T> res = resolvent(pi0, Q, s_e);
443 pi_exit[e].assign(E, std::vector<T>());
444 for (std::size_t h = 0; h < E; ++h)
445 if (envObj.arc(e, h).enabled) pi_exit[e][h] = res;
452 if constexpr (!num_traits<T>::has_transcendental) {
454 "SolverENV statevec: a non-exponential environment sojourn needs the transient "
455 "pi0 exp(Qt) from ctmc_transient, which is an adaptive approximation governed by "
456 "a tolerance and has no exact value in rational arithmetic; rerun with "
457 "--arith double, or use exponential transitions, whose resolvent is exact");
459 const mc::TransientResult<T> tr =
461 num_traits<T>::from_double(tspan_end[e]));
462 std::vector<double> t(tr.t.size());
463 for (std::size_t j = 0; j < tr.t.size(); ++j) t[j] = num_traits<T>::to_double(tr.t[j]);
465 pi_exit[e].assign(E, std::vector<T>());
466 for (std::size_t h = 0; h < E; ++h)
467 pi_exit[e][h] = stieltjes(tr.pi, cdf_weights(envObj.proc[e][h].map(), t));
469 const std::vector<T> avg =
470 stieltjes(tr.pi, cdf_weights(envObj.hold_time[e].map(), t));
476 const std::size_t last = tr.pi.rows() - 1, n = tr.pi.cols();
477 std::vector<T> tail(n);
478 for (std::size_t j = 0; j < n; ++j) tail[j] = tr.pi(last, j);
479 pi_timeavg[e] = tail;
489 const std::size_t E = envObj.nstages();
490 pi_enter_prev = pi_enter;
491 std::vector<std::vector<T>> next(E);
493 for (std::size_t e = 0; e < E; ++e) {
494 const std::size_t n = state_count(e);
495 std::vector<T> acc(n, num_traits<T>::from_int(0));
497 for (std::size_t h = 0; h < E; ++h) {
498 const double po = envObj.prob_orig(h, e);
499 if (!(po > 0.0))
continue;
500 if (pi_exit[h].size() <= e || pi_exit[h][e].empty())
continue;
501 const std::vector<T> pex = reset_apply(h, e, pi_exit[h][e]);
504 "SolverENV statevec: reset_state[" + std::to_string(h) +
"][" +
505 std::to_string(e) +
"] returned a " + std::to_string(pex.size()) +
506 "-element vector but stage " + std::to_string(e + 1) +
" has " +
508 " states; supply a reset that maps the state space of stage " +
509 std::to_string(h + 1) +
" onto that of stage " + std::to_string(e + 1));
510 const T w = num_traits<T>::from_double(po);
511 for (std::size_t s = 0; s < n; ++s) acc[s] += T(w * pex[s]);
515 const T w = num_traits<T>::from_double(wsum);
516 for (std::size_t s = 0; s < n; ++s) acc[s] = T(acc[s] / w);
520 next[e] = normalized(acc);
530 bool converged()
const {
531 const std::size_t E = envObj.nstages();
533 for (std::size_t e = 0; e < E; ++e) {
534 const std::vector<T>& a = pi_enter[e];
535 const std::vector<T>& b = pi_enter_prev[e];
536 if (a.empty() || b.empty() || a.size() != b.size())
return false;
538 for (std::size_t s = 0; s < a.size(); ++s)
539 d += std::fabs(num_traits<T>::to_double(a[s]) - num_traits<T>::to_double(b[s]));
540 l1 = std::max(l1, d);
542 if (!std::isfinite(l1))
return false;
543 return l1 < opt.iter_tol;
550 void finish(EnvStatevecSolution<T>& out) {
551 const std::size_t E = envObj.nstages();
552 const T zero = num_traits<T>::from_int(0);
556 out.QStage.assign(E, Matrix<T>(M, K, zero));
557 out.UStage.assign(E, Matrix<T>(M, K, zero));
558 out.TStage.assign(E, Matrix<T>(M, K, zero));
560 for (std::size_t e = 0; e < E; ++e) {
561 if (pi_timeavg[e].empty())
continue;
562 Matrix<T> QNe, UNe, TNe;
566 const mam::LdqbdAvg<T> a =
573 envObj.stage(e).model, stages[e].chain, pi_timeavg[e]);
581 const T p = num_traits<T>::from_double(envObj.prob_env[e]);
582 for (std::size_t i = 0; i < M; ++i)
583 for (std::size_t r = 0; r < K && r < QNe.cols(); ++r) {
584 out.QN(i, r) += T(p * QNe(i, r));
585 out.UN(i, r) += T(p * UNe(i, r));
586 out.TN(i, r) += T(p * TNe(i, r));
589 out.pi_enter = pi_enter;
590 out.pi_timeavg = pi_timeavg;
603 void cache_blend(EnvStatevecSolution<T>& out)
const {
608 if (mam_backend)
return;
609 const std::size_t E = envObj.nstages();
610 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
611 const T zero = num_traits<T>::from_int(0);
613 for (
const auto& kv : sn1.nodeparam) {
614 const std::size_t ind = kv.first;
615 const std::size_t isf = sn1.stateful_index(ind);
616 if (isf == 0)
continue;
617 std::vector<T> hitT(K, zero), missT(K, zero);
618 for (std::size_t e = 0; e < E; ++e) {
619 if (pi_timeavg[e].empty())
continue;
620 const std::vector<T> pv = normalized(pi_timeavg[e]);
621 const qn::NetworkStruct<T>& sne = envObj.stage(e).model;
622 const auto it = sne.nodeparam.find(ind);
623 if (it == sne.nodeparam.end())
continue;
624 const qn::CacheParam<T>& np = it->second;
625 const T w = num_traits<T>::from_double(envObj.prob_env[e]);
626 const auto& dr = stages[e].chain.dep_rates;
627 for (std::size_t k = 0; k < K && k < np.hitclass.size(); ++k) {
628 const std::size_t hc = np.hitclass[k];
629 const std::size_t mc = k < np.missclass.size() ? np.missclass[k] : 0;
630 if (hc == 0 || mc == 0)
continue;
631 for (std::size_t s = 0; s < pv.size(); ++s) {
632 hitT[k] += T(w * pv[s] * dr[s][isf - 1][hc - 1]);
633 missT[k] += T(w * pv[s] * dr[s][isf - 1][mc - 1]);
637 const T nan = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
638 std::vector<T> hp(K, nan), mp(K, nan);
639 for (std::size_t k = 0; k < K; ++k) {
640 const T tot = T(hitT[k] + missT[k]);
641 if (num_traits<T>::to_double(tot) > 0) {
642 hp[k] = T(hitT[k] / tot);
643 mp[k] = T(missT[k] / tot);
646 out.hit_prob[ind] = hp;
647 out.miss_prob[ind] = mp;
654 bool exp_sojourn(std::size_t e,
double& s)
const {
655 const std::size_t E = envObj.nstages();
658 for (std::size_t h = 0; h < E; ++h) {
659 const EnvArc<T>& a = envObj.arc(e, h);
660 if (!a.enabled)
continue;
662 s += num_traits<T>::to_double(a.dist.D1(0, 0));
665 return any && s > 0.0;
669 static std::vector<T> resolvent(
const std::vector<T>& pi0,
const Matrix<T>& Q,
double s) {
670 const std::size_t n = Q.rows();
671 const T sT = num_traits<T>::from_double(s);
672 Matrix<T> A(n, n, num_traits<T>::from_int(0));
673 for (std::size_t i = 0; i < n; ++i)
674 for (std::size_t j = 0; j < n; ++j)
675 A(j, i) = T((i == j ? sT : num_traits<T>::from_int(0)) - Q(i, j));
677 for (std::size_t i = 0; i < n; ++i) b[i] = T(sT * pi0[i]);
682 static void time_average(
const std::vector<T>& pi0,
const Matrix<T>& Q,
double d,
683 std::vector<T>& avg, std::vector<T>& ex) {
684 if constexpr (!num_traits<T>::has_transcendental) {
686 "SolverENV statevec: a deterministic sojourn needs ctmc_timeaverage, whose "
687 "uniformization carries Poisson weights exp(-qt) that are not rational; rerun "
688 "with --arith double");
690 const mc::TimeAverageResult<T> r =
705 static std::vector<double> cdf_weights(
const mam::Map<double>& m,
706 const std::vector<double>& t) {
707 std::vector<double> w(t.size(), 0.0);
708 if (t.size() < 2)
return w;
710 bool all_zero =
true;
711 for (std::size_t a = 0; a < m.D1.rows() && all_zero; ++a)
712 for (std::size_t b = 0; b < m.D1.cols() && all_zero; ++b)
713 if (m.D1(a, b) != 0.0) all_zero =
false;
714 if (all_zero)
return w;
716 for (std::size_t j = 1; j < t.size(); ++j) w[j] = F[j] - F[j - 1];
721 static std::vector<T> stieltjes(
const Matrix<T>& pit,
const std::vector<double>& w) {
724 if (std::isnan(v))
return std::vector<T>();
727 if (!(sw > 0.0))
return std::vector<T>();
728 const std::size_t n = pit.cols();
729 std::vector<T> out(n, num_traits<T>::from_int(0));
730 for (std::size_t j = 0; j < w.size() && j < pit.rows(); ++j) {
731 if (w[j] == 0.0)
continue;
732 const T wj = num_traits<T>::from_double(w[j] / sw);
733 for (std::size_t s = 0; s < n; ++s) out[s] += T(wj * pit(j, s));
740 std::vector<T> reset_apply(std::size_t h, std::size_t e,
const std::vector<T>& p)
const {
741 if (h < opt.reset_state.size() && e < opt.reset_state[h].size() && opt.reset_state[h][e])
742 return opt.reset_state[h][e](p);
747 static std::vector<T> normalized(
const std::vector<T>& p) {
748 const T zero = num_traits<T>::from_int(0);
749 std::vector<T> q = p;
751 for (std::size_t s = 0; s < q.size(); ++s) {
752 if (num_traits<T>::to_double(q[s]) < 0) q[s] = zero;
755 if (num_traits<T>::to_double(tot) > 0)
756 for (std::size_t s = 0; s < q.size(); ++s) q[s] = T(q[s] / tot);
760 Environment<T>& envObj;
761 EnvStatevecOptions<T> opt;
762 std::size_t M = 0, K = 0;
763 bool det_sojourn =
false;
764 std::vector<double> dvals, tspan_end;
765 std::vector<ctmc::CtmcSolution<T>> stages;
766 bool mam_backend =
false;
767 std::vector<mam::LdqbdBlocks<T>> mam_ld;
768 std::vector<mam::LdqbdFlat<T>> mam_flat;
769 std::vector<std::vector<T>> pi_enter, pi_enter_prev, pi_timeavg;
770 std::vector<std::vector<std::vector<T>>> pi_exit;