LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
lang_types.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_LANG_LANG_TYPES_H
6#define LINE_LANG_LANG_TYPES_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * Enumerations and the minimal distribution descriptor shared by the model
12 * layer of the C++ port.
13 *
14 * The numeric values are the MATLAB ones (matlab/src/lang/constant), not a
15 * fresh numbering, because they cross the JSON boundary and appear in the
16 * dumps used as parity oracles. _kb/11 records that MATLAB and Python disagree
17 * on ProcessType numbering (MATLAB starts at EXP=0, Python at EXP=1); this port
18 * follows MATLAB, the reference implementation, so a numeric comparison against
19 * a MATLAB dump is meaningful and one against a Python dump is not -- compare
20 * by name there.
21 *
22 * SCOPE: the model layer added here exists to run SolverLN over a layered
23 * queueing network whose layers are solved by SolverMVA. It carries the
24 * scheduling disciplines, node kinds and precedence types that path reaches
25 * and REFUSES the rest by name rather than silently mapping them onto a
26 * neighbour, because a discipline that is silently treated as FCFS returns a
27 * plausible number that is wrong.
28 */
29
30#include <algorithm>
31#include <cmath>
32#include <cstddef>
33#include <functional>
34#include <limits>
35#include <memory>
36#include <string>
37#include <vector>
38
41#include "line/lang/nnpp.h"
42#include "line/num/number.h"
43#include "line/util/error.h"
44#include "line/util/lu.h"
45#include "line/util/matrix.h"
46
47namespace line {
48namespace lang {
49
50/** Solver output metrics, with the numeric values of MATLAB `MetricType`. */
51enum class MetricType {
52 ResidT = 0,
53 RespT = 1,
55 QLen = 3,
56 QueueT = 4,
59 FJQLen = 7,
62 SysQLen = 10,
64 SysTput = 12,
65 Tput = 13,
66 ArvR = 14,
68 Util = 16,
73 Tard = 21,
74 SysTard = 22
75};
76
77/** Port of `MetricType.toText`. */
78inline const char* metric_to_text(MetricType metric) {
79 switch (metric) {
80 case MetricType::ResidT: return "Residence Time";
81 case MetricType::RespT: return "Response Time";
82 case MetricType::DropRate: return "Drop Rate";
83 case MetricType::QLen: return "Number of Customers";
84 case MetricType::QueueT: return "Queue Time";
85 case MetricType::FCRWeight: return "FCR Total Weight";
86 case MetricType::FCRMemOcc: return "FCR Memory Occupation";
87 case MetricType::FJQLen: return "Fork Join Number of Customers";
88 case MetricType::FJRespT: return "Fork Join Response Time";
89 case MetricType::RespTSink: return "Response Time per Sink";
90 case MetricType::SysQLen: return "System Number of Customers";
91 case MetricType::SysRespT: return "System Response Time";
92 case MetricType::SysTput: return "System Throughput";
93 case MetricType::Tput: return "Throughput";
94 case MetricType::ArvR: return "Arrival Rate";
95 case MetricType::TputSink: return "Throughput per Sink";
96 case MetricType::Util: return "Utilization";
97 case MetricType::TranQLen: return "Tran Number of Customers";
98 case MetricType::TranUtil: return "Tran Utilization";
99 case MetricType::TranTput: return "Tran Throughput";
100 case MetricType::TranRespT: return "Tran Response Time";
101 case MetricType::Tard: return "Tardiness";
102 case MetricType::SysTard: return "System Tardiness";
103 default: return "Unknown Metric";
104 }
105}
106
107/**
108 * The events a state can undergo, with the values of MATLAB EventType.
109 *
110 * An event is ACTIVE at the node that schedules it and PASSIVE at the node
111 * that receives it: a DEP at one station is the ARV at the next, and only the
112 * active half carries a rate. The passive half is marked with a rate of -1,
113 * which the generator assembly replaces with the active rate -- a convention
114 * that only reads as a sentinel because a rate can never be negative.
115 */
116enum class EventType {
117 INIT = -1, ///< the model is initialized, t = 0
118 LOCAL = 0, ///< dummy event, no state change outside the node
119 ARV = 1, ///< a job arrives
120 DEP = 2, ///< a job departs
121 PHASE = 3, ///< service advances a phase WITHOUT departing
122 READ = 4, ///< a cache item is read
123 STAGE = 5, ///< a random environment changes stage
124 ENABLE = 6, ///< an SPN mode becomes enabled
125 FIRE = 7, ///< an SPN mode fires
126 PRE = 8, ///< consume from a place or queue buffer, no server effect
127 POST = 9, ///< produce to a place or queue buffer
128 RENEGE = 10, ///< a waiting job abandons the queue (impatience)
129 RETRY = 11, ///< an orbiting job retries entry at a retrial station
130 SWITCH = 12, ///< a polling server advances its switchover timer
131 FAILURE = 13, ///< the server breaks down, going from up to down
132 REPAIR = 14, ///< the server is repaired, going from down to up, resuming
133 ///< the held job, which is why it emits no START
134 START = 15, ///< a job begins or resumes holding a server
135 PREEMPT = 16, ///< a job holding a server is pushed back into the buffer
136 DROP = 17, ///< an arriving job is lost (full buffer or region, balking);
137 ///< emitted only by simulation event logs
138 SETUP = 18, ///< a station server's setup clock moves a phase or completes
139 ///< (Queue.setDelayOff), making the server ACTIVE
140 DELAYOFF = 19 ///< a station server's delay-off clock moves a phase or expires,
141 ///< turning the server OFF
142};
143// START and PREEMPT are instantaneous tags on the arc of the ARV or DEP that
144// causes them, never the active half of an sn.sync entry: no clock, no state,
145// no change to any numerical result. PREEMPT is spelled in full because PRE
146// already names the Petri-net pre-arc.
147
148inline const char* event_to_text(EventType e) {
149 switch (e) {
150 case EventType::ARV: return "ARV";
151 case EventType::DEP: return "DEP";
152 case EventType::PHASE: return "PHASE";
153 case EventType::READ: return "READ";
154 case EventType::LOCAL: return "LOCAL";
155 case EventType::STAGE: return "STAGE";
156 case EventType::ENABLE: return "ENABLE";
157 case EventType::FIRE: return "FIRE";
158 case EventType::PRE: return "PRE";
159 case EventType::POST: return "POST";
160 case EventType::RENEGE: return "RENEGE";
161 case EventType::RETRY: return "RETRY";
162 case EventType::SWITCH: return "SWITCH";
163 case EventType::FAILURE: return "FAILURE";
164 case EventType::REPAIR: return "REPAIR";
165 case EventType::START: return "START";
166 case EventType::PREEMPT: return "PREEMPT";
167 case EventType::SETUP: return "SETUP";
168 case EventType::DELAYOFF: return "DELAYOFF";
169 default: return "INIT";
170 }
171}
172
173/**
174 * G-network signal classes, with the values of MATLAB SignalType.
175 *
176 * A signal is not a job: it never joins a station, it acts on the jobs already
177 * there and is annihilated. REPLY is the odd one out -- it completes a
178 * synchronous call and then joins as an ordinary job.
179 */
180enum class SignalType {
181 REPLY = 0, ///< completes a synchronous call, releasing a held server
182 NEGATIVE = 1, ///< removes a batch of jobs (Gelenbe's negative customer)
183 CATASTROPHE = 2 ///< removes EVERY job at the station
184};
185
186/** Which job a negative signal removes, with the values of MATLAB RemovalPolicy. */
187enum class RemovalPolicy {
188 RANDOM = 0, ///< uniform over waiting AND in-service jobs
189 FCFS = 1, ///< the oldest waiting job; servers only once nobody waits
190 LCFS = 2 ///< the newest waiting job; servers only once nobody waits
191};
192
193/** Scheduling disciplines, with the values of MATLAB SchedStrategy. */
194enum class SchedStrategy {
195 INF = 0,
196 FCFS = 1,
197 LCFS = 2,
198 SIRO = 3,
199 SJF = 4,
200 LJF = 5,
201 PS = 6,
202 DPS = 7,
203 GPS = 8,
204 SEPT = 9,
205 LEPT = 10,
206 HOL = 11,
207 FORK = 12,
208 EXT = 13,
209 REF = 14,
210 LCFSPR = 15,
212 // The preemptive and priority families. PR resumes an interrupted job in
213 // the phase it held; PI restarts it from the entry phase, which is why the
214 // two cannot share an encoding: PR must carry the phase of EVERY preempted
215 // job, PI need not. FCFSPRIO is MATLAB's alias for HOL, so it is not a
216 // distinct enumerator here.
217 PSPRIO = 17,
220 LCFSPI = 20,
224 FCFSPR = 24,
225 FCFSPI = 25,
228 SRPT = 28,
230 EDD = 30,
231 EDF = 31,
232 LPS = 32,
233 PSJF = 33,
234 FB = 34,
235 LAS = 34, // Least Attained Service: an ALIAS of FB (same value), as SchedStrategy.LAS in MATLAB and Python
236 LRPT = 35,
237 SETF = 36,
238 FSP = 37,
239 PAS = 38,
240 OI = 39,
241 // Round robin with a finite time slice (quantum), Haverkort (1998), Sect. 6.4.
242 // Solved by this port's CTMC and SSA (rr_info.h, after_event_station_rr)
243 // and simulated by the native LDES engine (EV_QUANTUM in ldes_engine.h).
244 RR = 40,
245 NONE = -1
246};
247
248inline const char* sched_to_text(SchedStrategy s) {
249 switch (s) {
250 case SchedStrategy::INF: return "inf";
251 case SchedStrategy::FCFS: return "fcfs";
252 case SchedStrategy::LCFS: return "lcfs";
253 case SchedStrategy::SIRO: return "siro";
254 case SchedStrategy::SJF: return "sjf";
255 case SchedStrategy::LJF: return "ljf";
256 case SchedStrategy::PS: return "ps";
257 case SchedStrategy::DPS: return "dps";
258 case SchedStrategy::GPS: return "gps";
259 case SchedStrategy::SEPT: return "sept";
260 case SchedStrategy::LEPT: return "lept";
261 case SchedStrategy::HOL: return "hol";
262 case SchedStrategy::FORK: return "fork";
263 case SchedStrategy::EXT: return "ext";
264 case SchedStrategy::REF: return "ref";
265 case SchedStrategy::LCFSPR: return "lcfspr";
266 case SchedStrategy::POLLING: return "polling";
267 case SchedStrategy::SRPT: return "srpt";
268 case SchedStrategy::LPS: return "lps";
269 case SchedStrategy::PSJF: return "psjf";
270 case SchedStrategy::FB: return "fb";
271 case SchedStrategy::LRPT: return "lrpt";
272 case SchedStrategy::SETF: return "setf";
273 case SchedStrategy::FSP: return "fsp";
274 case SchedStrategy::PSPRIO: return "psprio";
275 case SchedStrategy::DPSPRIO: return "dpsprio";
276 case SchedStrategy::GPSPRIO: return "gpsprio";
277 case SchedStrategy::LCFSPI: return "lcfspi";
278 case SchedStrategy::LCFSPRIO: return "lcfsprio";
279 case SchedStrategy::LCFSPRPRIO: return "lcfsprprio";
280 case SchedStrategy::LCFSPIPRIO: return "lcfspiprio";
281 case SchedStrategy::FCFSPR: return "fcfspr";
282 case SchedStrategy::FCFSPI: return "fcfspi";
283 case SchedStrategy::FCFSPRPRIO: return "fcfsprprio";
284 case SchedStrategy::FCFSPIPRIO: return "fcfspiprio";
285 case SchedStrategy::SRPTPRIO: return "srptprio";
286 case SchedStrategy::EDD: return "edd";
287 case SchedStrategy::EDF: return "edf";
288 case SchedStrategy::PAS: return "pas";
289 case SchedStrategy::OI: return "oi";
290 case SchedStrategy::RR: return "rr";
291 default: return "none";
292 }
293}
294
295/** Parse the `scheduling` attribute of an .lqnx processor or task. */
296inline SchedStrategy sched_from_lqnx(const std::string& s) {
297 if (s == "inf" || s == "INF") return SchedStrategy::INF;
298 if (s == "fcfs" || s == "FCFS") return SchedStrategy::FCFS;
299 if (s == "ps" || s == "PS") return SchedStrategy::PS;
300 if (s == "ref" || s == "REF") return SchedStrategy::REF;
301 if (s == "hol" || s == "HOL") return SchedStrategy::HOL;
302 // lqns spells preemptive priority resume (SCHEDULE_PPR) "pri"; "pp" is the
303 // stale lqn-core.xsd spelling, absent from the lqns 6.2.31 sources. It is
304 // preemptive, so it is FCFSPRPRIO and not the non-preemptive HOL
305 if (s == "pri" || s == "PRI" || s == "pp") return SchedStrategy::FCFSPRPRIO;
306 if (s == "rand" || s == "siro") return SchedStrategy::SIRO;
307 if (s == "sjf") return SchedStrategy::SJF;
308 if (s == "ljf") return SchedStrategy::LJF;
309 if (s == "lcfs") return SchedStrategy::LCFS;
310 if (s == "burst" || s == "poll") return SchedStrategy::FCFS;
311 // lqns completely fair scheduling: SchedStrategy.fromText maps it to GPS; <group> shares are not read there either
312 if (s == "cfs" || s == "CFS") return SchedStrategy::GPS;
313 throw UnsupportedError(ErrorKind{"Import"}, "lqn reader: unsupported scheduling discipline '" + s + "'");
314}
315
316/**
317 * The `scheduling` attribute an .lqnx processor or task carries for a strategy.
318 *
319 * The inverse of sched_from_lqnx over the disciplines the schema spells, and a
320 * refusal by name for every other one. It refuses rather than falling back on
321 * fcfs because the file is handed to an external solver: a task written as fcfs
322 * when the model says lcfspr is answered, not rejected, and the discipline
323 * would be lost inside a number that looks ordinary.
324 */
325inline std::string sched_to_lqnx(SchedStrategy s) {
326 switch (s) {
327 case SchedStrategy::INF: return "inf";
328 case SchedStrategy::FCFS: return "fcfs";
329 case SchedStrategy::PS: return "ps";
330 case SchedStrategy::REF: return "ref";
331 case SchedStrategy::HOL: return "hol";
332 case SchedStrategy::FCFSPRPRIO: return "pri";
333 case SchedStrategy::SIRO: return "rand";
334 case SchedStrategy::SJF: return "sjf";
335 case SchedStrategy::LJF: return "ljf";
336 case SchedStrategy::LCFS: return "lcfs";
337 default:
338 throw UnsupportedError(ErrorKind{"Export"},
339 std::string("the LQN XML schema has no spelling for scheduling discipline '") +
340 sched_to_text(s) + "'; it carries inf, fcfs, ps, ref, hol, pri, rand, sjf, ljf and lcfs");
341 }
342}
343
344/** Node kinds, with the values of MATLAB NodeType. */
345enum class NodeType {
346 Queue = 0,
348 Delay = 2,
351 Cache = 5,
353 Fork = 7,
354 Place = 8,
356 Region = 10,
357 Join = 11,
358 Sink = 12
359};
360
361/** Name of a node kind, for diagnostics. The JSON spelling lives in the writer. */
362inline const char* node_type_to_text(NodeType t) {
363 switch (t) {
364 case NodeType::Queue: return "Queue";
365 case NodeType::Source: return "Source";
366 case NodeType::Delay: return "Delay";
367 case NodeType::ClassSwitch: return "ClassSwitch";
368 case NodeType::Logger: return "Logger";
369 case NodeType::Cache: return "Cache";
370 case NodeType::Router: return "Router";
371 case NodeType::Fork: return "Fork";
372 case NodeType::Place: return "Place";
373 case NodeType::Transition: return "Transition";
374 case NodeType::Region: return "Region";
375 case NodeType::Join: return "Join";
376 case NodeType::Sink: return "Sink";
377 }
378 return "Unknown";
379}
380
381/** SPN transition timing, with the values of MATLAB TimingStrategy. */
382enum class TimingStrategy {
383 TIMED = 0, ///< fires after its firing distribution elapses
384 IMMEDIATE = 1 ///< fires with zero delay, resolved by weight and priority
385};
386
387/** Job class kinds, with the values of MATLAB JobClassType. */
388enum class JobClassType { OPEN = 0, CLOSED = 1 };
389
390/** Polling service disciplines, with the values of MATLAB PollingType. */
391enum class PollingType {
392 GATED = 0, ///< serve exactly the jobs present at the polling instant
393 EXHAUSTIVE = 1, ///< serve until the queue empties
394 KLIMITED = 2, ///< serve at most K per visit (K in pollingPar)
395 DECREMENTING = 3, ///< serve until the queue is one shorter than at arrival
396 GLIMITED = 4 ///< serve at most K of the jobs present at the polling instant
397};
398
399/**
400 * Visit-order rules of a polling server, with the values of MATLAB
401 * PollingOrder. CYCLIC walks the ring (or the polling table); the others are
402 * load-dependent and choose the next buffer when a visit ends.
403 */
404enum class PollingOrder {
405 CYCLIC = 0, ///< fixed cyclic order (or the polling table)
406 SKIPEMPTY = 1, ///< next non-empty buffer in cyclic order
407 LQF = 2, ///< longest buffer first, ties to the cyclic successor
408 THRESHOLD = 3 ///< a priority buffer above its threshold, else SKIPEMPTY
409};
410
411/** Visit-timer scopes of a polling server, with the values of MATLAB PollingTimer. */
412enum class PollingTimer {
413 NONE = 0, ///< no visit timer
414 LOCAL = 1, ///< a timer per visit, drawn at the polling instant
415 GLOBAL = 2 ///< a timed token: per-class target rotation timers
416};
417
418/** Cache replacement policies, with the values of MATLAB ReplacementStrategy. */
420 RR = 0, ///< random replacement
421 FIFO = 1, ///< first in, first out
422 SFIFO = 2, ///< strict FIFO
423 LRU = 3, ///< least recently used
424 HLRU = 4, ///< h-LRU / LRU(m): h lists, promote i -> i+1 on a hit
425 CLIMB = 5, ///< move up one position on a hit (transposition rule)
426 QLRU = 6 ///< q-LRU: LRU with probabilistic admission on a miss
427};
428
429/** Routing strategies, with the values of MATLAB RoutingStrategy. */
430enum class RoutingStrategy {
431 RAND = 0,
432 PROB = 1,
435 JSQ = 4,
437 SQ = 6,
438 /** Krzesinski (1987) product-form state-dependent routing. */
439 SDR = 7,
441};
442
443inline const char* routing_to_text(RoutingStrategy r) {
444 switch (r) {
445 case RoutingStrategy::RAND: return "rand";
446 case RoutingStrategy::PROB: return "prob";
447 case RoutingStrategy::RROBIN: return "rrobin";
448 case RoutingStrategy::WRROBIN: return "wrrobin";
449 case RoutingStrategy::JSQ: return "jsq";
450 case RoutingStrategy::FIRING: return "firing";
451 case RoutingStrategy::SQ: return "sq";
452 case RoutingStrategy::SDR: return "sdr";
453 default: return "disabled";
454 }
455}
456
457/**
458 * Blocking and loss rules, with the values of MATLAB DropStrategy.
459 *
460 * WAITQ is -1 and is also the marker `refreshCapacity` writes where the rule is
461 * never consulted (an unbounded station, or a closed class), so it means two
462 * different things depending on the station's capacity; see the comment in
463 * refresh_capacity().
464 */
465enum class DropStrategy {
466 WAITQ = -1,
467 DROP = 1,
468 BAS = 2,
469 BBS = 3,
470 RSRD = 4,
473};
474
475/**
476 * Impatience kinds, with the values of MATLAB ImpatienceType.
477 *
478 * RENEGING is a timer a job started at a queue; BALKING is a decision taken
479 * BEFORE joining, on the state of the queue, and is parameterized by
480 * `Station::balking` rather than by a distribution; RETRIAL sends the job to an
481 * orbit and is parameterized by `RetrialParam`.
482 */
483enum class ImpatienceType { NONE = 0, RENEGING = 1, BALKING = 2, RETRIAL = 3 };
484
485/** Balking rules, with the values of MATLAB BalkingStrategy. */
486enum class BalkingStrategy { NONE = 0, QUEUE_LENGTH = 1, EXPECTED_WAIT = 2, COMBINED = 3 };
487
488/**
489 * How a heterogeneous station picks among its server types, MATLAB
490 * HeteroSchedPolicy. ORDER is the default: the declared order of the types.
491 */
492enum class HeteroSchedPolicy { ORDER = 0, ALIS = 1, ALFS = 2, FAIRNESS = 3, FSF = 4, RAIS = 5 };
493
494/**
495 * When a Place releases a served token, MATLAB DepartureDiscipline. NORMAL is
496 * the standard queueing-Petri-net rule (available on completion); FIFO holds
497 * it until every earlier arrival to the depository has been released.
498 */
499enum class DepartureDiscipline { NORMAL = 0, FIFO = 1 };
500
501/** Join rules, with the values of MATLAB JoinStrategy. */
502enum class JoinStrategy { STD = 1, PARTIAL = 2 };
503
504/** LQN element kinds, with the values of MATLAB LayeredNetworkElement. */
505enum class LqnElement { HOST = 0, TASK = 1, ENTRY = 2, ACTIVITY = 3, CALL = 4 };
506
507/** Call kinds, with the values of MATLAB CallType. */
508enum class CallType { NONE = 0, SYNC = 1, ASYNC = 2, FWD = 3 };
509
510/** Activity precedence kinds, with the values of MATLAB ActivityPrecedenceType. */
522
523/** Distribution kinds, with the values of MATLAB ProcessType. */
524enum class ProcessType {
525 EXP = 0,
527 HYPEREXP = 2,
528 PH = 3,
529 APH = 4,
530 MAP = 5,
532 DET = 7,
534 GAMMA = 9,
535 PARETO = 10,
536 MMPP2 = 11,
540 COX2 = 15,
545 /**
546 * A `Prior`: a weighted set of ALTERNATIVE distributions, or a density over
547 * a scalar parameter plus a factory from it. It is not a mixture -- each
548 * alternative is a separate model realization -- and only SolverUQ consumes
549 * it; every other solver refuses it through Feature::Prior.
550 */
551 PRIOR = 20,
555 BMAP = 24,
556 ME = 25,
557 RAP = 26,
559 ZIPF = 28,
560 DMAP = 29,
561 MMAP = 31,
563 /**
564 * The time-INHOMOGENEOUS families of Ko and Pender (ORL 45, 2017): an
565 * NHPP is a rate schedule lambda(t), a MAPt a (D0(t), D1(t)) schedule and a
566 * PHt an (alpha(t), S(t)) one, all piecewise constant on one breakpoint
567 * vector and optionally cyclic. The numeric values are MATLAB's
568 * (`ProcessType.m:41-43`).
569 *
570 * THEY CARRY A NOMINAL PAIR TOO. `Distrib::D0`/`D1` hold the width-weighted
571 * time average of the schedule, which is what `sn_schedule_nominal` returns
572 * as its first two outputs and what every consumer that has no notion of
573 * time -- the phase count, the rate, the fluid layout -- reads. The schedule
574 * itself lives in `sched_bp`/`sched_D0`/`sched_D1` beside it, and only a
575 * solver that integrates in time looks at it.
576 */
577 NHPP = 33,
578 MAPT = 34,
579 PHT = 35,
580 /**
581 * The MARKED families, MATLAB's `ProcessType.m:36-38`. A mark is a label
582 * carried by an event, and at a Source it selects the class of the arriving
583 * job (`Source.setMarkedArrival`, `sn.markidx`, `marked_classes`).
584 *
585 * MPH is the RENEWAL special case of MMAP: a PH with K marked exits,
586 * lowered by D0 = S and D1k = s_k*alpha. MMAPT is MMAP with a
587 * piecewise-constant matrix schedule, carried in `sched_Dmark` beside
588 * `sched_D0`/`sched_D1`. MPHT is the same lowering applied segment by
589 * segment, so it is STORED CONVERTED to MMAPT form exactly as a PHt is
590 * stored as its equivalent MAPt pair, and the marked schedule walk serves
591 * both.
592 *
593 * MPH keeps an id of its own rather than aliasing MMAP, so a solver that
594 * cannot honour a marked renewal process refuses it explicitly instead of
595 * inheriting MMAP's support. Every `procid == MMAP` test that should also
596 * accept a marked renewal process is therefore a MEMBERSHIP test.
597 */
598 MPH = 36,
599 MMAPT = 37,
600 MPHT = 38,
601 /**
602 * BMMAPT crosses the BATCH axis with the two above: a block is indexed by
603 * segment, mark and batch size, carried in `sched_Dbatch` beside
604 * `sched_Dmark`, and one epoch releases a batch of jobs that all carry the
605 * same mark. It reduces to MMAPT when every batch size is 1 and to BMAP
606 * when the schedule is flat.
607 *
608 * Like MPH it keeps an id of its own so a solver that cannot release
609 * batches refuses it by name instead of inheriting MMAPT's support, and
610 * every `procid == BMAP` test that should serve every batch family is
611 * therefore a MEMBERSHIP test, `process_is_batch`.
612 */
613 BMMAPT = 39,
614 /**
615 * Three reliability laws of Trivedi and Bobbio, "Reliability and
616 * Availability Engineering" (2017), Sec. 3.2: the log-logistic (Fisk) law,
617 * an atom at zero mixed with any law, and a mass at infinity mixed with
618 * any law. The values are MATLAB `ProcessType.m`'s. The two wrappers carry
619 * the law they wrap in `Distrib::inner`; a Defective has an infinite mean,
620 * so it is a lifetime law only and no Network accepts it.
621 */
625 /**
626 * A nonstationary non-Poisson arrival process (thinning + SCIATA): a rate
627 * function lambda(t) on [0, S] and a dispersion ratio C, generated by
628 * thinning a Weibull equilibrium renewal process inverted through a
629 * piecewise-constant majorizer (`line/lang/nnpp.h`). MATLAB's value. The law
630 * itself is carried in `Distrib::nnpp`; `D0`/`D1` hold the Poisson nominal at
631 * the time-average rate, as an NHPP's do. Only SolverLDES simulates it.
632 */
633 NNPP = 43,
634 /**
635 * A Gaussian, and the ONE family whose value is not MATLAB's, because
636 * MATLAB has none to copy: `ProcessType.m` stops at 35 and `Normal.m` is a
637 * `ContinuousDistribution` with no id at all, exactly as `Normal.java` and
638 * the python `Normal` have none. That is not an oversight in the reference
639 * -- a Gaussian has mass below zero, so it can never be a service or
640 * interarrival process and can never appear in `sn.proc`. It reaches this
641 * port only as the PARAMETER density of a continuous `Prior`, where it is
642 * read through `dist_cdf` and `dist_quantile` and never through
643 * `dist_to_map`.
644 *
645 * The value is deliberately far outside the ids MATLAB assigns (0..38 as of
646 * the marked families) so that it can never collide with one added later; `sn.procid` must never carry it, and
647 * `dist_to_map` refuses it by name rather than handing back the Erlang fit
648 * its default arm would otherwise produce for a law with negative support.
649 */
650 NORMAL = 100,
651 NONE = -1
652};
653
654/** The MATLAB ProcessType name, as `sn.procid` prints it. */
655inline const char* process_to_text(ProcessType p) {
656 switch (p) {
657 case ProcessType::EXP: return "Exp";
658 case ProcessType::ERLANG: return "Erlang";
659 case ProcessType::HYPEREXP: return "HyperExp";
660 case ProcessType::PH: return "PH";
661 case ProcessType::APH: return "APH";
662 case ProcessType::MAP: return "MAP";
663 case ProcessType::UNIFORM: return "Uniform";
664 case ProcessType::DET: return "Det";
665 case ProcessType::COXIAN: return "Coxian";
666 case ProcessType::GAMMA: return "Gamma";
667 case ProcessType::PARETO: return "Pareto";
668 case ProcessType::MMPP2: return "MMPP2";
669 case ProcessType::REPLAYER: return "Replayer";
670 case ProcessType::IMMEDIATE: return "Immediate";
671 case ProcessType::DISABLED: return "Disabled";
672 case ProcessType::COX2: return "Cox2";
673 case ProcessType::WEIBULL: return "Weibull";
674 case ProcessType::LOGNORMAL: return "Lognormal";
675 case ProcessType::DUNIFORM: return "DiscreteUniform";
676 case ProcessType::BERNOULLI: return "Bernoulli";
677 case ProcessType::BINOMIAL: return "Binomial";
678 case ProcessType::POISSON: return "Poisson";
679 case ProcessType::GEOMETRIC: return "Geometric";
680 case ProcessType::BMAP: return "BMAP";
681 case ProcessType::ME: return "ME";
682 case ProcessType::RAP: return "RAP";
683 case ProcessType::DISCRETESAMPLER: return "DiscreteSampler";
684 case ProcessType::ZIPF: return "Zipf";
685 case ProcessType::DMAP: return "DMAP";
686 case ProcessType::MMAP: return "MMAP";
687 case ProcessType::EMPIRICALCDF: return "EmpiricalCDF";
688 case ProcessType::PRIOR: return "Prior";
689 case ProcessType::NHPP: return "NHPP";
690 case ProcessType::MAPT: return "MAPt";
691 case ProcessType::PHT: return "PHt";
692 case ProcessType::MPH: return "MPH";
693 case ProcessType::MMAPT: return "MMAPt";
694 case ProcessType::MPHT: return "MPHt";
695 case ProcessType::BMMAPT: return "BMMAPt";
696 case ProcessType::LOGLOGISTIC: return "LogLogistic";
697 case ProcessType::MASSATORIGIN: return "MassAtOrigin";
698 case ProcessType::DEFECTIVE: return "Defective";
699 case ProcessType::NNPP: return "NNPP";
700 case ProcessType::NORMAL: return "Normal";
701 default: return "none";
702 }
703}
704
705/**
706 * `ProcessType.isMarkovian`: true when `sn.proc` carries an exact matrix
707 * representation of the law, rather than the Erlang fit `convertToMAP` leaves
708 * there for the parameter-only families. ME and RAP count -- their
709 * representation is the matrix-exponential analogue, not a generator -- and the
710 * discrete families do not, so a solver reading `sn.proc` as the law must gate
711 * on this exactly as MATLAB `ProcessType.m` does.
712 */
714 switch (p) {
715 case ProcessType::EXP:
718 case ProcessType::PH:
719 case ProcessType::APH:
720 case ProcessType::MAP:
724 case ProcessType::ME:
725 case ProcessType::RAP:
729 case ProcessType::MPH:
732 case ProcessType::BMMAPT: return true;
733 default: return false;
734 }
735}
736
737/**
738 * True when the type carries PER-MARK arrival blocks, i.e. an event of this
739 * process is labelled and the label is meaningful to the model. At a Source the
740 * label selects the class of the arriving job (`marked_classes`, `sn.markidx`).
741 */
743 return p == ProcessType::MMAP || p == ProcessType::MPH;
744}
745
746/**
747 * True when `sn.proc` holds the MARKED SCHEDULE slot. MPHt is stored lowered to
748 * MMAPt form segment by segment, so one walk serves both, exactly as one MAPt
749 * walk serves MAPt and PHt.
750 */
754
755/**
756 * True when an EVENT of this process releases (or, as a service process, completes) a
757 * BATCH of jobs whose size the process itself carries in its blocks.
758 *
759 * The batch twin of `process_is_marked_stationary` and `process_is_marked_schedule`,
760 * and the same rule applies: a procid test that should serve every batch family is a
761 * MEMBERSHIP test, never equality with `ProcessType::BMAP`.
762 *
763 * Disjoint from `Station::arrival_batch`, which is a SEPARATE batch-size law bolted
764 * onto a renewal stream by `Source.setArrivalBatch`. A process that is batch already
765 * carries its own sizes, so the two are mutually exclusive by construction.
766 *
767 * BMMAPT is ALSO `process_is_marked_schedule`, and deliberately: a consumer gated on
768 * that predicate reads it as the MMAPt it aggregates down to, which is right for
769 * anything batch-blind and WRONG for anything that releases jobs.
770 */
772 return p == ProcessType::BMAP || p == ProcessType::BMMAPT;
773}
774
775/**
776 * True for every marked family. MPH is the renewal special case of MMAP and
777 * lowers to the same M3A cell (D0 = S, D1k = s_k*alpha), so a consumer reading
778 * that layout must gate on `process_is_marked_stationary` rather than on
779 * equality with `ProcessType::MMAP`.
780 */
784
785/**
786 * A class-dependent scaling map, `sn.cdscaling`.
787 *
788 * It takes the per-class population vector at one station and returns the
789 * per-class rate multipliers, which is the signature `pfqn_cdfun` consumes; the
790 * alias resolves to the same std::function type as `pfqn::CdScaling`, so a map
791 * built here is passed straight through to the api layer.
792 */
793template <class T>
794using CdScaling = std::function<std::vector<T>(const std::vector<T>&)>;
795
796/**
797 * A globally state-dependent scaling, `sn.gdscaling`.
798 *
799 * Unlike CdScaling it is declared on the NETWORK, not on a station: the argument
800 * is the FULL population matrix, given row-major as nstations rows of nclasses
801 * entries, and the result is either one scalar, one entry per station, or one
802 * entry per (station, class) in the same row-major order. This is the Whittle
803 * primitive -- a rate that reads the whole state -- and no per-station scaling
804 * can express it when one route holds several resources at once.
805 */
806template <class T>
807using GdScaling = std::function<std::vector<T>(const std::vector<T>&)>;
808
809// ---------------------------------------------------------------------------
810// Global constants
811// ---------------------------------------------------------------------------
812
813/**
814 * The MATLAB GlobalConstants, as reported by lineStart at its defaults.
815 *
816 * These are doubles on purpose even in the exact instantiation: they are
817 * tolerances and sentinels of the ALGORITHM, not quantities of the model, and
818 * `lineStart` prints exactly these values. Converting them through
819 * num_traits<T>::from_double keeps the exact backend reproducing the same
820 * branch decisions as the reference rather than a mathematically cleaner set.
821 */
823 static constexpr double FineTol = 1e-8;
824 static constexpr double CoarseTol = 1e-3;
825 static constexpr double Zero = 1e-14;
826 /** Below this an off-diagonal entry is NO ARC of the phase / state graph. */
827 static constexpr double ArcTol = 1e-12;
828 /** Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8. */
829 static constexpr double Immediate = 1e8;
830 /**
831 * Stand-in for an unbounded COUNT, MATLAB `GlobalConstants.MaxInt`. Used
832 * where a state row must hold a server count and Inf is not a count.
833 */
834 static constexpr double MaxInt = 2147483647.0;
835};
836
837// ---------------------------------------------------------------------------
838// Distribution descriptor
839// ---------------------------------------------------------------------------
840
841/**
842 * A LINE Distribution, as the model layer and `sn` carry it.
843 *
844 * WHAT EACH CONSUMER READS, which is why all of it is here:
845 * sn.rates, sn.scv the first two moments -- every AMVA path
846 * sn.procid the type tag -- the qsys and QNA dispatch
847 * sn.proc, sn.pie the (D0,D1) pair -- QNA, RQNA, cache, polling
848 * sn.mu, sn.phi the phase rates and completion probabilities
849 * sn.phases the order of that representation
850 * sn.lst the Laplace-Stieltjes transform -- M/G/1 analyzers
851 *
852 * `params` holds the constructor arguments in MATLAB's getParam order, so a
853 * dump can be compared parameter by parameter rather than through the moments,
854 * which two different distributions can share.
855 *
856 * Two values are special and must not be confused, because they enter the
857 * struct as opposite extremes:
858 * Immediate mean = 1/GlobalConstants.Immediate = 1e-8, rate = 1e8
859 * Disabled rate = NaN, which marks a (station, class) pair the class never
860 * visits; the chain and visit machinery keys on it.
861 *
862 * ARITHMETIC. The Markovian families are rational in their parameters and are
863 * built exactly. Gamma, Weibull and Lognormal are not -- their moments call
864 * tgamma or exp -- so their factories refuse by name under exact arithmetic
865 * rather than returning a rounded rational that would look exact.
866 */
867template <class T>
868struct PriorSpec;
869
870template <class T>
871struct Distrib;
872template <class T>
874
875template <class T>
876struct Distrib {
878 /**
879 * The law as DECLARED, when this one is a surrogate fitted over it.
880 *
881 * `sn_nonmarkov_toph` installs a fitted (D0,D1) over a Gamma or a Lognormal
882 * and retags `type` PH or ME, after which nothing names or evaluates the law
883 * the user wrote. MMAP[K]/G[K]/1 reads that law's TRANSFORM rather than the
884 * fit, so it needs the original; every other consumer wants the surrogate
885 * and reads this struct as before. Null when no substitution has happened.
886 * A POINTER, and shared, for the reason `prior` below is one: an inline
887 * member would make the type self-embedding.
888 */
889 std::shared_ptr<Distrib<T>> declared;
892 bool disabled = true;
893 /** Constructor arguments, in MATLAB getParam order. */
894 std::vector<T> params;
895 /** Replayer / Trace samples; empty for every other type. */
896 std::vector<T> trace;
897 /**
898 * The trace FILE a Replayer was read from, when there was one.
899 *
900 * The samples above are what every solver in this port uses, so the path is
901 * carried only for the exporters: `saveServiceStrategy` hands JMT a
902 * `ReplayerPar` naming a file, and a Replayer exported without it is a JMT
903 * model that reads nothing. Empty when the samples were supplied directly.
904 * `network_writer.h` emits it for the same reason: the samples have no wire
905 * form, so without the path a Replayer is written back as the moments and
906 * reloads as a different law.
907 */
908 std::string trace_file;
909 /** Built by cox2(mu1, mu2, phi1), MATLAB's 3-argument `Coxian(mu1, mu2, phi1)`; read only by the code generators. */
910 bool cox_scalar_form = false;
911 /**
912 * The (D0,D1) pair when the type carries one directly.
913 *
914 * EMPTY for Det, Uniform, Pareto, Gamma, Weibull, Lognormal and Replayer:
915 * MATLAB's getProcess returns their raw PARAMETERS there, and
916 * refreshProcessRepresentations replaces them with an Erlang approximation
917 * (`convertToMAP`) on the way into sn.proc. That conversion is a property
918 * of the refresh, not of the distribution, so it is not done here; see
919 * dist_to_map() in lang/distribution.h.
920 */
922 /**
923 * MMAP per-class D1 blocks / BMAP per-batch-size blocks; empty otherwise.
924 *
925 * OVERLOADED, and the type says which reading applies. For a BMMAPt it carries
926 * the MARK reading -- the width-weighted, BATCH-AGGREGATED per-mark averages --
927 * because that is what `mam::mmap_lambda` is asked for when the engine reports
928 * per-mark source throughputs. Its batch nominal is derived from `sched_Dbatch`
929 * instead, so the two axes never contend for this one field.
930 */
931 std::vector<Matrix<T>> Dmark;
932 /**
933 * The alternatives of a `Prior`, set only when `type == PRIOR`.
934 *
935 * A POINTER, and shared: `PriorSpec` holds `Distrib<T>` values, so an
936 * inline member would make the type self-embedding, and the spec is
937 * immutable once built, so copying a service table copies a pointer rather
938 * than a design. `mean` and `scv` beside it are the MIXTURE moments, as
939 * MATLAB's `Prior.getMean`/`getSCV` return: a Prior that reaches
940 * `refresh_rates` therefore lowers to a rate rather than to a NaN. That is
941 * for honesty of the struct dump only -- the featset gate refuses the model
942 * before any solver reads those rates, and `dist_to_map`, `dist_lst` and
943 * `dist_moment` refuse a Prior by name.
944 */
945 std::shared_ptr<PriorSpec<T>> prior;
946 /**
947 * The wrapped law of a MassAtOrigin or a Defective, null otherwise. Its
948 * probability (p0 or pInf) is `params[0]`, MATLAB getParam(1). A pointer
949 * for the reason `declared` is one.
950 */
951 std::shared_ptr<Distrib<T>> inner;
952 /**
953 * The NNPP law, set only when `type == NNPP`, null otherwise. It is the C++
954 * form of MATLAB's `sn.proc{i}{r} = {majBreakpoints, majRates, cyclic,
955 * dispersion, kind, params, horizon}`: `majorizer_breakpoints()`,
956 * `majorizer_rates()`, `is_cyclic()`, `dispersion()`, `kind()`, `params()`
957 * and `horizon()` return those seven entries in that order. Immutable and
958 * shared, so copying a service table copies a pointer.
959 */
960 std::shared_ptr<const Nnpp> nnpp;
961 bool is_prior() const { return type == ProcessType::PRIOR; }
962
963 /**
964 * `sn.proc{i}{r} = {breakpoints, A, B, cyclic}` of a MAPt / PHt / NHPP.
965 *
966 * `sched_bp` has one more entry than there are segments -- it is the
967 * BOUNDARY vector, so segment k is in force on [bp(k), bp(k+1)) -- and
968 * `sched_D0[k]`, `sched_D1[k]` are the pair of segment k, ALREADY in MAP
969 * form. A PHt is stored converted, D0 = S and D1 = (-S e) alpha, because
970 * `sn_schedule_nominal` converts it on every read and keeping the raw
971 * (alpha, S) here would make every consumer repeat that conversion and one
972 * of them eventually forget. The raw form is not needed: the conversion is
973 * lossless and nothing downstream asks for alpha again.
974 *
975 * EMPTY FOR EVERY OTHER TYPE. `has_schedule()` is the test, and a solver
976 * with no notion of time simply never calls it -- the nominal pair in
977 * `D0`/`D1` is a complete, time-averaged answer for such a solver.
978 */
979 std::vector<T> sched_bp;
980 std::vector<Matrix<T>> sched_D0, sched_D1;
981 /**
982 * The MARKED schedule, `sched_Dmark[c][k]` being the block of mark c+1 in segment k.
983 * Empty for an unmarked schedule. `sched_D1[k]` stays the per-segment AGGREGATE
984 * sum_c sched_Dmark[c][k], so every consumer that ignores marks reads the same
985 * unmarked schedule it always did; this is the schedule twin of `Dmark` beside `D1`.
986 */
987 std::vector<std::vector<Matrix<T>>> sched_Dmark;
988 /**
989 * The BATCH marked schedule, `sched_Dbatch[c][b][k]` being the block that, in
990 * segment k, releases a batch of b+1 jobs all carrying mark c+1. Empty for every
991 * family but BMMAPt.
992 *
993 * The two derived levels stay populated beside it and are what keeps every
994 * existing consumer working: `sched_Dmark[c][k]` is the batch-aggregated
995 * sum_b sched_Dbatch[c][b][k], and `sched_D1[k]` the aggregate over marks as
996 * well. So a consumer that ignores batches reads the MMAPt this hides down to,
997 * and one that ignores marks too reads the MAPt. Only a consumer that actually
998 * RELEASES jobs has to look here; `has_batch_schedule()` is the test.
999 *
1000 * The batch axis is DENSE in b = 1..B, as BMAP's blocks are, so an unused batch
1001 * size is a zero block rather than a gap.
1002 */
1003 std::vector<std::vector<std::vector<Matrix<T>>>> sched_Dbatch;
1004 bool sched_cyclic = false;
1005 bool has_schedule() const { return !sched_D0.empty(); }
1006 bool has_marked_schedule() const { return !sched_Dmark.empty(); }
1007 bool has_batch_schedule() const { return !sched_Dbatch.empty(); }
1008 /** Largest batch size the schedule declares, or 1 when it carries no batch axis. */
1009 std::size_t max_batch_size() const {
1010 return sched_Dbatch.empty() ? std::size_t(1) : sched_Dbatch[0].size();
1011 }
1012
1013 static Distrib exp_mean(const T& m) {
1014 const T one = num_traits<T>::from_int(1);
1015 Distrib d;
1017 d.mean = m;
1018 d.scv = one;
1019 d.disabled = false;
1020 const T lambda = m > num_traits<T>::from_int(0) ? T(one / m)
1023 d.params.push_back(lambda);
1024 d.D0 = Matrix<T>(1, 1, T(-lambda));
1025 d.D1 = Matrix<T>(1, 1, lambda);
1026 return d;
1027 }
1028 static Distrib exp_rate(const T& r) {
1029 const T zero = num_traits<T>::from_int(0);
1030 if (r <= zero) {
1031 // Exp.fitRate(0) rationale: see _kb/04-networkstruct.md (cpp port notes)
1033 }
1034 return exp_mean(T(num_traits<T>::from_int(1) / r));
1035 }
1036 /**
1037 * The point mass at zero.
1038 *
1039 * The Immediate singleton. Its MEAN is zero and its RATE is 1e8, and the
1040 * two are deliberately not reciprocal: MATLAB's Immediate.getMean() returns
1041 * 0 while Immediate.getRate() returns GlobalConstants.Immediate, and both
1042 * are read, by different callers. SolverLN reads the mean (a task with an
1043 * Immediate think time contributes no think time); Network.refreshRates
1044 * reads the rate (the station serves the class in 1e-8 time units, not in
1045 * zero, which would be an infinite service rate the MVA recursion cannot
1046 * carry). Collapsing them onto 1/mean or 1/rate breaks one caller or the
1047 * other, so the type tag decides.
1048 *
1049 * Its SCV is 1, NOT the 0 of a degenerate distribution. The reference makes
1050 * this explicit -- `Immediate.getSCV` returns 1 in MATLAB, in the JAR and in
1051 * Python -- because Immediate is realised downstream as an exponential of
1052 * rate GlobalConstants.Immediate rather than as a Dirac: `rate()` below
1053 * returns 1e8, and the SCV has to be the one that goes with it. Declaring 0
1054 * here is invisible on a layer of PS or infinite-server stations, where the
1055 * AMVA correction does not read the SCV at all, and shows up only once a
1056 * layer holds an FCFS or multiserver station -- so it survives a model like
1057 * lqn_ofbiz and breaks a model like lqn_basic.
1058 */
1060 Distrib d;
1064 d.disabled = false;
1066 d.D0 = Matrix<T>(1, 1, T(-imm));
1067 d.D1 = Matrix<T>(1, 1, imm);
1068 return d;
1069 }
1070 static Distrib disabled_dist() { return Distrib(); }
1071 static Distrib det(const T& m) {
1072 Distrib d;
1074 d.mean = m;
1076 d.disabled = false;
1077 d.params.push_back(m);
1078 return d;
1079 }
1080
1081 // -----------------------------------------------------------------------
1082 // The Markovian families: (D0,D1) is built here, exactly
1083 // -----------------------------------------------------------------------
1084
1085 /** Erlang(alpha, r): r phases of rate alpha, as MATLAB's Erlang(phaseRate, nphases). */
1086 static Distrib erlang(const T& phase_rate, std::size_t r) {
1087 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1088 if (r == 0) throw InputError("Erlang: the number of phases must be positive");
1089 if (!(phase_rate > zero)) throw InputError("Erlang: the phase rate must be positive");
1090 Distrib d;
1092 d.disabled = false;
1093 d.params.push_back(phase_rate);
1094 d.params.push_back(num_traits<T>::from_int(static_cast<long>(r)));
1095 d.mean = T(num_traits<T>::from_int(static_cast<long>(r)) / phase_rate);
1096 d.scv = T(one / num_traits<T>::from_int(static_cast<long>(r)));
1097 d.D0 = Matrix<T>(r, r, zero);
1098 d.D1 = Matrix<T>(r, r, zero);
1099 for (std::size_t i = 0; i < r; ++i) {
1100 d.D0(i, i) = T(-phase_rate);
1101 if (i + 1 < r) d.D0(i, i + 1) = phase_rate;
1102 }
1103 d.D1(r - 1, 0) = phase_rate;
1104 return d;
1105 }
1106
1107 /**
1108 * Erlang fitted to a mean and an SCV, as MATLAB's Erlang.fitMeanAndSCV.
1109 *
1110 * AN SCV ABOVE ONE IS REFUSED, not answered. An Erlang of order r has
1111 * SCV = 1/r, so the family reaches 1 and no higher; ceil(1/c2) is 1 for
1112 * every c2 > 1, and returning that means handing back an EXPONENTIAL under
1113 * the name of the distribution the caller asked for. MATLAB errors here and
1114 * this port now does too, so a mis-specified SCV is a diagnostic rather
1115 * than a silently different service process.
1116 */
1117 static Distrib erlang_fit(const T& m, const T& c2) {
1118 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1119 if (!(c2 > zero)) throw InputError("Erlang.fitMeanAndSCV: the SCV must be positive");
1120 if (c2 > one)
1121 throw InputError(
1122 "Erlang.fitMeanAndSCV: the Erlang distribution requires a squared coefficient "
1123 "of variation <= 1; use HyperExp, Coxian or APH above 1");
1124 // MATLAB: r = ceil(1/scv); alpha = r/mean
1125 const double r_d = std::ceil(1.0 / num_traits<T>::to_double(c2));
1126 const std::size_t r = static_cast<std::size_t>(r_d < 1.0 ? 1.0 : r_d);
1127 return erlang(T(num_traits<T>::from_int(static_cast<long>(r)) / m), r);
1128 }
1129
1130 /**
1131 * The same for any number of branches, which is what MATLAB `HyperExp`
1132 * accepts and what the writers emit as vector `p` and `lambda`. The
1133 * two-branch entry point stays because it carries MATLAB's getParam order
1134 * (p, lambda1, lambda2), which a parameter-by-parameter dump compares
1135 * against.
1136 */
1137 static Distrib hyperexp_n(const std::vector<T>& p, const std::vector<T>& lambda) {
1138 const T zero = num_traits<T>::from_int(0), two = num_traits<T>::from_int(2);
1139 const std::size_t n = p.size();
1140 if (n == 0 || lambda.size() != n)
1141 throw InputError("HyperExp: p and lambda must be non-empty and of equal length");
1142 Distrib d;
1144 d.disabled = false;
1145 for (const T& v : p) d.params.push_back(v);
1146 for (const T& v : lambda) d.params.push_back(v);
1147 d.D0 = Matrix<T>(n, n, zero);
1148 d.D1 = Matrix<T>(n, n, zero);
1149 T m1 = zero, m2 = zero;
1150 for (std::size_t i = 0; i < n; ++i) {
1151 if (!(lambda[i] > zero)) throw InputError("HyperExp: the phase rates must be positive");
1152 d.D0(i, i) = T(-lambda[i]);
1153 for (std::size_t j = 0; j < n; ++j) d.D1(i, j) = T(lambda[i] * p[j]);
1154 m1 += T(p[i] / lambda[i]);
1155 m2 += T(two * p[i] / (lambda[i] * lambda[i]));
1156 }
1157 d.mean = m1;
1158 d.scv = T((m2 - m1 * m1) / (m1 * m1));
1159 return d;
1160 }
1161
1162 /**
1163 * HyperExp(p, lambda1, lambda2): phase i chosen with probability p_i.
1164 *
1165 * D1(i,j) = mu(i) p(j) -- the OUTER product. Associating the other way
1166 * gives D1(i,j) = mu(i) p(i) replicated across the row, whose rows no
1167 * longer sum with D0 to zero; _kb records that trap in the MATLAB class.
1168 */
1169 static Distrib hyperexp(const T& p, const T& lambda1, const T& lambda2) {
1170 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1171 if (!(lambda1 > zero) || !(lambda2 > zero))
1172 throw InputError("HyperExp: the phase rates must be positive");
1173 if (p < zero || p > one) throw InputError("HyperExp: p is not a probability");
1174 Distrib d;
1176 d.disabled = false;
1177 d.params.push_back(p);
1178 d.params.push_back(lambda1);
1179 d.params.push_back(lambda2);
1180 const T q = T(one - p);
1181 d.mean = T(p / lambda1 + q / lambda2);
1182 const T m2 = T(num_traits<T>::from_int(2) *
1183 (p / (lambda1 * lambda1) + q / (lambda2 * lambda2)));
1184 d.scv = T((m2 - d.mean * d.mean) / (d.mean * d.mean));
1185 d.D0 = Matrix<T>(2, 2, zero);
1186 d.D1 = Matrix<T>(2, 2, zero);
1187 d.D0(0, 0) = T(-lambda1);
1188 d.D0(1, 1) = T(-lambda2);
1189 d.D1(0, 0) = T(lambda1 * p);
1190 d.D1(0, 1) = T(lambda1 * q);
1191 d.D1(1, 0) = T(lambda2 * p);
1192 d.D1(1, 1) = T(lambda2 * q);
1193 return d;
1194 }
1195
1196 /**
1197 * Coxian(mu, phi): phase i completes with probability phi(i) and otherwise
1198 * moves to phase i+1. The last phase always completes.
1199 */
1200 static Distrib coxian(const std::vector<T>& mu, const std::vector<T>& phi) {
1201 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1202 const std::size_t n = mu.size();
1203 if (n == 0 || phi.size() != n)
1204 throw InputError("Coxian: mu and phi must be non-empty and of equal length");
1205 Distrib d;
1207 d.disabled = false;
1208 for (const T& v : mu) d.params.push_back(v);
1209 for (const T& v : phi) d.params.push_back(v);
1210 d.D0 = Matrix<T>(n, n, zero);
1211 d.D1 = Matrix<T>(n, n, zero);
1212 for (std::size_t i = 0; i < n; ++i) {
1213 if (!(mu[i] > zero)) throw InputError("Coxian: the phase rates must be positive");
1214 d.D0(i, i) = T(-mu[i]);
1215 if (i + 1 < n) d.D0(i, i + 1) = T(mu[i] * (one - phi[i]));
1216 d.D1(i, 0) = T(mu[i] * phi[i]);
1217 }
1218 // moments of the absorbing chain started in phase 1: m_k = k! e_1 (-D0)^-k e
1219 d.mean = ph_moment_from(d.D0, 1, 1);
1220 const T m2 = ph_moment_from(d.D0, 1, 2);
1221 d.scv = T((m2 - d.mean * d.mean) / (d.mean * d.mean));
1222 return d;
1223 }
1224
1225 /** Cox2(mu1, mu2, phi1), MATLAB's two-phase Coxian constructor. */
1226 static Distrib cox2(const T& mu1, const T& mu2, const T& phi1) {
1227 std::vector<T> mu, phi;
1228 mu.push_back(mu1);
1229 mu.push_back(mu2);
1230 phi.push_back(phi1);
1231 phi.push_back(num_traits<T>::from_int(1));
1232 Distrib d = coxian(mu, phi);
1233 d.cox_scalar_form = true;
1234 return d;
1235 }
1236
1237 /**
1238 * PH / APH given by (alpha, A): D0 = A and D1 = (-A e) alpha.
1239 *
1240 * `acyclic` selects the type tag only; the representation is the same, and
1241 * no consumer of sn.proc distinguishes them.
1242 */
1243 static Distrib phase_type(const std::vector<T>& alpha, const Matrix<T>& A, bool acyclic) {
1244 const T zero = num_traits<T>::from_int(0);
1245 const std::size_t n = alpha.size();
1246 if (n == 0 || A.rows() != n || A.cols() != n)
1247 throw InputError("PH: alpha and the subgenerator have inconsistent sizes");
1248 Distrib d;
1249 d.type = acyclic ? ProcessType::APH : ProcessType::PH;
1250 d.disabled = false;
1251 for (const T& v : alpha) d.params.push_back(v);
1252 d.D0 = A;
1253 d.D1 = Matrix<T>(n, n, zero);
1254 for (std::size_t i = 0; i < n; ++i) {
1255 T out = zero;
1256 for (std::size_t j = 0; j < n; ++j) out += A(i, j);
1257 for (std::size_t j = 0; j < n; ++j) d.D1(i, j) = T(-out * alpha[j]);
1258 }
1259 d.mean = ph_moment(alpha, A, 1);
1260 const T m2 = ph_moment(alpha, A, 2);
1261 d.scv = T((m2 - d.mean * d.mean) / (d.mean * d.mean));
1262 return d;
1263 }
1264
1265 /** A MAP given by its two matrices; the moments are those of its stationary phase. */
1266 static Distrib map_dist(const Matrix<T>& D0, const Matrix<T>& D1, ProcessType tag) {
1267 if (D0.rows() != D0.cols() || D1.rows() != D1.cols() || D0.rows() != D1.rows())
1268 throw InputError("MAP: D0 and D1 must be square and of the same order");
1269 // A PH/APH given in MAP form is the renewal D1 = s alpha with s = -D0 e: recover
1270 // alpha, so the law carries its entry vector and moments like any phase_type.
1271 if (tag == ProcessType::PH || tag == ProcessType::APH) {
1272 const std::size_t n = D0.rows();
1273 std::vector<T> s(n, num_traits<T>::from_int(0)), alpha(n, num_traits<T>::from_int(0));
1274 T stot = num_traits<T>::from_int(0);
1275 for (std::size_t i = 0; i < n; ++i) {
1276 for (std::size_t j = 0; j < n; ++j) s[i] -= D0(i, j);
1277 stot += s[i];
1278 }
1279 if (n == 0 || num_traits<T>::to_double(stot) <= 0.0)
1280 throw InputError("PH: the subgenerator D0 has no exit rate");
1281 for (std::size_t j = 0; j < n; ++j) {
1282 for (std::size_t i = 0; i < n; ++i) alpha[j] += D1(i, j);
1283 alpha[j] = T(alpha[j] / stot);
1284 }
1285 double scale = 0.0;
1286 for (std::size_t i = 0; i < n; ++i)
1287 for (std::size_t j = 0; j < n; ++j)
1288 scale = std::max(scale, std::fabs(num_traits<T>::to_double(D1(i, j))));
1289 for (std::size_t i = 0; i < n; ++i)
1290 for (std::size_t j = 0; j < n; ++j)
1291 if (std::fabs(num_traits<T>::to_double(T(D1(i, j) - s[i] * alpha[j]))) >
1292 1e-10 * std::max(1.0, scale))
1293 throw InputError("PH: D1 must equal the exit vector -D0 e times the entry "
1294 "vector; this (D0, D1) is not a renewal phase-type");
1295 return phase_type(alpha, D0, tag == ProcessType::APH);
1296 }
1297 Distrib d;
1298 d.type = tag;
1299 d.disabled = false;
1300 d.D0 = D0;
1301 d.D1 = D1;
1302 // The moments of the law itself, so a MAP read before it is installed is not a zero-mean service.
1303 // A pair with no arrivals has no finite mean: keep the placeholders and let installation refuse it.
1306 if (tag == ProcessType::DMAP) {
1308 } else {
1309 mam::Map<T> m;
1310 m.D0 = D0;
1311 m.D1 = D1;
1313 d.mean = mam::map_mean(m);
1314 d.scv = mam::map_scv(m);
1315 }
1316 }
1317 return d;
1318 }
1319
1320 // -----------------------------------------------------------------------
1321 // The time-inhomogeneous families (Ko-Pender)
1322 // -----------------------------------------------------------------------
1323
1324 /**
1325 * Reject a schedule segment that is not a generator, the check MATLAB, the JAR
1326 * and Python all apply and this port used to skip.
1327 *
1328 * D0's off-diagonal and every arrival block must be non-negative, and
1329 * D0 + sum(blocks) must have zero row sums in every segment. Without it a
1330 * negative rate or a leaking row reaches the sampler, where it surfaces as a
1331 * negative holding time or a walk that never fires -- a wrong answer rather
1332 * than a refusal.
1333 */
1334 static void check_sched_generator(const std::string& who,
1335 const std::vector<Matrix<T>>& D0segs,
1336 const std::vector<std::vector<Matrix<T>>>& blocks) {
1337 const T zero = num_traits<T>::from_int(0);
1338 for (std::size_t k = 0; k < D0segs.size(); ++k) {
1339 const Matrix<T>& A = D0segs[k];
1340 for (std::size_t i = 0; i < A.rows(); ++i) {
1341 T rowsum = zero;
1342 for (std::size_t j = 0; j < A.cols(); ++j) {
1343 if (i != j && num_traits<T>::to_double(A(i, j)) < 0.0)
1344 throw InputError(who + ": off-diagonal D0 entries must be non-negative; "
1345 "segment " + std::to_string(k + 1) + " entry (" +
1346 std::to_string(i) + "," + std::to_string(j) + ") is not");
1347 rowsum += A(i, j);
1348 }
1349 for (const std::vector<Matrix<T>>& blk : blocks) {
1350 for (std::size_t j = 0; j < blk[k].cols(); ++j) {
1351 if (num_traits<T>::to_double(blk[k](i, j)) < 0.0)
1352 throw InputError(who + ": every arrival block must be non-negative; "
1353 "segment " + std::to_string(k + 1) + " entry (" +
1354 std::to_string(i) + "," + std::to_string(j) +
1355 ") is not");
1356 rowsum += blk[k](i, j);
1357 }
1358 }
1359 if (std::fabs(num_traits<T>::to_double(rowsum)) > 1e-10)
1360 throw InputError(who + ": D0 plus every arrival block must have zero row sums "
1361 "(generator); segment " + std::to_string(k + 1) + " row " +
1362 std::to_string(i) + " sums to " +
1363 std::to_string(num_traits<T>::to_double(rowsum)));
1364 }
1365 }
1366 }
1367
1368 /**
1369 * Reject a schedule whose matrices do not share one sparsity pattern, the twin of
1370 * MATLAB's `MAPt.checkCommonSupport`.
1371 *
1372 * The fluid solver expresses a segment as a per-entry multiplier on a nominal
1373 * matrix, and that multiplier is undefined where the nominal entry is zero.
1374 */
1375 static void check_common_support(const std::string& who, const std::string& label,
1376 const std::vector<Matrix<T>>& mats, bool ignore_diagonal) {
1377 if (mats.empty()) return;
1378 for (std::size_t k = 1; k < mats.size(); ++k) {
1379 for (std::size_t i = 0; i < mats[0].rows(); ++i)
1380 for (std::size_t j = 0; j < mats[0].cols(); ++j) {
1381 if (ignore_diagonal && i == j) continue;
1382 const bool a = num_traits<T>::to_double(mats[0](i, j)) != 0.0;
1383 const bool b = num_traits<T>::to_double(mats[k](i, j)) != 0.0;
1384 if (a != b)
1385 throw InputError(who + ": the " + label + " sparsity pattern must be "
1386 "identical across segments; segment " +
1387 std::to_string(k + 1) + " differs from segment 1 at (" +
1388 std::to_string(i) + "," + std::to_string(j) + "). A "
1389 "schedule that switches a transition on or off cannot be "
1390 "expressed as a per-entry multiplier on the time-averaged "
1391 "process. Keep the entry present with a small positive "
1392 "rate instead.");
1393 }
1394 }
1395 }
1396
1397 /** The shared constructor of the three schedule families. */
1398 static Distrib sched_dist(const std::vector<T>& breakpoints,
1399 const std::vector<Matrix<T>>& D0segs,
1400 const std::vector<Matrix<T>>& D1segs, bool cyclic, ProcessType tag) {
1401 const T zero = num_traits<T>::from_int(0);
1402 const std::string who = process_to_text(tag);
1403 const std::size_t n = D0segs.size();
1404 if (n == 0 || D1segs.size() != n)
1405 throw InputError(who + ": the two segment lists must be non-empty and equally long");
1406 if (breakpoints.size() != n + 1)
1407 throw InputError(who +
1408 ": breakpoints is the BOUNDARY vector and must hold one more entry "
1409 "than there are segments");
1410 for (std::size_t k = 0; k + 1 < breakpoints.size(); ++k)
1411 if (!(breakpoints[k + 1] > breakpoints[k]))
1412 throw InputError(who + ": breakpoints must be strictly increasing");
1413 const std::size_t order = D0segs[0].rows();
1414 for (std::size_t k = 0; k < n; ++k)
1415 if (D0segs[k].rows() != order || D0segs[k].cols() != order ||
1416 D1segs[k].rows() != order || D1segs[k].cols() != order)
1417 throw InputError(who +
1418 ": every segment must have the same order; the schedule "
1419 "modulates one phase structure and does not switch between them");
1420 // The generator check the other three codebases apply and this port used to
1421 // skip. It runs on the AGGREGATE arrival matrix, so it serves every schedule
1422 // family: a marked or batched one has already summed its blocks into D1segs.
1423 {
1424 std::vector<std::vector<Matrix<T>>> one;
1425 one.push_back(D1segs);
1426 check_sched_generator(who, D0segs, one);
1427 }
1428
1429 Distrib d;
1430 d.type = tag;
1431 d.disabled = false;
1432 d.sched_bp = breakpoints;
1433 d.sched_D0 = D0segs;
1434 d.sched_D1 = D1segs;
1435 d.sched_cyclic = cyclic;
1436 // The nominal pair: the width-weighted time average, i.e. the first two
1437 // outputs of `sn_schedule_nominal`.
1438 T total = zero;
1439 for (std::size_t k = 0; k < n; ++k) total += T(breakpoints[k + 1] - breakpoints[k]);
1440 d.D0 = Matrix<T>(order, order, zero);
1441 d.D1 = Matrix<T>(order, order, zero);
1442 for (std::size_t k = 0; k < n; ++k) {
1443 const T w = T(T(breakpoints[k + 1] - breakpoints[k]) / total);
1444 for (std::size_t a = 0; a < order; ++a)
1445 for (std::size_t b = 0; b < order; ++b) {
1446 d.D0(a, b) += w * D0segs[k](a, b);
1447 d.D1(a, b) += w * D1segs[k](a, b);
1448 }
1449 }
1450 // Same convention as `map_dist`: the moments of a MAP are computed by
1451 // `dist_moment`, not stored.
1452 d.mean = zero;
1454 return d;
1455 }
1456
1457 /**
1458 * MAPt(breakpoints, {D0_k}, {D1_k}, cyclic): a piecewise-constant
1459 * (D0(t), D1(t)).
1460 *
1461 * `breakpoints` is the boundary vector, so it holds one more entry than
1462 * there are segments and must be strictly increasing. Every segment must
1463 * have the SAME ORDER: the schedule modulates one phase structure, it does
1464 * not switch between structures, and a solver that integrated across a
1465 * change of order would have no way to map the phase occupancy across the
1466 * boundary. That is the reference's own constructor requirement.
1467 *
1468 * `D0` / `D1` are set to the WIDTH-WEIGHTED TIME AVERAGE of the segments,
1469 * which is `sn_schedule_nominal`'s nominal pair: it is the stationary
1470 * carrier of the phase structure the schedule modulates, so the phase count
1471 * and the mean rate a time-blind consumer reads are the ones the model
1472 * actually has.
1473 */
1474 static Distrib mapt(const std::vector<T>& breakpoints, const std::vector<Matrix<T>>& D0segs,
1475 const std::vector<Matrix<T>>& D1segs, bool cyclic) {
1476 check_common_support("MAPt", "off-diagonal D0", D0segs, true);
1477 check_common_support("MAPt", "D1", D1segs, false);
1478 return sched_dist(breakpoints, D0segs, D1segs, cyclic, ProcessType::MAPT);
1479 }
1480
1481 /**
1482 * PHt(breakpoints, {alpha_k}, {S_k}, cyclic), stored as its equivalent MAP
1483 * schedule: D0 = S and D1 = (-S e) alpha, the pair `sn_schedule_nominal`
1484 * builds from a PHt slot.
1485 */
1486 static Distrib pht(const std::vector<T>& breakpoints, const std::vector<std::vector<T>>& alphas,
1487 const std::vector<Matrix<T>>& Ssegs, bool cyclic) {
1488 const T zero = num_traits<T>::from_int(0);
1489 if (alphas.size() != Ssegs.size() || alphas.empty())
1490 throw InputError("PHt: alpha and S must have the same, non-zero number of segments");
1491 std::vector<Matrix<T>> D0segs, D1segs;
1492 for (std::size_t k = 0; k < Ssegs.size(); ++k) {
1493 const Matrix<T>& S = Ssegs[k];
1494 const std::vector<T>& a = alphas[k];
1495 if (S.rows() != S.cols() || S.rows() != a.size())
1496 throw InputError("PHt: alpha and the sub-generator disagree in order");
1497 Matrix<T> D1(S.rows(), S.cols(), zero);
1498 for (std::size_t i = 0; i < S.rows(); ++i) {
1499 T s = zero;
1500 for (std::size_t j = 0; j < S.cols(); ++j) s += S(i, j);
1501 for (std::size_t j = 0; j < S.cols(); ++j) D1(i, j) = T(-s * a[j]);
1502 }
1503 D0segs.push_back(S);
1504 D1segs.push_back(D1);
1505 }
1506 Distrib d = sched_dist(breakpoints, D0segs, D1segs, cyclic, ProcessType::PHT);
1507 return d;
1508 }
1509
1510 /**
1511 * MMAPt(breakpoints, {D0_k}, {{D1^(c)_k}}, cyclic): the marked schedule.
1512 *
1513 * `Dmarksegs` is MARK-MAJOR, `Dmarksegs[c][k]` being the block of mark c+1 in segment
1514 * k, matching the wire order of the `D1k` key. The aggregate per segment becomes
1515 * `sched_D1`, so the unmarked schedule this lowers to is exactly the MAPt with the
1516 * same matrices and a K = 1 MMAPt IS that MAPt.
1517 */
1518 static Distrib mmapt(const std::vector<T>& breakpoints, const std::vector<Matrix<T>>& D0segs,
1519 const std::vector<std::vector<Matrix<T>>>& Dmarksegs, bool cyclic) {
1520 const T zero = num_traits<T>::from_int(0);
1521 if (Dmarksegs.empty()) throw InputError("MMAPt: no marked arrival block was given");
1522 const std::size_t n = D0segs.size();
1523 for (const std::vector<Matrix<T>>& blk : Dmarksegs)
1524 if (blk.size() != n)
1525 throw InputError("MMAPt: every mark must be defined on the whole schedule; one "
1526 "carries " + std::to_string(blk.size()) + " segments against " +
1527 std::to_string(n) + " in D0");
1528 std::vector<Matrix<T>> D1segs;
1529 for (std::size_t k = 0; k < n; ++k) {
1530 Matrix<T> agg(D0segs[k].rows(), D0segs[k].cols(), zero);
1531 for (const std::vector<Matrix<T>>& blk : Dmarksegs) {
1532 if (blk[k].rows() != D0segs[k].rows() || blk[k].cols() != D0segs[k].cols())
1533 throw InputError("MMAPt: a mark block and D0 disagree in order in segment " +
1534 std::to_string(k + 1));
1535 for (std::size_t a = 0; a < agg.rows(); ++a)
1536 for (std::size_t b = 0; b < agg.cols(); ++b) agg(a, b) += blk[k](a, b);
1537 }
1538 D1segs.push_back(agg);
1539 }
1540 check_common_support("MMAPt", "off-diagonal D0", D0segs, true);
1541 for (std::size_t c = 0; c < Dmarksegs.size(); ++c)
1542 check_common_support("MMAPt", "D1 of mark " + std::to_string(c + 1), Dmarksegs[c],
1543 false);
1544 check_common_support("MMAPt", "aggregate D1", D1segs, false);
1545 Distrib d = sched_dist(breakpoints, D0segs, D1segs, cyclic, ProcessType::MMAPT);
1546 d.sched_Dmark = Dmarksegs;
1547 // The nominal per-mark blocks, beside the nominal aggregate `sched_dist` built.
1548 T total = zero;
1549 for (std::size_t k = 0; k < n; ++k) total += T(breakpoints[k + 1] - breakpoints[k]);
1550 const std::size_t order = D0segs[0].rows();
1551 for (const std::vector<Matrix<T>>& blk : Dmarksegs) {
1552 Matrix<T> nom(order, order, zero);
1553 for (std::size_t k = 0; k < n; ++k) {
1554 const T w = T(T(breakpoints[k + 1] - breakpoints[k]) / total);
1555 for (std::size_t a = 0; a < order; ++a)
1556 for (std::size_t b = 0; b < order; ++b) nom(a, b) += w * blk[k](a, b);
1557 }
1558 d.Dmark.push_back(nom);
1559 }
1560 return d;
1561 }
1562
1563 /**
1564 * BMMAPt(breakpoints, {D0_k}, {{{D^(c,b)_k}}}, cyclic): the BATCH marked schedule.
1565 *
1566 * `Dbatchsegs` is MARK-MAJOR, then BATCH, then segment: `Dbatchsegs[c][b][k]` is
1567 * the block that, in segment k, releases a batch of b+1 jobs all carrying mark
1568 * c+1. The batch axis is DENSE, as BMAP's blocks are, so an unused batch size is
1569 * declared as a zero block rather than omitted.
1570 *
1571 * Two derived levels are built here and are what makes the family cheap: the
1572 * batch-aggregated per-mark blocks become `sched_Dmark`, so every MMAPt consumer
1573 * reads the marked schedule unchanged, and their sum becomes `sched_D1`, so every
1574 * MAPt consumer reads the unmarked one. A B = 1 BMMAPt therefore IS the MMAPt
1575 * with the same blocks, and with K = 1 as well it IS the MAPt.
1576 *
1577 * The support rule binds the per-mark AGGREGATES and the total, not the
1578 * individual (mark, batch) blocks: requiring one pattern there too would forbid
1579 * a batch composition that changes with the segment, which is the one thing this
1580 * family exists to express and which neither reduction needs.
1581 */
1582 static Distrib bmmapt(const std::vector<T>& breakpoints, const std::vector<Matrix<T>>& D0segs,
1583 const std::vector<std::vector<std::vector<Matrix<T>>>>& Dbatchsegs,
1584 bool cyclic) {
1585 const T zero = num_traits<T>::from_int(0);
1586 if (Dbatchsegs.empty()) throw InputError("BMMAPt: no marked batch block was given");
1587 const std::size_t n = D0segs.size();
1588 if (n == 0) throw InputError("BMMAPt: D0 must carry at least one segment");
1589 const std::size_t B = Dbatchsegs[0].size();
1590 if (B == 0) throw InputError("BMMAPt: mark 1 declares no batch size");
1591 for (std::size_t c = 0; c < Dbatchsegs.size(); ++c) {
1592 if (Dbatchsegs[c].size() != B)
1593 throw InputError("BMMAPt: mark " + std::to_string(c + 1) + " declares " +
1594 std::to_string(Dbatchsegs[c].size()) + " batch sizes against " +
1595 std::to_string(B) + " in mark 1; the batch axis is dense and "
1596 "every mark must span it (use a zero block for an unused size)");
1597 for (std::size_t b = 0; b < B; ++b)
1598 if (Dbatchsegs[c][b].size() != n)
1599 throw InputError("BMMAPt: block (mark " + std::to_string(c + 1) + ", batch " +
1600 std::to_string(b + 1) + ") carries " +
1601 std::to_string(Dbatchsegs[c][b].size()) +
1602 " segments against " + std::to_string(n) + " in D0; every "
1603 "block must be defined on the whole schedule");
1604 }
1605 // The two derived levels: batch-aggregated per mark, then aggregated over marks.
1606 std::vector<std::vector<Matrix<T>>> Dmarksegs;
1607 for (std::size_t c = 0; c < Dbatchsegs.size(); ++c) {
1608 std::vector<Matrix<T>> permark;
1609 for (std::size_t k = 0; k < n; ++k) {
1610 Matrix<T> acc(D0segs[k].rows(), D0segs[k].cols(), zero);
1611 for (std::size_t b = 0; b < B; ++b) {
1612 const Matrix<T>& M = Dbatchsegs[c][b][k];
1613 if (M.rows() != D0segs[k].rows() || M.cols() != D0segs[k].cols())
1614 throw InputError("BMMAPt: block (mark " + std::to_string(c + 1) +
1615 ", batch " + std::to_string(b + 1) + ") and D0 disagree "
1616 "in order in segment " + std::to_string(k + 1));
1617 for (std::size_t a = 0; a < acc.rows(); ++a)
1618 for (std::size_t d = 0; d < acc.cols(); ++d) acc(a, d) += M(a, d);
1619 }
1620 permark.push_back(acc);
1621 }
1622 Dmarksegs.push_back(permark);
1623 }
1624 // Through mmapt, which builds sched_D1, the nominal pair and the nominal
1625 // per-mark blocks, and applies the generator and common-support checks to
1626 // exactly the three levels the reductions are constructed from.
1627 Distrib d = mmapt(breakpoints, D0segs, Dmarksegs, cyclic);
1629 d.sched_Dbatch = Dbatchsegs;
1630 return d;
1631 }
1632
1633 /**
1634 * MPHt(breakpoints, {alpha_k}, {S_k}, {{s^(c)_k}}, cyclic), stored LOWERED to MMAPt
1635 * form segment by segment: D0_k = S_k and D1^(c)_k = s^(c)_k alpha_k.
1636 *
1637 * Same treatment a PHt gets, for the same reason: one representation means one walk.
1638 * The exit vectors must partition the absorption rate, sum_c s^(c)_k = -S_k e, which
1639 * is what makes D0 plus the blocks a generator in every segment.
1640 */
1641 static Distrib mpht(const std::vector<T>& breakpoints,
1642 const std::vector<std::vector<T>>& alphas,
1643 const std::vector<Matrix<T>>& Ssegs,
1644 const std::vector<std::vector<std::vector<T>>>& exits, bool cyclic) {
1645 const T zero = num_traits<T>::from_int(0);
1646 if (alphas.size() != Ssegs.size() || alphas.empty())
1647 throw InputError("MPHt: alpha and S must have the same, non-zero number of segments");
1648 if (exits.empty()) throw InputError("MPHt: no marked exit vector was given");
1649 const std::size_t n = Ssegs.size();
1650 for (const std::vector<std::vector<T>>& ex : exits)
1651 if (ex.size() != n)
1652 throw InputError("MPHt: every mark must be defined on the whole schedule");
1653 std::vector<std::vector<Matrix<T>>> Dmarksegs;
1654 for (const std::vector<std::vector<T>>& ex : exits) {
1655 std::vector<Matrix<T>> blocks;
1656 for (std::size_t k = 0; k < n; ++k) {
1657 const Matrix<T>& S = Ssegs[k];
1658 const std::vector<T>& a = alphas[k];
1659 if (S.rows() != S.cols() || S.rows() != a.size() || ex[k].size() != S.rows())
1660 throw InputError("MPHt: alpha, S and the exit vector disagree in order in "
1661 "segment " + std::to_string(k + 1));
1662 Matrix<T> block(S.rows(), S.cols(), zero);
1663 for (std::size_t i = 0; i < S.rows(); ++i)
1664 for (std::size_t j = 0; j < S.cols(); ++j) block(i, j) = T(ex[k][i] * a[j]);
1665 blocks.push_back(block);
1666 }
1667 Dmarksegs.push_back(blocks);
1668 }
1669 // The partition identity, checked where it is still readable as exit vectors.
1670 for (std::size_t k = 0; k < n; ++k) {
1671 const Matrix<T>& S = Ssegs[k];
1672 for (std::size_t i = 0; i < S.rows(); ++i) {
1673 T rowsum = zero, marked = zero;
1674 for (std::size_t j = 0; j < S.cols(); ++j) rowsum += S(i, j);
1675 for (const std::vector<std::vector<T>>& ex : exits) marked += ex[k][i];
1676 const double slack = num_traits<T>::to_double(T(marked + rowsum));
1677 if (std::fabs(slack) > 1e-10)
1678 throw InputError("MPHt: the exit vectors must partition the absorption rate "
1679 "of S; in segment " + std::to_string(k + 1) + " phase " +
1680 std::to_string(i) + " they miss it by " +
1681 std::to_string(slack));
1682 }
1683 }
1684 Distrib d = mmapt(breakpoints, Ssegs, Dmarksegs, cyclic);
1686 return d;
1687 }
1688
1689 /**
1690 * NHPP(breakpoints, rates, cyclic): a MAPt of ORDER ONE, which is what an
1691 * inhomogeneous Poisson process is. Building it through the same path is
1692 * what makes every schedule consumer see one representation.
1693 */
1694 static Distrib nhpp(const std::vector<T>& breakpoints, const std::vector<T>& rates,
1695 bool cyclic) {
1696 std::vector<Matrix<T>> D0segs, D1segs;
1697 for (std::size_t k = 0; k < rates.size(); ++k) {
1698 Matrix<T> a(1, 1, T(-rates[k])), b(1, 1, rates[k]);
1699 D0segs.push_back(a);
1700 D1segs.push_back(b);
1701 }
1702 return sched_dist(breakpoints, D0segs, D1segs, cyclic, ProcessType::NHPP);
1703 }
1704
1705 /**
1706 * The Distrib that carries an NNPP law. `D0`/`D1` are the Poisson nominal at the
1707 * time-average rate mu(S)/S, which is what a time-blind consumer of an NHPP reads
1708 * too; `params` is the `sn.proc` params row. No schedule is set, so
1709 * `has_schedule()` stays false and the matrix-schedule consumers never see it.
1710 */
1711 static Distrib nnpp_dist(const Nnpp& n) {
1712 Distrib d;
1714 d.disabled = false;
1715 d.nnpp = std::make_shared<const Nnpp>(n);
1716 for (double v : n.params()) d.params.push_back(num_traits<T>::from_double(v));
1718 d.D0 = Matrix<T>(1, 1, T(-lam));
1719 d.D1 = Matrix<T>(1, 1, lam);
1722 return d;
1723 }
1724
1725 /**
1726 * NNPP.eptmp(alpha, gamma, omega, phi, horizon, dispersion, cyclic, Q):
1727 * lambda(t) = exp(sum alpha_i t^i + sum gamma_k sin(omega_k t + phi_k)) on [0, horizon].
1728 */
1729 static Distrib nnpp_eptmp(const std::vector<double>& alpha, const std::vector<double>& gamma,
1730 const std::vector<double>& omega, const std::vector<double>& phi,
1731 double horizon, double dispersion = 1.0, bool cyclic = true,
1732 int Q = 200) {
1733 return nnpp_dist(Nnpp::eptmp(alpha, gamma, omega, phi, horizon, dispersion, cyclic, Q));
1734 }
1735
1736 /** NNPP.piecewiseLinear(times, rates, dispersion, cyclic, Q): linear interpolation of knots. */
1737 static Distrib nnpp_piecewise_linear(const std::vector<double>& times,
1738 const std::vector<double>& rates, double dispersion = 1.0,
1739 bool cyclic = true, int Q = 200) {
1740 return nnpp_dist(Nnpp::piecewise_linear(times, rates, dispersion, cyclic, Q));
1741 }
1742
1743 // -----------------------------------------------------------------------
1744 // The non-Markovian families: parameters only, as MATLAB's getProcess
1745 // -----------------------------------------------------------------------
1746
1747 /** Uniform(a, b). */
1748 static Distrib uniform(const T& a, const T& b) {
1749 if (!(b > a)) throw InputError("Uniform: the upper bound must exceed the lower bound");
1750 Distrib d;
1752 d.disabled = false;
1753 d.params.push_back(a);
1754 d.params.push_back(b);
1755 d.mean = T((a + b) / num_traits<T>::from_int(2));
1756 const T w = T(b - a);
1757 d.scv = T((w * w / num_traits<T>::from_int(12)) / (d.mean * d.mean));
1758 return d;
1759 }
1760
1761 /** Pareto(shape, scale), with the MATLAB parameter order (alpha, k). */
1762 static Distrib pareto(const T& shape, const T& scale) {
1763 const T one = num_traits<T>::from_int(1), two = num_traits<T>::from_int(2);
1764 if (!(shape > two))
1765 throw InputError("Pareto: the shape must exceed 2 for a finite variance");
1766 Distrib d;
1768 d.disabled = false;
1769 d.params.push_back(shape);
1770 d.params.push_back(scale);
1771 d.mean = T(shape * scale / (shape - one));
1772 const T var = T(scale * scale * shape / ((shape - one) * (shape - one)) / (shape - two));
1773 d.scv = T(var / (d.mean * d.mean));
1774 return d;
1775 }
1776
1777 /**
1778 * Gamma(shape, scale), Weibull(scale, shape) and Lognormal(mu, sigma).
1779 *
1780 * Their moments are values of the gamma function or of exp, so they exist
1781 * only where the arithmetic has transcendentals. Under exact arithmetic the
1782 * factory REFUSES rather than storing a rounded rational: a rational that
1783 * came out of tgamma is not the exact moment of the distribution, and every
1784 * downstream claim of exactness would be false.
1785 */
1786 static Distrib gamma_dist(const T& shape, const T& scale) {
1787 const T one = num_traits<T>::from_int(1);
1788 Distrib d;
1790 d.disabled = false;
1791 d.params.push_back(shape);
1792 d.params.push_back(scale);
1793 d.mean = T(shape * scale);
1794 d.scv = T(one / shape);
1795 return d;
1796 }
1797
1798 static Distrib weibull(const T& scale, const T& shape) {
1799 if constexpr (!num_traits<T>::has_transcendental) {
1800 throw UnsupportedError(ErrorKind{"Arithmetic"},
1801 "Weibull: its moments are values of the gamma function, which exact arithmetic "
1802 "has no representation for; use the double or real backend");
1803 } else {
1804 const double a = num_traits<T>::to_double(scale);
1805 const double r = num_traits<T>::to_double(shape);
1806 if (!(a > 0.0) || !(r > 0.0))
1807 throw InputError("Weibull: the scale and the shape must be positive");
1808 const double g1 = std::tgamma(1.0 + 1.0 / r);
1809 const double g2 = std::tgamma(1.0 + 2.0 / r);
1810 Distrib d;
1812 d.disabled = false;
1813 d.params.push_back(scale);
1814 d.params.push_back(shape);
1815 d.mean = num_traits<T>::from_double(a * g1);
1816 d.scv = num_traits<T>::from_double((g2 - g1 * g1) / (g1 * g1));
1817 return d;
1818 }
1819 }
1820
1821 /**
1822 * `LogLogistic(shape, scale)`, stored in getParam order {alpha = scale,
1823 * beta = shape}. E[X^k] = alpha^k b/sin(b), b = k pi/beta, for k < beta;
1824 * the mean is Inf for beta <= 1 and the SCV tan(b)/b - 1 (b = pi/beta) is
1825 * Inf for beta <= 2.
1826 */
1827 static Distrib loglogistic(const T& shape, const T& scale) {
1828 if constexpr (!num_traits<T>::has_transcendental) {
1829 throw UnsupportedError(ErrorKind{"Arithmetic"},
1830 "LogLogistic: its moments are values of sin and tan, which exact arithmetic "
1831 "has no representation for; use the double or real backend");
1832 } else {
1833 const double b = num_traits<T>::to_double(shape);
1834 const double a = num_traits<T>::to_double(scale);
1835 if (!(b > 0.0)) throw InputError("LogLogistic: shape parameter must be > 0.0");
1836 if (!(a > 0.0)) throw InputError("LogLogistic: scale parameter must be > 0.0");
1837 const double inf = std::numeric_limits<double>::infinity();
1838 const double pi = 3.14159265358979323846;
1839 Distrib d;
1841 d.disabled = false;
1842 d.params.push_back(scale);
1843 d.params.push_back(shape);
1844 const double b1 = pi / b;
1845 d.mean = num_traits<T>::from_double(b <= 1.0 ? inf : a * b1 / std::sin(b1));
1846 d.scv = num_traits<T>::from_double(b <= 2.0 ? inf : std::tan(b1) / b1 - 1.0);
1847 return d;
1848 }
1849 }
1850
1851 /**
1852 * `MassAtOrigin(inner, p0)`: zero with probability p0, else `inner`.
1853 * Mean (1-p0) E[Y], SCV (1+SCV_Y)/(1-p0) - 1. `params` = {p0}.
1854 */
1855 static Distrib mass_at_origin(const Distrib& in, const T& p0) {
1856 const T one = num_traits<T>::from_int(1);
1857 if (in.type == ProcessType::DEFECTIVE)
1858 throw InputError("MassAtOrigin: nest MassAtOrigin inside Defective, not the other way round");
1859 if (in.disabled || in.type == ProcessType::IMMEDIATE || in.is_prior())
1860 throw InputError("MassAtOrigin: the first argument must be a continuous distribution");
1861 const double p0d = num_traits<T>::to_double(p0);
1862 if (!(p0d >= 0.0) || !(p0d < 1.0)) throw InputError("MassAtOrigin: p0 must lie in [0,1)");
1863 Distrib d;
1865 d.disabled = false;
1866 d.params.push_back(p0);
1867 d.inner = std::make_shared<Distrib>(in);
1868 const T q = T(one - p0);
1869 d.mean = T(q * in.mean);
1870 d.scv = T((one + in.scv) / q - one);
1871 return d;
1872 }
1873
1874 /**
1875 * `Defective(inner, pInf)`: infinite with probability pInf, else `inner`.
1876 * Mean and SCV are Inf when pInf > 0, so it is a lifetime law only and
1877 * every solver refuses it. `params` = {pInf}.
1878 */
1879 static Distrib defective(const Distrib& in, const T& pInf) {
1880 if (in.type == ProcessType::DEFECTIVE)
1881 throw InputError("Defective: nested Defective laws: combine them into one, pInf = 1-(1-p1)(1-p2)");
1882 if (in.disabled || in.type == ProcessType::IMMEDIATE || in.is_prior())
1883 throw InputError("Defective: the first argument must be a continuous distribution");
1884 const double pd = num_traits<T>::to_double(pInf);
1885 if (!(pd >= 0.0) || !(pd < 1.0)) throw InputError("Defective: pInf must lie in [0,1)");
1886 Distrib d;
1888 d.disabled = false;
1889 d.params.push_back(pInf);
1890 d.inner = std::make_shared<Distrib>(in);
1891 if (pd > 0.0) {
1892 if constexpr (num_traits<T>::has_transcendental) {
1893 d.mean = num_traits<T>::from_double(std::numeric_limits<double>::infinity());
1894 d.scv = d.mean;
1895 } else {
1896 throw UnsupportedError(ErrorKind{"Arithmetic"},
1897 "Defective: its mean is infinite, which exact arithmetic has no representation for");
1898 }
1899 } else {
1900 d.mean = in.mean;
1901 d.scv = in.scv;
1902 }
1903 return d;
1904 }
1905
1906 /** `dist.with_mass_at_origin(p0)`: shorthand for `MassAtOrigin(dist, p0)`. */
1907 Distrib with_mass_at_origin(const T& p0) const { return mass_at_origin(*this, p0); }
1908
1909 /** `dist.with_defect(pInf)`: shorthand for `Defective(dist, pInf)`. */
1910 Distrib with_defect(const T& pInf) const { return defective(*this, pInf); }
1911
1912 static Distrib lognormal(const T& logmean, const T& logsigma) {
1913 if constexpr (!num_traits<T>::has_transcendental) {
1914 throw UnsupportedError(ErrorKind{"Arithmetic"},
1915 "Lognormal: its moments are values of exp, which exact arithmetic has no "
1916 "representation for; use the double or real backend");
1917 } else {
1918 const double mu = num_traits<T>::to_double(logmean);
1919 const double sg = num_traits<T>::to_double(logsigma);
1920 if (!(sg > 0.0)) throw InputError("Lognormal: sigma must be positive");
1921 Distrib d;
1923 d.disabled = false;
1924 d.params.push_back(logmean);
1925 d.params.push_back(logsigma);
1926 d.mean = num_traits<T>::from_double(std::exp(mu + sg * sg / 2.0));
1927 d.scv = num_traits<T>::from_double(std::exp(sg * sg) - 1.0);
1928 return d;
1929 }
1930 }
1931
1932 /**
1933 * `Normal(mu, sigma)`: the Gaussian, for use as a continuous `Prior`'s
1934 * parameter density.
1935 *
1936 * `scv` is Inf at mu = 0, which is `Normal.m:52-63`'s own answer and not a
1937 * degradation: the SCV of a zero-mean law is not defined, and the reference
1938 * says so rather than dividing.
1939 */
1940 static Distrib normal(const T& mu, const T& sigma) {
1941 if (!(num_traits<T>::to_double(sigma) > 0.0))
1942 throw InputError("Normal: sigma must be positive");
1943 Distrib d;
1945 d.disabled = false;
1946 d.params.push_back(mu);
1947 d.params.push_back(sigma);
1948 d.mean = mu;
1949 const double m = num_traits<T>::to_double(mu), s = num_traits<T>::to_double(sigma);
1950 d.scv = std::abs(m) < GlobalConstants::FineTol
1951 ? num_traits<T>::from_double(std::numeric_limits<double>::infinity())
1952 : num_traits<T>::from_double((s * s) / (m * m));
1953 return d;
1954 }
1955
1956 /**
1957 * Replayer / Trace read FROM A FILE, which keeps the path beside the samples.
1958 *
1959 * Every solver in this port replays `trace`; the path is what the EXPORTERS
1960 * need. JMT is handed a `ReplayerPar` naming a file and has no way to take
1961 * samples inline, so a Replayer exported without it is a JMT model that
1962 * reads nothing -- `oqn_trace_driven` was refused outright for exactly that.
1963 */
1964 static Distrib replayer_from(const std::vector<T>& samples, const std::string& path) {
1965 Distrib d = replayer(samples);
1966 d.trace_file = path;
1967 return d;
1968 }
1969
1970 /** Replayer / Trace: the samples, with their empirical first two moments. */
1971 static Distrib replayer(const std::vector<T>& samples) {
1972 if (samples.empty()) throw InputError("Replayer: the trace is empty");
1973 Distrib d;
1975 d.disabled = false;
1976 d.trace = samples;
1977 const T n = num_traits<T>::from_int(static_cast<long>(samples.size()));
1979 for (const T& x : samples) {
1980 s1 += x;
1981 s2 += T(x * x);
1982 }
1983 d.mean = T(s1 / n);
1984 d.scv = T((s2 / n - d.mean * d.mean) / (d.mean * d.mean));
1985 return d;
1986 }
1987
1988 // -----------------------------------------------------------------------
1989 // The discrete families
1990 //
1991 // MATLAB's getProcess for each of these returns [mean, scv] and nothing
1992 // else, so they carry NO (D0,D1): refreshProcessRepresentations replaces
1993 // them with the Erlang fit convertToMAP, which `dist_to_map` reproduces
1994 // from the two moments alone. Storing an invented representation here
1995 // would make sn.proc disagree with the reference for the same model.
1996 // -----------------------------------------------------------------------
1997
1998 /** DiscreteUniform(a, b) over the integers a..b inclusive. */
1999 static Distrib discrete_uniform(const T& a, const T& b) {
2000 const T two = num_traits<T>::from_int(2), one = num_traits<T>::from_int(1);
2001 if (!(b >= a)) throw InputError("DiscreteUniform: the upper bound must not be below the lower");
2002 Distrib d;
2004 d.disabled = false;
2005 d.params.push_back(a);
2006 d.params.push_back(b);
2007 d.mean = T((a + b) / two);
2008 const T w = T(b - a + one);
2009 const T var = T((w * w - one) / num_traits<T>::from_int(12));
2010 d.scv = T(var / (d.mean * d.mean));
2011 return d;
2012 }
2013
2014 /** Bernoulli(p): one trial, mean p and variance p(1-p). */
2015 static Distrib bernoulli(const T& p) {
2016 const T one = num_traits<T>::from_int(1);
2017 Distrib d;
2019 d.disabled = false;
2020 d.params.push_back(p);
2021 d.mean = p;
2022 d.scv = T((one - p) / p);
2023 return d;
2024 }
2025
2026 /** Binomial(n, p). */
2027 static Distrib binomial(const T& n, const T& p) {
2028 const T one = num_traits<T>::from_int(1);
2029 Distrib d;
2031 d.disabled = false;
2032 d.params.push_back(n);
2033 d.params.push_back(p);
2034 d.mean = T(n * p);
2035 d.scv = T((one - p) / (n * p));
2036 return d;
2037 }
2038
2039 /**
2040 * Poisson(lambda), whose SCV is 1/lambda -- the count's variance is lambda
2041 * and its mean is lambda, so this is NOT the exponential's SCV of 1.
2042 */
2043 static Distrib poisson(const T& lambda) {
2044 const T one = num_traits<T>::from_int(1);
2045 Distrib d;
2047 d.disabled = false;
2048 d.params.push_back(lambda);
2049 d.mean = lambda;
2050 d.scv = T(one / lambda);
2051 return d;
2052 }
2053
2054 /**
2055 * Geometric(p) on the MATLAB convention: the NUMBER OF TRIALS to the first
2056 * success, support {1, 2, ...}, so the mean is 1/p and the SCV is 1-p.
2057 */
2058 static Distrib geometric(const T& p) {
2059 const T one = num_traits<T>::from_int(1);
2060 Distrib d;
2062 d.disabled = false;
2063 d.params.push_back(p);
2064 d.mean = T(one / p);
2065 d.scv = T(one - p);
2066 return d;
2067 }
2068
2069 /**
2070 * Zipf(s, n) over the ranks 1..n, with the generalized harmonic moments
2071 * H(s-1,n)/H(s,n) and H(s-2,n)/H(s,n) MATLAB `Zipf.m` uses.
2072 *
2073 * The harmonic sums call pow for a non-integer shape, so the factory is
2074 * gated on transcendental arithmetic exactly as Weibull and Lognormal are.
2075 */
2076 static Distrib zipf(const T& s, std::size_t n) {
2077 if constexpr (!num_traits<T>::has_transcendental) {
2078 (void)s;
2079 (void)n;
2080 throw UnsupportedError(ErrorKind{"Arithmetic"},
2081 "Zipf: its moments are generalized harmonic sums of a real exponent, which exact "
2082 "arithmetic has no representation for; use the double or real backend");
2083 } else {
2084 if (n == 0) throw InputError("Zipf: the item count must be positive");
2085 const double sv = num_traits<T>::to_double(s);
2086 auto harmonic = [n](double e) {
2087 double acc = 0.0;
2088 for (std::size_t k = 1; k <= n; ++k) acc += std::pow(double(k), -e);
2089 return acc;
2090 };
2091 const double h0 = harmonic(sv), h1 = harmonic(sv - 1.0), h2 = harmonic(sv - 2.0);
2092 Distrib d;
2094 d.disabled = false;
2095 d.params.push_back(s);
2096 d.params.push_back(num_traits<T>::from_int(static_cast<long>(n)));
2097 const double m1 = h1 / h0;
2099 d.scv = num_traits<T>::from_double((h2 / h0 - m1 * m1) / (m1 * m1));
2100 return d;
2101 }
2102 }
2103
2104 /**
2105 * DiscreteSampler(p, x): the pmf p over the points x.
2106 *
2107 * THE MOMENTS ARE TAKEN OVER x. This port, and MATLAB
2108 * `DiscreteSampler.getMean` with it, used to weight by the RANKS 1..n
2109 * instead; the two agree on the default x = 1:n, which is the form the
2110 * cache popularity vectors are written in, so the rank form survived
2111 * unnoticed until a fork's jobs-per-link distribution arrived on a shifted
2112 * support. The JAR and native Python already weighted by x.
2113 */
2114 static Distrib discrete_sampler(const std::vector<T>& p, const std::vector<T>& x) {
2115 if (p.empty()) throw InputError("DiscreteSampler: the probability vector is empty");
2116 if (!x.empty() && x.size() != p.size())
2117 throw InputError("DiscreteSampler: p and x must have the same length");
2118 Distrib d;
2120 d.disabled = false;
2121 d.params = p;
2122 d.trace = x;
2124 T tot = num_traits<T>::from_int(0);
2125 for (std::size_t k = 0; k < p.size(); ++k) {
2126 // an absent x is the default support 1..n
2127 const T pt = x.empty() ? num_traits<T>::from_int(static_cast<long>(k + 1)) : x[k];
2128 m1 += T(p[k] * pt);
2129 m2 += T(p[k] * pt * pt);
2130 tot += p[k];
2131 }
2132 m1 = T(m1 / tot);
2133 m2 = T(m2 / tot);
2134 d.mean = m1;
2135 d.scv = T((m2 - m1 * m1) / (m1 * m1));
2136 return d;
2137 }
2138
2139 /**
2140 * EmpiricalCDF(x, F): the moments of the MIDPOINT rule over the CDF bins,
2141 * which is what MATLAB `EmpiricalCDF.getMoments` integrates -- the atom
2142 * F_1 at x_1, then each bin's midpoint raised to the moment order, weighted
2143 * by the CDF increment. The rows are the (F, x) pairs in the order they arrive.
2144 */
2145 static Distrib empirical_cdf(const std::vector<T>& x, const std::vector<T>& F) {
2146 if (x.size() != F.size() || x.size() < 2)
2147 throw InputError("EmpiricalCDF: x and F must be equally long and hold at least two points");
2148 const T two = num_traits<T>::from_int(2);
2149 Distrib d;
2151 d.disabled = false;
2152 d.trace = x;
2153 d.params = F;
2154 // the F_1 atom at x_1 (mass the first point already holds), then the bins
2155 T m1 = T(F[0] * x[0]), m2 = T(F[0] * x[0] * x[0]);
2156 for (std::size_t i = 0; i + 1 < x.size(); ++i) {
2157 const T mid = T((x[i + 1] - x[i]) / two + x[i]);
2158 const T w = T(F[i + 1] - F[i]);
2159 m1 += T(mid * w);
2160 m2 += T(mid * mid * w);
2161 }
2162 d.mean = m1;
2163 d.scv = T(m2 / (m1 * m1) - num_traits<T>::from_int(1));
2164 return d;
2165 }
2166
2167 // -----------------------------------------------------------------------
2168 // The matrix-exponential and discrete-time Markovian families
2169 // -----------------------------------------------------------------------
2170
2171 /**
2172 * ME(alpha, A): the matrix-exponential distribution, whose moments are the
2173 * phase-type ones -- k! alpha (-A)^-k e -- evaluated by DEFINITION rather
2174 * than through the stationary vector of A + (-Ae)alpha. MATLAB `ME.getMean`
2175 * makes the same choice and says why: the stationary solve is a
2176 * probabilistic object that a non-Markovian A degrades badly (a CME of
2177 * order 101 lost 2.6e-4 in the SCV that way, against 1e-13 by definition).
2178 */
2179 static Distrib me(const std::vector<T>& alpha, const Matrix<T>& A) {
2180 Distrib d = phase_type(alpha, A, false);
2182 return d;
2183 }
2184
2185 /** RAP(H0, H1): a rational arrival process, whose moments are the MAP ones. */
2186 static Distrib rap(const Matrix<T>& H0, const Matrix<T>& H1) {
2187 return map_dist(H0, H1, ProcessType::RAP);
2188 }
2189
2190 /**
2191 * DMAP(D0, D1): a DISCRETE-time MAP, where D0 + D1 is stochastic rather
2192 * than a generator. Its moments cannot come from `dist_refresh_moments`'s
2193 * continuous formulas; `map_dist` fills them through `dmap_refresh_moments`.
2194 */
2195 static Distrib dmap(const Matrix<T>& D0, const Matrix<T>& D1) {
2196 return map_dist(D0, D1, ProcessType::DMAP);
2197 }
2198
2199 /**
2200 * MMAP: D0 plus one D1 block per mark. `D1` is their sum, the aggregate
2201 * arrival matrix every unmarked consumer reads, and the blocks stay in
2202 * `Dmark` for the ones that distinguish marks.
2203 */
2204 static Distrib mmap(const Matrix<T>& D0, const std::vector<Matrix<T>>& D1k) {
2205 if (D1k.empty()) throw InputError("MMAP: no marked arrival block was given");
2207 for (const Matrix<T>& Dk : D1k) {
2208 if (Dk.rows() != D0.rows() || Dk.cols() != D0.cols())
2209 throw InputError("MMAP: every marked block must have the order of D0");
2210 for (std::size_t i = 0; i < agg.rows(); ++i)
2211 for (std::size_t j = 0; j < agg.cols(); ++j) agg(i, j) += Dk(i, j);
2212 }
2214 d.Dmark = D1k;
2215 return d;
2216 }
2217
2218 /**
2219 * MMPP(Q, lambda): the Markov-modulated Poisson process, i.e. the MAP with
2220 * D0 = Q - diag(lambda) and D1 = diag(lambda). It IS a MAP and keeps that
2221 * process type, as MATLAB, the JAR and Python derive MMPP from MAP, so every
2222 * consumer of a MAP serves it; MMPP2 is its two-phase case.
2223 */
2224 static Distrib mmpp(const Matrix<T>& Q, const std::vector<T>& lambda) {
2225 const std::size_t n = Q.rows();
2226 if (Q.cols() != n) throw InputError("MMPP: Q must be a square matrix");
2227 if (lambda.size() != n)
2228 throw InputError("MMPP: lambda must have length " + std::to_string(n));
2229 Matrix<T> D0 = Q;
2231 for (std::size_t i = 0; i < n; ++i) {
2232 if (num_traits<T>::to_double(lambda[i]) < 0.0)
2233 throw InputError("MMPP: lambda must be non-negative");
2234 D0(i, i) -= lambda[i];
2235 D1(i, i) = lambda[i];
2236 }
2237 return map_dist(D0, D1, ProcessType::MAP);
2238 }
2239
2240 /**
2241 * MarkedMMPP(D0, {D1k}): the marked MMPP (M3PP), i.e. the MMAP whose marked
2242 * blocks are all DIAGONAL, so an arrival never changes the phase. It is an
2243 * MMAP and is stored as one (ProcessType::MMAP), exactly as MATLAB, the JAR
2244 * and Python derive MarkedMMPP from MarkedMAP; only the diagonal check is its
2245 * own, matching their constructors.
2246 */
2247 static Distrib marked_mmpp(const Matrix<T>& D0, const std::vector<Matrix<T>>& D1k) {
2248 for (const Matrix<T>& Dk : D1k)
2249 for (std::size_t i = 0; i < Dk.rows(); ++i)
2250 for (std::size_t j = 0; j < Dk.cols(); ++j)
2251 if (i != j && num_traits<T>::to_double(Dk(i, j)) != 0.0)
2252 throw InputError("MarkedMMPP: non-diagonal elements in the D1k matrices, not a Marked MMPP");
2253 return mmap(D0, D1k);
2254 }
2255
2256 /**
2257 * MPH(alpha, S, {s_k}): the marked phase-type law, a PH with K labelled exits.
2258 * It is the RENEWAL special case of an MMAP and is stored LOWERED to that cell,
2259 * D0 = S and D1k = s_k alpha, keeping the MPH process type so a featset gate can
2260 * still tell the two apart. Validated as MATLAB's MPH constructor: alpha is a
2261 * proper (non-defective) law, S a sub-generator, the exit vectors non-negative,
2262 * not all zero, and partitioning the absorption rate, sum_k s_k = -S e.
2263 */
2264 static Distrib mph(const std::vector<T>& alpha, const Matrix<T>& S,
2265 const std::vector<std::vector<T>>& exits) {
2266 const double tol = 1e-10;
2267 const T zero = num_traits<T>::from_int(0);
2268 const std::size_t h = alpha.size();
2269 if (h == 0 || exits.empty())
2270 throw InputError("MPH: alpha, S and a non-empty list of exit vectors are all required");
2271 if (S.rows() != h || S.cols() != h)
2272 throw InputError("MPH: S must be square of order " + std::to_string(h) + " to match alpha");
2273 double asum = 0.0;
2274 for (const T& a : alpha) {
2275 if (num_traits<T>::to_double(a) < 0.0) throw InputError("MPH: alpha must be non-negative");
2276 asum += num_traits<T>::to_double(a);
2277 }
2278 if (std::fabs(asum - 1.0) > tol)
2279 throw InputError("MPH: alpha must sum to one; it sums to " + std::to_string(asum) +
2280 ". A defective entry law would put mass on an instantaneous "
2281 "completion that carries no mark.");
2282 for (std::size_t i = 0; i < h; ++i)
2283 for (std::size_t j = 0; j < h; ++j) {
2284 const double v = num_traits<T>::to_double(S(i, j));
2285 if (i == j && v >= 0.0) throw InputError("MPH: the diagonal of S must be negative");
2286 if (i != j && v < 0.0)
2287 throw InputError("MPH: off-diagonal entries of S must be non-negative");
2288 }
2289 std::vector<double> marked(h, 0.0);
2290 for (std::size_t k = 0; k < exits.size(); ++k) {
2291 if (exits[k].size() != h)
2292 throw InputError("MPH: exit vector " + std::to_string(k + 1) + " must have " +
2293 std::to_string(h) + " entries");
2294 for (std::size_t i = 0; i < h; ++i) {
2295 const double v = num_traits<T>::to_double(exits[k][i]);
2296 if (v < 0.0)
2297 throw InputError("MPH: exit vector " + std::to_string(k + 1) + " must be non-negative");
2298 marked[i] += v;
2299 }
2300 }
2301 bool any_exit = false;
2302 for (std::size_t i = 0; i < h; ++i) {
2303 double absorb = 0.0;
2304 for (std::size_t j = 0; j < h; ++j) absorb -= num_traits<T>::to_double(S(i, j));
2305 if (std::fabs(marked[i] - absorb) > tol)
2306 throw InputError("MPH: the exit vectors must partition the absorption rate of S. "
2307 "Every way of leaving the transient phases must carry exactly one mark.");
2308 if (marked[i] != 0.0) any_exit = true;
2309 }
2310 if (!any_exit) throw InputError("MPH: every exit vector is zero, so absorption can never occur");
2311 std::vector<Matrix<T>> blocks;
2312 for (const std::vector<T>& sk : exits) {
2313 Matrix<T> block(h, h, zero);
2314 for (std::size_t i = 0; i < h; ++i)
2315 for (std::size_t j = 0; j < h; ++j) block(i, j) = T(sk[i] * alpha[j]);
2316 blocks.push_back(block);
2317 }
2318 Distrib d = mmap(S, blocks);
2320 return d;
2321 }
2322
2323 /**
2324 * BMAP: the batch-size blocks D0, D1, ..., Dk, where Dj carries an arrival
2325 * of batch size j. The wire form is the whole list including D0, so the
2326 * head is split off here.
2327 */
2328 static Distrib bmap(const std::vector<Matrix<T>>& D) {
2329 if (D.size() < 2) throw InputError("BMAP: the block list must carry D0 and at least one batch block");
2330 const std::vector<Matrix<T>> batches(D.begin() + 1, D.end());
2331 Distrib d = mmap(D[0], batches);
2333 return d;
2334 }
2335
2336 bool is_immediate() const { return type == ProcessType::IMMEDIATE; }
2337
2338 /** True when the type carries a (D0,D1) pair of its own. */
2339 bool has_map() const { return D0.rows() > 0; }
2340
2341 /**
2342 * Phase rates, MATLAB's getMu: the total outgoing rate of each phase.
2343 *
2344 * Empty when the type carries no representation, which is what
2345 * refreshProcessPhases writes as NaN for a Fork or a Join.
2346 */
2347 std::vector<T> mu_vec() const {
2348 std::vector<T> v;
2349 if (!has_map()) {
2350 if (disabled) return v;
2351 v.push_back(rate()); // one phase at the mean rate, as MATLAB does
2352 return v;
2353 }
2354 for (std::size_t i = 0; i < D0.rows(); ++i) v.push_back(T(-D0(i, i)));
2355 return v;
2356 }
2357
2358 /** Completion probabilities, MATLAB's getPhi: (D1 e) ./ (-diag(D0)). */
2359 std::vector<T> phi_vec() const {
2360 std::vector<T> v;
2361 if (!has_map()) {
2362 if (disabled) return v;
2363 v.push_back(num_traits<T>::from_int(1));
2364 return v;
2365 }
2366 const T zero = num_traits<T>::from_int(0);
2367 for (std::size_t i = 0; i < D1.rows(); ++i) {
2368 T s = zero;
2369 for (std::size_t j = 0; j < D1.cols(); ++j) s += D1(i, j);
2370 const T out = T(-D0(i, i));
2371 v.push_back(out == zero ? num_traits<T>::from_int(1) : T(s / out));
2372 }
2373 return v;
2374 }
2375
2376 /** The order of the representation, MATLAB's sn.phases. */
2377 std::size_t phases() const {
2378 if (disabled) return 0;
2379 return has_map() ? D0.rows() : 1;
2380 }
2381
2382 /**
2383 * The k-th raw moment of a phase-type (alpha, A): k! alpha (-A)^-k e.
2384 *
2385 * The inverse is never formed: the powers are accumulated by repeated
2386 * solves of (-A) x = b, which is exact in rational arithmetic and stable
2387 * in floating point.
2388 */
2389 static T ph_moment(const std::vector<T>& alpha, const Matrix<T>& A, unsigned k) {
2390 const std::size_t n = alpha.size();
2391 std::vector<T> x(n, num_traits<T>::from_int(1));
2392 for (unsigned i = 0; i < k; ++i) x = solve_neg(A, x);
2393 T acc = num_traits<T>::from_int(0);
2394 for (std::size_t i = 0; i < n; ++i) acc += alpha[i] * x[i];
2395 T fact = num_traits<T>::from_int(1);
2396 for (unsigned i = 2; i <= k; ++i) fact *= num_traits<T>::from_int(static_cast<long>(i));
2397 return T(fact * acc);
2398 }
2399
2400 /** The same, for a representation entered in a single phase (1-based). */
2401 static T ph_moment_from(const Matrix<T>& A, std::size_t start, unsigned k) {
2402 std::vector<T> alpha(A.rows(), num_traits<T>::from_int(0));
2403 alpha[start - 1] = num_traits<T>::from_int(1);
2404 return ph_moment(alpha, A, k);
2405 }
2406
2407 private:
2408 /** Solve (-A) x = b by Gaussian elimination with partial pivoting. */
2409 static std::vector<T> solve_neg(const Matrix<T>& A, const std::vector<T>& b) {
2410 const T zero = num_traits<T>::from_int(0);
2411 const std::size_t n = A.rows();
2412 if (A.cols() != n || b.size() != n)
2413 throw InputError("phase-type moment: the subgenerator is not square");
2414 Matrix<T> M(n, n, zero);
2415 std::vector<T> x = b;
2416 for (std::size_t i = 0; i < n; ++i)
2417 for (std::size_t j = 0; j < n; ++j) M(i, j) = T(-A(i, j));
2418 for (std::size_t col = 0; col < n; ++col) {
2419 std::size_t best = col;
2420 double bv = std::fabs(num_traits<T>::to_double(M(col, col)));
2421 for (std::size_t r = col + 1; r < n; ++r) {
2422 const double v = std::fabs(num_traits<T>::to_double(M(r, col)));
2423 if (v > bv) {
2424 bv = v;
2425 best = r;
2426 }
2427 }
2428 if (best != col) {
2429 for (std::size_t j = 0; j < n; ++j) std::swap(M(col, j), M(best, j));
2430 std::swap(x[col], x[best]);
2431 }
2432 if (M(col, col) == zero)
2433 throw NumericError(ErrorKind{"Singular"}, "phase-type moment: the subgenerator is singular");
2434 for (std::size_t r = 0; r < n; ++r) {
2435 if (r == col) continue;
2436 const T f = T(M(r, col) / M(col, col));
2437 if (f == zero) continue;
2438 for (std::size_t j = 0; j < n; ++j) M(r, j) = T(M(r, j) - f * M(col, j));
2439 x[r] = T(x[r] - f * x[col]);
2440 }
2441 }
2442 for (std::size_t i = 0; i < n; ++i) x[i] = T(x[i] / M(i, i));
2443 return x;
2444 }
2445
2446 public:
2447
2448
2449 /**
2450 * The rate MATLAB's refreshRates would store: 1/mean, with the Immediate
2451 * singleton short-circuited to its declared rate so that the reciprocal of
2452 * 1e-8 is exactly 1e8 in every arithmetic rather than 1e8 plus rounding.
2453 */
2460};
2461
2462/**
2463 * What a `Prior` carries, in either of its two forms.
2464 *
2465 * DISCRETE: an explicit set of alternative distributions and their prior
2466 * weights, which must sum to one. This is the form the model.json wire carries
2467 * (`{"type":"Prior","distributions":[...],"probabilities":[...]}`), because a
2468 * factory cannot cross JSON.
2469 *
2470 * CONTINUOUS: a density over a scalar parameter theta plus a map theta ->
2471 * Distribution, the form the epistemic propagation of Trivedi and Bobbio
2472 * (2017), Sec. 3.4 needs. It is reduced to the discrete form by
2473 * `prior_discretize` (lang/prior.h) before anything downstream sees it, so both
2474 * forms are consumed identically. It can only be BUILT programmatically.
2475 *
2476 * IT IS NOT A MIXTURE. Each alternative is a separate model realization whose
2477 * weight is a prior probability over models, not a branching probability inside
2478 * one model. The mixture moments are still computed (see `Distrib::prior`)
2479 * because MATLAB's `Prior.getMean`/`getSCV` do, but they are a summary of the
2480 * epistemic uncertainty and not the law any station serves.
2481 */
2482template <class T>
2484 /** True for the parameter-density form, false for the alternative-set form. */
2485 bool continuous = false;
2486 /** The alternatives and their weights; the discrete form only. */
2487 std::vector<Distrib<T>> alternatives;
2488 std::vector<T> probabilities;
2489 /** The law of the scalar parameter; the continuous form only. */
2491 /**
2492 * theta -> Distribution; the continuous form only.
2493 *
2494 * A `std::function` and not a serializable description, exactly as MATLAB's
2495 * `distFactory` is a function handle: the map is arbitrary code (a rate
2496 * becomes an Exp, a scale becomes an Erlang of fixed order), and no wire
2497 * format in this codebase encodes it. That is why the JSON reader builds
2498 * the discrete form only.
2499 */
2500 std::function<Distrib<T>(const T&)> factory;
2501};
2502
2503/**
2504 * The first two moments of a DISCRETE-time MAP, from its own law.
2505 *
2506 * With alpha the arrival-epoch stationary vector -- `dmap_pie`, the stationary
2507 * vector of (I - D0)^-1 D1 -- the interarrival count has
2508 * P(N = k) = alpha D0^(k-1) D1 e, so
2509 *
2510 * E[N] = alpha (I - D0)^-1 e (MATLAB `DMAP.getMean`)
2511 * E[N(N-1)] = 2 alpha D0 (I - D0)^-2 e
2512 *
2513 * THE SCV IS NOT MATLAB'S INHERITED ONE. `DMAP` declares no getSCV, so it falls
2514 * through to `Markovian.getSCV` = map_scv({D0,D1}), a CONTINUOUS-time formula
2515 * that reads D0 + D1 as a generator; for a DMAP that matrix is stochastic, so
2516 * the stationary solve behind it is singular and the number it returns is not
2517 * the SCV of anything. Reproducing it would propagate an undefined value into
2518 * every AMVA path, so the discrete second moment is computed here and the
2519 * reference defect is recorded in BUGS.md.
2520 */
2521template <class T>
2523 const std::size_t n = d.D0.rows();
2524 const T one = num_traits<T>::from_int(1), two = num_traits<T>::from_int(2);
2525 Matrix<T> ImD0(n, n);
2526 for (std::size_t i = 0; i < n; ++i)
2527 for (std::size_t j = 0; j < n; ++j) ImD0(i, j) = T((i == j ? one : T(0)) - d.D0(i, j));
2528 // alpha: the stationary vector of P = (I - D0)^-1 D1, formed column by
2529 // column through one factorization rather than by inverting ImD0.
2530 Matrix<T> LU = ImD0;
2531 const std::vector<std::size_t> piv = lu_factor(LU);
2532 Matrix<T> P(n, n);
2533 for (std::size_t j = 0; j < n; ++j) {
2534 std::vector<T> col(n);
2535 for (std::size_t i = 0; i < n; ++i) col[i] = d.D1(i, j);
2536 lu_solve(LU, piv, col);
2537 for (std::size_t i = 0; i < n; ++i) P(i, j) = col[i];
2538 }
2539 const std::vector<T> alpha = mc::dtmc_solve(P);
2540 std::vector<T> y(n, one);
2541 lu_solve(LU, piv, y); // (I - D0)^-1 e
2542 std::vector<T> z = y;
2543 lu_solve(LU, piv, z); // (I - D0)^-2 e
2545 for (std::size_t i = 0; i < n; ++i) {
2546 m1 += T(alpha[i] * y[i]);
2547 T dz = num_traits<T>::from_int(0);
2548 for (std::size_t j = 0; j < n; ++j) dz += T(d.D0(i, j) * z[j]);
2549 fac2 += T(alpha[i] * dz);
2550 }
2551 fac2 = T(two * fac2);
2552 const T m2 = T(fac2 + m1);
2553 d.mean = m1;
2554 d.scv = T((m2 - m1 * m1) / (m1 * m1));
2555}
2556
2557} // namespace lang
2558} // namespace line
2559
2560#endif // LINE_LANG_LANG_TYPES_H
Cache(model, name, params).
Definition nodes.h:254
ClassSwitch(model, name, C).
Definition nodes.h:223
Delay(model, name): the infinite-server station.
Definition nodes.h:173
Fork(model, name).
Definition nodes.h:236
InputError(const std::string &what)
Definition error.h:105
Join(model, name, fork).
Definition nodes.h:243
std::size_t size() const
Definition matrix.h:91
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
Place(model, name): a Petri-net place.
Definition nodes.h:274
Queue(model, name, strategy).
Definition nodes.h:165
Router(model, name): a stateless routing node.
Definition nodes.h:217
Sink(model, name): the external departure node, which holds no jobs.
Definition nodes.h:211
Source(model, name): the external arrival station.
Definition nodes.h:179
Transition(model, name): a Petri-net transition, with its modes declared after it as MATLAB,...
Definition nodes.h:323
UnsupportedError(const std::string &what)
Definition error.h:119
double time_average_rate() const
Definition nnpp.h:171
double mean() const
Definition nnpp.h:172
static Nnpp eptmp(const std::vector< double > &alpha, const std::vector< double > &gamma, const std::vector< double > &omega, const std::vector< double > &phi, double horizon, double dispersion=1.0, bool cyclic=true, int Q=200)
EPTMP: lambda(t) = exp(sum_i alpha_i t^i + sum_k gamma_k sin(omega_k t + phi_k)) on [0,...
Definition nnpp.h:70
std::vector< double > params() const
The params row of sn.proc, see from_params.
Definition nnpp.h:219
static Nnpp piecewise_linear(const std::vector< double > &times, const std::vector< double > &rates, double dispersion=1.0, bool cyclic=true, int Q=200)
PWLINEAR: lambda linearly interpolated between (times[j], rates[j]); horizon = times....
Definition nnpp.h:96
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
The exception types the port throws.
LU factorization with partial pivoting, templated on the number type.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
TimingStrategy
SPN transition timing, with the values of MATLAB TimingStrategy.
Definition lang_types.h:382
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
Definition lang_types.h:384
@ TIMED
fires after its firing distribution elapses
Definition lang_types.h:383
BalkingStrategy
Balking rules, with the values of MATLAB BalkingStrategy.
Definition lang_types.h:486
SignalType
G-network signal classes, with the values of MATLAB SignalType.
Definition lang_types.h:180
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:181
@ NEGATIVE
removes a batch of jobs (Gelenbe's negative customer)
Definition lang_types.h:182
@ CATASTROPHE
removes EVERY job at the station
Definition lang_types.h:183
bool process_is_batch(ProcessType p)
True when an EVENT of this process releases (or, as a service process, completes) a BATCH of jobs who...
Definition lang_types.h:771
PollingOrder
Visit-order rules of a polling server, with the values of MATLAB PollingOrder.
Definition lang_types.h:404
@ THRESHOLD
a priority buffer above its threshold, else SKIPEMPTY
Definition lang_types.h:408
@ SKIPEMPTY
next non-empty buffer in cyclic order
Definition lang_types.h:406
@ CYCLIC
fixed cyclic order (or the polling table)
Definition lang_types.h:405
@ LQF
longest buffer first, ties to the cyclic successor
Definition lang_types.h:407
JoinStrategy
Join rules, with the values of MATLAB JoinStrategy.
Definition lang_types.h:502
PrecedenceType
Activity precedence kinds, with the values of MATLAB ActivityPrecedenceType.
Definition lang_types.h:511
LqnElement
LQN element kinds, with the values of MATLAB LayeredNetworkElement.
Definition lang_types.h:505
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
@ SDR
Krzesinski (1987) product-form state-dependent routing.
Definition lang_types.h:439
SchedStrategy sched_from_lqnx(const std::string &s)
Parse the scheduling attribute of an .lqnx processor or task.
Definition lang_types.h:296
PollingTimer
Visit-timer scopes of a polling server, with the values of MATLAB PollingTimer.
Definition lang_types.h:412
@ GLOBAL
a timed token: per-class target rotation timers
Definition lang_types.h:415
DepartureDiscipline
When a Place releases a served token, MATLAB DepartureDiscipline.
Definition lang_types.h:499
bool process_is_marked(ProcessType p)
True for every marked family.
Definition lang_types.h:781
CallType
Call kinds, with the values of MATLAB CallType.
Definition lang_types.h:508
const char * metric_to_text(MetricType metric)
Port of MetricType.toText.
Definition lang_types.h:78
RemovalPolicy
Which job a negative signal removes, with the values of MATLAB RemovalPolicy.
Definition lang_types.h:187
@ LCFS
the newest waiting job; servers only once nobody waits
Definition lang_types.h:190
@ RANDOM
uniform over waiting AND in-service jobs
Definition lang_types.h:188
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
@ PHASE
service advances a phase WITHOUT departing
Definition lang_types.h:121
@ READ
a cache item is read
Definition lang_types.h:122
@ FAILURE
the server breaks down, going from up to down
Definition lang_types.h:131
@ STAGE
a random environment changes stage
Definition lang_types.h:123
@ SWITCH
a polling server advances its switchover timer
Definition lang_types.h:130
@ LOCAL
dummy event, no state change outside the node
Definition lang_types.h:118
@ RENEGE
a waiting job abandons the queue (impatience)
Definition lang_types.h:128
@ POST
produce to a place or queue buffer
Definition lang_types.h:127
@ DEP
a job departs
Definition lang_types.h:120
@ START
a job begins or resumes holding a server
Definition lang_types.h:134
@ ENABLE
an SPN mode becomes enabled
Definition lang_types.h:124
@ DELAYOFF
a station server's delay-off clock moves a phase or expires, turning the server OFF
Definition lang_types.h:140
@ FIRE
an SPN mode fires
Definition lang_types.h:125
@ DROP
an arriving job is lost (full buffer or region, balking); emitted only by simulation event logs
Definition lang_types.h:136
@ RETRY
an orbiting job retries entry at a retrial station
Definition lang_types.h:129
@ REPAIR
the server is repaired, going from down to up, resuming the held job, which is why it emits no START
Definition lang_types.h:132
@ ARV
a job arrives
Definition lang_types.h:119
@ PRE
consume from a place or queue buffer, no server effect
Definition lang_types.h:126
@ SETUP
a station server's setup clock moves a phase or completes (Queue.setDelayOff), making the server ACTI...
Definition lang_types.h:138
@ INIT
the model is initialized, t = 0
Definition lang_types.h:117
@ PREEMPT
a job holding a server is pushed back into the buffer
Definition lang_types.h:135
MetricType
Solver output metrics, with the numeric values of MATLAB MetricType.
Definition lang_types.h:51
HeteroSchedPolicy
How a heterogeneous station picks among its server types, MATLAB HeteroSchedPolicy.
Definition lang_types.h:492
PollingType
Polling service disciplines, with the values of MATLAB PollingType.
Definition lang_types.h:391
@ KLIMITED
serve at most K per visit (K in pollingPar)
Definition lang_types.h:394
@ EXHAUSTIVE
serve until the queue empties
Definition lang_types.h:393
@ GATED
serve exactly the jobs present at the polling instant
Definition lang_types.h:392
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
@ DECREMENTING
serve until the queue is one shorter than at arrival
Definition lang_types.h:395
JobClassType
Job class kinds, with the values of MATLAB JobClassType.
Definition lang_types.h:388
std::string sched_to_lqnx(SchedStrategy s)
The scheduling attribute an .lqnx processor or task carries for a strategy.
Definition lang_types.h:325
bool process_is_marked_schedule(ProcessType p)
True when sn.proc holds the MARKED SCHEDULE slot.
Definition lang_types.h:751
const char * node_type_to_text(NodeType t)
Name of a node kind, for diagnostics.
Definition lang_types.h:362
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
@ NORMAL
A Gaussian, and the ONE family whose value is not MATLAB's, because MATLAB has none to copy: ProcessT...
Definition lang_types.h:650
@ BMMAPT
BMMAPT crosses the BATCH axis with the two above: a block is indexed by segment, mark and batch size,...
Definition lang_types.h:613
@ MPH
The MARKED families, MATLAB's ProcessType.m:36-38.
Definition lang_types.h:598
@ NHPP
The time-INHOMOGENEOUS families of Ko and Pender (ORL 45, 2017): an NHPP is a rate schedule lambda(t)...
Definition lang_types.h:577
@ LOGLOGISTIC
Three reliability laws of Trivedi and Bobbio, "Reliability andAvailability Engineering" (2017),...
Definition lang_types.h:622
@ NNPP
A nonstationary non-Poisson arrival process (thinning + SCIATA): a rate function lambda(t) on [0,...
Definition lang_types.h:633
@ PRIOR
A Prior: a weighted set of ALTERNATIVE distributions, or a density over a scalar parameter plus a fac...
Definition lang_types.h:551
void dmap_refresh_moments(Distrib< T > &d)
The first two moments of a DISCRETE-time MAP, from its own law.
std::function< std::vector< T >(const std::vector< T > &)> GdScaling
A globally state-dependent scaling, sn.gdscaling.
Definition lang_types.h:807
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
bool process_is_markovian(ProcessType p)
ProcessType.isMarkovian: true when sn.proc carries an exact matrix representation of the law,...
Definition lang_types.h:713
bool process_is_marked_stationary(ProcessType p)
True when the type carries PER-MARK arrival blocks, i.e.
Definition lang_types.h:742
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
const char * routing_to_text(RoutingStrategy r)
Definition lang_types.h:443
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
const char * event_to_text(EventType e)
Definition lang_types.h:148
ReplacementStrategy
Cache replacement policies, with the values of MATLAB ReplacementStrategy.
Definition lang_types.h:419
@ HLRU
h-LRU / LRU(m): h lists, promote i -> i+1 on a hit
Definition lang_types.h:424
@ CLIMB
move up one position on a hit (transposition rule)
Definition lang_types.h:425
@ QLRU
q-LRU: LRU with probabilistic admission on a miss
Definition lang_types.h:426
@ LRU
least recently used
Definition lang_types.h:423
@ FIFO
first in, first out
Definition lang_types.h:421
ImpatienceType
Impatience kinds, with the values of MATLAB ImpatienceType.
Definition lang_types.h:483
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
T map_scv(const Map< T > &m)
Squared coefficient of variation.
Definition map_moment.h:140
T map_lambda(const Map< T > &m)
Stationary arrival rate, lambda = pi D1 e.
Definition map_moment.h:79
std::vector< T > dtmc_solve(const Matrix< T > &P)
Stationary distribution of a stochastic matrix P.
Definition dtmc_solve.h:106
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
void lu_solve(const Matrix< T > &LU, const std::vector< std::size_t > &piv, std::vector< T > &b)
Solve LUx = Pb in place on b, using the factors from lu_factor.
Definition lu.h:94
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Definition lu.h:48
NNPP: a nonstationary non-Poisson arrival process, generated by thinning a majorizing stream (Lewis a...
Number-type abstraction for the templated API port.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
bool is_immediate() const
static Distrib sched_dist(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< Matrix< T > > &D1segs, bool cyclic, ProcessType tag)
The shared constructor of the three schedule families.
static Distrib empirical_cdf(const std::vector< T > &x, const std::vector< T > &F)
EmpiricalCDF(x, F): the moments of the MIDPOINT rule over the CDF bins, which is what MATLAB Empirica...
std::vector< std::vector< std::vector< Matrix< double > > > > sched_Dbatch
static Distrib nhpp(const std::vector< T > &breakpoints, const std::vector< T > &rates, bool cyclic)
NHPP(breakpoints, rates, cyclic): a MAPt of ORDER ONE, which is what an inhomogeneous Poisson process...
std::vector< T > mu_vec() const
Phase rates, MATLAB's getMu: the total outgoing rate of each phase.
static void check_common_support(const std::string &who, const std::string &label, const std::vector< Matrix< T > > &mats, bool ignore_diagonal)
Reject a schedule whose matrices do not share one sparsity pattern, the twin of MATLAB's MAPt....
static Distrib mph(const std::vector< T > &alpha, const Matrix< T > &S, const std::vector< std::vector< T > > &exits)
MPH(alpha, S, {s_k}): the marked phase-type law, a PH with K labelled exits.
bool has_map() const
True when the type carries a (D0,D1) pair of its own.
static Distrib mmapt(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< std::vector< Matrix< T > > > &Dmarksegs, bool cyclic)
MMAPt(breakpoints, {D0_k}, {{D1^(c)_k}}, cyclic): the marked schedule.
static Distrib loglogistic(const T &shape, const T &scale)
LogLogistic(shape, scale), stored in getParam order {alpha = scale, beta = shape}.
static Distrib nnpp_piecewise_linear(const std::vector< double > &times, const std::vector< double > &rates, double dispersion=1.0, bool cyclic=true, int Q=200)
NNPP.piecewiseLinear(times, rates, dispersion, cyclic, Q): linear interpolation of knots.
std::vector< std::vector< Matrix< double > > > sched_Dmark
Definition lang_types.h:987
static Distrib replayer(const std::vector< double > &samples)
static Distrib marked_mmpp(const Matrix< T > &D0, const std::vector< Matrix< T > > &D1k)
MarkedMMPP(D0, {D1k}): the marked MMPP (M3PP), i.e.
std::vector< double > sched_bp
Definition lang_types.h:979
static Distrib normal(const T &mu, const T &sigma)
Normal(mu, sigma): the Gaussian, for use as a continuous Prior's parameter density.
static Distrib defective(const Distrib &in, const T &pInf)
Defective(inner, pInf): infinite with probability pInf, else inner.
static Distrib dmap(const Matrix< T > &D0, const Matrix< T > &D1)
DMAP(D0, D1): a DISCRETE-time MAP, where D0 + D1 is stochastic rather than a generator.
static Distrib exp_rate(const T &r)
static Distrib phase_type(const std::vector< T > &alpha, const Matrix< T > &A, bool acyclic)
PH / APH given by (alpha, A): D0 = A and D1 = (-A e) alpha.
std::vector< Matrix< double > > Dmark
Definition lang_types.h:931
static Distrib mapt(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< Matrix< T > > &D1segs, bool cyclic)
MAPt(breakpoints, {D0_k}, {D1_k}, cyclic): a piecewise-constant (D0(t), D1(t)).
std::shared_ptr< Distrib< double > > declared
Definition lang_types.h:889
static Distrib weibull(const T &scale, const T &shape)
std::shared_ptr< const Nnpp > nnpp
Definition lang_types.h:960
static Distrib replayer_from(const std::vector< T > &samples, const std::string &path)
Replayer / Trace read FROM A FILE, which keeps the path beside the samples.
bool has_schedule() const
static Distrib bmap(const std::vector< Matrix< T > > &D)
BMAP: the batch-size blocks D0, D1, ..., Dk, where Dj carries an arrival of batch size j.
static Distrib mass_at_origin(const Distrib &in, const T &p0)
MassAtOrigin(inner, p0): zero with probability p0, else inner.
static Distrib mmap(const Matrix< T > &D0, const std::vector< Matrix< T > > &D1k)
MMAP: D0 plus one D1 block per mark.
static Distrib disabled_dist()
static Distrib pht(const std::vector< T > &breakpoints, const std::vector< std::vector< T > > &alphas, const std::vector< Matrix< T > > &Ssegs, bool cyclic)
PHt(breakpoints, {alpha_k}, {S_k}, cyclic), stored as its equivalent MAP schedule: D0 = S and D1 = (-...
static double ph_moment(const std::vector< double > &alpha, const Matrix< double > &A, unsigned k)
static Distrib erlang_fit(const T &m, const T &c2)
Erlang fitted to a mean and an SCV, as MATLAB's Erlang.fitMeanAndSCV.
std::shared_ptr< Distrib< double > > inner
Definition lang_types.h:951
static Distrib pareto(const T &shape, const T &scale)
Pareto(shape, scale), with the MATLAB parameter order (alpha, k).
std::vector< double > params
Definition lang_types.h:894
static Distrib gamma_dist(const T &shape, const T &scale)
Gamma(shape, scale), Weibull(scale, shape) and Lognormal(mu, sigma).
Distrib with_mass_at_origin(const T &p0) const
dist.with_mass_at_origin(p0): shorthand for MassAtOrigin(dist, p0).
static Distrib cox2(const T &mu1, const T &mu2, const T &phi1)
Cox2(mu1, mu2, phi1), MATLAB's two-phase Coxian constructor.
static Distrib map_dist(const Matrix< T > &D0, const Matrix< T > &D1, ProcessType tag)
A MAP given by its two matrices; the moments are those of its stationary phase.
static Distrib poisson(const T &lambda)
Poisson(lambda), whose SCV is 1/lambda – the count's variance is lambda and its mean is lambda,...
std::vector< double > trace
Definition lang_types.h:896
static Distrib bernoulli(const T &p)
Bernoulli(p): one trial, mean p and variance p(1-p).
static double ph_moment_from(const Matrix< double > &A, std::size_t start, unsigned k)
static Distrib hyperexp_n(const std::vector< T > &p, const std::vector< T > &lambda)
The same for any number of branches, which is what MATLAB HyperExp accepts and what the writers emit ...
static Distrib discrete_uniform(const T &a, const T &b)
DiscreteUniform(a, b) over the integers a..b inclusive.
std::shared_ptr< PriorSpec< double > > prior
Definition lang_types.h:945
static Distrib geometric(const T &p)
Geometric(p) on the MATLAB convention: the NUMBER OF TRIALS to the first success, support {1,...
static Distrib det(const T &m)
static Distrib bmmapt(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< std::vector< std::vector< Matrix< T > > > > &Dbatchsegs, bool cyclic)
BMMAPt(breakpoints, {D0_k}, {{{D^(c,b)_k}}}, cyclic): the BATCH marked schedule.
static Distrib rap(const Matrix< T > &H0, const Matrix< T > &H1)
RAP(H0, H1): a rational arrival process, whose moments are the MAP ones.
bool has_batch_schedule() const
static Distrib uniform(const T &a, const T &b)
Uniform(a, b).
static Distrib nnpp_eptmp(const std::vector< double > &alpha, const std::vector< double > &gamma, const std::vector< double > &omega, const std::vector< double > &phi, double horizon, double dispersion=1.0, bool cyclic=true, int Q=200)
NNPP.eptmp(alpha, gamma, omega, phi, horizon, dispersion, cyclic, Q): lambda(t) = exp(sum alpha_i t^i...
std::vector< Matrix< double > > sched_D1
Definition lang_types.h:980
static Distrib lognormal(const T &logmean, const T &logsigma)
static Distrib hyperexp(const T &p, const T &lambda1, const T &lambda2)
HyperExp(p, lambda1, lambda2): phase i chosen with probability p_i.
std::vector< Matrix< double > > sched_D0
Definition lang_types.h:980
static Distrib me(const std::vector< T > &alpha, const Matrix< T > &A)
ME(alpha, A): the matrix-exponential distribution, whose moments are the phase-type ones – k!
static Distrib nnpp_dist(const Nnpp &n)
The Distrib that carries an NNPP law.
static Distrib immediate()
The point mass at zero.
std::vector< T > phi_vec() const
Completion probabilities, MATLAB's getPhi: (D1 e) .
static Distrib erlang(const T &phase_rate, std::size_t r)
Erlang(alpha, r): r phases of rate alpha, as MATLAB's Erlang(phaseRate, nphases).
bool has_marked_schedule() const
static Distrib exp_mean(const T &m)
std::size_t max_batch_size() const
Largest batch size the schedule declares, or 1 when it carries no batch axis.
static Distrib mpht(const std::vector< T > &breakpoints, const std::vector< std::vector< T > > &alphas, const std::vector< Matrix< T > > &Ssegs, const std::vector< std::vector< std::vector< T > > > &exits, bool cyclic)
MPHt(breakpoints, {alpha_k}, {S_k}, {{s^(c)_k}}, cyclic), stored LOWERED to MMAPt form segment by seg...
Distrib with_defect(const T &pInf) const
dist.with_defect(pInf): shorthand for Defective(dist, pInf).
std::size_t phases() const
The order of the representation, MATLAB's sn.phases.
static void check_sched_generator(const std::string &who, const std::vector< Matrix< T > > &D0segs, const std::vector< std::vector< Matrix< T > > > &blocks)
Reject a schedule segment that is not a generator, the check MATLAB, the JAR and Python all apply and...
static Distrib coxian(const std::vector< T > &mu, const std::vector< T > &phi)
Coxian(mu, phi): phase i completes with probability phi(i) and otherwise moves to phase i+1.
bool is_prior() const
Definition lang_types.h:961
static Distrib discrete_sampler(const std::vector< T > &p, const std::vector< T > &x)
DiscreteSampler(p, x): the pmf p over the points x.
static Distrib mmpp(const Matrix< T > &Q, const std::vector< T > &lambda)
MMPP(Q, lambda): the Markov-modulated Poisson process, i.e.
static Distrib binomial(const T &n, const T &p)
Binomial(n, p).
static Distrib zipf(const T &s, std::size_t n)
Zipf(s, n) over the ranks 1..n, with the generalized harmonic moments H(s-1,n)/H(s,...
The MATLAB GlobalConstants, as reported by lineStart at its defaults.
Definition lang_types.h:822
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double ArcTol
Below this an off-diagonal entry is NO ARC of the phase / state graph.
Definition lang_types.h:827
static constexpr double Zero
Definition lang_types.h:825
static constexpr double CoarseTol
Definition lang_types.h:824
static constexpr double MaxInt
Stand-in for an unbounded COUNT, MATLAB GlobalConstants.MaxInt.
Definition lang_types.h:834
A LINE Distribution, as the model layer and sn carry it.
std::function< Distrib< T >(const T &)> factory
theta -> Distribution; the continuous form only.
bool continuous
True for the parameter-density form, false for the alternative-set form.
Distrib< T > param_dist
The law of the scalar parameter; the continuous form only.
std::vector< T > probabilities
std::vector< Distrib< T > > alternatives
The alternatives and their weights; the discrete form only.
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54