5#ifndef LINE_API_MC_CTMC_HITTING_DIST_H
6#define LINE_API_MC_CTMC_HITTING_DIST_H
78#include <boost/math/special_functions/gamma.hpp>
90 std::vector<std::vector<double>>
states;
106 const std::vector<double>&,
const std::vector<std::vector<double>>&,
const std::vector<double>&)>;
116 std::vector<double>
q;
125 std::vector<double>
F;
128 std::array<double, 2>
muci{{0, 0}};
132 double theta = std::numeric_limits<double>::quiet_NaN();
133 double r = std::numeric_limits<double>::quiet_NaN();
134 double shape = std::numeric_limits<double>::quiet_NaN();
135 double rate = std::numeric_limits<double>::quiet_NaN();
140 std::vector<double>
q;
144 std::vector<std::array<double, 2>>
cteci;
149[[noreturn]]
inline void input(
const char* kind,
const std::string& msg) {
153[[noreturn]]
inline void numerical(
const char* kind,
const std::string& msg) {
159 std::snprintf(buf,
sizeof(buf),
"%g", v);
165 const long long a[6] = {1, 65539, 69069, 1, 65539, 69069};
166 const long long b[6] = {12345, 54321, 98765, 13579, 24680, 11111};
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);
175inline double vsum(
const std::vector<double>& x) {
177 for (
double v : x) s += v;
182inline long long pick(
const std::vector<double>& w,
double u) {
183 const double target = u *
vsum(w);
186 for (std::size_t k = 0; k < w.size(); ++k) {
189 j =
static_cast<long long>(k);
190 if (target < acc)
return j;
197inline double var(
const std::vector<double>& x) {
198 const double n =
static_cast<double>(x.size());
199 const double m =
vsum(x) / n;
201 for (
double v : x) acc += (v - m) * (v - m);
202 return acc / (n - 1.0);
214 for (
char& ch : c.
method) ch =
static_cast<char>(std::tolower(
static_cast<unsigned char>(ch)));
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));
222 if (c.
nCS < 2 || c.
nIS < 2)
223 input(
"Option",
"options.gamma leaves fewer than 2 cycles to crude or importance sampling.");
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.");
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) {
255 std::vector<State> Y;
256 std::vector<double> rt, ri;
259 const double q =
vsum(rt);
261 input(
"Argument",
"The chain reached an absorbing state outside the target set, so the cycle never ends.");
263 a = a - std::log(u) / q;
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);
279 if (j >= 0) L = L * (rt[j] / q) / (ri[j] / qi);
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)];
289 if (nsteps >= maxsteps)
290 numerical(
"MaxIter",
"A cycle took more than options.maxsteps = " +
fmt_g(maxsteps) +
" jumps.");
295template <
class State,
class Step,
class IsRates,
class Target>
300 const long long nCS = c.
nCS, nIS = c.
nIS;
301 const double dCS =
static_cast<double>(nCS), dIS =
static_cast<double>(nIS);
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;
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;
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;
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;
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);
327 const double p =
vsum(wIS) / dIS;
330 "No importance-sampled cycle reached the target set; increase options.nsamples or supply "
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;
338 s2 += std::pow(aCS[i], 2) * ret;
339 s3 += std::pow(aCS[i], 3) * ret;
341 for (
double v : aCS) sq += std::pow(v, 2);
345 const double eta = s1 / p;
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));
354 std::vector<double> vval, vw;
355 for (std::size_t i = 0; i < aIS.size(); ++i) {
357 vval.push_back(aIS[i]);
358 vw.push_back(wIS[i]);
361 const double swv =
vsum(vw);
362 for (
double& v : vw) v = v / swv;
364 const std::size_t nt = t.size();
368 for (std::size_t k = 0; k < nt; ++k) res.
Fexp[k] = 1.0 - std::exp(-t[k] / mu);
370 res.
Fconv.assign(nt, 0.0);
371 for (std::size_t k = 0; k < nt; ++k) {
373 for (std::size_t j = 0; j < vval.size(); ++j) {
374 const double x = t[k] - vval[j];
376 const double gv = eta > 0.0 ? 1.0 - std::exp(-x / eta) : 1.0;
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) -
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) {
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));
406 const double ET2 = (sq / dCS + 2.0 * s1 * mu) / p;
407 const double sigma2 = ET2 - std::pow(mu, 2);
409 res.
shape = std::pow(mu, 2) / sigma2;
410 res.
rate = mu / sigma2;
412 for (std::size_t k = 0; k < nt; ++k) res.
Fgamma[k] = boost::math::gamma_p(res.
shape, res.
rate * t[k]);
414 res.
Fgamma.assign(nt, std::numeric_limits<double>::quiet_NaN());
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]);
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) {
437 const double M = std::floor(std::log(u) / lq);
439 for (
double j = 0.0; j < M; j += 1.0) {
441 S = S + kval[
static_cast<std::size_t
>(std::floor(u * nK))];
444 const long long jv =
pick(vw, u);
445 Tb[l] = S + vval[
static_cast<std::size_t
>(jv)];
447 res.
Fboot.assign(nt, 0.0);
448 for (std::size_t k = 0; k < nt; ++k) {
451 if (v <= t[k]) cnt += 1.0;
452 res.
Fboot[k] = cnt / nb;
463 res.
muci = {{mu - z * semu, mu + z * semu}};
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()) {
473 for (
double qv :
opt.q) {
474 const double cq = -std::log(1.0 - qv);
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]}});
486 const std::function<std::vector<char>(std::size_t)>& makeMask,
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.");
502 for (std::size_t j = 0; j < n; ++j) {
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));
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.");
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)];
521 auto isr = [&Qis](
const int& x,
const std::vector<int>& Y,
const std::vector<double>&, std::vector<double>& ri) {
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]));
526 auto target = [&isA](
const int& x) {
return isA[
static_cast<std::size_t
>(x)] != 0; };
531 const std::size_t n = Q.
size();
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.");
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];
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);
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;
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;
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) {
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)
605 for (std::size_t j = 0; j < s.
rates.size(); ++j) {
608 rt.push_back(s.
rates[j]);
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.");
632 const std::vector<double>& t,
639 const std::vector<double>& t,
646 const std::vector<int>& target,
const std::vector<double>& t,
654 const std::vector<bool>& target,
const std::vector<double>& t,
InternalError(const std::string &what)
NumericError(const std::string &what)
SSJ's umontreal.ssj.rng.MRG32k3a, state and all.
void set_seed(const long long s[6])
SSJ's setSeed(long[6]).
double next_double()
SSJ's nextValue(): the combined generator, returning a double in (0, 1).
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.
Conservation laws of a layered queueing network, enumerated from its structure.
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....
Options, with the MATLAB defaults.
long long seed
in [0, 2^31)
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 > Fexp
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
std::vector< double > rates