---
title: "Pulse oximeter project: from photodetector signals to SpO₂"
heading: Computing the ratio of ratios from two-wavelength photoplethysmograms, checking it against Beer–Lambert theory, inverting the theory, and fitting an empirical calibration to reference data, then seeing why the calibration is needed
eyebrow: S15 · Lesson 53 · Pulse oximeter project
xp: 80
---

::: hook
Lesson 33 explained what a pulse oximeter measures; this project builds the calculation. You'll take the red and infrared signals a photodiode would record, extract the ratio of ratios, convert it to saturation with Beer–Lambert theory, and then do what every manufacturer does: fit a calibration line to reference measurements and show that it beats the theory by a wide margin. It's a small version of a real device-development step, where physics gives the form of the answer and data from people gives the numbers.
:::

::: predict
## Reference data follow SpO₂ = 110 − 25R. At R = 1, what does the Beer–Lambert theory of lesson 33 report?

- [ ] 85%, the same as the calibration
- [x] About 74%, far lower
- [ ] About 95%
- [ ] 100%

::: reveal
Inverting the theory with coefficients 3227/320 at 660 nm and 693/1214 at 940 nm gives S = 73.9% at R = 1, while the calibration gives 85%. Over the range the reference data cover, the theory reads about 10 percentage points low on average, because scattering makes red and infrared light travel different effective path lengths through tissue.
:::
:::

::: nameit
## Step 1: the ratio of ratios

For each wavelength, the DC level is the record's mean and the AC level its standard deviation; R is their ratios' ratio. Any consistent measure of the pulse works, because the same measure appears at both wavelengths. The tests build signals from Beer–Lambert, $I = I_0e^{-k\varepsilon(\lambda, S)p(t)}$, with a realistic pulse shape p(t), and check R against $\varepsilon(660, S)/\varepsilon(940, S)$.

## Step 2: theory both ways

`r_theory(S)` gives lesson 33's R; `spo2_theory(R)` inverts it:

$$S = \frac{\varepsilon_{Hb}^{660} - R\varepsilon_{Hb}^{940}}{\varepsilon_{Hb}^{660} - \varepsilon_{HbO_2}^{660} + R(\varepsilon_{HbO_2}^{940} - \varepsilon_{Hb}^{940})}$$

## Step 3: calibration

`fit_calibration` fits a straight line S = a + bR by least squares to 60 calibration points (with measurement scatter of 1.5 percentage points), and `spo2_calibrated` applies it. The tests check the fit on 40 new points and compare the theory's error on the same data.
:::

::: example
## What should step 2 give at 98% saturation, and for R = 0.5?

::: solution
1. **`r_theory(0.98)`.**
   $$\begin{aligned} R &= \frac{3227 \times 0.02 + 320 \times 0.98}{693 \times 0.02 + 1214 \times 0.98} \\ &= \frac{378.1}{1203.6} \\ &= 0.314 \end{aligned}$$
2. **`spo2_theory(0.5)`.** It returns 0.909.
3. **Against the empirical line.** The line gives 97.5% at R = 0.5, so the theory and the calibration disagree by about 7 points even near normal saturations.

**Answer:** `r_theory(0.98)` gives 0.314, and `spo2_theory(0.5)` gives 0.909, about 7 points below the empirical line's 97.5%.
:::
:::

::: example
## What does step 3 report on the test data?

::: solution
1. **The fitted line.** The fit gives a = 109.75 and b = −24.54, close to the 110 and −25 that generated the data.
2. **Its error on new points.** On the 40 new points its RMS error is 1.60 percentage points, about the scatter in the reference data.
3. **The theory's error.** On the same points the Beer–Lambert theory reads 10.4 points low on average.

**Answer:** the fit gives a = 109.75 and b = −24.54, with an RMS error of 1.60 points on the test data, while the uncalibrated theory reads 10.4 points low on average.
:::
:::

::: check
kind: python

## Step 1. Write `ratio_of_ratios`: the oximeter's measurement from two photodetector records.

```python starter
import numpy as np

def ratio_of_ratios(red, ir):
    # red and ir are photodetector records (same length). Take each one's DC as its mean and
    # its AC as its standard deviation, and return (AC_red/DC_red)/(AC_ir/DC_ir).
    return 0.0

fs = 100
t = np.arange(0, 10, 1/fs)
p = np.sin(2*np.pi*1.2*t)
print(ratio_of_ratios(1.0 - 0.01*p, 2.0 - 0.04*p))
```

```python solution
import numpy as np

def ratio_of_ratios(red, ir):
    red, ir = np.asarray(red, float), np.asarray(ir, float)
    return (np.std(red)/np.mean(red))/(np.std(ir)/np.mean(ir))

fs = 100
t = np.arange(0, 10, 1/fs)
p = np.sin(2*np.pi*1.2*t)
print(ratio_of_ratios(1.0 - 0.01*p, 2.0 - 0.04*p))
```

```python tests
EHB = {660: 3227.0, 940: 693.0}
EO2 = {660: 320.0, 940: 1214.0}
def eps(lam, S):
    return EHB[lam]*(1 - S) + EO2[lam]*S
fs = 100
t = np.arange(0, 10, 1/fs)
p = np.sin(2*np.pi*1.2*t) + 0.4*np.sin(2*np.pi*2.4*t + 1.0) + 0.15*np.sin(2*np.pi*3.6*t + 2.0)
for S in (0.98, 0.9, 0.75):
    k = 0.004/eps(660, 0.75)
    red = 0.8*np.exp(-k*eps(660, S)*p)
    ir = 1.5*np.exp(-k*eps(940, S)*p)
    R = ratio_of_ratios(red, ir)
    Rt = eps(660, S)/eps(940, S)
    assert abs(R/Rt - 1) < 0.01, f"At {S:.0%} saturation the pulses' ratio should be {Rt:.4f}; you got {R:.4f}."
assert abs(ratio_of_ratios(3.0*red, ir) - R) < 1e-12, "Scaling one wavelength's brightness must not change R: normalize each AC by its own DC."
```

::: right
Right. Your ratio of ratios matches the ratio of the blood's extinction coefficients to within 1%, whatever the detector brightness.
:::
:::

::: check
kind: python

## Step 2. Write `r_theory` and `spo2_theory`: Beer–Lambert in both directions.

```python starter
import numpy as np

EHB = {660: 3227.0, 940: 693.0}
EO2 = {660: 320.0, 940: 1214.0}

def r_theory(S):
    # Beer-Lambert ratio of ratios at saturation S (a fraction from 0 to 1).
    return 0.0

def spo2_theory(R):
    # Invert r_theory: the saturation (a fraction) that gives ratio R.
    return 0.0

print(r_theory(0.98), spo2_theory(0.5))
```

```python solution
import numpy as np

EHB = {660: 3227.0, 940: 693.0}
EO2 = {660: 320.0, 940: 1214.0}

def r_theory(S):
    return (EHB[660]*(1 - S) + EO2[660]*S)/(EHB[940]*(1 - S) + EO2[940]*S)

def spo2_theory(R):
    return (EHB[660] - R*EHB[940])/(EHB[660] - EO2[660] + R*(EO2[940] - EHB[940]))

print(r_theory(0.98), spo2_theory(0.5))
```

```python tests
assert abs(r_theory(1.0) - 320/1214) < 1e-12 and abs(r_theory(0.0) - 3227/693) < 1e-12, "At full and zero saturation R is the ratio of one form's coefficients."
assert abs(r_theory(0.98) - 0.31414) < 1e-4, f"At 98%, R should be 0.3141; got {r_theory(0.98):.4f}."
for S in np.linspace(0.3, 1.0, 15):
    assert abs(spo2_theory(r_theory(S)) - S) < 1e-12, f"spo2_theory must invert r_theory exactly; at S = {S:.3f} you got {spo2_theory(r_theory(S)):.6f}."
assert abs(spo2_theory(0.5) - 0.90939) < 1e-4, f"R = 0.5 means 90.9% in theory; got {100*spo2_theory(0.5):.2f}%."
```

::: right
Right. Your theory reproduces lesson 33's ratios and inverts them exactly.
:::
:::

::: check
kind: python

## Step 3. Write `fit_calibration`: an empirical calibration line from reference data.

```python starter
import numpy as np

EHB = {660: 3227.0, 940: 693.0}
EO2 = {660: 320.0, 940: 1214.0}

def spo2_theory(R):
    return (EHB[660] - R*EHB[940])/(EHB[660] - EO2[660] + R*(EO2[940] - EHB[940]))

def fit_calibration(R, S):
    # Least-squares line S = a + b*R through calibration data (S in percent). Return (a, b).
    return 0.0, 0.0

def spo2_calibrated(R, a, b):
    return a + b*np.asarray(R)

rng = np.random.default_rng(2)
R = rng.uniform(0.45, 1.6, 10)
print(fit_calibration(R, 110 - 25*R))
```

```python solution
import numpy as np

EHB = {660: 3227.0, 940: 693.0}
EO2 = {660: 320.0, 940: 1214.0}

def spo2_theory(R):
    return (EHB[660] - R*EHB[940])/(EHB[660] - EO2[660] + R*(EO2[940] - EHB[940]))

def fit_calibration(R, S):
    A = np.column_stack([np.ones(len(R)), np.asarray(R, float)])
    a, b = np.linalg.lstsq(A, np.asarray(S, float), rcond=None)[0]
    return a, b

def spo2_calibrated(R, a, b):
    return a + b*np.asarray(R)

rng = np.random.default_rng(2)
R = rng.uniform(0.45, 1.6, 10)
print(fit_calibration(R, 110 - 25*R))
```

```python tests
rng = np.random.default_rng(9)
Rc = rng.uniform(0.45, 1.6, 60)
Sc = 110 - 25*Rc + rng.normal(0, 1.5, 60)
a, b = fit_calibration(Rc, Sc)
A = np.column_stack([np.ones(60), Rc])
ref = np.linalg.lstsq(A, Sc, rcond=None)[0]
assert abs(a - ref[0]) < 1e-9 and abs(b - ref[1]) < 1e-9, f"The least-squares line is a = {ref[0]:.3f}, b = {ref[1]:.3f}; got {a:.3f}, {b:.3f}."
Rv = rng.uniform(0.45, 1.6, 40)
Sv = 110 - 25*Rv + rng.normal(0, 1.5, 40)
rms = np.sqrt(np.mean((spo2_calibrated(Rv, a, b) - Sv)**2))
assert rms < 2.0, f"On new subjects the calibration should be within about 2% RMS; it's {rms:.2f}%."
bias = np.mean(100*spo2_theory(Rv) - Sv)
assert bias < -5, f"(A check on the data, not on you: the uncalibrated Beer-Lambert estimate should read well low here; its mean error is {bias:.1f}%.)"
```

::: right
Right. The fitted calibration predicts new subjects to within about the reference data's own scatter, where the uncalibrated theory reads far low.
:::
:::

::: explain
## Why does a pulse oximeter need an empirical calibration when Beer–Lambert theory predicts the ratio from first principles?

::: model
Beer–Lambert assumes light travels in a straight line through a uniform absorber, so the path length cancels between the two wavelengths. Tissue scatters light strongly, and photons wander along paths whose average length depends on how strongly each wavelength is absorbed and scattered: red light, absorbed more by deoxygenated blood, samples shorter effective paths than infrared, and the difference changes with saturation. The ratio of ratios therefore isn't simply the ratio of extinction coefficients, and the error is tens of percent. Manufacturers measure R on volunteers breathing reduced oxygen while drawing arterial blood samples for reference saturation, and fit the calibration curve to those data, which absorbs the scattering effects the simple theory leaves out.
:::
:::

::: practice

::: check
given: S = 60 | 80 | 95
answer: (3227*(1 - S/100) + 320*S/100)/(693*(1 - S/100) + 1214*S/100)
tolerance: 0.5%

## Beer–Lambert R at {S}%?

::: misses
- [any] Weighted coefficients ratio.
:::
:::

::: check
given: R = 0.4 | 0.7 | 1.2
answer: 100*(3227 - R*693)/(3227 - 320 + R*(1214 - 693))
tolerance: 0.5%

## Beer–Lambert SpO₂ for R = {R}, in percent?

::: misses
- [any] Invert the ratio.
:::
:::

::: check
given: R = 0.4 | 0.7 | 1.2
answer: 110 - 25*R - 100*(3227 - R*693)/(3227 - 320 + R*(1214 - 693))
tolerance: 0.5%

## How far apart are the empirical line 110 − 25R and the Beer–Lambert theory at R = {R}, in percentage points?

::: misses
- [any] Subtract the two estimates.
:::
:::
:::
