1function [piTimeAvg,piExit,kmax]=ctmc_timeaverage(pi0,Q,t,tol,maxiter)
2% [PITIMEAVG,PIEXIT,KMAX]=CTMC_TIMEAVERAGE(PI0,Q,T,TOL,MAXITER)
4% Time-averaged transient distribution of a CTMC with generator Q over [0,T],
5% starting from the (arbitrary) initial distribution PI0, via Jensen
's
6% uniformization. Companion of CTMC_UNIFORMIZATION, which returns only the
7% endpoint PI0*exp(Q*T); this function additionally returns the time average
9% PITIMEAVG = PI0 * (1/T) * \int_0^T exp(Q*tau) d(tau)
11% as well as the endpoint PIEXIT = PI0*exp(Q*T) (computed from the same series).
12% Both are obtained without forming any dense matrix exponential.
14% Uniformization: with q = 1.1*max|diag(Q)| and P = I + Q/q (row-stochastic),
15% PI0*exp(Q*T) = sum_j w_j(qT) * (PI0*P^j)
16% PI0*\int_0^T exp(Q*tau) = (1/q) * sum_j (1 - W_j(qT)) * (PI0*P^j)
17% where w_j and W_j are the Poisson(qT) PMF and CDF. The time average divides
18% the integral by T (equivalently the integral sum by q*T).
20% Copyright (c) 2012-2026, Imperial College London
30q = 1.1*max(abs(diag(Q)));
31Qs = speye(size(Q)) + sparse(Q)/q;
34% Number of Poisson terms needed (right-tail below tol), as in ctmc_uniformization
35k = 0; s = 1; r = 1; iter = 0; kmax = 1;
41 if (1 - exp(-qt)*s) <= tol
47% Accumulate endpoint and integral over the shared PI0*P^j sequence
48w = exp(-qt); % Poisson PMF w_0
49W = w; % Poisson CDF W_0
52piIntSum = max(1 - W, 0) * P;
57 piExit = piExit + w * P;
58 piIntSum = piIntSum + max(1 - W, 0) * P;
61piTimeAvg = piIntSum / qt; % (1/q)*sum / t = sum/(q*t)