pyquist 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyquist/__init__.py +40 -0
- pyquist/audio.py +505 -0
- pyquist/audio_test.py +447 -0
- pyquist/cli.py +102 -0
- pyquist/device.py +323 -0
- pyquist/device_test.py +508 -0
- pyquist/helper.py +133 -0
- pyquist/helper_test.py +107 -0
- pyquist/paths.py +13 -0
- pyquist/plot.py +285 -0
- pyquist/plot_test.py +190 -0
- pyquist/py.typed +0 -0
- pyquist/score.py +512 -0
- pyquist/score_test.py +476 -0
- pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
- pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
- pyquist/test_data/ravel_bolero.mid +0 -0
- pyquist/web/__init__.py +7 -0
- pyquist/web/freesound.py +288 -0
- pyquist/web/theorytab.py +408 -0
- pyquist-0.1.0.dist-info/METADATA +180 -0
- pyquist-0.1.0.dist-info/RECORD +26 -0
- pyquist-0.1.0.dist-info/WHEEL +5 -0
- pyquist-0.1.0.dist-info/entry_points.txt +2 -0
- pyquist-0.1.0.dist-info/licenses/LICENSE +7 -0
- pyquist-0.1.0.dist-info/top_level.txt +1 -0
pyquist/helper_test.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .helper import (
|
|
6
|
+
amplitude_to_db,
|
|
7
|
+
db_to_amplitude,
|
|
8
|
+
frequency_to_pitch,
|
|
9
|
+
pitch_name_to_pitch,
|
|
10
|
+
pitch_to_frequency,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TestHelper(unittest.TestCase):
|
|
15
|
+
def test_db_amplitude_conversion(self):
|
|
16
|
+
db = np.array([-6.0, -3.0, 0.0, 3.0, 6.0])
|
|
17
|
+
amp = np.array([0.501187, 0.707946, 1.0, 1.412538, 1.995262])
|
|
18
|
+
for d, a in zip(db, amp):
|
|
19
|
+
self.assertAlmostEqual(db_to_amplitude(d), a, places=5)
|
|
20
|
+
self.assertAlmostEqual(amplitude_to_db(a), d, places=5)
|
|
21
|
+
self.assertAlmostEqual(db_to_amplitude(amplitude_to_db(a)), a, places=6)
|
|
22
|
+
self.assertAlmostEqual(amplitude_to_db(db_to_amplitude(d)), d, places=6)
|
|
23
|
+
|
|
24
|
+
self.assertTrue(np.allclose(db_to_amplitude(db), amp))
|
|
25
|
+
self.assertTrue(np.allclose(amplitude_to_db(amp), db))
|
|
26
|
+
self.assertTrue(np.allclose(db_to_amplitude(amplitude_to_db(amp)), amp))
|
|
27
|
+
self.assertTrue(np.allclose(amplitude_to_db(db_to_amplitude(db)), db))
|
|
28
|
+
|
|
29
|
+
def test_db_amplitude_well_known_values(self):
|
|
30
|
+
# Sanity-check a few canonical values with default reference=1.0.
|
|
31
|
+
self.assertAlmostEqual(db_to_amplitude(0.0), 1.0, places=6)
|
|
32
|
+
self.assertAlmostEqual(db_to_amplitude(-20.0), 0.1, places=6)
|
|
33
|
+
self.assertAlmostEqual(amplitude_to_db(1.0), 0.0, places=6)
|
|
34
|
+
self.assertAlmostEqual(amplitude_to_db(0.1), -20.0, places=6)
|
|
35
|
+
|
|
36
|
+
def test_db_amplitude_with_reference(self):
|
|
37
|
+
# 0 dB relative to a reference returns the reference itself.
|
|
38
|
+
self.assertAlmostEqual(db_to_amplitude(0.0, reference=0.5), 0.5, places=6)
|
|
39
|
+
self.assertAlmostEqual(db_to_amplitude(0.0, reference=2.0), 2.0, places=6)
|
|
40
|
+
# Conversely, an amplitude equal to the reference is 0 dB relative.
|
|
41
|
+
self.assertAlmostEqual(amplitude_to_db(0.5, reference=0.5), 0.0, places=6)
|
|
42
|
+
self.assertAlmostEqual(amplitude_to_db(2.0, reference=2.0), 0.0, places=6)
|
|
43
|
+
# -6 dB below a non-unity reference still halves the level (roughly).
|
|
44
|
+
self.assertAlmostEqual(
|
|
45
|
+
db_to_amplitude(-6.0, reference=0.5), 0.5 * 0.501187, places=5
|
|
46
|
+
)
|
|
47
|
+
# Round-trip with a non-unity reference.
|
|
48
|
+
for ref in [0.25, 0.5, 2.0, 10.0]:
|
|
49
|
+
for d in [-12.0, -3.0, 0.0, 6.0]:
|
|
50
|
+
a = db_to_amplitude(d, reference=ref)
|
|
51
|
+
self.assertAlmostEqual(amplitude_to_db(a, reference=ref), d, places=6)
|
|
52
|
+
|
|
53
|
+
def test_frequency_pitch_conversion(self):
|
|
54
|
+
frequency = np.array([440.0, 523.251, 659.255, 783.991, 987.767])
|
|
55
|
+
pitch = np.array([69.0, 72.0, 76.0, 79.0, 83.0])
|
|
56
|
+
for f, p in zip(frequency, pitch):
|
|
57
|
+
self.assertAlmostEqual(frequency_to_pitch(f), p, places=2)
|
|
58
|
+
self.assertAlmostEqual(pitch_to_frequency(p), f, places=2)
|
|
59
|
+
self.assertAlmostEqual(
|
|
60
|
+
frequency_to_pitch(pitch_to_frequency(p)), p, places=6
|
|
61
|
+
)
|
|
62
|
+
self.assertAlmostEqual(
|
|
63
|
+
pitch_to_frequency(frequency_to_pitch(f)), f, places=6
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
self.assertTrue(np.allclose(frequency_to_pitch(frequency), pitch))
|
|
67
|
+
self.assertTrue(np.allclose(pitch_to_frequency(pitch), frequency))
|
|
68
|
+
self.assertTrue(
|
|
69
|
+
np.allclose(frequency_to_pitch(pitch_to_frequency(pitch)), pitch)
|
|
70
|
+
)
|
|
71
|
+
self.assertTrue(
|
|
72
|
+
np.allclose(pitch_to_frequency(frequency_to_pitch(frequency)), frequency)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def test_pitch_name_to_pitch(self):
|
|
76
|
+
self.assertEqual(pitch_name_to_pitch("B3"), 59)
|
|
77
|
+
self.assertEqual(pitch_name_to_pitch("C4"), 60)
|
|
78
|
+
self.assertEqual(pitch_name_to_pitch("D4"), 62)
|
|
79
|
+
self.assertEqual(pitch_name_to_pitch("E4"), 64)
|
|
80
|
+
self.assertEqual(pitch_name_to_pitch("F4"), 65)
|
|
81
|
+
self.assertEqual(pitch_name_to_pitch("G4"), 67)
|
|
82
|
+
self.assertEqual(pitch_name_to_pitch("A4"), 69)
|
|
83
|
+
self.assertEqual(pitch_name_to_pitch("B4"), 71)
|
|
84
|
+
self.assertEqual(pitch_name_to_pitch("C5"), 72)
|
|
85
|
+
|
|
86
|
+
self.assertEqual(pitch_name_to_pitch("Bb3"), 58)
|
|
87
|
+
self.assertEqual(pitch_name_to_pitch("Bbbbb3"), 55)
|
|
88
|
+
self.assertEqual(pitch_name_to_pitch("C#4"), 61)
|
|
89
|
+
self.assertEqual(pitch_name_to_pitch("C####4"), 64)
|
|
90
|
+
self.assertEqual(pitch_name_to_pitch("c4"), 60)
|
|
91
|
+
|
|
92
|
+
self.assertEqual(
|
|
93
|
+
pitch_name_to_pitch(np.array(["B3", "C4", "D4"])).tolist(), [59, 60, 62]
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
with self.assertRaises(ValueError):
|
|
97
|
+
pitch_name_to_pitch("A")
|
|
98
|
+
with self.assertRaises(ValueError):
|
|
99
|
+
pitch_name_to_pitch("Z3")
|
|
100
|
+
with self.assertRaises(ValueError):
|
|
101
|
+
pitch_name_to_pitch("Cd3")
|
|
102
|
+
with self.assertRaises(ValueError):
|
|
103
|
+
pitch_name_to_pitch("BK")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
unittest.main()
|
pyquist/paths.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import pathlib
|
|
3
|
+
|
|
4
|
+
LIB_DIR = pathlib.Path(__file__).resolve().parent
|
|
5
|
+
|
|
6
|
+
if "PYQUIST_CACHE_DIR" in os.environ:
|
|
7
|
+
CACHE_DIR = pathlib.Path(os.environ["PYQUIST_CACHE_DIR"])
|
|
8
|
+
else:
|
|
9
|
+
CACHE_DIR = pathlib.Path(pathlib.Path.home(), ".cache", "pyquist")
|
|
10
|
+
CACHE_DIR = CACHE_DIR.resolve()
|
|
11
|
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
12
|
+
|
|
13
|
+
TEST_DATA_DIR = LIB_DIR / "test_data"
|
pyquist/plot.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Plot helpers for ``Audio`` (waveform, magnitude spectrum, spectrogram).
|
|
2
|
+
|
|
3
|
+
These work the same in a notebook and a regular script. Pass
|
|
4
|
+
``output_file=<path>`` to save the figure to disk in addition to (or instead
|
|
5
|
+
of) displaying it interactively.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import warnings
|
|
9
|
+
from typing import Optional, Tuple
|
|
10
|
+
|
|
11
|
+
import matplotlib.axes
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from .audio import Audio
|
|
16
|
+
from .helper import amplitude_to_db
|
|
17
|
+
|
|
18
|
+
# Upper bound on the FFT size chosen by ``plot_freq`` when ``n_fft`` is None.
|
|
19
|
+
# 2**16 = 65536 samples ≈ 1.5 s at 44.1 kHz. Beyond this the plot gets dense
|
|
20
|
+
# and the FFT slow; the user can override by passing ``n_fft`` explicitly.
|
|
21
|
+
NFFT_MAX = 1 << 16
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def plot(
|
|
25
|
+
audio: Audio,
|
|
26
|
+
*,
|
|
27
|
+
offset: Optional[float] = None,
|
|
28
|
+
duration: Optional[float] = None,
|
|
29
|
+
figsize: Tuple[float, float] = (10, 3),
|
|
30
|
+
ax: Optional[matplotlib.axes.Axes] = None,
|
|
31
|
+
output_file: Optional[str] = None,
|
|
32
|
+
) -> matplotlib.axes.Axes:
|
|
33
|
+
"""Plots the waveform of an Audio.
|
|
34
|
+
|
|
35
|
+
Channels are overlaid on a single axis. The x-axis is time in seconds if
|
|
36
|
+
``audio.sample_rate`` is set, otherwise sample index. The y-axis is
|
|
37
|
+
symmetric about zero.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
audio: The audio to plot.
|
|
41
|
+
offset: Start time in seconds. Defaults to ``0.0`` (beginning of audio).
|
|
42
|
+
Requires ``audio.sample_rate`` to be set.
|
|
43
|
+
duration: Length to plot in seconds. Defaults to the rest of the
|
|
44
|
+
audio. Requires ``audio.sample_rate`` to be set.
|
|
45
|
+
figsize: Figure size passed to ``plt.subplots`` (ignored if ``ax`` is given).
|
|
46
|
+
ax: An existing axis to draw into. If ``None``, a new figure is created.
|
|
47
|
+
output_file: If given, the figure is saved to this path via
|
|
48
|
+
``Figure.savefig``. Extension determines format (``.png``, ``.pdf``,
|
|
49
|
+
``.svg``, ...).
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
The matplotlib ``Axes`` the waveform was drawn on.
|
|
53
|
+
"""
|
|
54
|
+
seg = audio.segment(offset=offset, duration=duration)
|
|
55
|
+
n = seg.num_samples
|
|
56
|
+
|
|
57
|
+
if ax is None:
|
|
58
|
+
_, ax = plt.subplots(figsize=figsize)
|
|
59
|
+
|
|
60
|
+
if audio.sample_rate is None:
|
|
61
|
+
x = np.arange(n, dtype=float)
|
|
62
|
+
xlabel = "Sample"
|
|
63
|
+
else:
|
|
64
|
+
# Anchor labels at the clamped start time so the x-axis reflects the
|
|
65
|
+
# original audio's timeline rather than the slice's own [0, duration).
|
|
66
|
+
start_time = max(0.0, offset or 0.0)
|
|
67
|
+
x = start_time + np.arange(n) / audio.sample_rate
|
|
68
|
+
xlabel = "Time (s)"
|
|
69
|
+
|
|
70
|
+
for ch in range(seg.num_channels):
|
|
71
|
+
label = f"Channel {ch}" if seg.num_channels > 1 else None
|
|
72
|
+
ax.plot(x, seg.samples[:, ch], linewidth=0.5, label=label)
|
|
73
|
+
|
|
74
|
+
if seg.num_channels > 1:
|
|
75
|
+
ax.legend(loc="upper right")
|
|
76
|
+
|
|
77
|
+
ax.set_xlabel(xlabel)
|
|
78
|
+
ax.set_ylabel("Amplitude")
|
|
79
|
+
if n > 0:
|
|
80
|
+
ax.set_xlim(x[0], x[-1])
|
|
81
|
+
# Symmetric y-limits around zero with 5% headroom; fall back to ±1.0
|
|
82
|
+
# when the slice is silent or empty.
|
|
83
|
+
peak = seg.peak_amplitude
|
|
84
|
+
half = peak * 1.05 if peak > 0.0 else 1.0
|
|
85
|
+
ax.set_ylim(-half, half)
|
|
86
|
+
|
|
87
|
+
if output_file is not None:
|
|
88
|
+
ax.figure.savefig(output_file) # type: ignore[union-attr]
|
|
89
|
+
return ax
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def plot_freq(
|
|
93
|
+
audio: Audio,
|
|
94
|
+
*,
|
|
95
|
+
offset: Optional[float] = None,
|
|
96
|
+
duration: Optional[float] = None,
|
|
97
|
+
n_fft: Optional[int] = None,
|
|
98
|
+
log_frequency: bool = True,
|
|
99
|
+
log_amplitude: bool = True,
|
|
100
|
+
dynamic_range_db: float = 80.0,
|
|
101
|
+
figsize: Tuple[float, float] = (10, 3),
|
|
102
|
+
ax: Optional[matplotlib.axes.Axes] = None,
|
|
103
|
+
output_file: Optional[str] = None,
|
|
104
|
+
) -> matplotlib.axes.Axes:
|
|
105
|
+
"""Plots the magnitude spectrum of an Audio via a single FFT.
|
|
106
|
+
|
|
107
|
+
Multi-channel audio is first mixed to mono. By default ``n_fft`` is the
|
|
108
|
+
smallest power of two ``>= num_samples`` (zero-padding shorter signals),
|
|
109
|
+
capped at :data:`NFFT_MAX`. When the cap kicks in, a warning is issued
|
|
110
|
+
and the FFT is taken over only the first ``NFFT_MAX`` samples.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
audio: The audio to analyze. Must have a ``sample_rate``.
|
|
114
|
+
offset: Start time in seconds. Defaults to ``0.0`` (beginning of audio).
|
|
115
|
+
duration: Length to analyze in seconds. Defaults to the rest of the audio.
|
|
116
|
+
n_fft: FFT size. ``None`` (default) picks the smallest power of two
|
|
117
|
+
``>= num_samples`` (capped at ``NFFT_MAX``). When set explicitly,
|
|
118
|
+
shorter signals are zero-padded and longer signals are truncated
|
|
119
|
+
to the first ``n_fft`` samples (no warning).
|
|
120
|
+
log_frequency: If True (default), the x-axis uses a log scale.
|
|
121
|
+
log_amplitude: If True (default), magnitudes are converted to dB.
|
|
122
|
+
dynamic_range_db: Magnitudes below ``-dynamic_range_db`` dB are
|
|
123
|
+
floored for numerical stability. Only used when
|
|
124
|
+
``log_amplitude=True``.
|
|
125
|
+
figsize: Figure size (ignored if ``ax`` is given).
|
|
126
|
+
ax: An existing axis to draw into. If ``None``, a new figure is created.
|
|
127
|
+
output_file: If given, the figure is saved to this path.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
The matplotlib ``Axes`` the spectrum was drawn on.
|
|
131
|
+
"""
|
|
132
|
+
if audio.sample_rate is None:
|
|
133
|
+
raise ValueError("Cannot compute FFT without a sample_rate.")
|
|
134
|
+
|
|
135
|
+
seg = audio.segment(offset=offset, duration=duration).as_mono()
|
|
136
|
+
if seg.num_samples == 0:
|
|
137
|
+
raise ValueError(
|
|
138
|
+
f"plot_freq: selected segment is empty "
|
|
139
|
+
f"(offset={offset} is past audio duration {audio.duration:.3f}s)."
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
samples = seg.samples[:, 0]
|
|
143
|
+
|
|
144
|
+
if n_fft is None:
|
|
145
|
+
# Smallest power of two >= num_samples.
|
|
146
|
+
n_fft = 1 << (seg.num_samples - 1).bit_length()
|
|
147
|
+
if n_fft > NFFT_MAX:
|
|
148
|
+
warnings.warn(
|
|
149
|
+
f"plot_freq: audio segment has {seg.num_samples} samples; "
|
|
150
|
+
f"capping FFT size at NFFT_MAX={NFFT_MAX} and analyzing only "
|
|
151
|
+
f"the first {NFFT_MAX} samples. "
|
|
152
|
+
f"Pass an explicit n_fft to override.",
|
|
153
|
+
stacklevel=2,
|
|
154
|
+
)
|
|
155
|
+
n_fft = NFFT_MAX
|
|
156
|
+
|
|
157
|
+
# np.fft.rfft zero-pads if n > len(samples) and truncates if n < len(samples).
|
|
158
|
+
spectrum = np.fft.rfft(samples, n=n_fft)
|
|
159
|
+
magnitude = np.abs(spectrum)
|
|
160
|
+
freqs = np.fft.rfftfreq(n_fft, d=1.0 / audio.sample_rate)
|
|
161
|
+
|
|
162
|
+
if log_amplitude:
|
|
163
|
+
floor = 10 ** (-dynamic_range_db / 20)
|
|
164
|
+
y = amplitude_to_db(np.maximum(magnitude, floor))
|
|
165
|
+
ylabel = "Amplitude (dB)"
|
|
166
|
+
else:
|
|
167
|
+
y = magnitude
|
|
168
|
+
ylabel = "Amplitude"
|
|
169
|
+
|
|
170
|
+
if ax is None:
|
|
171
|
+
_, ax = plt.subplots(figsize=figsize)
|
|
172
|
+
|
|
173
|
+
ax.plot(freqs, y, linewidth=0.5)
|
|
174
|
+
|
|
175
|
+
if log_frequency:
|
|
176
|
+
ax.set_xscale("log")
|
|
177
|
+
# First bin is DC; skip it so the log axis has a positive floor.
|
|
178
|
+
ax.set_xlim(max(freqs[1], 20.0), audio.sample_rate / 2)
|
|
179
|
+
else:
|
|
180
|
+
ax.set_xlim(0, audio.sample_rate / 2)
|
|
181
|
+
|
|
182
|
+
ax.set_xlabel("Frequency (Hz)")
|
|
183
|
+
ax.set_ylabel(ylabel)
|
|
184
|
+
|
|
185
|
+
if output_file is not None:
|
|
186
|
+
ax.figure.savefig(output_file) # type: ignore[union-attr]
|
|
187
|
+
return ax
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def plot_spec(
|
|
191
|
+
audio: Audio,
|
|
192
|
+
*,
|
|
193
|
+
offset: Optional[float] = None,
|
|
194
|
+
duration: Optional[float] = None,
|
|
195
|
+
n_fft: int = 2048,
|
|
196
|
+
hop_length: int = 512,
|
|
197
|
+
log_frequency: bool = True,
|
|
198
|
+
log_amplitude: bool = True,
|
|
199
|
+
dynamic_range_db: float = 80.0,
|
|
200
|
+
figsize: Tuple[float, float] = (10, 4),
|
|
201
|
+
ax: Optional[matplotlib.axes.Axes] = None,
|
|
202
|
+
output_file: Optional[str] = None,
|
|
203
|
+
) -> matplotlib.axes.Axes:
|
|
204
|
+
"""Plots a magnitude spectrogram of an Audio.
|
|
205
|
+
|
|
206
|
+
Multi-channel audio is first mixed to mono. A Hann-windowed STFT with
|
|
207
|
+
``n_fft`` window size and ``hop_length`` frame advance is computed;
|
|
208
|
+
magnitudes are optionally converted to dB and plotted on a log-frequency
|
|
209
|
+
axis (both defaults).
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
audio: The audio to analyze. Must have a ``sample_rate``.
|
|
213
|
+
offset: Start time in seconds. Defaults to ``0.0`` (beginning of audio).
|
|
214
|
+
duration: Length to analyze in seconds. Defaults to the rest of the audio.
|
|
215
|
+
n_fft: STFT window size in samples. Defaults to 2048 (~46 ms at 44.1 kHz).
|
|
216
|
+
hop_length: Frame advance in samples. Defaults to 512 (75% overlap).
|
|
217
|
+
log_frequency: If True (default), the y-axis uses a log scale.
|
|
218
|
+
log_amplitude: If True (default), magnitudes are converted to dB
|
|
219
|
+
(via :func:`pyquist.helper.amplitude_to_db`).
|
|
220
|
+
dynamic_range_db: Magnitudes below ``-dynamic_range_db`` dB are floored
|
|
221
|
+
for numerical stability. Only used when ``log_amplitude=True``.
|
|
222
|
+
figsize: Figure size (ignored if ``ax`` is given).
|
|
223
|
+
ax: An existing axis to draw into. If ``None``, a new figure is created.
|
|
224
|
+
output_file: If given, the figure is saved to this path.
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
The matplotlib ``Axes`` the spectrogram was drawn on.
|
|
228
|
+
"""
|
|
229
|
+
if audio.sample_rate is None:
|
|
230
|
+
raise ValueError("Cannot compute spectrogram without a sample_rate.")
|
|
231
|
+
|
|
232
|
+
seg = audio.segment(offset=offset, duration=duration).as_mono()
|
|
233
|
+
if seg.num_samples == 0:
|
|
234
|
+
raise ValueError(
|
|
235
|
+
f"plot_spec: selected segment is empty "
|
|
236
|
+
f"(offset={offset} is past audio duration {audio.duration:.3f}s)."
|
|
237
|
+
)
|
|
238
|
+
if seg.num_samples < n_fft:
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"plot_spec: selected segment has {seg.num_samples} samples, "
|
|
241
|
+
f"which is shorter than n_fft={n_fft}. "
|
|
242
|
+
f"Use a smaller n_fft or a longer duration."
|
|
243
|
+
)
|
|
244
|
+
samples = seg.samples[:, 0]
|
|
245
|
+
win = np.hanning(n_fft).astype(samples.dtype)
|
|
246
|
+
frames = [
|
|
247
|
+
np.fft.rfft(samples[i : i + n_fft] * win)
|
|
248
|
+
for i in range(0, len(samples) - n_fft + 1, hop_length)
|
|
249
|
+
]
|
|
250
|
+
zxx = np.stack(frames, axis=1)
|
|
251
|
+
t = np.arange(len(frames)) * hop_length / audio.sample_rate + max(
|
|
252
|
+
0.0, offset or 0.0
|
|
253
|
+
)
|
|
254
|
+
f = np.fft.rfftfreq(n_fft, d=1.0 / audio.sample_rate)
|
|
255
|
+
|
|
256
|
+
magnitude = np.abs(zxx)
|
|
257
|
+
if log_amplitude:
|
|
258
|
+
floor = 10 ** (-dynamic_range_db / 20)
|
|
259
|
+
spec = amplitude_to_db(np.maximum(magnitude, floor))
|
|
260
|
+
cbar_label = "Amplitude (dB)"
|
|
261
|
+
else:
|
|
262
|
+
spec = magnitude
|
|
263
|
+
cbar_label = "Amplitude"
|
|
264
|
+
|
|
265
|
+
if ax is None:
|
|
266
|
+
_, ax = plt.subplots(figsize=figsize)
|
|
267
|
+
|
|
268
|
+
mesh = ax.pcolormesh(t, f, spec, shading="auto")
|
|
269
|
+
|
|
270
|
+
if log_frequency:
|
|
271
|
+
ax.set_yscale("log")
|
|
272
|
+
# First bin is DC; skip it so log scale has a positive floor.
|
|
273
|
+
ax.set_ylim(max(f[1], 20.0), audio.sample_rate / 2)
|
|
274
|
+
else:
|
|
275
|
+
ax.set_ylim(0, audio.sample_rate / 2)
|
|
276
|
+
|
|
277
|
+
ax.set_xlabel("Time (s)")
|
|
278
|
+
ax.set_ylabel("Frequency (Hz)")
|
|
279
|
+
|
|
280
|
+
cbar = plt.colorbar(mesh, ax=ax)
|
|
281
|
+
cbar.set_label(cbar_label)
|
|
282
|
+
|
|
283
|
+
if output_file is not None:
|
|
284
|
+
ax.figure.savefig(output_file) # type: ignore[union-attr]
|
|
285
|
+
return ax
|
pyquist/plot_test.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
import unittest
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
import matplotlib
|
|
7
|
+
|
|
8
|
+
matplotlib.use("Agg", force=True) # headless backend for tests
|
|
9
|
+
import matplotlib.pyplot as plt # noqa: E402
|
|
10
|
+
import numpy as np # noqa: E402
|
|
11
|
+
|
|
12
|
+
from .audio import Audio # noqa: E402
|
|
13
|
+
from .plot import NFFT_MAX, plot, plot_freq, plot_spec # noqa: E402
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _sine(freq=440.0, duration=1.0, sample_rate=44100, amplitude=0.3):
|
|
17
|
+
n = int(duration * sample_rate)
|
|
18
|
+
t = np.arange(n) / sample_rate
|
|
19
|
+
return Audio(
|
|
20
|
+
amplitude * np.sin(2 * np.pi * freq * t).astype(np.float32),
|
|
21
|
+
sample_rate=sample_rate,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TestPlotWaveform(unittest.TestCase):
|
|
26
|
+
def tearDown(self):
|
|
27
|
+
plt.close("all")
|
|
28
|
+
|
|
29
|
+
def test_labels_and_xscale(self):
|
|
30
|
+
ax = plot(_sine())
|
|
31
|
+
self.assertEqual(ax.get_xlabel(), "Time (s)")
|
|
32
|
+
self.assertEqual(ax.get_ylabel(), "Amplitude")
|
|
33
|
+
# Waveform has no title.
|
|
34
|
+
self.assertEqual(ax.get_title(), "")
|
|
35
|
+
|
|
36
|
+
def test_symmetric_ylim(self):
|
|
37
|
+
ax = plot(_sine(amplitude=0.3))
|
|
38
|
+
ylo, yhi = ax.get_ylim()
|
|
39
|
+
self.assertAlmostEqual(ylo, -yhi)
|
|
40
|
+
self.assertGreater(yhi, 0.3) # ≥ peak
|
|
41
|
+
|
|
42
|
+
def test_silent_audio_fallback_ylim(self):
|
|
43
|
+
silent = Audio(np.zeros(1000, dtype=np.float32), sample_rate=44100)
|
|
44
|
+
ax = plot(silent)
|
|
45
|
+
ylo, yhi = ax.get_ylim()
|
|
46
|
+
self.assertEqual((ylo, yhi), (-1.0, 1.0))
|
|
47
|
+
|
|
48
|
+
def test_no_sample_rate_uses_sample_axis(self):
|
|
49
|
+
buf = Audio(np.zeros(500, dtype=np.float32))
|
|
50
|
+
ax = plot(buf)
|
|
51
|
+
self.assertEqual(ax.get_xlabel(), "Sample")
|
|
52
|
+
|
|
53
|
+
def test_offset_duration_anchors_xlim_to_original_timeline(self):
|
|
54
|
+
ax = plot(_sine(duration=2.0), offset=0.5, duration=0.5)
|
|
55
|
+
xlo, xhi = ax.get_xlim()
|
|
56
|
+
self.assertAlmostEqual(xlo, 0.5, places=3)
|
|
57
|
+
# End is slightly before 1.0 because the slice is exclusive of end.
|
|
58
|
+
self.assertGreater(xhi, 0.95)
|
|
59
|
+
self.assertLess(xhi, 1.005)
|
|
60
|
+
|
|
61
|
+
def test_multichannel_adds_legend(self):
|
|
62
|
+
sr = 44100
|
|
63
|
+
stereo_samples = np.stack(
|
|
64
|
+
[np.linspace(-0.5, 0.5, sr), np.linspace(0.5, -0.5, sr)], axis=1
|
|
65
|
+
).astype(np.float32)
|
|
66
|
+
ax = plot(Audio(stereo_samples, sample_rate=sr))
|
|
67
|
+
self.assertIsNotNone(ax.get_legend())
|
|
68
|
+
|
|
69
|
+
def test_offset_without_sample_rate_raises(self):
|
|
70
|
+
buf = Audio(np.zeros(100, dtype=np.float32))
|
|
71
|
+
with self.assertRaises(ValueError):
|
|
72
|
+
plot(buf, offset=0.1)
|
|
73
|
+
|
|
74
|
+
def test_output_file_writes(self):
|
|
75
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
76
|
+
path = os.path.join(tmp, "waveform.png")
|
|
77
|
+
plot(_sine(), output_file=path)
|
|
78
|
+
self.assertTrue(os.path.exists(path))
|
|
79
|
+
self.assertGreater(os.path.getsize(path), 0)
|
|
80
|
+
|
|
81
|
+
def test_uses_provided_axis(self):
|
|
82
|
+
fig, ax = plt.subplots()
|
|
83
|
+
returned = plot(_sine(), ax=ax)
|
|
84
|
+
self.assertIs(returned, ax)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TestPlotFreq(unittest.TestCase):
|
|
88
|
+
def tearDown(self):
|
|
89
|
+
plt.close("all")
|
|
90
|
+
|
|
91
|
+
def test_default_axes_and_labels(self):
|
|
92
|
+
ax = plot_freq(_sine())
|
|
93
|
+
self.assertEqual(ax.get_xlabel(), "Frequency (Hz)")
|
|
94
|
+
self.assertEqual(ax.get_ylabel(), "Amplitude (dB)")
|
|
95
|
+
self.assertEqual(ax.get_xscale(), "log")
|
|
96
|
+
|
|
97
|
+
def test_linear_axes_opt_out(self):
|
|
98
|
+
ax = plot_freq(_sine(), log_frequency=False, log_amplitude=False)
|
|
99
|
+
self.assertEqual(ax.get_xscale(), "linear")
|
|
100
|
+
self.assertEqual(ax.get_ylabel(), "Amplitude")
|
|
101
|
+
|
|
102
|
+
def test_default_n_fft_is_next_power_of_two(self):
|
|
103
|
+
# 1000 samples → next pow2 is 1024. Bin spacing = sr / 1024.
|
|
104
|
+
sr = 44100
|
|
105
|
+
ax = plot_freq(_sine(duration=1000 / sr, sample_rate=sr), log_frequency=False)
|
|
106
|
+
# rfft of 1024 → 513 freq bins, last bin at sr/2.
|
|
107
|
+
line = ax.get_lines()[0]
|
|
108
|
+
x = line.get_xdata()
|
|
109
|
+
self.assertEqual(len(x), 1024 // 2 + 1)
|
|
110
|
+
|
|
111
|
+
def test_cap_at_nfft_max_emits_warning(self):
|
|
112
|
+
sr = 44100
|
|
113
|
+
long = Audio(np.zeros(NFFT_MAX * 2, dtype=np.float32), sample_rate=sr)
|
|
114
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
115
|
+
warnings.simplefilter("always")
|
|
116
|
+
plot_freq(long)
|
|
117
|
+
self.assertEqual(len(caught), 1)
|
|
118
|
+
self.assertIn("NFFT_MAX", str(caught[0].message))
|
|
119
|
+
|
|
120
|
+
def test_explicit_n_fft_does_not_warn(self):
|
|
121
|
+
sr = 44100
|
|
122
|
+
long = Audio(np.zeros(NFFT_MAX * 2, dtype=np.float32), sample_rate=sr)
|
|
123
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
124
|
+
warnings.simplefilter("always")
|
|
125
|
+
plot_freq(long, n_fft=2048)
|
|
126
|
+
self.assertEqual(len(caught), 0)
|
|
127
|
+
|
|
128
|
+
def test_empty_segment_raises(self):
|
|
129
|
+
with self.assertRaises(ValueError):
|
|
130
|
+
plot_freq(_sine(duration=1.0), offset=10.0)
|
|
131
|
+
|
|
132
|
+
def test_no_sample_rate_raises(self):
|
|
133
|
+
buf = Audio(np.zeros(100, dtype=np.float32))
|
|
134
|
+
with self.assertRaises(ValueError):
|
|
135
|
+
plot_freq(buf)
|
|
136
|
+
|
|
137
|
+
def test_output_file_writes(self):
|
|
138
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
139
|
+
path = os.path.join(tmp, "spec.png")
|
|
140
|
+
plot_freq(_sine(), output_file=path)
|
|
141
|
+
self.assertTrue(os.path.exists(path))
|
|
142
|
+
self.assertGreater(os.path.getsize(path), 0)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class TestPlotSpec(unittest.TestCase):
|
|
146
|
+
def tearDown(self):
|
|
147
|
+
plt.close("all")
|
|
148
|
+
|
|
149
|
+
def test_default_axes_and_labels(self):
|
|
150
|
+
ax = plot_spec(_sine())
|
|
151
|
+
self.assertEqual(ax.get_xlabel(), "Time (s)")
|
|
152
|
+
self.assertEqual(ax.get_ylabel(), "Frequency (Hz)")
|
|
153
|
+
self.assertEqual(ax.get_yscale(), "log")
|
|
154
|
+
|
|
155
|
+
def test_linear_axes_opt_out(self):
|
|
156
|
+
ax = plot_spec(_sine(), log_frequency=False, log_amplitude=False)
|
|
157
|
+
self.assertEqual(ax.get_yscale(), "linear")
|
|
158
|
+
|
|
159
|
+
def test_offset_past_end_clear_error(self):
|
|
160
|
+
with self.assertRaises(ValueError) as ctx:
|
|
161
|
+
plot_spec(_sine(duration=1.0), offset=10.0)
|
|
162
|
+
self.assertIn("empty", str(ctx.exception))
|
|
163
|
+
|
|
164
|
+
def test_segment_shorter_than_n_fft_clear_error(self):
|
|
165
|
+
with self.assertRaises(ValueError) as ctx:
|
|
166
|
+
plot_spec(_sine(duration=1.0), duration=0.01) # 441 samples < 2048
|
|
167
|
+
self.assertIn("n_fft", str(ctx.exception))
|
|
168
|
+
|
|
169
|
+
def test_no_sample_rate_raises(self):
|
|
170
|
+
buf = Audio(np.zeros(10000, dtype=np.float32))
|
|
171
|
+
with self.assertRaises(ValueError):
|
|
172
|
+
plot_spec(buf)
|
|
173
|
+
|
|
174
|
+
def test_output_file_writes(self):
|
|
175
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
176
|
+
path = os.path.join(tmp, "spec.png")
|
|
177
|
+
plot_spec(_sine(), output_file=path)
|
|
178
|
+
self.assertTrue(os.path.exists(path))
|
|
179
|
+
self.assertGreater(os.path.getsize(path), 0)
|
|
180
|
+
|
|
181
|
+
def test_offset_anchors_x_axis(self):
|
|
182
|
+
# The displayed time axis should start near the requested offset.
|
|
183
|
+
ax = plot_spec(_sine(duration=2.0), offset=0.5, duration=0.8)
|
|
184
|
+
xlo, _ = ax.get_xlim()
|
|
185
|
+
self.assertGreater(xlo, 0.4)
|
|
186
|
+
self.assertLess(xlo, 0.6)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
if __name__ == "__main__":
|
|
190
|
+
unittest.main()
|
pyquist/py.typed
ADDED
|
File without changes
|