views

One-way analyses, each saying what it drops: spectra and spectrograms (with the reassigned spectrogram), timbre descriptors, chroma, envelopes, modulation, the cepstrum and MFCCs, linear prediction and formant tracking, F0 tracking, the pitch-adaptive spectral envelope and band aperiodicity (after WORLD), envelope peaks and sound quilts, and the routes back to sound they have: the channel vocoder (with the envelopes) and the phase vocoder. A voice rebuilt from an F0 track, an envelope and an aperiodicity is in sonore.sources.source_filter.

sonore.views.view

Views: one-way analyses that say what they drop.

A Frame turns a sound into coefficients and back. A view keeps only part of a sound, so many sounds give the same view and none can be read back from it alone. Every view therefore has a View.synthesize() that refuses, raising NotInvertibleError with the mathematical reason (View.discards) and the route that does lead back to a sound (View.back_to_sound), if sonore has one.

That route is to_sound, on the views that have a canonical one, and its arguments are what the view discarded: Spectrum.to_sound takes a carrier for the phase, Cepstrum.to_sound a phase, PVAnalysis.to_sound a time scale and a frequency map. On any other view, View.to_sound() refuses as synthesize does.

Every view has View.plot(). A view with one obvious picture overrides it with a short call into sonore.plotting, where the drawing lives; a view with none keeps the base method, which raises NotImplementedError with View.no_plot, a sentence naming what to plot instead.

exception NotInvertibleError[source]

Bases: NotImplementedError

Raised by View.synthesize(), and by View.to_sound() on a view with no route back: the view keeps too little of a sound for any sound to be recovered from it alone.

class TimeFrequencyGrid(*args, **kwargs)[source]

Bases: Protocol

Anything held as values on a grid of times and frequencies and read at any point: t [s] and f [Hz] are the grid, data has shape (n_channels, len(f), len(t)), and view(t, f) gives the values at times t and frequencies f with shape (n_channels, len(f), len(t)). SpectralEnvelope and Aperiodicity are two; a user’s own class with these four members is a third, without inheriting anything. The functions that take any such view (source_filter_synthesize(), warp_frequency(), harmonic_complex(), Aperiodicity.bands) are typed with it.

t: np.ndarray
f: np.ndarray
data: np.ndarray
class View[source]

Bases: object

Base class of every view.

Each subclass sets two class attributes: discards, one sentence saying what the view drops and so why it cannot be inverted, and back_to_sound, one sentence naming the route to a sound that exists, or an empty string if there is none. A subclass that does not override plot() sets no_plot, one sentence saying why it has no picture and what to plot instead.

discards = ''
back_to_sound = ''
no_plot = ''
synthesize(*args, **kwargs) → Sound[source]

Refuse: raise NotInvertibleError with discards and back_to_sound as the message.

to_sound(*args, **kwargs) → Sound[source]

Refuse, as synthesize() does, on a view with no canonical route back to a sound; views that have one override it.

plot(*args, **kwargs) → Any[source]

Refuse, on a view with no single picture: raise NotImplementedError with no_plot as the message. Views that have a picture override it.

sonore.views.spectra

Spectra and spectrograms that keep power and drop the phase: the spectrum of a sound, a TANDEM-STRAIGHT-style power spectrogram, and the reassigned spectrogram.

A Spectrum’s levels are a one-sided power spectral density in dB re 1 per Hz, as Welch’s method gives it, so Spectrum.from_sound() and long_term_spectrum() agree for a steady noise (the first scatters, the second is smooth).

class Spectrum(f: ndarray, level: ndarray)[source]

Bases: View

A magnitude spectrum: frequencies [Hz] and levels [dB].

A view: it keeps one level per frequency and drops the phase, and with it all timing, so no sound can be read back from it.

discards = 'Spectrum keeps only the level at each frequency: it discards the phase, and with it all timing, so many sounds share one spectrum.'
back_to_sound = "Spectrum.to_sound makes a sound with this spectrum from a carrier that supplies the phase (a new noise, another sound's phase, or the minimum phase), which is not the analyzed sound."
f: ndarray
level: ndarray
classmethod from_sound(sound: Sound) → Spectrum[source]

The power spectral density of the whole sound from one FFT with no window, |X|**2 / (fs N) with every bin but 0 Hz and Nyquist counted twice (one-sided), in dB re 1 per Hz. The sound is first mixed to mono by averaging its channels, so channels in antiphase cancel. Each bin of a noise scatters about its expected level; see long_term_spectrum() for a smooth estimate on the same scale.

level_at(freqs: ndarray) → ndarray[source]

Levels [dB] linearly interpolated at freqs, held at the end values outside the spectrum’s frequencies.

level_in_range(freqs: ndarray) → ndarray[source]

level_at inside the spectrum’s frequencies and the floor outside them: a spectrum says nothing about the frequencies it was not measured at, so a sound made from it is silent there.

relative() → Spectrum[source]

Levels re the maximum (0 dB peak).

smooth(fraction: float = 0.3333333333333333) → Spectrum[source]

Fractional-octave smoothing (power average over fraction octave).

to_sound(duration: float, fs: float, *, carrier: Literal['noise', 'minimum'] | Sound = 'noise', rng: int | Generator | None = None, **noise_kwargs) → Sound[source]

A sound with this magnitude spectrum, its phase supplied by carrier.

"noise" draws Gaussian noise with this spectral shape (extra keyword arguments go to gaussian_noise()). A Sound lends its phase: its first duration seconds, each channel’s spectrum given this magnitude, so Spectrum.from_sound(x).to_sound(x.duration, x.fs, carrier=x) gives back x at RMS 1. "minimum" gives the minimum-phase impulse response with this magnitude, from the folded cepstrum as in Cepstrum.to_stft. The level is read at the FFT bins of duration by linear interpolation, and is silent outside the spectrum’s frequencies (a spectrum measured at 16 kHz gives nothing above 8 kHz at any fs). Every result has RMS 1, as the generators do. None is the analyzed sound: the spectrum keeps no phase to give back.

plot(ax: Axes | None = None, **kwargs) → Axes[source]

Level against frequency, on a log frequency axis and re the peak by default (see plot_spectrum()).

long_term_spectrum(sounds: Sound | Sequence[Sound], *, win_dur: float = 0.1) → Spectrum[source]

Long-term average spectrum via Welch’s method, averaged over sounds (weighted by duration), in dB re 1 per Hz. This is the right input for speech-shaped noise.

win_dur [s] is Welch’s segment length (Hann windows, half overlapping); the frequency spacing is 1 / win_dur, 10 Hz by default. A sound shorter than win_dur is one segment, its own length, zero-padded to win_dur, which puts it on the same frequencies without changing its spectrum. Sounds at another rate are resampled to the first one’s, and each is mixed to mono by averaging its channels.

class TFPower(power: ndarray, t: ndarray, f: ndarray)[source]

Bases: View

A time-frequency power that is not a frame’s coefficients, so it has no synthesis: for example tandem_power(). It keeps the power of each cell and drops the phase.

power has shape (n_channels, n_freqs, n_windows), on frequencies f [Hz] and window times t [s], which need not be uniform.

discards = "TFPower keeps only the power of each cell: it discards the phase, and the cells are not a frame's coefficients, so no synthesis undoes them."
back_to_sound = ''
power: ndarray
t: ndarray
f: ndarray
property db: ndarray[source]

10*log10(power), floored like the other representations.

plot(ax: Axes | None = None, *, channel: int = 0, **kwargs) → Axes[source]

Power in dB (see plot_tf_db()).

tandem_power(sound: Sound, f0_times: Sequence[float], f0: Sequence[float], *, periods: float = 2.5, overlap: float = 4, window: str | tuple = 'blackman') → TFPower[source]

A TANDEM-STRAIGHT-style power spectrogram: the average of two pitch-adaptive spectrograms whose windows sit a quarter period before and after each window center.

For a periodic sound, the power through a window centered at t fluctuates with period T0 as the window slides across the glottal pulses. Averaging the powers at t - T0/4 and t + T0/4 (half a period apart) cancels the odd harmonics of that fluctuation, including the largest, so a short window shows the spectral envelope steadily. The defaults, a Blackman window 2.5 periods long, are those of Kawahara et al. (2011). Only this averaging is implemented, not TANDEM-STRAIGHT’s smoothing or aperiodicity analysis.

The schedule is pitch_adaptive() over the sound, with F0 bridged across unvoiced stretches. The result is magnitude only: synthesizing from the pair would need a union of two frames, which sonore does not provide.

class ReassignedSpectrogram(t_hat: ndarray, f_hat: ndarray, power: ndarray, keep: ndarray)[source]

Bases: View

Spectrogram cells moved to their reassigned times and frequencies.

t_hat, f_hat and power have shape (n_channels, n_freqs, n_windows), one entry per STFT cell; keep marks the cells within the threshold of the maximum. binned() sums the kept power onto a grid for display. There is no synthesis: reassignment is not linear.

discards = "ReassignedSpectrogram discards the phase and moves each cell's power to a new time and frequency, many cells to one point, so different sounds give the same picture."
back_to_sound = ''
no_plot = 'ReassignedSpectrogram has no plot: its points lie off any grid until one is chosen, so plot binned(t_edges, f_edges).'
t_hat: ndarray
f_hat: ndarray
power: ndarray
keep: ndarray
binned(t_edges: ndarray, f_edges: ndarray) → TFPower[source]

Kept power summed into the cells of t_edges x f_edges [s, Hz]; points outside the edges are dropped.

reassigned_spectrogram(sound: Sound, frame: GaborFrame, *, threshold_db: float = -60.0) → ReassignedSpectrogram[source]

The reassigned spectrogram (Kodera et al., 1978; Auger & Flandrin, 1995).

Each cell of frame’s spectrogram is moved from its window time t and bin frequency f to

  • t_hat = t + Re(X_tw conj X) / |X|**2,

  • f_hat = f - Im(X_dw conj X) / (2 pi |X|**2),

where X uses the window w, X_tw the time-weighted window tau w(tau) and X_dw its derivative w'(tau), with tau in seconds from the window’s middle sample, which is where SciPy (and so GaborFrame) references each time window’s phase. A tone off the bin grid, an impulse and a linear chirp land on their true frequency, time and instantaneous-frequency line.

The derivative is taken from the window’s formula, so only "hann" and ("gaussian", std) windows are accepted, std in samples as in SciPy. Cells more than threshold_db below the maximum (per channel) are marked not kept: their positions are mostly noise.

sonore.views.temporal_envelope

Temporal envelopes: the slowly varying amplitude that shapes a sound over time.

“Envelope” names two things in sonore. A temporal envelope, this module’s TemporalEnvelope, is smoothed along time: the Hilbert magnitude of a sound, or of every band of a filterbank, with the fine structure dropped. A spectral envelope (sonore.views.spectral_envelope) is smoothed across frequency within one time window: the smooth curve over the harmonics, with the source dropped. Both are magnitudes on time (and frequency), but they smooth along different axes and keep different things.

A temporal envelope is not a sound. It is non-negative, it usually varies slowly enough to live at a low sampling rate, and you don’t listen to it: you apply it to a sound. One class holds both the envelope of a whole sound and one envelope per band of a filterbank:

  • snd.envelope() is a TemporalEnvelope with no filterbank; env * snd modulates the sound.

  • fb.analyze(snd).envelopes() is a TemporalEnvelope that keeps the filterbank: one envelope per band, which is a cochleagram when the filterbank is cochlea-like (an ERB cosine_filterbank() or a gammatone bank), and the band envelopes of any other bank otherwise. env * snd then splits the sound with that filterbank, multiplies each band by its envelope and sums the bands back; env * subbands modulates bands already split; env[i] is one band’s envelope.

The Hilbert decomposition of a band is then literal:

band == band.envelope() * (band / band.envelope())      # envelope x fine structure
sb == sb.envelopes() * sb.tfs()                          # for every band at once

Envelopes resampled to a lower rate are upsampled automatically (band-limited: polyphase, or the FFT for unusual rate ratios; clipped at zero) when applied to a sound.

to_sound(carrier=...) is the route back: the envelope imposed on a carrier’s fine structure. channel_vocode() is a channel vocoder: a sound’s own band envelopes imposed on a carrier. With bands of noise as the carrier (the default) it is the noise vocoder of Shannon et al. (1995), as in simulations of cochlear-implant hearing.

class TemporalEnvelope(data: ArrayLike, fs: float, filterbank: Filterbank | None = None, *, pad: int = 0, first_sample: int = 0)[source]

Bases: _PaddedBands, View

A temporal envelope: a magnitude over time, of a whole sound or of every band of a filterbank. A view: it keeps the magnitude and drops the fine structure (and, with lowpass, the envelope’s own fast detail).

Without a filterbank, data has shape (n_samples, n_channels) and env * snd modulates a Sound sample by sample (snd / env divides the envelope out). With a filterbank, data has shape (n_samples, n_bands, n_channels), the bands including the filterbank’s lowpass and highpass edge filters as in Subbands; env * snd splits the sound with the filterbank, multiplies each band by its envelope and sums the bands back, env * subbands modulates bands already split (imposing the envelopes on a carrier, not an inverse), env[i] is one band’s envelope, and env.modulation_spectrum() gives the 2-D modulation spectrum on the filterbank’s frequency scale (cycles/octave or cycles/ERB).

Arithmetic: *, / and + with numbers and with envelopes of the same shape (so 1 + 0.5 * env works). len(env) counts samples, as for a Sound; n_bands counts the bands (1 without a filterbank). A one-channel envelope applies to every channel of a sound; otherwise the channel counts must match.

Envelopes derived from padded Subbands carry the same zero-padding (pad samples at each end, hidden from data), so that modulating and re-synthesizing bands can’t wrap around. Envelopes made from scratch (e.g. a rendered ripple pattern) have pad=0 and are zero outside their own extent when combined with padded bands. to_sound() puts the envelope on a carrier’s fine structure.

discards = 'TemporalEnvelope discards the fine structure: only a magnitude over time is kept, one per band when a filterbank split the sound, smoothed further when a lowpass was asked for.'
back_to_sound = "TemporalEnvelope.to_sound puts it on the fine structure of a carrier (another sound, or with a filterbank bands of a new noise or tones at the band centers), which is not the analyzed sound's fine structure."
property data: ndarray[source]

shape (n_samples, n_channels) without a filterbank, (n_samples, n_bands, n_channels) with one.

Type:

The envelope values without the padding, read-only

property n_bands: int[source]

The number of bands, edge filters included; 1 without a filterbank.

property n_channels: int[source]

Number of channels, as for the sound the envelope came from.

property duration: float[source]

Length in seconds (without the padding).

property db: ndarray[source]

The envelope in dB (20*log10), the shape of data.

classmethod concatenate(parts: Sequence[TemporalEnvelope]) → TemporalEnvelope[source]

Join the parts of a stream (for example of EnvelopePooling, or the envelopes of a time-domain filterbank’s parts) in order.

pooled(win_dur: float = 0.025, hop_dur: float = 0.01) → TemporalEnvelope[source]

The envelope’s power averaged in Hann time windows of win_dur seconds every hop_dur, as an amplitude, at rate 1 / hop_dur (see EnvelopePooling, which streams it).

lowpass(cutoff: float, *, order: int = 4) → TemporalEnvelope[source]

Zero-phase Butterworth lowpass at cutoff Hz, of every band, padding included (result clipped at 0).

resample(fs: float) → TemporalEnvelope[source]

The envelope at rate fs, padding included: band-limited, clipped at zero, with the ends extended along a line rather than dragged toward zero. When the rate ratio is a small fraction the inner signal starts exactly on a sample; otherwise within half of one.

without_edges() → TemporalEnvelope[source]

Zero the lowpass and highpass edge bands (which lie outside f_lo..f_hi), keeping the band count unchanged. A bank built with edges=False has none, and its envelopes are returned as they are.

modulation_spectrum(*, scale: Literal['linear', 'db'] = 'linear', drop_edges: bool = True) → ModulationSpectrum[source]

2-D modulation spectrum (temporal Hz x spectral cycles per scale unit) of a filterbank’s envelopes.

scale="db" transforms log envelopes. The edge bands are dropped by default, since they aren’t evenly spaced with the others; a bank built with edges=False has none to drop, and all its bands are kept.

to_sound(carrier: Sound | str = 'noise', *, fs: float | None = None, rng: RNG = None) → Sound[source]

This envelope imposed on a carrier’s fine structure.

  • a Sound lasting as long as the envelope: its own envelope is divided out (carrier / carrier.envelope()) and this one multiplied in, so only its fine structure is used; with a filterbank, the carrier is analyzed with it and that happens in every band, then the bands are synthesized. Plain envelope * sound keeps the sound’s own envelope as well (amplitude modulation).

  • "noise": a Gaussian noise from rng. With a filterbank, each band of the noise is scaled to a mean-square envelope of 1 and keeps its own random envelope fluctuations, as in the classic noise vocoder; without one, the noise’s fine structure.

  • "tone": a cosine at each band’s center (a filterbank’s envelopes only).

fs is the output rate for "noise" and "tone" (by default the envelope’s own); a Sound carrier sets its own. The edge bands are kept (see without_edges()) and the level is the envelope’s own.

plot(ax: Axes | None = None, **kwargs) → Axes[source]

A single envelope against time (see plot_envelope()); a filterbank’s envelopes as a cochleagram, time by band in dB (see plot_envelopes()).

class EnvelopePooling(win_dur: float = 0.025, hop_dur: float = 0.01, filterbank: Filterbank | None = None)[source]

Bases: SlidingWindowStream

Envelopes pooled in time windows, a block at a time: the power of the envelope weighted by a periodic Hann window of win_dur seconds, one time window every hop_dur seconds, centered on the samples 0, hop, 2 hop, ... of the envelope, as an amplitude:

pooled[k] = sqrt(sum_j w[j] e[k hop - L // 2 + j]**2 / sum_j w[j])

with zeros before the first sample and after the last. The result is a TemporalEnvelope at fs / hop, one time window per hop that starts within the envelope. This is the cochleagram of 25 ms time windows every 10 ms. TemporalEnvelope.pooled() is the batch form; a stream takes envelope blocks (filterbank says whose bands they are, None for a single envelope):

bank = so.gammatone_filterbank(n_bands=64, edges=False)
pooling = so.EnvelopePooling(25e-3, 10e-3, bank)
envelopes = (part.envelopes() for part in so.stream(bank, so.blocks(snd, 441)))
so.TemporalEnvelope.concatenate(list(so.stream(pooling, envelopes)))
# == bank.analyze(snd, domain="time").envelopes().pooled(25e-3, 10e-3)

The sum runs over the window’s samples in order, one array operation per sample, so the result does not depend on how the envelope was cut into blocks, to the last bit.

win_dur: float = 0.025
hop_dur: float = 0.01
filterbank: Filterbank | None = None
block_type[source]

alias of TemporalEnvelope

window_layout(fs: float) → tuple[int, int, int][source]

(window_length, hop, first_start) in samples at fs; first_start is where time window 0 starts, negative when it reaches before sample 0.

window_count(n_samples: int, fs: float) → int[source]

How many time windows the batch analysis of n_samples samples has.

time_windows(samples: ndarray, fs: float, first: int, count: int, n_samples: int) → TemporalEnvelope[source]

The part holding time windows first to first + count - 1, from samples ((n, n_channels), starting at time window first’s first sample), after n_samples samples of the sound have arrived.

step(state: WindowState, block: TemporalEnvelope) → tuple[WindowState, TemporalEnvelope][source]

Pool block, an envelope of this pooling’s filterbank, and return every time window now complete.

channel_vocode(sound: Sound, n_bands: int = 16, f_lo: float = 80.0, f_hi: float = 8000.0, *, carrier: Sound | str = 'noise', env_lowpass: float | None = 50.0, rng: RNG = None) → Sound[source]

A channel vocoder with Hilbert envelopes: the sound’s band envelopes on a carrier. The default, carrier="noise", is the noise vocoder of Shannon et al. (1995).

The sound is split by a cosine_filterbank of n_bands bands from f_lo to f_hi (capped at Nyquist), each band’s Hilbert envelope is lowpassed at env_lowpass Hz, and the envelopes are imposed on the carrier with TemporalEnvelope.to_sound(): "noise" (bands of noise), "tone" (sinusoids at the band centers), or a Sound at the same rate and at least as long, whose fine structure carries them. The edge bands (outside f_lo..f_hi) are silenced. The output matches the input’s RMS.

sonore.views.mask

Time-frequency masks: gains on a frame’s coefficients.

A mask keeps one gain per coefficient and nothing of any sound, so it is a View. The way back to a sound goes through the coefficients it multiplies: (stft * mask).to_sound() is the frame’s least-squares inverse of the masked coefficients. A mask works with STFT, TVSTFT and Subbands.

The ideal binary mask is the goal Wang (2005) proposed for computational auditory scene analysis: keep the coefficients where the target is stronger than the masker by more than a local criterion lc_db, the parameter whose effect on listeners Brungart, Chang, Simpson & Wang (2006) measured. Ratio masks, soft gains from the target’s share of the power, go back to Srinivasan, Roman & Wang (2006); the ideal ratio mask (T**2 / (T**2 + M**2))**beta with beta = 0.5 is the form Wang, Narayanan & Wang (2014) found best, close to a square-root Wiener filter.

For complex coefficients the power of a cell is |X|**2. Subbands are real and oscillate, so their power is the Hilbert envelope squared: the mask then follows each band’s level, not its waveform.

class Mask(values: ArrayLike, like: STFT | TVSTFT | Subbands)[source]

Bases: View

Gains, usually between 0 and 1, one per coefficient of the coefficients like it was made for (same frame, same grid).

mask * coefs and coefs * mask give the masked coefficients; .to_sound() on those is the way back to a sound. values has the layout of the coefficients’ own array: (n_channels, n_freqs, n_windows) for an STFT, (n_samples, n_bands, n_channels) for Subbands (their padding included). The gains must be finite. A mask applies only to coefficients on its own grid: the same kind, sampling rate and shape, from the same frame (or filterbank and padding).

discards = "Mask holds gains for a frame's coefficients, not the coefficients themselves: it keeps no level or phase of any sound."
back_to_sound = 'Multiply coefficients by it and go back from those: (stft * mask).to_sound().'
property t: ndarray[source]

Times [s] of the coefficients’ columns (time windows, or samples for subbands). For subbands these are the sound’s sample times, without the padding that values includes, so t is shorter than the first axis of values by twice the padding.

property f: ndarray[source]

FFT bins, or the filterbank’s center frequencies for subbands.

Type:

Frequencies [Hz] of the coefficients’ rows

apply(coefs: STFT | TVSTFT | Subbands) → STFT | TVSTFT | Subbands[source]

The coefficients multiplied by this mask (what coefs * mask does).

plot(ax: Axes | None = None, *, channel: int = 0, **kwargs) → Axes[source]

Draw one channel’s gains as an image on the coefficients’ time and frequency axes; see sonore.plotting.plot_mask().

ideal_binary_mask(target: STFT | TVSTFT | Subbands, masker: STFT | TVSTFT | Subbands, *, lc_db: float = 0.0) → Mask[source]

1 where the target’s level exceeds the masker’s by more than lc_db, the local SNR criterion, else 0 (Wang, 2005; Brungart et al., 2006).

ideal_ratio_mask(target: STFT | TVSTFT | Subbands, masker: STFT | TVSTFT | Subbands, *, beta: float = 0.5) → Mask[source]

(T**2 / (T**2 + M**2))**beta with T**2 and M**2 the powers of each coefficient (Wang, Narayanan & Wang, 2014; 0 where both are silent). beta must be positive: a negative one turns silent cells into huge gains, and 0 keeps every cell.

sonore.views.modulation

Modulation spectra, and the filterbanks that measure modulation over time.

ModulationSpectrum is the 2-D Fourier transform of a time-frequency envelope (Singh & Theunissen, 2003; Chi et al., 1999): how much of the envelope’s pattern moves at each temporal rate [Hz] and each spectral density [cycles/octave or cycles/kHz]. It has no time axis, tells upward sweeps from downward ones, and goes back to sound with ModulationSpectrum.to_sound(). ModulationBlob draws a target spectrum in code.

The modulation filterbanks are tools rather than views: they filter envelopes along time, band by band. Two come from McDermott & Simoncelli (2011) and are used by sonore.texture:

  • ConstantQModulationFilterbank: half-cycle cosines on a linear frequency axis, each spanning cf +/- cf/Q, with centers log-spaced. Used for the modulation power spectrum.

  • OctaveModulationFilterbank: half-cycle cosines on a log2 axis, each two octaves wide (cf/2 .. 2*cf), centers one octave apart. Used for the C1/C2 modulation correlations.

These two filter in the frequency domain and are therefore circular: the envelope is treated as one period of a periodic signal. That is exact for texture synthesis (seamless loops); for other uses pad the envelope first.

A third bank, HannModulationFilterbank, is defined in time instead: Hann-windowed complex exponentials of finite length, applied by direct (zero-padded, not circular) correlation, centered or causal. It is the bank behind ModulationSpectrogram, and its finite kernels are what make a causal, block-by-block version possible.

class ModulationSpectrum(stft: STFT, *, channel: int = 0)[source]

Bases: View

2-D Fourier transform of a time-frequency envelope (Singh & Theunissen, 2003; Chi et al., 1999).

ModulationSpectrum(stft) uses a dB spectrogram, so spectral modulation is w.r.t. linear frequency (cycles/kHz). octave() uses subband envelopes on a log-frequency axis (cycles/octave), the axis on which ripples (sonore.sources.ripples) are defined; more generally, any TemporalEnvelope has .modulation_spectrum().

Sign convention: a ripple sin(2*pi*(rate*t + density*x)) appears at (+rate, +density). Only non-negative spectral modulations are stored (the other half is the complex conjugate).

A view: before the transform the envelope’s mean is removed and a Hann taper applied in time, and only the level (dB, floored) is kept, so the phase of the modulations is dropped and no envelope can be read back.

A spectrum made from a filterbank’s TemporalEnvelope (by octave() or env.modulation_spectrum()) also keeps, for to_sound(), the magnitude of the untapered transform on the whole plane, the envelope’s mean, and how the envelopes were made. Edit it with with_gain(), and hear it with to_sound(), whose carrier supplies the phases it lacks (see docs/design/views/modulation-targets.md).

discards = 'ModulationSpectrum keeps only the magnitude of the 2-D Fourier transform of an envelope: it discards the phase of the modulations, which holds the timing of every event, and the fine structure under the envelope.'
back_to_sound = "ModulationSpectrum.to_sound(carrier=...) puts envelopes with these magnitudes on a carrier. A Sound carrier lends its own modulation phase (unless rng is given) and its own fine structure; carrier='tone' draws a random modulation phase from rng and puts each envelope on a steady tone at its band's center."
classmethod from_array(env: ndarray, dt: float, dx: float, spectral_unit: str) → ModulationSpectrum[source]

From a (frequency, time) envelope array sampled every dt seconds and dx scale units.

classmethod octave(sound: Sound, *, bands_per_octave: float = 12, f_lo: float = 125.0, f_hi: float = 8000.0, env_fs: float = 1000.0, scale: Literal['linear', 'db'] = 'linear') → ModulationSpectrum[source]

Modulation spectrum on a log-frequency axis [cycles/octave].

Shorthand for:

fb = cosine_filterbank(f_lo=f_lo, f_hi=f_hi, spacing=1 / bands_per_octave, scale="octave")
fb.analyze(sound.mono()).envelopes(fs=env_fs).modulation_spectrum(scale)
classmethod from_blobs(blobs: ModulationBlob | Sequence[ModulationBlob], duration: float, *, f_lo: float = 250.0, f_hi: float = 8000.0, bands_per_octave: float = 12, env_fs: float = 1000.0, rms_depth: float | None = None, scale: Literal['linear', 'db'] = 'linear', sd_db: float | None = None) → ModulationSpectrum[source]

A target spectrum drawn in code: the sum of ModulationBlob powers, on the grid octave() would measure for a sound of duration seconds, ready for to_sound().

A drawing sets a shape, not a depth, and no long-term spectrum: every band gets the same mean envelope, and the depth is given separately. With scale="linear" the blobs describe the envelopes themselves and rms_depth (default 0.2) scales the modulation: the rms of the envelope array about its mean, relative to the mean. Because envelopes cannot go below zero, a random draw reaches only a limited depth: about 0.28 for a one-blob target (measured in docs/design/views/modulation-targets.md), against 0.71 for one full ripple. to_envelopes() refuses a draw that would need clipping and names the largest depth that fits it.

With scale="db" the blobs describe the envelopes in dB, as the spectrum of octave(..., scale="db") does, and sd_db (default 6) is the rms of that dB array about its mean. Any level in dB is a positive envelope, so nothing is clipped and the modulation can be as deep as wanted: a random draw is a Gaussian field of levels, as gaussian_spectrogram() is for exponential correlations. Deep dB draws spread some of the modulation power of the linear envelopes away from the blobs.

level shows the drawn power itself (no taper).

property filterbank: Filterbank[source]

The filterbank whose envelopes this spectrum describes.

with_gain(gain: float | Callable[[ndarray, ndarray], TypeAliasForwardRef('ArrayLike')]) → ModulationSpectrum[source]

A copy with every cell’s amplitude multiplied by gain.

gain is a function g(rate, density) of rate [Hz] and spectral modulation, evaluated with rate as a row and density as a column (as ripple patterns are), or a number. A sound’s spectrum is the same at (rate, density) and (-rate, -density), so the gain is averaged over each such pair; g = lambda r, d: abs(r) <= 4 removes every modulation faster than 4 Hz, lambda r, d: r * d <= 0 every downward sweep. The displayed level (Hann-tapered) gets the same gain, which is exact where the gain is smooth across the taper’s rate resolution.

to_envelopes(*, carrier: Sound | None = None, rng: RNG = None, phase: np.ndarray | None = None, quiet: bool = False) → TemporalEnvelope[source]

The envelopes this spectrum describes, given a modulation phase.

The stored magnitudes and mean fix everything but the phase of the 2-D transform, which holds when each event happens and how the bands line up. A Sound carrier lends the phase of its own envelopes (analyzed as this spectrum’s were), so the spectrum of x with carrier=x gives back x’s envelopes; with no carrier the phase is drawn at random from rng at every nonzero rate, while the zero-rate column keeps its own phase, so each band keeps its long-term level (the long-term spectrum). Envelopes rebuilt from a linear-scale spectrum can go below zero; they are clipped, with a warning saying how much, which changes their spectrum. Edge bands that the spectrum dropped are zero.

phase gives the modulation phase directly, in the shape modulation_phase() returns, in place of a carrier or a draw. quiet clips negative values without a warning, and without the refusal of a from_blobs() target, as inside a search.

modulation_phase(sound: Sound | Subbands) → np.ndarray[source]

Phase of the 2-D transform of the envelopes of sound, analyzed as this spectrum’s were, in the shape of the stored magnitudes.

A Sound is analyzed by filterbank (in mono, cut to the analyzed duration); Subbands must come from that filterbank and span the analyzed duration.

iterate(sound: Sound) → Sound[source]

One step of the search to_sound(iterations=n) takes: analyze sound, keep its fine structure and modulation phase, impose the stored magnitudes, and resynthesize.

sound (mono, at any rate) must be at least as long as the analyzed envelopes and is cut to their duration; so is the result, which is not normalized.

to_sound(*, carrier: Literal['tone'] | Sound, fs: float | None = None, rng: int | Generator | None = None, iterations: int = 0) → Sound[source]

A sound whose envelopes have this modulation spectrum: the envelopes of to_envelopes(), put on the carrier by TemporalEnvelope.to_sound.

A modulation spectrum lacks two kinds of phase, and the carrier supplies both:

  • the modulation phase (when each event happens, how the bands line up; see to_envelopes()): a Sound lends its own, unless rng is given; with "tone", or a Sound and rng, it is drawn at random from rng and keeps each band’s long-term level;

  • the fine structure under each band’s envelope: a Sound’s own, whatever the sound is (a noise of any color, a sentence, a harmonic complex), or a steady tone at each band’s center ("tone").

Unlike TemporalEnvelope.to_sound, there is no "noise" carrier here: bands of noise keep random envelopes of their own, which would add modulation that the spectrum does not have. For a noise, pass one: to_sound(carrier=so.gaussian_noise(duration, fs), rng=seed) uses only its fine structure.

to_sound(carrier=x) on the spectrum of x itself rebuilds x’s envelopes, so an edit made with with_gain() keeps the sound’s timing wherever the gain is 1. fs is the audio rate, needed for "tone"; a Sound sets its own and must be at least as long as the analyzed envelopes. The result has RMS 1.

A fine structure that fluctuates within a band (a sound’s own, or a noise’s) adds modulation of its own when the result is analyzed again, so an edit survives best on "tone": removing every rate above 4 Hz from a sentence leaves 12.6-14.4 dB less power at 6-40 Hz on tones (two talkers, five random modulation phases each), but only 2.5-4.2 dB less on a noise’s or the sentence’s own fine structure (tools/check_modulation_carriers.py).

iterations then searches for a sound whose own envelopes come closer to the spectrum, as Griffin & Lim (1984) do for a spectrogram: analyze the sound, keep its fine structure and its modulation phase, impose the stored magnitudes again, and go back. On the same sentence edit, 20 iterations from the sentence’s own fine structure leave 16.5 dB less power at 6-40 Hz (measured in docs/design/views/modulation-targets.md); each iteration costs one analysis and one synthesis. One iteration is public as iterate().

A drawn target (from_blobs()) has no timing of its own, so a Sound carrier with rng pairs a drawn timing with a chosen fine structure, such as a harmonic complex’s: to_sound(carrier=tone, rng=seed).

peak(*, exclude_dc: bool = True) → tuple[float, float][source]

(temporal Hz, spectral) coordinates of the largest component.

At zero spectral modulation, +rate and -rate are mirror images (the envelope is the same at every frequency, so it has no direction), and the rate is reported as non-negative.

plot(ax: Axes | None = None, **kwargs) → Axes[source]

The modulation spectrum as an image in dB (see plot_modulation_spectrum()).

class ModulationBlob(rate: float, density: float, rate_width: float = 0.5, density_width: float = 0.25, level: float = 0.0)[source]

Bases: object

A patch of modulation power, for drawing a target spectrum in code (ModulationSpectrum.from_blobs()).

A Gaussian bump centered on rate [Hz] and density [cycles/octave]: rate_width is its standard deviation in octaves of rate, density_width in cycles/octave, and level its peak power [dB] relative to the other blobs. The signs follow Ripple: positive rate and density are downward sweeps, a negative rate upward ones, and a blob at density 0 is temporal modulation alone. A ripple is a blob of zero width.

rate: float
density: float
rate_width: float = 0.5
density_width: float = 0.25
level: float = 0.0
power(rate: ndarray, density: ndarray) → ndarray[source]

Relative power at every (rate, density) (broadcast), zero on the other side of the rate axis.

class ModulationFilterbank[source]

Bases: object

Base class. Subclasses define n_bands, cfs and response().

Despite the name, a modulation filterbank is not a Filterbank: it filters envelopes to make views such as ModulationSpectrogram, and has no synthesis.

property cfs: ndarray[source]
response(freqs: ArrayLike) → ndarray[source]

Magnitude responses, shape (len(freqs), n_bands) (freqs >= 0).

transfer(n_samples: int, fs: float, *, analytic: bool = False) → ndarray[source]

What filter() multiplies a signal’s spectrum by, one column per band.

On the rfft grid of n_samples, shape (n_samples // 2 + 1, n_bands); with analytic=True, on the fft grid, shape (n_samples, n_bands), with negative frequencies removed and positive ones doubled.

filter(x: ArrayLike, fs: float, *, axis: int = 0, analytic: bool = False) → ndarray[source]

Filter x (circularly) along axis with every band.

The band index is appended as a new last axis. With analytic=True the output is the complex analytic signal of each band (negative frequencies removed, positive ones doubled), whose real part equals the ordinary filtered output.

class ConstantQModulationFilterbank(n_bands: int = 20, f_lo: float = 0.5, f_hi: float = 200.0, Q: float = 2.0)[source]

Bases: ModulationFilterbank

n_bands constant-Q filters with centers log-spaced from f_lo to f_hi [Hz]. Filter k is a half-cycle cosine on a linear frequency axis, nonzero on cf_k*(1 - 1/Q) .. cf_k*(1 + 1/Q).

Responses are scaled so that the summed squared response, averaged over the middle of the bank (between the 4th and the 4th-from-last center), is 1. That makes band powers sum to about the envelope’s variance.

n_bands: int = 20
f_lo: float = 0.5
f_hi: float = 200.0
Q: float = 2.0
property cfs: ndarray[source]
property scale: float[source]
response(freqs: ArrayLike) → ndarray[source]

Magnitude responses, shape (len(freqs), n_bands) (freqs >= 0).

class OctaveModulationFilterbank(n_bands: int = 7, f_hi: float = 100.0)[source]

Bases: ModulationFilterbank

n_bands filters with centers one octave apart, the highest at f_hi [Hz] (default: 1.5625, 3.125, …, 100 Hz). Filter k is a half-cycle cosine on log2 frequency spanning cf_k/2 .. 2*cf_k. Peak gain is 1 (the C1/C2 correlations are scale-invariant, so no further normalization is applied).

n_bands: int = 7
f_hi: float = 100.0
property cfs: ndarray[source]
response(freqs: ArrayLike) → ndarray[source]

Magnitude responses, shape (len(freqs), n_bands) (freqs >= 0).

class HannModulationFilterbank(f_lo: float = 0.5, f_hi: float = 64.0, per_octave: float = 2, cycles: int = 3, window: float | None = None)[source]

Bases: ModulationFilterbank

Hann-windowed complex exponentials, defined in time.

Band k correlates the envelope with h_k[j] = w_k[j] exp(i 2 pi f_k (j - (L_k - 1)/2) / fs), where w_k is a Hann window of L_k samples normalized to sum 1. Two ways to set the window:

  • cycles (the default, 3): every window holds that many cycles of its own rate, L_k = cycles * fs / f_k, with centers per_octave to the octave from f_lo to f_hi. A constant-Q bank (Q = cycles / 1.44, about 2.1 for 3 cycles), long windows for slow rates and short ones for fast rates.

  • window [s]: every band uses the same window T, with centers on the linear grid k / T from the first one at or above max(f_lo, 2/T) to f_hi. This is the STFT of the envelope.

Either way each window holds a whole number (at least 2) of cycles of its rate, so the bank ignores the envelope’s mean: the Hann window’s transform is zero at every whole bin from 2 on.

Unlike the other two banks, filter() works in time and is not circular: the envelope is taken to be zero outside its extent. The analytic output 2 y has magnitude A * m for an envelope component A * m * cos(2 pi f_k t), and its real part is the real filtered output, whose frequency response is response().

f_lo: float = 0.5
f_hi: float = 64.0
per_octave: float = 2
cycles: int = 3
window: float | None = None
property n_bands: int[source]
property cfs: ndarray[source]

Center rates [Hz].

durations() → ndarray[source]

Window length [s] of each band.

lengths(fs: float) → ndarray[source]

Window length in samples at fs (rounded, at least 3).

check_fs(fs: float) → None[source]

The envelope rate must be at least 3 * f_hi: the top band reaches about 1.25 * f_hi, and its window must hold enough samples.

kernels(fs: float) → list[tuple[ndarray, ndarray]][source]

(h_k, w_k) for every band at fs: the complex kernel and its normalized Hann window.

response(freqs: ArrayLike) → ndarray[source]

Magnitude response of the real filter (the real part of filter()’s analytic output), shape (len(freqs), n_bands), for continuous-time windows. Peak gain is about 1; zero at 0 Hz.

filter(x: ArrayLike, fs: float, *, axis: int = 0, analytic: bool = False, align: Literal['center', 'causal'] = 'center') → ndarray[source]

Filter x along axis with every band (zero outside x).

The band index is appended as a new last axis. align="center" puts each window’s middle on the output sample; "causal" ends it there, which is the centered output delayed by (L_k - 1) // 2 samples and is what a live, block-by-block analysis would produce.

sonore.views.modspectrogram

The modulation spectrogram: how strongly each band’s envelope is modulated at each rate, time window by time window.

An STFT shows how a sound’s power spectrum changes over time; a ModulationSpectrogram shows how its modulation spectrum changes over time. It is built from a filterbank’s TemporalEnvelope (any filterbank) by passing every band’s envelope through a HannModulationFilterbank and sampling the result every hop seconds. docs/design/views/modulation-spectrogram.md has the design and the numbers behind it. ModulationSpectrogramStream computes the causal one a block of envelopes at a time (docs/design/streaming.md).

class ModulationSpectrogram(envelopes: TemporalEnvelope, *, f_lo: float = 0.5, f_hi: float = 64.0, per_octave: float = 2, cycles: int = 3, window: float | None = None, hop: float = 0.01, align: Literal['center', 'causal'] = 'center', bank: HannModulationFilterbank | None = None)[source]

Bases: View

Modulation power, local mean and depth for every time window, acoustic band and modulation band.

For band envelope e_b and modulation band k with complex kernel h_k and window w_k (see HannModulationFilterbank), at each time window:

y    = sum_j e_b[n + j - c] conj(h_k[j])     (c: centered or causal)
mean = sum_j e_b[n + j - c] w_k[j]

and the stored arrays are power = |2 y|**2 and mean, both of shape (n_channels, n_bands, n_mod, n_windows). depth is 2 |y| / mean: a sinusoidal AM of depth m at the band’s rate reads m, so 100% modulation is 0 dB. Power says how much of the sound a modulation is; depth says how modulated the band is.

The acoustic axis f is the envelopes’ filterbank without its edge bands, fm holds the modulation rates and t the window times. valid ((n_bands, n_mod, n_windows)) is False where a number can’t be trusted: where the modulation rate exceeds the band’s -3 dB width (a band’s envelope can’t move faster than the band is wide), and where the window runs past either end of the envelopes (outside them the envelope is taken to be zero, so an abrupt start reads as modulation).

The representation is not invertible: the phase of y is dropped, as a magnitude spectrogram drops an STFT’s phase (the local mean is kept, and depth divides by it). For modulation filtering, filter the envelopes with a modulation bank directly.

Parameters:
  • envelopes – Band envelopes, for example fb.analyze(snd).envelopes(fs=1000). Their rate must be at least 3 times the highest modulation rate.

  • f_lo – The modulation bank (see HannModulationFilterbank): cycles sets a window of that many cycles of each band’s rate (constant Q); window [s] one window for every rate (the STFT of each envelope).

  • f_hi – The modulation bank (see HannModulationFilterbank): cycles sets a window of that many cycles of each band’s rate (constant Q); window [s] one window for every rate (the STFT of each envelope).

  • per_octave – The modulation bank (see HannModulationFilterbank): cycles sets a window of that many cycles of each band’s rate (constant Q); window [s] one window for every rate (the STFT of each envelope).

  • cycles – The modulation bank (see HannModulationFilterbank): cycles sets a window of that many cycles of each band’s rate (constant Q); window [s] one window for every rate (the STFT of each envelope).

  • window – The modulation bank (see HannModulationFilterbank): cycles sets a window of that many cycles of each band’s rate (constant Q); window [s] one window for every rate (the STFT of each envelope).

  • hop – Spacing between time windows [s], independent of the window, as in an STFT.

  • align – "center" (windows centered on the window times) or "causal" (windows ending at them: what a live analysis would see).

  • bank – A ready-made bank, instead of f_lo .. window.

discards = "ModulationSpectrogram discards the fine structure under the envelopes and the phase of every modulation band, as a magnitude spectrogram drops an STFT's phase."
back_to_sound = ''
first_window = 0
classmethod concatenate(parts: Sequence[ModulationSpectrogram]) → ModulationSpectrogram[source]

Join the parts of a stream (ModulationSpectrogramStream) in order. When the parts cover the whole envelope, the result equals ModulationSpectrogram(envelopes, align="causal", ...) to within 1e-12 of its peak (a stream carries sliding sums, the batch path convolves by FFT).

property depth: ndarray[source]

Modulation depth 2 |y| / mean, same shape as power; NaN where the window holds only digital silence.

at(t: float, *, kind: Literal['depth', 'power'] = 'depth') → ndarray[source]

The acoustic band x modulation rate image at the time window nearest t [s], shape (n_channels, n_bands, n_mod): Atlas and Shamma’s joint acoustic and modulation frequency display at one moment. kind is "depth" or "power".

average(*, kind: Literal['depth', 'power'] = 'power') → ndarray[source]

Average over the time windows where the cell is valid, shape (n_channels, n_bands, n_mod); NaN where a band and rate has no valid window (its rate exceeds the band’s width, or no window of that rate fits inside the sound). The average power is the per-band modulation power spectrum, the same kind of quantity as the texture statistics’ mod_power.

pooled_depth() → ndarray[source]

Depth pooled over acoustic bands, shape (n_channels, n_mod, n_windows): sqrt(sum_b power) / sqrt(sum_b mean**2) over the bands whose cell is valid, which weights bands by their level. NaN where no band is valid.

plot(ax: Axes | None = None, *, band: float | None = None, rate: float | None = None, **kwargs) → Axes[source]

Depth in dB as an image, invalid cells in gray. By default, modulation rate against time, pooled over bands (pooled_depth()); band= [Hz] shows the acoustic band nearest that frequency instead; rate= [Hz] shows acoustic band against time at the modulation band nearest that rate.

slices(t: float, *, rate: float = 4.0, **kwargs) → Figure[source]

Three linked cuts through the time x band x rate cube with a cursor at t [s]: rate against time (pooled), band against time at rate, and band against rate at t. Returns the figure.

animate(*, path: str | os.PathLike | None = None, sound: Sound | None = None, fps: float = 25.0, **kwargs) → FuncAnimation[source]

The band x rate image (depth, dB) time window by time window, as a matplotlib animation. With path, it is written to a video file (needs ffmpeg), and with sound as well, the sound becomes its audio track. Returns the animation.

class ModulationSpectrogramStream(filterbank: Filterbank, f_lo: float = 0.5, f_hi: float = 64.0, per_octave: float = 2, cycles: int = 3, window: float | None = None, hop: float = 0.01, bank: HannModulationFilterbank | None = None)[source]

Bases: object

The causal ModulationSpectrogram (align="causal"), a block of envelopes at a time. The parameters are the spectrogram’s, and filterbank is the one whose envelopes the blocks are. Each step returns a ModulationSpectrogram of the time windows that block completed, and ModulationSpectrogram.concatenate() joins them:

bank = so.gammatone_filterbank(n_bands=32, edges=False)
pooling = so.EnvelopePooling(2e-3, 1e-3, bank)     # envelopes at 1 kHz
modulation = so.ModulationSpectrogramStream(bank)
subbands = so.stream(bank, so.blocks(snd, 441))
envelopes = so.stream(pooling, (part.envelopes() for part in subbands))
parts = list(so.stream(modulation, envelopes))
so.ModulationSpectrogram.concatenate(parts)
# == so.ModulationSpectrogram(envelopes_of_snd, align="causal"), within 1e-12 of its peak

The time window at t holds the envelope up to t, so each time window is ready as soon as its sample arrives. Only the causal alignment streams: the centered one needs half a kernel of the future.

How it is computed: a kernel is a Hann window times a complex exponential, and sin(pi (j + 1/2) / L)**2 = 1/2 - (e**(i theta (j + 1/2)) + e**(-i theta (j + 1/2))) / 4 with theta = 2 pi / L, so y and the mean are each a few sliding sums S_n(a) = sum_j e[n - L + 1 + j] a**j with |a| = 1. A sliding sum moves on by one sample with S_n = conj(a) (S_(n-1) - e[n - L]) + e[n] a**(L - 1), so a sample costs the same for every kernel length, where the direct sum costs the kernel’s length for every time window. To keep rounding from building up, every RESTART_EVERY samples (counted from the start of the stream) the sums are computed again directly from the last samples, and in between they are carried from that restart. The result agrees with the batch path, which convolves by FFT, to within 3.2e-14 of its peak over 10 minutes, without growing, but not bit for bit (tools/check_streaming_claims.py, C12).

filterbank: Filterbank
f_lo: float = 0.5
f_hi: float = 64.0
per_octave: float = 2
cycles: int = 3
window: float | None = None
hop: float = 0.01
bank: HannModulationFilterbank | None = None
RESTART_EVERY: ClassVar[int] = 1024
PIECE: ClassVar[int] = 256
start(fs: float) → ModulationState[source]

Nothing seen yet: zeros before the first sample, as in batch.

step(state: ModulationState, block: TemporalEnvelope) → tuple[ModulationState, ModulationSpectrogram][source]

Take block, envelopes of this stream’s filterbank, and return every time window now complete.

finish(state: ModulationState) → ModulationSpectrogram[source]

Nothing: every time window ends at a sample already seen.

class ModulationState(fs: float, history: ndarray | None, n_seen: int, restart_sums: ndarray | None, carried: ndarray | None, restart: int)[source]

Bases: object

The state of a ModulationSpectrogramStream: the last samples (as many as the longest kernel, (L, n_bands, n_channels); None before the first block), how many have arrived, and each kernel’s five sliding sums at the last restart and what has been carried since.

fs: float
history: ndarray | None
n_seen: int
restart_sums: ndarray | None
carried: ndarray | None
restart: int

sonore.views.cepstrum

The real cepstrum of a short-time Fourier transform: liftering, resynthesis with the original or minimum phase, and cepstral F0.

class Cepstrum(coefs: STFT | TVSTFT, *, floor_db: float = -200.0, reference: float | None = None)[source]

Bases: View

The real cepstrum of each time window of an STFT or TVSTFT.

For a time window with spectrum X[k] on n_fft bins, the cepstrum is c[n] = IDFT(ln |X[k]|) at quefrency n / fs seconds. It is real and even in n because the sound is real, so only n = 0 .. n_fft // 2 is stored: data has shape (n_channels, n_fft // 2 + 1, n_windows) on quefrencies q [s] and window times t [s].

The natural log is used, so exp undoes it exactly: without liftering, to_sound() gives back the analyzed sound. Scaling the sound changes only c[0]. Before the log, magnitudes are floored at floor_db below the channel’s largest magnitude over all time windows, so a time window of digital silence has a flat log spectrum rather than -inf; real recordings stay far above the default. With reference the floor is fixed instead, floor_db below that magnitude in every time window, so each time window depends on its own samples only: this is what a stream needs, since it can’t know the loudest moment in advance, and cepstra of a stream’s STFT parts then join (concatenate()) into exactly the cepstrum of the whole sound with the same reference. Only the real cepstrum is provided: the complex cepstrum needs phase unwrapping, and the minimum phase comes from the real one.

Parameters:
  • coefs – The coefficients to take the cepstrum of. They are kept (as source) for their phase, frame and times.

  • floor_db – The floor, in dB below each channel’s maximum (or below reference); negative.

  • reference – A fixed magnitude, in the STFT’s units, for the floor to be set below; None (the default) sets it below each channel’s maximum.

discards = 'Cepstrum discards the phase: its coefficients are the transform of the log magnitude alone, and only the source STFT it keeps holds the phase.'
back_to_sound = "Cepstrum.to_sound borrows the phase of the STFT it was computed from, and gives the sound back exactly only for an unliftered cepstrum with phase='original'."
classmethod concatenate(parts: Sequence[Cepstrum]) → Cepstrum[source]

Cepstra of a stream’s STFT parts joined in order: exactly the cepstrum of the whole sound, if every part has the same fixed reference.

property q: ndarray[source]

Quefrencies [s].

property t: ndarray[source]

Window center times [s], those of source.

lifter(cutoff: float | Sequence[float], *, keep: Literal['low', 'high'] = 'low') → Cepstrum[source]

A rectangular lifter. keep="low" keeps the quefrencies below cutoff [s], the smooth spectral envelope; "high" keeps the rest, the fine structure such as the harmonics. cutoff is one value or one per time window, so it can follow an F0 track (half a period separates the envelope from the harmonics).

envelope() → ndarray[source]

exp(DFT(c)): the magnitude spectrum this cepstrum stands for, shape (n_channels, n_freqs, n_windows) on the source’s frequencies. After a low lifter it is the cepstral spectral envelope, which follows the shape of the true envelope but sits a few dB below the harmonic peaks, because the lifter averages the peaks with the dips between them.

envelope_view() → SpectralEnvelope[source]

envelope() as a SpectralEnvelope (method="cepstrum"): power on this cepstrum’s time windows and frequencies, read as env(t, f), so it goes wherever a spectral envelope is taken (warp_frequency(), source_filter_synthesize(), harmonic_complex()). Lifter first: cep.lifter(0.5 / f0).envelope_view().

to_stft(*, phase: Literal['original', 'minimum'] = 'original') → STFT | TVSTFT[source]

Coefficients of the source’s type and frame with envelope() as magnitude.

phase="original" takes the phase from source, so an unliftered cepstrum returns the source’s coefficients. "minimum" uses the minimum phase for that magnitude, from the folded cepstrum (c[0] kept, 2 c[n] up to n_fft / 2, zero beyond). Each time window’s response then starts at its phase reference, the middle of its window. The fold is exact up to the time aliasing of the cepstrum on n_fft bins, which is negligible once n_fft is several times the response’s length.

to_sound(*, phase: Literal['original', 'minimum'] = 'original') → Sound[source]

to_stft() synthesized by the source’s frame: exact for an unliftered cepstrum with the original phase, as long as no magnitude fell below floor_db (those are raised to the floor), and otherwise the least-squares signal for those coefficients. It is not an inverse of the cepstrum alone: the phase comes from the source STFT.

f0(*, f_lo: float = 75.0, f_hi: float = 400.0, threshold: float = 0.1) → tuple[ndarray, ndarray, ndarray][source]

Classic cepstral F0 (Noll, 1967): the largest cepstral peak between quefrencies 1/f_hi and 1/f_lo, refined by a parabola through it and its neighbors.

Returns (t, f0, peak): window times [s], and F0 [Hz] and the peak’s height for each channel and time window, shape (n_channels, n_windows). F0 is 0 where the peak is below threshold, a crude voicing rule.

A periodic sound puts ripples in the log spectrum, one per harmonic, and they are resolved only if the window holds about three periods: at two periods, many time windows come out an octave off. So every window must be at least 3 / f_lo long, or this raises. On a male spoken sentence (CMU ARCTIC bdl, 40 ms Hann time windows), the result agrees with WORLD’s Harvest within 5% on about 79% of the time windows Harvest calls voiced, and on 95% of those whose peak also exceeds 0.1. It is a baseline, not an F0 tracker: each time window is judged alone.

plot(ax: Axes | None = None, *, channel: int = 0, **kwargs) → Axes[source]

Cepstrum against time and quefrency in ms (see plot_cepstrum()).

sonore.views.mfcc

Mel-frequency cepstral coefficients (MFCCs): the log power in triangular bands on a mel scale, summarized by a discrete cosine transform.

mel_filterbank(n_mels: int, freqs: ndarray, f_lo: float, f_hi: float, *, scale: Literal['htk', 'slaney'] = 'htk', triangles: Literal['height', 'area'] = 'height', triangle_axis: Literal['mel', 'hz'] = 'mel') → tuple[ndarray, ndarray][source]

Triangular mel weights on the frequencies freqs [Hz].

The n_mels + 2 band edges are equally spaced in mel from f_lo to f_hi; band m rises linearly from edge m to edge m + 1 and falls to edge m + 2. “Linearly” is in mel with triangle_axis="mel", as HTK and Kaldi build them, and in Hz with "hz", as librosa does; the two differ inside each band, most in the wide high bands. With triangles="height" each peak is 1, and between the first and last centers the weights sum to 1. With "area" band m is scaled by 2 / (edge[m+2] - edge[m]) (Slaney’s normalization), which after the log only adds a constant to each band. The triangles are evaluated at the exact frequencies, not rounded to FFT bins.

Returns the weights, shape (n_mels, len(freqs)), and the edges [Hz].

symmetric_hamming(n_samples: int) → ndarray[source]

The Hamming window as HTK and Kaldi define it, 0.54 - 0.46 cos(2 pi i / (n - 1)): symmetric, with both ends at 0.08 (SciPy’s "hamming" spec, as a GaborFrame samples it, is the periodic one).

delta_features(values: ndarray, *, order: int = 1, width: int = 5, axis: int = -1) → ndarray[source]

Time derivatives of a feature track, computed as librosa’s feature.delta does.

Along axis, a polynomial of degree order is fitted by least squares to each run of width (odd) values and its order-th derivative taken: SciPy’s savgol_filter with mode="interp", so the first and last width // 2 values use the fit to the first or last width. For order=1 and width=5 this is HTK’s regression sum(n * c[t+n]) / sum(n**2) over n = -2..2 away from the ends. order=2 is the second derivative of a local quadratic, not the delta of the delta. Units are per time window.

class MFCC(source: Sound | STFT | TVSTFT, *, n_mfcc: int = 13, n_mels: int = 26, f_lo: float = 0.0, f_hi: float | None = None, mel_scale: Literal['htk', 'slaney'] = 'htk', triangles: Literal['height', 'area'] = 'height', triangle_axis: Literal['mel', 'hz'] = 'mel', floor_db: float = -200.0, reference: float | None = None, lifter: float = 0.0, win_dur: float | None = None, hop_dur: float | None = None)[source]

Bases: View

Mel-frequency cepstral coefficients of each time window (Davis & Mermelstein, 1980).

For each time window with power spectrum P[k]: band powers E[m] = sum_k W[m, k] P[k] through n_mels triangular mel bands (mel_filterbank()), their natural log, and the orthonormal DCT-II of that, of which the first n_mfcc coefficients are kept. The DCT of a log spectrum is a cepstrum, so the low coefficients are the slow ripples of the log mel spectrum: its envelope, without the pitch.

source is a Sound or the coefficients of an analysis:

  • a Sound is analyzed with the usual speech settings: a symmetric Hamming window win_dur long (25 ms), as HTK and Kaldi use, a hop of hop_dur (10 ms), and an FFT length of the smallest power of two at least as long as the window (512 for 25 ms at 16 kHz), as Kaldi rounds;

  • an STFT or TVSTFT is used as it is, so any window, hop or pitch-adaptive analysis can be summarized.

This is a view that discards information: the phase, everything inside each mel band, the faster ripples of the log mel spectrum beyond n_mfcc, and the level apart from c0. Many spectra have the same coefficients, and no sound is recovered from them; envelope() shows the smoothed spectrum they stand for.

The mel power is floored at floor_db below each channel’s largest band power over all time windows before the log, so scaling a sound changes only c0 and digital silence gives finite coefficients. Because the floor is set by the loudest moment, a deep floor (the default) keeps each time window independent of the rest of the sound, except where it binds (digital silence). With reference the floor is fixed instead, at floor_db below reference**2 in every time window, so each time window depends on its own samples only. A stream needs that, since it can’t know the loudest moment in advance: MFCCs of a stream’s STFT parts then join (concatenate()) into exactly the MFCCs of the whole sound with the same reference.

The defaults follow Kaldi and HTK: HTK’s mel scale, height-1 triangles straight in mel, and, for a sound, a symmetric Hamming window. With no pre-emphasis, no DC removal and use_energy=false, Kaldi’s MFCCs (compute-mfcc-feats, here through kaldi-native-fbank) are reproduced to float32 precision; Kaldi’s own lifter, low-freq of 20 Hz, 23 bins and “povey” window (a Hann window to the power 0.85, as a callable window of the GaborFrame) are all available. Kaldi’s time windows start at the first sample (snip-edges) where sonore’s are centered on multiples of the hop, so the grids line up only after trimming the sound by half a window modulo the hop.

To reproduce librosa’s feature.mfcc (Slaney mel, area-normalized triangles straight in Hz, power in dB floored 80 dB below the loudest cell), analyze with so.GaborFrame(n_fft / fs, hop / fs, window="hann", n_fft=n_fft) and use mel_scale="slaney", triangles="area", triangle_axis="hz", n_mels=128, n_mfcc=20, floor_db=-80 and db. sonore’s grid has one more time window, centered one hop before the first sample, and one or two more at the end; the others are librosa’s. librosa also floors the power at an absolute 1e-10, which matters only for sounds far quieter than any recording, and takes the loudest cell over all channels rather than per channel.

Pre-emphasis (y[n] = x[n] - 0.97 x[n-1], as in HTK and python_speech_features) is a change to the sound, so it is applied to the sound first, for example so.Sound(scipy.signal.lfilter([1, -0.97], 1, snd.data, axis=0), snd.fs). python_speech_features also rounds the triangle feet to FFT bins and replaces c0 with the log energy of the time window; neither is done here.

Parameters:
  • source – A sound, or the STFT or TVSTFT to summarize.

  • n_mfcc – Coefficients kept, c0 included.

  • n_mels – Mel bands.

  • f_lo – The outer feet of the first and last bands [Hz]; f_hi defaults to half the sampling rate.

  • f_hi – The outer feet of the first and last bands [Hz]; f_hi defaults to half the sampling rate.

  • mel_scale – "htk" or "slaney" (see freq_to_mel()).

  • triangles – "height" (peaks of 1, as HTK and Kaldi) or "area" (Slaney’s and librosa’s area normalization).

  • triangle_axis – "mel": the triangles are straight lines in mel (HTK, Kaldi); "hz": straight in Hz (librosa).

  • floor_db – Floor of the band powers, in dB below each channel’s largest (or below reference**2); negative.

  • reference – A fixed magnitude, in the STFT’s units, whose square the floor is set below; None (the default) sets it below each channel’s largest band power.

  • lifter – L of HTK’s sinusoidal lifter, which multiplies c[n] by 1 + (L / 2) sin(pi n / L); 0 for none. It is a fixed gain per coefficient: it changes Euclidean distances and nothing else.

  • win_dur – Window length and hop [s] used when source is a sound.

  • hop_dur – Window length and hop [s] used when source is a sound.

Variables:
  • data – The coefficients, shape (n_channels, n_mfcc, n_windows), in natural log units (db for dB).

  • mel_power – Band powers before the floor, shape (n_channels, n_mels, n_windows): the mel spectrogram.

  • edges – Band edges [Hz], n_mels + 2 of them; cfs are the centers.

  • source – The STFT or TVSTFT analyzed.

discards = 'MFCC discards the phase, the detail inside each mel band, and every coefficient past the last kept, so no sound has these MFCCs alone.'
back_to_sound = 'For an approximate voice, read the envelope with mfcc.envelope_view() and pass it to so.source_filter_synthesize with an F0 track and an aperiodicity.'
classmethod concatenate(parts: Sequence[MFCC]) → MFCC[source]

MFCCs of a stream’s STFT parts joined in order: exactly the MFCCs of the whole sound, if every part has the same settings and the same fixed reference.

property t: ndarray[source]

Window center times [s], those of source.

property cfs: ndarray[source]

Band centers [Hz].

property db: ndarray[source]

data times 10 / ln 10, as if the band powers had been taken in dB (10 log10) before the DCT.

Type:

The coefficients in dB units

property mel_db: ndarray[source]

The floored mel spectrogram in dB, shape (n_channels, n_mels, n_windows).

deltas(*, order: int = 1, width: int = 5) → ndarray[source]

Time derivatives of the coefficients, per time window, computed as librosa’s feature.delta (see delta_features()); width=9 is librosa’s default. Same shape as data.

With a 10 ms hop, the first-order deltas of width 5 act as a band-pass filter on each coefficient’s track, strongest near 14 Hz: they pick out changes at the rate of syllables and phonemes.

envelope(f: ArrayLike) → ndarray[source]

The smoothed power spectrum the kept coefficients stand for, at frequencies f [Hz], shape (n_channels, len(f), n_windows).

The lifter is undone, the missing coefficients are taken as zero, and the inverse DCT gives a smoothed log band power at each band center; between centers it is interpolated linearly in mel, and held constant beyond the first and last. It is a display of what the coefficients keep, for plotting against a spectrum or envelope, not an estimate of the spectrum: with as many coefficients as bands it returns the floored band powers at the centers, which are sums over bands, not spectral densities.

envelope_view(f: TypeAliasForwardRef('ArrayLike') | None = None) → SpectralEnvelope[source]

envelope() as a SpectralEnvelope (method="MFCC", with the coefficient count in its settings) on this analysis’s time windows, at frequencies f (by default its FFT bins), read as env(t, f), so it goes wherever a spectral envelope is taken (warp_frequency(), source_filter_synthesize(), harmonic_complex()). It holds band powers, sums over triangles that widen with frequency, so with triangles="height" it tilts upward against a spectral density; triangles="area" removes most of that tilt.

plot(ax: Axes | None = None, *, channel: int = 0, kind: Literal['mfcc', 'mel'] = 'mfcc', **kwargs) → Axes[source]

The coefficients against time (kind="mfcc") or the mel spectrogram in dB (kind="mel"); see plot_mfcc().

sonore.views.lpc

Linear prediction: an all-pole model of each time window, its spectral envelope, and formant tracks read from the roots of its polynomial.

levinson(autocorrelation: ndarray, order: int) → tuple[ndarray, ndarray, ndarray][source]

Solve the normal equations of linear prediction by the Levinson-Durbin recursion (Levinson, 1947; Durbin, 1960).

autocorrelation holds r[0] .. r[order] along its last axis; any leading axes are solved at once. Returns the predictor a (shape (..., order + 1), a[..., 0] = 1) minimizing the error of x[n] + a[1] x[n-1] + ... + a[p] x[n-p], the reflection coefficients k[1] .. k[p] (shape (..., order)), and the error power left, E = r[0] prod(1 - k[i]**2) (shape (...)). Each k[i] is the last coefficient of the order-i predictor, a[i] at that order (the sign Makhoul, 1975, uses). Where r[0] is 0 (a silent time window) the predictor is a = [1, 0, ..., 0] with no error.

class LPC(source: Sound | STFT | TVSTFT, order: int | None = None, *, win_dur: float | None = None, hop_dur: float | None = None)[source]

Bases: View

Linear prediction of each time window, by the autocorrelation method.

For a windowed segment with autocorrelation r[k], the predictor A(z) = 1 + a[1] z^-1 + ... + a[p] z^-p minimizes the power of the prediction error, and solves sum_j a[j] r[|i - j|] = -r[i] for i = 1 .. p (levinson()). The model of the segment is the all-pole filter 1 / A(z) driven by white noise of the error power E, with power spectrum E / |A|^2 (envelope()). Because the segment is zero outside its window, the autocorrelation is positive definite and every root of A(z) lies inside the unit circle: the model is always stable. A pair of roots |z| e^(+-j theta) is a resonance at theta fs / 2 pi Hz, -ln|z| fs / pi Hz wide (candidates()).

source is a Sound or the coefficients of an analysis:

  • a Sound is analyzed with the speech recipe: a symmetric Hamming window win_dur long (25 ms), a hop of hop_dur (10 ms), and an FFT length rounded up to a power of two at least order samples longer than the window;

  • an STFT or TVSTFT is used as it is. The autocorrelation of each time window is the inverse FFT of its power, which is the circular autocorrelation; it equals the true one at lags 0 .. order only when the FFT is at least order samples longer than the window, so a shorter FFT raises.

Pre-emphasis (y[n] = x[n] - 0.97 x[n-1]) is a change to the sound, so it is applied to the sound first, for example so.Sound( scipy.signal.lfilter([1, -0.97], 1, snd.data, axis=0), snd.fs). For formants it matters: without it, two of the poles go to the falling tilt of the voice source, and on Peterson and Barney’s vowels the formants come back about twice as far off. formant_track() does it itself.

This is a view that discards information: what the predictor cannot predict (the residual, in speech mostly the excitation: the pulses and the noise), the phase beyond the minimum phase of 1 / A(z), and the zeros of the spectrum, which an all-pole model can only imitate with poles.

Parameters:
  • source – A sound, or the STFT or TVSTFT to model.

  • order – The number of predictor coefficients p. Defaults to round(fs / 1000) + 2, the rule of thumb of one resonance per kilohertz plus two poles for the tilt (18 at 16 kHz).

  • win_dur – Window length and hop [s] used when source is a sound.

  • hop_dur – Window length and hop [s] used when source is a sound.

Variables:
  • data – The predictors a[0] .. a[p], shape (n_channels, order + 1, n_windows), with a[0] = 1.

  • error_power – The prediction error power E of each time window, shape (n_channels, n_windows).

  • reflection – The reflection coefficients, shape (n_channels, order, n_windows); all inside (-1, 1).

  • source – The STFT or TVSTFT analyzed.

discards = 'LPC keeps p coefficients and one error power per time window: the residual (the excitation), the phase and the zeros of the spectrum are gone.'
back_to_sound = 'so.formant_track reads formant tracks from it, and so.klatt_synthesize makes a voice from those and an F0 track; envelope_view() gives an envelope for so.source_filter_synthesize.'
property t: ndarray[source]

Window center times [s], those of source.

envelope(f: ArrayLike) → ndarray[source]

The model’s power spectrum E / |A|^2 at frequencies f [Hz], shape (n_channels, len(f), n_windows), on the scale of the time window’s power spectrum |X|^2: averaged over all n_fft bins, |X|^2 divided by it is exactly 1. That is why it runs close to the harmonic peaks and bridges the dips between them, where a cepstral envelope runs through the middle.

envelope_view(f: TypeAliasForwardRef('ArrayLike') | None = None) → SpectralEnvelope[source]

envelope() as a SpectralEnvelope (method="LPC", with the order in its settings) on this analysis’s time windows, at frequencies f (by default its FFT bins), read as env(t, f), so it goes wherever a spectral envelope is taken (warp_frequency(), source_filter_synthesize(), harmonic_complex()).

candidates() → tuple[ndarray, ndarray][source]

Every resonance of the model: the frequencies and bandwidths [Hz] of the roots of A(z) in the upper half plane, each shape (n_channels, order // 2, n_windows), sorted by frequency and padded with NaN. Real roots, which shape the tilt rather than a resonance, are left out. No root is dropped for being wide: on speech, a fixed bandwidth limit drops a formant now and then, and every formant above it is then mislabeled.

plot(ax: Axes | None = None, *, channel: int = 0, db_range: float = 60.0, fmax: float | None = None, **kwargs) → Axes[source]

The envelope as a time-frequency image with the candidates as dots (see plot_lpc()).

class FormantTrack(t: ndarray, frequencies: ndarray, bandwidths: ndarray, candidates: ndarray, candidate_bandwidths: ndarray, ceiling: float)[source]

Bases: View

Formant tracks: F1, F2 and F3 of each channel every hop seconds, from formant_track(). A view: it keeps only the formants.

frequencies and bandwidths have shape (n_channels, 3, n_windows), NaN where a time window had fewer resonances than formants. candidates and candidate_bandwidths have shape (n_channels, n_formants, n_windows) and hold every resonance the tracker chose from, NaN-padded. Every time window gets formants, silent and unvoiced ones too: mask them with an F0 track’s voicing (F0Track.voiced) before reading them as formants.

discards = 'FormantTrack keeps only the frequencies and bandwidths of three formants in each time window.'
back_to_sound = 'so.klatt_synthesize makes a voice from formant tracks, an F0 track and a voicing amplitude: copy synthesis, which keeps neither the source nor the higher formants of the original.'
t: ndarray
frequencies: ndarray
bandwidths: ndarray
candidates: ndarray
candidate_bandwidths: ndarray
ceiling: float
track(number: int, *, channel: int = 0) → tuple[ndarray, ndarray][source]

Formant number (1, 2 or 3) of one channel as a (times, values) pair, the form klatt_synthesize() takes for F1, F2 and F3; time windows where it is missing are left out.

plot(ax: Axes | None = None, *, channel: int = 0, candidates: bool = False, voiced: ArrayLike | None = None, **kwargs) → Axes[source]

F1 to F3 against time (see plot_formant_track()).

formant_track(sound: Sound, *, ceiling: float = 5000.0, n_formants: int = 5, win_dur: float = 0.025, hop: float = 0.005, nominal: tuple[float, float, float] = (500.0, 1500.0, 2500.0), nominal_weight: float = 1.0, bandwidth_weight: float = 1.0, skip_cost: float = 2.0, transition_weight: float = 5.0) → FormantTrack[source]

Track the first three formants of each channel of a sound.

Two stages, every hop seconds from time 0:

  1. Candidates, by Praat’s recipe for formants: the sound is resampled to twice ceiling, pre-emphasized (y[n] = x[n] - 0.97 x[n-1]), and modeled by LPC with 2 n_formants coefficients on a win_dur symmetric Hamming window; every resonance between 50 Hz and ceiling - 50 Hz is a candidate, however wide. Limiting the band to the ceiling, rather than fitting the whole band with a bandwidth limit, is what keeps the k-th candidate the k-th formant in most time windows. Praat’s advice for the ceiling is 5000 Hz for a male voice and 5500 Hz for a female one. On the two gallery sentences these candidates match Praat’s To Formant (burg) to within a median of 1 to 7 Hz, though Praat uses Burg’s method on a Gaussian window.

  2. Tracking. A Viterbi pass over the ways of giving each window’s candidates to F1, F2 and F3 in increasing order. In one window a choice costs, per formant, nominal_weight |ln(f / nominal)| plus bandwidth_weight * bandwidth / f, plus skip_cost for every candidate skipped below the highest one chosen; moving from one window to the next costs transition_weight |ln(f_now / f_before)| per formant. The nominal frequencies are those of a uniform tube 17.5 cm long, closed at one end. The weights were set by trying a few values on two sentences and a synthesized utterance, not optimized. On synthesized vowels the tracks equal the k-th candidates; on the female gallery sentence the tracker halves how often F3 jumps by more than 20% between windows.

The window and hop are rounded to whole samples at twice the ceiling, so at a ceiling of 5250 Hz the hop is 4.952 ms; t holds the times used. Unvoiced and silent time windows get formants too; mask them with an F0 track’s voicing.

Parameters:
  • sound – The sound.

  • ceiling – The highest frequency a formant can have [Hz]; the sound is resampled to twice it.

  • n_formants – How many resonances to look for below the ceiling; the LPC order is twice this.

  • win_dur – Window length and hop [s].

  • hop – Window length and hop [s].

  • nominal – The tracker’s costs (above).

  • nominal_weight – The tracker’s costs (above).

  • bandwidth_weight – The tracker’s costs (above).

  • skip_cost – The tracker’s costs (above).

  • transition_weight – The tracker’s costs (above).

sonore.views.f0

F0 tracking: candidates from a difference function, refinement by the instantaneous frequency of harmonics, a periodicity score, and a Viterbi pass that decides voicing.

class F0Track(t: ndarray, f0: ndarray, score: ndarray, candidates: ndarray, candidate_scores: ndarray, fs: float, threshold: float, first_window: int = 0)[source]

Bases: View

An F0 track: one estimate per channel every hop seconds. A view: it keeps only the pitch and the voicing.

f0 and score have shape (n_channels, n_windows); f0 is 0 where the time window is unvoiced, and score is the periodicity score of the chosen candidate (0 where unvoiced). candidates and candidate_scores have shape (n_channels, n_windows, 8) and hold every refined candidate the tracker weighed, NaN where a time window had fewer. t and a row of f0 go straight into pitch_adaptive() and lifter().

discards = 'F0Track keeps only the pitch and the voicing of each time window.'
back_to_sound = 'so.source_filter_synthesize rebuilds an approximation of the voice from it together with a spectral envelope and an aperiodicity.'
t: ndarray
f0: ndarray
score: ndarray
candidates: ndarray
candidate_scores: ndarray
fs: float
threshold: float
first_window: int = 0
classmethod concatenate(parts: Sequence[F0Track]) → F0Track[source]

Join the parts of a stream (F0TrackStream) in order: exactly f0_track(sound, delay=...) when they cover the whole sound.

property voiced: ndarray[source]

True where the time window is voiced, shape (n_channels, n_windows).

plot(ax: Axes | None = None, *, channel: int = 0, candidates: bool = False, **kwargs) → Axes[source]

F0 against time (see plot_f0_track()).

class F0TrackStream(f_lo: float = 60.0, f_hi: float = 500.0, hop: float = 0.005, threshold: float = 0.5, octave_cost: float = 2.0, switch_cost: float = 0.5, subharmonic_margin: float | None = 0.05, delay: float = 0.05)[source]

Bases: object

f0_track() a block of sound at a time, deciding each time window delay seconds after it (default 50 ms). The parameters are f0_track’s; each step returns an F0Track of the time windows it decided, and F0Track.concatenate() joins them into exactly f0_track(sound, ..., delay=delay):

tracker = so.F0TrackStream()
so.F0Track.concatenate(list(so.stream(tracker, so.blocks(snd, 441))))

A time window’s candidates need the samples a little after it (the difference function’s stretch, and the refinement’s and score’s windows at the lowest F0 searched), so a time window is decided once those samples and delay more have arrived. Its candidates are computed from its own samples only, as in batch, so they are the same numbers; the Viterbi pass carries its costs from one time window to the next and keeps the backpointers of the undecided time windows.

f_lo: float = 60.0
f_hi: float = 500.0
hop: float = 0.005
threshold: float = 0.5
octave_cost: float = 2.0
switch_cost: float = 0.5
subharmonic_margin: float | None = 0.05
delay: float = 0.05
start(fs: float) → F0State[source]

Nothing seen yet: zeros before the first sample, as in batch.

step(state: F0State, block: Sound) → tuple[F0State, F0Track][source]

Take block and return the time windows now decided.

finish(state: F0State) → F0Track[source]

The time windows left, with zeros after the last sample, the last delay of them decided by the whole path.

class F0State(fs: float, history: ndarray, origin: int, n_seen: int, next_window: int, cost: ndarray | None, last_states: ndarray | None, cands: ndarray = <factory>, scores: ndarray = <factory>, f_states: ndarray = <factory>, pointers: ndarray = <factory>, cheapest: ndarray = <factory>)[source]

Bases: object

The state of an F0TrackStream: the samples the next time windows need (history[0] is sample origin), how many samples have arrived and how many time windows have been scored, the Viterbi pass’s costs and states at the last time window scored, and for the time windows scored but not yet decided, (n_channels, n, ...): their candidates and scores, states, backpointers and cheapest state.

fs: float
history: ndarray
origin: int
n_seen: int
next_window: int
cost: ndarray | None
last_states: ndarray | None
cands: ndarray
scores: ndarray
f_states: ndarray
pointers: ndarray
cheapest: ndarray
f0_track(sound: Sound, *, f_lo: float = 60.0, f_hi: float = 500.0, hop: float = 0.005, threshold: float = 0.5, octave_cost: float = 2.0, switch_cost: float = 0.5, subharmonic_margin: float | None = 0.05, delay: float | None = None) → F0Track[source]

Track the F0 of each channel of a sound.

Four stages, every hop seconds from time 0:

  1. Candidates. Up to eight local minima of the cumulative-mean-normalized difference function (de Cheveigné & Kawahara, 2002) over a 25 ms window, at lags between 1/f_hi and 1/f_lo, each refined by a parabola. This is the autocorrelation idea with YIN’s corrections: it finds the period from all the harmonics, so it works when the fundamental is weak or filtered out. Every minimum below 1 is offered, so that the score alone decides voicing. A very regular voice has a minimum at every multiple of its period, so eight leave room for the period itself (with four, a steady 300 Hz vowel could lose it), and, as in YIN, the shortest-lag minimum within 0.1 of the deepest is always among them (with f_hi raised, a sung 800 Hz vowel has more multiples in range than there are candidates).

  2. Refinement. For a candidate f, a Blackman window three periods long; the instantaneous frequency of each harmonic is its phase advance over one sample, and the new F0 is the power-weighted mean of each harmonic’s frequency divided by its number, over the harmonics up to 1.5 kHz (at least six, at most 24). Done twice. This is the idea of WORLD’s StoneMask, written from its description; StoneMask uses the first six harmonics, which below 100 Hz hold a few percent of a vowel’s power and in noise put the refined F0 a percent off, enough for the score of a low voice to collapse.

  3. Score. The normalized correlation between a stretch two periods long, and at least 17 ms (one period of 60 Hz), and the same stretch one period later, the fractional part of the period done with a windowed sinc. For a periodic sound in independent noise it is about s / (1 + s), s the ratio of periodic to noise power, so 0.5 means the two are equally strong. Two periods rather than three so that a low voice whose F0 moves (a vibrato at 70 Hz) still lines up with its copy one period later; the floor so that a short-period candidate is judged across a whole glottal cycle of the lowest voice searched, where a formant’s ringing no longer passes for a period.

  4. Tracking. A Viterbi pass over (unvoiced, candidates) per time window. A candidate costs 1 - score and the unvoiced state 1 - threshold, so a time window leans voiced when its best score exceeds threshold; moving between candidates costs octave_cost per octave, and a voicing change costs switch_cost. A candidate is never chosen if another one at a whole multiple of its frequency (an octave, a twelfth, …) scores at least as well, less subharmonic_margin: anything periodic with period T is also periodic with period 2T, 3T, …, and without this rule a female voice is tracked low on about 1.4% of the time windows where it and the reference both say voiced (measured on the FDA database), and a steady synthetic vowel at 300 Hz at a half or a third of its F0. No smoothing follows.

Where each stage comes from: the candidates are YIN’s (de Cheveigné & Kawahara, 2002); the refinement is WORLD’s StoneMask (Morise et al., 2009); the score is the normalized correlation one period apart, as in RAPT (Talkin, 1995) and Praat (Boersma, 1993); the tracking is the dynamic programming of RAPT and Praat, with an unvoiced state and costs for octave jumps and voicing changes. The rule against whole multiples is sonore’s own. The combination is no single published tracker; pYIN (Mauch & Dixon, 2014), YIN candidates followed by a Viterbi pass over pitch and voicing, is the closest. Design and measurements in docs/design/views/f0.md.

On synthetic vowels the refined F0 is within 0.1% of the truth on a one octave per second glide and a 5.5 Hz vibrato. Against laryngograph reference F0 (a male and a female speaker), it gets the voicing of 4.0% and 1.6% of time windows wrong, where WORLD’s Harvest, which leans toward calling time windows voiced, gets about 21% wrong; where both it and the reference say voiced, 98% and 95% of time windows are within 5%. Lower threshold to voice more weak or creaky stretches, for example before resynthesis.

Parameters:
  • sound – The sound; each channel is tracked separately.

  • f_lo – The search range [Hz]. The defaults cover speaking voices; raise f_hi for singing (on speech that costs about 0.3 points of voicing error, mostly false voicings). Refined candidates are kept from 0.9 f_lo to 1.1 f_hi, so the F0 can come out up to 10% outside the range. The lowest voices are the least reliable: below about 70 Hz a vowel whose F0 moves by more than a few percent within the score’s stretch (a wide vibrato) can come out unvoiced or near a formant’s frequency, and lowering f_lo below the default voices period-doubled stretches, which the default leaves unvoiced, an octave low.

  • f_hi – The search range [Hz]. The defaults cover speaking voices; raise f_hi for singing (on speech that costs about 0.3 points of voicing error, mostly false voicings). Refined candidates are kept from 0.9 f_lo to 1.1 f_hi, so the F0 can come out up to 10% outside the range. The lowest voices are the least reliable: below about 70 Hz a vowel whose F0 moves by more than a few percent within the score’s stretch (a wide vibrato) can come out unvoiced or near a formant’s frequency, and lowering f_lo below the default voices period-doubled stretches, which the default leaves unvoiced, an octave low.

  • hop – Spacing between time windows [s].

  • threshold – The periodicity score above which a time window leans voiced.

  • octave_cost – Tracking costs, as above.

  • switch_cost – Tracking costs, as above.

  • subharmonic_margin – How much lower a candidate at a whole multiple may score and still rule out a candidate. None turns the rule off, to see the raw choice.

  • delay – None (the default) chooses the cheapest path through the whole track. A number of seconds decides each time window that long after it, as a live tracker must: the time window takes the state that the cheapest path to the time window delay later passes through (the last delay of the track take the whole path). F0TrackStream gives this result block by block. At 50 ms it chose the same as the whole track on all 12,505 time windows of 16 recordings (tools/check_streaming_claims.py, C8).

scale_f0(contour: ContourLike, ratio: float, *, range: float = 1.0) → ContourLike[source]

An F0 contour with its pitch changed: every voiced value multiplied by ratio and, if range is not 1, spread around its median on a log scale, median * ratio * (f0 / median) ** range (range=0 is a monotone at ratio times the median, 2 doubles every interval from it). Unvoiced time windows (0) stay unvoiced.

contour is an F0Track, which comes back as an F0Track (its candidates changed the same way), a (times, f0) pair, which comes back as a pair, or anything with .t and .f0, which comes back as a (times, f0) pair. A ratio in semitones st is 2 ** (st / 12). With ratio=1 and range=1 the contour itself is returned.

The envelope is not touched, so a voice resynthesized on the new contour keeps its formants (unlike pitch_shift(), which moves them with the pitch).

sonore.views.spectral_envelope

Spectral envelopes, and moving them along frequency.

A spectral envelope is the smooth curve over a time window’s spectrum with the source taken out: the harmonics, their phase and everything finer than the smoothing. (A temporal envelope, sonore.views.temporal_envelope, is the other “envelope”: smoothed along time, with the fine structure taken out.) Every estimator in sonore returns the one class SpectralEnvelope, power on a grid of times and frequencies with the estimator’s name in method and its parameters in settings: pitch_adaptive_envelope() here, Cepstrum.envelope_view, MFCC.envelope_view and LPC.envelope_view.

pitch_adaptive_envelope() is CheapTrick (Morise, 2015), written from the paper: a window three periods long, its power spectrum smoothed over 2 F0 / 3, and a cepstral lifter that removes the harmonic ripple and restores the level the smoothing took from the harmonic peaks. Where the paper leaves a choice open (the window’s gain, what happens below 0 Hz, unvoiced time windows, the FFT size), the choice is stated in the function’s docstring. It is not WORLD’s code: with the same q1 its envelopes are within a few hundredths of a dB of WORLD’s (median over voiced time windows: 0.00 to 0.01 dB on two recorded sentences, 0.03 dB on a breathy synthetic vowel), not equal.

An envelope is read as env(t, f), giving power at times t and frequencies f with shape (n_channels, len(f), len(t)): a SpectralEnvelope, anything else held on a grid (TimeFrequencyGrid), or a plain function. Aperiodicity is read the same way. warp_frequency() moves an envelope (or an aperiodicity) along frequency without looking at how it was made, so any envelope and any synthesizer combine: source_filter_synthesize() and harmonic_complex() both take any envelope.

class SpectralEnvelope(data: ArrayLike, t: ArrayLike, f: ArrayLike, *, fs: float | None = None, method: str | None = None, settings: Mapping[str, float] | None = None)[source]

Bases: _GridView

A spectral envelope: power on a grid of times t and frequencies f, data of shape (n_channels, len(f), len(t)). A view: it keeps the envelope and drops the harmonics and the phase.

Every estimator returns one, with its name in method ("CheapTrick", "cepstrum", "MFCC", "LPC") and its parameters in settings (for CheapTrick q1, f0_floor and unvoiced_f0); one built by hand has neither. fs is the sampling rate of the analyzed sound, or None for an envelope made by hand. Calling it, env(t, f), reads the power at any times and frequencies, linear in time and in dB over frequency, held beyond the ends of the grid, so it goes wherever an envelope is taken: warp_frequency(), source_filter_synthesize(), harmonic_complex().

discards = "SpectralEnvelope discards the harmonics, the phase, and everything finer than the envelope's smoothing."
back_to_sound = 'so.source_filter_synthesize rebuilds an approximation of the voice from it together with an F0 track and an aperiodicity.'
property n_fft: int | None[source]

The FFT size whose bins the frequencies are, 2 (len(f) - 1), when fs is known and f is that FFT’s grid from 0 to fs / 2; None for an envelope on any other grid.

property db: ndarray[source]

10 log10 of the power.

amplitude(t: ArrayLike, f: ArrayLike, *, channel: int = 0) → ndarray[source]

The amplitude (square root of the power) at the points (t[i], f[i]), t and f of the same shape: the form harmonic_complex() reads, one value per sample and harmonic. Linear in time and in dB over frequency, held beyond the first and last time windows.

plot(ax: Axes | None = None, *, channel: int = 0, db_range: float = 70.0, fmax: float | None = None) → Axes[source]

The envelope in dB as a time-frequency image.

pitch_adaptive_envelope(sound: Sound, f0: ContourLike, *, q1: float = -0.09, f0_floor: float = 71.0, unvoiced_f0: float = 500.0) → SpectralEnvelope[source]

The CheapTrick spectral envelope (Morise, 2015), written from the paper.

At each time window of the F0 track:

  1. The sound under a Hann window three periods long, centered on the sample nearest the window’s time and scaled to unit energy (so the level does not change with the window’s length); its power spectrum.

  2. That power smoothed by a moving average 2 F0 / 3 wide (the paper’s Eq. 4), which fills the dips between harmonics so the logarithm can be taken.

  3. The cepstrum of its logarithm, multiplied by sinc(F0 q), which removes the ripple at the harmonic spacing (Eq. 7), and by the recovery lifter (1 - 2 q1) + 2 q1 cos(2 pi F0 q), which gives back the level the smoothing took from the harmonic peaks (Eq. 8); then back to a spectrum.

The result follows the harmonic peaks and barely changes with the window’s position within a period. It is a SpectralEnvelope on the FFT grid (n_fft // 2 + 1 frequencies from 0 to fs / 2) at the F0 track’s times, with method="CheapTrick" and the three parameters in settings.

Choices the paper leaves open: where the smoothing reaches below 0 Hz or above Nyquist the spectrum is mirrored there; samples beyond the ends of the sound are zeros; 1e-12 is added to the power before the logarithm; unvoiced time windows are analyzed at unvoiced_f0 (a short window and wide smoothing, which suits noise); F0 below f0_floor is raised to it; the FFT size is the smallest power of two above 3 fs / f0_floor.

Parameters:
  • sound – The sound, at any sampling rate.

  • f0 – An F0Track (one row per channel) or a (times, f0) pair; 0 marks unvoiced time windows. The envelope is computed at these times.

  • q1 – The recovery lifter’s parameter. -0.09 is the paper’s value (WORLD’s code later used -0.15, which sharpens the peaks a little more); 0 is no recovery.

  • f0_floor – The lowest F0 analyzed; it sets the FFT size.

  • unvoiced_f0 – The F0 at which unvoiced time windows are analyzed.

warp_frequency(view: TimeFrequencyGrid | Callable[[ndarray, ndarray], ndarray], ratio: float | tuple[TypeAliasForwardRef('ArrayLike'), TypeAliasForwardRef('ArrayLike')] | Callable[[ndarray], TypeAliasForwardRef('ArrayLike')]) → TimeFrequencyGrid | Callable[[ndarray, ndarray], ndarray][source]

A spectral envelope (or aperiodicity) moved along frequency: new(t, f) = view(t, f / ratio). A ratio above 1 moves every formant up by that factor, as a shorter vocal tract would; below 1, down. The F0 is not touched, so the pitch stays.

view is anything read as view(t, f): a SpectralEnvelope, an Aperiodicity, any other TimeFrequencyGrid, or a function. A view held on a grid comes back as the same type on the same grid, with its method and settings (so source_filter_synthesize takes it as before); a function comes back as a function.

ratio is:

  • a number: one ratio for the whole sound;

  • a (times, ratios) pair: a ratio that changes over time, read at each time window (linearly between the given times, held beyond them); only for a view held on a grid;

  • a function f -> source frequency: any frequency map, giving for each new frequency the one it is read from (a piecewise or bilinear warp, for example).

Values above the view’s top frequency (when lowering) hold the top value. The level is not adjusted: a warp stretches or squeezes the envelope’s area, which changes the output level by a little (about 1.5 dB for a ratio of 0.8 on the speech example), which normalize removes. A ratio of exactly 1 returns the view itself, so a voice resynthesized with it is the same, sample for sample.

sonore.views.aperiodicity

Aperiodicity, the share of noise in a voice at each frequency: D4C (Morise, 2016), written from the paper, and a harmonic-residual aperiodicity that measures the share of noise directly.

band_aperiodicity() follows the D4C paper’s steps; where the paper leaves a choice open, the choice is stated in its docstring. It is not WORLD’s code, and it reads differently from WORLD’s: on harmonics plus white noise it follows the true noise share with a slope of 1 but about 8 dB low, close to the bias the paper reports for itself, while WORLD’s code moves about half as much as the true share does.

class Aperiodicity(data: ndarray, t: ndarray, fs: float, method: str)[source]

Bases: _GridView

An aperiodicity, from band_aperiodicity() or harmonic_aperiodicity(): per frequency and time window, how much of the power is noise rather than harmonics. Stored as WORLD stores it, an amplitude ratio between 0 and 1 (data, shape (n_channels, n_freqs, n_windows)) on the FFT grid of n_fft // 2 + 1 frequencies f from 0 to fs / 2: its square share is the share of the power that is noise, which is what source_filter_synthesize() uses. method names the measure that made it (“D4C” or “harmonic residual”). Calling it, ap(t, f), reads the ratio at any times and frequencies.

discards = 'Aperiodicity keeps only the share of noise in each frequency and time window: it discards the spectrum, the pitch and the phase.'
back_to_sound = 'so.source_filter_synthesize rebuilds an approximation of the voice from it together with an F0 track and a spectral envelope.'
property share: ndarray[source]

The noise share of the power, data ** 2.

property db: ndarray[source]

0 dB is all noise.

Type:

The noise share in dB, 10 log10 share

bands(edges: Sequence[float], *, envelope: TimeFrequencyGrid | None = None) → ndarray[source]

The noise share averaged over each band [edges[i], edges[i+1]), shape (n_channels, n_bands, n_windows). With an envelope (any spectral envelope, read on this aperiodicity’s grid), the average is weighted by its power, so the result is the band’s noise power over its total power.

plot(ax: Axes | None = None, *, channel: int = 0, db_range: float = 60.0, fmax: float | None = None) → Axes[source]

The noise share in dB as a time-frequency image (0 dB is all noise).

band_aperiodicity(sound: Sound, f0: ContourLike, *, f0_floor: float = 71.0, correction_db: float = 8.0) → Aperiodicity[source]

The D4C aperiodicity (Morise, 2016), written from the paper.

At each voiced time window:

  1. A group delay that does not move with the window. The group delay of the sound under a Blackman window four periods long, taken a quarter period before and a quarter period after the window’s time: their sum cancels the terms that change with the window’s position (the paper’s Eqs. 7, 8 and 19). It is divided by the power spectrum under a Hann window four periods long, smoothed over F0 (Eqs. 21 and 22).

  2. Shaped into a sinusoid. That group delay smoothed over F0 / 2, less its own trend smoothed over F0 (Eqs. 23 to 25). For a periodic sound what is left is close to a sinusoid along frequency with period F0; noise adds everything else.

  3. The share that is not the sinusoid. For each band, centered every 3 kHz from 3 to 15 kHz where its 6 kHz window fits below Nyquist, the shaped group delay under a Nuttall window is transformed back (Eq. 26), the power of the result sorted, and the share of the energy outside its strongest 2 w_bw (w_bw the width of the window’s main lobe) is the band’s noise share (Eqs. 27 and 28).

  4. Across frequency. Linear in dB from -60 dB at 0 Hz through the band values, held at the last band’s value up to Nyquist.

Unvoiced time windows (F0 of 0) are all noise; voicing is the F0 track’s decision.

As the paper’s own evaluation finds, the band values read too periodic by a steady amount: on harmonics plus white noise from 5 to 40 dB SNR they follow the true noise share with a slope of 1 but about 8 dB low (7 dB at an F0 of 125 Hz, 9 dB at 250 Hz; tools/check_paper_vocoder_claims.py). The paper reports about 6 dB and suggests subtracting it; correction_db adds the 8 dB measured here to every band value, capped at 0 dB (all noise). It is not WORLD’s code: before the correction, its band values are within about 0.6 dB of WORLD’s D4C (median over voiced time windows at 16 and 48 kHz).

Choices the paper leaves open: F0 below f0_floor is raised to it; the FFT size is the smallest power of two above 4 fs / f0_floor; samples beyond the ends of the sound are zeros; spectra are mirrored about 0 Hz and Nyquist where a smoothing reaches past them; 1e-12 guards the division; only the positive half of each band’s transform is kept (it holds the lobe at one period once); w_bw is the first zero of the Nuttall window’s transform.

Parameters:
  • sound – As pitch_adaptive_envelope(). The sampling rate must be at least 12 kHz, so that one band fits.

  • f0 – As pitch_adaptive_envelope(). The sampling rate must be at least 12 kHz, so that one band fits.

  • f0_floor – The lowest F0 analyzed. It also sets the output’s frequency grid, which must match the envelope’s for synthesis.

  • correction_db – Added to every band value [dB]; 0 gives the paper’s values as they are.

harmonic_aperiodicity(sound: Sound, f0: ContourLike, *, periods: float = 4.0, f0_floor: float = 71.0, cell_harmonics: float = 2.0) → Aperiodicity[source]

The share of noise, measured by fitting the harmonics and keeping what is left. Not part of D4C or WORLD; it is sonore’s own.

The F0 track is interpolated to every sample and integrated to a running phase Phi(t). At each voiced time window, under a Hann window periods periods long, a weighted least-squares fit of the harmonics cos(k Phi), sin(k Phi) below Nyquist, each with a linear change of amplitude across the window, is subtracted. The running phase already follows a vibrato; the changes of amplitude follow a tremolo or an onset (on a 30% tremolo at 6 Hz the share reads within 0.4 dB of the truth with them and about 1 dB too noisy without them). The residual’s power, over the windowed sound’s power, is the noise share. The fit also absorbs a little of the noise near every harmonic; how much is known exactly from the fit (the share of white noise the residual keeps at each frequency), and is divided out. Both are summed over cells cell_harmonics harmonics wide, and the cells’ shares are interpolated in dB onto the grid of pitch_adaptive_envelope(). Unvoiced time windows are all noise.

The measure is what the word means, so it reads a known share of noise within a few tenths of a dB on a steady vowel; but it needs F0 to about 0.1%, since a harmonic that drifts out of phase with the fit over the window reads as noise, and so do jitter and shimmer.

Parameters:
  • sound – As pitch_adaptive_envelope().

  • f0 – As pitch_adaptive_envelope().

  • periods – The window’s length in periods of the time window’s F0. The fit has four unknowns per harmonic, so the window needs at least 1.25 samples per unknown, about 2.5 periods; a shorter window fits the noise too and is refused.

  • f0_floor – Sets the output’s frequency grid, as pitch_adaptive_envelope().

  • cell_harmonics – The width of the cells, in harmonics.

sonore.views.envelope_peaks

Envelope peaks: how big a sound’s pops are, as the exponent of a power law.

Pops (fire crackling, a typewriter, tapping) make a few moments far louder than the typical ones. When the sizes of those moments follow a power law with a small exponent, the envelope’s variance and kurtosis have no stable value: measured on a recording, they keep growing with its length. The exponent itself does not. The design and its numbers are in docs/design/views/envelope-peaks.md.

class EnvelopePeaks(maxima: ndarray, exponent: ndarray, uncertainty: ndarray, threshold: ndarray, cutoffs_hz: tuple[float, ...], bin_seconds: float, fraction: float, n_fitted: int)[source]

Bases: View

The largest envelope value in each bin of a sound high-passed at each cutoff, and the power-law exponent of their upper tail. A view: it keeps only those maxima.

maxima has shape (n_bins, n_cutoffs). exponent and uncertainty have one value per cutoff: exponent is alpha in P(maximum > x) ~ x**-alpha, fitted by the Hill estimator on the largest fraction of the maxima, and uncertainty is its standard error, exponent / sqrt(n_fitted). threshold is, per cutoff, the largest maximum left out of the fit. Below about 2 the sound is made of pops, with no smooth background under them. Gaussian noise gives about 15 at 8 kHz, 20 to 30 at 16 kHz and 30 to 40 at 44.1 kHz: more at a higher sample rate, which puts more samples in each bin. Pops sparser than the fraction fitted read below 1 whatever their sizes (see envelope_peaks()).

discards = 'EnvelopePeaks keeps only the largest envelope value in each bin above each cutoff, and drops when the bins occurred, the spectrum and everything below each maximum.'
back_to_sound = 'There is no inverse; so.event_train with level_db drawn from an exponential distribution of scale 20 / (exponent * ln 10) makes pops with a given exponent, to hear what it means.'
maxima: ndarray
exponent: ndarray
uncertainty: ndarray
threshold: ndarray
cutoffs_hz: tuple[float, ...]
bin_seconds: float
fraction: float
n_fitted: int
plot(ax: Axes | None = None, **kwargs) → Axes[source]

The survival of the maxima on log-log axes, with the fitted line (see plot_envelope_peaks()).

envelope_peaks(sound: Sound, *, cutoffs_hz: Sequence[float] = (300.0, 2000.0), bin_seconds: float = 0.005, fraction: float = 0.05) → EnvelopePeaks[source]

Measure how heavy the tail of a sound’s envelope peaks is.

For each cutoff, separately:

  1. High-pass the sound at the cutoff (4th-order Butterworth, forward and backward). Pops are broadband, and a high cutoff keeps low rumble out.

  2. Take the Hilbert envelope and smooth it with a 500 Hz low-pass.

  3. Take the envelope’s maximum in each bin bin_seconds long. The maximum, not the mean, because the mean smooths short pops away.

  4. Fit the exponent of the upper tail of the maxima by the Hill estimator (Hill, 1975) on the largest fraction of them, at least 10: with x_1 >= x_2 >= ... the sorted maxima and k the number fitted, exponent = k / sum(log(x_i / x_(k+1))) over i <= k.

The uncertainty is exponent / sqrt(k). With the defaults, 2 s of sound fits 20 values (about 25%) and 7 s fits 70 (about 12%), and a short excerpt can miss the big events altogether; fewer than 50 fitted values raise a warning. Mono only.

The exponent describes the pops only when they fill more bins than the fraction fitted: with the defaults, more than about 10 pops per second (5% of 200 bins a second). Sparser pops leave the fit straddling them and the floor beneath, so it measures how far they stand above the floor, not how their sizes spread: such trains read below 1 whatever their sizes, and equal clicks twice a second read 0.47. A smaller fraction fits sparse pops.

sonore.views.phasevocoder

Phase vocoder (Gordon & Strawn, 1985; Dolson, 1986).

The phase vocoder treats each STFT channel as a slowly varying sinusoid with an amplitude and an instantaneous frequency, estimated from how much the channel’s phase advances between time windows beyond what its center frequency predicts. With amplitudes and frequencies in hand you can:

  • change duration without changing pitch (time_stretch()), by re-accumulating phase at a different hop and overlap-adding;

  • change pitch without changing duration (pitch_shift()), by stretching and then resampling;

  • go back to a sound through an oscillator bank with any frequency remapping (PVAnalysis.to_sound()), e.g. to shift or stretch partials.

Time stretching uses identity phase locking (Laroche & Dolson, 1999) by default: bins around each spectral peak keep their original phase relationship to the peak, which removes most of the classic “phasiness”.

class PVAnalysis(magnitude: ndarray, phase: ndarray, freq: ndarray, t: ndarray, fs: float, n_win: int, hop: int, n_samples: int)[source]

Bases: View

Phase-vocoder analysis: per-channel magnitude, phase and instantaneous frequency, all shaped (n_channels, n_bins, n_windows). A view: it reads each bin as one sinusoid, and to_sound() rebuilds a sound from those sinusoids, closely for tonal sounds but not exactly.

discards = 'PVAnalysis reads each STFT bin as a single sinusoid, which a sound with more than one component per bin (noise, close partials) is not, so its oscillator resynthesis is not an inverse.'
back_to_sound = 'PVAnalysis.to_sound rebuilds an approximation through an oscillator bank; so.GaborFrame gives an exact STFT.'
no_plot = 'PVAnalysis has no plot: its magnitudes are those of an STFT, so plot so.GaborFrame(...).analyze(sound).'
magnitude: ndarray
phase: ndarray
freq: ndarray
t: ndarray
fs: float
n_win: int
hop: int
n_samples: int
to_sound(*, time_scale: float = 1.0, freq_map: float | Callable[[ndarray], ndarray] | None = None, floor_db: float = -80.0, chunk: int = 64) → Sound[source]

Oscillator-bank resynthesis.

Each bin drives a sinusoid whose amplitude and frequency are interpolated between time windows and whose phase is the running integral of frequency. time_scale stretches the time axis; freq_map is a ratio (e.g. 1.5) or a function mapping frequencies in Hz to new frequencies. For example lambda f: f + 70 makes a 220 Hz harmonic complex inharmonic; note that shifting by a multiple of half the f0 keeps it harmonic (f + 110 gives odd harmonics of 110 Hz). Bins that never come within floor_db of the loudest bin are skipped, and partials mapped above Nyquist are dropped.

This is designed for tonal sounds, which it reconstructs closely (r > 0.999 for harmonic complexes). For noise, neighboring channels drift out of phase and partially cancel (about 2 dB low, r about 0.93); use time_stretch() for noisy material. Both figures are measured by tools/measure_docstring_numbers.py.

pv_analyze(sound: Sound, *, win_dur: float = 0.046, hop_dur: float | None = None) → PVAnalysis[source]

Phase-vocoder analysis with a Hann window of win_dur seconds and a hop of hop_dur (default: a quarter window, the largest hop at which instantaneous frequency is unambiguous across a Hann main lobe).

time_stretch(sound: Sound, factor: float, *, win_dur: float = 0.046, phase_lock: bool = True) → Sound[source]

Change duration by factor (2 = twice as long) without changing pitch.

The standard phase vocoder: the synthesis hop is fixed at a quarter window and the analysis hop is synthesis_hop / factor rounded to whole samples, so the content is stretched by synthesis_hop / analysis_hop. The output length is round(len(sound) * factor) whatever that ratio, so where the two differ the end is cut off or followed by silence. With the default 46 ms window the gap is at most 1.1% for factors 1 to 4 and 2.8% for 4 to 10 at 16 kHz (0.4% and 1.0% at 44.1 kHz), and grows beyond. A longer window means longer hops and a smaller gap: twice the win_dur halves it, at the cost of time resolution (transients smear over a longer window). Measured by tools/measure_docstring_numbers.py.

pitch_shift(sound: Sound, semitones: float, *, win_dur: float = 0.046, phase_lock: bool = True) → Sound[source]

Shift pitch by semitones without changing duration (time-stretch, then resample). Formants shift along with the pitch.

sonore.views.timbre

Timbre descriptors after Peeters et al. (2011), “The Timbre Toolbox”: the log attack time, the spectral centroid and the spectral flux.

Written from the paper’s equations, not from the Timbre Toolbox’s code, whose license forbids redistribution. Where the defaults differ from the paper’s, the reason is measured in tools/check_timbre_claims.py and set out in docs/design/music/timbre-page.md.

class DescriptorTrack(t: ndarray, values: ndarray, name: str, unit: str)[source]

Bases: View

One descriptor’s value in every time window, for each channel. A view: it keeps one number per time window.

values has shape (n_channels, n_windows) and is NaN where a time window is silent. median and iqr are the summaries Peeters et al. (2011) use, since silent and near-silent time windows make a mean or a standard deviation meaningless; both skip NaN.

discards = 'DescriptorTrack keeps one number per time window: it discards the rest of the spectrum or envelope, so many sounds share one track.'
t: ndarray
values: ndarray
name: str
unit: str
property median: ndarray[source]

Median over time, one per channel.

property iqr: ndarray[source]

Interquartile range over time, one per channel.

plot(ax: Axes | None = None, *, channel: int = 0, **kwargs) → Axes[source]

The descriptor against time (see plot_descriptor_track()).

attack_segment(sound: Sound, *, channel: int = 0, cutoff: float = 20.0, zero_phase: bool = True) → tuple[float, float][source]

Start and end of the attack [s], by the weakest-effort method of Peeters et al. (2011), III A 2 a.

The energy envelope (the amplitude of the analytic signal, low-passed by a third-order Butterworth filter at cutoff Hz) is cut at 0.1, 0.2, …, 1 times its maximum, and the “efforts” are the times it takes to climb from one level to the next. The attack starts within the first effort at most three times the mean effort and ends within the last one, at the envelope’s minimum and maximum inside those two efforts. It measures one channel, channel, where the spectral descriptors measure every channel. The envelope filter sets how short an attack it can resolve, as the next paragraph measures.

The paper computes its descriptors with a 5 Hz filter applied once (cutoff=5, zero_phase=False), which measures a 5 ms attack as about 80 ms. The default here is the paper’s onset setting (20 Hz, forward and backward), which measures it as about 16 ms; see tools/check_timbre_claims.py.

log_attack_time(sound: Sound, *, channel: int = 0, cutoff: float = 20.0, zero_phase: bool = True) → float[source]

The base-10 logarithm of the attack’s duration in seconds, log10(end - start) with the start and end of attack_segment() (Peeters et al., 2011, eq. 4). One sample is the shortest duration.

spectral_centroid(sound: Sound, *, scale: Literal['power', 'magnitude'] = 'power', win_dur: float = 0.0232, hop_dur: float = 0.0058) → DescriptorTrack[source]

The center of gravity of the spectrum in each time window, sum(f_k a_k) / sum(a_k) (Peeters et al., 2011, eq. 7), on a Hamming STFT of 23.2 ms windows every 5.8 ms by default.

scale is "power" (the default) or "magnitude", the two spectra the paper offers; they differ a lot (2.5 times for a tone with harmonics falling as 1/n), so say which one you report. The power centroid of a steady harmonic tone matches the one computed from its partials. The magnitude centroid also counts the window’s sidelobes in every bin up to Nyquist, which for a dull tone can outweigh the weak high partials: for harmonics falling as n^-3 at E-flat 4 it measures 810 Hz at 44.1 kHz and 592 Hz at 22.05 kHz, against 414 Hz from the partials (tools/check_timbre_claims.py).

spectral_flux(sound: Sound, *, spacing: float | None = 0.1, scale: Literal['power', 'magnitude'] = 'magnitude', win_dur: float = 0.0232, hop_dur: float = 0.0058) → DescriptorTrack[source]

How much the spectrum changes: 1 minus the normalized correlation of two spectra (Peeters et al., 2011, eq. 24, “spectral variation”), 0 for spectra of the same shape and up to 1.

The paper correlates successive time windows, one hop (5.8 ms) apart: spacing=None. At that spacing a steady tone and a tone whose spectral slope glides over a second measure almost alike; spacing correlates spectra that far apart instead (100 ms by default), at which the two differ 25 times (tools/check_timbre_claims.py). Each value is placed at the later of its two time windows.

sonore.views.chroma

Chroma: the power in each of the 12 pitch classes, the octaves folded together.

The sound is split into semitone bands by the cosine filterbank on the cents scale (an exact constant-Q filter bank), each band’s power is averaged over time windows, and every band of the same pitch class is added together: C2, C3, C4 and so on become one row for C. The way back plays each pitch class as a Shepard tone, whose partials are all octaves of that one class, so its chroma comes back unchanged. The design and its numbers are in docs/design/views/chroma.md.

class Chroma(t: ndarray, power: ndarray, window: float, reference: float, f_lo: float, f_hi: float)[source]

Bases: View

The power in each pitch class, C to B, in each time window, for each channel. A view: it adds the octaves of each pitch class together.

power has shape (n_windows, 12, n_channels): the mean power of the semitone bands of each pitch class over each time window, which start at t - window / 2. reference is the frequency of A4 that placed the bands; f_lo and f_hi are the centers of the lowest and highest band [Hz].

discards = "Chroma adds the semitone bands of each pitch class together, so it discards octave height (how each pitch class's power spreads over octaves) and everything within a band: many sounds share one chroma."
back_to_sound = 'Chroma.to_sound plays each pitch class as a Shepard tone, with octaves= saying how its power spreads over octaves.'
t: ndarray
power: ndarray
window: float
reference: float
f_lo: float
f_hi: float
property n_channels: int[source]

Number of channels.

property duration: float[source]

Length [s] the time windows cover.

to_sound(fs: float, *, octaves: str | float | Callable[[ndarray], ndarray] | None = None) → Sound[source]

A sound with this chroma: each pitch class a Shepard tone (Shepard, 1964), its level following that pitch class’s row.

octaves is what the view dropped, how each pitch class’s power spreads over octaves, as the level of each partial at its frequency:

  • None: a bell over log frequency centered between f_lo and f_hi, one octave wide (standard deviation), so no octave stands out;

  • a note such as "C4", or a frequency [Hz]: a narrow bell there, so each pitch class sounds in the octave nearest it;

  • a function of frequency [Hz], for any other spread.

The partials are the octaves of each pitch class from f_lo to f_hi, the range the chroma was measured on, so the chroma of the result is this chroma, up to the smoothing of the time windows. The sound is duration long, at the level the chroma measured.

plot(ax: Axes | None = None, *, channel: int = 0, db_range: float = 40.0, **kwargs) → Axes[source]

The 12 rows against time, in dB (see plot_chroma()).

chroma(sound: Sound, *, window: float = 0.05, reference: float = 440.0, f_lo: float = 55.0, f_hi: float = 7040.0) → Chroma[source]

The power in each pitch class in each time window (Fujishima, 1999, who called it a pitch class profile).

The sound goes through a cosine filterbank on the cents scale, one band per equal-tempered semitone with A4 at reference Hz (by default 440 Hz, the standard pitch of ISO 16), centered from f_lo to f_hi (A1 to A8 by default; both are moved to the nearest semitone). Each band’s power is averaged over time windows window seconds long, rounded to a whole number of samples (Chroma.window is the length used; a last, shorter stretch is dropped), and the bands of each pitch class are added together. Power is kept as measured: a window is not scaled to its own maximum. Overtones land on other pitch classes (the third harmonic of C is a G), so chroma summarizes partials, not notes.

sonore.views.quilting

Sound quilts (Overath, McDermott, Zarate & Poeppel, 2015): a sound cut into segments of one length and strung together in a new order, so that it keeps its structure within a segment and across each join, and loses it beyond the segment length.

Written from the paper’s Online Methods; McDermott’s Sound Quilting Toolbox (MATLAB) was consulted for behavior only. Where the two differ, this follows the paper (docs/design/views/quilting.md lists the differences).

quilt(sound: Sound, segment_dur: float, duration: float, *, rng: int | Generator | None = None, filterbank: Filterbank | None = None, border_dur: float = 0.03, crossfade: float = 0.03, max_shift: float = 0.015, fade: Literal['adaptive', 'equal_gain'] = 'adaptive') → Sound[source]

A sound quilt of sound, duration [s] long, made of segments segment_dur [s] long (Overath et al., 2015).

The sound is cut into whole segments, and the quilt uses each one at most once. The first segment is drawn at random from rng, from all but the sound’s last segment unless the quilt is that one segment long. After segment k, the next is the one whose join with k changes the cochleagram by as much as the sound itself changed after k: the n that minimizes |d(k, n) - d(k, k + 1)|, where d is the mean squared difference between the last border_dur of one segment and the first border_dur of another. The sound’s own next segment k + 1 is never chosen, so every join is a new one, and its last segment, which has no change of its own to match, may only end the quilt.

The cochleagram is the Hilbert envelope of each band of filterbank, raised to the power 0.3 (default: the paper’s 30 ERB-spaced cosine filters from 20 Hz to 10 kHz, capped at Nyquist, with their edge filters). The segments are joined by splice(), with raised-cosine cross-fades crossfade long, each new segment moved by up to max_shift to align its waveform with what precedes it. The paper’s raised-cosine ramps (fade="equal_gain") lose about 1 dB of a noise-like sound when the cross-fade is as long as the segment; the default "adaptive" fade keeps the level (see splice()).

The quilt keeps the sound’s level and is trimmed to duration; the paper’s band-limiting, pause removal and final fade are left to the caller. The same rng seed and sound give the same quilt. The sound must have at least one segment more than the quilt needs: with none to spare, the rule can be left with only the sound’s own next segment for the last place, on some seeds and not others. Mono only.