Ir al contenido

signals: test signals

La referencia de la API se publica en inglés en los dos idiomas: se genera a partir de los docstrings del código, que son su texto original.

Every name on this page is published by phonometry.signals: from phonometry import signals, then signals.<name>.

Test signals and sample-rate utilities.

The signal toolbox of the metrology domain: deterministic test signals and the two sample-rate operations every measurement chain eventually needs, with their accuracy stated instead of implied.

  • noise_signal: Gaussian noise with an exact power-law spectral slope: white (0 dB/octave), pink (-3.01), red (-6.02, also called Brownian), blue (+3.01) and violet (+6.02). The autospectral density follows with = 0, -1, -2, +1 and +2 respectively, so the level changes by exactly dB per octave ( dB). The colors are synthesized by filtering seeded white Gaussian noise in the frequency domain: the DFT of the white record is multiplied by the exact magnitude response bin by bin (a zero-phase FIR filter applied circularly), so the expected spectrum follows the power law exactly at every synthesis bin above DC and a measured slope deviates only by the random error of the spectral estimate, not the piecewise or few-pole approximations whose pink slope ripples by fractions of a dB. The DC bin is zeroed for the colored variants (a power law has no finite DC value) and the record is rescaled to the requested RMS exactly. With the same seed the generator is fully deterministic across runs.

  • tone_burst: the gated sine burst of IEC 60268-1:1985 (Appendix A, Clause A2): the tone starts at a zero crossing and lasts an integral number of full periods, either as a single burst or as a repetitive train with a stated repetition rate. The result records the rectangular gating envelope and the exact on/off sample bookkeeping, so meter ballistics and dynamic-response tests can state their stimulus instead of hand-rolling it.

  • resample_signal: polyphase resampling behind an explicit anti-alias specification. The lowpass FIR is designed here (Kaiser window method) from two numbers the caller controls (the stopband attenuation in dB and the transition-band fraction of the target Nyquist), and the designed filter is returned with the result, so the alias rejection of a resampled record is a documented property, not a library default.

  • fractional_delay: band-limited delay by an arbitrary (sub-sample) number of samples via a frequency-domain phase ramp, linear (zero-padded, for transients and impulse responses; the same kernel align_impulse_responses uses) or circular (for periodic records, exact to machine precision on bin-centered tones).

Auto-generated from the source docstrings by scripts/generate_api_docs.py (make api-docs). Do not edit by hand.

fractional_delay(
x: Signal,
delay: float,
*,
mode: Literal['linear', 'circular'] = ...,
) -> Signal
fractional_delay(
x: NumericArrayLike,
delay: float,
*,
mode: Literal['linear', 'circular'] = ...,
) -> NDArray[np.float64]

Delay a record by an arbitrary (sub-sample) number of samples.

Band-limited delay via a frequency-domain phase ramp : every spectral component is delayed by exactly delay samples, i.e. its phase changes by radians. Two boundary conventions:

  • 'linear' (default): the record is zero-padded past the shift before the ramp, so samples leaving one end land in the padding instead of wrapping around; use it for transients and impulse responses. Content shifted beyond the record length is discarded (the output keeps the input length).
  • 'circular': the ramp is applied over the record itself and the shift wraps around; use it for periodic records. For a tone centered on a DFT bin the delayed record equals the analytically delayed tone to machine precision.

An integer delay in 'linear' mode reduces to an exact sample shift with zero fill. Negative delays advance the record.

A real record of even length cannot carry a fractionally delayed Nyquist-bin component (the inverse real FFT keeps its real part), so keep the signal band-limited below Nyquist, as any properly sampled signal is, or use odd lengths, and the operation is exact.

Parameters

Name Description
x Input record, 1-D. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so the delayed record comes out in Pa.
delay Delay in samples (fractional and negative allowed); magnitude less than the record length.
mode Boundary convention, 'linear' or 'circular'.

Returns: The delayed record, same length as x.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if delay is not a single number, or mode is not a text, or x holds a text or a value that is not a real number.
noise_signal(
fs: float,
*,
duration_s: float = 1.0,
color: Literal['white', 'pink', 'red', 'blue', 'violet'] = 'white',
rms: float = 1.0,
seed: int | None = None,
) -> NDArray[np.float64]

Generate Gaussian noise with an exact power-law spectral slope.

with = 0 (white), -1 (pink, -3.01 dB/octave), -2 (red/Brownian, -6.02), +1 (blue, +3.01) or +2 (violet, +6.02), shaped by an exact frequency-domain filter (see the module docstring), zero-mean and rescaled to the requested RMS exactly.

Parameters

Name Description
fs Rate to generate at, in Hz.
duration_s Duration, in seconds (at least 16 samples).
color Noise color: 'white', 'pink', 'red', 'blue' or 'violet'.
rms Root-mean-square value of the returned record.
seed Seed for numpy.random.default_rng; the same seed reproduces the same record. None draws fresh entropy.

Returns: The noise record, round(fs * duration_s) samples.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if duration_s, fs or rms is not a single number, or color is not a text.
resample_signal(
x: Signal | NumericArrayLike,
fs: float | None = None,
*,
fs_new: float,
stopband_attenuation: float = 120.0,
transition_width: float = 0.05,
max_denominator: int | np.integer[Any] = 1000,
) -> ResampledSignalResult

Resample a record with a stated anti-alias specification.

Polyphase rational resampling (scipy.signal.resample_poly) behind a lowpass FIR designed here by the Kaiser window method: the stopband starts at the smaller of the two Nyquist frequencies and provides stopband_attenuation of alias rejection, the passband ends transition_width below it and is flat within the same ripple bound . The designed taps travel with the result, so the spec is a property of the returned filter, not of a library default.

Parameters

Name Description
x Input record, 1-D. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so the resampled record comes out in Pa and comes back as a Signal at the new rate.
fs Sample rate of x, in Hz. Required for a bare array; a Signal brings its own, and an explicit value that disagrees with it raises instead of silently winning.
fs_new Target sample rate, in Hz. The ratio fs_new/fs must be a rational number with denominator at most max_denominator (e.g. 48000/44100 = 160/147).
stopband_attenuation Anti-alias stopband attenuation, in dB (at least 30).
transition_width Transition-band width as a fraction of the smaller Nyquist frequency, in (0, 0.5].
max_denominator Largest denominator accepted for the rational rate ratio.

Returns: A ResampledSignalResult.

Raises

Exception When
ValueError If the inputs or parameters are invalid, or if the rate ratio is not rational within max_denominator.
TypeError if stopband_attenuation or transition_width is not a single number, or max_denominator is a flag, a text or an array where a count goes, or x holds a text or a value that is not a real number.
ResampledSignalResult(
signal: Signal | NDArray[np.float64],
fs: float,
original_fs: float,
up: int,
down: int,
filter_taps: NDArray[np.float64],
passband_edge_hz: float,
stopband_edge_hz: float,
stopband_attenuation: float,
transition_width: float,
)

Resampled record with the designed anti-alias filter and its spec.

The polyphase resampler filters at the intermediate rate fs_original * up with a linear-phase Kaiser-window lowpass designed from the two numbers below; the filter taps are returned so the spec can be verified against the filter itself.

Attributes

Name Description
signal The resampled record, in the type the input arrived as: a Signal at the new rate when it was one (in pascals and carrying calibration_factor=1.0 when it was calibrated), a bare array otherwise.
fs Sample rate of signal, in Hz.
original_fs Sample rate of the input, in Hz.
up Interpolation factor of the rational ratio up/down.
down Decimation factor of the rational ratio up/down.
filter_taps Anti-alias FIR taps (unit passband gain; the polyphase engine applies the up interpolation gain), designed at the intermediate rate original_fs * up. A single 1.0 tap when the ratio is 1 (no filtering).
passband_edge_hz Passband edge of the design, in Hz.
stopband_edge_hz Stopband edge of the design (the smaller of the two Nyquist frequencies), in Hz.
stopband_attenuation Designed stopband attenuation, in dB (also the passband ripple bound: the Kaiser window method holds the ripple of both bands within the same , though, unlike a true equiripple design, its ripple decays away from the band edges rather than staying at the bound).
transition_width Transition-band width as a fraction of the smaller Nyquist frequency.

property

Length of the designed anti-alias FIR.

ResampledSignalResult.plot(
ax: Axes | None = None,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> Axes

Plot the delivered anti-alias filter against its design spec.

The magnitude response of filter_taps with the passband edge, the stopband edge at the alias fold, the designed stopband attenuation and the rejected band shaded.

Parameters

Name Description
ax Existing axes, or None to create a figure.
language Label language, "en" (default) or "es".
kwargs Forwarded to the magnitude plot call.

Returns: The axes.

tone_burst(
fs: float,
frequency: float,
n_cycles: int | np.integer[Any],
*,
amplitude: float = 1.0,
n_repetitions: int | np.integer[Any] = 1,
repetition_rate: float | None = None,
pre_silence: float = 0.0,
post_silence: float = 0.0,
) -> ToneBurstResult

Generate an IEC 60268-1 tone burst (single or repetitive).

IEC 60268-1:1985, Clause A2.1: “The burst should start at the zero-crossing of the […] tone and should consist of an integral number of full periods.” The burst is a sine of n_cycles full periods gated by a rectangular envelope; with repetition_rate a train of n_repetitions identical bursts is produced, one per repetition period, as in the repetitive-burst test of Clause A2.2 (there: 5 ms bursts of 5 kHz tone at 2, 10 or 100 bursts per second).

The gate closes after round(fs * cycles / frequency) samples, so the “integral number of full periods” is sample-exact only when fs and frequency are commensurate (fs * n_cycles/frequency an integer). Otherwise the gate closes up to half a sample away from the tone’s final zero crossing and the gated waveform carries a residual step of up to there (e.g. 10 cycles of 997 Hz at 48 kHz span 481.44 samples, gated at 481); a ToneBurstWarning quantifies the realized residual.

Parameters

Name Description
fs Rate to generate at, in Hz.
frequency Tone frequency, in Hz (below the Nyquist rate).
n_cycles Full tone periods per burst (positive integer).
amplitude Peak amplitude of the tone.
n_repetitions Number of bursts (requires repetition_rate when greater than 1).
repetition_rate Bursts per second; each burst then occupies one full repetition period (burst plus silence). None (the default) produces a single burst with no trailing period.
pre_silence Silence before the first burst, in seconds.
post_silence Silence after the last burst (or after the last repetition period), in seconds.

Returns: A ToneBurstResult.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if n_cycles or n_repetitions is a flag, a text or an array where a count goes. post_silence or pre_silence are refused the same way when any is not one real number.

Warns

Warning When
ToneBurstWarning If fs and frequency are incommensurate.
ToneBurstResult(
signal: NDArray[np.float64],
envelope: NDArray[np.float64],
fs: float,
frequency: float,
n_cycles: int,
amplitude: float,
burst_s: float,
burst_samples: int,
onset_sample: int,
n_repetitions: int,
repetition_rate: float | None,
period_samples: int | None,
duty_cycle: float | None,
)

Gated sine burst per IEC 60268-1:1985 (Appendix A, Clause A2).

The tone starts at a zero crossing (positive-going) and the gate stays open for an integral number of full periods, as Clause A2.1 requires of the dynamic-response stimulus. With a repetition rate the record is a train of identical bursts, one per repetition period (Clause A2.2).

Attributes

Name Description
signal The burst record (silence, bursts and gaps included).
envelope Rectangular gating envelope of signal (amplitude while the gate is open, 0 elsewhere).
fs Sample rate, in Hz.
frequency Tone frequency, in Hz.
n_cycles Full tone periods per burst.
amplitude Peak amplitude of the tone.
burst_s Burst duration n_cycles/frequency, in seconds.
burst_samples Samples per burst, round(fs * cycles / frequency).
onset_sample Index of the first sample of the first burst.
n_repetitions Number of bursts in the record.
repetition_rate Bursts per second, or None (single burst).
period_samples Samples per repetition period (round(fs/repetition_rate)), or None (single burst).
duty_cycle On fraction burst_samples/period_samples, or None (single burst).
ToneBurstResult.plot(
ax: Axes | None = None,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> Axes

Plot the burst waveform with its gating envelope.

Parameters

Name Description
language Label language, "en" (default) or "es".

A tone burst whose gate cannot close on the tone’s zero crossing.

Emitted by tone_burst when the sample rate and the tone frequency are incommensurate, so the gate closes away from the final zero crossing and leaves a residual step, which the message quantifies.