This repository has been archived by the owner on Feb 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Spectrum.py
218 lines (174 loc) · 6.25 KB
/
Spectrum.py
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
"""
Spectrum class
ndarray subclass for spectral data
Last updated: 9 December 2012
"""
from __future__ import division
import math
import numpy
from numpy import *
import scipy.stats
import scipy.stats.mstats
import matplotlib.pyplot as plt
import pymir
from pymir import MFCC, Pitch, Transforms
class Spectrum(numpy.ndarray):
def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
strides=None, order=None):
# Create the ndarray instance of our type, given the usual
# ndarray input arguments. This will call the standard
# ndarray constructor, but return an object of our type.
# It also triggers a call to InfoArray.__array_finalize__
obj = numpy.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides,
order)
obj.sampleRate = 0
# Finally, we must return the newly created object:
return obj
def __array_finalize__(self, obj):
# ``self`` is a new object resulting from
# ndarray.__new__(InfoArray, ...), therefore it only has
# attributes that the ndarray.__new__ constructor gave it -
# i.e. those of a standard ndarray.
#
# We could have got to the ndarray.__new__ call in 3 ways:
# From an explicit constructor - e.g. InfoArray():
# obj is None
# (we're in the middle of the InfoArray.__new__
# constructor, and self.info will be set when we return to
# InfoArray.__new__)
if obj is None: return
# From view casting - e.g arr.view(InfoArray):
# obj is arr
# (type(obj) can be InfoArray)
# From new-from-template - e.g infoarr[:3]
# type(obj) is InfoArray
#
# Note that it is here, rather than in the __new__ method,
# that we set the default value for 'info', because this
# method sees all creation of default objects - with the
# InfoArray.__new__ constructor, but also with
# arr.view(InfoArray).
self.sampleRate = getattr(obj, 'sampleRate', None)
# We do not need to return anything
#####################
# Spectrum methods
#####################
def centroid(self):
"""
Compute the spectral centroid.
Characterizes the "center of gravity" of the spectrum.
Approximately related to timbral "brightness"
"""
binNumber = 0
numerator = 0
denominator = 0
for bin in self:
# Compute center frequency
f = (self.sampleRate / 2.0) / len(self)
f = f * binNumber
numerator = numerator + (f * abs(bin))
denominator = denominator + abs(bin)
binNumber = binNumber + 1
return (numerator * 1.0) / denominator
def chroma(self):
"""
Compute the 12-ET chroma vector from this spectrum
"""
return Pitch.chroma(self)
def crest(self):
"""
Compute the spectral crest factor, i.e. the ratio of the maximum of the spectrum to the
sum of the spectrum
"""
absSpectrum = abs(self)
spectralSum = numpy.sum(absSpectrum)
maxFrequencyIndex = numpy.argmax(absSpectrum)
maxSpectrum = absSpectrum[maxFrequencyIndex]
return maxSpectrum / spectralSum
def flatness(self):
"""
Compute the spectral flatness (ratio between geometric and arithmetic means)
"""
geometricMean = scipy.stats.mstats.gmean(abs(self))
arithmeticMean = self.mean()
return geometricMean / arithmeticMean
def idct(self):
"""
Compute the Inverse Discrete Cosine Transform (IDCT)
"""
return Transforms.idct(self)
def ifft(self):
"""
Compute the Inverse FFT
"""
return Transforms.ifft(self)
def kurtosis(self):
"""
Compute the spectral kurtosis (fourth spectral moment)
"""
return scipy.stats.kurtosis(abs(self))
def mean(self):
"""
Compute the spectral mean (first spectral moment)
"""
return numpy.sum(abs(self)) / len(self)
def mfcc(self, m, NumFilters = 48):
"""
Compute the Mth Mel-Frequency Cepstral Coefficient
"""
return MFCC.mfcc(self, m, NumFilters)
def mfcc2(self):
"""
Vectorized MFCC implementation
"""
return MFCC.mfcc2(self)
def plot(self):
"""
Plot the spectrum using matplotlib
"""
plt.plot(abs(self))
plt.xlim(0, len(self))
plt.show()
def rolloff(self):
"""
Determine the spectral rolloff, i.e. the frequency below which 85% of the spectrum's energy
is located
"""
absSpectrum = abs(self)
spectralSum = numpy.sum(absSpectrum)
rolloffSum = 0
rolloffIndex = 0
for i in range(0, len(self)):
rolloffSum = rolloffSum + absSpectrum[i]
if rolloffSum > (0.85 * spectralSum):
rolloffIndex = i
break
# Convert the index into a frequency
frequency = rolloffIndex * (self.sampleRate / 2.0) / len(self)
return frequency
def skewness(self):
"""
Compute the spectral skewness (third spectral moment)
"""
return scipy.stats.skew(abs(self))
def spread(self):
"""
Compute the spectral spread (basically a variance of the spectrum around the spectral centroid)
"""
centroid = self.centroid()
binNumber = 0
numerator = 0
denominator = 0
for bin in self:
# Compute center frequency
f = (self.sampleRate / 2.0) / len(self)
f = f * binNumber
numerator = numerator + (((f - centroid) ** 2) * abs(bin))
denominator = denominator + abs(bin)
binNumber = binNumber + 1
return math.sqrt((numerator * 1.0) / denominator)
def variance(self):
"""
Compute the spectral variance (second spectral moment)
"""
return numpy.var(abs(self))