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:
NotImplementedErrorRaised by
View.synthesize(), and byView.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:
ProtocolAnything held as values on a grid of times and frequencies and read at any point:
t[s] andf[Hz] are the grid,datahas shape(n_channels, len(f), len(t)), andview(t, f)gives the values at timestand frequenciesfwith shape(n_channels, len(f), len(t)).SpectralEnvelopeandAperiodicityare 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:
objectBase 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, andback_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 overrideplot()setsno_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
NotInvertibleErrorwithdiscardsandback_to_soundas 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.
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:
ViewA 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; seelong_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_atinside 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.
- smooth(fraction: float = 0.3333333333333333) Spectrum[source]¶
Fractional-octave smoothing (power average over
fractionoctave).
- 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 togaussian_noise()). ASoundlends its phase: its firstdurationseconds, each channel’s spectrum given this magnitude, soSpectrum.from_sound(x).to_sound(x.duration, x.fs, carrier=x)gives backxat RMS 1."minimum"gives the minimum-phase impulse response with this magnitude, from the folded cepstrum as inCepstrum.to_stft. The level is read at the FFT bins ofdurationby linear interpolation, and is silent outside the spectrum’s frequencies (a spectrum measured at 16 kHz gives nothing above 8 kHz at anyfs). 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 is1 / win_dur, 10 Hz by default. A sound shorter thanwin_duris one segment, its own length, zero-padded towin_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:
ViewA 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.powerhas shape(n_channels, n_freqs, n_windows), on frequenciesf[Hz] and window timest[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¶
- 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
tfluctuates with period T0 as the window slides across the glottal pulses. Averaging the powers att - T0/4andt + 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:
ViewSpectrogram cells moved to their reassigned times and frequencies.
t_hat,f_hatandpowerhave shape(n_channels, n_freqs, n_windows), one entry per STFT cell;keepmarks 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¶
- 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 timetand bin frequencyftot_hat = t + Re(X_tw conj X) / |X|**2,f_hat = f - Im(X_dw conj X) / (2 pi |X|**2),
where
Xuses the windoww,X_twthe time-weighted windowtau w(tau)andX_dwits derivativew'(tau), withtauin seconds from the window’s middle sample, which is where SciPy (and soGaborFrame) 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,stdin samples as in SciPy. Cells more thanthreshold_dbbelow 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 aTemporalEnvelopewith no filterbank;env * sndmodulates the sound.fb.analyze(snd).envelopes()is aTemporalEnvelopethat keeps the filterbank: one envelope per band, which is a cochleagram when the filterbank is cochlea-like (an ERBcosine_filterbank()or a gammatone bank), and the band envelopes of any other bank otherwise.env * sndthen splits the sound with that filterbank, multiplies each band by its envelope and sums the bands back;env * subbandsmodulates 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,ViewA 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,
datahas shape(n_samples, n_channels)andenv * sndmodulates aSoundsample by sample (snd / envdivides the envelope out). With a filterbank,datahas shape(n_samples, n_bands, n_channels), the bands including the filterbank’s lowpass and highpass edge filters as inSubbands;env * sndsplits the sound with the filterbank, multiplies each band by its envelope and sums the bands back,env * subbandsmodulates bands already split (imposing the envelopes on a carrier, not an inverse),env[i]is one band’s envelope, andenv.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 (so1 + 0.5 * envworks).len(env)counts samples, as for a Sound;n_bandscounts 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 (
padsamples at each end, hidden fromdata), so that modulating and re-synthesizing bands can’t wrap around. Envelopes made from scratch (e.g. a rendered ripple pattern) havepad=0and 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
- 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_durseconds everyhop_dur, as an amplitude, at rate1 / hop_dur(seeEnvelopePooling, which streams it).
- lowpass(cutoff: float, *, order: int = 4) TemporalEnvelope[source]¶
Zero-phase Butterworth lowpass at
cutoffHz, 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 withedges=Falsehas 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 withedges=Falsehas 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. Plainenvelope * soundkeeps the sound’s own envelope as well (amplitude modulation)."noise": a Gaussian noise fromrng. 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).
fsis the output rate for"noise"and"tone"(by default the envelope’s own); a Sound carrier sets its own. The edge bands are kept (seewithout_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 (seeplot_envelopes()).
- class EnvelopePooling(win_dur: float = 0.025, hop_dur: float = 0.01, filterbank: Filterbank | None = None)[source]¶
Bases:
SlidingWindowStreamEnvelopes pooled in time windows, a block at a time: the power of the envelope weighted by a periodic Hann window of
win_durseconds, one time window everyhop_durseconds, centered on the samples0, 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
TemporalEnvelopeatfs / 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 (filterbanksays whose bands they are,Nonefor 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 atfs;first_startis 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_samplessamples has.
- time_windows(samples: ndarray, fs: float, first: int, count: int, n_samples: int) TemporalEnvelope[source]¶
The part holding time windows
firsttofirst + count - 1, fromsamples((n, n_channels), starting at time windowfirst’s first sample), aftern_samplessamples 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_filterbankofn_bandsbands fromf_lotof_hi(capped at Nyquist), each band’s Hilbert envelope is lowpassed atenv_lowpassHz, and the envelopes are imposed on thecarrierwithTemporalEnvelope.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 (outsidef_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:
ViewGains, usually between 0 and 1, one per coefficient of the coefficients
likeit was made for (same frame, same grid).mask * coefsandcoefs * maskgive the masked coefficients;.to_sound()on those is the way back to a sound.valueshas 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
valuesincludes, sotis shorter than the first axis ofvaluesby 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 * maskdoes).
- 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))**betawithT**2andM**2the powers of each coefficient (Wang, Narayanan & Wang, 2014; 0 where both are silent).betamust 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 spanningcf +/- 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:
View2-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, anyTemporalEnvelopehas.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(byoctave()orenv.modulation_spectrum()) also keeps, forto_sound(), the magnitude of the untapered transform on the whole plane, the envelope’s mean, and how the envelopes were made. Edit it withwith_gain(), and hear it withto_sound(), whose carrier supplies the phases it lacks (seedocs/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
dtseconds anddxscale 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
ModulationBlobpowers, on the gridoctave()would measure for a sound ofdurationseconds, ready forto_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 andrms_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 indocs/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 ofoctave(..., scale="db")does, andsd_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, asgaussian_spectrogram()is for exponential correlations. Deep dB draws spread some of the modulation power of the linear envelopes away from the blobs.levelshows 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.gainis a functiong(rate, density)of rate [Hz] and spectral modulation, evaluated withrateas a row anddensityas 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) <= 4removes every modulation faster than 4 Hz,lambda r, d: r * d <= 0every downward sweep. The displayedlevel(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
Soundcarrierlends the phase of its own envelopes (analyzed as this spectrum’s were), so the spectrum ofxwithcarrier=xgives backx’s envelopes; with no carrier the phase is drawn at random fromrngat 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.phasegives the modulation phase directly, in the shapemodulation_phase()returns, in place of a carrier or a draw.quietclips negative values without a warning, and without the refusal of afrom_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
Soundis analyzed byfilterbank(in mono, cut to the analyzed duration);Subbandsmust come from that filterbank and span the analyzed duration.
- iterate(sound: Sound) Sound[source]¶
One step of the search
to_sound(iterations=n)takes: analyzesound, 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 byTemporalEnvelope.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()): aSoundlends its own, unlessrngis given; with"tone", or a Sound andrng, it is drawn at random fromrngand 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 ofxitself rebuildsx’s envelopes, so an edit made withwith_gain()keeps the sound’s timing wherever the gain is 1.fsis 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).iterationsthen 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 indocs/design/views/modulation-targets.md); each iteration costs one analysis and one synthesis. One iteration is public asiterate().A drawn target (
from_blobs()) has no timing of its own, so a Sound carrier withrngpairs 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,
+rateand-rateare 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:
objectA patch of modulation power, for drawing a target spectrum in code (
ModulationSpectrum.from_blobs()).A Gaussian bump centered on
rate[Hz] anddensity[cycles/octave]:rate_widthis its standard deviation in octaves of rate,density_widthin cycles/octave, andlevelits peak power [dB] relative to the other blobs. The signs followRipple: 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¶
- class ModulationFilterbank[source]¶
Bases:
objectBase class. Subclasses define
n_bands,cfsandresponse().Despite the name, a modulation filterbank is not a
Filterbank: it filters envelopes to make views such asModulationSpectrogram, and has no synthesis.- 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
rfftgrid ofn_samples, shape(n_samples // 2 + 1, n_bands); withanalytic=True, on thefftgrid, 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) alongaxiswith every band.The band index is appended as a new last axis. With
analytic=Truethe 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:
ModulationFilterbankn_bandsconstant-Q filters with centers log-spaced fromf_lotof_hi[Hz]. Filterkis a half-cycle cosine on a linear frequency axis, nonzero oncf_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¶
- class OctaveModulationFilterbank(n_bands: int = 7, f_hi: float = 100.0)[source]¶
Bases:
ModulationFilterbankn_bandsfilters with centers one octave apart, the highest atf_hi[Hz] (default: 1.5625, 3.125, …, 100 Hz). Filterkis a half-cycle cosine on log2 frequency spanningcf_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¶
- 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:
ModulationFilterbankHann-windowed complex exponentials, defined in time.
Band
kcorrelates the envelope withh_k[j] = w_k[j] exp(i 2 pi f_k (j - (L_k - 1)/2) / fs), wherew_kis a Hann window ofL_ksamples 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 centersper_octaveto the octave fromf_lotof_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 gridk / Tfrom the first one at or abovemax(f_lo, 2/T)tof_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 output2 yhas magnitudeA * mfor an envelope componentA * m * cos(2 pi f_k t), and its real part is the real filtered output, whose frequency response isresponse().- f_lo: float = 0.5¶
- f_hi: float = 64.0¶
- per_octave: float = 2¶
- cycles: int = 3¶
- window: float | None = None¶
- 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 atfs: 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
xalongaxiswith every band (zero outsidex).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) // 2samples 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:
ViewModulation power, local mean and depth for every time window, acoustic band and modulation band.
For band envelope
e_band modulation bandkwith complex kernelh_kand windoww_k(seeHannModulationFilterbank), 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|**2andmean, both of shape(n_channels, n_bands, n_mod, n_windows).depthis2 |y| / mean: a sinusoidal AM of depthmat the band’s rate readsm, 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
fis the envelopes’ filterbank without its edge bands,fmholds the modulation rates andtthe 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
yis dropped, as a magnitude spectrogram drops an STFT’s phase (the local mean is kept, anddepthdivides 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):cyclessets 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):cyclessets 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):cyclessets 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):cyclessets 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):cyclessets 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 equalsModulationSpectrogram(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 aspower; 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.kindis"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 isvalid, 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 atrate, and band against rate att. 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 withsoundas 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:
objectThe causal
ModulationSpectrogram(align="causal"), a block of envelopes at a time. The parameters are the spectrogram’s, andfilterbankis the one whose envelopes the blocks are. Each step returns a ModulationSpectrogram of the time windows that block completed, andModulationSpectrogram.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
tholds the envelope up tot, 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))) / 4withtheta = 2 pi / L, soyand the mean are each a few sliding sumsS_n(a) = sum_j e[n - L + 1 + j] a**jwith|a| = 1. A sliding sum moves on by one sample withS_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:
objectThe state of a
ModulationSpectrogramStream: the last samples (as many as the longest kernel,(L, n_bands, n_channels);Nonebefore 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:
ViewThe real cepstrum of each time window of an
STFTorTVSTFT.For a time window with spectrum
X[k]onn_fftbins, the cepstrum isc[n] = IDFT(ln |X[k]|)at quefrencyn / fsseconds. It is real and even innbecause the sound is real, so onlyn = 0 .. n_fft // 2is stored:datahas shape(n_channels, n_fft // 2 + 1, n_windows)on quefrenciesq[s] and window timest[s].The natural log is used, so
expundoes it exactly: without liftering,to_sound()gives back the analyzed sound. Scaling the sound changes onlyc[0]. Before the log, magnitudes are floored atfloor_dbbelow 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. Withreferencethe floor is fixed instead,floor_dbbelow 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 samereference. 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.
- lifter(cutoff: float | Sequence[float], *, keep: Literal['low', 'high'] = 'low') Cepstrum[source]¶
A rectangular lifter.
keep="low"keeps the quefrencies belowcutoff[s], the smooth spectral envelope;"high"keeps the rest, the fine structure such as the harmonics.cutoffis 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 aSpectralEnvelope(method="cepstrum"): power on this cepstrum’s time windows and frequencies, read asenv(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 fromsource, 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 ton_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 onn_fftbins, which is negligible oncen_fftis 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 belowfloor_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_hiand1/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 belowthreshold, 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_lolong, or this raises. On a male spoken sentence (CMU ARCTICbdl, 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 + 2band edges are equally spaced in mel fromf_lotof_hi; bandmrises linearly from edgemto edgem + 1and falls to edgem + 2. “Linearly” is in mel withtriangle_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. Withtriangles="height"each peak is 1, and between the first and last centers the weights sum to 1. With"area"bandmis scaled by2 / (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 aGaborFramesamples 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.deltadoes.Along
axis, a polynomial of degreeorderis fitted by least squares to each run ofwidth(odd) values and itsorder-th derivative taken: SciPy’ssavgol_filterwithmode="interp", so the first and lastwidth // 2values use the fit to the first or lastwidth. Fororder=1andwidth=5this is HTK’s regressionsum(n * c[t+n]) / sum(n**2)overn = -2..2away from the ends.order=2is 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:
ViewMel-frequency cepstral coefficients of each time window (Davis & Mermelstein, 1980).
For each time window with power spectrum
P[k]: band powersE[m] = sum_k W[m, k] P[k]throughn_melstriangular mel bands (mel_filterbank()), their natural log, and the orthonormal DCT-II of that, of which the firstn_mfcccoefficients 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.sourceis aSoundor the coefficients of an analysis:a
Soundis analyzed with the usual speech settings: a symmetric Hamming windowwin_durlong (25 ms), as HTK and Kaldi use, a hop ofhop_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
STFTorTVSTFTis 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 fromc0. 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_dbbelow each channel’s largest band power over all time windows before the log, so scaling a sound changes onlyc0and 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). Withreferencethe floor is fixed instead, atfloor_dbbelowreference**2in 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 samereference.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-freqof 20 Hz, 23 bins and “povey” window (a Hann window to the power 0.85, as a callablewindowof theGaborFrame) 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 withso.GaborFrame(n_fft / fs, hop / fs, window="hann", n_fft=n_fft)and usemel_scale="slaney",triangles="area",triangle_axis="hz",n_mels=128,n_mfcc=20,floor_db=-80anddb. 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 exampleso.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 replacesc0with 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,
c0included.n_mels – Mel bands.
f_lo – The outer feet of the first and last bands [Hz];
f_hidefaults to half the sampling rate.f_hi – The outer feet of the first and last bands [Hz];
f_hidefaults to half the sampling rate.mel_scale –
"htk"or"slaney"(seefreq_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 –
Lof HTK’s sinusoidal lifter, which multipliesc[n]by1 + (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
sourceis a sound.hop_dur – Window length and hop [s] used when
sourceis a sound.
- Variables:
data – The coefficients, shape
(n_channels, n_mfcc, n_windows), in natural log units (dbfor dB).mel_power – Band powers before the floor, shape
(n_channels, n_mels, n_windows): the mel spectrogram.edges – Band edges [Hz],
n_mels + 2of them;cfsare 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 db: ndarray[source]¶
datatimes10 / 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(seedelta_features());width=9is librosa’s default. Same shape asdata.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 aSpectralEnvelope(method="MFCC", with the coefficient count in its settings) on this analysis’s time windows, at frequenciesf(by default its FFT bins), read asenv(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 withtriangles="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"); seeplot_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).
autocorrelationholdsr[0] .. r[order]along its last axis; any leading axes are solved at once. Returns the predictora(shape(..., order + 1),a[..., 0] = 1) minimizing the error ofx[n] + a[1] x[n-1] + ... + a[p] x[n-p], the reflection coefficientsk[1] .. k[p](shape(..., order)), and the error power left,E = r[0] prod(1 - k[i]**2)(shape(...)). Eachk[i]is the last coefficient of the order-ipredictor,a[i]at that order (the sign Makhoul, 1975, uses). Wherer[0]is 0 (a silent time window) the predictor isa = [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:
ViewLinear prediction of each time window, by the autocorrelation method.
For a windowed segment with autocorrelation
r[k], the predictorA(z) = 1 + a[1] z^-1 + ... + a[p] z^-pminimizes the power of the prediction error, and solvessum_j a[j] r[|i - j|] = -r[i]fori = 1 .. p(levinson()). The model of the segment is the all-pole filter1 / A(z)driven by white noise of the error powerE, with power spectrumE / |A|^2(envelope()). Because the segment is zero outside its window, the autocorrelation is positive definite and every root ofA(z)lies inside the unit circle: the model is always stable. A pair of roots|z| e^(+-j theta)is a resonance attheta fs / 2 piHz,-ln|z| fs / piHz wide (candidates()).sourceis aSoundor the coefficients of an analysis:a
Soundis analyzed with the speech recipe: a symmetric Hamming windowwin_durlong (25 ms), a hop ofhop_dur(10 ms), and an FFT length rounded up to a power of two at leastordersamples longer than the window;an
STFTorTVSTFTis 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 lags0 .. orderonly when the FFT is at leastordersamples 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 exampleso.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 toround(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
sourceis a sound.hop_dur – Window length and hop [s] used when
sourceis a sound.
- Variables:
data – The predictors
a[0] .. a[p], shape(n_channels, order + 1, n_windows), witha[0] = 1.error_power – The prediction error power
Eof 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.'¶
- envelope(f: ArrayLike) ndarray[source]¶
The model’s power spectrum
E / |A|^2at frequenciesf[Hz], shape(n_channels, len(f), n_windows), on the scale of the time window’s power spectrum|X|^2: averaged over alln_fftbins,|X|^2divided 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 aSpectralEnvelope(method="LPC", with the order in its settings) on this analysis’s time windows, at frequenciesf(by default its FFT bins), read asenv(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:
ViewFormant tracks: F1, F2 and F3 of each channel every
hopseconds, fromformant_track(). A view: it keeps only the formants.frequenciesandbandwidthshave shape(n_channels, 3, n_windows), NaN where a time window had fewer resonances than formants.candidatesandcandidate_bandwidthshave 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 formklatt_synthesize()takes forF1,F2andF3; 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
hopseconds from time 0: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 byLPCwith2 n_formantscoefficients on awin_dursymmetric Hamming window; every resonance between 50 Hz andceiling - 50Hz 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’sTo Formant (burg)to within a median of 1 to 7 Hz, though Praat uses Burg’s method on a Gaussian window.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)|plusbandwidth_weight * bandwidth / f, plusskip_costfor every candidate skipped below the highest one chosen; moving from one window to the next coststransition_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;
tholds 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:
ViewAn F0 track: one estimate per channel every
hopseconds. A view: it keeps only the pitch and the voicing.f0andscorehave shape(n_channels, n_windows);f0is 0 where the time window is unvoiced, andscoreis the periodicity score of the chosen candidate (0 where unvoiced).candidatesandcandidate_scoreshave shape(n_channels, n_windows, 8)and hold every refined candidate the tracker weighed, NaN where a time window had fewer.tand a row off0go straight intopitch_adaptive()andlifter().- 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: exactlyf0_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:
objectf0_track()a block of sound at a time, deciding each time windowdelayseconds after it (default 50 ms). The parameters aref0_track’s; each step returns anF0Trackof the time windows it decided, andF0Track.concatenate()joins them into exactlyf0_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
delaymore 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¶
- 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:
objectThe state of an
F0TrackStream: the samples the next time windows need (history[0]is sampleorigin), 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
hopseconds from time 0: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_hiand1/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 (withf_hiraised, a sung 800 Hz vowel has more multiples in range than there are candidates).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.
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),sthe 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.Tracking. A Viterbi pass over (unvoiced, candidates) per time window. A candidate costs
1 - scoreand the unvoiced state1 - threshold, so a time window leans voiced when its best score exceedsthreshold; moving between candidates costsoctave_costper octave, and a voicing change costsswitch_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, lesssubharmonic_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
thresholdto 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_hifor singing (on speech that costs about 0.3 points of voicing error, mostly false voicings). Refined candidates are kept from 0.9f_loto 1.1f_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 loweringf_lobelow 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_hifor singing (on speech that costs about 0.3 points of voicing error, mostly false voicings). Refined candidates are kept from 0.9f_loto 1.1f_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 loweringf_lobelow 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.
Noneturns 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 windowdelaylater passes through (the lastdelayof the track take the whole path).F0TrackStreamgives 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
ratioand, ifrangeis not 1, spread around its median on a log scale,median * ratio * (f0 / median) ** range(range=0is a monotone atratiotimes the median, 2 doubles every interval from it). Unvoiced time windows (0) stay unvoiced.contouris anF0Track, which comes back as anF0Track(its candidates changed the same way), a(times, f0)pair, which comes back as a pair, or anything with.tand.f0, which comes back as a(times, f0)pair. A ratio in semitonesstis2 ** (st / 12). Withratio=1andrange=1the 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:
_GridViewA spectral envelope: power on a grid of times
tand frequenciesf,dataof 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 insettings(for CheapTrickq1,f0_floorandunvoiced_f0); one built by hand has neither.fsis 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), whenfsis known andfis that FFT’s grid from 0 tofs / 2; None for an envelope on any other grid.
- amplitude(t: ArrayLike, f: ArrayLike, *, channel: int = 0) ndarray[source]¶
The amplitude (square root of the power) at the points
(t[i], f[i]),tandfof the same shape: the formharmonic_complex()reads, one value per sample and harmonic. Linear in time and in dB over frequency, held beyond the first and last time windows.
- 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:
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.
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.
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
SpectralEnvelopeon the FFT grid (n_fft // 2 + 1frequencies from 0 tofs / 2) at the F0 track’s times, withmethod="CheapTrick"and the three parameters insettings.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-12is added to the power before the logarithm; unvoiced time windows are analyzed atunvoiced_f0(a short window and wide smoothing, which suits noise); F0 belowf0_flooris raised to it; the FFT size is the smallest power of two above3 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.09is the paper’s value (WORLD’s code later used-0.15, which sharpens the peaks a little more);0is 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.viewis anything read asview(t, f): aSpectralEnvelope, anAperiodicity, any otherTimeFrequencyGrid, or a function. A view held on a grid comes back as the same type on the same grid, with itsmethodandsettings(sosource_filter_synthesizetakes it as before); a function comes back as a function.ratiois: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
normalizeremoves. 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:
_GridViewAn aperiodicity, from
band_aperiodicity()orharmonic_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 ofn_fft // 2 + 1frequenciesffrom 0 tofs / 2: its squareshareis the share of the power that is noise, which is whatsource_filter_synthesize()uses.methodnames 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.'¶
The noise share of the power,
data ** 2.
- 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 anenvelope(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.
- 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:
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).
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.
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_bwthe width of the window’s main lobe) is the band’s noise share (Eqs. 27 and 28).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_dbadds 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_flooris raised to it; the FFT size is the smallest power of two above4 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-12guards the division; only the positive half of each band’s transform is kept (it holds the lobe at one period once);w_bwis 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];
0gives 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 windowperiodsperiods long, a weighted least-squares fit of the harmonicscos(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 cellscell_harmonicsharmonics wide, and the cells’ shares are interpolated in dB onto the grid ofpitch_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:
ViewThe 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.
maximahas shape(n_bins, n_cutoffs).exponentanduncertaintyhave one value per cutoff:exponentis alpha inP(maximum > x) ~ x**-alpha, fitted by the Hill estimator on the largestfractionof the maxima, anduncertaintyis its standard error,exponent / sqrt(n_fitted).thresholdis, 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 (seeenvelope_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:
High-pass the sound at the cutoff (4th-order Butterworth, forward and backward). Pops are broadband, and a high cutoff keeps low rumble out.
Take the Hilbert envelope and smooth it with a 500 Hz low-pass.
Take the envelope’s maximum in each bin
bin_secondslong. The maximum, not the mean, because the mean smooths short pops away.Fit the exponent of the upper tail of the maxima by the Hill estimator (Hill, 1975) on the largest
fractionof them, at least 10: withx_1 >= x_2 >= ...the sorted maxima andkthe number fitted,exponent = k / sum(log(x_i / x_(k+1)))overi <= 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
fractionfits 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:
ViewPhase-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, andto_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_scalestretches the time axis;freq_mapis a ratio (e.g.1.5) or a function mapping frequencies in Hz to new frequencies. For examplelambda f: f + 70makes a 220 Hz harmonic complex inharmonic; note that shifting by a multiple of half the f0 keeps it harmonic (f + 110gives odd harmonics of 110 Hz). Bins that never come withinfloor_dbof 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_durseconds and a hop ofhop_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 / factorrounded to whole samples, so the content is stretched bysynthesis_hop / analysis_hop. The output length isround(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 thewin_durhalves it, at the cost of time resolution (transients smear over a longer window). Measured by tools/measure_docstring_numbers.py.
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:
ViewOne descriptor’s value in every time window, for each channel. A view: it keeps one number per time window.
valueshas shape(n_channels, n_windows)and is NaN where a time window is silent.medianandiqrare 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¶
- 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
cutoffHz) 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; seetools/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 ofattack_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.scaleis"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;spacingcorrelates 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:
ViewThe 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.
powerhas shape(n_windows, 12, n_channels): the mean power of the semitone bands of each pitch class over each time window, which start att - window / 2.referenceis the frequency of A4 that placed the bands;f_loandf_hiare 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¶
- 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.
octavesis 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 betweenf_loandf_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_lotof_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 isdurationlong, 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
referenceHz (by default 440 Hz, the standard pitch of ISO 16), centered fromf_lotof_hi(A1 to A8 by default; both are moved to the nearest semitone). Each band’s power is averaged over time windowswindowseconds long, rounded to a whole number of samples (Chroma.windowis 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 segmentssegment_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 segmentk, the next is the one whose join withkchanges the cochleagram by as much as the sound itself changed afterk: thenthat minimizes|d(k, n) - d(k, k + 1)|, wheredis the mean squared difference between the lastborder_durof one segment and the firstborder_durof another. The sound’s own next segmentk + 1is 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 bysplice(), with raised-cosine cross-fadescrossfadelong, each new segment moved by up tomax_shiftto 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 (seesplice()).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 samerngseed 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.