LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
api_dispatch_qsys.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 *
5 * --api dispatch entries for the 'qsys' group (see api_dispatch_detail.h):
6 * the remaining closed-form queueing systems, the fork-join (fj) family, the
7 * age-of-information transforms, the moment conversions and the simulation
8 * planning helpers.
9 *
10 * CONVENTIONS, shared with api_dispatch.cpp:
11 * - argument keys are the MATLAB parameter names, output keys the MATLAB
12 * output names (struct fields where MATLAB returns a struct);
13 * - an absent optional argument calls the port's shorter overload, or leaves
14 * the port's own default in place; no default is restated here. Where the
15 * port takes its optional arguments POSITIONALLY, a later one cannot be
16 * given without the earlier ones (prefix_count), and where it takes a group
17 * of tuning knobs only together, the group is all-or-none (all_or_none);
18 * - a function handle cannot cross JSON. Where the port offers a constructor
19 * for a NAMED law, the handle is replaced by that law (a model.json
20 * distribution record, or the aoi_lst_* constructors); otherwise the
21 * argument is refused by name, and a function whose handle is REQUIRED is
22 * listed as library-only below.
23 */
24
25#include "api_dispatch_detail.h"
26
27#include <array>
28#include <cmath>
29#include <complex>
30#include <initializer_list>
31#include <limits>
32#include <string>
33#include <vector>
34
40#include "line/api/fj/fj_amva.h"
52#include "line/api/fj/fj_qgb.h"
69// qsys_bmapm1.h names lang::GlobalConstants without including the header that
70// declares it, so lang_types.h must come first.
120
121namespace line {
122namespace reg {
123
124namespace {
125
126// ---------------------------------------------------------------------------
127// Shared readers
128// ---------------------------------------------------------------------------
129
130/**
131 * How many of the port's POSITIONAL optional arguments the caller gave. They
132 * must form a prefix: naming a later one without the earlier would make this
133 * boundary restate the earlier defaults, which it does not do.
134 */
135std::size_t prefix_count(const Args& a, std::initializer_list<const char*> keys,
136 const std::string& fn) {
137 std::size_t n = 0;
138 bool gap = false;
139 const char* missing = nullptr;
140 for (const char* k : keys) {
141 if (a.has(k)) {
142 if (gap)
143 throw InputError(fn + ": '" + k + "' follows '" + missing +
144 "' positionally in the port; give '" + missing + "' as well");
145 ++n;
146 } else if (!gap) {
147 gap = true;
148 missing = k;
149 }
150 }
151 return n;
152}
153
154/** A group of tuning knobs the port takes only together: all of them or none. */
155bool all_or_none(const Args& a, std::initializer_list<const char*> keys, const std::string& fn) {
156 std::size_t n = 0;
157 std::string names;
158 for (const char* k : keys) {
159 if (a.has(k)) ++n;
160 if (!names.empty()) names += ", ";
161 names += std::string("'") + k + "'";
162 }
163 if (n != 0 && n != keys.size())
164 throw InputError(fn + ": " + names + " tune one computation together; give all of them "
165 "or none");
166 return n != 0;
167}
168
169std::vector<unsigned> read_uints(Args& a, const char* key, const std::string& fn) {
170 const std::vector<int> v = a.ints(key);
171 std::vector<unsigned> out;
172 for (std::size_t i = 0; i < v.size(); ++i) {
173 if (v[i] < 0)
174 throw InputError(fn + ": '" + key + "' holds counts and cannot be negative");
175 out.push_back(static_cast<unsigned>(v[i]));
176 }
177 return out;
178}
179
180/** A required flag, which Args::boolean only offers with a fallback. */
181bool required_flag(Args& a, const char* key, const std::string& fn) {
182 if (!a.has(key)) throw InputError(fn + ": missing required argument '" + key + "'");
183 return a.boolean(key, false);
184}
185
186/** A MAP as the (D0, D1) pair the reference passes around, under any two keys. */
187template <class T>
188mam::Map<T> read_map(Args& a, const char* d0, const char* d1) {
189 mam::Map<T> m;
190 m.D0 = a.matrix<T>(d0);
191 m.D1 = a.matrix<T>(d1);
192 return m;
193}
194
195/** A MAP given as MATLAB's cell {D0, D1}: a two-element list of matrices. */
196template <class T>
197mam::Map<T> map_from_pair(const Json& j, const std::string& where) {
198 if (!j.is_array() || j.size() != 2)
199 throw InputError(where + ": expected the MAP as a list [D0, D1] of two matrices");
200 mam::Map<T> m;
201 m.D0 = matrix_from_json<T>(j[0], where + "[0]");
202 m.D1 = matrix_from_json<T>(j[1], where + "[1]");
203 return m;
204}
205
206/** A list of MAPs, each a [D0, D1] pair. */
207template <class T>
208std::vector<mam::Map<T> > maps_from_json(const Json& j, const std::string& where) {
209 if (!j.is_array()) throw InputError(where + ": expected a list of [D0, D1] pairs");
210 std::vector<mam::Map<T> > out;
211 for (std::size_t i = 0; i < j.size(); ++i)
212 out.push_back(map_from_pair<T>(j[i], where + "[" + std::to_string(i) + "]"));
213 return out;
214}
215
216/**
217 * A distribution given as its model.json record, e.g. {"type":"Exp",
218 * "params":{"lambda":2}}. The record reader parses its numbers through double,
219 * so at --arith real a law is as precise as a double literal, and a malformed
220 * record is reported as the caller's input rather than as a JSON library fault.
221 */
222template <class T>
223lang::Distrib<T> dist_record(const Json& j, const std::string& where) {
224 if (!j.is_object() || !j.contains("type"))
225 throw InputError(where + ": expected a distribution record {\"type\": ..., ...} as "
226 "written to model.json");
227 try {
228 return io::detail::dist_from_json<T>(j);
229 } catch (const Json::exception& e) {
230 throw InputError(where + ": malformed distribution record: " + e.what());
231 }
232}
233
234/**
235 * The service law of the MAP/G/1/K family, MATLAB's svc struct: {"type":"det",
236 * "d"}, {"type":"gamma","alpha","theta"} or {"type":"ph","alpha","T"}. The
237 * 'density' type carries a function handle and has no JSON form.
238 */
239template <class T>
240qsys::ServiceLaw<T> read_svc(Args& a, const std::string& fn) {
241 Args sv(a.get("svc"), fn + ": svc");
242 const std::string type = sv.text("type", "");
243 qsys::ServiceLaw<T> svc;
244 if (type == "det") {
245 svc = qsys::ServiceLaw<T>::deterministic(sv.number<T>("d"));
246 } else if (type == "gamma") {
247 const T al = sv.number<T>("alpha");
248 svc = qsys::ServiceLaw<T>::gamma(al, sv.number<T>("theta"));
249 } else if (type == "ph") {
250 const std::vector<T> al = sv.vector<T>("alpha");
251 svc = qsys::ServiceLaw<T>::phase_type(al, sv.matrix<T>("T"));
252 } else if (type == "density") {
253 throw UnsupportedError(ErrorKind{"Api"},
254 fn + ": a 'density' service law is a function handle and has no named-JSON form; "
255 "use 'det', 'gamma' or 'ph', or call it from the library");
256 } else {
257 throw UnsupportedError(ErrorKind{"Distribution"},
258 fn + ": svc.type must be 'det', 'gamma' or 'ph', got '" + type + "'");
259 }
260 sv.done();
261 return svc;
262}
263
264/** A vector output that MATLAB reshapes to the scalar it was given. */
265template <class T>
266Json encode_shaped(const std::vector<T>& v, bool scalar) {
267 if (scalar && v.size() == 1) return encode_scalar(v[0]);
268 return encode_vector(v);
269}
270
271/** The MATLAB message every exact refusal of the sim family shares. */
272std::string sim_exact_refusal(const char* fn, const char* why) {
273 return std::string(fn) + ": " + why +
274 ", so exact rational arithmetic has nothing to preserve and is refused; rerun with "
275 "--arith double or --arith real";
276}
277
278// ---------------------------------------------------------------------------
279// Moment tensors: nested JSON arrays, outer index = dimension 1
280// ---------------------------------------------------------------------------
281
282template <class T>
283void tensor_fill(const Json& node, std::size_t depth, std::size_t offset,
284 const std::vector<std::size_t>& sz, const std::vector<std::size_t>& stride,
285 std::vector<T>& data, const std::string& where) {
286 if (depth == sz.size()) {
287 if (node.is_array())
288 throw InputError(where + ": the tensor is nested deeper than its first element");
289 data[offset] = number_from_json<T>(node, where);
290 return;
291 }
292 if (!node.is_array() || node.size() != sz[depth])
293 throw InputError(where + ": ragged tensor, dimension " + std::to_string(depth + 1) +
294 " must have " + std::to_string(sz[depth]) + " entries throughout");
295 for (std::size_t i = 0; i < sz[depth]; ++i)
296 tensor_fill<T>(node[i], depth + 1, offset + i * stride[depth], sz, stride, data, where);
297}
298
299/**
300 * A moment tensor from nested arrays: the nesting depth is the order and the
301 * outermost index runs over dimension 1, so A[i][j] is MATLAB's A(i,j). A flat
302 * array is an order-1 tensor, a bare number a one-entry one.
303 */
304template <class T>
305moment::MomentTensor<T> tensor_from_json(const Json& j, const std::string& where) {
306 std::vector<std::size_t> sz;
307 if (!j.is_array()) {
308 sz.push_back(1);
309 } else {
310 const Json* p = &j;
311 while (p->is_array()) {
312 sz.push_back(p->size());
313 if (p->empty()) break;
314 p = &(*p)[0];
315 }
316 }
317 std::vector<std::size_t> stride(sz.size(), 1);
318 for (std::size_t l = 1; l < sz.size(); ++l) stride[l] = stride[l - 1] * sz[l - 1];
319 moment::MomentTensor<T> t(sz);
320 if (!j.is_array())
321 t.data[0] = number_from_json<T>(j, where);
322 else if (t.numel() > 0)
323 tensor_fill<T>(j, 0, 0, sz, stride, t.data, where);
324 return t;
325}
326
327template <class T>
328Json tensor_nest(const moment::MomentTensor<T>& t, std::size_t depth, std::size_t offset) {
329 Json out = Json::array();
330 const std::size_t st = t.stride(depth);
331 for (std::size_t i = 0; i < t.sz[depth]; ++i) {
332 if (depth + 1 == t.order())
333 out.push_back(encode_scalar(t.data[offset + i * st]));
334 else
335 out.push_back(tensor_nest(t, depth + 1, offset + i * st));
336 }
337 return out;
338}
339
340/** The inverse of tensor_from_json; an order-1 tensor is a flat array. */
341template <class T>
342Json encode_tensor(const moment::MomentTensor<T>& t) {
343 return tensor_nest(t, 0, 0);
344}
345
346Json encode_sizes(const std::vector<std::size_t>& v) {
347 Json out = Json::array();
348 for (std::size_t i = 0; i < v.size(); ++i) out.push_back(encode_count(v[i]));
349 return out;
350}
351
352// ---------------------------------------------------------------------------
353// moment: one-dimensional sequence conversions, vector in and vector out
354// ---------------------------------------------------------------------------
355
356#define LINE_MOMENT_VEC_OP(OPNAME, FN, IN, OUT) \
357 struct OPNAME { \
358 template <class T> \
359 static Json run(Args& a) { \
360 const std::vector<T> x = a.vector<T>(IN); \
361 a.done(); \
362 Json out; \
363 out[OUT] = encode_vector(moment::FN<T>(x)); \
364 return out; \
365 } \
366 };
367
368LINE_MOMENT_VEC_OP(OpMomentCumulantFromRaw, moment_cumulant_from_raw, "m", "kappa")
369LINE_MOMENT_VEC_OP(OpMomentRawFromCumulant, moment_raw_from_cumulant, "kappa", "m")
370LINE_MOMENT_VEC_OP(OpMomentFactcumulantFromFactorial, moment_factcumulant_from_factorial, "f",
371 "kappa")
372LINE_MOMENT_VEC_OP(OpMomentFactorialFromFactcumulant, moment_factorial_from_factcumulant,
373 "kappa", "f")
374LINE_MOMENT_VEC_OP(OpMomentBinomialFromTail, moment_binomial_from_tail, "t", "b")
375LINE_MOMENT_VEC_OP(OpMomentTailFromBinomial, moment_tail_from_binomial, "b", "t")
376#undef LINE_MOMENT_VEC_OP
377
378// ---------------------------------------------------------------------------
379// moment: joint (tensor) conversions, tensor in and tensor out
380// ---------------------------------------------------------------------------
381
382#define LINE_MOMENT_TENSOR_OP(OPNAME, FN, IN, OUT) \
383 struct OPNAME { \
384 template <class T> \
385 static Json run(Args& a) { \
386 const moment::MomentTensor<T> x = \
387 tensor_from_json<T>(a.get(IN), std::string(#FN ": ") + IN); \
388 a.done(); \
389 Json out; \
390 out[OUT] = encode_tensor(moment::FN<T>(x)); \
391 return out; \
392 } \
393 };
394
395LINE_MOMENT_TENSOR_OP(OpMjBinomialFromFactorial, moment_joint_binomial_from_factorial, "f", "b")
396LINE_MOMENT_TENSOR_OP(OpMjBinomialFromNegbinomial, moment_joint_binomial_from_negbinomial, "bm",
397 "b")
398LINE_MOMENT_TENSOR_OP(OpMjBinomialFromTail, moment_joint_binomial_from_tail, "t", "b")
399LINE_MOMENT_TENSOR_OP(OpMjCentralFromRaw, moment_joint_central_from_raw, "m", "mc")
400LINE_MOMENT_TENSOR_OP(OpMjCentralFromTail, moment_joint_central_from_tail, "t", "mc")
401LINE_MOMENT_TENSOR_OP(OpMjCumulantFromRaw, moment_joint_cumulant_from_raw, "m", "kappa")
402LINE_MOMENT_TENSOR_OP(OpMjFactcumulantFromFactorial, moment_joint_factcumulant_from_factorial,
403 "f", "kappa")
404LINE_MOMENT_TENSOR_OP(OpMjFactorialFromBinomial, moment_joint_factorial_from_binomial, "b", "f")
405LINE_MOMENT_TENSOR_OP(OpMjFactorialFromFactcumulant, moment_joint_factorial_from_factcumulant,
406 "kappa", "f")
407LINE_MOMENT_TENSOR_OP(OpMjFactorialFromRaw, moment_joint_factorial_from_raw, "m", "f")
408LINE_MOMENT_TENSOR_OP(OpMjFactorialFromUpfactorial, moment_joint_factorial_from_upfactorial, "fp",
409 "f")
410LINE_MOMENT_TENSOR_OP(OpMjNegbinomialFromBinomial, moment_joint_negbinomial_from_binomial, "b",
411 "bm")
412LINE_MOMENT_TENSOR_OP(OpMjNegbinomialFromUpfactorial, moment_joint_negbinomial_from_upfactorial,
413 "fp", "bm")
414LINE_MOMENT_TENSOR_OP(OpMjRawFromCumulant, moment_joint_raw_from_cumulant, "kappa", "m")
415LINE_MOMENT_TENSOR_OP(OpMjRawFromFactorial, moment_joint_raw_from_factorial, "f", "m")
416LINE_MOMENT_TENSOR_OP(OpMjRawFromUpfactorial, moment_joint_raw_from_upfactorial, "fp", "m")
417LINE_MOMENT_TENSOR_OP(OpMjTailFromBinomial, moment_joint_tail_from_binomial, "b", "t")
418LINE_MOMENT_TENSOR_OP(OpMjUpfactorialFromFactorial, moment_joint_upfactorial_from_factorial, "f",
419 "fp")
420LINE_MOMENT_TENSOR_OP(OpMjUpfactorialFromNegbinomial, moment_joint_upfactorial_from_negbinomial,
421 "bm", "fp")
422LINE_MOMENT_TENSOR_OP(OpMjUpfactorialFromRaw, moment_joint_upfactorial_from_raw, "m", "fp")
423#undef LINE_MOMENT_TENSOR_OP
424
425struct OpMjCentralFromRawMean {
426 template <class T>
427 static Json run(Args& a) {
428 const moment::MomentTensor<T> m =
429 tensor_from_json<T>(a.get("m"), "moment_joint_central_from_raw_mean: m");
430 const std::vector<T> mu = a.vector<T>("mu");
431 a.done();
432 Json out;
433 out["mc"] = encode_tensor(moment::moment_joint_central_from_raw_mean<T>(m, mu));
434 return out;
435 }
436};
437
438struct OpMjRawFromCentral {
439 template <class T>
440 static Json run(Args& a) {
441 const moment::MomentTensor<T> mc =
442 tensor_from_json<T>(a.get("mc"), "moment_joint_raw_from_central: mc");
443 const std::vector<T> mu = a.vector<T>("mu");
444 a.done();
445 Json out;
446 out["m"] = encode_tensor(moment::moment_joint_raw_from_central<T>(mc, mu));
447 return out;
448 }
449};
450
451struct OpMjAggregate {
452 template <class T>
453 static Json run(Args& a) {
454 const moment::MomentTensor<T> F =
455 tensor_from_json<T>(a.get("F"), "moment_joint_aggregate: F");
456 a.done();
457 Json out;
459 return out;
460 }
461};
462
463struct OpMjMarking {
464 template <class T>
465 static Json run(Args& a) {
466 const std::vector<T> f = a.vector<T>("f");
467 const std::vector<T> p = a.vector<T>("p");
468 const std::vector<unsigned> d = read_uints(a, "dims", "moment_joint_marking");
469 a.done();
470 const std::vector<std::size_t> dims(d.begin(), d.end());
471 Json out;
472 out["F"] = encode_tensor(moment::moment_joint_marking<T>(f, p, dims));
473 return out;
474 }
475};
476
477struct OpMomentHousematrix {
478 template <class T>
479 static Json run(Args& a) {
480 const std::string edge = a.text("edge", "");
481 if (edge.empty()) throw InputError("moment_housematrix: missing required argument 'edge'");
482 const int n = a.required_integer("n");
483 a.done();
484 Json out;
485 out["T"] = encode_matrix(moment::moment_housematrix<T>(edge, n));
486 return out;
487 }
488};
489
490struct OpMomentTensorsize {
491 template <class T>
492 static Json run(Args& a) {
493 const moment::MomentTensor<T> A = tensor_from_json<T>(a.get("A"), "moment_tensorsize: A");
494 a.done();
495 Json out;
496 out["sz"] = encode_sizes(moment::moment_tensorsize<T>(A));
497 return out;
498 }
499};
500
501struct OpMomentTensortrans {
502 template <class T>
503 static Json run(Args& a) {
504 const moment::MomentTensor<T> A = tensor_from_json<T>(a.get("A"), "moment_tensortrans: A");
505 const Matrix<T> Tm = a.matrix<T>("T");
506 const std::size_t mode = a.count("mode");
507 a.done();
508 // MATLAB's mode is 1-based, the port's 0-based.
509 if (mode < 1) throw InputError("moment_tensortrans: 'mode' is 1-based and must be >= 1");
510 Json out;
511 out["B"] = encode_tensor(moment::moment_tensortrans<T>(A, Tm, mode - 1));
512 return out;
513 }
514};
515
516struct OpMomentJointtrans {
517 template <class T>
518 static Json run(Args& a) {
519 const moment::MomentTensor<T> A = tensor_from_json<T>(a.get("A"), "moment_jointtrans: A");
520 const std::string edge = a.text("edge", "");
521 if (edge.empty()) throw InputError("moment_jointtrans: missing required argument 'edge'");
522 a.done();
523 Json out;
524 out["B"] = encode_tensor(moment::moment_jointtrans<T>(A, edge));
525 return out;
526 }
527};
528
529// ---------------------------------------------------------------------------
530// fj: fork-join response times and maxima
531// ---------------------------------------------------------------------------
532
533/**
534 * fj_amva / fj_qgb: MATLAB defaults Z to 0, but the port has no overload
535 * without Z, so Z is required here rather than restated.
536 */
537struct OpFjAmva {
538 template <class T>
539 static Json run(Args& a) {
540 const std::vector<T> D = a.vector<T>("D");
541 const std::vector<unsigned> P = read_uints(a, "P", "fj_amva");
542 const unsigned M = a.uinteger("M");
543 const T Z = a.number<T>("Z");
544 a.done();
545 const fj::FJAmvaResult<T> r = fj::fj_amva<T>(D, P, M, Z);
546 Json out;
547 out["R"] = encode_vector(r.R);
548 out["Q"] = encode_vector(r.Q);
549 out["X"] = encode_scalar(r.X);
550 out["U"] = encode_vector(r.U);
551 return out;
552 }
553};
554
555struct OpFjQgb {
556 template <class T>
557 static Json run(Args& a) {
558 const std::vector<T> D = a.vector<T>("D");
559 const std::vector<unsigned> P = read_uints(a, "P", "fj_qgb");
560 const unsigned M = a.uinteger("M");
561 const T Z = a.number<T>("Z");
562 a.done();
563 const fj::FJQgbResult<T> r = fj::fj_qgb<T>(D, P, M, Z);
564 Json out;
565 out["Q"] = encode_vector(r.Q);
566 out["y"] = encode_vector(r.y);
567 return out;
568 }
569};
570
571struct OpFjCharMaxBlom {
572 template <class T>
573 static Json run(Args& a) {
574 const unsigned K = a.uinteger("K");
575 a.unsupported("Finv", "it is a quantile function handle; omit it for the standard "
576 "normal the port selects");
577 const std::size_t n = prefix_count(a, {"alpha", "beta"}, "fj_char_max_blom");
578 const T alpha = n >= 1 ? a.number<T>("alpha") : T();
579 const T beta = n >= 2 ? a.number<T>("beta") : T();
580 a.done();
581 const std::function<T(const T&)> none;
582 const fj::FJCharMaxBlomResult<T> r =
583 n == 0 ? fj::fj_char_max_blom<T>(K)
584 : (n == 1 ? fj::fj_char_max_blom<T>(K, none, alpha)
585 : fj::fj_char_max_blom<T>(K, none, alpha, beta));
586 Json out;
587 out["mK"] = encode_scalar(r.mK);
588 // MATLAB returns NaN for the bracket when the port's guard says it does
589 // not exist; the absence is reported by omitting it.
590 if (r.bracket_available) {
591 out["lo"] = encode_scalar(r.lo);
592 out["hi"] = encode_scalar(r.hi);
593 }
594 return out;
595 }
596};
597
598struct OpFjCharMaxDiscrete {
599 template <class T>
600 static Json run(Args& a) {
601 const unsigned K = a.uinteger("K");
602 std::string type = a.text("dist_type", "");
603 const T par = a.number<T>("param");
604 a.done();
605 for (std::size_t i = 0; i < type.size(); ++i)
606 type[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(type[i])));
608 if (type == "geometric" || type == "geom")
610 else if (type == "poisson" || type == "pois")
612 else
613 throw UnsupportedError(ErrorKind{"Distribution"},
614 "fj_char_max_discrete: dist_type must be 'geometric' or 'poisson', got '" + type +
615 "'");
616 const fj::FJCharMaxDiscreteResult<T> r = fj::fj_char_max_discrete<T>(K, dist, par);
617 Json out;
618 out["MK"] = encode_scalar(r.MK);
619 out["mK"] = static_cast<long long>(r.mK);
620 out["exact"] = encode_scalar(r.exact);
621 return out;
622 }
623};
624
625struct OpFjCoxFit {
626 template <class T>
627 static Json run(Args& a) {
628 const T m1 = a.number<T>("m1");
629 const T c2 = a.number<T>("c2");
630 a.done();
631 const fj::FJCoxFitResult<T> r = fj::fj_cox_fit<T>(m1, c2);
632 Json out;
633 out["mu1"] = encode_scalar(r.mu1);
634 out["mu2"] = encode_scalar(r.mu2);
635 out["q"] = encode_scalar(r.q);
636 out["kmin"] = static_cast<long long>(r.kmin);
637 out["kmax"] = static_cast<long long>(r.kmax);
638 return out;
639 }
640};
641
642struct OpFjDagMakespan {
643 template <class T>
644 static Json run(Args& a) {
645 const Matrix<T> pred = a.matrix<T>("pred");
646 Matrix<T> rate = a.matrix<T>("rate");
647 a.done();
648 // MATLAB also takes an n-vector of constant rates and repmats it to the
649 // n by n concurrency table; the port takes only the table.
650 const std::size_t n = pred.rows();
651 if ((rate.rows() == 1 || rate.cols() == 1) && rate.rows() * rate.cols() == n && n > 1) {
652 Matrix<T> full(n, n);
653 for (std::size_t i = 0; i < n; ++i)
654 for (std::size_t k = 0; k < n; ++k)
655 full(i, k) = rate.rows() == 1 ? rate(0, i) : rate(i, 0);
656 rate = full;
657 }
658 const fj::FJDagMakespanResult<T> r = fj::fj_dag_makespan<T>(pred, rate);
659 Json out;
660 out["C"] = encode_scalar(r.C);
661 out["I"] = encode_vector(r.I);
662 out["Cend"] = encode_vector(r.Cend);
663 out["E"] = encode_vector(r.E);
664 return out;
665 }
666};
667
668/** MATLAB's options.npoints counts Simpson NODES, the port's npanels panels. */
669unsigned panels_from_npoints(Args& o, const std::string& fn) {
670 const unsigned np = o.uinteger("npoints");
671 if (np < 2) throw InputError(fn + ": options.npoints must be at least 2");
672 return np - 1;
673}
674
675/**
676 * fj_delay_opt(shape, rate, options). The options struct carries maxsweeps,
677 * dtol and npoints, taken positionally by the port in that order. options.tol
678 * is refused: the port fixes the dispersion tolerance and takes no argument
679 * for it.
680 */
681struct OpFjDelayOpt {
682 template <class T>
683 static Json run(Args& a) {
684 const std::vector<unsigned> shape = read_uints(a, "shape", "fj_delay_opt");
685 const std::vector<T> rate = a.vector<T>("rate");
686 std::size_t n = 0;
687 unsigned maxsweeps = 0, npanels = 0;
688 T dtol = T();
689 if (const Json* oj = a.opt("options")) {
690 Args o(*oj, "fj_delay_opt: options");
691 o.unsupported("tol", "the port fixes the dispersion tolerance of the inner "
692 "fj_dispersion calls and takes no argument for it");
693 n = prefix_count(o, {"maxsweeps", "dtol", "npoints"}, "fj_delay_opt: options");
694 if (n >= 1) maxsweeps = o.uinteger("maxsweeps");
695 if (n >= 2) dtol = o.number<T>("dtol");
696 if (n >= 3) npanels = panels_from_npoints(o, "fj_delay_opt");
697 o.done();
698 }
699 a.done();
700 fj::FJDelayOptResult<T> r;
701 if (n == 0) r = fj::fj_delay_opt<T>(shape, rate);
702 else if (n == 1) r = fj::fj_delay_opt<T>(shape, rate, maxsweeps);
703 else if (n == 2) r = fj::fj_delay_opt<T>(shape, rate, maxsweeps, dtol);
704 else r = fj::fj_delay_opt<T>(shape, rate, maxsweeps, dtol, npanels);
705 Json out;
706 out["d"] = encode_vector(r.d);
707 out["Edisp"] = encode_scalar(r.Edisp);
708 out["Emax"] = encode_scalar(r.Emax);
709 return out;
710 }
711};
712
713/**
714 * fj_dispersion(shape, rate, d, options). Without d the port's two-argument
715 * overload runs; options {tol, npoints} are positional after d, so they
716 * require d.
717 */
718struct OpFjDispersion {
719 template <class T>
720 static Json run(Args& a) {
721 const std::vector<unsigned> shape = read_uints(a, "shape", "fj_dispersion");
722 const std::vector<T> rate = a.vector<T>("rate");
723 const bool hasD = a.has("d");
724 const std::vector<T> d = a.vector_or_empty<T>("d");
725 std::size_t n = 0;
726 unsigned npanels = 0;
727 T tol = T();
728 if (const Json* oj = a.opt("options")) {
729 if (!hasD)
730 throw InputError("fj_dispersion: 'options' follows 'd' positionally in the port; "
731 "give 'd' as well");
732 Args o(*oj, "fj_dispersion: options");
733 n = prefix_count(o, {"tol", "npoints"}, "fj_dispersion: options");
734 if (n >= 1) tol = o.number<T>("tol");
735 if (n >= 2) npanels = panels_from_npoints(o, "fj_dispersion");
736 o.done();
737 }
738 a.done();
739 fj::FJDispersionResult<T> r;
740 if (!hasD) r = fj::fj_dispersion<T>(shape, rate);
741 else if (n == 0) r = fj::fj_dispersion<T>(shape, rate, d);
742 else if (n == 1) r = fj::fj_dispersion<T>(shape, rate, d, tol);
743 else r = fj::fj_dispersion<T>(shape, rate, d, tol, npanels);
744 Json out;
745 out["Edisp"] = encode_scalar(r.Edisp);
746 out["Emax"] = encode_scalar(r.Emax);
747 out["Emin"] = encode_scalar(r.Emin);
748 return out;
749 }
750};
751
752struct OpFjIsmGreen {
753 template <class T>
754 static Json run(Args& a) {
755 const T lambda = a.number<T>("lambda");
756 const T mu = a.number<T>("mu");
757 const unsigned s = a.uinteger("s");
758 const std::vector<T> c = a.vector<T>("c");
759 a.done();
760 const fj::FJIsmGreenResult<T> r = fj::fj_ism_green<T>(lambda, mu, s, c);
761 Json o;
762 o["EB"] = encode_scalar(r.EB);
763 o["EB2"] = encode_scalar(r.EB2);
764 o["ED"] = encode_scalar(r.ED);
765 o["ED2"] = encode_scalar(r.ED2);
766 o["EQ"] = encode_scalar(r.EQ);
767 o["EQbar"] = encode_scalar(r.EQbar);
768 o["pq"] = encode_scalar(r.pq);
769 o["pd"] = encode_scalar(r.pd);
770 o["pi0"] = encode_scalar(r.pi0);
771 o["rho"] = encode_scalar(r.rho);
772 o["q"] = encode_vector(r.q);
773 o["ES"] = encode_scalar(r.ES);
774 Json out;
775 out["W"] = encode_scalar(r.W);
776 out["R"] = encode_scalar(r.R);
777 out["out"] = o;
778 return out;
779 }
780};
781
782struct OpFjLstMaxHet {
783 template <class T>
784 static Json run(Args& a) {
785 const std::vector<T> lambda = a.vector<T>("lambda");
786 const T s = a.number<T>("s");
787 a.done();
788 Json out;
789 out["L"] = encode_scalar(fj::fj_lst_max_het<T>(lambda, s));
790 return out;
791 }
792};
793
794struct OpFjResptBulk {
795 template <class T>
796 static Json run(Args& a) {
797 const unsigned K = a.uinteger("K");
798 const T lambda = a.number<T>("lambda");
799 const T mu = a.number<T>("mu");
800 const unsigned c = a.uinteger("c");
801 const bool hasN = a.has("nmax");
802 const std::size_t nmax = a.count("nmax", 0);
803 a.done();
804 const fj::FJResptBulkResult<T> r = hasN ? fj::fj_respt_bulk<T>(K, lambda, mu, c, nmax)
805 : fj::fj_respt_bulk<T>(K, lambda, mu, c);
806 Json out;
807 out["Rreq"] = encode_scalar(r.Rreq);
808 out["Rtask"] = encode_scalar(r.Rtask);
809 out["Q"] = encode_scalar(r.Q);
810 out["p"] = encode_vector(r.p);
811 return out;
812 }
813};
814
815struct OpFjResptClosed {
816 template <class T>
817 static Json run(Args& a) {
818 const unsigned K = a.uinteger("K");
819 const T x = a.number<T>("x");
820 const unsigned M = a.uinteger("M");
821 const bool hasA = a.has("A");
822 const T A = hasA ? a.number<T>("A") : T();
823 a.done();
824 const fj::FJResptClosedResult<T> r =
825 hasA ? fj::fj_respt_closed<T>(K, x, M, A) : fj::fj_respt_closed<T>(K, x, M);
826 Json out;
827 out["R"] = encode_scalar(r.R);
828 out["exact"] = r.exact;
829 return out;
830 }
831};
832
833struct OpFjResptNosplit {
834 template <class T>
835 static Json run(Args& a) {
836 const unsigned K = a.uinteger("K");
837 const T lambda = a.number<T>("lambda");
838 const T mu = a.number<T>("mu");
839 a.done();
840 const fj::FJResptNosplitResult<T> r = fj::fj_respt_nosplit<T>(K, lambda, mu);
841 Json out;
842 out["R"] = encode_scalar(r.R);
843 out["rho"] = encode_scalar(r.rho);
844 return out;
845 }
846};
847
848struct OpFjSerialization {
849 template <class T>
850 static Json run(Args& a) {
851 const std::vector<T> Rs = a.vector<T>("Rs");
852 const T R0 = a.number<T>("R0");
853 const unsigned M = a.uinteger("M");
854 const bool hasAlpha = a.has("alpha");
855 const T alpha = hasAlpha ? a.number<T>("alpha") : T();
856 a.done();
857 const fj::FJSerializationResult<T> r = hasAlpha
858 ? fj::fj_serialization<T>(Rs, R0, M, alpha)
859 : fj::fj_serialization<T>(Rs, R0, M);
860 Json out;
861 out["P"] = encode_vector(r.P);
862 out["delay"] = encode_vector(r.delay);
863 out["Rtot"] = encode_scalar(r.Rtot);
864 return out;
865 }
866};
867
868struct OpFjTsmCapacity {
869 template <class T>
870 static Json run(Args& a) {
871 const unsigned s = a.uinteger("s");
872 const std::vector<T> f = a.vector<T>("f");
873 const std::vector<unsigned> rr = read_uints(a, "r", "fj_tsm_capacity");
874 const std::vector<T> x = a.vector<T>("x");
875 a.done();
876 const fj::FJTsmCapacityResult<T> r = fj::fj_tsm_capacity<T>(s, f, rr, x);
877 Json out;
878 out["Lmax"] = encode_scalar(r.Lmax);
879 out["Llp"] = encode_scalar(r.Llp);
880 // MATLAB's Lfcfs is NaN outside the two-class closed form; omitted then.
881 if (r.fcfs_available) out["Lfcfs"] = encode_scalar(r.Lfcfs);
882 Json states = Json::array();
883 for (std::size_t i = 0; i < r.states.size(); ++i) {
884 Json row = Json::array();
885 for (std::size_t k = 0; k < r.states[i].size(); ++k)
886 row.push_back(static_cast<long long>(r.states[i][k]));
887 states.push_back(row);
888 }
889 Json p;
890 p["states"] = states;
891 p["prob"] = encode_vector(r.prob);
892 out["p"] = p;
893 return out;
894 }
895};
896
897struct OpFjXmaxCoxian {
898 template <class T>
899 static Json run(Args& a) {
900 const unsigned K = a.uinteger("K");
901 const T mu1 = a.number<T>("mu1");
902 const T mu2 = a.number<T>("mu2");
903 const T q = a.number<T>("q");
904 a.done();
905 const fj::FJXmaxCoxianResult<T> r = fj::fj_xmax_coxian<T>(K, mu1, mu2, q);
906 Json out;
907 out["Xmax"] = encode_scalar(r.Xmax);
908 out["m1"] = encode_scalar(r.m1);
909 out["c2"] = encode_scalar(r.c2);
910 return out;
911 }
912};
913
914struct OpFjXmaxHet {
915 template <class T>
916 static Json run(Args& a) {
917 const std::vector<T> lambda = a.vector<T>("lambda");
918 const bool hasN = a.has("n");
919 const unsigned n = a.uinteger("n", 0);
920 a.done();
921 Json out;
922 out["Mn"] = encode_scalar(hasN ? fj::fj_xmax_het<T>(lambda, n) : fj::fj_xmax_het<T>(lambda));
923 return out;
924 }
925};
926
927struct OpFjXmaxMomentsHet {
928 template <class T>
929 static Json run(Args& a) {
930 const std::vector<T> lambda = a.vector<T>("lambda");
931 const bool hasN = a.has("n");
932 const unsigned n = a.uinteger("n", 0);
933 a.done();
934 Json out;
935 out["M"] = encode_vector(hasN ? fj::fj_xmax_moments_het<T>(lambda, n)
937 return out;
938 }
939};
940
941struct OpFjXmaxHz {
942 template <class T>
943 static Json run(Args& a) {
944 const T m1 = a.number<T>("m1");
945 const T m2 = a.number<T>("m2");
946 const unsigned K = a.uinteger("K");
947 a.done();
948 const fj::FJXmaxHzResult<T> r = fj::fj_xmax_hz<T>(m1, m2, K);
949 Json out;
950 out["Xmax"] = encode_scalar(r.Xmax);
951 out["resid"] = encode_scalar(r.resid);
952 return out;
953 }
954};
955
956struct OpFjMg1ResptMoments {
957 template <class T>
958 static Json run(Args& a) {
959 const T lambda = a.number<T>("lambda");
960 const T ES = a.number<T>("ES");
961 const T ES2 = a.number<T>("ES2");
962 const T ES3 = a.number<T>("ES3");
963 a.done();
964 const fj::Mg1ResptMoments<T> r = fj::fj_mg1_respt_moments<T>(lambda, ES, ES2, ES3);
965 Json out;
966 out["ET"] = encode_scalar(r.ET);
967 out["VT"] = encode_scalar(r.VT);
968 return out;
969 }
970};
971
972template <class T>
973Json forktail_results(const fj::ForkTailResult<T>& r) {
974 Json out;
975 out["xp"] = encode_scalar(r.xp);
976 out["alpha"] = encode_vector(r.alpha);
977 out["beta"] = encode_vector(r.beta);
978 return out;
979}
980
981/** fj_tail_forktail(ET, VT, K, p, P): K, p and P are positional. */
982struct OpFjTailForktail {
983 template <class T>
984 static Json run(Args& a) {
985 const std::vector<T> ET = a.vector<T>("ET");
986 const std::vector<T> VT = a.vector<T>("VT");
987 const std::size_t n = prefix_count(a, {"K", "p", "P"}, "fj_tail_forktail");
988 const std::vector<T> K = n >= 1 ? a.vector<T>("K") : std::vector<T>();
989 const T p = n >= 2 ? a.number<T>("p") : T();
990 const std::vector<T> P = n >= 3 ? a.vector<T>("P") : std::vector<T>();
991 a.done();
992 if (n == 0) return forktail_results(fj::fj_tail_forktail<T>(ET, VT));
993 if (n == 1) return forktail_results(fj::fj_tail_forktail<T>(ET, VT, K));
994 if (n == 2) return forktail_results(fj::fj_tail_forktail<T>(ET, VT, K, p));
995 return forktail_results(fj::fj_tail_forktail<T>(ET, VT, K, p, P));
996 }
997};
998
999/** fj_tail_ordstat(ET, VT, K, p, kreq): K, p and kreq are positional. */
1000struct OpFjTailOrdstat {
1001 template <class T>
1002 static Json run(Args& a) {
1003 const std::vector<T> ET = a.vector<T>("ET");
1004 const std::vector<T> VT = a.vector<T>("VT");
1005 const std::size_t n = prefix_count(a, {"K", "p", "kreq"}, "fj_tail_ordstat");
1006 const std::size_t K = n >= 1 ? a.count("K") : 0;
1007 const T p = n >= 2 ? a.number<T>("p") : T();
1008 const std::size_t kreq = n >= 3 ? a.count("kreq") : 0;
1009 a.done();
1010 if (n == 0) return forktail_results(fj::fj_tail_ordstat<T>(ET, VT));
1011 if (n == 1) return forktail_results(fj::fj_tail_ordstat<T>(ET, VT, K));
1012 if (n == 2) return forktail_results(fj::fj_tail_ordstat<T>(ET, VT, K, p));
1013 return forktail_results(fj::fj_tail_ordstat<T>(ET, VT, K, p, kreq));
1014 }
1015};
1016
1017/**
1018 * fj_branch_members(lqn, joinaidx). Of the LayeredNetworkStruct only the four
1019 * fields the algorithm reads cross the boundary, as the object lqn; indices
1020 * stay 1-based, as in MATLAB.
1021 */
1022struct OpFjBranchMembers {
1023 template <class T>
1024 static Json run(Args& a) {
1025 Args l(a.get("lqn"), "fj_branch_members: lqn");
1026 fj::LqnBranchView<T> v;
1027 v.graph = l.matrix<T>("graph");
1028 v.ashift = l.count("ashift");
1029 v.nacts = l.count("nacts");
1030 v.actposttype = l.ints("actposttype");
1031 l.done();
1032 const std::size_t joinaidx = a.count("joinaidx");
1033 a.done();
1034 const std::vector<std::vector<std::size_t> > m = fj::fj_branch_members<T>(v, joinaidx);
1035 Json members = Json::array();
1036 for (std::size_t i = 0; i < m.size(); ++i) members.push_back(encode_sizes(m[i]));
1037 Json out;
1038 out["members"] = members;
1039 return out;
1040 }
1041};
1042
1043/**
1044 * fj_dist2fj(lineMAP, distType, sn, ist, r). The reference reads ONE field of
1045 * sn, procid(ist, r), so sn crosses as {"procid": [[..]]} and nothing else;
1046 * ist and r are 1-based. The codes are MATLAB's ProcessType values.
1047 */
1048struct OpFjDist2fj {
1049 template <class T>
1050 static Json run(Args& a) {
1051 const mam::Map<T> m = map_from_pair<T>(a.get("lineMAP"), "fj_dist2fj: lineMAP");
1052 const std::string distType = a.text("distType", "");
1053 Args sn(a.get("sn"), "fj_dist2fj: sn");
1054 const Matrix<double> procid = sn.matrix<double>("procid");
1055 sn.done();
1056 const std::size_t ist = a.count("ist");
1057 const std::size_t r = a.count("r");
1058 a.done();
1059 fj::FjDistKind kind;
1060 if (distType == "arrival")
1062 else if (distType == "service")
1064 else
1065 throw InputError("fj_dist2fj: distType must be 'arrival' or 'service', got '" +
1066 distType + "'");
1067 if (ist < 1 || r < 1 || ist > procid.rows() || r > procid.cols())
1068 throw InputError("fj_dist2fj: (ist, r) are 1-based and must index sn.procid");
1069 const double code = procid(ist - 1, r - 1);
1070 fj::FjProcType pt;
1071 if (code == 0.0) pt = fj::FjProcType::Exp;
1072 else if (code == 1.0) pt = fj::FjProcType::Erlang;
1073 else if (code == 2.0) pt = fj::FjProcType::HyperExp;
1074 else if (code == 5.0) pt = fj::FjProcType::Map;
1075 else
1076 throw UnsupportedError(ErrorKind{"Distribution"},
1077 "fj_dist2fj: sn.procid(ist, r) = " + std::to_string(code) +
1078 " is not a process FJ_codes takes (EXP=0, ERLANG=1, HYPEREXP=2, MAP=5)");
1079 const fj::FjDist<T> d = fj::fj_dist2fj<T>(m, kind, pt);
1080 Json out;
1081 if (kind == fj::FjDistKind::Arrival) {
1082 out["lambda"] = encode_scalar(d.lambda);
1083 out["lambda0"] = encode_matrix(d.lambda0);
1084 out["lambda1"] = encode_matrix(d.lambda1);
1085 out["ma"] = encode_count(d.ma);
1086 out["Ia"] = encode_matrix(d.Ia);
1087 out["ArrChoice"] = d.choice;
1088 } else {
1089 out["mu"] = encode_scalar(d.mu);
1090 out["ST"] = encode_matrix(d.ST);
1091 out["St"] = encode_vector(d.St);
1092 out["tau_st"] = encode_vector(d.tau_st);
1093 out["SerChoice"] = d.choice;
1094 }
1095 return out;
1096 }
1097};
1098
1099// ---------------------------------------------------------------------------
1100// aoi: the service-law transforms, evaluated where the caller asks
1101// ---------------------------------------------------------------------------
1102//
1103// aoi_lst_* return a function handle in MATLAB. A handle cannot cross JSON, so
1104// the boundary takes the points "s" at which to evaluate it and returns the
1105// values as "lst". The law is the port's own constructor, unchanged.
1106
1107template <class T>
1108Json lst_values(Args& a, const aoi::Lst<T>& L) {
1109 const std::vector<T> s = a.vector<T>("s");
1110 a.done();
1111 std::vector<T> v(s.size());
1112 for (std::size_t i = 0; i < s.size(); ++i) v[i] = L(s[i]);
1113 Json out;
1114 out["lst"] = encode_vector(v);
1115 return out;
1116}
1117
1118struct OpAoiLstDet {
1119 template <class T>
1120 static Json run(Args& a) {
1121 const T d = a.number<T>("d");
1122 return lst_values<T>(a, aoi::aoi_lst_det<T>(d));
1123 }
1124};
1125
1126struct OpAoiLstErlang {
1127 template <class T>
1128 static Json run(Args& a) {
1129 const unsigned k = a.uinteger("k");
1130 const T mu = a.number<T>("mu");
1131 return lst_values<T>(a, aoi::aoi_lst_erlang<T>(k, mu));
1132 }
1133};
1134
1135struct OpAoiLstExp {
1136 template <class T>
1137 static Json run(Args& a) {
1138 const T mu = a.number<T>("mu");
1139 return lst_values<T>(a, aoi::aoi_lst_exp<T>(mu));
1140 }
1141};
1142
1143struct OpAoiLstPh {
1144 template <class T>
1145 static Json run(Args& a) {
1146 const std::vector<T> alpha = a.vector<T>("alpha");
1147 const Matrix<T> Tm = a.matrix<T>("T");
1148 return lst_values<T>(a, aoi::aoi_lst_ph<T>(alpha, Tm));
1149 }
1150};
1151
1152/** aoi_dist2ph(proc): proc is MATLAB's cell {D0, D1}. */
1153struct OpAoiDist2ph {
1154 template <class T>
1155 static Json run(Args& a) {
1156 const mam::Map<T> m = map_from_pair<T>(a.get("proc"), "aoi_dist2ph: proc");
1157 a.done();
1158 const aoi::AoiPh<T> r = aoi::aoi_dist2ph<T>(m);
1159 Json out;
1160 out["alpha"] = encode_vector(r.alpha);
1161 out["T"] = encode_matrix(r.Tmat);
1162 return out;
1163 }
1164};
1165
1166// ---------------------------------------------------------------------------
1167// qsys: MAP/G/1/K and its marked and per-flow variants
1168// ---------------------------------------------------------------------------
1169
1170/** The 'tol' and 'nmax' pair of the MAP/G/1/K family, which tune one truncation. */
1171template <class T>
1172struct Truncation {
1173 bool given = false;
1174 T tol = T();
1175 std::size_t nmax = 0;
1176};
1177
1178template <class T>
1179Truncation<T> read_truncation(Args& a, const std::string& fn) {
1180 Truncation<T> tr;
1181 tr.given = all_or_none(a, {"tol", "nmax"}, fn);
1182 if (tr.given) {
1183 tr.tol = a.number<T>("tol");
1184 tr.nmax = a.count("nmax");
1185 } else {
1186 a.opt("tol");
1187 a.opt("nmax");
1188 }
1189 return tr;
1190}
1191
1192struct OpQsysMapg1k {
1193 template <class T>
1194 static Json run(Args& a) {
1195 const mam::Map<T> arrival = read_map<T>(a, "D0", "D1");
1196 const qsys::ServiceLaw<T> svc = read_svc<T>(a, "qsys_mapg1k");
1197 const std::size_t K = a.count("K");
1198 const Truncation<T> tr = read_truncation<T>(a, "qsys_mapg1k");
1199 a.done();
1200 const qsys::MapG1kResult<T> r = tr.given
1201 ? qsys::qsys_mapg1k<T>(arrival, svc, K, tr.tol, tr.nmax)
1202 : qsys::qsys_mapg1k<T>(arrival, svc, K);
1203 Json out;
1204 out["p0"] = encode_scalar(r.p0);
1205 out["pK"] = encode_scalar(r.pK);
1206 out["lossProbability"] = encode_scalar(r.lossProbability);
1207 out["throughput"] = encode_scalar(r.throughput);
1208 out["lambda"] = encode_scalar(r.lambda);
1209 out["meanServiceTime"] = encode_scalar(r.meanServiceTime);
1210 out["utilization"] = encode_scalar(r.utilization);
1211 out["rho"] = encode_scalar(r.rho);
1212 out["nmax"] = encode_count(r.nmax);
1213 out["sigma"] = encode_vector(r.sigma);
1214 out["pKvec"] = encode_vector(r.pKvec);
1215 out["p0vec"] = encode_vector(r.p0vec);
1216 out["plevel"] = encode_vector(r.plevel);
1217 out["meanQueueLength"] = encode_scalar(r.meanQueueLength);
1218 out["countingResidual"] = encode_scalar(r.countingResidual);
1219 return out;
1220 }
1221};
1222
1223struct OpQsysMmapg1k {
1224 template <class T>
1225 static Json run(Args& a) {
1226 const Matrix<T> D0 = a.matrix<T>("D0");
1227 const std::vector<Matrix<T> > D1c = a.matrices<T>("D1c");
1228 const qsys::ServiceLaw<T> svc = read_svc<T>(a, "qsys_mmapg1k");
1229 const std::size_t K = a.count("K");
1230 const Truncation<T> tr = read_truncation<T>(a, "qsys_mmapg1k");
1231 a.done();
1232 const qsys::MmapG1kResult<T> r =
1233 tr.given ? qsys::qsys_mmapg1k<T>(D0, D1c, svc, K, tr.tol, tr.nmax)
1234 : qsys::qsys_mmapg1k<T>(D0, D1c, svc, K);
1235 Json out;
1236 out["throughput"] = encode_vector(r.throughput);
1237 out["lossRatio"] = encode_vector(r.lossRatio);
1238 out["lambda"] = encode_vector(r.lambda);
1239 out["lambdaAggregate"] = encode_scalar(r.lambdaAggregate);
1240 out["throughputAggregate"] = encode_scalar(r.throughputAggregate);
1241 out["lossAggregate"] = encode_scalar(r.lossAggregate);
1242 out["p0"] = encode_scalar(r.p0);
1243 out["pK"] = encode_scalar(r.pK);
1244 out["pKvec"] = encode_vector(r.pKvec);
1245 out["plevel"] = encode_vector(r.plevel);
1246 out["meanQueueLength"] = encode_scalar(r.meanQueueLength);
1247 out["meanServiceTime"] = encode_scalar(r.meanServiceTime);
1248 out["utilization"] = encode_scalar(r.utilization);
1249 out["rho"] = encode_scalar(r.rho);
1250 return out;
1251 }
1252};
1253
1254/** qsys_mapg1k_perflow(MAPS, svc, K): MAPS is a list of [D0, D1] pairs. */
1255struct OpQsysMapg1kPerflow {
1256 template <class T>
1257 static Json run(Args& a) {
1258 const std::vector<mam::Map<T> > flows =
1259 maps_from_json<T>(a.get("MAPS"), "qsys_mapg1k_perflow: MAPS");
1260 const qsys::ServiceLaw<T> svc = read_svc<T>(a, "qsys_mapg1k_perflow");
1261 const std::size_t K = a.count("K");
1262 const Truncation<T> tr = read_truncation<T>(a, "qsys_mapg1k_perflow");
1263 a.done();
1264 const qsys::MapG1kPerflowResult<T> r =
1265 tr.given ? qsys::qsys_mapg1k_perflow<T>(flows, svc, K, tr.tol, tr.nmax)
1266 : qsys::qsys_mapg1k_perflow<T>(flows, svc, K);
1267 Json out;
1268 out["throughput"] = encode_vector(r.throughput);
1269 out["lossRatio"] = encode_vector(r.lossRatio);
1270 out["lambda"] = encode_vector(r.lambda);
1271 out["lambdaAggregate"] = encode_scalar(r.lambdaAggregate);
1272 out["throughputAggregate"] = encode_scalar(r.throughputAggregate);
1273 out["lossAggregate"] = encode_scalar(r.lossAggregate);
1274 out["p0"] = encode_vector(r.p0);
1275 out["pK"] = encode_vector(r.pK);
1276 out["meanServiceTime"] = encode_scalar(r.meanServiceTime);
1277 out["rho"] = encode_scalar(r.rho);
1278 return out;
1279 }
1280};
1281
1282struct OpQsysSvclawCoeffs {
1283 template <class T>
1284 static Json run(Args& a) {
1285 const qsys::ServiceLaw<T> svc = read_svc<T>(a, "qsys_svclaw_coeffs");
1286 const T theta = a.number<T>("theta");
1287 const T tol = a.number<T>("tol");
1288 const std::size_t nmaxCap = a.count("nmaxCap");
1289 a.done();
1290 const qsys::SvclawCoeffsResult<T> r = qsys::qsys_svclaw_coeffs<T>(svc, theta, tol, nmaxCap);
1291 Json out;
1292 out["cn"] = encode_vector(r.cn);
1293 out["Smean"] = encode_scalar(r.Smean);
1294 out["residual"] = encode_scalar(r.residual);
1295 return out;
1296 }
1297};
1298
1299// ---------------------------------------------------------------------------
1300// qsys: laws given as distribution records
1301// ---------------------------------------------------------------------------
1302
1303/**
1304 * qsys_ldps_workload(lambda, B, alpha, N, t, ngrid). B is MATLAB's
1305 * Distribution object; it crosses as its model.json record, and the port is
1306 * handed exactly the three things the reference reads from it: getMean,
1307 * getSCV and evalCDF. An empty or absent t selects the automatic grid, as in
1308 * MATLAB; the port takes t and ngrid together, so ngrid is required whenever
1309 * either is named.
1310 */
1311struct OpQsysLdpsWorkload {
1312 template <class T>
1313 static Json run(Args& a) {
1314 const T lambda = a.number<T>("lambda");
1315 const lang::Distrib<T> law = dist_record<T>(a.get("B"), "qsys_ldps_workload: B");
1316 const std::vector<T> alpha = a.vector<T>("alpha");
1317 const std::size_t N = a.count("N");
1318 const bool tuned = a.has("t") || a.has("ngrid");
1319 if (tuned && !a.has("ngrid"))
1320 throw InputError("qsys_ldps_workload: the port takes 't' and 'ngrid' together; give "
1321 "'ngrid' with 't'");
1322 const std::vector<T> t = a.vector_or_empty<T>("t");
1323 const std::size_t ngrid = a.count("ngrid", 0);
1324 a.done();
1325 qsys::WorkloadServiceLaw<T> B;
1326 B.mean = lang::dist_moment(law, 1u);
1327 const T m2 = lang::dist_moment(law, 2u);
1328 B.scv = T(m2 / (B.mean * B.mean) - num_traits<T>::from_int(1));
1329 B.cdf = [law](const T& x) { return lang::dist_cdf(law, x); };
1330 const qsys::LdpsWorkloadResult<T> r =
1331 tuned ? qsys::qsys_ldps_workload<T>(lambda, B, alpha, N, t, ngrid)
1332 : qsys::qsys_ldps_workload<T>(lambda, B, alpha, N);
1333 Json out;
1334 out["F"] = encode_vector(r.F);
1335 out["t"] = encode_vector(r.t);
1336 out["p"] = encode_vector(r.p);
1337 return out;
1338 }
1339};
1340
1341/**
1342 * qsys_mmapgk1(MMAP, svc, ...). MMAP is the LINE list [D0, D1, D^(1), ...].
1343 * Each svc entry is a [D0s, D1s] pair (a phase-type MAP) or a distribution
1344 * record; MATLAB's third form, a struct holding an lst handle, cannot cross.
1345 * The port takes wPoints, numWMoms, tol and the iteration cap together (MATLAB
1346 * fixes the cap internally, the port exposes it as iterMax), and quadNodes
1347 * only after them.
1348 */
1349struct OpQsysMmapgk1 {
1350 template <class T>
1351 static Json run(Args& a) {
1352 const std::vector<Matrix<T> > MMAP = a.matrices<T>("MMAP");
1353 const Json& sj = a.get("svc");
1354 if (!sj.is_array()) throw InputError("qsys_mmapgk1: svc must be a list, one law per type");
1355 std::vector<qsys::MmapGk1Service<T> > svc;
1356 for (std::size_t k = 0; k < sj.size(); ++k) {
1357 const std::string where = "qsys_mmapgk1: svc[" + std::to_string(k) + "]";
1358 if (sj[k].is_array()) {
1359 svc.push_back(qsys::MmapGk1Service<T>(map_from_pair<T>(sj[k], where)));
1360 } else if (sj[k].is_object() && sj[k].contains("lst")) {
1361 throw UnsupportedError(ErrorKind{"JsonApi"},
1362 where + ": a transform struct carries an lst function handle, which cannot "
1363 "cross the JSON API boundary; give the law as a distribution record "
1364 "or a [D0, D1] pair");
1365 } else {
1366 svc.push_back(qsys::MmapGk1Service<T>(dist_record<T>(sj[k], where)));
1367 }
1368 }
1369 const bool tuned = all_or_none(a, {"wPoints", "numWMoms", "tol", "iterMax"}, "qsys_mmapgk1");
1370 if (a.has("quadNodes") && !tuned)
1371 throw InputError("qsys_mmapgk1: 'quadNodes' follows 'wPoints', 'numWMoms', 'tol' and "
1372 "'iterMax' positionally in the port; give them as well");
1373 const std::vector<T> w = a.vector_or_empty<T>("wPoints");
1374 const std::size_t nm = a.count("numWMoms", 0);
1375 const double tol = a.scalar<double>("tol", 0.0);
1376 const std::size_t iterMax = a.count("iterMax", 0);
1377 const bool hasQ = a.has("quadNodes");
1378 const std::size_t q = a.count("quadNodes", 0);
1379 a.done();
1380 qsys::MmapGk1Result<T> r;
1381 if (!tuned) r = qsys::qsys_mmapgk1<T>(MMAP, svc);
1382 else if (!hasQ) r = qsys::qsys_mmapgk1<T>(MMAP, svc, w, nm, tol, iterMax);
1383 else r = qsys::qsys_mmapgk1<T>(MMAP, svc, w, nm, tol, iterMax, q);
1384 Json out;
1385 out["lambda"] = encode_vector(r.lambdas);
1386 out["arrivalRate"] = encode_scalar(r.arrivalRate);
1387 out["utilization"] = encode_scalar(r.utilization);
1388 out["idleVector"] = encode_vector(r.idleVector);
1389 out["waitMoments"] = encode_vectors(r.waitMoments);
1390 out["meanWaitingTime"] = encode_vector(r.meanWaitingTime);
1391 out["meanSojournTime"] = encode_vector(r.meanSojournTime);
1392 out["meanQueueLength"] = encode_scalar(r.meanQueueLength);
1393 out["waitCDF"] = encode_vectors(r.waitCDF);
1394 out["waitPoints"] = encode_vector(r.waitPoints);
1395 return out;
1396 }
1397};
1398
1399/**
1400 * qsys_mmapgk1_lcfspr(MMAP, svc, ...). MMAP and svc as for qsys_mmapgk1; the
1401 * MATLAB name-value options nMax, wPoints, quadNodes and tol are each optional.
1402 * respLST is a function handle and cannot cross JSON; as for aoi_lst_*, the
1403 * optional points "s" (real) say where to evaluate it, and "respLST" returns
1404 * its values there, [type][point]. respCDF carries the CDF values.
1405 */
1406struct OpQsysMmapgk1Lcfspr {
1407 template <class T>
1408 static Json run(Args& a) {
1409 const std::vector<Matrix<T> > MMAP = a.matrices<T>("MMAP");
1410 const Json& sj = a.get("svc");
1411 if (!sj.is_array())
1412 throw InputError("qsys_mmapgk1_lcfspr: svc must be a list, one law per type");
1413 std::vector<qsys::MmapGk1Service<T> > svc;
1414 for (std::size_t k = 0; k < sj.size(); ++k) {
1415 const std::string where = "qsys_mmapgk1_lcfspr: svc[" + std::to_string(k) + "]";
1416 if (sj[k].is_array()) {
1417 svc.push_back(qsys::MmapGk1Service<T>(map_from_pair<T>(sj[k], where)));
1418 } else if (sj[k].is_object() && sj[k].contains("lst")) {
1419 throw UnsupportedError(ErrorKind{"JsonApi"},
1420 where + ": a transform struct carries an lst function handle, which cannot "
1421 "cross the JSON API boundary; give the law as a distribution record "
1422 "or a [D0, D1] pair");
1423 } else {
1424 svc.push_back(qsys::MmapGk1Service<T>(dist_record<T>(sj[k], where)));
1425 }
1426 }
1427 qsys::MmapGk1LcfsprOptions<T> opt;
1428 if (a.has("nMax")) opt.nMax = static_cast<long>(a.count("nMax"));
1429 opt.wPoints = a.vector_or_empty<T>("wPoints");
1430 opt.quadNodes = a.count("quadNodes", 120);
1431 opt.tol = a.scalar<double>("tol", 1e-12);
1432 const bool wantLst = a.has("s");
1433 const std::vector<T> sPts = wantLst ? a.vector<T>("s") : std::vector<T>();
1434 a.done();
1435 const qsys::MmapGk1LcfsprResult<T> r = qsys::qsys_mmapgk1_lcfspr<T>(MMAP, svc, opt);
1436 Json out;
1437 out["lambda"] = encode_vector(r.lambdas);
1438 out["arrivalRate"] = encode_scalar(r.arrivalRate);
1439 out["utilization"] = encode_scalar(r.utilization);
1440 out["Q"] = encode_matrix(r.Q);
1441 out["kappa"] = encode_vector(r.kappa);
1442 out["Rk"] = encode_matrices(r.Rk);
1443 out["R"] = encode_matrix(r.R);
1444 out["classMeanQueueLength"] = encode_vector(r.classMeanQueueLength);
1445 out["meanQueueLength"] = encode_scalar(r.meanQueueLength);
1446 out["meanSojournTime"] = encode_vector(r.meanSojournTime);
1447 out["queueLengthDistr"] = encode_vector(r.queueLengthDistr);
1448 out["classQueueLengthDistr"] = encode_vectors(r.classQueueLengthDistr);
1449 out["respCDF"] = encode_vectors(r.respCDF);
1450 out["respPoints"] = encode_vector(r.respPoints);
1451 if (wantLst) {
1452 const std::size_t K = r.lambdas.size();
1453 std::vector<std::vector<T> > lv(K, std::vector<T>(sPts.size()));
1454 for (std::size_t i = 0; i < sPts.size(); ++i) {
1455 const std::vector<std::complex<double> > w =
1456 r.respLST(std::complex<double>(num_traits<T>::to_double(sPts[i]), 0.0));
1457 for (std::size_t k = 0; k < K; ++k) lv[k][i] = num_traits<T>::from_double(w[k].real());
1458 }
1459 out["respLST"] = encode_vectors(lv);
1460 }
1461 out["analyzer"] = r.analyzer;
1462 return out;
1463 }
1464};
1465
1466/**
1467 * qsys_tandem_ub_ciucu(x, lst, p, mu, dlst). lst is the interarrival
1468 * Laplace-Stieltjes transform; it crosses as the distribution record of the
1469 * interarrival law, whose transform the port evaluates. dlst is refused: the
1470 * port differentiates lst itself when it is absent.
1471 */
1472struct OpQsysTandemUbCiucu {
1473 template <class T>
1474 static Json run(Args& a) {
1475 const std::vector<T> x = a.vector<T>("x");
1476 const lang::Distrib<T> law = dist_record<T>(a.get("lst"), "qsys_tandem_ub_ciucu: lst");
1477 const std::vector<T> p = a.vector<T>("p");
1478 const std::vector<T> mu = a.vector<T>("mu");
1479 a.unsupported("dlst", "it is a function handle; omit it and the port differentiates the "
1480 "transform of lst numerically");
1481 a.done();
1482 const std::function<T(const T&)> lst = [law](const T& s) { return lang::dist_lst(law, s); };
1483 const qsys::TandemUbResult<T> r = qsys::qsys_tandem_ub_ciucu<T>(x, lst, p, mu);
1484 Json out;
1485 out["S"] = encode_vector(r.S);
1486 out["W"] = encode_vector(r.W);
1487 out["theta"] = encode_scalar(r.theta);
1488 out["alpha"] = encode_scalar(r.alpha);
1489 out["A"] = encode_scalar(r.A);
1490 out["B"] = encode_scalar(r.B);
1491 out["C"] = encode_scalar(r.C);
1492 out["D"] = encode_scalar(r.D);
1493 out["analyzer"] = r.analyzer;
1494 return out;
1495 }
1496};
1497
1498// ---------------------------------------------------------------------------
1499// qsys: Lindley recursions
1500// ---------------------------------------------------------------------------
1501
1502template <class T>
1503Json lindley_results(const qsys::LindleyResult<T>& r, bool scalar) {
1504 Json out;
1505 out["mean"] = encode_shaped(r.mean, scalar);
1506 out["var"] = encode_shaped(r.var, scalar);
1507 out["moments"] = encode_matrix(r.moments);
1508 out["mmax"] = static_cast<long long>(r.mmax);
1509 out["analyzer"] = r.analyzer;
1510 return out;
1511}
1512
1513struct OpQsysHh1Lindley {
1514 template <class T>
1515 static Json run(Args& a) {
1516 const std::vector<T> lambda = a.vector<T>("lambda");
1517 const std::vector<T> pa = a.vector<T>("pa");
1518 const std::vector<T> mu = a.vector<T>("mu");
1519 const std::vector<T> ps = a.vector<T>("ps");
1520 const bool scalar = !a.get("Wn").is_array();
1521 const std::vector<T> Wn = a.vector<T>("Wn");
1522 const bool hasM = a.has("mmax");
1523 const unsigned mmax = a.uinteger("mmax", 0);
1524 a.done();
1525 if (scalar)
1526 return lindley_results(
1527 hasM ? qsys::qsys_hh1_lindley<T>(lambda, pa, mu, ps, Wn[0], mmax)
1528 : qsys::qsys_hh1_lindley<T>(lambda, pa, mu, ps, Wn[0]),
1529 true);
1530 return lindley_results(hasM ? qsys::qsys_hh1_lindley<T>(lambda, pa, mu, ps, Wn, mmax)
1531 : qsys::qsys_hh1_lindley<T>(lambda, pa, mu, ps, Wn),
1532 false);
1533 }
1534};
1535
1536struct OpQsysMm1Lindley {
1537 template <class T>
1538 static Json run(Args& a) {
1539 const T lambda = a.number<T>("lambda");
1540 const T mu = a.number<T>("mu");
1541 const bool scalar = !a.get("Wn").is_array();
1542 const std::vector<T> Wn = a.vector<T>("Wn");
1543 const bool hasM = a.has("mmax");
1544 const unsigned mmax = a.uinteger("mmax", 0);
1545 a.done();
1546 if (scalar)
1547 return lindley_results(hasM ? qsys::qsys_mm1_lindley<T>(lambda, mu, Wn[0], mmax)
1548 : qsys::qsys_mm1_lindley<T>(lambda, mu, Wn[0]),
1549 true);
1550 return lindley_results(hasM ? qsys::qsys_mm1_lindley<T>(lambda, mu, Wn, mmax)
1551 : qsys::qsys_mm1_lindley<T>(lambda, mu, Wn),
1552 false);
1553 }
1554};
1555
1556struct OpQsysLindleyMoment {
1557 template <class T>
1558 static Json run(Args& a) {
1559 const T lambda = a.number<T>("lambda");
1560 const T mu = a.number<T>("mu");
1561 const bool scalar = !a.get("Wn").is_array();
1562 const std::vector<T> Wn = a.vector<T>("Wn");
1563 const unsigned m = a.uinteger("m");
1564 a.done();
1565 Json out;
1566 if (scalar)
1567 out["value"] = encode_scalar(qsys::qsys_lindley_moment<T>(lambda, mu, Wn[0], m));
1568 else
1569 out["value"] = encode_vector(qsys::qsys_lindley_moment<T>(lambda, mu, Wn, m));
1570 return out;
1571 }
1572};
1573
1574struct OpQsysMm1TandemLindley {
1575 template <class T>
1576 static Json run(Args& a) {
1577 const T lambda = a.number<T>("lambda");
1578 const T mu1 = a.number<T>("mu1");
1579 const T mu2 = a.number<T>("mu2");
1580 const bool s1 = !a.get("Wk").is_array();
1581 const bool s2 = !a.get("Wk1").is_array();
1582 const std::vector<T> Wk = a.vector<T>("Wk");
1583 const std::vector<T> Wk1 = a.vector<T>("Wk1");
1584 a.done();
1585 const bool scalar = s1 && s2;
1586 const qsys::Mm1TandemLindleyResult<T> r =
1587 scalar ? qsys::qsys_mm1_tandem_lindley<T>(lambda, mu1, mu2, Wk[0], Wk1[0])
1588 : qsys::qsys_mm1_tandem_lindley<T>(lambda, mu1, mu2, Wk, Wk1);
1589 Json out;
1590 out["mean"] = encode_shaped(r.mean, scalar);
1591 out["interdepMean"] = encode_shaped(r.interdepMean, scalar);
1592 out["idleProb"] = encode_shaped(r.idleProb, scalar);
1593 out["analyzer"] = r.analyzer;
1594 return out;
1595 }
1596};
1597
1598struct OpQsysTandemLindley {
1599 template <class T>
1600 static Json run(Args& a) {
1601 const std::vector<T> A = a.vector<T>("A");
1602 const Matrix<T> S = a.matrix<T>("S");
1603 const bool hasW0 = a.has("W0");
1604 const std::vector<T> W0 = a.vector_or_empty<T>("W0");
1605 a.done();
1606 const qsys::TandemLindleyResult<T> r =
1607 hasW0 ? qsys::qsys_tandem_lindley<T>(A, S, W0) : qsys::qsys_tandem_lindley<T>(A, S);
1608 Json out;
1609 out["W"] = encode_matrix(r.W);
1610 out["G"] = encode_matrix(r.G);
1611 out["T"] = encode_matrix(r.T_);
1612 out["departure"] = encode_matrix(r.departure);
1613 out["analyzer"] = r.analyzer;
1614 return out;
1615 }
1616};
1617
1618struct OpQsysMm1Ps {
1619 template <class T>
1620 static Json run(Args& a) {
1621 const std::vector<T> lambda = a.vector<T>("lambda");
1622 const std::vector<T> mu = a.vector<T>("mu");
1623 a.done();
1624 const qsys::Mm1PsResult<T> r = qsys::qsys_mm1_ps<T>(lambda, mu);
1625 Json out;
1626 out["W"] = encode_vector(r.W);
1627 out["W2"] = encode_vector(r.W2);
1628 out["alpha"] = encode_scalar(r.alpha);
1629 return out;
1630 }
1631};
1632
1633// ---------------------------------------------------------------------------
1634// qsys: the remaining stand-alone systems
1635// ---------------------------------------------------------------------------
1636
1637/**
1638 * qsys_mg1_ps(lambda, svc, svcparam, ...), the phase-type path: svc is the
1639 * initial vector alpha and svcparam the subgenerator T. The transform-handle
1640 * path (svc a handle, svcparam the mean) and the 'pdf' option are handles and
1641 * cannot cross. The handle-valued outputs are not reported; their tabulations
1642 * on x, s and t are.
1643 */
1644struct OpQsysMg1Ps {
1645 static Json run(Args& a) {
1646 const double lambda = a.number<double>("lambda");
1647 if (a.get("svc").is_string())
1648 throw UnsupportedError(ErrorKind{"JsonApi"},
1649 "qsys_mg1_ps: argument 'svc' cannot cross the JSON API boundary as a transform "
1650 "handle; give the phase-type initial vector alpha, with svcparam its "
1651 "subgenerator T");
1652 const std::vector<double> alpha = a.vector<double>("svc");
1653 const Matrix<double> Tm = a.matrix<double>("svcparam");
1654 qsys::Mg1PsOptions opt;
1655 if (a.has("x")) opt.x = a.vector<double>("x");
1656 if (a.has("s")) opt.s = a.vector<double>("s");
1657 if (a.has("t")) opt.t = a.vector<double>("t");
1658 opt.nterms = a.count("nterms", opt.nterms);
1659 a.unsupported("pdf", "it is a density function handle; on the phase-type path the port "
1660 "derives the density itself");
1661 a.done();
1662 const qsys::Mg1PsResult r = qsys::qsys_mg1_ps(lambda, alpha, Tm, opt);
1663 Json out;
1664 out["rho"] = r.rho;
1665 out["m1"] = r.m1;
1666 out["m2"] = r.m2;
1667 out["x"] = encode_vector(r.x);
1668 out["s"] = encode_vector(r.s);
1669 out["t"] = encode_vector(r.t);
1670 out["lstCondVal"] = encode_matrix(r.lstCondVal);
1671 out["lstUncondVal"] = encode_vector(r.lstUncondVal);
1672 out["atomCond"] = encode_vector(r.atomCond);
1673 out["atomUncond"] = r.atomUncond;
1674 out["meanCond"] = encode_vector(r.meanCond);
1675 out["m2Cond"] = encode_vector(r.m2Cond);
1676 out["varCond"] = encode_vector(r.varCond);
1677 out["meanUncond"] = r.meanUncond;
1678 out["m2Uncond"] = r.m2Uncond;
1679 out["varUncond"] = r.varUncond;
1680 out["pdfCond"] = encode_matrix(r.pdfCond);
1681 out["cdfCond"] = encode_matrix(r.cdfCond);
1682 out["pdfUncond"] = encode_vector(r.pdfUncond);
1683 out["cdfUncond"] = encode_vector(r.cdfUncond);
1684 return out;
1685 }
1686};
1687
1688/**
1689 * qsys_bmapm1(D, mu, ...). The port's tuned overload takes all five options;
1690 * Uniformization and MaxLevel have the port's own "select automatically"
1691 * values (<= 0 and 0), which are what MATLAB's empty defaults mean, while
1692 * MaxIter, Tolerance and TailTolerance have numeric defaults that are not
1693 * restated: naming any option therefore requires those three.
1694 */
1695struct OpQsysBmapm1 {
1696 template <class T>
1697 static Json run(Args& a) {
1698 const std::vector<Matrix<T> > D = a.matrices<T>("D");
1699 const T mu = a.number<T>("mu");
1700 const bool tuned = a.has("Uniformization") || a.has("MaxLevel") || a.has("MaxIter") ||
1701 a.has("Tolerance") || a.has("TailTolerance");
1702 if (tuned && !(a.has("MaxIter") && a.has("Tolerance") && a.has("TailTolerance")))
1703 throw InputError("qsys_bmapm1: the port takes its options together; with any of them "
1704 "give 'MaxIter', 'Tolerance' and 'TailTolerance'");
1705 const T q = a.scalar<T>("Uniformization", num_traits<T>::from_int(0));
1706 const std::size_t maxLevel = a.count("MaxLevel", 0);
1707 const unsigned maxIter = a.uinteger("MaxIter", 0);
1708 const T tol = a.scalar<T>("Tolerance", num_traits<T>::from_int(0));
1709 const double tailTol = a.scalar<double>("TailTolerance", 0.0);
1710 a.done();
1711 const qsys::BmapM1Result<T> r =
1712 tuned ? qsys::qsys_bmapm1<T>(D, mu, q, maxLevel, maxIter, tol, tailTol)
1713 : qsys::qsys_bmapm1<T>(D, mu);
1714 Json out;
1715 out["theta"] = encode_vector(r.theta);
1716 out["lambda"] = encode_scalar(r.lambda);
1717 out["rho"] = encode_scalar(r.rho);
1718 out["q"] = encode_scalar(r.q);
1719 out["A0"] = encode_matrix(r.A0);
1720 out["A1"] = encode_matrix(r.A1);
1721 out["B0"] = encode_matrix(r.B0);
1722 out["Bk"] = encode_matrices(r.Bk);
1723 out["A"] = encode_matrix(r.A);
1724 out["alpha"] = encode_vector(r.alpha);
1725 out["G"] = encode_matrix(r.G);
1726 out["drift"] = encode_scalar(r.drift);
1727 out["decayRate"] = r.decayRate;
1728 out["levelProb"] = encode_matrix(r.levelProb);
1729 out["pi0"] = encode_scalar(r.pi0);
1730 out["meanQueueLength"] = encode_scalar(r.meanQueueLength);
1731 out["utilization"] = encode_scalar(r.utilization);
1732 out["throughput"] = encode_scalar(r.throughput);
1733 out["truncLevel"] = encode_count(r.truncLevel);
1734 out["truncError"] = r.truncError;
1735 out["gConverged"] = r.gConverged;
1736 return out;
1737 }
1738};
1739
1740/** qsys_maxima_twomoment(n, mean_, cs2, 'q', 'exactFitted'), positional in the port. */
1741struct OpQsysMaximaTwomoment {
1742 template <class T>
1743 static Json run(Args& a) {
1744 const std::size_t n = a.count("n");
1745 const T mean = a.number<T>("mean_");
1746 const T cs2 = a.number<T>("cs2");
1747 const std::size_t k = prefix_count(a, {"q", "exactFitted"}, "qsys_maxima_twomoment");
1748 const T q = k >= 1 ? a.number<T>("q") : T();
1749 const bool ef = k >= 2 ? a.boolean("exactFitted", false) : false;
1750 a.done();
1751 const qsys::MaximaResult<T> r =
1752 k == 0 ? qsys::qsys_maxima_twomoment<T>(n, mean, cs2)
1753 : (k == 1 ? qsys::qsys_maxima_twomoment<T>(n, mean, cs2, q)
1754 : qsys::qsys_maxima_twomoment<T>(n, mean, cs2, q, ef));
1755 Json out;
1756 out["value"] = encode_scalar(r.value);
1757 out["slope"] = encode_scalar(r.slope);
1758 out["eta"] = encode_scalar(r.eta);
1759 out["threshold"] = encode_scalar(r.threshold);
1760 out["reliable"] = r.reliable;
1761 out["family"] = r.family;
1762 if (r.hasFitted) out["exactFittedValue"] = encode_scalar(r.exactFittedValue);
1763 return out;
1764 }
1765};
1766
1767/**
1768 * qsys_mgisrgi_whitt(lambda, mu, s, r, patience, ...). r may be the string
1769 * "Inf". A numeric patience is the exponential rate theta, as in MATLAB; the
1770 * hazard and ccdf forms are function handles and cannot cross. The options
1771 * keep the port's MgisrgiOptions defaults unless named.
1772 */
1773struct OpQsysMgisrgiWhitt {
1774 template <class T>
1775 static Json run(Args& a) {
1776 const T lambda = a.number<T>("lambda");
1777 const T mu = a.number<T>("mu");
1778 const unsigned s = a.uinteger("s");
1779 const double r = a.number<double>("r");
1780 const Json& pj = a.get("patience");
1781 if (pj.is_object() || pj.is_string())
1782 throw UnsupportedError(ErrorKind{"JsonApi"},
1783 "qsys_mgisrgi_whitt: argument 'patience' cannot cross the JSON API boundary as a "
1784 "hazard or ccdf function handle; give the exponential rate theta as a number");
1785 const qsys::Patience<T> patience =
1786 qsys::Patience<T>::exponential(a.number<T>("patience"));
1787 qsys::MgisrgiOptions opt;
1788 if (a.has("wPoints")) opt.wPoints = a.vector<double>("wPoints");
1789 opt.maxQueue = a.count("maxQueue", opt.maxQueue);
1790 opt.tol = a.scalar<double>("tol", opt.tol);
1791 opt.invMethod = a.text("invMethod", opt.invMethod);
1792 opt.invN = a.count("invN", opt.invN);
1793 a.done();
1794 const qsys::QsysAbandonResult<T> res =
1795 qsys::qsys_mgisrgi_whitt<T>(lambda, mu, s, r, patience, opt);
1796 Json out;
1797 out["queueLengthDist"] = encode_vector(res.queueLengthDist);
1798 out["probLoss"] = encode_scalar(res.probLoss);
1799 out["probNoWait"] = encode_scalar(res.probNoWait);
1800 out["probServed"] = encode_scalar(res.probServed);
1801 out["probAbandon"] = encode_scalar(res.probAbandon);
1802 out["meanNumber"] = encode_scalar(res.meanNumber);
1803 out["varNumber"] = encode_scalar(res.varNumber);
1804 out["meanQueueLength"] = encode_scalar(res.meanQueueLength);
1805 out["varQueueLength"] = encode_scalar(res.varQueueLength);
1806 out["utilization"] = encode_scalar(res.utilization);
1807 out["throughput"] = encode_scalar(res.throughput);
1808 out["abandonRate"] = encode_scalar(res.abandonRate);
1809 out["meanWaitServed"] = encode_scalar(res.meanWaitServed);
1810 out["varWaitServed"] = encode_scalar(res.varWaitServed);
1811 out["meanWaitAbandon"] = encode_scalar(res.meanWaitAbandon);
1812 out["varWaitAbandon"] = encode_scalar(res.varWaitAbandon);
1813 out["meanWait"] = encode_scalar(res.meanWait);
1814 out["secondMomentWait"] = encode_scalar(res.secondMomentWait);
1815 out["abandonRates"] = encode_vector(res.abandonRates);
1816 out["totalAbandonRates"] = encode_vector(res.totalAbandonRates);
1817 out["numWaitingSpaces"] = encode_count(res.numWaitingSpaces);
1818 out["exponentialPatience"] = res.exponentialPatience;
1819 out["patienceRate"] = encode_scalar(res.patienceRate);
1820 out["waitPoints"] = encode_vector(res.waitPoints);
1821 out["cdfWaitServed"] = encode_vector(res.cdfWaitServed);
1822 out["cdfWaitAbandon"] = encode_vector(res.cdfWaitAbandon);
1823 out["cdfWait"] = encode_vector(res.cdfWait);
1824 return out;
1825 }
1826};
1827
1828/** qsys_mapmapc(D0, D1, S0, S1, c, 'maxNumComp', 'numWMoms'), positional in the port. */
1829struct OpQsysMapmapc {
1830 template <class T>
1831 static Json run(Args& a) {
1832 const mam::Map<T> arrival = read_map<T>(a, "D0", "D1");
1833 const mam::Map<T> service = read_map<T>(a, "S0", "S1");
1834 const unsigned c = a.uinteger("c");
1835 const std::size_t k = prefix_count(a, {"maxNumComp", "numWMoms"}, "qsys_mapmapc");
1836 const std::size_t dsz = k >= 1 ? a.count("maxNumComp") : 0;
1837 const std::size_t nw = k >= 2 ? a.count("numWMoms") : 0;
1838 a.done();
1839 const qsys::MapPhcResult<T> r =
1840 k == 0 ? qsys::qsys_mapmapc<T>(arrival, service, c)
1841 : (k == 1 ? qsys::qsys_mapmapc<T>(arrival, service, c, dsz)
1842 : qsys::qsys_mapmapc<T>(arrival, service, c, dsz, nw));
1843 Json out;
1844 out["meanQueueLength"] = encode_scalar(r.meanQueueLength);
1845 out["meanWaitingTime"] = encode_scalar(r.meanWaitingTime);
1846 out["meanSojournTime"] = encode_scalar(r.meanSojournTime);
1847 out["utilization"] = encode_scalar(r.utilization);
1848 out["queueLengthDist"] = encode_vector(r.queueLengthDist);
1849 out["waitingTimeMoments"] = encode_vector(r.waitingTimeMoments);
1850 out["waitingTimeCCDF"] = encode_vector(r.waitingTimeCCDF);
1851 out["waitingTimePoints"] = encode_vector(r.waitingTimePoints);
1852 out["probWait"] = encode_scalar(r.probWait);
1853 out["phaseCount"] = encode_count(r.phaseCount);
1854 return out;
1855 }
1856};
1857
1858/**
1859 * qsys_mmapmap1(D, svc, 'carry'). D is MATLAB's BUTools-layout cell
1860 * {D0, D1_1, ..., D1_K}: the per-mark blocks, whose sum is the aggregate D1.
1861 * svc is a list of [S0, S1] pairs, one per mark.
1862 */
1863struct OpQsysMmapmap1 {
1864 template <class T>
1865 static Json run(Args& a) {
1866 const std::vector<Matrix<T> > D = a.matrices<T>("D");
1867 const std::vector<mam::Map<T> > svc = maps_from_json<T>(a.get("svc"), "qsys_mmapmap1: svc");
1868 const bool hasCarry = a.has("carry");
1869 const std::vector<int> ci = a.ints_or_empty("carry");
1870 a.done();
1871 if (D.size() < 2)
1872 throw InputError("qsys_mmapmap1: D must be {D0, D1_1, ..., D1_K} with K >= 1");
1873 mam::Mmap<T> mm;
1874 mm.D0 = D[0];
1875 mm.D1 = D[1];
1876 mm.Dc.push_back(D[1]);
1877 for (std::size_t k = 2; k < D.size(); ++k) {
1878 if (D[k].rows() != mm.D1.rows() || D[k].cols() != mm.D1.cols())
1879 throw InputError("qsys_mmapmap1: the blocks of D must share one size");
1880 for (std::size_t i = 0; i < mm.D1.rows(); ++i)
1881 for (std::size_t j = 0; j < mm.D1.cols(); ++j)
1882 mm.D1(i, j) = T(mm.D1(i, j) + D[k](i, j));
1883 mm.Dc.push_back(D[k]);
1884 }
1885 std::vector<bool> carry;
1886 for (std::size_t i = 0; i < ci.size(); ++i) {
1887 if (ci[i] != 0 && ci[i] != 1)
1888 throw InputError("qsys_mmapmap1: 'carry' holds flags, 0 or 1");
1889 carry.push_back(ci[i] != 0);
1890 }
1891 const qsys::MmapMap1Result<T> r = hasCarry ? qsys::qsys_mmapmap1<T>(mm, svc, carry)
1892 : qsys::qsys_mmapmap1<T>(mm, svc);
1893 Json out;
1894 out["meanQueueLength"] = encode_vector(r.meanQueueLength);
1895 out["meanSojournTime"] = encode_vector(r.meanSojournTime);
1896 out["arrivalRate"] = encode_vector(r.arrivalRate);
1897 Json cj = Json::array();
1898 for (std::size_t i = 0; i < r.carry.size(); ++i) cj.push_back(static_cast<bool>(r.carry[i]));
1899 out["carry"] = cj;
1900 out["markCount"] = encode_count(r.markCount);
1901 return out;
1902 }
1903};
1904
1905// ---------------------------------------------------------------------------
1906// sim: planning and option helpers
1907// ---------------------------------------------------------------------------
1908
1909/** sim_quest_options(options): the MATLAB options struct, validated and completed. */
1910struct OpSimQuestOptions {
1911 static Json run(Args& a) {
1912 sim::QuestOptions in;
1913 const Json* oj = a.opt("options");
1914 if (oj) {
1915 Args o(*oj, "sim_quest_options: options");
1916 in.b0 = static_cast<long>(o.integer("b0", static_cast<int>(in.b0)));
1917 in.m0 = static_cast<long>(o.integer("m0", static_cast<int>(in.m0)));
1918 if (o.has("s")) {
1919 const std::vector<int> s = o.ints("s");
1920 in.s.assign(s.begin(), s.end());
1921 }
1922 in.beta = o.scalar<double>("beta", in.beta);
1923 in.eta = o.scalar<double>("eta", in.eta);
1924 in.theta = o.scalar<double>("theta", in.theta);
1925 in.weight = o.scalar<double>("weight", in.weight);
1926 in.force = o.boolean("force", in.force);
1927 o.done();
1928 }
1929 a.done();
1930 const sim::QuestOptions r = oj ? sim::sim_quest_options(in) : sim::sim_quest_options();
1931 Json opt;
1932 opt["b0"] = static_cast<long long>(r.b0);
1933 opt["m0"] = static_cast<long long>(r.m0);
1934 Json s = Json::array();
1935 for (std::size_t i = 0; i < r.s.size(); ++i) s.push_back(static_cast<long long>(r.s[i]));
1936 opt["s"] = s;
1937 opt["beta"] = r.beta;
1938 opt["eta"] = r.eta;
1939 opt["theta"] = r.theta;
1940 opt["weight"] = r.weight;
1941 opt["force"] = r.force;
1942 Json out;
1943 out["opt"] = opt;
1944 return out;
1945 }
1946};
1947
1948struct OpSimQuestHeuristicCi {
1949 template <class T>
1950 static Json run(Args& a) {
1951 if constexpr (!num_traits<T>::has_transcendental) {
1952 throw UnsupportedError(ErrorKind{"Arithmetic"}, sim_exact_refusal(
1953 "sim_quest_heuristic_ci", "the interval is a quantile times a square root"));
1954 } else {
1955 const std::vector<T> bqe = a.vector<T>("bqe");
1956 const T centre = a.number<T>("centre");
1957 const T Ap = a.number<T>("Ap");
1958 const T Np = a.number<T>("Np");
1959 const std::size_t nstar = a.count("nstar");
1960 const double alpha = a.number<double>("alpha");
1961 const bool ac = required_flag(a, "useAutocorr", "sim_quest_heuristic_ci");
1962 a.done();
1963 const sim::QuestInterval<T> r =
1964 sim::sim_quest_heuristic_ci<T>(bqe, centre, Ap, Np, nstar, alpha, ac);
1965 Json out;
1966 out["lower"] = encode_scalar(r.lower);
1967 out["upper"] = encode_scalar(r.upper);
1968 return out;
1969 }
1970 }
1971};
1972
1973/** sim_runlength(mean_, asymVar, 'relPrecision', 'confidence', 'runLength'), positional. */
1974struct OpSimRunlength {
1975 template <class T>
1976 static Json run(Args& a) {
1977 if constexpr (!num_traits<T>::has_transcendental) {
1978 throw UnsupportedError(ErrorKind{"Arithmetic"}, sim_exact_refusal(
1979 "sim_runlength", "the run length is set by a normal quantile"));
1980 } else {
1981 const T mean = a.number<T>("mean_");
1982 const T av = a.number<T>("asymVar");
1983 const std::size_t k =
1984 prefix_count(a, {"relPrecision", "confidence", "runLength"}, "sim_runlength");
1985 const T rp = k >= 1 ? a.number<T>("relPrecision") : T();
1986 const T cf = k >= 2 ? a.number<T>("confidence") : T();
1987 const T rl = k >= 3 ? a.number<T>("runLength") : T();
1988 a.done();
1989 sim::RunLengthResult<T> r;
1990 if (k == 0) r = sim::sim_runlength<T>(mean, av);
1991 else if (k == 1) r = sim::sim_runlength<T>(mean, av, rp);
1992 else if (k == 2) r = sim::sim_runlength<T>(mean, av, rp, cf);
1993 else r = sim::sim_runlength<T>(mean, av, rp, cf, rl);
1994 Json out;
1995 out["requiredRunLength"] = encode_scalar(r.requiredRunLength);
1996 out["z"] = encode_scalar(r.z);
1997 if (r.hasRun) {
1998 out["halfWidth"] = encode_scalar(r.halfWidth);
1999 out["achievedRelPrecision"] = encode_scalar(r.achievedRelPrecision);
2000 }
2001 return out;
2002 }
2003 }
2004};
2005
2006// ---------------------------------------------------------------------------
2007// Exact closed forms: finite-source, loss, priority, busy-period, setup and
2008// renewal-arrival queues. A law argument (svc, LA, EU, lst) is the model.json
2009// distribution record; MATLAB's LST-handle form has no JSON spelling.
2010// ---------------------------------------------------------------------------
2011
2012/** The refusal of an LST function handle where the reference also takes one. */
2013[[noreturn]] void refuse_lst_handle(const std::string& fn, const char* key) {
2014 throw UnsupportedError(ErrorKind{"JsonApi"},
2015 fn + ": argument '" + key + "' cannot cross the JSON API boundary as an LST function "
2016 "handle; give it as a distribution record {\"type\": ..., ...}");
2017}
2018
2019/** qsys_mmckk(alpha, mu, c, K, 'tPoints', 'percentiles'): M/M/c/K/K. */
2020struct OpQsysMmckk {
2021 static Json run(Args& a) {
2022 const double alpha = a.number<double>("alpha");
2023 const double mu = a.number<double>("mu");
2024 const unsigned c = a.uinteger("c");
2025 const unsigned K = a.uinteger("K");
2026 const qsys::QsysResOptions o = read_qsys_res_options(a, false);
2027 a.done();
2028 return encode_qsys_res(qsys::qsys_mmckk(alpha, mu, c, K, o));
2029 }
2030};
2031
2032/**
2033 * qsys_fcfs_alis(lambda, mu, compat): the isolated FCFS-ALIS pool. compat is a
2034 * C x M matrix whose nonzero entries mark a compatible class-server pair, as
2035 * MATLAB's logical(compat).
2036 */
2037struct OpQsysFcfsAlis {
2038 template <class T>
2039 static Json run(Args& a) {
2040 const std::vector<T> lambda = a.vector<T>("lambda");
2041 const std::vector<T> mu = a.vector<T>("mu");
2042 const Matrix<T> cm = a.matrix<T>("compat");
2043 a.done();
2044 const T zero = num_traits<T>::from_int(0);
2045 std::vector<std::vector<bool> > compat(cm.rows(), std::vector<bool>(cm.cols(), false));
2046 for (std::size_t c = 0; c < cm.rows(); ++c)
2047 for (std::size_t m = 0; m < cm.cols(); ++m) compat[c][m] = cm(c, m) != zero;
2048 const qsys::FcfsAlisResult<T> r = qsys::qsys_fcfs_alis<T>(lambda, mu, compat);
2049 Json out = Json::object();
2050 out["Q"] = encode_vector(r.Q);
2051 out["Qw"] = encode_vector(r.Qw);
2052 out["X"] = encode_matrix(r.X);
2053 out["U"] = encode_vector(r.U);
2054 out["P0"] = encode_scalar(r.P0);
2055 out["stable"] = r.stable;
2056 return out;
2057 }
2058};
2059
2060/** qsys_engset(alpha, mu, c, K): the Engset loss system. */
2061struct OpQsysEngset {
2062 static Json run(Args& a) {
2063 const double alpha = a.number<double>("alpha");
2064 const double mu = a.number<double>("mu");
2065 const unsigned c = a.uinteger("c");
2066 const unsigned K = a.uinteger("K");
2067 a.done();
2068 return encode_qsys_res(qsys::qsys_engset(alpha, mu, c, K));
2069 }
2070};
2071
2072/** qsys_mg1kk(alpha, K, svc[, ES]): the finite-source M/G/1//K queue (Takacs). */
2073struct OpQsysMg1kk {
2074 static Json run(Args& a) {
2075 const double alpha = a.number<double>("alpha");
2076 const unsigned K = a.uinteger("K");
2077 if (a.get("svc").is_string()) refuse_lst_handle("qsys_mg1kk", "svc");
2078 const lang::Distrib<double> svc = dist_record<double>(a.get("svc"), "qsys_mg1kk: svc");
2079 // With a Distribution the reference reads the mean from the law and ignores ES.
2080 if (a.has("ES")) (void)a.number<double>("ES");
2081 a.done();
2082 return encode_qsys_res(qsys::qsys_mg1kk(alpha, K, svc));
2083 }
2084};
2085
2086/** qsys_ddckk(EO, ES, c, K): the deterministic finite-source D/D/c/K/K queue. */
2087struct OpQsysDdckk {
2088 template <class T>
2089 static Json run(Args& a) {
2090 const T EO = a.number<T>("EO");
2091 const T ES = a.number<T>("ES");
2092 const unsigned c = a.uinteger("c");
2093 const unsigned K = a.uinteger("K");
2094 a.done();
2095 return encode_qsys_res(qsys::qsys_ddckk(EO, ES, c, K));
2096 }
2097};
2098
2099/** qsys_mg1_setup(lambda, mu, cs, EU[, EU2]): M/G/1 with setup times; EU a number or a law. */
2100struct OpQsysMg1Setup {
2101 template <class T>
2102 static Json run(Args& a) {
2103 const T lambda = a.number<T>("lambda");
2104 const T mu = a.number<T>("mu");
2105 const T cs = a.number<T>("cs");
2106 qsys::Mg1SetupResult<T> r;
2107 if (a.get("EU").is_object()) {
2108 const lang::Distrib<T> U = dist_record<T>(a.get("EU"), "qsys_mg1_setup: EU");
2109 a.done();
2110 r = qsys::qsys_mg1_setup(lambda, mu, cs, U);
2111 } else {
2112 const T EU = a.number<T>("EU");
2113 if (!a.has("EU2"))
2114 throw InputError(ErrorKind("Argument"),
2115 "qsys_mg1_setup: qsys_mg1_setup needs the second moment EU2 of the setup time "
2116 "after EU, or a setup Distribution in place of EU");
2117 const T EU2 = a.number<T>("EU2");
2118 a.done();
2119 r = qsys::qsys_mg1_setup(lambda, mu, cs, EU, EU2);
2120 }
2121 Json out;
2122 out["W"] = encode_scalar(r.W);
2123 out["Wq"] = encode_scalar(r.Wq);
2124 out["U"] = encode_scalar(r.U);
2125 out["Q"] = encode_scalar(r.Q);
2126 out["res"] = encode_qsys_res(r.res);
2127 return out;
2128 }
2129};
2130
2131/** qsys_mg1_exceptional(lambda, mu, cs, muf, csf): M/G/1 with exceptional first service. */
2132struct OpQsysMg1Exceptional {
2133 template <class T>
2134 static Json run(Args& a) {
2135 const T lambda = a.number<T>("lambda");
2136 const T mu = a.number<T>("mu");
2137 const T cs = a.number<T>("cs");
2138 const T muf = a.number<T>("muf");
2139 const T csf = a.number<T>("csf");
2140 a.done();
2141 const qsys::Mg1ExceptionalResult<T> r = qsys::qsys_mg1_exceptional(lambda, mu, cs, muf, csf);
2142 Json out;
2143 out["W"] = encode_scalar(r.W);
2144 out["Wq"] = encode_scalar(r.Wq);
2145 out["U"] = encode_scalar(r.U);
2146 out["Q"] = encode_scalar(r.Q);
2147 out["res"] = encode_qsys_res(r.res);
2148 return out;
2149 }
2150};
2151
2152/** qsys_mmcc(lambda, mu, c): the Erlang-B loss system. */
2153struct OpQsysMmcc {
2154 static Json run(Args& a) {
2155 const double lambda = a.number<double>("lambda");
2156 const double mu = a.number<double>("mu");
2157 const unsigned c = a.uinteger("c");
2158 a.done();
2159 return encode_qsys_res(qsys::qsys_mmcc(lambda, mu, c));
2160 }
2161};
2162
2163/** qsys_mgc_ps(lambda, mu, c): the insensitive M/G/c processor-sharing queue. */
2164struct OpQsysMgcPs {
2165 static Json run(Args& a) {
2166 const double lambda = a.number<double>("lambda");
2167 const double mu = a.number<double>("mu");
2168 const unsigned c = a.uinteger("c");
2169 a.done();
2170 return encode_qsys_res(qsys::qsys_mgc_ps(lambda, mu, c));
2171 }
2172};
2173
2174/** qsys_mg1_prio_pr(lambda, mu, cs, 'ES3'): preemptive-resume priority M/G/1. */
2175struct OpQsysMg1PrioPr {
2176 template <class T>
2177 static Json run(Args& a) {
2178 const std::vector<T> lambda = a.vector<T>("lambda");
2179 const std::vector<T> mu = a.vector<T>("mu");
2180 const std::vector<T> cs = a.vector<T>("cs");
2181 const std::vector<T> ES3 = a.vector_or_empty<T>("ES3");
2182 a.done();
2183 const qsys::Mg1PrioPrResult<T> r = qsys::qsys_mg1_prio_pr(lambda, mu, cs, ES3);
2184 Json out;
2185 out["W"] = encode_vector(r.W);
2186 out["rhohat"] = encode_scalar(r.rho);
2187 out["res"] = encode_qsys_res(r.res);
2188 return out;
2189 }
2190};
2191
2192/** qsys_mmc_prio(lambda, mu, c): non-preemptive priority M/M/c, common service rate. */
2193struct OpQsysMmcPrio {
2194 template <class T>
2195 static Json run(Args& a) {
2196 const std::vector<T> lambda = a.vector<T>("lambda");
2197 const T mu = a.number<T>("mu");
2198 const unsigned c = a.uinteger("c");
2199 a.done();
2200 const qsys::MmcPrioResult<T> r = qsys::qsys_mmc_prio(lambda, mu, c);
2201 Json out;
2202 out["W"] = encode_vector(r.W);
2203 out["rhohat"] = encode_scalar(r.rho);
2204 out["res"] = encode_qsys_res(r.res);
2205 return out;
2206 }
2207};
2208
2209/** qsys_mmc_prio_tardiness(lambda, mu, c, d[, type, method]): exact priority M/M/c tardiness (HGK 2013). */
2210struct OpQsysMmcPrioTardiness {
2211 static Json run(Args& a) {
2212 const std::vector<double> lambda = a.vector<double>("lambda");
2213 const double mu = a.number<double>("mu");
2214 const unsigned c = a.uinteger("c");
2215 const std::vector<double> d = a.vector<double>("d");
2216 const std::string type = a.text("type", "np");
2217 const std::string method = a.text("method", "euler");
2218 a.done();
2219 const qsys::MmcPrioTardinessResult r = qsys::qsys_mmc_prio_tardiness(lambda, mu, c, d, type, method);
2220 Json out;
2221 out["Tard"] = encode_vector(r.Tard);
2222 out["Ptard"] = encode_vector(r.Ptard);
2223 out["res"] = encode_qsys_res(r.res);
2224 return out;
2225 }
2226};
2227
2228/** qsys_mmc_prio_eta(lambda, mu, c, r, v, q, d[, type, method]): expected tardiness at arrival (HGK 2013). */
2229struct OpQsysMmcPrioEta {
2230 static Json run(Args& a) {
2231 const std::vector<double> lambda = a.vector<double>("lambda");
2232 const double mu = a.number<double>("mu");
2233 const unsigned c = a.uinteger("c");
2234 const unsigned r = a.uinteger("r");
2235 const unsigned v = a.uinteger("v");
2236 const unsigned q = a.uinteger("q");
2237 const std::vector<double> d = a.vector<double>("d");
2238 const std::string type = a.text("type", "np");
2239 const std::string method = a.text("method", "euler");
2240 a.done();
2241 const qsys::MmcPrioEtaResult e = qsys::qsys_mmc_prio_eta(lambda, mu, c, r, v, q, d, type, method);
2242 Json out;
2243 out["Tard"] = encode_vector(e.Tard);
2244 out["Ptard"] = encode_vector(e.Ptard);
2245 out["S"] = encode_scalar(e.S);
2246 return out;
2247 }
2248};
2249
2250/**
2251 * [Fc, info] = qsys_mtmstm_dets(mu, theta, s0, tk, dsk, nq, tau, policy[, wait]):
2252 * DETS waiting-time CCDF of the Mt/M/st+M queue (Konrad and Liu, WSC 2023).
2253 * dsk is the net change per change time, or a K-by-2 [added, removed] matrix,
2254 * told apart as MATLAB does: a vector with one entry per change time is the
2255 * net form. An infinite meanPWT is spelled "Inf".
2256 */
2257struct OpQsysMtmstmDets {
2258 static Json run(Args& a) {
2259 const double mu = a.number<double>("mu");
2260 const double theta = a.number<double>("theta");
2261 const int s0 = a.required_integer("s0");
2262 const std::vector<double> tk = a.vector_or_empty<double>("tk");
2263 const Matrix<double> dm = a.matrix_or_empty<double>("dsk");
2264 const int nq = a.required_integer("nq");
2265 const std::vector<double> tau = a.vector<double>("tau");
2266 const std::string policy = a.text("policy", "");
2267 const std::string wait = a.text("wait", "pwt");
2268 a.done();
2269 const auto to_int = [](double v) {
2270 if (!std::isfinite(v) || v != std::floor(v) || std::fabs(v) > 2147483647.0)
2271 throw InputError(ErrorKind{"Argument"}, "qsys_mtmstm_dets: The staffing changes must be integers.");
2272 return static_cast<int>(v);
2273 };
2274 const std::size_t K = tk.size();
2275 qsys::DetsResult r;
2276 if (dm.rows() == K && dm.cols() == 2 && !((dm.rows() == 1 || dm.cols() == 1) && dm.rows() * dm.cols() == K)) {
2277 std::vector<std::array<int, 2> > pairs(K);
2278 for (std::size_t k = 0; k < K; ++k) pairs[k] = {{to_int(dm(k, 0)), to_int(dm(k, 1))}};
2279 r = qsys::qsys_mtmstm_dets(mu, theta, s0, tk, pairs, nq, tau, policy, wait);
2280 } else {
2281 std::vector<int> net;
2282 for (std::size_t i = 0; i < dm.rows(); ++i)
2283 for (std::size_t j = 0; j < dm.cols(); ++j) net.push_back(to_int(dm(i, j)));
2284 r = qsys::qsys_mtmstm_dets(mu, theta, s0, tk, net, nq, tau, policy, wait);
2285 }
2286 Json info;
2287 info["cdf"] = encode_vector(r.cdf);
2288 info["meanPWT"] = std::isinf(r.meanPWT) ? Json("Inf") : Json(r.meanPWT);
2289 info["meanAWT"] = encode_scalar(r.meanAWT);
2290 info["poa"] = encode_scalar(r.poa);
2291 info["s"] = encode_ints(r.s);
2292 Json out;
2293 out["Fc"] = encode_vector(r.Fc);
2294 out["info"] = info;
2295 return out;
2296 }
2297};
2298
2299/** qsys_mg1_conservation(lambda, mu, cs[, W]): Kleinrock's conservation law. */
2300struct OpQsysMg1Conservation {
2301 template <class T>
2302 static Json run(Args& a) {
2303 const std::vector<T> lambda = a.vector<T>("lambda");
2304 const std::vector<T> mu = a.vector<T>("mu");
2305 const std::vector<T> cs = a.vector<T>("cs");
2306 const std::vector<T> W = a.vector_or_empty<T>("W");
2307 a.done();
2308 const qsys::Mg1ConservationResult<T> r = qsys::qsys_mg1_conservation(lambda, mu, cs, W);
2309 Json res = Json::object();
2310 res["invariant"] = encode_scalar(r.V);
2311 res["fcfsWaitingTime"] = encode_scalar(r.fcfsWaitingTime);
2312 // MATLAB's NaN when W is not given; JSON has no NaN, so null.
2313 res["residual"] = r.hasResidual ? encode_scalar(r.residual) : Json();
2314 Json out;
2315 out["V"] = encode_scalar(r.V);
2316 out["res"] = res;
2317 return out;
2318 }
2319};
2320
2321/** qsys_mg1_sjf(lambda, mu, cs): non-preemptive shortest-job-first M/G/1. */
2322struct OpQsysMg1Sjf {
2323 static Json run(Args& a) {
2324 const std::vector<double> lambda = a.vector<double>("lambda");
2325 const std::vector<double> mu = a.vector<double>("mu");
2326 const std::vector<double> cs = a.vector<double>("cs");
2327 a.done();
2328 const qsys::Mg1SjfResult r = qsys::qsys_mg1_sjf(lambda, mu, cs);
2329 Json out;
2330 out["W"] = encode_vector(r.W);
2331 out["rhohat"] = r.rhohat;
2332 out["res"] = encode_qsys_res(r.res);
2333 return out;
2334 }
2335};
2336
2337/** qsys_mg1_busy(lambda, mu, cs, 'ES3', 'lst', 'sPoints'): the M/G/1 busy period. */
2338struct OpQsysMg1Busy {
2339 static Json run(Args& a) {
2340 const double lambda = a.number<double>("lambda");
2341 const double mu = a.number<double>("mu");
2342 const double cs = a.number<double>("cs");
2343 qsys::Mg1BusyOptions o;
2344 if (a.has("ES3")) o.ES3 = a.number<double>("ES3");
2345 if (a.has("lst")) {
2346 if (a.get("lst").is_string()) refuse_lst_handle("qsys_mg1_busy", "lst");
2347 const lang::Distrib<double> d = dist_record<double>(a.get("lst"), "qsys_mg1_busy: lst");
2348 o.lst = [d](double s) { return lang::dist_lst(d, s); };
2349 }
2350 if (a.has("sPoints")) o.sPoints = a.vector<double>("sPoints");
2351 a.done();
2352 return encode_qsys_res(qsys::qsys_mg1_busy(lambda, mu, cs, o));
2353 }
2354};
2355
2356/** qsys_gimc(LA, mu, c, 'lambda', 'tPoints', 'percentiles', 'nmax'): the GI/M/c queue. */
2357struct OpQsysGimc {
2358 static Json run(Args& a) {
2359 if (a.get("LA").is_string()) refuse_lst_handle("qsys_gimc", "LA");
2360 const lang::Distrib<double> LA = dist_record<double>(a.get("LA"), "qsys_gimc: LA");
2361 const double mu = a.number<double>("mu");
2362 const unsigned c = a.uinteger("c");
2363 const double lambda = a.has("lambda") ? a.number<double>("lambda") : -1.0;
2364 const qsys::QsysResOptions o = read_qsys_res_options(a);
2365 a.done();
2366 return encode_qsys_res(qsys::qsys_gimc(LA, mu, c, o, lambda));
2367 }
2368};
2369
2370/** qsys_md1(lambda, mu, 'nmax'): the M/D/1 queue. */
2371struct OpQsysMd1 {
2372 static Json run(Args& a) {
2373 const double lambda = a.number<double>("lambda");
2374 const double mu = a.number<double>("mu");
2375 const long nmax = a.has("nmax") ? static_cast<long>(a.count("nmax")) : -1L;
2376 a.done();
2377 return encode_qsys_res(qsys::qsys_md1(lambda, mu, nmax));
2378 }
2379};
2380
2381/** The complex roots and coefficients, as [re, im] pairs. */
2382Json encode_cplx_pairs(const std::vector<std::complex<double> >& v) {
2383 Json out = Json::array();
2384 for (const std::complex<double>& z : v) out.push_back(Json::array({z.real(), z.imag()}));
2385 return out;
2386}
2387
2388/** qsys_mer1(lambda, mu, r, 'tPoints', 'percentiles', 'nmax'): the M/Er/1 queue. */
2389struct OpQsysMer1 {
2390 static Json run(Args& a) {
2391 const double lambda = a.number<double>("lambda");
2392 const double mu = a.number<double>("mu");
2393 const unsigned r = a.uinteger("r");
2394 const qsys::QsysResOptions o = read_qsys_res_options(a);
2395 a.done();
2396 const qsys::Mer1Result m = qsys::qsys_mer1(lambda, mu, r, o);
2397 Json out = encode_qsys_res(m.res);
2398 // MATLAB's res.roots and res.coeffs are complex; a complex number is a pair [re, im].
2399 out["roots"] = encode_cplx_pairs(m.roots);
2400 out["coeffs"] = encode_cplx_pairs(m.coeffs);
2401 return out;
2402 }
2403};
2404
2405/** qsys_mh21(lambda, p1, mu1, mu2, 'tPoints', 'percentiles', 'nmax'): the M/H2/1 queue. */
2406struct OpQsysMh21 {
2407 static Json run(Args& a) {
2408 const double lambda = a.number<double>("lambda");
2409 const double p1 = a.number<double>("p1");
2410 const double mu1 = a.number<double>("mu1");
2411 const double mu2 = a.number<double>("mu2");
2412 const qsys::QsysResOptions o = read_qsys_res_options(a);
2413 a.done();
2414 return encode_qsys_res(qsys::qsys_mh21(lambda, p1, mu1, mu2, o));
2415 }
2416};
2417
2418/** [P,EN,P0,res] = qsys_mm1_transient(lambda, mu, n0, t, nmax, 'tol', tol, 'method', m). */
2419struct OpQsysMm1Transient {
2420 static Json run(Args& a) {
2421 const double lambda = a.number<double>("lambda");
2422 const double mu = a.number<double>("mu");
2423 const double n0 = a.number<double>("n0");
2424 const std::vector<double> t = a.vector<double>("t");
2425 const double nmax = a.has("nmax") ? a.number<double>("nmax") : std::numeric_limits<double>::quiet_NaN();
2426 const double tol = a.has("tol") ? a.number<double>("tol") : 1e-14;
2427 const std::string method = a.text("method", "auto");
2428 a.done();
2429 const qsys::Mm1TransientResult r = qsys::qsys_mm1_transient(lambda, mu, n0, t, nmax, tol, method);
2430 Json res;
2431 res["rho"] = r.rho;
2432 res["nmax"] = r.nmax;
2433 res["tol"] = r.tol;
2434 res["method"] = r.method;
2435 res["errBound"] = encode_vector(r.errBound);
2436 res["errBoundMean"] = encode_vector(r.errBoundMean);
2437 res["tailMass"] = encode_vector(r.tailMass);
2438 // [nL nR] per time, NaN for 'bessel' (spelled "NaN", the convention of this layer)
2439 Json win = Json::array();
2440 for (std::size_t i = 0; i < r.window.rows(); ++i) {
2441 Json row = Json::array();
2442 for (std::size_t k = 0; k < r.window.cols(); ++k)
2443 row.push_back(std::isnan(r.window(i, k)) ? Json("NaN") : Json(r.window(i, k)));
2444 win.push_back(row);
2445 }
2446 res["window"] = win;
2447 Json out;
2448 out["P"] = encode_matrix(r.P);
2449 out["EN"] = encode_vector(r.EN);
2450 out["P0"] = encode_vector(r.P0);
2451 out["res"] = res;
2452 return out;
2453 }
2454};
2455
2456/** [P,EN,P0,res] = qsys_mm1k_transient(lambda, mu, K, n0, t, 'tol', tol, 'method', m). */
2457struct OpQsysMm1kTransient {
2458 static Json run(Args& a) {
2459 const double lambda = a.number<double>("lambda");
2460 const double mu = a.number<double>("mu");
2461 const double K = a.number<double>("K");
2462 const double n0 = a.number<double>("n0");
2463 const std::vector<double> t = a.vector<double>("t");
2464 const double tol = a.has("tol") ? a.number<double>("tol") : 1e-14;
2465 const std::string method = a.text("method", "auto");
2466 a.done();
2467 const qsys::Mm1kTransientResult r = qsys::qsys_mm1k_transient(lambda, mu, K, n0, t, tol, method);
2468 Json res;
2469 res["rho"] = r.rho;
2470 res["method"] = r.method;
2471 res["kappa"] = r.kappa;
2472 res["errBound"] = encode_vector(r.errBound);
2473 res["pi"] = encode_vector(r.pi);
2474 res["tol"] = r.tol;
2475 Json out;
2476 out["P"] = encode_matrix(r.P);
2477 out["EN"] = encode_vector(r.EN);
2478 out["P0"] = encode_vector(r.P0);
2479 out["res"] = res;
2480 return out;
2481 }
2482};
2483
2484/**
2485 * result = qsys_match_fcfm(lambda, G, K): the FCFM stochastic matching model.
2486 * K is optional (default Inf, no capacity). When K = Inf and NCond fails the
2487 * measures are Inf/NaN, so every double is encoded through finite_or_text.
2488 */
2489struct OpQsysMatchFcfm {
2490 static Json finite_or_text(double v) {
2491 if (std::isnan(v)) return Json("NaN");
2492 if (std::isinf(v)) return Json(v > 0 ? "Inf" : "-Inf");
2493 return Json(v);
2494 }
2495 static Json vec(const std::vector<double>& v) {
2496 Json a = Json::array();
2497 for (double x : v) a.push_back(finite_or_text(x));
2498 return a;
2499 }
2500 static Json mat(const std::vector<std::vector<double> >& m) {
2501 Json a = Json::array();
2502 for (const auto& row : m) a.push_back(vec(row));
2503 return a;
2504 }
2505 static Json run(Args& a) {
2506 const std::vector<double> lambda = a.vector<double>("lambda");
2507 const Matrix<double> Gm = a.matrix<double>("G");
2508 const double K = a.has("K") ? a.number<double>("K") : std::numeric_limits<double>::infinity();
2509 a.done();
2510 std::vector<std::vector<double> > G(Gm.rows(), std::vector<double>(Gm.cols(), 0.0));
2511 for (std::size_t i = 0; i < Gm.rows(); ++i)
2512 for (std::size_t j = 0; j < Gm.cols(); ++j) G[i][j] = Gm(i, j);
2513 const qsys::MatchFcfmResult r = qsys::qsys_match_fcfm(lambda, G, K);
2514 Json res = Json::object();
2515 res["Q"] = vec(r.Q);
2516 res["W"] = vec(r.W);
2517 res["X"] = vec(r.X);
2518 res["omega"] = vec(r.omega);
2519 res["pblock"] = vec(r.pblock);
2520 res["pmatch"] = mat(r.pmatch);
2521 res["rmatch"] = mat(r.rmatch);
2522 res["P0"] = finite_or_text(r.P0);
2523 res["Z"] = finite_or_text(r.Z);
2524 res["piSet"] = vec(r.piSet);
2525 res["stable"] = r.stable;
2526 res["analyzer"] = "qsys_match_fcfm";
2527 Json out;
2528 out["result"] = res;
2529 return out;
2530 }
2531};
2532
2533} // namespace
2534
2536 // moment: all three arithmetics
2537 t["moment_cumulant_from_raw"] = make<OpMomentCumulantFromRaw>();
2538 t["moment_raw_from_cumulant"] = make<OpMomentRawFromCumulant>();
2539 t["moment_factcumulant_from_factorial"] = make<OpMomentFactcumulantFromFactorial>();
2540 t["moment_factorial_from_factcumulant"] = make<OpMomentFactorialFromFactcumulant>();
2541 t["moment_binomial_from_tail"] = make<OpMomentBinomialFromTail>();
2542 t["moment_tail_from_binomial"] = make<OpMomentTailFromBinomial>();
2543 t["moment_housematrix"] = make<OpMomentHousematrix>();
2544 t["moment_tensorsize"] = make<OpMomentTensorsize>();
2545 t["moment_tensortrans"] = make<OpMomentTensortrans>();
2546 t["moment_jointtrans"] = make<OpMomentJointtrans>();
2547 t["moment_joint_aggregate"] = make<OpMjAggregate>();
2548 t["moment_joint_marking"] = make<OpMjMarking>();
2549 t["moment_joint_central_from_raw_mean"] = make<OpMjCentralFromRawMean>();
2550 t["moment_joint_raw_from_central"] = make<OpMjRawFromCentral>();
2551 t["moment_joint_binomial_from_factorial"] = make<OpMjBinomialFromFactorial>();
2552 t["moment_joint_binomial_from_negbinomial"] = make<OpMjBinomialFromNegbinomial>();
2553 t["moment_joint_binomial_from_tail"] = make<OpMjBinomialFromTail>();
2554 t["moment_joint_central_from_raw"] = make<OpMjCentralFromRaw>();
2555 t["moment_joint_central_from_tail"] = make<OpMjCentralFromTail>();
2556 t["moment_joint_cumulant_from_raw"] = make<OpMjCumulantFromRaw>();
2557 t["moment_joint_factcumulant_from_factorial"] = make<OpMjFactcumulantFromFactorial>();
2558 t["moment_joint_factorial_from_binomial"] = make<OpMjFactorialFromBinomial>();
2559 t["moment_joint_factorial_from_factcumulant"] = make<OpMjFactorialFromFactcumulant>();
2560 t["moment_joint_factorial_from_raw"] = make<OpMjFactorialFromRaw>();
2561 t["moment_joint_factorial_from_upfactorial"] = make<OpMjFactorialFromUpfactorial>();
2562 t["moment_joint_negbinomial_from_binomial"] = make<OpMjNegbinomialFromBinomial>();
2563 t["moment_joint_negbinomial_from_upfactorial"] = make<OpMjNegbinomialFromUpfactorial>();
2564 t["moment_joint_raw_from_cumulant"] = make<OpMjRawFromCumulant>();
2565 t["moment_joint_raw_from_factorial"] = make<OpMjRawFromFactorial>();
2566 t["moment_joint_raw_from_upfactorial"] = make<OpMjRawFromUpfactorial>();
2567 t["moment_joint_tail_from_binomial"] = make<OpMjTailFromBinomial>();
2568 t["moment_joint_upfactorial_from_factorial"] = make<OpMjUpfactorialFromFactorial>();
2569 t["moment_joint_upfactorial_from_negbinomial"] = make<OpMjUpfactorialFromNegbinomial>();
2570 t["moment_joint_upfactorial_from_raw"] = make<OpMjUpfactorialFromRaw>();
2571
2572 // fj: all three arithmetics
2573 t["fj_amva"] = make<OpFjAmva>();
2574 t["fj_char_max_blom"] = make<OpFjCharMaxBlom>();
2575 t["fj_cox_fit"] = make<OpFjCoxFit>();
2576 t["fj_dag_makespan"] = make<OpFjDagMakespan>();
2577 t["fj_ism_green"] = make<OpFjIsmGreen>();
2578 t["fj_lst_max_het"] = make<OpFjLstMaxHet>();
2579 t["fj_qgb"] = make<OpFjQgb>();
2580 t["fj_respt_bulk"] = make<OpFjResptBulk>();
2581 t["fj_respt_closed"] = make<OpFjResptClosed>();
2582 t["fj_respt_nosplit"] = make<OpFjResptNosplit>();
2583 t["fj_serialization"] = make<OpFjSerialization>();
2584 t["fj_tsm_capacity"] = make<OpFjTsmCapacity>();
2585 t["fj_xmax_coxian"] = make<OpFjXmaxCoxian>();
2586 t["fj_xmax_het"] = make<OpFjXmaxHet>();
2587 t["fj_xmax_hz"] = make<OpFjXmaxHz>();
2588 t["fj_xmax_moments_het"] = make<OpFjXmaxMomentsHet>();
2589 t["fj_mg1_respt_moments"] = make<OpFjMg1ResptMoments>();
2590 t["fj_branch_members"] = make<OpFjBranchMembers>();
2591 t["fj_dist2fj"] = make<OpFjDist2fj>();
2592 // fj: double and real
2593 t["fj_char_max_discrete"] = make<NeedsTranscendental<OpFjCharMaxDiscrete> >();
2594 t["fj_delay_opt"] = make<NeedsTranscendental<OpFjDelayOpt> >();
2595 t["fj_dispersion"] = make<NeedsTranscendental<OpFjDispersion> >();
2596 t["fj_tail_forktail"] = make<NeedsTranscendental<OpFjTailForktail> >();
2597 t["fj_tail_ordstat"] = make<NeedsTranscendental<OpFjTailOrdstat> >();
2598
2599 // aoi
2600 t["aoi_lst_det"] = make<NeedsTranscendental<OpAoiLstDet> >();
2601 t["aoi_lst_erlang"] = make<OpAoiLstErlang>();
2602 t["aoi_lst_exp"] = make<OpAoiLstExp>();
2603 t["aoi_lst_ph"] = make<OpAoiLstPh>();
2604 t["aoi_dist2ph"] = make<OpAoiDist2ph>();
2605 // qsys: the registry lists all three arithmetics for these six, but the hh1,
2606 // lindley_moment, mm1 and mm1_tandem ports static_assert a transcendental
2607 // scalar, so an exact call is refused here with the Arithmetic reason.
2608 t["qsys_hh1_lindley"] = make<NeedsTranscendental<OpQsysHh1Lindley>>();
2609 t["qsys_lindley_moment"] = make<NeedsTranscendental<OpQsysLindleyMoment>>();
2610 t["qsys_mm1_lindley"] = make<NeedsTranscendental<OpQsysMm1Lindley>>();
2611 t["qsys_mm1_ps"] = make<OpQsysMm1Ps>();
2612 t["qsys_mm1_tandem_lindley"] = make<NeedsTranscendental<OpQsysMm1TandemLindley>>();
2613 t["qsys_tandem_lindley"] = make<OpQsysTandemLindley>();
2614 // qsys: double and real
2615 t["qsys_mapg1k"] = make<NeedsTranscendental<OpQsysMapg1k> >();
2616 t["qsys_mmapg1k"] = make<NeedsTranscendental<OpQsysMmapg1k> >();
2617 t["qsys_mapg1k_perflow"] = make<NeedsTranscendental<OpQsysMapg1kPerflow> >();
2618 t["qsys_svclaw_coeffs"] = make<NeedsTranscendental<OpQsysSvclawCoeffs> >();
2619 t["qsys_ldps_workload"] = make<NeedsTranscendental<OpQsysLdpsWorkload> >();
2620 t["qsys_mmapgk1"] = make<NeedsTranscendental<OpQsysMmapgk1> >();
2621 t["qsys_mmapgk1_lcfspr"] = make<NeedsTranscendental<OpQsysMmapgk1Lcfspr> >();
2622 t["qsys_tandem_ub_ciucu"] = make<NeedsTranscendental<OpQsysTandemUbCiucu> >();
2623 t["qsys_bmapm1"] = make<NeedsTranscendental<OpQsysBmapm1> >();
2624 t["qsys_maxima_twomoment"] = make<NeedsTranscendental<OpQsysMaximaTwomoment> >();
2625 t["qsys_mgisrgi_whitt"] = make<NeedsTranscendental<OpQsysMgisrgiWhitt> >();
2626 t["qsys_mapmapc"] = make<NeedsTranscendental<OpQsysMapmapc> >();
2627 t["qsys_mmapmap1"] = make<NeedsTranscendental<OpQsysMmapmap1> >();
2628 // qsys: double only
2629 t["qsys_mg1_ps"] = make<DoubleOnly<OpQsysMg1Ps> >();
2630 t["qsys_mmckk"] = make<DoubleOnly<OpQsysMmckk> >();
2631 t["qsys_engset"] = make<DoubleOnly<OpQsysEngset> >();
2632 t["qsys_mm1_transient"] = make<DoubleOnly<OpQsysMm1Transient> >();
2633 t["qsys_mm1k_transient"] = make<DoubleOnly<OpQsysMm1kTransient> >();
2634 t["qsys_match_fcfm"] = make<DoubleOnly<OpQsysMatchFcfm> >();
2635 t["qsys_mg1kk"] = make<DoubleOnly<OpQsysMg1kk> >();
2636 t["qsys_mmcc"] = make<DoubleOnly<OpQsysMmcc> >();
2637 t["qsys_mgc_ps"] = make<DoubleOnly<OpQsysMgcPs> >();
2638 t["qsys_mg1_sjf"] = make<DoubleOnly<OpQsysMg1Sjf> >();
2639 t["qsys_mg1_busy"] = make<DoubleOnly<OpQsysMg1Busy> >();
2640 t["qsys_gimc"] = make<DoubleOnly<OpQsysGimc> >();
2641 t["qsys_md1"] = make<DoubleOnly<OpQsysMd1> >();
2642 t["qsys_mer1"] = make<DoubleOnly<OpQsysMer1> >();
2643 t["qsys_mh21"] = make<DoubleOnly<OpQsysMh21> >();
2644 // qsys exact closed forms: all three arithmetics
2645 t["qsys_ddckk"] = make<OpQsysDdckk>();
2646 t["qsys_mg1_setup"] = make<OpQsysMg1Setup>();
2647 t["qsys_mg1_exceptional"] = make<OpQsysMg1Exceptional>();
2648 t["qsys_mg1_prio_pr"] = make<OpQsysMg1PrioPr>();
2649 t["qsys_mmc_prio"] = make<OpQsysMmcPrio>();
2650 t["qsys_mmc_prio_tardiness"] = make<DoubleOnly<OpQsysMmcPrioTardiness> >();
2651 t["qsys_mmc_prio_eta"] = make<DoubleOnly<OpQsysMmcPrioEta> >();
2652 t["qsys_mtmstm_dets"] = make<DoubleOnly<OpQsysMtmstmDets> >();
2653 t["qsys_mg1_conservation"] = make<OpQsysMg1Conservation>();
2654 t["qsys_fcfs_alis"] = make<OpQsysFcfsAlis>();
2655
2656 // sim
2657 t["sim_quest_options"] = make<DoubleOnly<OpSimQuestOptions> >();
2658 t["sim_quest_heuristic_ci"] = make<OpSimQuestHeuristicCi>();
2659 t["sim_runlength"] = make<OpSimRunlength>();
2660}
2661
2663 t["qsys_oi_loss"] =
2664 "its order-independent service rate mu is a callable of the per-class count vector "
2665 "(std::function), which has no JSON representation.";
2666 t["qsys_gig1_rq"] =
2667 "its interarrival law IaFun is a function handle (a CDF or transform evaluated by the "
2668 "port), and the port offers no constructor that builds it from a named law.";
2669 t["qsys_mg1k_loss"] =
2670 "its service law svc_density is a density function handle the port integrates, and the "
2671 "port takes no named-law form for it.";
2672 t["qsys_ggingi_tga"] =
2673 "its patience law (patienceCcdf, patiencePdf) and service law (serviceCcdf) are function "
2674 "handles the port integrates, with no named-law form.";
2675 t["qsys_ggisgi_fluid"] =
2676 "its patience and service laws (patienceCcdf, servingCcdf) are function handles the port "
2677 "integrates, with no named-law form.";
2678 t["qsys_gtmtst_fluid"] =
2679 "its time-varying arrival rate, staffing and service rate (lambdaFun, sFun, muFun) and "
2680 "its patience law (patienceCcdf) are function handles of time.";
2681 t["qsys_mtginf"] =
2682 "its time-varying arrival rate lambdaFun is a function handle of time and its service law "
2683 "serviceCcdf a function handle, with no named-law form.";
2684 t["qsys_mtgs0_mol"] =
2685 "its time-varying arrival rate lambdaFun is a function handle of time and its service law "
2686 "serviceCcdf a function handle, with no named-law form.";
2687 t["fj_order_stat"] =
2688 "its branch law F_X is a CDF function handle the port evaluates, with no named-law form.";
2689 t["fj_xmax_hz_het"] =
2690 "its branch laws are a list of CDF function handles the port integrates, with no "
2691 "named-law form.";
2692}
2693
2694} // namespace reg
2695} // namespace line
MAP to PH conversion for the age-of-information solvers.
Laplace-Stieltjes transform of a deterministic (constant) distribution.
Laplace-Stieltjes transform of an Erlang-k distribution.
Laplace-Stieltjes transform of an exponential distribution.
Laplace-Stieltjes transform of a phase-type distribution PH(alpha, T).
Internal to the –api dispatcher: what a per-domain translation unit needs to add entries to the table...
#define LINE_MOMENT_TENSOR_OP(OPNAME, FN, IN, OUT)
#define LINE_MOMENT_VEC_OP(OPNAME, FN, IN, OUT)
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
Named-argument reader over the parsed JSON object.
Definition api_json.h:391
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
Mean value analysis of a closed network of fork-join subnetworks.
Activities belonging to each branch of an AND-join.
Blom-corrected plotting position for the characteristic maximum.
Characteristic maximum of a lattice random variable.
Two-stage Coxian fit of a mean and a squared coefficient of variation.
Makespan of a task system with precedence constraints.
Deterministic subtask delays that minimise mean dispersion.
Mean subtask dispersion of a split-merge system with Erlang branches.
Conversion of a LINE MAP into the arrival or service descriptor of the fork-join response-time-tail a...
Green's independent server model of simultaneous server requests.
Laplace-Stieltjes transform of the maximum of heterogeneous exponentials.
Mean and variance of the M/G/1 response time, as ForkTail inputs.
Geometric bound on the queue length of a fork-join subnetwork.
Centralized splitting analysed as an M[K]/M/c bulk arrival system.
Varki bound on the residence time of a closed fork-join subnetwork.
Mean response time of the distributed no-splitting parallel system.
Blocking probability and pseudoserver delay of serialization phases.
ForkTail black-box tail-latency approximation for fork-join requests.
Tail latency of a k-of-n (QUORUM) fork-join request.
Saturation throughput of the team service model.
Expected maximum of K i.i.d.
Exact moments of the maximum of heterogeneous exponentials.
Harrison-Zertal approximation of the maximum of i.i.d.
Moments of the maximum of heterogeneous exponentials by recurrence.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Cumulants from raw moments and the inverse, plus the factorial-cumulant pair.
Conversion matrix of one edge of the house of moments.
Joint moment conversions on the house of moments.
Binomial moments from tail moments and the inverse.
Joint moment arrays and the mode products used by every joint conversion.
std::function< T(const T &)> Lst
A Laplace-Stieltjes transform evaluated at real arguments.
Definition aoi_types.h:41
Lst< T > aoi_lst_exp(const T &mu)
Laplace-Stieltjes transform of an exponential distribution.
Definition aoi_lst_exp.h:36
Lst< T > aoi_lst_erlang(unsigned k, const T &mu)
Laplace-Stieltjes transform of an Erlang-k distribution.
Lst< T > aoi_lst_ph(const std::vector< T > &alpha, const Matrix< T > &Tmat)
Laplace-Stieltjes transform of a phase-type distribution PH(alpha, T).
Definition aoi_lst_ph.h:48
AoiPh< T > aoi_dist2ph(const Matrix< T > &D0, const Matrix< T > &D1)
Convert a MAP (D0, D1) into the PH pair (alpha, T).
Definition aoi_dist2ph.h:68
Lst< T > aoi_lst_det(const T &d)
Laplace-Stieltjes transform of a deterministic (constant) distribution.
Definition aoi_lst_det.h:37
std::string nm(const char *tag, std::size_t i, std::size_t r)
std::vector< T > fj_xmax_moments_het(const std::vector< T > &lambda, unsigned n=1)
Moments of the maximum of heterogeneous exponentials by recurrence.
FjDistKind
Which of the two descriptors to build.
Definition fj_dist2fj.h:68
FJCharMaxBlomResult< T > fj_char_max_blom(unsigned K, const std::function< T(const T &)> &Finv=std::function< T(const T &)>(), const T &alpha=num_traits< T >::from_double(0.4886), const T &beta=num_traits< T >::from_double(0.3140))
Blom-corrected plotting position for the characteristic maximum.
T fj_lst_max_het(const std::vector< T > &lambda, const T &s)
Laplace-Stieltjes transform of the maximum of heterogeneous exponentials.
FJIsmGreenResult< T > fj_ism_green(const T &lambda, const T &mu, unsigned s, const std::vector< T > &c)
Green's independent server model of simultaneous server requests.
FJDelayOptResult< T > fj_delay_opt(const std::vector< unsigned > &shape, const std::vector< T > &rate, unsigned maxsweeps=40, const T &dtol=num_traits< T >::from_double(1e-8), unsigned npanels=2000)
Deterministic subtask delays that minimise mean dispersion.
FJXmaxCoxianResult< T > fj_xmax_coxian(unsigned K, const T &mu1, const T &mu2, const T &q)
Expected maximum of K i.i.d.
std::vector< std::vector< std::size_t > > fj_branch_members(const LqnBranchView< T > &lqn, std::size_t joinaidx)
Branch membership of an AND-join.
FJDagMakespanResult< T > fj_dag_makespan(const Matrix< T > &pred, const Matrix< T > &rate)
Makespan of a task system with precedence constraints.
FJResptNosplitResult< T > fj_respt_nosplit(unsigned K, const T &lambda, const T &mu)
Mean response time of the distributed no-splitting parallel system.
FJTsmCapacityResult< T > fj_tsm_capacity(unsigned s, const std::vector< T > &f, const std::vector< unsigned > &r, const std::vector< T > &x)
Saturation throughput of the team service model.
T fj_xmax_het(const std::vector< T > &lambda, unsigned n=1)
Exact moments of the maximum of heterogeneous exponentials.
Definition fj_xmax_het.h:40
FJCharMaxDiscreteResult< T > fj_char_max_discrete(unsigned K, FJDiscreteDist dist, const T &par)
Characteristic maximum of a lattice random variable.
FJSerializationResult< T > fj_serialization(const std::vector< T > &Rs, const T &R0, unsigned M, const T &alpha=num_traits< T >::from_double(0.5))
Blocking probability and pseudoserver delay of serialization phases.
Mg1ResptMoments< T > fj_mg1_respt_moments(const T &lambda, const T &ES, const T &ES2, const T &ES3)
Mean and variance of the M/G/1 response time, as ForkTail inputs.
FjDist< T > fj_dist2fj(const mam::Map< T > &m, FjDistKind kind, FjProcType procType)
Build the fork-join descriptor of a MAP.
Definition fj_dist2fj.h:99
ForkTailResult< T > fj_tail_forktail(const std::vector< T > &ET, const std::vector< T > &VT, const std::vector< T > &K=std::vector< T >(), const T &p_in=num_traits< T >::from_int(99), const std::vector< T > &P=std::vector< T >())
ForkTail black-box tail-latency approximation for fork-join requests.
FJResptClosedResult< T > fj_respt_closed(unsigned K, const T &x, unsigned M, const T &A)
Varki bound on the residence time of a closed fork-join subnetwork.
FJQgbResult< T > fj_qgb(const std::vector< T > &D, const std::vector< unsigned > &P, unsigned M, const T &Z)
Geometric bound on the queue length of a fork-join subnetwork.
Definition fj_qgb.h:52
FJXmaxHzResult< T > fj_xmax_hz(const T &m1, const T &m2, unsigned K)
Harrison-Zertal approximation of the maximum of i.i.d.
Definition fj_xmax_hz.h:47
ForkTailResult< T > fj_tail_ordstat(const std::vector< T > &ET, const std::vector< T > &VT, std::size_t K=1, const T &p_in=num_traits< T >::from_int(99), std::size_t kreq=0)
Tail latency of a k-of-n (QUORUM) fork-join request.
FJAmvaResult< T > fj_amva(const std::vector< T > &D, const std::vector< unsigned > &P, unsigned M, const T &Z)
Mean value analysis of a closed network of fork-join subnetworks.
Definition fj_amva.h:55
FJCoxFitResult< T > fj_cox_fit(const T &m1, const T &c2)
Two-stage Coxian fit of a mean and a squared coefficient of variation.
Definition fj_cox_fit.h:52
FJDispersionResult< T > fj_dispersion(const std::vector< unsigned > &shape, const std::vector< T > &rate, const std::vector< T > &d, const T &tol=num_traits< T >::from_double(1e-10), unsigned npanels=4000)
Mean subtask dispersion of a split-merge system with Erlang branches.
FjProcType
The subset of ProcessType that the fork-join algorithm accepts.
Definition fj_dist2fj.h:65
FJResptBulkResult< T > fj_respt_bulk(unsigned K, const T &lambda, const T &mu, unsigned c, std::size_t nmax=0)
Centralized splitting analysed as an M[K]/M/c bulk arrival system.
FJDiscreteDist
The lattice laws for which the characteristic maximum is closed.
long to_int(const std::string &s)
Python int(token): an optionally signed run of decimal digits.
T dist_lst(const Distrib< T > &d, const T &s)
sn.lst: the Laplace-Stieltjes transform E[exp(-sX)].
T dist_cdf(const Distrib< T > &d, const T &x)
F(x) = P{X <= x}, MATLAB's Distribution.evalCDF.
T dist_moment(const Distrib< T > &d, unsigned k)
The k-th raw moment.
double z(double v)
Definition lqn_focus.h:261
bool in(const std::string &s, std::initializer_list< const char * > set)
std::vector< T > moment_joint_aggregate(const MomentTensor< T > &F)
Factorial moments of a total count from the joint factorial moments of its parts.
MomentTensor< T > moment_joint_marking(const std::vector< T > &f, const std::vector< T > &p, const std::vector< std::size_t > &dims)
Joint factorial moments of a multinomially marked count from the aggregate ones.
std::vector< std::size_t > moment_tensorsize(const MomentTensor< T > &A)
Extents with the trailing singleton dimensions removed.
Matrix< T > moment_housematrix(MomentEdge edge, int n)
(n+1)x(n+1) conversion table of the given edge.
MomentTensor< T > moment_tensortrans(const MomentTensor< T > &A, const Matrix< T > &Tm, std::size_t mode)
Mode product: every fibre of A along dimension mode is replaced by Tm times that fibre.
MomentTensor< T > moment_joint_central_from_raw_mean(const MomentTensor< T > &m, const std::vector< T > &mu)
Joint central moments from joint raw moments about a given mean vector.
MomentTensor< T > moment_jointtrans(const MomentTensor< T > &A, MomentEdge edge)
Applies the conversion matrix of one edge along every dimension of A.
MomentTensor< T > moment_joint_raw_from_central(const MomentTensor< T > &mc, const std::vector< T > &mu)
Joint raw moments from joint central moments about a given mean vector.
@ Gm
the reference's alias of 'cub'
Definition pfqn_nc.h:111
Mg1ConservationResult< T > qsys_mg1_conservation(const std::vector< T > &lambda, const std::vector< T > &mu, const std::vector< T > &cs, const std::vector< T > &W=std::vector< T >())
The M/G/1 conservation-law invariant.
MaximaResult< T > qsys_maxima_twomoment(std::size_t n, const T &mean, const T &cs2, const T &q=num_traits< T >::from_int(0), bool exactFitted=true)
Two-moment approximation for the maximum of n iid non-negative variables.
MapG1kResult< T > qsys_mapg1k(const mam::Map< T > &arrival, const ServiceLaw< T > &svc, std::size_t K, const T &tol, std::size_t nmaxCap)
MAP/G/1/K with tail drop.
QsysRes qsys_gimc(const std::function< double(double)> &lst, double lambda, double mu, unsigned c, const QsysResOptions &o=QsysResOptions())
Definition qsys_gimc.h:74
LindleyResult< T > qsys_hh1_lindley(const std::vector< T > &lambda, const std::vector< T > &pa, const std::vector< T > &mu, const std::vector< T > &ps, const std::vector< T > &Wn, unsigned mmax=2)
Conditional waiting-time moments of the Hl/Hn/1 Lindley recursion.
Mer1Result qsys_mer1(double lambda, double mu, unsigned r, const QsysResOptions &o=QsysResOptions())
Exact M/Er/1 queue.
Definition qsys_mer1.h:57
LdpsWorkloadResult< T > qsys_ldps_workload(const T &lambda, const WorkloadServiceLaw< T > &B, const std::vector< T > &alpha, std::size_t N, const std::vector< T > &t, std::size_t ngrid)
Workload distribution of the load-dependent PS station with blocking.
MapPhcResult< T > qsys_mapmapc(const mam::Map< T > &arrival, const mam::Map< T > &service, unsigned c, std::size_t dist_size=500, std::size_t num_w_moms=3)
MAP/MAP/c FCFS with the service phase carried in start order, exactly.
FcfsAlisResult< T > qsys_fcfs_alis(const std::vector< T > &lambda, const std::vector< T > &mu, const std::vector< std::vector< bool > > &compat)
Exact means of the isolated FCFS-ALIS pool.
Mg1SjfResult qsys_mg1_sjf(const std::vector< double > &lambda, const std::vector< double > &mu, const std::vector< double > &cs)
M/G/1 non-preemptive SJF.
Mm1TandemLindleyResult< T > qsys_mm1_tandem_lindley(const T &lambda, const T &mu1, const T &mu2, const std::vector< T > &Wk, const std::vector< T > &Wk1)
Conditional waiting time at the SECOND station of an M/M/1 -> /M/1 tandem.
Mm1PsResult< T > qsys_mm1_ps(const std::vector< T > &lambda, const std::vector< T > &mu)
Exact sojourn-time moments of the multiclass M/M/1-PS queue.
Definition qsys_mm1_ps.h:63
Mg1ExceptionalResult< T > qsys_mg1_exceptional(const T &lambda, const T &mu, const T &cs, const T &muf, const T &csf)
M/G/1 with exceptional first service.
MmapGk1Result< T > qsys_mmapgk1(const std::vector< Matrix< T > > &MMAP, const std::vector< MmapGk1Service< T > > &svc, const std::vector< T > &w_points, std::size_t num_w_moms, double tol, std::size_t iter_max, std::size_t quad_nodes)
MMAP[K]/G[K]/1 FCFS, per type.
SvclawCoeffsResult< T > qsys_svclaw_coeffs(const ServiceLaw< T > &svc, const T &theta, const T &tol, std::size_t nmaxCap)
qsys_svclaw_coeffs: uniformization coefficients of a service-time descriptor; see qsys_svclaw_coeffs....
Mm1TransientResult qsys_mm1_transient(double lambda, double mu, double n0, const std::vector< double > &t, double nmax=std::numeric_limits< double >::quiet_NaN(), double tol=1e-14, const std::string &method_in="auto")
Transient distribution of the M/M/1 queue (Rubino 2020).
MmcPrioTardinessResult qsys_mmc_prio_tardiness(const std::vector< double > &lambda, double mu, unsigned c, const std::vector< double > &d, const std::string &type="np", const std::string &method="euler")
Stationary per-class expected tardiness of a priority M/M/c queue.
MmcPrioResult< T > qsys_mmc_prio(const std::vector< T > &lambda, const T &mu, unsigned c)
M/M/c with head-of-line priorities.
DetsResult qsys_mtmstm_dets(double mu, double theta, int s0, const std::vector< double > &tk, const std::vector< int > &dsk, int nq, const std::vector< double > &tau, const std::string &policy, const std::string &wait="pwt")
DETS waiting-time CCDF with the staffing changes given as net signed changes.
QsysRes qsys_mmckk(double alpha, double mu, unsigned c, unsigned K, const QsysResOptions &o=QsysResOptions())
Exact M/M/c/K/K finite-source queue.
Definition qsys_mmckk.h:48
QsysAbandonResult< T > qsys_mgisrgi_whitt(const T &lambda, const T &mu, unsigned s, double r, const Patience< T > &patience, const MgisrgiOptions &opts=MgisrgiOptions())
Engineering solution of the call-center model M/GI/s/r+GI.
MatchFcfmResult qsys_match_fcfm(const std::vector< double > &lam, const std::vector< std::vector< double > > &Gm, double Kcap=std::numeric_limits< double >::infinity())
Exact FCFM matching model.
QsysRes qsys_mh21(double lambda, double p1, double mu1, double mu2, const QsysResOptions &o=QsysResOptions())
Exact M/H2/1 queue.
Definition qsys_mh21.h:44
TandemLindleyResult< T > qsys_tandem_lindley(const std::vector< T > &A, const Matrix< T > &S, const std::vector< T > &W0=std::vector< T >())
Sample-path Lindley recursion along a tandem of single-server FCFS queues.
QsysResT< T > qsys_ddckk(const T &EO, const T &ES, unsigned c, unsigned K)
Exact D/D/c/K/K finite-source queue.
Definition qsys_ddckk.h:48
LindleyResult< T > qsys_mm1_lindley(const T &lambda, const T &mu, const std::vector< T > &Wn, unsigned mmax=2)
Conditional waiting-time moments of the M/M/1 Lindley recursion.
Mg1SetupResult< T > qsys_mg1_setup(const T &lambda, const T &mu, const T &cs, const T &EU, const T &EU2)
M/G/1 with setup times, setup given by its first two moments.
BmapM1Result< T > qsys_bmapm1(const std::vector< Matrix< T > > &D, const T &mu, const T &qParam, std::size_t maxLevelParam, unsigned maxIter, const T &tol, double tailTol)
BMAP/M/1 by the matrix-analytic (M/G/1-type) method.
TandemUbResult< T > qsys_tandem_ub_ciucu(const std::vector< T > &x, const std::function< T(const T &)> &lst, const std::vector< T > &p, const std::vector< T > &mu, const std::function< T(const T &)> &dlst=std::function< T(const T &)>())
Tail bounds for a GI/Hn/1 -> .
MmapMap1Result< T > qsys_mmapmap1(const mam::Mmap< T > &arrival, const std::vector< mam::Map< T > > &svc, std::vector< bool > carry=std::vector< bool >())
MMAP[K]/MAP[K]/1 FCFS with per-class carried service phases, exactly.
QsysRes qsys_engset(double alpha, double mu, unsigned c, unsigned K)
Exact Engset M/G/c/c/K loss system.
Definition qsys_engset.h:59
QsysRes qsys_mmcc(double lambda, double mu, unsigned c)
Exact M/M/c/c Erlang loss system.
Definition qsys_mmcc.h:38
Mg1PsResult qsys_mg1_ps(double lambda, const std::vector< double > &alpha, const Matrix< double > &Tmat, const Mg1PsOptions &opt)
Sojourn-time distribution of the M/G/1 processor-sharing queue.
QsysRes qsys_mg1_busy(double lambda, double mu, double cs, const Mg1BusyOptions &o=Mg1BusyOptions())
Busy-period measures of the M/G/1 queue.
QsysRes qsys_mgc_ps(double lambda, double mu, unsigned c)
Exact M/G/c-PS queue.
Definition qsys_mgc_ps.h:44
Mg1PrioPrResult< T > qsys_mg1_prio_pr(const std::vector< T > &lambda, const std::vector< T > &mu, const std::vector< T > &cs, const std::vector< T > &ES3=std::vector< T >())
M/G/1 with preemptive-resume priorities.
MmapG1kResult< T > qsys_mmapg1k(const Matrix< T > &D0, const std::vector< Matrix< T > > &D1c, const ServiceLaw< T > &svc, std::size_t K, const T &tol, std::size_t nmaxCap)
MMAP[K]/G/1/K with tail drop.
Mm1kTransientResult qsys_mm1k_transient(double lambda, double mu, double K, double n0, const std::vector< double > &t, double tol=1e-14, const std::string &method_in="auto")
Transient distribution of the M/M/1/K queue (Takacs; Rubino 2020).
MmapGk1LcfsprResult< T > qsys_mmapgk1_lcfspr(const std::vector< Matrix< T > > &MMAP, const std::vector< MmapGk1Service< T > > &svc, const MmapGk1LcfsprOptions< T > &opt)
MMAP[K]/G[K]/1 LCFS-PR, per type, by Takine's matrix product form.
MapG1kPerflowResult< T > qsys_mapg1k_perflow(const std::vector< mam::Map< T > > &flows, const ServiceLaw< T > &svc, std::size_t K, const T &tol, std::size_t nmaxCap)
Per-flow analysis of a MAP-fed tail-drop buffer.
QsysRes qsys_md1(double lambda, double mu, long nmax=-1)
Exact M/D/1 queue.
Definition qsys_md1.h:43
std::vector< T > qsys_lindley_moment(const T &lambda, const T &mu, const std::vector< T > &Wn, unsigned m)
One conditional Lindley moment for exponential primitives.
MmcPrioEtaResult qsys_mmc_prio_eta(const std::vector< double > &lambda, double mu, unsigned c, unsigned r, unsigned v, unsigned q, const std::vector< double > &d, const std::string &type="np", const std::string &method="euler")
Expected tardiness at arrival of a class-r order.
QsysRes qsys_mg1kk(double alpha, unsigned K, const std::function< double(double)> &lst, double ES, bool means_only=false)
Exact M/G/1/K/K finite-source queue, service given by its LST.
Definition qsys_mg1kk.h:65
nlohmann::json Json
Definition api_json.h:63
Json encode_vectors(const std::vector< std::vector< T > > &v)
A list of vectors, the shape a per-class or per-segment result returns.
Definition api_json.h:366
Matrix< T > matrix_from_json(const Json &j, const std::string &where)
A matrix from a JSON value: 2-D array as rows, 1-D array as a row vector, scalar as 1x1,...
Definition api_json.h:223
Json encode_matrices(const std::vector< Matrix< T > > &v)
A list of matrices, the shape the MMAP/BMAP families return as {D0,D1,...}.
Definition api_json.h:358
void register_api_qsys(DispatchTable &t)
qsys::QsysResOptions read_qsys_res_options(Args &a, bool with_nmax=true)
The 'tPoints', 'percentiles' and 'nmax' options those functions share.
T number_from_json(const Json &j, const std::string &where)
Definition api_json.h:210
Json encode_vector(const std::vector< T > &v)
Definition api_json.h:333
Json encode_matrix(const Matrix< T > &m)
Definition api_json.h:340
void register_library_only_qsys(LibraryOnlyTable &t)
Json encode_scalar(const T &v)
Definition api_json.h:328
Json encode_count(std::size_t n)
A count.
Definition api_json.h:378
std::map< std::string, std::string > LibraryOnlyTable
name -> why the function has no named-JSON-argument form.
Json encode_qsys_res(const qsys::QsysResT< T > &r)
MATLAB's res struct of the exact queueing-system functions: one key per measure, in the reference's f...
Json encode_ints(const std::vector< int > &v)
Definition api_json.h:350
std::map< std::string, Invoker > DispatchTable
QuestOptions sim_quest_options(const QuestOptions &options=QuestOptions())
Validates an option set and returns it.
QuestInterval< T > sim_quest_heuristic_ci(const std::vector< T > &bqe, const T &centre, const T &Ap, const T &Np, std::size_t nstar, double alpha, bool useAutocorr)
Fallback interval used when a QUEST stage test fails.
RunLengthResult< T > sim_runlength(const T &mean, const T &asymVar, const T &relPrecision=num_traits< T >::from_rational(1, 20), const T &confidence=num_traits< T >::from_rational(19, 20), const T &runLength=num_traits< T >::from_int(0))
Run length for a steady-state estimate of a given relative precision.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Reader for the LINE model.json interchange (a Network model) into a qn::Network<T> built through the ...
BMAP/M/1 by the matrix-analytic (M/G/1-type) method.
Exact analysis of the finite-source D/D/c/K/K machine-repair model.
Exact analysis of the Engset loss system M/G/c/c/K: K sources, each idle for an Exp(alpha) time,...
Exact steady-state means of an isolated FCFS parallel-server system with job-server compatibilities u...
Exact analysis of the GI/M/c queue (Takacs, 1962).
Conditional waiting-time moments of the Hl/Hn/1 Lindley recursion.
Stationary distribution of the unfinished work in a single-stage load-dependent generalized-processor...
One conditional Lindley moment for exponential primitives.
The MAP/G/1/K queue with tail drop: Markovian arrivals, an arbitrary service law F,...
Per-flow throughput and loss ratio of a tail-drop FIFO buffer fed by N flows of mutually different st...
The MAP/MAP/c FCFS queue whose service MAP is CARRIED in service-start order.
Exact analysis of the first-come-first-matched (FCFM) stochastic matching model (Comte 2022).
Two-moment approximation for the maximum of n iid non-negative variables.
Exact analysis of the M/D/1 queue: the M/G/1 moments with deterministic service plus the queue-length...
Exact analysis of the M/Er/1 queue (Erlang-r service of total rate mu/r per phase-sum,...
Busy-period measures of the M/G/1 queue.
Kleinrock's conservation law for work-conserving non-preemptive M/G/1 disciplines.
M/G/1 with exceptional first service: the job that starts a busy period has service law Bf,...
M/G/1 with preemptive-resume priorities: per-class mean (and optionally variance of the) response tim...
Sojourn-time distribution of the M/G/1 processor-sharing queue.
M/G/1 with setup times: the server switches off when empty and needs a setup time U before serving th...
M/G/1 with non-preemptive shortest-job-first scheduling: per-class mean response times.
Exact analysis of the finite-source M/G/1/K/K (machine-repair) queue.
Exact analysis of the M/G/c processor-sharing queue.
Engineering solution of the call-center model M/GI/s/r+GI.
Exact analysis of the M/H2/1 queue: hyperexponential service with branch probabilities (p1,...
Conditional waiting-time moments of the M/M/1 Lindley recursion.
Exact sojourn-time moments of the multiclass M/M/1-PS queue.
Conditional waiting time at the SECOND station of an M/M/1 -> /M/1 tandem.
Transient queue-length distribution of the M/M/1 queue.
Transient queue-length distribution of the M/M/1/K queue.
Exact per-class throughput and loss ratio of an MMAP[K]/G/1/K tail-drop queue.
The MMAP[K]/G[K]/1 FCFS queue: K customer types with class-dependent GENERAL service,...
The MMAP[K]/G[K]/1 LCFS-PR queue: K customer types with class-dependent GENERAL service under preempt...
The MMAP[K]/MAP[K]/1 FCFS queue in which each class's service phase is CARRIED.
M/M/c with non-preemptive (head-of-line) priorities and a common exponential service rate (Cobham,...
Expected tardiness at arrival (ETA) in a multiclass priority M/M/c queue, conditional on the state th...
Exact stationary expected tardiness in a multiclass priority M/M/c queue (Hafizoglu,...
Exact analysis of the M/M/c/c (Erlang loss) system.
Exact analysis of the finite-source M/M/c/K/K (machine-repair) queue.
DETS, the delay estimator under time-varying staffing of Konrad and Liu (WSC 2023): waiting-time dist...
Sample-path Lindley recursion along a tandem of single-server FCFS queues.
Tail bounds for a GI/Hn/1 -> .
Fallback interval used when a QUEST stage test fails.
Options of the QUEST procedures, with the published FQUEST defaults.
Run-length planning for steady-state simulation.
ErrorKind(std::string n)
Definition error.h:39
static Patience exponential(const T &theta)
Exponential patience of rate theta, h(t) = theta, the Erlang A case.
static ServiceLaw deterministic(const T &d)
Constant service time d.
static ServiceLaw phase_type(const std::vector< T > &alpha, const Matrix< T > &Tmat)
Phase type (alpha, Tmat).
static ServiceLaw gamma(const T &shape, const T &scale)
Gamma(shape, scale).