---
title: Markov chains and reliability
heading: Steady states, settling times and the expected time to failure
eyebrow: A7 · Lesson 35 · Markov chains and reliability
xp: 40
---

::: hook
A wireless link drifts between a good state, where errors are rare, and a bad one, where a fade wipes out whole bursts of bits. A redundant power supply has two units; either can carry the load, a failed one gets repaired, and the system only goes down if the second fails before the first is back. Neither has a simple formula, but both are **Markov chains**: a vector of probabilities that a fixed matrix multiplies forward one step at a time. Lesson 34 showed that such a matrix has the eigenvalue 1. This lesson uses the whole spectrum: the eigenvector for 1 is the long-run behavior, the next eigenvalue says how fast it arrives, and an inverse matrix gives the expected time until something breaks.
:::

::: play
- The solid curve is the mean time to failure of two units with repair, against the probability per hour that a failed unit is repaired. The dashed lines are the same two units with no repair, and one unit alone.
- Slide the failure probability. Halving it roughly quadruples the repaired system's life, but only doubles the others'.
:::

```sim plot
view: graph
x: mu = 0.001..1 log
y: hours = 1000..100000000 log
slider: lam = 0.0002..0.005 step 0.0001 = 0.001
plot: (3*lam + mu)/(2*lam^2) | label: two units, repaired
plot: 1.5/lam + 0*mu | dashed | label: two units, no repair
plot: 1/lam + 0*mu | dashed | color: ch3 | label: one unit
readout: gain from repairs at 0.1 an hour = ((3*lam + 0.1)/(2*lam^2))/(1.5/lam) | digits: 3
```

::: predict
## A link in its good state stays good with probability 0.95 each step; in its bad state it recovers with probability 0.3 each step. In the long run, what fraction of steps is it bad?

- [ ] 5%
- [x] About 14%
- [ ] 30%
- [ ] 50%

::: reveal
About 14%: $0.05/(0.05 + 0.3) = 1/7$. In the long run the flow from good to bad must balance the flow back, $0.05\,\pi_g = 0.3\,\pi_b$, so the bad state gets one share in seven. The link falls into a fade rarely, but each fade lasts a while: $1/0.3 \approx 3.3$ steps on average.
:::
:::

::: nameit
## The transition matrix

Number the states and let column $j$ of $P$ hold the probabilities of moving from state $j$ to each state, so every column adds to 1. If $\mathbf{x}_k$ holds the probabilities of being in each state at step $k$,

$$\mathbf{x}_{k+1} = P\mathbf{x}_k \qquad \mathbf{x}_k = P^k\mathbf{x}_0$$

## The steady state

Because every column adds to 1, the row vector of ones satisfies $\mathbf{1}^TP = \mathbf{1}^T$, so 1 is an eigenvalue of $P$. Its eigenvector, scaled so its entries add to 1, is the **steady state** $\boldsymbol{\pi}$: $P\boldsymbol{\pi} = \boldsymbol{\pi}$. For two states with switching probabilities $p$ (from 1 to 2) and $q$ (back),

$$\boldsymbol{\pi} = \left(\frac{q}{p + q},\ \frac{p}{p + q}\right)$$

## How fast it settles

Write $\mathbf{x}_0$ in the eigenvectors of $P$. Each step multiplies each component by its eigenvalue, so everything except the steady state shrinks like $|\lambda_2|^k$, where $\lambda_2$ is the next-largest eigenvalue in size. For two states $\lambda_2 = 1 - p - q$. A chain whose $|\lambda_2|$ is close to 1 has a long memory.

## Absorbing chains and the time to failure

A state you can't leave, like "both supplies down", is **absorbing**. Put the transient states first; the part of $P$ that moves among them is a square block $Q$. Then

$$N = (I - Q)^{-1} = I + Q + Q^2 + \cdots$$

is the **fundamental matrix**: $N_{ij}$ is the expected number of steps spent in transient state $i$ starting from state $j$. Adding up column $j$ gives the expected number of steps before absorption, the **mean time to failure** from state $j$.
:::

::: example
## A link has $P = \begin{bmatrix}0.95 & 0.3\\0.05 & 0.7\end{bmatrix}$ (state 1 good, state 2 bad). The bit error rate is 0.001 in the good state and 0.1 in the bad one. Find the steady state, the average error rate, and how many steps it takes a link that starts good to come within 1% of the steady state.

::: solution
1. **Eigenvalues.** They are 1 and
   $$1 - 0.05 - 0.3 = 0.65$$
2. **Steady state.**
   $$(0.3, 0.05)/0.35 = (0.857, 0.143)$$
3. **Average error rate.**
   $$\begin{aligned} &0.857 \times 0.001 + 0.143 \times 0.1 \\ &= 0.0151 \end{aligned}$$
   nearly all of it from the 14% of the time in fades.
4. **Approach to steady state.** Starting good, the bad-state probability approaches 0.143 with an error that shrinks by 0.65 each step.
5. **Within 1%.** That needs $0.65^k < 0.01$:
   $$\begin{aligned} k &> \frac{\ln 0.01}{\ln 0.65} \\ &= 10.7 \end{aligned}$$
   so 11 steps.

**Answer:** the steady state is $(0.857, 0.143)$, the average error rate is 0.0151, and a link that starts good is within 1% of the steady state after 11 steps.
:::
:::

::: example
## Two supplies each fail with probability 0.001 per hour. A failed one is repaired with probability 0.1 per hour, but if the second fails first, the system is down. Starting with both working, what is the expected time to system failure? What would it be without repair?

::: solution
1. **States.** The transient states are "both up" and "one up"; "both down" absorbs.
2. **Transitions.** Per hour, both-up moves to one-up with probability 0.002 (either unit failing). One-up returns with probability 0.1 and fails with 0.001. So
   $$Q = \begin{bmatrix}0.998 & 0.1\\0.002 & 0.899\end{bmatrix}$$
3. **Fundamental matrix.**
   $$\begin{aligned} N &= (I - Q)^{-1} \\ &= \begin{bmatrix}50\,500 & 50\,000\\1000 & 1000\end{bmatrix} \end{aligned}$$
4. **Mean time to failure.** From both-up the system spends 50 500 hours, on average, with both working and 1000 with one, so its mean time to failure is 51 500 hours.
5. **Without repair.** With $0.1 \to 0$, $N$'s first column becomes $(500, 1000)$: 1500 hours, only 1.5 times a single unit's 1000.
6. **Compare.** Repair multiplies the redundant system's life by 34, which is why redundancy without maintenance buys so little.

**Answer:** 51 500 hours with repair, and 1500 hours without it.
:::
:::

::: example
## A machine is "running", "degraded" or "failed and being repaired". Each hour, running stays running with 0.98 and degrades with 0.02; degraded fails with 0.1, stays with 0.85 and is serviced back to running with 0.05; failed is repaired to running with 0.25 and stays failed otherwise. What fraction of the time is it running?

::: solution
1. **Find the steady state.** Each column of `P` adds to 1, and the eigenvector for $\lambda = 1$, scaled to add to 1, is the steady state:

```python
import numpy as np
P = np.array([[0.98, 0.05, 0.25],
              [0.02, 0.85, 0.00],
              [0.00, 0.10, 0.75]])
w, V = np.linalg.eig(P)
pi = np.real(V[:, np.argmin(abs(w - 1))])
pi /= pi.sum()
print(pi)          # [0.8427 0.1124 0.0449]
```

2. **Read the result.** Running 84.3% of the time, degraded 11.2% and down 4.5%.
3. **How fast it settles.** The other two eigenvalues, a complex pair $0.79 \pm 0.02j$, say a disturbance dies away by a factor of 0.79 an hour: to under 1% within 20 hours.
4. **Check by hand.** The balance checks it: degraded is entered at $0.02\pi_r$ and left at $0.15\pi_d$, so
   $$\pi_d = 0.133\pi_r$$

**Answer:** it's running 84.3% of the time (degraded 11.2% and down 4.5%).
:::
:::

::: check
given: p = 0.01 | 0.05 | 0.1 | 0.15; q = 0.2 | 0.3 | 0.5
answer: p/(p + q)
tolerance: 0.5%

## A two-state channel goes from good to bad with probability {p} per step and from bad to good with {q}. In the long run, what fraction of the steps is it bad?

::: right
Right. Balancing the flows, $\pi_g\given{p} = \pi_b\given{q}$, with $\pi_g + \pi_b = 1$, gives $\pi_b = \given{p}/(\given{p} + \given{q})$ = {answer}.
:::

::: misses
- [q/(p + q)] That's the fraction of time it's good.
- [p] That's the chance of falling into the bad state in one step, not how much of the time it spends there.
- [p/q] That's the ratio $\pi_b/\pi_g$. Divide by $1 + \given{p}/\given{q}$ to make the two add to 1.
- [any] Not yet. Balance the flows between the states and use $\pi_g + \pi_b = 1$.
:::
:::

::: check
kind: parts
given: p = 0.02 | 0.05 | 0.1; q = 0.15 | 0.25 | 0.5

## The same kind of channel, with $p$ = {p} and $q$ = {q}.

::: part
answer: 1 - p - q
tolerance: 0.5%

### What is the second eigenvalue of its transition matrix?

::: misses
- [p + q] The trace is $(1 - p) + (1 - q)$ and one eigenvalue is 1, so the other is the trace minus 1.
- [any] Not yet. The eigenvalues add to the trace, $2 - p - q$, and one of them is 1.
:::
:::

::: part
answer: 1/q
tolerance: 0.5%

### How many steps does a bad spell last on average?

::: misses
- [1/p] That's how long a good spell lasts. A bad spell ends with probability {q} each step.
- [q] That's the chance of leaving each step. The expected length is one over it.
- [any] Not yet. A spell that ends with probability $q$ each step lasts $1/q$ steps on average.
:::
:::

::: right
Right. A small $p + q$ puts the second eigenvalue near 1: the channel remembers its state for a long time, and its errors come in long bursts.
:::
:::

::: check
kind: parts
given: lam = 0.0005 | 0.001 | 0.002

## A unit fails with probability {lam} per hour and is never repaired.

::: part
answer: 1/lam
unit: h
tolerance: 0.5%

### What is one unit's mean time to failure, in hours?

::: misses
- [lam] That's the failure probability per hour. The expected time is its reciprocal.
- [any] Not yet. A unit that fails with probability $\lambda$ each hour lasts $1/\lambda$ hours on average.
:::
:::

::: part
answer: 1/(2*lam) + 1/lam
tolerance: 0.5%

### Two such units run in parallel, and the system fails when both have. What is its mean time to failure?

::: misses
- [2/lam] That treats the second unit as starting fresh after the first fails, with nothing lost while both run. While both run, the first failure comes twice as fast: $1/(2\lambda)$.
- [1/(2*lam)] That's only the time until the first unit fails. The survivor then runs another $1/\lambda$ on average.
- [any] Not yet. Add the expected time until the first failure, $1/(2\lambda)$, and the survivor's expected life, $1/\lambda$.
:::
:::

::: right
Right. Without repair, a second unit adds only half a unit's life, 1.5 times in all. It's repair, getting back to two units before the second fails, that makes redundancy pay.
:::
:::

::: check
kind: python
given: k = 0..2 int

## The starter gives a 3-state transition matrix `P` (columns add to 1). Set `pi` to its steady state from `np.linalg.eig` (the eigenvector for the eigenvalue nearest 1, scaled to add to 1), `lam2` to the size of the next-largest eigenvalue, and `x50` to the state probabilities after 50 steps from state 0, found by repeated multiplication.

```python starter
import numpy as np
P = [np.array([[0.98, 0.05, 0.25], [0.02, 0.85, 0.0], [0.0, 0.10, 0.75]]),
     np.array([[0.9, 0.2, 0.1], [0.05, 0.7, 0.3], [0.05, 0.1, 0.6]]),
     np.array([[0.5, 0.25, 0.0], [0.5, 0.5, 0.5], [0.0, 0.25, 0.5]])][k]
pi = np.ones(3) / 3
lam2 = 0
x50 = np.array([1.0, 0, 0])
print(pi, lam2, x50)
```

```python solution
import numpy as np
P = [np.array([[0.98, 0.05, 0.25], [0.02, 0.85, 0.0], [0.0, 0.10, 0.75]]),
     np.array([[0.9, 0.2, 0.1], [0.05, 0.7, 0.3], [0.05, 0.1, 0.6]]),
     np.array([[0.5, 0.25, 0.0], [0.5, 0.5, 0.5], [0.0, 0.25, 0.5]])][k]
w, V = np.linalg.eig(P)
i = np.argmin(abs(w - 1))
pi = np.real(V[:, i])
pi = pi / pi.sum()
lam2 = sorted(abs(w))[-2]
x50 = np.array([1.0, 0, 0])
for _ in range(50):
    x50 = P @ x50
print(pi, lam2, x50)
```

```python tests
import numpy as np
w, V = np.linalg.eig(P)
p = np.real(V[:, np.argmin(abs(w - 1))]); p = p / p.sum()
assert np.allclose(pi, p) and abs(sum(pi) - 1) < 1e-12, f"The steady state is {np.round(p, 4)}: the eigenvector for λ = 1, scaled to add to 1."
assert np.allclose(P @ pi, pi), "P @ pi should equal pi."
assert abs(lam2 - sorted(abs(w))[-2]) < 1e-12, "lam2 is the second-largest eigenvalue in size."
assert np.allclose(x50, np.linalg.matrix_power(P, 50) @ np.array([1.0, 0, 0])), "x50 is P applied 50 times to [1, 0, 0]."
assert np.max(abs(x50 - p)) < 2 * lam2**50 + 1e-12, "After 50 steps the distance from the steady state should be on the order of lam2**50."
```

::: right
Right. The eigenvector gives the steady state directly, and 50 multiplications land on it to within about $|\lambda_2|^{50}$. For the third chain $|\lambda_2| = 0.5$, so 50 steps leave a difference near $10^{-15}$.
:::
:::

::: check
kind: python
given: lam = 0.0005 | 0.001 | 0.002; mu = 0.02 | 0.1 | 0.5

## Two supplies each fail with probability `lam` = {lam} per hour; a failed one is repaired with probability `mu` = {mu} per hour, and the system is down if both fail. Build $Q$ for the transient states (both up, one up) as in the second example, set `N` to the fundamental matrix, `mttf` to the expected hours to system failure from both up, and `gain` to `mttf` divided by the value with no repair.

```python starter
import numpy as np
N = np.eye(2)
mttf = 1 / lam
gain = 1
print(mttf, gain)
```

```python solution
import numpy as np
def mttf_of(mu):
    Q = np.array([[1 - 2 * lam, mu], [2 * lam, 1 - mu - lam]])
    return np.linalg.inv(np.eye(2) - Q)
N = mttf_of(mu)
mttf = N[:, 0].sum()
gain = mttf / mttf_of(0)[:, 0].sum()
print(mttf, gain)
```

```python tests
import numpy as np
Q = np.array([[1 - 2 * lam, mu], [2 * lam, 1 - mu - lam]])
NN = np.linalg.inv(np.eye(2) - Q)
assert np.allclose(N, NN), "N is inv(I - Q), with Q's columns 'from both up' and 'from one up'."
assert abs(mttf - NN[:, 0].sum()) < 1e-6 * NN[:, 0].sum(), f"From both up the mean time to failure is {NN[:, 0].sum():.6g} hours: add up N's first column."
assert abs(mttf - (3 * lam + mu) / (2 * lam**2)) < 1e-6 * mttf, "That matches the closed form (3λ + μ)/(2λ²)."
assert abs(gain - mttf / (1.5 / lam)) < 1e-9 * gain, "Without repair the mean time to failure is 1.5/λ."
```

::: right
Right. The closed form, $(3\lambda + \mu)/(2\lambda^2)$, grows with the repair rate and with the square of the reliability: halving $\lambda$ quadruples the system's life when repair is fast.
:::
:::

::: check
kind: python
given: p = 0.05 | 0.1; q = 0.3 | 0.5; s = 1 | 2 | 3

## Simulate the two-state channel ($p$ = {p} good to bad, $q$ = {q} back) for 200 000 steps with `rng = np.random.default_rng(s)`, starting good, drawing one uniform number per step: leave the current state if the number is below that state's switching probability. Set `frac_bad` to the fraction of steps spent bad and `mean_burst` to the average length of the bad spells, then compare with $p/(p + q)$ and $1/q$.

```python starter
import numpy as np
rng = np.random.default_rng(s)
frac_bad = p / (p + q)
mean_burst = 1 / q
print(frac_bad, mean_burst)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
u = rng.random(200000)
bad = np.zeros(200000, dtype=bool)
state = False
for k in range(200000):
    if state:
        if u[k] < q:
            state = False
    elif u[k] < p:
        state = True
    bad[k] = state
frac_bad = bad.mean()
starts = np.nonzero(bad[1:] & ~bad[:-1])[0].size + int(bad[0])
mean_burst = bad.sum() / starts
print(frac_bad, mean_burst)
```

```python tests
import numpy as np
u = np.random.default_rng(s).random(200000)
b = np.zeros(200000, dtype=bool); st = False
for k in range(200000):
    st = (not (u[k] < q)) if st else (u[k] < p)
    b[k] = st
fb = b.mean(); n = np.nonzero(b[1:] & ~b[:-1])[0].size + int(b[0]); mb = b.sum() / n
assert abs(frac_bad - fb) < 1e-12, f"With this seed the channel is bad {fb:.5f} of the time. Draw one number per step and switch when it's below the current state's probability."
assert abs(mean_burst - mb) < 1e-9, f"The bad spells average {mb:.4f} steps."
assert abs(frac_bad - p / (p + q)) < 0.01 and abs(mean_burst - 1 / q) < 0.15 / q, "The simulation should land near p/(p + q) and 1/q."
```

::: right
Right. Two hundred thousand steps land within a fraction of a percent of the theory. A simulation like this is how you'd check a chain too complicated to solve by hand, or a model fitted to measured fades.
:::
:::

::: check
kind: choice

## Why does every transition matrix (columns adding to 1) have 1 as an eigenvalue?

- [x] Because the row of ones times $P$ is the row of ones again, so 1 is an eigenvalue of $P^T$, and $P$ and $P^T$ have the same eigenvalues
- [ ] Because its diagonal entries are probabilities
- [ ] Because it's symmetric
- [ ] Because its determinant is 1

::: right
Right. Each column adding to 1 says exactly $\mathbf{1}^TP = \mathbf{1}^T$. Transposing doesn't change eigenvalues, so 1 is also an eigenvalue of $P$, and its eigenvector is the steady state.
:::

::: misses
- [2] The diagonal entries can be anything from 0 to 1; it's the column sums that matter.
- [3] Transition matrices usually aren't symmetric: going from good to bad needn't be as likely as the reverse.
- [4] The determinant is the product of all the eigenvalues, and it's rarely 1: for the link above it's 0.65.
:::
:::

::: check
kind: derivation
vars: p = 0.01..0.5, q = 0.01..0.5

## Derive the two-state steady state. The chain moves from state 1 to 2 with probability $p$ and back with $q$.

::: step
answer: p/q

### In the steady state the flow from 1 to 2, $p\pi_1$, equals the flow back, $q\pi_2$. What is $\pi_2/\pi_1$?
:::

::: step
answer: q/(p + q)

### With $\pi_1 + \pi_2 = 1$, what is $\pi_1$?
:::

::: step
answer: p/(p + q)

### And $\pi_2$?
:::

::: right
Right. The state you leave slowly is the one you're in most: if $q$ is small, bad spells last and $\pi_2$ grows.
:::
:::

::: explain
## A redundant system's mean time to failure jumped from 1500 to 51 500 hours when repair was added. Explain where the extra time comes from, in terms of the chain.

::: model
Without repair the chain can only move toward failure: from both up to one up to down, spending about 500 hours in the first state and 1000 in the second. With repair, the one-up state has an exit back to both up that's a hundred times likelier each hour than the exit to failure. So the chain bounces between both up and one up about fifty times, on average, before the rare second failure happens during a repair. The fundamental matrix counts all those return visits: it's $I + Q + Q^2 + \cdots$, every path that stays alive, and repair makes those paths far longer.
:::
:::

::: practice

::: check
given: p = 0.1 | 0.2 | 0.4; q = 0.15 | 0.35 | 0.55
answer: 1 - p - q
tolerance: 0.5%

## A two-state chain switches with probabilities {p} and {q}. What is its second eigenvalue?

::: misses
- [p + q] The eigenvalues add to the trace, $2 - p - q$, and one is 1.
- [any] One eigenvalue is 1 and they add to $2 - p - q$.
:::
:::

::: check
given: lam = 0.001 | 0.004; mu = 0.05 | 0.2
answer: (3*lam + mu)/(2*lam^2)
unit: h
tolerance: 0.5%

## Two units with failure probability {lam} per hour and repair probability {mu}: what is the mean time to failure from both up, in hours?

::: misses
- [1.5/lam] That's the value without repair.
- [any] Use $(3\lambda + \mu)/(2\lambda^2)$, from the fundamental matrix.
:::
:::
:::
