LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
api_dispatch_trace.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 'trace' group (see api_dispatch_detail.h):
6 * the trace, mtrace and infer domains.
7 *
8 * ARGUMENT AND RESULT NAMES are the MATLAB ones: a trace is a JSON vector, a
9 * marked trace a vector plus a label vector, and the results carry the MATLAB
10 * output names. Where the port leaves a statistic UNDEFINED (a class with no
11 * sample, which MATLAB reports as 0/0 = NaN) the entry is written as JSON null
12 * at every arithmetic, rather than as whatever the port left in the slot.
13 *
14 * POSITIONAL OPTIONALS. A MATLAB positional optional maps onto a C++ default
15 * argument. An absent optional calls the shorter overload, so no default is
16 * restated here; a later optional given without the earlier ones is refused,
17 * because reaching it would mean inventing the value of the earlier one.
18 */
19
20#include "api_dispatch_detail.h"
21
22#include <array>
23#include <cctype>
24#include <cmath>
25#include <cstddef>
26#include <functional>
27#include <limits>
28#include <string>
29#include <vector>
30
77
78namespace line {
79namespace reg {
80
81namespace {
82
83// ---------------------------------------------------------------------------
84// Shared readers and encoders
85// ---------------------------------------------------------------------------
86
87Json encode_longs(const std::vector<long>& v) {
88 Json a = Json::array();
89 for (long x : v) a.push_back(static_cast<long long>(x));
90 return a;
91}
92
93Json encode_long_matrix(const Matrix<long>& m) {
94 Json a = Json::array();
95 for (std::size_t i = 0; i < m.rows(); ++i) {
96 Json row = Json::array();
97 for (std::size_t k = 0; k < m.cols(); ++k) row.push_back(static_cast<long long>(m(i, k)));
98 a.push_back(row);
99 }
100 return a;
101}
102
103Json encode_sizes(const std::vector<std::size_t>& v) {
104 Json a = Json::array();
105 for (std::size_t x : v) a.push_back(encode_count(x));
106 return a;
107}
108
109/** An undefined statistic (no sample behind it) is null, at every arithmetic. */
110template <class T>
111Json encode_defined(const T& v, long count) {
112 return count == 0 ? Json(nullptr) : encode_scalar(v);
113}
114
115template <class T>
116Json encode_vector_defined(const std::vector<T>& v, const std::vector<long>& count) {
117 Json a = Json::array();
118 for (std::size_t k = 0; k < v.size(); ++k) a.push_back(encode_defined(v[k], count[k]));
119 return a;
120}
121
122template <class T>
123Json encode_matrix_defined(const Matrix<T>& m, const Matrix<long>& count) {
124 Json a = Json::array();
125 for (std::size_t i = 0; i < m.rows(); ++i) {
126 Json row = Json::array();
127 for (std::size_t k = 0; k < m.cols(); ++k) row.push_back(encode_defined(m(i, k), count(i, k)));
128 a.push_back(row);
129 }
130 return a;
131}
132
133std::string where_of(const std::string& fn, const char* key) { return fn + ": " + key; }
134
135std::vector<long> to_longs(const std::vector<int>& v) { return std::vector<long>(v.begin(), v.end()); }
136
137/** Nonnegative integers, e.g. moment orders or 0-based-or-sink state labels. */
138std::vector<std::size_t> nonneg_sizes(const std::vector<int>& v, const std::string& where) {
139 std::vector<std::size_t> out;
140 out.reserve(v.size());
141 for (int x : v) {
142 if (x < 0) throw InputError(where + ": entries must be nonnegative, got " + std::to_string(x));
143 out.push_back(static_cast<std::size_t>(x));
144 }
145 return out;
146}
147
148std::vector<unsigned> nonneg_unsigned(const std::vector<int>& v, const std::string& where) {
149 const std::vector<std::size_t> s = nonneg_sizes(v, where);
150 return std::vector<unsigned>(s.begin(), s.end());
151}
152
153/** MATLAB 1-based class labels to the port's 0-based ones. */
154std::vector<std::size_t> one_based_to_zero(const std::vector<int>& v, const std::string& where) {
155 std::vector<std::size_t> out;
156 out.reserve(v.size());
157 for (int x : v) {
158 if (x < 1) throw InputError(where + ": class labels are 1-based, got " + std::to_string(x));
159 out.push_back(static_cast<std::size_t>(x - 1));
160 }
161 return out;
162}
163
164std::vector<std::size_t> one_based_sizes(const std::vector<int>& v, const std::string& where) {
165 std::vector<std::size_t> out;
166 out.reserve(v.size());
167 for (int x : v) {
168 if (x < 1) throw InputError(where + ": class labels are 1-based, got " + std::to_string(x));
169 out.push_back(static_cast<std::size_t>(x));
170 }
171 return out;
172}
173
174/** A number where JSON null stands for `fill` (MATLAB's NaN or Inf placeholder). */
175template <class T>
176T number_or_fill(const Json& j, const std::string& where, const T& fill) {
177 return j.is_null() ? fill : number_from_json<T>(j, where);
178}
179
180/**
181 * A matrix like matrix_from_json, but with JSON null read as `fill`. The JSON
182 * encoder writes a double NaN as null, so this is how a NaN placeholder
183 * (MATLAB's 'not observed', 'not applicable') crosses the boundary.
184 */
185template <class T>
186Matrix<T> matrix_or_fill(const Json& j, const std::string& where, const T& fill) {
187 if (!j.is_array()) {
188 Matrix<T> m(1, 1);
189 m(0, 0) = number_or_fill<T>(j, where, fill);
190 return m;
191 }
192 if (j.empty()) return Matrix<T>();
193 if (j[0].is_array()) {
194 const std::size_t rows = j.size(), cols = j[0].size();
195 for (std::size_t i = 0; i < rows; ++i)
196 if (!j[i].is_array() || j[i].size() != cols)
197 throw InputError(where + ": row " + std::to_string(i) + " is not an array of " +
198 std::to_string(cols) + " entries");
199 if (cols == 0) return Matrix<T>();
200 Matrix<T> m(rows, cols);
201 for (std::size_t i = 0; i < rows; ++i)
202 for (std::size_t k = 0; k < cols; ++k) m(i, k) = number_or_fill<T>(j[i][k], where, fill);
203 return m;
204 }
205 Matrix<T> m(1, j.size());
206 for (std::size_t k = 0; k < j.size(); ++k) m(0, k) = number_or_fill<T>(j[k], where, fill);
207 return m;
208}
209
210/** MATLAB's reshape(X, 1, numel(X)): column-major flattening of any shape. */
211template <class T>
212std::vector<T> column_major(const Matrix<T>& m) {
213 std::vector<T> v;
214 v.reserve(m.rows() * m.cols());
215 for (std::size_t c = 0; c < m.cols(); ++c)
216 for (std::size_t r = 0; r < m.rows(); ++r) v.push_back(m(r, c));
217 return v;
218}
219
220std::string lower(std::string s) {
221 for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
222 return s;
223}
224
225std::string string_of(const Json& j, const std::string& where) {
226 if (!j.is_string())
227 throw InputError(where + ": expected a string, got " + std::string(j.type_name()));
228 return j.get<std::string>();
229}
230
231std::vector<std::string> strings_of(const Json& j, const std::string& where) {
232 if (!j.is_array()) throw InputError(where + ": expected a list of strings");
233 std::vector<std::string> out;
234 for (const Json& e : j) out.push_back(string_of(e, where));
235 return out;
236}
237
238/** A flag stored as a JSON boolean or 0/1. */
239bool flag_of(const Json& j, const std::string& where) {
240 if (j.is_boolean()) return j.get<bool>();
241 const std::vector<int> v = int_vector_from_json(j, where);
242 if (v.size() != 1 || (v[0] != 0 && v[0] != 1))
243 throw InputError(where + ": expected true, false, 0 or 1");
244 return v[0] != 0;
245}
246
247/**
248 * The MATLAB 6 x (K+1) cell array `data` of the inference traces, of which the
249 * references read row 3 (arrival times, ms) and row 4 (response times) of the
250 * first K columns. Row-major JSON: data[row][column], each cell a vector.
251 */
252template <class T>
253void read_trace_cells(const Json& data, const std::string& where, std::vector<std::vector<T>>& at_ms,
254 std::vector<std::vector<T>>& rt) {
255 if (!data.is_array() || data.size() < 4)
256 throw InputError(where + ": expected the 6 x (K+1) cell array, as a list of rows; rows 3 "
257 "(arrival times, ms) and 4 (response times) are read");
258 const std::size_t cols = data[0].is_array() ? data[0].size() : 0;
259 for (std::size_t r = 0; r < data.size(); ++r)
260 if (!data[r].is_array() || data[r].size() != cols)
261 throw InputError(where + ": row " + std::to_string(r + 1) + " must have " +
262 std::to_string(cols) + " cells, like row 1");
263 if (cols < 2) throw InputError(where + ": at least one class column plus the trailing column");
264 const std::size_t K = cols - 1;
265 at_ms.assign(K, std::vector<T>());
266 rt.assign(K, std::vector<T>());
267 for (std::size_t k = 0; k < K; ++k) {
268 at_ms[k] = vector_from_json<T>(data[2][k], where + "{3," + std::to_string(k + 1) + "}");
269 rt[k] = vector_from_json<T>(data[3][k], where + "{4," + std::to_string(k + 1) + "}");
270 }
271}
272
273// ---------------------------------------------------------------------------
274// trace: one trace in, one scalar out
275// ---------------------------------------------------------------------------
276
277#define LINE_TRACE_SCALAR_OP(Name, fn, outkey) \
278 struct Name { \
279 template <class T> \
280 static Json run(Args& a) { \
281 const std::vector<T> S = a.vector<T>("S"); \
282 a.done(); \
283 Json out; \
284 out[outkey] = encode_scalar(line::trace::fn<T>(S)); \
285 return out; \
286 } \
287 };
288
289LINE_TRACE_SCALAR_OP(OpTraceMean, trace_mean, "m")
290LINE_TRACE_SCALAR_OP(OpTraceVar, trace_var, "v")
291LINE_TRACE_SCALAR_OP(OpTraceScv, trace_scv, "scv")
292LINE_TRACE_SCALAR_OP(OpTraceSkew, trace_skew, "skew")
293LINE_TRACE_SCALAR_OP(OpTraceIdc, trace_idc, "IDC")
294#undef LINE_TRACE_SCALAR_OP
295
296struct OpTraceAcf {
297 template <class T>
298 static Json run(Args& a) {
299 const std::vector<T> S = a.vector<T>("S");
300 const bool has_lags = a.has("lags");
301 const std::vector<int> lags = a.ints_or_empty("lags");
302 a.done();
303 Json out;
304 out["rho"] = encode_vector(has_lags ? line::trace::trace_acf<T>(S, lags)
306 return out;
307 }
308};
309
310struct OpTraceBicov {
311 template <class T>
312 static Json run(Args& a) {
313 const std::vector<T> S = a.vector<T>("S");
314 const std::vector<int> grid = a.ints("GRID");
315 a.done();
316 const line::trace::TraceBicovResult<T> r = line::trace::trace_bicov<T>(S, grid);
317 Json lags = Json::array();
318 for (const std::vector<int>& l : r.lags) lags.push_back(encode_ints(l));
319 Json out;
320 out["BiCov"] = encode_vector(r.bicov);
321 out["BiCovLags"] = lags;
322 return out;
323 }
324};
325
326struct OpTraceGamma {
327 template <class T>
328 static Json run(Args& a) {
329 const std::vector<T> S = a.vector<T>("T");
330 const bool has_limit = a.has("limit");
331 const int limit = has_limit ? a.required_integer("limit") : 0;
332 a.opt("limit");
333 a.done();
334 const line::trace::TraceGammaResult<T> r =
335 has_limit ? line::trace::trace_gamma<T>(S, static_cast<long>(limit))
336 : line::trace::trace_gamma<T>(S);
337 Json out;
338 out["GAMMA"] = encode_scalar(r.gamma);
339 out["RHO0"] = encode_scalar(r.rho0);
340 out["RESIDUALS"] = encode_scalar(r.residuals);
341 return out;
342 }
343};
344
345struct OpTraceIat2bins {
346 template <class T>
347 static Json run(Args& a) {
348 const std::vector<T> S = a.vector<T>("S");
349 const T scale = a.number<T>("scale");
350 a.done();
351 const line::trace::TraceBinsResult r = line::trace::trace_iat2bins<T>(S, scale);
352 Json out;
353 out["C"] = encode_longs(r.counts);
354 out["bC"] = encode_longs(r.membership);
355 return out;
356 }
357};
358
359struct OpTraceIat2counts {
360 template <class T>
361 static Json run(Args& a) {
362 const std::vector<T> S = a.vector<T>("S");
363 const T scale = a.number<T>("scale");
364 a.done();
365 Json out;
366 out["C"] = encode_longs(line::trace::trace_iat2counts<T>(S, scale));
367 return out;
368 }
369};
370
371/**
372 * trace_idi(S, kset, OPTION, n). OPTION 'aggregate' with n is the port's
373 * aggregate_n; 'aggregate-mix' is not ported (see trace_idi.h). The kset
374 * default of the reference (min(1000, ceil(n/30))) has no overload in the port,
375 * so kset is required rather than restated here.
376 */
377struct OpTraceIdi {
378 template <class T>
379 static Json run(Args& a) {
380 const std::vector<T> S = a.vector<T>("S");
381 const std::vector<long> kset = to_longs(a.ints("kset"));
382 const bool has_option = a.has("OPTION");
383 const std::string option = lower(a.text("OPTION", std::string()));
384 const bool has_n = a.has("n");
385 a.opt("n");
386 line::trace::TraceIdiResult<T> r;
387 if (!has_option) {
388 if (has_n)
389 throw InputError("trace_idi: 'n' is the aggregation count of OPTION 'aggregate'; "
390 "give OPTION too");
391 a.done();
392 r = line::trace::trace_idi<T>(S, kset);
393 } else if (option == "aggregate") {
394 if (!has_n) throw InputError("trace_idi: OPTION 'aggregate' needs 'n'");
395 const int n = a.required_integer("n");
396 if (n < 1) throw InputError("trace_idi: 'n' must be a positive integer");
397 a.done();
398 r = line::trace::trace_idi<T>(S, kset, static_cast<long>(n));
399 } else if (option == "aggregate-mix") {
400 throw UnsupportedError(ErrorKind{"JsonApi"},
401 "trace_idi: OPTION 'aggregate-mix' is not ported; the reference branch keeps "
402 "only the statistic of its last partition (see trace_idi.h)");
403 } else {
404 throw InputError("trace_idi: OPTION must be 'aggregate', got '" + option + "'");
405 }
406 Json out;
407 out["IDIk"] = encode_vector(r.idi);
408 out["support"] = encode_longs(r.support);
409 return out;
410 }
411};
412
413struct OpTraceJoint {
414 template <class T>
415 static Json run(Args& a) {
416 const std::vector<T> S = a.vector<T>("S");
417 const std::vector<int> lag = a.ints("lag");
418 const std::vector<unsigned> order = nonneg_unsigned(a.ints("order"), "trace_joint: order");
419 a.done();
420 Json out;
421 out["JM"] = encode_scalar(line::trace::trace_joint<T>(S, lag, order));
422 return out;
423 }
424};
425
426struct OpTracePmf {
427 template <class T>
428 static Json run(Args& a) {
429 const std::vector<int> X = a.ints("X");
430 a.done();
431 const line::trace::TracePmfResult<T> r = line::trace::trace_pmf<T>(X);
432 Json out;
433 out["pmf"] = encode_vector(r.pmf);
434 out["px"] = encode_ints(r.values);
435 return out;
436 }
437};
438
439/**
440 * trace_summary(m). The port's skewness is bias-corrected and its percentiles
441 * are type 7, its ACF covers lags 1..4 and its tail is the 95th percentile
442 * alone; those are the values reported (see trace_summary.h). KURT is MATLAB's
443 * kurtosis, i.e. the port's excess kurtosis plus 3.
444 */
445struct OpTraceSummary {
446 template <class T>
447 static Json run(Args& a) {
448 const std::vector<T> S = a.vector<T>("m");
449 a.unsupported("fid", "it is a MATLAB file identifier for the printed report; the API "
450 "returns the values instead of printing them");
451 a.done();
452 const line::trace::TraceSummary<T> r = line::trace::trace_summary<T>(S);
453 Json out;
454 out["MEAN"] = encode_scalar(r.mean);
455 out["SCV"] = encode_scalar(r.scv);
456 out["MAD"] = encode_scalar(r.mad);
457 out["SKEW"] = encode_scalar(r.skew);
458 out["KURT"] = encode_scalar(T(r.kurt_excess + num_traits<T>::from_int(3)));
459 out["QUART"] = encode_vector(std::vector<T>{r.q25, r.q50, r.q75});
460 out["TAILS1PERC"] = encode_vector(std::vector<T>{r.p95});
461 out["MINMAX"] = encode_vector(std::vector<T>{r.min, r.max});
462 out["IQR"] = encode_scalar(r.iqr);
463 out["ACF"] = encode_vector(r.acf);
464 out["IDC"] = encode_scalar(r.idc);
465 return out;
466 }
467};
468
469// ---------------------------------------------------------------------------
470// mtrace: marked traces
471// ---------------------------------------------------------------------------
472
473struct OpMtraceMoment {
474 template <class T>
475 static Json run(Args& a) {
476 const std::vector<T> Tv = a.vector<T>("T");
477 const std::vector<int> A = a.ints("A");
478 const std::vector<unsigned> orders = nonneg_unsigned(a.ints("ORDERS"), "mtrace_moment: ORDERS");
479 const bool has_after = a.has("AFTER"), has_norm = a.has("NORM");
480 if (has_norm && !has_after)
481 throw InputError("mtrace_moment: NORM follows AFTER positionally; give AFTER too");
482 const bool after = has_after ? a.boolean("AFTER", false) : false;
483 const bool norm = has_norm ? a.boolean("NORM", false) : false;
484 a.opt("AFTER");
485 a.opt("NORM");
486 a.done();
487 Matrix<T> M;
488 if (has_norm)
489 M = line::trace::mtrace_moment<T>(Tv, A, orders, after, norm);
490 else if (has_after)
491 M = line::trace::mtrace_moment<T>(Tv, A, orders, after);
492 else
493 M = line::trace::mtrace_moment<T>(Tv, A, orders);
494 Json out;
495 out["M"] = encode_matrix(M);
496 return out;
497 }
498};
499
500#define LINE_MTRACE_DIRECTED_MOMENT_OP(Name, fn) \
501 struct Name { \
502 template <class T> \
503 static Json run(Args& a) { \
504 const std::vector<T> Tv = a.vector<T>("T"); \
505 const std::vector<int> A = a.ints("A"); \
506 const std::vector<unsigned> orders = \
507 nonneg_unsigned(a.ints("ORDERS"), #fn ": ORDERS"); \
508 const bool has_norm = a.has("NORM"); \
509 const bool norm = has_norm ? a.boolean("NORM", false) : false; \
510 a.opt("NORM"); \
511 a.done(); \
512 Json out; \
513 out["M"] = encode_matrix(has_norm ? line::trace::fn<T>(Tv, A, orders, norm) \
514 : line::trace::fn<T>(Tv, A, orders)); \
515 return out; \
516 } \
517 };
518
519LINE_MTRACE_DIRECTED_MOMENT_OP(OpMtraceForwardMoment, mtrace_forward_moment)
520LINE_MTRACE_DIRECTED_MOMENT_OP(OpMtraceBackwardMoment, mtrace_backward_moment)
521#undef LINE_MTRACE_DIRECTED_MOMENT_OP
522
523#define LINE_MTRACE_CROSS_MOMENT_OP(Name, fn) \
524 struct Name { \
525 template <class T> \
526 static Json run(Args& a) { \
527 const std::vector<T> Tv = a.vector<T>("T"); \
528 const std::vector<int> L = a.ints("L"); \
529 const unsigned k = a.uinteger("k"); \
530 a.done(); \
531 const line::trace::MtraceCrossMomentResult<T> r = \
532 line::trace::fn<T>(Tv, L, k); \
533 Json out; \
534 out["MC"] = encode_matrix_defined(r.mc, r.count); \
535 return out; \
536 } \
537 };
538
539LINE_MTRACE_CROSS_MOMENT_OP(OpMtraceCrossMoment, mtrace_cross_moment)
540LINE_MTRACE_CROSS_MOMENT_OP(OpMtraceMomentSimple, mtrace_moment_simple)
541#undef LINE_MTRACE_CROSS_MOMENT_OP
542
543struct OpMtraceCount {
544 template <class T>
545 static Json run(Args& a) {
546 const std::vector<T> Tv = a.vector<T>("T");
547 const std::vector<int> A = a.ints("A");
548 const T t = a.number<T>("t");
549 a.done();
550 Json out;
551 out["N"] = encode_long_matrix(line::trace::mtrace_count<T>(Tv, A, t).counts);
552 return out;
553 }
554};
555
556struct OpMtraceCov {
557 template <class T>
558 static Json run(Args& a) {
559 const std::vector<T> Tv = a.vector<T>("T");
560 const std::vector<int> A = a.ints("A");
561 a.done();
562 const std::vector<std::vector<Matrix<T>>> cov = line::trace::mtrace_cov<T>(Tv, A);
563 Json c = Json::array();
564 for (const std::vector<Matrix<T>>& row : cov) c.push_back(encode_matrices(row));
565 Json out;
566 out["COV"] = c;
567 return out;
568 }
569};
570
571struct OpMtraceIat2counts {
572 template <class T>
573 static Json run(Args& a) {
574 const std::vector<T> Tv = a.vector<T>("T");
575 const std::vector<int> A = a.ints("A");
576 const T scale = a.number<T>("scale");
577 a.unsupported("no_mex", "it selects between MATLAB's MEX and script implementations of "
578 "the same counts; the port has one implementation");
579 a.done();
580 Json out;
581 out["C"] = encode_long_matrix(line::trace::mtrace_iat2counts<T>(Tv, A, scale).counts);
582 return out;
583 }
584};
585
586struct OpMtraceJoint {
587 template <class T>
588 static Json run(Args& a) {
589 const std::vector<T> Tv = a.vector<T>("T");
590 const std::vector<int> A = a.ints("A");
591 const std::vector<unsigned> i = nonneg_unsigned(a.ints("i"), "mtrace_joint: i");
592 if (i.size() != 2) throw InputError("mtrace_joint: 'i' must hold the two orders [i1, i2]");
593 a.done();
594 const line::trace::MtraceJointResult<T> r = line::trace::mtrace_joint<T>(Tv, A, i[0], i[1]);
595 Json out;
596 out["JM"] = encode_vector_defined(r.jm, r.count);
597 return out;
598 }
599};
600
601struct OpMtraceMean {
602 template <class T>
603 static Json run(Args& a) {
604 const std::vector<T> Tv = a.vector<T>("trace");
605 const int ntypes = a.required_integer("ntypes");
606 const std::vector<int> type = a.ints("type");
607 a.done();
608 const line::trace::MtraceMeanResult<T> r =
609 line::trace::mtrace_mean<T>(Tv, static_cast<long>(ntypes), type);
610 Json out;
611 out["m"] = encode_vector_defined(r.mean, r.count);
612 return out;
613 }
614};
615
616struct OpMtraceMerge {
617 template <class T>
618 static Json run(Args& a) {
619 const std::vector<T> t1 = a.vector<T>("t1");
620 const std::vector<T> t2 = a.vector<T>("t2");
621 a.done();
622 const line::trace::MtraceMergeResult<T> r = line::trace::mtrace_merge<T>(t1, t2);
623 Json out;
624 out["T"] = encode_vector(r.times);
625 out["L"] = encode_ints(r.labels);
626 return out;
627 }
628};
629
630/** The reference's first argument T is never read: the statistic is of the labels. */
631void refuse_unused_times(Args& a, const char* fn) {
632 if (a.has("T"))
633 throw InputError(std::string(fn) + ": 'T' is not read by the reference, whose result "
634 "depends on the labels L alone; omit it");
635 a.opt("T");
636}
637
638struct OpMtracePc {
639 template <class T>
640 static Json run(Args& a) {
641 const std::vector<int> C = a.ints("C");
642 a.done();
643 Json out;
645 return out;
646 }
647};
648
649struct OpMtraceSigma {
650 template <class T>
651 static Json run(Args& a) {
652 refuse_unused_times(a, "mtrace_sigma");
653 const std::vector<int> L = a.ints("L");
654 a.done();
655 Json out;
657 return out;
658 }
659};
660
661/** sigma(i,j,h) as a C x C x C nested array, from the port's (i, j*C+h) layout. */
662struct OpMtraceSigma2 {
663 template <class T>
664 static Json run(Args& a) {
665 refuse_unused_times(a, "mtrace_sigma2");
666 const std::vector<int> L = a.ints("L");
667 a.done();
668 const Matrix<T> s = line::trace::mtrace_sigma2<T>(L);
669 const std::size_t C = s.rows();
670 Json cube = Json::array();
671 for (std::size_t i = 0; i < C; ++i) {
672 Json plane = Json::array();
673 for (std::size_t j = 0; j < C; ++j) {
674 Json row = Json::array();
675 for (std::size_t h = 0; h < C; ++h) row.push_back(encode_scalar(s(i, j * C + h)));
676 plane.push_back(row);
677 }
678 cube.push_back(plane);
679 }
680 Json out;
681 out["sigma"] = cube;
682 return out;
683 }
684};
685
686struct OpMtraceSplit {
687 template <class T>
688 static Json run(Args& a) {
689 const std::vector<T> Tv = a.vector<T>("T");
690 const std::vector<int> L = a.ints("L");
691 a.done();
692 Json out;
693 out["TL"] = encode_vectors(line::trace::mtrace_split<T>(Tv, L).traces);
694 return out;
695 }
696};
697
698struct OpMtraceSummary {
699 template <class T>
700 static Json run(Args& a) {
701 const std::vector<T> Tv = a.vector<T>("T");
702 const std::vector<int> C = a.ints("C");
703 a.done();
704 const line::trace::MtraceSummary<T> r = line::trace::mtrace_summary<T>(Tv, C);
705 Json s;
706 s["M"] = encode_vector(r.M);
707 s["ACF"] = encode_vector(r.acf);
708 s["F1"] = encode_matrix(r.F1);
709 s["F2"] = encode_matrix(r.F2);
710 s["B1"] = encode_matrix(r.B1);
711 s["B2"] = encode_matrix(r.B2);
712 s["C1"] = encode_matrix(r.C1);
713 s["C2"] = encode_matrix(r.C2);
714 s["Pc"] = encode_vector(r.Pc);
715 s["Pab"] = encode_matrix(r.Pab);
716 Json out;
717 out["summary"] = s;
718 return out;
719 }
720};
721
722// ---------------------------------------------------------------------------
723// infer: queue lengths and demands from traces
724// ---------------------------------------------------------------------------
725
726struct OpInferComputeQlAtArrival {
727 template <class T>
728 static Json run(Args& a) {
729 const std::vector<T> at = a.vector<T>("at");
730 const std::vector<long> at_jobid = to_longs(a.ints("at_jobid"));
731 const std::vector<T> rt = a.vector<T>("rt");
732 const std::vector<long> rt_jobid = to_longs(a.ints("rt_jobid"));
733 const std::vector<std::size_t> cls =
734 one_based_to_zero(a.ints("class"), "infer_compute_ql_at_arrival: class");
735 const std::size_t R = a.count("R");
736 a.done();
737 Json out;
738 out["ql"] = encode_matrix(
739 line::infer::infer_compute_ql_at_arrival<T>(at, at_jobid, rt, rt_jobid, cls, R));
740 return out;
741 }
742};
743
744struct OpInferGetQlenArrival {
745 template <class T>
746 static Json run(Args& a) {
747 std::vector<std::vector<T>> at_ms, rt;
748 read_trace_cells<T>(a.get("data"), "infer_get_qlen_arrival: data", at_ms, rt);
749 a.done();
750 Json out;
752 return out;
753 }
754};
755
756struct OpInferLqnFindbyname {
757 template <class T>
758 static Json run(Args& a) {
759 const Json& container = a.get("container");
760 const std::string name = string_of(a.get("name"), "infer_lqn_findbyname: name");
761 a.done();
762 if (!container.is_array())
763 throw InputError("infer_lqn_findbyname: 'container' must be a list of elements");
764 std::vector<std::string> names;
765 for (std::size_t k = 0; k < container.size(); ++k) {
766 const Json& e = container[k];
767 if (!e.is_object() || e.find("name") == e.end())
768 throw InputError("infer_lqn_findbyname: container entry " + std::to_string(k + 1) +
769 " has no 'name' field");
770 names.push_back(string_of(e["name"], "infer_lqn_findbyname: container.name"));
771 }
772 const std::size_t idx = line::infer::infer_lqn_findbyname(names, name);
773 Json out;
774 out["el"] = idx == line::infer::INFER_LQN_NOT_FOUND ? Json(nullptr) : container[idx];
775 return out;
776 }
777};
778
779struct OpInferLqnGetobs {
780 template <class T>
781 static Json run(Args& a) {
782 const std::vector<std::string> names = strings_of(a.get("names"), "infer_lqn_getobs: names");
783 const Json& mj = a.get("metrics");
784 const Json& sj = a.get("obsSpec");
785 a.done();
786 line::infer::LqnMetrics<T> m;
787 {
788 Args ma(mj, "infer_lqn_getobs: metrics");
789 m.QLen = ma.vector_or_empty<T>("QLen");
790 m.Util = ma.vector_or_empty<T>("Util");
791 m.RespT = ma.vector_or_empty<T>("RespT");
792 m.Tput = ma.vector_or_empty<T>("Tput");
793 ma.done();
794 }
795 if (!sj.is_array()) throw InputError("infer_lqn_getobs: 'obsSpec' must be a list of {metric, name}");
796 std::vector<line::infer::LqnObsSpec> spec;
797 for (const Json& e : sj) {
798 Args ea(e, "infer_lqn_getobs: obsSpec");
799 const std::string metric = lower(string_of(ea.get("metric"), "infer_lqn_getobs: obsSpec.metric"));
800 line::infer::LqnObsSpec s;
801 s.name = string_of(ea.get("name"), "infer_lqn_getobs: obsSpec.name");
802 ea.done();
803 if (metric == "respt")
805 else if (metric == "util")
807 else if (metric == "tput")
809 else if (metric == "qlen")
811 else
812 throw InputError("infer_lqn_getobs: Unknown metric '" + metric + "'.");
813 spec.push_back(s);
814 }
815 Json out;
816 out["z"] = encode_vector(line::infer::infer_lqn_getobs<T>(names, m, spec));
817 return out;
818 }
819};
820
821struct OpInferQmle {
822 template <class T>
823 static Json run(Args& a) {
824 const Matrix<T> Q = a.matrix<T>("Q");
825 const std::vector<T> N = a.vector<T>("N");
826 const std::vector<T> Z = a.vector<T>("Z");
827 a.done();
828 Json out;
829 out["D"] = encode_matrix(line::infer::infer_qmle<T>(Q, N, Z));
830 return out;
831 }
832};
833
834struct OpInferRps {
835 template <class T>
836 static Json run(Args& a) {
837 const std::vector<T> rt = a.vector<T>("rt");
838 const std::vector<std::size_t> cls = one_based_to_zero(a.ints("class"), "infer_rps: class");
839 const Matrix<T> ql = a.matrix<T>("ql");
840 const int V = a.required_integer("V");
841 a.done();
842 Json out;
843 out["demandEst"] = encode_vector(line::infer::infer_rps<T>(rt, cls, ql, static_cast<long>(V)));
844 return out;
845 }
846};
847
848/**
849 * infer_quick_model(open, stations, classes, servers, jobs, routing). The
850 * routing of a closed model is one M x M matrix per class (MATLAB's cell
851 * form), or a single M x M matrix that every class uses.
852 */
853struct OpInferQuickModel {
854 template <class T>
855 static Json run(Args& a) {
856 const bool is_open = flag_of(a.get("open"), "infer_quick_model: open");
857 std::vector<lang::SchedStrategy> stations;
858 for (const std::string& s : strings_of(a.get("stations"), "infer_quick_model: stations"))
859 stations.push_back(io::detail::sched_from_json(s));
860 const Matrix<T> demands = a.matrix<T>("classes");
861 const bool has_servers = a.has("servers"), has_jobs = a.has("jobs"),
862 has_routing = a.has("routing");
863 if (has_jobs && !has_servers)
864 throw InputError("infer_quick_model: 'jobs' follows 'servers' positionally; give servers too");
865 if (has_routing && !(has_servers && has_jobs))
866 throw InputError("infer_quick_model: 'routing' follows 'servers' and 'jobs' "
867 "positionally; give both");
868 if (has_routing && is_open)
869 throw InputError("infer_quick_model: 'routing' applies to a closed model; an open "
870 "model is routed serially from the source to the sink");
871 const std::vector<double> servers = a.vector_or_empty<double>("servers");
872 const std::vector<double> jobs = a.vector_or_empty<double>("jobs");
873 std::vector<Matrix<T>> routing;
874 if (has_routing) {
875 const Json& rj = a.get("routing");
876 const bool cell_form = rj.is_array() && !rj.empty() && rj[0].is_array() &&
877 !rj[0].empty() && rj[0][0].is_array();
878 if (cell_form) {
879 routing = a.matrices<T>("routing");
880 } else {
881 const Matrix<T> P = a.matrix<T>("routing");
882 routing.assign(demands.rows(), P);
883 }
884 }
885 a.done();
886 qn::Network<T> model =
887 has_routing ? line::infer::infer_quick_model<T>(is_open, stations, demands, servers, jobs, routing)
888 : has_jobs ? line::infer::infer_quick_model<T>(is_open, stations, demands, servers, jobs)
889 : has_servers ? line::infer::infer_quick_model<T>(is_open, stations, demands, servers)
890 : line::infer::infer_quick_model<T>(is_open, stations, demands);
891 Json out;
892 out["model"] = io::network_json_envelope(model.get_struct());
893 return out;
894 }
895};
896
897/**
898 * infer_nhpp_ks(times, T, 'cumRate', f, 'method', m, 'T0', t0). The port's
899 * options are positional (cumRate, method, T0); an absent cumRate is the
900 * constant rate in both, so method is reached through the empty callable.
901 */
902struct OpInferNhppKs {
903 template <class T>
904 static Json run(Args& a) {
905 const std::vector<T> times = a.vector<T>("times");
906 const T Tend = a.number<T>("T");
907 a.unsupported("cumRate", "it is a function handle; without it the rate is taken "
908 "constant over the interval");
909 const bool has_method = a.has("method"), has_t0 = a.has("T0");
910 const std::string m = lower(a.text("method", std::string()));
911 if (has_t0 && !has_method)
912 throw InputError("infer_nhpp_ks: the port takes T0 after method; give 'method' too");
913 line::infer::NhppKsResult<T> r;
914 if (!has_method) {
915 a.done();
916 r = line::infer::infer_nhpp_ks<T>(times, Tend);
917 } else {
919 if (m == "cu")
921 else if (m == "lewis")
923 else
924 throw InputError("infer_nhpp_ks: method must be 'cu' or 'lewis' ('tt' tests a "
925 "given cumRate, which is a function handle)");
926 const std::function<T(const T&)> constant;
927 if (has_t0) {
928 const T t0 = a.number<T>("T0");
929 a.done();
930 r = line::infer::infer_nhpp_ks<T>(times, Tend, constant, method, t0);
931 } else {
932 a.opt("T0");
933 a.done();
934 r = line::infer::infer_nhpp_ks<T>(times, Tend, constant, method);
935 }
936 }
937 Json res;
938 res["statistic"] = encode_scalar(r.statistic);
939 res["pvalue"] = encode_scalar(r.pvalue);
940 res["n"] = encode_count(r.n);
941 res["uniforms"] = encode_vector(r.uniforms);
942 res["transformed"] = encode_vector(r.transformed);
943 Json out;
944 out["result"] = res;
945 return out;
946 }
947};
948
949/** The optional 'alpha' significance level of the NHPP fitting intervals. */
950template <class T>
951double nhpp_fit_alpha(Args& a) {
952 return a.has("alpha") ? num_traits<T>::to_double(a.number<T>("alpha")) : 0.05;
953}
954
955/** infer_nhpp_leemis(times, T, 'tq', q, 'alpha', a). */
956struct OpInferNhppLeemis {
957 template <class T>
958 static Json run(Args& a) {
959 const std::vector<T> times = a.vector<T>("times");
960 const T Tend = a.number<T>("T");
961 const std::vector<T> tq = a.vector_or_empty<T>("tq");
962 const double alpha = nhpp_fit_alpha<T>(a);
963 a.opt("alpha");
964 a.done();
965 const line::infer::NhppLeemisResult<T> r = line::infer::infer_nhpp_leemis<T>(times, Tend, tq, alpha);
966 Json res;
967 res["n"] = encode_count(r.n);
968 res["T"] = encode_scalar(r.horizon);
969 res["knots"] = encode_vector(r.knots);
970 res["knotValues"] = encode_vector(r.knotValues);
971 res["rates"] = encode_vector(r.rates);
972 res["tq"] = encode_vector(r.tq);
973 res["cumRate"] = encode_vector(r.cumRate);
974 res["step"] = encode_vector(r.step);
975 res["lower"] = encode_vector(r.lower);
976 res["upper"] = encode_vector(r.upper);
977 Json out;
978 out["result"] = res;
979 return out;
980 }
981};
982
983/** infer_nhpp_powerlaw(times, T, 'alpha', a). */
984struct OpInferNhppPowerlaw {
985 template <class T>
986 static Json run(Args& a) {
987 const std::vector<T> times = a.vector<T>("times");
988 const T Tend = a.number<T>("T");
989 const double alpha = nhpp_fit_alpha<T>(a);
990 a.opt("alpha");
991 a.done();
992 const line::infer::NhppPowerLawResult<T> r = line::infer::infer_nhpp_powerlaw<T>(times, Tend, alpha);
993 Matrix<T> info(2, 2), cov(2, 2);
994 for (int i = 0; i < 2; ++i)
995 for (int j = 0; j < 2; ++j) {
996 info(i, j) = r.info[i][j];
997 cov(i, j) = r.cov[i][j];
998 }
999 Json res;
1000 res["n"] = encode_count(r.n);
1001 res["T"] = encode_scalar(r.horizon);
1002 res["scale"] = encode_scalar(r.scale);
1003 res["shape"] = encode_scalar(r.shape);
1004 res["loglik"] = encode_scalar(r.loglik);
1005 res["info"] = encode_matrix(info);
1006 res["cov"] = encode_matrix(cov);
1007 res["se"] = encode_vector(std::vector<T>{r.se[0], r.se[1]});
1008 res["scaleCI"] = encode_vector(std::vector<T>{r.scaleCI[0], r.scaleCI[1]});
1009 res["shapeCI"] = encode_vector(std::vector<T>{r.shapeCI[0], r.shapeCI[1]});
1010 Json out;
1011 out["result"] = res;
1012 return out;
1013 }
1014};
1015
1016// ---- semi-Markov inference (double only) ----------------------------------
1017
1018Json encode_smp_fit(const line::infer::SmpFit& f) {
1019 Json arcs = Json::array();
1020 for (const line::infer::SmpArc& c : f.arcs) {
1021 Json j;
1022 j["from"] = encode_count(c.from);
1023 j["to"] = encode_count(c.to);
1024 j["family"] = c.family;
1025 j["theta"] = encode_vector(c.theta);
1026 j["params"] = encode_vector(c.params);
1027 j["beta"] = encode_vector(c.beta);
1028 j["se"] = encode_vector(c.se);
1029 j["prob"] = c.prob;
1030 j["nevents"] = encode_count(c.nevents);
1031 arcs.push_back(j);
1032 }
1033 Json j;
1034 j["approach"] = f.approach;
1035 j["nstates"] = encode_count(f.nstates);
1036 j["ncov"] = encode_count(f.ncov);
1037 j["arcs"] = arcs;
1038 j["loglik"] = f.loglik;
1039 j["nparams"] = encode_count(f.nparams);
1040 j["aic"] = f.aic;
1041 j["P"] = encode_matrix(f.P);
1042 return j;
1043}
1044
1045std::vector<double> doubles_nan(const Json& j, const std::string& where) {
1046 const Matrix<double> m = matrix_or_fill<double>(j, where, std::numeric_limits<double>::quiet_NaN());
1047 return column_major(m);
1048}
1049
1050/** The `fit` struct infer_smp returns, read back field for field. */
1051line::infer::SmpFit read_smp_fit(const Json& j) {
1052 const std::string w = "infer_smp_hazard: fit";
1053 Args f(j, w);
1054 line::infer::SmpFit fit;
1055 fit.approach = string_of(f.get("approach"), w + ".approach");
1056 fit.nstates = f.count("nstates");
1057 fit.ncov = f.count("ncov");
1058 fit.loglik = number_or_fill<double>(f.get("loglik"), w + ".loglik",
1059 std::numeric_limits<double>::quiet_NaN());
1060 fit.nparams = f.count("nparams");
1061 fit.aic = number_or_fill<double>(f.get("aic"), w + ".aic", std::numeric_limits<double>::quiet_NaN());
1062 fit.P = matrix_or_fill<double>(f.get("P"), w + ".P", std::numeric_limits<double>::quiet_NaN());
1063 const Json& arcs = f.get("arcs");
1064 f.done();
1065 if (!arcs.is_array()) throw InputError(w + ".arcs: expected a list of arcs");
1066 for (const Json& e : arcs) {
1067 Args c(e, w + ".arcs");
1068 line::infer::SmpArc arc;
1069 arc.from = c.count("from");
1070 arc.to = c.count("to");
1071 arc.family = string_of(c.get("family"), w + ".arcs.family");
1072 arc.theta = doubles_nan(c.get("theta"), w + ".arcs.theta");
1073 arc.params = doubles_nan(c.get("params"), w + ".arcs.params");
1074 arc.beta = doubles_nan(c.get("beta"), w + ".arcs.beta");
1075 arc.se = doubles_nan(c.get("se"), w + ".arcs.se");
1076 arc.prob = number_or_fill<double>(c.get("prob"), w + ".arcs.prob",
1077 std::numeric_limits<double>::quiet_NaN());
1078 arc.nevents = c.count("nevents");
1079 c.done();
1080 fit.arcs.push_back(arc);
1081 }
1082 return fit;
1083}
1084
1085struct OpInferSmp {
1086 static Json run(Args& a) {
1087 const std::string w = "infer_smp";
1088 const std::vector<std::size_t> from = nonneg_sizes(a.ints("from"), w + ": from");
1089 const std::vector<std::size_t> to = nonneg_sizes(a.ints("to"), w + ": to");
1090 const std::vector<double> dur = a.vector<double>("dur");
1091 line::infer::SmpOptions opt;
1092 if (a.has("approach")) opt.approach = lower(a.text("approach", std::string()));
1093 if (const Json* d = a.opt("dist")) {
1094 if (d->is_string()) {
1095 opt.dist = lower(d->get<std::string>());
1096 } else {
1097 if (!d->is_array()) throw InputError(w + ": 'dist' must be a family name or an E x E table of them");
1098 for (const Json& row : *d) {
1099 if (!row.is_array()) throw InputError(w + ": 'dist' table rows must be lists");
1100 std::vector<std::string> r;
1101 for (const Json& e : row) r.push_back(e.is_null() ? std::string() : lower(string_of(e, w + ": dist")));
1102 opt.dist_table.push_back(r);
1103 }
1104 }
1105 }
1106 if (a.has("covariates")) opt.covariates = a.matrix<double>("covariates");
1107 if (const Json* cm = a.opt("covmask")) {
1108 if (!cm->is_array()) throw InputError(w + ": 'covmask' must be an E x E x p array");
1109 for (const Json& plane : *cm) {
1110 if (!plane.is_array()) throw InputError(w + ": 'covmask' must be an E x E x p array");
1111 std::vector<std::vector<bool>> p;
1112 for (const Json& row : plane) {
1113 if (!row.is_array()) throw InputError(w + ": 'covmask' must be an E x E x p array");
1114 std::vector<bool> r;
1115 for (const Json& e : row) r.push_back(flag_of(e, w + ": covmask"));
1116 p.push_back(r);
1117 }
1118 opt.covmask.push_back(p);
1119 }
1120 }
1121 if (a.has("nstates")) opt.nstates = a.count("nstates");
1122 if (a.has("tolx")) opt.tolx = a.number<double>("tolx");
1123 if (a.has("tolf")) opt.tolf = a.number<double>("tolf");
1124 if (a.has("maxiter")) opt.maxiter = a.count("maxiter");
1125 a.opt("approach");
1126 a.opt("covariates");
1127 a.opt("nstates");
1128 a.opt("tolx");
1129 a.opt("tolf");
1130 a.opt("maxiter");
1131 a.done();
1132 Json out;
1133 out["fit"] = encode_smp_fit(line::infer::infer_smp(from, to, dur, opt));
1134 return out;
1135 }
1136};
1137
1138struct OpInferSmpHazard {
1139 static Json run(Args& a) {
1140 const line::infer::SmpFit fit = read_smp_fit(a.get("fit"));
1141 const std::vector<double> t = a.vector<double>("t");
1142 const bool has_z = a.has("z");
1143 const std::vector<double> z = a.vector_or_empty<double>("z");
1144 a.done();
1145 const std::vector<line::infer::SmpHazard> h =
1146 has_z ? line::infer::infer_smp_hazard(fit, t, z) : line::infer::infer_smp_hazard(fit, t);
1147 Json hz = Json::array();
1148 for (const line::infer::SmpHazard& e : h) {
1149 Json j;
1150 j["from"] = encode_count(e.from);
1151 j["to"] = encode_count(e.to);
1152 j["intensity"] = encode_vector(e.intensity);
1153 j["sojourn"] = encode_vector(e.sojourn);
1154 j["cumulative"] = encode_vector(e.cumulative);
1155 j["cif"] = encode_vector(e.cif);
1156 hz.push_back(j);
1157 }
1158 Json out;
1159 out["hz"] = hz;
1160 return out;
1161 }
1162};
1163
1164struct OpInferSmpNelsonAalen {
1165 static Json run(Args& a) {
1166 const std::string w = "infer_smp_nelson_aalen";
1167 const std::vector<std::size_t> from = nonneg_sizes(a.ints("from"), w + ": from");
1168 const std::vector<std::size_t> to = nonneg_sizes(a.ints("to"), w + ": to");
1169 const std::vector<double> dur = a.vector<double>("dur");
1170 const bool has_e = a.has("nstates");
1171 const std::size_t E = has_e ? a.count("nstates") : 0;
1172 a.opt("nstates");
1173 a.done();
1174 const std::vector<line::infer::SmpNelsonAalen> r =
1175 has_e ? line::infer::infer_smp_nelson_aalen(from, to, dur, E)
1176 : line::infer::infer_smp_nelson_aalen(from, to, dur);
1177 Json na = Json::array();
1178 for (const line::infer::SmpNelsonAalen& e : r) {
1179 Json j;
1180 j["from"] = encode_count(e.from);
1181 j["to"] = encode_count(e.to);
1182 j["time"] = encode_vector(e.time);
1183 j["A"] = encode_vector(e.A);
1184 j["var"] = encode_vector(e.var);
1185 na.push_back(j);
1186 }
1187 Json out;
1188 out["na"] = na;
1189 return out;
1190 }
1191};
1192
1193/**
1194 * infer_smp_family(family, mode, ...), one entry for the five modes, with the
1195 * mode's positional arguments under the names of the reference's help text.
1196 */
1197struct OpInferSmpFamily {
1198 static Json run(Args& a) {
1199 const std::string w = "infer_smp_family";
1200 const std::string family = string_of(a.get("family"), w + ": family");
1201 const std::string mode = string_of(a.get("mode"), w + ": mode");
1202 // Validates the family name before any parameter vector is indexed.
1203 const std::size_t npar = line::infer::infer_smp_family_npar(family);
1204 auto theta = [&]() {
1205 const std::vector<double> th = a.vector<double>("THETA");
1206 if (th.size() != npar)
1207 throw InputError(w + ": THETA must have " + std::to_string(npar) + " entries for '" +
1208 family + "'");
1209 return th;
1210 };
1211 Json out;
1212 if (mode == "npar") {
1213 a.done();
1214 out["N"] = encode_count(npar);
1215 } else if (mode == "logfs") {
1216 const std::vector<double> th = theta();
1217 const std::vector<double> t = a.vector<double>("T");
1218 const std::vector<double> eta = a.vector_or_empty<double>("ETA");
1219 if (eta.size() > 1 && eta.size() != t.size())
1220 throw InputError(w + ": ETA must be a scalar or have one entry per instant of T");
1221 a.done();
1222 std::vector<double> logf, logS;
1223 line::infer::infer_smp_family_logfs(family, th, t, eta, logf, logS);
1224 out["LOGF"] = encode_vector(logf);
1225 out["LOGS"] = encode_vector(logS);
1226 } else if (mode == "natural") {
1227 const std::vector<double> th = theta();
1228 a.done();
1230 } else if (mode == "theta0") {
1231 const std::vector<double> tev = a.vector<double>("TEV");
1232 const double texp = a.number<double>("TEXP");
1233 a.done();
1234 out["THETA"] = encode_vector(line::infer::infer_smp_family_theta0(family, tev, texp));
1235 } else if (mode == "dist") {
1236 const std::vector<double> th = theta();
1237 const double eta = a.number<double>("ETA");
1238 a.done();
1239 out["D"] = io::detail::dist_to_json(line::infer::infer_smp_family_dist(family, th, eta));
1240 } else {
1241 throw InputError(w + ": Unknown mode '" + mode +
1242 "': use 'npar', 'logfs', 'natural', 'theta0' or 'dist'.");
1243 }
1244 return out;
1245 }
1246};
1247
1248// ---- variational inference --------------------------------------------------
1249
1250/**
1251 * infer_variational(spec, options). The spec is MATLAB's struct; NaN entries
1252 * (arcrate where the arc is governed by a parameter, obsData where nothing was
1253 * observed) are written as null, and so is an Inf capacity. obsRange and
1254 * capacity are flattened column-major, as the reference's reshape does.
1255 */
1256struct OpInferVariational {
1257 template <class T>
1258 static Json run(Args& a) {
1259 const std::string w = "infer_variational";
1260 const Json& sj = a.get("spec");
1261 const Json* oj = a.opt("options");
1262 a.done();
1263 const T nan = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
1264 const T inf = num_traits<T>::from_double(std::numeric_limits<double>::infinity());
1265
1266 line::infer::VariationalSpec<T> spec;
1267 {
1268 Args s(sj, w + ": spec");
1269 const Matrix<T> arcs = s.matrix<T>("arcs");
1270 if (!arcs.empty() && arcs.cols() != 3)
1271 throw InputError(w + ": spec.arcs must have three columns [i j c].");
1272 const std::vector<int> arcint = int_vector_from_json(s.get("arcs"), w + ": spec.arcs");
1273 const std::vector<std::size_t> arcsz = nonneg_sizes(arcint, w + ": spec.arcs");
1274 for (std::size_t e = 0; e < arcs.rows(); ++e)
1275 spec.arcs.push_back(std::array<std::size_t, 3>{arcsz[3 * e], arcsz[3 * e + 1], arcsz[3 * e + 2]});
1276 spec.x0 = s.matrix<T>("x0");
1277 spec.sched = s.ints("sched");
1278 spec.nservers = s.vector<T>("nservers");
1279 spec.routeprob = s.vector<T>("routeprob");
1280 spec.arcparam = nonneg_sizes(s.ints("arcparam"), w + ": spec.arcparam");
1281 spec.arcrate = column_major(matrix_or_fill<T>(s.get("arcrate"), w + ": spec.arcrate", nan));
1282 spec.alpha0 = s.vector<T>("alpha0");
1283 spec.beta0 = s.vector<T>("beta0");
1284 spec.obsTimes = s.vector<T>("obsTimes");
1285 spec.obsData = matrix_or_fill<T>(s.get("obsData"), w + ": spec.obsData",
1287 spec.obsRange = column_major(s.matrix<T>("obsRange"));
1288 spec.epsilon = s.number<T>("epsilon");
1289 if (const Json* c = s.opt("capacity"))
1290 spec.capacity = column_major(matrix_or_fill<T>(*c, w + ": spec.capacity", inf));
1291 s.done();
1292 }
1293 line::infer::VariationalOptions<T> opt;
1294 if (oj) {
1295 Args o(*oj, w + ": options");
1296 if (o.has("verbose")) opt.verbose = o.required_integer("verbose");
1297 if (o.has("iter_max")) opt.iter_max = o.count("iter_max");
1298 if (o.has("tol")) opt.tol = o.number<double>("tol");
1299 if (o.has("nsamples")) opt.nsamples = o.count("nsamples");
1300 if (o.has("delta")) opt.delta = o.number<double>("delta");
1301 if (o.has("floor")) opt.floor = o.number<double>("floor");
1302 if (o.has("rate_max")) opt.rate_max = o.number<double>("rate_max");
1303 if (o.has("rate_cap_factor")) opt.rate_cap_factor = o.number<double>("rate_cap_factor");
1304 if (o.has("unifmax")) opt.unifmax = o.number<double>("unifmax");
1305 if (o.has("unif_tol")) opt.unif_tol = o.number<double>("unif_tol");
1306 if (o.has("unif_max_terms")) opt.unif_max_terms = o.count("unif_max_terms");
1307 if (o.has("tmax")) opt.tmax = o.number<double>("tmax");
1308 if (o.has("dt")) opt.dt = o.number<double>("dt");
1309 if (o.has("ngrid")) opt.ngrid = static_cast<long>(o.count("ngrid"));
1310 if (o.has("ymax")) opt.ymax = static_cast<long>(o.count("ymax"));
1311 for (const char* k : {"verbose", "iter_max", "tol", "nsamples", "delta", "floor",
1312 "rate_max", "rate_cap_factor", "unifmax", "unif_tol",
1313 "unif_max_terms", "tmax", "dt", "ngrid", "ymax"})
1314 o.opt(k);
1315 o.done();
1316 }
1317 const line::infer::VariationalResult<T> r =
1318 oj ? line::infer::infer_variational<T>(spec, opt) : line::infer::infer_variational<T>(spec);
1319 Json res;
1320 res["alpha"] = encode_vector(r.alpha);
1321 res["beta"] = encode_vector(r.beta);
1322 res["rates"] = encode_vector(r.rates);
1323 res["meanServiceTime"] = encode_vector(r.mean_service_time);
1324 res["bound"] = encode_vector(r.bound);
1325 res["alphaTrace"] = encode_matrix(r.alpha_trace);
1326 res["betaTrace"] = encode_matrix(r.beta_trace);
1327 res["Y"] = encode_matrices(r.Y);
1328 res["nu"] = encode_matrices(r.nu);
1329 res["tgrid"] = encode_vector(r.tgrid);
1330 res["qlen"] = encode_matrix(r.qlen);
1331 res["iter"] = encode_count(r.iter);
1332 res["converged"] = r.converged;
1333 res["tailmass"] = encode_scalar(r.tailmass);
1334 Json out;
1335 out["out"] = res;
1336 return out;
1337 }
1338};
1339
1340// ---- MLPS / MINPS (double only) --------------------------------------------
1341
1342const char* const kMlpsModelWhy =
1343 "the reference reads the delay rates and the server count off the model; pass them as "
1344 "'muZ' (per-class think rates) and 'nCores' instead";
1345
1346std::vector<line::api::MlpsSample> read_mlps_samples(Args& a, const std::string& w) {
1347 const std::vector<double> rt = a.vector<double>("rt");
1348 const std::vector<std::size_t> cls = one_based_sizes(a.ints("class"), w + ": class");
1349 const Matrix<double> ql = a.matrix<double>("ql");
1350 if (cls.size() != rt.size() || ql.rows() != rt.size())
1351 throw InputError(w + ": rt, class and ql must have one row per sample");
1352 std::vector<line::api::MlpsSample> samples(rt.size());
1353 for (std::size_t i = 0; i < rt.size(); ++i) {
1354 samples[i].rt = rt[i];
1355 samples[i].cls = cls[i];
1356 samples[i].ql.resize(ql.cols());
1357 for (std::size_t c = 0; c < ql.cols(); ++c) samples[i].ql[c] = ql(i, c);
1358 }
1359 return samples;
1360}
1361
1362struct OpInferMlps {
1363 static Json run(Args& a) {
1364 a.unsupported("model", kMlpsModelWhy);
1365 a.unsupported("node", kMlpsModelWhy);
1366 const std::vector<double> muZ = a.vector<double>("muZ");
1367 const double nCores = a.number<double>("nCores");
1368 const std::vector<line::api::MlpsSample> samples = read_mlps_samples(a, "infer_mlps");
1369 a.done();
1370 Json out;
1371 out["demandEst"] = encode_vector(line::api::infer_mlps(muZ, nCores, samples));
1372 return out;
1373 }
1374};
1375
1376/**
1377 * infer_minps_setup(data, initSample, sampleSize, V, model, node): prepare the
1378 * window, then run MINPS on it, as the reference's last line does. The port
1379 * also reports what the preparation decided (lambda, Wexp, classMap).
1380 */
1381struct OpInferMinpsSetup {
1382 static Json run(Args& a) {
1383 const std::string w = "infer_minps_setup";
1384 a.unsupported("model", kMlpsModelWhy);
1385 a.unsupported("node", kMlpsModelWhy);
1386 if (a.has("V"))
1387 throw InputError(w + ": 'V' is not read by the reference, which takes the server count "
1388 "from the node; pass it as 'nCores'");
1389 a.opt("V");
1390 std::vector<std::vector<double>> at_ms, rt;
1391 read_trace_cells<double>(a.get("data"), w + ": data", at_ms, rt);
1392 std::vector<line::api::MinpsClassTrace> traces(at_ms.size());
1393 for (std::size_t k = 0; k < at_ms.size(); ++k) {
1394 traces[k].arrival_ms = at_ms[k];
1395 traces[k].rt = rt[k];
1396 }
1397 const std::size_t initSample = a.count("initSample");
1398 const std::size_t sampleSize = a.count("sampleSize");
1399 const std::vector<double> muZ = a.vector<double>("muZ");
1400 const double nCores = a.number<double>("nCores");
1401 a.done();
1402 const line::api::MinpsSetup st = line::api::infer_minps_setup(traces, initSample, sampleSize);
1403 if (muZ.size() != st.classMap.size())
1404 throw InputError(w + ": 'muZ' must have one entry per class with samples (" +
1405 std::to_string(st.classMap.size()) + "), in the order of classMap");
1406 Json out;
1407 out["demandEst"] = encode_vector(line::api::infer_minps(muZ, nCores, st.samples));
1408 out["lambda"] = encode_vector(st.lambda);
1409 out["Wexp"] = st.threads;
1410 out["classMap"] = encode_sizes(st.classMap);
1411 return out;
1412 }
1413};
1414
1415
1416/**
1417 * demand = infer_gibbs(data, nbCores, tol, seed). data is the 6 x (K+1) cell
1418 * array, of which rows 3 (arrival times, ms), 4 (response times, s) and 6
1419 * (the think-time observations) of the first K columns are read; tol defaults
1420 * to 1e-3 as in the reference. The test-set draw and the slice sampler take a
1421 * pfqn::McRng named by the required seed: MATLAB uses the session RNG, so its
1422 * estimates agree with these in law, not draw for draw.
1423 */
1424struct OpInferGibbs {
1425 static Json run(Args& a) {
1426 const std::string w = "infer_gibbs";
1427 const Json& data = a.get("data");
1428 std::vector<std::vector<double>> at_ms, rt;
1429 read_trace_cells<double>(data, w + ": data", at_ms, rt);
1430 if (data.size() < 6)
1431 throw InputError(w + ": data needs row 6 (the think-time observations) as well as "
1432 "rows 3 and 4");
1433 std::vector<line::infer::GibbsTrace<double>> traces(at_ms.size());
1434 for (std::size_t k = 0; k < at_ms.size(); ++k) {
1435 traces[k].arrival_ms = at_ms[k];
1436 traces[k].respt_s = rt[k];
1437 traces[k].think_obs =
1438 vector_from_json<double>(data[5][k], w + ": data{6," + std::to_string(k + 1) + "}");
1439 }
1440 const double nbCores = a.number<double>("nbCores");
1441 const double tol = a.scalar<double>("tol", 1e-3);
1442 pfqn::McRng rng(required_seed(a, w));
1443 a.done();
1444 Json out;
1445 out["demand"] = encode_vector(line::infer::infer_gibbs<double>(traces, nbCores, tol, rng));
1446 return out;
1447 }
1448};
1449
1450} // namespace
1451
1453 // trace
1454 t["trace_mean"] = make<OpTraceMean>();
1455 t["trace_var"] = make<OpTraceVar>();
1456 t["trace_scv"] = make<OpTraceScv>();
1457 t["trace_skew"] = make<NeedsTranscendental<OpTraceSkew>>();
1458 t["trace_idc"] = make<OpTraceIdc>();
1459 t["trace_acf"] = make<OpTraceAcf>();
1460 t["trace_bicov"] = make<OpTraceBicov>();
1461 t["trace_gamma"] = make<OpTraceGamma>();
1462 t["trace_iat2bins"] = make<OpTraceIat2bins>();
1463 t["trace_iat2counts"] = make<OpTraceIat2counts>();
1464 t["trace_idi"] = make<OpTraceIdi>();
1465 t["trace_joint"] = make<OpTraceJoint>();
1466 t["trace_pmf"] = make<OpTracePmf>();
1467 t["trace_summary"] = make<NeedsTranscendental<OpTraceSummary>>();
1468 // mtrace
1469 t["mtrace_moment"] = make<OpMtraceMoment>();
1470 t["mtrace_forward_moment"] = make<OpMtraceForwardMoment>();
1471 t["mtrace_backward_moment"] = make<OpMtraceBackwardMoment>();
1472 t["mtrace_cross_moment"] = make<OpMtraceCrossMoment>();
1473 t["mtrace_moment_simple"] = make<OpMtraceMomentSimple>();
1474 t["mtrace_count"] = make<OpMtraceCount>();
1475 t["mtrace_cov"] = make<OpMtraceCov>();
1476 t["mtrace_iat2counts"] = make<OpMtraceIat2counts>();
1477 t["mtrace_joint"] = make<OpMtraceJoint>();
1478 t["mtrace_mean"] = make<OpMtraceMean>();
1479 t["mtrace_merge"] = make<OpMtraceMerge>();
1480 t["mtrace_pc"] = make<OpMtracePc>();
1481 t["mtrace_sigma"] = make<OpMtraceSigma>();
1482 t["mtrace_sigma2"] = make<OpMtraceSigma2>();
1483 t["mtrace_split"] = make<OpMtraceSplit>();
1484 t["mtrace_summary"] = make<OpMtraceSummary>();
1485 // infer
1486 t["infer_compute_ql_at_arrival"] = make<OpInferComputeQlAtArrival>();
1487 t["infer_get_qlen_arrival"] = make<OpInferGetQlenArrival>();
1488 t["infer_lqn_findbyname"] = make<OpInferLqnFindbyname>();
1489 t["infer_lqn_getobs"] = make<OpInferLqnGetobs>();
1490 t["infer_qmle"] = make<OpInferQmle>();
1491 t["infer_rps"] = make<OpInferRps>();
1492 t["infer_quick_model"] = make<OpInferQuickModel>();
1493 t["infer_nhpp_ks"] = make<NeedsTranscendental<OpInferNhppKs>>();
1494 t["infer_nhpp_leemis"] = make<NeedsTranscendental<OpInferNhppLeemis>>();
1495 t["infer_nhpp_powerlaw"] = make<NeedsTranscendental<OpInferNhppPowerlaw>>();
1496 t["infer_variational"] = make<NeedsTranscendental<OpInferVariational>>();
1497 t["infer_smp"] = make<DoubleOnly<OpInferSmp>>();
1498 t["infer_smp_hazard"] = make<DoubleOnly<OpInferSmpHazard>>();
1499 t["infer_smp_nelson_aalen"] = make<DoubleOnly<OpInferSmpNelsonAalen>>();
1500 t["infer_smp_family"] = make<DoubleOnly<OpInferSmpFamily>>();
1501 t["infer_mlps"] = make<DoubleOnly<OpInferMlps>>();
1502 t["infer_minps_setup"] = make<DoubleOnly<OpInferMinpsSetup>>();
1503 t["infer_gibbs"] = make<DoubleOnly<OpInferGibbs>>();
1504}
1505
1507 t["infer_lqn_jacobian"] =
1508 "its first argument hfun is a function handle (the LQN observation map), which JSON "
1509 "cannot carry.";
1510 t["infer_lqn_ekf"] =
1511 "its first argument hfun is a function handle (the LQN observation map), which JSON "
1512 "cannot carry.";
1513 t["infer_lqn"] =
1514 "it calibrates a LayeredNetwork model in place through a solver callable; no line-cli "
1515 "analysis serves LQN inference yet.";
1516 t["infer_lqn_setparams"] =
1517 "it writes parameters into a LayeredNetwork model object in place; there is no data "
1518 "result to return.";
1519 t["infer_fmlps"] =
1520 "it reads the Network model and the station node (NetworkStruct), not a data argument; "
1521 "no line-cli analysis serves demand inference yet.";
1522 t["infer_smp_env"] =
1523 "it takes the per-stage Network models and returns an Environment model object; solve "
1524 "the resulting environment with line-cli -s env.";
1525}
1526
1527} // namespace reg
1528} // namespace line
Internal to the –api dispatcher: what a per-domain translation unit needs to add entries to the table...
#define LINE_MTRACE_DIRECTED_MOMENT_OP(Name, fn)
#define LINE_MTRACE_CROSS_MOMENT_OP(Name, fn)
#define LINE_TRACE_SCALAR_OP(Name, fn, outkey)
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
Per-class queue lengths seen by each arriving job, reconstructed from arrival and response time sampl...
Per-class queue lengths at arrival for the per-class sample format.
Gibbs sampling demand estimator for a closed delay-plus-queue model.
First element of a named LQN container matching a name.
Observation vector of a solved LQN, z = h(a).
Turn a raw per-class trace into the sample set MINPS estimates from.
Maximum-likelihood service-demand estimation at a processor-sharing queue.
Fitting a nonstationary Poisson process from ONE observed sequence of arrival times.
Kolmogorov-Smirnov tests for a non-homogeneous Poisson arrival process.
Queue-length-based maximum-likelihood estimator of the service demands of a closed queueing network.
Convenience factory for the single-layer networks the inference estimators fit.
Regression for Processor Sharing (RPS) demand estimator.
Maximum-likelihood fit of a parametric semi-Markov multi-state model.
Variational inference for Markovian queueing networks.
Backward moments of a marked trace: the moments of the inter-arrival time that PRECEDES an event of e...
Per-class count process of a marked trace on a fixed resolution: the number of events of each class i...
Class-pair covariance matrices of a marked trace.
Class-pair cross moments of a marked trace: the k-th moment of the interval that separates an event o...
Forward moments of a marked trace: the moments of the inter-arrival time that FOLLOWS an event of eac...
Per-class counting processes of a marked trace: for each arrival, how many events of each class fall ...
Class-dependent joint moments of a marked trace,.
Per-type sample mean of a trace.
Superposes two single-class traces into one marked trace, labelling the events of the first stream 1 ...
Empirical class-dependent moments of a marked trace.
Class-pair cross moments of a marked trace.
Class probabilities of a marked trace, p_c = count_c / N.
Two-step class transition frequencies of a marked trace,.
One-step class transition frequencies of a marked trace,.
Splits a marked trace into its per-class traces: for each class, the inter-arrival times BETWEEN CONS...
Descriptor set of a marked trace: the first five raw moments of the inter-arrival times,...
std::vector< double > infer_minps(const std::vector< double > &muZ, double nCores, const std::vector< MlpsSample > &samples)
MINPS: run MLPS and RPS and keep whichever gives the smaller mean demand.
Definition infer_mlps.h:322
std::vector< double > infer_mlps(const std::vector< double > &muZ, double nCores, const std::vector< MlpsSample > &samples)
MLPS demand estimation at a PS queue.
Definition infer_mlps.h:117
MinpsSetup infer_minps_setup(const std::vector< MinpsClassTrace > &traces, std::size_t initSample, std::size_t sampleSize)
Turn a raw per-class trace into the sample set MINPS estimates from.
NhppKsResult< Tv > infer_nhpp_ks(const std::vector< Tv > &times, const Tv &T, const std::function< Tv(const Tv &)> &cumRate=std::function< Tv(const Tv &)>(), NhppKsMethod method=NhppKsMethod::Lewis, const Tv &T0=num_traits< Tv >::from_int(0))
Kolmogorov-Smirnov tests for a non-homogeneous Poisson arrival process.
static const std::size_t INFER_LQN_NOT_FOUND
Returned when no element carries the requested name, MATLAB's [].
std::size_t infer_smp_family_npar(const std::string &family)
infer_smp_family(F, 'npar'): the number of parameters, validating the name.
Definition infer_smp.h:80
VariationalResult< T > infer_variational(VariationalSpec< T > spec, VariationalOptions< T > opt=VariationalOptions< T >())
Run the variational inference procedure.
std::vector< SmpHazard > infer_smp_hazard(const SmpFit &fit, const std::vector< double > &t, const std::vector< double > &zin=std::vector< double >())
infer_smp_hazard(fit, t, 'z', z): both hazard functions of every arc of a fit on the ascending instan...
Definition infer_smp.h:887
std::vector< T > infer_rps(const std::vector< T > &rt, const std::vector< std::size_t > &cls, const Matrix< T > &ql, long V)
Regression for Processor Sharing (RPS) demand estimator.
Definition infer_rps.h:57
std::vector< double > infer_smp_family_natural(const std::string &family, const std::vector< double > &th)
infer_smp_family(F, 'natural', THETA): rate | shape, scale | mu, sigma.
Definition infer_smp.h:140
qn::Network< T > infer_quick_model(bool is_open, const std::vector< lang::SchedStrategy > &stations, const Matrix< T > &demands, const std::vector< double > &servers=std::vector< double >(), const std::vector< double > &jobs=std::vector< double >(), const std::vector< Matrix< T > > &routing=std::vector< Matrix< T > >())
Build a simple open or closed queueing network.
void infer_smp_family_logfs(const std::string &family, const std::vector< double > &th, const std::vector< double > &t, const std::vector< double > &eta, std::vector< double > &logf, std::vector< double > &logS)
infer_smp_family(F, 'logfs', THETA, T, ETA): log density and log survival at t under the proportional...
Definition infer_smp.h:95
std::size_t infer_lqn_findbyname(const std::vector< std::string > &names, const std::string &name)
First element of a named LQN container matching a name.
std::vector< T > infer_gibbs(const std::vector< GibbsTrace< T > > &data, const T &nbCores, const GibbsOptions &opts, pfqn::McRng &rng)
Estimated per-class mean demands.
Matrix< T > infer_qmle(const Matrix< T > &Q, const std::vector< T > &N, const std::vector< T > &Z)
Queue-length-based maximum-likelihood estimator of the service demands of a closed queueing network.
Definition infer_qmle.h:50
lang::Distrib< double > infer_smp_family_dist(const std::string &family, const std::vector< double > &th, double eta)
infer_smp_family(F, 'dist', THETA, ETA): the LINE distribution of the law with hazard h0(t) exp(eta).
Definition infer_smp.h:187
std::vector< double > infer_smp_family_theta0(const std::string &family, const std::vector< double > &tev, double texp)
infer_smp_family(F, 'theta0', TEV, TEXP): the starting point from the event times tev and the total e...
Definition infer_smp.h:154
std::vector< Matrix< T > > infer_get_qlen_arrival(const std::vector< std::vector< T > > &at_ms, const std::vector< std::vector< T > > &rt)
Per-class queue lengths at arrival for the per-class sample format.
NhppPowerLawResult< T > infer_nhpp_powerlaw(const std::vector< T > &times, const T &horizon, double alpha=0.05)
Maximum likelihood power-law NHPP fit, Lambda(t) = (a t)^b, from one sample path, with observed-infor...
NhppKsMethod
Which test to run on the conditional-uniform data.
std::vector< T > infer_lqn_getobs(const std::vector< std::string > &names, const LqnMetrics< T > &metrics, const std::vector< LqnObsSpec > &spec)
Observation vector of a solved LQN, z = h(a).
NhppLeemisResult< T > infer_nhpp_leemis(const std::vector< T > &times, const T &horizon, const std::vector< T > &tq=std::vector< T >(), double alpha=0.05)
Nonparametric integrated-rate estimate of an NHPP from one sample path: the step-function estimator w...
Matrix< T > infer_compute_ql_at_arrival(const std::vector< T > &at, const std::vector< long > &at_jobid, const std::vector< T > &rt, const std::vector< long > &rt_jobid, const std::vector< std::size_t > &cls, std::size_t R)
Per-class queue lengths seen by each arriving job, reconstructed from arrival and response time sampl...
SmpFit infer_smp(const std::vector< std::size_t > &from, const std::vector< std::size_t > &to, const std::vector< double > &dur, const SmpOptions &opt=SmpOptions())
infer_smp(from, to, dur, ...): the fit, under opt.approach.
Definition infer_smp.h:671
std::vector< SmpNelsonAalen > infer_smp_nelson_aalen(const std::vector< std::size_t > &from, const std::vector< std::size_t > &to, const std::vector< double > &dur, std::size_t nstates=0)
infer_smp_nelson_aalen(from, to, dur, 'nstates', E): the Nelson-Aalen estimate of the cumulative tran...
Definition infer_smp.h:1028
detail::json network_json_envelope(const qn::NetworkStruct< T > &sn)
The complete model.json envelope: {format, version, model}.
double z(double v)
Definition lqn_focus.h:261
std::string name(const Element *el, const std::string &key="name")
std::mt19937_64 McRng
The generator type every Monte Carlo entry point in this tree accepts.
nlohmann::json Json
Definition api_json.h:63
void register_library_only_trace(LibraryOnlyTable &t)
std::uint64_t required_seed(Args &a, const std::string &fn, const char *spelled="seed")
The seed of a function whose port draws from a caller-owned generator.
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
std::vector< int > int_vector_from_json(const Json &j, const std::string &where)
An integer vector; a non-integral entry is an error, never a truncation.
Definition api_json.h:267
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
T number_from_json(const Json &j, const std::string &where)
Definition api_json.h:210
std::vector< T > vector_from_json(const Json &j, const std::string &where)
A flat numeric vector: 1-D array, or a 1-row / 1-column 2-D array.
Definition api_json.h:255
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_api_trace(DispatchTable &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_ints(const std::vector< int > &v)
Definition api_json.h:350
std::map< std::string, Invoker > DispatchTable
MtraceCountResult< T > mtrace_count(const std::vector< T > &Tv, const std::vector< int > &A, const T &t)
Per-class count process of a marked trace on a fixed resolution: the number of events of each class i...
MtraceJointResult< T > mtrace_joint(const std::vector< T > &Tv, const std::vector< int > &A, unsigned i1, unsigned i2)
Class-dependent joint moments of a marked trace, JM(a) = (1/N_a) sum_{j : A_{j+1} = a}...
MtraceMeanResult< T > mtrace_mean(const std::vector< T > &Tv, long ntypes, const std::vector< int > &type)
Per-type sample mean of a trace.
Definition mtrace_mean.h:50
TraceBicovResult< T > trace_bicov(const std::vector< T > &S, const std::vector< int > &grid)
Bicovariance of a trace on a lag grid.
Definition trace_bicov.h:50
TraceSummary< T > trace_summary(const std::vector< T > &S)
Descriptive summary of a trace: moments, shape, order statistics, autocorrelation and burstiness.
std::vector< std::vector< Matrix< T > > > mtrace_cov(const std::vector< T > &Tv, const std::vector< int > &A)
Class-pair covariance matrices of a marked trace.
Definition mtrace_cov.h:48
TracePmfResult< T > trace_pmf(const std::vector< int > &X)
Empirical probability mass function of a discrete trace (counts, batch sizes, queue-length samples).
Definition trace_pmf.h:54
TraceBinsResult trace_iat2bins(const std::vector< T > &S, const T &scale)
Bins a trace on a fixed time grid: the number of arrivals falling in each interval ((i-1)*scale,...
Matrix< T > mtrace_sigma2(const std::vector< int > &L)
Two-step class transition frequencies of a marked trace, sigma(i,j,h) = #{t : A_t = i,...
MtraceMergeResult< T > mtrace_merge(const std::vector< T > &t1, const std::vector< T > &t2)
Superposes two single-class traces into one marked trace, labelling the events of the first stream 1 ...
MtraceSummary< T > mtrace_summary(const std::vector< T > &Tv, const std::vector< int > &A, int max_lag=100)
Descriptor set of a marked trace: the first five raw moments of the inter-arrival times,...
MtraceCountsResult< T > mtrace_iat2counts(const std::vector< T > &Tv, const std::vector< int > &A, const T &scale)
Per-class counting processes of a marked trace: for each arrival, how many events of each class fall ...
TraceGammaResult< T > trace_gamma(const std::vector< T > &S, long limit=1000, const std::vector< T > &grid=std::vector< T >())
Autocorrelation decay rate of a trace: the gamma of the geometric model rho(k) = rho0 * gamma^k,...
Definition trace_gamma.h:73
MtraceSplitResult< T > mtrace_split(const std::vector< T > &Tv, const std::vector< int > &L)
Splits a marked trace into its per-class traces: for each class, the inter-arrival times BETWEEN CONS...
std::vector< T > mtrace_pc(const std::vector< int > &A)
Class probabilities of a marked trace, p_c = count_c / N.
Definition mtrace_pc.h:42
Matrix< T > mtrace_moment(const std::vector< T > &Tv, const std::vector< int > &A, const std::vector< unsigned > &orders, bool after=false, bool norm=false)
Empirical class-dependent moments of a marked trace.
TraceIdiResult< T > trace_idi(const std::vector< T > &S, const std::vector< long > &k_set, long aggregate_n=0, bool drop_trailing_zero=false)
Index of dispersion for intervals, IDI(k) = k * var(S_t + ... + S_{t+k-1}) / mean(S_t + ....
Definition trace_idi.h:71
T trace_joint(const std::vector< T > &S, const std::vector< int > &lag, const std::vector< unsigned > &order)
Joint moments of a trace, E[X_i^{k_1} X_{i+l_2}^{k_2} ...].
Definition trace_joint.h:53
Matrix< T > mtrace_sigma(const std::vector< int > &L)
One-step class transition frequencies of a marked trace, sigma(i,j) = #{t : A_t = i,...
std::vector< T > trace_acf(const std::vector< T > &S, const std::vector< int > &lags)
Autocorrelation coefficients of a trace at the requested lags.
Definition trace_acf.h:57
std::vector< long > trace_iat2counts(const std::vector< T > &S, const T &scale)
Counting process of a trace: the number of arrivals in the window of length scale that starts at each...
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 ...
qn::NetworkStruct -> model.json, the inverse of network_reader.h.
std::vector< double > lambda
per-surviving-class think-time rate
std::vector< MlpsSample > samples
sorted by arrival time, window applied
std::vector< std::size_t > classMap
Original 1-based class label of each surviving class, in the new order.
double threads
Wexp, the largest total queue length seen.
T statistic
the KS distance
std::vector< T > uniforms
after the conditional-uniform transformation
std::size_t n
number of arrivals used
T pvalue
asymptotic p-value
std::vector< T > transformed
after the Durbin step (Lewis), or 1-exp(-gap) (Tt)
std::vector< T > tq
query points
std::vector< T > knots
breakpoints [0, times, T], length N+2
T horizon
the observation horizon
std::vector< T > rates
piecewise-constant rate on each gap, length N+1
std::size_t n
number of arrivals N
std::vector< T > knotValues
piecewise-linear estimate at the knots
std::vector< T > cumRate
piecewise-linear estimate at tq
std::vector< T > upper
upper pointwise bound at tq
std::vector< T > step
step-function estimate at tq
std::vector< T > lower
lower pointwise bound at tq, floored at zero
T shape
the power-law shape b
T se[2]
standard errors of (a, b)
T scaleCI[2]
Wald interval for a.
T horizon
the observation horizon
T info[2][2]
observed information, order (a, b)
T shapeCI[2]
Wald interval for b.
T scale
the power-law scale a
T loglik
maximised log-likelihood
std::size_t n
number of arrivals N
std::size_t from
Definition infer_smp.h:233
std::vector< double > beta
p covariate effects, zero where masked out
Definition infer_smp.h:237
std::string family
Definition infer_smp.h:234
std::vector< double > theta
unconstrained parameters
Definition infer_smp.h:235
std::vector< double > se
standard errors of [theta; beta]
Definition infer_smp.h:238
std::size_t nevents
Definition infer_smp.h:241
std::vector< double > params
natural parameters
Definition infer_smp.h:236
double prob
Approach I: p_ij; Approach II: the embedded probability at z = 0.
Definition infer_smp.h:240
std::size_t nstates
Definition infer_smp.h:247
std::size_t nparams
Definition infer_smp.h:251
std::string approach
Definition infer_smp.h:246
Matrix< double > P
E x E embedded jump chain at z = 0.
Definition infer_smp.h:253
std::vector< SmpArc > arcs
Definition infer_smp.h:249
std::size_t ncov
Definition infer_smp.h:248
double delta
rate added to every feasible transition by the space expansion.
double rate_max
cap on the variational rates; derived from ymax and tmax when negative.
std::vector< Matrix< T > > nu
std::vector< Matrix< T > > Y
std::vector< T > obsRange
(M*R) support size of the uniform contamination.
std::vector< T > arcrate
(T) known rate for transitions with arcparam == 0.
std::vector< T > capacity
(M*R) upper bound on the queue length, empty for none.
std::vector< std::size_t > arcparam
(T) index in 1..P of the rate governing the transition, 0 when known.
Matrix< T > x0
(M x R) initial queue lengths.
Matrix< T > obsData
(K x M*R) observed queue lengths; an unobserved entry is unobserved.
static T unobserved()
Sentinel marking an unobserved entry of obsData.
std::vector< std::array< std::size_t, 3 > > arcs
(T x 3) transitions [i j c]; i==0 external source, j==0 sink.
std::vector< int > sched
(M) discipline codes.
std::vector< T > obsTimes
(K) observation epochs.
std::vector< T > alpha0
(P) Gamma prior shapes and rates.
std::vector< T > nservers
(M) number of servers.
std::vector< T > routeprob
(T) routing probability of each transition.
T epsilon
probability that a reading is faulty.
std::vector< long > count
interior events of each label; 0 = undefined
std::vector< T > jm
one moment per label 1..max(A)
std::vector< T > mean
one mean per type; undefined where count = 0
Definition mtrace_mean.h:38
std::vector< long > count
samples of each type
Definition mtrace_mean.h:39
std::vector< int > labels
1 for the first stream, 2 for the second
std::vector< T > times
inter-arrival times of the merged process
Matrix< T > Pab
one-step class transition frequencies
std::vector< T > Pc
class probabilities
std::vector< T > M
raw moments of order 1..5
Matrix< T > C2
class-pair cross moments of order 1 and 2
Matrix< T > B2
backward moments of order 1 and 2
std::vector< T > acf
autocorrelation at the requested lags
Matrix< T > F2
forward moments of order 1 and 2
std::vector< std::vector< int > > lags
the [1,i,j] increment triples
Definition trace_bicov.h:40
std::vector< T > bicov
one moment per grid pair
Definition trace_bicov.h:39
std::vector< long > counts
arrivals per bin
std::vector< long > membership
1-based bin index of each binned arrival
T rho0
(1 - 1/scv)/2, the GE-type lag-0 amplitude
Definition trace_gamma.h:58
T gamma
best decay rate on the grid
Definition trace_gamma.h:57
T residuals
sum of squared deviations from the fitted model
Definition trace_gamma.h:59
std::vector< T > idi
one value per requested k
Definition trace_idi.h:53
std::vector< long > support
the number of points each value rests on
Definition trace_idi.h:54
std::vector< T > pmf
relative frequency of each distinct value
Definition trace_pmf.h:43
std::vector< int > values
the distinct values, in increasing order
Definition trace_pmf.h:44
T mad
median absolute deviation about the median
T kurt_excess
population kurtosis minus 3
std::vector< T > acf
lags 1..4
T skew
bias-corrected skewness, see trace_skew
Autocorrelation coefficients of a trace at the requested lags.
Bicovariance of a trace on a lag grid.
Autocorrelation decay rate of a trace: the gamma of the geometric model rho(k) = rho0 * gamma^k,...
Bins a trace on a fixed time grid: the number of arrivals falling in each interval ((i-1)*scale,...
Counting process of a trace: the number of arrivals in the window of length scale that starts at each...
Index of dispersion for counts, estimated by its asymptotic equality with the index of dispersion for...
Index of dispersion for intervals,.
Joint moments of a trace, E[X_i^{k_1} X_{i+l_2}^{k_2} ...].
Sample mean of a trace.
Empirical probability mass function of a discrete trace (counts, batch sizes, queue-length samples).
Squared coefficient of variation of a trace, var/mean^2.
Bias-corrected sample skewness (MATLAB's skewness(S,0), equivalently the G1 estimator).
Descriptive summary of a trace: moments, shape, order statistics, autocorrelation and burstiness.
Sample variance of a trace.