-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdisplay.py
More file actions
2096 lines (1707 loc) Β· 64 KB
/
Copy pathdisplay.py
File metadata and controls
2096 lines (1707 loc) Β· 64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Display
=======
Data visualization
------------------
.. autosummary::
:toctree: generated/
specshow
waveshow
Axis formatting
---------------
.. autosummary::
:toctree: generated/
TimeFormatter
NoteFormatter
SvaraFormatter
FJSFormatter
LogHzFormatter
ChromaFormatter
ChromaSvaraFormatter
ChromaFJSFormatter
TonnetzFormatter
Miscellaneous
-------------
.. autosummary::
:toctree: generated/
cmap
AdaptiveWaveplot
"""
from __future__ import annotations
from itertools import product
import warnings
import numpy as np
from matplotlib import colormaps as mcm
import matplotlib.axes as mplaxes
import matplotlib.ticker as mplticker
import matplotlib.pyplot as plt
from . import core
from . import util
from .util.deprecation import rename_kw, Deprecated
from .util.exceptions import ParameterError
from typing import TYPE_CHECKING, Any, Collection, Optional, Union, Callable, Dict
from ._typing import _FloatLike_co
if TYPE_CHECKING:
import matplotlib
from matplotlib.collections import QuadMesh, PolyCollection
from matplotlib.lines import Line2D
from matplotlib.path import Path as MplPath
from matplotlib.markers import MarkerStyle
from matplotlib.colors import Colormap
__all__ = [
"specshow",
"waveshow",
"cmap",
"TimeFormatter",
"NoteFormatter",
"FJSFormatter",
"LogHzFormatter",
"ChromaFormatter",
"ChromaSvaraFormatter",
"ChromaFJSFormatter",
"TonnetzFormatter",
"AdaptiveWaveplot",
]
# mypy: disable-error-code="attr-defined"
class TimeFormatter(mplticker.Formatter):
"""A tick formatter for time axes.
Automatically switches between seconds, minutes:seconds,
or hours:minutes:seconds.
Parameters
----------
lag : bool
If ``True``, then the time axis is interpreted in lag coordinates.
Anything past the midpoint will be converted to negative time.
unit : str or None
Abbreviation of the string representation for axis labels and ticks.
List of supported units:
* `"h"`: hour-based format (`H:MM:SS`)
* `"m"`: minute-based format (`M:SS`)
* `"s"`: second-based format (`S.sss` in scientific notation)
* `"ms"`: millisecond-based format (`s.¡¡¡` in scientific notation)
* `None`: adaptive to the duration of the underlying time range: similar
to `"h"` above 3600 seconds; to `"m"` between 60 and 3600 seconds; to
`"s"` between 1 and 60 seconds; and to `"ms"` below 1 second.
See Also
--------
matplotlib.ticker.Formatter
Examples
--------
For normal time
>>> import matplotlib.pyplot as plt
>>> times = np.arange(30)
>>> values = np.random.randn(len(times))
>>> fig, ax = plt.subplots()
>>> ax.plot(times, values)
>>> ax.xaxis.set_major_formatter(librosa.display.TimeFormatter())
>>> ax.set(xlabel='Time')
Manually set the physical time unit of the x-axis to milliseconds
>>> times = np.arange(100)
>>> values = np.random.randn(len(times))
>>> fig, ax = plt.subplots()
>>> ax.plot(times, values)
>>> ax.xaxis.set_major_formatter(librosa.display.TimeFormatter(unit='ms'))
>>> ax.set(xlabel='Time (ms)')
For lag plots
>>> times = np.arange(60)
>>> values = np.random.randn(len(times))
>>> fig, ax = plt.subplots()
>>> ax.plot(times, values)
>>> ax.xaxis.set_major_formatter(librosa.display.TimeFormatter(lag=True))
>>> ax.set(xlabel='Lag')
"""
def __init__(self, lag: bool = False, unit: Optional[str] = None):
if unit not in ["h", "m", "s", "ms", None]:
raise ParameterError(f"Unknown time unit: {unit}")
self.unit = unit
self.lag = lag
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Return the time format as pos"""
_, dmax = self.axis.get_data_interval()
vmin, vmax = self.axis.get_view_interval()
# In lag-time axes, anything greater than dmax / 2 is negative time
if self.lag and x >= dmax * 0.5:
# In lag mode, don't tick past the limits of the data
if x > dmax:
return ""
value = np.abs(x - dmax)
# Do we need to tweak vmin/vmax here?
sign = "-"
else:
value = x
sign = ""
if self.unit == "h" or ((self.unit is None) and (vmax - vmin > 3600)):
s = "{:d}:{:02d}:{:02d}".format(
int(value / 3600.0),
int(np.mod(value / 60.0, 60)),
int(np.mod(value, 60)),
)
elif self.unit == "m" or ((self.unit is None) and (vmax - vmin > 60)):
s = "{:d}:{:02d}".format(int(value / 60.0), int(np.mod(value, 60)))
elif self.unit == "s":
s = f"{value:.3g}"
elif self.unit == None and (vmax - vmin >= 1):
s = f"{value:.2g}"
elif self.unit == "ms":
s = "{:.3g}".format(value * 1000)
elif self.unit == None and (vmax - vmin < 1):
s = f"{value:.3f}"
return f"{sign:s}{s:s}"
class NoteFormatter(mplticker.Formatter):
"""Ticker formatter for Notes
Parameters
----------
octave : bool
If ``True``, display the octave number along with the note name.
Otherwise, only show the note name (and cent deviation)
major : bool
If ``True``, ticks are always labeled.
If ``False``, ticks are only labeled if the span is less than 2 octaves
key : str
Key for determining pitch spelling.
unicode : bool
If ``True``, use unicode symbols for accidentals.
If ``False``, use ASCII symbols for accidentals.
See Also
--------
LogHzFormatter
matplotlib.ticker.Formatter
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = librosa.midi_to_hz(np.arange(48, 72))
>>> fig, ax = plt.subplots(nrows=2)
>>> ax[0].bar(np.arange(len(values)), values)
>>> ax[0].set(ylabel='Hz')
>>> ax[1].bar(np.arange(len(values)), values)
>>> ax[1].yaxis.set_major_formatter(librosa.display.NoteFormatter())
>>> ax[1].set(ylabel='Note')
"""
def __init__(
self,
octave: bool = True,
major: bool = True,
key: str = "C:maj",
unicode: bool = True,
):
self.octave = octave
self.major = major
self.key = key
self.unicode = unicode
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Apply the formatter to position"""
if x <= 0:
return ""
# Only use cent precision if our vspan is less than an octave
vmin, vmax = self.axis.get_view_interval()
if not self.major and vmax > 4 * max(1, vmin):
return ""
cents = vmax <= 2 * max(1, vmin)
return core.hz_to_note(
x, octave=self.octave, cents=cents, key=self.key, unicode=self.unicode
)
class SvaraFormatter(mplticker.Formatter):
"""Ticker formatter for Svara
Parameters
----------
octave : bool
If ``True``, display the octave number along with the note name.
Otherwise, only show the note name (and cent deviation)
major : bool
If ``True``, ticks are always labeled.
If ``False``, ticks are only labeled if the span is less than 2 octaves
Sa : number > 0
Frequency (in Hz) of Sa
mela : str or int
For Carnatic svara, the index or name of the melakarta raga in question
To use Hindustani svara, set ``mela=None``
unicode : bool
If ``True``, use unicode symbols for accidentals.
If ``False``, use ASCII symbols for accidentals.
See Also
--------
NoteFormatter
matplotlib.ticker.Formatter
librosa.hz_to_svara_c
librosa.hz_to_svara_h
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = librosa.midi_to_hz(np.arange(48, 72))
>>> fig, ax = plt.subplots(nrows=2)
>>> ax[0].bar(np.arange(len(values)), values)
>>> ax[0].set(ylabel='Hz')
>>> ax[1].bar(np.arange(len(values)), values)
>>> ax[1].yaxis.set_major_formatter(librosa.display.SvaraFormatter(261))
>>> ax[1].set(ylabel='Note')
"""
def __init__(
self,
Sa: float,
octave: bool = True,
major: bool = True,
abbr: bool = False,
mela: Optional[Union[str, int]] = None,
unicode: bool = True,
):
if Sa is None:
raise ParameterError(
"Sa frequency is required for svara display formatting"
)
self.Sa = Sa
self.octave = octave
self.major = major
self.abbr = abbr
self.mela = mela
self.unicode = unicode
def __call__(self, x: float, pos: Optional[int] = None) -> str:
if x <= 0:
return ""
# Only use cent precision if our vspan is less than an octave
vmin, vmax = self.axis.get_view_interval()
if not self.major and vmax > 4 * max(1, vmin):
return ""
if self.mela is None:
return core.hz_to_svara_h(
x, Sa=self.Sa, octave=self.octave, abbr=self.abbr, unicode=self.unicode
)
else:
return core.hz_to_svara_c(
x,
Sa=self.Sa,
mela=self.mela,
octave=self.octave,
abbr=self.abbr,
unicode=self.unicode,
)
class FJSFormatter(mplticker.Formatter):
"""Ticker formatter for Functional Just System (FJS) notation
Parameters
----------
fmin : float
The unison frequency for this axis
intervals : str or array of float in [1, 2)
The interval specification for the frequency axis.
See `core.interval_frequencies` for supported values.
major : bool
If ``True``, ticks are always labeled.
If ``False``, ticks are only labeled if the span is less than 2 octaves
unison : str
The unison note name. If not provided, it will be inferred from fmin.
unicode : bool
If ``True``, use unicode symbols for accidentals.
If ``False``, use ASCII symbols for accidentals.
See Also
--------
NoteFormatter
hz_to_fjs
matplotlib.ticker.Formatter
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = librosa.midi_to_hz(np.arange(48, 72))
>>> fig, ax = plt.subplots(nrows=2)
>>> ax[0].bar(np.arange(len(values)), values)
>>> ax[0].set(ylabel='Hz')
>>> ax[1].bar(np.arange(len(values)), values)
>>> ax[1].yaxis.set_major_formatter(librosa.display.NoteFormatter())
>>> ax[1].set(ylabel='Note')
"""
def __init__(
self,
*,
fmin: int,
n_bins: int,
bins_per_octave: int,
intervals: Union[str, Collection[float]],
major: bool = True,
unison: Optional[str] = None,
unicode: bool = True,
):
self.fmin = fmin
self.major = major
self.unison = unison
self.unicode = unicode
self.intervals = intervals
self.n_bins = n_bins
self.bins_per_octave = bins_per_octave
self.frequencies_ = core.interval_frequencies(
n_bins, fmin=fmin, intervals=intervals, bins_per_octave=bins_per_octave
)
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Apply the formatter to position"""
if x <= 0:
return ""
# Only use cent precision if our vspan is less than an octave
vmin, vmax = self.axis.get_view_interval()
if not self.major and vmax > 4 * max(1, vmin):
return ""
# Map the given frequency to the nearest JI interval
idx = util.match_events(np.atleast_1d(x), self.frequencies_)[0]
label: str = core.hz_to_fjs(
self.frequencies_[idx],
fmin=self.fmin,
unison=self.unison,
unicode=self.unicode,
)
return label
class LogHzFormatter(mplticker.Formatter):
"""Ticker formatter for logarithmic frequency
Parameters
----------
major : bool
If ``True``, ticks are always labeled.
If ``False``, ticks are only labeled if the span is less than 2 octaves
See Also
--------
NoteFormatter
matplotlib.ticker.Formatter
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = librosa.midi_to_hz(np.arange(48, 72))
>>> fig, ax = plt.subplots(nrows=2)
>>> ax[0].bar(np.arange(len(values)), values)
>>> ax[0].yaxis.set_major_formatter(librosa.display.LogHzFormatter())
>>> ax[0].set(ylabel='Hz')
>>> ax[1].bar(np.arange(len(values)), values)
>>> ax[1].yaxis.set_major_formatter(librosa.display.NoteFormatter())
>>> ax[1].set(ylabel='Note')
"""
def __init__(self, major: bool = True):
self.major = major
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Apply the formatter to position"""
if x <= 0:
return ""
vmin, vmax = self.axis.get_view_interval()
if not self.major and vmax > 4 * max(1, vmin):
return ""
return f"{x:g}"
class ChromaFormatter(mplticker.Formatter):
"""A formatter for chroma axes
See Also
--------
matplotlib.ticker.Formatter
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = np.arange(12)
>>> fig, ax = plt.subplots()
>>> ax.plot(values)
>>> ax.yaxis.set_major_formatter(librosa.display.ChromaFormatter())
>>> ax.set(ylabel='Pitch class')
"""
def __init__(self, key: str = "C:maj", unicode: bool = True):
self.key = key
self.unicode = unicode
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Format for chroma positions"""
return core.midi_to_note(
int(x), octave=False, cents=False, key=self.key, unicode=self.unicode
)
class ChromaSvaraFormatter(mplticker.Formatter):
"""A formatter for chroma axes with svara instead of notes.
If mela is given, Carnatic svara names will be used.
Otherwise, Hindustani svara names will be used.
If `Sa` is not given, it will default to 0 (equivalent to `C`).
See Also
--------
ChromaFormatter
"""
def __init__(
self,
Sa: Optional[float] = None,
mela: Optional[Union[int, str]] = None,
abbr: bool = True,
unicode: bool = True,
):
if Sa is None:
Sa = 0
self.Sa = Sa
self.mela = mela
self.abbr = abbr
self.unicode = unicode
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Format for chroma positions"""
if self.mela is not None:
return core.midi_to_svara_c(
int(x),
Sa=self.Sa,
mela=self.mela,
octave=False,
abbr=self.abbr,
unicode=self.unicode,
)
else:
return core.midi_to_svara_h(
int(x), Sa=self.Sa, octave=False, abbr=self.abbr, unicode=self.unicode
)
class ChromaFJSFormatter(mplticker.Formatter):
"""A formatter for chroma axes with functional just notation
See Also
--------
matplotlib.ticker.Formatter
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = np.arange(12)
>>> fig, ax = plt.subplots()
>>> ax.plot(values)
>>> ax.yaxis.set_major_formatter(librosa.display.ChromaFJSFormatter(intervals="ji5", bins_per_octave=12))
>>> ax.set(ylabel='Pitch class')
"""
def __init__(
self,
*,
intervals: Union[str, Collection[float]],
unison: str = "C",
unicode: bool = True,
bins_per_octave: Optional[int] = None,
):
self.unison = unison
self.unicode = unicode
self.intervals = intervals
try:
if not isinstance(intervals, str):
bins_per_octave = len(intervals)
if not isinstance(bins_per_octave, int):
raise ParameterError(
f"bins_per_octave={bins_per_octave} must be integer-valued"
)
self.bins_per_octave: int = bins_per_octave
# Construct the explicit interval set
self.intervals_ = core.interval_frequencies(
self.bins_per_octave,
fmin=1,
intervals=intervals,
bins_per_octave=self.bins_per_octave,
)
except TypeError as exc:
raise ParameterError(
f"intervals={intervals} must be of type str or a collection of numbers between 1 and 2"
) from exc
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Format for chroma positions"""
lab: str = core.interval_to_fjs(
self.intervals_[int(x) % self.bins_per_octave],
unison=self.unison,
unicode=self.unicode,
)
return lab
class TonnetzFormatter(mplticker.Formatter):
"""A formatter for tonnetz axes
See Also
--------
matplotlib.ticker.Formatter
Examples
--------
>>> import matplotlib.pyplot as plt
>>> values = np.arange(6)
>>> fig, ax = plt.subplots()
>>> ax.plot(values)
>>> ax.yaxis.set_major_formatter(librosa.display.TonnetzFormatter())
>>> ax.set(ylabel='Tonnetz')
"""
def __call__(self, x: float, pos: Optional[int] = None) -> str:
"""Format for tonnetz positions"""
return [r"5$_x$", r"5$_y$", r"m3$_x$", r"m3$_y$", r"M3$_x$", r"M3$_y$"][int(x)]
class AdaptiveWaveplot:
"""A helper class for managing adaptive wave visualizations.
This object is used to dynamically switch between sample-based and envelope-based
visualizations of waveforms.
When the display is zoomed in such that no more than `max_samples` would be
visible, the sample-based display is used.
When displaying the raw samples would require more than `max_samples`, an
envelope-based plot is used instead.
You should never need to instantiate this object directly, as it is constructed
automatically by `waveshow`.
Parameters
----------
times : np.ndarray
An array containing the time index (in seconds) for each sample.
y : np.ndarray
An array containing the (monophonic) wave samples.
steps : matplotlib.lines.Line2D
The matplotlib artist used for the sample-based visualization.
This is constructed by `matplotlib.pyplot.step`.
envelope : matplotlib.collections.PolyCollection
The matplotlib artist used for the envelope-based visualization.
This is constructed by `matplotlib.pyplot.fill_between`.
sr : number > 0
The sampling rate of the audio
max_samples : int > 0
The maximum number of samples to use for sample-based display.
transpose : bool
If `True`, display the wave vertically instead of horizontally.
See Also
--------
waveshow
"""
def __init__(
self,
times: np.ndarray,
y: np.ndarray,
steps: Line2D,
envelope: PolyCollection,
sr: float = 22050,
max_samples: int = 11025,
transpose: bool = False,
):
self.times = times
self.samples = y
self.steps = steps
self.envelope = envelope
self.sr = sr
self.max_samples = max_samples
self.transpose = transpose
self.cid: Optional[int] = None
self.ax: Optional[mplaxes.Axes] = None
def __del__(self) -> None:
"""Disconnect callback methods on delete"""
self.disconnect(strict=True)
def connect(
self,
ax: mplaxes.Axes,
*,
signal: str = "xlim_changed",
) -> None:
"""Connect the adaptor to a signal on an axes object.
Note that if the adaptor has already been connected to an axes object,
that connect is first broken and then replaced by a new callback.
Parameters
----------
ax : matplotlib.axes.Axes
The axes to connect with this adaptor's `update`
signal : string, {"xlim_changed", "ylim_changed"}
The signal to connect
See Also
--------
disconnect
"""
# Disconnect any existing callback first
self.disconnect()
# Attach to axes and store the connection id
self.ax = ax
self.cid = ax.callbacks.connect(signal, self.update)
def disconnect(self, *, strict: bool = False) -> None:
"""Disconnect the adaptor's update callback.
Parameters
----------
strict : bool
If `True`, remove references to the connected axes.
If `False` (default), only disconnect the callback.
This functionality is intended primarily for internal use,
and should have no observable effects for users.
See Also
--------
connect
"""
if self.ax:
self.ax.callbacks.disconnect(self.cid)
self.cid = None
if strict:
self.ax = None
def update(self, ax: mplaxes.Axes) -> None:
"""Update the matplotlib display according to the current viewport limits.
This is a callback function, and should not be used directly.
Parameters
----------
ax : matplotlib.axes.Axes
The axes object to update
"""
lims = ax.viewLim
if self.transpose:
dim = lims.height * self.sr
start, end = lims.y0, lims.y1
xdata, ydata = self.samples, self.times
data = self.steps.get_ydata()
else:
dim = lims.width * self.sr
start, end = lims.x0, lims.x1
xdata, ydata = self.times, self.samples
data = self.steps.get_xdata()
# Does our width cover fewer than max_samples?
# If so, then use the sample-based plot
if dim <= self.max_samples:
self.envelope.set_visible(False)
self.steps.set_visible(True)
# Now check our viewport
if start <= data[0] or end >= data[-1]:
# Viewport expands beyond current data in steps; update
# we want to cover a window of self.max_samples centered on the current viewport
midpoint_time = (start + end) / 2
idx_start = np.searchsorted(
self.times, midpoint_time - 0.5 * self.max_samples / self.sr
)
self.steps.set_data(
xdata[idx_start : idx_start + self.max_samples],
ydata[idx_start : idx_start + self.max_samples],
)
else:
# Otherwise, use the envelope plot
self.envelope.set_visible(True)
self.steps.set_visible(False)
ax.figure.canvas.draw_idle()
def cmap(
data: np.ndarray,
*,
robust: bool = True,
cmap_seq: str = "magma",
cmap_bool: str = "gray_r",
cmap_div: str = "coolwarm",
) -> Colormap:
"""Get a default colormap from the given data.
If the data is boolean, use a black and white colormap.
If the data has both positive and negative values,
use a diverging colormap.
Otherwise, use a sequential colormap.
Parameters
----------
data : np.ndarray
Input data
robust : bool
If True, discard the top and bottom 2% of data when calculating
range.
cmap_seq : str
The sequential colormap name
cmap_bool : str
The boolean colormap name
cmap_div : str
The diverging colormap name
Returns
-------
cmap : matplotlib.colors.Colormap
The colormap to use for ``data``
See Also
--------
matplotlib.pyplot.colormaps
"""
data = np.atleast_1d(data)
if data.dtype == "bool":
return mcm[cmap_bool]
data = data[np.isfinite(data)]
if robust:
min_p, max_p = 2, 98
else:
min_p, max_p = 0, 100
min_val, max_val = np.percentile(data, [min_p, max_p])
if min_val >= 0 or max_val <= 0:
return mcm[cmap_seq]
return mcm[cmap_div]
def __envelope(x, hop):
"""Compute the max-envelope of non-overlapping frames of x at length hop
x is assumed to be multi-channel, of shape (n_channels, n_samples).
"""
x_frame = np.abs(util.frame(x, frame_length=hop, hop_length=hop))
return x_frame.max(axis=1)
_chroma_ax_types = (
"chroma",
"chroma_h",
"chroma_c",
"chroma_fjs",
)
_cqt_ax_types = (
"cqt_hz",
"cqt_note",
"cqt_svara",
)
_freq_ax_types = (
"linear",
"fft",
"hz",
"fft_note",
"fft_svara",
)
_time_ax_types = (
"time",
"h",
"m",
"s",
"ms",
)
_lag_ax_types = (
"lag",
"lag_h",
"lag_m",
"lag_s",
"lag_ms",
)
_misc_ax_types = (
"tempo",
"fourier_tempo",
"mel",
"log",
"tonnetz",
"frames",
)
_AXIS_COMPAT = set(
[(t, t) for t in _misc_ax_types]
+ [t for t in product(_chroma_ax_types, _chroma_ax_types)]
+ [t for t in product(_cqt_ax_types, _cqt_ax_types)]
+ [t for t in product(_freq_ax_types, _freq_ax_types)]
+ [t for t in product(_time_ax_types, _time_ax_types)]
+ [t for t in product(_lag_ax_types, _lag_ax_types)]
)
def specshow(
data: np.ndarray,
*,
x_coords: Optional[np.ndarray] = None,
y_coords: Optional[np.ndarray] = None,
x_axis: Optional[str] = None,
y_axis: Optional[str] = None,
sr: float = 22050,
hop_length: int = 512,
n_fft: Optional[int] = None,
win_length: Optional[int] = None,
fmin: Optional[float] = None,
fmax: Optional[float] = None,
tempo_min: Optional[float] = 16,
tempo_max: Optional[float] = 480,
tuning: float = 0.0,
bins_per_octave: int = 12,
key: str = "C:maj",
Sa: Optional[Union[float, int]] = None,
mela: Optional[Union[str, int]] = None,
thaat: Optional[str] = None,
auto_aspect: bool = True,
htk: bool = False,
unicode: bool = True,
intervals: Optional[Union[str, np.ndarray]] = None,
unison: Optional[str] = None,
ax: Optional[mplaxes.Axes] = None,
**kwargs: Any,
) -> QuadMesh:
"""Display a spectrogram/chromagram/cqt/etc.
For a detailed overview of this function, see :ref:`sphx_glr_auto_examples_plot_display.py`
Parameters
----------
data : np.ndarray [shape=(d, n)]
Matrix to display (e.g., spectrogram)
sr : number > 0 [scalar]
Sample rate used to determine time scale in x-axis.
hop_length : int > 0 [scalar]
Hop length, also used to determine time scale in x-axis
n_fft : int > 0 or None
Number of samples per frame in STFT/spectrogram displays.
By default, this will be inferred from the shape of ``data``
as ``2 * (d - 1)``.
If ``data`` was generated using an odd frame length, the correct
value can be specified here.
win_length : int > 0 or None
The number of samples per window.
By default, this will be inferred to match ``n_fft``.
This is primarily useful for specifying odd window lengths in
Fourier tempogram displays.
x_axis, y_axis : None or str
Range for the x- and y-axes.
Valid types are:
- None, 'none', or 'off' : no axis decoration is displayed.
Frequency types:
- 'linear', 'fft', 'hz' : frequency range is determined by
the FFT window and sampling rate.
- 'log' : the spectrum is displayed on a log scale.
- 'fft_note': the spectrum is displayed on a log scale with pitches marked.
- 'fft_svara': the spectrum is displayed on a log scale with svara marked.
- 'mel' : frequencies are determined by the mel scale.
- 'cqt_hz' : frequencies are determined by the CQT scale.
- 'cqt_note' : pitches are determined by the CQT scale.
- 'cqt_svara' : like `cqt_note` but using Hindustani or Carnatic svara
- 'vqt_fjs' : like `cqt_note` but using Functional Just System (FJS)
notation. This requires a just intonation-based variable-Q