555 return ::line::method_registry::methods(
"LN");
567 opt.layer_ssa.verbose =
false;
569 for (
char& ch : opt.interlock_refpath_scope)
570 ch =
char(std::tolower(
static_cast<unsigned char>(ch)));
571 if (opt.interlock_refpath_scope !=
"merging" && opt.interlock_refpath_scope !=
"all")
572 throw InputError(
"Unknown config.interlock_refpath_scope '" +
573 opt.interlock_refpath_scope +
"', use 'merging' or 'all'.");
574 if (std::isnan(opt.interlock_maxpaths) || opt.interlock_maxpaths < 0.0)
575 throw InputError(
"config.interlock_maxpaths must be a non-negative number.");
576 validate_nlp_options();
583 const std::vector<double>&
nlp_solution()
const {
return nlp_solution_; }
594 o.
alpha = opt.nlp_alpha;
595 o.
fork = opt.nlp_fork;
596 return ::line::lqn::lqn_nlp_program(lqn, o);
605 if (opt.method ==
"mw.upper" || opt.method ==
"mw.lower")
return box_bounds();
607 if (lnmethod ==
"nlp")
return nlp_analyzer();
613 return trapped_overlay(is_ph_encoding() ? aggregate_ph() : aggregate());
623 if (!zerocap.any_trapped())
return s;
625 for (std::size_t idx = 1; idx <= lqn.nidx; ++idx) {
626 if (!zerocap.onroute[idx])
continue;
628 switch (lqn.type[idx]) {
629 case LqnElement::TASK:
631 if (ignore[idx] || !s.
defined_Q[idx]) s.
QN[idx] = Tzero();
632 s.
QN[idx] = T(s.
QN[idx] + held);
634 if (ignore[idx] && !lqn.isref[idx]) {
639 case LqnElement::ENTRY:
640 case LqnElement::ACTIVITY:
645 if (lqn.type[idx] == LqnElement::ACTIVITY) {
670 if (lnmethod ==
"nlp")
672 "method='nlp' solves for means only and builds no layers, so there is no response-time "
673 "distribution to report. Use method='moment3' for getCdfRespT.");
674 if (lqn.nentries == 0)
return entrycdfrespt;
675 if (entrycdfrespt.size() <= lqn.nentries || entrycdfrespt[1].empty()) {
682 if (is_ph_encoding())
684 "getCdfRespT needs the routing encoding of the activity graph, which "
685 "method='srvn.ph' does not build. Rebuild the solver with "
686 "method='srvn.cs' or method='moment3'.");
693 const std::string saved = opt.method;
694 const std::string saved_resolved = lnmethod;
695 opt.method =
"moment3";
696 lnmethod =
"moment3";
700 lnmethod = saved_resolved;
702 return entrycdfrespt;
713 if (lnmethod ==
"nlp")
715 "method='nlp' states the steady state as one program and builds no layers, so there is "
716 "no layer transient to integrate. Use a layered method ('srvn.cs', 'flat.cs') for getTranAvg.");
717 if (opt.ln_transient ==
"decoupled")
return tran_avg_decoupled();
718 if (opt.ln_transient ==
"coupled")
return tran_avg_coupled();
719 throw InputError(
"SolverLN: unknown ln_transient mode '" + opt.ln_transient +
720 "' (use 'coupled' or 'decoupled')");
737 if (lnmethod ==
"nlp")
739 "method='nlp' states the model as one program and builds no layers, so there are no "
740 "per-layer sensitivities to report. Use a layered method ('srvn', 'srvn.ph', 'flat.cs') "
741 "for getSensitivityTable.");
742 if (results.empty()) iterate();
746 for (std::size_t e = 0; e < ensemble.size(); ++e) {
749 so.
replicate = [
this](std::size_t k, std::size_t n) {
750 this->sens_rep_k = k;
751 this->sens_rep_n = n;
753 const bool exact_available =
754 opt.layer_solver ==
"mva" || opt.layer_solver ==
"nc";
756 ensemble[e], so, exact_available && !fj_tr[e].active(),
757 [
this, e]() {
return this->solve_layer(e); });
761 row.layer = ensemble[e].name;
768 out.
rows.push_back(row);
775 if (m.empty())
continue;
791 const bool upper = opt.method !=
"mw.lower";
796 const std::size_t N = lqn.nidx;
797 auto blank = [&](std::vector<T>& v, std::vector<bool>& d) {
798 v.assign(N + 1, Tzero());
799 d.assign(N + 1,
false);
807 for (std::size_t i = 1; i <= N; ++i) {
808 if (b.defined_T[i]) {
809 s.
TN[i] = upper ? b.TN_up[i] : b.TN_lo[i];
812 if (b.defined_U[i]) {
813 s.
UN[i] = upper ? b.UN_up[i] : b.UN_lo[i];
823 std::size_t
nlayers()
const {
return ensemble.size(); }
824 const std::vector<qn::Layer<T>>&
layers()
const {
return ensemble; }
836 const std::size_t E = ensemble.size();
841 for (std::size_t e = 0; e < E; ++e) {
844 b.
msz[e] = ensemble[e].nstations;
845 b.
ksz[e] = ensemble[e].nclasses;
862 if (results.empty() || results.back().size() < ensemble.size())
863 throw InputError(
"SolverLN::get_block_avg reads the layer averages of the last fixed-point "
864 "iterate; call get_ensemble_avg first");
871 for (std::size_t i = 0; i < b.
msz[e] && i < S.
rows(); ++i)
872 for (std::size_t r = 0; r < b.
ksz[e] && r < S.
cols(); ++r)
874 D(b.
roff[e] + i, b.
coff[e] + r) = S(i, r);
876 for (std::size_t e = 0; e < ensemble.size(); ++e) {
907 const std::size_t E = ensemble.size();
908 layer_tran_init.assign(E, std::vector<double>());
909 if (n.
empty())
return;
913 "SolverLN::init_from_marginal: the marginal is " + std::to_string(n.
rows()) +
"x" +
914 std::to_string(n.
cols()) +
" where the block-diagonal union of the layers is " +
915 std::to_string(b.
M) +
"x" + std::to_string(b.
K) +
916 "; the aggregate view is layerBlocks', not the LQN element count");
917 for (std::size_t e = 0; e < E; ++e) {
920 std::vector<double> y(lay.
nstates, 0.0);
922 for (std::size_t i = 0; i < L.
nstations && i < b.
msz[e]; ++i)
923 for (std::size_t r = 0; r < L.
nclasses && r < b.
ksz[e]; ++r) {
924 if (!lay.
enabled[i][r])
continue;
925 const double q = std::max(0.0, n(b.
roff[e] + i, b.
coff[e] + r));
926 y[lay.
qidx[i][r]] = q;
927 if (q > 0.0) any =
true;
933 if (any) layer_tran_init[e] = y;
980 std::vector<qn::Layer<T>> ensemble;
981 std::vector<long> idxhash;
982 std::vector<bool> ignore;
987 std::size_t idx, aidx, node, cls;
989 std::vector<UpdRow> servt_map, thinkt_map, call_map, actthinkt_map;
999 std::vector<UpdRow> arv_call_map;
1002 std::size_t idx, tidx_caller, eidx, nodefrom, nodeto, cfrom, cto;
1004 std::vector<RouteRow> route_map;
1005 std::vector<std::size_t> unique_route_idx;
1006 std::vector<std::size_t> route_reset, svc_reset;
1009 std::string interlockMethod =
"ilrate";
1017 std::size_t idx, node, cls;
1021 std::size_t fromentry;
1023 std::vector<RefPathRow> refpath_map;
1025 std::vector<std::array<std::size_t, 3>> refpath_keys;
1026 std::vector<std::size_t> refpath_group;
1028 std::vector<double> refpath_stage_prev;
1029 std::vector<T> refpath_stage_prev_v;
1035 std::map<std::size_t, std::vector<std::size_t>> layer_normclass;
1037 std::vector<T> entryvisits;
1039 Matrix<double> njobs;
1042 std::vector<T> servt, residt, tput, util, thinkt;
1043 std::vector<T> callservt, callresidt;
1050 bool has_phase2 =
false;
1051 std::vector<T> servt_ph1, servt_ph2, prOvertake;
1053 std::vector<T> entry_servt_last, entry_servt_ph2;
1054 std::vector<T> join_tail;
1056 std::set<std::size_t> single_replica_tasks;
1063 std::map<std::size_t, std::size_t> host_all_replica_tasks;
1064 std::vector<Distrib<T>> servtproc, thinkproc, thinktproc, tputproc, callservtproc;
1070 std::vector<fluid::FluidPassage> servtcdf, callservtcdf;
1071 std::vector<LnCdf> entrycdfrespt;
1072 std::vector<mam::AphPair<T>> entryproc;
1074 std::vector<std::vector<std::vector<fluid::FluidPassage>>> cdf_repo;
1075 std::vector<double> servt_prev, residt_prev, tput_prev, thinkt_prev;
1076 std::vector<double> callservt_prev, callresidt_prev;
1077 std::vector<T> servt_prev_v, residt_prev_v, tput_prev_v, thinkt_prev_v, callservt_prev_v;
1078 Matrix<T> servtmatrix;
1081 Matrix<T> il_all, il_ph1;
1082 std::vector<std::vector<std::size_t>> il_common_entries, il_src_all, il_src_ph2;
1088 std::vector<std::vector<std::vector<double>>> layer_interlock;
1089 std::vector<double> il_num_sources;
1091 std::vector<std::vector<LayerResult<T>>> results;
1099 std::size_t sens_rep_k = 0, sens_rep_n = 0;
1107 std::vector<LayerResult<T>> results_raw_last;
1108 bool results_raw_valid =
false;
1109 std::vector<Matrix<T>> layer_init_sol;
1114 std::vector<std::vector<double>> layer_tran_init;
1126 std::vector<mva::FjMmt<T>> fj_tr;
1127 std::vector<std::vector<T>> fj_lambda;
1128 double relax_omega = 1.0;
1130 std::shared_ptr<LnStochController<T>> stoch_ctl;
1131 long averagingstart = -1;
1132 bool hasconverged =
false;
1134 bool warmstarted_ =
false;
1136 std::vector<double> nlp_solution_;
1137 double nlp_objective_ = std::numeric_limits<double>::quiet_NaN();
1139 bool moment_pass_done =
false;
1140 std::vector<double> maxitererr;
1141 int iterations_done = 0;
1142 bool did_converge =
false;
1144 std::size_t NT()
const {
return lqn.tshift + lqn.ntasks; }
1146 static T Tzero() {
return num_traits<T>::from_int(0); }
1147 static T Tone() {
return num_traits<T>::from_int(1); }
1148 static double dbl(
const T& x) {
return num_traits<T>::to_double(x); }
1160 reject_unsupported();
1163 const std::size_t N = lqn.nidx;
1164 ignore.assign(N + 1,
false);
1167 std::vector<long> comp(N + 1, -1);
1169 for (std::size_t v = 1; v <= N; ++v) {
1170 if (comp[v] >= 0)
continue;
1171 std::vector<std::size_t>
stack{v};
1173 while (!
stack.empty()) {
1174 const std::size_t u =
stack.back();
1176 for (std::size_t w : lqn.graph.succ(u))
1181 for (std::size_t w : lqn.graph.pred(u))
1190 std::vector<bool> has_ref(ncomp,
false);
1191 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1192 const std::size_t tidx = lqn.tshift + t;
1193 if (lqn.sched[tidx] == SchedStrategy::REF) has_ref[comp[tidx]] =
true;
1195 for (std::size_t v = 1; v <= N; ++v)
1196 if (!has_ref[comp[v]]) ignore[v] =
true;
1201 if (!zerocap.reason.empty())
throw UnsupportedError(ErrorKind{
"Structure"}, zerocap.reason);
1202 if (zerocap.any_trapped()) {
1203 if (ln_requested_method(opt.method) ==
"nlp")
1205 "method='nlp' cannot solve a model whose reference task is trapped at a "
1206 "zero-capacity element; use a layered method.");
1207 if (num_traits<T>::is_exact)
1209 "A reference task trapped at a zero-capacity element has infinite response "
1210 "times, which exact arithmetic cannot represent; solve it in double precision.");
1212 for (std::size_t v = 1; v <= N; ++v)
1213 if (zerocap.ignore[v]) ignore[v] =
true;
1214 if (zerocap.any_trapped()) {
1216 std::vector<double> liveMult = lqn.mult;
1217 for (std::size_t i = 1; i < liveMult.size(); ++i)
1218 if (zerocap.trapped[i]) liveMult[i] = 0.0;
1226 for (std::size_t i = 1; i <= N; ++i) {
1227 servtproc[i] = lqn.hostdem[i];
1228 thinkproc[i] = lqn.think[i];
1231 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
1232 callservtproc[c] = lqn.hostdem[lqn.callpair_dst[c]];
1236 entryvisits.assign(N + 1, Tone());
1237 refpath_map.clear();
1238 layer_normclass.clear();
1240 njobs = Matrix<double>(NT() + 1, NT() + 1, 0.0);
1245 if (ln_requested_method(opt.method) ==
"nlp" || !zerocap.live) {
1246 if (zerocap.live) lnmethod =
"nlp";
1252 std::vector<bool> rr(NT() + 1,
false), sr(NT() + 1,
false);
1253 for (
const RouteRow& r : route_map) rr[r.idx] =
true;
1254 for (
const UpdRow& r : thinkt_map) sr[r.idx] =
true;
1255 for (
const UpdRow& r : call_map) sr[r.idx] =
true;
1261 for (
const RefPathRow& r : refpath_map) sr[r.idx] =
true;
1264 for (
const UpdRow& r : arv_call_map) rr[r.idx] =
true;
1265 for (std::size_t i = 1; i <= NT(); ++i) {
1266 if (rr[i] && idxhash[i] >= 0) route_reset.push_back(std::size_t(idxhash[i]));
1267 if (sr[i] && idxhash[i] >= 0) svc_reset.push_back(std::size_t(idxhash[i]));
1269 std::sort(route_reset.begin(), route_reset.end());
1270 route_reset.erase(std::unique(route_reset.begin(), route_reset.end()), route_reset.end());
1271 std::sort(svc_reset.begin(), svc_reset.end());
1272 svc_reset.erase(std::unique(svc_reset.begin(), svc_reset.end()), svc_reset.end());
1275 refpath_keys.clear();
1276 refpath_group.clear();
1277 for (
const RefPathRow& r : refpath_map) refpath_keys.push_back({r.idx, r.node, r.cls});
1278 std::sort(refpath_keys.begin(), refpath_keys.end());
1279 refpath_keys.erase(std::unique(refpath_keys.begin(), refpath_keys.end()),
1280 refpath_keys.end());
1281 for (
const RefPathRow& r : refpath_map) {
1282 const std::array<std::size_t, 3> key{r.idx, r.node, r.cls};
1283 refpath_group.push_back(std::size_t(
1284 std::lower_bound(refpath_keys.begin(), refpath_keys.end(), key) -
1285 refpath_keys.begin()));
1287 if (refpath_map.empty() && interlockMethod ==
"refpath") {
1294 interlockMethod =
"ilrate";
1296 refpath_stage_prev.assign(refpath_keys.size(), std::numeric_limits<double>::quiet_NaN());
1297 refpath_stage_prev_v.assign(refpath_keys.size(), Tzero());
1305 void detect_phase2() {
1307 for (std::size_t a = 1; a <= lqn.nacts; ++a)
1308 if (lqn.actphase[a] > 1) has_phase2 =
true;
1312 for (std::size_t aidx = 1; aidx <= lqn.nidx && aidx < lqn.actquorum.size(); ++aidx) {
1313 if (lqn.actquorum[aidx] < 1)
continue;
1314 std::size_t nbranches = 0;
1315 for (std::size_t tail = 1; tail <= lqn.nidx; ++tail) {
1316 if (tail == aidx || lqn.actpretype[tail] != PrecedenceType::PRE_AND)
continue;
1317 for (std::size_t sx : lqn.graph.succ(tail))
1318 if (sx == aidx) ++nbranches;
1320 if (lqn.actquorum[aidx] < nbranches) has_phase2 =
true;
1333 bool is_fwd_target(std::size_t eidx)
const {
1334 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
1335 if (lqn.calltype[c] == CallType::FWD && lqn.callpair_dst[c] == eidx)
return true;
1352 double open_arrival_rate_of(std::size_t tidx)
const {
1353 if (lqn.isref[tidx])
return 0.0;
1354 for (std::size_t e : lqn.entriesof[tidx])
1355 if (lqn.issynccaller.any_col(e) || lqn.isasynccaller.any_col(e) || is_fwd_target(e))
1358 for (std::size_t e : lqn.entriesof[tidx]) {
1359 if (!lqn.has_arrival[e])
continue;
1360 const double m = dbl(lqn.arrival[e].mean);
1373 T sync_call_residt_of(
const std::vector<std::size_t>& acts)
const {
1375 for (std::size_t aidx : acts)
1376 for (std::size_t cidx : lqn.callsof[aidx])
1377 if (lqn.calltype[cidx] == CallType::SYNC && cidx < callresidt.size() &&
1378 std::isfinite(dbl(callresidt[cidx])))
1379 total += callresidt[cidx];
1384 T open_arrival_call_residt(std::size_t tidx,
double arvrate)
const {
1386 if (!(arvrate > 0.0))
return total;
1387 for (std::size_t e : lqn.entriesof[tidx]) {
1388 if (!lqn.has_arrival[e])
continue;
1389 const double m = dbl(lqn.arrival[e].mean);
1391 total += T(num_traits<T>::from_double(1.0 / m / arvrate) *
1392 sync_call_residt_of(lqn.actsof[e]));
1398 bool has_cache_node(std::size_t e)
const {
1399 for (std::size_t n = 0; n < ensemble[e].nodes.size(); ++n)
1400 if (ensemble[e].nodes[n].nodetype == NodeType::Cache)
return true;
1405 bool async_only_activity(std::size_t aidx)
const {
1406 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts)
return false;
1407 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
1408 const std::size_t eidx = lqn.eshift + e;
1409 if (lqn.graph.get(eidx, aidx) == Tzero())
continue;
1410 return lqn.isasynccaller.any_col(eidx) && !lqn.issynccaller.any_col(eidx);
1425 void reject_unsupported()
const {}
1432 void resolve_interlock_method() {
1433 const LnInterlockChoice ch =
1435 interlockMethod = ch.method;
1436 if (!ch.why.empty()) std::cerr <<
"[LINE] Warning: " << ch.why <<
"\n";
1442 void build_layers() {
1449 const std::string requested = ln_requested_method(opt.method);
1450 assert_call_groups(requested ==
"flat.cs");
1451 if (requested ==
"flat.cs") {
1452 lnmethod =
"flat.cs";
1453 resolve_interlock_method();
1457 if (requested ==
"flat.ph") {
1462 ph_laws_ready =
false;
1463 lnmethod =
"flat.ph";
1464 assert_warmstart_encoding();
1465 build_layers_ph(
true);
1468 if (requested ==
"srvn.ph" || requested ==
"srvn") {
1469 ph_laws_ready =
false;
1471 if (requested ==
"srvn.ph" || (!has_interlock() && probe_srvn_ph())) {
1472 lnmethod =
"srvn.ph";
1473 assert_warmstart_encoding();
1478 lnmethod = (requested ==
"moment3") ?
"moment3" :
"srvn.cs";
1479 resolve_interlock_method();
1480 std::vector<qn::Layer<T>> raw(NT() + 1);
1481 std::vector<bool> present(NT() + 1,
false);
1483 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
1484 if (ignore[hidx])
continue;
1485 std::vector<std::size_t> hcallers;
1486 for (std::size_t c : lqn.tasksof[hidx])
1487 if (!ignore[c]) hcallers.push_back(c);
1488 build_layer(raw[hidx], {hidx}, hcallers,
true,
false);
1489 present[hidx] =
true;
1491 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1492 const std::size_t tidx = lqn.tshift + t;
1493 if (ignore[tidx] || lqn.isref[tidx])
continue;
1494 bool any_caller = lqn.iscaller.any_row(tidx) || lqn.iscaller.any_col(tidx);
1495 if (!any_caller)
continue;
1497 std::vector<std::size_t> callers;
1498 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
1499 const std::size_t c = lqn.tshift + ct;
1500 if (ignore[c])
continue;
1502 for (std::size_t e : lqn.entriesof[tidx])
1503 if (lqn.iscaller.get(c, e)) calls =
true;
1504 if (calls) callers.push_back(c);
1506 if (callers.empty())
continue;
1507 build_layer(raw[tidx], {tidx}, callers,
false,
false);
1508 present[tidx] =
true;
1511 idxhash.assign(lqn.nidx + 1, -1);
1513 for (std::size_t i = 1; i <= NT(); ++i)
1515 idxhash[i] = next++;
1516 ensemble.push_back(std::move(raw[i]));
1518 layer_init_sol.assign(ensemble.size(), Matrix<T>());
1537 void assert_call_groups(
bool flat)
const {
1538 if (lqn.callgroups.empty())
return;
1541 "Call groups routed by a routing strategy require the squashed layering; use "
1542 "method='flat'. Under srvn the targets never share a submodel, so the dispatch "
1543 "order cannot be represented.");
1544 if (!layer_solver_is_stochastic())
1546 "Routed call groups need a layer solver that resolves the strategy from the "
1547 "state; set layer_solver='ssa', 'ldes' or 'jmt'. MVA, NC and FLD read the routing matrix, into "
1548 "which refresh_routing has expanded the strategy as a uniform split, and would "
1549 "return that split under a round-robin or JSQ label.");
1561 std::vector<std::size_t> flat_server_set()
const {
1562 std::vector<std::size_t> servers;
1563 for (std::size_t i = 1; i <= NT(); ++i) {
1564 if (lqn.repl[i] > 1.0)
1566 "Flat layering does not support replicated processors or tasks, use the "
1567 "default 'srvn' layering.");
1570 "Flat layering does not support cache tasks, use the default 'srvn' "
1572 if (lqn.hassetup[i])
1574 "Flat layering does not support setup tasks, use the default 'srvn' "
1577 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx)
1578 if (!ignore[hidx] && !lqn.tasksof[hidx].empty()) servers.push_back(hidx);
1579 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1580 const std::size_t tidx = lqn.tshift + t;
1581 if (ignore[tidx] || lqn.isref[tidx])
continue;
1582 if (!lqn.iscaller.any_row(tidx) && !lqn.iscaller.any_col(tidx))
continue;
1583 bool has_task_caller =
false;
1584 for (std::size_t eidx : lqn.entriesof[tidx])
1585 for (std::size_t c = 1; c <= lqn.ntasks; ++c)
1586 if (lqn.iscaller.get(lqn.tshift + c, eidx)) has_task_caller =
true;
1587 if (has_task_caller) servers.push_back(tidx);
1589 if (servers.empty())
1591 "Flat layering found no server: the model has no processor with tasks.");
1603 void build_flat_layer() {
1604 const std::vector<std::size_t> flat_servers = flat_server_set();
1605 std::vector<std::size_t> flat_callers;
1606 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
1607 const std::size_t tidx = lqn.tshift + t;
1608 if (!ignore[tidx]) flat_callers.push_back(tidx);
1611 build_layer(layer, flat_servers, flat_callers,
false,
true);
1613 ensemble.push_back(std::move(layer));
1614 idxhash.assign(lqn.nidx + 1, -1);
1615 for (std::size_t s : flat_servers) idxhash[s] = 0;
1616 layer_init_sol.assign(ensemble.size(), Matrix<T>());
1624 void build_fork_views() {
1625 fj_tr.assign(ensemble.size(), mva::FjMmt<T>());
1626 fj_lambda.assign(ensemble.size(), {});
1627 for (std::size_t e = 0; e < ensemble.size(); ++e) {
1628 if (!ensemble[e].has_fork())
continue;
1635 if (ensemble[e].sourceIdx != 0)
1637 "SolverLN: layer '" + ensemble[e].name +
1638 "' carries both an AND fork and an open stream (an async call or an entry "
1639 "arrival); the fork-join transform needs a Source of its own");
1641 fj_lambda[e].assign(fj_tr[e].V.classes.size() + 1,
1662 const std::shared_ptr<std::vector<std::vector<std::size_t>>>& chaincols, std::size_t R) {
1663 return [f, cols, chaincols, R](
const std::vector<T>& n) -> std::vector<T> {
1664 const std::size_t L = n.size();
1665 const std::vector<std::vector<std::size_t>>& use =
1666 (L == R || chaincols->empty()) ? cols : *chaincols;
1667 std::vector<T> nop(use.size(), num_traits<T>::from_int(0));
1668 for (std::size_t j = 0; j < use.size(); ++j)
1669 for (std::size_t k = 0; k < use[j].size(); ++k)
1670 if (use[j][k] < L) nop[j] = T(nop[j] + n[use[j][k]]);
1671 const std::vector<T> w = f(nop);
1672 std::vector<T> v(L, num_traits<T>::from_int(1));
1673 if (w.empty())
return v;
1674 for (std::size_t j = 0; j < use.size(); ++j) {
1675 const T wj = w[j < w.size() ? j : w.size() - 1];
1676 for (std::size_t k = 0; k < use[j].size(); ++k)
1677 if (use[j][k] < L) v[use[j][k]] = wj;
1684 static std::vector<T> layer_peak(
const std::vector<T>& peakPerOperand,
1685 const std::vector<std::vector<std::size_t>>& cols,
1687 std::vector<T> peak(R, num_traits<T>::from_int(1));
1688 if (peakPerOperand.empty())
return peak;
1689 for (std::size_t j = 0; j < cols.size(); ++j) {
1690 const T pj = peakPerOperand[j < peakPerOperand.size() ? j : peakPerOperand.size() - 1];
1691 for (std::size_t k = 0; k < cols[j].size(); ++k)
1692 if (cols[j][k] < R) peak[cols[j][k]] = pj;
1706 void apply_host_task_priorities(qn::Layer<T>& m,
const std::vector<std::size_t>& idxSet)
const {
1709 return s == SchedStrategy::HOL || s == SchedStrategy::FCFSPRPRIO ||
1710 s == SchedStrategy::FCFSPIPRIO || s == SchedStrategy::LCFSPRIO ||
1711 s == SchedStrategy::LCFSPRPRIO || s == SchedStrategy::LCFSPIPRIO ||
1712 s == SchedStrategy::PSPRIO || s == SchedStrategy::DPSPRIO ||
1713 s == SchedStrategy::GPSPRIO;
1715 const std::size_t R = m.classes.size();
1716 std::vector<std::size_t> owner(R + 1, 0);
1717 auto own = [&](std::size_t k, std::size_t t) {
1718 if (k >= 1 && k <= R && owner[k] == 0) owner[k] = t;
1720 for (
const auto& a : m.attr_tasks) own(a.first, a.second);
1721 for (
const auto& a : m.attr_entries) own(a.first, lqn.parent[a.second]);
1722 for (
const auto& a : m.attr_activities) own(a.first, lqn.parent[a.second]);
1723 for (
const auto& a : m.attr_calls) own(a[0], lqn.parent[a[2]]);
1724 for (std::size_t s : idxSet) {
1725 if (s < 1 || s > lqn.nhosts || !
is_prio(lqn.sched[s]))
continue;
1727 for (std::size_t t = lqn.tshift + 1; t <= lqn.tshift + lqn.ntasks; ++t)
1728 if (lqn.parent[t] == s) pmax = std::max(pmax, lqn.prio[t]);
1729 for (std::size_t k = 1; k <= R; ++k)
1730 if (owner[k] != 0 && lqn.parent[owner[k]] == s)
1731 m.classes[k - 1].prio = pmax - lqn.prio[owner[k]];
1744 void build_layer(qn::Layer<T>& m,
const std::vector<std::size_t>& idxSet,
1745 const std::vector<std::size_t>& callers,
bool ishostlayer,
bool flat) {
1746 const T one = Tone();
1750 const std::size_t idx = idxSet[0];
1751 m.name = flat ? lqn.hashnames[idx] +
".Flat" : lqn.hashnames[idx];
1754 const double rawrepl = lqn.repl[idx];
1755 std::size_t nreplicas = 1;
1756 if (!flat && rawrepl > 1.0 && !callers.empty()) {
1765 for (std::size_t c : callers)
1766 if (lqn.repl[c] != rawrepl) reduce =
false;
1768 for (std::size_t c : callers)
1769 if (lqn.fanout_at(c, idx) < rawrepl) reduce =
false;
1771 nreplicas = reduce ? 1 :
static_cast<std::size_t
>(std::llround(rawrepl));
1772 if (reduce && !ishostlayer) single_replica_tasks.insert(idx);
1774 const bool reduce_fanout = (nreplicas == 1 && rawrepl > 1.0 && !callers.empty());
1775 const std::vector<double>&
mult = lqn.maxmult;
1779 m.clientIdx = m.add_station(qn::Station<T>{
"Clients", NodeType::Delay, SchedStrategy::INF,
1780 std::numeric_limits<double>::infinity(),
false, 0});
1781 const std::size_t clientNode = m.node_of_station(m.clientIdx);
1782 m.serverIdx = m.clientIdx + 1;
1786 std::vector<std::vector<std::size_t>> srv(lqn.nidx + 1);
1787 std::vector<std::vector<std::size_t>> srvnode(lqn.nidx + 1);
1788 m.server_idx_of.assign(lqn.nidx + 1, 0);
1789 for (std::size_t sidx : idxSet) {
1790 const bool sishost = sidx <= lqn.nhosts;
1791 srv[sidx].resize(nreplicas);
1792 for (std::size_t r = 0; r < nreplicas; ++r) {
1794 st.name = r == 0 ? lqn.hashnames[sidx]
1795 : lqn.hashnames[sidx] +
"." + std::to_string(r + 1);
1798 lqn.sched[sidx] == SchedStrategy::INF ? NodeType::Delay : NodeType::Queue;
1799 st.sched = lqn.sched[sidx];
1801 st.nservers = lqn.sched[sidx] == SchedStrategy::INF
1802 ? std::numeric_limits<double>::infinity()
1804 st.attr_ishost = flat ? sishost : ishostlayer;
1806 srv[sidx][r] = m.add_station(st);
1807 srvnode[sidx].push_back(m.node_of_station(srv[sidx][r]));
1809 m.server_idx_of[sidx] = srv[sidx][0];
1811 m.host_stations.push_back(srv[sidx][0]);
1813 m.task_stations.push_back(srv[sidx][0]);
1816 const std::vector<std::size_t>& server = srv[idx];
1817 const std::vector<std::size_t>& serverNode = srvnode[idx];
1820 auto servers_for = [&](std::size_t
elem) ->
const std::vector<std::size_t>& {
1821 static const std::vector<std::size_t> none;
1822 if (elem >= 1 && elem <= lqn.nidx && !srv[elem].empty())
return srv[
elem];
1825 auto server_nodes_for = [&](std::size_t
elem) ->
const std::vector<std::size_t>& {
1826 static const std::vector<std::size_t> none;
1827 if (elem >= 1 && elem <= lqn.nidx && !srvnode[elem].empty())
return srvnode[
elem];
1831 auto host_is_server = [&](std::size_t tidx_) {
1832 return !servers_for(lqn.parent[tidx_]).empty();
1835 auto is_layer_client = [&](std::size_t tidx_) {
1836 for (std::size_t s : idxSet)
1837 for (std::size_t e : lqn.entriesof[s])
1838 if (lqn.issynccaller.get(tidx_, e))
return true;
1842 auto set_all_servers = [&](std::size_t cl,
const Distrib<T>& d) {
1843 for (std::size_t s : idxSet)
1844 for (std::size_t st : srv[s]) m.set_service(st, cl, d);
1852 std::vector<std::size_t> group_of_call(lqn.ncalls + 1, 0);
1853 std::vector<std::vector<std::size_t>> group_members(lqn.callgroups.size() + 1);
1854 for (std::size_t g = 0; g < lqn.callgroups.size(); ++g) {
1855 const LqnCallGroup& grp = lqn.callgroups[g];
1856 for (std::size_t tgt : grp.
targets)
1857 for (std::size_t cidx : lqn.callsof[grp.
caller])
1858 if (lqn.callpair_dst[cidx] == tgt && lqn.calltype[cidx] == CallType::SYNC &&
1859 group_of_call[cidx] == 0) {
1860 group_of_call[cidx] = g + 1;
1861 group_members[g + 1].push_back(cidx);
1866 std::vector<std::size_t> grp_router(lqn.callgroups.size() + 1, 0);
1867 std::vector<std::size_t> grp_dispatch(lqn.callgroups.size() + 1, 0);
1868 std::vector<std::size_t> grp_class(lqn.callgroups.size() + 1, 0);
1871 std::vector<std::array<std::size_t, 3>> routed_group_sites;
1874 std::vector<std::size_t> acts_in_caller;
1875 for (std::size_t c : callers)
1876 for (std::size_t a : lqn.actsof[c]) acts_in_caller.push_back(a);
1877 bool hasfork =
false, hasjoin =
false;
1878 std::size_t maxfanout = 1;
1879 for (std::size_t a : acts_in_caller) {
1880 if (lqn.actposttype[a] == PrecedenceType::POST_AND) hasfork =
true;
1881 if (lqn.actpretype[a] == PrecedenceType::PRE_AND) hasjoin =
true;
1882 std::size_t nand = 0;
1883 for (std::size_t sx : lqn.graph.succ(a))
1884 if (lqn.actposttype[sx] == PrecedenceType::POST_AND) ++nand;
1885 if (nand > maxfanout) maxfanout = nand;
1887 std::size_t forkNode = 0, joinNode = 0, joinStation = 0;
1888 std::vector<std::size_t> forkRouter;
1890 forkNode = m.add_node(
"Fork_PostAnd", NodeType::Fork,
false);
1891 for (std::size_t f = 1; f <= maxfanout; ++f)
1892 forkRouter.push_back(
1893 m.add_node(
"Fork_PostAnd_" + std::to_string(f), NodeType::Router,
true));
1897 js.name =
"Join_PreAnd";
1898 js.nodetype = NodeType::Join;
1899 js.sched = SchedStrategy::INF;
1900 js.nservers = std::numeric_limits<double>::infinity();
1901 js.attr_ishost =
false;
1903 joinStation = m.add_station(js);
1904 joinNode = m.node_of_station(joinStation);
1905 if (forkNode) m.fj.emplace_back(forkNode, joinNode);
1912 bool iscachelayer = !flat && ishostlayer && !callers.empty();
1913 for (std::size_t c : callers)
1914 if (!lqn.iscache[c]) iscachelayer =
false;
1923 std::size_t cacheNode = 0;
1924 qn::CacheParam<T> cachepar;
1926 const std::size_t ct = callers[0];
1927 cachepar.nitems = lqn.nitems[ct];
1928 cachepar.itemcap = lqn.itemcap[ct];
1929 cachepar.replacestrat = lqn.replacestrat[ct];
1930 cacheNode = m.add_node(lqn.hashnames[ct], NodeType::Cache,
true);
1940 std::vector<std::size_t> async_here;
1941 for (std::size_t c : callers)
1942 for (std::size_t aidx : lqn.actsof[c])
1943 for (std::size_t cidx : lqn.callsof[aidx])
1944 if (lqn.calltype[cidx] == CallType::ASYNC &&
1945 !servers_for(lqn.parent[lqn.callpair_dst[cidx]]).empty())
1946 async_here.push_back(cidx);
1947 std::vector<std::size_t> open_entries;
1948 for (std::size_t c : callers) {
1956 for (std::size_t eidx : lqn.entriesof[c])
1957 if (lqn.has_arrival[eidx]) open_entries.push_back(eidx);
1960 std::size_t sourceStation = 0, sourceNode = 0, sinkNode = 0;
1961 if (!async_here.empty() || !open_entries.empty()) {
1963 src.name =
"Source";
1964 src.nodetype = NodeType::Source;
1966 src.sched = SchedStrategy::EXT;
1968 src.attr_ishost =
false;
1970 sourceStation = m.add_station(src);
1971 sourceNode = m.node_of_station(sourceStation);
1972 sinkNode = m.add_node(
"Sink", NodeType::Sink,
false);
1973 m.sourceIdx = sourceStation;
1974 m.sinkNode = sinkNode;
1978 std::vector<std::size_t> forkClassStack;
1981 std::vector<std::size_t> cls(lqn.nidx + 1, 0);
1982 std::vector<std::size_t> callcls(lqn.ncalls + 1, 0);
1985 std::vector<std::size_t> auxcallcls(lqn.ncalls + 1, 0);
1993 auto caller_needs_class = [&](std::size_t tidx_caller) {
1994 if (host_is_server(tidx_caller)) {
1995 if (lqn.isref[tidx_caller])
return true;
1996 for (std::size_t e : lqn.entriesof[tidx_caller])
1997 if (lqn.issynccaller.any_col(e) || lqn.isasynccaller.any_col(e) ||
1998 is_fwd_target(e) || lqn.has_arrival[e])
2001 return is_layer_client(tidx_caller);
2003 auto caller_acts_visible = [&](std::size_t tidx_caller) {
2004 return host_is_server(tidx_caller) || is_layer_client(tidx_caller);
2012 auto caller_pool = [&](std::size_t tidx_) ->
double {
2014 const bool single_replica = reduce_fanout || single_replica_tasks.count(tidx_) > 0;
2015 if (ishostlayer && !single_replica && lqn.repl[tidx_] > 1.0)
2016 host_all_replica_tasks[tidx_] = nreplicas;
2017 if (njobs(tidx_, idx) != 0.0)
return njobs(tidx_, idx);
2018 double nj = single_replica ?
mult[tidx_] :
mult[tidx_] * lqn.repl[tidx_];
2019 if (std::isinf(nj)) {
2021 for (std::size_t c = 1; c <= NT(); ++c)
2022 if (lqn.taskgraph.get(c, tidx_) != Tzero()) s +=
mult[c];
2024 if (std::isinf(nj)) {
2026 for (std::size_t c = 1; c <= NT(); ++c)
2027 if (std::isfinite(mult[c])) s2 +=
mult[c] * lqn.repl[c];
2028 nj = std::min(s2, 1000.0);
2044 std::vector<bool> rp_member(lqn.nidx + 1,
false);
2045 std::vector<bool> rp_spliced(lqn.nidx + 1,
false);
2046 std::vector<bool> rp_hop(lqn.nidx + 1,
false);
2047 std::vector<bool> rp_expand(lqn.ncalls + 1,
false);
2048 std::vector<std::size_t> rp_child_task(lqn.ncalls + 1, 0);
2049 std::vector<std::size_t> rp_child_entry(lqn.ncalls + 1, 0);
2050 std::vector<T> rp_ret_share(lqn.ncalls + 1, Tzero());
2051 std::vector<T> rp_call_mean(lqn.ncalls + 1, Tzero());
2052 std::vector<std::vector<std::size_t>> rp_hop_children(lqn.nidx + 1);
2053 std::vector<double> rp_hop_seed(lqn.nidx + 1, 0.0);
2054 std::vector<std::vector<std::size_t>> rp_member_inbound(lqn.nidx + 1);
2055 std::vector<std::vector<std::size_t>> rp_hop_inbound(lqn.nidx + 1);
2056 std::vector<std::vector<std::size_t>> rp_group_roots;
2057 std::vector<std::size_t> rp_group_reftask;
2058 std::vector<bool> rp_group_head_is_caller;
2060 std::vector<std::size_t> rp_ref_stage;
2061 std::vector<std::size_t> rp_hop_cls(lqn.nidx + 1, 0), rp_hop_ret(lqn.nidx + 1, 0),
2062 rp_ret_cls(lqn.nidx + 1, 0);
2063 std::vector<std::size_t> rp_gate(lqn.ncalls + 1, 0), rp_aux(lqn.ncalls + 1, 0),
2064 rp_resume(lqn.ncalls + 1, 0);
2067 auto host_demand_of_entry = [&](std::size_t eidx_) {
2069 for (std::size_t a_ : lqn.actsof[eidx_]) {
2070 if (lqn.hostdem[a_].disabled)
continue;
2071 const double m_ = dbl(lqn.hostdem[a_].mean);
2072 if (std::isfinite(m_)) d += m_;
2076 const auto in_idxset = [&](std::size_t t_) {
2077 return std::find(idxSet.begin(), idxSet.end(), t_) != idxSet.end();
2084 if (interlockMethod !=
"refpath" || flat || iscachelayer || hasfork || hasjoin)
return;
2087 if (reduce_fanout || nreplicas > 1)
return;
2088 for (std::size_t t_ : callers)
2089 if (lqn.repl[t_] > 1.0 || single_replica_tasks.count(t_) > 0)
return;
2090 const lqn::LqnRefRoutes<T> R =
2092 if (!R.why.empty()) {
2094 std::cerr <<
"[LINE] Warning: layer '" << lqn.hashnames[idx]
2095 <<
"' falls back to the 'ilrate' interlock method: " << R.why
2099 std::vector<std::size_t> keep;
2100 for (std::size_t g_ = 0; g_ < R.groups.size(); ++g_) {
2101 const lqn::LqnRefGroup<T>& G = R.groups[g_];
2102 bool wanted = G.members.size() >= 2;
2105 if (!wanted && opt.interlock_refpath_scope ==
"all" && !G.head_is_caller &&
2108 if (!wanted)
continue;
2113 for (std::size_t t_ : G.members) pool += caller_pool(t_);
2114 const double chainPop =
mult[G.reftask] * lqn.repl[G.reftask];
2115 if (!(pool > chainPop))
continue;
2118 if (keep.empty())
return;
2121 std::vector<bool> sMember(lqn.nidx + 1,
false), sSpliced(lqn.nidx + 1,
false),
2122 sHop(lqn.nidx + 1,
false), sExpand(lqn.ncalls + 1,
false);
2123 std::vector<std::size_t> sChildTask(lqn.ncalls + 1, 0),
2124 sChildEntry(lqn.ncalls + 1, 0);
2125 std::vector<T> sRetShare(lqn.ncalls + 1, Tzero()), sCallMean(lqn.ncalls + 1, Tzero());
2126 std::vector<std::vector<std::size_t>> sHopChildren(lqn.nidx + 1),
2127 sMemberInbound(lqn.nidx + 1), sHopInbound(lqn.nidx + 1);
2128 std::vector<double> sHopSeed(lqn.nidx + 1, 0.0);
2129 std::vector<std::vector<std::size_t>> sRoots;
2130 std::vector<std::size_t> sRefTask;
2131 std::vector<bool> sHeadIsCaller;
2132 for (std::size_t g_ : keep) {
2133 const lqn::LqnRefGroup<T>& G = R.groups[g_];
2134 const std::size_t nE = G.entries.size();
2136 std::vector<bool> leads(G.ismember.begin(), G.ismember.end());
2137 for (std::size_t i_ = nE; i_-- > 0;)
2138 for (
const lqn::LqnRefCall<T>& c_ : G.calls)
2139 if (c_.from == i_ && leads[c_.to]) leads[i_] =
true;
2140 for (std::size_t t_ : G.members)
2141 if (!caller_needs_class(t_))
return;
2142 if (G.head_is_caller && !caller_needs_class(G.reftask))
return;
2144 if (!G.head_is_caller && !std::isfinite(lqn.maxmult[G.reftask]))
return;
2145 for (std::size_t i_ = 0; i_ < nE; ++i_) {
2146 if (!leads[i_] || G.ismember[i_])
continue;
2148 if (in_idxset(G.etask[i_]) || lqn.repl[G.etask[i_]] > 1.0)
return;
2150 for (
const lqn::LqnRefCall<T>& c_ : G.calls) {
2151 if (!leads[c_.to])
continue;
2152 if (in_idxset(G.etask[c_.to]))
return;
2155 const std::size_t head = G.reftask;
2156 for (std::size_t t_ : G.members) {
2158 sSpliced[t_] = !(G.head_is_caller && t_ == head);
2160 std::vector<T> inTotMember(lqn.nidx + 1, Tzero()), inTotHop(lqn.nidx + 1, Tzero());
2161 for (
const lqn::LqnRefCall<T>& c_ : G.calls) {
2162 if (!leads[c_.to])
continue;
2163 const std::size_t cidx_ = c_.cidx;
2164 const std::size_t fromEidx = G.entries[c_.from];
2165 sExpand[cidx_] =
true;
2166 sCallMean[cidx_] = lqn.callproc_mean[cidx_];
2167 sHopChildren[fromEidx].push_back(cidx_);
2168 if (G.ismember[c_.to]) {
2169 const std::size_t tv = G.etask[c_.to];
2170 sChildTask[cidx_] = tv;
2171 sMemberInbound[tv].push_back(cidx_);
2172 inTotMember[tv] = T(inTotMember[tv] + c_.vcall);
2174 const std::size_t ev = G.entries[c_.to];
2175 sChildEntry[cidx_] = ev;
2176 sHopInbound[ev].push_back(cidx_);
2177 inTotHop[ev] = T(inTotHop[ev] + c_.vcall);
2179 sRetShare[cidx_] = c_.vcall;
2181 for (
const lqn::LqnRefCall<T>& c_ : G.calls) {
2182 const std::size_t cidx_ = c_.cidx;
2183 if (!sExpand[cidx_])
continue;
2184 const T
tot = sChildTask[cidx_] > 0 ? inTotMember[sChildTask[cidx_]]
2185 : inTotHop[sChildEntry[cidx_]];
2187 ? T(sRetShare[cidx_] / tot)
2190 for (std::size_t i_ = 0; i_ < nE; ++i_)
2191 if (leads[i_] && !G.ismember[i_]) {
2192 const std::size_t ev = G.entries[i_];
2194 sHopSeed[ev] = host_demand_of_entry(ev);
2196 if (!G.head_is_caller) {
2200 for (std::size_t ev : lqn.entriesof[G.reftask])
2203 sHopSeed[ev] = host_demand_of_entry(ev);
2206 sRoots.push_back(lqn.entriesof[head]);
2207 sRefTask.push_back(head);
2208 sHeadIsCaller.push_back(G.head_is_caller);
2210 rp_member = sMember;
2211 rp_spliced = sSpliced;
2213 rp_expand = sExpand;
2214 rp_child_task = sChildTask;
2215 rp_child_entry = sChildEntry;
2216 rp_ret_share = sRetShare;
2217 rp_call_mean = sCallMean;
2218 rp_hop_children = sHopChildren;
2219 rp_hop_seed = sHopSeed;
2220 rp_member_inbound = sMemberInbound;
2221 rp_hop_inbound = sHopInbound;
2222 rp_group_roots = sRoots;
2223 rp_group_reftask = sRefTask;
2224 rp_group_head_is_caller = sHeadIsCaller;
2229 for (std::size_t tidx_caller : callers) {
2230 if (caller_needs_class(tidx_caller)) {
2231 double nj = njobs(tidx_caller, idx);
2233 nj = caller_pool(tidx_caller);
2234 njobs(tidx_caller, idx) = nj;
2239 const bool rp_spliced_here = rp_on && rp_spliced[tidx_caller];
2241 jc.name = lqn.hashnames[tidx_caller];
2242 jc.type = JobClassType::CLOSED;
2243 jc.population = rp_spliced_here ? 0.0 : nj;
2244 jc.refstat = m.clientIdx;
2245 jc.completes =
false;
2248 jc.is_ref_class = !rp_spliced_here;
2249 jc.attr_kind = int(LqnElement::TASK);
2250 jc.attr_idx = tidx_caller;
2251 cls[tidx_caller] = m.add_class(jc);
2252 m.attr_tasks.emplace_back(cls[tidx_caller], tidx_caller);
2253 if (lqn.isref[tidx_caller]) {
2254 m.set_service(m.clientIdx, cls[tidx_caller], thinkproc[tidx_caller]);
2255 }
else if (rp_spliced_here) {
2264 thinkt_map.push_back({idx, tidx_caller, m.clientIdx, cls[tidx_caller]});
2267 for (std::size_t eidx : lqn.entriesof[tidx_caller]) {
2269 ec.name = lqn.hashnames[eidx];
2270 ec.type = JobClassType::CLOSED;
2271 ec.population = 0.0;
2272 ec.refstat = m.clientIdx;
2273 ec.completes =
false;
2274 ec.attr_kind = int(LqnElement::ENTRY);
2276 cls[eidx] = m.add_class(ec);
2277 m.attr_entries.emplace_back(cls[eidx], eidx);
2282 for (std::size_t aidx : lqn.actsof[tidx_caller]) {
2283 if (caller_acts_visible(tidx_caller)) {
2285 ac.name = lqn.hashnames[aidx];
2286 ac.type = JobClassType::CLOSED;
2287 ac.population = 0.0;
2288 ac.refstat = m.clientIdx;
2289 ac.completes =
false;
2290 ac.attr_kind = int(LqnElement::ACTIVITY);
2292 cls[aidx] = m.add_class(ac);
2293 m.attr_activities.emplace_back(cls[aidx], aidx);
2297 const std::size_t hidx = lqn.parent[lqn.parent[aidx]];
2298 if (servers_for(hidx).empty())
2299 m.set_service(m.clientIdx, cls[aidx], servtproc[aidx]);
2301 for (std::size_t cidx : lqn.callsof[aidx]) {
2302 if (lqn.calltype[cidx] == CallType::ASYNC) {
2306 const std::size_t adst = lqn.parent[lqn.callpair_dst[cidx]];
2307 if (servers_for(adst).empty())
continue;
2309 oc.name = lqn.callhashnames[cidx];
2310 oc.type = JobClassType::OPEN;
2311 oc.population = std::numeric_limits<double>::infinity();
2312 oc.refstat = sourceStation;
2313 oc.completes =
false;
2314 oc.is_ref_class =
false;
2315 oc.attr_kind = int(LqnElement::CALL);
2317 callcls[cidx] = m.add_class(oc);
2318 m.attr_calls.push_back({callcls[cidx], cidx, lqn.callpair_src[cidx],
2319 lqn.callpair_dst[cidx]});
2327 m.set_service(sourceStation, callcls[cidx],
2330 T minRespTA = Tzero();
2331 for (std::size_t ta : lqn.actsof[adst]) minRespTA += lqn.hostdem[ta].mean;
2332 for (std::size_t st : servers_for(adst)) {
2334 call_map.push_back({idx, cidx, st, callcls[cidx]});
2336 arv_call_map.push_back({idx, cidx, sourceStation, callcls[cidx]});
2339 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
2340 const std::size_t gid = group_of_call[cidx];
2349 if (grp_dispatch[gid] == 0) {
2355 const std::string tag =
2356 lqn.hashnames[aidx] +
".Dispatch" + std::to_string(gid);
2357 grp_router[gid] = m.add_node(tag +
".Router", NodeType::Router,
true);
2360 dc.type = JobClassType::CLOSED;
2361 dc.population = 0.0;
2362 dc.refstat = m.clientIdx;
2363 dc.completes =
false;
2364 dc.attr_kind = int(LqnElement::CALL);
2366 grp_dispatch[gid] = m.add_class(dc);
2369 gc.name = lqn.callhashnames[cidx] +
".Group" + std::to_string(gid);
2370 gc.type = JobClassType::CLOSED;
2371 gc.population = 0.0;
2372 gc.refstat = m.clientIdx;
2373 gc.completes =
false;
2374 gc.attr_kind = int(LqnElement::CALL);
2376 grp_class[gid] = m.add_class(gc);
2378 routed_group_sites.push_back(
2379 {grp_router[gid], grp_dispatch[gid], gid});
2381 callcls[cidx] = grp_dispatch[gid];
2382 m.attr_calls.push_back({callcls[cidx], cidx, lqn.callpair_src[cidx],
2383 lqn.callpair_dst[cidx]});
2384 for (std::size_t st2 : servers_for(lqn.parent[lqn.callpair_dst[cidx]]))
2385 m.set_service(st2, callcls[cidx], callservtproc[cidx]);
2389 cc.name = lqn.callhashnames[cidx];
2390 cc.type = JobClassType::CLOSED;
2391 cc.population = 0.0;
2392 cc.refstat = m.clientIdx;
2393 cc.completes =
false;
2394 cc.attr_kind = int(LqnElement::CALL);
2396 callcls[cidx] = m.add_class(cc);
2397 m.attr_calls.push_back({callcls[cidx], cidx, lqn.callpair_src[cidx],
2398 lqn.callpair_dst[cidx]});
2406 const std::size_t seedidx = flat ? lqn.parent[lqn.callpair_dst[cidx]] : idx;
2407 T minRespT = Tzero();
2408 for (std::size_t ta : lqn.actsof[seedidx]) minRespT += lqn.hostdem[ta].mean;
2409 for (std::size_t st : servers_for(seedidx))
2412 if (lqn.callproc_mean[cidx] !=
2413 num_traits<T>::from_double(
double(nreplicas))) {
2415 xc.name = lqn.callhashnames[cidx] +
".Aux";
2416 xc.type = JobClassType::CLOSED;
2417 xc.population = 0.0;
2418 xc.refstat = m.clientIdx;
2419 xc.completes =
false;
2420 xc.attr_kind = int(LqnElement::CALL);
2422 auxcallcls[cidx] = m.add_class(xc);
2434 auto rp_class = [&](
const std::string& nm,
double pop, std::size_t
attr) {
2437 rc.type = JobClassType::CLOSED;
2438 rc.population = pop;
2439 rc.refstat = m.clientIdx;
2440 rc.completes =
false;
2441 rc.is_ref_class =
false;
2444 const std::size_t k_ = m.add_class(rc);
2449 for (std::size_t g_ = 0; g_ < rp_group_reftask.size(); ++g_) {
2450 if (rp_group_head_is_caller[g_]) {
2451 rp_ref_stage.push_back(0);
2454 const std::size_t rt = rp_group_reftask[g_];
2455 const std::size_t k_ =
2456 rp_class(lqn.hashnames[rt] +
".RefPath", mult[rt] * lqn.repl[rt], rt);
2457 m.classes[k_ - 1].is_ref_class =
true;
2458 m.set_service(m.clientIdx, k_, thinkproc[rt]);
2459 rp_ref_stage.push_back(k_);
2461 for (std::size_t ev = 1; ev <= lqn.nidx; ++ev) {
2462 if (!rp_hop[ev])
continue;
2463 const std::size_t k_ = rp_class(lqn.hashnames[ev] +
".RefHop", 0.0, ev);
2465 m.set_service(m.clientIdx, k_,
2467 rp_hop_cls[ev] = k_;
2470 refpath_map.push_back({idx, m.clientIdx, k_, 1, ev, 1.0, 0});
2471 for (std::size_t c_ : rp_hop_children[ev])
2472 refpath_map.push_back({idx, m.clientIdx, k_, 2, c_, -1.0, ev});
2473 refpath_map.push_back({idx, m.clientIdx, k_, 3, lqn.parent[ev], 1.0, 0});
2474 rp_hop_ret[ev] = rp_class(lqn.hashnames[ev] +
".RefHopRet", 0.0, ev);
2476 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv)
2477 if (rp_spliced[tv]) rp_ret_cls[tv] = rp_class(lqn.hashnames[tv] +
".RefRet", 0.0, tv);
2478 for (std::size_t cidx_ = 1; cidx_ <= lqn.ncalls; ++cidx_) {
2479 if (!rp_expand[cidx_])
continue;
2480 if (callcls[cidx_] != 0) {
2481 rp_gate[cidx_] = callcls[cidx_];
2483 if (auxcallcls[cidx_] != 0) rp_aux[cidx_] = auxcallcls[cidx_];
2485 rp_gate[cidx_] = rp_class(lqn.callhashnames[cidx_] +
".RefGate", 0.0, cidx_);
2486 if (rp_call_mean[cidx_] != Tone())
2488 rp_class(lqn.callhashnames[cidx_] +
".RefGate.Aux", 0.0, cidx_);
2493 if (rp_child_task[cidx_] > 0)
2494 refpath_map.push_back(
2495 {idx, m.clientIdx, rp_gate[cidx_], 3, rp_child_task[cidx_], 1.0, 0});
2496 rp_resume[cidx_] = rp_class(lqn.callhashnames[cidx_] +
".RefResume", 0.0, cidx_);
2502 std::size_t curclass;
2508 std::vector<std::size_t> curnodes;
2510 const int atClient = 1, atServer = 2, atCache = 3;
2511 std::vector<int> jobposkey(lqn.nidx + 1, atClient);
2512 std::vector<std::size_t> curclasskey(lqn.nidx + 1, 0);
2513 std::vector<std::vector<std::size_t>> curnodeskey(lqn.nidx + 1);
2520 auto rp_descent = [&](std::size_t cidx_, Ctx st) -> Ctx {
2521 const std::size_t gate = rp_gate[cidx_], res = rp_resume[cidx_], aux = rp_aux[cidx_];
2522 const T m_ = rp_call_mean[cidx_];
2523 const std::size_t enter = rp_child_task[cidx_] > 0 ? cls[rp_child_task[cidx_]]
2524 : rp_hop_cls[rp_child_entry[cidx_]];
2525 if (st.jobpos == atClient)
2526 m.set_route(st.curclass, gate, clientNode, clientNode, Tone());
2528 for (std::size_t nd : st.curnodes) m.set_route(st.curclass, gate, nd, clientNode, Tone());
2531 m.set_route(gate, enter, clientNode, clientNode, Tone());
2533 }
else if (m_ > Tone()) {
2534 m.set_route(gate, enter, clientNode, clientNode, Tone());
2535 m.set_route(res, enter, clientNode, clientNode, T(Tone() - Tone() / m_));
2536 m.set_route(res, aux, clientNode, clientNode, T(Tone() / m_));
2539 m.set_route(gate, enter, clientNode, clientNode, m_);
2540 m.set_route(gate, aux, clientNode, clientNode, T(Tone() - m_));
2541 m.set_route(res, aux, clientNode, clientNode, Tone());
2544 st.jobpos = atClient;
2545 st.curnodes.clear();
2550 std::function<Ctx(std::size_t, std::size_t, Ctx)> recur =
2551 [&](std::size_t tidx_caller, std::size_t aidx, Ctx st) -> Ctx {
2552 jobposkey[aidx] = st.jobpos;
2553 curclasskey[aidx] = st.curclass;
2554 curnodeskey[aidx] = st.curnodes;
2555 const std::vector<std::size_t> nexts = lqn.graph.succ(aidx);
2556 std::size_t lastEntryClass = st.curclass;
2558 bool next_is_fork =
false;
2559 for (std::size_t sx : nexts)
2560 if (lqn.actposttype[sx] == PrecedenceType::POST_AND) next_is_fork =
true;
2561 const Ctx preFork = st;
2562 std::vector<std::size_t> andSuccs;
2563 for (std::size_t sx : nexts)
2564 if (lqn.actposttype[sx] == PrecedenceType::POST_AND) andSuccs.push_back(sx);
2566 for (std::size_t k = 0; k < nexts.size(); ++k) {
2567 const std::size_t nextaidx = nexts[k];
2568 if (next_is_fork) st = preFork;
2569 bool isLoop = lqn.graph.get(aidx, nextaidx) != lqn.dag.get(aidx, nextaidx);
2570 if (lqn.parent[aidx] != lqn.parent[nextaidx]) {
2572 std::size_t cidx = 0;
2573 for (std::size_t c : lqn.callsof[aidx])
2574 if (lqn.callpair_dst[c] == nextaidx) cidx = c;
2575 if (cidx == 0)
continue;
2577 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
2578 const std::size_t gid = group_of_call[cidx];
2582 if (group_members[gid].empty() || group_members[gid][0] != cidx)
continue;
2589 std::vector<std::size_t> tnode2, tstat2, tcall2;
2590 for (std::size_t mc : group_members[gid]) {
2591 const std::size_t tt = lqn.parent[lqn.callpair_dst[mc]];
2592 if (servers_for(tt).empty())
continue;
2593 tnode2.push_back(server_nodes_for(tt)[0]);
2594 tstat2.push_back(servers_for(tt)[0]);
2595 tcall2.push_back(mc);
2597 if (tnode2.size() < 2)
continue;
2598 const std::size_t fromNode2 =
2599 st.jobpos == atClient ? clientNode : st.curnodes[0];
2600 const std::size_t dc = grp_dispatch[gid], gc = grp_class[gid];
2601 m.set_route(st.curclass, dc, fromNode2, grp_router[gid], Tone());
2603 T(Tone() / num_traits<T>::from_int(
int(tnode2.size())));
2604 for (std::size_t d = 0; d < tnode2.size(); ++d) {
2605 m.set_route(dc, dc, grp_router[gid], tnode2[d], share2);
2606 m.set_route(dc, gc, tnode2[d], clientNode, Tone());
2607 m.set_service(tstat2[d], dc, callservtproc[tcall2[d]]);
2608 call_map.push_back({idx, tcall2[d], tstat2[d], dc});
2611 st.jobpos = atClient;
2612 st.curnodes.clear();
2615 if (rp_on && rp_expand[cidx]) {
2618 st = rp_descent(cidx, st);
2621 const std::size_t ctgt = lqn.parent[lqn.callpair_dst[cidx]];
2622 st = route_sync_call(m, idx, cidx, st, server_nodes_for(ctgt),
2623 servers_for(ctgt), callcls, auxcallcls, clientNode,
2624 atClient, atServer, flat);
2628 bool any_entry_succ =
false;
2629 for (std::size_t sx : nexts)
2630 if (sx > lqn.eshift && sx <= lqn.eshift + lqn.nentries) any_entry_succ =
true;
2631 if (!any_entry_succ) {
2632 st.jobpos = jobposkey[aidx];
2633 st.curclass = curclasskey[aidx];
2634 st.curnodes = curnodeskey[aidx];
2636 if (k > 0 && nexts[k - 1] > lqn.eshift && nexts[k - 1] <= lqn.eshift + lqn.nentries)
2637 lastEntryClass = st.curclass;
2638 st.jobpos = atClient;
2639 st.curclass = lastEntryClass;
2640 st.curnodes.clear();
2642 const T w = lqn.graph.get(aidx, nextaidx);
2650 if (iscachelayer && lqn.nitems[aidx] > 0 && cls[nextaidx] != 0) {
2651 const std::size_t readcls = cls[nextaidx];
2652 m.set_route(st.curclass, readcls, clientNode, cacheNode, w);
2653 if (cachepar.pread.size() < m.classes.size())
2654 cachepar.pread.resize(m.classes.size());
2655 cachepar.pread[readcls - 1] = lqn.itemproc[aidx];
2656 const std::vector<std::size_t> hm = lqn.graph.succ(nextaidx);
2658 throw InputError(
"SolverLN: the cache read '" + lqn.names[nextaidx] +
2659 "' needs exactly one hit and one miss successor");
2660 if (cachepar.hitclass.size() < m.classes.size()) {
2661 cachepar.hitclass.resize(m.classes.size(), 0);
2662 cachepar.missclass.resize(m.classes.size(), 0);
2664 cachepar.hitclass[readcls - 1] = cls[hm[0]];
2665 cachepar.missclass[readcls - 1] = cls[hm[1]];
2666 st.jobpos = atCache;
2667 st.curclass = readcls;
2668 st.curnodes.clear();
2669 st = recur(tidx_caller, nextaidx, st);
2673 const bool is_and_join_tail = lqn.actpretype[aidx] == PrecedenceType::PRE_AND;
2675 std::size_t fbranch = 0;
2677 for (std::size_t q = 0; q < andSuccs.size(); ++q)
2678 if (andSuccs[q] == nextaidx) fbranch = q + 1;
2685 const std::size_t hidxOf = lqn.parent[lqn.parent[nextaidx]];
2686 const std::vector<std::size_t>& actStations = servers_for(hidxOf);
2687 const std::vector<std::size_t>& actNodes = server_nodes_for(hidxOf);
2688 const bool actAtServer = !actStations.empty();
2689 const std::size_t from = st.jobpos == atClient ? clientNode
2690 : st.jobpos == atCache ? cacheNode
2696 const T split = actAtServer ? T(Tone() / num_traits<T>::from_double(
double(nreplicas)))
2698 const bool oneToOne = st.jobpos != atClient && st.jobpos != atCache &&
2699 st.curnodes.size() == nreplicas;
2700 for (std::size_t r = 0; r < nreplicas; ++r) {
2701 const std::size_t fromNode =
2702 st.jobpos == atClient ? clientNode
2703 : st.jobpos == atCache ? cacheNode
2704 : st.curnodes[std::min(r, st.curnodes.size() - 1)];
2705 const std::size_t toNode = actAtServer ? actNodes[r] : clientNode;
2706 if (next_is_fork && fbranch > 0) {
2707 m.set_route(st.curclass, st.curclass, fromNode, forkNode, Tone());
2708 if (r == 0) forkClassStack.push_back(st.curclass);
2709 m.set_route(st.curclass, st.curclass, forkNode, forkRouter[fbranch - 1],
2711 m.set_route(st.curclass, cls[nextaidx], forkRouter[fbranch - 1], toNode,
2713 }
else if (is_and_join_tail) {
2716 if (forkClassStack.empty())
2717 throw InputError(
"SolverLN: an AND join has no matching fork in '" +
2718 lqn.names[aidx] +
"'");
2719 const std::size_t forkClass = forkClassStack.back();
2720 if (r + 1 == nreplicas) forkClassStack.pop_back();
2721 m.set_route(st.curclass, forkClass, fromNode, joinNode, Tone());
2722 m.set_route(forkClass, cls[nextaidx], joinNode, toNode, T(Tone() * split));
2726 m.set_route(st.curclass, cls[nextaidx], fromNode, toNode,
2727 oneToOne ? w : T(w * split));
2730 m.set_service(actStations[r], cls[nextaidx], lqn.hostdem[nextaidx]);
2734 st.jobpos = atServer;
2735 st.curclass = cls[nextaidx];
2736 st.curnodes = actNodes;
2737 servt_map.push_back({idx, nextaidx, actStations[0], cls[nextaidx]});
2739 st.jobpos = atClient;
2740 st.curclass = cls[nextaidx];
2741 st.curnodes.clear();
2742 m.set_service(m.clientIdx, cls[nextaidx], servtproc[nextaidx]);
2743 thinkt_map.push_back({idx, nextaidx, m.clientIdx, cls[nextaidx]});
2745 if (aidx != nextaidx && !isLoop) {
2746 st = recur(tidx_caller, nextaidx, st);
2750 const std::size_t reply =
2751 (rp_on && rp_spliced[tidx_caller]) ? rp_ret_cls[tidx_caller]
2753 if (st.jobpos == atClient) {
2754 m.set_route(st.curclass, reply, clientNode, clientNode, Tone());
2756 for (std::size_t nd : st.curnodes)
2757 m.set_route(st.curclass, reply, nd, clientNode, Tone());
2760 if (!is_aux_class(m.classes[st.curclass - 1].name))
2761 m.classes[st.curclass - 1].completes =
true;
2767 for (std::size_t tidx_caller : callers) {
2768 if (!caller_needs_class(tidx_caller))
continue;
2769 const std::vector<std::size_t>& ents = lqn.entriesof[tidx_caller];
2770 const T share = T(Tone() / num_traits<T>::from_int(
int(ents.size())));
2771 for (std::size_t eidx : ents) {
2772 m.set_route(cls[tidx_caller], cls[eidx], clientNode, clientNode, share);
2773 if (ents.size() > 1)
2774 route_map.push_back({idx, tidx_caller, eidx, m.clientIdx, m.clientIdx,
2775 cls[tidx_caller], cls[eidx]});
2776 Ctx st{cls[eidx], atClient, {}};
2777 recur(tidx_caller, eidx, st);
2785 for (std::size_t g_ = 0; g_ < rp_group_reftask.size(); ++g_) {
2786 if (rp_group_head_is_caller[g_])
continue;
2787 std::vector<std::size_t> roots;
2788 for (std::size_t r_ : rp_group_roots[g_])
2789 if (rp_hop[r_]) roots.push_back(r_);
2790 if (roots.empty())
continue;
2792 const T share = T(Tone() / num_traits<T>::from_int(
int(roots.size())));
2793 for (std::size_t r_ : roots) {
2794 m.set_route(rp_ref_stage[g_], rp_hop_cls[r_], clientNode, clientNode, share);
2795 m.set_route(rp_hop_ret[r_], rp_ref_stage[g_], clientNode, clientNode, Tone());
2799 for (std::size_t ev = 1; ev <= lqn.nidx; ++ev) {
2800 if (!rp_hop[ev])
continue;
2801 Ctx cur{rp_hop_cls[ev], atClient, {}};
2802 for (std::size_t c_ : rp_hop_children[ev]) cur = rp_descent(c_, cur);
2803 m.set_route(cur.curclass, rp_hop_ret[ev], clientNode, clientNode, Tone());
2807 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv) {
2808 if (!rp_spliced[tv])
continue;
2809 for (std::size_t c_ : rp_member_inbound[tv])
2810 if (rp_ret_share[c_] > Tzero())
2811 m.set_route(rp_ret_cls[tv], rp_resume[c_], clientNode, clientNode,
2814 for (std::size_t ev = 1; ev <= lqn.nidx; ++ev) {
2815 if (!rp_hop[ev])
continue;
2816 for (std::size_t c_ : rp_hop_inbound[ev])
2817 if (rp_ret_share[c_] > Tzero())
2818 m.set_route(rp_hop_ret[ev], rp_resume[c_], clientNode, clientNode,
2829 if (sourceStation != 0) {
2830 const T nrep = num_traits<T>::from_int(
int(nreplicas));
2831 for (std::size_t cidx : async_here) {
2832 const std::size_t oc = callcls[cidx];
2833 if (oc == 0)
continue;
2836 const std::vector<std::size_t>& anode =
2837 server_nodes_for(lqn.parent[lqn.callpair_dst[cidx]]);
2838 const T callmean = lqn.callproc_mean[cidx];
2839 if (callmean < Tone()) {
2841 m.set_route(oc, oc, sourceNode, sinkNode, T(Tone() - callmean));
2842 for (std::size_t r = 0; r < anode.size(); ++r) {
2843 m.set_route(oc, oc, sourceNode, anode[r], T(callmean / nrep));
2844 m.set_route(oc, oc, anode[r], sinkNode, Tone());
2848 const T p = T(Tone() / callmean);
2849 for (std::size_t r = 0; r < anode.size(); ++r) {
2850 m.set_route(oc, oc, sourceNode, anode[r], T(Tone() / nrep));
2851 for (std::size_t q = 0; q < anode.size(); ++q)
2852 m.set_route(oc, oc, anode[r], anode[q], T((Tone() - p) / nrep));
2853 m.set_route(oc, oc, anode[r], sinkNode, p);
2857 for (std::size_t eidx : open_entries) {
2859 eo.name = lqn.hashnames[eidx] +
"_Open";
2860 eo.type = JobClassType::OPEN;
2861 eo.population = std::numeric_limits<double>::infinity();
2862 eo.refstat = sourceStation;
2863 eo.completes =
false;
2864 eo.is_ref_class =
false;
2865 eo.attr_kind = int(LqnElement::ENTRY);
2867 const std::size_t ec = m.add_class(eo);
2869 m.set_service(sourceStation, ec, lqn.arrival[eidx]);
2871 std::size_t bound = 0;
2872 for (std::size_t sx : lqn.graph.succ(eidx))
2873 if (bound == 0 && sx > lqn.ashift) bound = sx;
2874 const Distrib<T>& svc = bound != 0 ? servtproc[bound] : servtproc[eidx];
2877 const std::vector<std::size_t>& ostat =
2878 flat ? servers_for(lqn.parent[eidx]) : server;
2879 const std::vector<std::size_t>& onode =
2880 flat ? server_nodes_for(lqn.parent[eidx]) : serverNode;
2881 for (std::size_t r = 0; r < ostat.size(); ++r) {
2882 m.set_service(ostat[r], ec, svc);
2883 m.set_route(ec, ec, sourceNode, onode[r], T(Tone() / nrep));
2884 m.set_route(ec, ec, onode[r], sinkNode, Tone());
2898 std::vector<std::vector<T>> Arows;
2899 std::vector<T> brows;
2900 if (idx < lqn.lincon_A.size() && lqn.lincon_A[idx].rows() > 0) {
2901 const Matrix<T>& Aelem = lqn.lincon_A[idx];
2902 Matrix<T> Alayer(Aelem.rows(), m.classes.size(), Tzero());
2903 const std::vector<std::size_t>& constrained =
2904 ishostlayer ? lqn.tasksof[idx] : lqn.entriesof[idx];
2905 for (std::size_t j = 0; j < constrained.size() && j < Aelem.cols(); ++j) {
2906 std::vector<std::size_t> layerClasses;
2908 for (std::size_t a : lqn.actsof[constrained[j]])
2909 if (cls[a] != 0) layerClasses.push_back(cls[a]);
2911 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
2912 if (lqn.callpair_dst[c] == constrained[j] && callcls[c] != 0)
2913 layerClasses.push_back(callcls[c]);
2915 for (std::size_t k = 0; k < layerClasses.size(); ++k)
2916 for (std::size_t rr = 0; rr < Aelem.rows(); ++rr)
2917 Alayer(rr, layerClasses[k] - 1) =
2918 T(Alayer(rr, layerClasses[k] - 1) + Aelem(rr, j));
2920 for (std::size_t rr = 0; rr < Alayer.rows(); ++rr) {
2921 std::vector<T> row(m.classes.size(), Tzero());
2922 for (std::size_t k = 0; k < m.classes.size(); ++k) row[k] = Alayer(rr, k);
2923 Arows.push_back(row);
2924 brows.push_back(lqn.lincon_b[idx][rr]);
2933 if (rp_on && layer_solver_declares_region()) {
2934 std::vector<std::size_t> srvEntries;
2935 for (std::size_t sidx : idxSet)
2936 for (std::size_t e : lqn.entriesof[sidx]) srvEntries.push_back(e);
2937 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv) {
2938 if (!rp_spliced[tv])
continue;
2939 const double cap = lqn.maxmult[tv];
2940 if (!std::isfinite(cap) || cap <= 0.0)
continue;
2941 std::vector<T> row(m.classes.size(), Tzero());
2945 for (std::size_t a_ : lqn.actsof[tv])
2947 row[cls[a_] - 1] = Tone();
2952 for (std::size_t a_ : lqn.actsof[tv])
2953 for (std::size_t c_ : lqn.callsof[a_])
2954 if (std::find(srvEntries.begin(), srvEntries.end(),
2955 lqn.callpair_dst[c_]) != srvEntries.end() &&
2957 row[callcls[c_] - 1] = Tone();
2962 Arows.push_back(row);
2963 brows.push_back(num_traits<T>::from_double(cap));
2969 for (
const std::vector<T>& row : Arows)
2970 for (
const T& v : row)
2971 if (v != Tzero()) any =
true;
2973 Matrix<T> Alayer(Arows.size(), m.classes.size(), Tzero());
2974 for (std::size_t rr = 0; rr < Arows.size(); ++rr)
2975 for (std::size_t k = 0; k < m.classes.size(); ++k) Alayer(rr, k) = Arows[rr][k];
2979 typename qn::NetworkStruct<T>::Region rg;
2980 const std::size_t M = m.stations.size(), K = m.classes.size();
2981 rg.cap.assign(M, std::vector<double>(K + 1, -1.0));
2982 rg.maxmem.assign(M, -1.0);
2983 rg.members.assign(M,
false);
2985 rg.weight.assign(K, Tone());
2986 rg.size.assign(K, Tone());
2987 for (std::size_t r = 0; r < nreplicas; ++r) rg.members[server[r] - 1] =
true;
2988 rg.lincon_A = Alayer;
2989 rg.lincon_b = brows;
2990 m.regions.push_back(rg);
2997 if (cacheNode != 0) {
2998 cachepar.pread.resize(m.classes.size());
2999 cachepar.hitclass.resize(m.classes.size(), 0);
3000 cachepar.missclass.resize(m.classes.size(), 0);
3001 m.nodeparam[cacheNode] = cachepar;
3009 for (
const std::array<std::size_t, 3>& site : routed_group_sites) {
3010 qn::NodeDef& nd = m.nodes[site[0] - 1];
3011 if (nd.routing.size() < m.classes.size())
3012 nd.routing.resize(m.classes.size(), RoutingStrategy::PROB);
3013 nd.routing[site[1] - 1] = lqn.callgroups[site[2] - 1].strategy;
3025 std::vector<std::pair<std::shared_ptr<std::vector<std::vector<std::size_t>>>,
3026 std::vector<std::vector<std::size_t>>>> deferred_chaincols;
3027 for (std::size_t sidx : idxSet) {
3028 const bool hasld = sidx < lqn.lldscaling.size() && !lqn.lldscaling[sidx].empty();
3029 const bool hascd = sidx < lqn.cdscaling.size() && bool(lqn.cdscaling[sidx]);
3030 const bool hasjd = sidx < lqn.jdscaling.size() && bool(lqn.jdscaling[sidx]);
3031 const bool haspools = sidx < lqn.pools.size() && !lqn.pools[sidx].empty();
3032 if (!(hasld || hascd || hasjd || haspools))
continue;
3033 const bool sishost = sidx <= lqn.nhosts;
3034 const std::vector<std::size_t>& operandIdx =
3035 sishost ? lqn.tasksof[sidx] : lqn.entriesof[sidx];
3036 std::vector<std::vector<std::size_t>> cols(operandIdx.size());
3037 for (std::size_t j = 0; j < operandIdx.size(); ++j) {
3039 for (std::size_t a : lqn.actsof[operandIdx[j]])
3040 if (cls[a] != 0) cols[j].push_back(cls[a] - 1);
3042 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
3043 if (lqn.callpair_dst[c] == operandIdx[j] && callcls[c] != 0)
3044 cols[j].push_back(callcls[c] - 1);
3047 const std::size_t R = m.classes.size();
3048 std::shared_ptr<std::vector<std::vector<std::size_t>>> chaincols =
3049 std::make_shared<std::vector<std::vector<std::size_t>>>();
3050 deferred_chaincols.push_back(std::make_pair(chaincols, cols));
3051 for (std::size_t r = 0; r < nreplicas; ++r) {
3056 qn::Station<T>& stn = m.stations[srv[sidx][r] - 1];
3057 if (hasld) stn.lldscaling = lqn.lldscaling[sidx];
3063 bool one_class_each =
true;
3064 for (std::size_t j = 0; j < cols.size(); ++j)
3065 if (cols[j].size() > 1) one_class_each =
false;
3067 layer_dep_handle(lqn.cdscaling[sidx], cols, chaincols, R);
3068 const std::vector<T> pk = layer_peak(lqn.cdscalingpeak[sidx], cols, R);
3069 if (one_class_each) {
3071 stn.cdscalingpeak = pk;
3074 stn.jdscalingpeak = pk;
3078 stn.jdscaling = layer_dep_handle(lqn.jdscaling[sidx], cols, chaincols, R);
3079 stn.jdscalingpeak = layer_peak(lqn.jdscalingpeak[sidx], cols, R);
3090 const lqn::ServerPools<T>& pl = lqn.pools[sidx];
3091 const Matrix<T> compat = pl.compat;
3092 const std::vector<double> counts = pl.counts;
3093 const std::vector<T> rates = pl.rates;
3095 rates](
const std::vector<T>& nop) {
3096 return std::vector<T>(
3099 stn.jdscaling = layer_dep_handle(etaPool, cols, chaincols, R);
3100 stn.jdscalingpeak = layer_peak(
3101 std::vector<T>(cols.size(), num_traits<T>::from_int(1)), cols, R);
3111 std::vector<std::size_t> nc(m.classes.size(), 0);
3112 for (std::size_t tv = 1; tv <= lqn.nidx; ++tv) {
3113 if (!rp_member[tv] || cls[tv] == 0)
continue;
3114 const std::size_t own = cls[tv];
3115 std::vector<std::size_t> owned{cls[tv]};
3116 for (std::size_t e_ : lqn.entriesof[tv]) owned.push_back(cls[e_]);
3117 for (std::size_t a_ : lqn.actsof[tv]) {
3118 owned.push_back(cls[a_]);
3119 for (std::size_t c_ : lqn.callsof[a_]) {
3120 owned.push_back(callcls[c_]);
3121 owned.push_back(auxcallcls[c_]);
3125 for (std::size_t q_ : owned)
3126 if (q_ != 0 && m.classes[q_ - 1].type == JobClassType::CLOSED) nc[q_ - 1] = own;
3128 layer_normclass[idx] = nc;
3129 ref_path_audit(m, idx, callers, caller_needs_class, rp_spliced, rp_member, rp_hop,
3130 rp_expand, rp_group_head_is_caller, rp_ref_stage, rp_hop_cls,
3131 rp_hop_ret, rp_ret_cls, rp_gate, rp_aux, rp_resume, cls);
3135 apply_host_task_priorities(m, idxSet);
3140 for (std::size_t d = 0; d < deferred_chaincols.size(); ++d) {
3141 const std::vector<std::vector<std::size_t>>& cols = deferred_chaincols[d].second;
3142 std::vector<std::vector<std::size_t>>& out = *deferred_chaincols[d].first;
3143 out.assign(cols.size(), std::vector<std::size_t>());
3144 for (std::size_t j = 0; j < cols.size(); ++j) {
3145 for (std::size_t k = 0; k < cols[j].size(); ++k)
3146 for (std::size_t cc = 0; cc < m.chains.size(); ++cc)
3147 if (cols[j][k] < m.chains[cc].size() && m.chains[cc][cols[j][k]]) {
3149 for (std::size_t q = 0; q < out[j].size(); ++q)
3150 if (out[j][q] == cc) seen =
true;
3151 if (!seen) out[j].push_back(cc);
3172 bool layer_solver_declares_region()
const {
3174 return opt.layer_solver ==
"nc" || opt.layer_solver ==
"fluid" || opt.layer_solver ==
"ssa" ||
3175 opt.layer_solver ==
"ctmc" || opt.layer_solver ==
"ldes" || opt.layer_solver ==
"jmt";
3179 bool layer_solver_is_stochastic()
const {
3180 return opt.layer_solver ==
"ssa" || opt.layer_solver ==
"ldes" || opt.layer_solver ==
"jmt";
3188 long layer_seed(
long base, std::size_t e)
const {
3189 const long it = cur_it > 0 ? cur_it : 1;
3190 return base + (it - 1) *
static_cast<long>(ensemble.size()) +
static_cast<long>(e) + 1 +
3195 long sens_rep_offset()
const {
3196 return sens_rep_k > 0 ?
static_cast<long>(sens_rep_k) - 1 : 0;
3201 S sens_rep_samples(S samples)
const {
3202 if (sens_rep_k == 0 || sens_rep_n == 0)
return samples;
3203 const double v = std::ceil(
static_cast<double>(samples) /
static_cast<double>(sens_rep_n));
3204 return static_cast<S
>(v < 1.0 ? 1.0 : v);
3213 template <
class NeedsClass>
3214 void ref_path_audit(
const qn::Layer<T>& m, std::size_t idx,
3215 const std::vector<std::size_t>& callers,
const NeedsClass& needs_class,
3216 const std::vector<bool>& spliced,
const std::vector<bool>& member,
3217 const std::vector<bool>& hop,
const std::vector<bool>& expand,
3218 const std::vector<bool>& head_is_caller,
3219 const std::vector<std::size_t>& ref_stage,
3220 const std::vector<std::size_t>& hop_cls,
3221 const std::vector<std::size_t>& hop_ret,
3222 const std::vector<std::size_t>& ret_cls,
3223 const std::vector<std::size_t>& gate,
const std::vector<std::size_t>& aux,
3224 const std::vector<std::size_t>& resume,
3225 const std::vector<std::size_t>& cls)
const {
3226 std::set<std::size_t> watch;
3227 for (std::size_t k : ref_stage)
3228 if (k) watch.insert(k);
3229 for (std::size_t e = 1; e < hop.size(); ++e)
3231 if (hop_cls[e]) watch.insert(hop_cls[e]);
3232 if (hop_ret[e]) watch.insert(hop_ret[e]);
3234 for (std::size_t t = 1; t < member.size(); ++t)
3236 if (ret_cls[t]) watch.insert(ret_cls[t]);
3237 if (cls[t]) watch.insert(cls[t]);
3239 for (std::size_t c = 1; c <
expand.size(); ++c)
3241 if (gate[c]) watch.insert(gate[c]);
3242 if (aux[c]) watch.insert(aux[c]);
3243 if (resume[c]) watch.insert(resume[c]);
3245 const std::size_t I = m.nodes.size();
3246 for (std::size_t r : watch) {
3247 for (std::size_t n = 1; n <= I; ++n) {
3250 for (
const auto& kv : m.P) {
3251 if (kv.first.first != r || n > kv.second.rows())
continue;
3252 for (std::size_t j = 0; j < kv.second.cols(); ++j) {
3253 const double v = dbl(kv.second(n - 1, j));
3259 std::cerr <<
"[LINE] Warning: refpath layer '" << lqn.hashnames[idx]
3260 <<
"': class '" << m.classes[r - 1].name <<
"' routes out of node "
3261 << n <<
" with a negative probability.\n";
3263 std::cerr <<
"[LINE] Warning: refpath layer '" << lqn.hashnames[idx]
3264 <<
"': class '" << m.classes[r - 1].name <<
"' leaves node " << n
3265 <<
" with total probability " <<
tot <<
".\n";
3268 std::size_t nref = 0;
3269 for (
const qn::JobClass& jc : m.classes)
3270 if (jc.is_ref_class) ++nref;
3272 for (
bool h : head_is_caller)
3274 for (std::size_t t : callers)
3275 if (!spliced[t] && needs_class(t)) ++
expect;
3277 std::cerr <<
"[LINE] Warning: refpath layer '" << lqn.hashnames[idx] <<
"' declares "
3278 << nref <<
" reference classes where " <<
expect
3279 <<
" were built; a chain holding two makes refresh_chains throw.\n";
3311 std::size_t curclass;
3316 static bool is_aux_class(
const std::string& name) {
3317 return name.size() >= 4 &&
name.compare(
name.size() - 4, 4,
".Aux") == 0;
3319 template <
class Ctx>
3320 Ctx route_sync_call(qn::Layer<T>& m, std::size_t idx, std::size_t cidx, Ctx st,
3321 const std::vector<std::size_t>& tnode,
3322 const std::vector<std::size_t>& tstat,
3323 const std::vector<std::size_t>& callcls,
3324 const std::vector<std::size_t>& auxcallcls, std::size_t clientNode,
3325 int atClient,
int atServer,
bool flat) {
3326 const T one = Tone();
3330 const std::size_t ntgt = tnode.size();
3331 const bool to_this_server = ntgt > 0;
3332 const T nrep = num_traits<T>::from_int(
int(ntgt > 0 ? ntgt : 1));
3333 const T share = T(one / nrep);
3334 const T callmean = lqn.callproc_mean[cidx];
3335 const std::size_t cc = callcls[cidx];
3336 const std::size_t ax = auxcallcls[cidx];
3337 const bool below = callmean < one;
3338 const bool above = callmean > one;
3339 if (st.jobpos == atClient) {
3340 if (to_this_server) {
3342 m.set_route(st.curclass, ax, clientNode, clientNode, T(one - callmean));
3343 for (std::size_t r = 0; r < ntgt; ++r) {
3344 m.set_route(st.curclass, cc, clientNode, tnode[r], T(callmean / nrep));
3345 m.set_route(cc, cc, tnode[r], clientNode, one);
3348 m.set_route(ax, cc, clientNode, clientNode, one);
3350 for (std::size_t r = 0; r < ntgt; ++r) {
3351 m.set_route(st.curclass, cc, clientNode, tnode[r], share);
3352 m.set_route(cc, ax, tnode[r], clientNode, one);
3353 m.set_route(ax, cc, clientNode, tnode[r], T((one - one / callmean) / nrep));
3355 m.set_route(ax, cc, clientNode, clientNode, T(one / callmean));
3357 for (std::size_t r = 0; r < ntgt; ++r) {
3358 m.set_route(st.curclass, cc, clientNode, tnode[r], share);
3359 m.set_route(cc, cc, tnode[r], clientNode, one);
3362 for (std::size_t r = 0; r < ntgt; ++r) {
3363 m.set_service(tstat[r], cc, callservtproc[cidx]);
3364 call_map.push_back({idx, cidx, tstat[r], cc});
3367 st.jobpos = atClient;
3368 st.curnodes.clear();
3371 m.set_route(st.curclass, cc, clientNode, clientNode, one);
3372 if (below || above) {
3373 m.set_route(cc, ax, clientNode, clientNode, one);
3378 st.jobpos = atClient;
3379 st.curnodes.clear();
3380 m.set_service(m.clientIdx, cc, callservtproc[cidx]);
3381 call_map.push_back({idx, cidx, m.clientIdx, cc});
3385 auto fromNode = [&](std::size_t r) {
3386 return st.curnodes[std::min(r, st.curnodes.size() - 1)];
3388 if (to_this_server) {
3397 for (std::size_t r = 0; r < ntgt; ++r) {
3398 m.set_route(st.curclass, ax, fromNode(r), clientNode, T(one - callmean));
3399 m.set_route(st.curclass, cc, fromNode(r), tnode[r], T(callmean / nrep));
3400 m.set_route(cc, cc, tnode[r], clientNode, one);
3402 m.set_route(ax, cc, clientNode, clientNode, one);
3404 st.jobpos = atClient;
3405 st.curnodes.clear();
3411 for (std::size_t r = 0; r < ntgt; ++r) {
3412 m.set_route(st.curclass, cc, fromNode(r), tnode[r], one);
3413 m.set_route(cc, ax, tnode[r], clientNode, one);
3414 m.set_route(ax, cc, clientNode, tnode[r],
3415 T((one - one / callmean) / nrep));
3417 m.set_route(ax, cc, clientNode, clientNode, T(one / callmean));
3421 for (std::size_t r = 0; r < ntgt; ++r) {
3422 m.set_route(st.curclass, cc, fromNode(r), tnode[r], one);
3423 m.set_route(cc, cc, tnode[r], tnode[r], T(one - one / callmean));
3424 m.set_route(cc, ax, tnode[r], clientNode, T(one / callmean));
3428 st.jobpos = atClient;
3429 st.curnodes.clear();
3431 for (std::size_t r = 0; r < ntgt; ++r)
3432 m.set_route(st.curclass, cc, fromNode(r), tnode[r], one);
3436 for (std::size_t r = 0; r < ntgt; ++r)
3437 m.set_route(cc, cc, tnode[r], clientNode, one);
3439 st.jobpos = atClient;
3440 st.curnodes.clear();
3442 st.jobpos = atServer;
3443 st.curnodes = tnode;
3447 for (std::size_t r = 0; r < ntgt; ++r) {
3448 m.set_service(tstat[r], cc, callservtproc[cidx]);
3449 call_map.push_back({idx, cidx, tstat[r], cc});
3452 for (std::size_t nd : st.curnodes)
3453 m.set_route(st.curclass, cc, nd, clientNode, one);
3454 if (below || above) {
3455 m.set_route(cc, ax, clientNode, clientNode, one);
3460 st.jobpos = atClient;
3461 st.curnodes.clear();
3462 m.set_service(m.clientIdx, cc, callservtproc[cidx]);
3463 call_map.push_back({idx, cidx, m.clientIdx, cc});
3478 void build_entry_service_matrix() {
3479 const std::size_t dim = lqn.nidx + lqn.ncalls;
3480 servtmatrix =
Matrix<T>(dim + 1, dim + 1, Tzero());
3481 std::function<void(std::size_t, std::size_t)> rec = [&](std::size_t aidx, std::size_t eidx) {
3482 for (std::size_t nextaidx : lqn.graph.succ(aidx)) {
3483 const bool isLoop = lqn.graph.get(aidx, nextaidx) != lqn.dag.get(aidx, nextaidx);
3484 if (lqn.parent[aidx] != lqn.parent[nextaidx]) {
3485 for (std::size_t cidx : lqn.callsof[aidx])
3486 if (lqn.calltype[cidx] == CallType::SYNC)
3487 servtmatrix(eidx, lqn.nidx + cidx) = Tone();
3488 }
else if (nextaidx != aidx && !isLoop) {
3489 servtmatrix(eidx, nextaidx) = Tone();
3490 rec(nextaidx, eidx);
3494 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
3495 const std::size_t eidx = lqn.eshift + e;
3513 bool has_interlock() {
3514 if (!opt.interlocking)
return false;
3515 if (il_num_sources.empty()) init_interlock();
3516 for (std::size_t s = 0; s < il_num_sources.size(); ++s)
3517 if (il_num_sources[s] > 0.0 && s < il_common_entries.size() &&
3518 !il_common_entries[s].empty())
3523 void init_interlock() {
3524 const std::size_t NE = lqn.nentries;
3525 il_all =
Matrix<T>(NE + 1, NE + 1, Tzero());
3526 il_ph1 =
Matrix<T>(NE + 1, NE + 1, Tzero());
3528 std::function<void(std::size_t, std::size_t, T, T, std::vector<bool>&,
int)> trace =
3529 [&](std::size_t eidx, std::size_t root_e, T pall, T pph1, std::vector<bool>& visited,
3531 if (eidx <= lqn.eshift || eidx > lqn.eshift + NE)
return;
3532 const std::size_t e = eidx - lqn.eshift;
3533 if (visited[e])
return;
3535 il_all(root_e, e) = T(il_all(root_e, e) + pall);
3536 il_ph1(root_e, e) = T(il_ph1(root_e, e) + pph1);
3537 for (std::size_t aidx : lqn.actsof[eidx]) {
3538 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts)
continue;
3539 const std::size_t a = aidx - lqn.ashift;
3540 if (depth > 0 && lqn.actphase[a] > 1)
continue;
3541 const bool is_ph1 = lqn.actphase[a] <= 1;
3542 for (std::size_t cidx : lqn.callsof[aidx]) {
3543 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
3544 if (!(lqn.callproc_mean[cidx] > Tzero()))
continue;
3545 const std::size_t dst = lqn.callpair_dst[cidx];
3546 if (dst <= lqn.eshift || dst > lqn.eshift + NE)
continue;
3547 trace(dst, root_e, T(pall * lqn.callproc_mean[cidx]),
3548 is_ph1 ? T(pph1 * lqn.callproc_mean[cidx]) : Tzero(), visited,
3554 for (std::size_t e = 1; e <= NE; ++e) {
3555 std::vector<bool> visited(NE + 1,
false);
3556 trace(lqn.eshift + e, e, Tone(), Tone(), visited, 0);
3559 il_common_entries.assign(NT() + 1, {});
3560 il_src_all.assign(NT() + 1, {});
3561 il_src_ph2.assign(NT() + 1, {});
3562 il_num_sources.assign(NT() + 1, 0.0);
3564 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
3565 const std::size_t tidx = lqn.tshift + t;
3566 if (lqn.isref[tidx] || lqn.sched[tidx] == SchedStrategy::INF)
continue;
3567 interlock_for_server(tidx);
3569 for (std::size_t h = 1; h <= lqn.nhosts; ++h) {
3570 if (lqn.sched[h] == SchedStrategy::INF)
continue;
3571 interlock_for_server(h);
3575 std::vector<std::size_t> server_entry_nums(std::size_t serverIdx)
const {
3576 std::vector<std::size_t> out;
3577 if (serverIdx <= lqn.nhosts) {
3578 for (std::size_t tidx : lqn.tasksof[serverIdx])
3579 for (std::size_t se : lqn.entriesof[tidx]) out.push_back(se - lqn.eshift);
3581 for (std::size_t se : lqn.entriesof[serverIdx]) out.push_back(se - lqn.eshift);
3586 std::vector<std::size_t> client_tasks(std::size_t serverIdx)
const {
3587 std::vector<std::size_t> out;
3588 if (serverIdx <= lqn.nhosts)
return lqn.tasksof[serverIdx];
3589 for (std::size_t se : lqn.entriesof[serverIdx])
3590 for (std::size_t ci : lqn.iscaller.col(se))
3591 if (ci > lqn.tshift && ci <= NT()) out.push_back(ci);
3592 std::sort(out.begin(), out.end());
3593 out.erase(std::unique(out.begin(), out.end()), out.end());
3597 std::vector<std::size_t> call_dst_tasks(std::size_t src_eidx, std::size_t target_e)
const {
3598 std::vector<std::size_t> out;
3599 for (std::size_t aidx : lqn.actsof[src_eidx]) {
3600 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts)
continue;
3601 for (std::size_t cidx : lqn.callsof[aidx]) {
3602 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
3603 const std::size_t dst = lqn.callpair_dst[cidx];
3604 const std::size_t de = dst - lqn.eshift;
3605 if (de >= 1 && de <= lqn.nentries && il_all(de, target_e) > Tzero())
3606 out.push_back(lqn.parent[dst]);
3609 std::sort(out.begin(), out.end());
3610 out.erase(std::unique(out.begin(), out.end()), out.end());
3614 bool is_branch_point(std::size_t srcX, std::size_t entryA, std::size_t srcY,
3615 std::size_t entryB)
const {
3616 const std::size_t taskA = lqn.parent[entryA], taskB = lqn.parent[entryB];
3617 const std::size_t taskX = lqn.parent[srcX];
3618 if (taskX == taskA && taskX == taskB)
return false;
3619 if (srcX == entryA || srcY == entryB)
return true;
3620 const std::vector<std::size_t> dx = call_dst_tasks(srcX, entryA - lqn.eshift);
3621 const std::vector<std::size_t> dy = call_dst_tasks(srcY, entryB - lqn.eshift);
3622 for (std::size_t a : dx)
3623 for (std::size_t b : dy)
3624 if (a != b)
return true;
3628 void trace_to_server(std::size_t eidx, std::size_t serverIdx, std::vector<bool>& visited,
3629 std::vector<std::size_t>& itasks,
bool isHead)
const {
3630 if (eidx <= lqn.eshift || eidx > lqn.eshift + lqn.nentries)
return;
3631 const std::size_t e = eidx - lqn.eshift;
3632 if (visited[e])
return;
3633 const std::size_t owner = lqn.parent[eidx];
3634 if (owner == serverIdx)
return;
3635 if (serverIdx <= lqn.nhosts && lqn.parent[owner] == serverIdx)
return;
3638 const std::vector<std::size_t> sen = server_entry_nums(serverIdx);
3639 for (std::size_t aidx : lqn.actsof[eidx]) {
3640 if (aidx <= lqn.ashift || aidx > lqn.ashift + lqn.nacts)
continue;
3641 for (std::size_t cidx : lqn.callsof[aidx]) {
3642 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
3643 const std::size_t dst = lqn.callpair_dst[cidx];
3644 const std::size_t dtask = lqn.parent[dst];
3645 bool reaches = dtask == serverIdx ||
3646 (serverIdx <= lqn.nhosts && lqn.parent[dtask] == serverIdx);
3648 const std::size_t de = dst - lqn.eshift;
3649 for (std::size_t sn : sen)
3650 if (il_all(de, sn) > Tzero()) reaches =
true;
3653 trace_to_server(dst, serverIdx, visited, itasks,
false);
3658 if (found && !isHead) {
3659 itasks.push_back(owner);
3660 std::sort(itasks.begin(), itasks.end());
3661 itasks.erase(std::unique(itasks.begin(), itasks.end()), itasks.end());
3666 void interlock_for_server(std::size_t serverIdx) {
3667 const std::vector<std::size_t> sen = server_entry_nums(serverIdx);
3668 if (sen.empty())
return;
3669 const std::vector<std::size_t> cts = client_tasks(serverIdx);
3670 if (cts.empty())
return;
3672 std::vector<std::pair<std::size_t, std::size_t>> pairs;
3673 for (std::size_t ct : cts)
3674 for (std::size_t ce : lqn.entriesof[ct]) {
3675 const std::size_t cen = ce - lqn.eshift;
3676 if (cen < 1 || cen > lqn.nentries)
continue;
3677 for (std::size_t se : sen)
3678 if (il_all(cen, se) > Tzero()) {
3679 pairs.emplace_back(ct, cen);
3683 if (pairs.size() < 2)
return;
3688 std::vector<bool> reach_ph1(lqn.nentries + 1,
false);
3689 for (
const auto& p : pairs)
3690 for (std::size_t se : sen)
3691 if (il_ph1(p.second, se) > Tzero()) {
3692 reach_ph1[p.second] =
true;
3696 std::vector<std::size_t> common;
3697 for (std::size_t i = 0; i < pairs.size(); ++i)
3698 for (std::size_t j = i + 1; j < pairs.size(); ++j) {
3699 if (pairs[i].first == pairs[j].first)
continue;
3700 const std::size_t eA = pairs[i].second, eC = pairs[j].second;
3701 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
3702 const std::size_t tidx = lqn.tshift + t;
3703 for (std::size_t ex : lqn.entriesof[tidx])
3704 for (std::size_t ey : lqn.entriesof[tidx]) {
3705 const std::size_t xn = ex - lqn.eshift, yn = ey - lqn.eshift;
3706 if (xn < 1 || yn < 1 || xn > lqn.nentries || yn > lqn.nentries)
continue;
3707 if (il_all(xn, eA) > Tzero() && il_all(yn, eC) > Tzero() &&
3708 (reach_ph1[eA] || xn == eA) && (reach_ph1[eC] || yn == eC) &&
3709 is_branch_point(ex, eA + lqn.eshift, ey, eC + lqn.eshift))
3710 common.push_back(ex);
3714 std::sort(common.begin(), common.end());
3715 common.erase(std::unique(common.begin(), common.end()), common.end());
3716 if (common.empty())
return;
3718 std::vector<std::size_t> interlocked;
3719 for (std::size_t ce : common) {
3720 std::vector<bool> visited(lqn.nentries + 1,
false);
3721 std::vector<std::size_t> it;
3722 trace_to_server(ce, serverIdx, visited, it,
true);
3723 for (std::size_t x : it) interlocked.push_back(x);
3725 std::sort(interlocked.begin(), interlocked.end());
3726 interlocked.erase(std::unique(interlocked.begin(), interlocked.end()), interlocked.end());
3728 std::vector<std::size_t> src_all;
3729 for (std::size_t ce : common) src_all.push_back(lqn.parent[ce]);
3730 std::sort(src_all.begin(), src_all.end());
3731 src_all.erase(std::unique(src_all.begin(), src_all.end()), src_all.end());
3733 std::vector<std::size_t> diff;
3734 for (std::size_t x : src_all)
3735 if (!std::binary_search(interlocked.begin(), interlocked.end(), x)) diff.push_back(x);
3743 std::vector<std::size_t> src_ph2;
3744 for (std::size_t it : interlocked)
3745 for (std::size_t ie : lqn.entriesof[it])
3746 for (std::size_t ci : lqn.iscaller.col(ie))
3747 if (ci > lqn.tshift && ci <= NT() &&
3748 !std::binary_search(interlocked.begin(), interlocked.end(), ci))
3749 src_all.push_back(ci);
3750 std::sort(src_all.begin(), src_all.end());
3751 src_all.erase(std::unique(src_all.begin(), src_all.end()), src_all.end());
3754 for (std::size_t st : src_all) nsrc += lqn.mult[st];
3756 il_common_entries[serverIdx] = common;
3757 il_src_all[serverIdx] = src_all;
3758 il_src_ph2[serverIdx] = src_ph2;
3759 il_num_sources[serverIdx] = nsrc;
3766 const std::size_t N = lqn.nidx;
3767 tput.assign(N + 1, Tzero());
3768 util.assign(N + 1, Tzero());
3769 servt.assign(N + 1, Tzero());
3770 residt.assign(N + 1, Tzero());
3771 thinkt.assign(N + 1, Tzero());
3772 callservt.assign(lqn.ncalls + 1, Tzero());
3773 callresidt.assign(lqn.ncalls + 1, Tzero());
3775 servt_ph1.assign(N + 1, Tzero());
3776 servt_ph2.assign(N + 1, Tzero());
3777 prOvertake.assign(lqn.nentries + 1, Tzero());
3778 build_entry_service_matrix();
3780 relax_omega = (opt.relax ==
"fixed" || opt.relax ==
"adaptive") ? opt.relax_factor : 1.0;
3782 servt_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3783 residt_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3784 tput_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3785 thinkt_prev.assign(N + 1, std::numeric_limits<double>::quiet_NaN());
3786 callservt_prev.assign(lqn.ncalls + 1, std::numeric_limits<double>::quiet_NaN());
3787 callresidt_prev.assign(lqn.ncalls + 1, std::numeric_limits<double>::quiet_NaN());
3788 servt_prev_v.assign(N + 1, Tzero());
3789 residt_prev_v.assign(N + 1, Tzero());
3790 tput_prev_v.assign(N + 1, Tzero());
3791 thinkt_prev_v.assign(N + 1, Tzero());
3792 callservt_prev_v.assign(lqn.ncalls + 1, Tzero());
3794 unique_route_idx.clear();
3795 for (
const RouteRow& r : route_map) unique_route_idx.push_back(r.idx);
3796 std::sort(unique_route_idx.begin(), unique_route_idx.end());
3797 unique_route_idx.erase(std::unique(unique_route_idx.begin(), unique_route_idx.end()),
3798 unique_route_idx.end());
3801 if (interlockMethod ==
"ilrate") init_interlock();
3803 maxitererr.assign(opt.iter_max + 2, 0.0);
3804 results_raw_last.clear();
3805 results_raw_valid =
false;
3806 averagingstart = -1;
3807 hasconverged =
false;
3808 moment_pass_done =
false;
3811 servtcdf.assign(N + 1, fluid::FluidPassage());
3812 callservtcdf.assign(lqn.ncalls + 1, fluid::FluidPassage());
3813 entrycdfrespt.assign(lqn.nentries + 1, LnCdf());
3814 entryproc.assign(lqn.nentries + 1, mam::AphPair<T>());
3815 cdf_repo.assign(ensemble.size(), std::vector<std::vector<fluid::FluidPassage>>());
3819 warmstarted_ =
false;
3820 if (opt.warmstart ==
"nlp") {
3822 }
else if (opt.warmstart ==
"mol") {
3838 const bool stoch = layer_solver_is_stochastic();
3841 cfg.iter_tol = opt.iter_tol;
3842 cfg.relax_burnin = relax_omega;
3843 stoch_ctl = std::make_shared<LnStochController<T>>(cfg);
3848 bool done = !stoch && converged(it);
3849 while (!done && it < opt.iter_max) {
3850 if (results_raw_valid) {
3851 results.back() = results_raw_last;
3852 results_raw_valid =
false;
3855 results.emplace_back(ensemble.size());
3856 for (std::size_t e = 0; e < ensemble.size(); ++e) analyze(it, e);
3859 std::vector<double> jobs(ensemble.size(), 0.0);
3860 for (std::size_t e = 0; e < ensemble.size(); ++e)
3861 jobs[e] = ensemble[e].total_jobs();
3862 const bool stop = stoch_ctl->update(it, results.back(), jobs, servt, residt);
3865 relax_omega = stoch_ctl->relax_omega();
3867 did_converge =
true;
3868 hasconverged =
true;
3872 done = converged(it);
3875 iterations_done = it;
3878 if (stoch && stoch_ctl && stoch_ctl->averaging_count() > 0) {
3879 const std::vector<LayerResult<T>>& avg = stoch_ctl->averaged_results();
3880 for (std::size_t e = 0; e < results.back().size() && e < avg.size(); ++e)
3881 results.back()[e] = avg[e];
3882 servt = stoch_ctl->averaged_servt();
3883 residt = stoch_ctl->averaged_residt();
3907 Matrix<T> filter_metric(
const qn::Layer<T>& L,
const Matrix<T>& metric,
3908 const std::vector<std::vector<bool>>* zero_mask)
const {
3909 const std::size_t M = L.nstations, K = L.nclasses;
3910 Matrix<T> out(M, K, Tzero());
3911 for (std::size_t i = 0; i < M; ++i)
3912 for (std::size_t k = 0; k < K; ++k)
3913 if (!L.disabled[i][k]) out(i, k) = metric(i, k);
3915 for (std::size_t i = 0; i < M; ++i)
3916 for (std::size_t k = 0; k < K; ++k)
3917 if ((*zero_mask)[i][k]) out(i, k) = Tzero();
3918 for (std::size_t i = 0; i < M; ++i)
3919 for (std::size_t k = 0; k < K; ++k)
3921 for (std::size_t k = 0; k < K; ++k) {
3922 std::size_t c = L.nchains;
3923 for (std::size_t cc = 0; cc < L.nchains; ++cc)
3924 if (L.chains[cc][k]) c = cc;
3925 if (c == L.nchains)
continue;
3926 for (std::size_t i = 0; i < M; ++i)
3927 if (L.visits[c](L.stateful_of_station(i + 1) - 1, k) == Tzero())
3928 out(i, k) = Tzero();
3945 mva::MvaSolution<T> solve_layer_ctmc(std::size_t e) {
3946 refuse_fork_layer(e);
3947 qn::Layer<T>& L = ensemble[e];
3952 const ctmc::CtmcOptions& co = opt.layer_ctmc;
3957 mva::MvaSolution<T> out;
3958 out.method =
"ctmc";
3979 mva::MvaSolution<T> solve_layer_mam(std::size_t e) {
3980 refuse_fork_layer(e);
3981 qn::Layer<T>& L = ensemble[e];
3983 L.refresh_capacity();
3990 void refuse_fork_layer(std::size_t e)
const {
3991 if (fj_tr[e].active())
3993 "SolverLN: layer '" + ensemble[e].name +
3994 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
3995 "model with layer_solver 'mva'");
4008 mva::MvaSolution<T> solve_layer_nc(std::size_t e) {
4009 if (fj_tr[e].active())
4011 "SolverLN: layer '" + ensemble[e].name +
4012 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
4013 "model with layer_solver 'mva'");
4014 qn::Layer<T>& L = ensemble[e];
4044 mva::MvaSolution<T> solve_layer_ssa(std::size_t e) {
4045 if (fj_tr[e].active())
4047 "SolverLN: layer '" + ensemble[e].name +
4048 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
4049 "model with layer_solver 'mva'");
4050 qn::Layer<T>& L = ensemble[e];
4052 ssa::SsaOptions so = opt.layer_ssa;
4053 so.seed =
static_cast<unsigned long>(
static_cast<long>(so.seed) + sens_rep_offset());
4054 so.samples = sens_rep_samples(so.samples);
4056 mva::MvaSolution<T> out;
4059 out.Q =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4060 out.U =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4061 out.R =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4062 out.Tp =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4063 for (std::size_t i = 0; i < L.nstations; ++i)
4064 for (std::size_t r = 0; r < L.nclasses; ++r) {
4065 out.Q(i, r) = num_traits<T>::from_double(s.QN(i, r));
4066 out.U(i, r) = num_traits<T>::from_double(s.UN(i, r));
4067 out.R(i, r) = num_traits<T>::from_double(s.RN(i, r));
4068 out.Tp(i, r) = num_traits<T>::from_double(s.TN(i, r));
4070 out.C.assign(L.nclasses, Tzero());
4071 out.X.assign(L.nclasses, Tzero());
4072 for (std::size_t r = 0; r < L.nclasses && r < s.XN.size(); ++r) {
4073 out.X[r] = num_traits<T>::from_double(s.XN[r]);
4074 out.C[r] = num_traits<T>::from_double(s.CN[r]);
4090 mva::MvaSolution<T> solve_layer_ldes(std::size_t e) {
4091 refuse_fork_layer(e);
4092 qn::Layer<T>& L = ensemble[e];
4095 if constexpr (!std::is_same<T, double>::value) {
4097 "SolverLN: the ldes layer engine simulates in double precision; "
4098 "rerun with --arith double");
4101 ldes::LdesOptions lo = opt.layer_ldes;
4102 lo.seed = layer_seed(opt.layer_ldes.seed, e);
4103 lo.samples = sens_rep_samples(lo.samples);
4104 if (lo.events > 0) lo.events = sens_rep_samples(lo.events);
4106 mva::MvaSolution<T> out = sim_layer_solution(L, s.QN, s.UN, s.RN, s.TN,
"ldes");
4107 for (std::size_t r = 0; r < L.nclasses && r < s.XN.cols(); ++r) {
4108 out.X[r] = s.XN(0, r);
4109 out.C[r] = s.CN(0, r);
4124 mva::MvaSolution<T> solve_layer_jmt(std::size_t e) {
4125 refuse_fork_layer(e);
4126 qn::Layer<T>& L = ensemble[e];
4127 for (std::size_t i = 0; i < L.immfeed.size(); ++i)
4128 for (std::size_t r = 0; r < L.immfeed[i].size(); ++r)
4129 if (L.immfeed[i][r])
4131 "SolverJMT cannot solve LN layer " + std::to_string(e + 1) +
4132 ": the layer carries immediate feedback (sn.immfeed), which SolverJMT does "
4133 "not support, so LN would fail at the first iteration. Use the default layer "
4134 "factory (MVA/NC) or another layer solver that supports immediate feedback.");
4136 jmt::JmtOptions jo = opt.layer_jmt;
4137 jo.seed = layer_seed(opt.layer_jmt.seed, e);
4138 jo.samples = sens_rep_samples(jo.samples);
4141 Matrix<double> Q(L.nstations, L.nclasses, 0.0), U = Q, R = Q, X = Q;
4142 for (std::size_t i = 0; i < L.nstations; ++i)
4143 for (std::size_t r = 0; r < L.nclasses; ++r) {
4144 Q(i, r) = num_traits<T>::to_double(s.avg.QN(i, r));
4145 U(i, r) = num_traits<T>::to_double(s.avg.UN(i, r));
4146 R(i, r) = num_traits<T>::to_double(s.avg.RN(i, r));
4147 X(i, r) = num_traits<T>::to_double(s.avg.TN(i, r));
4149 mva::MvaSolution<T> out = sim_layer_solution(L, Q, U, R, X,
"jmt");
4150 for (std::size_t r = 0; r < L.nclasses; ++r) {
4151 if (r < s.avg.XN.size()) out.X[r] = s.avg.XN[r];
4152 if (r < s.avg.CN.size()) out.C[r] = s.avg.CN[r];
4158 static mva::MvaSolution<T> sim_layer_solution(
const qn::Layer<T>& L,
const Matrix<double>& Q,
4159 const Matrix<double>& U,
const Matrix<double>& R,
4160 const Matrix<double>& X,
const char* method) {
4161 mva::MvaSolution<T> out;
4162 out.method = method;
4164 out.Q =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4165 out.U =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4166 out.R =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4167 out.Tp =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4168 for (std::size_t i = 0; i < L.nstations; ++i)
4169 for (std::size_t r = 0; r < L.nclasses; ++r) {
4170 out.Q(i, r) = num_traits<T>::from_double(Q(i, r));
4171 out.U(i, r) = num_traits<T>::from_double(U(i, r));
4172 out.R(i, r) = num_traits<T>::from_double(R(i, r));
4173 out.Tp(i, r) = num_traits<T>::from_double(X(i, r));
4175 out.C.assign(L.nclasses, Tzero());
4176 out.X.assign(L.nclasses, Tzero());
4202 mva::MvaSolution<T> solve_layer_fluid(std::size_t e) {
4203 if (fj_tr[e].active())
4205 "SolverLN: layer '" + std::to_string(e) +
4206 "' carries a fork, whose fixed point is driven by MVA in this port; solve this "
4207 "model with layer_solver 'mva'");
4208 qn::Layer<T>& L = ensemble[e];
4218 mva::MvaSolution<T> out;
4219 out.method =
"fluid";
4221 out.Q =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4222 out.U =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4223 out.R =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4224 out.Tp =
Matrix<T>(L.nstations, L.nclasses, Tzero());
4225 out.C.assign(L.nclasses, Tzero());
4226 out.X.assign(L.nclasses, Tzero());
4227 detail::ln_fluid_solve(L, opt.layer_fluid, out);
4243 mva::MvaSolution<T> solve_layer(std::size_t e) {
4253 ensemble[e].refresh_capacity();
4263 if (!ensemble[e].regions.empty() && opt.layer_solver !=
"ldes" && opt.layer_solver !=
"jmt")
4264 return solve_layer_ctmc(e);
4277 if (has_cache_node(e)) ensemble[e].refresh_rt();
4278 if (opt.layer_solver ==
"fluid")
return solve_layer_fluid(e);
4279 if (opt.layer_solver ==
"nc")
return solve_layer_nc(e);
4280 if (opt.layer_solver ==
"ssa")
return solve_layer_ssa(e);
4281 if (opt.layer_solver ==
"mam")
return solve_layer_mam(e);
4282 if (opt.layer_solver ==
"ctmc")
return solve_layer_ctmc(e);
4283 if (opt.layer_solver ==
"ldes")
return solve_layer_ldes(e);
4284 if (opt.layer_solver ==
"jmt")
return solve_layer_jmt(e);
4285 if (opt.layer_solver !=
"mva")
4286 throw UnsupportedError(ErrorKind{
"Option"},
"SolverLN: layer_solver '" + opt.layer_solver +
4287 "' is not available; use 'mva', 'nc', 'fluid', 'ssa', 'mam', 'ctmc', "
4295 mva::MvaOptions eopt = opt.layer;
4296 if (e < layer_interlock.size()) eopt.interlock = layer_interlock[e];
4297 if (!fj_tr[e].active())
4299 mva::MvaOptions lopt = eopt;
4300 if (lopt.method ==
"default") lopt.method =
"amva";
4302 ensemble[e], fj_tr[e], fj_lambda[e], eopt,
4303 [&lopt](qn::NetworkStruct<T>& V) {
4308 void analyze(
int it, std::size_t e) {
4309 qn::Layer<T>& L = ensemble[e];
4311 const mva::MvaSolution<T> s = solve_layer(e);
4312 LayerResult<T>& r = results[it - 1][e];
4313 r.RN = filter_metric(L, s.R,
nullptr);
4314 std::vector<std::vector<bool>> zmask(L.nstations, std::vector<bool>(L.nclasses,
false));
4315 for (std::size_t i = 0; i < L.nstations; ++i)
4316 for (std::size_t k = 0; k < L.nclasses; ++k)
4318 r.QN = filter_metric(L, s.Q, &zmask);
4319 r.UN = filter_metric(L, s.U, &zmask);
4320 r.TN = filter_metric(L, s.Tp,
nullptr);
4321 r.WN = residence_from_response(L, r.RN);
4331 if (!fj_tr[e].active() && opt.layer_solver ==
"mva") {
4332 Matrix<T> Qch(L.nstations, L.nchains, Tzero());
4333 for (std::size_t c = 0; c < L.nchains; ++c)
4334 for (std::size_t i = 0; i < L.nstations; ++i) {
4336 for (std::size_t k : L.inchain[c]) s2 += s.Q(i, k - 1);
4339 layer_init_sol[e] = Qch;
4344 Matrix<T> residence_from_response(
const qn::Layer<T>& L,
const Matrix<T>& RN)
const {
4345 Matrix<T> V(L.nstations, L.nclasses, Tzero());
4346 for (std::size_t c = 0; c < L.nchains; ++c)
4347 for (std::size_t i = 0; i < L.nstations; ++i) {
4348 const std::size_t sf = L.stateful_of_station(i + 1) - 1;
4349 for (std::size_t k = 0; k < L.nclasses; ++k)
4350 V(i, k) = T(V(i, k) + L.visits[c](sf, k));
4352 Matrix<T> WN(L.nstations, L.nclasses, Tzero());
4353 for (std::size_t i = 0; i < L.nstations; ++i)
4354 for (std::size_t k = 0; k < L.nclasses; ++k) {
4355 if (L.disabled[i][k])
continue;
4356 if (!(RN(i, k) > Tzero()))
continue;
4358 WN(i, k) = RN(i, k);
4362 for (std::size_t cc = 0; cc < L.nchains; ++cc)
4363 if (L.chains[cc][k]) c = cc;
4364 const std::size_t rstat = L.classes[k].refstat;
4366 if (L.refclass[c] > 0) {
4367 den = V(rstat - 1, L.refclass[c] - 1);
4369 for (std::size_t kk : L.inchain[c]) den += V(rstat - 1, kk - 1);
4371 if (den == Tzero())
continue;
4372 WN(i, k) = T(RN(i, k) * V(i, k) / den);
4374 for (std::size_t i = 0; i < L.nstations; ++i)
4375 for (std::size_t k = 0; k < L.nclasses; ++k)
4384 if (interlockMethod ==
"ilrate") update_populations(it);
4385 update_think_times(it);
4387 update_routing_probabilities(it);
4388 for (std::size_t e : route_reset) {
4389 ensemble[e].refresh_chains();
4395 for (std::size_t e : svc_reset) ensemble[e].refresh_rates();
4399 bool converged(
int it) {
4400 const std::size_t E = ensemble.size();
4401 const int iter_min = std::max<int>(2 *
int(E),
int(std::ceil(opt.iter_max / 4.0)));
4402 const int wnd_size = std::max(5,
int(std::ceil(iter_min / 5.0)));
4404 if (it >= iter_min &&
int(results.size()) >= wnd_size) {
4405 results_raw_last = results.back();
4406 results_raw_valid =
true;
4407 const T w = T(Tone() / num_traits<T>::from_int(wnd_size));
4408 for (std::size_t e = 0; e < E; ++e) {
4409 LayerResult<T>& cur = results[results.size() - 1][e];
4410 auto scale = [&](Matrix<T>& A) {
4411 for (std::size_t i = 0; i < A.rows(); ++i)
4412 for (std::size_t j = 0; j < A.cols(); ++j) A(i, j) = T(A(i, j) * w);
4414 Matrix<T> Q = cur.QN, U = cur.UN, R = cur.RN, Tp = cur.TN, W = cur.WN;
4415 scale(Q); scale(U); scale(R); scale(Tp); scale(W);
4416 for (
int k = 1; k < wnd_size; ++k) {
4417 const LayerResult<T>& old = results[results.size() - 1 - k][e];
4418 auto add = [&](Matrix<T>& A,
const Matrix<T>& B) {
4419 for (std::size_t i = 0; i < A.rows(); ++i)
4420 for (std::size_t j = 0; j < A.cols(); ++j) A(i, j) = T(A(i, j) + B(i, j) * w);
4422 add(Q, old.QN); add(U, old.UN); add(R, old.RN); add(Tp, old.TN); add(W, old.WN);
4424 cur.QN = Q; cur.UN = U; cur.RN = R; cur.TN = Tp; cur.WN = W;
4430 for (std::size_t e = 0; e < E; ++e) {
4431 const Matrix<T>& Q = results[results.size() - 1][e].QN;
4432 const Matrix<T>& Q1 = results[results.size() - 2][e].QN;
4433 const double Njobs = ensemble[e].total_jobs();
4434 if (!(Njobs > 0.0))
continue;
4436 for (std::size_t i = 0; i < Q.rows(); ++i)
4437 for (std::size_t j = 0; j < Q.cols(); ++j)
4438 mx = std::max(mx, std::fabs(dbl(Q(i, j)) - dbl(Q1(i, j))));
4441 maxitererr[it] =
err;
4443 static_cast<long>(it),
4444 "layer iteration %zu: max queue-length change %.3e (tolerance %.3e)",
4445 static_cast<std::size_t
>(it), err, opt.iter_tol);
4446 if (it == iter_min) {
4448 averagingstart = it;
4455 const int stop_floor = warmstarted_ ? 3 : iter_min;
4456 if (it > stop_floor && maxitererr[it] < opt.iter_tol && maxitererr[it - 1] < opt.iter_tol &&
4457 maxitererr[it - 2] < opt.iter_tol) {
4458 if (!hasconverged) {
4459 hasconverged =
true;
4461 did_converge =
true;
4465 hasconverged =
false;
4500 std::string lnmethod;
4502 bool ph_laws_ready =
false;
4519 static std::string ln_requested_method(
const std::string& method) {
4521 for (
char c : method) m +=
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
4522 if (m.empty() || m ==
"srvn" || m ==
"default" || m ==
"auto")
return "srvn";
4523 if (m ==
"srvn.ph" || m ==
"ph")
return "srvn.ph";
4524 if (m ==
"srvn.cs" || m ==
"srvncs" || m ==
"cs")
return "srvn.cs";
4525 if (m ==
"flat.cs" || m ==
"flatcs" || m ==
"flat" || m ==
"squashed")
return "flat.cs";
4526 if (m ==
"flat.ph" || m ==
"flatph" || m ==
"squashed.ph")
return "flat.ph";
4527 if (m ==
"moment3")
return "moment3";
4529 if (m ==
"nlp" || m ==
"qdamva" || m ==
"qd-amva")
return "nlp";
4539 void assert_warmstart_encoding()
const {
4540 if (!is_ph_encoding() || opt.warmstart.empty())
return;
4541 throw InputError(
"config['warmstart']='" + opt.warmstart +
"' cannot seed method='" + lnmethod +
4542 "': its layers carry a COMPOSED PHASE-TYPE service law and the seed solves for "
4543 "means, so there is no phase distribution to start it from. Use method='srvn.cs' "
4544 "for the same layering under the routing encoding, which those means do "
4553 void validate_nlp_options()
const {
4554 const bool nlp = ln_requested_method(opt.method) ==
"nlp";
4555 if (!opt.warmstart.empty()) {
4556 if (opt.warmstart !=
"nlp" && opt.warmstart !=
"mol")
4557 throw InputError(
"config['warmstart'] takes 'nlp', 'mol' or None, got '" + opt.warmstart +
4558 "'. 'nlp' seeds the layered fixed point with the QD-AMVA program's solution "
4559 "and 'mol' with the Method of Layers'; None starts it from the model's own "
4562 throw InputError(
"config['warmstart']='" + opt.warmstart +
4563 "' is a starting point for a LAYERED method, and method='nlp' runs no "
4564 "iteration to start. Drop one of the two.");
4566 if ((nlp || !opt.warmstart.empty()) && !std::is_same<T, double>::value)
4568 std::string(nlp ?
"SolverLN: method='nlp'" :
"SolverLN: config.warmstart") +
4569 " roots a double-precision program, so it has no exact answer to give; rerun with "
4574 static T fromd(
double v) {
return num_traits<T>::from_double(v); }
4577 std::vector<double> nlp_root(::line::lqn::NlpProgram& P)
const {
4579 std::vector<double> x =
P.solve(opt.nlp_warm, opt.nlp_maxiter).x;
4580 for (
double& v : x) v = std::max(v, 0.0);
4585 static std::vector<double> nlp_act_util(const ::line::lqn::NlpProgram& P,
const std::vector<double>& Xa) {
4586 std::vector<double> u(
P.NA, 0.0);
4587 for (std::size_t a = 0; a <
P.NA; ++a) {
4588 const std::size_t h =
P.task_host[
P.act_task[a]];
4589 const double busy =
P.act_demand[a] * Xa[a];
4590 u[a] =
P.host_delay[h] ? busy : busy /
P.host_maxmult[h];
4601 LnSolution<T> nlp_analyzer() {
4602 using P_ = ::line::lqn::NlpProgram;
4604 const std::vector<double> x = nlp_root(P);
4605 const double obj =
P.objective(x);
4607 nlp_objective_ = obj;
4608 hasconverged =
P.solved(x);
4609 did_converge = hasconverged;
4612 const std::size_t N = lqn.nidx;
4613 auto blank = [&](std::vector<T>& v, std::vector<bool>& d) {
4614 v.assign(N + 1, Tzero());
4615 d.assign(N + 1,
false);
4617 blank(s.QN, s.defined_Q);
4618 blank(s.UN, s.defined_U);
4619 blank(s.RN, s.defined_R);
4620 blank(s.TN, s.defined_T);
4621 blank(s.AN, s.defined_A);
4622 blank(s.WN, s.defined_W);
4623 auto put = [&](std::vector<T>& v, std::vector<bool>& d, std::size_t i,
double val) {
4627 const std::vector<double> Xe =
P.block(x, P_::XE), Xa =
P.block(x, P_::XA), W =
P.block(x, P_::W),
4628 S =
P.block(x, P_::S), R =
P.block(x, P_::R);
4629 const std::vector<double> util_a = nlp_act_util(P, Xa);
4630 for (std::size_t a = 0; a <
P.NA; ++a) {
4632 for (std::size_t c :
P.calls_of_act[a]) resp +=
P.call_mean[c] * R[c];
4633 const std::size_t aidx = lqn.ashift + a + 1;
4634 put(s.TN, s.defined_T, aidx, Xa[a]);
4635 put(s.RN, s.defined_R, aidx, resp);
4636 put(s.QN, s.defined_Q, aidx, Xa[a] * resp);
4637 put(s.UN, s.defined_U, aidx, util_a[a]);
4638 put(s.WN, s.defined_W, aidx,
P.act_visits[a] * W[a]);
4640 for (std::size_t e = 0; e <
P.NE; ++e) {
4641 const std::size_t eidx = lqn.eshift + e + 1;
4643 for (std::size_t a = 0; a <
P.NA; ++a)
4644 if (
P.act_entry[a] == e) u += util_a[a];
4645 put(s.TN, s.defined_T, eidx, Xe[e]);
4646 put(s.RN, s.defined_R, eidx, S[e]);
4647 put(s.QN, s.defined_Q, eidx, Xe[e] * S[e]);
4648 put(s.UN, s.defined_U, eidx, u);
4650 for (std::size_t t = 0; t <
P.NT; ++t) {
4651 double tn = 0.0, qn = 0.0, un = 0.0, wn = 0.0;
4652 for (std::size_t e = 0; e <
P.NE; ++e)
4653 if (
P.entry_task[e] == t) {
4657 for (std::size_t a = 0; a <
P.NA; ++a)
4658 if (
P.act_task[a] == t) {
4660 wn +=
P.act_visits[a] * W[a];
4662 const std::size_t tidx = lqn.tshift + t + 1;
4663 put(s.TN, s.defined_T, tidx, tn);
4664 put(s.QN, s.defined_Q, tidx, qn);
4665 put(s.UN, s.defined_U, tidx, un);
4666 put(s.WN, s.defined_W, tidx, wn);
4668 for (std::size_t h = 0; h <
P.NH; ++h) {
4670 for (std::size_t a :
P.acts_of_host[h]) un += util_a[a];
4671 put(s.UN, s.defined_U, lqn.hshift + h + 1, un);
4673 for (std::size_t i = 1; i <= N; ++i)
4675 put(s.QN, s.defined_Q, i, 0.0);
4676 put(s.UN, s.defined_U, i, 0.0);
4677 put(s.RN, s.defined_R, i, 0.0);
4678 put(s.TN, s.defined_T, i, 0.0);
4679 put(s.AN, s.defined_A, i, 0.0);
4680 put(s.WN, s.defined_W, i, 0.0);
4683 s.converged = hasconverged;
4685 s.warning =
"method='nlp' did not reach a root of the QD-AMVA laws (objective " +
4687 " residuals); the reported means satisfy the linear relations but not every congestion "
4688 "law. solve() already escalated the warm start to 100 sweeps, so raise "
4689 "config['nlp_warm'] past that to start it further along.";
4694 void seed_think_time(std::size_t tidx,
double X,
double busy,
double z,
bool inf,
double mult) {
4696 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
4697 const double val = inf ? (nj - busy) / X - z : nj * std::fabs(1.0 - busy /
mult) / X -
z;
4699 thinkt[tidx] = fromd(th);
4704 void seed_processes() {
4705 for (std::size_t i = 1; i <= lqn.nidx; ++i)
4707 for (std::size_t c = 1; c <= lqn.ncalls; ++c)
4712 void seed_layers() {
4714 for (std::size_t e : svc_reset) ensemble[e].refresh_rates();
4715 warmstarted_ =
true;
4723 void nlp_warm_start() {
4724 using P_ = ::line::lqn::NlpProgram;
4726 const std::vector<double> x = nlp_root(P);
4727 const std::vector<double> Xe =
P.block(x, P_::XE), Xa =
P.block(x, P_::XA), W =
P.block(x, P_::W),
4728 S =
P.block(x, P_::S), R =
P.block(x, P_::R), BC =
P.block(x, P_::BC),
4729 BR =
P.block(x, P_::BR);
4730 const std::vector<double> util_a = nlp_act_util(P, Xa);
4731 for (std::size_t a = 0; a <
P.NA; ++a) {
4732 const std::size_t idx = lqn.ashift + a + 1;
4734 for (std::size_t c :
P.calls_of_act[a]) st +=
P.call_mean[c] * R[c];
4735 servt[idx] = fromd(st);
4736 residt[idx] = fromd(
P.act_visits[a] * W[a]);
4737 tput[idx] = fromd(Xa[a]);
4738 util[idx] = fromd(util_a[a]);
4740 for (std::size_t e = 0; e <
P.NE; ++e) {
4741 const std::size_t idx = lqn.eshift + e + 1;
4742 servt[idx] = residt[idx] = fromd(S[e]);
4743 tput[idx] = fromd(Xe[e]);
4745 for (std::size_t t = 0; t <
P.NT; ++t) {
4747 for (std::size_t e = 0; e <
P.NE; ++e)
4748 if (
P.entry_task[e] == t) x_t += Xe[e];
4749 tput[lqn.tshift + t + 1] = fromd(x_t);
4751 for (std::size_t c = 0; c <
P.NC; ++c) {
4752 callservt[c + 1] = fromd(R[c]);
4753 callresidt[c + 1] = fromd(
P.call_mean[c] * R[c]);
4757 for (std::size_t t = 0; t <
P.NT; ++t) {
4758 const std::size_t idx = lqn.tshift + t + 1;
4759 const double X = dbl(tput[idx]);
4761 const auto r = std::find(
P.ref_tasks.begin(),
P.ref_tasks.end(), t);
4763 if (r !=
P.ref_tasks.end()) {
4764 busy = BR[std::size_t(r -
P.ref_tasks.begin())];
4766 for (std::size_t c :
P.calls_into_task[t]) busy += BC[c];
4768 const double mult =
P.task_mult[t];
4769 seed_think_time(idx, X, busy,
P.task_think[t],
4770 lqn.sched[idx] == SchedStrategy::INF || std::isinf(mult), mult);
4780 void mol_warm_start() {
4781 if constexpr (num_traits<T>::has_transcendental) {
4782 ::line::lqn::LqnMolOptions mo;
4787 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
4788 const std::size_t eidx = lqn.eshift + e;
4789 const std::size_t aidx = lqn.actsof[eidx].at(0);
4790 servt[eidx] = residt[eidx] = m.info.servt[eidx];
4791 tput[eidx] = m.TN[eidx];
4792 servt[aidx] = m.info.servt[eidx];
4793 residt[aidx] = m.info.residt[eidx];
4794 tput[aidx] = m.TN[eidx];
4795 util[aidx] = m.UN[eidx];
4797 for (std::size_t t = 1; t <= lqn.ntasks; ++t) tput[lqn.tshift + t] = m.TN[lqn.tshift + t];
4798 for (std::size_t c = 1; c <= lqn.ncalls; ++c) {
4799 double y = dbl(lqn.callproc_mean[c]);
4800 if (std::isnan(y)) y = 0.0;
4801 callservt[c] = m.info.callservt[c];
4802 callresidt[c] = T(fromd(y) * m.info.callservt[c]);
4806 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
4807 const std::size_t tidx = lqn.tshift + t;
4808 const double X = dbl(m.TN[tidx]);
4811 if (tidx < lqn.think.size() && !lqn.think[tidx].disabled) {
4812 z = dbl(lqn.think[tidx].mean);
4813 if (!std::isfinite(z) || z < 0.0)
z = 0.0;
4815 double mult = tidx < lqn.mult.size() ? lqn.mult[tidx] : 1.0;
4816 if (mult == 0.0)
mult = 1.0;
4817 seed_think_time(tidx, X, dbl(m.QN[tidx]), z,
4818 lqn.sched[tidx] == SchedStrategy::INF || !std::isfinite(mult),
4819 std::max(1.0, mult));
4825 "SolverLN: config.warmstart='mol' needs transcendental arithmetic; rerun with --arith double");
4830 bool is_srvn_ph()
const {
return lnmethod ==
"srvn.ph"; }
4838 bool is_ph_encoding()
const {
return lnmethod ==
"srvn.ph" || lnmethod ==
"flat.ph"; }
4841 bool is_flat_layering()
const {
return lnmethod ==
"flat.cs" || lnmethod ==
"flat.ph"; }
4849 static std::size_t station_idx_of(
const qn::Layer<T>& L, std::size_t elem) {
4850 if (elem >= 1 && elem < L.server_idx_of.size() && L.server_idx_of[elem] != 0)
4851 return L.server_idx_of[
elem];
4859 std::size_t station_idx_of_class(
const qn::Layer<T>& L, std::size_t k)
const {
4860 const int kind = L.classes[k].attr_kind;
4861 const std::size_t a = L.classes[k].attr_idx;
4862 if (kind ==
int(LqnElement::ACTIVITY))
4863 return station_idx_of(L, lqn.parent[lqn.parent[a]]);
4864 if (kind ==
int(LqnElement::CALL))
4865 return station_idx_of(L, lqn.parent[lqn.callpair_dst[a]]);
4877 bool probe_srvn_ph() {
4879 ph_assert_supported();
4881 ph_laws_ready =
true;
4883 }
catch (
const std::exception&) {
4884 ph_laws_ready =
false;
4891 std::size_t idx = 0;
4892 bool ishost =
false;
4893 std::vector<std::size_t> callers;
4895 std::vector<std::size_t> class_of_caller;
4896 std::size_t nreplicas = 1;
4898 std::vector<std::size_t> qstations;
4900 std::vector<T> svcmean_by_class;
4902 std::vector<std::pair<std::size_t, long>> open_arrivals;
4912 std::vector<workflow::Workflow<T>> ph_wf, ph_wfhost;
4913 std::vector<std::unordered_map<std::size_t, T>> ph_execs;
4914 std::vector<bool> ph_has_wf;
4915 std::vector<workflow::PhLaw<T>> ph_hostlaw, ph_entrylaw;
4916 std::vector<T> ph_hostmean, ph_entrymean, ph_entryscv;
4917 std::vector<T> ph_share, ph_overlap, ph_setupshare, ph_xdemand;
4918 Matrix<T> ph_ncalls, ph_calltime;
4919 std::vector<T> ph_procresid, ph_actthinkt, ph_calltotal;
4920 std::vector<T> ph_procsave;
4921 Matrix<T> ph_callsave;
4922 std::vector<PHLayer> ph_layers;
4923 std::vector<bool> ph_has_layer;
4926 T act_think_time(std::size_t aidx)
const {
4927 if (aidx >= lqn.actthink.size() || lqn.actthink[aidx].disabled)
return Tzero();
4928 const double m = dbl(lqn.actthink[aidx].mean);
4930 return lqn.actthink[aidx].mean;
4934 std::unordered_map<std::size_t, double> setupcharge;
4970 double setup_charge(std::size_t tidx,
double S = std::numeric_limits<double>::quiet_NaN()) {
4971 if (tidx >= lqn.hassetup.size() || !lqn.hassetup[tidx])
return 0.0;
4972 const double s = tidx < lqn.setuptime.size() && !lqn.setuptime[tidx].disabled
4973 ? dbl(lqn.setuptime[tidx].mean) : 0.0;
4974 const double d = tidx < lqn.delayofftime.size() && !lqn.delayofftime[tidx].disabled
4975 ? dbl(lqn.delayofftime[tidx].mean) : 0.0;
4977 const double mult = lqn.mult[tidx];
4978 if (!std::isfinite(mult) || mult <= 0.0)
return 0.0;
4979 if (std::isnan(S)) {
4980 const auto it = setupcharge.find(tidx);
4981 return it == setupcharge.end() ? s : it->second;
4983 const double c = setup_charge_exact(tidx,
static_cast<int>(std::llround(mult)), S, s, d);
4984 setupcharge[tidx] = c;
4989 double setup_charge_exact(std::size_t tidx,
int k,
double S,
double s,
double d)
const {
4992 || results.empty() || std::size_t(idxhash[tidx]) >= results.back().size())
4994 const std::size_t e = std::size_t(idxhash[tidx]);
4995 const qn::Layer<T>& L = ensemble[e];
4996 const LayerResult<T>& r = results.back()[e];
4997 if (r.TN.rows() == 0 || r.QN.rows() == 0)
return s;
4998 const std::size_t ts = station_idx_of(L, tidx) - 1;
5000 double X = 0.0, Q = 0.0;
5001 for (std::size_t c = 0; c < L.nclasses && c < r.TN.cols(); ++c) {
5002 const double tn = dbl(r.TN(ts, c)), qn = dbl(r.QN(ts, c));
5003 if (!std::isnan(tn)) X += tn;
5004 if (!std::isnan(qn)) Q += qn;
5011 bool isopen =
false;
5012 for (std::size_t ch = 0; ch < L.inchain.size(); ++ch) {
5013 bool visits =
false;
5015 for (std::size_t c1 : L.inchain[ch]) {
5016 if (c1 < 1 || c1 > L.nclasses || c1 > r.TN.cols())
continue;
5017 if (dbl(r.TN(ts, c1 - 1)) > 0.0) visits =
true;
5018 pop += L.classes[c1 - 1].population;
5020 if (!visits)
continue;
5021 if (std::isfinite(pop)) N += pop;
5024 const double mu = 1.0 / S;
5025 auto scv_of = [](
const std::vector<Distrib<T>>& procs, std::size_t i) {
5026 if (i >= procs.size() || procs[i].disabled)
return 1.0;
5027 const double v = dbl(procs[i].scv);
5028 return (std::isfinite(v) && v > 0.0) ? v : 1.0;
5030 const double ascv = scv_of(lqn.setuptime, tidx);
5031 const double bscv = scv_of(lqn.delayofftime, tidx);
5034 if (isopen || N <= 0.0) {
5035 if (X >= k * mu)
return 0.0;
5037 k, std::numeric_limits<double>::infinity(), X, mu, 1.0 / s, ascv, 1.0 / d, bscv);
5039 return mmk_equiv_service([&](
double Sp) {
return mmk_open_resp(k, X, 1.0 / Sp); }, S,
5040 res.QN / res.XN, k / X) - S;
5042 const int pop =
static_cast<int>(std::llround(N));
5044 const mam::SetupDelayoffMMk<double> res =
5047 return mmk_equiv_service([&](
double Sp) {
return mmk_closed_resp(k, pop, Z, 1.0 / Sp); }, S,
5048 res.QN / res.XN, res.QN / res.XN) - S;
5056 static double mmk_equiv_service(
const F& resp,
double S,
double Rs,
double hi) {
5058 if (resp(lo) >= Rs)
return S;
5059 for (
int it = 0; it < 200; ++it) {
5060 const double mid = 0.5 * (lo + hi);
5061 if (resp(mid) < Rs) lo = mid;
5063 if (hi - lo <= 1e-12 * hi)
break;
5065 return 0.5 * (lo + hi);
5072 static double mmk_closed_resp(
int k,
int N,
double Z,
double mu) {
5073 std::vector<double> p(std::size_t(N) + 1, 0.0);
5075 for (
int n = 1; n <= N; ++n) {
5076 p[n] = p[n - 1] * ((N - n + 1) / Z) / (std::min(n, k) * mu);
5078 for (
int i = 0; i <= n; ++i) p[i] /= p[n];
5080 double tot = 0.0, Qs = 0.0, Xs = 0.0;
5081 for (
int n = 0; n <= N; ++n) tot += p[n];
5082 for (
int n = 0; n <= N; ++n) {
5083 Qs += n * p[n] /
tot;
5084 Xs += (N - n) / Z * p[n] / tot;
5090 static double mmk_open_resp(
int k,
double lam,
double mu) {
5091 const double a = lam / mu, rho = a / k;
5092 double term = 1.0, acc = 1.0;
5093 for (
int i = 1; i < k; ++i) {
5097 const double tk = term * a / k;
5098 const double C = tk / (1.0 - rho) / (acc + tk / (1.0 - rho));
5099 return 1.0 / mu + C / (k * mu - lam);
5108 double ph_setup_prob(std::size_t eidx,
double m1) {
5109 const std::size_t tidx = lqn.parent[eidx];
5110 if (tidx >= lqn.hassetup.size() || !lqn.hassetup[tidx])
return 0.0;
5111 const double s = tidx < lqn.setuptime.size() && !lqn.setuptime[tidx].disabled
5112 ? dbl(lqn.setuptime[tidx].mean) : 0.0;
5113 const double d = tidx < lqn.delayofftime.size() && !lqn.delayofftime[tidx].disabled
5114 ? dbl(lqn.delayofftime[tidx].mean) : 0.0;
5116 return std::min(1.0, std::max(0.0, setup_charge(tidx, m1) / s));
5120 double ph_host_servers(std::size_t hidx)
const {
5121 if (lqn.sched[hidx] == SchedStrategy::INF)
return 1.0;
5122 const double m = lqn.maxmult[hidx];
5123 return (std::isfinite(m) && m > 0.0) ? m : 1.0;
5127 bool ph_any_caller_of(std::size_t eidx)
const {
5128 return lqn.issynccaller.any_col(eidx) || lqn.isasynccaller.any_col(eidx);
5136 bool ph_open_arrival_only(std::size_t tidx)
const {
5137 if (lqn.isref[tidx])
return false;
5138 for (std::size_t eidx : lqn.entriesof[tidx])
5139 if (ph_any_caller_of(eidx))
return false;
5140 for (std::size_t eidx : lqn.entriesof[tidx])
5141 if (lqn.has_arrival[eidx])
return true;
5146 std::vector<std::size_t> ph_async_calls_into(std::size_t tidx)
const {
5147 std::vector<std::size_t> out;
5148 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
5149 if (lqn.calltype[cidx] != CallType::ASYNC)
continue;
5150 for (std::size_t e : lqn.entriesof[tidx])
5151 if (lqn.callpair_dst[cidx] == e) { out.push_back(cidx);
break; }
5161 bool ph_has_task_layer(std::size_t tidx)
const {
5162 if (ignore[tidx] || lqn.isref[tidx])
return false;
5163 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
5164 const std::size_t c = lqn.tshift + ct;
5165 if (c == tidx || ignore[c])
continue;
5166 for (std::size_t e : lqn.entriesof[tidx])
5167 if (lqn.issynccaller.get(c, e))
return true;
5169 return !ph_async_calls_into(tidx).empty();
5176 void ph_assert_supported(
bool flat =
false)
const {
5179 const std::string mname = flat ?
"flat.ph" :
"srvn.ph";
5185 "method='" + mname +
"' does not support second-phase activities: the composed "
5186 "entry law has no reply point. Use method='default'.");
5192 const std::string why = ph_method_refusal(mname);
5211 std::string ph_method_refusal(
const std::string& method)
const {
5212 if (method !=
"srvn.ph" && method !=
"flat.ph")
return std::string();
5215 if (method ==
"flat.ph") {
5216 for (std::size_t i = 1; i <= NT(); ++i) {
5217 if (lqn.repl[i] > 1.0)
5218 return "method='flat.ph' does not support replicated processors or tasks, "
5219 "whose replicas need a submodel each. Use method='srvn.ph'.";
5220 if (lqn.hassetup[i])
5221 return "method='flat.ph' does not support setup tasks, whose powered-down "
5222 "threads are per-layer state. Use method='srvn.ph'.";
5225 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx)
5226 if (lqn.calltype[cidx] == CallType::FWD)
5227 return "method='" + method +
5228 "' does not support forwarding calls, whose target is not part of the "
5229 "caller's activity graph. Use method='default'.";
5230 for (std::size_t i = 1; i < lqn.iscache.size(); ++i)
5232 return "method='" + method +
5233 "' does not support cache tasks. Use method='default'.";
5234 for (std::size_t i = 1; i < lqn.hassetup.size(); ++i) {
5235 if (!lqn.hassetup[i])
continue;
5236 if (lqn.sched[i] == SchedStrategy::INF || !std::isfinite(lqn.mult[i]))
5237 return "method='" + method +
"': task '" + lqn.names[i] +
5238 "' declares a setup time on an infinite-server task, which holds no "
5239 "thread to power down; give it a finite multiplicity.";
5241 for (std::size_t i = 0; i < lqn.lincon_A.size(); ++i)
5242 if (lqn.lincon_A[i].rows() > 0)
5243 return "method='" + method +
5244 "' does not support admission constraints on a layer station. "
5245 "Use method='default'.";
5246 for (std::size_t i = 1; i < lqn.lldscaling.size(); ++i) {
5247 const char* fname =
nullptr;
5248 if (!lqn.lldscaling[i].empty()) fname =
"a load dependence";
5249 else if (lqn.cdscaling[i]) fname =
"a class dependence";
5250 else if (lqn.jdscaling[i]) fname =
"a joint dependence";
5251 else if (!lqn.pools[i].empty()) fname =
"server pools";
5252 if (fname !=
nullptr)
5253 return "method='" + method +
5254 "' does not support queue-dependent service rates on a layer station ('" +
5255 lqn.names[i] +
"' declares " + fname +
"). Use method='srvn.cs'.";
5257 return std::string();
5261 void ph_init_laws() {
5262 const std::size_t N = lqn.nidx;
5263 ph_wf.assign(N + 1, workflow::Workflow<T>(
"empty"));
5264 ph_wfhost.assign(N + 1, workflow::Workflow<T>(
"empty"));
5265 ph_execs.assign(N + 1, {});
5266 ph_has_wf.assign(N + 1,
false);
5267 ph_hostlaw.assign(N + 1, workflow::PhLaw<T>());
5268 ph_entrylaw.assign(N + 1, workflow::PhLaw<T>());
5269 ph_hostmean.assign(N + 1, Tzero());
5270 ph_entrymean.assign(N + 1, Tzero());
5271 ph_entryscv.assign(N + 1, Tone());
5272 ph_share.assign(N + 1, Tzero());
5273 ph_overlap.assign(N + 1, Tone());
5274 ph_setupshare.assign(N + 1, Tzero());
5275 ph_xdemand.assign(N + 1, Tzero());
5276 ph_ncalls =
Matrix<T>(N + 1, N + 1, Tzero());
5277 ph_calltime =
Matrix<T>(N + 1, N + 1, Tzero());
5278 ph_procresid.assign(N + 1, Tzero());
5279 ph_actthinkt.assign(N + 1, Tzero());
5280 ph_calltotal.assign(N + 1, Tzero());
5281 ph_procsave.assign(N + 1, Tzero());
5282 ph_callsave =
Matrix<T>(N + 1, N + 1, Tzero());
5283 ph_layers.assign(NT() + 1, PHLayer());
5284 ph_has_layer.assign(NT() + 1,
false);
5286 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
5287 const std::size_t eidx = lqn.eshift + e;
5288 const std::size_t tidx = lqn.parent[eidx];
5289 if (ignore[tidx])
continue;
5291 ph_wf[eidx] = std::move(ew.wf);
5292 ph_execs[eidx] = ew.execs;
5293 ph_has_wf[eidx] =
true;
5295 ph_wfhost[eidx] = std::move(eh.wf);
5305 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5306 const std::size_t tidx = lqn.tshift + t;
5307 const std::size_t n = lqn.entriesof[tidx].size();
5308 if (n == 0)
continue;
5309 for (std::size_t eidx : lqn.entriesof[tidx])
5310 ph_share[eidx] = num_traits<T>::from_double(1.0 /
double(n));
5321 Distrib<T> ph_call_burst_law(std::size_t cidx)
const {
5322 const double m = dbl(lqn.callproc_mean[cidx]);
5323 const std::size_t eidx = lqn.callpair_dst[cidx];
5325 const T R = T(callservt[cidx] / lqn.callproc_mean[cidx]);
5326 double scvd = dbl(ph_entryscv[eidx]);
5332 const workflow::PhLaw<T> loop =
5346 Distrib<T> ph_station_law(
const workflow::PhLaw<T>& law)
const {
5354 static workflow::PhLaw<T> ph_immediate_law() {
5355 workflow::PhLaw<T> out;
5356 out.alpha.assign(1, Tone());
5362 bool ph_has_and_fork(std::size_t eidx)
const {
5363 for (std::size_t aidx : lqn.actsof[eidx])
5364 if (aidx < lqn.actposttype.size() && lqn.actposttype[aidx] == PrecedenceType::POST_AND)
return true;
5373 bool ph_single_server_host(std::size_t eidx)
const {
5374 const std::size_t hidx = lqn.parent[lqn.parent[eidx]];
5375 if (lqn.sched[hidx] == SchedStrategy::INF)
return false;
5376 const double m = lqn.mult[hidx];
5377 return std::isfinite(m) && m <= 1.0;
5385 double ph_entry_host_servers(std::size_t eidx)
const {
5386 const std::size_t hidx = lqn.parent[lqn.parent[eidx]];
5387 if (lqn.sched[hidx] == SchedStrategy::INF)
return std::numeric_limits<double>::infinity();
5388 const double m = lqn.mult[hidx];
5389 if (!std::isfinite(m))
return std::numeric_limits<double>::infinity();
5390 return std::max(m, 1.0);
5402 void ph_compose_entry_laws() {
5403 const std::size_t N = lqn.nidx;
5404 std::vector<T> entry_setup_share(N + 1, Tzero());
5405 ph_overlap.assign(N + 1, Tone());
5406 std::vector<bool> hostserial(N + 1,
false);
5408 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
5409 const std::size_t eidx = lqn.eshift + e;
5410 if (!ph_has_wf[eidx])
continue;
5411 workflow::Workflow<T>& w = ph_wf[eidx];
5412 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
5413 T entrysum = Tzero(), procsum = Tzero(), pres = Tzero();
5414 for (std::size_t aidx : lqn.actsof[eidx]) {
5415 T m = T(residt[aidx] + act_think_time(aidx));
5416 const T xa = ex.at(aidx);
5417 procsum += T(xa * m);
5418 pres += T(xa * residt[aidx]);
5419 const double md = dbl(m);
5420 w.set_activity_demand_mean(
5424 for (std::size_t cidx : lqn.callsof[aidx]) {
5425 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
5426 w.set_activity_demand(lqn.callhashnames[cidx], ph_call_burst_law(cidx));
5427 m = T(m + callservt[cidx]);
5429 entrysum += T(xa * m);
5433 T m1 = mm.first, scv = mm.second;
5444 const double hservers = ph_entry_host_servers(eidx);
5445 if (std::isfinite(hservers)) {
5446 const T procfloor = T(procsum / num_traits<T>::from_double(hservers));
5448 const T f = T(m1 / procfloor);
5449 for (std::size_t i = 0; i < law.S.rows(); ++i)
5450 for (std::size_t j = 0; j < law.S.cols(); ++j) law.S(i, j) = T(law.S(i, j) * f);
5458 if (ph_has_and_fork(eidx) && ph_single_server_host(eidx)) {
5459 hostserial[eidx] =
true;
5461 const T add = T((Tone() - num_traits<T>::from_double(
5462 std::min(1.0, dbl(m1) / dbl(entrysum)))) * pres);
5464 const T f = T(m1 / (m1 + add));
5465 for (std::size_t i = 0; i < law.S.rows(); ++i)
5466 for (std::size_t j = 0; j < law.S.cols(); ++j) law.S(i, j) = T(law.S(i, j) * f);
5477 const double p = ph_setup_prob(eidx, dbl(m1));
5479 const std::size_t tidx = lqn.parent[eidx];
5480 const double sm = dbl(lqn.setuptime[tidx].mean);
5481 double sscv = dbl(lqn.setuptime[tidx].scv);
5485 num_traits<T>::from_double(sm), num_traits<T>::from_double(sscv)));
5486 std::vector<workflow::PhLaw<T>> mix;
5489 std::vector<T> probs;
5490 probs.push_back(num_traits<T>::from_double(p));
5491 probs.push_back(num_traits<T>::from_double(1.0 - p));
5501 entry_setup_share[eidx] = num_traits<T>::from_double(p * sm / denom);
5504 ph_entrylaw[eidx] = law;
5505 ph_entrymean[eidx] = m1;
5506 ph_entryscv[eidx] = scv;
5507 if (hostserial[eidx]) {
5509 const double rest = dbl(entrysum) - dbl(pres);
5511 const double r = std::min(1.0, std::max(0.0, (dbl(m1) - dbl(pres)) / rest));
5512 ph_overlap[eidx] = num_traits<T>::from_double(r);
5515 const double r = std::min(1.0, dbl(m1) / dbl(entrysum));
5516 ph_overlap[eidx] = num_traits<T>::from_double(r);
5522 ph_setupshare.assign(N + 1, Tzero());
5523 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5524 const std::size_t tidx = lqn.tshift + t;
5525 if (ignore[tidx])
continue;
5526 for (std::size_t eidx : lqn.entriesof[tidx])
5527 ph_setupshare[tidx] = T(ph_setupshare[tidx] + ph_share[eidx] * entry_setup_share[eidx]);
5531 ph_ncalls =
Matrix<T>(N + 1, N + 1, Tzero());
5532 ph_calltime =
Matrix<T>(N + 1, N + 1, Tzero());
5533 ph_procresid.assign(N + 1, Tzero());
5534 ph_actthinkt.assign(N + 1, Tzero());
5535 ph_calltotal.assign(N + 1, Tzero());
5541 ph_procsave.assign(N + 1, Tzero());
5542 ph_callsave =
Matrix<T>(N + 1, N + 1, Tzero());
5543 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5544 const std::size_t tidx = lqn.tshift + t;
5545 if (ignore[tidx])
continue;
5546 for (std::size_t eidx : lqn.entriesof[tidx]) {
5547 if (!ph_has_wf[eidx])
continue;
5548 const T w = ph_share[eidx];
5549 if (!(dbl(w) > 0.0))
continue;
5550 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
5551 const T r = ph_overlap[eidx];
5552 const T sv = ph_has_and_fork(eidx) ? T(Tone() - r) : Tzero();
5554 const T rp = hostserial[eidx] ? Tone() : r;
5555 const T svp = hostserial[eidx] ? Tzero() : sv;
5556 for (std::size_t aidx : lqn.actsof[eidx]) {
5557 const T xa = ex.at(aidx);
5558 ph_procresid[tidx] = T(ph_procresid[tidx] + w * rp * xa * residt[aidx]);
5559 ph_procsave[tidx] = T(ph_procsave[tidx] + w * svp * xa * residt[aidx]);
5560 ph_actthinkt[tidx] = T(ph_actthinkt[tidx] + w * r * xa * act_think_time(aidx));
5561 for (std::size_t cidx : lqn.callsof[aidx]) {
5562 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
5563 const std::size_t tgte = lqn.callpair_dst[cidx];
5564 const std::size_t tgtt = lqn.parent[tgte];
5567 ph_ncalls(tidx, tgte) =
5568 T(ph_ncalls(tidx, tgte) + w * xa * lqn.callproc_mean[cidx]);
5569 ph_calltime(tidx, tgtt) =
5570 T(ph_calltime(tidx, tgtt) + w * r * xa * callservt[cidx]);
5571 ph_calltotal[tidx] = T(ph_calltotal[tidx] + w * r * xa * callservt[cidx]);
5572 ph_callsave(tidx, tgtt) =
5573 T(ph_callsave(tidx, tgtt) + w * sv * xa * callservt[cidx]);
5581 void build_layers_ph(
bool flat =
false) {
5582 if (!ph_laws_ready) ph_assert_supported(flat);
5586 opt.interlocking =
false;
5587 interlockMethod =
"none";
5591 if (!ph_laws_ready) ph_init_laws();
5594 const std::size_t N = lqn.nidx;
5595 residt.assign(N + 1, Tzero());
5596 servt.assign(N + 1, Tzero());
5597 callservt.assign(lqn.ncalls + 1, Tzero());
5598 callresidt.assign(lqn.ncalls + 1, Tzero());
5599 for (std::size_t aidx = lqn.ashift + 1; aidx <= lqn.ashift + lqn.nacts; ++aidx)
5600 residt[aidx] = lqn.hostdem[aidx].disabled ? Tzero() : lqn.hostdem[aidx].mean;
5601 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
5602 if (lqn.calltype[cidx] != CallType::SYNC && lqn.calltype[cidx] != CallType::ASYNC)
5604 const std::size_t eidx = lqn.callpair_dst[cidx];
5605 callservt[cidx] = T(lqn.callproc_mean[cidx] * ph_hostmean[eidx]);
5606 callresidt[cidx] = callservt[cidx];
5608 ph_compose_entry_laws();
5612 build_ph_flat_layer();
5613 tput.assign(N + 1, Tzero());
5614 util.assign(N + 1, Tzero());
5615 thinkt.assign(N + 1, Tzero());
5616 update_layers_ph(0);
5617 for (qn::Layer<T>& e : ensemble) e.refresh_chains();
5621 std::vector<qn::Layer<T>> raw(NT() + 1);
5622 std::vector<bool> present(NT() + 1,
false);
5624 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
5625 if (ignore[hidx])
continue;
5626 std::vector<std::size_t> callers;
5627 for (std::size_t tidx : lqn.tasksof[hidx]) {
5628 if (ignore[tidx])
continue;
5629 if (lqn.isref[tidx]) { callers.push_back(tidx);
continue; }
5630 for (std::size_t eidx : lqn.entriesof[tidx])
5631 if (ph_any_caller_of(eidx) || lqn.has_arrival[eidx]) {
5632 callers.push_back(tidx);
5636 if (callers.empty())
continue;
5637 build_layer_ph(raw[hidx], hidx, callers,
true);
5638 present[hidx] =
true;
5640 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5641 const std::size_t tidx = lqn.tshift + t;
5642 if (ignore[tidx] || lqn.isref[tidx])
continue;
5643 std::vector<std::size_t> callers;
5644 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
5645 const std::size_t c = lqn.tshift + ct;
5646 if (c == tidx || ignore[c])
continue;
5647 for (std::size_t e : lqn.entriesof[tidx])
5648 if (lqn.issynccaller.get(c, e)) { callers.push_back(c);
break; }
5650 if (callers.empty() && ph_async_calls_into(tidx).empty())
continue;
5651 build_layer_ph(raw[tidx], tidx, callers,
false);
5652 present[tidx] =
true;
5655 idxhash.assign(lqn.nidx + 1, -1);
5657 for (std::size_t i = 1; i <= NT(); ++i)
5659 idxhash[i] = next++;
5660 ensemble.push_back(std::move(raw[i]));
5662 layer_init_sol.assign(ensemble.size(), Matrix<T>());
5667 tput.assign(N + 1, Tzero());
5668 util.assign(N + 1, Tzero());
5669 thinkt.assign(N + 1, Tzero());
5670 update_layers_ph(0);
5674 for (qn::Layer<T>& e : ensemble) e.refresh_chains();
5690 void build_ph_flat_layer() {
5691 const std::vector<std::size_t> servers = ph_flat_server_set();
5692 const std::size_t nsrv = servers.size();
5696 m.clientIdx = m.add_station(qn::Station<T>{
5697 "Clients", NodeType::Delay, SchedStrategy::INF,
5698 std::numeric_limits<double>::infinity(),
false, 0});
5699 const std::size_t clientNode = m.node_of_station(m.clientIdx);
5700 m.server_idx_of.assign(lqn.nidx + 1, 0);
5702 std::vector<std::size_t> station_of(lqn.nidx + 1, 0);
5703 std::vector<std::size_t> serverNode(nsrv, 0);
5704 std::vector<std::size_t> srvStation(nsrv, 0);
5705 for (std::size_t si = 0; si < nsrv; ++si) {
5706 const std::size_t idx = servers[si];
5707 const bool ishost = idx <= lqn.nhosts;
5709 st.name = lqn.hashnames[idx];
5710 st.nodetype = lqn.sched[idx] == SchedStrategy::INF ? NodeType::Delay : NodeType::Queue;
5711 st.sched = lqn.sched[idx];
5712 st.nservers = lqn.sched[idx] == SchedStrategy::INF
5713 ? std::numeric_limits<double>::infinity()
5715 st.attr_ishost = ishost;
5717 const std::size_t s = m.add_station(st);
5719 station_of[idx] = s;
5720 serverNode[si] = m.node_of_station(s);
5721 m.server_idx_of[idx] = s;
5723 m.host_stations.push_back(s);
5725 m.task_stations.push_back(s);
5728 m.serverIdx = station_of[servers[0]];
5732 std::vector<std::vector<std::size_t>> callers_of(lqn.nidx + 1);
5733 std::vector<std::size_t> all_callers;
5734 for (std::size_t si = 0; si < nsrv; ++si) {
5735 const std::size_t idx = servers[si];
5736 std::vector<std::size_t> cs;
5737 if (idx <= lqn.nhosts) {
5738 for (std::size_t tidx : lqn.tasksof[idx]) {
5739 if (ignore[tidx])
continue;
5740 if (lqn.isref[tidx]) { cs.push_back(tidx);
continue; }
5741 for (std::size_t eidx : lqn.entriesof[tidx])
5742 if (ph_any_caller_of(eidx) || lqn.has_arrival[eidx]) {
5748 for (std::size_t ct = 1; ct <= lqn.ntasks; ++ct) {
5749 const std::size_t c = lqn.tshift + ct;
5750 if (c == idx || ignore[c])
continue;
5751 for (std::size_t e : lqn.entriesof[idx])
5752 if (lqn.issynccaller.get(c, e)) { cs.push_back(c);
break; }
5755 callers_of[idx] = cs;
5756 for (std::size_t c : cs)
5757 if (std::find(all_callers.begin(), all_callers.end(), c) == all_callers.end())
5758 all_callers.push_back(c);
5760 std::sort(all_callers.begin(), all_callers.end());
5763 std::vector<std::size_t> class_of_caller(lqn.nidx + 1, 0);
5765 for (std::size_t c : all_callers) {
5768 double nj = lqn.maxmult[c];
5769 if (std::isinf(nj)) {
5771 for (std::size_t k = 1; k <= NT(); ++k)
5772 if (lqn.taskgraph.get(k, c) != Tzero()) sacc += lqn.maxmult[k];
5774 if (std::isinf(nj) || nj == 0.0) {
5776 for (std::size_t k = 1; k <= NT(); ++k)
5777 if (std::isfinite(lqn.maxmult[k])) s2 += lqn.maxmult[k];
5778 nj = std::min(s2, 1000.0);
5782 jc.name = lqn.hashnames[c];
5783 jc.type = JobClassType::CLOSED;
5785 jc.refstat = m.clientIdx;
5786 jc.is_ref_class =
true;
5787 jc.attr_kind = int(LqnElement::TASK);
5789 const std::size_t k = m.add_class(jc);
5790 class_of_caller[c] = k;
5791 m.attr_tasks.emplace_back(k, c);
5793 const double zt = dbl(ref_think_time(c));
5794 m.set_service(m.clientIdx, k,
5803 for (std::size_t si = 0; si < nsrv; ++si)
5805 for (std::size_t si = 0; si < nsrv; ++si) {
5806 const std::size_t idx = servers[si];
5807 const std::vector<std::size_t>& cs = callers_of[idx];
5808 if (std::find(cs.begin(), cs.end(), c) == cs.end())
continue;
5809 m.set_service(srvStation[si], k,
5813 thinkt_map.push_back({idx, c, m.clientIdx, k});
5814 servt_map.push_back({idx, c, station_of[idx], k});
5819 std::vector<std::vector<std::pair<std::size_t, long>>> open_of(lqn.nidx + 1);
5820 std::size_t sourceStation = 0, sinkNode = 0;
5821 for (std::size_t si = 0; si < nsrv; ++si) {
5822 const std::size_t hidx = servers[si];
5823 if (hidx > lqn.nhosts)
continue;
5824 for (std::size_t c : callers_of[hidx]) {
5830 if (ph_open_arrival_only(c))
continue;
5831 for (std::size_t eidx : lqn.entriesof[c]) {
5832 if (!lqn.has_arrival[eidx])
continue;
5833 if (sourceStation == 0) {
5834 sourceStation = m.add_station(qn::Station<T>{
5835 "Source", NodeType::Source, SchedStrategy::EXT,
5836 std::numeric_limits<double>::infinity(),
false, 0});
5837 m.sourceIdx = sourceStation;
5838 sinkNode = m.add_node(
"Sink", NodeType::Sink,
false);
5839 m.sinkNode = sinkNode;
5842 oc.name = lqn.hashnames[eidx] +
".Open";
5843 oc.type = JobClassType::OPEN;
5844 oc.population = std::numeric_limits<double>::infinity();
5845 oc.refstat = sourceStation;
5846 oc.attr_kind = int(LqnElement::ENTRY);
5848 const std::size_t k = m.add_class(oc);
5849 m.set_service(sourceStation, k, lqn.arrival[eidx]);
5851 for (std::size_t s2 = 0; s2 < nsrv; ++s2)
5854 m.set_service(srvStation[si], k,
5856 open_of[hidx].emplace_back(k,
long(eidx));
5857 m.attr_entries.emplace_back(k, eidx);
5861 for (std::size_t si = 0; si < nsrv; ++si) {
5862 const std::size_t tidx = servers[si];
5863 if (tidx <= lqn.nhosts)
continue;
5864 for (std::size_t cidx : ph_async_calls_into(tidx)) {
5865 if (sourceStation == 0) {
5866 sourceStation = m.add_station(qn::Station<T>{
5867 "Source", NodeType::Source, SchedStrategy::EXT,
5868 std::numeric_limits<double>::infinity(),
false, 0});
5869 m.sourceIdx = sourceStation;
5870 sinkNode = m.add_node(
"Sink", NodeType::Sink,
false);
5871 m.sinkNode = sinkNode;
5873 const std::size_t eidx = lqn.callpair_dst[cidx];
5875 oc.name = lqn.callhashnames[cidx];
5876 oc.type = JobClassType::OPEN;
5877 oc.population = std::numeric_limits<double>::infinity();
5878 oc.refstat = sourceStation;
5879 oc.attr_kind = int(LqnElement::CALL);
5881 const std::size_t k = m.add_class(oc);
5884 for (std::size_t s2 = 0; s2 < nsrv; ++s2)
5887 m.set_service(srvStation[si], k,
5889 open_of[tidx].emplace_back(k, -
long(cidx));
5890 m.attr_calls.push_back({k, cidx, lqn.callpair_src[cidx], eidx});
5891 arv_call_map.push_back({tidx, cidx, sourceStation, k});
5892 call_map.push_back({tidx, cidx, station_of[tidx], k});
5899 for (std::size_t c : all_callers) {
5900 const std::size_t k = class_of_caller[c];
5901 std::size_t prev = clientNode;
5902 bool visited =
false;
5903 for (std::size_t si = 0; si < nsrv; ++si) {
5904 const std::vector<std::size_t>& cs = callers_of[servers[si]];
5905 if (std::find(cs.begin(), cs.end(), c) == cs.end())
continue;
5906 m.set_route(k, k, prev, serverNode[si], Tone());
5907 prev = serverNode[si];
5910 if (visited) m.set_route(k, k, prev, clientNode, Tone());
5912 if (sourceStation != 0) {
5913 const std::size_t srcNode = m.node_of_station(sourceStation);
5914 for (std::size_t si = 0; si < nsrv; ++si)
5915 for (
const auto& oa : open_of[servers[si]]) {
5916 m.set_route(oa.first, oa.first, srcNode, serverNode[si], Tone());
5917 m.set_route(oa.first, oa.first, serverNode[si], sinkNode, Tone());
5920 apply_host_task_priorities(m, servers);
5923 idxhash.assign(lqn.nidx + 1, -1);
5924 for (std::size_t idx : servers) idxhash[idx] = 0;
5926 ensemble.push_back(std::move(m));
5927 layer_init_sol.assign(ensemble.size(), Matrix<T>());
5930 const std::size_t nclasses = ensemble[0].classes.size();
5931 for (std::size_t idx : servers) {
5934 L.ishost = idx <= lqn.nhosts;
5935 L.callers = callers_of[idx];
5936 L.class_of_caller = class_of_caller;
5938 L.qstations.assign(1, station_of[idx]);
5939 L.svcmean_by_class.assign(nclasses + 1, Tzero());
5940 L.open_arrivals = open_of[idx];
5941 L.npop = npop < 1.0 ? 1.0 : npop;
5943 ph_has_layer[idx] =
true;
5956 std::vector<std::size_t> ph_flat_server_set()
const {
5957 for (std::size_t i = 1; i <= NT(); ++i) {
5958 if (lqn.repl[i] > 1.0)
5960 "method='flat.ph' does not support replicated processors or tasks, whose "
5961 "replicas need a submodel each. Use method='srvn.ph'.");
5964 "method='flat.ph' does not support cache tasks. Use method='default'.");
5965 if (lqn.hassetup[i])
5967 "method='flat.ph' does not support setup tasks, whose powered-down threads "
5968 "are per-layer state. Use method='srvn.ph'.");
5970 std::vector<std::size_t> servers;
5971 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
5972 if (ignore[hidx] || lqn.tasksof[hidx].empty())
continue;
5974 for (std::size_t tidx : lqn.tasksof[hidx]) {
5975 if (ignore[tidx])
continue;
5976 if (lqn.isref[tidx]) { any =
true;
break; }
5977 for (std::size_t eidx : lqn.entriesof[tidx])
5978 if (ph_any_caller_of(eidx) || lqn.has_arrival[eidx]) { any =
true;
break; }
5981 if (any) servers.push_back(hidx);
5983 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
5984 const std::size_t tidx = lqn.tshift + t;
5985 if (ignore[tidx] || lqn.isref[tidx])
continue;
5986 bool has_caller =
false;
5987 for (std::size_t ct = 1; ct <= lqn.ntasks && !has_caller; ++ct) {
5988 const std::size_t c = lqn.tshift + ct;
5989 if (c == tidx || ignore[c])
continue;
5990 for (std::size_t e : lqn.entriesof[tidx])
5991 if (lqn.issynccaller.get(c, e)) { has_caller =
true;
break; }
5993 if (!has_caller && ph_async_calls_into(tidx).empty())
continue;
5994 servers.push_back(tidx);
5996 if (servers.empty())
5998 "method='flat.ph' found no server: the model has no processor with tasks.");
6003 void build_layer_ph(qn::Layer<T>& m, std::size_t idx,
6004 const std::vector<std::size_t>& callers,
bool ishost) {
6005 m.name = lqn.hashnames[idx];
6010 const double rawrepl = lqn.repl[idx];
6011 std::size_t nreplicas = 1;
6012 if (rawrepl > 1.0 && !callers.empty()) {
6015 for (std::size_t c : callers)
6016 if (lqn.repl[c] != rawrepl) reduce =
false;
6018 for (std::size_t c : callers)
6019 if (lqn.fanout_at(c, idx) < rawrepl) reduce =
false;
6021 nreplicas = reduce ? 1 :
static_cast<std::size_t
>(std::llround(rawrepl));
6022 if (reduce && !ishost) single_replica_tasks.insert(idx);
6024 const bool reduce_fanout = (nreplicas == 1 && rawrepl > 1.0 && !callers.empty());
6026 m.clientIdx = m.add_station(qn::Station<T>{
6027 "Clients", NodeType::Delay, SchedStrategy::INF,
6028 std::numeric_limits<double>::infinity(),
false, 0});
6029 const std::size_t clientNode = m.node_of_station(m.clientIdx);
6030 m.serverIdx = m.clientIdx + 1;
6034 L.callers = callers;
6035 L.nreplicas = nreplicas;
6036 L.class_of_caller.assign(lqn.nidx + 1, 0);
6037 std::vector<std::size_t> serverNode(nreplicas);
6038 for (std::size_t r = 0; r < nreplicas; ++r) {
6040 st.name = r == 0 ? lqn.hashnames[idx] : lqn.hashnames[idx] +
"." + std::to_string(r + 1);
6041 st.nodetype = lqn.sched[idx] == SchedStrategy::INF ? NodeType::Delay : NodeType::Queue;
6042 st.sched = lqn.sched[idx];
6043 st.nservers = lqn.sched[idx] == SchedStrategy::INF
6044 ? std::numeric_limits<double>::infinity()
6046 st.attr_ishost = ishost;
6048 const std::size_t s = m.add_station(st);
6049 L.qstations.push_back(s);
6050 serverNode[r] = m.node_of_station(s);
6054 for (std::size_t c : callers) {
6055 double nj = njobs(c, idx);
6057 const bool caller_single_replica =
6058 reduce_fanout || single_replica_tasks.count(c) > 0;
6059 nj = caller_single_replica ? lqn.maxmult[c] : lqn.maxmult[c] * lqn.repl[c];
6060 if (std::isinf(nj)) {
6062 for (std::size_t k = 1; k <= NT(); ++k)
6063 if (lqn.taskgraph.get(k, c) != Tzero()) s += lqn.maxmult[k];
6065 if (std::isinf(nj) || nj == 0.0) {
6067 for (std::size_t k = 1; k <= NT(); ++k)
6068 if (std::isfinite(lqn.maxmult[k])) s2 += lqn.maxmult[k] * lqn.repl[k];
6069 nj = std::min(s2, 1000.0);
6075 jc.name = lqn.hashnames[c];
6076 jc.type = JobClassType::CLOSED;
6078 jc.refstat = m.clientIdx;
6079 jc.is_ref_class =
true;
6080 jc.attr_kind = int(LqnElement::TASK);
6082 const std::size_t k = m.add_class(jc);
6083 L.class_of_caller[c] = k;
6084 m.attr_tasks.emplace_back(k, c);
6085 const double zt = dbl(ref_think_time(c));
6086 m.set_service(m.clientIdx, k,
6089 for (std::size_t s : L.qstations)
6094 thinkt_map.push_back({idx, c, m.clientIdx, k});
6095 servt_map.push_back({idx, c, L.qstations[0], k});
6101 std::size_t sourceStation = 0, sinkNode = 0;
6103 for (std::size_t c : callers) {
6110 if (ph_open_arrival_only(c))
continue;
6117 if (ph_has_task_layer(c))
continue;
6118 for (std::size_t eidx : lqn.entriesof[c]) {
6119 if (!lqn.has_arrival[eidx])
continue;
6120 if (sourceStation == 0) {
6121 sourceStation = m.add_station(qn::Station<T>{
6122 "Source", NodeType::Source, SchedStrategy::EXT,
6123 std::numeric_limits<double>::infinity(),
false, 0});
6124 m.sourceIdx = sourceStation;
6125 sinkNode = m.add_node(
"Sink", NodeType::Sink,
false);
6126 m.sinkNode = sinkNode;
6129 oc.name = lqn.hashnames[eidx] +
".Open";
6130 oc.type = JobClassType::OPEN;
6131 oc.population = std::numeric_limits<double>::infinity();
6132 oc.refstat = sourceStation;
6133 oc.attr_kind = int(LqnElement::ENTRY);
6135 const std::size_t k = m.add_class(oc);
6136 m.set_service(sourceStation, k, lqn.arrival[eidx]);
6137 for (std::size_t s : L.qstations) {
6141 L.open_arrivals.emplace_back(k,
long(eidx));
6142 m.attr_entries.emplace_back(k, eidx);
6149 for (std::size_t eidx : lqn.entriesof[idx]) {
6150 if (!lqn.has_arrival[eidx])
continue;
6151 if (sourceStation == 0) {
6152 sourceStation = m.add_station(qn::Station<T>{
6153 "Source", NodeType::Source, SchedStrategy::EXT,
6154 std::numeric_limits<double>::infinity(),
false, 0});
6155 m.sourceIdx = sourceStation;
6156 sinkNode = m.add_node(
"Sink", NodeType::Sink,
false);
6157 m.sinkNode = sinkNode;
6160 oc.name = lqn.hashnames[eidx] +
".Open";
6161 oc.type = JobClassType::OPEN;
6162 oc.population = std::numeric_limits<double>::infinity();
6163 oc.refstat = sourceStation;
6164 oc.attr_kind = int(LqnElement::ENTRY);
6166 const std::size_t k = m.add_class(oc);
6167 m.set_service(sourceStation, k, lqn.arrival[eidx]);
6168 for (std::size_t s : L.qstations) {
6172 L.open_arrivals.emplace_back(k,
long(eidx));
6173 m.attr_entries.emplace_back(k, eidx);
6175 for (std::size_t cidx : ph_async_calls_into(idx)) {
6176 if (sourceStation == 0) {
6177 sourceStation = m.add_station(qn::Station<T>{
6178 "Source", NodeType::Source, SchedStrategy::EXT,
6179 std::numeric_limits<double>::infinity(),
false, 0});
6180 m.sourceIdx = sourceStation;
6181 sinkNode = m.add_node(
"Sink", NodeType::Sink,
false);
6182 m.sinkNode = sinkNode;
6184 const std::size_t eidx = lqn.callpair_dst[cidx];
6186 oc.name = lqn.callhashnames[cidx];
6187 oc.type = JobClassType::OPEN;
6188 oc.population = std::numeric_limits<double>::infinity();
6189 oc.refstat = sourceStation;
6190 oc.attr_kind = int(LqnElement::CALL);
6192 const std::size_t k = m.add_class(oc);
6194 for (std::size_t s : L.qstations) {
6198 L.open_arrivals.emplace_back(k, -
long(cidx));
6199 m.attr_calls.push_back({k, cidx, lqn.callpair_src[cidx], eidx});
6200 arv_call_map.push_back({idx, cidx, sourceStation, k});
6201 call_map.push_back({idx, cidx, L.qstations[0], k});
6207 const T share = num_traits<T>::from_double(1.0 /
double(nreplicas));
6208 for (std::size_t c : callers) {
6209 const std::size_t k = L.class_of_caller[c];
6210 for (std::size_t r = 0; r < nreplicas; ++r) {
6211 m.set_route(k, k, clientNode, serverNode[r], share);
6212 m.set_route(k, k, serverNode[r], clientNode, Tone());
6215 for (
const auto& oa : L.open_arrivals) {
6216 const std::size_t k = oa.first;
6217 const std::size_t srcNode = m.node_of_station(sourceStation);
6218 for (std::size_t r = 0; r < nreplicas; ++r) {
6219 m.set_route(k, k, srcNode, serverNode[r], share);
6220 m.set_route(k, k, serverNode[r], sinkNode, Tone());
6223 L.svcmean_by_class.assign(m.classes.size() + 1, Tzero());
6225 for (std::size_t c : callers) {
6226 const double v = njobs(c, idx);
6227 if (std::isfinite(v) && v > 0.0) np += v;
6229 L.npop = np < 1.0 ? 1.0 : np;
6230 apply_host_task_priorities(m, std::vector<std::size_t>{idx});
6233 ph_has_layer[idx] =
true;
6237 workflow::PhLaw<T> ph_service_law(std::size_t idx,
bool ishost, std::size_t c)
const {
6240 std::vector<workflow::PhLaw<T>> laws;
6241 std::vector<T> probs;
6243 for (std::size_t eidx : lqn.entriesof[c]) {
6244 if (ph_hostlaw[eidx].S.rows() == 0 || !(dbl(ph_share[eidx]) > 0.0))
continue;
6245 laws.push_back(ph_hostlaw[eidx]);
6246 probs.push_back(ph_share[eidx]);
6247 tot += dbl(ph_share[eidx]);
6249 if (laws.empty())
return ph_immediate_law();
6250 for (T& p : probs) p = T(p / num_traits<T>::from_double(tot));
6256 bool started =
false;
6257 workflow::PhLaw<T> out;
6258 for (std::size_t eidx : lqn.entriesof[idx]) {
6259 const T n = ph_ncalls(c, eidx);
6261 const workflow::PhLaw<T> lp =
6266 if (!started)
return ph_immediate_law();
6274 T ph_delay_mean(std::size_t idx, std::size_t c)
const {
6284 T
z = T(thinkt[c] + ref_think_time(c));
6285 if (!std::isfinite(dbl(z)) || dbl(z) < 0.0)
z = Tzero();
6286 z = T(z + ph_actthinkt[c]);
6287 const std::size_t hidx = lqn.parent[c];
6292 if (!ph_served_here(idx, hidx))
z = T(z + ph_procresid[c]);
6293 else z = T(z - ph_procsave[c]);
6294 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6295 const std::size_t tidx = lqn.tshift + t;
6296 if (!ph_served_here(idx, tidx))
z = T(z + ph_calltime(c, tidx));
6297 else z = T(z - ph_callsave(c, tidx));
6299 if (!std::isfinite(dbl(z)) || dbl(z) < 0.0)
6309 bool ph_served_here(std::size_t idx, std::size_t elem)
const {
6310 if (elem < 1 || elem >= idxhash.size() || idx < 1 || idx >= idxhash.size())
6312 return idxhash[
elem] >= 0 && idxhash[
elem] == idxhash[idx];
6324 void update_layers_ph(
int) {
6325 for (std::size_t idx = 1; idx <= NT(); ++idx) {
6326 if (idxhash[idx] < 0 || !ph_has_layer[idx])
continue;
6327 PHLayer& L = ph_layers[idx];
6328 qn::Layer<T>& m = ensemble[std::size_t(idxhash[idx])];
6329 for (std::size_t c : L.callers) {
6330 const std::size_t k = L.class_of_caller[c];
6331 const workflow::PhLaw<T> sl = ph_service_law(idx, L.ishost, c);
6333 const Distrib<T> law = ph_station_law(sl);
6334 for (std::size_t s : L.qstations) m.set_service(s, k, law);
6335 const double zd = std::max(dbl(ph_delay_mean(idx, c)),
6337 m.set_service(m.clientIdx, k,
6340 for (
const auto& oa : L.open_arrivals) {
6341 const std::size_t k = oa.first;
6342 if (oa.second > 0 && L.ishost) {
6345 L.svcmean_by_class[k] = ph_hostmean[std::size_t(oa.second)];
6348 if (oa.second > 0) {
6352 const std::size_t eo = std::size_t(oa.second);
6353 L.svcmean_by_class[k] = ph_entrymean[eo];
6354 const Distrib<T> elaw = ph_station_law(ph_entrylaw[eo]);
6355 for (std::size_t s : L.qstations) m.set_service(s, k, elaw);
6358 const std::size_t cidx = std::size_t(-oa.second);
6359 const std::size_t eidx = lqn.callpair_dst[cidx];
6360 L.svcmean_by_class[k] = ph_entrymean[eidx];
6361 const Distrib<T> law = ph_station_law(ph_entrylaw[eidx]);
6362 for (std::size_t s : L.qstations) m.set_service(s, k, law);
6363 const std::size_t aidx = lqn.callpair_src[cidx];
6364 double rate = dbl(tput[aidx]) * dbl(lqn.callproc_mean[cidx]);
6367 m.set_service(m.sourceIdx, k,
6380 static T ph_residence(
const T& Q,
const T& X,
const T& RN) {
6381 const double q = num_traits<T>::to_double(Q), x = num_traits<T>::to_double(X);
6392 static T ph_inflation_of(
const T& R,
const T& S,
double npop) {
6394 const double s = num_traits<T>::to_double(S), r = num_traits<T>::to_double(R);
6396 if (!std::isfinite(f) || f < 1.0) f = 1.0;
6397 if (std::isfinite(npop) && npop >= 1.0 && f > npop) f = npop;
6398 return num_traits<T>::from_double(f);
6402 double ph_layer_pop(
const PHLayer& L, std::size_t idx)
const {
6406 if (!L.open_arrivals.empty())
return std::numeric_limits<double>::infinity();
6409 if (L.npop >= 1.0)
return L.npop;
6411 for (std::size_t c : L.callers) {
6412 const double v = njobs(c, idx);
6413 if (std::isfinite(v) && v > 0.0) n += v;
6415 return n < 1.0 ? 1.0 : n;
6431 void update_metrics_ph(
int it) {
6432 const std::size_t N = lqn.nidx;
6433 servt.assign(N + 1, Tzero());
6434 residt.assign(N + 1, Tzero());
6435 callservt.assign(lqn.ncalls + 1, Tzero());
6436 callresidt.assign(lqn.ncalls + 1, Tzero());
6438 std::vector<T> inflNum(N + 1, Tzero()), inflDen(N + 1, Tzero());
6439 std::vector<T> taskTput(N + 1, Tzero()), openTput(N + 1, Tzero());
6442 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx) {
6443 if (idxhash[hidx] < 0 || !ph_has_layer[hidx])
continue;
6444 const PHLayer& L = ph_layers[hidx];
6445 const LayerResult<T>& res = results.back()[std::size_t(idxhash[hidx])];
6446 const double npop = ph_layer_pop(L, hidx);
6447 for (std::size_t c : L.callers) {
6448 const std::size_t k = L.class_of_caller[c];
6449 T X = Tzero(), Q = Tzero();
6450 for (std::size_t s : L.qstations) {
6451 X = T(X + res.TN(s - 1, k - 1));
6452 Q = T(Q + res.QN(s - 1, k - 1));
6454 const T R = ph_residence(Q, X, res.RN(L.qstations[0] - 1, k - 1));
6455 const T f = ph_inflation_of(R, L.svcmean_by_class[k], npop);
6456 if (!std::isfinite(dbl(X)) || dbl(X) < 0.0) X = Tzero();
6464 double rc = lqn.repl[c];
6465 if (rc > 1.0 && njobs(c, hidx) >= lqn.maxmult[c] * rc) rc = 1.0;
6466 taskTput[c] = T(taskTput[c] + num_traits<T>::from_double(rc) * X);
6467 for (std::size_t eidx : lqn.entriesof[c]) {
6468 const T sh = dbl(ph_share[eidx]) > 0.0 ? ph_share[eidx] : Tzero();
6469 const T w = T(sh * X);
6470 inflNum[eidx] = T(inflNum[eidx] + w * f);
6471 inflDen[eidx] = T(inflDen[eidx] + w);
6474 for (
const auto& oa : L.open_arrivals) {
6475 if (oa.second <= 0)
continue;
6476 const std::size_t k = oa.first;
6477 const std::size_t eidx = std::size_t(oa.second);
6478 T X = Tzero(), Q = Tzero();
6479 for (std::size_t s : L.qstations) {
6480 X = T(X + res.TN(s - 1, k - 1));
6481 Q = T(Q + res.QN(s - 1, k - 1));
6483 if (!std::isfinite(dbl(X)) || dbl(X) <= 0.0)
continue;
6484 const T f = ph_inflation_of(ph_residence(Q, X, res.RN(L.qstations[0] - 1, k - 1)),
6485 L.svcmean_by_class[k], npop);
6486 inflNum[eidx] = T(inflNum[eidx] + X * f);
6487 inflDen[eidx] = T(inflDen[eidx] + X);
6488 openTput[eidx] = T(openTput[eidx] + X);
6489 taskTput[lqn.parent[eidx]] = T(taskTput[lqn.parent[eidx]] + X);
6493 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
6494 const std::size_t eidx = lqn.eshift + e;
6497 f = dbl(inflNum[eidx]) / dbl(inflDen[eidx]);
6498 if (!std::isfinite(f) || f < 1.0) f = 1.0;
6499 const T fv = num_traits<T>::from_double(f);
6500 for (std::size_t aidx : lqn.actsof[eidx])
6501 residt[aidx] = T(fv * (lqn.hostdem[aidx].disabled ? Tzero()
6502 : lqn.hostdem[aidx].mean));
6506 std::vector<T> relw(N + 1, Tzero());
6507 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6508 const std::size_t tidx = lqn.tshift + t;
6509 if (idxhash[tidx] < 0 || !ph_has_layer[tidx])
continue;
6510 const PHLayer& L = ph_layers[tidx];
6511 const LayerResult<T>& res = results.back()[std::size_t(idxhash[tidx])];
6512 const double npop = ph_layer_pop(L, tidx);
6513 for (std::size_t c : L.callers) {
6514 const std::size_t k = L.class_of_caller[c];
6515 T X = Tzero(), Q = Tzero();
6516 for (std::size_t s : L.qstations) {
6517 X = T(X + res.TN(s - 1, k - 1));
6518 Q = T(Q + res.QN(s - 1, k - 1));
6520 if (!std::isfinite(dbl(X)) || dbl(X) < 0.0) X = Tzero();
6521 const T g = ph_inflation_of(ph_residence(Q, X, res.RN(L.qstations[0] - 1, k - 1)),
6522 L.svcmean_by_class[k], npop);
6523 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
6524 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
6525 if (lqn.parent[lqn.callpair_src[cidx]] != c)
continue;
6526 if (lqn.parent[lqn.callpair_dst[cidx]] != tidx)
continue;
6527 const std::size_t eidx = lqn.callpair_dst[cidx];
6528 callservt[cidx] = T(lqn.callproc_mean[cidx] * g * ph_entrymean[eidx]);
6529 callresidt[cidx] = callservt[cidx];
6531 for (std::size_t eidx : lqn.entriesof[tidx])
6532 relw[eidx] = T(relw[eidx] + X * ph_ncalls(c, eidx));
6534 for (
const auto& oa : L.open_arrivals) {
6535 if (oa.second == 0)
continue;
6536 const std::size_t k = oa.first;
6537 if (oa.second > 0) {
6543 for (std::size_t s : L.qstations) Xo = T(Xo + res.TN(s - 1, k - 1));
6544 if (std::isfinite(dbl(Xo)) && dbl(Xo) > 0.0)
6545 openTput[std::size_t(oa.second)] = T(openTput[std::size_t(oa.second)] + Xo);
6548 const std::size_t cidx = std::size_t(-oa.second);
6549 const std::size_t eidx = lqn.callpair_dst[cidx];
6551 for (std::size_t s : L.qstations) X = T(X + res.TN(s - 1, k - 1));
6552 const T R = res.RN(L.qstations[0] - 1, k - 1);
6553 if (std::isfinite(dbl(R)) && dbl(R) > 0.0) {
6554 callservt[cidx] = T(R * lqn.callproc_mean[cidx]);
6555 callresidt[cidx] = callservt[cidx];
6557 if (std::isfinite(dbl(X)) && dbl(X) > 0.0) relw[eidx] = T(relw[eidx] + X);
6562 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6563 const std::size_t tidx = lqn.tshift + t;
6564 const std::vector<std::size_t>& entries = lqn.entriesof[tidx];
6565 if (entries.empty())
continue;
6572 for (std::size_t eidx : entries)
tot = T(tot + relw[eidx] + openTput[eidx]);
6574 for (std::size_t eidx : entries)
6575 ph_share[eidx] = T((relw[eidx] + openTput[eidx]) / tot);
6577 for (std::size_t eidx : entries)
6578 ph_share[eidx] = num_traits<T>::from_double(1.0 /
double(entries.size()));
6586 for (std::size_t eidx : entries) tput[eidx] = T(tput[tidx] * ph_share[eidx]);
6592 const T nrep = num_traits<T>::from_double(std::max(1.0, lqn.repl[tidx]));
6594 : T(tput[tidx] / nrep);
6598 for (std::size_t aidx = lqn.ashift + 1; aidx <= lqn.ashift + lqn.nacts; ++aidx) {
6600 if (!std::isfinite(dbl(v)) && it > 1 && !std::isnan(residt_prev[aidx]))
6601 v = residt_prev_v[aidx];
6602 if (relax_omega < 1.0 && it > 1 && !std::isnan(residt_prev[aidx])) {
6603 const T om = num_traits<T>::from_double(relax_omega);
6604 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6605 v = T(om * v + om1 * residt_prev_v[aidx]);
6608 residt_prev[aidx] = dbl(v);
6609 residt_prev_v[aidx] = v;
6611 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
6612 T v = callservt[cidx];
6613 if (!std::isfinite(dbl(v)))
6614 v = (it > 1 && std::isfinite(callservt_prev[cidx])) ? callservt_prev_v[cidx]
6616 if (relax_omega < 1.0 && it > 1 && !std::isnan(callservt_prev[cidx])) {
6617 const T om = num_traits<T>::from_double(relax_omega);
6618 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6619 v = T(om * v + om1 * callservt_prev_v[cidx]);
6621 callservt[cidx] = v;
6622 callresidt[cidx] = v;
6623 callservt_prev[cidx] = dbl(v);
6624 callresidt_prev[cidx] = dbl(v);
6625 callservt_prev_v[cidx] = v;
6633 ph_compose_entry_laws();
6635 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
6636 const std::size_t eidx = lqn.eshift + e;
6637 if (!ph_has_wf[eidx])
continue;
6638 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
6639 for (std::size_t aidx : lqn.actsof[eidx]) {
6640 T sa = T(residt[aidx] + act_think_time(aidx));
6641 for (std::size_t cidx : lqn.callsof[aidx])
6642 if (lqn.calltype[cidx] == CallType::SYNC) sa = T(sa + callservt[cidx]);
6644 servt_prev[aidx] = dbl(sa);
6645 servt_prev_v[aidx] = sa;
6646 tput[aidx] = T(tput[eidx] * ex.at(aidx));
6647 tput_prev[aidx] = dbl(tput[aidx]);
6648 tput_prev_v[aidx] = tput[aidx];
6651 : Distrib<T>::disabled_dist();
6654 servt[eidx] = ph_entrymean[eidx];
6655 residt[eidx] = ph_entrymean[eidx];
6673 T thread_busy_fraction(
const qn::Layer<T>& L, std::size_t ts,
const LayerResult<T>& r,
6674 bool skipnan)
const {
6675 const qn::Station<T>& st = L.stations[ts - 1];
6676 const double c = st.nservers;
6677 const bool hasdep = !st.lldscaling.empty() || bool(st.cdscaling) || bool(st.jdscaling);
6679 if (!hasdep || std::isinf(c) || c <= 0.0) {
6680 for (std::size_t k = 0; k < L.nclasses; ++k) {
6681 const T v = r.UN(ts - 1, k);
6682 if (!skipnan || !std::isnan(dbl(v))) u = T(u + v);
6686 for (std::size_t k = 0; k < L.nclasses; ++k) {
6687 const T x = r.TN(ts - 1, k);
6688 if (std::isnan(dbl(x)) || !(dbl(x) > 0.0))
continue;
6689 const Distrib<T>& d = L.service[ts - 1][k];
6690 if (d.disabled)
continue;
6691 if (std::isfinite(dbl(d.mean))) u = T(u + x * d.mean);
6693 return T(u / num_traits<T>::from_double(c));
6707 void update_think_times_ph(
int it) {
6710 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6711 const std::size_t tidx = lqn.tshift + t;
6712 if (ignore[tidx])
continue;
6713 const T ztask = ref_think_time(tidx);
6714 if (idxhash[tidx] < 0) {
6719 const double arvrate = open_arrival_rate_of(tidx);
6721 double nja = lqn.maxmult[tidx];
6722 if (!std::isfinite(nja) || nja <= 0.0) {
6724 for (std::size_t c = 1; c <= NT(); ++c) nja = std::max(nja, njobs(tidx, c));
6727 const std::size_t hidx = lqn.parent[tidx];
6728 if (hidx >= 1 && hidx < idxhash.size() && idxhash[hidx] >= 0 &&
6729 ph_has_layer[hidx] && ph_layers[hidx].class_of_caller[tidx] > 0) {
6730 const PHLayer& HL = ph_layers[hidx];
6731 const LayerResult<T>& hr = results.back()[std::size_t(idxhash[hidx])];
6732 const T rr = hr.RN(HL.qstations[0] - 1, HL.class_of_caller[tidx] - 1);
6733 if (!std::isnan(dbl(rr))) hres = rr;
6735 hres += open_arrival_call_residt(tidx, arvrate);
6736 T za = T(num_traits<T>::from_double(nja / arvrate) - hres - ztask);
6737 if (za < floorv) za = floorv;
6738 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
6739 const T om = num_traits<T>::from_double(relax_omega);
6740 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6741 za = T(om * za + om1 * thinkt_prev_v[tidx]);
6743 tput[tidx] = num_traits<T>::from_double(arvrate);
6745 thinkt_prev[tidx] = dbl(za);
6746 thinkt_prev_v[tidx] = za;
6756 const PHLayer& L = ph_layers[tidx];
6757 const qn::Layer<T>& m = ensemble[std::size_t(idxhash[tidx])];
6758 const LayerResult<T>& r = results.back()[std::size_t(idxhash[tidx])];
6760 T U = thread_busy_fraction(m, L.qstations[0], r,
true);
6767 if (dbl(ph_setupshare[tidx]) > 0.0)
6768 U = T(U * (Tone() - ph_setupshare[tidx]));
6771 T X = ph_xdemand[tidx];
6774 double nj = lqn.maxmult[tidx];
6775 if (!std::isfinite(nj) || nj <= 0.0) {
6777 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
6781 if (lqn.sched[tidx] == SchedStrategy::INF) {
6783 z = T((num_traits<T>::from_double(nj) - U) / X - ztask);
6785 const T om = U > Tone() ? T(U - Tone()) : T(Tone() - U);
6786 z = T(num_traits<T>::from_double(nj) * om / X - ztask);
6791 if (z < floorv)
z = floorv;
6792 if (it > 1 && !std::isnan(thinkt_prev[tidx]) && !std::isfinite(dbl(z)))
6793 z = thinkt_prev_v[tidx];
6794 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
6795 const T om = num_traits<T>::from_double(relax_omega);
6796 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
6797 z = T(om * z + om1 * thinkt_prev_v[tidx]);
6800 thinkt_prev[tidx] = dbl(z);
6801 thinkt_prev_v[tidx] =
z;
6815 LnSolution<T> aggregate_ph() {
6816 const std::size_t N = lqn.nidx;
6818 out.QN.assign(N + 1, Tzero());
6819 out.UN.assign(N + 1, Tzero());
6820 out.RN.assign(N + 1, Tzero());
6821 out.TN.assign(N + 1, Tzero());
6822 out.AN.assign(N + 1, Tzero());
6823 out.WN.assign(N + 1, Tzero());
6824 out.defined_Q.assign(N + 1,
false);
6825 out.defined_U.assign(N + 1,
false);
6826 out.defined_R.assign(N + 1,
false);
6827 out.defined_T.assign(N + 1,
false);
6828 out.defined_A.assign(N + 1,
false);
6829 out.defined_W.assign(N + 1,
false);
6830 out.iterations = iterations_done;
6831 out.converged = did_converge;
6833 std::vector<T> PN(N + 1, Tzero()), UT(N + 1, Tzero());
6834 std::vector<bool> hasPN(N + 1,
false), hasUT(N + 1,
false);
6836 for (std::size_t a = 1; a <= lqn.nacts; ++a) {
6837 const std::size_t aidx = lqn.ashift + a;
6838 const std::size_t tidx = lqn.parent[aidx];
6839 if (ignore[tidx])
continue;
6840 const std::size_t hidx = lqn.parent[tidx];
6841 out.TN[aidx] = tput[aidx];
6842 out.defined_T[aidx] =
true;
6843 out.RN[aidx] = servt[aidx];
6844 out.defined_R[aidx] =
true;
6845 UT[aidx] = T(tput[aidx] * servt[aidx]);
6851 const T hd = lqn.hostdem[aidx].disabled ? Tzero() : lqn.hostdem[aidx].mean;
6852 PN[aidx] = T(tput[aidx] * hd / num_traits<T>::from_double(ph_host_servers(hidx)));
6854 PN[hidx] = T(PN[hidx] + PN[aidx]);
6858 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
6859 const std::size_t eidx = lqn.eshift + e;
6860 const std::size_t tidx = lqn.parent[eidx];
6861 if (ignore[tidx])
continue;
6862 out.TN[eidx] = tput[eidx];
6863 out.defined_T[eidx] =
true;
6864 out.RN[eidx] = servt[eidx];
6865 out.defined_R[eidx] =
true;
6866 UT[eidx] = T(tput[eidx] * servt[eidx]);
6868 for (std::size_t aidx : lqn.actsof[eidx]) {
6869 PN[eidx] = T(PN[eidx] + PN[aidx]);
6876 if (ph_has_wf[eidx]) {
6877 const std::unordered_map<std::size_t, T>& ex = ph_execs[eidx];
6878 for (std::size_t aidx : lqn.actsof[eidx]) {
6879 out.WN[aidx] = T(ph_share[eidx] * ex.at(aidx) * residt[aidx]);
6880 out.defined_W[aidx] =
true;
6883 UT[tidx] = T(UT[tidx] + UT[eidx]);
6887 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
6888 const std::size_t tidx = lqn.tshift + t;
6889 if (ignore[tidx])
continue;
6890 out.TN[tidx] = tput[tidx];
6891 out.defined_T[tidx] =
true;
6894 for (std::size_t aidx : lqn.actsof[tidx]) {
6895 PN[tidx] = T(PN[tidx] + PN[aidx]);
6897 if (out.defined_W[aidx]) { w = T(w + out.WN[aidx]); anyw =
true; }
6899 if (anyw) { out.WN[tidx] = w; out.defined_W[tidx] =
true; }
6902 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx)
6903 out.defined_T[hidx] =
false;
6905 for (std::size_t idx = 1; idx <= N; ++idx) {
6906 out.QN[idx] = UT[idx];
6907 out.defined_Q[idx] = hasUT[idx];
6908 out.UN[idx] = PN[idx];
6909 out.defined_U[idx] = hasPN[idx];
6915 out.UN[idx] = Tzero();
6916 out.defined_U[idx] =
true;
6917 out.defined_A[idx] =
false;
6918 const bool host = lqn.type[idx] == LqnElement::HOST;
6919 const bool task = lqn.type[idx] == LqnElement::TASK;
6920 const bool entry = lqn.type[idx] == LqnElement::ENTRY;
6921 out.QN[idx] = Tzero();
6922 out.defined_Q[idx] = !host;
6923 out.RN[idx] = Tzero();
6924 out.defined_R[idx] = !host && !task;
6925 out.WN[idx] = Tzero();
6926 out.defined_W[idx] = !host && !entry;
6927 out.TN[idx] = Tzero();
6928 out.defined_T[idx] = !host;
6934 void update_metrics(
int it) {
6935 if (is_ph_encoding()) {
6936 update_metrics_ph(it);
6939 if (lnmethod ==
"moment3") {
6940 update_metrics_moment_based(it);
6943 update_metrics_default(it);
6954 std::size_t layer_refclass(std::size_t idx,
const qn::Layer<T>& L, std::size_t k)
const {
6955 const auto it = layer_normclass.find(idx);
6956 if (it != layer_normclass.end() && k < it->second.size() && it->second[k] > 0)
6957 return it->second[k];
6959 for (std::size_t cc = 0; cc < L.nchains; ++cc)
6960 if (L.chains[cc][k]) c = cc;
6961 return L.refclass[c];
6964 void update_metrics_default(
int it) {
6965 const std::size_t N = lqn.nidx;
6966 servt.assign(N + 1, Tzero());
6967 residt.assign(N + 1, Tzero());
6968 const int iter_min = std::min(30,
int(std::ceil(opt.iter_max / 4.0)));
6969 const bool averaging = averagingstart >= 0 && it >= iter_min;
6970 const int wnd = averaging ? int(it - averagingstart + 1) : 1;
6972 for (
const UpdRow& row : servt_map) {
6973 const std::size_t e = std::size_t(idxhash[row.idx]);
6974 const qn::Layer<T>& L = ensemble[e];
6975 const std::size_t k = row.cls - 1;
6976 const std::size_t refclass_c = layer_refclass(row.idx, L, k);
6977 const std::size_t refstat_k = L.classes[k].refstat;
6979 T sv = Tzero(), rs = Tzero(), tp = Tzero();
6980 const T wT = T(Tone() / num_traits<T>::from_int(wnd));
6981 for (
int w = 0; w < wnd; ++w) {
6982 const LayerResult<T>& r = results[results.size() - 1 - w][e];
6983 sv += r.RN(row.node - 1, k) * wT;
6984 const T TN_ref = (refclass_c > 0 && refstat_k > 0) ? r.TN(refstat_k - 1, refclass_c - 1) : Tzero();
6986 rs += r.QN(row.node - 1, k) / TN_ref * wT;
6988 rs += r.WN(row.node - 1, k) * wT;
6989 tp += r.TN(row.node - 1, k) * wT;
6991 servt[row.aidx] = sv;
6992 residt[row.aidx] = rs;
6993 tput[row.aidx] = tp;
6998 if (lqn.parent[lqn.parent[row.aidx]] == row.idx) {
6999 const auto hr = host_all_replica_tasks.find(lqn.parent[row.aidx]);
7000 if (hr != host_all_replica_tasks.end() && hr->second > 1) {
7001 const T h = num_traits<T>::from_double(
double(hr->second));
7002 residt[row.aidx] = T(h * residt[row.aidx]);
7003 tput[row.aidx] = T(h * tput[row.aidx]);
7008 const Distrib<T>& at = lqn.actthink[row.aidx];
7010 servt[row.aidx] = T(servt[row.aidx] + at.mean);
7011 residt[row.aidx] = T(residt[row.aidx] + at.mean);
7019 if (async_only_activity(row.aidx)) residt[row.aidx] = servt[row.aidx];
7021 if (relax_omega < 1.0 && it > 1) {
7022 const T om = num_traits<T>::from_double(relax_omega);
7023 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
7024 if (!std::isnan(servt_prev[row.aidx]))
7025 servt[row.aidx] = T(om * servt[row.aidx] + om1 * servt_prev_v[row.aidx]);
7026 if (!std::isnan(residt_prev[row.aidx]))
7027 residt[row.aidx] = T(om * residt[row.aidx] + om1 * residt_prev_v[row.aidx]);
7028 if (!std::isnan(tput_prev[row.aidx]))
7029 tput[row.aidx] = T(om * tput[row.aidx] + om1 * tput_prev_v[row.aidx]);
7031 servt_prev[row.aidx] = dbl(servt[row.aidx]);
7032 residt_prev[row.aidx] = dbl(residt[row.aidx]);
7033 tput_prev[row.aidx] = dbl(tput[row.aidx]);
7034 servt_prev_v[row.aidx] = servt[row.aidx];
7035 residt_prev_v[row.aidx] = residt[row.aidx];
7036 tput_prev_v[row.aidx] = tput[row.aidx];
7038 if (servt[row.aidx] > Tzero() && dbl(servt[row.aidx]) <= 1e10)
7048 servt_ph1.assign(N + 1, Tzero());
7049 servt_ph2.assign(N + 1, Tzero());
7050 for (std::size_t a = 1; a <= lqn.nacts; ++a) {
7051 const std::size_t aidx = lqn.ashift + a;
7052 if (lqn.actphase[a] == 1)
7053 servt_ph1[aidx] = servt[aidx];
7055 servt_ph2[aidx] = servt[aidx];
7062 for (
const UpdRow& row : thinkt_map) {
7063 if (!tputproc[row.aidx].disabled)
continue;
7064 const std::size_t e = std::size_t(idxhash[row.idx]);
7066 const T wT = T(Tone() / num_traits<T>::from_int(wnd));
7067 for (
int w = 0; w < wnd; ++w)
7068 tp += results[results.size() - 1 - w][e].TN(row.node - 1, row.cls - 1) * wT;
7069 tput[row.aidx] = tp;
7074 callservt.assign(lqn.ncalls + 1, Tzero());
7075 callresidt.assign(lqn.ncalls + 1, Tzero());
7082 std::vector<std::size_t> call_rows(call_map.size(), 1);
7083 for (std::size_t q = 0; q < call_map.size(); ++q) {
7084 std::vector<std::size_t> st;
7085 for (
const UpdRow& o : call_map)
7086 if (o.idx == call_map[q].idx && o.aidx == call_map[q].aidx && o.node > 1 &&
7087 std::find(st.begin(), st.end(), o.node) == st.end())
7088 st.push_back(o.node);
7089 call_rows[q] = std::max<std::size_t>(1, st.size());
7091 for (std::size_t q = 0; q < call_map.size(); ++q) {
7092 const UpdRow& row = call_map[q];
7093 if (row.node <= 1)
continue;
7094 const std::size_t e = std::size_t(idxhash[row.idx]);
7095 const LayerResult<T>& r = results.back()[e];
7096 callservt[row.aidx] =
7097 T(r.RN(row.node - 1, row.cls - 1) * lqn.callproc_mean[row.aidx]);
7103 const qn::Layer<T>& L = ensemble[e];
7104 const std::size_t k = row.cls - 1;
7105 const std::size_t refclass_c = layer_refclass(row.idx, L, k);
7106 const std::size_t refstat_k = L.classes[k].refstat;
7107 const T TN_ref = (refclass_c > 0 && refstat_k > 0) ? r.TN(refstat_k - 1, refclass_c - 1) : Tzero();
7109 ? T(num_traits<T>::from_int(
int(call_rows[q])) *
7110 r.QN(row.node - 1, k) / TN_ref)
7111 : r.WN(row.node - 1, k);
7113 const T rw = region_wait(e, row.cls);
7115 callservt[row.aidx] = T(callservt[row.aidx] + rw);
7116 callresidt[row.aidx] = T(callresidt[row.aidx] + rw);
7118 if (relax_omega < 1.0 && it > 1 && !std::isnan(callservt_prev[row.aidx])) {
7119 const T om = num_traits<T>::from_double(relax_omega);
7120 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
7121 callservt[row.aidx] =
7122 T(om * callservt[row.aidx] + om1 * callservt_prev_v[row.aidx]);
7124 callservt_prev[row.aidx] = dbl(callservt[row.aidx]);
7125 callservt_prev_v[row.aidx] = callservt[row.aidx];
7126 callresidt_prev[row.aidx] = dbl(callresidt[row.aidx]);
7129 resolve_entry_service();
7141 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7142 const std::size_t eidx = lqn.eshift + e;
7143 servt_ph2[eidx] = (eidx < entry_servt_last.size() && entry_servt_last[eidx] > Tzero())
7144 ? T(entry_servt_ph2[eidx] * servt[eidx] / entry_servt_last[eidx])
7146 servt_ph1[eidx] = T(servt[eidx] - servt_ph2[eidx]);
7148 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7149 const std::size_t eidx = lqn.eshift + e;
7150 const std::size_t tidx = lqn.parent[eidx];
7152 if (lqn.isref[tidx] || !lqn.issynccaller.any_col(eidx)) {
7153 residt[eidx] = servt[eidx];
7156 T entry_tput = Tzero();
7158 entry_tput = tput[eidx];
7160 entry_tput = tput[tidx];
7166 residt[eidx] = T(servt_ph1[eidx] + prOvertake[e] * servt_ph2[eidx]);
7170 for (
const UpdRow& row : call_map) {
7171 if (row.node <= 1)
continue;
7172 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7175 for (
const UpdRow& row : call_map) {
7176 if (row.node <= 1)
continue;
7177 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7179 callservt[row.aidx] = servt[eidx];
7180 callservtproc[row.aidx] = servtproc[eidx];
7181 }
else if (callservt[row.aidx] > Tzero()) {
7194 if (has_phase2 && (is_flat_layering() || it == 1)) {
7195 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
7196 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
7197 const std::size_t target = lqn.callpair_dst[cidx];
7198 if (target <= lqn.eshift || target > lqn.eshift + lqn.nentries)
continue;
7200 const T eff = residt[target];
7201 if (!(eff > Tzero()))
continue;
7202 const T w = T(eff * lqn.callproc_mean[cidx]);
7203 callservt[cidx] = w;
7204 callresidt[cidx] = w;
7224 static void cdf_moments(
const fluid::FluidPassage& c,
double& m1,
double& m2,
double& m3) {
7226 for (std::size_t i = 0; i + 1 < c.t.size(); ++i) {
7227 const double x = 0.5 * (c.t[i + 1] + c.t[i]);
7228 const double w = c.cdf[i + 1] - c.cdf[i];
7231 m3 += x * x * x * w;
7236 const std::vector<std::vector<fluid::FluidPassage>>& layer_cdf(std::size_t e) {
7237 if (cdf_repo[e].empty()) {
7244 ensemble[e].refresh_rt();
7246 cdf_repo[e] = detail::ln_fluid_cdf_respt(ensemble[e], opt.layer_fluid);
7247 }
catch (
const std::exception&) {
7254 cdf_repo[e] = layer_cdf_exp_fallback(e);
7262 std::vector<std::vector<fluid::FluidPassage>> layer_cdf_exp_fallback(std::size_t e) {
7263 const qn::NetworkStruct<T>& L = ensemble[e];
7264 std::vector<std::vector<fluid::FluidPassage>> out(
7265 L.nstations, std::vector<fluid::FluidPassage>(L.nclasses));
7266 if (results.empty() || e >= results.back().size())
return out;
7267 const Matrix<T>& RN = results.back()[e].RN;
7268 const std::size_t npts = 100;
7269 for (std::size_t i = 0; i < L.nstations; ++i) {
7270 if (L.stations[i].nodetype == qn::NodeType::Source)
continue;
7271 for (std::size_t r = 0; r < L.nclasses; ++r) {
7272 if (L.disabled[i][r])
continue;
7273 const double rn = (i < static_cast<std::size_t>(RN.rows()) &&
7274 r < static_cast<std::size_t>(RN.cols()))
7277 if (!(std::isfinite(rn) && rn > 0.0))
continue;
7278 fluid::FluidPassage& cell = out[i][r];
7279 cell.t.reserve(npts);
7280 cell.cdf.reserve(npts);
7281 for (std::size_t j = 0; j < npts; ++j) {
7283 0.001 + (0.999 - 0.001) *
static_cast<double>(j) / (npts - 1);
7284 cell.cdf.push_back(q);
7285 cell.t.push_back(-std::log(1.0 - q) * rn);
7306 int entry_visit_ratio(std::size_t eidx, T& ratio)
const {
7307 const std::size_t tidx = lqn.parent[eidx];
7308 const std::size_t hidx = lqn.parent[tidx];
7309 if (ignore[tidx] || ignore[hidx] || idxhash[hidx] < 0)
return 0;
7310 if (!lqn.issynccaller.any_col(eidx))
return 1;
7311 const std::size_t hl = std::size_t(idxhash[hidx]);
7312 const qn::Layer<T>& L = ensemble[hl];
7313 const LayerResult<T>& r = results.back()[hl];
7314 T task_tput = Tzero(), entry_tput = Tzero();
7315 for (
const auto& kv : L.attr_tasks)
7316 if (kv.second == tidx) task_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7317 for (
const auto& kv : L.attr_entries)
7318 if (kv.second == eidx) entry_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7320 ratio = T(task_tput / (entry_tput > floor ? entry_tput : floor));
7325 Matrix<T> entry_service_resolvent()
const {
7326 const std::size_t dim = lqn.nidx + lqn.ncalls;
7327 Matrix<T> A(dim + 1, dim + 1, Tzero());
7328 for (std::size_t i = 0; i <= dim; ++i) {
7330 for (std::size_t j = 0; j <= dim; ++j) A(i, j) = T(A(i, j) - servtmatrix(i, j));
7332 return ::line::inverse(A);
7358 void update_metrics_moment_based(
int it) {
7359 const std::size_t N = lqn.nidx;
7360 servt.assign(N + 1, Tzero());
7361 residt.assign(N + 1, Tzero());
7362 callservt.assign(lqn.ncalls + 1, Tzero());
7363 callresidt.assign(lqn.ncalls + 1, Tzero());
7366 for (
const UpdRow& row : servt_map) {
7367 const std::size_t e = std::size_t(idxhash[row.idx]);
7368 const qn::Layer<T>& L = ensemble[e];
7369 const LayerResult<T>& r = results.back()[e];
7370 const std::size_t k = row.cls - 1;
7372 for (std::size_t cc = 0; cc < L.nchains; ++cc)
7373 if (L.chains[cc][k]) c = cc;
7374 const std::size_t refclass_c = L.refclass[c];
7375 const std::size_t refstat_k = L.classes[k].refstat;
7376 const T TN_ref = (refclass_c > 0 && refstat_k > 0) ? r.TN(refstat_k - 1, refclass_c - 1) : Tzero();
7378 tput[row.aidx] = r.TN(row.node - 1, k);
7380 ? T(r.QN(row.node - 1, k) / TN_ref)
7381 : r.WN(row.node - 1, k);
7382 if (!hasconverged) {
7383 servt[row.aidx] = r.RN(row.node - 1, k);
7385 const Distrib<T>& at = lqn.actthink[row.aidx];
7387 servt[row.aidx] = T(servt[row.aidx] + at.mean);
7388 residt[row.aidx] = T(residt[row.aidx] + at.mean);
7393 if (async_only_activity(row.aidx)) residt[row.aidx] = servt[row.aidx];
7395 servtcdf[row.aidx] = layer_cdf(e)[row.node - 1][k];
7399 for (
const UpdRow& row : call_map) {
7400 if (row.node <= 1)
continue;
7401 const std::size_t e = std::size_t(idxhash[row.idx]);
7402 const LayerResult<T>& r = results.back()[e];
7403 callresidt[row.aidx] = r.WN(row.node - 1, row.cls - 1);
7405 callservt[row.aidx] =
7406 T(r.RN(row.node - 1, row.cls - 1) * lqn.callproc_mean[row.aidx]);
7408 callservtcdf[row.aidx] = layer_cdf(e)[row.node - 1][row.cls - 1];
7412 moment3_means_pass(it);
7414 moment3_distribution_pass(it);
7418 void moment3_means_pass(
int it) {
7419 const std::size_t dim = lqn.nidx + lqn.ncalls;
7420 std::vector<T> x(dim + 1, Tzero());
7421 for (std::size_t i = 1; i <= lqn.nidx; ++i) x[i] = residt[i];
7422 for (std::size_t c = 1; c <= lqn.ncalls; ++c) x[lqn.nidx + c] = callresidt[c];
7425 const Matrix<T> Rinv = entry_service_resolvent();
7426 std::vector<T> entry_servt(dim + 1, Tzero());
7427 for (std::size_t i = 1; i <= dim; ++i) {
7429 for (std::size_t j = 1; j <= dim; ++j)
7430 if (Rinv(i, j) != Tzero()) s += Rinv(i, j) * x[j];
7433 for (std::size_t i = 1; i <= lqn.eshift; ++i) entry_servt[i] = Tzero();
7444 for (std::size_t e = 1; e <= lqn.nentries; ++e)
7445 servt[lqn.eshift + e] = entry_servt[lqn.eshift + e];
7448 std::vector<T> entry_residt(dim + 1, Tzero());
7449 for (std::size_t i = lqn.eshift + 1; i <= lqn.eshift + lqn.nentries; ++i) {
7451 for (std::size_t j = 1; j <= dim; ++j)
7452 if (servtmatrix(i, j) != Tzero()) s += servtmatrix(i, j) * x[j];
7453 entry_residt[i] = s;
7456 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7457 const std::size_t eidx = lqn.eshift + e;
7459 const int state = entry_visit_ratio(eidx, ratio);
7460 if (state == 0)
continue;
7462 residt[eidx] = entry_residt[eidx];
7465 servt[eidx] = T(entry_servt[eidx] * ratio);
7466 residt[eidx] = T(entry_residt[eidx] * ratio);
7469 for (
const UpdRow& row : call_map) {
7470 if (row.node <= 1)
continue;
7471 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7474 for (
const UpdRow& row : call_map) {
7475 if (row.node <= 1)
continue;
7476 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7479 callservt[row.aidx] = servt[eidx];
7480 callservtproc[row.aidx] = servtproc[eidx];
7481 }
else if (callservt[row.aidx] > Tzero()) {
7497 void moment3_distribution_pass(
int it) {
7498 if constexpr (!num_traits<T>::has_transcendental) {
7500 "SolverLN: the 'moment3' method fits an APH to a response-time CDF, which needs "
7501 "square roots and a matrix exponential; rerun with --arith double or real");
7503 const std::size_t dim = lqn.nidx + lqn.ncalls;
7504 const Matrix<T> Rinv = entry_service_resolvent();
7507 mam::AphPair<T> zero_law;
7508 zero_law.alpha.push_back(Tone());
7511 for (std::size_t en = 1; en <= lqn.nentries; ++en) {
7512 const std::size_t eidx = lqn.eshift + en;
7513 std::vector<mam::AphPair<T>> seq;
7514 for (std::size_t fitidx = 1; fitidx <= dim; ++fitidx) {
7515 if (!(Rinv(eidx, fitidx) > Tzero()))
continue;
7519 if (fitidx <= lqn.eshift + lqn.nentries)
continue;
7520 const bool is_call = fitidx > lqn.nidx;
7521 const fluid::FluidPassage& curve =
7522 is_call ? callservtcdf[fitidx - lqn.nidx] : servtcdf[fitidx];
7523 double m1 = 0.0, m2 = 0.0, m3 = 0.0;
7524 cdf_moments(curve, m1, m2, m3);
7528 if (!is_call && !lqn.actthink[fitidx].disabled &&
7530 const Distrib<T>& zt = lqn.actthink[fitidx];
7534 m3 = m3 + 3.0 * m2 * t1 + 3.0 * m1 * t2 + t3;
7535 m2 = m2 + 2.0 * m1 * t1 + t2;
7546 num_traits<T>::from_double(m1), num_traits<T>::from_double(m2),
7547 num_traits<T>::from_double(m3), 10u,
7549 const mam::AphPair<T> law = aph_pair_of_map(fit.aph);
7551 double reps = dbl(Rinv(eidx, fitidx));
7554 if (is_call) reps *= dbl(lqn.callproc_mean[fitidx - lqn.nidx]);
7555 const long whole =
static_cast<long>(std::floor(reps));
7556 const double frac = reps -
static_cast<double>(whole);
7557 for (
long q = 0; q < whole; ++q) seq.push_back(law);
7560 num_traits<T>::from_double(frac),
7561 num_traits<T>::from_double(1.0 - frac),
7565 const std::size_t cidx = fitidx - lqn.nidx;
7566 callservt[cidx] = num_traits<T>::from_double(m1);
7569 servt[fitidx] = num_traits<T>::from_double(m1);
7575 servt[eidx] = Tzero();
7579 entryproc[en] = entry_law;
7582 entrycdfrespt[en] = aph_eval_cdf(entry_law);
7590 std::vector<T> x(dim + 1, Tzero());
7591 for (std::size_t i = 1; i <= lqn.nidx; ++i) x[i] = residt[i];
7592 for (std::size_t c = 1; c <= lqn.ncalls; ++c) x[lqn.nidx + c] = callresidt[c];
7593 for (std::size_t en = 1; en <= lqn.nentries; ++en) {
7594 const std::size_t eidx = lqn.eshift + en;
7596 for (std::size_t j = 1; j <= dim; ++j)
7597 if (servtmatrix(eidx, j) != Tzero()) s += servtmatrix(eidx, j) * x[j];
7599 const int state = entry_visit_ratio(eidx, ratio);
7600 if (state == 0)
continue;
7601 residt[eidx] = state == 2 ? T(s * ratio) : s;
7605 for (
const UpdRow& row : call_map) {
7606 if (row.node <= 1)
continue;
7607 const std::size_t eidx = lqn.callpair_dst[row.aidx];
7608 callservt[row.aidx] = servt[eidx];
7615 moment_pass_done =
true;
7627 static mam::AphPair<T> aph_pair_of_map(
const mam::Map<T>& m) {
7628 mam::AphPair<T> out;
7629 const std::size_t n = m.D0.rows();
7631 out.alpha.assign(n, Tzero());
7632 for (std::size_t i = 0; i < n; ++i) {
7634 for (std::size_t j = 0; j < n; ++j) rowsum += m.D1(i, j);
7636 for (std::size_t j = 0; j < n; ++j) out.alpha[j] = T(m.D1(i, j) / rowsum);
7641 out.alpha[0] = Tone();
7649 static LnCdf aph_eval_cdf(
const mam::AphPair<T>& law) {
7653 const double var = m2 - m1 * m1;
7654 const double sigma =
var > 0.0 ? std::sqrt(var) : 0.0;
7655 const double tmax = m1 + 10.0 * sigma;
7656 const std::size_t
P = 500;
7659 for (std::size_t k = 0; k <
P; ++k) {
7660 const double t = tmax *
static_cast<double>(k) /
static_cast<double>(P - 1);
7662 Matrix<T> St(law.S.rows(), law.S.cols(), Tzero());
7663 for (std::size_t i = 0; i < law.S.rows(); ++i)
7664 for (std::size_t j = 0; j < law.S.cols(); ++j)
7665 St(i, j) = T(law.S(i, j) * num_traits<T>::from_double(t));
7668 for (std::size_t i = 0; i < E.rows(); ++i)
7669 for (std::size_t j = 0; j < E.cols(); ++j) surv += law.alpha[i] * E(i, j);
7670 out.cdf[k] = 1.0 - dbl(surv);
7689 std::vector<T> join_excess() {
7690 std::vector<T> excess(lqn.nidx + 1, Tzero());
7691 join_tail.assign(lqn.nidx + 1, Tzero());
7692 std::vector<std::size_t> joined;
7693 for (std::size_t tail = 1; tail <= lqn.nidx; ++tail) {
7694 if (lqn.actpretype[tail] != PrecedenceType::PRE_AND)
continue;
7695 for (std::size_t sx : lqn.graph.succ(tail))
7696 if (sx > lqn.ashift && sx <= lqn.ashift + lqn.nacts) joined.push_back(sx);
7698 std::sort(joined.begin(), joined.end());
7699 joined.erase(std::unique(joined.begin(), joined.end()), joined.end());
7700 if (joined.empty())
return excess;
7702 fj::LqnBranchView<T> view;
7703 view.graph =
Matrix<T>(lqn.nidx, lqn.nidx, Tzero());
7704 for (std::size_t i = 1; i <= lqn.nidx; ++i)
7705 for (
const auto& e : lqn.graph.row[i]) view.graph(i - 1, e.first - 1) = e.second;
7706 view.ashift = lqn.ashift;
7707 view.nacts = lqn.nacts;
7708 view.actposttype.assign(lqn.nidx, 0);
7709 for (std::size_t i = 1; i <= lqn.nidx; ++i)
7710 view.actposttype[i - 1] =
static_cast<int>(lqn.actposttype[i]);
7712 for (std::size_t aidx : joined) {
7713 const std::vector<std::vector<std::size_t>> branches =
7715 if (branches.empty())
continue;
7716 std::vector<T> means;
7717 for (
const auto& br : branches) {
7719 for (std::size_t a : br) {
7723 if (a < lqn.callsof.size())
7724 for (std::size_t cidx : lqn.callsof[a])
7725 if (cidx < lqn.calltype.size() && lqn.calltype[cidx] == CallType::SYNC
7726 && cidx < callresidt.size())
7727 s += callresidt[cidx];
7731 if (means.size() == 1)
continue;
7732 std::size_t quorum = means.size();
7733 if (lqn.actquorum[aidx] >= 1 && lqn.actquorum[aidx] <= means.size())
7734 quorum = lqn.actquorum[aidx];
7735 std::vector<T> vars;
7736 for (
const T& m2 : means) vars.push_back(T(m2 * m2));
7738 for (
const T& m2 : means) serial += m2;
7739 if constexpr (num_traits<T>::has_transcendental) {
7741 excess[aidx] = T(q.m - serial);
7742 if (quorum < means.size()) {
7745 if (all.m > q.m) join_tail[aidx] = T(all.m - q.m);
7749 "SolverLN: the AND-join completion time is a k-th order statistic fitted "
7750 "through a three-point distribution, which needs a square root; use the "
7751 "double or real backend for a model with an AND join");
7758 void resolve_entry_service() {
7759 const std::size_t dim = lqn.nidx + lqn.ncalls;
7760 std::vector<T> x(dim + 1, Tzero());
7761 for (std::size_t i = 1; i <= lqn.nidx; ++i) x[i] = residt[i];
7762 for (std::size_t c = 1; c <= lqn.ncalls; ++c) x[lqn.nidx + c] = callresidt[c];
7763 std::vector<T> entry_servt(dim + 1, Tzero());
7764 for (std::size_t i = 1; i <= dim; ++i) {
7766 for (std::size_t j = 1; j <= dim; ++j)
7767 if (servtmatrix(i, j) != Tzero()) s += servtmatrix(i, j) * x[j];
7773 const std::vector<T> excess = join_excess();
7774 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7775 const std::size_t eidx = lqn.eshift + e;
7776 for (std::size_t aidx = 1; aidx <= lqn.nidx; ++aidx) {
7777 if (excess[aidx] == Tzero())
continue;
7778 if (servtmatrix(eidx, aidx) > Tzero())
7779 entry_servt[eidx] = T(entry_servt[eidx] + excess[aidx]);
7781 if (entry_servt[eidx] < Tzero()) entry_servt[eidx] = Tzero();
7783 for (std::size_t aidx = 1; aidx <= lqn.nidx; ++aidx)
7784 if (join_tail[aidx] > Tzero() && servtmatrix(eidx, aidx) > Tzero())
7785 entry_servt[eidx] = T(entry_servt[eidx] + join_tail[aidx]);
7795 std::unordered_map<std::size_t, double> charge_su;
7796 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7797 const std::size_t tidx = lqn.parent[lqn.eshift + e];
7798 if (charge_su.count(tidx))
continue;
7800 for (std::size_t e2 = 1; e2 <= lqn.nentries; ++e2)
7801 if (lqn.parent[lqn.eshift + e2] == tidx) S += dbl(entry_servt[lqn.eshift + e2]);
7802 charge_su[tidx] = setup_charge(tidx, S);
7804 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7805 const std::size_t eidx = lqn.eshift + e;
7806 const double c = charge_su[lqn.parent[eidx]];
7808 entry_servt[eidx] = T(entry_servt[eidx] + num_traits<T>::from_double(c));
7814 std::vector<T> x2(dim + 1, Tzero());
7815 for (std::size_t a = 1; a <= lqn.nacts; ++a)
7816 if (lqn.actphase[a] > 1) x2[lqn.ashift + a] = x[lqn.ashift + a];
7817 for (std::size_t c = 1; c <= lqn.ncalls; ++c) {
7818 const std::size_t src = lqn.callpair_src[c];
7819 if (src > lqn.ashift && src <= lqn.ashift + lqn.nacts && lqn.actphase[src - lqn.ashift] > 1)
7820 x2[lqn.nidx + c] = x[lqn.nidx + c];
7822 entry_servt_ph2.assign(dim + 1, Tzero());
7823 for (std::size_t i = lqn.eshift + 1; i <= dim; ++i) {
7825 for (std::size_t j = 1; j <= dim; ++j)
7826 if (servtmatrix(i, j) != Tzero()) s2 += servtmatrix(i, j) * x2[j];
7827 entry_servt_ph2[i] = s2;
7830 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7831 const std::size_t eidx = lqn.eshift + e;
7832 for (std::size_t aidx = 1; aidx <= lqn.nidx; ++aidx)
7833 if (join_tail[aidx] > Tzero() && servtmatrix(eidx, aidx) > Tzero())
7834 entry_servt_ph2[eidx] = T(entry_servt_ph2[eidx] + join_tail[aidx]);
7836 entry_servt_last = entry_servt;
7841 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
7842 const std::size_t eidx = lqn.eshift + e;
7843 const std::size_t tidx = lqn.parent[eidx];
7844 const std::size_t hidx = lqn.parent[tidx];
7845 if (ignore[tidx] || ignore[hidx])
continue;
7846 if (idxhash[hidx] < 0)
continue;
7847 const bool has_sync = lqn.issynccaller.any_col(eidx);
7849 servt[eidx] = entry_servt[eidx];
7850 residt[eidx] = entry_servt[eidx];
7853 const std::size_t hl = std::size_t(idxhash[hidx]);
7854 const qn::Layer<T>& L = ensemble[hl];
7855 const LayerResult<T>& r = results.back()[hl];
7856 T task_tput = Tzero(), entry_tput = Tzero();
7857 for (
const auto& kv : L.attr_tasks)
7858 if (kv.second == tidx) task_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7859 for (
const auto& kv : L.attr_entries)
7860 if (kv.second == eidx) entry_tput += r.TN(L.clientIdx - 1, kv.first - 1);
7862 servt[eidx] = T(entry_servt[eidx] * task_tput / entry_tput);
7863 residt[eidx] = servt[eidx];
7867 entryvisits[eidx] = T(entry_tput / task_tput);
7869 servt[eidx] = entry_servt[eidx];
7870 residt[eidx] = entry_servt[eidx];
7886 bool layer_takes_interlock(std::size_t e)
const {
7887 return opt.layer_solver ==
"mva" && e < ensemble.size() &&
7903 std::vector<std::vector<double>> build_layer_interlock(std::size_t e,
7904 const std::vector<std::size_t>& hts,
7905 const std::vector<T>& prIL,
7906 const std::vector<T>& PrIL)
const {
7907 const qn::Layer<T>& L = ensemble[e];
7908 const std::size_t R = L.nclasses;
7909 std::vector<double> cls_ir(R, 0.0);
7910 std::vector<double> cls_pr(R, 0.0);
7911 auto stamp = [&](std::size_t classIdx, std::size_t tidx) {
7912 if (classIdx < 1 || classIdx > R)
return;
7913 for (std::size_t i = 0; i < hts.size(); ++i)
7914 if (hts[i] == tidx) {
7915 cls_ir[classIdx - 1] = dbl(prIL[i]);
7916 cls_pr[classIdx - 1] = dbl(PrIL[i]);
7919 for (
const auto& a : L.attr_tasks) stamp(a.first, a.second);
7920 for (
const auto& a : L.attr_entries) stamp(a.first, lqn.parent[a.second]);
7921 for (
const auto& a : L.attr_activities) stamp(a.first, lqn.parent[a.second]);
7922 for (
const auto& a : L.attr_calls) stamp(a[0], lqn.parent[a[2]]);
7924 std::vector<std::vector<double>> IL(R, std::vector<double>(R, 0.0));
7926 for (std::size_t r = 0; r < R; ++r) {
7928 for (std::size_t sIl = 0; sIl < R; ++sIl) {
7930 IL[r][sIl] = cls_pr[sIl] * cls_ir[sIl] * cls_ir[r];
7934 return any ? IL : std::vector<std::vector<double>>();
7947 std::pair<T, T> interlock_prob(std::size_t client_tidx, std::size_t server_idx,
7948 bool isProcessorHost)
const {
7949 const std::vector<std::size_t>& common = il_common_entries[server_idx];
7950 const double nsrc = il_num_sources[server_idx];
7951 if (nsrc == 0.0 || common.empty())
return std::make_pair(Tzero(), Tzero());
7952 const std::vector<std::size_t>& allsrc = il_src_all[server_idx];
7953 T sum_flow = Tzero();
7954 T sum_pril = Tzero();
7955 for (std::size_t ce : common) {
7956 const std::size_t srcTask = lqn.parent[ce];
7957 const std::size_t cen = ce - lqn.eshift;
7959 double m_src = lqn.mult[srcTask];
7960 if (!std::isfinite(m_src) || m_src < 1.0) m_src = 1.0;
7961 double m_eff = m_src;
7962 if (isProcessorHost) m_eff = (m_src > 3.0) ? (m_src + m_src) : (m_src * m_src);
7963 for (std::size_t dst : lqn.entriesof[client_tidx]) {
7964 const std::size_t dn = dst - lqn.eshift;
7965 if (dn < 1 || dn > lqn.nentries)
continue;
7966 if (!(il_all(cen, dn) > Tzero()))
continue;
7967 T ce_tput = tput[ce];
7969 ce_tput = tput[lqn.actsof[ce][0]];
7973 if (std::find(allsrc.begin(), allsrc.end(), srcTask) != allsrc.end()) {
7974 const T contrib = T(ce_tput * il_all(cen, dn));
7975 sum_flow += contrib;
7976 sum_pril += T(contrib / num_traits<T>::from_double(m_eff));
7980 T client_tput = tput[client_tidx];
7982 for (std::size_t e : lqn.entriesof[client_tidx]) {
7985 et = tput[lqn.actsof[e][0]];
7986 client_tput = T(client_tput + et);
7990 return std::make_pair(Tzero(), Tzero());
7991 const T flow = sum_flow < client_tput ? sum_flow : client_tput;
7992 T IR = T(flow / client_tput);
7993 if (IR > Tone()) IR = Tone();
7994 if (dbl(IR) < 0.0) IR = Tzero();
7997 if (pr > Tone()) pr = Tone();
7998 if (dbl(pr) < 0.0) pr = Tzero();
7999 return std::make_pair(IR, pr);
8002 void update_populations(
int) {
8003 const std::vector<T> residt_orig = residt;
8004 const std::vector<T> callresidt_orig = callresidt;
8005 bool adjusted =
false;
8009 layer_interlock.assign(ensemble.size(), {});
8016 std::vector<bool> il_in_layer(lqn.nidx + 1,
false);
8017 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
8018 const std::size_t server_tidx = lqn.tshift + t;
8019 if (server_tidx >= il_common_entries.size() || il_common_entries[server_tidx].empty())
continue;
8020 if (!(idxhash[server_tidx] >= 0) || !layer_takes_interlock(std::size_t(idxhash[server_tidx])))
8022 const std::size_t e = std::size_t(idxhash[server_tidx]);
8023 std::vector<std::size_t> cts;
8024 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
8025 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
8026 if (lqn.parent[lqn.callpair_dst[cidx]] != server_tidx)
continue;
8027 const std::size_t ctidx = lqn.parent[lqn.callpair_src[cidx]];
8028 if (std::find(cts.begin(), cts.end(), ctidx) == cts.end()) cts.push_back(ctidx);
8030 std::vector<T> prIL(cts.size(), Tzero()), PrIL(cts.size(), Tzero());
8031 for (std::size_t i = 0; i < cts.size(); ++i) {
8032 const std::pair<T, T> ilp = interlock_prob(cts[i], server_tidx,
false);
8033 prIL[i] = ilp.first;
8034 PrIL[i] = ilp.second;
8036 il_in_layer[server_tidx] =
true;
8037 layer_interlock[e] = build_layer_interlock(e, cts, prIL, PrIL);
8040 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
8041 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
8042 const std::size_t dst = lqn.callpair_dst[cidx];
8043 const std::size_t server_tidx = lqn.parent[dst];
8044 std::size_t server = 0;
8045 if (server_tidx <= NT() && !il_common_entries[server_tidx].empty()) {
8046 server = server_tidx;
8047 }
else if (server_tidx > lqn.tshift) {
8048 const std::size_t h = lqn.parent[server_tidx];
8049 if (h >= 1 && h <= NT() && !il_common_entries[h].empty()) server = h;
8051 if (server == 0 || il_in_layer[server])
continue;
8057 if (server <= lqn.nhosts && idxhash[server] >= 0 &&
8058 layer_takes_interlock(std::size_t(idxhash[server])))
8060 const std::size_t client_tidx = lqn.parent[lqn.callpair_src[cidx]];
8064 const std::pair<T, T> ilp = interlock_prob(client_tidx, server,
false);
8065 const T prIL = T(ilp.first * ilp.second);
8067 const T S = servt[dst];
8068 const T cm = lqn.callproc_mean[cidx];
8069 if (!(cm > Tzero()) || !(callservt[cidx] > Tzero()))
continue;
8070 const T RN = T(callservt[cidx] / cm);
8071 const T W = RN > S ? T(RN - S) : Tzero();
8073 const T RN_adj = T(S + (Tone() - prIL) * W);
8074 const T scale = T(RN_adj / RN);
8075 callservt[cidx] = T(callservt[cidx] * scale);
8076 callresidt[cidx] = T(callresidt[cidx] * scale);
8077 if (callservt[cidx] > Tzero())
8082 for (std::size_t h = 1; h <= lqn.nhosts; ++h) {
8083 if (il_common_entries[h].empty())
continue;
8084 const std::vector<std::size_t>& hts = lqn.tasksof[h];
8085 std::vector<T> prIL(hts.size(), Tzero()), PrIL(hts.size(), Tzero()),
8086 tutil(hts.size(), Tzero());
8087 for (std::size_t i = 0; i < hts.size(); ++i) {
8089 const std::pair<T, T> ilp = interlock_prob(hts[i], h,
true);
8090 prIL[i] = ilp.first;
8091 PrIL[i] = ilp.second;
8092 for (std::size_t e : lqn.entriesof[hts[i]])
8093 for (std::size_t a : lqn.actsof[e]) tutil[i] += tput[a] * lqn.hostdem[a].mean;
8095 T Utot = Tzero(), Uil = Tzero();
8096 for (std::size_t i = 0; i < hts.size(); ++i) {
8102 const T frac = T(Uil / Utot);
8110 if (idxhash[h] >= 0 && layer_takes_interlock(std::size_t(idxhash[h]))) {
8111 const std::size_t e = std::size_t(idxhash[h]);
8112 layer_interlock[e] = build_layer_interlock(e, hts, prIL, PrIL);
8116 for (std::size_t i = 0; i < hts.size(); ++i) {
8124 const T eff = T(prIL[i] * PrIL[i] * frac);
8125 for (std::size_t e : lqn.entriesof[hts[i]])
8126 for (std::size_t a : lqn.actsof[e]) {
8130 const T D = lqn.hostdem[a].mean;
8131 const T R = servt[a];
8133 residt[a] = T(residt[a] * (D + (Tone() - eff) * (R - D)) / R);
8140 if (!adjusted)
return;
8141 const std::size_t dim = lqn.nidx + lqn.ncalls;
8142 auto esum = [&](
const std::vector<T>& rs,
const std::vector<T>& cr, std::size_t i) {
8144 for (std::size_t j = 1; j <= dim; ++j) {
8145 if (servtmatrix(i, j) == Tzero())
continue;
8146 s += servtmatrix(i, j) * (j <= lqn.nidx ? rs[j] : cr[j - lqn.nidx]);
8154 std::vector<bool> isph2(dim + 1,
false);
8156 for (std::size_t a = 1; a <= lqn.nacts; ++a)
8157 if (lqn.actphase[a] > 1) isph2[lqn.ashift + a] =
true;
8158 for (std::size_t c = 1; c <= lqn.ncalls; ++c) {
8159 const std::size_t src = lqn.callpair_src[c];
8160 if (src > lqn.ashift && src <= lqn.ashift + lqn.nacts && lqn.actphase[src - lqn.ashift] > 1)
8161 isph2[lqn.nidx + c] =
true;
8164 auto esum2 = [&](
const std::vector<T>& rs,
const std::vector<T>& cr, std::size_t i) {
8166 for (std::size_t j = 1; j <= dim; ++j) {
8167 if (!isph2[j] || servtmatrix(i, j) == Tzero())
continue;
8168 s += servtmatrix(i, j) * (j <= lqn.nidx ? rs[j] : cr[j - lqn.nidx]);
8172 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
8173 const std::size_t eidx = lqn.eshift + e;
8174 const T oldv = esum(residt_orig, callresidt_orig, eidx);
8176 const T ratio = T(esum(residt, callresidt, eidx) / oldv);
8178 const T old2 = esum2(residt_orig, callresidt_orig, eidx);
8179 const T new2 = esum2(residt, callresidt, eidx);
8180 const T old1 = T(oldv - old2);
8181 const T new1 = T(esum(residt, callresidt, eidx) - new2);
8184 servt_ph1[eidx] = T(servt_ph1[eidx] * r1);
8185 servt_ph2[eidx] = T(servt_ph2[eidx] * r2);
8186 servt[eidx] = T(servt_ph1[eidx] + servt_ph2[eidx]);
8190 const std::size_t tidx = lqn.parent[eidx];
8191 if (lqn.isref[tidx] || !lqn.issynccaller.any_col(eidx))
8192 residt[eidx] = servt[eidx];
8194 residt[eidx] = T(servt_ph1[eidx] + prOvertake[e] * servt_ph2[eidx]);
8205 if (!moment_pass_done) {
8206 servt[eidx] = T(servt[eidx] * ratio);
8209 residt[eidx] = T(residt[eidx] * ratio);
8225 T ref_think_time(std::size_t tidx)
const {
8226 if (tidx >= lqn.isref.size() || !lqn.isref[tidx])
return Tzero();
8227 if (lqn.think[tidx].disabled)
return Tzero();
8228 return lqn.think[tidx].mean;
8237 T phase2_tail(std::size_t tidx)
const {
8239 if (!has_phase2)
return tail;
8242 for (std::size_t eidx : lqn.entriesof[tidx]) {
8243 if (servt_ph2[eidx] <= fine)
continue;
8245 if (w <= fine) w = Tone();
8246 const T d = T(servt[eidx] - residt[eidx]);
8247 tail += T(w * (d > Tzero() ? d : Tzero()));
8250 if (wtot > fine) tail = T(tail / wtot);
8254 void update_think_times(
int it) {
8257 if (is_ph_encoding()) {
8258 update_think_times_ph(it);
8262 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
8263 const std::size_t tidx = lqn.tshift + t;
8265 const T ztask = ref_think_time(tidx);
8266 if (idxhash[tidx] < 0) {
8270 const double arvrate = open_arrival_rate_of(tidx);
8273 for (std::size_t c = 1; c <= NT(); ++c) nja = std::max(nja, njobs(tidx, c));
8274 if (!(nja > 0.0)) nja = lqn.maxmult[tidx];
8276 for (std::size_t eidx : lqn.entriesof[tidx]) {
8277 for (std::size_t aidx : lqn.actsof[eidx])
8278 if (!std::isnan(dbl(residt[aidx]))) hres += residt[aidx];
8279 hres += sync_call_residt_of(lqn.actsof[eidx]);
8282 T za = T(num_traits<T>::from_double(nja / arvrate) - hres - ztask);
8283 if (za < floora) za = floora;
8284 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
8285 const T om = num_traits<T>::from_double(relax_omega);
8286 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
8287 za = T(om * za + om1 * thinkt_prev_v[tidx]);
8289 tput[tidx] = num_traits<T>::from_double(arvrate);
8291 thinkt_prev[tidx] = dbl(za);
8292 thinkt_prev_v[tidx] = za;
8300 const std::size_t e = std::size_t(idxhash[tidx]);
8301 const qn::Layer<T>& L = ensemble[e];
8302 const LayerResult<T>& r = results.back()[e];
8304 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
8306 const std::size_t ts = station_idx_of(L, tidx);
8308 for (std::size_t k = 0; k < L.nclasses; ++k) tp += r.TN(ts - 1, k);
8309 tput[tidx] = T(num_traits<T>::from_double(lqn.repl[tidx]) * tp);
8311 util[tidx] = thread_busy_fraction(L, ts, r,
false);
8315 const double nrep = std::max(1.0, lqn.repl[tidx]);
8316 const T xcyc = T(tput[tidx] / num_traits<T>::from_double(nrep));
8317 if (nrep > 1.0 && std::isfinite(lqn.maxmult[tidx]) && lqn.maxmult[tidx] > 0.0) nj = lqn.maxmult[tidx];
8319 if (lqn.sched[tidx] == SchedStrategy::INF) {
8321 raw = xcyc == Tzero()
8323 : T((num_traits<T>::from_double(nj) - util[tidx]) / xcyc - ztask);
8325 const T om = util[tidx] > Tone() ? T(util[tidx] - Tone()) : T(Tone() - util[tidx]);
8326 raw = xcyc == Tzero()
8328 : T(num_traits<T>::from_double(nj) * om / xcyc - ztask);
8331 thinkt[tidx] = raw < floorv ? floorv : raw;
8335 if (lnmethod !=
"flat.cs") {
8336 const T lessz = T(thinkt[tidx] - phase2_tail(tidx));
8337 thinkt[tidx] = lessz < floorv ? floorv : lessz;
8349 const double c = setup_charge(tidx);
8351 const T withc = T(thinkt[tidx] + num_traits<T>::from_double(c));
8352 thinkt[tidx] = withc < floorv ? floorv : withc;
8356 if (relax_omega < 1.0 && it > 1 && !std::isnan(thinkt_prev[tidx])) {
8357 const double rawd = dbl(thinkt[tidx]);
8359 thinkt_prev[tidx] = rawd;
8360 thinkt_prev_v[tidx] = thinkt[tidx];
8362 const T om = num_traits<T>::from_double(relax_omega);
8363 const T om1 = num_traits<T>::from_double(1.0 - relax_omega);
8364 thinkt[tidx] = T(om * thinkt[tidx] + om1 * thinkt_prev_v[tidx]);
8366 thinkt_prev[tidx] = dbl(thinkt[tidx]);
8367 thinkt_prev_v[tidx] = thinkt[tidx];
8375 void update_layers(
int it) {
8378 if (is_ph_encoding()) {
8379 update_layers_ph(it);
8382 const bool elevator = (it % 2) == 1;
8383 const std::size_t nt = thinkt_map.size();
8384 for (std::size_t r = 0; r < nt; ++r) {
8385 const UpdRow& row = thinkt_map[elevator ? nt - 1 - r : r];
8386 qn::Layer<T>& L = ensemble[std::size_t(idxhash[row.idx])];
8387 if (row.aidx <= NT() && opt.interlocking &&
8388 L.classes[row.cls - 1].type == JobClassType::CLOSED)
8389 L.classes[row.cls - 1].population = njobs(row.aidx, row.idx);
8390 if (row.node == L.clientIdx) {
8391 if (lqn.type[row.aidx] == LqnElement::TASK) {
8392 if (lqn.sched[row.aidx] != SchedStrategy::REF) {
8393 if (!thinktproc[row.aidx].disabled)
8394 L.set_service(row.node, row.cls, thinktproc[row.aidx]);
8396 L.set_service(row.node, row.cls, servtproc[row.aidx]);
8399 L.set_service(row.node, row.cls, servtproc[row.aidx]);
8402 L.set_service(row.node, row.cls, servtproc[row.aidx]);
8405 const std::size_t nc = call_map.size();
8406 for (std::size_t r = 0; r < nc; ++r) {
8407 const UpdRow& row = call_map[elevator ? nc - 1 - r : r];
8408 qn::Layer<T>& L = ensemble[std::size_t(idxhash[row.idx])];
8409 if (row.node == L.clientIdx) {
8410 L.set_service(row.node, row.cls, callservtproc[row.aidx]);
8412 const std::size_t eidx = lqn.callpair_dst[row.aidx];
8419 L.set_service(row.node, row.cls, servtproc[eidx]);
8430 if (interlockMethod ==
"refpath") update_ref_path_stages(it);
8431 for (
const UpdRow& row : arv_call_map) {
8432 qn::Layer<T>& L = ensemble[std::size_t(idxhash[row.idx])];
8433 const Distrib<T>& d = tputproc[lqn.callpair_src[row.aidx]];
8434 if (!d.disabled) L.set_service(row.node, row.cls, d);
8448 void update_ref_path_stages(
int it) {
8449 if (refpath_map.empty())
return;
8450 const std::size_t nkeys = refpath_keys.size();
8451 std::vector<T> stage(nkeys, Tzero());
8452 for (std::size_t r = 0; r < refpath_map.size(); ++r) {
8453 const RefPathRow& row = refpath_map[r];
8457 term = residt[row.elem];
8462 v = entryvisits[row.fromentry];
8463 term = T(callresidt[row.elem] / v);
8467 term = thread_wait(row.elem);
8470 if (!std::isfinite(dbl(term))) term = Tzero();
8471 stage[refpath_group[r]] = T(stage[refpath_group[r]] + term * num_traits<T>::from_double(row.sign));
8473 const double omega = relax_omega;
8474 for (std::size_t k = 0; k < nkeys; ++k) {
8475 if (stage[k] < Tzero()) stage[k] = Tzero();
8477 if (omega < 1.0 && it > 1 && !std::isnan(refpath_stage_prev[k])) {
8478 T prevS = refpath_stage_prev_v[k];
8481 stage[k] = T(num_traits<T>::from_double(omega) * stage[k] +
8482 num_traits<T>::from_double(1.0 - omega) * prevS);
8484 refpath_stage_prev[k] = dbl(stage[k]);
8485 refpath_stage_prev_v[k] = stage[k];
8486 qn::Layer<T>& L = ensemble[std::size_t(idxhash[refpath_keys[k][0]])];
8501 T thread_wait(std::size_t tidx)
const {
8502 if (tidx < 1 || tidx > lqn.nidx)
return Tzero();
8503 if (lqn.sched[tidx] == SchedStrategy::INF || !std::isfinite(lqn.maxmult[tidx]))
return Tzero();
8504 if (idxhash[tidx] < 0 || results.empty())
return Tzero();
8505 const std::size_t e = std::size_t(idxhash[tidx]);
8506 const qn::Layer<T>& L = ensemble[e];
8507 const LayerResult<T>& r = results.back()[e];
8508 const std::size_t ks = station_idx_of(L, tidx);
8510 for (std::size_t c = 0; c < L.nclasses; ++c) Qtot += r.QN(ks - 1, c);
8511 const T Btot = T(num_traits<T>::from_double(lqn.maxmult[tidx]) * util[tidx]);
8512 const T Xtot = T(tput[tidx] / num_traits<T>::from_double(std::max(1.0, lqn.repl[tidx])));
8514 T d = T(Qtot - Btot);
8533 T region_wait(std::size_t e, std::size_t cls)
const {
8534 const qn::Layer<T>& L = ensemble[e];
8535 if (L.regions.empty() || results.empty())
return Tzero();
8536 const LayerResult<T>& r = results.back()[e];
8537 const std::size_t k = cls - 1;
8538 std::size_t c = L.nchains;
8539 for (std::size_t cc = 0; cc < L.nchains; ++cc)
8540 if (L.chains[cc][k]) c = cc;
8541 if (c == L.nchains)
return Tzero();
8545 std::size_t rs = L.serverIdx;
8546 for (std::size_t i = 0; i < L.regions[0].members.size(); ++i)
8547 if (L.regions[0].members[i]) { rs = i + 1;
break; }
8550 T inside = Tzero(), tput_srv = Tzero();
8551 for (std::size_t j = 0; j < L.nclasses; ++j) {
8552 if (!L.chains[c][j])
continue;
8553 const double p = L.classes[j].population;
8554 if (!std::isfinite(p))
return Tzero();
8556 for (std::size_t i = 0; i < L.nstations; ++i) inside += r.QN(i, j);
8557 tput_srv += r.TN(rs - 1, j);
8559 const T deficit = T(num_traits<T>::from_double(pop) - inside);
8560 if (!(deficit > Tzero()) || !(tput_srv > Tzero()))
return Tzero();
8561 return T(deficit / tput_srv);
8565 void update_routing_probabilities(
int) {
8566 for (std::size_t u = 0; u < unique_route_idx.size(); ++u) {
8569 const std::size_t idx = unique_route_idx[unique_route_idx.size() - 1 - u];
8570 qn::Layer<T>& L = ensemble[std::size_t(idxhash[idx])];
8571 bool updated =
false;
8572 for (
const RouteRow& r : route_map) {
8573 if (r.idx != idx)
continue;
8574 if (idxhash[r.tidx_caller] < 0)
continue;
8575 const std::size_t cl = std::size_t(idxhash[r.tidx_caller]);
8576 const qn::Layer<T>& CL = ensemble[cl];
8577 const LayerResult<T>& cr = results.back()[cl];
8580 const std::size_t cs = station_idx_of(CL, r.tidx_caller);
8582 for (std::size_t k = 0; k < CL.nclasses; ++k) Xtot += cr.TN(cs - 1, k);
8583 if (!(Xtot > Tzero()))
continue;
8584 T entry_tput = Tzero();
8585 for (
const auto& a : CL.attr_calls)
8587 entry_tput += cr.TN(station_idx_of(CL, lqn.parent[a[3]]) - 1, a[0] - 1);
8588 L.set_route(r.cfrom, r.cto, r.nodefrom, r.nodeto, T(entry_tput / Xtot));
8591 if (updated) L.refresh_chains();
8610 void require_transient_ready()
const {
8611 if (opt.layer_solver !=
"fluid")
8613 "SolverLN: the layered transient is the transient OF EACH LAYER, which only the "
8614 "fluid layer solver has; rebuild the ensemble with layer_solver 'fluid'");
8618 bool has_finite_horizon()
const {
8619 return std::isfinite(opt.timespan_end) && opt.timespan_end > 0.0;
8624 std::vector<std::vector<std::vector<double>>> Q, U, Tp, R;
8631 void run_layer_transient(std::size_t e,
const std::vector<FluidRateSched>& sched,
8632 LnTranLayer& block, TranTraj& traj) {
8633 qn::Layer<T>& L = ensemble[e];
8635 fluid::FluidOptions fo = opt.layer_fluid;
8636 fo.rate_sched = sched;
8642 if (e < layer_tran_init.size() && !layer_tran_init[e].empty())
8643 fo.init_sol = layer_tran_init[e];
8648 const double t_end =
8650 const std::vector<fluid::FluidTranPoint> pts =
8651 detail::ln_fluid_transient(L, fo, t_end, opt.tran_points, opt.tran_grid);
8652 const std::size_t M = L.nstations, K = L.nclasses,
P = pts.size();
8654 auto alloc = [&](std::vector<std::vector<std::vector<double>>>& A) {
8655 A.assign(M, std::vector<std::vector<double>>(K, std::vector<double>(P, 0.0)));
8664 for (std::size_t p = 0; p <
P; ++p) {
8665 block.t[p] = pts[p].t;
8666 for (std::size_t i = 0; i < M; ++i)
8667 for (std::size_t r = 0; r < K; ++r) {
8668 const double q = pts[p].QN(i, r), u = pts[p].UN(i, r), x = pts[p].TN(i, r);
8669 block.QN[i][r][p] = q;
8670 block.UN[i][r][p] = u;
8671 block.TN[i][r][p] = x;
8672 traj.Q[i][r][p] = q;
8673 traj.U[i][r][p] = u;
8674 traj.Tp[i][r][p] = x;
8686 LnTranSolution tran_avg_decoupled() {
8687 require_transient_ready();
8688 if (results.empty()) iterate();
8690 out.mode =
"decoupled";
8691 out.layers.resize(ensemble.size());
8692 for (std::size_t e = 0; e < ensemble.size(); ++e) {
8694 run_layer_transient(e, std::vector<FluidRateSched>(), out.layers[e], tj);
8716 LnTranSolution tran_avg_coupled() {
8717 require_transient_ready();
8722 if (!has_finite_horizon())
return tran_avg_decoupled();
8723 if (results.empty()) iterate();
8724 const std::size_t E = ensemble.size();
8727 out.mode =
"coupled";
8728 out.layers.resize(E);
8729 std::vector<TranTraj> traj(E), prev(E);
8730 for (std::size_t e = 0; e < E; ++e)
8731 run_layer_transient(e, std::vector<FluidRateSched>(), out.layers[e], traj[e]);
8732 const std::vector<double> tgrid = out.layers.empty() ? std::vector<double>() : out.
layers[0].t;
8734 for (
long iter = 1; iter <= opt.ln_transient_iter_max; ++iter) {
8736 const std::vector<std::vector<FluidRateSched>> sched =
8737 build_rate_sched(recompute_demand(traj, tgrid), tgrid);
8738 for (std::size_t e = 0; e < E; ++e)
8739 run_layer_transient(e, sched[e], out.layers[e], traj[e]);
8741 for (std::size_t e = 0; e < E; ++e)
8742 for (std::size_t i = 0; i < traj[e].Q.size(); ++i)
8743 for (std::size_t r = 0; r < traj[e].Q[i].size(); ++r)
8744 for (std::size_t p = 0; p < traj[e].Q[i][r].size(); ++p)
8745 gap = std::max(gap, std::fabs(traj[e].Q[i][r][p] - prev[e].Q[i][r][p]));
8746 out.iterations = iter;
8748 if (gap < opt.ln_transient_tol)
break;
8755 std::map<std::size_t, std::vector<double>> thinkt;
8756 std::map<std::size_t, std::vector<double>> callservt;
8767 TranDemand recompute_demand(
const std::vector<TranTraj>& traj,
8768 const std::vector<double>& tgrid)
const {
8770 const std::size_t ng = tgrid.size();
8772 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
8773 const std::size_t tidx = lqn.tshift + t;
8774 if (idxhash[tidx] < 0 || lqn.isref[tidx])
continue;
8775 const std::size_t e = std::size_t(idxhash[tidx]);
8776 const qn::Layer<T>& L = ensemble[e];
8777 const std::size_t s = station_idx_of(L, tidx) - 1;
8779 for (std::size_t c = 1; c <= NT(); ++c) nj = std::max(nj, njobs(tidx, c));
8781 const double userthink = dbl(ref_think_time(tidx));
8782 std::vector<double> tk(ng, 0.0);
8783 for (std::size_t p = 0; p < ng; ++p) {
8784 double U = 0.0, X = 0.0;
8785 for (std::size_t r = 0; r < L.nclasses; ++r) {
8786 U += traj[e].U[s][r][p];
8787 X += traj[e].Tp[s][r][p];
8790 double v = lqn.sched[tidx] == SchedStrategy::INF
8791 ? (nj - U) / Xs - userthink
8792 : nj * std::fabs(1.0 - U) / Xs - userthink;
8794 tk[p] = v + userthink;
8796 out.thinkt[tidx] = tk;
8799 for (std::size_t cidx = 1; cidx <= lqn.ncalls; ++cidx) {
8800 if (lqn.calltype[cidx] != CallType::SYNC)
continue;
8801 const std::size_t eidx = lqn.callpair_dst[cidx];
8802 const std::size_t tidx = lqn.parent[eidx];
8803 if (tidx > NT() || idxhash[tidx] < 0)
continue;
8804 const std::size_t e = std::size_t(idxhash[tidx]);
8805 const qn::Layer<T>& L = ensemble[e];
8806 const std::size_t s = station_idx_of(L, tidx) - 1;
8807 std::vector<double> Rc(ng, 0.0);
8809 for (std::size_t r = 0; r < L.nclasses; ++r) {
8810 if (L.classes[r].attr_kind !=
int(LqnElement::ENTRY))
continue;
8811 if (L.classes[r].attr_idx != eidx)
continue;
8813 for (std::size_t p = 0; p < ng; ++p) Rc[p] += traj[e].R[s][r][p];
8818 for (std::size_t r = 0; r < L.nclasses; ++r)
8819 for (std::size_t p = 0; p < ng; ++p) Rc[p] += traj[e].R[s][r][p];
8821 const double cm = dbl(lqn.callproc_mean[cidx]);
8822 for (std::size_t p = 0; p < ng; ++p) Rc[p] *= cm;
8823 out.callservt[cidx] = Rc;
8839 std::vector<std::vector<FluidRateSched>> build_rate_sched(
8840 const TranDemand& demand,
const std::vector<double>& tgrid)
const {
8841 std::vector<std::vector<FluidRateSched>> out(ensemble.size());
8842 const bool want_think =
8843 opt.ln_transient_channels ==
"both" || opt.ln_transient_channels ==
"thinkt";
8844 const bool want_call =
8845 opt.ln_transient_channels ==
"both" || opt.ln_transient_channels ==
"callservt";
8847 auto add = [&](std::size_t e, std::size_t station, std::size_t cls,
8848 const std::vector<double>& d) {
8849 if (d.empty())
return;
8850 const double dend = d.back();
8855 const double cap = 20.0;
8860 s.rates.resize(d.size());
8861 for (std::size_t p = 0; p < d.size(); ++p) {
8862 const double v = std::min(std::max(d[p], dend / cap), dend * cap);
8863 s.rates[p] = 1.0 / v;
8865 s.nominal = 1.0 / dend;
8866 out[e].push_back(s);
8870 for (
const UpdRow& row : thinkt_map) {
8871 if (idxhash[row.idx] < 0)
continue;
8872 const std::size_t e = std::size_t(idxhash[row.idx]);
8873 if (row.node != ensemble[e].clientIdx)
continue;
8874 if (lqn.type[row.aidx] != LqnElement::TASK)
continue;
8875 if (lqn.sched[row.aidx] == SchedStrategy::REF)
continue;
8876 const auto it = demand.thinkt.find(row.aidx);
8877 if (it == demand.thinkt.end())
continue;
8878 add(e, row.node, row.cls, it->second);
8881 for (
const UpdRow& row : call_map) {
8882 if (idxhash[row.idx] < 0)
continue;
8883 const std::size_t e = std::size_t(idxhash[row.idx]);
8884 if (row.node != ensemble[e].clientIdx)
continue;
8885 const auto it = demand.callservt.find(row.aidx);
8886 if (it == demand.callservt.end())
continue;
8887 add(e, row.node, row.cls, it->second);
8893 std::size_t bound_activity_of(std::size_t eidx)
const {
8894 for (std::size_t sx : lqn.graph.succ(eidx))
8895 if (sx > lqn.ashift)
return sx;
8902 LnSolution<T> aggregate() {
8903 const std::size_t N = lqn.nidx;
8905 auto mk = [&](std::vector<T>& v, std::vector<bool>& d) {
8906 v.assign(N + 1, Tzero());
8907 d.assign(N + 1,
false);
8909 std::vector<T>
QN,
UN, RN, TN, PN, SN, WN, AN;
8910 std::vector<bool> dQ, dU, dR, dT, dP, dS, dW, dA;
8911 mk(QN, dQ); mk(UN, dU); mk(RN, dR); mk(TN, dT);
8912 mk(PN, dP); mk(SN, dS); mk(WN, dW); mk(AN, dA);
8913 std::vector<bool> wn_done(N + 1,
false);
8915 for (std::size_t e = 0; e < ensemble.size(); ++e) {
8916 const qn::Layer<T>& L = ensemble[e];
8917 const LayerResult<T>& r = results.back()[e];
8918 const std::size_t clientIdx = L.clientIdx;
8923 const bool has_host_server = !L.host_stations.empty();
8924 for (std::size_t hs : L.host_stations) {
8925 const std::size_t hidx = L.stations[hs - 1].attr_idx;
8930 for (std::size_t k = 0; k < L.nclasses; ++k) {
8931 if (L.classes[k].completes) {
8932 T t = clientIdx > 0 ? r.TN(clientIdx - 1, k) : Tzero();
8933 const T ts = r.TN(hs - 1, k);
8934 TN[hidx] = T(TN[hidx] + (t > ts ? t : ts));
8936 if (L.classes[k].attr_kind ==
int(LqnElement::ACTIVITY)) {
8938 if (station_idx_of_class(L, k) != hs)
continue;
8939 const std::size_t aidx = L.classes[k].attr_idx;
8940 const std::size_t tidx = lqn.parent[aidx];
8943 PN[aidx] = T(PN[aidx] + r.UN(hs - 1, k));
8944 PN[tidx] = T(PN[tidx] + r.UN(hs - 1, k));
8945 PN[hidx] = T(PN[hidx] + r.UN(hs - 1, k));
8946 }
else if (L.classes[k].attr_kind ==
int(LqnElement::ENTRY)
8947 && L.classes[k].type == JobClassType::OPEN) {
8951 if (station_idx_of_class(L, k) != hs)
continue;
8952 const std::size_t eidx = L.classes[k].attr_idx;
8953 const std::size_t tidx = lqn.parent[eidx];
8954 const std::size_t aidx = bound_activity_of(eidx);
8955 const T uo = r.UN(hs - 1, k);
8958 PN[aidx] = T(PN[aidx] + uo);
8961 PN[tidx] = T(PN[tidx] + uo);
8962 PN[hidx] = T(PN[hidx] + uo);
8968 for (std::size_t k = 0; k < L.nclasses; ++k) {
8969 const int kind = L.classes[k].attr_kind;
8973 const std::size_t serverIdx = station_idx_of_class(L, k);
8974 if (kind ==
int(LqnElement::TASK)) {
8975 const std::size_t tidx = L.classes[k].attr_idx;
8976 if (has_host_server && !dT[tidx]) {
8978 TN[tidx] = r.TN(clientIdx - 1, k);
8980 }
else if (kind ==
int(LqnElement::ENTRY) && L.classes[k].type == JobClassType::OPEN) {
8984 const std::size_t eidx = L.classes[k].attr_idx;
8985 const T to = r.TN(L.classes[k].refstat - 1, k);
8986 for (std::size_t idx : {eidx, lqn.parent[eidx], bound_activity_of(eidx)}) {
8987 if (idx == 0)
continue;
8989 TN[idx] = T(TN[idx] + to);
8991 }
else if (kind ==
int(LqnElement::ENTRY)) {
8992 const std::size_t eidx = L.classes[k].attr_idx;
8999 if (has_host_server && !dT[eidx]) {
9001 TN[eidx] = r.TN(clientIdx - 1, k);
9003 }
else if (kind ==
int(LqnElement::CALL)) {
9004 const std::size_t cidx = L.classes[k].attr_idx;
9005 const std::size_t aidx = lqn.callpair_src[cidx];
9006 if (lqn.calltype[cidx] == CallType::SYNC) {
9008 SN[aidx] = T(SN[aidx] + r.RN(serverIdx - 1, k) * lqn.callproc_mean[cidx]);
9011 QN[aidx] = T(QN[aidx] + r.QN(serverIdx - 1, k));
9012 }
else if (kind ==
int(LqnElement::ACTIVITY)) {
9013 const std::size_t aidx = L.classes[k].attr_idx;
9014 const std::size_t tidx = lqn.parent[aidx];
9016 QN[tidx] = T(QN[tidx] + r.QN(serverIdx - 1, k));
9019 TN[aidx] = T(TN[aidx] + r.TN(serverIdx - 1, k));
9021 SN[aidx] = T(SN[aidx] + r.RN(serverIdx - 1, k));
9023 RN[aidx] = T(RN[aidx] + r.RN(serverIdx - 1, k));
9026 WN[aidx] = residt[aidx];
9027 if (!wn_done[aidx]) {
9028 WN[tidx] = T(WN[tidx] + residt[aidx]);
9029 wn_done[aidx] =
true;
9031 QN[aidx] = T(QN[aidx] + r.QN(serverIdx - 1, k));
9039 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
9040 const std::size_t tidx = lqn.tshift + t;
9041 const double nrep = lqn.repl[tidx];
9042 if (!(nrep > 1.0))
continue;
9043 std::vector<std::size_t> scaleIdx{tidx};
9044 scaleIdx.insert(scaleIdx.end(), lqn.entriesof[tidx].begin(), lqn.entriesof[tidx].end());
9045 scaleIdx.insert(scaleIdx.end(), lqn.actsof[tidx].begin(), lqn.actsof[tidx].end());
9048 const auto hr = host_all_replica_tasks.find(tidx);
9049 const bool hall = hr != host_all_replica_tasks.end();
9050 const T pscale = num_traits<T>::from_double(hall ?
double(hr->second) : nrep);
9051 for (std::size_t idx : scaleIdx) {
9052 const bool isact = std::find(lqn.actsof[tidx].begin(), lqn.actsof[tidx].end(), idx) !=
9053 lqn.actsof[tidx].end();
9054 const T tscale = !hall ? num_traits<T>::from_double(nrep)
9055 : isact ? pscale : Tone();
9056 if (dT[idx]) TN[idx] = T(tscale * TN[idx]);
9057 if (dP[idx]) PN[idx] = T(pscale * PN[idx]);
9060 for (std::size_t hidx = 1; hidx <= lqn.nhosts; ++hidx)
9061 if (lqn.repl[hidx] > 1.0 && dP[hidx]) PN[hidx] = T(num_traits<T>::from_double(lqn.repl[hidx]) * PN[hidx]);
9067 for (std::size_t t = 1; t <= lqn.ntasks; ++t) {
9068 const std::size_t tidx = lqn.tshift + t;
9069 bool has_fork =
false;
9070 for (std::size_t aidx : lqn.actsof[tidx]) {
9071 if (lqn.actposttype[aidx] == PrecedenceType::POST_AND) {
9077 const T task_tput = tput[tidx];
9079 const T flow_scale = T(task_tput / TN[tidx]);
9080 if (!(dbl(flow_scale) > 0.0) || !std::isfinite(dbl(flow_scale)))
continue;
9081 std::vector<std::size_t> scale_idx{tidx};
9082 scale_idx.insert(scale_idx.end(), lqn.entriesof[tidx].begin(), lqn.entriesof[tidx].end());
9083 scale_idx.insert(scale_idx.end(), lqn.actsof[tidx].begin(), lqn.actsof[tidx].end());
9084 for (std::size_t idx : scale_idx)
9085 if (dT[idx]) TN[idx] = T(flow_scale * TN[idx]);
9088 for (std::size_t e = 1; e <= lqn.nentries; ++e) {
9089 const std::size_t eidx = lqn.eshift + e;
9090 const std::size_t tidx = lqn.parent[eidx];
9097 ? T(TN[eidx] * (servt_ph1[eidx] + servt_ph2[eidx]))
9098 : T(TN[eidx] * SN[eidx]);
9101 for (std::size_t a : lqn.actsof[eidx])
9106 if (!lqn.actsof[eidx].empty()) {
9108 PN[eidx] = any ? ps : Tzero();
9110 for (std::size_t a : lqn.actsof[tidx]) {
9112 UN[a] = T(TN[a] * SN[a]);
9114 UN[tidx] = T(UN[tidx] + UN[eidx]);
9126 for (std::size_t i = 1; i <= N; ++i)
9131 const bool host = lqn.type[i] == LqnElement::HOST;
9132 const bool task = lqn.type[i] == LqnElement::TASK;
9133 const bool entry = lqn.type[i] == LqnElement::ENTRY;
9137 dS[i] = !host && !task;
9139 dW[i] = !host && !entry;
9145 s.QN =
UN; s.defined_Q = dU;
9146 s.UN = PN; s.defined_U = dP;
9147 s.RN = SN; s.defined_R = dS;
9148 s.TN = TN; s.defined_T = dT;
9149 s.AN = AN; s.defined_A = dA;
9150 s.WN = WN; s.defined_W = dW;
9151 s.iterations = iterations_done;
9152 s.converged = did_converge;