The Typical Day
A smooth curve over the day, shared by all cameras, on a clock that follows the prayers.
What we want
Part 2 ended with a flat line through a day that rises and falls with the prayers. The model needs a curve over the day, the same for all cameras for now:
Here s is the position of minute t in the day, and f is the unknown curve: one value for each minute. Three questions have to be answered before it can be fitted. On which clock does s run? What makes f a curve and not 641 unrelated numbers? And is one curve enough for Fridays and Saturdays?
import json
import numpy as np
import pandas as pd
from pyinla import pyinla
import crowd
from crowd import pc
d = pd.read_pickle("work/table.pkl") # the rows, from Part 1
x = pd.read_pickle("work/x_part2.pkl") # the model table so far: y, cam, day
terms = json.load(open("work/terms_part2.json")) # the model so far: camera and day levelsWhich clock?
1. The adhan moves. The prayer times follow the sun, so they shift from day to day:
hhmm = lambda m: f"{int(round(m)) // 60:02d}:{int(round(m)) % 60:02d}"
adhan = pd.DataFrame({day: crowd.prayer_times(day) for day in sorted(d.day.unique())}).T
print(adhan.apply(lambda col: col.map(hhmm))) fajr dhuhr asr maghrib isha
2026-09-04 04:44 12:22 15:49 18:37 20:07
2026-09-05 04:45 12:21 15:49 18:36 20:06
2026-09-11 04:48 12:19 15:46 18:30 20:00
2026-09-12 04:48 12:19 15:46 18:29 19:59
2026-09-18 04:51 12:17 15:43 18:23 19:53
2026-09-19 04:51 12:16 15:42 18:22 19:52Between 5 and 19 September the isha adhan moves from 20:06 to 19:52, a quarter of an hour. A crowd that follows the adhan does on 19 September at 19:52 what it did on 5 September at 20:06. A curve on the wall clock would average the two days at 20:00 as if they were in the same state.
2. The prayer clock. We therefore stretch each day a little, so that its five adhans fall where those of one reference day do, 11 September. Between two adhans the minutes are spread evenly.
def prayer_clock(day, minute, ref_day="2026-09-11"):
"""Minute of day on the prayer clock: the day is stretched so that its adhans fall where those of
ref_day do."""
a, r = prayer_times(day), prayer_times(ref_day)
return np.interp(minute, [0, *a.values(), 1440], [0, *r.values(), 1440])The adhan times themselves are computed from the position of the sun by crowd.prayer_times(); no outside data are used. The curve f will have one value per minute of this clock, and position 1 is 11:00 on the reference day.
on_clock = pd.concat([pd.Series(crowd.prayer_clock(day, g.minute_of_day), index=g.index)
for day, g in d.groupby("day")])
x["clock"] = on_clock.round().astype(int) - 659 # prayer clock: 1 is 11:00 on 11 September
x["wall"] = d.minute_of_day - 659 # wall clock: 1 is 11:00 on every day
saturdays = ["2026-09-05", "2026-09-12", "2026-09-19"]
print(pd.DataFrame({
"day": saturdays,
"isha adhan": [hhmm(crowd.prayer_times(s)["isha"]) for s in saturdays],
"20:00 on the wall clock": 1200 - 659,
"20:00 on the prayer clock": [int(round(crowd.prayer_clock(s, 1200))) - 659 for s in saturdays],
}).to_string(index=False)) day isha adhan 20:00 on the wall clock 20:00 on the prayer clock
2026-09-05 20:06 541 535
2026-09-12 19:59 541 542
2026-09-19 19:52 541 549
Whether this is worth the trouble is a question for the data, answered below.
What makes it a curve
3. A smooth curve. With one free value per minute, f could jump anywhere. A curve is smooth: three neighbouring values lie almost on a line. The second-order random walk says exactly this,
for every minute s. A small σf forces the curve towards a straight line; a large one lets it bend sharply. As with the levels, σf is estimated from the data: the model decides how smooth the day is. In pyINLA this is "model": "rw2" on the clock index.
The curve is defined around zero: it adds nothing to the day's average and only moves the count up and down within the day. The option scale.model puts σf on a standard scale, so that the same prior means the same thing for a curve of any length.
4. Friday is not Saturday. On Fridays the noon prayer is the weekly congregational prayer, Jumu'ah, and the day looks different. One curve for both days would blur them. "replicate": "weekday" gives two curves, one per weekday, which share one σf: they are equally smooth, but otherwise free.
Let the data choose
We have two choices to make: wall clock or prayer clock, one curve or two. Each can be tested by fitting both versions and comparing them. Two numbers are compared:
- sd left: the standard deviation of what the fit does not explain, as in Part 2;
- WAIC: an estimate of how well the model would predict counts it has not seen. It rewards a close fit and penalises needless flexibility. Lower is better, and only differences matter.
x["weekday"] = crowd.codes(d.weekday) # 1 = Friday, 2 = Saturday
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}})
def left(res):
"""The sd of what the fit leaves unexplained."""
return (x.y - res.summary_linear_predictor["mean"].to_numpy()).std()
def rw2(index, **more):
"""A smooth curve over the index: a second-order random walk."""
return {"id": index, "model": "rw2", "scale.model": True, "hyper": pc(1), **more}
candidates = {"wall clock, one curve": rw2("wall"),
"prayer clock, one curve": rw2("clock"),
"wall clock, a curve per weekday": rw2("wall", replicate="weekday"),
"prayer clock, a curve per weekday": rw2("clock", replicate="weekday")}
fits = {name: fit(term) for name, term in candidates.items()}
print(pd.DataFrame({"sd left": {name: round(left(res), 3) for name, res in fits.items()},
"WAIC": {name: round(res.waic["waic"]) for name, res in fits.items()}})) sd left WAIC
wall clock, one curve 0.451 13403
prayer clock, one curve 0.442 12961
wall clock, a curve per weekday 0.430 12465
prayer clock, a curve per weekday 0.423 12130Reading the result.
- The prayer clock is better than the wall clock, with one curve (WAIC 12,961 against 13,403) and with two (12,130 against 12,465).
- A curve per weekday is better than one curve for both days (12,130 against 12,961).
- With the best of the four, the sd left falls from 0.59 to 0.42.
The gain from the prayer clock is modest in the sd left, because the noon and afternoon adhans hardly move in two weeks. It is clear in the evening, and WAIC sees it.
The typical day
We keep the prayer clock with a curve per weekday. A fitted term is a table: one row for each of its values, with the posterior mean, standard deviation and quantiles.
curve = candidates["prayer clock, a curve per weekday"]
res = fits["prayer clock, a curve per weekday"]
f = res.summary_random["clock"]
print(len(f), "rows: 641 minutes of the Friday curve, then 641 of the Saturday curve\n")
print(f[["ID", "mean", "sd", "0.025quant", "0.975quant"]].round(3).head(3))1282 rows: 641 minutes of the Friday curve, then 641 of the Saturday curve
ID mean sd 0.025quant 0.975quant
0 1.0 -0.171 0.088 -0.344 0.002
1 2.0 -0.158 0.073 -0.301 -0.015
2 3.0 -0.144 0.061 -0.264 -0.025
Reading the result. The values are on the log scale, so the figure shows their exponentials: 2 means twice the level. The curve dips after each adhan and surges about half an hour later. The two weekdays agree in the afternoon and differ most around noon, where the Friday surge is larger and lasts longer.
What it cannot do
This curve is shared: every camera is given the same shape, scaled by its level. If one place fills up before a prayer while another empties, the shared curve can only show their average. Part 4 looks at what it misses, camera by camera.
x = x.drop(columns="wall")
x.to_pickle("work/x_part3.pkl") # the model table so far
json.dump(terms + [curve], open("work/terms_part3.json", "w")) # the model so far
# 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/part3.pkl")
f.to_pickle("work/part3_clock.pkl")
json.dump({name: [float(left(r)), float(r.waic["waic"])] for name, r in fits.items()},
open("work/part3.json", "w"))The code of this part, with the output it printed: 03_typical_day.ipynb. It reads crowd.py and the files the earlier parts saved in work/.