LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ldes_sampler.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_SOLVERS_LDES_LDES_SAMPLER_H
6#define LINE_SOLVERS_LDES_LDES_SAMPLER_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The variate generators of the native LDES engine.
12 *
13 * ONE SAMPLER PER (station, class) PAIR, built once and then advanced, which is
14 * what `Solver_ssj.initializeGenerators` does and is not an optimization: a
15 * MAP, a RAP and an ME carry a PHASE across successive samples, and rebuilding
16 * the generator per variate would restart that phase every time and silently
17 * turn a correlated process into a renewal one with the same marginal. The
18 * autocorrelation is the reason those processes are in the model at all, so
19 * losing it produces a run that looks converged and answers a different
20 * question.
21 *
22 * WHERE THE PARAMETERS COME FROM, transcribed from
23 * `createNonMarkovianArrivalGen` and `firingGenFromMeanScv`:
24 *
25 * - ERLANG, HYPEREXP, PH, APH, COXIAN, COX2, MAP, MMPP2, ME, RAP, DMAP read
26 * the (D0,D1) REPRESENTATION, so their higher moments are exactly the
27 * model's;
28 * - UNIFORM, GAMMA, WEIBULL, LOGNORMAL, PARETO read the MOMENT PAIR (mean,
29 * SCV) and invert it, because `sn.proc` carries an Erlang FIT for them
30 * rather than their own parameters (see _kb/09-ldes-and-cache.md);
31 * - DET, IMMEDIATE, REPLAYER, LOGLOGISTIC, and the counting families read
32 * their own parameters directly; a MASSATORIGIN samples zero with
33 * probability p0 and otherwise its inner law, and a DEFECTIVE is refused.
34 *
35 * A moment pair that no member of the family can realise is REFUSED by name.
36 * A non-negative uniform needs SCV <= 1/3; papering over that with a clamp
37 * would run a model with a different variance and report it as the user's.
38 */
39
40#include <algorithm>
41#include <cmath>
42#include <cstddef>
43#include <limits>
44#include <memory>
45#include <random>
46#include <string>
47#include <vector>
48
52#include "line/util/rng_ssj.h"
54#include "line/util/error.h"
55#include "line/util/matrix.h"
56
57namespace line {
58namespace ldes {
59namespace engine {
60
61/**
62 * The engine's randomness, in the SHAPE the Java engine uses it.
63 *
64 * `Solver_ssj` carries TWO generators wherever it samples, and which one serves
65 * depends on the family rather than on the call site:
66 *
67 * MRG32k3a stream = new MRG32k3a();
68 * stream.setSeed(LdesStreamSeeds.mrg32k3a(seed, offset));
69 * this.svcRng[i][k] = new java.util.Random(seed + offset);
70 *
71 * The SSJ `randvar` generators (Exponential, Erlang, Uniform, Weibull, Pareto,
72 * Lognormal, Gamma, Poisson, Binomial, Bernoulli) are built on the MRG STREAM;
73 * the Markovian families do not go through SSJ at all -- `MapSampleGen` calls
74 * `Map_sample.map_sample(D0, D1, 1, rng)` with the java.util.Random. So a C++
75 * engine that means to walk the same sample path needs both, seeded from the
76 * same (seed, offset), and must send each family to the same one. The MRG
77 * stream's six seeds are HASHED from (seed, offset) (`rng::SeedHash`, since
78 * equally spaced seed vectors give linearly dependent streams); the
79 * java.util.Random keeps `seed + offset`, whose seed scrambling and 48-bit
80 * state show no such dependence (u1 - 2*u2 + u3 over three spaced seeds is
81 * uniform to within its standard error).
82 *
83 * `mc` is the third generator and the one still out of step: `rap_sample` and
84 * `me_sample` take `pfqn::McRng` by reference, and the RAP/ME path has no SSJ
85 * or java.util.Random counterpart to align to yet.
86 */
87struct Rng {
88 rng::Mrg32k3a stream; ///< SSJ MRG32k3a: every renewal family
89 rng::JavaRandom aux; ///< java.util.Random: the Markovian samplers
90 pfqn::McRng mc; ///< the residual RAP/ME path, not yet aligned
91
92 /**
93 * A run seed and the TWO offsets the reference derives, one per generator.
94 *
95 * They are not always equal, which is why this takes both. At a SERVICE
96 * site `Solver_ssj` seeds the stream and the java.util.Random from the same
97 * `((numSources + svcIdx) * numClasses + k) * 10 + 1000`; at an ARRIVAL site
98 * the stream gets `(srcIdx * numClasses + k) * 10` and the Random the same
99 * expression PLUS 2000. Seeding both from one offset would put the
100 * Markovian arrival samplers on a stream the reference never uses.
101 */
102 Rng(long long seed, long long stream_offset, long long aux_offset)
103 : aux(seed + aux_offset), mc(static_cast<std::uint64_t>(seed + aux_offset)) {
104 stream.set_seed_offset(seed, stream_offset);
105 }
106
107 /** The common case, where the reference uses one offset for both. */
108 Rng(long long seed, long long offset) : Rng(seed, offset, offset) {}
109};
110
111/** Uniform on (0,1) off the MRG stream; `next_double` never returns 0. */
112inline double uniform01(Rng& g) { return g.stream.next_double(); }
113
114/**
115 * The phases one walked interval visited and how long it held each, filled by a
116 * sampler only while the sample-path export hands it one (`Sampler::set_trace`).
117 * Transcribes the reference's `jline.api.mam.PhaseTrace`. Recording reads the
118 * draws a walk already takes and consumes none, so a traced walk returns the
119 * same interval, bit for bit, as an untraced one.
120 */
122 std::vector<int> phase;
123 std::vector<double> dt;
124 int exit_phase = -1;
125 void clear() {
126 phase.clear();
127 dt.clear();
128 exit_phase = -1;
129 }
130 void add(int ph, double holding) {
131 phase.push_back(ph);
132 dt.push_back(holding);
133 }
134 void set_exit_phase(int ph) { exit_phase = ph; }
135 std::size_t size() const { return phase.size(); }
136 /** Sum of the holdings, in order, as the reference adds them. */
137 double total() const {
138 double s = 0.0;
139 for (double v : dt) s += v;
140 return s;
141 }
142};
143
144/**
145 * One variate generator, holding whatever state its family needs.
146 *
147 * Deliberately a tagged struct rather than a class hierarchy: the sampler is
148 * called once per event on the engine's hot path, and a virtual dispatch there
149 * costs more than the switch. The tag IS `ProcessType`, so a family added to
150 * the language shows up here as a missing case rather than as silence.
151 */
152class Sampler {
153public:
155
156 /** Build the generator of `d`; the (station, class) names are for diagnostics. */
157 template <class T>
158 Sampler(const lang::Distrib<T>& d, const std::string& where) : where_(where) {
159 type_ = d.type;
162 switch (type_) {
164 break;
166 require_mean();
167 rate_ = 1.0 / mean_;
168 break;
170 require_mean();
171 break;
173 // The reference serves an Immediate in 1e-8 time units, not in
174 // zero: a zero service time is an infinite rate the estimators
175 // cannot carry. See Distrib::immediate().
177 break;
179 for (const T& v : d.trace) trace_.push_back(num_traits<T>::to_double(v));
180 if (trace_.empty())
181 throw InputError("SolverLDES (native engine): the Replayer at " + where_ +
182 " carries no samples");
183 break;
185 require_moments();
186 const double half = mean_ * std::sqrt(3.0 * scv_);
187 a_ = mean_ - half;
188 b_ = mean_ + half;
189 if (!(a_ >= 0.0) || !(b_ > a_))
190 throw InputError("SolverLDES (native engine): the Uniform at " + where_ +
191 " implies a support reaching below zero; a non-negative "
192 "uniform requires an SCV of at most 1/3");
193 break;
194 }
196 require_moments();
197 a_ = 1.0 / scv_; // shape
198 b_ = mean_ * scv_; // SCALE, not the reference's rate
199 break;
201 require_moments();
202 const double c = std::sqrt(scv_);
203 a_ = std::pow(c, -1.086); // shape
204 b_ = mean_ / std::tgamma(1.0 + 1.0 / a_); // scale
205 if (!(a_ > 0.0) || !(b_ > 0.0))
206 throw InputError("SolverLDES (native engine): the Weibull at " + where_ +
207 " has unusable moments");
208 break;
209 }
211 require_moments();
212 const double c2p1 = scv_ + 1.0;
213 a_ = std::log(mean_ / std::sqrt(c2p1)); // mu
214 b_ = std::sqrt(std::log(c2p1)); // sigma
215 if (!(b_ > 0.0))
216 throw InputError("SolverLDES (native engine): the Lognormal at " + where_ +
217 " has a zero log-variance");
218 break;
219 }
221 // The port keeps the raw parameters, so they are read directly:
222 // params {alpha = scale, beta = shape}, MATLAB getParam order.
223 require_mean();
226 break;
228 // Zero with probability p0, else a draw of the inner law.
229 require_mean();
231 if (!d.inner)
232 throw InputError("SolverLDES (native engine): the MassAtOrigin at " + where_ +
233 " carries no inner law");
234 inner_ = std::make_shared<Sampler>(*d.inner, where_);
235 break;
237 throw InputError(ErrorKind{"Argument"},
238 "SolverLDES (native engine): the process at " + where_ + " is a Defective law, "
239 "which is infinite with probability pInf, so its mean is Inf and it cannot be "
240 "a service or interarrival time");
242 require_moments();
243 // SCV = 1/(a(a-2)) for a > 2, so a = 1 + sqrt(1 + 1/SCV), and the
244 // scale follows from mean = a*m/(a-1).
245 a_ = std::sqrt(1.0 + 1.0 / scv_) + 1.0; // shape
246 b_ = mean_ * (a_ - 1.0) / a_; // scale
247 break;
249 require_mean();
250 // Supported on {1,2,...}: the trial index of the first success,
251 // mean 1/p and SCV 1-p. SSJ's own Geometric counts FAILURES and
252 // would admit a zero-length interval.
253 a_ = 1.0 / mean_;
254 if (!(a_ > 0.0) || a_ > 1.0)
255 throw InputError("SolverLDES (native engine): the Geometric at " + where_ +
256 " has a success probability outside (0,1]");
257 break;
259 // The reference carries a DiscreteUniform as the moment pair
260 // {mean, SCV}, not as its bounds, so the bounds are recovered from
261 // the pair HERE TOO rather than read off `d.params`: the two
262 // engines must place the lattice identically, and the Java one has
263 // nothing but the moments. var = (w^2-1)/12 gives the integral
264 // width, and the mean then places it, which leaves a lower bound
265 // off the integers where the user put it.
266 require_moments();
267 const double var = scv_ * mean_ * mean_;
268 b_ = std::floor(std::sqrt(12.0 * var + 1.0) + 0.5); // width
269 a_ = mean_ - (b_ - 1.0) / 2.0; // lower bound
270 if (!(b_ >= 1.0))
271 throw InputError("SolverLDES (native engine): the DiscreteUniform at " +
272 where_ + " has moments no (min,max) pair realises");
273 if (!(a_ >= 0.0))
274 throw InputError("SolverLDES (native engine): the DiscreteUniform at " +
275 where_ + " reaches below zero");
276 break;
277 }
279 require_mean();
280 break;
282 if (!(mean_ >= 0.0) || !(mean_ <= 1.0))
283 throw InputError("SolverLDES (native engine): the Bernoulli at " + where_ +
284 " has a mean outside [0,1]");
285 break;
287 require_moments();
288 const double p = 1.0 - scv_ * mean_;
289 if (!(p > 0.0) || p > 1.0)
290 throw InputError("SolverLDES (native engine): the Binomial at " + where_ +
291 " has moments no (n,p) pair realises");
292 a_ = p;
293 b_ = std::floor(mean_ / p + 0.5);
294 break;
295 }
302 load_schedule(d);
303 break;
305 // Lewis-Shedler thinning plus SCIATA (nnpp.h). The stream state
306 // lives here, so a copied sampler starts a fresh stream.
307 if (!d.nnpp)
308 throw InputError("SolverLDES (native engine): the NNPP at " + where_ +
309 " carries no rate function");
310 nnpp_ = d.nnpp;
311 nnpp_stream_ = lang::Nnpp::Stream();
312 mean_ = nnpp_->mean();
313 break;
328 load_map(d);
329 break;
330 default:
331 throw UnsupportedError(ErrorKind{"Distribution"}, "SolverLDES (native engine): the process at " + where_ +
332 " is of a family this engine does not sample");
333 }
334 }
335
336 bool disabled() const { return type_ == lang::ProcessType::DISABLED; }
337 lang::ProcessType type() const { return type_; }
338 double mean() const { return mean_; }
339
340 /**
341 * One variate from a TIME-INHOMOGENEOUS process, given the instant it
342 * starts at.
343 *
344 * The families whose parameters depend on absolute time cannot be sampled
345 * from a duration alone, so this overload takes `from` and every other
346 * family ignores it. The engine calls it wherever a duration is drawn; a
347 * homogeneous process is unaffected.
348 */
349 double next_at(Rng& g, double from) {
350 if (nnpp_) return nnpp_gap(g, from);
351 if (!has_schedule_) return next(g);
352 return schedule_sample(g, from);
353 }
354
355 bool time_varying() const { return has_schedule_ || static_cast<bool>(nnpp_); }
356
357 /**
358 * AN NHPP SERVICE RUNS IN OPERATIONAL TIME (closed 2026-11-14).
359 *
360 * A time-varying service rate mu(t) completes a job when the cumulative
361 * intensity delivered to it reaches an Exp(1) budget, because NHPP
362 * completions are a unit-rate Poisson process in tau = int mu(u) du. The
363 * engine draws that budget once, with ONE uniform as the reference does
364 * (`-log(1 - u)`), carries every residual in tau, and converts to the wall
365 * clock only where it times a completion. That is exact under processor
366 * sharing, preemption and a state-dependent rescaling, none of which a wall
367 * duration sampled at the service start can survive: the old walk timed the
368 * job against mu(t) as if it held the whole server from start to finish.
369 * Only a SERVICE sampler takes this path; an NHPP arrival stream keeps
370 * `schedule_sample`. Transcribes `serviceWorkBetween`,
371 * `scheduleCumulativeIntensity` and `serviceWallAfterWork` of Solver_ssj.
372 */
373 bool op_time() const { return type_ == lang::ProcessType::NHPP && has_schedule_; }
374
375 /**
376 * The Exp(1) operational-time budget of one service, one uniform drawn off
377 * the java.util.Random (`aux`), as the reference draws it off `serviceRng`
378 * rather than off the MRG stream.
379 */
380 double op_budget(Rng& g) const { return -std::log(1.0 - g.aux.next_double()); }
381
382 /** int_{b0}^{t} mu(u) du, cyclic with the horizon as period or clamped. */
383 double op_cum_intensity(double t) const {
384 const std::size_t n = segs_.size();
385 const double b0 = bp_[0];
386 const double horizon = bp_[n] - b0;
387 double total = 0.0;
388 for (std::size_t i = 0; i < n; ++i) total += op_rate(i) * (bp_[i + 1] - bp_[i]);
389 const double x = t - b0;
390 double mass, rem;
391 if (cyclic_) {
392 const double periods = std::floor(x / horizon);
393 rem = x - periods * horizon;
394 mass = periods * total;
395 } else if (x <= 0.0) {
396 return 0.0;
397 } else if (x >= horizon) {
398 return total;
399 } else {
400 rem = x;
401 mass = 0.0;
402 }
403 double seg_start = 0.0;
404 for (std::size_t i = 0; i < n; ++i) {
405 const double len = bp_[i + 1] - bp_[i];
406 if (rem <= seg_start + len) {
407 mass += op_rate(i) * (rem - seg_start);
408 break;
409 }
410 mass += op_rate(i) * len;
411 seg_start += len;
412 }
413 return mass;
414 }
415
416 /** Operational time delivered at full share between two wall instants. */
417 double op_work_between(double t0, double t1) const {
418 if (t1 <= t0) return 0.0;
419 return op_cum_intensity(t1) - op_cum_intensity(t0);
420 }
421
422 /**
423 * The wall instant at which `work` units of operational time have been
424 * delivered since t0, or +infinity when a non-cyclic schedule runs out
425 * first ("never fires").
426 */
427 double op_wall_after(double t0, double work) const {
428 if (work <= 0.0) return t0;
429 const std::size_t n = segs_.size();
430 const double b0 = bp_[0];
431 const double horizon = bp_[n] - b0;
432 double offset = t0 - b0;
433 if (cyclic_) {
434 offset = std::fmod(offset, horizon);
435 if (offset < 0.0) offset += horizon;
436 } else if (offset >= horizon) {
437 return std::numeric_limits<double>::infinity();
438 } else if (offset < 0.0) {
439 offset = 0.0;
440 }
441 double pos = b0 + offset;
442 std::size_t idx = 0;
443 while (idx + 1 < n && pos >= bp_[idx + 1]) ++idx;
444 double residual = work;
445 double elapsed = 0.0;
446 for (;;) {
447 const double in_seg = bp_[idx + 1] - pos;
448 const double mass = op_rate(idx) * in_seg;
449 if (op_rate(idx) > 0.0 && mass >= residual) return t0 + elapsed + residual / op_rate(idx);
450 residual -= mass;
451 elapsed += in_seg;
452 ++idx;
453 if (idx >= n) {
454 if (!cyclic_) return std::numeric_limits<double>::infinity();
455 idx = 0;
456 }
457 pos = bp_[idx];
458 }
459 }
460
461 /**
462 * One variate. Advances whatever phase the family carries.
463 *
464 * EVERY RENEWAL FAMILY BUT THE ERLANG COSTS EXACTLY ONE UNIFORM off the MRG
465 * stream, which is not an optimization but the reference's behaviour: SSJ's
466 * instance generators invert, and a family that drew twice would shift
467 * every later event in the run. The quantiles live in
468 * `ldes_ssj_variates.h` and are pinned there against SSJ's own output. The
469 * Erlang is the exception, and deliberately so: it costs k uniforms in both
470 * engines because the Gamma inversion SSJ used is not reproducible across
471 * JVM releases.
472 */
473 double next(Rng& g) {
474 // An NNPP has no duration law apart from its own clock: continue the
475 // stream from its last arrival.
476 if (nnpp_) return nnpp_gap(g, nnpp_stream_.first ? 0.0 : nnpp_stream_.t_last);
477 return resolve_zero_atom(draw(g));
478 }
479
480 /**
481 * The reference's `resolveZeroAtom`: the discrete laws supported on
482 * {0,1,...} can return a zero-length interval, and a zero-length service is
483 * an infinite rate no estimator carries. `Immediate` is exactly what a
484 * zero-length interval denotes elsewhere in the engine, so the atom is
485 * served at that scale. Under SLOTTED mode 1/Immediate is not a lattice
486 * point, so `slot_snap` refuses the sample rather than inventing one, which
487 * is the refusal the reference raises in its own words.
488 */
489 double resolve_zero_atom(double v) const {
490 if (v != 0.0) return v;
491 switch (type_) {
498 default:
499 return v;
500 }
501 }
502
503private:
504 /**
505 * The gap from `from` to the next NNPP arrival. The stream advances on its
506 * own clock; a non-cyclic process past its horizon returns 0, which ends the
507 * stream exactly as an exhausted non-cyclic NHPP does.
508 */
509 double nnpp_gap(Rng& g, double from) {
510 auto unif = [&g]() { return uniform01(g); };
511 const double t = nnpp_->next_arrival(nnpp_stream_, unif);
512 if (!std::isfinite(t)) return 0.0;
513 const double gap = t - from;
514 return gap > 0.0 ? gap : std::numeric_limits<double>::denorm_min();
515 }
516
517 double draw(Rng& g) {
518 switch (type_) {
520 // SSJ's ExponentialDist.inverseF is -log1p(-u)/lambda, which is
521 // NOT -log(u)/lambda: they differ in the last bits for small u,
522 // exactly where an interarrival time matters most.
523 return ssj::exponential_inverse(rate_, uniform01(g));
526 return mean_;
528 const double v = trace_[trace_idx_];
529 trace_idx_ = (trace_idx_ + 1) % trace_.size();
530 // The reference floors a non-positive trace entry rather than
531 // scheduling an event in the past.
532 return (v <= 0.0) ? 1e-9 : v;
533 }
535 return ssj::uniform_inverse(a_, b_, uniform01(g));
537 // b_ is the SCALE here; SSJ's GammaGen takes the RATE.
538 return ssj::gamma_inverse(a_, 1.0 / b_, uniform01(g));
540 // b_ is the SCALE; SSJ's WeibullGen takes lambda = 1/scale.
541 return ssj::weibull_inverse(a_, 1.0 / b_, 0.0, uniform01(g));
543 return ssj::lognormal_inverse(a_, b_, uniform01(g));
545 return ssj::pareto_inverse(a_, b_, uniform01(g));
547 // Inverse CDF, alpha (u/(1-u))^(1/beta): one uniform, as the
548 // other renewal families.
549 const double u = uniform01(g);
550 return a_ * std::pow(u / (1.0 - u), 1.0 / b_);
551 }
553 if (uniform01(g) < a_) return 0.0;
554 return inner_->draw(g);
556 if (a_ >= 1.0) {
557 uniform01(g); // keep the stream consumption independent of p
558 return 1.0;
559 }
560 return std::ceil(std::log(1.0 - uniform01(g)) / std::log(1.0 - a_));
561 }
563 return ssj::uniform_int_inverse(a_, b_, uniform01(g));
565 return ssj::poisson_inverse(mean_, uniform01(g));
567 return ssj::bernoulli_inverse(mean_, uniform01(g));
569 return ssj::binomial_inverse(static_cast<int>(b_), a_, uniform01(g));
571 // An Erlang costs k uniforms, one per phase, which is the one
572 // renewal family that does not invert in a single draw. The
573 // reference used to invert the Gamma here, but that inversion
574 // is iterative and its last bits move between JVM releases, so
575 // a seeded run was not reproducible across JVMs; both engines
576 // now convolve exponentials instead.
577 if (erlang_k_ <= 0) return next_markovian(g);
578 double sum = 0.0;
579 for (int i = 0; i < erlang_k_; ++i)
580 sum += ssj::exponential_inverse(erlang_rate_, uniform01(g));
581 return sum;
582 }
583 default:
584 return next_markovian(g);
585 }
586 }
587
588public:
589 /**
590 * The phase the process is in, for a caller that must carry it across a
591 * preemption or across successive executions of an LQN entry. -1 when the
592 * family has no phase.
593 */
594 int phase() const { return has_phase_ ? static_cast<int>(phase_) : -1; }
595 /**
596 * Sample-path export: the walk phase as the reference's `getPhase()` reports
597 * it, 0 for a one-phase process, -1 before the first walk has drawn one.
598 */
599 int sp_phase() const {
600 if (map_.order() <= 1) return 0;
601 return phase_known_ ? static_cast<int>(phase_) : -1;
602 }
603 /** Phases of an Erlang recovered for convolution, 0 when none was. */
604 int erlang_k() const { return erlang_k_; }
605 /** Order of the (D0,D1) representation, 0 for a family that carries none. */
606 std::size_t map_order() const { return map_.order(); }
607 /**
608 * Sample-path export: the trace the next MAP/PH/MMAP/BMAP walk fills, or
609 * null (the default) to record nothing. The engine sets it around one draw.
610 */
611 void set_trace(PhaseTrace* t) { ptrace_ = t; }
612 /**
613 * The 1-based mark of the interval last returned by `next`/`next_at`, or 0 when
614 * this process carries none. At a Source the engine reads it to pick the class of
615 * the arriving job, exactly as `Solver_ssj` consumes `arrivalPendingMark`.
616 */
617 int last_mark() const { return last_mark_; }
618 /**
619 * How many jobs the epoch last returned by `next`/`next_at` releases, or 1 when
620 * this process carries no batch axis. At a Source the engine reads it to release
621 * that many jobs at one instant, exactly as `Solver_ssj` consumes
622 * `arrivalBatchSize`; at a bulk server it is how many completions the firing
623 * clears.
624 */
625 int last_batch() const { return last_batch_ > 0 ? last_batch_ : 1; }
626 bool marked() const { return !mark_.empty() || !seg_mark_.empty(); }
627 /** True when the process carries its OWN batch sizes: a BMAP or a BMMAPt. */
628 bool batched() const { return !batch_.empty() || !seg_batch_.empty(); }
629 void set_phase(int p) {
630 if (has_phase_ && p >= 0 && static_cast<std::size_t>(p) < map_.order()) {
631 phase_ = static_cast<std::size_t>(p);
632 phase_known_ = true;
633 }
634 }
635
636private:
637 void require_mean() const {
638 if (!(mean_ > 0.0) || !std::isfinite(mean_))
639 throw InputError("SolverLDES (native engine): the process at " + where_ +
640 " has a mean that is neither finite nor positive");
641 }
642 void require_moments() const {
643 require_mean();
644 if (!(scv_ > 0.0) || !std::isfinite(scv_))
645 throw InputError("SolverLDES (native engine): the process at " + where_ +
646 " has an SCV that is neither finite nor positive");
647 }
648
649 template <class T>
650 void load_map(const lang::Distrib<T>& d) {
651 if (d.D0.rows() == 0 || d.D0.rows() != d.D1.rows())
652 throw InputError("SolverLDES (native engine): the process at " + where_ +
653 " declares no (D0,D1) representation to sample");
654 const std::size_t K = d.D0.rows();
655 pie_.clear();
656 map_.D0 = Matrix<double>(K, K, 0.0);
657 map_.D1 = Matrix<double>(K, K, 0.0);
658 for (std::size_t i = 0; i < K; ++i)
659 for (std::size_t j = 0; j < K; ++j) {
660 map_.D0(i, j) = num_traits<T>::to_double(d.D0(i, j));
661 map_.D1(i, j) = num_traits<T>::to_double(d.D1(i, j));
662 }
663 // THE MOMENTS OF A (D0,D1) PROCESS COME FROM THE PAIR, not from the
664 // Distrib's own fields: `Distrib::map_dist` leaves mean 0 and SCV 1 as
665 // placeholders, so reading them would give this station a zero mean
666 // service time and a utilization computed against nothing.
667 if (!(mean_ > 0.0)) {
668 mean_ = num_traits<T>::to_double(mam::map_mean(map_));
669 if (!(mean_ > 0.0))
670 throw InputError("SolverLDES (native engine): the process at " + where_ +
671 " has a non-positive mean under its (D0,D1) representation");
672 }
673 // THE PER-MARK BLOCKS. `d.D1` is the aggregate sum_k D1k, which is what the
674 // interval walk uses; `Dmark` tells the marks apart once a D1 transition has
675 // fired. An MPH arrives here already lowered (D0 = S, D1k = s_k*alpha), so
676 // the same blocks serve it and no separate renewal path is needed.
677 mark_.clear();
678 batch_.clear();
680 for (const Matrix<T>& Dk : d.Dmark) {
681 Matrix<double> m(K, K, 0.0);
682 for (std::size_t i = 0; i < K; ++i)
683 for (std::size_t j = 0; j < K; ++j)
684 m(i, j) = num_traits<T>::to_double(Dk(i, j));
685 mark_.push_back(m);
686 }
687 }
688 // A BMAP OVERLOADS THE SAME FIELD WITH BATCH SIZES: `Dmark[b]` is the block
689 // that releases b+1 jobs. They used to be read into `mark_` and never
690 // consulted, because `mark_` is filled only for a marked stationary process
691 // and nothing else looked -- so this engine answered a BMAP model as its
692 // AGGREGATE MAP, every batch collapsed to one job, in silence. The blocks now
693 // drive `next_bmap_java`, which is the transcription of the reference's
694 // `Map_sample.BmapSampler`.
695 if (type_ == lang::ProcessType::BMAP) {
696 for (const Matrix<T>& Db : d.Dmark) {
697 Matrix<double> m(K, K, 0.0);
698 for (std::size_t i = 0; i < K; ++i)
699 for (std::size_t j = 0; j < K; ++j)
700 m(i, j) = num_traits<T>::to_double(Db(i, j));
701 batch_.push_back(m);
702 }
703 }
704 // ONLY the genuinely correlated families carry a phase between samples.
705 // A PH, an Erlang, a HyperExp and a Coxian are RENEWAL: restarting them
706 // from the entry law each time is what makes successive services
707 // independent, and carrying the phase instead would introduce a
708 // correlation the model does not have.
709 has_phase_ = (type_ == lang::ProcessType::MAP || type_ == lang::ProcessType::MMPP2 ||
710 type_ == lang::ProcessType::RAP ||
713 // ONCE PER STATION, not once per event: the table costs a matrix
714 // exponential and a thousand row-vector products, and every service at
715 // this station then inverts by binary search.
716 if (type_ == lang::ProcessType::ME)
717 me_.reset(new mam::MeSampler<double>(map_));
718 if (type_ == lang::ProcessType::ERLANG) recover_erlang();
719 }
720
721 /**
722 * Recovers (k, lambda) from an Erlang's (D0,D1) so `next` can convolve k
723 * exponentials off the MRG stream instead of walking the phases off the
724 * auxiliary java.util.Random. The reference engine samples the same
725 * convolution, so the two engines then agree sample for sample on an
726 * Erlang model; walking the phases does not, because it draws 2k uniforms
727 * from a different stream. A cell that does not carry the bidiagonal
728 * equal-rate structure of an Erlang is left to the MAP walk rather than
729 * approximated.
730 */
731 void recover_erlang() {
732 erlang_k_ = 0;
733 const std::size_t n = map_.order();
734 if (n == 0) return;
735 const double lambda = -map_.D0(0, 0);
736 if (!(lambda > 0.0)) return;
737 const double tol = 1e-12 * lambda;
738 for (std::size_t i = 0; i < n; ++i) {
739 if (std::fabs(-map_.D0(i, i) - lambda) > tol) return;
740 for (std::size_t j = 0; j < n; ++j) {
741 if (j == i) continue;
742 const double want = (j == i + 1) ? lambda : 0.0;
743 if (std::fabs(map_.D0(i, j) - want) > tol) return;
744 }
745 // Only the last phase completes, and it completes into phase 0.
746 for (std::size_t j = 0; j < n; ++j) {
747 const double want = (i + 1 == n && j == 0) ? lambda : 0.0;
748 if (std::fabs(map_.D1(i, j) - want) > tol) return;
749 }
750 }
751 erlang_k_ = static_cast<int>(n);
752 erlang_rate_ = lambda;
753 }
754
755 /**
756 * One interval from a MAP, transcribed from `Map_sample.MapSampler.next`.
757 *
758 * THE GENERATOR IS java.util.Random, NOT the MRG stream. `MapSampleGen`
759 * extends SSJ's `RandomVariateGen` and is handed the stream like every other
760 * generator, but its `nextDouble` ignores it and calls
761 * `Map_sample.map_sample(D0, D1, 1, rng)` with the java.util.Random built
762 * beside it. Drawing this family off the MRG stream would both use the wrong
763 * numbers and desynchronize every renewal draw that follows.
764 *
765 * The walk itself: hold the phase across calls (it is only advanced here,
766 * so an idle server freezes its service process), draw the initial phase
767 * from map_pie on the first call, then alternate an exponential holding
768 * time at rate -D0(i,i) with a choice among the 2n competing transitions,
769 * ending when the chosen one is a D1 (an event) rather than a D0 (a hidden
770 * phase change). One uniform for the holding time and one for the choice,
771 * per step, in that order.
772 */
773 double next_map_java(Rng& g) {
774 const std::size_t n = map_.order();
775 if (ptrace_) ptrace_->clear();
776 if (n == 1) {
777 // The reference's exponential shortcut: -log(u)/lambda, with plain
778 // log and not log1p, because Map_sample spells it that way.
779 const double lambda = map_.D1(0, 0);
780 const double x = -std::log(g.aux.next_double()) / lambda;
781 if (ptrace_) {
782 ptrace_->add(0, x);
783 ptrace_->set_exit_phase(0);
784 }
785 return x;
786 }
787 if (!phase_known_) {
788 const std::vector<double> pie = mam::map_pie(map_);
789 double sum = 0.0;
790 const double r = g.aux.next_double();
791 phase_ = n - 1;
792 for (std::size_t i = 0; i < n; ++i) {
793 sum += pie[i];
794 if (r < sum) {
795 phase_ = i;
796 break;
797 }
798 }
799 phase_known_ = true;
800 }
801 double sample = 0.0;
802 std::vector<double> row(2 * n, 0.0);
803 bool go = true;
804 while (go) {
805 const double rate = -map_.D0(phase_, phase_);
806 const double holding = -std::log(g.aux.next_double()) / rate;
807 sample += holding;
808 if (ptrace_) ptrace_->add(static_cast<int>(phase_), holding);
809 for (std::size_t k = 0; k < n; ++k) {
810 row[k] = map_.D0(phase_, k);
811 row[n + k] = map_.D1(phase_, k);
812 }
813 row[phase_] = 0.0; // the diagonal is the exit rate, not a target
814 std::size_t next_state = 2 * n - 1;
815 double sum = 0.0;
816 const double r = g.aux.next_double();
817 for (std::size_t j = 0; j < 2 * n; ++j) {
818 sum += row[j] / rate;
819 if (r < sum) {
820 if (j >= n) {
821 next_state = j - n;
822 go = false;
823 if (ptrace_) ptrace_->set_exit_phase(static_cast<int>(next_state));
824 } else {
825 next_state = j;
826 go = true;
827 }
828 break;
829 }
830 }
831 if (next_state >= 2 * n - 1 && go) {
832 // The loop above fell through: the reference leaves nextState at
833 // its initialized 2n-1 and continues, which is a D1 transition.
834 next_state = n - 1;
835 go = false;
836 }
837 phase_ = (next_state < n) ? next_state : next_state - n;
838 }
839 return sample;
840 }
841
842 /**
843 * The 1-based mark of an arrival firing on transition (i, j), drawn with
844 * probability D1k(i,j)/D1_agg(i,j). Transcribes `Mmap_sample.MmapSampler.sampleMark`,
845 * including its fallbacks: an unmarked process reports mark 1, and so does a
846 * transition on which every block is zero.
847 */
848 int sample_mark(std::size_t i, std::size_t j, Rng& g) {
849 const std::size_t C = mark_.size();
850 if (C == 0) return 1;
851 double total = 0.0;
852 for (std::size_t c = 0; c < C; ++c) total += std::max(0.0, mark_[c](i, j));
853 if (!(total > 0.0)) return 1;
854 const double r = g.aux.next_double() * total;
855 double sum = 0.0;
856 for (std::size_t c = 0; c < C; ++c) {
857 sum += std::max(0.0, mark_[c](i, j));
858 if (r < sum) return static_cast<int>(c) + 1;
859 }
860 return static_cast<int>(C);
861 }
862
863 /**
864 * One marked interval, transcribed from `Mmap_sample.MmapSampler.next`.
865 *
866 * The interval walk is the unmarked one over the aggregate pair; the mark is a
867 * SECOND draw taken on the transition that ended it, so an unmarked and a marked
868 * process of the same pair do not share a sample path past the first arrival.
869 * That is the reference's own ordering and must not be reordered to save a draw.
870 *
871 * Unlike `next_map_java` this does NOT carry the reference's fall-through repair:
872 * `MmapSampler` leaves nextState at its initialized 2n-1 and reads it as a D1
873 * transition into phase n-1, which is what is transcribed here.
874 */
875 double next_mmap_java(Rng& g) {
876 const std::size_t n = map_.order();
877 if (ptrace_) ptrace_->clear();
878 if (n == 1) {
879 const double lambda = map_.D1(0, 0);
880 const double time = -std::log(g.aux.next_double()) / lambda;
881 if (ptrace_) {
882 ptrace_->add(0, time);
883 ptrace_->set_exit_phase(0);
884 }
885 last_mark_ = sample_mark(0, 0, g);
886 return time;
887 }
888 if (!phase_known_) {
889 const std::vector<double> pie = mam::map_pie(map_);
890 double sum = 0.0;
891 const double r = g.aux.next_double();
892 phase_ = n - 1;
893 for (std::size_t i = 0; i < n; ++i) {
894 sum += pie[i];
895 if (r < sum) {
896 phase_ = i;
897 break;
898 }
899 }
900 phase_known_ = true;
901 }
902 double sample = 0.0;
903 std::vector<double> row(2 * n, 0.0);
904 while (true) {
905 const double rate = -map_.D0(phase_, phase_);
906 const double holding = -std::log(g.aux.next_double()) / rate;
907 sample += holding;
908 if (ptrace_) ptrace_->add(static_cast<int>(phase_), holding);
909 for (std::size_t k = 0; k < n; ++k) {
910 row[k] = map_.D0(phase_, k);
911 row[n + k] = map_.D1(phase_, k);
912 }
913 row[phase_] = 0.0; // the diagonal is the exit rate, not a target
914 std::size_t next_state = 2 * n - 1;
915 double sum = 0.0;
916 const double r = g.aux.next_double();
917 for (std::size_t j = 0; j < 2 * n; ++j) {
918 sum += row[j] / rate;
919 if (r < sum) {
920 next_state = j;
921 break;
922 }
923 }
924 if (next_state >= n) {
925 const std::size_t dest = next_state - n;
926 if (ptrace_) ptrace_->set_exit_phase(static_cast<int>(dest));
927 last_mark_ = sample_mark(phase_, dest, g);
928 phase_ = dest;
929 return sample;
930 }
931 phase_ = next_state;
932 }
933 }
934
935 /**
936 * One BATCH interval, transcribed from `Map_sample.BmapSampler.next`.
937 *
938 * Unlike the marked walk, the batch label is NOT a second draw: the block that
939 * fires decides both the destination phase and how many jobs the epoch releases,
940 * so the row scanned is D0 followed by the batch blocks BATCH-MAJOR then
941 * destination, which is the reference's own `row[nphases + b*nphases + k]`
942 * indexing. Reordering it would keep the same law and lose the sample path.
943 *
944 * The one-phase case is the reference's fast path and takes TWO draws: the
945 * exponential interval, then the batch size against the per-batch rates.
946 */
947 double next_bmap_java(Rng& g) {
948 const std::size_t n = map_.order();
949 const std::size_t B = batch_.size();
950 last_batch_ = 1;
951 if (ptrace_) ptrace_->clear();
952 if (n == 1) {
953 const double lambda = map_.D1(0, 0);
954 const double time = -std::log(g.aux.next_double()) / lambda;
955 if (ptrace_) {
956 ptrace_->add(0, time);
957 ptrace_->set_exit_phase(0);
958 }
959 double total = 0.0;
960 for (std::size_t b = 0; b < B; ++b) total += batch_[b](0, 0);
961 if (total > 0.0) {
962 const double r = g.aux.next_double() * total;
963 double cum = 0.0;
964 for (std::size_t b = 0; b < B; ++b) {
965 cum += batch_[b](0, 0);
966 if (r < cum) {
967 last_batch_ = static_cast<int>(b) + 1;
968 break;
969 }
970 }
971 }
972 return time;
973 }
974 if (!phase_known_) {
975 const std::vector<double> pie = mam::map_pie(map_);
976 double sum = 0.0;
977 const double r = g.aux.next_double();
978 phase_ = n - 1;
979 for (std::size_t i = 0; i < n; ++i) {
980 sum += pie[i];
981 if (r < sum) {
982 phase_ = i;
983 break;
984 }
985 }
986 phase_known_ = true;
987 }
988 const std::size_t cols = n + B * n;
989 std::vector<double> row(cols, 0.0);
990 double sample = 0.0;
991 while (true) {
992 const double rate = -map_.D0(phase_, phase_);
993 const double holding = -std::log(g.aux.next_double()) / rate;
994 sample += holding;
995 if (ptrace_) ptrace_->add(static_cast<int>(phase_), holding);
996 for (std::size_t k = 0; k < n; ++k) row[k] = map_.D0(phase_, k);
997 row[phase_] = 0.0; // the diagonal is the exit rate, not a target
998 for (std::size_t b = 0; b < B; ++b)
999 for (std::size_t k = 0; k < n; ++k) row[n + b * n + k] = batch_[b](phase_, k);
1000 std::size_t next_state = phase_;
1001 bool fired = false;
1002 double sum = 0.0;
1003 const double r = g.aux.next_double();
1004 for (std::size_t j = 0; j < cols; ++j) {
1005 sum += row[j] / rate;
1006 if (r < sum) {
1007 if (j < n) {
1008 next_state = j;
1009 } else {
1010 const std::size_t idx = j - n;
1011 last_batch_ = static_cast<int>(idx / n) + 1;
1012 next_state = idx % n;
1013 fired = true;
1014 }
1015 break;
1016 }
1017 }
1018 phase_ = next_state;
1019 if (fired) {
1020 if (ptrace_) ptrace_->set_exit_phase(static_cast<int>(phase_));
1021 return sample;
1022 }
1023 }
1024 }
1025
1026 /**
1027 * One RENEWAL phase-type variate, transcribed from the reference's STATIC
1028 * `Map_sample.map_sample(D0, D1, 1, rng)`, which is what `Solver_ssj` calls
1029 * for a PH, APH, HyperExp, Coxian or Cox2 service or arrival (closed
1030 * 2026-11-14: these families used to share `next_map_java`, whose phase is
1031 * carried across calls, so after the first sample this engine skipped the
1032 * entry draw the reference takes on EVERY call and the two streams parted).
1033 *
1034 * Per call: the order-1 shortcut -log(u)/lambda; otherwise a FRESH entry
1035 * phase from map_pie, whose fall-through default is `pie.getNumRows()`,
1036 * i.e. phase 1, then the holding/choice walk of `next_map_java` with no
1037 * fall-through repair (the reference has none here). Nothing is carried:
1038 * `phase_` is left alone, since the reference keeps no sampler for these
1039 * families and so reports no phase for them.
1040 */
1041 double next_ph_renewal_java(Rng& g) {
1042 const std::size_t n = map_.order();
1043 if (ptrace_) ptrace_->clear();
1044 if (n == 1) {
1045 const double lambda = map_.D1(0, 0);
1046 const double x = -std::log(g.aux.next_double()) / lambda;
1047 if (ptrace_) {
1048 ptrace_->add(0, x);
1049 ptrace_->set_exit_phase(0);
1050 }
1051 return x;
1052 }
1053 if (pie_.size() != n) pie_ = mam::map_pie(map_);
1054 std::size_t state = 1; // `pie.getNumRows()` of a 1 x n row vector
1055 {
1056 double sum = 0.0;
1057 const double r = g.aux.next_double();
1058 for (std::size_t i = 0; i < n; ++i) {
1059 sum += pie_[i];
1060 if (r < sum) {
1061 state = i;
1062 break;
1063 }
1064 }
1065 }
1066 double sample = 0.0;
1067 std::vector<double> row(2 * n, 0.0);
1068 bool go = true;
1069 while (go) {
1070 const double rate = -map_.D0(state, state);
1071 const double holding = -std::log(g.aux.next_double()) / rate;
1072 sample += holding;
1073 if (ptrace_) ptrace_->add(static_cast<int>(state), holding);
1074 for (std::size_t k = 0; k < n; ++k) {
1075 row[k] = map_.D0(state, k);
1076 row[n + k] = map_.D1(state, k);
1077 }
1078 row[state] = 0.0;
1079 std::size_t next_state = 2 * n - 1;
1080 double sum = 0.0;
1081 const double r = g.aux.next_double();
1082 for (std::size_t j = 0; j < 2 * n; ++j) {
1083 sum += row[j] / rate;
1084 if (r < sum) {
1085 if (j >= n) {
1086 next_state = j - n;
1087 go = false;
1088 if (ptrace_) ptrace_->set_exit_phase(static_cast<int>(next_state));
1089 } else {
1090 next_state = j;
1091 }
1092 break;
1093 }
1094 }
1095 // A fall-through leaves next_state at 2n-1, which the reference
1096 // would then index out of range; only rounding in the cumulative
1097 // sum reaches it, and the nearest valid reading is its last phase.
1098 state = (next_state < n) ? next_state : n - 1;
1099 }
1100 return sample;
1101 }
1102
1103 double next_markovian(Rng& g) {
1104 std::vector<double> out;
1105 if (type_ == lang::ProcessType::MAP || type_ == lang::ProcessType::MMPP2) {
1106 return next_map_java(g);
1107 }
1108 if (type_ == lang::ProcessType::PH || type_ == lang::ProcessType::APH ||
1111 return next_ph_renewal_java(g);
1112 }
1114 return next_mmap_java(g);
1115 }
1116 if (type_ == lang::ProcessType::BMAP && !batch_.empty()) {
1117 return next_bmap_java(g);
1118 }
1119 if (type_ == lang::ProcessType::ME) {
1120 // An ME is a RENEWAL process: the entry law is the same at every
1121 // sample, so the inversion table built in `load_map` serves them
1122 // all. Routing it through `rap_sample` instead cost a matrix
1123 // exponential per bisection step and ran 140x slower than the Java
1124 // engine, which is a wall-clock timeout rather than a slow answer.
1125 return me_->next(g.mc);
1126 }
1127 if (type_ == lang::ProcessType::RAP) {
1128 // A RAP's state is the real-valued ENTRY LAW, not a discrete phase,
1129 // so it is chained through `a_out` rather than recovered from a
1130 // trace.
1131 std::vector<double> a_next;
1132 out = mam::rap_sample(map_, 1, g.mc, entry_, &a_next);
1133 entry_ = a_next;
1134 } else {
1135 mam::SampleTrace tr;
1136 std::vector<double> start;
1137 if (has_phase_ && phase_known_) {
1138 start.assign(map_.order(), 0.0);
1139 start[phase_] = 1.0;
1140 }
1141 out = mam::map_sample(map_, 1, g.mc, start, &tr);
1142 if (has_phase_ && !tr.last.empty()) {
1143 phase_ = tr.last[0];
1144 phase_known_ = true;
1145 }
1146 }
1147 if (out.empty()) return 0.0;
1148 // A discrete-time MAP samples a SLOT COUNT, which is already the
1149 // interval on the lattice; the continuous families sample the interval
1150 // directly. Neither needs rescaling here.
1151 return out[0];
1152 }
1153
1154 template <class T>
1155 void load_schedule(const lang::Distrib<T>& d) {
1156 if (!d.has_schedule())
1157 throw InputError("SolverLDES (native engine): the time-inhomogeneous process at " +
1158 where_ + " carries no segment schedule");
1159 for (const T& b : d.sched_bp) bp_.push_back(num_traits<T>::to_double(b));
1160 if (bp_.size() != d.sched_D0.size() + 1)
1161 throw InputError("SolverLDES (native engine): the schedule at " + where_ +
1162 " has a boundary vector that does not bound its segments");
1163 for (std::size_t k = 0; k < d.sched_D0.size(); ++k) {
1164 const std::size_t H = d.sched_D0[k].rows();
1165 mam::Map<double> seg;
1166 seg.D0 = Matrix<double>(H, H, 0.0);
1167 seg.D1 = Matrix<double>(H, H, 0.0);
1168 for (std::size_t a = 0; a < H; ++a)
1169 for (std::size_t b2 = 0; b2 < H; ++b2) {
1170 seg.D0(a, b2) = num_traits<T>::to_double(d.sched_D0[k](a, b2));
1171 seg.D1(a, b2) = num_traits<T>::to_double(d.sched_D1[k](a, b2));
1172 }
1173 segs_.push_back(seg);
1174 }
1175 // The per-mark blocks, segment-major here (`seg_mark_[k][c]`) because the walk
1176 // scans one segment at a time; the wire and the Distrib are mark-major.
1177 seg_mark_.clear();
1178 if (d.has_marked_schedule()) {
1179 const std::size_t C = d.sched_Dmark.size();
1180 for (std::size_t k = 0; k < d.sched_D0.size(); ++k) {
1181 const std::size_t H = d.sched_D0[k].rows();
1182 std::vector<Matrix<double>> per_mark;
1183 for (std::size_t c = 0; c < C; ++c) {
1184 Matrix<double> m(H, H, 0.0);
1185 for (std::size_t a = 0; a < H; ++a)
1186 for (std::size_t b2 = 0; b2 < H; ++b2)
1187 m(a, b2) = num_traits<T>::to_double(d.sched_Dmark[c][k](a, b2));
1188 per_mark.push_back(m);
1189 }
1190 seg_mark_.push_back(per_mark);
1191 }
1192 }
1193 // The batch blocks, transposed the same way: the Distrib is mark-major then
1194 // batch then segment, the walk is segment-major, so this is
1195 // `seg_batch_[k][c][b]`. `seg_mark_` stays the batch-AGGREGATED per-mark
1196 // schedule and `segs_[k].D1` the aggregate over marks as well, so a consumer
1197 // that ignores batches walks exactly the MMAPt this hides down to.
1198 seg_batch_.clear();
1199 if (d.has_batch_schedule()) {
1200 const std::size_t C = d.sched_Dbatch.size();
1201 const std::size_t B = d.sched_Dbatch[0].size();
1202 for (std::size_t k = 0; k < d.sched_D0.size(); ++k) {
1203 const std::size_t H = d.sched_D0[k].rows();
1204 std::vector<std::vector<Matrix<double>>> per_mark;
1205 for (std::size_t c = 0; c < C; ++c) {
1206 std::vector<Matrix<double>> per_batch;
1207 for (std::size_t b = 0; b < B; ++b) {
1208 Matrix<double> m(H, H, 0.0);
1209 for (std::size_t a = 0; a < H; ++a)
1210 for (std::size_t b2 = 0; b2 < H; ++b2)
1211 m(a, b2) = num_traits<T>::to_double(d.sched_Dbatch[c][b][k](a, b2));
1212 per_batch.push_back(m);
1213 }
1214 per_mark.push_back(per_batch);
1215 }
1216 seg_batch_.push_back(per_mark);
1217 }
1218 }
1219 cyclic_ = d.sched_cyclic;
1220 has_schedule_ = true;
1221 phase_ = 0;
1222 if (!(mean_ > 0.0)) mean_ = num_traits<T>::to_double(d.mean);
1223 if (!(mean_ > 0.0) && !segs_.empty()) mean_ = num_traits<double>::to_double(
1224 mam::map_mean(segs_[0]));
1225 }
1226
1227 double period() const { return bp_.back() - bp_.front(); }
1228
1229 /** The NHPP rate of segment k, the 1x1 D1 its schedule stores. */
1230 double op_rate(std::size_t k) const { return segs_[k].D1(0, 0); }
1231
1232 /**
1233 * Position of t within one period, measured from bp_.front(), or -1 past a
1234 * non-cyclic horizon.
1235 *
1236 * The walk below carries this REDUCED offset rather than the wall clock: it
1237 * stays bounded by the period however far the simulation has run, which is
1238 * what keeps a boundary crossing representable.
1239 */
1240 double offset_at(double t) const {
1241 double offset = t - bp_.front();
1242 const double per = period();
1243 if (cyclic_) {
1244 offset = std::fmod(offset, per);
1245 if (offset < 0.0) offset += per;
1246 } else if (offset < 0.0 || offset >= per) {
1247 return -1.0;
1248 }
1249 return offset;
1250 }
1251
1252 /** Index of the segment holding an offset already reduced to [0, period). */
1253 int segment_of(double offset) const {
1254 const double pos = bp_.front() + offset;
1255 for (std::size_t k = 0; k + 1 < bp_.size(); ++k)
1256 if (pos < bp_[k + 1]) return static_cast<int>(k);
1257 return static_cast<int>(segs_.size()) - 1;
1258 }
1259
1260 /** Index of the segment in force at t, or -1 past a non-cyclic horizon. */
1261 int segment_at(double t) const {
1262 const double offset = offset_at(t);
1263 return (offset < 0.0) ? -1 : segment_of(offset);
1264 }
1265
1266 /**
1267 * One interval of a MAPt / PHt / NHPP, started at `from`.
1268 *
1269 * The walk advances through the phase process and STOPS AT EVERY SEGMENT
1270 * BOUNDARY, resampling the holding time under the new generator. That is
1271 * what makes the schedule piecewise-constant rather than merely
1272 * time-averaged: an exponential holding time drawn under one segment's rate
1273 * and allowed to run past the boundary would carry the old rate into the
1274 * new segment, which is exactly the approximation the family exists to
1275 * avoid. Transcribes `sampleMAPtInterarrival`.
1276 */
1277 double schedule_sample(Rng& g, double from) {
1278 const std::size_t H = segs_[0].order();
1279 double offset = offset_at(from);
1280 if (offset < 0.0) return 0.0; // past a non-cyclic horizon: no more events
1281 std::size_t idx = static_cast<std::size_t>(segment_of(offset));
1282 double elapsed = 0.0;
1283 for (int guard = 0; guard < 1000000; ++guard) {
1284 const double to_boundary = (bp_[idx + 1] - bp_.front()) - offset;
1285 const mam::Map<double>& seg = segs_[idx];
1286 const double total = -seg.D0(phase_, phase_);
1287 // An absorbing phase never fires, so it always reaches the boundary.
1288 const double holding = (total > 0.0) ? -std::log(uniform01(g)) / total
1289 : std::numeric_limits<double>::infinity();
1290 if (holding >= to_boundary) {
1291 ++idx;
1292 if (idx >= segs_.size()) {
1293 if (!cyclic_) return 0.0;
1294 idx = 0;
1295 }
1296 elapsed += to_boundary;
1297 // LAND EXACTLY ON THE BOUNDARY by taking the next segment's own
1298 // offset. Adding to_boundary to a running position instead would
1299 // stall the walk: far from the schedule origin the sliver left by
1300 // the modulo is below one ulp of that position, so the addition
1301 // does not move it and the loop spins on the same boundary until
1302 // the guard trips -- a hang, not a wrong number, and one that only
1303 // shows up once the simulation clock has run far enough.
1304 offset = bp_[idx] - bp_.front();
1305 continue;
1306 }
1307 elapsed += holding;
1308 offset += holding;
1309 // The transitions competing out of the current phase, ARRIVALS
1310 // FIRST: a D1 entry ends the interval, a D0 entry only moves phase.
1311 const double u = uniform01(g) * total;
1312 double cum = 0.0;
1313 int chosen = -1;
1314 // A MARKED schedule splits the arrival arm across the mark blocks at NO EXTRA
1315 // DRAW: the scan runs destination-major and mark-minor, so the running total
1316 // after all marks of a destination equals the aggregate total after that
1317 // destination. The winning destination is therefore the one the unmarked walk
1318 // would pick for the same uniform, which is what makes a K = 1 MMAPt reproduce
1319 // the MAPt with the same matrices sample path for sample path.
1320 if (!seg_mark_.empty()) {
1321 const std::vector<Matrix<double>>& marks = seg_mark_[idx];
1322 // The BATCH axis goes INSIDE the mark axis, so dropping it (every
1323 // batch size 1) leaves the scan order untouched and a B = 1 BMMAPt
1324 // reproduces the MMAPt sample path exactly as a K = 1 MMAPt
1325 // reproduces the MAPt. Neither label costs an extra draw.
1326 const bool batched_here = !seg_batch_.empty();
1327 const std::size_t B = batched_here ? seg_batch_[idx][0].size() : std::size_t(1);
1328 for (std::size_t j = 0; j < H; ++j) {
1329 for (std::size_t c = 0; c < marks.size(); ++c) {
1330 if (!batched_here) {
1331 cum += marks[c](phase_, j);
1332 if (u < cum) {
1333 last_mark_ = static_cast<int>(c) + 1;
1334 last_batch_ = 1;
1335 phase_ = j;
1336 return elapsed;
1337 }
1338 continue;
1339 }
1340 for (std::size_t b = 0; b < B; ++b) {
1341 cum += seg_batch_[idx][c][b](phase_, j);
1342 if (u < cum) {
1343 last_mark_ = static_cast<int>(c) + 1;
1344 last_batch_ = static_cast<int>(b) + 1;
1345 phase_ = j;
1346 return elapsed;
1347 }
1348 }
1349 }
1350 }
1351 for (std::size_t j = 0; j < H; ++j) {
1352 if (j == phase_) continue;
1353 cum += seg.D0(phase_, j);
1354 if (u < cum) {
1355 chosen = static_cast<int>(H + j);
1356 break;
1357 }
1358 }
1359 if (chosen < 0) {
1360 // Rounding shortfall: attribute the draw to the last positive arrival
1361 // entry, as the unmarked walk below does.
1362 for (std::size_t j = H; j-- > 0;)
1363 for (std::size_t c = marks.size(); c-- > 0;) {
1364 if (!batched_here) {
1365 if (marks[c](phase_, j) > 0.0) {
1366 last_mark_ = static_cast<int>(c) + 1;
1367 last_batch_ = 1;
1368 phase_ = j;
1369 return elapsed;
1370 }
1371 continue;
1372 }
1373 for (std::size_t b = B; b-- > 0;)
1374 if (seg_batch_[idx][c][b](phase_, j) > 0.0) {
1375 last_mark_ = static_cast<int>(c) + 1;
1376 last_batch_ = static_cast<int>(b) + 1;
1377 phase_ = j;
1378 return elapsed;
1379 }
1380 }
1381 last_mark_ = 1;
1382 last_batch_ = 1;
1383 return elapsed;
1384 }
1385 phase_ = static_cast<std::size_t>(chosen) - H;
1386 continue;
1387 }
1388 for (std::size_t j = 0; j < 2 * H; ++j) {
1389 const double w = (j < H) ? seg.D1(phase_, j)
1390 : ((j - H == phase_) ? 0.0 : seg.D0(phase_, j - H));
1391 cum += w;
1392 if (u < cum) {
1393 chosen = static_cast<int>(j);
1394 break;
1395 }
1396 }
1397 if (chosen < 0)
1398 for (std::size_t j = 2 * H; j-- > 0;) {
1399 const double w = (j < H) ? seg.D1(phase_, j)
1400 : ((j - H == phase_) ? 0.0 : seg.D0(phase_, j - H));
1401 if (w > 0.0) {
1402 chosen = static_cast<int>(j);
1403 break;
1404 }
1405 }
1406 if (chosen < static_cast<int>(H)) {
1407 phase_ = static_cast<std::size_t>(chosen);
1408 return elapsed;
1409 }
1410 phase_ = static_cast<std::size_t>(chosen) - H;
1411 }
1412 return 0.0;
1413 }
1414
1416 std::string where_;
1417 double mean_ = 0.0, scv_ = 1.0, rate_ = 0.0;
1418 double a_ = 0.0, b_ = 0.0; ///< the family's two shape/scale slots
1419 /** The sampler of the law a MassAtOrigin wraps; null otherwise. */
1420 std::shared_ptr<Sampler> inner_;
1421 int erlang_k_ = 0; ///< phases of an Erlang, 0 when not recovered
1422 std::vector<double> pie_; ///< cached map_pie for the renewal phase-type walk
1423 PhaseTrace* ptrace_ = nullptr; ///< sample-path export: walk trace, null when off
1424 double erlang_rate_ = 0.0; ///< per-phase rate of an Erlang
1425 std::vector<double> trace_;
1426 std::size_t trace_idx_ = 0;
1427 mam::Map<double> map_;
1428 std::vector<double> entry_; ///< RAP entry law, chained across samples
1429 std::shared_ptr<mam::MeSampler<double>> me_; ///< ME inversion table, built once
1430 /// Per-SEGMENT, per-mark arrival blocks of a marked schedule; empty otherwise.
1431 std::vector<std::vector<Matrix<double>>> seg_mark_;
1432 /// Per-mark arrival blocks D1k; empty for an unmarked process.
1433 std::vector<Matrix<double>> mark_;
1434 /// Per-BATCH-SIZE blocks of a stationary BMAP, `batch_[b]` releasing b+1 jobs;
1435 /// empty for every other family. The schedule twin is `seg_batch_`.
1436 std::vector<Matrix<double>> batch_;
1437 /// Per-SEGMENT, per-mark, per-batch blocks of a BMMAPt; empty otherwise.
1438 std::vector<std::vector<std::vector<Matrix<double>>>> seg_batch_;
1439 /// The 1-based mark of the interval last returned; 0 before the first draw.
1440 int last_mark_ = 0;
1441 /// How many jobs the epoch last returned releases; 0 before the first draw.
1442 int last_batch_ = 0;
1443 bool has_phase_ = false, phase_known_ = false;
1444 // The time-inhomogeneous schedule: boundaries, per-segment (D0,D1), and
1445 // whether the schedule repeats past its last boundary.
1446 bool has_schedule_ = false, cyclic_ = false;
1447 std::vector<double> bp_;
1448 std::vector<mam::Map<double>> segs_;
1449 std::size_t phase_ = 0;
1450 /// The NNPP law and its stream state; null for every other family.
1451 std::shared_ptr<const lang::Nnpp> nnpp_;
1452 lang::Nnpp::Stream nnpp_stream_;
1453};
1454
1455} // namespace engine
1456} // namespace ldes
1457} // namespace line
1458
1459#endif // LINE_SOLVERS_LDES_LDES_SAMPLER_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
double next_at(Rng &g, double from)
One variate from a TIME-INHOMOGENEOUS process, given the instant it starts at.
double resolve_zero_atom(double v) const
The reference's resolveZeroAtom: the discrete laws supported on {0,1,...} can return a zero-length in...
lang::ProcessType type() const
bool batched() const
True when the process carries its OWN batch sizes: a BMAP or a BMMAPt.
int last_mark() const
The 1-based mark of the interval last returned by next/next_at, or 0 when this process carries none.
double op_cum_intensity(double t) const
int_{b0}^{t} mu(u) du, cyclic with the horizon as period or clamped.
int phase() const
The phase the process is in, for a caller that must carry it across a preemption or across successive...
double op_work_between(double t0, double t1) const
Operational time delivered at full share between two wall instants.
double op_wall_after(double t0, double work) const
The wall instant at which work units of operational time have been delivered since t0,...
int sp_phase() const
Sample-path export: the walk phase as the reference's getPhase() reports it, 0 for a one-phase proces...
bool op_time() const
AN NHPP SERVICE RUNS IN OPERATIONAL TIME (closed 2026-11-14).
void set_trace(PhaseTrace *t)
Sample-path export: the trace the next MAP/PH/MMAP/BMAP walk fills, or null (the default) to record n...
int erlang_k() const
Phases of an Erlang recovered for convolution, 0 when none was.
std::size_t map_order() const
Order of the (D0,D1) representation, 0 for a family that carries none.
int last_batch() const
How many jobs the epoch last returned by next/next_at releases, or 1 when this process carries no bat...
Sampler(const lang::Distrib< T > &d, const std::string &where)
Build the generator of d; the (station, class) names are for diagnostics.
double next(Rng &g)
One variate.
double op_budget(Rng &g) const
The Exp(1) operational-time budget of one service, one uniform drawn off the java....
java.util.Random, the 48-bit LCG of the Java Language Specification.
Definition rng_ssj.h:219
double next_double()
Java's nextDouble(): a 26-bit and a 27-bit draw.
Definition rng_ssj.h:253
SSJ's umontreal.ssj.rng.MRG32k3a, state and all.
Definition rng_ssj.h:120
double next_double()
SSJ's nextValue(): the combined generator, returning a double in (0, 1).
Definition rng_ssj.h:141
void set_seed_offset(long long seed, long long offset)
The stream an LDES engine names by (run seed, offset): its seeds hashed by SeedHash.
Definition rng_ssj.h:131
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
The variate layer of the Java LDES engine, reproduced: SSJ's randvar generators as inverse-CDF functi...
Sample the inter-arrival times of a MAP, a RAP or a matrix exponential.
Dense matrix and non-owning view.
Sample a matrix exponential by numerical inversion of its exact CDF.
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
@ 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
bool process_is_marked_stationary(ProcessType p)
True when the type carries PER-MARK arrival blocks, i.e.
Definition lang_types.h:742
double uniform01(Rng &g)
Uniform on (0,1) off the MRG stream; next_double never returns 0.
double exponential_inverse(double lambda, double u)
ExponentialDist.inverseF(lambda, u), SSJ's log1p spelling.
double uniform_int_inverse(double lo, double width, double u)
UniformIntDist.inverseF(i, j, u), written over the lower bound and the WIDTH w = j - i + 1 so that a ...
double binomial_inverse(int n, double p, double u)
BinomialDist.inverseF(n, p, u), by the same forward inversion.
double uniform_inverse(double a, double b, double u)
UniformDist.inverseF(a, b, u).
double weibull_inverse(double alpha, double lambda, double delta, double u)
WeibullDist.inverseF(alpha, lambda, delta, u).
double pareto_inverse(double alpha, double beta, double u)
ParetoDist.inverseF(alpha, beta, u) = beta (1-u)^(-1/alpha).
double gamma_inverse(double alpha, double lambda, double u)
GammaDist.inverseF(alpha, lambda, u): the quantile of a Gamma of shape alpha and RATE lambda,...
double bernoulli_inverse(double p, double u)
BernoulliDist.inverseF(p, u): 1 when u exceeds 1 - p.
double lognormal_inverse(double mu, double sigma, double u)
LognormalDist.inverseF(mu, sigma, u) = exp(mu + sigma Phi^-1(u)).
double poisson_inverse(double lambda, double u)
PoissonDist.inverseF(lambda, u): the smallest k whose cdf reaches u.
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
std::vector< T > rap_sample(const Map< T > &m, std::size_t n, pfqn::McRng &rng, const std::vector< T > &a0=std::vector< T >(), std::vector< T > *a_out=0)
Sample a RAP or a matrix exponential by inverse transform.
Definition map_sample.h:257
std::vector< T > map_sample(const Map< T > &m, std::size_t n, pfqn::McRng &rng, const std::vector< T > &pie0=std::vector< T >(), SampleTrace *trace=0)
Sample the inter-arrival times of a MAP, a RAP or a matrix exponential.
Definition map_sample.h:98
std::mt19937_64 McRng
The generator type every Monte Carlo entry point in this tree accepts.
double sum(const Vec &a)
Definition spn_ispn.h:191
double elapsed(const Frame &f)
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The two random number generators the Java LDES engine draws from, reproduced exactly: SSJ's MRG32k3a ...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
std::vector< Matrix< T > > Dmark
MMAP per-class D1 blocks / BMAP per-batch-size blocks; empty otherwise.
Definition lang_types.h:931
std::shared_ptr< const Nnpp > nnpp
The NNPP law, set only when type == NNPP, null otherwise.
Definition lang_types.h:960
std::shared_ptr< Distrib< T > > inner
The wrapped law of a MassAtOrigin or a Defective, null otherwise.
Definition lang_types.h:951
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
Definition lang_types.h:894
std::vector< T > trace
Replayer / Trace samples; empty for every other type.
Definition lang_types.h:896
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
One arrival path: renewal epoch in majorizer space, first-gap flag, last arrival.
Definition nnpp.h:58
The phases one walked interval visited and how long it held each, filled by a sampler only while the ...
double total() const
Sum of the holdings, in order, as the reference adds them.
std::vector< double > dt
void add(int ph, double holding)
The engine's randomness, in the SHAPE the Java engine uses it.
Rng(long long seed, long long stream_offset, long long aux_offset)
A run seed and the TWO offsets the reference derives, one per generator.
rng::JavaRandom aux
java.util.Random: the Markovian samplers
Rng(long long seed, long long offset)
The common case, where the reference uses one offset for both.
rng::Mrg32k3a stream
SSJ MRG32k3a: every renewal family.
pfqn::McRng mc
the residual RAP/ME path, not yet aligned
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
static double to_double(const double &v)
Definition number.h:137