What Is Different Today
What the typical day leaves over has memory and is partly shared. Three AR(1) terms and a noise that depends on camera size complete the model.
Is what is left noise?
After Part 4 the model leaves a standard deviation of 0.19. Before adding anything we ask what kind of thing it is. Noise has no memory: what is left at one minute says nothing about the next. So we correlate what is left with itself a few minutes later, camera by camera.
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_part4.pkl") # the model table so far
terms = json.load(open("work/terms_part4.json")) # the model so far: levels and curvesleft = x.y - pd.read_pickle("work/part4.pkl").fitted # what the model of Part 4 leaves
wide = pd.DataFrame({"recording": d.recording, "minute": d.minute_of_day,
"camera": d.unit, "left": left})
wide = wide.pivot_table(index=["recording", "minute"], columns="camera", values="left")
def memory(k):
"""Correlation of what is left with itself k minutes later, all cameras and recordings."""
recording, minute = wide.index.get_level_values(0), wide.index.get_level_values(1)
later = wide.set_axis(pd.MultiIndex.from_arrays([recording, minute - k]))
return pd.concat([wide.stack(), later.stack()], axis=1).dropna().corr().iloc[0, 1]
lags = [1, 2, 5, 10, 15, 30]
print(pd.DataFrame({"minutes later": lags, "correlation": [round(memory(k), 2) for k in lags]})
.to_string(index=False)) minutes later correlation
1 0.37
2 0.23
5 0.16
10 0.07
15 -0.02
30 -0.00
Reading the result. One minute later the correlation is 0.37; five minutes later 0.16; after a quarter of an hour it is gone. Two things are mixed in what is left:
- a part with no memory at all, which is why even one minute later the correlation is only 0.37: this is noise;
- a part that lasts for some minutes and then fades: something that happened that day, such as a group arriving or a gate closing.
A series in which each value is a fraction of the one before plus a small step fades in exactly this way. It is the AR(1) of Part 4, now running over the minutes of one day.
Who shares it?
If something happens today, do all cameras see it? We correlate what is left between cameras, at the same minute.
order = ["cam_A", "cam_E", "cam_F", "cam_B", "cam_C", "cam_D", "cam_G", "cam_H"]
print(wide[order].corr(min_periods=200).round(2))camera cam_A cam_E cam_F cam_B cam_C cam_D cam_G cam_H
camera
cam_A 1.00 0.68 0.73 0.10 -0.02 0.11 0.06 -0.08
cam_E 0.68 1.00 0.53 0.10 -0.15 -0.25 0.03 -0.00
cam_F 0.73 0.53 1.00 0.11 -0.03 0.08 0.11 -0.10
cam_B 0.10 0.10 0.11 1.00 0.03 0.13 0.42 0.06
cam_C -0.02 -0.15 -0.03 0.03 1.00 -0.11 -0.09 -0.04
cam_D 0.11 -0.25 0.08 0.13 -0.11 1.00 -0.02 -0.06
cam_G 0.06 0.03 0.11 0.42 -0.09 -0.02 1.00 0.06
cam_H -0.08 -0.00 -0.10 0.06 -0.04 -0.06 0.06 1.00Reading the result.
- Cameras A, E and F move together: their correlations are 0.53 to 0.73. The data do not say where the cameras stand. These three are the largest and move as one, as cameras on one open square would, so we call them the plaza cameras.
- Every other pair is close to zero. What happens at one small camera is not seen by the others.
- One exception: cameras B and G (0.42). A term for this pair would be the next refinement; it is left out here.
So today's departure needs three terms: a small one shared by all cameras, one shared by the plaza cameras, and one for each camera alone.
The noise depends on the camera
The part without memory is the noise. Its size can be read from the change of the log count from one minute to the next:
logy = pd.DataFrame({"recording": d.recording, "camera": d.unit, "minute": d.minute_of_day,
"y": x.y}).dropna().sort_values(["recording", "camera", "minute"])
step = logy.groupby(["recording", "camera"])[["minute", "y"]].diff() # from one row to the next
noise = step[step.minute == 1].y.groupby(logy.camera).std() / np.sqrt(2)
size = d[d.obs].groupby("unit").people.median()
print(pd.DataFrame({"median count": size.round(0).astype(int), "noise sd": noise.round(3),
"noise sd x sqrt(count)": (noise * np.sqrt(size)).round(2)})) median count noise sd noise sd x sqrt(count)
cam_A 199 0.077 1.09
cam_B 19 0.190 0.82
cam_C 22 0.187 0.89
cam_D 30 0.149 0.82
cam_E 233 0.062 0.94
cam_F 135 0.089 1.04
cam_G 7 0.293 0.76
cam_H 14 0.185 0.69
cam_I 49 0.115 0.81
cam_J 62 0.127 1.00
cam_K 90 0.131 1.25
cam_L 78 0.090 0.79
cam_M 14 0.200 0.75Reading the result. The noise is 0.06 on the largest camera and 0.29 on the smallest. Multiplied by the square root of the camera's count it is between 0.69 and 1.25 for every camera. So the noise variance is roughly proportional to one over the camera's size, as it would be for counts. The model takes this in through scale: the noise precision of each row is multiplied by its camera's relative size.
Three terms for today
| term | one series for | shared by |
|---|---|---|
| Zr(t) | each recording r | all cameras |
| Pr(t) | each recording | the plaza cameras, through a 0/1 weight |
| Uc,r(t) | each camera and recording | nobody |
Each is an AR(1) series over the minutes of a recording. They are built like the camera curves of Part 4: an iid effect over the recordings and a group index for the minute. All series of one term share one standard deviation and one correlation.
start = d.groupby("recording").minute_of_day.transform("min")
t = d.minute_of_day - start + 1 # minute of the recording
x["rec_all"], x["t_all"] = crowd.codes(d.recording), t # a series per recording
x["rec_plaza"], x["t_plaza"] = x["rec_all"], t # another, for the plaza cameras
x["w_plaza"] = d.unit.isin(crowd.PLAZA).astype(float) # ... switched on by a weight
x["rec_cam"], x["t_cam"] = crowd.codes(d.unit, d.recording), t # a series per camera
today_all = {"id": "rec_all", "model": "iid", "group": "t_all",
"control.group": ar1(0.9), "hyper": pc(0.5)}
today_plaza = {"id": "rec_plaza", "model": "iid", "group": "t_plaza",
"control.group": ar1(0.9), "hyper": pc(0.5), "weights": "w_plaza"}
today_own = {"id": "rec_cam", "model": "iid", "group": "t_cam",
"control.group": ar1(0.9), "hyper": pc(0.5)}
scale = (size / size.mean())[d.unit].to_numpy() # noise precision in proportion to camera sizemodel = {"response": "y", "fixed": ["1"], "random": terms + [today_all, today_plaza, today_own]}
res = pyinla(model=model, family="gaussian", data=x, scale=scale, num_threads=crowd.THREADS,
control={"predictor": {"compute": True}, "compute": {"waic": True},
"inla": {"int.strategy": "eb"}})
fitted = res.summary_linear_predictor["mean"].to_numpy()
print(f"sd left: {(x.y - fitted).std():.3f} WAIC: {res.waic['waic']:.0f}")sd left: 0.145 WAIC: -12313This is the full model. Its fit takes several minutes on four threads. The sd left falls from 0.19 to 0.15, and what remains is the counting noise.
Reading the hyperparameters
pyINLA reports each term's precision and each AR(1) correlation. Two changes of scale make them readable. A precision becomes a standard deviation on the log scale, where 0.1 means a change of about 10%. A correlation becomes a half-life: the time after which half of a deviation is gone.
def readable(h):
"""Hyperparameters on a scale that can be read, as 95% interval and median:
a precision as a standard deviation (log scale), a correlation as a half-life (minutes)."""
q = h[["0.025quant", "0.5quant", "0.975quant"]]
prec, rho = q[q.index.str.startswith("Precision")], q[q.index.str.startswith("GroupRho")]
sd = (1 / np.sqrt(prec)).iloc[:, ::-1] # the sd falls as the precision rises: quantiles swap
half = np.log(0.5) / np.log(rho)
sd.index = sd.index.str.replace("Precision for ", "sd of ")
half.index = half.index.str.replace("GroupRho for ", "half-life of ")
sd.columns = half.columns = ["lo", "median", "hi"]
return pd.concat([sd, half])
print(readable(res.summary_hyperpar).round(3)) lo median hi
sd of the Gaussian observations 0.090 0.092 0.094
sd of cam 0.645 1.063 1.603
sd of day 0.087 0.162 0.305
sd of clock 5.199 6.173 7.311
sd of cam_curve 0.236 0.367 0.604
sd of cam_jumuah 0.405 0.511 0.650
sd of cam_weekend 0.022 0.044 0.091
sd of rec_all 0.071 0.091 0.119
sd of rec_plaza 0.188 0.236 0.294
sd of rec_cam 0.129 0.141 0.155
half-life of cam_curve 121.488 304.553 861.227
half-life of cam_jumuah 34.655 55.522 90.508
half-life of rec_all 6.035 10.043 17.089
half-life of rec_plaza 12.552 19.868 30.957
half-life of rec_cam 11.109 13.909 17.457| term | standard deviation (log scale) | half-life | reading |
|---|---|---|---|
| Camera level a | 1.06 (0.64 to 1.60) | cameras differ in size by about ×3 | |
| Day level b | 0.16 (0.09 to 0.31) | days differ by about 18% | |
| Camera on a weekend e | 0.04 (0.02 to 0.09) | levels move about 4% between weekends | |
| Camera curve g | 0.37 (0.24 to 0.60) | 305 min (121 to 861) | slow departures, lasting hours |
| Friday-midday curve j | 0.51 (0.40 to 0.65) | 56 min (35 to 91) | larger departures, about an hour |
| Today, all cameras Z | 0.09 (0.07 to 0.12) | 10 min (6 to 17) | small |
| Today, plaza P | 0.24 (0.19 to 0.29) | 20 min (13 to 31) | the largest of today's terms |
| Today, own camera U | 0.14 (0.13 to 0.15) | 14 min (11 to 17) | what one camera does alone |
| Noise ε, average camera | 0.092 (0.090 to 0.094) | counting noise of about 10% |
Posterior medians with 95% intervals. Three things stand out:
- Today's deviations are short-lived. Half of one is gone after 10 to 20 minutes. A forecast 15 minutes ahead therefore starts from the current level and drifts back towards the typical day.
- The plaza cameras move together. Their shared deviation (0.24) is larger than a camera's own (0.14). A plaza camera with a gap can borrow from the other two.
- The other cameras share little. The deviation shared by all cameras is small (0.09). For a small camera, the other cameras say little about what it is doing right now.
One count taken apart
The model is a sum, so every fitted value can be split into its terms. pyINLA stores a replicated term one replicate after the other and a grouped term one group after the other; the function below follows that order to place every term on every row.
def components(res, x, stat="mean"):
"""Every term of the model on every row (posterior mean by default).
The columns of the means add up to the mean of the linear predictor."""
s = lambda name: res.summary_random[name][stat].to_numpy()
n = lambda name: int(x[name].max())
by_id = lambda name: s(name)[x[name] - 1]
by_group = lambda name, g: s(name)[(x[g] - 1) * n(name) + x[name] - 1] # group by group
return pd.DataFrame({
"intercept": res.summary_fixed[stat].iloc[0],
"cam": by_id("cam"), "day": by_id("day"), "cam_weekend": by_id("cam_weekend"),
"clock": s("clock")[(x.weekday - 1) * n("clock") + x.clock - 1], # replicate by replicate
"cam_curve": by_group("cam_curve", "clock_cam"),
"cam_jumuah": x.w_jumuah * by_group("cam_jumuah", "clock_jumuah"),
"rec_all": by_group("rec_all", "t_all"),
"rec_plaza": x.w_plaza * by_group("rec_plaza", "t_plaza"),
"rec_cam": by_group("rec_cam", "t_cam"),
}, index=x.index)
parts = components(res, x)
gap = np.abs(parts.sum(axis=1) - fitted).max()
print(f"largest difference between the sum of the terms and the fit: {gap:.1e}\n")
row = (d.unit == "cam_A") & (d.day == "2026-09-12") & (d.minute_of_day == 765) # camera A at 12:45
one = parts[row].T.round(2).set_axis(["log scale"], axis=1)
print(one.assign(times=np.exp(one["log scale"]).round(2)))largest difference between the sum of the terms and the fit: 2.7e-15
log scale times
intercept 3.68 39.65
cam 1.51 4.53
day -0.13 0.88
cam_weekend -0.02 0.98
clock -0.24 0.79
cam_curve 0.31 1.36
cam_jumuah -0.00 1.00
rec_all 0.09 1.09
rec_plaza 0.62 1.86
rec_cam 0.09 1.09Reading the result. At 12:45 on 12 September the count of camera A is the product of the last column: an average camera, times the size of camera A, times the day, and so on. The largest factor after the camera's size is the plaza's deviation of that day.

On this Saturday the plaza term carries most of what was unusual. The plaza ran up to 90% above its typical Saturday (at 12:42) and down to 33% below it (at 14:24). The term shared by all cameras stayed within 13%, and camera A's own term within 16%.
The day levels, again
Part 2 warned that its day levels mixed up busy hours and busy days. The full model knows the time of day, so its day levels can be read:
| day | level, as a multiple of an average day | 95% interval |
|---|---|---|
| Fri 4 Sep | ×1.05 | ×0.89 to ×1.24 |
| Sat 5 Sep | ×0.81 | ×0.70 to ×0.95 |
| Fri 11 Sep | ×1.11 | ×0.96 to ×1.29 |
| Sat 12 Sep | ×0.88 | ×0.76 to ×1.02 |
| Fri 18 Sep | ×1.25 | ×1.08 to ×1.45 |
| Sat 19 Sep | ×0.96 | ×0.82 to ×1.11 |
Every Friday is above the average and every Saturday below it, and both rise from week to week, by about 9% a week. With three weeks this is a description of these six days, not yet a trend to extrapolate.
x.to_pickle("work/x_part5.pkl") # the model table
json.dump(model["random"], open("work/terms_part5.json", "w")) # the model
np.save("work/scale.npy", scale)
tau = res.summary_hyperpar.loc["Precision for the Gaussian observations", "0.5quant"]
json.dump({"theta": [float(v) for v in res.mode["theta"]], "tau": float(tau),
"left": float((x.y - fitted).std()), "waic": float(res.waic["waic"])},
open("work/part5.json", "w"))
res.summary_linear_predictor.set_index(x.index).to_pickle("work/part5_predictor.pkl")
# for the figures and the last parts
res.summary_hyperpar.to_pickle("work/part5_hyperpar.pkl")
today = ["rec_all", "rec_plaza", "rec_cam"]
bands = pd.concat([components(res, x, "0.025quant")[today].add_suffix("_lo"),
components(res, x, "0.975quant")[today].add_suffix("_hi")], axis=1)
pd.concat([parts, bands], axis=1).to_pickle("work/part5_terms.pkl")
res.summary_random["day"].to_pickle("work/part5_day.pkl")The code of this part, with the output it printed: 05_today.ipynb. It reads crowd.py and the files the earlier parts saved in work/.