\documentclass[11pt]{article}
\usepackage{listings}
\usepackage{numprint}
\usepackage{enumerate}
\usepackage{multirow}
\usepackage{bbm}
\usepackage{bbold}
\usepackage{../Math598}

\usepackage{amsfonts,amsmath,amssymb}

\setlength{\parindent}{0pt}

\setlength\headheight{13.6pt}
\setlength{\evensidemargin}{-0.25 in} \setlength{\oddsidemargin}{-0.25 in}
\setlength{\textwidth}{6.9 in} \setlength{\topmargin}{-0.75 in}
\setlength{\textheight}{9.3 in}


\lstloadlanguages{R}

\definecolor{keywordcolor}{rgb}{0,0.6,0.6}
\definecolor{delimcolor}{rgb}{0.461,0.039,0.102}
\definecolor{Rcommentcolor}{rgb}{0.101,0.043,0.432}

\lstdefinestyle{Rsettings}{
  basicstyle=\ttfamily,
  breaklines=true,
  showstringspaces=false,
  keywords={if, else, function, theFunction, tmp}, % Write as many keywords
  otherkeywords={},
  commentstyle=\itshape\color{Rcommentcolor},
  keywordstyle=\color{keywordcolor},
  moredelim=[s][\color{delimcolor}]{"}{"},
}

\lstset{basicstyle=\ttfamily, numbers=none, literate={~} {$\sim$}{2}}

\def\lra{\longrightarrow}
\def\CiP{\stackrel{p}{\lra}}
\def\calH{\mathcal{H}}
\def\calX{\mathcal{X}}
\def\o{\text{o}}

\def\Pr{\text{Pr}}

\begin{document}

<<setup, cache=FALSE, echo=FALSE>>=
library(knitr)
# global chunk options
opts_chunk$set(cache=TRUE, autodep=TRUE)
options(scipen=999)
options(repos=c(CRAN="https://cloud.r-project.org/"))
inline_hook <- function (x) {
  if (is.numeric(x)) {
    # ifelse does a vectorized comparison
    # If integer, print without decimal; otherwise print two places
    res <- ifelse(x == round(x),
      sprintf("%.2f", x),
      sprintf("%.4f", x)
    )
    paste(res, collapse = ", ")
  }
}
knit_hooks$set(inline = inline_hook)
@

\begin{center}
\textsclarge{MATH 559: Bayesian Theory and Methods}

\vspace{0.1 in} 

\textsc{Markov Chain Calculations}
\end{center}

The generic notation for a discrete-time Markov chain is
\[
\{X_t, t = 0,1,\ldots\}
\]
whereas typically in continuous time, we write
\[
\{X(t), t \in [0,T)\}.
\]
In both cases, the random process (i.e. time-indexed sequence of random variables) takes values on a countable set, $\calX$, usually a finite set of integers such as
\[
\calX = \{1,2,\ldots,K\}.
\]

\bigskip

\textbf{Markov chain example:}  A Markov chain is a discrete time model.  Let the state space be $\calX = \{1,2\}$ and the transition matrix be
\[
P =  \begin{pmatrix}
  P_{11} & P_{12} \\
  P_{21} & P_{22}
\end{pmatrix} = \begin{pmatrix}
  0.3 & 0.7 \\
  0.9 & 0.1
\end{pmatrix}
\]
so that for $t=0,1,\ldots$,
\[
P_{12} = \Pr[X_{t+1}=2|X_t=1] = 0.7 \qquad P_{21} = \Pr[X_{t+1}=1|X_t=2] = 0.9.
\]
Let the initial distribution be the row vector
\[
p^{(0)}= \left[ \Pr[X_0 = 1] \; \Pr[X_0 = 2] \right]= [0.25 \; 0.75]
\]
and let $p^{(t)},t=1,2,\ldots$ be the distribution vector at step $t$.  For example
\[
p^{(0)} = \left[ \Pr[X_1 = 1] \; \Pr[X_1 = 2] \right]
\]
where, by the Theorem of Total Probability, we have that
\begin{align*}
\Pr[X_1 = 1] & = \Pr[X_1 = 1|X_0 = 1] \Pr[X_0 = 1] + \Pr[X_1 = 1|X_0 = 2] \Pr[X_0 = 2] \\[6pt]
& = P_{11} p^{(0)}(1) + P_{21} p^{(0)}(2)
\end{align*}
and
\begin{align*}
\Pr[X_1 = 2] & = \Pr[X_1 = 2|X_0 = 1] \Pr[X_0 = 1] + \Pr[X_1 = 2|X_0 = 2] \Pr[X_0 = 2] \\[6pt]
& = P_{12} p^{(0)}(1) + P_{22} p^{(0)}(2)
\end{align*}
so that, in matrix form
\[
\left[ \Pr[X_1 = 1] \; \Pr[X_1 = 2] \right] = \left[ \Pr[X_0 = 1] \; \Pr[X_0 = 2] \right] P
\]
or
\[
p^{(0)} = p^{(0)} P.
\]
By recursion, and the time homogeneity of the chain, we have
\[
p^{(2)}= p^{(1)} P = p^{(0)} P^2.
\]
and consequently, for $t=1,2,\ldots$, we have that
\[
p^{(t)} = p^{(0)} P^t.
\]

\textbf{Holding time distribution:}  Consider the probability that a chain starting in state $k$ stays in state $k$ for $t$ more steps, that is
\[
\Pr[X_1 = k, X_2 = k, \ldots, X_t = k | X_0 = k].
\]
It is evident that this occurs only if there are no transitions out of $k$ in the $t$ steps, which occurs with probability $P_{kk}^t$, and corresponds to the event that the first transition out of state $k$ happens after more than $t$ steps.  Let $T_1(k)$ denote the holding time for state $k$, that is, the time of the first transition out of state $k$; we have that
\[
\Pr[T_1(k) > t] = 1-P_{kk}^t
\]
so that $T_1(k) \sim Geometric(1-P_{kk})$.  A similar result holds for any $k$, and by the Markov property, for transitions out of a state at any point in the chain.

<<IS00,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
set.seed(3242)
K<-2
P<-matrix(c(0.3,0.7,0.9,0.1),K,K,byrow=T);P

#Powers of P
Ptmp<-P %*% P
Ptmp

for(k in 3:8){
    Ptmp<-Ptmp %*% P
    print(Ptmp)
}
Tval<-20
p.mat<-matrix(0,nrow=Tval,ncol=2)
colnames(p.mat)<-c('State 1','State 2')
rownames(p.mat)<-paste('t =',0:(Tval-1))
p.mat[1,]<-c(0.25,0.75)
for(tval in 2:Tval){p.mat[tval,]<- p.mat[tval-1,] %*% P}
p.mat
@
We can see that the probability of each state is converging: if we run this to 200 steps, we see the convergence to limiting value
<<IS01,comment='+', fig.width=7, fig.height=4.0, fig.align='center'>>=
set.seed(3242)
Tval<-200
p.mat<-matrix(0,nrow=Tval,ncol=2)
colnames(p.mat)<-c('State 1','State 2')
rownames(p.mat)<-paste('t =',0:(Tval-1))
p.mat[1,]<-c(0.25,0.75)
for(tval in 2:Tval){p.mat[tval,]<- p.mat[tval-1,] %*% P}
p.mat[(Tval-10):Tval,]
par(mar=c(4,4,1,0))
plot(0:25,p.mat[1:26,1],type='l',ylim=range(0,1),xlab='t',ylab=expression(p[t](1)))
@
This limiting vector is the stationary distribution, $\pi$, which solves
\[
\pi = \pi P
\]
that is, it is probability distribution that is left unchanged by the application of the transition mapping by $P$
<<IS02,comment='+', fig.width=7, fig.height=4.0, fig.align='center'>>=
pivec<-p.mat[Tval,]
pivec
pivec %*% P
@
Notice also that we can compute $\pi$ as the identical rows of the matrix $P^t$ as $t \longrightarrow \infty$
\[
\mathbf{1} \pi = \lim_{t \lra \infty} P^t.
\]

<<IS03,comment='+', fig.width=7, fig.height=4.0, fig.align='center'>>=
Ptmp<-P
for(tval in 1:200){Ptmp<-P%*% Ptmp  }
Ptmp
@

\textit{Diagonalization} can help facilitate this calculation; attempt to write $P = A D A^{-1}$ where $D$ is a diagonal matrix, so that
\[
P^2 = P P = (A D A^{-1}) (A D A^{-1}) = A D^2 A^{-1}
\]
so therefore
\[
P^t = A D^t A^{-1}.
\]
We have that the entries of $D$ are the eigenvalues of $P$, and the columns of $A$ are the (right) eigenvectors.  We can use \texttt{eigen} in \texttt{R} to compute this.
<<IS03a,comment='+', fig.width=7, fig.height=4.0, fig.align='center'>>=
eigen(P)
D<-diag(eigen(P)$values)
A<-eigen(P)$vectors
A %*% D %*% solve(A)
@
Therefore
\[
P^t = A D^t A^{-1} = A
\begin{bmatrix}
  \Sexpr{round(D[1,1],2)} & 0 \\
  0 & \Sexpr{round(D[2,2],2)}
\end{bmatrix}^t
 A^{-1} = A
\begin{bmatrix}
  \Sexpr{round(D[1,1],2)} & 0 \\
  0 & (\Sexpr{round(D[2,2],2)})^t
\end{bmatrix} A^{-1}
\]
and so
\[
P^t \longrightarrow A
\begin{bmatrix}
  1 & 0 \\
  0 & 0
\end{bmatrix} A^{-1}
\]
<<IS03b,comment='+', fig.width=7, fig.height=4.0, fig.align='center'>>=
A %*% diag(c(1,0)) %*% solve(A)
@

\bigskip
\textbf{Reversibility:} This Markov chain is \textit{reversible} as it obeys \textit{detailed balance}, that is
\[
\pi_j P_{jk} = \pi_k P_{kj} \qquad j,k = 1,2, j \neq k.
\]
For detailed balance, we require that
\[
\pi_1 P_{12} = \pi_2 P_{21}
\]
but as $\pi_2 = 1-\pi_1$ we must have
\[
\frac{\pi_1}{1-\pi_1} = \frac{P_{21}}{P_{12}} = \frac{0.9}{0.7}
\]
so therefore have that
\[
\pi_1 = \frac{0.9}{0.7 + 0.9} = \Sexpr{0.9/1.6} \qquad \pi_2 = 1-\pi_1=\Sexpr{0.7/1.6}.
\]
as before.  Finally, note that realizations of the chain (that is, replicated sampled runs of the chain) reflect this stationary behaviour.  We have that, after $T$ steps
\[
\widehat \pi_j = \frac{1}{T} \sum_{t=1}^T \mathbb{1}\{X_t = j\}
\]
and observe that $\widehat \pi_j \CiP \pi_j$ as $T \lra \infty$.  The following simulation shows 200 realizations of the chain run up to $T=10000$ steps, with the estimate $\widehat \pi_2$ shown converging to the true value $\pi_2 = 0.4375$.


<<IS04,comment='+', fig.width=7, fig.height=5, fig.align='center'>>=
set.seed(3242)
Tval<-10000
nreps<-200
Xmat<-matrix(0,nrow=nreps,ncol=Tval)
Xmat[,1]<-rbinom(nreps,1,0.5)+1
pi.est<-Xmat*0
for(irep in 1:nreps){
    for(tval in 2:Tval){
        Xmat[irep,tval]<-sample(c(1:K),size=1,prob=P[Xmat[irep,tval-1],])
    }
    pi.est[irep,]<-cumsum(Xmat[irep,]-1)/c(1:Tval)
}
par(mar=c(4,5,2,0))
plot(c(1:Tval),xlab='t',pi.est[1,],ylim=range(0,1),type="l",ylab=expression(hat(pi)[2]))
for(irep in 2:nreps){lines(c(1:Tval),pi.est[irep,])}
abline(h=pivec[2],col="red",lwd=2)
@

\bigskip

\textbf{Example: 4 state chain.} Let the state space be $\calX = \{1,2,3,4\}$. First, we will randomly generate a $P$ matrix, and set the initial distribution $p^{(0)}$ to be uniform on the 4 states.

<<IS05,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
set.seed(3242)
K<-4
P<-matrix(rgamma(K*K,2),K,K)
P<-t(apply(P,1,function(x){return(x/sum(x))}))
P
p.mat<-matrix(0,nrow=Tval,ncol=K)
colnames(p.mat)<-c('State 1','State 2','State 3','State 4')
rownames(p.mat)<-paste('t =',0:(Tval-1))
p.mat[1,]<-rep(1,K)/K
@
Here is an example simulation:
<<IS06,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
Tval<-25
X<-rep(0,Tval)
X[1]<-sample(1:K,size=1,prob=p.mat[1,])
for(tval in 2:Tval){
    X[tval]<-sample(c(1:K),size=1,prob=P[X[tval-1],])
}
X
@
Here is the equilibrium distribution calculations:

<<IS07,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
for(tval in 2:Tval){p.mat[tval,]<- p.mat[tval-1,] %*% P}
p.mat[1:Tval,]
Ptmp<-P
for(tval in 1:Tval){Ptmp<-P%*% Ptmp  }
Ptmp
@


<<IS08,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
eigen(P)
D<-diag(eigen(P)$values)
A<-eigen(P)$vectors
A %*% D %*% solve(A)
A %*% diag(c(1,0,0,0)) %*% solve(A)
@

Notice that 1 is again an eigenvalue, all the other values are less than one in absolute value, so in the diagonalization calculation $D^t$ converges to the matrix with value 1 in the (1,1) position, and zeros elsewhere.

\pagebreak

\textbf{Continuous time model:}  For a Markov chain operating in continuous time, we have that $\{X(t),t \geq 0\}$ comprises an uncountable collection of random variables that take values on $\calX$, subject to the Markov assumption that says that for all $s,t > 0$, and for all $j$ and $k$
\[
\Pr[X(t+s) = k | X(s) = j, \calH_s ] = \Pr[X(t+s) = k | X(s) = j ]
\]
where $\calH_s$ is (informally) the history of the chain up to time $s$.  Typically the chain is presumed to be time homogeneous, so that
\[
\Pr[X(t+s) = k | X(s) = j ] \equiv \Pr[X(t) = k | X(0) = j ] \qquad \forall s,t,j,k.
\]
We can summarize the chain by listing the times at which the state value changes, and the state value after the change; that is we consider the sequence of transition times
\[
0 = T_0 < T_1 < \cdots < T_n < \cdots
\]
which is a countable collection of non-negative, increasing random variables, along with the countable collection of random variables
\[
X(0), X(T_1), X(T_2), \ldots, X(T_n), \ldots
\]
where we might write $X_{T_n} \equiv X(T_n) \equiv X_n$.

\bigskip

It remains to specify the form of
\[
\Pr[X(t) = k | X(0) = j ] = P_{jk}(t)
\]
say.  First, note that for $s,t>0$
\begin{align*}
\Pr[X(t+s) = k | X(0) = j ] & = \sum_{i=1}^K \Pr[X(t+s) = k | X(s) = i, X(0) = j ] \Pr[X(s) = i | X(0) = j ] & \textrm{Total Prob.}\\[6pt]
   & = \sum_{i=1}^K \Pr[X(t+s) = k | X(s) = i] \Pr[X(s) = i | X(0) = j ] & \textrm{Markov assumption}\\[6pt]
   & = \sum_{i=1}^K P_{ik}(t) P_{ji}(s) & \textrm{Time homog.}
\end{align*}
and arranging the entries $(j,k)$ into $K \times K$ matrix $P(t)$, we have
\begin{equation} \label{eq:C-K}
P(t+s) = P(s) P(t) = P(t) P(s)
\end{equation}
as $s$ and $t$ are arbitrary. These identities are the \textit{Chapman-Kolmogorov equations} in continuous time. Note that $P(0)$ is the identity matrix.


\bigskip
We consider the rate (per unit time) of transitions \textit{out} of each state, that is, define
\[
q_{jk} = \lim_{t \lra 0} \frac{P_{jk}(t)}{t} \qquad j \neq k.
\]
as the rate of transition from $j$ to $k$.  The quantity $q_{jk}$ is not a probability, but the \textit{net} (or \textit{aggregate}) rate of transitions out of state $j$ can be written
\[
\lambda_j = \sum_{k \neq j} q_{jk}
\]
so we may also consider the \textit{instantaneous} probability of transition by defining
\[
P_{jk} = \frac{q_{jk}}{\sum\limits_{i \neq j} q_{ji}}
\]
which is does not depend on $t$, and satisfies
\[
0 \leq P_{jk} \leq 1 \qquad \sum_{k \neq j} P_{jk} = 1.
\]
The $K \times K$ matrix of $P_{jk}$ values has zero on the main diagonal, that is, $P_{jj} = 0, j=1,\ldots,K$.  We may write
\[
q_{jk} = \lambda_j P_{jk}.
\]
Note finally that
\[
\lambda_j = \sum_{k \neq j} q_{jk} = \sum_{k \neq j} \lim_{t \lra 0} \frac{P_{jk}(t)}{t} = \lim_{t \lra 0} \sum_{k \neq j} \frac{P_{jk}(t)}{t} = \lim_{t \lra 0} \frac{(1- P_{jj}(t))}{t}.
\]
The model essentially assumes that for $h$ small and for all $t > 0$
\begin{equation}\label{eq:model}
\Pr[X(t+h) = k | X(t) = j] = q_{jk} h + \o(h) = \lambda_j P_{jk} h + \o(h)
\end{equation}
so that for all $k \neq j$,
\[
P_{jk}(h) = \lambda_j P_{jk} h + \o(h).
\]
Now the Chapman-Kolmogorov equations imply that as $P(0)$ is the identity
\[
\frac{P(t+h)-P(t)}{h} = \frac{P(t)P(h)-P(t)}{h} = P(t) \frac{P(h)-P(0)}{h}
\]
and taking the limit as $h \longrightarrow 0$ we have
\begin{equation}\label{eq:DE}
P^\prime(t) = P(t) P^\prime(0) = P^\prime(0) P(t)
\end{equation}
where the prime indicates time derivative.  All of these quantities are matrices, and the derivative is interpreted componentwise.   Taking the second version
\[
P^\prime(t) = P^\prime(0) P(t)
\]
evaluating componentwise we have
\[
P_{jk}^\prime(t) = \sum_{i=1}^K P_{ji}^\prime(0) P_{ik}(t).
\]
Recall that for $i \neq j$
\[
 P_{ji}^\prime(0) = q_{ji} = \lambda_j P_{ji}.
\]
Now consider $P_{jj}^\prime(0)$, that is
\[
P_{jj}^\prime(0) = \lim_{h \lra 0} \frac{(P_{jj}(h) - P_{jj}(0))}{h} = \lim_{h \lra 0} \frac{(P_{jj}(h) - 1)}{h} = -\lambda_j
\]
by the earlier definition.   The matrix $P^\prime(0)$ therefore takes the form
\[
P_{jk}^\prime(0) = \left\{
\begin{array}{rr}
  q_{jk} & k \neq j \\[6pt]
  -\lambda_j & k = j
\end{array}
\right.
\]
and is termed the \textit{infinitesimal generator} matrix.  Note that
\[
\sum_{k=1}^K P_{jk}^\prime(0) = -\lambda_j + \sum_{k \neq j} q_{jk} = -\lambda_j + \lambda_j = 0
\]
by the earlier definitions, so the rows of $P^\prime(0)$ sum to zero.

\begin{itemize}

\item \textbf{Backward equation:} We have from $P^\prime(t) = P^\prime(0) P(t)$ that for any $j,k$,
\[
P_{jk}^\prime(t) = \sum_{i=1}^K P_{ji}^\prime(0) P_{ik}(t).
\]
Note that for $k \neq j$,
\[
P_{jk}^\prime(0) = \lim_{h \lra 0} \frac{P_{jk}(h)-P_{jk}(0)}{h} = \lim_{h \lra 0} \frac{P_{jk}(h)}{h} = q_{jk}
\]
as $P(0)$ has zero as the $(j,k)$th entry.  In fact
\begin{align*}
\frac{P_{jk}(t+h)-P_{jk}(t)}{h} & = \frac{1}{h} \left( \sum_{i=1}^K P_{ji}(h) P_{ik}(t) - P_{jk}(t) \right) & \text{C-K eqn. \eqref{eq:C-K}}\\[6pt]
& =  \left( \sum_{i \neq j} \frac{P_{ji}(h)}{h} P_{ik}(t) - \frac{(1-P_{jj}(h))}{h} P_{jk}(t) \right)
\end{align*}
and taking limits as $h \lra 0$, we have
\[
P_{jk}^\prime(t) = \sum_{i \neq j} q_{ji} P_{ik}(t) - \lambda_j P_{jk}(t)
\]
which is termed the \textit{backward} Kolmogorov equation; note that as $t \lra 0$
\[
P_{jk}^\prime(0) = \lim_{t \lra 0} P_{jk}^\prime(t) = \sum_{i \neq j} q_{ji} P_{ik}(0) - \lambda_j P_{jk}(0) = q_{jk}
\]
as before, as only the term with $i=k$ contributes to the sum.

\medskip

\item \textbf{Forward equation:} We could have equivalently written $P^\prime(t) = P(t) P^\prime(0) $ so that
\[
P_{jk}^\prime(t) = \sum_{i=1}^K P_{ji}(t) P_{ik}^\prime(0)
\]
and hence
\begin{align*}
\frac{P_{jk}(t+h)-P_{jk}(t)}{h} & = \frac{1}{h} \left( \sum_{i=1}^K P_{ji}(t) P_{ik}(h) - P_{jk}(t) \right) & \text{C-K eqn. \eqref{eq:C-K}}\\[6pt]
& =  \left( \sum_{i \neq k} \frac{P_{ik}(h)}{h} P_{ji}(t) - \frac{(1-P_{kk}(h))}{h} P_{jk}(t) \right)
\end{align*}
and taking limits as $h \lra 0$, we have
\[
P_{jk}^\prime(t) = \sum_{i \neq j} q_{ik} P_{ji}(t) - \lambda_k P_{jk}(t)
\]
which is termed the \textit{forward} Kolmogorov equation.

\end{itemize}

\bigskip

\textbf{Matrix exponentials:}  We seek to solve \eqref{eq:DE} to get $P(t)$ explicitly.  Recall first that the solution to the ordinary differential equation
\[
\frac{d y(t) }{d t} = \mu y(t)
\]
is
\[
y(t) = y(0) \exp\{ \mu t \}.
\]
The equivalent for \eqref{eq:DE} would be
\[
P(t) = P(0) \exp\{ P^\prime(0) t \} = \exp\{ P^\prime(0) t \}
\]
as $P(0)$ is the identity matrix, but we need to take care with this calculation as $P^\prime(0)$ is also a matrix -- the exponentiation does not operate componentwise.  If we use the usual definition of the exponential function, we may write for matrix $A$
\[
\exp\{ A t \} = \sum_{n=0}^\infty A^n \frac{t^n}{n!}
\]
implying the solution
\[
P(t) = \sum_{n=0}^\infty \{P^\prime(0)\}^n \frac{t^n}{n!}.
\]
We confirm this is a solution by checking directly:
\[
P^\prime(t) = \sum_{n=1}^\infty \{P^\prime(0)\}^n \frac{t^{n-1}}{(n-1)!} = P^\prime(0) \sum_{n=1}^\infty \{P^\prime(0))\}^{n-1} \frac{t^{n-1}}{(n-1)!} \equiv  P^\prime(0) P(t).
\]
Thus we have that
\begin{equation}\label{eq:PtMatrixExp}
P(t) = \exp\{ P^\prime(0) t \}.
\end{equation}

\bigskip

\textbf{Holding times:}  Recall that the net rate of transition out of state $j$ is $\lambda_j$.  Suppose that $X_{n-1} \equiv X(T_{n-1}) = j$.  The next transition is observed at $T_{n}$.  Let
\[
L_{n} = T_{n} - T_{n-1} \qquad n=1,2,\ldots
\]
We have by the Markov property that $L_1,L_2,\ldots,L_n,\ldots$ are independent.  We have also that
\[
\Pr[L_n > l|X_{n-1} = j] = \exp\{ -\lambda_j l\}
\]
that is, given $X_{n-1} = j$, $L_n \sim Exponential(\lambda_j)$.   To see this, consider the interval $(0,l]$ broken into $N$ equal intervals,
\[
\left(0,\frac{l}{N} \right], \left(\frac{l}{N},\frac{2l}{N} \right],\ldots, \left(\frac{(N-1)l}{N},l \right].
\]
with $N$ large. Then by assumption, for $i=1,\ldots,N$,
\[
P \left[ \text{`One event in $\left(\frac{(i-1)l}{N},\frac{il}{N}\right]$'} \bigg |X_{n-1} = j \right] = \frac{\lambda_j l}{N} + \o(N^{-1})
\]
\begin{align*}
\Pr[\text{`No event in $(0,l]$'}|X_{n-1} = j] & = P \left[ \bigcap_{i=1}^N \text{`No event in $\left(\frac{(i-1)l}{N},\frac{il}{N} \right]$ '} \bigg |X_{n-1} = j \right] \\[6pt]
& = \left(1-\frac{\lambda_j l}{N} + \o(N^{-1})\right)^N & \text{independence}\\[6pt]
& \lra \exp\{-\lambda_j l\}
\end{align*}
as $N \lra \infty$.  By using the same argument, transitions out from state $j$ occur at rates $q_{jk}, k \neq j$.  Suppose, without loss of generality, that $j=1$, and consider random variables $Z_2,\ldots,Z_K$ where $Z_k \sim Exponential(q_{1k}), k=2,\ldots,K$.  These variables are the hypothetical exit times into states $2,\ldots,K$, conditional on $X_{n-1} = 1$.  The observed transition occurs after length of time $L_n$ since entering state $1$ at time $T_{n-1}$.  Then
\[
L_n = \min\{Z_2,\ldots,Z_K\}
\]
and by standard theory for minimum order statistics
\[
L_n \sim Exponential \left(\sum_{k=2}^K q_{1k} \right) \equiv Exponential(\lambda_1).
\]
The equivalent result holds for whatever state the chain enters at time $T_{n-1}$, that is, whatever the value of $X_{n-1}$.  Note also that
\[
P_[X_{n} = k | X_{n-1} = j] = \frac{q_{jk}}{\lambda_j} = P_{jk}
\]
which tells us that the random variables $X_0,X_1,\ldots,X_n,\ldots$ observed at the transition times form a discrete time Markov chain with transition matrix formed by the instantaneous probabilities $P_{jk}$.

\bigskip
\textbf{Stationary distribution:}  As in the discrete time case, we can consider the stationary distribution of the continuous time Markov chain.  Let $p(j,t)$ denote the probability of being in state $j$ at time $t$ after the initial state is chosen from initial distribution $p(j,0)$.  We may define the stationary distribution $\pi$ by
\[
\pi_k = \lim_{t \lra \infty} P_{jk}(t) \qquad k=1,\ldots,K
\]
assuming the limit exists and does not depend on $j$.  In vector form we have as before
\[
\mathbf{1} \pi = \lim_{t \lra \infty} P (t).
\]
Recall from the forward Kolmogorov equation
\[
P_{jk}^\prime(t) = \sum_{i \neq k} q_{ik} P_{ji}(t) - \lambda_k P_{jk}(t).
\]
Letting $t \lra \infty$, we obtain
\begin{align*}
\lim_{t \lra \infty} P_{jk}^\prime(t) & = \lim_{t \lra \infty} \left\{\sum_{i \neq k} q_{ik} P_{ji}(t) - \lambda_k P_{jk}(t) \right\} \\[6pt]
& = \sum_{i \neq k} q_{ik} \pi_i - \lambda_k \pi_k.
\end{align*}
Now, as it assumed the limits exist in the interval $[0,1]$ for the $P_{jk}(t)$, we must have that 
\[
\lim_{t \lra \infty} P_{jk}^\prime(t) = 0
\]
implying that $\pi$ must satisfy
\[
\sum_{i \neq k} q_{ik} \pi_i - \lambda_k \pi_k = 0 \qquad  k = 1,\ldots,K
\]
which defines a set of linear equations which can be solved to find $\pi$, that is
\[
\begin{bmatrix}
\pi_1 & \pi_2 & \cdots & \pi(K)
\end{bmatrix} \begin{bmatrix}
-\lambda_1 & q_{12} & q_{13} & \cdots & q_{1K} \\[6pt]
q_{21} & -\lambda_2 & q_{23} & \cdots & q_{2K} \\[6pt]
q_{31} &  q_{32}    & -\lambda_3 & \cdots & q_{3K} \\[6pt]
\vdots & \vdots     & \vdots &  \ddots & \vdots \\[6pt]
q_{K1} & q_{K2}     & q_{K3} & \cdots & -\lambda_K
\end{bmatrix} = \mathbf{0}
\]
that is, in the previous notation
\[
\pi P^\prime (0) = \mathbf{0}.
\]
Note that $\pi$ satisfies
\[
\lambda_k \pi_k = \sum_{i \neq k} q_{ik} \pi_i \qquad k=1,\ldots,K
\]
and the left hand side of this equation measures the long run rate at which the chain leaves state $k$, whereas the right hand side measures the net log run rate at which the chain enters state $k$.  That is, the stationary distribution results when these to quantities balance.  We may also write this
\[
\pi_k  = \sum_{i \neq k} P_{ik} \pi_i
\]
using the instantaneous probability matrix.

\bigskip

\textbf{Example: Two state chain.}  Let $K = 2$, and suppose that the infinitesimal generator is
\[
P^\prime (0) = 
\begin{bmatrix}
-\lambda_1 & q_{12} \\
q_{21} & -\lambda_2
\end{bmatrix}
=\begin{bmatrix}
-1 & 1 \\
1.5 & -1.5
\end{bmatrix}
\]
(recall that the row sums must be zero).

<<IS09,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
set.seed(3242)
K<-2
Q<-matrix(c(-1,1.5,1,-1.5),2,2)
Q
lambda<--diag(Q)
P.inst<-Q/lambda+diag(rep(1,K))
P.inst
@
We can compute the $P(t)$ matrix by using \eqref{eq:PtMatrixExp} and the \texttt{expm} function from the \texttt{Matrix} package.

<<IS10,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
library(Matrix)
Pt.mat<-array(0,c(10,2,2))
for(tval in 1:10){
    Pt.mat[tval,,]<-as.matrix(expm(tval*Q))
}
Pt.mat[2,,]
Pt.mat[5,,]
Pt.mat[10,,]
@
This computation gives the stationary distribution by computing for large $t$.  Here is an example simulation on the interval $[0,10]$
<<IS11,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
p0<-c(1:K)/K
X<-Tvec<-rep(0,1000)
Tval<-10
X[1]<-sample(1:K,size=1,prob=p0)
Ttot<-0
ico<-1
Tvec[1]<-0
while(Ttot < Tval){
    L<-rexp(1,lambda[X[ico]])
    Ttot<-Ttot+L
    ico<-ico+1
    Tvec[ico]<-Ttot
    X[ico]<-ifelse(X[ico-1]==1,2,1)
}
X<-X[1:ico]
Tvec<-Tvec[1:ico]
cbind(Tvec,X)
par(mar=c(4,4,2,0))
plot(Tvec,X,xlim=range(0,10),ylim=range(0,3),type='s',yaxt='n',xlab='t',ylab='X(t)')
axis(2,at=c(1,2))
@

\bigskip

\textbf{Example: Four state chain.}  Let $K = 4$, and suppose that the infinitesimal generator is
\[
P^\prime (0) =
\begin{bmatrix}
-\lambda_1 & q_{12} & q_{13} & q_{14}\\
q_{21} & -\lambda_2 & q_{23} & q_{24}\\
q_{31} & q_{32} & -\lambda_3 & q_{34}\\
q_{41} & q_{42} & q_{43} & - \lambda_4
\end{bmatrix}
=\begin{bmatrix}
-3 & 1 & 2 & 0\\
2 & -3 & 0 & 1\\
0.5 & 0.5 & -2 & 1\\
0 & 0 & 2 & -2
\end{bmatrix}
\]
Note that the net flow out of states 1 and 2 is higher than the net flow out of states 3 and 4.   Note also that the instantaneous transition matrix is
\[
\begin{bmatrix}
0 & 1/3 & 2/3 & 0\\
2/3 & 0 & 0 & 1/3\\
1/4 & 1/4 & 0 & 1/2\\
0 & 0 & 1 & 0
\end{bmatrix}
\]
so, for example, transitions out of state 4 must be into state 3.

<<IS12,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
set.seed(3242)
K<-4
qvec<-c(-3,2,0.5,0,1,-3,0.5,0,2,0,-2,2,0,1,1,-2)
Q<-matrix(qvec,4,4)
Q
lambda<--diag(Q)
P.inst<-Q/lambda+diag(rep(1,K))
P.inst
@
We can compute the $P(t)$ matrix by using \eqref{eq:PtMatrixExp} and the \texttt{expm} function from the \texttt{Matrix} package.

<<IS13,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
library(Matrix)
Pt.mat<-array(0,c(10,4,4))
for(tval in 1:10){
    Pt.mat[tval,,]<-as.matrix(expm(tval*Q))
}
Pt.mat[2,,]
Pt.mat[5,,]
Pt.mat[10,,]
@
Here are two example simulations on the interval $[0,10]$: simulation 1
<<IS14,comment='+', fig.width=7, fig.height=4.5, fig.align='center'>>=
p0<-c(1:K)/K
X<-Tvec<-rep(0,1000)
Tval<-10
X[1]<-sample(1:K,size=1,prob=p0)
Ttot<-0
ico<-1
Tvec[1]<-0
Svec<-c(1:K)
while(Ttot < Tval){
    L<-rexp(1,lambda[X[ico]])
    Ttot<-Ttot+L
    ico<-ico+1
    Tvec[ico]<-Ttot
    X[ico]<-sample(Svec[-X[ico-1]],size=1,prob=P.inst[X[ico-1],-X[ico-1]])
}
X<-X[1:ico]
Tvec<-Tvec[1:ico]
cbind(Tvec,X)
par(mar=c(4,4,2,0))
plot(Tvec,X,xlim=range(0,10),ylim=range(0,5),type='s',yaxt='n',xlab='t',ylab='X(t)')
axis(2,at=c(1:K))
@
Simulation 2:
<<IS15,comment='+', fig.width=7, fig.height=4.5, fig.align='center',echo=FALSE>>=
p0<-c(1:K)/K
X<-Tvec<-rep(0,1000)
Tval<-10
X[1]<-sample(1:K,size=1,prob=p0)
Ttot<-0
ico<-1
Tvec[1]<-0
Svec<-c(1:K)
while(Ttot < Tval){
    L<-rexp(1,lambda[X[ico]])
    Ttot<-Ttot+L
    ico<-ico+1
    Tvec[ico]<-Ttot
    X[ico]<-sample(Svec[-X[ico-1]],size=1,prob=P.inst[X[ico-1],-X[ico-1]])
}
X<-X[1:ico]
Tvec<-Tvec[1:ico]
par(mar=c(4,4,2,0))
plot(Tvec,X,xlim=range(0,10),ylim=range(0,5),type='s',yaxt='n',xlab='t',ylab='X(t)')
axis(2,at=c(1:K))
@

\textbf{Diagonalization:}  Recalling that we have the explicit form
\[
P(t) = \exp\{ P^\prime(0) t \} = \sum_{n=0}^\infty \{P^\prime(0)\}^n \frac{t^n}{n!}.
\]
so if we can diagonalize $P^\prime(0)$ as
\[
P^\prime(0) = A D A^{-1}
\]
then
\[
\left\{ P^\prime(0) \right\}^n  = A D^n A^{-1}
\]
and so
\[
P(t) = \exp\{ P^\prime(0) t \} = \sum_{n=0}^\infty A D^n A^{-1} \frac{t^n}{n!} = A \left( \sum_{n=0}^\infty D^n \frac{t^n}{n!} \right) A^{-1} = A \exp\{ D t \} A^{-1}
\]
If $D$ is the diagonal matrix with diagonal entries $(d_1,\ldots,d_K)$, then $\exp\{ D t \}$ is also a diagonal matrix with diagonal entries $(\exp\{d_1 t\},\ldots,\exp\{d_K t\})$, so $P(t)$ is easily computed.

<<IS16,comment='+', fig.width=7, fig.height=4.0, fig.align='center'>>=
eigen(Q)
D<-diag(eigen(Q)$values)
A<-eigen(Q)$vectors
round(A %*% D %*% solve(A),6)
round(A %*% diag(diag(exp(D*10))) %*% solve(A),6) #Computing P(10).
@

\end{document}

