LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ctmc_hitting_dist.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_API_MC_CTMC_HITTING_DIST_H
6#define LINE_API_MC_CTMC_HITTING_DIST_H
7
8/**
9 * @file
10 * @ingroup api_mc
11 * Distribution of the hitting time of a rarely visited set by regenerative
12 * simulation of a continuous-time Markov chain, with the five estimators of
13 * Glynn, Nakayama and Tuffin (WSC 2020): exponential, convolution, corrected
14 * convolution, gamma and bootstrap.
15 *
16 * Port of matlab/src/api/mc/ctmc_hitting_dist.m, cross-checked against
17 * python/line_solver/api/mc/hitting_dist.py.
18 *
19 * METHOD. The chain starts in the regeneration state x0, and a cycle ends at
20 * its first return to x0. With T the hitting time of the target set A and tau
21 * the cycle length, T = S + V, where S is the geometric sum of the M cycles
22 * completed before the first one that reaches A and V is the time to reach A
23 * inside that cycle. Every estimator needs p = P(T < tau), which is small, and
24 * some cycle statistics under the original law. They come from measure-specific
25 * importance sampling (Goyal et al. 1992): nCS = floor(gamma*n + 0.5) cycles of
26 * crude simulation estimate the cycle statistics, and the other nIS = n - nCS
27 * cycles, run under the change of measure, estimate p and the law H of V.
28 *
29 * "exp" F(t) = 1 - exp(-t/mu), mu = E[T ^ tau]/p (eq. 6)
30 * "conv" exponential law of S, mean eta, convolved with H (eq. 10)
31 * "corr" Blanchet-Glynn corrected exponential law of S with H (Est. 3)
32 * "gamma" gamma law with the first two moments of T, E[T^2] from
33 * Proposition 1 (Est. 4)
34 * "boot" semi-parametric bootstrap of S + V (Est. 5)
35 *
36 * The convolutions are evaluated as E[I(V <= t) G(t - V)]. The printed form of
37 * Estimator 3 writes G((t - V)^+) without the indicator, which is the same thing
38 * only for a law of S with no mass at 0; the corrected law has some. The change
39 * of measure acts on the embedded jump chain only: holding times are drawn from
40 * the original total rate, so the likelihood ratio of a path is the product of
41 * P(x,y)/P'(x,y) over its jumps. A field is NaN when its estimator is undefined
42 * on the sample: corr needs a crude cycle that returned before reaching A,
43 * gamma a positive variance estimate.
44 *
45 * TWO FORMS. In function form a state is a vector of doubles, the transition
46 * function returns its successors and their rates (successors equal to the
47 * state and zero rates are dropped, keeping the order of the rest), the target
48 * is a predicate and the change of measure is HittingDistOptions::istrans. In
49 * generator form a state is a 0-BASED row index of a dense generator Q, its
50 * successors are the columns with a positive off-diagonal rate in ASCENDING
51 * column order, the target is a list of 0-based row indices or a mask over the
52 * rows, and the change of measure is the importance generator
53 * HittingDistOptions::isgen of the same size.
54 *
55 * RANDOM NUMBERS. All draws come from one MRG32k3a stream (line::rng::Mrg32k3a,
56 * L'Ecuyer's double-precision form, SSJ's nextValue), seeded from options.seed
57 * by the affine map of sim_prio_tailquantile and consumed in a fixed order:
58 * crude cycles, then importance cycles, then the bootstrap; in a cycle each jump
59 * takes the holding time first and the successor second. MATLAB, Python and the
60 * JAR consume the same stream in the same order, so a seed gives the same
61 * estimates everywhere up to last-ulp differences of log() and exp().
62 *
63 * Reference: P. W. Glynn, M. K. Nakayama, B. Tuffin, "Comparing regenerative-
64 * simulation-based estimators of the distribution of the hitting time to a
65 * rarely visited set", Proc. Winter Simulation Conference 2020, 421-432.
66 */
67
68#include <array>
69#include <cctype>
70#include <cmath>
71#include <cstddef>
72#include <cstdio>
73#include <functional>
74#include <limits>
75#include <string>
76#include <vector>
77
78#include <boost/math/special_functions/gamma.hpp>
79
81#include "line/util/error.h"
82#include "line/util/matrix.h"
83#include "line/util/rng_ssj.h"
84
85namespace line {
86namespace mc {
87
88/** Successor states of a state and their rates (function form). */
90 std::vector<std::vector<double>> states;
91 std::vector<double> rates;
92};
93
94/** Transition function of the function form. */
95using HittingDistTransition = std::function<HittingDistSuccessors(const std::vector<double>&)>;
96
97/** Target-set predicate of the function form. */
98using HittingDistTarget = std::function<bool(const std::vector<double>&)>;
99
100/**
101 * Change of measure of the function form: given the state x, the successors Y
102 * and their rates as the transition function gave them (after dropping zero
103 * rates and self-loops), the importance rate of each successor.
104 */
105using HittingDistImportance = std::function<std::vector<double>(
106 const std::vector<double>&, const std::vector<std::vector<double>>&, const std::vector<double>&)>;
107
108/** Options, with the MATLAB defaults. */
110 std::string method = "conv"; ///< "exp", "conv", "corr", "gamma" or "boot": which estimate F holds
111 long long nsamples = 10000; ///< total number of cycles n (>= 4)
112 double gamma = 0.5; ///< fraction of the n cycles run by crude simulation, in (0,1)
113 long long nboot = -1; ///< bootstrap replications n'; -1 means nsamples
114 double maxbootdraws = 1e8; ///< cap on the expected bootstrap cycle draws n'(1-p)/p
115 double maxsteps = 1e7; ///< jumps allowed in one cycle
116 std::vector<double> q; ///< quantile levels for quantile and cte (may be empty)
117 double conflevel = 0.95; ///< level of the intervals
118 long long seed = 23000; ///< in [0, 2^31)
119 HittingDistImportance istrans; ///< function form: importance rates (empty = none)
120 Matrix<double> isgen; ///< generator form: importance generator (empty = none)
121};
122
123/** Estimates and diagnostics; every vector over t has one entry per time. */
125 std::vector<double> F; ///< the estimate of P(T <= t) selected by options.method
126 std::string method;
127 double mu = 0; ///< E[T] estimate, zeta/p
128 std::array<double, 2> muci{{0, 0}}; ///< delta-method interval for mu
129 double p = 0; ///< P(T < tau) estimate
130 double zeta = 0; ///< E[T ^ tau] estimate
131 double eta = 0; ///< E[S] estimate
132 double theta = std::numeric_limits<double>::quiet_NaN(); ///< corrected law (NaN if undefined)
133 double r = std::numeric_limits<double>::quiet_NaN(); ///< corrected law (NaN if undefined)
134 double shape = std::numeric_limits<double>::quiet_NaN(); ///< gamma law (NaN if undefined)
135 double rate = std::numeric_limits<double>::quiet_NaN(); ///< gamma law (NaN if undefined)
136 long long nCS = 0, nIS = 0; ///< crude and importance-sampled cycles
137 long long hitsCS = 0, hitsIS = 0; ///< cycles of each kind that reached the target
138 std::vector<double> Fexp, Fconv, Fcorr, Fgamma;
139 std::vector<double> Fboot; ///< empty unless method is "boot"
140 std::vector<double> q; ///< the quantile levels (empty when options.q is)
141 std::vector<double> quantile; ///< -log(1-q) mu, eq. (7)
142 std::vector<std::array<double, 2>> quantileci;
143 std::vector<double> cte; ///< (1 - log(1-q)) mu, eq. (7)
144 std::vector<std::array<double, 2>> cteci;
145};
146
147namespace detail_hit {
148
149[[noreturn]] inline void input(const char* kind, const std::string& msg) {
150 throw InputError(ErrorKind{kind}, std::string("ctmc_hitting_dist: ") + msg);
151}
152
153[[noreturn]] inline void numerical(const char* kind, const std::string& msg) {
154 throw NumericError(ErrorKind{kind}, std::string("ctmc_hitting_dist: ") + msg);
155}
156
157inline std::string fmt_g(double v) {
158 char buf[64];
159 std::snprintf(buf, sizeof(buf), "%g", v);
160 return buf;
161}
162
163/** Six MRG32k3a seeds from one integer, the affine map of sim_prio_tailquantile. */
164inline void seed_stream(rng::Mrg32k3a& g, long long seed) {
165 const long long a[6] = {1, 65539, 69069, 1, 65539, 69069};
166 const long long b[6] = {12345, 54321, 98765, 13579, 24680, 11111};
167 long long s[6];
168 for (int i = 0; i < 6; ++i) {
169 const long long m = (i < 3) ? 4294967087LL : 4294944443LL;
170 s[i] = 1 + (seed * a[i] + b[i]) % (m - 1);
171 }
172 g.set_seed(s);
173}
174
175inline double vsum(const std::vector<double>& x) {
176 double s = 0.0;
177 for (double v : x) s += v;
178 return s;
179}
180
181/** Index drawn from the weights w by the uniform u, by a left-to-right scan; -1 if none is positive. */
182inline long long pick(const std::vector<double>& w, double u) {
183 const double target = u * vsum(w);
184 double acc = 0.0;
185 long long j = -1;
186 for (std::size_t k = 0; k < w.size(); ++k) {
187 if (w[k] > 0) {
188 acc += w[k];
189 j = static_cast<long long>(k);
190 if (target < acc) return j;
191 }
192 }
193 return j;
194}
195
196/** Sample variance with the n - 1 denominator. */
197inline double var(const std::vector<double>& x) {
198 const double n = static_cast<double>(x.size());
199 const double m = vsum(x) / n;
200 double acc = 0.0;
201 for (double v : x) acc += (v - m) * (v - m);
202 return acc / (n - 1.0);
203}
204
205struct Checked {
206 std::string method;
207 long long nCS = 0, nIS = 0, nboot = 0;
208};
209
210/** The option and time checks MATLAB runs before looking at the chain, in its order. */
211inline Checked check_options(const std::vector<double>& t, const HittingDistOptions& opt) {
212 Checked c;
213 c.method = opt.method;
214 for (char& ch : c.method) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
215 if (c.method != "exp" && c.method != "conv" && c.method != "corr" && c.method != "gamma" &&
216 c.method != "boot")
217 input("Option", "options.method must be one of exp, conv, corr, gamma, boot.");
218 if (opt.nsamples < 4) input("Option", "options.nsamples must be an integer >= 4.");
219 if (!(opt.gamma > 0.0 && opt.gamma < 1.0)) input("Option", "options.gamma must lie in (0,1).");
220 c.nCS = static_cast<long long>(std::floor(opt.gamma * static_cast<double>(opt.nsamples) + 0.5));
221 c.nIS = opt.nsamples - c.nCS;
222 if (c.nCS < 2 || c.nIS < 2)
223 input("Option", "options.gamma leaves fewer than 2 cycles to crude or importance sampling.");
224 c.nboot = opt.nboot == -1 ? opt.nsamples : opt.nboot;
225 if (c.nboot < 1) input("Option", "options.nboot must be a positive integer.");
226 if (!(opt.maxsteps >= 1.0)) input("Option", "options.maxsteps must be a positive number.");
227 if (!(opt.maxbootdraws >= 1.0)) input("Option", "options.maxbootdraws must be a positive number.");
228 if (!(opt.conflevel > 0.0 && opt.conflevel < 1.0)) input("Option", "options.conflevel must lie in (0,1).");
229 if (opt.seed < 0 || opt.seed >= (1LL << 31)) input("Option", "options.seed must be an integer in [0, 2^31).");
230 for (double v : opt.q)
231 if (!(v > 0.0 && v < 1.0)) input("Option", "options.q must lie in (0,1).");
232 bool tok = !t.empty();
233 for (double v : t) tok = tok && std::isfinite(v) && v >= 0.0;
234 if (!tok) input("Argument", "T must be a non-empty vector of finite nonnegative times.");
235 return c;
236}
237
238/**
239 * One regenerative cycle from x0: a = T ^ tau, hit = I(T < tau) and L the
240 * likelihood ratio of the path (1 without a change of measure).
241 *
242 * Step: void(const State& x, std::vector<State>& Y, std::vector<double>& rt)
243 * IsRates: void(const State& x, const std::vector<State>& Y, const std::vector<double>& rt,
244 * std::vector<double>& ri)
245 * Target: bool(const State& x)
246 */
247template <class State, class Step, class IsRates, class Target>
248void run_cycle(const Step& step, const IsRates& isr, bool useIS, const Target& target, const State& x0,
249 double maxsteps, rng::Mrg32k3a& g, double& a, bool& hit, double& L) {
250 State x = x0;
251 a = 0.0;
252 L = 1.0;
253 hit = false;
254 double nsteps = 0.0;
255 std::vector<State> Y;
256 std::vector<double> rt, ri;
257 while (true) {
258 step(x, Y, rt);
259 const double q = vsum(rt);
260 if (!(q > 0.0))
261 input("Argument", "The chain reached an absorbing state outside the target set, so the cycle never ends.");
262 double u = g.next_double();
263 a = a - std::log(u) / q;
264 long long j;
265 if (!useIS) {
266 u = g.next_double();
267 j = pick(rt, u);
268 } else {
269 isr(x, Y, rt, ri);
270 bool ok = ri.size() == rt.size();
271 for (double v : ri) ok = ok && std::isfinite(v) && v >= 0.0;
272 if (!ok) input("Option", "options.istrans must return one finite nonnegative rate per successor.");
273 for (std::size_t k = 0; k < rt.size(); ++k)
274 if (rt[k] > 0.0 && ri[k] <= 0.0)
275 input("Option", "The change of measure gives zero rate to a transition the chain can take.");
276 const double qi = vsum(ri);
277 u = g.next_double();
278 j = pick(ri, u);
279 if (j >= 0) L = L * (rt[j] / q) / (ri[j] / qi);
280 }
281 if (j < 0) throw InternalError("ctmc_hitting_dist: no successor could be drawn from a positive total rate.");
282 x = Y[static_cast<std::size_t>(j)];
283 if (target(x)) {
284 hit = true;
285 return;
286 }
287 if (x == x0) return;
288 nsteps += 1.0;
289 if (nsteps >= maxsteps)
290 numerical("MaxIter", "A cycle took more than options.maxsteps = " + fmt_g(maxsteps) + " jumps.");
291 }
292}
293
294/** The cycles and the five estimators, common to both forms. */
295template <class State, class Step, class IsRates, class Target>
296HittingDistResult estimate(const Step& step, const IsRates& isr, bool hasIS, const Target& target, const State& x0,
297 const std::vector<double>& t, const Checked& c, const HittingDistOptions& opt) {
299 seed_stream(g, opt.seed);
300 const long long nCS = c.nCS, nIS = c.nIS;
301 const double dCS = static_cast<double>(nCS), dIS = static_cast<double>(nIS);
302
303 // cycles: crude first, then importance-sampled
304 std::vector<double> aCS(static_cast<std::size_t>(nCS), 0.0);
305 std::vector<char> hitCS(static_cast<std::size_t>(nCS), 0);
306 for (long long i = 0; i < nCS; ++i) {
307 double a = 0.0, L = 1.0;
308 bool hit = false;
309 run_cycle(step, isr, false, target, x0, opt.maxsteps, g, a, hit, L);
310 aCS[static_cast<std::size_t>(i)] = a;
311 hitCS[static_cast<std::size_t>(i)] = hit ? 1 : 0;
312 }
313 std::vector<double> aIS(static_cast<std::size_t>(nIS), 0.0), LIS(static_cast<std::size_t>(nIS), 1.0);
314 std::vector<char> hitIS(static_cast<std::size_t>(nIS), 0);
315 for (long long i = 0; i < nIS; ++i) {
316 double a = 0.0, L = 1.0;
317 bool hit = false;
318 run_cycle(step, isr, hasIS, target, x0, opt.maxsteps, g, a, hit, L);
319 aIS[static_cast<std::size_t>(i)] = a;
320 hitIS[static_cast<std::size_t>(i)] = hit ? 1 : 0;
321 LIS[static_cast<std::size_t>(i)] = L;
322 }
323
324 // moment estimators
325 std::vector<double> wIS(static_cast<std::size_t>(nIS));
326 for (std::size_t i = 0; i < wIS.size(); ++i) wIS[i] = LIS[i] * (hitIS[i] ? 1.0 : 0.0); // I(T' < tau') L'
327 const double p = vsum(wIS) / dIS;
328 if (!(p > 0.0))
329 numerical("NoSample",
330 "No importance-sampled cycle reached the target set; increase options.nsamples or supply "
331 "options.istrans.");
332 const double zeta = vsum(aCS) / dCS;
333 const double mu = zeta / p;
334 double s1 = 0.0, s2 = 0.0, s3 = 0.0, sq = 0.0;
335 for (std::size_t i = 0; i < aCS.size(); ++i) {
336 const double ret = hitCS[i] ? 0.0 : 1.0; // crude cycles with tau < T
337 s1 += aCS[i] * ret;
338 s2 += std::pow(aCS[i], 2) * ret;
339 s3 += std::pow(aCS[i], 3) * ret;
340 }
341 for (double v : aCS) sq += std::pow(v, 2);
342 s1 /= dCS; // E[tau I(tau < T)]
343 s2 /= dCS;
344 s3 /= dCS;
345 const double eta = s1 / p;
346
347 // delta-method interval for mu (independent crude and importance samples)
348 const double z = sim::sim_norminv(1.0 - (1.0 - opt.conflevel) / 2.0);
349 const double varzeta = var(aCS) / dCS;
350 const double varp = var(wIS) / dIS;
351 const double semu = std::sqrt(varzeta / std::pow(p, 2) + std::pow(zeta, 2) * varp / std::pow(p, 4));
352
353 // law of V: atoms aIS(j) of weight wIS(j)/sum(wIS) over the hitting importance cycles
354 std::vector<double> vval, vw;
355 for (std::size_t i = 0; i < aIS.size(); ++i) {
356 if (hitIS[i]) {
357 vval.push_back(aIS[i]);
358 vw.push_back(wIS[i]);
359 }
360 }
361 const double swv = vsum(vw);
362 for (double& v : vw) v = v / swv;
363
364 const std::size_t nt = t.size();
366 res.method = c.method;
367 res.Fexp.resize(nt);
368 for (std::size_t k = 0; k < nt; ++k) res.Fexp[k] = 1.0 - std::exp(-t[k] / mu);
369
370 res.Fconv.assign(nt, 0.0);
371 for (std::size_t k = 0; k < nt; ++k) {
372 double acc = 0.0;
373 for (std::size_t j = 0; j < vval.size(); ++j) {
374 const double x = t[k] - vval[j];
375 if (x >= 0.0) {
376 const double gv = eta > 0.0 ? 1.0 - std::exp(-x / eta) : 1.0; // eta = 0: S = 0 a.s.
377 acc += vw[j] * gv;
378 }
379 }
380 res.Fconv[k] = acc;
381 }
382
383 res.Fcorr.assign(nt, std::numeric_limits<double>::quiet_NaN());
384 if (p < 1.0 && s1 > 0.0) {
385 const double m1 = s1 / (1.0 - p), m2 = s2 / (1.0 - p), m3 = s3 / (1.0 - p);
386 const double chi1 = 1.0 / m1;
387 const double chi2 = (2.0 * std::pow(m1, 2) - m2) / (2.0 * std::pow(m1, 3));
388 const double chi3 = (3.0 * std::pow(m2, 2) - 6.0 * m2 * std::pow(m1, 2) + 6.0 * std::pow(m1, 4) - m1 * m3) /
389 (6.0 * std::pow(m1, 5));
390 const double del1 = (2.0 * std::pow(m1, 2) - m2) / (2.0 * std::pow(m1, 2));
391 const double del2 = (12.0 * std::pow(m1, 4) - 12.0 * m2 * std::pow(m1, 2) + 15.0 * std::pow(m2, 2) -
392 8.0 * m3 * m1) /
393 (24.0 * std::pow(m1, 4));
394 res.theta = chi1 * p + chi2 * std::pow(p, 2) + chi3 * std::pow(p, 3);
395 res.r = del1 * p + del2 * std::pow(p, 2);
396 for (std::size_t k = 0; k < nt; ++k) {
397 double acc = 0.0;
398 for (std::size_t j = 0; j < vval.size(); ++j) {
399 const double x = t[k] - vval[j];
400 if (x >= 0.0) acc += vw[j] * (1.0 - (1.0 - p) * std::exp(-res.theta * x + res.r));
401 }
402 res.Fcorr[k] = acc;
403 }
404 }
405
406 const double ET2 = (sq / dCS + 2.0 * s1 * mu) / p; // Proposition 1
407 const double sigma2 = ET2 - std::pow(mu, 2);
408 if (sigma2 > 0.0) {
409 res.shape = std::pow(mu, 2) / sigma2;
410 res.rate = mu / sigma2;
411 res.Fgamma.resize(nt);
412 for (std::size_t k = 0; k < nt; ++k) res.Fgamma[k] = boost::math::gamma_p(res.shape, res.rate * t[k]);
413 } else {
414 res.Fgamma.assign(nt, std::numeric_limits<double>::quiet_NaN());
415 }
416
417 if (c.method == "boot") {
418 if (p >= 1.0)
419 numerical("Infeasible", "The estimate of p is " + fmt_g(p) +
420 " >= 1, so the geometric number of cycles of the bootstrap is undefined.");
421 const double nb = static_cast<double>(c.nboot);
422 if (nb * (1.0 - p) / p > opt.maxbootdraws)
423 input("Option", "The bootstrap would draw about " + fmt_g(nb * (1.0 - p) / p) + " cycles (p = " +
424 fmt_g(p) + "); use another method or raise options.maxbootdraws.");
425 std::vector<double> kval;
426 for (std::size_t i = 0; i < aCS.size(); ++i)
427 if (!hitCS[i]) kval.push_back(aCS[i]);
428 if (kval.empty())
429 numerical("NoSample",
430 "No crude cycle returned before reaching the target set, so the bootstrap has no cycle "
431 "length to resample.");
432 const double nK = static_cast<double>(kval.size());
433 const double lq = std::log(1.0 - p);
434 std::vector<double> Tb(static_cast<std::size_t>(c.nboot), 0.0);
435 for (std::size_t l = 0; l < Tb.size(); ++l) {
436 double u = g.next_double();
437 const double M = std::floor(std::log(u) / lq);
438 double S = 0.0;
439 for (double j = 0.0; j < M; j += 1.0) {
440 u = g.next_double();
441 S = S + kval[static_cast<std::size_t>(std::floor(u * nK))];
442 }
443 u = g.next_double();
444 const long long jv = pick(vw, u);
445 Tb[l] = S + vval[static_cast<std::size_t>(jv)];
446 }
447 res.Fboot.assign(nt, 0.0);
448 for (std::size_t k = 0; k < nt; ++k) {
449 double cnt = 0.0;
450 for (double v : Tb)
451 if (v <= t[k]) cnt += 1.0;
452 res.Fboot[k] = cnt / nb;
453 }
454 }
455
456 if (c.method == "exp") res.F = res.Fexp;
457 else if (c.method == "conv") res.F = res.Fconv;
458 else if (c.method == "corr") res.F = res.Fcorr;
459 else if (c.method == "gamma") res.F = res.Fgamma;
460 else res.F = res.Fboot;
461
462 res.mu = mu;
463 res.muci = {{mu - z * semu, mu + z * semu}};
464 res.p = p;
465 res.zeta = zeta;
466 res.eta = eta;
467 res.nCS = nCS;
468 res.nIS = nIS;
469 for (char h : hitCS) res.hitsCS += h ? 1 : 0;
470 for (char h : hitIS) res.hitsIS += h ? 1 : 0;
471 if (!opt.q.empty()) {
472 res.q = opt.q;
473 for (double qv : opt.q) {
474 const double cq = -std::log(1.0 - qv);
475 res.quantile.push_back(cq * mu);
476 res.quantileci.push_back({{cq * res.muci[0], cq * res.muci[1]}});
477 res.cte.push_back((1.0 + cq) * mu);
478 res.cteci.push_back({{(1.0 + cq) * res.muci[0], (1.0 + cq) * res.muci[1]}});
479 }
480 }
481 return res;
482}
483
484/** Generator form after the target has been turned into a mask by makeMask(n). */
486 const std::function<std::vector<char>(std::size_t)>& makeMask,
487 const std::vector<double>& t, const HittingDistOptions& opt) {
488 const Checked c = check_options(t, opt);
489 const std::size_t n = Q.rows();
490 if (Q.cols() != n || n < 2) input("Argument", "A generator TRANS must be a square matrix of order >= 2.");
491 if (x0 < 0 || static_cast<std::size_t>(x0) >= n) input("Argument", "X0 must be a row index of the generator.");
492 const std::vector<char> isA = makeMask(n);
493 std::vector<std::vector<int>> succ(n);
494 std::vector<std::vector<double>> srate(n);
495 for (std::size_t i = 0; i < n; ++i) {
496 for (std::size_t j = 0; j < n; ++j) {
497 if (j == i) continue;
498 const double v = Q(i, j);
499 if (!(v >= 0.0) || !std::isfinite(v))
500 input("Argument", "The off-diagonal rates of the generator must be finite and nonnegative.");
501 }
502 for (std::size_t j = 0; j < n; ++j) { // ascending column order
503 if (j != i && Q(i, j) > 0.0) {
504 succ[i].push_back(static_cast<int>(j));
505 srate[i].push_back(Q(i, j));
506 }
507 }
508 }
509 if (opt.istrans)
510 input("Option", "With a generator TRANS, options.istrans must be a generator of the same size.");
511 const bool hasIS = opt.isgen.rows() > 0 || opt.isgen.cols() > 0;
512 if (hasIS && (opt.isgen.rows() != n || opt.isgen.cols() != n))
513 input("Option", "With a generator TRANS, options.istrans must be a generator of the same size.");
514 if (isA[static_cast<std::size_t>(x0)]) input("Argument", "The regeneration state X0 lies in the target set.");
515
516 const Matrix<double>& Qis = opt.isgen;
517 auto step = [&succ, &srate](const int& x, std::vector<int>& Y, std::vector<double>& rt) {
518 Y = succ[static_cast<std::size_t>(x)];
519 rt = srate[static_cast<std::size_t>(x)];
520 };
521 auto isr = [&Qis](const int& x, const std::vector<int>& Y, const std::vector<double>&, std::vector<double>& ri) {
522 ri.resize(Y.size());
523 for (std::size_t k = 0; k < Y.size(); ++k)
524 ri[k] = Qis(static_cast<std::size_t>(x), static_cast<std::size_t>(Y[k]));
525 };
526 auto target = [&isA](const int& x) { return isA[static_cast<std::size_t>(x)] != 0; };
527 return estimate<int>(step, isr, hasIS, target, x0, t, c, opt);
528}
529
530inline Matrix<double> to_matrix(const std::vector<std::vector<double>>& Q) {
531 const std::size_t n = Q.size();
532 std::size_t m = 0;
533 for (const auto& row : Q) m = row.size() > m ? row.size() : m;
534 for (const auto& row : Q)
535 if (row.size() != m) input("Argument", "A generator TRANS must be a square matrix of order >= 2.");
536 Matrix<double> A(n, m, 0.0);
537 for (std::size_t i = 0; i < n; ++i)
538 for (std::size_t j = 0; j < m; ++j) A(i, j) = Q[i][j];
539 return A;
540}
541
542inline std::function<std::vector<char>(std::size_t)> index_mask(const std::vector<int>& target) {
543 return [target](std::size_t n) {
544 if (target.empty()) input("Argument", "TARGET must be a non-empty set of row indices of the generator.");
545 std::vector<char> isA(n, 0);
546 for (int v : target)
547 if (v < 0 || static_cast<std::size_t>(v) >= n)
548 input("Argument", "TARGET must be a non-empty set of row indices of the generator.");
549 for (int v : target) isA[static_cast<std::size_t>(v)] = 1;
550 return isA;
551 };
552}
553
554inline std::function<std::vector<char>(std::size_t)> bool_mask(const std::vector<bool>& target) {
555 return [target](std::size_t n) {
556 if (target.size() != n) input("Argument", "A logical TARGET must have one entry per state.");
557 std::vector<char> isA(n, 0);
558 for (std::size_t i = 0; i < n; ++i) isA[i] = target[i] ? 1 : 0;
559 return isA;
560 };
561}
562
563} // namespace detail_hit
564
565/**
566 * Hitting-time distribution of a target set, function form.
567 *
568 * @param trans successors of a state and their rates; zero rates and
569 * successors equal to the state are ignored
570 * @param x0 regeneration state; must not be in the target set
571 * @param target predicate, true on the target set A
572 * @param t times at which P(T <= t) is evaluated (finite, >= 0)
573 * @param opt options; the change of measure is opt.istrans
574 * @return the selected estimate in F, the other estimates and diagnostics
575 * @throws InputError LINE:input:Option / LINE:input:Argument on bad input,
576 * NumericError LINE:numerical:NoSample when no importance cycle (or,
577 * for "boot", no crude cycle returning first) is available,
578 * LINE:numerical:Infeasible when "boot" meets p >= 1, and
579 * LINE:numerical:MaxIter when a cycle exceeds opt.maxsteps jumps
580 */
581inline HittingDistResult ctmc_hitting_dist(const HittingDistTransition& trans, const std::vector<double>& x0,
582 const HittingDistTarget& target, const std::vector<double>& t,
584 using detail_hit::input;
586 if (!trans) input("Argument", "TRANS must be a function handle or a generator matrix.");
587 if (!target) input("Argument", "With a function TRANS, TARGET must be a function handle.");
588 if (x0.empty()) input("Argument", "X0 must be a 1-by-d state.");
589 if (opt.isgen.rows() > 0 || opt.isgen.cols() > 0)
590 input("Option", "With a function TRANS, options.istrans must be a function handle.");
591 const bool hasIS = static_cast<bool>(opt.istrans);
592 auto step = [&trans](const std::vector<double>& x, std::vector<std::vector<double>>& Y,
593 std::vector<double>& rt) {
594 const HittingDistSuccessors s = trans(x);
595 if (s.states.size() != s.rates.size())
596 detail_hit::input("Argument", "TRANS must return one rate per successor row.");
597 for (const auto& y : s.states)
598 if (y.size() != x.size())
599 detail_hit::input("Argument", "TRANS must return successor states of the width of the state.");
600 for (double v : s.rates)
601 if (!std::isfinite(v) || v < 0.0)
602 detail_hit::input("Argument", "TRANS must return finite nonnegative rates.");
603 Y.clear();
604 rt.clear();
605 for (std::size_t j = 0; j < s.rates.size(); ++j) {
606 if (s.rates[j] > 0.0 && !(s.states[j] == x)) { // self-loops removed
607 Y.push_back(s.states[j]);
608 rt.push_back(s.rates[j]);
609 }
610 }
611 };
612 const HittingDistImportance& istrans = opt.istrans;
613 auto isr = [&istrans](const std::vector<double>& x, const std::vector<std::vector<double>>& Y,
614 const std::vector<double>& rt, std::vector<double>& ri) { ri = istrans(x, Y, rt); };
615 auto tf = [&target](const std::vector<double>& x) { return static_cast<bool>(target(x)); };
616 if (tf(x0)) input("Argument", "The regeneration state X0 lies in the target set.");
617 return detail_hit::estimate<std::vector<double>>(step, isr, hasIS, tf, x0, t, c, opt);
618}
619
620/**
621 * Hitting-time distribution of a target set, generator form.
622 *
623 * @param Q dense generator (off-diagonal rates finite and >= 0; the
624 * diagonal is ignored); a state is a 0-based row index and its
625 * successors are taken in ascending column order
626 * @param x0 0-based regeneration state; must not be in the target set
627 * @param target non-empty list of 0-based row indices forming A
628 * @param t times at which P(T <= t) is evaluated
629 * @param opt options; the change of measure is the importance generator opt.isgen
630 */
631inline HittingDistResult ctmc_hitting_dist(const Matrix<double>& Q, int x0, const std::vector<int>& target,
632 const std::vector<double>& t,
634 return detail_hit::generator_form(Q, x0, detail_hit::index_mask(target), t, opt);
635}
636
637/** Generator form with the target given as a mask over the rows. */
638inline HittingDistResult ctmc_hitting_dist(const Matrix<double>& Q, int x0, const std::vector<bool>& target,
639 const std::vector<double>& t,
641 return detail_hit::generator_form(Q, x0, detail_hit::bool_mask(target), t, opt);
642}
643
644/** Generator form with Q as nested rows and the target as 0-based row indices. */
645inline HittingDistResult ctmc_hitting_dist(const std::vector<std::vector<double>>& Q, int x0,
646 const std::vector<int>& target, const std::vector<double>& t,
650}
651
652/** Generator form with Q as nested rows and the target as a mask over the rows. */
653inline HittingDistResult ctmc_hitting_dist(const std::vector<std::vector<double>>& Q, int x0,
654 const std::vector<bool>& target, const std::vector<double>& t,
658}
659
660} // namespace mc
661} // namespace line
662
663#endif // LINE_API_MC_CTMC_HITTING_DIST_H
InputError(const std::string &what)
Definition error.h:105
InternalError(const std::string &what)
Definition error.h:133
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
SSJ's umontreal.ssj.rng.MRG32k3a, state and all.
Definition rng_ssj.h:120
void set_seed(const long long s[6])
SSJ's setSeed(long[6]).
Definition rng_ssj.h:125
double next_double()
SSJ's nextValue(): the combined generator, returning a double in (0, 1).
Definition rng_ssj.h:141
The exception types the port throws.
Dense matrix and non-owning view.
void run_cycle(const Step &step, const IsRates &isr, bool useIS, const Target &target, const State &x0, double maxsteps, rng::Mrg32k3a &g, double &a, bool &hit, double &L)
One regenerative cycle from x0: a = T ^ tau, hit = I(T < tau) and L the likelihood ratio of the path ...
double var(const std::vector< double > &x)
Sample variance with the n - 1 denominator.
std::function< std::vector< char >(std::size_t)> index_mask(const std::vector< int > &target)
void numerical(const char *kind, const std::string &msg)
void input(const char *kind, const std::string &msg)
std::function< std::vector< char >(std::size_t)> bool_mask(const std::vector< bool > &target)
Matrix< double > to_matrix(const std::vector< std::vector< double > > &Q)
HittingDistResult generator_form(const Matrix< double > &Q, int x0, const std::function< std::vector< char >(std::size_t)> &makeMask, const std::vector< double > &t, const HittingDistOptions &opt)
Generator form after the target has been turned into a mask by makeMask(n).
std::string fmt_g(double v)
double vsum(const std::vector< double > &x)
Checked check_options(const std::vector< double > &t, const HittingDistOptions &opt)
The option and time checks MATLAB runs before looking at the chain, in its order.
long long pick(const std::vector< double > &w, double u)
Index drawn from the weights w by the uniform u, by a left-to-right scan; -1 if none is positive.
HittingDistResult estimate(const Step &step, const IsRates &isr, bool hasIS, const Target &target, const State &x0, const std::vector< double > &t, const Checked &c, const HittingDistOptions &opt)
The cycles and the five estimators, common to both forms.
void seed_stream(rng::Mrg32k3a &g, long long seed)
Six MRG32k3a seeds from one integer, the affine map of sim_prio_tailquantile.
HittingDistResult ctmc_hitting_dist(const HittingDistTransition &trans, const std::vector< double > &x0, const HittingDistTarget &target, const std::vector< double > &t, const HittingDistOptions &opt=HittingDistOptions())
Hitting-time distribution of a target set, function form.
std::function< HittingDistSuccessors(const std::vector< double > &)> HittingDistTransition
Transition function of the function form.
std::function< std::vector< double >( const std::vector< double > &, const std::vector< std::vector< double > > &, const std::vector< double > &)> HittingDistImportance
Change of measure of the function form: given the state x, the successors Y and their rates as the tr...
std::function< bool(const std::vector< double > &)> HittingDistTarget
Target-set predicate of the function form.
double sim_norminv(double p)
Standard normal quantile function.
Definition sim_dist.h:62
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 ...
Normal and Student t quantiles used by the output-analysis routines.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Options, with the MATLAB defaults.
long long nboot
bootstrap replications n'; -1 means nsamples
HittingDistImportance istrans
function form: importance rates (empty = none)
double conflevel
level of the intervals
Matrix< double > isgen
generator form: importance generator (empty = none)
double maxbootdraws
cap on the expected bootstrap cycle draws n'(1-p)/p
std::string method
"exp", "conv", "corr", "gamma" or "boot": which estimate F holds
std::vector< double > q
quantile levels for quantile and cte (may be empty)
double gamma
fraction of the n cycles run by crude simulation, in (0,1)
double maxsteps
jumps allowed in one cycle
long long nsamples
total number of cycles n (>= 4)
Estimates and diagnostics; every vector over t has one entry per time.
double shape
gamma law (NaN if undefined)
double zeta
E[T ^ tau] estimate.
std::vector< double > cte
(1 - log(1-q)) mu, eq. (7)
long long nIS
crude and importance-sampled cycles
std::vector< std::array< double, 2 > > quantileci
double p
P(T < tau) estimate.
std::vector< double > quantile
-log(1-q) mu, eq. (7)
double theta
corrected law (NaN if undefined)
double r
corrected law (NaN if undefined)
std::array< double, 2 > muci
delta-method interval for mu
long long hitsIS
cycles of each kind that reached the target
std::vector< double > Fconv
std::vector< double > Fboot
empty unless method is "boot"
std::vector< std::array< double, 2 > > cteci
double mu
E[T] estimate, zeta/p.
double rate
gamma law (NaN if undefined)
std::vector< double > Fcorr
std::vector< double > Fgamma
std::vector< double > q
the quantile levels (empty when options.q is)
std::vector< double > F
the estimate of P(T <= t) selected by options.method
Successor states of a state and their rates (function form).
std::vector< std::vector< double > > states