5#ifndef LINE_SOLVERS_FLUID_SOLVER_FLUID_H
6#define LINE_SOLVERS_FLUID_SOLVER_FLUID_H
287 std::vector<std::pair<std::size_t, std::size_t> >
nhpp_sched;
428 const std::size_t M =
sn.nstations, K =
sn.nclasses;
429 const double inf = std::numeric_limits<double>::infinity();
430 std::vector<std::vector<double>> nplace(M, std::vector<double>(K, 0.0));
431 std::vector<double> totplace(M, 0.0);
434 const bool has_cap =
sn.cap.size() == M &&
sn.classcap.size() == M;
436 for (std::size_t r = 0; r < K; ++r) {
437 const double pop =
sn.classes[r].population;
438 if (!std::isfinite(pop))
continue;
441 std::vector<std::size_t> order;
442 const std::size_t rs =
sn.classes[r].refstat;
443 if (rs >= 1 && rs <= M) order.push_back(rs - 1);
444 for (std::size_t i = 0; i < M; ++i)
445 if (order.empty() || i != order[0]) order.push_back(i);
453 nplace[rs - 1][r] = pop;
454 totplace[rs - 1] += pop;
458 double remaining = pop;
459 for (std::size_t oi = 0; oi < order.size() && remaining > 0.0; ++oi) {
460 const std::size_t j = order[oi];
469 if (!L.
enabled[j][r])
continue;
470 const double ccap = (has_cap &&
sn.classcap[j].size() > r) ?
sn.classcap[j][r] : inf;
471 const double scap = has_cap ?
sn.cap[j] : inf;
472 const double avail = std::min(ccap - nplace[j][r], scap - totplace[j]);
473 const double take = std::min(remaining, std::max(0.0, avail));
474 nplace[j][r] += take;
479 throw InputError(
"solver_fluid_initsol: cannot place the population of class '" +
481 "': the total capacity of the stations that serve it is insufficient");
532 const std::vector<std::vector<double>>& nplace,
533 std::vector<double>& y0) {
534 const std::size_t M =
sn.nstations, K =
sn.nclasses;
536 std::vector<double> out(L.nstates, 0.0);
537 for (std::size_t i = 0; i < M; ++i) {
538 const std::size_t ind =
sn.node_of_station(i + 1);
540 const typename std::map<std::size_t, Matrix<T>>::const_iterator ss =
541 sn.statespace.find(ind);
542 const typename std::map<std::size_t, std::vector<T>>::const_iterator sp =
543 sn.stateprior.find(ind);
544 std::size_t pick =
static_cast<std::size_t
>(-1);
545 if (ss !=
sn.statespace.end() && sp !=
sn.stateprior.end() && ss->second.cols() > 0 &&
546 ss->second.rows() == sp->second.size()) {
547 for (std::size_t r = 0; r < ss->second.rows() && pick ==
static_cast<std::size_t
>(-1);
552 bool decoded =
false;
553 if (pick !=
static_cast<std::size_t
>(-1)) {
554 std::vector<T> row(ss->second.cols());
555 for (std::size_t c = 0; c < ss->second.cols(); ++c) row[c] = ss->second(pick, c);
556 std::vector<std::size_t> ph(K, 1), shift(K, 0);
558 for (std::size_t r = 0; r < K; ++r) {
565 decoded = m.nir.size() == K && m.kir.size() == K;
566 }
catch (
const Error&) {
570 for (std::size_t r = 0; r < K; ++r) {
571 if (!L.enabled[i][r])
continue;
575 if (!ext && nplace[i][r] > 0.0) out[L.qidx[i][r]] = nplace[i][r];
576 if (ext && !std::isfinite(sn.
classes[r].population)) out[L.qidx[i][r]] = 1.0;
579 const std::size_t np = L.kic[i][r];
580 for (std::size_t k = 0; k < np; ++k) {
582 if (k < m.kir[r].size()) v = num_traits<T>::to_double(m.kir[r][k]);
583 if (k == 0 && !ext) {
586 for (std::size_t j = 1; j < m.kir[r].size(); ++j)
587 served += num_traits<T>::to_double(m.kir[r][j]);
588 v = num_traits<T>::to_double(m.nir[r]) - served;
592 if (!std::isfinite(v)) v = 0.0;
593 out[L.qidx[i][r] + k] = v;
598 if (!any)
return false;
605std::vector<double> fluid_default_initsol(
const qn::NetworkStruct<T>& sn,
const FluidLayout& L) {
606 const std::size_t M = sn.nstations, K = sn.nclasses;
607 std::vector<double> y0(L.nstates, 0.0);
608 const std::vector<std::vector<double>> nplace = fluid_initsol_placement(sn, L);
609 if (fluid_declared_initsol(sn, L, nplace, y0))
return y0;
610 for (std::size_t r = 0; r < K; ++r) {
611 if (std::isfinite(sn.classes[r].population)) {
618 for (std::size_t i = 0; i < M; ++i)
619 if (L.enabled[i][r] && nplace[i][r] > 0.0) y0[L.qidx[i][r]] = nplace[i][r];
622 for (std::size_t i = 0; i < M; ++i)
624 y0[L.qidx[i][r]] = 1.0;
644inline void fluid_snap_fine(Matrix<double>& m) {
645 for (std::size_t i = 0; i < m.rows(); ++i)
646 for (std::size_t j = 0; j < m.cols(); ++j)
659inline void fluid_snap_all(Matrix<double>& q, Matrix<double>& u, Matrix<double>& r,
665 for (std::size_t i = 0; i < r.rows(); ++i)
666 for (std::size_t j = 0; j < r.cols(); ++j)
667 if (t(i, j) == 0.0 && q(i, j) == 0.0) r(i, j) = 0.0;
688std::vector<char> fluid_visited_pairs(
const qn::NetworkStruct<T>& sn, std::size_t M, std::size_t K) {
689 std::vector<char> visited(M * K, 0);
691 std::size_t max_cols = 0;
692 for (std::size_t c = 0; c < sn.visits.size(); ++c) {
693 const Matrix<T>& Vc = sn.visits[c];
694 if (Vc.rows() == 0 || Vc.cols() == 0)
continue;
696 max_cols = std::max(max_cols, Vc.cols());
697 for (std::size_t i = 0; i < M; ++i) {
698 const std::size_t isf = sn.stateful_of_station(i + 1);
699 if (isf == 0 || isf > Vc.rows()) {
700 for (std::size_t r = 0; r < K; ++r) visited[i * K + r] = 1;
703 for (std::size_t r = 0; r < K && r < Vc.cols(); ++r)
704 if (std::fabs(num_traits<T>::to_double(Vc(isf - 1, r))) >
706 visited[i * K + r] = 1;
710 std::fill(visited.begin(), visited.end(),
static_cast<char>(1));
714 for (std::size_t i = 0; i < M; ++i)
715 for (std::size_t r = max_cols; r < K; ++r) visited[i * K + r] = 1;
745void fluid_analyzer_correct(
const qn::NetworkStruct<T>& sn,
const Matrix<double>& Q,
746 Matrix<double>& U, Matrix<double>& R,
const Matrix<double>& T_) {
747 const std::size_t M = Q.rows(), K = Q.cols();
750 const std::vector<char> visited = fluid_visited_pairs(sn, M, K);
751 const Matrix<double> U0 = U;
752 for (std::size_t i = 0; i < M; ++i) {
753 double u0sum = 0.0, share_den = 0.0;
754 for (std::size_t r = 0; r < K; ++r) {
755 if (!(Q(i, r) > 0.0) || !visited[i * K + r])
continue;
757 const double rate = num_traits<T>::to_double(sn.rates(i, r));
758 if (rate != 0.0) share_den += T_(i, r) / rate;
765 double c = sn.stations[i].nservers;
766 for (std::size_t k = 0; k < sn.stations[i].lldscaling.size(); ++k)
767 c = std::max(c, num_traits<T>::to_double(sn.stations[i].lldscaling[k]));
769 for (std::size_t r = 0; r < K; ++r) {
770 if (!(Q(i, r) > 0.0) || !visited[i * K + r]) {
780 if (std::isfinite(c) && c > 0.0) best = std::min(best, Q(i, r) / c);
781 const double rate = num_traits<T>::to_double(sn.rates(i, r));
782 if (rate != 0.0 && share_den != 0.0)
783 best = std::min(best, u0sum * (T_(i, r) / rate) / share_den);
785 if (T_(i, r) != 0.0) R(i, r) = Q(i, r) / T_(i, r);
788 for (std::size_t i = 0; i < M; ++i)
789 for (std::size_t r = 0; r < K; ++r) {
790 if (std::isnan(U(i, r))) U(i, r) = 0.0;
791 if (std::isnan(R(i, r))) R(i, r) = 0.0;
808 const std::string& m,
const std::vector<double>& xs,
Matrix<double>& Q,
810 const std::size_t M =
sn.nstations, K =
sn.nclasses;
817 for (std::size_t i = 0; i < M; ++i)
818 for (std::size_t r = 0; r < K; ++r) {
820 for (std::size_t k = 0; k < L.
kic[i][r]; ++k) q += xs[L.
qidx[i][r] + k];
825 std::vector<std::vector<std::vector<double>>> xservice(M, std::vector<std::vector<double>>(K));
826 for (std::size_t i = 0; i < M; ++i) {
829 for (std::size_t r = 0; r < K; ++r) xi += Q(i, r);
831 for (std::size_t r = 0; r < K; ++r)
832 wxi += (r <
sn.stations[i].schedparam.size()
836 const double c =
sn.stations[i].nservers;
849 std::vector<double> wmean(K, 0.0);
852 for (std::size_t r = 0; r < K; ++r) {
853 if (!L.
enabled[i][r])
continue;
855 const std::size_t nn =
sn.service[i][r].D0.rows();
858 for (std::size_t a = 0; a < nn; ++a)
859 for (std::size_t bb = 0; bb < nn; ++bb) {
864 wni += wmean[r] * Q(i, r);
868 for (std::size_t r = 0; r < K; ++r) {
869 xservice[i][r].assign(L.
kic[i][r], 0.0);
870 if (!L.
enabled[i][r])
continue;
871 std::vector<double> mu, phi;
872 detail::fluid_mu_phi(
sn.service[i][r], mu, phi);
873 const std::size_t b = L.
qidx[i][r], n = L.
kic[i][r];
876 for (std::size_t k = 0; k < n; ++k)
877 xservice[i][r][k] = xs[b + k] * mu[k] * wmean[r] / wni * served;
879 for (std::size_t k = 0; k < n; ++k) s2 += xservice[i][r][k];
883 for (std::size_t k = 0; k < n; ++k) {
884 double mass = xs[b + k];
890 for (std::size_t p = 1; p < n; ++p) rest += xs[b + p];
893 tn += mass * mu[k] * phi[k];
894 xservice[i][r][k] = mass * mu[k];
897 tn += mass * mu[k] * phi[k];
898 xservice[i][r][k] = mass * mu[k];
901 const double w = r <
sn.stations[i].schedparam.size()
905 tn += mass * mu[k] * phi[k] * w / wxi * served;
906 xservice[i][r][k] = mass * mu[k] * w / wxi * served;
912 tn += mass * mu[k] * phi[k] / xi * served;
913 xservice[i][r][k] = mass * mu[k] / xi * served;
924 for (std::size_t i = 0; i < M; ++i) {
926 for (std::size_t r = 0; r < K; ++r) {
927 if (!L.
enabled[i][r])
continue;
928 std::vector<double> mu, phi;
929 detail::fluid_mu_phi(
sn.service[i][r], mu, phi);
931 for (std::size_t k = 0; k < xservice[i][r].size(); ++k)
932 if (xservice[i][r][k] > 0.0 && mu[k] > 0.0) u += xservice[i][r][k] / mu[k];
935 double c =
sn.stations[i].nservers;
936 for (std::size_t k = 0; k < sys.
lld[i].size(); ++k) c = std::max(c, sys.
lld[i][k]);
937 U(i, r) = (is_delay || !std::isfinite(c) || c <= 0.0) ? u : u / c;
942 for (std::size_t i = 0; i < M; ++i)
943 for (std::size_t r = 0; r < K; ++r)
944 if (T_(i, r) > 0.0) R(i, r) = Q(i, r) / T_(i, r);
952 for (std::size_t i = 0; i < M; ++i) {
954 if (nt != qn::NodeType::Source && nt != qn::NodeType::Sink)
continue;
955 for (std::size_t r = 0; r < K; ++r) {
962 detail::fluid_snap_all(Q, U, R, T_);
979inline void fluid_nhpp_steps(
const std::vector<double>& bp,
const std::vector<double>& seg_rate,
980 bool cyclic,
double t0,
double thi, std::vector<double>& seg_t,
981 std::vector<double>& seg_r) {
984 if (bp.size() < 2 || seg_rate.empty() || !(thi > t0))
return;
985 const double period = bp.back() - bp.front();
986 std::vector<double> bounds;
987 bounds.push_back(t0);
988 if (cyclic && period > 0.0) {
989 const long kmax =
static_cast<long>(std::ceil((thi - t0) / period)) + 2;
990 for (
long k = -1; k <= kmax; ++k)
991 for (std::size_t a = 0; a < bp.size(); ++a)
992 bounds.push_back(bp[a] +
static_cast<double>(k) * period);
994 for (std::size_t a = 0; a < bp.size(); ++a) bounds.push_back(bp[a]);
996 bounds.push_back(thi);
997 std::sort(bounds.begin(), bounds.end());
998 bounds.erase(std::remove_if(bounds.begin(), bounds.end(),
999 [&](
double v) { return v < t0 || v > thi; }),
1001 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
1002 if (bounds.size() < 2)
return;
1006 const auto rate_at = [&](
double t) ->
double {
1007 double offset = t - bp.front();
1010 offset = std::fmod(offset, period);
1011 if (offset < 0.0) offset += period;
1015 }
else if (offset < 0.0 || offset >= period) {
1018 const double pos = bp.front() + offset;
1019 std::size_t idx = seg_rate.size() - 1;
1020 for (std::size_t k = 1; k < bp.size(); ++k)
1025 return idx < seg_rate.size() ? seg_rate[idx] : 0.0;
1028 const double neps = std::max(1e-9, 1e-6 * (thi - t0));
1029 for (std::size_t k = 0; k + 1 < bounds.size(); ++k) {
1030 const double a = bounds[k], b = bounds[k + 1];
1031 const double r = rate_at(0.5 * (a + b));
1034 seg_t.push_back(std::max(a + neps, b - neps));
1040inline FluidRateMult fluid_ratemult_merge(
const FluidRateMult& a,
const FluidRateMult& b,
1041 std::size_t nevents) {
1042 if (a.empty())
return b;
1043 if (b.empty())
return a;
1044 std::vector<double> tg = a.tgrid;
1045 tg.insert(tg.end(), b.tgrid.begin(), b.tgrid.end());
1046 std::sort(tg.begin(), tg.end());
1047 tg.erase(std::unique(tg.begin(), tg.end()), tg.end());
1050 out.Mmat = Matrix<double>(nevents, tg.size(), 1.0);
1051 std::vector<double> ca, cb;
1052 for (std::size_t j = 0; j < tg.size(); ++j) {
1055 for (std::size_t e = 0; e < nevents; ++e) {
1056 const double va = e < ca.size() ? ca[e] : 1.0;
1057 const double vb = e < cb.size() ? cb[e] : 1.0;
1058 out.Mmat(e, j) = va * vb;
1073inline bool fluid_has_time_varying_rates(
const FluidOptions& opt) {
1074 return !opt.rate_traj.empty() || !opt.nhpp_sched.empty() || !opt.rate_sched.empty();
1078inline std::vector<std::size_t> fluid_events_of(
const FluidOdeSystem& sys, std::size_t i,
1080 std::vector<std::size_t> rows;
1081 const std::size_t lo = sys.layout.qidx[i][c];
1082 const std::size_t hi = lo + sys.layout.kic[i][c];
1083 for (std::size_t e = 0; e < sys.events.size(); ++e)
1084 if (sys.events[e].event_idx >= lo && sys.events[e].event_idx < hi) rows.push_back(e);
1089inline FluidRateMult fluid_ratemult_rows(
const FluidOdeSystem& sys, std::size_t i, std::size_t c,
1090 const std::vector<double>& seg_t,
1091 const std::vector<double>& seg_r,
double nominal) {
1093 if (seg_t.empty() || !(nominal > 0.0))
return out;
1094 const std::vector<std::size_t> rows = fluid_events_of(sys, i, c);
1095 if (rows.empty())
return out;
1097 out.Mmat = Matrix<double>(sys.events.size(), seg_t.size(), 1.0);
1098 for (std::size_t j = 0; j < seg_t.size(); ++j)
1099 for (std::size_t e : rows) out.Mmat(e, j) = seg_r[j] / nominal;
1118FluidRateMult fluid_ratemult(
const qn::NetworkStruct<T>& sn,
const FluidOdeSystem& sys,
1119 const FluidOptions& opt) {
1120 const std::size_t nev = sys.events.size();
1122 if (!opt.rate_traj.empty()) {
1123 if (opt.rate_traj.Mmat.rows() != nev)
1124 throw InputError(
"solver_fluid_ratemult: rate_traj has " +
1125 std::to_string(opt.rate_traj.Mmat.rows()) +
1126 " rows but the closing ODE has " + std::to_string(nev) +
" events");
1127 out = opt.rate_traj;
1134 const double tend = opt.timespan_end;
1137 for (std::size_t a = 0; a < opt.nhpp_sched.size(); ++a) {
1138 const std::size_t i = opt.nhpp_sched[a].first - 1, c = opt.nhpp_sched[a].second - 1;
1139 if (i >= sn.nstations || c >= sn.nclasses)
continue;
1140 if (!sys.layout.enabled[i][c])
continue;
1141 const lang::Distrib<T>& d = sn.service[i][c];
1142 if (!d.has_schedule())
continue;
1143 const std::vector<T> mu = d.mu_vec();
1144 if (mu.empty())
continue;
1145 const double nominal = num_traits<T>::to_double(mu[0]);
1146 if (!(nominal > 0.0))
continue;
1148 std::vector<double> bp, seg_r;
1149 for (std::size_t k = 0; k < d.sched_bp.size(); ++k)
1150 bp.push_back(num_traits<T>::to_double(d.sched_bp[k]));
1153 for (std::size_t k = 0; k < d.sched_D0.size(); ++k) {
1155 m.D0 = d.sched_D0[k];
1156 m.D1 = d.sched_D1[k];
1159 const double period = bp.empty() ? 0.0 : bp.back() - bp.front();
1161 if (!std::isfinite(thi))
1162 thi = (std::isfinite(period) && period > 0.0) ? t0 + 3.0 * period : t0 + 1.0;
1163 std::vector<double> seg_t, seg_v;
1164 fluid_nhpp_steps(bp, seg_r, d.sched_cyclic, t0, thi, seg_t, seg_v);
1165 nh = fluid_ratemult_merge(nh, fluid_ratemult_rows(sys, i, c, seg_t, seg_v, nominal), nev);
1169 for (std::size_t a = 0; a < opt.rate_sched.size(); ++a) {
1170 const FluidOptions::RateSched& e = opt.rate_sched[a];
1171 const std::size_t i = e.station - 1, c = e.cls - 1;
1172 if (i >= sn.nstations || c >= sn.nclasses)
continue;
1173 if (!sys.layout.enabled[i][c])
continue;
1174 if (e.tgrid.size() != e.rates.size() || e.tgrid.empty())
1175 throw InputError(
"solver_fluid_ratemult: rate_sched tgrid and rates must be "
1176 "non-empty and of equal length");
1177 double nominal = e.nominal;
1178 if (!(nominal > 0.0)) {
1179 const std::vector<T> mu = sn.service[i][c].mu_vec();
1180 if (mu.empty())
continue;
1181 nominal = num_traits<T>::to_double(mu[0]);
1183 if (!(nominal > 0.0))
continue;
1184 rs = fluid_ratemult_merge(rs, fluid_ratemult_rows(sys, i, c, e.tgrid, e.rates, nominal),
1188 out = fluid_ratemult_merge(out, nh, nev);
1189 out = fluid_ratemult_merge(out, rs, nev);
1200double fluid_slow_rate(
const qn::NetworkStruct<T>& sn,
const FluidLayout& L,
double tol) {
1201 double min_rate = std::numeric_limits<double>::infinity();
1202 for (std::size_t i = 0; i < sn.nstations; ++i)
1203 for (std::size_t r = 0; r < sn.nclasses; ++r) {
1204 if (!L.enabled[i][r])
continue;
1205 const lang::Distrib<T>& d = sn.service[i][r];
1206 for (std::size_t k = 0; k < d.D0.rows(); ++k) {
1207 const double mu = -num_traits<T>::to_double(d.D0(k, k));
1208 if (mu > tol && std::isfinite(mu)) min_rate = std::min(min_rate, mu);
1211 return std::isfinite(min_rate) ? min_rate : 1.0;
1224FluidSolution fluid_dispatch(
const qn::NetworkStruct<T>& sn,
const FluidOptions& opt) {
1225 if (!std::is_same<T, double>::value)
1227 "solver_fluid: the fluid solver integrates its drift with LSODA, whose coefficients "
1228 "assume double precision; rerun with --arith double");
1230 std::string m = opt.method;
1231 if (m.compare(0, 4,
"fld.") == 0) m = m.substr(4);
1233 bool statedep_family =
false;
1245 bool has_dps =
false, has_cache =
false;
1246 for (
const auto& st : sn.stations)
1248 for (
const qn::NodeDef& nd : sn.nodes)
1249 if (nd.nodetype == qn::NodeType::Cache) has_cache =
true;
1250 if ((m ==
"matrix" || m ==
"pnorm") && has_dps)
1252 "solver_fluid: the matrix method does not support DPS scheduling; use method "
1253 "'closing' (which is what 'default' selects on a DPS model)");
1254 if (m ==
"default") {
1257 "solver_fluid: a Cache model resolves to the 'rmf' fluid method, which is ported "
1258 "in fluid_cacheqn.h and reached through solver_fluid_run_analyzer (fluid_runner.h); this "
1259 "function is solver_fluid_analyzer alone and cannot call it without a cyclic "
1261 if (has_dps) m =
"closing";
1263 const bool matrix_family = (m ==
"default" || m ==
"matrix" || m ==
"pnorm");
1264 if (m ==
"statedep") {
1265 statedep_family =
true;
1267 }
else if (m ==
"softmin") {
1268 statedep_family =
true;
1270 }
else if (!(matrix_family || m ==
"closing" || m ==
"tbi" || m ==
"diffusion" || m ==
"mfq")) {
1271 throw UnsupportedError(ErrorKind{
"Method"},
"solver_fluid: the '" + opt.method +
1272 "' fluid method is not solved here; available are 'closing', "
1273 "'statedep', 'softmin', 'pnorm', 'matrix', 'tbi', 'diffusion' and "
1274 "'mfq', while 'rmf', 'minnormal', 'mnrefined', 'dae' and 'kp' are "
1275 "reached through solver_fluid_run_analyzer (fluid_runner.h), which is the "
1276 "port of runAnalyzer's resolution");
1279 const std::size_t M = sn.nstations, K = sn.nclasses;
1284 sys.closure = opt.closure;
1288 sys.ratemult = detail::fluid_ratemult(sn, sys, opt);
1289 const FluidLayout& L = sys.layout;
1291 throw InputError(
"solver_fluid: no station serves any class, so the drift is empty");
1294 const double min_rate = fluid_slow_rate(sn, L, opt.tol);
1297 std::vector<double> x = opt.init_sol.empty() ? detail::fluid_default_initsol(sn, L) : opt.init_sol;
1298 if (x.size() != L.nstates)
1299 throw InputError(
"solver_fluid: init_sol has " + std::to_string(x.size()) +
1300 " entries but the fluid state has " + std::to_string(L.nstates));
1309 const FluidAoiResult ar =
fluid_aoi(sn, atop, opt.aoi_preemption);
1315 out.QN = Matrix<double>(M, K, 0.0);
1316 out.UN = Matrix<double>(M, K, 0.0);
1317 out.RN = Matrix<double>(M, K, 0.0);
1318 out.TN = Matrix<double>(M, K, 0.0);
1319 out.XN.assign(K, 0.0);
1320 out.CN.assign(K, 0.0);
1321 for (std::size_t r = 0; r < K; ++r) {
1322 out.QN(atop.queue, r) = ar.QN[r];
1323 out.UN(atop.queue, r) = ar.UN[r];
1324 out.RN(atop.queue, r) = ar.RN[r];
1325 out.TN(atop.queue, r) = ar.TN[r];
1327 out.TN(atop.source, r) = (r == atop.cls) ? ar.lambda : 0.0;
1328 out.XN[r] = out.TN(atop.source, r);
1329 out.CN[r] = ar.RN[r];
1340 FluidOptions mopt = opt;
1341 mopt.method =
"matrix";
1342 return fluid_dispatch(sn, mopt);
1347 bool mixed_prio =
false;
1349 for (std::size_t j = 1; j < top.open_classes.size(); ++j)
1350 if (sn.classes[top.open_classes[j]].prio != sn.classes[top.open_classes[0]].prio)
1356 FluidOptions fb = opt;
1357 fb.method =
"matrix";
1363 out.QN = Matrix<double>(M, K, 0.0);
1364 out.UN = Matrix<double>(M, K, 0.0);
1365 out.RN = Matrix<double>(M, K, 0.0);
1366 out.TN = Matrix<double>(M, K, 0.0);
1367 out.XN.assign(K, 0.0);
1368 out.CN.assign(K, 0.0);
1369 for (std::size_t r = 0; r < K; ++r) {
1370 out.QN(top.queue, r) = pr.QN[r];
1371 out.TN(top.queue, r) = pr.TN[r];
1372 out.TN(top.source, r) = pr.TN[r];
1373 out.XN[r] = pr.TN[r];
1382 for (std::size_t r = 0; r < K; ++r) {
1383 out.UN(top.queue, r) = pr.UN[r];
1384 out.RN(top.queue, r) = pr.RN[r];
1385 if (pr.QN[r] > 0.0) out.CN[r] = inf ? pr.RN[r] : pr.QN[r] / pr.TN[r];
1393 FluidOptions mopt = opt;
1394 mopt.method =
"matrix";
1395 return fluid_dispatch(sn, mopt);
1397 const MfqResult r =
fluid_mfq(sn, top, opt.tol);
1401 out.QN = Matrix<double>(M, K, 0.0);
1402 out.UN = Matrix<double>(M, K, 0.0);
1403 out.RN = Matrix<double>(M, K, 0.0);
1404 out.TN = Matrix<double>(M, K, 0.0);
1405 out.QN(top.queue, top.cls) = r.QN;
1406 out.UN(top.queue, top.cls) = r.UN;
1407 out.RN(top.queue, top.cls) = r.RN;
1408 out.TN(top.queue, top.cls) = r.TN;
1409 out.TN(top.source, top.cls) = r.TN;
1410 out.XN.assign(K, 0.0);
1411 out.CN.assign(K, 0.0);
1412 out.XN[top.cls] = r.TN;
1413 out.CN[top.cls] = r.RN;
1418 if (m ==
"diffusion") {
1419 DiffusionOptions dopt;
1421 if (std::isfinite(opt.timespan_end) && opt.timestep > 0.0)
1422 dopt.steps = std::max<std::size_t>(2,
static_cast<std::size_t
>(std::ceil(opt.timespan_end / opt.timestep)));
1423 dopt.dt = opt.timestep;
1424 dopt.seed = opt.seed;
1428 out.method =
"diffusion";
1433 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
1434 out.XN.assign(K, 0.0);
1435 out.CN.assign(K, 0.0);
1436 for (std::size_t r = 0; r < K; ++r) {
1437 const std::size_t rs = sn.classes[r].refstat;
1438 if (rs >= 1 && rs <= M) out.XN[r] = out.TN(rs - 1, r);
1440 for (std::size_t i = 0; i < M; ++i) q += out.QN(i, r);
1441 if (out.XN[r] > 0.0) out.CN[r] = q / out.XN[r];
1447 lopt.rtol = opt.tol;
1448 lopt.atol = opt.tol;
1451 if (matrix_family) {
1455 const double ps = (m ==
"pnorm" || opt.pstar_set) ? opt.pstar : 0.0;
1457 const std::function<void(
double,
const double*,
double*)> mdrift =
fluid_matrix_drift(ms);
1459 std::min(opt.timespan_end,
1460 10.0 *
static_cast<double>(opt.iter_max) / ms.min_rate);
1462 for (
double& v : xm)
1463 if (v < 0.0) v = 0.0;
1485 FluidMatrixSystem msr = ms;
1487 msr.var_closure =
true;
1488 const std::function<void(
double,
const double*,
double*)> cdrift =
1491 bool finite = xc.size() == xm.size();
1492 for (std::size_t a = 0; finite && a < xc.size(); ++a)
1493 if (!std::isfinite(xc[a])) finite =
false;
1495 for (
double& v : xc)
1496 if (v < 0.0) v = 0.0;
1501 msr.var_closure =
false;
1506 std::vector<double> theta(ms.nstates, 0.0);
1507 detail::fluid_matrix_theta(msr, xm.data(), theta);
1511 out.method = (m ==
"pnorm") ?
"pnorm" :
"matrix";
1513 out.QN = Matrix<double>(M, K, 0.0);
1514 out.UN = Matrix<double>(M, K, 0.0);
1515 out.RN = Matrix<double>(M, K, 0.0);
1516 out.TN = Matrix<double>(M, K, 0.0);
1517 for (std::size_t i = 0; i < M; ++i)
1518 for (std::size_t r = 0; r < K; ++r) {
1519 double q = 0.0, u = 0.0, t = 0.0;
1520 for (std::size_t a = 0; a < ms.nstates; ++a) {
1521 q += ms.sqc(i * K + r, a) * xm[a];
1522 u += ms.suc(i * K + r, a) * theta[a];
1523 t += ms.stc(i * K + r, a) * theta[a];
1533 !std::isfinite(sn.stations[i].nservers))
1547 for (std::size_t i = 0; i < M; ++i) {
1549 if (nt != qn::NodeType::Source && nt != qn::NodeType::Sink)
continue;
1550 for (std::size_t r = 0; r < K; ++r) {
1554 if (nt == qn::NodeType::Source && ms.src_arrival.rows() == M)
1555 out.TN(i, r) = ms.src_arrival(i, r);
1558 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
1559 out.XN.assign(K, 0.0);
1560 out.CN.assign(K, 0.0);
1561 for (std::size_t r = 0; r < K; ++r) {
1562 const std::size_t rs = sn.classes[r].refstat;
1563 if (rs >= 1 && rs <= M) out.XN[r] = out.TN(rs - 1, r);
1565 for (std::size_t i = 0; i < M; ++i) q += out.QN(i, r);
1566 if (out.XN[r] > 0.0) out.CN[r] = q / out.XN[r];
1582 lopt.rtol = lopt.atol =
1583 opt.tol / std::max<double>(1.0,
static_cast<double>(opt.iter_max));
1589 FluidOdeSystem dsys = sys;
1590 FluidImmediateResult imm_result;
1593 if (imm_result.eliminated) {
1594 dsys = imm_result.sys;
1599 std::vector<double> xp(x.size(), 0.0);
1600 for (std::size_t f = 0; f < x.size() && f < imm_result.absorb.rows(); ++f)
1601 for (std::size_t sidx = 0; sidx < x.size() && sidx < imm_result.absorb.cols();
1603 xp[sidx] += x[f] * imm_result.absorb(f, sidx);
1604 for (std::size_t a = 0; a < x.size(); ++a) x[a] = xp[a];
1608 const std::function<void(
double,
const double*,
double*)> drift =
1613 const std::vector<std::vector<std::size_t>> tbi_cells =
1614 (m !=
"tbi") ? std::vector<std::vector<std::size_t>>()
1615 : opt.tbi_cells.empty() ?
tbi_partition(sn, opt.tbi_cellsize)
1620 const double drift_tol = std::max(opt.iter_tol, opt.tol);
1621 const double drift_safety = 0.01;
1622 const double min_horizon = 10.0 / min_rate;
1623 double moved_prev = std::numeric_limits<double>::infinity();
1624 std::vector<double> rho_hist(3, std::numeric_limits<double>::quiet_NaN());
1625 int drift_below = 0;
1626 std::vector<double> drift_buf(x.size(), 0.0);
1629 std::size_t iter = 0;
1630 for (; iter < opt.iter_max; ++iter) {
1634 const double horizon = 10.0 *
static_cast<double>(iter + 1) / min_rate;
1635 const double t1 = std::min(opt.timespan_end, horizon);
1636 if (!(t1 > t0))
break;
1637 const std::vector<double> prev = x;
1665 const bool fp_armed = opt.earlystop && !std::isfinite(opt.timespan_end)
1666 && !fluid_has_time_varying_rates(opt);
1668 drift(t0, x.data(), drift_buf.data());
1669 double dn = 0.0, dtot = 0.0;
1670 for (std::size_t i = 0; i < x.size(); ++i) {
1671 dn += std::fabs(drift_buf[i]);
1697 lopt.step_stop = {};
1698 if (fp_armed && m !=
"tbi") {
1699 const double fp_rate = min_rate;
1700 lopt.step_stop = [&drift, fp_rate](
double tt,
const std::vector<double>& yy) {
1701 if (yy.empty() || !(fp_rate > 0.0))
return false;
1702 std::vector<double> dy(yy.size(), 0.0);
1703 drift(tt, yy.data(), dy.data());
1704 double dn = 0.0, dtot = 0.0;
1705 for (std::size_t i = 0; i < yy.size(); ++i) {
1706 dn += std::fabs(dy[i]);
1714 x =
tbi_advance(sys, tbi_cells, x, t0, t1, TbiOptions(), lopt);
1715 }
else if (opt.stiff) {
1719 FluidStiffOptions sopt;
1720 sopt.rtol = lopt.rtol;
1721 sopt.atol = lopt.atol;
1724 if (lopt.step_stop) {
1725 const std::function<bool(
double,
const std::vector<double>&)> ss_stop =
1727 sopt.step_stop = [ss_stop](
const double& tt,
const std::vector<double>& yy) {
1728 return ss_stop(tt, yy);
1732 x = ss.final_state();
1740 if (v < 0.0) v = 0.0;
1750 if (opt.closure.gaussian()) {
1754 "The moment-closure drift left the model: closed chain " +
1755 std::to_string(bad) +
" moved more than " +
1757 "% of a population the drift conserves exactly, by t = " +
1758 std::to_string(t1) +
1759 ", so the excursion is a divergence rather than a solution. "
1760 "Falling back to a first-order closure.");
1765 double moved = 0.0, total = 0.0;
1766 for (std::size_t i = 0; i < x.size(); ++i) {
1767 moved += std::fabs(x[i] - prev[i]);
1770 const double ratio = (total > 0.0) ? moved / 2.0 / total : 0.0;
1776 if (opt.iter_tol > 0.0 && ratio < opt.iter_tol && !std::isfinite(opt.timespan_end)) {
1787 if (opt.earlystop && iter > 0 && !std::isfinite(opt.timespan_end) && t1 >= min_horizon) {
1788 rho_hist[iter % rho_hist.size()] =
1791 for (
double v : rho_hist)
1792 if (std::isfinite(v) && v > rho) rho = v;
1793 drift(t1, x.data(), drift_buf.data());
1794 double dn = 0.0, dtot = 0.0;
1795 for (std::size_t i = 0; i < x.size(); ++i) {
1796 dn += std::fabs(drift_buf[i]);
1799 const double drift_displ = (dtot > 0.0) ? dn / 2.0 / dtot / min_rate : 0.0;
1812 if (rho < 1.0 && ratio * rho / (1.0 - rho) < drift_safety * drift_tol
1813 && drift_displ < drift_tol) {
1814 if (++drift_below >= 2) {
1823 if (t1 >= opt.timespan_end) {
1832 out.method = (statedep_family || m ==
"tbi") ? m : std::string(
"closing");
1834 out.QN = Matrix<double>(M, K, 0.0);
1835 out.UN = Matrix<double>(M, K, 0.0);
1836 out.RN = Matrix<double>(M, K, 0.0);
1837 out.TN = Matrix<double>(M, K, 0.0);
1848 if (imm_result.eliminated) {
1849 const FluidLayout& LL = sys.layout;
1850 std::vector<std::size_t> cs(LL.nstates, 0), cc(LL.nstates, 0);
1851 for (std::size_t i = 0; i < M; ++i)
1852 for (std::size_t r = 0; r < K; ++r)
1853 for (std::size_t k = 0; k < LL.kic[i][r]; ++k) {
1854 cs[LL.qidx[i][r] + k] = i;
1855 cc[LL.qidx[i][r] + k] = r;
1857 std::vector<bool> kept(LL.nstates,
false);
1858 for (std::size_t a = 0; a < imm_result.state_map.size(); ++a)
1859 kept[imm_result.state_map[a]] =
true;
1860 std::vector<double> rr(x.begin(), x.end());
1862 for (std::size_t o = 0; o < sys.n_departures && o < sys.events.size(); ++o) {
1863 const std::size_t c = sys.events[o].event_idx;
1864 if (c >= LL.nstates || kept[c])
continue;
1866 for (std::size_t e = 0; e < rr.size() && e < imm_result.emap.rows(); ++e)
1867 extra += imm_result.emap(e, o) * rr[e];
1868 out.TN(cs[c], cc[c]) += extra;
1870 for (std::size_t i = 0; i < M; ++i)
1871 for (std::size_t r = 0; r < K; ++r)
1873 out.RN(i, r) = out.QN(i, r) / out.TN(i, r);
1875 detail::fluid_snap_all(out.QN, out.UN, out.RN, out.TN);
1878 out.XN.assign(K, 0.0);
1879 out.CN.assign(K, 0.0);
1880 for (std::size_t r = 0; r < K; ++r) {
1881 const std::size_t rs = sn.classes[r].refstat;
1882 if (rs >= 1 && rs <= M) out.XN[r] = out.TN(rs - 1, r);
1884 for (std::size_t i = 0; i < M; ++i) q += out.QN(i, r);
1885 if (out.XN[r] > 0.0) out.CN[r] = q / out.XN[r];
1947inline bool fluid_method_refits_fcfs(
const std::string& method) {
1948 std::string m = method;
1949 if (m.size() > 4 && m.compare(0, 4,
"fld.") == 0) m = m.substr(4);
1950 return m ==
"matrix" || m ==
"closing" || m ==
"tbi" || m ==
"minnormal" || m ==
"mnrefined" ||
1956Matrix<T> fluid_station_visits(
const qn::NetworkStruct<T>& sn) {
1957 const T
zero = num_traits<T>::from_int(0);
1958 Matrix<T> V(sn.nstations, sn.nclasses, zero);
1959 for (std::size_t c = 0; c < sn.nchains; ++c)
1960 for (std::size_t i = 0; i < sn.nstations; ++i) {
1961 const std::size_t sf = sn.stateful_of_station(i + 1);
1962 for (std::size_t k = 0; k < sn.nclasses; ++k)
1963 V(i, k) = T(V(i, k) + sn.visits[c](sf - 1, k));
1976inline double fluid_eta_gap(
const std::vector<double>& eta,
const std::vector<double>& eta_1) {
1977 double best = -std::numeric_limits<double>::infinity();
1979 for (std::size_t i = 0; i < eta.size(); ++i) {
1980 const double g = std::fabs(1.0 - eta[i] / eta_1[i]);
1981 if (std::isnan(g))
continue;
1983 best = std::max(best, g);
1985 return any ? best : 0.0;
1991Matrix<T> fluid_reciprocal_guarded(
const Matrix<T>& A) {
1992 const T one = num_traits<T>::from_int(1);
1993 Matrix<T> B(A.rows(), A.cols(), num_traits<T>::from_int(0));
1994 for (std::size_t i = 0; i < A.rows(); ++i)
1995 for (std::size_t r = 0; r < A.cols(); ++r) {
1996 const double a = num_traits<T>::to_double(A(i, r));
1999 else if (a == 0.0 || std::isinf(1.0 / a))
2007 B(i, r) = T(one / A(i, r));
2020bool fluid_refit_fcfs_stations(qn::NetworkStruct<T>& sn,
const Matrix<T>& rates,
2021 const Matrix<T>& SCV,
2022 std::vector<std::vector<std::size_t>>& phases) {
2023 const T
zero = num_traits<T>::from_int(0);
2024 const T one = num_traits<T>::from_int(1);
2025 const std::size_t M = sn.nstations, K = sn.nclasses;
2026 bool changed =
false;
2027 for (std::size_t i = 0; i < M; ++i) {
2029 for (std::size_t r = 0; r < K; ++r) {
2030 if (!(rates(i, r) > zero) || !(SCV(i, r) > zero))
continue;
2037 if (cx.mu.size() != phases[i][r]) changed =
true;
2038 phases[i][r] = cx.mu.size();
2061template <
class T,
class Solve>
2062FluidSolution fluid_fcfs_nonexp_refit(
const qn::NetworkStruct<T>& sn0,
const FluidOptions& opt,
2063 const FluidSolution& seed, Solve
solve,
2064 qn::NetworkStruct<T>* sn_out =
nullptr) {
2065 const std::size_t M = sn0.nstations, K = sn0.nclasses;
2071 if (sn_out) *sn_out = sn0;
2072 if (!fluid_method_refits_fcfs(opt.method))
return seed;
2073 bool any_fcfs =
false;
2074 for (std::size_t i = 0; i < M; ++i)
2076 if (!any_fcfs)
return seed;
2078 const T
zero = num_traits<T>::from_int(0);
2079 const T one = num_traits<T>::from_int(1);
2080 const Matrix<T>& rates0 = sn0.rates;
2081 const Matrix<T>& SCV = sn0.scv;
2082 const Matrix<T> V = fluid_station_visits(sn0);
2083 const Matrix<T> ST0 = fluid_reciprocal_guarded(rates0);
2085 std::vector<bool> isFCFS(M,
false);
2086 std::vector<T> nservers(M, one), gamma(M, zero);
2087 for (std::size_t i = 0; i < M; ++i) {
2089 nservers[i] = num_traits<T>::from_double(sn0.stations[i].nservers);
2092 qn::NetworkStruct<T> sn = sn0;
2093 std::vector<std::vector<std::size_t>> phases(M, std::vector<std::size_t>(K, 0));
2094 for (std::size_t i = 0; i < M; ++i)
2095 for (std::size_t r = 0; r < K; ++r) phases[i][r] = sn0.service[i][r].D0.rows();
2097 FluidSolution cur = seed;
2098 std::vector<double> eta(M, std::numeric_limits<double>::infinity()), eta_1(M, 0.0);
2099 std::size_t iter = 0;
2108 Matrix<T> U(M, K, zero), TN(M, K, zero);
2109 for (std::size_t i = 0; i < M; ++i)
2110 for (std::size_t r = 0; r < K; ++r) {
2111 TN(i, r) = num_traits<T>::from_double(cur.TN(i, r));
2112 if (rates0(i, r) > zero) U(i, r) = T(TN(i, r) / rates0(i, r));
2116 opt.highvar, isFCFS, rates0, ST0, V, SCV, TN, U, gamma, nservers);
2118 for (std::size_t i = 0; i < M; ++i) eta[i] = num_traits<T>::to_double(na.eta[i]);
2120 const Matrix<T> rates = fluid_reciprocal_guarded(na.ST);
2121 const bool phase_change = fluid_refit_fcfs_stations(sn, rates, SCV, phases);
2123 FluidOptions o = opt;
2124 const std::vector<double> fresh = fluid_default_initsol(sn,
fluid_layout(sn));
2125 o.init_sol = (!phase_change && cur.xvec.size() == fresh.size()) ? cur.xvec : fresh;
2132 FluidOptions o = opt;
2133 o.init_sol = fluid_default_initsol(sn,
fluid_layout(sn));
2134 FluidSolution out =
solve(sn, o);
2135 out.refit_sweeps = iter;
2136 if (sn_out) *sn_out = sn;
2172 out = detail::fluid_fcfs_nonexp_refit(
2176 detail::fluid_analyzer_correct(
sn, out.
QN, out.
UN, out.
RN, out.
TN);
2177 detail::fluid_snap_all(out.
QN, out.
UN, out.
RN, out.
TN);
2198 std::vector<std::pair<std::size_t, std::size_t> > out;
2199 for (std::size_t i = 0; i <
sn.nstations; ++i) {
2201 for (std::size_t r = 0; r <
sn.nclasses; ++r)
2202 if (!
sn.disabled[i][r] &&
sn.service[i][r].has_schedule())
2203 out.push_back(std::make_pair(i + 1, r + 1));
2237 std::size_t points = 101,
2238 const std::vector<double>& out_grid =
2239 std::vector<double>()) {
2240 if (!std::is_same<T, double>::value)
2242 "solver_fluid_transient: the fluid drift is integrated by LSODA, which is double "
2243 "precision by construction; rerun with --arith double");
2244 if (!(t_end > 0.0))
throw InputError(
"solver_fluid_transient: t_end must be positive");
2245 if (points < 2)
throw InputError(
"solver_fluid_transient: need at least two output points");
2250 sys.
ratemult = detail::fluid_ratemult(
sn, sys, o);
2253 throw InputError(
"solver_fluid_transient: no station serves any class");
2255 std::vector<double> y0 =
2258 throw InputError(
"solver_fluid_transient: init_sol has the wrong length");
2260 std::vector<double> grid = out_grid;
2262 grid.resize(points);
2263 for (std::size_t j = 0; j < points; ++j)
2264 grid[j] = t_end *
static_cast<double>(j) /
static_cast<double>(points - 1);
2270 const std::function<void(
double,
const double*,
double*)> tdrift =
fluid_drift(sys);
2273 std::vector<FluidTranPoint> out;
2274 out.reserve(sol.
y.size());
2275 for (std::size_t j = 0; j < sol.
y.size(); ++j) {
2276 std::vector<double> xs = sol.
y[j];
2277 for (
double& v : xs)
2278 if (v < 0.0) v = 0.0;
2283 detail::fluid_snap_all(pt.
QN, pt.
UN, R, pt.
TN);
2314 if (std::isfinite(
opt.timespan_end) &&
opt.timespan_end > 0.0)
return opt.timespan_end;
2315 double min_rate = std::numeric_limits<double>::infinity();
2316 for (std::size_t i = 0; i <
sn.nstations; ++i)
2317 for (std::size_t r = 0; r <
sn.nclasses; ++r) {
2318 if (
sn.disabled[i][r])
continue;
2320 if (std::isfinite(rate) && rate >
opt.tol) min_rate = std::min(min_rate, rate);
2322 if (!std::isfinite(min_rate)) min_rate = 1.0;
2323 return 30.0 / min_rate;
2339 std::size_t points = 101) {
2356 if (x.size() != n)
throw InputError(
"fluid_jacobian: the state has the wrong length");
2357 const std::function<void(
double,
const double*,
double*)> f =
fluid_drift(sys);
2359 std::vector<double> xp(x), xm(x), fp(n, 0.0), fm(n, 0.0);
2360 for (std::size_t j = 0; j < n; ++j) {
2362 const double h = 1e-6 * std::max(1.0, std::fabs(x[j]));
2367 f(0.0, xp.data(), fp.data());
2368 f(0.0, xm.data(), fm.data());
2369 for (std::size_t i = 0; i < n; ++i) J(i, j) = (fp[i] - fm[i]) / (2.0 * h);
2392 std::size_t i,
const std::vector<double>& nir,
2393 double* logp_out =
nullptr) {
2394 const std::size_t K =
sn.nclasses;
2397 std::vector<std::size_t> idx;
2398 std::vector<double> m, a, b;
2399 for (std::size_t r = 0; r < K; ++r) {
2400 if (cb[r].empty()) {
2404 if (logp_out) *logp_out = -std::numeric_limits<double>::infinity();
2410 m.push_back(sol.
QN(i, r));
2411 a.push_back(nir[r] <= 0.0 ? -std::numeric_limits<double>::infinity() : nir[r] - 0.5);
2412 const double pop =
sn.classes[r].population;
2413 b.push_back((std::isfinite(pop) && nir[r] >= pop) ? std::numeric_limits<double>::infinity()
2418 if (logp_out) *logp_out = 0.0;
2422 const std::size_t nr = idx.size();
2424 for (std::size_t u = 0; u < nr; ++u)
2425 for (std::size_t v = u; v < nr; ++v) {
2427 for (std::size_t p = 0; p < cb[idx[u]].size(); ++p)
2428 for (std::size_t q = 0; q < cb[idx[v]].size(); ++q)
2429 acc += sol.
moments.
Sigma(cb[idx[u]][p], cb[idx[v]][q]);
2435 if (logp_out) *logp_out = p > 0.0 ? std::log(p) : -std::numeric_limits<double>::infinity();
2454 double* logp_out =
nullptr) {
2455 const std::size_t M =
sn.nstations, K =
sn.nclasses;
2456 if (ist == 0 || ist > M)
2457 throw InputError(
"fluid_prob_aggr: station number exceeds the number of stations");
2458 const std::size_t i = ist - 1;
2463 std::vector<double> nir(K, 0.0);
2464 for (std::size_t r = 0; r < K; ++r) {
2465 const double pop =
sn.classes[r].population;
2466 if (std::isfinite(pop) &&
sn.classes[r].refstat == ist) nir[r] = pop;
2470 bool minus_inf =
false;
2485 bool open_here =
false;
2486 for (std::size_t r = 0; r < K; ++r)
2494 bool any_open =
false;
2495 for (std::size_t r = 0; r < K; ++r)
2496 if (!std::isfinite(
sn.classes[r].population)) any_open =
true;
2498 for (std::size_t r = 0; r < K; ++r) {
2499 if (std::isfinite(
sn.classes[r].population))
continue;
2500 const double q = sol.
QN(i, r);
2502 logp += nir[r] * std::log(q) - q - std::lgamma(nir[r] + 1.0);
2503 else if (nir[r] > 0.0)
2507 double rho_total = 0.0, n_total = 0.0;
2508 for (std::size_t r = 0; r < K; ++r) {
2509 if (std::isfinite(
sn.classes[r].population))
continue;
2510 rho_total += sol.
UN(i, r);
2513 if (rho_total < 1.0) {
2514 logp += std::log(1.0 - rho_total) + std::lgamma(n_total + 1.0);
2515 for (std::size_t r = 0; r < K; ++r) {
2516 if (std::isfinite(
sn.classes[r].population) || !(nir[r] > 0.0))
continue;
2517 const double rho_r = sol.
UN(i, r);
2519 logp += nir[r] * std::log(rho_r) - std::lgamma(nir[r] + 1.0);
2529 for (std::size_t r = 0; r < K; ++r) {
2530 const double N =
sn.classes[r].population;
2531 if (!std::isfinite(N))
continue;
2532 const double q = sol.
QN(i, r);
2533 const double p = (N > 0.0) ? q / N : 0.0;
2535 logp += std::lgamma(N + 1.0) - std::lgamma(nir[r] + 1.0) - std::lgamma(N - nir[r] + 1.0);
2537 logp += nir[r] * std::log(p);
2538 }
else if (nir[r] > 0.0) {
2542 logp += (N - nir[r]) * std::log(1.0 - p);
2543 }
else if (N - nir[r] > 0.0) {
2549 if (logp_out) *logp_out = -std::numeric_limits<double>::infinity();
2552 if (logp_out) *logp_out = logp;
2553 return std::exp(logp);
UnsupportedError(const std::string &what)
FluidNonHyperbolicError(const std::string &what)
A network plus its refreshed NetworkStruct.
std::size_t nvars_of(std::size_t ind) const
Total local-variable width of node ind (1-based).
std::vector< JobClass > classes
std::size_t phasessz_of(std::size_t ist, std::size_t r) const
The exception types the port throws.
Fork-join section metrics: FJQLen, FJRespT and FJTput of every Fork/Join pair.
Age of Information by Markovian fluid queues: a port of solver_mfq_aoi.m (identical to solver_fluid_a...
Detects a moment-closure trajectory that has left the model.
The diffusion method: a port of solver_fluid_diffusion.m.
The matrix fluid method: a port of solver_fluid_matrix.m, the formulation of Ruuskanen,...
The mfq method: a port of solver_mfq.m and the single-queue gate fluid_is_single_queue....
Port of fluid_mfq_admits.m and fluid_is_single_queue.m: can the mfq fluid method (and its alias aoi) ...
The priority branch of the mfq method: a port of solver_mfq_prio.m.
Port of fluid_mvn_rectangle.m: the rectangle probability P(a <= Y <= b) for Y ~ Normal(m,...
The one exception the fluid fallback ladder catches.
The fluid drift: a port of solver_fluid_odes.m and the ode_jumps_new / ode_rate_base / ode_rates_clos...
The state-dependent fluid drifts: ports of ode_statedep.m, ode_softmin.m and ode_pnorm....
Port of ode_eliminate_immediate.m, eliminate_immediate_matrix.m and ode_solve_stiff....
The tbi method: a port of solver_fluid_tbi_iteration.m and tbi_partition.m.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
LSODA: the LINE-facing wrapper over the vendored solver in third_party/lsoda.hpp.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
bool sn_has_nonmarkov(const qn::NetworkStruct< T > &sn, bool preserve_det=false)
Whether any law in the struct would be replaced, so a caller can skip copying the struct when there i...
bool nonmkv_enabled(const std::string &method)
Resolve options.config.nonmkv to NonmarkovOptions::enabled.
@ Ph
Bernstein density fit: a genuine phase-type, shape-carrying.
void sn_nonmarkov_toph(qn::NetworkStruct< T > &sn, const NonmarkovOptions &opts=NonmarkovOptions())
Replace every non-Markovian service and firing law by a Markovian surrogate.
double fluid_default_horizon(const qn::NetworkStruct< T > &sn, const FluidOptions &opt)
The horizon a transient runs to when the caller gives none.
FluidMfqAdmits fluid_mfq_admits(const qn::NetworkStruct< T > &sn)
Port of fluid_mfq_admits.m.
std::vector< std::pair< std::size_t, std::size_t > > fluid_detect_nhpp(const qn::NetworkStruct< T > &sn)
Port of local_detect_nhpp in @@SolverFLD/getTranAvg.m: the (station, class) pairs whose SOURCE carrie...
FluidLayout fluid_layout(const qn::NetworkStruct< T > &sn)
Port of the layout half of solver_fluid_odes.m.
constexpr double kFluidConservationTol
Relative population drift that counts as having left the model.
std::vector< double > fluid_integrate_leg(const std::function< void(double, const double *, double *)> &f, double t0, double t1, const std::vector< double > &y0, const LsodaOptions &lopt)
One integration leg, with the reference's retry on a failed solve.
bool fluid_matrix_degenerate(const FluidMatrixSystem &s, const std::function< void(double, const double *, double *)> &drift, const std::vector< double > &x, std::size_t K)
Is the returned point one of a CONTINUUM of fixed points?
FluidMatrixSystem fluid_matrix_system(const qn::NetworkStruct< T > &sn, const std::vector< double > &init_sol, double pstar)
Assemble the matrix-form drift of sn.
void fluid_closing_metrics(const qn::NetworkStruct< T > &sn, const FluidOdeSystem &sys, const std::string &m, const std::vector< double > &xs, Matrix< double > &Q, Matrix< double > &U, Matrix< double > &R, Matrix< double > &T_)
Read Q/U/R/T off ONE fluid state, for the closing family.
ClosureValue fluid_capacity_closure(double n, double c, double s2, const std::vector< double > &lldrow, bool is_inf)
Port of fluid_capacity_closure.m: E[psi(X)] and its derivative, where psi(n) = min(n,...
double fluid_prob_aggr(const qn::NetworkStruct< T > &sn, const FluidSolution &sol, std::size_t ist, double *logp_out=nullptr)
Port of @@SolverFLD/getProbAggr: the probability that station ist holds the marginal population of th...
AoiTopology aoi_is_aoi(const qn::NetworkStruct< T > &sn)
Port of aoi_is_aoi.m.
StateDepKind
Which smoothing the drift applies at a saturated station.
double fluid_mvn_rectangle(const std::vector< double > &m, const Matrix< double > &C, const std::vector< double > &a, const std::vector< double > &b, std::size_t npoints=FLUID_MVN_POINTS)
P(a <= Y <= b) for Y ~ Normal(m, C).
DiffusionResult fluid_diffusion(const qn::NetworkStruct< T > &sn, const DiffusionOptions &opt)
Run the diffusion approximation of sn.
std::function< void(double, const double *, double *)> fluid_drift_statedep(const FluidStateDepSystem &s)
The drift dx/dt for the state-dependent family.
std::vector< std::vector< std::size_t > > tbi_check_partition(const qn::NetworkStruct< T > &sn, const std::vector< std::vector< std::size_t > > &cells)
The options.config.tbi_cells branch of tbi_partition.m: an explicit partition, returned as given once...
std::vector< FluidTranPoint > solver_fluid_transient(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, double t_end, std::size_t points=101, const std::vector< double > &out_grid=std::vector< double >())
Port of @@SolverFLD/getTranAvg: the metrics along the trajectory, not just at the fixed point.
FluidStateDepSystem fluid_statedep_system(const qn::NetworkStruct< T > &sn, StateDepKind kind, double alpha=20.0, double pstar=20.0)
Assemble what the state-dependent drifts need from sn.
FluidSolution solver_fluid(const qn::NetworkStruct< T > &sn_in, const FluidOptions &opt, qn::NetworkStruct< T > *sn_out=nullptr)
Port of solver_fluid_analyzer.m: dispatch on the method, refit the non-exponential FCFS stations the ...
MfqTopology mfq_is_single_queue(const qn::NetworkStruct< T > &sn)
Port of fluid_is_single_queue.m: the model must be one open class flowing Source -> Queue -> Sink and...
std::vector< FluidTranPoint > solver_fluid_tran_avg(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, std::size_t points=101)
getTranAvg on the first-order closing drift, over that horizon.
LsodaSolution fluid_integrate_grid(const std::function< void(double, const double *, double *)> &f, const std::vector< double > &y0, const std::vector< double > &grid, const LsodaOptions &lopt)
The same retry over a whole output grid, for the callers that ask LSODA for a trajectory rather than ...
FluidJacobian fluid_jacobian(const FluidSymSystem &sys, const FluidSymbolicOptions &opt=FluidSymbolicOptions())
Jacobian, drift and equilibria of the mean-field vector field.
int fluid_conservation_violation(const qn::NetworkStruct< T > &sn, const FluidLayout &L, const std::vector< double > &x, double tol=kFluidConservationTol)
The closed chain whose conserved population has drifted past tol, or -1.
MfqResult fluid_mfq(const qn::NetworkStruct< T > &sn, const MfqTopology &top, double tol)
Solve the single fluid queue of sn.
double fluid_prob_aggr_gaussian(const qn::NetworkStruct< T > &sn, const FluidSolution &sol, std::size_t i, const std::vector< double > &nir, double *logp_out=nullptr)
The joint probability of the per-class populations at station i (0-based) under the linear noise appr...
FluidOdeSystem fluid_ode_system(const qn::NetworkStruct< T > &sn)
Build the drift of sn: the port of ode_jumps_new and ode_rate_base fused into one pass.
std::function< void(double, const double *, double *)> fluid_drift(const FluidOdeSystem &sys)
The drift dx/dt, ready to hand to the integrator.
std::vector< std::vector< std::size_t > > tbi_partition(const qn::NetworkStruct< T > &sn, std::size_t cellsize=5)
Port of tbi_partition.m: stations grouped by routing coupling.
std::vector< double > tbi_advance(const FluidOdeSystem &sys, const std::vector< std::vector< std::size_t > > &cells, const std::vector< double > &y0, double t0, double t1, const TbiOptions &topt, const LsodaOptions &lopt)
Advance the state over [t0, t1] by time-based iteration.
void fluid_interpcols(const std::vector< double > &tg, const Matrix< double > &B, double tt, std::vector< double > &out)
Port of fluid_interpcols.m: clamped piecewise-linear interpolation of the columns of B at a scalar ti...
void fluid_rates_closing(const FluidOdeSystem &sys, const double *x, std::vector< double > &g)
The reference's ode_rates_closing name, kept for the first-order callers.
std::function< void(double, const double *, double *)> fluid_matrix_drift(const FluidMatrixSystem &s)
The drift dx/dt = W' theta(x) + A_lambda.
MfqPrioResult fluid_mfq_prio(const qn::NetworkStruct< T > &sn, const MfqTopology &top, double tol)
Solve the single priority fluid queue of sn.
FluidImmediateResult fluid_eliminate_immediate(const FluidOdeSystem &sys, double imm_tol=fluid_immediate_transition_tol())
Stochastic complementation of the INSTANTANEOUS coordinates of a fluid drift, the twin of ode_elimina...
bool fluid_hide_immediate(const qn::NetworkStruct< T > &sn, const Opt &opt)
Whether this model's fluid drift is built on the stochastic complement of its INSTANTANEOUS coordinat...
OdeSolution< double > fluid_ode_solve_stiff(const std::function< void(double, const double *, double *)> &f, double t0, double t1, const std::vector< double > &y0, const FluidStiffOptions &opt=FluidStiffOptions())
Port of ode_solve_stiff.m.
FluidAoiResult fluid_aoi(const qn::NetworkStruct< T > &sn, const AoiTopology &top, double preempt_override)
Port of solver_mfq_aoi.m.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
NodeType
Node kinds, with the values of MATLAB NodeType.
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
T map_lambda(const Map< T > &m)
Stationary arrival rate, lambda = pi D1 e.
NonexpApproxResult< T > npfqn_nonexp_approx(const std::string &method, const std::vector< bool > &isFCFS, const Matrix< T > &rates, const Matrix< T > &ST, const Matrix< T > &V, const Matrix< T > &SCV, const Matrix< T > &Tput, const Matrix< T > &U, const std::vector< T > &gamma, const std::vector< T > &nservers)
Handler for non-exponential service and arrival processes in AMVA and NC.
MarieCoxFit< T > marie_cox_fit(const T &mean, const T &scv)
Closed-form Coxian fit of a mean and an SCV (matlab/src/lang/processes/Coxian.m, fitMeanAndSCV),...
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
Conservation laws of a layered queueing network, enumerated from its structure.
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
A queueing network and its refreshed NetworkStruct.
Handler for non-exponential service and arrival processes in AMVA and NC.
Marie's iterative aggregation-decomposition for closed networks with FCFS general (Coxian) service.
Replace every non-Markovian service and firing law by a Markovian surrogate.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
double atol
absolute tolerance, applied to every component
double rtol
relative tolerance, applied to every component
Result of an integration, mirroring OdeSolution in ode.h.
std::vector< std::vector< double > > y
y[i] is the state at t[i]
std::vector< double > t
output times, t[0] = t_eval[0]
options.config.nonmkv and friends.
std::size_t order
nonmkvorder, the phase budget
PhFit phfit
which surrogate family
Both age laws of one system, with the policy parameter that produced them.
The second moment the drift closes its non-linear terms with, i.e.
Where each (station, class) block sits in the state vector.
std::vector< std::vector< std::size_t > > qidx
0-based first index of (i,r)
std::size_t nstates
length of the state vector
std::vector< std::vector< bool > > enabled
whether (i,r) is served at all
std::vector< std::vector< std::size_t > > kic
phases held by (i,r); 0 when disabled
The second-order results of the moment-closure methods, i.e.
std::vector< std::vector< std::vector< std::size_t > > > class_block
state coordinates of each (station,class): Sigma is indexed by SERVICE PHASE, so reading a per-class ...
Matrix< double > Sigma
state-level covariance, on range(D)
Matrix< double > QStd
per station and class queue-length variance
std::vector< double > refinement
the 1/N correction, mnrefined only
std::vector< double > sigma2
per-station population variance
The assembled drift: the layout, the events, and the per-station schedule.
FluidRateMult ratemult
solver_fluid_ratemult's multiplier; empty is the autonomous drift.
std::vector< std::vector< double > > lld
sn.lldscaling(i,:) per station, EMPTY when the station has none or when every entry is one – the refe...
options.config.rate_sched: explicit per-(station, class) rate trajectories, the third source solver_f...
std::size_t station
1-based
double nominal
The nominal baked into rate_base; <= 0 selects Mu{i}{c}(1).
std::vector< double > rates
std::vector< double > tgrid
Controls, defaulting to SolverOptions('Fluid') in the reference.
FluidClosure closure
options.config.moment_sigma2 and options.config.moment_cov: the second moment the drift's non-linear ...
std::vector< std::pair< std::size_t, std::size_t > > nhpp_sched
options.config.nhpp_sched: the (station, class) pairs whose SOURCE carries a non-homogeneous intensit...
std::vector< double > init_sol
initial state; empty selects the default below
double softmin_alpha
sharpness of the 'softmin' smoothing
std::string fork_join
options.config.fork_join: which fork-join arm the fixed point takes, 'default'/'mmt'/'fjt' or 'ht'.
std::vector< RateSched > rate_sched
std::string highvar
options.config.highvar: which non-exponential FCFS correction the analyzer's outer refit loop applies...
std::size_t nonmkv_order
options.config.nonmkvorder: the phase budget sn_nonmarkov_toph spends on a non-Markovian service law.
std::size_t dae_maxstate
options.config.dae_maxstate and options.config.dae_maxcov: the DAE route's own two refusal thresholds...
std::vector< double > kp_init_sol
options.config.kp_init_sol: the kp method's initial state, in the KO-PENDER layout – one offset count...
double pstar
exponent of the 'pnorm' smoothing
FluidRateMult rate_traj
options.config.rate_traj = {tgrid, Mmat}: a caller-supplied per-EVENT multiplier, which is what the c...
unsigned long seed
'diffusion' RNG seed
bool earlystop
options.config.fluid_earlystop: stop on the geometric tail of the window iteration
double iter_tol
>0 stops early when the moved-mass ratio falls below it; 0 runs to iter_max, as the reference does
double timestep
'diffusion' Euler-Maruyama step
double tol
absolute and relative tolerance handed to the integrator
bool hide_immediate
options.config.hide_immediate: fold the Immediate-rate transitions into the timed ones by stochastic ...
std::string fluid_boundary
options.config.fluid_boundary: how the Petri dae route reports a fluid place level held at a bound,...
std::string nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
double aoi_preemption
options.config.aoi_preemption: the preemption (bufferless) or replacement (single buffer) probability...
Matrix< double > init_qcov
options.config.init_qcov: the companion covariance of init_qlen, over the station-class pairs,...
std::size_t iter_max
cap on outer integrations
std::vector< std::vector< std::size_t > > tbi_cells
options.config.tbi_cells: an explicit partition for method tbi, as disjoint 0-BASED station index set...
Matrix< double > init_qlen
options.config.init_qlen: the kp method's initial state over (station, class) PAIRS,...
bool pstar_set
Opt in to the p-norm under matrix/default too, which is what options.config.pstar does in MATLAB,...
bool stiff
options.stiff: integrate the closing family with the explicit stiff arm of fluid_stiff....
Matrix< double > init_cov
options.config.init_cov: the kp method's initial covariance Sigma(0), dim-by-dim in the same layout a...
std::size_t moment_maxstate
options.config.moment_maxstate: the largest phase-resolved state the moment-closure methods will buil...
Port of solver_fluid_ratemult.m's output: a per-event MULTIPLIER on a time grid, evaluated by fluid_i...
What the analyzer returns, in the same shape as the MVA solver's result.
bool has_moments
result.solverSpecific.moments: set only by minnormal and mnrefined.
bool has_aoi
result.solverSpecific.aoiResults: set only by the AoI branch of mfq, where the age laws,...
FluidMomentReport moments
std::string warning
The reference's line_warning text, verbatim, empty when it did not warn.
std::vector< double > xvec
the converged fluid state
solvers::FjMetrics< double > fj
self.result.FJ, set by the fork-join arm (fluid_fork_join_run); empty otherwise.
std::size_t refit_sweeps
iter of solver_fluid_analyzer.m: the FCFS non-exponential refit sweeps.
One point of a transient trajectory: the metrics at time t.
Matrix< double > QCov
The same second moment as a FULL (M*K)-by-(M*K) covariance, indexed ir = r*M + i, empty wherever QVar...
Matrix< double > QVar
Per-(station,class) queue-length VARIANCE at this instant, empty where the method carries no second m...
static Distrib coxian(const std::vector< T > &mu, const std::vector< T > &phi)
Coxian(mu, phi): phase i completes with probability phi(i) and otherwise moves to phase i+1.
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
static constexpr double FineTol
static constexpr double Zero
static constexpr double CoarseTol
A MAP as the pair of matrices (D0, D1).
self.result.FJ: one row per Fork/Join pair, one column per class.