295 const std::size_t E = envObj.nstages();
302 std::vector<std::vector<double>> qfirst_prev(E), qfirst_curr(E);
304 for (it = 1; it <= opt.iter_max; ++it) {
305 for (std::size_t e = 0; e < E; ++e) analyze(e);
308 qfirst_prev = qfirst_curr;
309 qfirst_curr.assign(E, std::vector<double>());
310 for (std::size_t e = 0; e < E; ++e) {
311 qfirst_curr[e].reserve(M * K);
312 for (std::size_t i = 0; i < M; ++i)
313 for (std::size_t r = 0; r < K; ++r) qfirst_curr[e].push_back(tranQ[e][i][r][0]);
317 for (std::size_t e = 0; e < E && conv; ++e) {
318 const double d = detail::env_maxpe(qfirst_curr[e], qfirst_prev[e]);
319 if (d < 0.0)
continue;
320 if (!std::isfinite(d) || d >= opt.iter_tol) conv =
false;
338 if (
opt.stage_solver ==
"mva" ||
opt.stage_solver ==
"nc")
340 "SolverENV: the mean-field environment coupling integrates each stage over its "
341 "sojourn, so it needs transient averages from the stage solver, which " +
342 std::string(
opt.stage_solver ==
"mva" ?
"SolverMVA" :
"SolverNC") +
343 " (stage 1) does not produce. Use a fluid or CTMC stage solver, or method='dec' "
345 if (
opt.stage_solver !=
"fluid" &&
opt.stage_solver !=
"ctmc")
348 "' is not available; the environment coupling needs a TRANSIENT stage solve and "
349 "only the fluid analyzer and the enumerated CTMC provide one in this port");
351 if (opt.
method ==
"statevec")
353 "SolverENV: the state-vector analyzer (solver_env_statevec_analyzer.m) carries the "
354 "full joint distribution across a switch, which THIS class does not: it is the "
355 "mean-field coupling and carries the marginal means. The state-vector coupling is "
356 "ported as env::SolverEnvStatevec, with its own options and its CTMC stage solver; "
357 "reach it through env::solver_env (env_dispatch.h), which is the analyzer "
358 "selection of SolverENV.init");
359 if (opt.method ==
"avg" || opt.method ==
"dec" || opt.method ==
"occupation")
361 "SolverENV: the closed-form fast/slow environment limits (SolverENV.solveEnvLimit) "
362 "and the occupation weighting (SolverENV.solveEnvOccupation) "
363 "replace this fixed point rather than configure it -- neither carries anything "
364 "across a switch. They are ported as env::SolverEnvLimit, with their own result "
365 "type; reach them through env::solver_env (env_dispatch.h), which is the method "
366 "dispatch of SolverENV.runAnalyzer");
370 smp = (opt.method ==
"smp");
371 statedep = (opt.method ==
"statedep");
381 if (opt.method !=
"meanfield" && opt.method !=
"default" && opt.method !=
"mean"
382 && opt.method !=
"meancov" && opt.method !=
"blend" && opt.method !=
"blending"
383 && opt.method !=
"smp"
385 throw UnsupportedError(ErrorKind{
"Method"},
"SolverENV: unknown method '" + opt.method +
"'");
389 meancov = (opt.method ==
"meancov");
400 std::string sm = opt.stage.method;
401 if (sm.size() > 4 && sm.compare(0, 4,
"fld.") == 0) sm = sm.substr(4);
402 kp_stages = (!ctmc_stages && sm ==
"kp");
412 dae_stages = (!ctmc_stages && !kp_stages && sm ==
"dae");
419 if (!(opt.timespan_end > 0.0) || !std::isfinite(opt.timespan_end))
421 "SolverENV: the stage transient needs a finite positive horizon, "
422 "options.timespan(2); the mean-field coupling integrates each stage's "
423 "TRAJECTORY against the holding-time CDF and has nothing to integrate over an "
425 if (opt.tran_points < 2)
426 throw InputError(
"SolverENV: the transient grid needs at least two points");
427 if (!std::is_same<T, double>::value)
429 "SolverENV: a fluid stage integrates its drift with LSODA, which is double only; "
430 "rerun with --arith double");
434 envObj.require_declared();
435 envObj.refuse_semi_markov(opt.method);
436 if (smp && envObj.is_semi_markov() && opt.stage_solver ==
"fluid" &&
437 !envObj.has_lqn_stages()) {
438 const qn::NetworkStruct<T>& sn1 = envObj.stage(0).model;
439 for (std::size_t ind = 0; ind < sn1.nodes.size(); ++ind)
442 "SolverENV: The mean-field cache fixed point integrates each stage's "
443 "holding time as a phase process inside the cache drift, which a "
444 "semi-Markov stage (a non-Markovian or kernel transition) does not have. "
445 "Fit the transitions to phase-type laws, or use a non-fluid stage solver.");
447 envObj.refuse_absorbing(opt.method);
449 const std::size_t E = envObj.nstages();
451 for (std::size_t e = 1; e < E; ++e)
452 if (envObj.is_lqn(0) && envObj.is_lqn(e) && lnsolv[e]->nlayers() != lnsolv[0]->nlayers())
454 "Stages 1 and " + std::to_string(e + 1) +
" are layered networks whose layers "
455 "differ (a zero-capacity element removes the layers only a trapped reference task "
456 "reaches), and method '" + opt.method +
"' couples the stages layer by layer. Use "
457 "method 'occupation'.");
460 for (std::size_t e = 1; e < E; ++e)
461 if (stage_M(e) != M || stage_K(e) != K)
463 "SolverENV: every stage must have the same stations and classes; the metrics "
464 "are blended entrywise across them. A LAYERED stage counts the block-diagonal "
465 "union of the layers SolverLN builds for it, which is what layerBlocks "
466 "reports, so two layered stages agree exactly when they have the same layer "
467 "shape -- not merely the same LQN element count");
468 entry.assign(E, Matrix<double>(M, K, 0.0));
469 centry.assign(E, Matrix<double>(M * K, M * K, 0.0));
470 tranC.assign(E, std::vector<Matrix<double>>());
471 tranT.assign(E, std::vector<double>());
472 tranQ.assign(E, std::vector<std::vector<std::vector<double>>>());
473 tranU.assign(E, std::vector<std::vector<std::vector<double>>>());
474 tranTp.assign(E, std::vector<std::vector<std::vector<double>>>());
475 steady.assign(E, StageSteady());
476 steady_asked.assign(E, 0);
477 det_sojourn = (opt.sojourn ==
"deterministic");
478 dvals.assign(E, 0.0);
479 refresh_sojourn_means();
482 for (std::size_t e = 0; e < E; ++e)
483 for (std::size_t h = 0; h < E; ++h)
484 if (envObj.arc(e, h).enabled && envObj.arc(e, h).reset_rates) any =
true;
487 "SolverENV: method 'statedep' updates each environment transition from the "
488 "state its stage is left in, and no arc carries a rate reset "
489 "(Environment::set_env_rate_reset, resetEnvRatesFun in the reference); the "
490 "run would be the mean-field fixed point under a different name");
508 void build_lqn_stages() {
509 const std::size_t E = envObj.nstages();
510 lnsolv.assign(E, std::shared_ptr<ln::SolverLN<T>>());
511 lnblk.assign(E, ln::LnLayerBlocks());
512 if (!envObj.has_lqn_stages())
return;
515 "SolverENV: a LayeredNetwork stage is solved by SolverLN over its layers, not by "
516 "an enumerated CTMC over one stage generator -- an LQN has no single generator to "
517 "enumerate. Leave stage_solver at 'fluid', which names the engine each LAYER is "
518 "integrated with (EnvOptions::lqn.layer_solver)");
519 if (opt.lqn.layer_solver !=
"fluid")
521 "SolverENV: a LayeredNetwork stage is carried across an environment switch by its "
522 "queue lengths, so the coupling needs the stage's TRANSIENT; among the layer "
523 "engines only the fluid one produces one, and this ensemble asks for '" +
524 opt.lqn.layer_solver +
"' layers (EnvOptions::lqn.layer_solver)");
525 for (std::size_t e = 0; e < E; ++e) {
526 if (!envObj.is_lqn(e))
continue;
527 ln::LnOptions lo = opt.lqn;
535 lo.timespan_end = opt.timespan_end;
536 lo.tran_points = opt.tran_points;
537 lo.tran_grid.clear();
538 lnsolv[e] = std::make_shared<ln::SolverLN<T>>(envObj.stage(e).lqn_model, lo);
539 lnblk[e] = lnsolv[e]->layer_blocks();
544 std::size_t stage_M(std::size_t e)
const {
545 return envObj.is_lqn(e) ? lnblk[e].M : envObj.stage(e).model.nstations;
549 std::size_t stage_K(std::size_t e)
const {
550 return envObj.is_lqn(e) ? lnblk[e].K : envObj.stage(e).model.nclasses;
571 void lqn_stage_transient(std::size_t e,
bool seed) {
572 ln::SolverLN<T>& s = *lnsolv[e];
573 s.init_from_marginal(seed ? entry[e] : Matrix<double>());
574 s.set_tran_grid(stage_grid(e));
575 const ln::LnTranSolution tr = s.get_tran_avg();
576 const ln::LnLayerBlocks& b = lnblk[e];
581 if (!tr.layers.empty()) tranT[e] = tr.layers[0].t;
582 const std::size_t
P = std::max<std::size_t>(tranT[e].size(), 1);
583 tranQ[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
584 tranU[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
585 tranTp[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
586 if (tranT[e].empty())
return;
592 for (std::size_t l = 0; l < tr.layers.size(); ++l) {
593 const ln::LnTranLayer& L = tr.layers[l];
594 for (std::size_t i = 0; i < b.msz[l]; ++i)
595 for (std::size_t r = 0; r < b.ksz[l]; ++r) {
596 const std::size_t row = b.roff[l] + i, col = b.coff[l] + r;
597 copy_series(L.QN[i][r], tranQ[e][row][col]);
598 copy_series(L.UN[i][r], tranU[e][row][col]);
599 copy_series(L.TN[i][r], tranTp[e][row][col]);
612 static void copy_series(
const std::vector<double>& src, std::vector<double>& dst) {
613 for (std::size_t j = 0; j < dst.size() && j < src.size(); ++j) dst[j] = src[j];
617 void refresh_sojourn_means() {
618 if (!det_sojourn)
return;
619 for (std::size_t e = 0; e < envObj.nstages(); ++e)
620 dvals[e] = envObj.hold_time_mean(e);
638 const std::size_t E = envObj.nstages();
639 for (std::size_t e = 0; e < E; ++e) {
640 if (envObj.is_lqn(e)) {
644 lqn_stage_transient(e,
false);
645 if (tranT[e].empty())
continue;
646 const std::size_t last = tranT[e].size() - 1;
647 for (std::size_t i = 0; i < M; ++i)
648 for (std::size_t r = 0; r < K; ++r) entry[e](i, r) = tranQ[e][i][r][last];
656 const ctmc::CtmcTransient<T> tr = ctmc_stage_transient(e,
false, std::vector<double>());
657 if (tr.t.empty())
continue;
658 for (std::size_t i = 0; i < M; ++i)
659 for (std::size_t r = 0; r < K; ++r)
660 entry[e](i, r) = num_traits<T>::to_double(tr.QNt[i][r].back());
664 kp_stage_transient(e,
false);
665 if (tranT[e].empty())
continue;
666 const std::size_t last = tranT[e].size() - 1;
667 for (std::size_t i = 0; i < M; ++i)
668 for (std::size_t r = 0; r < K; ++r) entry[e](i, r) = tranQ[e][i][r][last];
671 fluid::FluidOptions fo = opt.stage;
677 const std::vector<fluid::FluidTranPoint> tr =
679 opt.timespan_end, opt.tran_points)
681 opt.timespan_end, opt.tran_points);
682 if (tr.empty())
continue;
683 for (std::size_t i = 0; i < M; ++i)
684 for (std::size_t r = 0; r < K; ++r) entry[e](i, r) = tr.back().
QN(i, r);
689 void analyze(std::size_t e) {
690 if (envObj.is_lqn(e)) {
691 lqn_stage_transient(e,
true);
696 tranQ[e].assign(M, std::vector<std::vector<double>>(K));
697 tranU[e].assign(M, std::vector<std::vector<double>>(K));
698 tranTp[e].assign(M, std::vector<std::vector<double>>(K));
709 const ctmc::CtmcTransient<T> tr = ctmc_stage_transient(e,
true, stage_grid(e));
710 for (std::size_t j = 0; j < tr.t.size(); ++j) {
711 tranT[e].push_back(num_traits<T>::to_double(tr.t[j]));
712 for (std::size_t i = 0; i < M; ++i)
713 for (std::size_t r = 0; r < K; ++r) {
714 tranQ[e][i][r].push_back(num_traits<T>::to_double(tr.QNt[i][r][j]));
715 tranU[e][i][r].push_back(num_traits<T>::to_double(tr.UNt[i][r][j]));
716 tranTp[e][i][r].push_back(num_traits<T>::to_double(tr.TNt[i][r][j]));
721 const qn::NetworkStruct<T>& sn = envObj.stage(e).model;
723 kp_stage_transient(e,
true);
726 fluid::FluidOptions fo = opt.stage;
727 fo.init_sol = initsol_from_marginal(sn, entry[e]);
732 if (meancov && dae_stages) fo.init_qcov = centry[e];
733 const std::vector<fluid::FluidTranPoint> tr =
735 opt.tran_points, stage_grid(e))
737 opt.tran_points, stage_grid(e));
738 for (
const fluid::FluidTranPoint& p : tr) {
739 tranT[e].push_back(p.t);
740 for (std::size_t i = 0; i < M; ++i)
741 for (std::size_t r = 0; r < K; ++r) {
742 tranQ[e][i][r].push_back(p.QN(i, r));
743 tranU[e][i][r].push_back(p.UN(i, r));
744 tranTp[e][i][r].push_back(p.TN(i, r));
746 if (meancov && dae_stages && p.QCov.rows() == M * K) tranC[e].push_back(p.QCov);
751 if (tranC[e].size() != tranT[e].size()) tranC[e].clear();
770 void kp_stage_transient(std::size_t e,
bool seed) {
773 const qn::NetworkStruct<T>& sn = envObj.stage(e).model;
774 fluid::FluidOptions fo = opt.stage;
777 fo.timespan_end = opt.timespan_end;
779 fo.init_qlen = entry[e];
780 if (meancov) fo.init_qcov = centry[e];
782 fluid::FluidKpTransient tr;
785 const std::size_t
P = tr.t.size();
786 tranQ[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
787 tranU[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
788 tranTp[e].assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
792 for (std::size_t n = 0; n <
P; ++n)
793 for (std::size_t i = 0; i < M; ++i)
794 for (std::size_t r = 0; r < K; ++r) {
795 tranQ[e][i][r][n] = tr.QN[n](i, r);
796 tranU[e][i][r][n] = tr.UN[n](i, r);
797 tranTp[e][i][r][n] = tr.TN[n](i, r);
799 if (meancov) tranC[e] = tr.QCov;
818 ctmc::CtmcTransient<T> ctmc_stage_transient(std::size_t e,
bool seed,
819 const std::vector<double>& grid)
const {
820 qn::NetworkStruct<T> sn = envObj.stage(e).model;
824 if (seed) seed_ctmc_state(sn, entry[e]);
826 g.reserve(grid.size());
827 for (std::size_t j = 0; j < grid.size(); ++j) g.push_back(num_traits<T>::from_double(grid[j]));
829 sn, ctmc_stage_options(), num_traits<T>::from_int(0),
830 num_traits<T>::from_double(opt.timespan_end), g);
834 ctmc::CtmcOptions ctmc_stage_options()
const {
835 ctmc::CtmcOptions co;
836 co.cutoff = opt.stage_cutoff;
837 co.stiff = opt.stage_stiff;
849 void seed_ctmc_state(qn::NetworkStruct<T>& sn,
const Matrix<double>& Q)
const {
850 if (Q.empty())
return;
851 const std::vector<std::vector<std::size_t>> nir = round_marginal(sn, Q);
852 for (std::size_t i = 0; i < sn.nstations && i < nir.size(); ++i) {
853 const std::size_t ind = sn.station_to_node[i];
858 std::vector<std::size_t> ph(sn.nclasses, 1);
859 for (std::size_t r = 0; r < sn.nclasses; ++r) ph[r] = sn.phasessz_of(i + 1, r + 1);
863 Matrix<T> space(1, row.size());
864 for (std::size_t c = 0; c < row.size(); ++c) space(0, c) = row[c];
865 sn.statespace[ind] = space;
866 sn.stateprior[ind] = std::vector<T>(1, num_traits<T>::from_int(1));
879 std::vector<std::vector<std::size_t>> round_marginal(
const qn::NetworkStruct<T>& sn,
880 const Matrix<double>& Q)
const {
881 std::vector<std::vector<std::size_t>> n(sn.nstations, std::vector<std::size_t>(sn.nclasses, 0));
882 for (std::size_t r = 0; r < sn.nclasses; ++r) {
883 const double pop = sn.classes[r].population;
884 std::vector<double> frac(sn.nstations, 0.0);
886 for (std::size_t i = 0; i < sn.nstations; ++i) {
887 const double q = (i < Q.rows() && r < Q.cols()) ? std::max(0.0, Q(i, r)) : 0.0;
888 const double fl = std::floor(q);
889 n[i][r] =
static_cast<std::size_t
>(fl);
891 placed +=
static_cast<long>(fl);
893 if (!std::isfinite(pop))
continue;
894 long want =
static_cast<long>(std::llround(pop));
895 while (placed < want) {
896 std::size_t best = 0;
898 for (std::size_t i = 0; i < sn.nstations; ++i)
899 if (frac[i] > bv) { bv = frac[i]; best = i; }
905 while (placed > want) {
906 std::size_t best = 0;
909 for (std::size_t i = 0; i < sn.nstations; ++i)
910 if (n[i][r] > 0 && frac[i] < bv) { bv = frac[i]; best = i; any =
true; }
922 Matrix<double> QN, UN, TN;
968 const StageSteady& stage_steady(std::size_t e) {
969 if (steady_asked[e])
return steady[e];
971 StageSteady& out = steady[e];
972 out.QN = Matrix<double>(M, K, 0.0);
973 out.UN = Matrix<double>(M, K, 0.0);
974 out.TN = Matrix<double>(M, K, 0.0);
975 if (envObj.is_lqn(e))
return out;
976 const qn::NetworkStruct<T>& sn = envObj.stage(e).model;
979 copy_finite(a.QN, out.QN);
980 copy_finite(a.UN, out.UN);
981 copy_finite(a.TN, out.TN);
984 fluid::FluidOptions fo = opt.stage;
988 fo.init_qlen = Matrix<double>();
989 fo.init_qcov = Matrix<double>();
990 fo.timespan_end = std::numeric_limits<double>::infinity();
991 fluid::FluidSolution s;
995 }
else if (dae_stages) {
999 fo.method =
"closing";
1002 copy_finite(s.QN, out.QN);
1003 copy_finite(s.UN, out.UN);
1004 copy_finite(s.TN, out.TN);
1017 static void copy_finite(
const Matrix<S>& src, Matrix<double>& dst) {
1018 for (std::size_t i = 0; i < dst.rows(); ++i)
1019 for (std::size_t r = 0; r < dst.cols(); ++r) {
1020 const double v = num_traits<S>::to_double(src(i, r));
1021 if (std::isfinite(v)) dst(i, r) = v;
1050 void stage_exit(std::size_t e,
bool want_all, Matrix<double>& Qe, Matrix<double>& Ue,
1051 Matrix<double>& Te,
bool report =
false) {
1052 std::vector<double> w;
1054 if (!tranT[e].empty() && !det_sojourn) {
1055 w = cdf_weights(e, tranT[e]);
1056 for (
double v : w) wsum += v;
1057 if (report && wsum > 0.0) {
1060 w = sojourn_avg_weights(e, tranT[e]);
1062 for (
double v : w) wsum += v;
1065 if (tranT[e].empty() || (!det_sojourn && !(wsum > 0.0))) {
1066 const StageSteady& st = stage_steady(e);
1074 for (std::size_t i = 0; i < M; ++i)
1075 for (std::size_t r = 0; r < K; ++r) {
1080 Qe(i, r) = detail::env_det_avg(tranT[e], tranQ[e][i][r], dvals[e]);
1081 if (!want_all)
continue;
1082 Ue(i, r) = detail::env_det_avg(tranT[e], tranU[e][i][r], dvals[e]);
1083 Te(i, r) = detail::env_det_avg(tranT[e], tranTp[e][i][r], dvals[e]);
1086 Qe(i, r) = detail::env_det_eval(tranT[e], tranQ[e][i][r], dvals[e]);
1087 if (!want_all)
continue;
1088 Ue(i, r) = detail::env_det_eval(tranT[e], tranU[e][i][r], dvals[e]);
1089 Te(i, r) = detail::env_det_eval(tranT[e], tranTp[e][i][r], dvals[e]);
1092 Qe(i, r) = weighted(tranQ[e][i][r], w, wsum);
1093 if (!want_all)
continue;
1094 Ue(i, r) = weighted(tranU[e][i][r], w, wsum);
1095 Te(i, r) = weighted(tranTp[e][i][r], w, wsum);
1104 const std::size_t E = envObj.nstages();
1105 std::vector<std::vector<Matrix<double>>> Qexit(
1106 E, std::vector<Matrix<double>>(E, Matrix<double>(M, K, 0.0)));
1110 std::vector<std::vector<Matrix<double>>> Uexit, Texit;
1112 Uexit.assign(E, std::vector<Matrix<double>>(E, Matrix<double>(M, K, 0.0)));
1113 Texit.assign(E, std::vector<Matrix<double>>(E, Matrix<double>(M, K, 0.0)));
1115 for (std::size_t e = 0; e < E; ++e) {
1120 Matrix<double> Qd(M, K, 0.0), Ud(M, K, 0.0), Td(M, K, 0.0);
1121 stage_exit(e, statedep, Qd, Ud, Td);
1122 for (std::size_t h = 0; h < E; ++h) {
1124 if (!statedep)
continue;
1128 if (dest_resolved(e)) exit_by_destination(e, Qexit, Uexit, Texit);
1135 const std::size_t n2 = M * K;
1136 std::vector<Matrix<double>> Cexit;
1138 Cexit.assign(E, Matrix<double>(n2, n2, 0.0));
1139 for (std::size_t e = 0; e < E; ++e)
1140 if (!tranT[e].empty()) Cexit[e] = stage_exit_cov(e);
1143 for (std::size_t e = 0; e < E; ++e) {
1144 if (tranT[e].empty())
continue;
1145 Matrix<double> Qe(M, K, 0.0);
1146 std::vector<double> ment(meancov ? n2 : 0, 0.0);
1147 Matrix<double> sent(meancov ? n2 : 0, meancov ? n2 : 0, 0.0);
1148 for (std::size_t h = 0; h < E; ++h) {
1149 const double p = envObj.prob_orig(h, e);
1150 if (!(p > 0.0))
continue;
1152 const Matrix<double> reset = f ? f(Qexit[h][e]) : Qexit[h][e];
1153 if (reset.rows() != M || reset.cols() != K)
1155 "SolverENV: a reset policy returned a matrix of the wrong shape");
1156 for (std::size_t i = 0; i < M; ++i)
1157 for (std::size_t r = 0; r < K; ++r) Qe(i, r) += p * reset(i, r);
1158 if (!meancov)
continue;
1164 const Matrix<double> R = reset_jacobian(f, Qexit[h][e]);
1165 const Matrix<double> Ch = congruence(R, Cexit[h]);
1166 for (std::size_t a = 0; a < n2; ++a) {
1167 const double ma = reset(a % M, a / M);
1169 for (std::size_t b = 0; b < n2; ++b)
1170 sent(a, b) += p * (Ch(a, b) + ma * reset(b % M, b / M));
1174 if (!meancov)
continue;
1175 Matrix<double> Ce(n2, n2, 0.0);
1176 for (std::size_t a = 0; a < n2; ++a)
1177 for (std::size_t b = 0; b < n2; ++b)
1178 Ce(a, b) = 0.5 * ((sent(a, b) - ment[a] * ment[b]) +
1179 (sent(b, a) - ment[b] * ment[a]));
1188 if (!statedep)
return;
1189 bool touched =
false;
1190 for (std::size_t e = 0; e < E; ++e)
1191 for (std::size_t h = 0; h < E; ++h) {
1192 const EnvArc<T>& a = envObj.arc(e, h);
1193 if (!a.enabled || !a.reset_rates)
continue;
1194 envObj.set_transition_dist(e, h,
1195 a.reset_rates(a.dist, Qexit[e][h], Uexit[e][h],
1199 if (!touched)
return;
1205 refresh_sojourn_means();
1212 void finish(EnvSolution& out) {
1213 const std::size_t E = envObj.nstages();
1214 out.QExit.assign(E, Matrix<double>(M, K, 0.0));
1215 out.UExit.assign(E, Matrix<double>(M, K, 0.0));
1216 out.TExit.assign(E, Matrix<double>(M, K, 0.0));
1217 for (std::size_t e = 0; e < E; ++e)
1222 stage_exit(e,
true, out.QExit[e], out.UExit[e], out.TExit[e],
true);
1223 for (std::size_t e = 0; e < E; ++e) {
1224 const double p = envObj.prob_env[e];
1225 for (std::size_t i = 0; i < M; ++i)
1226 for (std::size_t r = 0; r < K; ++r) {
1227 out.QN(i, r) += p * out.QExit[e](i, r);
1228 out.UN(i, r) += p * out.UExit[e](i, r);
1229 out.TN(i, r) += p * out.TExit[e](i, r);
1233 if (!meancov)
return;
1240 const std::size_t n = M * K;
1241 std::vector<double> mval(n, 0.0);
1242 Matrix<double> sval(n, n, 0.0);
1243 for (std::size_t e = 0; e < E; ++e) {
1244 const double p = envObj.prob_env[e];
1245 if (!(p > 0.0) || tranT[e].empty())
continue;
1246 const Matrix<double> Ce = stage_exit_cov(e);
1247 for (std::size_t a = 0; a < n; ++a) {
1248 const double ma = out.QExit[e](a % M, a / M);
1250 for (std::size_t b = 0; b < n; ++b)
1251 sval(a, b) += p * (Ce(a, b) + ma * out.QExit[e](b % M, b / M));
1254 out.QCov = Matrix<double>(n, n, 0.0);
1255 out.QVar = Matrix<double>(M, K, 0.0);
1256 for (std::size_t a = 0; a < n; ++a) {
1257 for (std::size_t b = 0; b < n; ++b)
1258 out.QCov(a, b) = 0.5 * ((sval(a, b) - mval[a] * mval[b]) +
1259 (sval(b, a) - mval[b] * mval[a]));
1260 out.QVar(a % M, a / M) = std::max(0.0, out.QCov(a, a));
1284 static constexpr std::size_t kCdfInterp = 5000;
1286 static std::vector<double> refine_grid(
double mean_hold,
bool disabled,
1287 const std::vector<double>& t) {
1288 if (t.size() < 2)
return t;
1293 if (disabled)
return t;
1294 const double t0 = t.front();
1295 const double tend = t.back();
1296 double mean_sojourn = mean_hold;
1297 if (!(mean_sojourn > 0.0) || !std::isfinite(mean_sojourn))
1298 mean_sojourn = (tend - t0) / 10.0;
1299 double tcdf = std::min(tend, 5.0 * mean_sojourn);
1300 if (tcdf <= t0) tcdf = tend;
1301 const std::size_t ndense =
static_cast<std::size_t
>(0.9 * kCdfInterp);
1302 const std::size_t ntail = kCdfInterp - ndense;
1303 const bool with_tail = tcdf < tend && ntail > 1;
1304 std::vector<double> fine;
1305 fine.reserve(with_tail ? ndense + ntail : ndense);
1306 for (std::size_t k = 0; k < ndense; ++k)
1307 fine.push_back(t0 + (tcdf - t0) *
static_cast<double>(k) /
1308 static_cast<double>(ndense - 1));
1310 for (std::size_t k = 1; k <= ntail; ++k)
1311 fine.push_back(tcdf + (tend - tcdf) *
static_cast<double>(k) /
1312 static_cast<double>(ntail));
1331 std::vector<double> stage_grid(std::size_t e)
const {
1332 std::vector<double> ends(2);
1334 ends[1] = opt.timespan_end;
1335 const std::vector<double> g =
1336 refine_grid(hold_disabled(e) ? 0.0 : envObj.hold_time_mean(e), hold_disabled(e), ends);
1339 if (g.size() < 3)
return std::vector<double>();
1356 Matrix<double> stage_exit_cov(std::size_t e)
const {
1357 const std::size_t n = M * K;
1358 Matrix<double> C(n, n, 0.0);
1359 const std::vector<double>& t = tranT[e];
1360 if (t.size() < 2)
return C;
1361 const bool have_c = tranC[e].size() == t.size();
1363 if (!have_c)
return C;
1367 double d = std::max(t.front(), std::min(dvals[e], t.back()));
1368 std::size_t j = t.size() - 1;
1369 for (std::size_t k = 1; k < t.size(); ++k)
1374 const double dt = t[j] - t[j - 1];
1375 const double a = (dt > 0.0) ? (d - t[j - 1]) / dt : 0.0;
1376 for (std::size_t p = 0; p < n; ++p)
1377 for (std::size_t q = 0; q < n; ++q)
1378 C(p, q) = (1.0 - a) * tranC[e][j - 1](p, q) + a * tranC[e][j](p, q);
1381 const std::vector<double> w = cdf_weights(e, t);
1383 for (
double v : w) wsum += v;
1384 if (!(wsum > 0.0))
return C;
1385 std::vector<double> mexit(n, 0.0);
1386 for (std::size_t a = 0; a < n; ++a)
1387 mexit[a] = weighted(tranQ[e][a % M][a / M], w, wsum);
1388 for (std::size_t a = 0; a < n; ++a) {
1389 const std::vector<double>& qa = tranQ[e][a % M][a / M];
1390 for (std::size_t b = 0; b < n; ++b) {
1391 const std::vector<double>& qb = tranQ[e][b % M][b / M];
1393 for (std::size_t k = 0; k < w.size() && k < qa.size() && k < qb.size(); ++k)
1394 acc += w[k] * qa[k] * qb[k];
1396 for (std::size_t k = 0; k < w.size(); ++k) acc += w[k] * tranC[e][k](a, b);
1397 C(a, b) = acc / wsum - mexit[a] * mexit[b];
1400 for (std::size_t a = 0; a < n; ++a)
1401 for (std::size_t b = a + 1; b < n; ++b) {
1402 const double v = 0.5 * (C(a, b) + C(b, a));
1420 Matrix<double> reset_jacobian(
const ResetMarginal& f,
const Matrix<double>& qexit)
const {
1421 const std::size_t n = M * K;
1422 Matrix<double> R(n, n, 0.0);
1424 for (std::size_t a = 0; a < n; ++a) R(a, a) = 1.0;
1427 const Matrix<double> base = f(qexit);
1428 if (base.rows() != M || base.cols() != K)
return R;
1430 for (std::size_t i = 0; i < M; ++i)
1431 for (std::size_t r = 0; r < K; ++r) scale = std::max(scale, std::fabs(qexit(i, r)));
1432 const double step = 1e-6 * scale;
1433 for (std::size_t j = 0; j < n; ++j) {
1434 Matrix<double> qp = qexit;
1435 qp(j % M, j / M) += step;
1436 const Matrix<double> pert = f(qp);
1437 if (pert.rows() != M || pert.cols() != K)
continue;
1438 for (std::size_t a = 0; a < n; ++a)
1439 R(a, j) = (pert(a % M, a / M) - base(a % M, a / M)) / step;
1445 static Matrix<double> congruence(
const Matrix<double>& R,
const Matrix<double>& C) {
1446 const std::size_t n = R.rows();
1447 Matrix<double> RC(n, n, 0.0), out(n, n, 0.0);
1448 for (std::size_t a = 0; a < n; ++a)
1449 for (std::size_t b = 0; b < n; ++b) {
1451 for (std::size_t c = 0; c < n; ++c) acc += R(a, c) * C(c, b);
1454 for (std::size_t a = 0; a < n; ++a)
1455 for (std::size_t b = 0; b < n; ++b) {
1457 for (std::size_t c = 0; c < n; ++c) acc += RC(a, c) * R(b, c);
1467 bool hold_disabled(std::size_t e)
const {
1468 if (envObj.hold_time_is_semi_markov(e))
return false;
1469 const mam::Map<double> m = envObj.hold_time[e].map();
1470 for (std::size_t a = 0; a < m.D1.rows(); ++a)
1471 for (std::size_t b = 0; b < m.D1.cols(); ++b)
1472 if (m.D1(a, b) != 0.0)
return false;
1481 std::vector<double> cdf_weights(std::size_t e,
const std::vector<double>& t)
const {
1482 std::vector<double> w(t.size(), 0.0);
1483 if (t.size() < 2)
return w;
1484 if (hold_disabled(e))
return w;
1485 const std::vector<double> F = envObj.hold_time_cdf(e, t);
1486 for (std::size_t j = 1; j < t.size(); ++j) w[j] = F[j] - F[j - 1];
1500 std::vector<double> sojourn_avg_weights(std::size_t e,
const std::vector<double>& t)
const {
1501 std::vector<double> W(t.size(), 0.0);
1502 if (t.size() < 2)
return W;
1503 const std::vector<double> F = envObj.hold_time_cdf(e, t);
1504 for (std::size_t j = 1; j < t.size(); ++j) {
1505 const double h = 0.5 * (t[j] - t[j - 1]);
1506 W[j - 1] += h * (1.0 - F[j - 1]);
1507 W[j] += h * (1.0 - F[j]);
1522 bool dest_resolved(std::size_t e)
const {
1523 if (!smp || det_sojourn)
return false;
1524 const std::size_t E = envObj.nstages();
1525 std::size_t nsucc = 0;
1526 for (std::size_t h = 0; h < E; ++h)
1527 if (envObj.pemb(e, h) > 0.0) ++nsucc;
1528 if (nsucc < 2)
return false;
1529 if (envObj.is_kernel_stage(e))
return true;
1530 std::vector<lang::Distrib<T>> arcs;
1531 std::vector<double> probs;
1532 envObj.stage_arcs(e, arcs, probs);
1533 for (
const lang::Distrib<T>& a : arcs)
1549 void exit_by_destination(std::size_t e, std::vector<std::vector<Matrix<double>>>& Qexit,
1550 std::vector<std::vector<Matrix<double>>>& Uexit,
1551 std::vector<std::vector<Matrix<double>>>& Texit) {
1552 const std::size_t E = envObj.nstages();
1553 const StageSteady& st = stage_steady(e);
1554 for (std::size_t h = 0; h < E; ++h) {
1555 Qexit[e][h] = st.QN;
1556 if (!statedep)
continue;
1557 Uexit[e][h] = st.UN;
1558 Texit[e][h] = st.TN;
1560 if (tranT[e].empty())
return;
1561 std::vector<lang::Distrib<T>> arcs;
1562 std::vector<double> probs;
1563 envObj.stage_arcs(e, arcs, probs);
1565 const std::size_t nt = tranT[e].size();
1566 for (std::size_t h = 0; h < E; ++h) {
1567 if (!(envObj.pemb(e, h) > 0.0))
continue;
1568 std::vector<double> w(nt, 0.0);
1571 for (std::size_t j = 1; j < nt; ++j) {
1572 w[j] = c.C(h, j) - c.C(h, j - 1);
1573 if (std::isnan(w[j])) nan =
true;
1576 if (nan || !(wsum > 0.0))
continue;
1577 for (std::size_t i = 0; i < M; ++i)
1578 for (std::size_t r = 0; r < K; ++r) {
1579 Qexit[e][h](i, r) = weighted(tranQ[e][i][r], w, wsum);
1580 if (!statedep)
continue;
1581 Uexit[e][h](i, r) = weighted(tranU[e][i][r], w, wsum);
1582 Texit[e][h](i, r) = weighted(tranTp[e][i][r], w, wsum);
1587 static double weighted(
const std::vector<double>& v,
const std::vector<double>& w,
1590 for (std::size_t j = 0; j < v.size() && j < w.size(); ++j) s += v[j] * w[j];
1603 std::vector<double> initsol_from_marginal(
const qn::NetworkStruct<T>& sn,
1604 const Matrix<double>& Q)
const {
1606 std::vector<double> y(L.nstates, 0.0);
1607 for (std::size_t i = 0; i < sn.nstations && i < Q.rows(); ++i)
1608 for (std::size_t r = 0; r < sn.nclasses && r < Q.cols(); ++r) {
1609 if (!L.enabled[i][r])
continue;
1610 y[L.qidx[i][r]] = std::max(0.0, Q(i, r));
1615 Environment<T>& envObj;
1617 std::size_t M = 0, K = 0;
1618 bool det_sojourn =
false;
1619 bool statedep =
false;
1621 bool ctmc_stages =
false;
1622 bool meancov =
false;
1623 bool kp_stages =
false;
1624 bool dae_stages =
false;
1625 std::vector<double> dvals;
1626 std::vector<Matrix<double>> entry;
1634 std::vector<Matrix<double>> centry;
1635 std::vector<std::vector<Matrix<double>>> tranC;
1636 std::vector<std::vector<double>> tranT;
1637 std::vector<std::vector<std::vector<std::vector<double>>>> tranQ, tranU, tranTp;
1643 std::vector<StageSteady> steady;
1644 std::vector<char> steady_asked;
1646 std::vector<std::shared_ptr<ln::SolverLN<T>>> lnsolv;
1648 std::vector<ln::LnLayerBlocks> lnblk;