Code
# The two talkers, by the CMU ARCTIC speaker names. Sources: docs/speech/SOURCES.md.
SPEAKERS = {"Male talker": "bdl", "Female talker": "slt"}
talkers = {
label: finish(so.load(fetch(f"docs/speech/{speaker}_arctic_a0131.flac")))
for label, speaker in SPEAKERS.items()
}
tracks = {label: so.f0_track(snd) for label, snd in talkers.items()}
fs = 16000
rng = np.random.default_rng(0)
def analyze(snd):
"""The cochleagram, and modulation spectrograms with a 1 s and a 0.25 s window."""
env = so.cosine_filterbank(n_bands=16, f_lo=100, f_hi=7000).analyze(snd).envelopes(fs=1000)
return env, so.ModulationSpectrogram(env, window=1.0), so.ModulationSpectrogram(env, window=0.25)
def depth_db(msg):
"""Depth in dB for every band, rate and time window, NaN where the cell is not valid."""
db = 20 * np.log10(msg.depth[0])
db[~msg.valid] = np.nan
return db
def rate_ticks(axis):
"""Label a logarithmic rate axis at whole octaves (2, 4, ..., 64 Hz) and nowhere else."""
from matplotlib.ticker import FixedLocator, NullFormatter, ScalarFormatter
axis.set_major_locator(FixedLocator([2, 4, 8, 16, 32, 64]))
axis.set_major_formatter(ScalarFormatter())
axis.set_minor_formatter(NullFormatter())
def draw(column, snd, marks):
"""The cochleagram and both modulation spectrograms, one above the other in ``column`` (a
figure or subfigure), with dashed lines at ``marks`` [s]. Returns the analyses and axes."""
env, msg, sharp = analyze(snd)
axes = column.subplots(3, 1, sharex=True)
env.plot(ax=axes[0])
axes[0].set(title="Cochleagram", xlabel="")
msg.plot(ax=axes[1], colorbar=False)
axes[1].set(title="Modulation spectrogram, 1 s window (pooled over bands)", xlabel="")
sharp.plot(ax=axes[2], colorbar=False)
axes[2].set_title("Modulation spectrogram, 0.25 s window (pooled over bands)")
# One color scale for both windows, so their depths can be compared
top = max(np.nanmax(20 * np.log10(view.pooled_depth()[0])) for view in (msg, sharp))
for ax in axes[1:]:
ax.collections[0].set_clim(top - 30, top)
column.colorbar(axes[1].collections[0], ax=axes[1:], label="Depth [dB]", shrink=0.9)
for ax in axes[1:]:
rate_ticks(ax.yaxis)
for ax in axes:
for m in marks:
ax.axvline(m, color="c", lw=1, ls="--")
return msg, list(axes)
def show(snd, marks=(), start=None):
"""``draw`` for one sound, and the band x rate depth image (1 s window) that follows the sound
beside the player."""
fig = plt.figure(figsize=(9, 8.4), layout="constrained")
msg, axes = draw(fig, snd, marks)
db = depth_db(msg)
top = np.nanmax(db)
# Only the time windows that lie wholly inside the sound: before the first one and after the
# last, the image holds still. And only rates about half an octave apart, so the image's
# even grid of cells reads as a logarithmic rate axis, as in the figures.
measured = msg.valid.any(axis=(0, 1))
columns = np.unique([np.argmin(np.abs(np.log(msg.fm / (2 * 2 ** (k / 2))))) for k in range(11)])
live = {
"t": msg.t[measured],
"image": db[:, columns][:, :, measured],
"x": msg.fm[columns],
"y": msg.f,
"range": (top - 30, top),
"xlabel": "Modulation rate [Hz]",
"ylabel": "Frequency [Hz]",
"title": "Depth",
"start": snd.duration / 2 if start is None else start,
}
return fig, axes, live
def show_pair(sounds, marks, moments):
"""One column per talker: ``draw``, and under it the band x rate depth image (1 s window) at
each of that talker's ``moments`` [s], named by their keys. Returns the figure and, for
each talker, the panels the playhead follows."""
fig = plt.figure(figsize=(12, 11), layout="constrained")
columns = fig.subfigures(1, 2)
playhead = {}
for column, (label, snd) in zip(columns, sounds.items(), strict=True):
upper, lower = column.subfigures(2, 1, height_ratios=[3, 1])
msg, axes = draw(upper, snd, marks[label])
upper.suptitle(label, fontsize=11)
db = depth_db(msg)
top = np.nanmax(db)
cuts = lower.subplots(1, len(moments[label]), sharey=True)
for ax, (name, moment) in zip(cuts, moments[label].items(), strict=True):
i = int(np.argmin(np.abs(msg.t - moment)))
image = ax.pcolormesh(
msg.fm, msg.f, db[:, :, i], cmap="magma", vmin=top - 30, vmax=top, shading="nearest"
)
image.cmap.set_bad("0.75")
so.plotting.log_frequency_axis(ax, "both")
ax.set(title=f"{name}, {msg.t[i]:.1f} s", xlabel="Rate [Hz]")
rate_ticks(ax.xaxis)
cuts[0].set_ylabel("Frequency [Hz]")
lower.colorbar(image, ax=cuts, label="Depth [dB]", shrink=0.9)
playhead[label] = axes
return fig, playhead