Urban Analytics & Transportation · Part 4 of 7

Each Camera's Own Shape

A curve for each camera, a second one around the Friday prayer, and a level for each weekend.

What the shared curve misses

Part 3 gave every camera the same typical day. To see what that misses, take what the model leaves unexplained, and average it for each camera over the 40 minutes before the noon adhan. On the log scale an average of zero means the model is right on average; its exponential is how many times the count is above or below the fit.

import json

import numpy as np
import pandas as pd
from pyinla import pyinla

import crowd
from crowd import ar1, pc

d = pd.read_pickle("work/table.pkl")                  # the rows, from Part 1
x = pd.read_pickle("work/x_part3.pkl")                # the model table so far
terms = json.load(open("work/terms_part3.json"))      # the model so far: levels, typical day
left = x.y - pd.read_pickle("work/part3.pkl").fitted  # what the model of Part 3 leaves
friday = (d.weekday == "Fri").to_numpy()
before_noon = x.clock.between(41, 80).to_numpy()      # the 40 minutes before the noon adhan
ratio = lambda rows: np.exp(left[rows].groupby(d.unit).mean()).round(2)
print(pd.DataFrame({"Friday": ratio(friday & before_noon),
                    "Saturday": ratio(~friday & before_noon)}).T)
unit      cam_A  cam_B  cam_C  cam_D  cam_E  cam_F  cam_G  cam_H
Friday     0.49   0.58   5.51   0.68   1.00   0.30   0.92   2.26
Saturday   1.35   0.77   0.71   0.66   1.23   1.48   1.00   0.92

Reading the result. Before the Friday prayer camera C counts 5.5 times what the model says, and camera H 2.3 times. Cameras A and F count 0.49 and 0.30 times: half and less. One place fills while another empties, and a shared curve can only show the average of the two. On Saturdays all cameras stay between 0.66 and 1.48 times the fit: the rearrangement belongs to Friday noon.

So the model needs two more things: a shape for each camera, and a second shape for each camera around the Friday prayer.

A curve for each camera

1. What we want. Each camera keeps the shared curve and adds its own departure from it, gc(s):

$$\log y_{c,d}(t) = \mu + a_c + b_d + f_{\text{weekday}}(s) + g_c(s) + \varepsilon$$

2. A curve that comes back to zero. For the shared curve we used a random walk. For the thirteen departures we use a different smooth curve, the first-order autoregression AR(1):

$$g_c(s) = \rho\, g_c(s-1) + \text{innovation}, \qquad 0 < \rho < 1$$

Each value is a fraction ρ of the one before, plus a small step. With ρ close to 1 the curve is smooth. Unlike a random walk it is pulled back to zero, and that matters here. Several cameras have no data for hours, or on whole days. Where a camera has no data, its departure fades to zero and the camera falls back on the shared curve. A random walk would instead carry on in whatever direction it was last heading.

3. Thirteen curves that share their hyperparameters. All cameras should have the same standard deviation and the same ρ: one estimate of how large and how smooth such departures are. pyINLA builds this from two pieces: an iid effect over the cameras, and a group index along the clock with an AR(1) model across the groups. The result is thirteen independent AR(1) curves with common hyperparameters.

def ar1(u):
    """AR(1) across the groups of a term, with a prior for its correlation: P(rho > u) = 0.5."""
    return {"model": "ar1", "hyper": {"rho": {"prior": "pc.cor1", "param": [u, 0.5]}}}
x["cam_curve"], x["clock_cam"] = x["cam"], x["clock"]
shape = {"id": "cam_curve", "model": "iid", "group": "clock_cam",
         "control.group": ar1(0.95), "hyper": pc(1)}

ar1(0.95) is the AR(1) across the groups, with a prior that puts even odds on ρ being above 0.95: we expect smooth curves, and let the data say how smooth.

4. One curve for both weekdays. In Part 3 the shared curve was split by weekday. The camera curve is not, on purpose. A camera that is hidden on a Saturday may have been seen on Fridays only. A curve per camera and weekday would then have no data at all for its Saturday. One curve per camera carries its shape from one weekday to the other.

Friday midday

The table above showed where one curve per camera is not enough: before the Friday prayer. There each camera gets a second departure, jc(s), built like the first and switched on by a weight w(s):

$$\dots + g_c(s) + w(s)\, j_c(s) + \dots$$

The weight is 1 on Fridays until 13:50, falls to 0 by 14:20, and is 0 on Saturdays. In pyINLA a weight is a column of the table, named in the term's weights.

x["cam_jumuah"] = x["cam"]
x["clock_jumuah"] = np.minimum(x["clock"], 201)                   # position 201 is 14:20
x["w_jumuah"] = friday * np.clip((201 - x["clock"]) / 30, 0, 1)   # 1 until 13:50, 0 from 14:20
midday = {"id": "cam_jumuah", "model": "iid", "group": "clock_jumuah",
          "control.group": ar1(0.95), "hyper": pc(1), "weights": "w_jumuah"}

The camera on a weekend

One level is still missing. A camera can run a little above or below its usual level for a whole weekend. This is a level for each camera and weekend, ec,w, an iid term like those of Part 2.

saturday = (d.weekday == "Sat").astype(int)
friday_of = pd.to_datetime(d.day) - pd.to_timedelta(saturday, "D")
weekend = friday_of.dt.strftime("%d %b")              # a weekend is named by its Friday
x["cam_weekend"] = crowd.codes(d.unit, weekend)
level = {"id": "cam_weekend", "model": "iid", "hyper": pc(0.5)}
print(pd.crosstab(d.day, weekend.rename("weekend")).gt(0).astype(int))
weekend     04 Sep  11 Sep  18 Sep
day                               
2026-09-04       1       0       0
2026-09-05       1       0       0
2026-09-11       0       1       0
2026-09-12       0       1       0
2026-09-18       0       0       1
2026-09-19       0       0       1

It has a second use. A camera hidden on the Saturday of a weekend was seen on its Friday, and this term carries what was learned there across.

Let the data choose

The three terms are added one after the other, and each fit is compared with the one before, as in Part 3.

def fit(*new):
    """Fit the model so far plus the new terms."""
    return pyinla(model={"response": "y", "fixed": ["1"], "random": terms + list(new)},
                  family="gaussian", data=x, num_threads=crowd.THREADS,
                  control={"predictor": {"compute": True}, "compute": {"waic": True},
                           "inla": {"int.strategy": "eb"}})


def left_sd(res):
    """The sd of what the fit leaves unexplained."""
    return (x.y - res.summary_linear_predictor["mean"].to_numpy()).std()


steps = {"a curve per camera": [shape],
         "and its Friday-midday curve": [shape, midday],
         "and its level on the weekend": [shape, midday, level]}
fits = {name: fit(*new) for name, new in steps.items()}
print(pd.DataFrame({"sd left": {name: round(left_sd(res), 3) for name, res in fits.items()},
                    "WAIC": {name: round(res.waic["waic"]) for name, res in fits.items()}}))
                              sd left  WAIC
a curve per camera              0.304  6210
and its Friday-midday curve     0.192 -1947
and its level on the weekend    0.189 -2215

Reading the result.

The models are larger now, with more than 12,000 unknown curve values. The setting "int.strategy": "eb" tells pyINLA to use the most likely values of the hyperparameters and not to average over them. With thousands of counts behind each hyperparameter the difference is small, and each fit takes seconds.

The camera curves

res = fits["and its level on the weekend"]
h = res.summary_hyperpar["0.5quant"]
for name in ("cam_curve", "cam_jumuah"):
    sd, rho = 1 / np.sqrt(h[f"Precision for {name}"]), h[f"GroupRho for {name}"]
    print(f"{name}: sd {sd:.2f}, correlation between neighbouring minutes {rho:.3f}, "
          f"half gone after {np.log(0.5) / np.log(rho):.0f} minutes")
cam_curve: sd 0.35, correlation between neighbouring minutes 0.989, half gone after 61 minutes
cam_jumuah: sd 0.63, correlation between neighbouring minutes 0.987, half gone after 52 minutes
The Friday-midday curve of cameras C, H, A and F with 95% bands
The Friday-midday curve of four cameras, as a multiple of the camera's usual curve, with 95% bands. The dotted line is the noon adhan.

Reading the result. In the hour before the Friday prayer cameras C and H rise far above their usual curves while cameras A and F fall to a fraction of theirs. After the prayer all four return to 1. Nobody told the model where people gather for the Friday prayer; the curves are estimated from the counts.

Both kinds of curve are smooth: half of a departure is gone after about an hour (61 and 52 minutes). The Friday-midday departures are the larger ones, with a standard deviation of 0.63 against 0.35.

What it cannot do

Levels and curves describe a typical day: the same for every Friday, and the same for every Saturday. What is left is how a particular day departs from it. Part 5 looks at whether that is noise or has a pattern.

x.to_pickle("work/x_part4.pkl")                                              # the model table
json.dump(terms + [shape, midday, level], open("work/terms_part4.json", "w"))    # the model
# for the figures and the last part
fitted = res.summary_linear_predictor["mean"].to_numpy()
pd.DataFrame({"fitted": fitted}, index=x.index).to_pickle("work/part4.pkl")
res.summary_random["cam_jumuah"].to_pickle("work/part4_cam_jumuah.pkl")
json.dump({name: [float(left_sd(r)), float(r.waic["waic"])] for name, r in fits.items()},
          open("work/part4.json", "w"))

The code of this part, with the output it printed: 04_camera_shapes.ipynb. It reads crowd.py and the files the earlier parts saved in work/.

Next: Part 5: What Is Different Today →

Part 5 models what is different today: deviations that last a few minutes and are shared between cameras.