5#ifndef LINE_LANG_LAL_MAM_TRAFFIC_H
6#define LINE_LANG_LAL_MAM_TRAFFIC_H
40 mam::Mmap<double> out;
43 for (std::size_t k = 2; k < m.size(); ++k) out.Dc.push_back(m[k]);
49 for (
const Matrix<double>& d : m.Dc) out.push_back(d);
59inline mam::Mmap<double> compress_mmap(
const mam::Mmap<double>& in,
const std::string& method) {
61 if (method ==
"exponential") {
64 mam::Mmap<double> out;
65 out.D0 = Matrix<double>(1, 1, -lambda);
66 out.D1 = Matrix<double>(1, 1, lambda);
67 for (std::size_t c = 0; c <
in.classes(); ++c) out.Dc.push_back(Matrix<double>(1, 1, p[c] * lambda));
70 static const std::map<std::string, MmapCompressMethod> names = {
71 {
"default", MmapCompressMethod::MixtureOrder1},
72 {
"mixture", MmapCompressMethod::MixtureOrder1},
73 {
"mixture.order1", MmapCompressMethod::MixtureOrder1},
74 {
"mixture.order2", MmapCompressMethod::MixtureOrder2},
75 {
"mamap2", MmapCompressMethod::Mamap2},
76 {
"mamap2.fb", MmapCompressMethod::Mamap2Fb},
77 {
"m3pp.approx_cov", MmapCompressMethod::M3ppApproxCov},
78 {
"m3pp.approx_ag", MmapCompressMethod::M3ppApproxAg},
79 {
"m3pp.exact_delta", MmapCompressMethod::M3ppExactDelta},
80 {
"m3pp.approx_delta", MmapCompressMethod::M3ppApproxDelta}};
81 auto it = names.find(method);
82 if (it == names.end())
throw InputError(
"Unknown compression method: " + method);
90inline Matrix<double> block_diag(
const std::vector<Matrix<double>>& blocks) {
92 for (
const Matrix<double>& b : blocks) n += b.rows();
93 Matrix<double> out(n, n, 0.0);
95 for (
const Matrix<double>& b : blocks) {
96 for (std::size_t i = 0; i < b.rows(); ++i)
97 for (std::size_t j = 0; j < b.cols(); ++j) out(off + i, off + j) = b(i, j);
114 bool materialize =
true) {
115 if (!snapshot.
min_syncs.empty())
return std::nullopt;
116 std::vector<std::string> names;
118 if (a.
name != level_name) names.push_back(a.
name);
119 if (names.empty())
return std::nullopt;
120 std::map<Endpoint, std::vector<Endpoint>> sync;
121 std::vector<Endpoint> sync_order;
123 if (!sync.count(s.
active)) sync_order.push_back(s.
active);
127 for (
const std::string& name : names) {
129 for (std::size_t i = 0; i < agent.
states.size(); ++i)
130 if (agent.
states[i] !=
"phase_" + std::to_string(i))
return std::nullopt;
131 std::vector<std::string> actions;
134 if (
tr.action !=
"_phase" && std::find(actions.begin(), actions.end(),
tr.action) == actions.end())
135 actions.push_back(
tr.action);
137 if (actions.empty() || sync.count(
Endpoint(name,
"_phase")))
return std::nullopt;
138 for (
const std::string& action : actions) {
139 auto it = sync.find(
Endpoint(name, action));
140 if (it == sync.end() || it->second.size() != 1 || it->second[0].first != level_name)
return std::nullopt;
142 const std::size_t n = agent.
states.size();
144 std::vector<Matrix<double>> marks(actions.size(),
Matrix<double>(n, n, 0.0));
147 if (
tr.action ==
"_phase") {
148 if (i != j) d0(i, j) +=
tr.value;
150 const std::size_t k =
static_cast<std::size_t
>(
151 std::find(actions.begin(), actions.end(),
tr.action) - actions.begin());
152 marks[k](i, j) +=
tr.value;
157 for (std::size_t i = 0; i < n; ++i) {
159 for (std::size_t j = 0; j < n; ++j) r += d0(i, j);
161 for (std::size_t j = 0; j < n; ++j) r += m(i, j);
165 stream.insert(stream.end(), marks.begin(), marks.end());
167 for (
const std::string& action : actions) {
168 t.
marks.push_back(name +
"." + action);
172 for (
const Endpoint& active : sync_order) {
173 const std::vector<Endpoint>& partners = sync[active];
174 if (active.first == level_name || std::find(names.begin(), names.end(), active.first) == names.end() ||
175 active.second ==
"_phase")
177 if (partners.size() != 1 || partners[0].first != level_name)
return std::nullopt;
180 if (!detail::feasible(s, 1e-6))
return std::nullopt;
183 for (std::size_t k = 1; k < t.
streams.size(); ++k)
186 if (!detail::feasible(c, 1e-6))
return std::nullopt;
193 t.
blocking = std::string(
"Excluded: accepted traffic depends on queue state.");
236 const std::size_t n = q.
rows();
237 const std::size_t marks = stream.size() - 2;
238 const std::vector<double> pi = stationary(q);
239 auto row_times = [&](
const std::vector<double>& v,
const Matrix<double>& a) {
240 std::vector<double> out(a.cols(), 0.0);
241 for (std::size_t i = 0; i < a.rows(); ++i)
242 for (std::size_t j = 0; j < a.cols(); ++j) out[j] += v[i] * a(i, j);
245 auto total = [](
const std::vector<double>& v) {
247 for (
double x : v) s += x;
250 std::vector<double> rates(marks, 0.0);
251 for (std::size_t k = 0; k < marks; ++k) rates[k] = total(row_times(pi, stream[k + 2]));
252 Matrix<double> generator(3 * n, 3 * n, 0.0);
254 for (std::size_t i = 0; i < n; ++i) {
255 for (std::size_t j = 0; j < n; ++j) {
256 generator(i, j) = q(i, j) * duration;
257 finite = finite && std::isfinite(generator(i, j));
259 generator(i, n + i) = 1.0;
260 generator(n + i, 2 * n + i) = 1.0;
262 if (!finite)
throw mam_refusal(
"Numerical",
"Traffic count window exceeds numerical limits.");
263 const Matrix<double> e =
line::expm(generator);
264 Matrix<double> integral(n, n, 0.0);
265 for (std::size_t i = 0; i < n; ++i)
266 for (std::size_t j = 0; j < n; ++j) integral(i, j) = e(i, 2 * n + j);
267 std::vector<Matrix<double>> scaled_marks;
268 for (std::size_t k = 0; k < marks; ++k) scaled_marks.push_back(scaled(stream[k + 2], duration));
269 std::vector<double> means(marks, 0.0);
270 for (std::size_t k = 0; k < marks; ++k) means[k] = rates[k] * duration;
271 Matrix<double> covariance(marks, marks, 0.0);
272 for (std::size_t i = 0; i < marks; ++i)
273 for (std::size_t j = 0; j < marks; ++j) {
274 const double lr = total(row_times(row_times(row_times(pi, scaled_marks[i]), integral), scaled_marks[j]));
275 const double rl = total(row_times(row_times(row_times(pi, scaled_marks[j]), integral), scaled_marks[i]));
276 covariance(i, j) = lr + rl - means[i] * means[j] + (i == j ? means[i] : 0.0);
278 return {rates, covariance};
293 const std::string& method,
const std::string& compress_method,
double fit_time,
295 auto refuse = [](
const std::string& message) {
return detail::mam_refusal(
"Model", message); };
296 if (!std::isfinite(fit_time) || fit_time <= 0)
throw InputError(
"lal_fit_time must be finite and positive");
297 if (!std::isfinite(fit_tolerance) || fit_tolerance < 0)
298 throw InputError(
"lal_fit_tolerance must be finite and nonnegative");
299 if (method ==
"compress" && !original)
300 throw refuse(
"Compression requires the original superposed MMAP within its storage limit.");
301 const double tiny = detail::tiny();
303 if (detail::strong_count_positive(detail::add(stream[0], stream[1])) != 1)
304 throw refuse(
"Traffic fitting requires irreducible offered phase processes.");
306 for (std::size_t k = 0; k < stream[1].size(); ++k)
307 if (stream[1][k] > 0) any =
true;
308 if (!any)
throw refuse(
"Traffic fitting does not support an entirely zero-rate source.");
310 double largest_rate = 0.0;
311 for (
const MarkedMatrices& stream : traffic.
streams) largest_rate = std::max(largest_rate, detail::marked_max_abs(stream));
312 const double factor = (largest_rate < 1e-8 || largest_rate > 1e8) ? largest_rate : 1.0;
313 if (!std::isfinite(factor) || factor <= 0 || !std::isfinite(fit_time * factor) || fit_time * factor == 0)
314 throw refuse(
"Traffic fitting time scale exceeds numerical limits.");
317 for (
const Matrix<double>& x : m) out.push_back(detail::scaled(x, 1.0 / f));
322 for (
const Matrix<double>& x : m) out.push_back(detail::scaled(x, f));
325 std::vector<MarkedMatrices> fitting_streams;
326 for (
const MarkedMatrices& stream : traffic.
streams) fitting_streams.push_back(divided(stream, factor));
327 const double fitting_time = fit_time * factor;
329 if (method ==
"compress") {
330 const MarkedMatrices scaled_original = divided(*original, factor);
331 if (backend.compress)
332 fitted = backend.compress(scaled_original, compress_method);
334 fitted = detail::from_mmap(detail::compress_mmap(detail::to_mmap(scaled_original), compress_method));
335 }
else if (method ==
"interpos") {
336 if (traffic.
streams.size() < 2)
throw refuse(
"Interposition requires at least two independent marked sources.");
340 bool diagonal =
true;
341 for (std::size_t k = 2; k < source.size(); ++k) {
342 const double scale = std::max(tiny, detail::max_abs(source[k]));
343 for (std::size_t i = 0; i < source[k].rows(); ++i)
344 for (std::size_t j = 0; j < source[k].cols(); ++j)
345 if (i != j && std::fabs(source[k](i, j)) > 1e-12 * scale) diagonal =
false;
347 if (source[0].rows() <= 2 && diagonal)
return source;
348 const double source_scale = detail::marked_max_abs(source);
349 const double local_factor = (source_scale < 1e-8 || source_scale > 1e8) ? source_scale : 1.0;
350 const double local_time = fitting_time * local_factor;
351 if (!std::isfinite(local_time) || local_time <= 0)
352 throw refuse(
"An interposition source has an unsupported time scale.");
355 backend.m3pp_fit ? backend.m3pp_fit(normalized, std::string(
"exact_delta"), local_time, 1e6)
357 std::string(
"exact_delta"), local_time, 1e6));
358 return multiplied(fitted_source, local_factor);
360 std::vector<MarkedMatrices> fitted_sources;
361 for (
const MarkedMatrices& s : fitting_streams) fitted_sources.push_back(fit_source(s));
363 if (s[0].rows() != 1 && s[0].rows() != 2)
364 throw refuse(
"Interposition requires one- or two-phase fitted source processes.");
368 std::vector<std::size_t> order, poisson;
369 for (std::size_t i = 0; i < fitted_sources.size(); ++i)
370 (fitted_sources[i][0].rows() == 2 ? order : poisson).push_back(i);
371 std::stable_sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) {
372 return fitted_sources[a][0](0, 1) > fitted_sources[b][0](0, 1);
377 if (!order.empty()) {
378 std::vector<mam::Mmap<double>> parts;
379 for (std::size_t i : order) parts.push_back(detail::to_mmap(fitted_sources[i]));
384 std::map<std::size_t, std::vector<Matrix<double>>> slices;
385 std::size_t offset = 2;
386 for (std::size_t i : order) {
387 const std::size_t count = fitted_sources[i].size() - 2;
388 slices[i] = std::vector<Matrix<double>>(combined.begin() +
static_cast<long>(offset),
389 combined.begin() +
static_cast<long>(offset + count));
392 const std::size_t n = combined[0].rows();
393 double added_rate = 0.0;
394 for (std::size_t i : poisson) {
395 for (std::size_t k = 2; k < fitted_sources[i].size(); ++k) {
396 const double rate = fitted_sources[i][k](0, 0);
397 slices[i].push_back(detail::scaled(
eye<double>(n), rate));
401 fitted = {detail::add(combined[0], detail::scaled(
eye<double>(n), -added_rate)),
402 detail::add(combined[1], detail::scaled(
eye<double>(n), added_rate))};
403 for (std::size_t i = 0; i < fitted_sources.size(); ++i)
406 throw InputError(
"Unknown LAL traffic fitting method");
408 fitted = multiplied(fitted, factor);
409 const double fitted_scale = std::max(tiny, detail::marked_max_abs(fitted));
411 for (
const Matrix<double>& x : fitted) finite = finite && detail::all_finite(x);
412 if (fitted.size() != traffic.
marks.size() + 2 || !finite || !detail::feasible(fitted, 1e-10 * fitted_scale))
413 throw refuse(
"The fitted marked process is infeasible or lost mark matrices.");
414 const std::size_t n = fitted[0].rows();
415 bool negative =
false;
416 for (std::size_t i = 0; i < n; ++i)
417 for (std::size_t j = 0; j < n; ++j) {
418 if (i != j && fitted[0](i, j) < 0) negative =
true;
419 if (i == j && fitted[0](i, j) > 0) negative =
true;
421 for (std::size_t k = 1; k < fitted.size(); ++k)
422 for (std::size_t e = 0; e < fitted[k].size(); ++e)
423 if (fitted[k][e] < 0) negative =
true;
424 if (negative)
throw refuse(
"The fitted marked process contains negative transition rates.");
425 for (std::size_t i = 0; i < n; ++i) {
426 double row = 0.0, row_scale = 0.0;
427 for (std::size_t j = 0; j < n; ++j) {
428 row += fitted[0](i, j) + fitted[1](i, j);
429 row_scale += std::fabs(fitted[0](i, j)) + std::fabs(fitted[1](i, j));
431 if (std::fabs(row) > 1e-10 * std::max(row_scale, tiny))
432 throw refuse(
"The fitted marked process has invalid generator row sums.");
434 for (std::size_t e = 0; e < fitted[1].size(); ++e) {
435 double mark_sum = 0.0;
436 for (std::size_t k = 2; k < fitted.size(); ++k) mark_sum += fitted[k][e];
437 const double scale = std::max(std::max(std::fabs(fitted[1][e]), std::fabs(mark_sum)), tiny);
438 if (std::fabs(fitted[1][e] - mark_sum) > 1e-10 * scale)
439 throw refuse(
"The fitted aggregate event matrix does not match its marks.");
441 if (detail::strong_count_positive(detail::add(fitted[0], fitted[1])) != 1)
442 throw refuse(
"The fitted offered phase process is reducible.");
444 std::vector<Matrix<double>> covs;
446 const auto stats = detail::count_statistics(stream, fit_time);
448 covs.push_back(stats.second);
451 const auto after = detail::count_statistics(fitted, fit_time);
455 for (
double r : out.
before_rate) ok = ok && std::isfinite(r);
456 for (
double r : out.
after_rate) ok = ok && std::isfinite(r);
457 if (!ok)
throw refuse(
"Traffic fit counting statistics are not finite.");
459 const double scale = std::max(tiny, detail::max_abs(*cov));
460 const std::size_t m = cov->rows();
463 for (std::size_t i = 0; i < m; ++i)
464 for (std::size_t j = 0; j < m; ++j) {
465 if (std::fabs((*cov)(i, j) - (*cov)(j, i)) > 1e-8 * scale) bad =
true;
466 sym(i, j) = ((*cov)(i, j) + (*cov)(j, i)) / 2.0;
469 const std::vector<double> ev = detail::eigvalsh(
sym);
470 if (ev.front() < -1e-8 * scale) bad =
true;
472 if (bad)
throw refuse(
"Traffic fit count covariance is numerically invalid.");
475 throw refuse(
"The fitted marked process is infeasible or lost mark matrices.");
480 double max_rate = 0.0;
481 for (
double r : out.
before_rate) max_rate = std::max(max_rate, std::fabs(r));
482 const double rate_floor = std::max(tiny, max_rate * 1e-12);
484 for (std::size_t k = 0; k < out.
before_rate.size(); ++k) {
489 const double covariance_floor = std::max(tiny, detail::max_abs(out.
before_cov) * 1e-12);
490 std::vector<double> sd(m, 0.0);
491 for (std::size_t i = 0; i < m; ++i) sd[i] = std::sqrt(std::max(out.
before_cov(i, i), 0.0));
493 for (std::size_t i = 0; i < m; ++i)
494 for (std::size_t j = 0; j < m; ++j) {
495 const double s = sd[i] * sd[j];
496 const double scale = s > 0 ? s : covariance_floor;
501 throw refuse(
"Traffic fit error exceeds lal_fit_tolerance: rate=" + detail::fmt_g(out.
rate_error) +
Matrix exponential by scaling and squaring with a diagonal Pade approximant.
LUMPED interleaving of several M3PP(2, m), and the two fitters built on it (matlab/lib/m3a/m3a/m3pp/m...
LINE Agent Language (LAL): shared types and numerical helpers of the SolverMAM LAL paths (python/line...
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Compression of a marked MAP into a smaller representation, and the two M3A primitives it is built fro...
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
Marked MAP statistics: embedded chains, class-transition probabilities, forward and cross moments,...
std::vector< Matrix< double > > MarkedMatrices
A marked process as Python's list [D0, D1, D1_1, ..., D1_K].
std::pair< std::string, std::string > Endpoint
(agent, action).
TrafficFit fit_traffic(const Traffic &traffic, const std::optional< MarkedMatrices > &original, const std::string &method, const std::string &compress_method, double fit_time, double fit_tolerance, const TrafficFitBackend &backend=TrafficFitBackend())
Fit offered marked streams and enforce a finite-time counting budget (fit_traffic).
std::optional< Traffic > offered_traffic(const Model &snapshot, const std::string &level_name, bool materialize=true)
Exact superposed offered MMAP and mark provenance, or nullopt (offered_traffic).
bool in(const std::string &s, std::initializer_list< const char * > set)
Mmap< T > mmap_normalize(const Mmap< T > &in)
Clamp negative off-diagonal and per-class entries to zero and rebuild D1 and the diagonal of D0 from ...
MmapCompressMethod
The compression methods of mmap_compress.m.
Mmap< T > m3pp2m_interleave(const std::vector< Mmap< T > > &parts)
Interleave L M3PP(2, m_i) into one M3PP of order L + 1 whose class list is the concatenation of their...
bool mmap_isfeasible_tol(const Mmap< T > &m, const T &tol)
Feasibility of a marked MAP WITHIN A TOLERANCE, the semantics of matlab/lib/m3a/m3a/mmap/mmap_isfeasi...
Mmap< T > mmap_compress(const Mmap< T > &in, MmapCompressMethod method)
Compress an MMAP (mmap_compress.m).
Mmap< T > mmap_super(const Mmap< T > &a, const Mmap< T > &b)
Superposition of two MMAPs: the phase process is the product chain, and the class list of the result ...
std::vector< T > mmap_pc(const Mmap< T > &m)
Class probabilities seen by an arriving job, pc = pie (-D0)^-1 D1^(c) e.
T map_lambda(const Map< T > &m)
Stationary arrival rate, lambda = pi D1 e.
Mmap< T > m3pp2m_fitc_theoretical(const Mmap< T > &mm, const std::string &method, const T &t, const T &tinf)
Fit the counting characteristics of a GIVEN MMAP with an M3PP(2, m).
Conservation laws of a layered queueing network, enumerated from its structure.
Matrix< T > eye(std::size_t n)
Identity of order n.
Matrix< T > expm(const Matrix< T > &A)
Matrix exponential exp(A).
The immutable agent record (core.Agent).
std::vector< Transition > transitions
std::vector< std::string > states
std::size_t state_index(const std::string &s) const
Zero-based index of a local state, or npos.
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
std::vector< MinSync > min_syncs
std::vector< Sync > syncs
std::vector< AgentRecord > agents
const AgentRecord & agent(const std::string &name) const
An ordinary synchronisation: one active endpoint, hand passives and injected node arrivals.
std::vector< Endpoint > passive
Replaceable numerical kernels of fit_traffic, so a test can intercept them as the Python tests monkey...
std::function< MarkedMatrices(const MarkedMatrices &, const std::string &, double, double)> m3pp_fit
std::function< MarkedMatrices(const MarkedMatrices &, const std::string &)> compress
Matrix< double > before_cov
Matrix< double > after_cov
std::vector< double > before_rate
std::vector< double > after_rate
The traffic dictionary of a MAM result (result.traffic).
std::vector< std::string > marks
std::optional< MarkedMatrices > matrices
std::vector< std::string > targets
std::vector< std::string > sources
std::optional< std::string > blocking
std::vector< MarkedMatrices > streams
One labelled local transition source --(action, value)--> target.
An MMAP: the underlying MAP plus the per-class arrival matrices.