Problem 646185 · easy · Level 06 Heuristics & Optimization

Following a Greenhouse as It Warms

Kalman filter · random walk · process noise · missing data · prediction

A greenhouse logs its air temperature every 10 minutes from a wireless sensor. The temperature does not stay put: on a sunny morning it creeps up by an unknown amount each interval. A simple model for that is a random walk: the next temperature is this one plus a random change of variance q (°C²). The sensor's readings have error variance r. Sometimes the radio link drops and a reading is missing (None).

Starting from the estimate x = x0 with variance p = p0, for every entry z of readings in order:

p = p + q                     predict: the temperature may have moved (x stays the same)
if z is not None:             update, only when there is a reading
    K = p / (p + r)
    x = x + K * (z - x)
    p = (1 - K) * p

Write follow(readings, x0, p0, q, r) that returns a pair: the list of the estimates x after each entry (one per entry, missing ones included), and the final variance p.

Examples

Input:  readings = [18.2, 18.9, None, None, 20.1, 20.4], x0 = 18.0, p0 = 0.25, q = 0.05, r = 0.2
Output: ([18.12, 18.478378378378377, 18.478378378378377, 18.478378378378377, 19.36605504587156, 19.824755423224158], 0.08872820076563165)
Explanation: during the two missing readings the estimate holds still, but its variance grows from
0.09 to 0.14 and 0.19, so the reading of 20.1 that follows gets a gain of 0.55 (0.42 without the gap).

Input:  readings = [None, None], x0 = 5, p0 = 1, q = 0.5, r = 1
Output: ([5, 5], 2.0)

With q = 0 the same six readings give a last estimate of only 19.17 °C: a filter told that nothing changes averages the whole morning together and lags behind. Press Run with plot(follow(readings, 18.0, 0.25, 0.05, 0.2)[0]) and again with q = 0 to compare.

Constraints

  • answers are compared with a tolerance of 1e-6

Goals

  • Add the predict step to a one-number Kalman filter for a quantity that drifts
  • Carry on through missing readings by predicting without updating
  • See that without process noise the filter falls behind a quantity that moves
Starting Python…