|
| 1 | +import matplotlib.pyplot as plt |
| 2 | +import numpy as np |
| 3 | +from IPython.lib.display import Audio |
| 4 | +from scipy.io import wavfile |
| 5 | +from scipy.fftpack import fft, fftfreq |
| 6 | +import logging |
| 7 | +from tempfile import mkdtemp |
| 8 | +import os.path as path |
| 9 | +import sys |
| 10 | + |
| 11 | +logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w', |
| 12 | + format='%(levelname)s - %(name)s: %(message)s') |
| 13 | + |
| 14 | +class Hn: |
| 15 | + def __init__(self, **kwargs): |
| 16 | + self.data = [] |
| 17 | + self.name = 'H[n]' |
| 18 | + self.path = None |
| 19 | + self.points = [[], []] |
| 20 | + if kwargs['path'] != '': |
| 21 | + self.path = kwargs['path'] |
| 22 | + file = open(self.path, 'r') |
| 23 | + for line in file: |
| 24 | + self.data += [float(line)] |
| 25 | + elif kwargs['data']: |
| 26 | + self.data = kwargs['data'] |
| 27 | + elif kwargs['path'] != '' and kwargs['data']: |
| 28 | + logging.debug('please insert a path or array of data') |
| 29 | + raise AttributeError('please insert a path or array of data') |
| 30 | + else: |
| 31 | + logging.debug('please insert a path or array of data') |
| 32 | + raise AttributeError('please insert a path or array of data') |
| 33 | + logging.info('Hn = {}'.format(str(self.data))) |
| 34 | + |
| 35 | + for i in range(len(self.data)): |
| 36 | + self.points[0] += [i] |
| 37 | + self.points[1] += [self.data[i]] |
| 38 | + |
| 39 | + def draw(self): |
| 40 | + plt.title(self.name) |
| 41 | + plt.plot(self.points[0], self.points[1]) |
| 42 | + plt.xlabel('Time (s)') |
| 43 | + plt.ylabel('Amplitude') |
| 44 | + plt.savefig('{}'.format(self.name)) |
| 45 | + plt.grid(True) |
| 46 | + plt.show() |
| 47 | + |
| 48 | + def draw_phase(self): |
| 49 | + plt.title(self.name + 'Phase spectrum') |
| 50 | + plt.phase_spectrum(self.points[1]) |
| 51 | + plt.savefig('{} Phase spectrum'.format(self.name)) |
| 52 | + plt.grid(True) |
| 53 | + plt.show() |
| 54 | + |
| 55 | + def __str__(self): |
| 56 | + return self.data |
| 57 | + |
| 58 | + |
| 59 | +class Noise: |
| 60 | + def __init__(self, **kwargs): |
| 61 | + self.data = [] |
| 62 | + self.sample_rate = 0 |
| 63 | + self.fft = [] |
| 64 | + self.frame = 0 |
| 65 | + self.path = None |
| 66 | + |
| 67 | + if kwargs['path']: |
| 68 | + self.path = kwargs['path'] |
| 69 | + self.parse_wav() |
| 70 | + elif kwargs['data'] is not None: |
| 71 | + self.data = kwargs['data'] |
| 72 | + self.sample_rate = 32000 |
| 73 | + logging.info('noise data = {}'.format(self.data)) |
| 74 | + elif kwargs['path'] != '' and kwargs['data']: |
| 75 | + logging.debug('please insert a path or array of data') |
| 76 | + raise AttributeError('please insert a path or array of data') |
| 77 | + else: |
| 78 | + logging.debug('please insert a path or array of data') |
| 79 | + raise AttributeError('please insert a path or array of data') |
| 80 | + |
| 81 | + try: |
| 82 | + self.name = kwargs['name'] |
| 83 | + except: |
| 84 | + self.name = 'Unknown' if self.path is None else self.path |
| 85 | + |
| 86 | + logging.info('{} noise created.'.format(self.name)) |
| 87 | + |
| 88 | + def parse_wav(self): |
| 89 | + sample_rate, data = wavfile.read(self.path, 'r') |
| 90 | + self.data = data |
| 91 | + self.sample_rate = sample_rate |
| 92 | + logging.info('noise sample rate = {}'.format(self.sample_rate)) |
| 93 | + logging.info('noise data = {}'.format(self.data)) |
| 94 | + return self.data |
| 95 | + |
| 96 | + def init_fft(self): |
| 97 | + self.fft = fft(self.data) |
| 98 | + |
| 99 | + def get_fft(self): |
| 100 | + self.init_fft() |
| 101 | + return self.fft |
| 102 | + |
| 103 | + def get_energy(self): |
| 104 | + return np.sum((np.abs(self.data) ** 2)) / len(self.data) |
| 105 | + |
| 106 | + def get_duration(self): |
| 107 | + return len(self.data) / float(self.sample_rate) |
| 108 | + |
| 109 | + def get_slice(self, slc): |
| 110 | + length = len(self.data) |
| 111 | + mul = (slc / self.get_duration()) * length |
| 112 | + index = int(mul) |
| 113 | + return Noise(name='{}s of {}'.format(slc, self.name), data=self.data[0:index], path='') |
| 114 | + |
| 115 | + def get_max(self): |
| 116 | + return np.amax(self.data) |
| 117 | + |
| 118 | + def when_max(self): |
| 119 | + length = len(self.data) |
| 120 | + index = np.where(self.data == self.get_max()) |
| 121 | + when = ((index[0] * self.get_duration()) / length)[0] |
| 122 | + logging.info('{} at {}s is max'.format(self.name, when)) |
| 123 | + return when |
| 124 | + |
| 125 | + def shift_right(self, slc): |
| 126 | + if slc < 0: |
| 127 | + return self.shift_left(abs(slc)) |
| 128 | + amount = int(slc * self.sample_rate) |
| 129 | + filename = path.join(mkdtemp(), 'newfile.dat') |
| 130 | + fpath = np.memmap(filename, dtype='float64', mode='w+', shape=len(self.data)) |
| 131 | + fpath[amount:] = self.data[:-amount] |
| 132 | + logging.info('{} {} shifted right'.format(self.name, amount)) |
| 133 | + return Noise(name='{} time shifted right {}'.format(amount, self.name), |
| 134 | + data=fpath, path='') |
| 135 | + |
| 136 | + def shift_left(self, slc): |
| 137 | + if slc < 0: |
| 138 | + return self.shift_right(abs(slc)) |
| 139 | + amount = int(slc * self.sample_rate) |
| 140 | + filename = path.join(mkdtemp(), 'newfile.dat') |
| 141 | + fpath = np.memmap(filename, dtype='float64', mode='w+', shape=len(self.data)) |
| 142 | + fpath[:-amount] = self.data[amount:] |
| 143 | + logging.info('{} {} shifted left'.format(self.name, amount)) |
| 144 | + return Noise(name='{} time shifted left {}'.format(amount, self.name), |
| 145 | + data=fpath, path='') |
| 146 | + |
| 147 | + def reverse(self): |
| 148 | + self.data = [ele for ele in reversed(self.data)] |
| 149 | + |
| 150 | + def draw(self): |
| 151 | + plt.figure(self.name, figsize=(12, 5)) |
| 152 | + plt.title(self.name + ' Noise') |
| 153 | + time = np.arange(0, self.get_duration(), 1 / self.sample_rate) # time vector |
| 154 | + plt.plot(time, self.data) |
| 155 | + plt.xlabel('Time (s)') |
| 156 | + plt.ylabel('Amplitude') |
| 157 | + plt.grid(True) |
| 158 | + plt.show() |
| 159 | + |
| 160 | + def draw_fft(self): |
| 161 | + self.init_fft() |
| 162 | + plt.figure(self.name + ' FFT') |
| 163 | + plt.plot(self.fft) |
| 164 | + plt.xlim([10, self.sample_rate / 2]) |
| 165 | + plt.xscale('log') |
| 166 | + plt.grid(True) |
| 167 | + plt.xlabel('Frequency (Hz)') |
| 168 | + plt.show() |
| 169 | + |
| 170 | + def draw_all(self): |
| 171 | + plt.figure(self.name) |
| 172 | + plt.plot(self.data) |
| 173 | + plt.grid(True) |
| 174 | + plt.figure(self.name + ' FFT') |
| 175 | + plt.plot(self.fft) |
| 176 | + plt.xlim([10, self.sample_rate / 2]) |
| 177 | + plt.xscale('log') |
| 178 | + plt.grid(True) |
| 179 | + plt.xlabel('Frequency (Hz)') |
| 180 | + plt.show() |
| 181 | + |
| 182 | + def draw_phase(self): |
| 183 | + plt.title(self.name + 'Phase spectrum') |
| 184 | + plt.phase_spectrum(self.data) |
| 185 | + plt.show() |
| 186 | + |
| 187 | + def convolve(self, other): |
| 188 | + return Noise(name='{} * {}'.format(self.name, other.name), data=np.convolve(self.data, other.data), path='') |
| 189 | + |
| 190 | + def hear_noise(self): |
| 191 | + return Audio(data=self.data, rate=self.sample_rate) |
| 192 | + |
| 193 | + def __mul__(self, other): |
| 194 | + return self.convolve(other) |
| 195 | + |
| 196 | + def __str__(self): |
| 197 | + return self.data |
0 commit comments