Rhythms of a street
June 23, 2026
I bought a Raspberry Pi, a tiny computer that people have used for fun little robotic projects, house automation, game emulators or weather stations. This isn't my first experience with this kind of device: in 2024 I used a toolkit from AMD as part of a robot that moves particles with fluids.
As a computational scientist, I usually see computers as tools for simulation and data analysis. What attracted me here was a different use: turning a computer into an instrument that continuously observes the physical world. I bought a USB microphone for a few dollars, and wrote a short program to record how loud my bedroom was over the course of two weeks. Let's see if we find anything interesting.
The signal is very noisy, partly because of the low-quality microphone, but mostly because the street under my window is a noisy place. Nevertheless, a simple moving average reveals some expected patterns. There are clear peaks during the morning and evening rush hours, when the traffic is the heaviest. It is also easy to distinguish the nighttime, when it is a lot quieter. The large peak in the night of May 21st corresponds to my AC unit fighting the particular high heat of that day.
We can observe this daily repetition when we look at the autocorrelation of the signal:
There is again a clear peak around 24 hours, although the correlation is relatively weak. (By the way, computing an autocorrelation is very similar to a convolution, which can be done efficiently using FFTs.) The autocorrelation still looks noisy. Let's zoom in:
Surprisingly, among all the apparent noise, we see very clear oscillations. Their period is around 85 seconds. This was the time scale I was hoping to find: the traffic light cycle around the block. I measured it on my walk home and the agreement is surprisingly good.
This was the first experiment with my Raspberry Pi. I had no specific questions other than: how noisy is my street when I am not paying attention? Despite the relatively cheap microphone, I found surprisingly rich dynamics at multiple time scales. Right now my Raspberry Pi isn't listening anymore, but I might make it watch soon...
The figures were originally produced with the following scripts:
Show code
#!/usr/bin/env python
import argparse
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.lines import Line2D
import numpy as np
import pandas as pd
def main():
parser = argparse.ArgumentParser()
parser.add_argument('audio_csv', type=str, help='rms data')
parser.add_argument('--save', type=str, default=None)
args = parser.parse_args()
tz = "America/New_York"
df = pd.read_csv(args.audio_csv)
rms_scale = df["rms_mean"].mean()
df["rms_mean"] /= rms_scale
df["rms_max"] /= rms_scale
df["peak_max"] /= rms_scale
df["time"] = pd.to_datetime(df["interval_start_utc"], utc=True, format='ISO8601').dt.tz_convert(tz)
df = df.sort_values("time")
df = df.set_index("time")
df["rms_30m"] = df["rms_mean"].rolling("30min", center=True).mean()
df["rms_1h"] = df["rms_mean"].rolling("1h", center=True).mean()
fig, ax = plt.subplots()
ax.plot(df.index, df["rms_mean"], '.', ms=0.1, c='C0', label='10s window', rasterized=True)
ax.plot(df.index, df["rms_1h"], '-', lw=1, c='C1', label='1h window')
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(
mdates.DateFormatter("%b %d")
)
plt.setp(
ax.get_xticklabels(),
rotation=45,
ha="right",
)
ax.set_ylabel("RMS energy")
ax.set_ylim(0.0, 5)
legend_elements = [
Line2D(
[0], [0],
marker='.',
linestyle='None',
color='C0',
markersize=6,
label='10s window'
),
Line2D(
[0], [0],
color='C1',
lw=1,
label='1h window'
),
]
ax.legend(handles=legend_elements)
plt.tight_layout()
if args.save:
plt.savefig(args.save, dpi=200)
else:
plt.show()
if __name__ == '__main__':
main()
Show code
#!/usr/bin/env python
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def main():
parser = argparse.ArgumentParser()
parser.add_argument("audio_csv", type=str, help="rms data")
parser.add_argument("--max-lag-hours", type=float, default=24.0)
parser.add_argument("--minutes", action="store_true", help="show x axis in minutes instead of hours")
parser.add_argument("--save", type=str, default=None)
args = parser.parse_args()
df = pd.read_csv(args.audio_csv)
df["time"] = pd.to_datetime(df["interval_start_utc"], utc=True, format="ISO8601")
df = df.sort_values("time").set_index("time")
x = df["rms_mean"] / df["rms_mean"].mean()
dt = "10s"
x = x.resample(dt).mean().interpolate()
dt_seconds = pd.to_timedelta(dt).total_seconds()
max_lag_samples = int(args.max_lag_hours * 3600 / dt_seconds)
y = x.to_numpy()
y -= y.mean()
# FFT-based autocorrelation — O(n log n), avoids O(n^2) loop
n = len(y)
yf = np.fft.rfft(y, n=2 * n)
acf = np.fft.irfft(yf * np.conj(yf))[:n].real
acf /= acf[0]
acf = acf[:max_lag_samples + 1]
lags_hours = np.arange(len(acf)) * dt_seconds / 3600
if args.minutes:
lags = lags_hours * 60
max_lag = args.max_lag_hours * 60
xlabel = "Lag (minutes)"
else:
lags = lags_hours
max_lag = args.max_lag_hours
xlabel = "Lag (hours)"
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(lags, acf, "-", lw=0.8, c="C0")
ax.axhline(0, color="k", lw=0.5, ls="--")
ax.set_xlabel(xlabel)
ax.set_ylabel("Autocorrelation")
ax.set_xlim(0, max_lag)
plt.tight_layout()
if args.save:
plt.savefig(args.save)
else:
plt.show()
if __name__ == "__main__":
main()
And I then asked Claude Code to make them interactive with plotly:
Show code
#!/usr/bin/env python
"""Interactive (plotly) versions of the figures in plot_raw.py and
plot_autocorrelation.py. Each figure is saved as an HTML fragment (div +
inline script, no plotly.js) to be inlined by the {{plotly(...)}} directive;
plotly.js itself is added once per page by tools/blogpage.py."""
import argparse
import numpy as np
import pandas as pd
import plotly.graph_objects as go
# Match source/blog/matplotlibrc: color cycle, spines left+bottom only,
# no grid, transparent background.
C0 = "#C70303"
C1 = "#2979EA"
AXIS = dict(
showline=True,
linecolor="#1f2328",
linewidth=1,
ticks="outside",
ticklen=4,
tickwidth=1,
tickcolor="#1f2328",
showgrid=False,
zeroline=False,
mirror=False,
)
LAYOUT = dict(
font=dict(family='"IBM Plex Serif", Georgia, serif', size=14, color="#1f2328"),
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
margin=dict(l=60, r=8, t=12, b=50),
showlegend=False,
)
CONFIG = {
"responsive": True,
"displaylogo": False,
"modeBarButtonsToRemove": ["select2d", "lasso2d", "autoScale2d"],
}
def load_rms(audio_csv, tz):
df = pd.read_csv(audio_csv)
scale = df["rms_mean"].mean()
t = pd.to_datetime(df["interval_start_utc"], utc=True, format="ISO8601")
if tz is not None:
t = t.dt.tz_convert(tz)
return pd.Series(df["rms_mean"].values / scale, index=t).sort_index()
def uniform(series, dt):
"""Resample to a uniform grid so the trace can be stored as (x0, dx, y)
instead of one timestamp per point — much smaller HTML payload."""
u = series.resample(dt).mean()
u.index = u.index.tz_localize(None)
x0 = u.index[0].isoformat(sep=" ")
dx_ms = pd.to_timedelta(dt).total_seconds() * 1000
return x0, dx_ms, np.round(u.to_numpy(), 3)
def fig_raw(audio_csv):
s = load_rms(audio_csv, tz="America/New_York")
x0, dx, y = uniform(s, "10s")
x0_1h, dx_1h, y_1h = uniform(s.rolling("1h", center=True).mean(), "5min")
fig = go.Figure()
fig.add_trace(go.Scattergl(
x0=x0, dx=dx, y=y,
mode="markers",
marker=dict(color=C0, size=2, opacity=0.25),
name="10s window",
hovertemplate="%{x|%b %d, %H:%M:%S}<br>RMS %{y:.2f}<extra>10s window</extra>",
))
fig.add_trace(go.Scattergl(
x0=x0_1h, dx=dx_1h, y=y_1h,
mode="lines",
line=dict(color=C1, width=1.5),
name="1h window",
hovertemplate="%{x|%b %d, %H:%M}<br>RMS %{y:.2f}<extra>1h window</extra>",
))
fig.update_layout(
**LAYOUT,
height=420,
xaxis=dict(AXIS, tickangle=-45),
yaxis=dict(AXIS, title=dict(text="RMS energy"), range=[0.0, 5.0]),
)
fig.update_layout(
showlegend=True,
# itemsizing='constant' keeps the size-2 markers visible in the legend
legend=dict(x=0.98, y=0.98, xanchor="right", yanchor="top",
bgcolor="rgba(0,0,0,0)", itemsizing="constant"),
)
return fig
def autocorrelation(audio_csv, max_lag_hours):
s = load_rms(audio_csv, tz=None)
dt = "10s"
x = s.resample(dt).mean().interpolate()
dt_seconds = pd.to_timedelta(dt).total_seconds()
max_lag_samples = int(max_lag_hours * 3600 / dt_seconds)
y = x.to_numpy()
y -= y.mean()
# FFT-based autocorrelation — O(n log n), avoids O(n^2) loop
n = len(y)
yf = np.fft.rfft(y, n=2 * n)
acf = np.fft.irfft(yf * np.conj(yf))[:n].real
acf /= acf[0]
acf = acf[:max_lag_samples + 1]
lags_hours = np.arange(len(acf)) * dt_seconds / 3600
return lags_hours, acf
def fig_autocorrelation(audio_csv, max_lag_hours, minutes):
lags, acf = autocorrelation(audio_csv, max_lag_hours)
if minutes:
lags = lags * 60
max_lag = max_lag_hours * 60
xlabel = "Lag (minutes)"
hover = "%{x:.1f} min<br>ACF %{y:.3f}<extra></extra>"
else:
max_lag = max_lag_hours
xlabel = "Lag (hours)"
hover = "%{x:.2f} h<br>ACF %{y:.3f}<extra></extra>"
fig = go.Figure()
# SVG scatter (not gl): few enough points, and it renders without WebGL
fig.add_trace(go.Scatter(
x=np.round(lags, 4), y=np.round(acf, 4),
mode="lines",
line=dict(color=C0, width=1),
hovertemplate=hover,
))
fig.add_hline(y=0, line=dict(color="black", width=0.5, dash="dash"))
fig.update_layout(
**LAYOUT,
height=300,
xaxis=dict(AXIS, title=dict(text=xlabel), range=[0, max_lag]),
yaxis=dict(AXIS, title=dict(text="Autocorrelation")),
)
return fig
def main():
parser = argparse.ArgumentParser()
parser.add_argument("which", choices=["raw", "acf-long", "acf-short"])
parser.add_argument("audio_csv", type=str, help="rms data")
parser.add_argument("--save", type=str, required=True)
args = parser.parse_args()
if args.which == "raw":
fig = fig_raw(args.audio_csv)
elif args.which == "acf-long":
fig = fig_autocorrelation(args.audio_csv, max_lag_hours=48, minutes=False)
else:
fig = fig_autocorrelation(args.audio_csv, max_lag_hours=0.5, minutes=True)
div_id = "plotly-" + args.which
fig.write_html(args.save, full_html=False, include_plotlyjs=False,
div_id=div_id, config=CONFIG)
if __name__ == "__main__":
main()