- Timestamp:
- Jun 22, 2016, 1:00:10 PM (9 years ago)
- Branches:
- feature/autosink, feature/cnn, feature/cnn_org, feature/constantq, feature/crepe, feature/crepe_org, feature/pitchshift, feature/pydocstrings, feature/timestretch, fix/ffmpeg5, master, pitchshift, sampler, timestretch, yinfft+
- Children:
- 4b9443c4
- Parents:
- 60fc05b (diff), 6769586 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the(diff)
links above to see all the changes relative to each parent. - Location:
- python
- Files:
-
- 11 added
- 7 deleted
- 65 edited
Legend:
- Unmodified
- Added
- Removed
-
python/README
r60fc05b rf264b17 46 46 $ export PYTHONPATH=$PYTHONPATH:$PWD/`ls -rtd build/lib.* | head -1`:$PWD/tests 47 47 48 Similarly, you can use the aubio module without installing libaubio by pointing49 LD_LIBRARY_PATH to the path libaubio can be found at:50 51 $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:PWD/../build/src52 53 Or on Mac OS X systems, setting DYLD_LIBRARY_PATH:54 55 $ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$PWD/../build/src56 57 48 Testing the Python module 58 49 ------------------------- -
python/demos/demo_bpm_extract.py
r60fc05b rf264b17 4 4 from numpy import median, diff 5 5 6 def get_file_bpm(path, params = {}):6 def get_file_bpm(path, params = None): 7 7 """ Calculate the beats per minute (bpm) of a given file. 8 8 path: path to the file 9 9 param: dictionary of parameters 10 10 """ 11 if params is None: 12 params = {} 11 13 try: 12 14 win_s = params['win_s'] 13 15 samplerate = params['samplerate'] 14 16 hop_s = params['hop_s'] 15 except :17 except KeyError: 16 18 """ 17 19 # super fast … … 44 46 45 47 # Convert to periods and to bpm 46 bpms = 60./diff(beats) 47 b = median(bpms) 48 if len(beats) > 1: 49 if len(beats) < 4: 50 print("few beats found in {:s}".format(path)) 51 bpms = 60./diff(beats) 52 b = median(bpms) 53 else: 54 b = 0 55 print("not enough beats found in {:s}".format(path)) 48 56 return b 49 57 … … 52 60 for f in sys.argv[1:]: 53 61 bpm = get_file_bpm(f) 54 print "%6s" % ("%.2f" % bpm), f62 print("{:6s} {:s}".format("{:2f}".format(bpm), f)) -
python/demos/demo_filterbank.py
r60fc05b rf264b17 2 2 3 3 from aubio import filterbank, fvec 4 from pylab import loglog, show, subplot,xlim, ylim, xlabel, ylabel, title4 from pylab import loglog, show, xlim, ylim, xlabel, ylabel, title 5 5 from numpy import vstack, arange 6 6 … … 20 20 f.set_coeffs(coeffs) 21 21 22 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)22 times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters) 23 23 title('Bank of filters built using a simple list of boundaries\nThe middle band has been amplified by 2.') 24 24 loglog(times.T, f.get_coeffs().T, '.-') -
python/demos/demo_filterbank_slaney.py
r60fc05b rf264b17 2 2 3 3 from aubio import filterbank 4 from numpy import ar ray, arange, vstack4 from numpy import arange, vstack 5 5 6 6 win_s = 8192 … … 12 12 from pylab import loglog, title, show, xlim, ylim, xlabel, ylabel 13 13 xlim([0,samplerate / 2]) 14 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * 40)14 times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * 40) 15 15 loglog(times.T, f.get_coeffs().T, '.-') 16 16 title('Mel frequency bands coefficients') -
python/demos/demo_filterbank_triangle_bands.py
r60fc05b rf264b17 17 17 subplot(211) 18 18 title('Examples of filterbank built with set_triangle_bands and set_coeffs') 19 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)19 times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters) 20 20 loglog(times.T, f.get_coeffs().T, '.-') 21 21 xlim([50, samplerate/2]) … … 38 38 39 39 subplot(212) 40 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)40 times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters) 41 41 loglog(times.T, f.get_coeffs().T, '.-') 42 42 xlim([50, samplerate/2]) -
python/demos/demo_keyboard.py
r60fc05b rf264b17 26 26 27 27 def create_keyboard_patches(firstnote, lastnote, ax = None): 28 import numpy as np29 28 import matplotlib.pyplot as plt 30 29 from matplotlib.path import Path -
python/demos/demo_mel-energy.py
r60fc05b rf264b17 2 2 3 3 import sys 4 from aubio import fvec,source, pvoc, filterbank4 from aubio import source, pvoc, filterbank 5 5 from numpy import vstack, zeros 6 6 7 7 win_s = 512 # fft size 8 hop_s = win_s / 4# hop size8 hop_s = win_s // 4 # hop size 9 9 10 10 if len(sys.argv) < 2: 11 print "Usage: %s <filename> [samplerate]" % sys.argv[0]11 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 12 12 sys.exit(1) 13 13 … … 35 35 fftgrain = pv(samples) 36 36 new_energies = f(fftgrain) 37 print '%f' % (total_frames / float(samplerate) ),38 print ' '.join(['%f' % b for b in new_energies])37 timestr = '%f' % (total_frames / float(samplerate) ) 38 print('{:s} {:s}'.format(timestr, ' '.join(['%f' % b for b in new_energies]))) 39 39 energies = vstack( [energies, new_energies] ) 40 40 total_frames += read … … 42 42 43 43 if 1: 44 print "done computing, now plotting"44 print("done computing, now plotting") 45 45 import matplotlib.pyplot as plt 46 46 from demo_waveform_plot import get_waveform_plot -
python/demos/demo_mfcc.py
r60fc05b rf264b17 3 3 import sys 4 4 from aubio import source, pvoc, mfcc 5 from numpy import array,vstack, zeros5 from numpy import vstack, zeros 6 6 7 7 win_s = 512 # fft size 8 hop_s = win_s / 4# hop size8 hop_s = win_s // 4 # hop size 9 9 n_filters = 40 # must be 40 for mfcc 10 10 n_coeffs = 13 … … 12 12 13 13 if len(sys.argv) < 2: 14 print "Usage: %s <source_filename>" % sys.argv[0]14 print("Usage: %s <source_filename>" % sys.argv[0]) 15 15 sys.exit(1) 16 16 -
python/demos/demo_onset.py
r60fc05b rf264b17 5 5 6 6 win_s = 512 # fft size 7 hop_s = win_s / 2# hop size7 hop_s = win_s // 2 # hop size 8 8 9 9 if len(sys.argv) < 2: 10 print "Usage: %s <filename> [samplerate]" % sys.argv[0]10 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 11 11 sys.exit(1) 12 12 … … 29 29 samples, read = s() 30 30 if o(samples): 31 print "%f" % o.get_last_s()31 print("%f" % o.get_last_s()) 32 32 onsets.append(o.get_last()) 33 33 total_frames += read -
python/demos/demo_onset_plot.py
r60fc05b rf264b17 3 3 import sys 4 4 from aubio import onset, source 5 from numpy import array,hstack, zeros5 from numpy import hstack, zeros 6 6 7 7 win_s = 512 # fft size 8 hop_s = win_s / 2# hop size8 hop_s = win_s // 2 # hop size 9 9 10 10 if len(sys.argv) < 2: 11 print "Usage: %s <filename> [samplerate]" % sys.argv[0]11 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 12 12 sys.exit(1) 13 13 … … 35 35 samples, read = s() 36 36 if o(samples): 37 print "%f" % (o.get_last_s())37 print("%f" % (o.get_last_s())) 38 38 onsets.append(o.get_last()) 39 39 # keep some data to plot it later 40 new_maxes = (abs(samples.reshape(hop_s/ downsample, downsample))).max(axis=0)40 new_maxes = (abs(samples.reshape(hop_s//downsample, downsample))).max(axis=0) 41 41 allsamples_max = hstack([allsamples_max, new_maxes]) 42 42 desc.append(o.get_descriptor()) … … 47 47 if 1: 48 48 # do plotting 49 from numpy import arange50 49 import matplotlib.pyplot as plt 51 50 allsamples_max = (allsamples_max > 0) * allsamples_max … … 63 62 plt1.yaxis.set_visible(False) 64 63 desc_times = [ float(t) * hop_s / samplerate for t in range(len(desc)) ] 65 desc_plot = [d / max(desc) for d in desc] 64 desc_max = max(desc) if max(desc) != 0 else 1. 65 desc_plot = [d / desc_max for d in desc] 66 66 plt2.plot(desc_times, desc_plot, '-g') 67 tdesc_plot = [d / max(desc)for d in tdesc]67 tdesc_plot = [d / desc_max for d in tdesc] 68 68 for stamp in onsets: 69 69 stamp /= float(samplerate) -
python/demos/demo_pitch.py
r60fc05b rf264b17 2 2 3 3 import sys 4 from aubio import source, pitch , freqtomidi4 from aubio import source, pitch 5 5 6 6 if len(sys.argv) < 2: 7 print "Usage: %s <filename> [samplerate]" % sys.argv[0]7 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 8 8 sys.exit(1) 9 9 … … 11 11 12 12 downsample = 1 13 samplerate = 44100 / downsample13 samplerate = 44100 // downsample 14 14 if len( sys.argv ) > 2: samplerate = int(sys.argv[2]) 15 15 16 win_s = 4096 / downsample # fft size17 hop_s = 512 / downsample # hop size16 win_s = 4096 // downsample # fft size 17 hop_s = 512 // downsample # hop size 18 18 19 19 s = source(filename, samplerate, hop_s) … … 37 37 confidence = pitch_o.get_confidence() 38 38 #if confidence < 0.8: pitch = 0. 39 #print "%f %f %f" % (total_frames / float(samplerate), pitch, confidence)39 print("%f %f %f" % (total_frames / float(samplerate), pitch, confidence)) 40 40 pitches += [pitch] 41 41 confidences += [confidence] … … 46 46 47 47 #print pitches 48 import os.path 48 49 from numpy import array, ma 49 50 import matplotlib.pyplot as plt … … 64 65 65 66 def array_from_text_file(filename, dtype = 'float'): 66 import os.path67 from numpy import array68 67 filename = os.path.join(os.path.dirname(__file__), filename) 69 68 return array([line.split() for line in open(filename).readlines()], … … 71 70 72 71 ax2 = fig.add_subplot(312, sharex = ax1) 73 import sys, os.path74 72 ground_truth = os.path.splitext(filename)[0] + '.f0.Corrected' 75 73 if os.path.isfile(ground_truth): -
python/demos/demo_pitch_sinusoid.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy import random, sin, arange, ones, zeros 4 from math import pi 5 from aubio import fvec, pitch 3 import numpy as np 4 import aubio 6 5 7 6 def build_sinusoid(length, freqs, samplerate): 8 return sin( 2. * pi * arange(length) * freqs / samplerate)7 return np.sin( 2. * np.pi * np.arange(length) * freqs / samplerate).astype(aubio.float_type) 9 8 10 9 def run_pitch(p, input_vec): 11 f = fvec (p.hop_size) 12 cands = [] 13 count = 0 14 for vec_slice in input_vec.reshape((-1, p.hop_size)): 15 f[:] = vec_slice 16 cands.append(p(f)) 17 return cands 10 cands = [] 11 for vec_slice in input_vec.reshape((-1, p.hop_size)): 12 a = p(vec_slice)[0] 13 cands.append(a) 14 return cands 18 15 19 16 methods = ['default', 'schmitt', 'fcomb', 'mcomb', 'yin', 'yinfft'] … … 24 21 samplerate = 44100 25 22 sin_length = (samplerate * 10) % 512 * 512 26 freqs = zeros(sin_length)23 freqs = np.zeros(sin_length) 27 24 28 partition = sin_length / 825 partition = sin_length // 8 29 26 pointer = 0 30 27 … … 41 38 pointer += partition 42 39 pointer += partition 43 freqs[ pointer : pointer + partition ] = 400 + 5 * random.random(sin_length/8)40 freqs[ pointer : pointer + partition ] = 400 + 5 * np.random.random(sin_length/8) 44 41 45 42 a = build_sinusoid(sin_length, freqs, samplerate) 46 43 47 44 for method in methods: 48 p = pitch(method, buf_size, hop_size, samplerate) 49 cands[method] = run_pitch(p, a) 45 p = aubio.pitch(method, buf_size, hop_size, samplerate) 46 cands[method] = run_pitch(p, a) 47 print(method) 48 print(cands[method]) 50 49 51 print "done computing"50 print("done computing") 52 51 53 52 if 1: 54 from pylab import plot, show, xlabel, ylabel, legend, ylim 55 ramp = arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate 56 for method in methods: 57 plot(ramp, cands[method],'.-') 53 import matplotlib.pyplot as plt 58 54 59 # plot ground truth 60 ramp = arange(0, sin_length).astype('float') / samplerate 61 plot(ramp, freqs, ':') 55 # times 56 ramp = np.arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate 62 57 63 legend(methods+['ground truth'], 'upper right') 64 xlabel('time (s)') 65 ylabel('frequency (Hz)') 66 ylim([0,2000]) 67 show() 58 # plot each result 59 for method in methods: 60 plt.plot(ramp, cands[method], '.-', label=method) 68 61 62 # plot ground truth 63 ramp = np.arange(0, sin_length).astype('float') / samplerate 64 plt.plot(ramp, freqs, ':', label = 'ground truth') 65 66 plt.legend(loc='upper left') 67 68 plt.xlabel('time (s)') 69 plt.ylabel('frequency (Hz)') 70 plt.ylim([0,2000]) 71 plt.show() -
python/demos/demo_pysoundcard_play.py
r60fc05b rf264b17 11 11 samplerate = f.samplerate 12 12 13 s = Stream(sample _rate = samplerate, block_length= hop_size)13 s = Stream(samplerate = samplerate, blocksize = hop_size) 14 14 s.start() 15 15 read = 0 -
python/demos/demo_pysoundcard_record.py
r60fc05b rf264b17 9 9 hop_size = 256 10 10 duration = 5 # in seconds 11 s = Stream(block _length = hop_size)12 g = sink(sink_path, samplerate = s.sample_rate)11 s = Stream(blocksize = hop_size, channels = 1) 12 g = sink(sink_path, samplerate = int(s.samplerate)) 13 13 14 14 s.start() 15 15 total_frames = 0 16 while total_frames < duration * s.sample_rate: 17 vec = s.read(hop_size) 18 # mix down to mono 19 mono_vec = vec.sum(-1) / float(s.input_channels) 20 g(mono_vec, hop_size) 21 total_frames += hop_size 16 try: 17 while total_frames < duration * s.samplerate: 18 vec = s.read(hop_size) 19 # mix down to mono 20 mono_vec = vec.sum(-1) / float(s.channels[0]) 21 g(mono_vec, hop_size) 22 total_frames += hop_size 23 except KeyboardInterrupt: 24 duration = total_frames / float(s.samplerate) 25 print("stopped after %.2f seconds" % duration) 22 26 s.stop() 23 27 -
python/demos/demo_simple_robot_voice.py
r60fc05b rf264b17 5 5 6 6 if __name__ == '__main__': 7 if len(sys.argv) < 2:8 print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]9 sys.exit(1)10 samplerate = 4410011 f = source(sys.argv[1], samplerate, 256)12 g = sink(sys.argv[2], samplerate)13 total_frames, read = 0, 2567 if len(sys.argv) < 2: 8 print('usage: %s <inputfile> <outputfile>' % sys.argv[0]) 9 sys.exit(1) 10 samplerate = 44100 11 f = source(sys.argv[1], samplerate, 256) 12 g = sink(sys.argv[2], samplerate) 13 total_frames, read = 0, 256 14 14 15 win_s = 512# fft size16 hop_s = win_s / 2# hop size17 pv = pvoc(win_s, hop_s)# phase vocoder15 win_s = 512 # fft size 16 hop_s = win_s // 2 # hop size 17 pv = pvoc(win_s, hop_s) # phase vocoder 18 18 19 while read:20 samples, read = f()21 spectrum = pv(samples)# compute spectrum22 #spectrum.norm *= .8# reduce amplitude a bit23 spectrum.phas[:] = 0.# zero phase24 new_samples = pv.rdo(spectrum)# compute modified samples25 g(new_samples, read)# write to output26 total_frames += read19 while read: 20 samples, read = f() 21 spectrum = pv(samples) # compute spectrum 22 #spectrum.norm *= .8 # reduce amplitude a bit 23 spectrum.phas[:] = 0. # zero phase 24 new_samples = pv.rdo(spectrum) # compute modified samples 25 g(new_samples, read) # write to output 26 total_frames += read 27 27 28 print "wrote", total_frames, "from", f.uri, "to", g.uri 29 30 28 format_str = "read {:d} samples from {:s}, written to {:s}" 29 print(format_str.format(total_frames, f.uri, g.uri)) -
python/demos/demo_simple_spectral_weighting.py
r60fc05b rf264b17 14 14 if __name__ == '__main__': 15 15 if len(sys.argv) < 2: 16 print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]16 print('usage: %s <inputfile> <outputfile>' % sys.argv[0]) 17 17 sys.exit(1) 18 18 samplerate = 0 … … 23 23 24 24 win_s = 512 # fft size 25 hop_s = win_s / 2 # hop size25 hop_s = win_s // 2 # hop size 26 26 pv = pvoc(win_s, hop_s) # phase vocoder 27 27 … … 31 31 zeros( 50 ), 32 32 1.3 * hanningz(100), 33 zeros (win_s / 2 + 1 - 40 - 50 - 100),33 zeros (win_s // 2 + 1 - 40 - 50 - 100), 34 34 ] ) 35 35 … … 53 53 total_frames += read 54 54 55 print "read", total_frames / float(samplerate), "seconds from", f.uri 55 duration = total_frames / float(samplerate) 56 print("read {:.3f}s from {:s}".format(duration, f.uri)) -
python/demos/demo_sink.py
r60fc05b rf264b17 6 6 if __name__ == '__main__': 7 7 if len(sys.argv) < 3: 8 print 'usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0]8 print('usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0]) 9 9 sys.exit(1) 10 10 … … 23 23 g(vec, read) 24 24 total_frames += read 25 print "wrote", "%.2fs" % (total_frames / float(samplerate) ), 26 print "(", total_frames, "frames", "in", 27 print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")", 28 print "from", f.uri, 29 print "to", g.uri 25 outstr = "wrote %.2fs" % (total_frames / float(samplerate)) 26 outstr += " (%d frames in" % total_frames 27 outstr += " %d blocks" % (total_frames // f.hop_size) 28 outstr += " at %dHz)" % f.samplerate 29 outstr += " from " + f.uri 30 outstr += " to " + g.uri 31 print(outstr) -
python/demos/demo_sink_create_woodblock.py
r60fc05b rf264b17 3 3 import sys 4 4 from math import pi, e 5 from aubio import sink 6 from numpy import arange, resize,sin, exp, zeros5 from aubio import sink, float_type 6 from numpy import arange, sin, exp, zeros 7 7 8 8 if len(sys.argv) < 2: 9 print 'usage: %s <outputfile> [samplerate]' % sys.argv[0]9 print('usage: %s <outputfile> [samplerate]' % sys.argv[0]) 10 10 sys.exit(1) 11 11 … … 26 26 # create a sine lookup table 27 27 tablelen = 1000 28 sinetable = arange(tablelen + 1, dtype = 'float32')28 sinetable = arange(tablelen + 1, dtype = float_type) 29 29 sinetable = 0.7 * sin(twopi * sinetable/tablelen) 30 sinetone = zeros((duration,), dtype = 'float32')30 sinetone = zeros((duration,), dtype = float_type) 31 31 32 32 # compute sinetone at floating point period … … 40 40 41 41 # apply some envelope 42 float_ramp = arange(duration, dtype = 'float32')42 float_ramp = arange(duration, dtype = float_type) 43 43 sinetone *= exp( - e * float_ramp / duration / decay) 44 44 sinetone[:attack] *= exp( e * ( float_ramp[:attack] / attack - 1 ) ) -
python/demos/demo_sink_multi.py
r60fc05b rf264b17 6 6 if __name__ == '__main__': 7 7 if len(sys.argv) < 3: 8 print 'usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0]8 print('usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0]) 9 9 sys.exit(1) 10 10 … … 23 23 g.do_multi(vec, read) 24 24 total_frames += read 25 print "wrote", "%.2fs" % (total_frames / float(samplerate) ), 26 print "(", total_frames, "frames", "in", 27 print total_frames / f.hop_size, "blocks", 28 print "of", f.channels, "channels", 29 print "at", "%dHz" % f.samplerate, ")", 30 print "from", f.uri, 31 print "to", g.uri 25 outstr = "wrote %.2fs" % (total_frames / float(samplerate)) 26 outstr += " (%d frames in" % total_frames 27 outstr += " %d blocks" % (total_frames // f.hop_size) 28 outstr += " of %d channels" % f.channels 29 outstr += " at %dHz)" % f.samplerate 30 outstr += " from " + f.uri 31 outstr += " to " + g.uri 32 print(outstr) -
python/demos/demo_slicing.py
r60fc05b rf264b17 7 7 if __name__ == '__main__': 8 8 if len(sys.argv) < 3: 9 print 'usage: %s <inputfile> <duration>' % sys.argv[0]9 print('usage: %s <inputfile> <duration>' % sys.argv[0]) 10 10 sys.exit(1) 11 11 source_file = sys.argv[1] … … 45 45 total_duration = total_frames_written / float(samplerate) 46 46 slice_n += 1 47 print 'created %(slice_n)s slices from %(source_base_name)s%(source_ext)s' % locals(), 48 print ' (total duration %(total_duration).2fs)' % locals() 47 outstr = 'created %(slice_n)s slices from %(source_base_name)s%(source_ext)s' % locals() 48 outstr += ' (total duration %(total_duration).2fs)' % locals() 49 print(outstr) 49 50 # close source and sink files 50 51 del f, g -
python/demos/demo_source.py
r60fc05b rf264b17 6 6 if __name__ == '__main__': 7 7 if len(sys.argv) < 2: 8 print 'usage: %s <inputfile> [samplerate] [hop_size]' % sys.argv[0]8 print('usage: %s <inputfile> [samplerate] [hop_size]' % sys.argv[0]) 9 9 sys.exit(1) 10 10 samplerate = 0 … … 21 21 total_frames += read 22 22 if read < f.hop_size: break 23 print "read", "%.2fs" % (total_frames / float(samplerate) ), 24 print "(", total_frames, "frames", "in", 25 print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")", 26 print "from", f.uri 23 outstr = "read %.2fs" % (total_frames / float(samplerate)) 24 outstr += " (%d frames in" % total_frames 25 outstr += " %d blocks" % (total_frames // f.hop_size) 26 outstr += " at %dHz)" % f.samplerate 27 outstr += " from " + f.uri 28 print(outstr) -
python/demos/demo_specdesc.py
r60fc05b rf264b17 2 2 3 3 import sys 4 from aubio import fvec, source, pvoc, specdesc 5 from numpy import hstack4 import numpy as np 5 from aubio import source, pvoc, specdesc 6 6 7 7 win_s = 512 # fft size 8 hop_s = win_s / 4# hop size8 hop_s = win_s // 4 # hop size 9 9 10 10 if len(sys.argv) < 2: 11 print "Usage: %s <filename> [samplerate]" % sys.argv[0]11 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 12 12 sys.exit(1) 13 13 … … 31 31 for method in methods: 32 32 cands = [] 33 all_descs[method] = fvec(0)33 all_descs[method] = np.array([]) 34 34 o[method] = specdesc(method, win_s) 35 35 … … 40 40 samples, read = s() 41 41 fftgrain = pv(samples) 42 # print "%f" % ( total_frames / float(samplerate) ),42 #outstr = "%f" % ( total_frames / float(samplerate) ) 43 43 for method in methods: 44 44 specdesc_val = o[method](fftgrain)[0] 45 all_descs[method] = hstack ( [all_descs[method], specdesc_val])46 # print "%f" % specdesc_val,47 #print 45 all_descs[method] = np.append(all_descs[method], specdesc_val) 46 #outstr += " %f" % specdesc_val 47 #print(outstr) 48 48 total_frames += read 49 49 if read < hop_s: break 50 50 51 51 if 1: 52 print "done computing, now plotting"52 print("done computing, now plotting") 53 53 import matplotlib.pyplot as plt 54 54 from demo_waveform_plot import get_waveform_plot -
python/demos/demo_spectrogram.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 import sys 4 from aubio import pvoc, source 5 from numpy import array, arange, zeros, shape, log10, vstack6 from pylab import imshow, show, cm, axis, ylabel, xlabel, xticks, yticks 3 import sys, os.path 4 from aubio import pvoc, source, float_type 5 from numpy import zeros, log10, vstack 6 import matplotlib.pyplot as plt 7 7 8 8 def get_spectrogram(filename, samplerate = 0): 9 win_s = 512 # fft window size10 hop_s = win_s / 2# hop size11 fft_s = win_s / 2 + 1# spectrum bins9 win_s = 512 # fft window size 10 hop_s = win_s // 2 # hop size 11 fft_s = win_s // 2 + 1 # spectrum bins 12 12 13 a = source(filename, samplerate, hop_s) # source file14 if samplerate == 0: samplerate = a.samplerate15 pv = pvoc(win_s, hop_s) # phase vocoder16 specgram = zeros([0, fft_s], dtype='float32')# numpy array to store spectrogram13 a = source(filename, samplerate, hop_s) # source file 14 if samplerate == 0: samplerate = a.samplerate 15 pv = pvoc(win_s, hop_s) # phase vocoder 16 specgram = zeros([0, fft_s], dtype=float_type) # numpy array to store spectrogram 17 17 18 # analysis19 while True:20 samples, read = a() # read file21 specgram = vstack((specgram,pv(samples).norm)) # store new norm vector22 if read < a.hop_size: break18 # analysis 19 while True: 20 samples, read = a() # read file 21 specgram = vstack((specgram,pv(samples).norm)) # store new norm vector 22 if read < a.hop_size: break 23 23 24 # plotting 25 imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=cm.gray_r) 26 axis([0, len(specgram), 0, len(specgram[0])]) 27 # show axes in Hz and seconds 28 time_step = hop_s / float(samplerate) 29 total_time = len(specgram) * time_step 30 print "total time: %0.2fs" % total_time, 31 print ", samplerate: %.2fkHz" % (samplerate / 1000.) 32 n_xticks = 10 33 n_yticks = 10 24 # plotting 25 fig = plt.imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=plt.cm.gray_r) 26 ax = fig.axes 27 ax.axis([0, len(specgram), 0, len(specgram[0])]) 28 # show axes in Hz and seconds 29 time_step = hop_s / float(samplerate) 30 total_time = len(specgram) * time_step 31 outstr = "total time: %0.2fs" % total_time 32 print(outstr + ", samplerate: %.2fkHz" % (samplerate / 1000.)) 33 n_xticks = 10 34 n_yticks = 10 34 35 35 def get_rounded_ticks( top_pos, step, n_ticks ): 36 top_label = top_pos * step 37 # get the first label 38 ticks_first_label = top_pos * step / n_ticks 39 # round to the closest .1 40 ticks_first_label = round ( ticks_first_label * 10. ) / 10. 41 # compute all labels from the first rounded one 42 ticks_labels = [ ticks_first_label * n for n in range(n_ticks) ] + [ top_label ] 43 # get the corresponding positions 44 ticks_positions = [ ticks_labels[n] / step for n in range(n_ticks) ] + [ top_pos ] 45 # convert to string 46 ticks_labels = [ "%.1f" % x for x in ticks_labels ] 47 # return position, label tuple to use with x/yticks 48 return ticks_positions, ticks_labels 49 50 # apply to the axis 51 xticks( *get_rounded_ticks ( len(specgram), time_step, n_xticks ) ) 52 yticks( *get_rounded_ticks ( len(specgram[0]), (samplerate / 2. / 1000.) / len(specgram[0]), n_yticks ) ) 53 ylabel('Frequency (kHz)') 54 xlabel('Time (s)') 36 def get_rounded_ticks( top_pos, step, n_ticks ): 37 top_label = top_pos * step 38 # get the first label 39 ticks_first_label = top_pos * step / n_ticks 40 # round to the closest .1 41 ticks_first_label = round ( ticks_first_label * 10. ) / 10. 42 # compute all labels from the first rounded one 43 ticks_labels = [ ticks_first_label * n for n in range(n_ticks) ] + [ top_label ] 44 # get the corresponding positions 45 ticks_positions = [ ticks_labels[n] / step for n in range(n_ticks) ] + [ top_pos ] 46 # convert to string 47 ticks_labels = [ "%.1f" % x for x in ticks_labels ] 48 # return position, label tuple to use with x/yticks 49 return ticks_positions, ticks_labels 50 51 # apply to the axis 52 x_ticks, x_labels = get_rounded_ticks ( len(specgram), time_step, n_xticks ) 53 y_ticks, y_labels = get_rounded_ticks ( len(specgram[0]), (samplerate / 1000. / 2.) / len(specgram[0]), n_yticks ) 54 ax.set_xticks( x_ticks ) 55 ax.set_yticks ( y_ticks ) 56 ax.set_xticklabels( x_labels ) 57 ax.set_yticklabels ( y_labels ) 58 ax.set_ylabel('Frequency (kHz)') 59 ax.set_xlabel('Time (s)') 60 ax.set_title(os.path.basename(filename)) 61 for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + 62 ax.get_xticklabels() + ax.get_yticklabels()): 63 item.set_fontsize('x-small') 64 return fig 55 65 56 66 if __name__ == '__main__': 57 if len(sys.argv) < 2: 58 print "Usage: %s <filename>" % sys.argv[0] 59 else: 60 for soundfile in sys.argv[1:]: 61 get_spectrogram(soundfile) 62 # display graph 63 show() 67 if len(sys.argv) < 2: 68 print("Usage: %s <filename>" % sys.argv[0]) 69 else: 70 for soundfile in sys.argv[1:]: 71 fig = get_spectrogram(soundfile) 72 # display graph 73 plt.show() 74 #outimage = os.path.basename(soundfile) + '.png' 75 #print ("writing: " + outimage) 76 #plt.savefig(outimage) 77 plt.close() -
python/demos/demo_tempo.py
r60fc05b rf264b17 5 5 6 6 win_s = 512 # fft size 7 hop_s = win_s / 2# hop size7 hop_s = win_s // 2 # hop size 8 8 9 9 if len(sys.argv) < 2: 10 print "Usage: %s <filename> [samplerate]" % sys.argv[0]10 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 11 11 sys.exit(1) 12 12 … … 34 34 if is_beat: 35 35 this_beat = int(total_frames - delay + is_beat[0] * hop_s) 36 print "%f" % (this_beat / float(samplerate))36 print("%f" % (this_beat / float(samplerate))) 37 37 beats.append(this_beat) 38 38 total_frames += read -
python/demos/demo_tempo_plot.py
r60fc05b rf264b17 5 5 6 6 win_s = 512 # fft size 7 hop_s = win_s / 2# hop size7 hop_s = win_s // 2 # hop size 8 8 9 9 if len(sys.argv) < 2: 10 print "Usage: %s <filename> [samplerate]" % sys.argv[0]10 print("Usage: %s <filename> [samplerate]" % sys.argv[0]) 11 11 sys.exit(1) 12 12 … … 40 40 if len(beats) > 1: 41 41 # do plotting 42 from numpy import array, arange,mean, median, diff42 from numpy import mean, median, diff 43 43 import matplotlib.pyplot as plt 44 44 bpms = 60./ diff(beats) 45 print 'mean period:', "%.2f" % mean(bpms), 'bpm', 'median', "%.2f" % median(bpms), 'bpm'46 print 'plotting', filename45 print('mean period: %.2fbpm, median: %.2fbpm' % (mean(bpms), median(bpms))) 46 print('plotting %s' % filename) 47 47 plt1 = plt.axes([0.1, 0.75, 0.8, 0.19]) 48 48 plt2 = plt.axes([0.1, 0.1, 0.8, 0.65], sharex = plt1) … … 76 76 77 77 else: 78 print 'mean period:', "%.2f" % 0, 'bpm', 'median', "%.2f" % 0, 'bpm',79 print 'nothing to plot, file too short?'78 print('mean period: %.2fbpm, median: %.2fbpm' % (0, 0)) 79 print('plotting %s' % filename) -
python/demos/demo_tss.py
r60fc05b rf264b17 5 5 6 6 if __name__ == '__main__': 7 if len(sys.argv) < 2:8 print 'usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0]9 sys.exit(1)7 if len(sys.argv) < 2: 8 print('usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0]) 9 sys.exit(1) 10 10 11 samplerate = 4410012 win_s = 1024# fft size13 hop_s = win_s/ 4 # block size14 threshold = 0.511 samplerate = 44100 12 win_s = 1024 # fft size 13 hop_s = win_s // 4 # block size 14 threshold = 0.5 15 15 16 f = source(sys.argv[1], samplerate, hop_s)17 g = sink(sys.argv[2], samplerate)18 h = sink(sys.argv[3], samplerate)16 f = source(sys.argv[1], samplerate, hop_s) 17 g = sink(sys.argv[2], samplerate) 18 h = sink(sys.argv[3], samplerate) 19 19 20 pva = pvoc(win_s, hop_s) # a phase vocoder21 pvb = pvoc(win_s, hop_s) # another phase vocoder22 t = tss(win_s, hop_s) # transient steady state separation20 pva = pvoc(win_s, hop_s) # a phase vocoder 21 pvb = pvoc(win_s, hop_s) # another phase vocoder 22 t = tss(win_s, hop_s) # transient steady state separation 23 23 24 t.set_threshold(threshold)24 t.set_threshold(threshold) 25 25 26 read = hop_s26 read = hop_s 27 27 28 while read:29 samples, read = f() # read file30 spec = pva(samples)# compute spectrum31 trans_spec, stead_spec = t(spec) # transient steady-state separation32 transients = pva.rdo(trans_spec)# overlap-add synthesis of transients33 steadstate = pvb.rdo(stead_spec)# overlap-add synthesis of steady states34 g(transients, read) # write transients to output35 h(steadstate, read) # write steady states to output28 while read: 29 samples, read = f() # read file 30 spec = pva(samples) # compute spectrum 31 trans_spec, stead_spec = t(spec) # transient steady-state separation 32 transients = pva.rdo(trans_spec) # overlap-add synthesis of transients 33 steadstate = pvb.rdo(stead_spec) # overlap-add synthesis of steady states 34 g(transients, read) # write transients to output 35 h(steadstate, read) # write steady states to output 36 36 37 del f, g, h# finish writing the files now37 del f, g, h # finish writing the files now 38 38 39 from demo_spectrogram import get_spectrogram40 from pylab import subplot, show41 subplot(311)42 get_spectrogram(sys.argv[1])43 subplot(312)44 get_spectrogram(sys.argv[2])45 subplot(313)46 get_spectrogram(sys.argv[3])47 show()39 from demo_spectrogram import get_spectrogram 40 from pylab import subplot, show 41 subplot(311) 42 get_spectrogram(sys.argv[1]) 43 subplot(312) 44 get_spectrogram(sys.argv[2]) 45 subplot(313) 46 get_spectrogram(sys.argv[3]) 47 show() -
python/demos/demo_waveform_plot.py
r60fc05b rf264b17 2 2 3 3 import sys 4 from aubio import pvoc,source4 from aubio import source 5 5 from numpy import zeros, hstack 6 6 … … 22 22 samples, read = a() 23 23 # keep some data to plot it later 24 new_maxes = (abs(samples.reshape(hop_s/ downsample, downsample))).max(axis=0)24 new_maxes = (abs(samples.reshape(hop_s//downsample, downsample))).max(axis=0) 25 25 allsamples_max = hstack([allsamples_max, new_maxes]) 26 26 total_frames += read … … 49 49 import matplotlib.pyplot as plt 50 50 if len(sys.argv) < 2: 51 print "Usage: %s <filename>" % sys.argv[0]51 print("Usage: %s <filename>" % sys.argv[0]) 52 52 else: 53 53 for soundfile in sys.argv[1:]: -
python/ext/aubio-types.h
r60fc05b rf264b17 1 1 #include <Python.h> 2 2 #include <structmember.h> 3 4 #include "aubio-generated.h" 3 5 4 6 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION … … 34 36 35 37 #if HAVE_AUBIO_DOUBLE 36 #error "Ouch! Python interface for aubio has not been much tested yet." 38 // 64 bit precision with HAVE_AUBIO_DOUBLE=1 37 39 #define AUBIO_NPY_SMPL NPY_DOUBLE 40 #define AUBIO_NPY_SMPL_STR "float64" 41 #define AUBIO_NPY_SMPL_CHR "d" 38 42 #else 43 // default is 32 bit precision 39 44 #define AUBIO_NPY_SMPL NPY_FLOAT 45 #define AUBIO_NPY_SMPL_STR "float32" 46 #define AUBIO_NPY_SMPL_CHR "f" 40 47 #endif 41 48 42 // special python type for cvec 43 typedef struct 44 { 45 PyObject_HEAD 46 cvec_t * o; 47 uint_t length; 48 uint_t channels; 49 } Py_cvec; 49 // compat with Python < 2.6 50 #ifndef Py_TYPE 51 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) 52 #endif 53 50 54 extern PyTypeObject Py_cvecType; 51 55 56 PyObject * new_py_fvec(uint_t length); 57 PyObject * new_py_cvec(uint_t length); 58 PyObject * new_py_fmat(uint_t height, uint_t length); 59 52 60 // defined in aubio-proxy.c 61 extern int PyAubio_IsValidVector (PyObject *input); 62 53 63 extern PyObject *PyAubio_CFvecToArray (fvec_t * self); 54 extern fvec_t *PyAubio_ArrayToCFvec (PyObject * self);64 extern int PyAubio_ArrayToCFvec (PyObject * self, fvec_t *out); 55 65 56 extern Py_cvec *PyAubio_CCvecToPyCvec (cvec_t * self); 57 extern cvec_t *PyAubio_ArrayToCCvec (PyObject *input); 66 extern int PyAubio_PyCvecToCCvec (PyObject *input, cvec_t *i); 58 67 59 68 extern PyObject *PyAubio_CFmatToArray (fmat_t * self); 60 extern fmat_t *PyAubio_ArrayToCFmat (PyObject *input);69 extern int PyAubio_ArrayToCFmat (PyObject *input, fmat_t *out); 61 70 62 71 // hand written wrappers -
python/ext/aubiomodule.c
r60fc05b rf264b17 1 1 #define PY_AUBIO_MODULE_MAIN 2 2 #include "aubio-types.h" 3 #include "aubio-generated.h"4 3 #include "py-musicutils.h" 5 4 … … 84 83 { 85 84 PyObject *input; 86 fvec_t *vec;85 fvec_t vec; 87 86 smpl_t alpha; 88 87 PyObject *result; 89 88 90 if (!PyArg_ParseTuple (args, "O f:alpha_norm", &input, &alpha)) {89 if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":alpha_norm", &input, &alpha)) { 91 90 return NULL; 92 91 } … … 96 95 } 97 96 98 vec = PyAubio_ArrayToCFvec (input); 99 100 if (vec == NULL) { 97 if (!PyAubio_ArrayToCFvec(input, &vec)) { 101 98 return NULL; 102 99 } 103 100 104 101 // compute the function 105 result = Py_BuildValue ( "f", fvec_alpha_norm (vec, alpha));102 result = Py_BuildValue (AUBIO_NPY_SMPL_CHR, fvec_alpha_norm (&vec, alpha)); 106 103 if (result == NULL) { 107 104 return NULL; … … 117 114 smpl_t output; 118 115 119 if (!PyArg_ParseTuple (args, "| fff", &input, &samplerate, &fftsize)) {116 if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR , &input, &samplerate, &fftsize)) { 120 117 return NULL; 121 118 } … … 132 129 smpl_t output; 133 130 134 if (!PyArg_ParseTuple (args, "| fff", &input, &samplerate, &fftsize)) {131 if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR , &input, &samplerate, &fftsize)) { 135 132 return NULL; 136 133 } … … 147 144 smpl_t output; 148 145 149 if (!PyArg_ParseTuple (args, "| fff", &input, &samplerate, &fftsize)) {146 if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR, &input, &samplerate, &fftsize)) { 150 147 return NULL; 151 148 } … … 162 159 smpl_t output; 163 160 164 if (!PyArg_ParseTuple (args, "| fff", &input, &samplerate, &fftsize)) {161 if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR, &input, &samplerate, &fftsize)) { 165 162 return NULL; 166 163 } … … 175 172 { 176 173 PyObject *input; 177 fvec_t *vec;174 fvec_t vec; 178 175 PyObject *result; 179 176 … … 186 183 } 187 184 188 vec = PyAubio_ArrayToCFvec (input); 189 190 if (vec == NULL) { 185 if (!PyAubio_ArrayToCFvec(input, &vec)) { 191 186 return NULL; 192 187 } 193 188 194 189 // compute the function 195 result = Py_BuildValue ( "f", aubio_zero_crossing_rate (vec));190 result = Py_BuildValue (AUBIO_NPY_SMPL_CHR, aubio_zero_crossing_rate (&vec)); 196 191 if (result == NULL) { 197 192 return NULL; … … 205 200 { 206 201 PyObject *input; 207 fvec_t *vec;202 fvec_t vec; 208 203 209 204 if (!PyArg_ParseTuple (args, "O:min_removal", &input)) { … … 215 210 } 216 211 217 vec = PyAubio_ArrayToCFvec (input); 218 219 if (vec == NULL) { 212 if (!PyAubio_ArrayToCFvec(input, &vec)) { 220 213 return NULL; 221 214 } 222 215 223 216 // compute the function 224 fvec_min_removal ( vec);217 fvec_min_removal (&vec); 225 218 226 219 // since this function does not return, we could return None 227 220 //Py_RETURN_NONE; 228 221 // however it is convenient to return the modified vector 229 return (PyObject *) PyAubio_CFvecToArray( vec);222 return (PyObject *) PyAubio_CFvecToArray(&vec); 230 223 // or even without converting it back to an array 231 224 //Py_INCREF(vec); … … 246 239 {"level_detection", Py_aubio_level_detection, METH_VARARGS, Py_aubio_level_detection_doc}, 247 240 {"window", Py_aubio_window, METH_VARARGS, Py_aubio_window_doc}, 248 {NULL, NULL } /* Sentinel */241 {NULL, NULL, 0, NULL} /* Sentinel */ 249 242 }; 250 243 251 PyMODINIT_FUNC 252 init_aubio (void) 253 { 254 PyObject *m; 244 #if PY_MAJOR_VERSION >= 3 245 // Python3 module definition 246 static struct PyModuleDef moduledef = { 247 PyModuleDef_HEAD_INIT, 248 "_aubio", /* m_name */ 249 aubio_module_doc, /* m_doc */ 250 -1, /* m_size */ 251 aubio_methods, /* m_methods */ 252 NULL, /* m_reload */ 253 NULL, /* m_traverse */ 254 NULL, /* m_clear */ 255 NULL, /* m_free */ 256 }; 257 #endif 258 259 static PyObject * 260 initaubio (void) 261 { 262 PyObject *m = NULL; 255 263 int err; 256 264 … … 266 274 || (generated_types_ready() < 0 ) 267 275 ) { 268 return; 269 } 270 276 return m; 277 } 278 279 #if PY_MAJOR_VERSION >= 3 280 m = PyModule_Create(&moduledef); 281 #else 271 282 m = Py_InitModule3 ("_aubio", aubio_methods, aubio_module_doc); 283 #endif 272 284 273 285 if (m == NULL) { 274 return ;286 return m; 275 287 } 276 288 … … 296 308 PyModule_AddObject (m, "sink", (PyObject *) & Py_sinkType); 297 309 310 PyModule_AddStringConstant(m, "float_type", AUBIO_NPY_SMPL_STR); 311 298 312 // add generated objects 299 313 add_generated_objects(m); … … 301 315 // add ufunc 302 316 add_ufuncs(m); 303 } 317 318 return m; 319 } 320 321 #if PY_MAJOR_VERSION >= 3 322 // Python3 init 323 PyMODINIT_FUNC PyInit__aubio(void) 324 { 325 return initaubio(); 326 } 327 #else 328 // Python 2 init 329 PyMODINIT_FUNC init_aubio(void) 330 { 331 initaubio(); 332 } 333 #endif -
python/ext/aubioproxy.c
r60fc05b rf264b17 1 1 #include "aubio-types.h" 2 2 3 fvec_t * 4 PyAubio_ArrayToCFvec (PyObject *input) { 5 PyObject *array; 6 fvec_t *vec; 7 if (input == NULL) { 8 PyErr_SetString (PyExc_ValueError, "input array is not a python object"); 9 goto fail; 10 } 11 // parsing input object into a Py_fvec 12 if (PyArray_Check(input)) { 3 PyObject * 4 new_py_fvec(uint_t length) { 5 npy_intp dims[] = { length, 1 }; 6 return PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0); 7 } 13 8 14 // we got an array, convert it to an fvec 15 if (PyArray_NDIM ((PyArrayObject *)input) == 0) { 16 PyErr_SetString (PyExc_ValueError, "input array is a scalar"); 17 goto fail; 18 } else if (PyArray_NDIM ((PyArrayObject *)input) > 1) { 19 PyErr_SetString (PyExc_ValueError, 20 "input array has more than one dimensions"); 21 goto fail; 22 } 23 24 if (!PyArray_ISFLOAT ((PyArrayObject *)input)) { 25 PyErr_SetString (PyExc_ValueError, "input array should be float"); 26 goto fail; 27 } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) { 28 PyErr_SetString (PyExc_ValueError, "input array should be float32"); 29 goto fail; 30 } else { 31 // input data type is float32, nothing else to do 32 array = input; 33 } 34 35 // vec = new_fvec (vec->length); 36 // no need to really allocate fvec, just its struct member 37 vec = (fvec_t *)malloc(sizeof(fvec_t)); 38 long length = PyArray_SIZE ((PyArrayObject *)array); 39 if (length > 0) { 40 vec->length = (uint_t)length; 41 } else { 42 PyErr_SetString (PyExc_ValueError, "input array size should be greater than 0"); 43 goto fail; 44 } 45 vec->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)array, 0); 46 47 } else if (PyObject_TypeCheck (input, &PyList_Type)) { 48 PyErr_SetString (PyExc_ValueError, "does not convert from list yet"); 49 return NULL; 50 } else { 51 PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input"); 52 return NULL; 53 } 54 55 return vec; 56 57 fail: 58 return NULL; 9 PyObject * 10 new_py_fmat(uint_t height, uint_t length) { 11 npy_intp dims[] = { height, length, 1 }; 12 return PyArray_ZEROS(2, dims, AUBIO_NPY_SMPL, 0); 59 13 } 60 14 … … 66 20 } 67 21 68 Py_cvec * 69 PyAubio_CCvecToPyCvec (cvec_t * input) { 70 Py_cvec *vec = (Py_cvec*) PyObject_New (Py_cvec, &Py_cvecType); 71 vec->length = input->length; 72 vec->o = input; 73 Py_INCREF(vec); 74 return vec; 22 int 23 PyAubio_IsValidVector (PyObject * input) { 24 npy_intp length; 25 if (input == NULL) { 26 PyErr_SetString (PyExc_ValueError, "input array is not a python object"); 27 return 0; 28 } 29 // parsing input object into a Py_fvec 30 if (PyArray_Check(input)) { 31 32 // we got an array, convert it to an fvec 33 if (PyArray_NDIM ((PyArrayObject *)input) == 0) { 34 PyErr_SetString (PyExc_ValueError, "input array is a scalar"); 35 return 0; 36 } else if (PyArray_NDIM ((PyArrayObject *)input) > 1) { 37 PyErr_SetString (PyExc_ValueError, 38 "input array has more than one dimensions"); 39 return 0; 40 } 41 42 if (!PyArray_ISFLOAT ((PyArrayObject *)input)) { 43 PyErr_SetString (PyExc_ValueError, "input array should be float"); 44 return 0; 45 } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) { 46 PyErr_SetString (PyExc_ValueError, "input array should be " AUBIO_NPY_SMPL_STR); 47 return 0; 48 } 49 50 length = PyArray_SIZE ((PyArrayObject *)input); 51 if (length <= 0) { 52 PyErr_SetString (PyExc_ValueError, "input array size should be greater than 0"); 53 return 0; 54 } 55 56 } else if (PyObject_TypeCheck (input, &PyList_Type)) { 57 PyErr_SetString (PyExc_ValueError, "does not convert from list yet"); 58 return 0; 59 } else { 60 PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input"); 61 return 0; 62 } 63 return 1; 75 64 } 76 65 77 cvec_t * 78 PyAubio_ArrayToCCvec (PyObject *input) { 79 if (PyObject_TypeCheck (input, &Py_cvecType)) { 80 return ((Py_cvec*)input)->o; 81 } else { 82 PyErr_SetString (PyExc_ValueError, "input array should be float32"); 83 return NULL; 66 int 67 PyAubio_ArrayToCFvec (PyObject *input, fvec_t *out) { 68 69 if (!PyAubio_IsValidVector(input)){ 70 return 0; 84 71 } 72 73 out->length = (uint_t) PyArray_SIZE ((PyArrayObject *)input); 74 out->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)input, 0); 75 return 1; 85 76 } 86 77 … … 102 93 } 103 94 104 fmat_t * 105 PyAubio_ArrayToCFmat (PyObject *input) { 106 PyObject *array; 107 fmat_t *mat; 108 uint_t i; 95 int 96 PyAubio_ArrayToCFmat (PyObject *input, fmat_t *mat) { 97 uint_t i, new_height; 98 npy_intp length, height; 109 99 if (input == NULL) { 110 100 PyErr_SetString (PyExc_ValueError, "input array is not a python object"); 111 goto fail;101 return 0; 112 102 } 113 103 // parsing input object into a Py_fvec … … 117 107 if (PyArray_NDIM ((PyArrayObject *)input) == 0) { 118 108 PyErr_SetString (PyExc_ValueError, "input array is a scalar"); 119 goto fail;109 return 0; 120 110 } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) { 121 111 PyErr_SetString (PyExc_ValueError, 122 112 "input array has more than two dimensions"); 123 goto fail;113 return 0; 124 114 } 125 115 126 116 if (!PyArray_ISFLOAT ((PyArrayObject *)input)) { 127 117 PyErr_SetString (PyExc_ValueError, "input array should be float"); 128 goto fail;118 return 0; 129 119 } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) { 130 PyErr_SetString (PyExc_ValueError, "input array should be float32"); 131 goto fail; 132 } else { 133 // input data type is float32, nothing else to do 134 array = input; 120 PyErr_SetString (PyExc_ValueError, "input array should be " AUBIO_NPY_SMPL_STR); 121 return 0; 135 122 } 136 123 137 124 // no need to really allocate fvec, just its struct member 138 mat = (fmat_t *)malloc(sizeof(fmat_t)); 139 long length = PyArray_DIM ((PyArrayObject *)array, 1); 140 if (length > 0) { 141 mat->length = (uint_t)length; 142 } else { 125 length = PyArray_DIM ((PyArrayObject *)input, 1); 126 if (length <= 0) { 143 127 PyErr_SetString (PyExc_ValueError, "input array dimension 1 should be greater than 0"); 144 goto fail;128 return 0; 145 129 } 146 long height = PyArray_DIM ((PyArrayObject *)array, 0); 147 if (height > 0) { 148 mat->height = (uint_t)height; 149 } else { 130 height = PyArray_DIM ((PyArrayObject *)input, 0); 131 if (height <= 0) { 150 132 PyErr_SetString (PyExc_ValueError, "input array dimension 0 should be greater than 0"); 151 goto fail; 152 } 153 mat->data = (smpl_t **)malloc(sizeof(smpl_t*) * mat->height); 154 for (i=0; i< mat->height; i++) { 155 mat->data[i] = (smpl_t*)PyArray_GETPTR1 ((PyArrayObject *)array, i); 133 return 0; 156 134 } 157 135 158 136 } else if (PyObject_TypeCheck (input, &PyList_Type)) { 159 137 PyErr_SetString (PyExc_ValueError, "can not convert list to fmat"); 160 return NULL;138 return 0; 161 139 } else { 162 140 PyErr_SetString (PyExc_ValueError, "can only accept matrix of float as input"); 163 return NULL;141 return 0; 164 142 } 165 143 166 return mat; 144 new_height = (uint_t)PyArray_DIM ((PyArrayObject *)input, 0); 145 if (mat->height != new_height) { 146 if (mat->data) { 147 free(mat->data); 148 } 149 mat->data = (smpl_t **)malloc(sizeof(smpl_t*) * new_height); 150 } 167 151 168 fail: 169 return NULL; 152 mat->height = new_height; 153 mat->length = (uint_t)PyArray_DIM ((PyArrayObject *)input, 1); 154 for (i=0; i< mat->height; i++) { 155 mat->data[i] = (smpl_t*)PyArray_GETPTR1 ((PyArrayObject *)input, i); 156 } 157 return 1; 170 158 } 171 -
python/ext/py-cvec.c
r60fc05b rf264b17 1 1 #include "aubio-types.h" 2 2 3 /* cvec type definition 3 /* cvec type definition 4 4 5 5 class cvec(): 6 def __ init__(self, length = 1024):7 self.length = length 8 self.norm = array(length)9 self.phas = array(length)6 def __new__(self, length = 1024): 7 self.length = length / 2 + 1 8 self.norm = np.zeros(length / 2 + 1) 9 self.phas = np.zeros(length / 2 + 1) 10 10 11 11 */ 12 12 13 // special python type for cvec 14 typedef struct 15 { 16 PyObject_HEAD 17 PyObject *norm; 18 PyObject *phas; 19 uint_t length; 20 } Py_cvec; 21 13 22 static char Py_cvec_doc[] = "cvec object"; 23 24 25 PyObject * 26 new_py_cvec(uint_t length) { 27 Py_cvec* vec = (Py_cvec*) PyObject_New (Py_cvec, &Py_cvecType); 28 npy_intp dims[] = { length / 2 + 1, 1 }; 29 vec->norm = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0); 30 vec->phas = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0); 31 vec->length = length / 2 + 1; 32 return (PyObject*)vec; 33 } 34 35 int 36 PyAubio_PyCvecToCCvec (PyObject *input, cvec_t *i) { 37 if (PyObject_TypeCheck (input, &Py_cvecType)) { 38 Py_cvec * in = (Py_cvec *)input; 39 i->norm = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)(in->norm), 0); 40 i->phas = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)(in->phas), 0); 41 i->length = ((Py_cvec*)input)->length; 42 return 1; 43 } else { 44 PyErr_SetString (PyExc_ValueError, "input array should be aubio.cvec"); 45 return 0; 46 } 47 } 14 48 15 49 static PyObject * … … 24 58 return NULL; 25 59 } 26 27 60 28 61 self = (Py_cvec *) type->tp_alloc (type, 0); … … 48 81 Py_cvec_init (Py_cvec * self, PyObject * args, PyObject * kwds) 49 82 { 50 self->o = new_cvec ((self->length - 1) * 2); 51 if (self->o == NULL) { 52 return -1; 53 } 54 83 npy_intp dims[] = { self->length, 1 }; 84 self->phas = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0); 85 self->norm = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0); 55 86 return 0; 56 87 } … … 59 90 Py_cvec_del (Py_cvec * self) 60 91 { 61 del_cvec (self->o); 62 self->ob_type->tp_free ((PyObject *) self); 92 Py_DECREF(self->norm); 93 Py_DECREF(self->phas); 94 Py_TYPE(self)->tp_free ((PyObject *) self); 63 95 } 64 96 … … 70 102 PyObject *result = NULL; 71 103 72 format = Py String_FromString ("aubio cvec of %d elements");104 format = PyUnicode_FromString ("aubio cvec of %d elements"); 73 105 if (format == NULL) { 74 106 goto fail; … … 79 111 goto fail; 80 112 } 81 cvec_print ( self->o );82 83 result = Py String_Format (format, args);113 // hide actual norm / phas content 114 115 result = PyUnicode_Format (format, args); 84 116 85 117 fail: … … 91 123 92 124 PyObject * 93 PyAubio_CvecNormToArray (Py_cvec * self)94 {95 npy_intp dims[] = { self->o->length, 1 };96 return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->norm);97 }98 99 100 PyObject *101 PyAubio_CvecPhasToArray (Py_cvec * self)102 {103 npy_intp dims[] = { self->o->length, 1 };104 return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->phas);105 }106 107 PyObject *108 PyAubio_ArrayToCvecPhas (PyObject * self)109 {110 return NULL;111 }112 113 PyObject *114 125 Py_cvec_get_norm (Py_cvec * self, void *closure) 115 126 { 116 return PyAubio_CvecNormToArray(self); 127 // we want self->norm to still exist after our caller return it 128 Py_INCREF(self->norm); 129 return (PyObject*)(self->norm); 117 130 } 118 131 … … 120 133 Py_cvec_get_phas (Py_cvec * self, void *closure) 121 134 { 122 return PyAubio_CvecPhasToArray(self); 135 // we want self->phas to still exist after our caller return it 136 Py_INCREF(self->phas); 137 return (PyObject *)(self->phas); 123 138 } 124 139 … … 126 141 Py_cvec_set_norm (Py_cvec * vec, PyObject *input, void * closure) 127 142 { 128 PyArrayObject * array; 129 if (input == NULL) { 130 PyErr_SetString (PyExc_ValueError, "input array is not a python object"); 131 goto fail; 132 } 133 if (PyArray_Check(input)) { 134 135 // we got an array, convert it to a cvec.norm 136 if (PyArray_NDIM ((PyArrayObject *)input) == 0) { 137 PyErr_SetString (PyExc_ValueError, "input array is a scalar"); 138 goto fail; 139 } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) { 140 PyErr_SetString (PyExc_ValueError, 141 "input array has more than two dimensions"); 142 goto fail; 143 } 144 145 if (!PyArray_ISFLOAT ((PyArrayObject *)input)) { 146 PyErr_SetString (PyExc_ValueError, "input array should be float"); 147 goto fail; 148 } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) { 149 PyErr_SetString (PyExc_ValueError, "input array should be float32"); 150 goto fail; 151 } 152 array = (PyArrayObject *)input; 153 154 // check input array dimensions 155 if (PyArray_NDIM (array) != 1) { 156 PyErr_Format (PyExc_ValueError, 157 "input array has %d dimensions, not 1", 158 PyArray_NDIM (array)); 159 goto fail; 160 } else { 161 if (vec->o->length != PyArray_SIZE (array)) { 162 PyErr_Format (PyExc_ValueError, 163 "input array has length %d, but cvec has length %d", 164 (int)PyArray_SIZE (array), vec->o->length); 165 goto fail; 166 } 167 } 168 169 vec->o->norm = (smpl_t *) PyArray_GETPTR1 (array, 0); 170 171 } else { 172 PyErr_SetString (PyExc_ValueError, "can only accept array as input"); 173 return 1; 174 } 175 176 Py_INCREF(array); 143 npy_intp length; 144 if (!PyAubio_IsValidVector(input)) { 145 return 1; 146 } 147 length = PyArray_SIZE ((PyArrayObject *)input); 148 if (length != vec->length) { 149 PyErr_Format (PyExc_ValueError, 150 "input array has length %ld, but cvec has length %d", length, 151 vec->length); 152 return 1; 153 } 154 155 Py_XDECREF(vec->norm); 156 vec->norm = input; 157 Py_INCREF(vec->norm); 177 158 return 0; 178 179 fail:180 return 1;181 159 } 182 160 … … 184 162 Py_cvec_set_phas (Py_cvec * vec, PyObject *input, void * closure) 185 163 { 186 PyArrayObject * array; 187 if (input == NULL) { 188 PyErr_SetString (PyExc_ValueError, "input array is not a python object"); 189 goto fail; 190 } 191 if (PyArray_Check(input)) { 192 193 // we got an array, convert it to a cvec.phas 194 if (PyArray_NDIM ((PyArrayObject *)input) == 0) { 195 PyErr_SetString (PyExc_ValueError, "input array is a scalar"); 196 goto fail; 197 } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) { 198 PyErr_SetString (PyExc_ValueError, 199 "input array has more than two dimensions"); 200 goto fail; 201 } 202 203 if (!PyArray_ISFLOAT ((PyArrayObject *)input)) { 204 PyErr_SetString (PyExc_ValueError, "input array should be float"); 205 goto fail; 206 } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) { 207 PyErr_SetString (PyExc_ValueError, "input array should be float32"); 208 goto fail; 209 } 210 array = (PyArrayObject *)input; 211 212 // check input array dimensions 213 if (PyArray_NDIM (array) != 1) { 214 PyErr_Format (PyExc_ValueError, 215 "input array has %d dimensions, not 1", 216 PyArray_NDIM (array)); 217 goto fail; 218 } else { 219 if (vec->o->length != PyArray_SIZE (array)) { 220 PyErr_Format (PyExc_ValueError, 221 "input array has length %d, but cvec has length %d", 222 (int)PyArray_SIZE (array), vec->o->length); 223 goto fail; 224 } 225 } 226 227 vec->o->phas = (smpl_t *) PyArray_GETPTR1 (array, 0); 228 229 } else { 230 PyErr_SetString (PyExc_ValueError, "can only accept array as input"); 231 return 1; 232 } 233 234 Py_INCREF(array); 164 npy_intp length; 165 if (!PyAubio_IsValidVector(input)) { 166 return 1; 167 } 168 length = PyArray_SIZE ((PyArrayObject *)input); 169 if (length != vec->length) { 170 PyErr_Format (PyExc_ValueError, 171 "input array has length %ld, but cvec has length %d", length, 172 vec->length); 173 return 1; 174 } 175 176 Py_XDECREF(vec->phas); 177 vec->phas = input; 178 Py_INCREF(vec->phas); 235 179 return 0; 236 237 fail:238 return 1;239 180 } 240 181 … … 261 202 262 203 PyTypeObject Py_cvecType = { 263 PyObject_HEAD_INIT (NULL) 264 0, /* ob_size */ 204 PyVarObject_HEAD_INIT(NULL, 0) 265 205 "aubio.cvec", /* tp_name */ 266 206 sizeof (Py_cvec), /* tp_basicsize */ … … 273 213 (reprfunc) Py_cvec_repr, /* tp_repr */ 274 214 0, /* tp_as_number */ 275 0, //&Py_cvec_tp_as_sequence, 215 0, //&Py_cvec_tp_as_sequence, /* tp_as_sequence */ 276 216 0, /* tp_as_mapping */ 277 217 0, /* tp_hash */ … … 300 240 0, /* tp_alloc */ 301 241 Py_cvec_new, /* tp_new */ 302 }; 242 0, 243 0, 244 0, 245 0, 246 0, 247 0, 248 0, 249 0, 250 0, 251 }; -
python/ext/py-fft.c
r60fc05b rf264b17 1 #include "aubio wraphell.h"1 #include "aubio-types.h" 2 2 3 3 static char Py_fft_doc[] = "fft object"; 4 4 5 AUBIO_DECLARE(fft, uint_t win_s) 5 typedef struct 6 { 7 PyObject_HEAD 8 aubio_fft_t * o; 9 uint_t win_s; 10 // do / rdo input vectors 11 fvec_t vecin; 12 cvec_t cvecin; 13 // do / rdo output results 14 PyObject *doout; 15 PyObject *rdoout; 16 } Py_fft; 6 17 7 //AUBIO_NEW(fft)8 18 static PyObject * 9 19 Py_fft_new (PyTypeObject * type, PyObject * args, PyObject * kwds) … … 37 47 } 38 48 49 static int 50 Py_fft_init (Py_fft * self, PyObject * args, PyObject * kwds) 51 { 52 self->o = new_aubio_fft (self->win_s); 53 if (self->o == NULL) { 54 PyErr_Format(PyExc_RuntimeError, 55 "error creating fft with win_s=%d " 56 "(should be a power of 2 greater than 1; " 57 "try recompiling aubio with --enable-fftw3)", 58 self->win_s); 59 return -1; 60 } 39 61 40 AUBIO_INIT(fft, self->win_s) 62 self->doout = new_py_cvec(self->win_s); 63 self->rdoout = new_py_fvec(self->win_s); 41 64 42 AUBIO_DEL(fft) 65 return 0; 66 } 43 67 44 static PyObject * 45 Py_fft_do(PyObject * self, PyObject * args) 68 static void 69 Py_fft_del (Py_fft *self, PyObject *unused) 70 { 71 Py_XDECREF(self->doout); 72 Py_XDECREF(self->rdoout); 73 if (self->o) { 74 del_aubio_fft(self->o); 75 } 76 Py_TYPE(self)->tp_free((PyObject *) self); 77 } 78 79 static PyObject * 80 Py_fft_do(Py_fft * self, PyObject * args) 46 81 { 47 82 PyObject *input; 48 fvec_t *vec; 49 cvec_t *output; 83 cvec_t c_out; 50 84 51 85 if (!PyArg_ParseTuple (args, "O", &input)) { … … 53 87 } 54 88 55 vec = PyAubio_ArrayToCFvec (input); 56 57 if (vec == NULL) { 89 if (!PyAubio_ArrayToCFvec(input, &(self->vecin))) { 58 90 return NULL; 59 91 } 60 92 61 output = new_cvec(((Py_fft *) self)->win_s); 93 if (self->vecin.length != self->win_s) { 94 PyErr_Format(PyExc_ValueError, 95 "input array has length %d, but fft expects length %d", 96 self->vecin.length, self->win_s); 97 return NULL; 98 } 62 99 100 Py_INCREF(self->doout); 101 if (!PyAubio_PyCvecToCCvec(self->doout, &c_out)) { 102 return NULL; 103 } 63 104 // compute the function 64 aubio_fft_do ( ((Py_fft *)self)->o, vec, output);65 return (PyObject *)PyAubio_CCvecToPyCvec(output);105 aubio_fft_do (self->o, &(self->vecin), &c_out); 106 return self->doout; 66 107 } 67 108 68 AUBIO_MEMBERS_START(fft) 109 static PyMemberDef Py_fft_members[] = { 69 110 {"win_s", T_INT, offsetof (Py_fft, win_s), READONLY, 70 111 "size of the window"}, 71 AUBIO_MEMBERS_STOP(fft) 112 {NULL} 113 }; 72 114 73 static PyObject * 115 static PyObject * 74 116 Py_fft_rdo(Py_fft * self, PyObject * args) 75 117 { 76 118 PyObject *input; 77 cvec_t *vec; 78 fvec_t *output; 119 fvec_t out; 79 120 80 121 if (!PyArg_ParseTuple (args, "O", &input)) { … … 82 123 } 83 124 84 vec = PyAubio_ArrayToCCvec (input); 85 86 if (vec == NULL) { 125 if (!PyAubio_PyCvecToCCvec (input, &(self->cvecin)) ) { 87 126 return NULL; 88 127 } 89 128 90 output = new_fvec(self->win_s); 129 if (self->cvecin.length != self->win_s / 2 + 1) { 130 PyErr_Format(PyExc_ValueError, 131 "input cvec has length %d, but fft expects length %d", 132 self->cvecin.length, self->win_s / 2 + 1); 133 return NULL; 134 } 91 135 136 Py_INCREF(self->rdoout); 137 if (!PyAubio_ArrayToCFvec(self->rdoout, &out) ) { 138 return NULL; 139 } 92 140 // compute the function 93 aubio_fft_rdo ( ((Py_fft *)self)->o, vec, output);94 return (PyObject *)PyAubio_CFvecToArray(output);141 aubio_fft_rdo (self->o, &(self->cvecin), &out); 142 return self->rdoout; 95 143 } 96 144 … … 101 149 }; 102 150 103 AUBIO_TYPEOBJECT(fft, "aubio.fft") 151 PyTypeObject Py_fftType = { 152 PyVarObject_HEAD_INIT (NULL, 0) 153 "aubio.fft", 154 sizeof (Py_fft), 155 0, 156 (destructor) Py_fft_del, 157 0, 158 0, 159 0, 160 0, 161 0, 162 0, 163 0, 164 0, 165 0, 166 (ternaryfunc)Py_fft_do, 167 0, 168 0, 169 0, 170 0, 171 Py_TPFLAGS_DEFAULT, 172 Py_fft_doc, 173 0, 174 0, 175 0, 176 0, 177 0, 178 0, 179 Py_fft_methods, 180 Py_fft_members, 181 0, 182 0, 183 0, 184 0, 185 0, 186 0, 187 (initproc) Py_fft_init, 188 0, 189 Py_fft_new, 190 0, 191 0, 192 0, 193 0, 194 0, 195 0, 196 0, 197 0, 198 0, 199 }; -
python/ext/py-filter.c
r60fc05b rf264b17 6 6 aubio_filter_t * o; 7 7 uint_t order; 8 fvec_t vec; 9 PyObject *out; 10 fvec_t c_out; 8 11 } Py_filter; 9 12 … … 48 51 return -1; 49 52 } 50 53 self->out = NULL; 51 54 return 0; 52 55 } … … 55 58 Py_filter_del (Py_filter * self) 56 59 { 60 Py_XDECREF(self->out); 57 61 del_aubio_filter (self->o); 58 self->ob_type->tp_free ((PyObject *) self);59 } 60 61 static PyObject * 62 Py_TYPE(self)->tp_free ((PyObject *) self); 63 } 64 65 static PyObject * 62 66 Py_filter_do(Py_filter * self, PyObject * args) 63 67 { 64 68 PyObject *input; 65 fvec_t *vec;66 69 67 70 if (!PyArg_ParseTuple (args, "O:digital_filter.do", &input)) { … … 73 76 } 74 77 75 vec = PyAubio_ArrayToCFvec (input); 76 77 if (vec == NULL) { 78 return NULL; 79 } 80 78 if (!PyAubio_ArrayToCFvec(input, &(self->vec))) { 79 return NULL; 80 } 81 82 // initialize output now 83 if (self->out == NULL) { 84 self->out = new_py_fvec(self->vec.length); 85 } 86 87 Py_INCREF(self->out); 88 if (!PyAubio_ArrayToCFvec(self->out, &(self->c_out)) ) { 89 return NULL; 90 } 81 91 // compute the function 82 fvec_t * out = new_fvec(vec->length); 83 aubio_filter_do_outplace (self->o, vec, out); 84 return PyAubio_CFvecToArray(out); 85 } 86 87 static PyObject * 92 aubio_filter_do_outplace (self->o, &(self->vec), &(self->c_out)); 93 return self->out; 94 } 95 96 static PyObject * 88 97 Py_filter_set_c_weighting (Py_filter * self, PyObject *args) 89 98 { … … 103 112 } 104 113 105 static PyObject * 114 static PyObject * 106 115 Py_filter_set_a_weighting (Py_filter * self, PyObject *args) 107 116 { … … 157 166 158 167 PyTypeObject Py_filterType = { 159 PyObject_HEAD_INIT (NULL) 160 0, /* ob_size */ 168 PyVarObject_HEAD_INIT(NULL, 0) 161 169 "aubio.digital_filter", /* tp_name */ 162 170 sizeof (Py_filter), /* tp_basicsize */ … … 196 204 0, /* tp_alloc */ 197 205 Py_filter_new, /* tp_new */ 206 0, 207 0, 208 0, 209 0, 210 0, 211 0, 212 0, 213 0, 214 0, 198 215 }; -
python/ext/py-filterbank.c
r60fc05b rf264b17 1 #include "aubio wraphell.h"1 #include "aubio-types.h" 2 2 3 3 static char Py_filterbank_doc[] = "filterbank object"; 4 4 5 AUBIO_DECLARE(filterbank, uint_t n_filters; uint_t win_s) 6 7 //AUBIO_NEW(filterbank) 5 typedef struct 6 { 7 PyObject_HEAD 8 aubio_filterbank_t * o; 9 uint_t n_filters; 10 uint_t win_s; 11 cvec_t vec; 12 fvec_t freqs; 13 fmat_t coeffs; 14 PyObject *out; 15 fvec_t c_out; 16 } Py_filterbank; 17 8 18 static PyObject * 9 19 Py_filterbank_new (PyTypeObject * type, PyObject * args, PyObject * kwds) … … 45 55 } 46 56 47 48 AUBIO_INIT(filterbank, self->n_filters, self->win_s) 49 50 AUBIO_DEL(filterbank) 57 static int 58 Py_filterbank_init (Py_filterbank * self, PyObject * args, PyObject * kwds) 59 { 60 self->o = new_aubio_filterbank (self->n_filters, self->win_s); 61 if (self->o == NULL) { 62 PyErr_Format(PyExc_RuntimeError, "error creating filterbank with" 63 " n_filters=%d, win_s=%d", self->n_filters, self->win_s); 64 return -1; 65 } 66 self->out = new_py_fvec(self->n_filters); 67 68 return 0; 69 } 70 71 static void 72 Py_filterbank_del (Py_filterbank *self, PyObject *unused) 73 { 74 if (self->o) { 75 free(self->coeffs.data); 76 del_aubio_filterbank(self->o); 77 } 78 Py_XDECREF(self->out); 79 Py_TYPE(self)->tp_free((PyObject *) self); 80 } 51 81 52 82 static PyObject * … … 54 84 { 55 85 PyObject *input; 56 cvec_t *vec;57 fvec_t *out;58 86 59 87 if (!PyArg_ParseTuple (args, "O", &input)) { … … 61 89 } 62 90 63 vec = PyAubio_ArrayToCCvec (input); 64 65 if (vec == NULL) { 66 return NULL; 67 } 68 69 out = new_fvec (self->n_filters); 70 91 if (!PyAubio_PyCvecToCCvec(input, &(self->vec) )) { 92 return NULL; 93 } 94 95 if (self->vec.length != self->win_s / 2 + 1) { 96 PyErr_Format(PyExc_ValueError, 97 "input cvec has length %d, but fft expects length %d", 98 self->vec.length, self->win_s / 2 + 1); 99 return NULL; 100 } 101 102 Py_INCREF(self->out); 103 if (!PyAubio_ArrayToCFvec(self->out, &(self->c_out))) { 104 return NULL; 105 } 71 106 // compute the function 72 aubio_filterbank_do (self->o, vec, out);73 return (PyObject *)PyAubio_CFvecToArray(out);74 } 75 76 AUBIO_MEMBERS_START(filterbank) 107 aubio_filterbank_do (self->o, &(self->vec), &(self->c_out)); 108 return self->out; 109 } 110 111 static PyMemberDef Py_filterbank_members[] = { 77 112 {"win_s", T_INT, offsetof (Py_filterbank, win_s), READONLY, 78 113 "size of the window"}, 79 114 {"n_filters", T_INT, offsetof (Py_filterbank, n_filters), READONLY, 80 115 "number of filters"}, 81 AUBIO_MEMBERS_STOP(filterbank) 116 {NULL} /* sentinel */ 117 }; 82 118 83 119 static PyObject * … … 88 124 PyObject *input; 89 125 uint_t samplerate; 90 fvec_t *freqs;91 126 if (!PyArg_ParseTuple (args, "OI", &input, &samplerate)) { 92 127 return NULL; … … 97 132 } 98 133 99 freqs = PyAubio_ArrayToCFvec (input); 100 101 if (freqs == NULL) { 134 if (!PyAubio_ArrayToCFvec(input, &(self->freqs) )) { 102 135 return NULL; 103 136 } 104 137 105 138 err = aubio_filterbank_set_triangle_bands (self->o, 106 freqs, samplerate);139 &(self->freqs), samplerate); 107 140 if (err > 0) { 108 141 PyErr_SetString (PyExc_ValueError, … … 138 171 139 172 PyObject *input; 140 fmat_t *coeffs;141 142 173 if (!PyArg_ParseTuple (args, "O", &input)) { 143 174 return NULL; 144 175 } 145 176 146 coeffs = PyAubio_ArrayToCFmat (input); 147 148 if (coeffs == NULL) { 149 PyErr_SetString (PyExc_ValueError, 150 "unable to parse input array"); 151 return NULL; 152 } 153 154 err = aubio_filterbank_set_coeffs (self->o, coeffs); 177 if (!PyAubio_ArrayToCFmat(input, &(self->coeffs))) { 178 return NULL; 179 } 180 181 err = aubio_filterbank_set_coeffs (self->o, &(self->coeffs)); 155 182 156 183 if (err > 0) { … … 181 208 }; 182 209 183 AUBIO_TYPEOBJECT(filterbank, "aubio.filterbank") 210 PyTypeObject Py_filterbankType = { 211 PyVarObject_HEAD_INIT (NULL, 0) 212 "aubio.filterbank", 213 sizeof (Py_filterbank), 214 0, 215 (destructor) Py_filterbank_del, 216 0, 217 0, 218 0, 219 0, 220 0, 221 0, 222 0, 223 0, 224 0, 225 (ternaryfunc)Py_filterbank_do, 226 0, 227 0, 228 0, 229 0, 230 Py_TPFLAGS_DEFAULT, 231 Py_filterbank_doc, 232 0, 233 0, 234 0, 235 0, 236 0, 237 0, 238 Py_filterbank_methods, 239 Py_filterbank_members, 240 0, 241 0, 242 0, 243 0, 244 0, 245 0, 246 (initproc) Py_filterbank_init, 247 0, 248 Py_filterbank_new, 249 0, 250 0, 251 0, 252 0, 253 0, 254 0, 255 0, 256 0, 257 0, 258 }; -
python/ext/py-musicutils.c
r60fc05b rf264b17 9 9 10 10 if (!PyArg_ParseTuple (args, "|sI", &wintype, &winlen)) { 11 PyErr_SetString (PyExc_ValueError, "failed parsing arguments");12 11 return NULL; 13 12 } … … 26 25 { 27 26 PyObject *input; 28 fvec_t *vec;27 fvec_t vec; 29 28 PyObject *level_lin; 30 29 31 30 if (!PyArg_ParseTuple (args, "O:level_lin", &input)) { 32 PyErr_SetString (PyExc_ValueError, "failed parsing arguments");33 31 return NULL; 34 32 } … … 38 36 } 39 37 40 vec = PyAubio_ArrayToCFvec (input); 41 if (vec == NULL) { 38 if (!PyAubio_ArrayToCFvec(input, &vec)) { 42 39 return NULL; 43 40 } 44 41 45 level_lin = Py_BuildValue( "f", aubio_level_lin(vec));42 level_lin = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_level_lin(&vec)); 46 43 if (level_lin == NULL) { 47 44 PyErr_SetString (PyExc_ValueError, "failed computing level_lin"); … … 56 53 { 57 54 PyObject *input; 58 fvec_t *vec;55 fvec_t vec; 59 56 PyObject *db_spl; 60 57 61 58 if (!PyArg_ParseTuple (args, "O:db_spl", &input)) { 62 PyErr_SetString (PyExc_ValueError, "failed parsing arguments");63 59 return NULL; 64 60 } … … 68 64 } 69 65 70 vec = PyAubio_ArrayToCFvec (input); 71 if (vec == NULL) { 66 if (!PyAubio_ArrayToCFvec(input, &vec)) { 72 67 return NULL; 73 68 } 74 69 75 db_spl = Py_BuildValue( "f", aubio_db_spl(vec));70 db_spl = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_db_spl(&vec)); 76 71 if (db_spl == NULL) { 77 72 PyErr_SetString (PyExc_ValueError, "failed computing db_spl"); … … 86 81 { 87 82 PyObject *input; 88 fvec_t *vec;83 fvec_t vec; 89 84 PyObject *silence_detection; 90 85 smpl_t threshold; 91 86 92 if (!PyArg_ParseTuple (args, "Of:silence_detection", &input, &threshold)) { 93 PyErr_SetString (PyExc_ValueError, "failed parsing arguments"); 87 if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":silence_detection", &input, &threshold)) { 94 88 return NULL; 95 89 } … … 99 93 } 100 94 101 vec = PyAubio_ArrayToCFvec (input); 102 if (vec == NULL) { 95 if (!PyAubio_ArrayToCFvec(input, &vec)) { 103 96 return NULL; 104 97 } 105 98 106 silence_detection = Py_BuildValue("I", aubio_silence_detection( vec, threshold));99 silence_detection = Py_BuildValue("I", aubio_silence_detection(&vec, threshold)); 107 100 if (silence_detection == NULL) { 108 101 PyErr_SetString (PyExc_ValueError, "failed computing silence_detection"); … … 117 110 { 118 111 PyObject *input; 119 fvec_t *vec;112 fvec_t vec; 120 113 PyObject *level_detection; 121 114 smpl_t threshold; 122 115 123 if (!PyArg_ParseTuple (args, "Of:level_detection", &input, &threshold)) { 124 PyErr_SetString (PyExc_ValueError, "failed parsing arguments"); 116 if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":level_detection", &input, &threshold)) { 125 117 return NULL; 126 118 } … … 130 122 } 131 123 132 vec = PyAubio_ArrayToCFvec (input); 133 if (vec == NULL) { 124 if (!PyAubio_ArrayToCFvec(input, &vec)) { 134 125 return NULL; 135 126 } 136 127 137 level_detection = Py_BuildValue( "f", aubio_level_detection(vec, threshold));128 level_detection = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_level_detection(&vec, threshold)); 138 129 if (level_detection == NULL) { 139 130 PyErr_SetString (PyExc_ValueError, "failed computing level_detection"); -
python/ext/py-musicutils.h
r60fc05b rf264b17 1 #ifndef _PY_AUBIO_MUSICUTILS_H_2 #define _PY_AUBIO_MUSICUTILS_H_1 #ifndef PY_AUBIO_MUSICUTILS_H 2 #define PY_AUBIO_MUSICUTILS_H 3 3 4 4 static char Py_aubio_window_doc[] = "" … … 72 72 PyObject * Py_aubio_level_detection(PyObject *self, PyObject *args); 73 73 74 #endif /* _PY_AUBIO_MUSICUTILS_H_*/74 #endif /* PY_AUBIO_MUSICUTILS_H */ -
python/ext/py-phasevoc.c
r60fc05b rf264b17 1 #include "aubio wraphell.h"1 #include "aubio-types.h" 2 2 3 3 static char Py_pvoc_doc[] = "pvoc object"; 4 4 5 AUBIO_DECLARE(pvoc, uint_t win_s; uint_t hop_s) 6 7 //AUBIO_NEW(pvoc) 5 typedef struct 6 { 7 PyObject_HEAD 8 aubio_pvoc_t * o; 9 uint_t win_s; 10 uint_t hop_s; 11 fvec_t vecin; 12 cvec_t cvecin; 13 PyObject *output; 14 cvec_t c_output; 15 PyObject *routput; 16 fvec_t c_routput; 17 } Py_pvoc; 18 19 8 20 static PyObject * 9 21 Py_pvoc_new (PyTypeObject * type, PyObject * args, PyObject * kwds) … … 50 62 } 51 63 52 53 AUBIO_INIT(pvoc, self->win_s, self->hop_s) 54 55 AUBIO_DEL(pvoc) 56 57 static PyObject * 64 static int 65 Py_pvoc_init (Py_pvoc * self, PyObject * args, PyObject * kwds) 66 { 67 self->o = new_aubio_pvoc ( self->win_s, self->hop_s); 68 if (self->o == NULL) { 69 PyErr_Format(PyExc_RuntimeError, 70 "failed creating pvoc with win_s=%d, hop_s=%d", 71 self->win_s, self->hop_s); 72 return -1; 73 } 74 75 self->output = new_py_cvec(self->win_s); 76 self->routput = new_py_fvec(self->hop_s); 77 78 return 0; 79 } 80 81 82 static void 83 Py_pvoc_del (Py_pvoc *self, PyObject *unused) 84 { 85 Py_XDECREF(self->output); 86 Py_XDECREF(self->routput); 87 if (self->o) { 88 del_aubio_pvoc(self->o); 89 } 90 Py_TYPE(self)->tp_free((PyObject *) self); 91 } 92 93 94 static PyObject * 58 95 Py_pvoc_do(Py_pvoc * self, PyObject * args) 59 96 { 60 97 PyObject *input; 61 fvec_t *vec;62 cvec_t *output;63 98 64 99 if (!PyArg_ParseTuple (args, "O", &input)) { … … 66 101 } 67 102 68 vec = PyAubio_ArrayToCFvec (input); 69 70 if (vec == NULL) { 71 return NULL; 72 } 73 74 output = new_cvec(self->win_s); 75 103 if (!PyAubio_ArrayToCFvec (input, &(self->vecin) )) { 104 return NULL; 105 } 106 107 if (self->vecin.length != self->hop_s) { 108 PyErr_Format(PyExc_ValueError, 109 "input fvec has length %d, but pvoc expects length %d", 110 self->vecin.length, self->hop_s); 111 return NULL; 112 } 113 114 Py_INCREF(self->output); 115 if (!PyAubio_PyCvecToCCvec (self->output, &(self->c_output))) { 116 return NULL; 117 } 76 118 // compute the function 77 aubio_pvoc_do (self->o, vec, output);78 return (PyObject *)PyAubio_CCvecToPyCvec(output);79 } 80 81 AUBIO_MEMBERS_START(pvoc) 119 aubio_pvoc_do (self->o, &(self->vecin), &(self->c_output)); 120 return self->output; 121 } 122 123 static PyMemberDef Py_pvoc_members[] = { 82 124 {"win_s", T_INT, offsetof (Py_pvoc, win_s), READONLY, 83 125 "size of the window"}, 84 126 {"hop_s", T_INT, offsetof (Py_pvoc, hop_s), READONLY, 85 127 "size of the hop"}, 86 AUBIO_MEMBERS_STOP(pvoc) 87 88 static PyObject * 128 { NULL } // sentinel 129 }; 130 131 static PyObject * 89 132 Py_pvoc_rdo(Py_pvoc * self, PyObject * args) 90 133 { 91 134 PyObject *input; 92 cvec_t *vec;93 fvec_t *output;94 95 135 if (!PyArg_ParseTuple (args, "O", &input)) { 96 136 return NULL; 97 137 } 98 138 99 vec = PyAubio_ArrayToCCvec (input); 100 101 if (vec == NULL) { 102 return NULL; 103 } 104 105 output = new_fvec(self->hop_s); 106 139 if (!PyAubio_PyCvecToCCvec (input, &(self->cvecin) )) { 140 return NULL; 141 } 142 143 if (self->cvecin.length != self->win_s / 2 + 1) { 144 PyErr_Format(PyExc_ValueError, 145 "input cvec has length %d, but pvoc expects length %d", 146 self->cvecin.length, self->win_s / 2 + 1); 147 return NULL; 148 } 149 150 Py_INCREF(self->routput); 151 if (!PyAubio_ArrayToCFvec(self->routput, &(self->c_routput)) ) { 152 return NULL; 153 } 107 154 // compute the function 108 aubio_pvoc_rdo (self->o, vec, output);109 return (PyObject *)PyAubio_CFvecToArray(output);155 aubio_pvoc_rdo (self->o, &(self->cvecin), &(self->c_routput)); 156 return self->routput; 110 157 } 111 158 … … 116 163 }; 117 164 118 AUBIO_TYPEOBJECT(pvoc, "aubio.pvoc") 165 PyTypeObject Py_pvocType = { 166 PyVarObject_HEAD_INIT (NULL, 0) 167 "aubio.pvoc", 168 sizeof (Py_pvoc), 169 0, 170 (destructor) Py_pvoc_del, 171 0, 172 0, 173 0, 174 0, 175 0, 176 0, 177 0, 178 0, 179 0, 180 (ternaryfunc)Py_pvoc_do, 181 0, 182 0, 183 0, 184 0, 185 Py_TPFLAGS_DEFAULT, 186 Py_pvoc_doc, 187 0, 188 0, 189 0, 190 0, 191 0, 192 0, 193 Py_pvoc_methods, 194 Py_pvoc_members, 195 0, 196 0, 197 0, 198 0, 199 0, 200 0, 201 (initproc) Py_pvoc_init, 202 0, 203 Py_pvoc_new, 204 0, 205 0, 206 0, 207 0, 208 0, 209 0, 210 0, 211 0, 212 0, 213 }; -
python/ext/py-sink.c
r60fc05b rf264b17 1 #include "aubio wraphell.h"1 #include "aubio-types.h" 2 2 3 3 typedef struct … … 8 8 uint_t samplerate; 9 9 uint_t channels; 10 fvec_t write_data; 11 fmat_t mwrite_data; 10 12 } Py_sink; 11 13 … … 116 118 } 117 119 if (self->o == NULL) { 118 PyErr_SetString (PyExc_ StandardError, "error creating sink with this uri");120 PyErr_SetString (PyExc_RuntimeError, "error creating sink with this uri"); 119 121 return -1; 120 122 } … … 125 127 } 126 128 127 AUBIO_DEL(sink) 129 static void 130 Py_sink_del (Py_sink *self, PyObject *unused) 131 { 132 del_aubio_sink(self->o); 133 free(self->mwrite_data.data); 134 Py_TYPE(self)->tp_free((PyObject *) self); 135 } 128 136 129 137 /* function Py_sink_do */ … … 135 143 136 144 /* input vectors prototypes */ 137 fvec_t* write_data;138 145 uint_t write; 139 146 … … 143 150 } 144 151 145 146 152 /* input vectors parsing */ 147 write_data = PyAubio_ArrayToCFvec (write_data_obj); 148 149 if (write_data == NULL) { 150 return NULL; 151 } 152 153 154 153 if (!PyAubio_ArrayToCFvec(write_data_obj, &(self->write_data))) { 154 return NULL; 155 } 155 156 156 157 157 158 /* compute _do function */ 158 aubio_sink_do (self->o, write_data, write);159 aubio_sink_do (self->o, &(self->write_data), write); 159 160 160 161 Py_RETURN_NONE; … … 169 170 170 171 /* input vectors prototypes */ 171 fmat_t * write_data;172 172 uint_t write; 173 173 … … 179 179 180 180 /* input vectors parsing */ 181 write_data = PyAubio_ArrayToCFmat (write_data_obj); 182 183 if (write_data == NULL) { 184 return NULL; 185 } 186 187 188 189 181 if (!PyAubio_ArrayToCFmat(write_data_obj, &(self->mwrite_data))) { 182 return NULL; 183 } 190 184 191 185 /* compute _do function */ 192 aubio_sink_do_multi (self->o, write_data, write);186 aubio_sink_do_multi (self->o, &(self->mwrite_data), write); 193 187 Py_RETURN_NONE; 194 188 } 195 189 196 AUBIO_MEMBERS_START(sink) 190 static PyMemberDef Py_sink_members[] = { 197 191 {"uri", T_STRING, offsetof (Py_sink, uri), READONLY, 198 192 "path at which the sink was created"}, … … 201 195 {"channels", T_INT, offsetof (Py_sink, channels), READONLY, 202 196 "number of channels with which the sink was created"}, 203 AUBIO_MEMBERS_STOP(sink) 197 { NULL } // sentinel 198 }; 204 199 205 200 static PyObject * … … 217 212 }; 218 213 219 AUBIO_TYPEOBJECT(sink, "aubio.sink") 214 PyTypeObject Py_sinkType = { 215 PyVarObject_HEAD_INIT (NULL, 0) 216 "aubio.sink", 217 sizeof (Py_sink), 218 0, 219 (destructor) Py_sink_del, 220 0, 221 0, 222 0, 223 0, 224 0, 225 0, 226 0, 227 0, 228 0, 229 (ternaryfunc)Py_sink_do, 230 0, 231 0, 232 0, 233 0, 234 Py_TPFLAGS_DEFAULT, 235 Py_sink_doc, 236 0, 237 0, 238 0, 239 0, 240 0, 241 0, 242 Py_sink_methods, 243 Py_sink_members, 244 0, 245 0, 246 0, 247 0, 248 0, 249 0, 250 (initproc) Py_sink_init, 251 0, 252 Py_sink_new, 253 0, 254 0, 255 0, 256 0, 257 0, 258 0, 259 0, 260 0, 261 0, 262 }; -
python/ext/py-source.c
r60fc05b rf264b17 1 #include "aubio wraphell.h"1 #include "aubio-types.h" 2 2 3 3 typedef struct … … 9 9 uint_t channels; 10 10 uint_t hop_size; 11 uint_t duration; 12 PyObject *read_to; 13 fvec_t c_read_to; 14 PyObject *mread_to; 15 fmat_t c_mread_to; 11 16 } Py_source; 12 17 … … 136 141 self->o = new_aubio_source ( self->uri, self->samplerate, self->hop_size ); 137 142 if (self->o == NULL) { 138 char_t errstr[30 + strlen(self->uri)]; 139 sprintf(errstr, "error creating source with %s", self->uri); 140 PyErr_SetString (PyExc_StandardError, errstr); 143 PyErr_Format (PyExc_RuntimeError, "error creating source with \"%s\"", 144 self->uri); 141 145 return -1; 142 146 } … … 145 149 self->channels = aubio_source_get_channels ( self->o ); 146 150 } 151 self->duration = aubio_source_get_duration ( self->o ); 152 153 self->read_to = new_py_fvec(self->hop_size); 154 self->mread_to = new_py_fmat(self->channels, self->hop_size); 147 155 148 156 return 0; 149 157 } 150 158 151 AUBIO_DEL(source) 159 static void 160 Py_source_del (Py_source *self, PyObject *unused) 161 { 162 if (self->o) { 163 del_aubio_source(self->o); 164 free(self->c_mread_to.data); 165 } 166 Py_XDECREF(self->read_to); 167 Py_XDECREF(self->mread_to); 168 Py_TYPE(self)->tp_free((PyObject *) self); 169 } 170 152 171 153 172 /* function Py_source_do */ … … 155 174 Py_source_do(Py_source * self, PyObject * args) 156 175 { 157 158 159 /* output vectors prototypes */ 160 fvec_t* read_to; 176 PyObject *outputs; 161 177 uint_t read; 162 163 164 165 166 167 168 /* creating output read_to as a new_fvec of length self->hop_size */169 read_to = new_fvec (self->hop_size);170 178 read = 0; 171 179 172 180 Py_INCREF(self->read_to); 181 if (!PyAubio_ArrayToCFvec(self->read_to, &(self->c_read_to))) { 182 return NULL; 183 } 173 184 /* compute _do function */ 174 aubio_source_do (self->o, read_to, &read); 175 176 PyObject *outputs = PyList_New(0); 177 PyList_Append( outputs, (PyObject *)PyAubio_CFvecToArray (read_to)); 178 //del_fvec (read_to); 179 PyList_Append( outputs, (PyObject *)PyInt_FromLong (read)); 185 aubio_source_do (self->o, &(self->c_read_to), &read); 186 187 outputs = PyTuple_New(2); 188 PyTuple_SetItem( outputs, 0, self->read_to ); 189 PyTuple_SetItem( outputs, 1, (PyObject *)PyLong_FromLong(read)); 180 190 return outputs; 181 191 } … … 185 195 Py_source_do_multi(Py_source * self, PyObject * args) 186 196 { 187 188 189 /* output vectors prototypes */ 190 fmat_t* read_to; 197 PyObject *outputs; 191 198 uint_t read; 192 193 194 195 196 197 198 /* creating output read_to as a new_fvec of length self->hop_size */199 read_to = new_fmat (self->channels, self->hop_size);200 199 read = 0; 201 200 202 201 Py_INCREF(self->mread_to); 202 if (!PyAubio_ArrayToCFmat(self->mread_to, &(self->c_mread_to))) { 203 return NULL; 204 } 203 205 /* compute _do function */ 204 aubio_source_do_multi (self->o, read_to, &read); 205 206 PyObject *outputs = PyList_New(0); 207 PyList_Append( outputs, (PyObject *)PyAubio_CFmatToArray (read_to)); 208 //del_fvec (read_to); 209 PyList_Append( outputs, (PyObject *)PyInt_FromLong (read)); 206 aubio_source_do_multi (self->o, &(self->c_mread_to), &read); 207 208 outputs = PyTuple_New(2); 209 PyTuple_SetItem( outputs, 0, self->mread_to); 210 PyTuple_SetItem( outputs, 1, (PyObject *)PyLong_FromLong(read)); 210 211 return outputs; 211 212 } 212 213 213 AUBIO_MEMBERS_START(source) 214 static PyMemberDef Py_source_members[] = { 214 215 {"uri", T_STRING, offsetof (Py_source, uri), READONLY, 215 216 "path at which the source was created"}, … … 220 221 {"hop_size", T_INT, offsetof (Py_source, hop_size), READONLY, 221 222 "number of consecutive frames that will be read at each do or do_multi call"}, 222 AUBIO_MEMBERS_STOP(source) 223 223 {"duration", T_INT, offsetof (Py_source, duration), READONLY, 224 "total number of frames in the source (estimated)"}, 225 { NULL } // sentinel 226 }; 224 227 225 228 static PyObject * … … 227 230 { 228 231 uint_t tmp = aubio_source_get_samplerate (self->o); 229 return (PyObject *)Py Int_FromLong (tmp);232 return (PyObject *)PyLong_FromLong (tmp); 230 233 } 231 234 … … 234 237 { 235 238 uint_t tmp = aubio_source_get_channels (self->o); 236 return (PyObject *)Py Int_FromLong (tmp);239 return (PyObject *)PyLong_FromLong (tmp); 237 240 } 238 241 … … 249 252 uint_t err = 0; 250 253 251 uint_t position;254 int position; 252 255 if (!PyArg_ParseTuple (args, "I", &position)) { 256 return NULL; 257 } 258 259 if (position < 0) { 260 PyErr_Format(PyExc_ValueError, 261 "error when seeking in source: can not seek to negative value %d", 262 position); 253 263 return NULL; 254 264 } … … 279 289 }; 280 290 281 AUBIO_TYPEOBJECT(source, "aubio.source") 291 PyTypeObject Py_sourceType = { 292 PyVarObject_HEAD_INIT (NULL, 0) 293 "aubio.source", 294 sizeof (Py_source), 295 0, 296 (destructor) Py_source_del, 297 0, 298 0, 299 0, 300 0, 301 0, 302 0, 303 0, 304 0, 305 0, 306 (ternaryfunc)Py_source_do, 307 0, 308 0, 309 0, 310 0, 311 Py_TPFLAGS_DEFAULT, 312 Py_source_doc, 313 0, 314 0, 315 0, 316 0, 317 0, 318 0, 319 Py_source_methods, 320 Py_source_members, 321 0, 322 0, 323 0, 324 0, 325 0, 326 0, 327 (initproc) Py_source_init, 328 0, 329 Py_source_new, 330 0, 331 0, 332 0, 333 0, 334 0, 335 0, 336 0, 337 0, 338 0, 339 }; -
python/ext/ufuncs.c
r60fc05b rf264b17 85 85 { 86 86 int err = 0; 87 PyObject *dict, *f, *g, *h; 87 88 88 89 err = _import_umath (); … … 92 93 } 93 94 94 PyObject *f, *dict;95 95 dict = PyModule_GetDict(m); 96 96 f = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_unwrap2pi_data, Py_aubio_unary_types, … … 100 100 Py_DECREF(f); 101 101 102 PyObject *g;103 102 g = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_freqtomidi_data, Py_aubio_unary_types, 104 103 Py_aubio_unary_n_types, Py_aubio_unary_n_inputs, Py_aubio_unary_n_outputs, … … 107 106 Py_DECREF(g); 108 107 109 PyObject *h;110 108 h = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_miditofreq_data, Py_aubio_unary_types, 111 109 Py_aubio_unary_n_types, Py_aubio_unary_n_inputs, Py_aubio_unary_n_outputs, -
python/lib/aubio/__init__.py
r60fc05b rf264b17 2 2 3 3 import numpy 4 from _aubio import * 5 from midiconv import * 6 from slicing import * 4 from ._aubio import * 5 from ._aubio import float_type 6 from .midiconv import * 7 from .slicing import * 7 8 8 9 class fvec(numpy.ndarray): 9 " a simple numpy array holding a vector of float32 " 10 def __new__(self, length = 1024, **kwargs): 11 self.length = length 12 if type(length) == type([]): 13 return numpy.array(length, dtype='float32', **kwargs) 14 return numpy.zeros(length, dtype='float32', **kwargs) 10 """a numpy vector holding audio samples""" 11 12 def __new__(cls, input_arg=1024, **kwargs): 13 if isinstance(input_arg, int): 14 if input_arg == 0: 15 raise ValueError("vector length of 1 or more expected") 16 return numpy.zeros(input_arg, dtype=float_type, **kwargs) 17 else: 18 return numpy.array(input_arg, dtype=float_type, **kwargs) -
python/lib/aubio/midiconv.py
r60fc05b rf264b17 1 1 # -*- coding: utf-8 -*- 2 """ utilities to convert midi note number to and from note names """ 3 4 __all__ = ['note2midi', 'midi2note', 'freq2note'] 5 6 import sys 7 py3 = sys.version_info[0] == 3 8 if py3: 9 str_instances = str 10 int_instances = int 11 else: 12 str_instances = (str, unicode) 13 int_instances = (int, long) 2 14 3 15 def note2midi(note): 4 16 " convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] " 5 17 _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} 6 _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, 'b': -1, u'♭': -1, u'\ufffd': -2} 18 _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, 19 'b': -1, u'♭': -1, u'\ufffd': -2} 7 20 _valid_octaves = range(-1, 10) 8 if type(note) not in (str, unicode): 9 raise TypeError, "a string is required, got %s" % note 10 if not (1 < len(note) < 5): 11 raise ValueError, "string of 2 to 4 characters expected, got %d (%s)" % (len(note), note) 21 if not isinstance(note, str_instances): 22 raise TypeError("a string is required, got %s (%s)" % (note, str(type(note)))) 23 if len(note) not in range(2, 5): 24 raise ValueError("string of 2 to 4 characters expected, got %d (%s)" \ 25 % (len(note), note)) 12 26 notename, modifier, octave = [None]*3 13 27 … … 27 41 28 42 if notename not in _valid_notenames: 29 raise ValueError , "%s is not a valid note name" % notename43 raise ValueError("%s is not a valid note name" % notename) 30 44 if modifier not in _valid_modifiers: 31 raise ValueError , "%s is not a valid modifier" % modifier45 raise ValueError("%s is not a valid modifier" % modifier) 32 46 if octave not in _valid_octaves: 33 raise ValueError , "%s is not a valid octave" % octave47 raise ValueError("%s is not a valid octave" % octave) 34 48 35 49 midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier] 36 50 if midi > 127: 37 raise ValueError , "%s is outside of the range C-2 to G8" % note51 raise ValueError("%s is outside of the range C-2 to G8" % note) 38 52 return midi 39 53 40 54 def midi2note(midi): 41 55 " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] " 42 if type(midi) != int: 43 raise TypeError, "an integer is required, got %s" % midi 44 if not (-1 < midi < 128): 45 raise ValueError, "an integer between 0 and 127 is excepted, got %d" % midi 46 midi = int(midi) 56 if not isinstance(midi, int_instances): 57 raise TypeError("an integer is required, got %s" % midi) 58 if midi not in range(0, 128): 59 raise ValueError("an integer between 0 and 127 is excepted, got %d" % midi) 47 60 _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] 48 return _valid_notenames[midi % 12] + str( midi / 12- 1)61 return _valid_notenames[midi % 12] + str(int(midi / 12) - 1) 49 62 50 63 def freq2note(freq): 64 " convert frequency in Hz to nearest note name, e.g. [0, 22050.] -> [C-1, G9] " 51 65 from aubio import freqtomidi 52 66 return midi2note(int(freqtomidi(freq))) -
python/lib/aubio/slicing.py
r60fc05b rf264b17 1 """utility routines to slice sound files at given timestamps""" 2 3 import os 1 4 from aubio import source, sink 2 import os3 5 4 max_timestamp = 1e1206 _max_timestamp = 1e120 5 7 6 def slice_source_at_stamps(source_file, timestamps, timestamps_end = None, 7 output_dir = None, 8 samplerate = 0, 9 hopsize = 256): 8 def slice_source_at_stamps(source_file, timestamps, timestamps_end=None, 9 output_dir=None, samplerate=0, hopsize=256): 10 """ slice a sound file at given timestamps """ 10 11 11 if timestamps ==None or len(timestamps) == 0:12 raise ValueError 12 if timestamps is None or len(timestamps) == 0: 13 raise ValueError("no timestamps given") 13 14 14 15 if timestamps[0] != 0: 15 16 timestamps = [0] + timestamps 16 if timestamps_end !=None:17 if timestamps_end is not None: 17 18 timestamps_end = [timestamps[1] - 1] + timestamps_end 18 19 19 if timestamps_end !=None:20 if timestamps_end is not None: 20 21 if len(timestamps_end) != len(timestamps): 21 raise ValueError 22 raise ValueError("len(timestamps_end) != len(timestamps)") 22 23 else: 23 timestamps_end = [t - 1 for t in timestamps[1:] ] + [ max_timestamp]24 timestamps_end = [t - 1 for t in timestamps[1:]] + [_max_timestamp] 24 25 25 regions = zip(timestamps, timestamps_end)26 regions = list(zip(timestamps, timestamps_end)) 26 27 #print regions 27 28 28 source_base_name, source_ext= os.path.splitext(os.path.basename(source_file))29 if output_dir !=None:29 source_base_name, _ = os.path.splitext(os.path.basename(source_file)) 30 if output_dir is not None: 30 31 if not os.path.isdir(output_dir): 31 32 os.makedirs(output_dir) … … 33 34 34 35 def new_sink_name(source_base_name, timestamp, samplerate): 36 """ create a sink based on a timestamp in samples, converted in seconds """ 35 37 timestamp_seconds = timestamp / float(samplerate) 36 38 return source_base_name + "_%011.6f" % timestamp_seconds + '.wav' 37 39 38 # reopen source file39 s= source(source_file, samplerate, hopsize)40 samplerate = s.get_samplerate()40 # open source file 41 _source = source(source_file, samplerate, hopsize) 42 samplerate = _source.samplerate 41 43 42 44 total_frames = 0 … … 45 47 while True: 46 48 # get hopsize new samples from source 47 vec, read = s.do_multi()49 vec, read = _source.do_multi() 48 50 # if the total number of frames read will exceed the next region start 49 51 if len(regions) and total_frames + read >= regions[0][0]: … … 54 56 new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate) 55 57 # create its sink 56 g = sink(new_sink_path, samplerate, s.channels)58 _sink = sink(new_sink_path, samplerate, _source.channels) 57 59 # create a dictionary containing all this 58 new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': g}60 new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': _sink} 59 61 # append the dictionary to the current list of slices 60 62 slices.append(new_slice) … … 63 65 start_stamp = current_slice['start_stamp'] 64 66 end_stamp = current_slice['end_stamp'] 65 g= current_slice['sink']67 _sink = current_slice['sink'] 66 68 # sample index to start writing from new source vector 67 69 start = max(start_stamp - total_frames, 0) … … 73 75 if remaining > start: 74 76 # write remaining samples from current region 75 g.do_multi(vec[:,start:remaining], remaining - start)77 _sink.do_multi(vec[:, start:remaining], remaining - start) 76 78 #print "closing region", "remaining", remaining 77 79 # close this file 78 g.close()80 _sink.close() 79 81 elif read > start: 80 82 # write all the samples 81 g.do_multi(vec[:,start:read], read - start)83 _sink.do_multi(vec[:, start:read], read - start) 82 84 total_frames += read 83 if read < hopsize: break 85 if read < hopsize: 86 break -
python/scripts/aubiocut
r60fc05b rf264b17 135 135 options.source_file = args[0] 136 136 else: 137 print "no file name given\n", usage137 print ("no file name given\n" + usage) 138 138 sys.exit(1) 139 139 return options, args … … 172 172 if o(samples): 173 173 timestamps.append (o.get_last()) 174 if options.verbose: print "%.4f" % o.get_last_s()174 if options.verbose: print ("%.4f" % o.get_last_s()) 175 175 total_frames += read 176 176 if read < hopsize: break … … 189 189 timestamps_end = None 190 190 if options.cut_until_nslices and options.cut_until_nsamples: 191 print "warning: using cut_until_nslices, but cut_until_nsamples is set"191 print ("warning: using cut_until_nslices, but cut_until_nsamples is set") 192 192 if options.cut_until_nsamples: 193 193 timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]] -
python/tests/run_all_tests
r60fc05b rf264b17 2 2 3 3 if __name__ == '__main__': 4 import os, sys, unittest 5 def load_test(): 6 # get relevant files 7 curdir = os.path.dirname(sys.argv[0]) 8 if curdir == '': curdir = '.' 9 files = os.listdir(curdir) 10 modfiles = filter (lambda y: y.endswith('.py'), files) 11 modfiles = filter (lambda f: f.startswith('test_'), modfiles) 12 modfiles = filter (lambda y: not 'beattracking' in y, modfiles) 13 modfiles = filter (lambda y: not 'hist' in y, modfiles) 14 modfiles = filter (lambda y: not 'scale' in y, modfiles) 15 modfiles = filter (lambda y: not 'peakpicker' in y, modfiles) 16 # get module names 17 modnames = map (lambda x: os.path.splitext(x)[0], modfiles) 18 # import them 19 modules = map (__import__, modnames) 20 # create a test suites from the imported module 21 load_from_module = unittest.defaultTestLoader.loadTestsFromModule 22 tests = map(load_from_module, modules) 23 return unittest.TestSuite(tests) 24 unittest.main(defaultTest = 'load_test') 4 import nose2.main 5 nose2.discover() -
python/tests/test_aubio.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 3 from unittest import main 4 from numpy.testing import TestCase 4 5 5 6 class aubiomodule_test_case(TestCase): 6 7 7 def test_import(self):8 """ try importing aubio """9 import aubio8 def test_import(self): 9 """ try importing aubio """ 10 import aubio 10 11 11 12 if __name__ == '__main__': 12 from unittest import main 13 main() 13 main() 14 14 -
python/tests/test_cvec.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 4 from numpy.testing import assert_equal, assert_almost_equal 5 from aubio import cvec 6 from numpy import array, shape, pi 3 from unittest import main 4 import numpy as np 5 from numpy.testing import TestCase, assert_equal 6 from aubio import cvec, fvec, float_type 7 8 wrong_type = 'float32' if float_type == 'float64' else 'float64' 7 9 8 10 class aubio_cvec_test_case(TestCase): … … 10 12 def test_vector_created_with_zeroes(self): 11 13 a = cvec(10) 12 shape(a.norm)13 shape(a.phas)14 a.norm[0]14 assert_equal(a.norm.shape[0], 10 / 2 + 1) 15 assert_equal(a.phas.shape[0], 10 / 2 + 1) 16 _ = a.norm[0] 15 17 assert_equal(a.norm, 0.) 16 18 assert_equal(a.phas, 0.) … … 42 44 def test_assign_cvec_phas_slice(self): 43 45 spec = cvec(1024) 44 spec.phas[39:-1] = - pi46 spec.phas[39:-1] = -np.pi 45 47 assert_equal(spec.phas[0:39], 0) 46 assert_equal(spec.phas[39:-1], - pi)48 assert_equal(spec.phas[39:-1], -np.pi) 47 49 assert_equal(spec.norm, 0) 48 50 51 def test_assign_cvec_with_other_cvec(self): 52 """ check dest cvec is still reachable after source was deleted """ 53 spec = cvec(1024) 54 a = np.random.rand(1024//2+1).astype(float_type) 55 b = np.random.rand(1024//2+1).astype(float_type) 56 spec.norm = a 57 spec.phas = b 58 new_spec = spec 59 del spec 60 assert_equal(a, new_spec.norm) 61 assert_equal(b, new_spec.phas) 62 assert_equal(id(a), id(new_spec.norm)) 63 assert_equal(id(b), id(new_spec.phas)) 64 65 def test_pass_to_numpy(self): 66 spec = cvec(1024) 67 norm = spec.norm 68 phas = spec.phas 69 del spec 70 new_spec = cvec(1024) 71 new_spec.norm = norm 72 new_spec.phas = phas 73 assert_equal(norm, new_spec.norm) 74 assert_equal(phas, new_spec.phas) 75 assert_equal(id(norm), id(new_spec.norm)) 76 assert_equal(id(phas), id(new_spec.phas)) 77 del norm 78 del phas 79 assert_equal(new_spec.norm, 0.) 80 assert_equal(new_spec.phas, 0.) 81 del new_spec 82 83 def test_assign_norm_too_large(self): 84 a = cvec(512) 85 b = fvec(512//2+1 + 4) 86 with self.assertRaises(ValueError): 87 a.norm = b 88 89 def test_assign_norm_too_small(self): 90 a = cvec(512) 91 b = fvec(512//2+1 - 4) 92 with self.assertRaises(ValueError): 93 a.norm = b 94 95 def test_assign_phas_too_large(self): 96 a = cvec(512) 97 b = fvec(512//2+1 + 4) 98 with self.assertRaises(ValueError): 99 a.phas = b 100 101 def test_assign_phas_too_small(self): 102 a = cvec(512) 103 b = fvec(512//2+1 - 4) 104 with self.assertRaises(ValueError): 105 a.phas = b 106 107 def test_cvec_repr(self): 108 win_s = 512 109 c = cvec(win_s) 110 expected_repr = "aubio cvec of {:d} elements".format(win_s//2+1) 111 self.assertEqual(repr(c), expected_repr) 112 113 class aubio_cvec_wrong_norm_input(TestCase): 114 115 def test_wrong_length(self): 116 with self.assertRaises(ValueError): 117 cvec(-1) 118 119 def test_set_norm_with_scalar(self): 120 a = cvec(512) 121 with self.assertRaises(ValueError): 122 a.norm = 1 123 124 def test_set_norm_with_scalar_array(self): 125 a = cvec(512) 126 with self.assertRaises(ValueError): 127 a.norm = np.ndarray(1, dtype = 'int') 128 129 def test_set_norm_with_int_array(self): 130 a = cvec(512) 131 with self.assertRaises(ValueError): 132 a.norm = np.zeros(512//2+1, dtype = 'int') 133 134 def test_set_norm_with_wrong_float_array(self): 135 a = cvec(512) 136 with self.assertRaises(ValueError): 137 a.norm = np.zeros(512//2+1, dtype = wrong_type) 138 139 def test_set_norm_with_wrong_2d_array(self): 140 a = cvec(512) 141 with self.assertRaises(ValueError): 142 a.norm = np.zeros((512//2+1, 2), dtype = float_type) 143 49 144 if __name__ == '__main__': 50 from unittest import main51 145 main() -
python/tests/test_fft.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 3 from unittest import main 4 from numpy.testing import TestCase 4 5 from numpy.testing import assert_equal, assert_almost_equal 6 import numpy as np 5 7 from aubio import fvec, fft, cvec 6 from numpy import array, shape7 from math import pi8 from math import pi, floor 9 from random import random 8 10 9 11 class aubio_fft_test_case(TestCase): … … 21 23 f = fft (win_s) 22 24 fftgrain = f (timegrain) 23 assert_equal (shape(fftgrain.norm), (win_s/2+1,)) 24 assert_equal (shape(fftgrain.phas), (win_s/2+1,)) 25 del f 26 assert_equal (fftgrain.norm.shape, (win_s/2+1,)) 27 assert_equal (fftgrain.phas.shape, (win_s/2+1,)) 25 28 26 29 def test_zeros(self): … … 35 38 def test_impulse(self): 36 39 """ check the transform of one impulse at a random place """ 37 from random import random38 from math import floor39 40 win_s = 256 40 i = floor(random()*win_s)41 i = int(floor(random()*win_s)) 41 42 impulse = pi * random() 42 43 f = fft(win_s) … … 50 51 51 52 def test_impulse_negative(self): 52 """ check the transform of one impulse at a random place """ 53 from random import random 54 from math import floor 53 """ check the transform of a negative impulse at a random place """ 55 54 win_s = 256 56 i = 057 impulse = - 10.55 i = int(floor(random()*win_s)) 56 impulse = -.1 58 57 f = fft(win_s) 59 58 timegrain = fvec(win_s) 59 timegrain[0] = 0 60 60 timegrain[i] = impulse 61 61 fftgrain = f ( timegrain ) 62 62 #self.plot_this ( fftgrain.phas ) 63 assert_almost_equal ( fftgrain.norm, abs(impulse), decimal = 6)63 assert_almost_equal ( fftgrain.norm, abs(impulse), decimal = 5 ) 64 64 if impulse < 0: 65 65 # phase can be pi or -pi, as it is not unwrapped 66 assert_almost_equal ( abs(fftgrain.phas[1:-1]) , pi, decimal = 6 )66 #assert_almost_equal ( abs(fftgrain.phas[1:-1]) , pi, decimal = 6 ) 67 67 assert_almost_equal ( fftgrain.phas[0], pi, decimal = 6) 68 assert_almost_equal ( fftgrain.phas[-1], pi, decimal = 6)68 assert_almost_equal ( np.fmod(fftgrain.phas[-1], pi), 0, decimal = 6) 69 69 else: 70 assert_equal ( fftgrain.phas[1:-1] == 0, True)71 assert_equal ( fftgrain.phas[0] == 0, True)72 assert_ equal ( fftgrain.phas[-1] == 0, True)70 #assert_equal ( fftgrain.phas[1:-1] == 0, True) 71 assert_equal ( fftgrain.phas[0], 0) 72 assert_almost_equal ( np.fmod(fftgrain.phas[-1], pi), 0, decimal = 6) 73 73 # now check the resynthesis 74 74 synthgrain = f.rdo ( fftgrain ) … … 96 96 """ check running fft.rdo before fft.do works """ 97 97 win_s = 1024 98 impulse = pi99 98 f = fft(win_s) 100 99 fftgrain = cvec(win_s) … … 107 106 show () 108 107 108 def test_local_fftgrain(self): 109 """ check aubio.fft() result can be accessed after deletion """ 110 def compute_grain(impulse): 111 win_s = 1024 112 timegrain = fvec(win_s) 113 timegrain[0] = impulse 114 f = fft(win_s) 115 fftgrain = f ( timegrain ) 116 return fftgrain 117 impulse = pi 118 fftgrain = compute_grain(impulse) 119 assert_equal ( fftgrain.phas[0], 0) 120 assert_almost_equal ( fftgrain.phas[1], 0) 121 assert_almost_equal ( fftgrain.norm[0], impulse, decimal = 6 ) 122 123 def test_local_reconstruct(self): 124 """ check aubio.fft.rdo() result can be accessed after deletion """ 125 def compute_grain(impulse): 126 win_s = 1024 127 timegrain = fvec(win_s) 128 timegrain[0] = impulse 129 f = fft(win_s) 130 fftgrain = f ( timegrain ) 131 r = f.rdo(fftgrain) 132 return r 133 impulse = pi 134 r = compute_grain(impulse) 135 assert_almost_equal ( r[0], impulse, decimal = 6) 136 assert_almost_equal ( r[1:], 0) 137 138 def test_large_input_timegrain(self): 139 win_s = 1024 140 f = fft(win_s) 141 t = fvec(win_s + 1) 142 with self.assertRaises(ValueError): 143 f(t) 144 145 def test_small_input_timegrain(self): 146 win_s = 1024 147 f = fft(win_s) 148 t = fvec(1) 149 with self.assertRaises(ValueError): 150 f(t) 151 152 def test_large_input_fftgrain(self): 153 win_s = 1024 154 f = fft(win_s) 155 s = cvec(win_s + 5) 156 with self.assertRaises(ValueError): 157 f.rdo(s) 158 159 def test_small_input_fftgrain(self): 160 win_s = 1024 161 f = fft(win_s) 162 s = cvec(16) 163 with self.assertRaises(ValueError): 164 f.rdo(s) 165 166 class aubio_fft_wrong_params(TestCase): 167 168 def test_wrong_buf_size(self): 169 win_s = -1 170 with self.assertRaises(ValueError): 171 fft(win_s) 172 173 def test_buf_size_not_power_of_two(self): 174 # when compiled with fftw3, aubio supports non power of two fft sizes 175 win_s = 320 176 try: 177 with self.assertRaises(RuntimeError): 178 fft(win_s) 179 except AssertionError: 180 self.skipTest('creating aubio.fft with size %d did not fail' % win_s) 181 182 def test_buf_size_too_small(self): 183 win_s = 1 184 with self.assertRaises(RuntimeError): 185 fft(win_s) 186 109 187 if __name__ == '__main__': 110 from unittest import main111 188 main() 112 -
python/tests/test_filter.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from unittest import main 3 4 from numpy.testing import TestCase, assert_equal, assert_almost_equal 4 5 from aubio import fvec, digital_filter 5 from numpy import array6 6 from utils import array_from_text_file 7 7 8 8 class aubio_filter_test_case(TestCase): 9 9 10 def test_members(self): 11 f = digital_filter() 12 assert_equal (f.order, 7) 13 f = digital_filter(5) 14 assert_equal (f.order, 5) 15 f(fvec()) 16 17 def test_cweighting_error(self): 18 f = digital_filter (2) 19 self.assertRaises ( ValueError, f.set_c_weighting, 44100 ) 20 f = digital_filter (8) 21 self.assertRaises ( ValueError, f.set_c_weighting, 44100 ) 22 f = digital_filter (5) 23 self.assertRaises ( ValueError, f.set_c_weighting, 4000 ) 24 f = digital_filter (5) 25 self.assertRaises ( ValueError, f.set_c_weighting, 193000 ) 26 f = digital_filter (7) 27 self.assertRaises ( ValueError, f.set_a_weighting, 193000 ) 28 f = digital_filter (5) 29 self.assertRaises ( ValueError, f.set_a_weighting, 192000 ) 10 def test_members(self): 11 f = digital_filter() 12 assert_equal (f.order, 7) 13 f = digital_filter(5) 14 assert_equal (f.order, 5) 15 f(fvec()) 30 16 31 def test_c_weighting(self): 32 expected = array_from_text_file('c_weighting_test_simple.expected') 33 f = digital_filter(5) 34 f.set_c_weighting(44100) 35 v = fvec(32) 36 v[12] = .5 37 u = f(v) 38 assert_almost_equal (expected[1], u) 17 def test_cweighting_error(self): 18 f = digital_filter (2) 19 self.assertRaises ( ValueError, f.set_c_weighting, 44100 ) 20 f = digital_filter (8) 21 self.assertRaises ( ValueError, f.set_c_weighting, 44100 ) 22 f = digital_filter (5) 23 self.assertRaises ( ValueError, f.set_c_weighting, 4000 ) 24 f = digital_filter (5) 25 self.assertRaises ( ValueError, f.set_c_weighting, 193000 ) 26 f = digital_filter (7) 27 self.assertRaises ( ValueError, f.set_a_weighting, 193000 ) 28 f = digital_filter (5) 29 self.assertRaises ( ValueError, f.set_a_weighting, 192000 ) 39 30 40 def test_c_weighting_8000(self):41 expected = array_from_text_file('c_weighting_test_simple_8000.expected')42 f = digital_filter(5)43 f.set_c_weighting(8000)44 v = fvec(32)45 v[12] = .546 u = f(v)47 assert_almost_equal (expected[1], u)31 def test_c_weighting(self): 32 expected = array_from_text_file('c_weighting_test_simple.expected') 33 f = digital_filter(5) 34 f.set_c_weighting(44100) 35 v = fvec(32) 36 v[12] = .5 37 u = f(v) 38 assert_almost_equal (expected[1], u) 48 39 49 def test_a_weighting(self):50 expected = array_from_text_file('a_weighting_test_simple.expected')51 f = digital_filter(7)52 f.set_a_weighting(44100)53 v = fvec(32)54 v[12] = .555 u = f(v)56 assert_almost_equal (expected[1], u)40 def test_c_weighting_8000(self): 41 expected = array_from_text_file('c_weighting_test_simple_8000.expected') 42 f = digital_filter(5) 43 f.set_c_weighting(8000) 44 v = fvec(32) 45 v[12] = .5 46 u = f(v) 47 assert_almost_equal (expected[1], u) 57 48 58 def test_a_weighting_parted(self): 59 expected = array_from_text_file('a_weighting_test_simple.expected') 60 f = digital_filter(7) 61 f.set_a_weighting(44100) 62 v = fvec(16) 63 v[12] = .5 64 u = f(v) 65 assert_almost_equal (expected[1][:16], u) 66 # one more time 67 v = fvec(16) 68 u = f(v) 69 assert_almost_equal (expected[1][16:], u) 49 def test_a_weighting(self): 50 expected = array_from_text_file('a_weighting_test_simple.expected') 51 f = digital_filter(7) 52 f.set_a_weighting(44100) 53 v = fvec(32) 54 v[12] = .5 55 u = f(v) 56 assert_almost_equal (expected[1], u) 57 58 def test_a_weighting_parted(self): 59 expected = array_from_text_file('a_weighting_test_simple.expected') 60 f = digital_filter(7) 61 f.set_a_weighting(44100) 62 v = fvec(16) 63 v[12] = .5 64 u = f(v) 65 assert_almost_equal (expected[1][:16], u) 66 # one more time 67 v = fvec(16) 68 u = f(v) 69 assert_almost_equal (expected[1][16:], u) 70 71 def test_set_biquad(self): 72 f = digital_filter(3) 73 f.set_biquad(0., 0., 0, 0., 0.) 74 75 def test_set_biquad_wrong_order(self): 76 f = digital_filter(4) 77 with self.assertRaises(ValueError): 78 f.set_biquad(0., 0., 0, 0., 0.) 79 80 class aubio_filter_wrong_params(TestCase): 81 82 def test_negative_order(self): 83 with self.assertRaises(ValueError): 84 digital_filter(-1) 70 85 71 86 if __name__ == '__main__': 72 from unittest import main 73 main() 74 87 main() -
python/tests/test_filterbank.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 3 from unittest import main 4 from numpy.testing import TestCase 4 5 from numpy.testing import assert_equal, assert_almost_equal 5 from numpy import random 6 from math import pi 7 from numpy import array 8 from aubio import cvec, filterbank 6 import numpy as np 7 from aubio import cvec, filterbank, float_type 9 8 from utils import array_from_text_file 10 9 11 10 class aubio_filterbank_test_case(TestCase): 12 11 13 def test_members(self):14 f = filterbank(40, 512)15 assert_equal ([f.n_filters, f.win_s], [40, 512])12 def test_members(self): 13 f = filterbank(40, 512) 14 assert_equal ([f.n_filters, f.win_s], [40, 512]) 16 15 17 def test_set_coeffs(self):18 f = filterbank(40, 512)19 r = random.random([40, 512 / 2 + 1]).astype('float32')20 f.set_coeffs(r)21 assert_equal (r, f.get_coeffs())16 def test_set_coeffs(self): 17 f = filterbank(40, 512) 18 r = np.random.random([40, int(512 / 2) + 1]).astype(float_type) 19 f.set_coeffs(r) 20 assert_equal (r, f.get_coeffs()) 22 21 23 def test_phase(self):24 f = filterbank(40, 512)25 c = cvec(512)26 c.phas[:] =pi27 assert_equal( f(c), 0);22 def test_phase(self): 23 f = filterbank(40, 512) 24 c = cvec(512) 25 c.phas[:] = np.pi 26 assert_equal( f(c), 0); 28 27 29 def test_norm(self):30 f = filterbank(40, 512)31 c = cvec(512)32 c.norm[:] = 133 assert_equal( f(c), 0);28 def test_norm(self): 29 f = filterbank(40, 512) 30 c = cvec(512) 31 c.norm[:] = 1 32 assert_equal( f(c), 0); 34 33 35 def test_random_norm(self):36 f = filterbank(40, 512)37 c = cvec(512)38 c.norm[:] = random.random((512 / 2 + 1,)).astype('float32')39 assert_equal( f(c), 0)34 def test_random_norm(self): 35 f = filterbank(40, 512) 36 c = cvec(512) 37 c.norm[:] = np.random.random((int(512 / 2) + 1,)).astype(float_type) 38 assert_equal( f(c), 0) 40 39 41 def test_random_coeffs(self): 42 f = filterbank(40, 512) 43 c = cvec(512) 44 r = random.random([40, 512 / 2 + 1]).astype('float32') 45 r /= r.sum() 46 f.set_coeffs(r) 47 c.norm[:] = random.random((512 / 2 + 1,)).astype('float32') 48 assert_equal ( f(c) < 1., True ) 49 assert_equal ( f(c) > 0., True ) 40 def test_random_coeffs(self): 41 win_s = 128 42 f = filterbank(40, win_s) 43 c = cvec(win_s) 44 r = np.random.random([40, int(win_s / 2) + 1]).astype(float_type) 45 r /= r.sum() 46 f.set_coeffs(r) 47 c.norm[:] = np.random.random((int(win_s / 2) + 1,)).astype(float_type) 48 assert_equal ( f(c) < 1., True ) 49 assert_equal ( f(c) > 0., True ) 50 50 51 def test_mfcc_coeffs(self):52 f = filterbank(40, 512)53 c = cvec(512)54 f.set_mel_coeffs_slaney(44100)55 c.norm[:] = random.random((512 / 2 + 1,)).astype('float32')56 assert_equal ( f(c) < 1., True )57 assert_equal ( f(c) > 0., True )51 def test_mfcc_coeffs(self): 52 f = filterbank(40, 512) 53 c = cvec(512) 54 f.set_mel_coeffs_slaney(44100) 55 c.norm[:] = np.random.random((int(512 / 2) + 1,)).astype(float_type) 56 assert_equal ( f(c) < 1., True ) 57 assert_equal ( f(c) > 0., True ) 58 58 59 def test_mfcc_coeffs_16000(self): 60 expected = array_from_text_file('filterbank_mfcc_16000_512.expected') 61 f = filterbank(40, 512) 62 f.set_mel_coeffs_slaney(16000) 63 assert_almost_equal ( expected, f.get_coeffs() ) 59 def test_mfcc_coeffs_16000(self): 60 expected = array_from_text_file('filterbank_mfcc_16000_512.expected') 61 f = filterbank(40, 512) 62 f.set_mel_coeffs_slaney(16000) 63 assert_almost_equal ( expected, f.get_coeffs() ) 64 65 class aubio_filterbank_wrong_values(TestCase): 66 67 def test_negative_window(self): 68 self.assertRaises(ValueError, filterbank, 40, -20) 69 70 def test_negative_filters(self): 71 self.assertRaises(ValueError, filterbank, -40, 1024) 72 73 def test_filterbank_long_cvec(self): 74 f = filterbank(40, 512) 75 with self.assertRaises(ValueError): 76 f(cvec(1024)) 77 78 def test_filterbank_short_cvec(self): 79 f = filterbank(40, 512) 80 with self.assertRaises(ValueError): 81 f(cvec(256)) 64 82 65 83 if __name__ == '__main__': 66 from unittest import main 67 main() 68 84 main() -
python/tests/test_filterbank_mel.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 3 from unittest import main 4 from numpy.testing import TestCase 4 5 from numpy.testing import assert_equal, assert_almost_equal 5 6 from numpy import array, shape 6 from aubio import cvec, filterbank 7 from aubio import cvec, filterbank, float_type 7 8 8 9 class aubio_filterbank_mel_test_case(TestCase): 9 10 10 def test_slaney(self):11 f = filterbank(40, 512)12 f.set_mel_coeffs_slaney(16000)13 a = f.get_coeffs()14 assert_equal(shape (a), (40, 512/2 + 1) )11 def test_slaney(self): 12 f = filterbank(40, 512) 13 f.set_mel_coeffs_slaney(16000) 14 a = f.get_coeffs() 15 assert_equal(shape (a), (40, 512/2 + 1) ) 15 16 16 def test_other_slaney(self):17 f = filterbank(40, 512*2)18 f.set_mel_coeffs_slaney(44100)19 a= f.get_coeffs()20 #print "sum is", sum(sum(a))21 for win_s in [256, 512, 1024, 2048, 4096]:22 f = filterbank(40, win_s)23 f.set_mel_coeffs_slaney(320000)24 a= f.get_coeffs()25 #print "sum is", sum(sum(a))17 def test_other_slaney(self): 18 f = filterbank(40, 512*2) 19 f.set_mel_coeffs_slaney(44100) 20 _ = f.get_coeffs() 21 #print "sum is", sum(sum(a)) 22 for win_s in [256, 512, 1024, 2048, 4096]: 23 f = filterbank(40, win_s) 24 f.set_mel_coeffs_slaney(32000) 25 _ = f.get_coeffs() 26 #print "sum is", sum(sum(a)) 26 27 27 def test_triangle_freqs_zeros(self):28 f = filterbank(9, 1024)29 freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]30 freqs = array(freq_list, dtype = 'float32')31 f.set_triangle_bands(freqs, 48000)32 f.get_coeffs().T33 assert_equal ( f(cvec(1024)), 0)28 def test_triangle_freqs_zeros(self): 29 f = filterbank(9, 1024) 30 freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000] 31 freqs = array(freq_list, dtype = float_type) 32 f.set_triangle_bands(freqs, 48000) 33 _ = f.get_coeffs().T 34 assert_equal ( f(cvec(1024)), 0) 34 35 35 def test_triangle_freqs_ones(self):36 f = filterbank(9, 1024)37 freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]38 freqs = array(freq_list, dtype = 'float32')39 f.set_triangle_bands(freqs, 48000)40 f.get_coeffs().T41 spec = cvec(1024)42 spec.norm[:] = 143 assert_almost_equal ( f(spec),44 [ 0.02070313, 0.02138672, 0.02127604, 0.02135417,45 0.02133301, 0.02133301, 0.02133311, 0.02133334,0.02133345])36 def test_triangle_freqs_ones(self): 37 f = filterbank(9, 1024) 38 freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000] 39 freqs = array(freq_list, dtype = float_type) 40 f.set_triangle_bands(freqs, 48000) 41 _ = f.get_coeffs().T 42 spec = cvec(1024) 43 spec.norm[:] = 1 44 assert_almost_equal ( f(spec), 45 [ 0.02070313, 0.02138672, 0.02127604, 0.02135417, 46 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345]) 46 47 47 48 if __name__ == '__main__': 48 from unittest import main 49 main() 50 51 49 main() -
python/tests/test_fvec.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 4 from numpy.testing import assert_equal, assert_almost_equal 3 from unittest import main 4 import numpy as np 5 from numpy.testing import TestCase, assert_equal, assert_almost_equal 5 6 from aubio import fvec, zero_crossing_rate, alpha_norm, min_removal 6 from numpy import array, shape 7 from aubio import float_type 8 9 wrong_type = 'float32' if float_type == 'float64' else 'float64' 7 10 8 11 default_size = 512 … … 12 15 def test_vector_created_with_zeroes(self): 13 16 a = fvec(10) 14 assert a.dtype == 'float32'17 assert a.dtype == float_type 15 18 assert a.shape == (10,) 16 assert_equal 19 assert_equal(a, 0) 17 20 18 21 def test_vector_create_with_list(self): 19 a = fvec([0, 1,2,3])20 assert a.dtype == 'float32'22 a = fvec([0, 1, 2, 3]) 23 assert a.dtype == float_type 21 24 assert a.shape == (4,) 22 assert_equal (range(4), a)25 assert_equal(list(range(4)), a) 23 26 24 27 def test_vector_assign_element(self): … … 35 38 def test_vector(self): 36 39 a = fvec() 37 a, len(a) #a.length 38 a[0] 39 array(a) 40 len(a) 41 _ = a[0] 42 np.array(a) 43 a = fvec(1) 40 44 a = fvec(10) 41 a = fvec(1) 42 a.T 43 array(a).T 44 a = range(len(a)) 45 _ = a.T 45 46 46 def test_wrong_values(self): 47 self.assertRaises (ValueError, fvec, -10) 48 47 class aubio_fvec_wrong_values(TestCase): 48 49 def test_negative_length(self): 50 """ test creating fvec with negative length fails (pure python) """ 51 self.assertRaises(ValueError, fvec, -10) 52 53 def test_zero_length(self): 54 """ test creating fvec with zero length fails (pure python) """ 55 self.assertRaises(ValueError, fvec, 0) 56 57 def test_out_of_bound(self): 58 """ test assiging fvec out of bounds fails (pure python) """ 49 59 a = fvec(2) 50 self.assertRaises 51 self.assertRaises 60 self.assertRaises(IndexError, a.__getitem__, 3) 61 self.assertRaises(IndexError, a.__getitem__, 2) 52 62 53 def test_alpha_norm_of_fvec(self): 54 a = fvec(2) 55 self.assertEquals (alpha_norm(a, 1), 0) 56 a[0] = 1 57 self.assertEquals (alpha_norm(a, 1), 0.5) 58 a[1] = 1 59 self.assertEquals (alpha_norm(a, 1), 1) 60 a = array([0, 1], dtype='float32') 61 from math import sqrt 62 assert_almost_equal (alpha_norm(a, 2), sqrt(2)/2.) 63 class aubio_wrong_fvec_input(TestCase): 64 """ uses min_removal to test PyAubio_IsValidVector """ 63 65 64 def test_ alpha_norm_of_none(self):65 self.assertRaises (ValueError, alpha_norm, None, 1)66 def test_no_input(self): 67 self.assertRaises(TypeError, min_removal) 66 68 67 def test_alpha_norm_of_array_of_float32(self): 68 # check scalar fails 69 a = array(1, dtype = 'float32') 70 self.assertRaises (ValueError, alpha_norm, a, 1) 71 # check 2d array fails 72 a = array([[2],[4]], dtype = 'float32') 73 self.assertRaises (ValueError, alpha_norm, a, 1) 74 # check 1d array 75 a = array(range(10), dtype = 'float32') 76 self.assertEquals (alpha_norm(a, 1), 4.5) 69 def test_none(self): 70 self.assertRaises(ValueError, min_removal, None) 77 71 78 def test_alpha_norm_of_array_of_int(self): 79 a = array(1, dtype = 'int') 80 self.assertRaises (ValueError, alpha_norm, a, 1) 81 a = array([[[1,2],[3,4]]], dtype = 'int') 82 self.assertRaises (ValueError, alpha_norm, a, 1) 83 a = array(range(10), dtype = 'int') 84 self.assertRaises (ValueError, alpha_norm, a, 1) 72 def test_wrong_scalar(self): 73 a = np.array(10, dtype=float_type) 74 self.assertRaises(ValueError, min_removal, a) 85 75 86 def test_alpha_norm_of_array_of_string (self): 87 a = "hello" 88 self.assertRaises (ValueError, alpha_norm, a, 1) 76 def test_wrong_dimensions(self): 77 a = np.array([[[1, 2], [3, 4]]], dtype=float_type) 78 self.assertRaises(ValueError, min_removal, a) 79 80 def test_wrong_array_size(self): 81 x = np.array([], dtype=float_type) 82 self.assertRaises(ValueError, min_removal, x) 83 84 def test_wrong_type(self): 85 a = np.zeros(10, dtype=wrong_type) 86 self.assertRaises(ValueError, min_removal, a) 87 88 def test_wrong_list_input(self): 89 self.assertRaises(ValueError, min_removal, [0., 1.]) 90 91 def test_good_input(self): 92 a = np.zeros(10, dtype=float_type) 93 assert_equal(np.zeros(10, dtype=float_type), min_removal(a)) 94 95 class aubio_alpha_norm(TestCase): 96 97 def test_alpha_norm_of_random(self): 98 x = np.random.rand(1024).astype(float_type) 99 alpha = np.random.rand() * 5. 100 x_alpha_norm = (np.sum(np.abs(x)**alpha)/len(x))**(1/alpha) 101 assert_almost_equal(alpha_norm(x, alpha), x_alpha_norm, decimal = 5) 102 103 class aubio_zero_crossing_rate_test(TestCase): 89 104 90 105 def test_zero_crossing_rate(self): 91 a = array([0,1,-1], dtype='float32') 92 assert_almost_equal (zero_crossing_rate(a), 1./3. ) 93 a = array([0.]*100, dtype='float32') 94 self.assertEquals (zero_crossing_rate(a), 0 ) 95 a = array([-1.]*100, dtype='float32') 96 self.assertEquals (zero_crossing_rate(a), 0 ) 97 a = array([1.]*100, dtype='float32') 98 self.assertEquals (zero_crossing_rate(a), 0 ) 106 a = np.array([0, 1, -1], dtype=float_type) 107 assert_almost_equal(zero_crossing_rate(a), 1./3.) 99 108 100 def test_ alpha_norm_of_array_of_float64(self):101 # check scalar fail102 a = array(1, dtype = 'float64')103 self.assertRaises (ValueError, alpha_norm, a, 1) 104 # check 3d array fail105 a = array([[[1,2],[3,4]]], dtype = 'float64')106 self.assert Raises (ValueError, alpha_norm, a, 1)107 # check float64 1d array fail 108 a = array(range(10), dtype = 'float64')109 self.assertRaises (ValueError, alpha_norm, a, 1)110 # check float64 2d array fail111 a = array([range(10), range(10)], dtype = 'float64') 112 self.assertRaises (ValueError, alpha_norm, a, 1) 109 def test_zero_crossing_rate_zeros(self): 110 a = np.zeros(100, dtype=float_type) 111 self.assertEqual(zero_crossing_rate(a), 0) 112 113 def test_zero_crossing_rate_minus_ones(self): 114 a = np.ones(100, dtype=float_type) 115 self.assertEqual(zero_crossing_rate(a), 0) 116 117 def test_zero_crossing_rate_plus_ones(self): 118 a = np.ones(100, dtype=float_type) 119 self.assertEqual(zero_crossing_rate(a), 0) 120 121 class aubio_fvec_min_removal(TestCase): 113 122 114 123 def test_fvec_min_removal_of_array(self): 115 a = array([20,1,19], dtype='float32')124 a = np.array([20, 1, 19], dtype=float_type) 116 125 b = min_removal(a) 117 assert_equal (array(b), [19, 0, 18]) 118 assert_equal (b, [19, 0, 18]) 119 assert_equal (a, b) 120 a[0] = 0 121 assert_equal (a, b) 126 assert_equal(b, [19, 0, 18]) 122 127 123 def test_fvec_min_removal_of_array_float64(self): 124 a = array([20,1,19], dtype='float64') 125 self.assertRaises (ValueError, min_removal, a) 128 class aubio_fvec_test_memory(TestCase): 126 129 127 def test_fvec_min_removal_of_fvec(self): 128 a = fvec(3) 129 a = array([20, 1, 19], dtype = 'float32') 130 b = min_removal(a) 131 assert_equal (array(b), [19, 0, 18]) 132 assert_equal (b, [19, 0, 18]) 133 assert_equal (a, b) 130 def test_pass_to_numpy(self): 131 a = fvec(10) 132 a[:] = 1. 133 b = a 134 del a 135 assert_equal(b, 1.) 136 c = fvec(10) 137 c = b 138 del b 139 assert_equal(c, 1.) 140 del c 134 141 135 142 if __name__ == '__main__': 136 from unittest import main137 143 main() -
python/tests/test_mathutils.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from unittest import main 3 4 from numpy.testing import TestCase, assert_equal 4 5 from numpy import array, arange, isnan, isinf … … 13 14 unwrap2pi(int(23)) 14 15 unwrap2pi(float(23.)) 15 unwrap2pi( long(23.))16 unwrap2pi(int(23.)) 16 17 unwrap2pi(arange(10)) 17 18 unwrap2pi(arange(10).astype("int")) … … 24 25 unwrap2pi(a) 25 26 a = pi/100. * arange(-600,600).astype("float") 26 b = unwrap2pi(a)27 unwrap2pi(a) 27 28 #print zip(a, b) 28 29 29 try: 30 print unwrap2pi(["23.","24.",25.]) 31 except Exception, e: 32 pass 30 def test_unwrap2pi_fails_on_list(self): 31 with self.assertRaises((TypeError, NotImplementedError)): 32 unwrap2pi(["23.","24.",25.]) 33 33 34 34 def test_unwrap2pi_takes_fvec(self): … … 54 54 55 55 def test_freqtomidi(self): 56 a = array( range(-20, 50000, 100) + [ -1e32, 1e32 ])56 a = array(list(range(-20, 50000, 100)) + [ -1e32, 1e32 ]) 57 57 b = freqtomidi(a) 58 58 #print zip(a, b) … … 62 62 63 63 def test_miditofreq(self): 64 a = range(-30, 200) + [-100000, 10000]64 a = list(range(-30, 200)) + [-100000, 10000] 65 65 b = miditofreq(a) 66 66 #print zip(a, b) … … 70 70 71 71 def test_miditobin(self): 72 a = range(-30, 200) + [-100000, 10000]73 b = [ bintomidi(x, 44100, 512) for x in a ]72 a = list(range(-30, 200)) + [-100000, 10000] 73 b = [ miditobin(x, 44100, 512) for x in a ] 74 74 #print zip(a, b) 75 75 assert_equal ( isnan(array(b)), False ) … … 78 78 79 79 def test_bintomidi(self): 80 a = range(-100, 512)80 a = list(range(-100, 512)) 81 81 b = [ bintomidi(x, 44100, 512) for x in a ] 82 82 #print zip(a, b) … … 86 86 87 87 def test_freqtobin(self): 88 a = range(-20, 50000, 100) + [ -1e32, 1e32 ]88 a = list(range(-20, 50000, 100)) + [ -1e32, 1e32 ] 89 89 b = [ freqtobin(x, 44100, 512) for x in a ] 90 90 #print zip(a, b) … … 94 94 95 95 def test_bintofreq(self): 96 a = range(-20, 148)96 a = list(range(-20, 148)) 97 97 b = [ bintofreq(x, 44100, 512) for x in a ] 98 98 #print zip(a, b) … … 102 102 103 103 if __name__ == '__main__': 104 from unittest import main105 104 main() -
python/tests/test_midi2note.py
r60fc05b rf264b17 28 28 self.assertRaises(ValueError, midi2note, -2) 29 29 30 def test_midi2note_ negative_value(self):30 def test_midi2note_large(self): 31 31 " fails when passed a value greater than 127 " 32 32 self.assertRaises(ValueError, midi2note, 128) -
python/tests/test_musicutils.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from unittest import main 4 import numpy as np 3 5 from numpy.testing import TestCase 4 6 from numpy.testing.utils import assert_equal, assert_almost_equal 5 from numpy import cos, arange6 from math import pi7 8 7 from aubio import window, level_lin, db_spl, silence_detection, level_detection 9 10 from aubio import fvec 8 from aubio import fvec, float_type 11 9 12 10 class aubio_window(TestCase): … … 16 14 17 15 def test_fail_name_not_string(self): 18 try:16 with self.assertRaises(TypeError): 19 17 window(10, 1024) 20 except ValueError, e:21 pass22 else:23 self.fail('non-string window type does not raise a ValueError')24 18 25 19 def test_fail_size_not_int(self): 26 try:20 with self.assertRaises(TypeError): 27 21 window("default", "default") 28 except ValueError, e:29 pass30 else:31 self.fail('non-integer window length does not raise a ValueError')32 22 33 23 def test_compute_hanning_1024(self): 34 24 size = 1024 35 25 aubio_window = window("hanning", size) 36 numpy_window = .5 - .5 * cos(2. * pi *arange(size) / size)26 numpy_window = .5 - .5 * np.cos(2. * np.pi * np.arange(size) / size) 37 27 assert_almost_equal(aubio_window, numpy_window) 38 28 … … 42 32 43 33 def test_fail_not_fvec(self): 44 try:34 with self.assertRaises(ValueError): 45 35 level_lin("default") 46 except ValueError, e:47 pass48 else:49 self.fail('non-number input phase does not raise a TypeError')50 36 51 37 def test_zeros_is_zeros(self): … … 53 39 54 40 def test_minus_ones_is_one(self): 55 from numpy import ones 56 assert_equal(level_lin(-ones(1024, dtype="float32")), 1.) 41 assert_equal(level_lin(-np.ones(1024, dtype = float_type)), 1.) 57 42 58 43 class aubio_db_spl(TestCase): … … 61 46 62 47 def test_fail_not_fvec(self): 63 try:48 with self.assertRaises(ValueError): 64 49 db_spl("default") 65 except ValueError, e:66 pass67 else:68 self.fail('non-number input phase does not raise a TypeError')69 50 70 51 def test_zeros_is_inf(self): 71 from math import isinf 72 assert isinf(db_spl(fvec(1024))) 52 assert np.isinf(db_spl(fvec(1024))) 73 53 74 54 def test_minus_ones_is_zero(self): 75 from numpy import ones 76 assert_equal(db_spl(-ones(1024, dtype="float32")), 0.) 55 assert_equal(db_spl(-np.ones(1024, dtype = float_type)), 0.) 77 56 78 57 class aubio_silence_detection(TestCase): … … 81 60 82 61 def test_fail_not_fvec(self): 83 try:62 with self.assertRaises(ValueError): 84 63 silence_detection("default", -70) 85 except ValueError, e:86 pass87 else:88 self.fail('non-number input phase does not raise a TypeError')89 64 90 65 def test_zeros_is_one(self): 91 from math import isinf92 66 assert silence_detection(fvec(1024), -70) == 1 93 67 94 68 def test_minus_ones_is_zero(self): 95 69 from numpy import ones 96 assert silence_detection(ones(1024, dtype ="float32"), -70) == 070 assert silence_detection(ones(1024, dtype = float_type), -70) == 0 97 71 98 72 class aubio_level_detection(TestCase): … … 101 75 102 76 def test_fail_not_fvec(self): 103 try:77 with self.assertRaises(ValueError): 104 78 level_detection("default", -70) 105 except ValueError, e:106 pass107 else:108 self.fail('non-number input phase does not raise a TypeError')109 79 110 80 def test_zeros_is_one(self): 111 from math import isinf112 81 assert level_detection(fvec(1024), -70) == 1 113 82 114 83 def test_minus_ones_is_zero(self): 115 84 from numpy import ones 116 assert level_detection(ones(1024, dtype ="float32"), -70) == 085 assert level_detection(ones(1024, dtype = float_type), -70) == 0 117 86 118 87 if __name__ == '__main__': 119 from unittest import main120 88 main() -
python/tests/test_note2midi.py
r60fc05b rf264b17 2 2 # -*- coding: utf-8 -*- 3 3 4 from aubio import note2midi 4 from __future__ import unicode_literals 5 6 from aubio import note2midi, freq2note 5 7 import unittest 6 8 … … 15 17 ( 'A#4', 70 ), 16 18 ( 'Bb4', 70 ), 17 ( u'B♭4', 70 ),19 ( 'B♭4', 70 ), 18 20 ( 'G8', 115 ), 19 ( u'G♯8', 116 ),21 ( 'G♯8', 116 ), 20 22 ( 'G9', 127 ), 21 ( u'G\udd2a2', 45 ),22 ( u'B\ufffd2', 45 ),23 ( u'A♮2', 45 ),23 ( 'G\udd2a2', 45 ), 24 ( 'B\ufffd2', 45 ), 25 ( 'A♮2', 45 ), 24 26 ) 25 27 … … 50 52 51 53 def test_note2midi_out_of_range(self): 52 " fails when passed a out of range note"54 " fails when passed a note out of range" 53 55 self.assertRaises(ValueError, note2midi, 'A9') 56 57 def test_note2midi_wrong_note_name(self): 58 " fails when passed a note with a wrong name" 59 self.assertRaises(ValueError, note2midi, 'W9') 60 61 def test_note2midi_low_octave(self): 62 " fails when passed a note with a too low octave" 63 self.assertRaises(ValueError, note2midi, 'C-9') 54 64 55 65 def test_note2midi_wrong_data_type(self): … … 57 67 self.assertRaises(TypeError, note2midi, 123) 58 68 69 70 class freq2note_simple_test(unittest.TestCase): 71 72 def test_freq2note(self): 73 " make sure freq2note(441) == A4 " 74 self.assertEqual("A4", freq2note(441)) 75 59 76 if __name__ == '__main__': 60 77 unittest.main() -
python/tests/test_onset.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite4 from numpy.testing import assert_equal, assert_almost_equal3 from unittest import main 4 from numpy.testing import TestCase, assert_equal, assert_almost_equal 5 5 from aubio import onset 6 6 … … 85 85 86 86 if __name__ == '__main__': 87 from unittest import main88 87 main() -
python/tests/test_phasevoc.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, assert_equal, assert_almost_equal 4 from aubio import fvec, cvec, pvoc 5 from numpy import array, shape 6 from numpy.random import random 3 from numpy.testing import TestCase, assert_equal, assert_array_less 4 from aubio import fvec, cvec, pvoc, float_type 5 from nose2 import main 6 from nose2.tools import params 7 import numpy as np 7 8 8 precision = 6 9 if float_type == 'float32': 10 max_sq_error = 1.e-12 11 else: 12 max_sq_error = 1.e-29 13 14 def create_sine(hop_s, freq, samplerate): 15 t = np.arange(hop_s).astype(float_type) 16 return np.sin( 2. * np.pi * freq * t / float(samplerate)) 17 18 def create_noise(hop_s): 19 return np.random.rand(hop_s).astype(float_type) * 2. - 1. 9 20 10 21 class aubio_pvoc_test_case(TestCase): … … 31 42 f = pvoc (win_s, hop_s) 32 43 t = fvec (hop_s) 33 for time in range( 4 * win_s / hop_s):44 for _ in range( int ( 4 * win_s / hop_s ) ): 34 45 s = f(t) 35 46 r = f.rdo(s) 36 assert_equal ( array(t), 0)37 assert_equal ( s.norm, 0 )38 assert_equal ( s.phas, 0 )39 assert_equal ( r, 0 )47 assert_equal ( t, 0.) 48 assert_equal ( s.norm, 0.) 49 assert_equal ( s.phas, 0.) 50 assert_equal ( r, 0.) 40 51 41 def test_resynth_two_steps(self): 42 """ check the resynthesis of steps is correct with 50% overlap """ 43 hop_s = 512 44 buf_s = hop_s * 2 52 @params( 53 ( 256, 8), 54 ( 256, 4), 55 ( 256, 2), 56 ( 512, 8), 57 ( 512, 4), 58 ( 512, 2), 59 #( 129, 2), 60 #( 320, 4), 61 #( 13, 8), 62 (1024, 8), 63 (1024, 4), 64 (1024, 2), 65 (2048, 8), 66 (2048, 4), 67 (2048, 2), 68 (4096, 8), 69 (4096, 4), 70 (4096, 2), 71 (8192, 8), 72 (8192, 4), 73 (8192, 2), 74 ) 75 def test_resynth_steps_noise(self, hop_s, ratio): 76 """ check the resynthesis of a random signal is correct """ 77 sigin = create_noise(hop_s) 78 self.reconstruction(sigin, hop_s, ratio) 79 80 @params( 81 (44100, 256, 8, 441), 82 (44100, 256, 4, 1203), 83 (44100, 256, 2, 3045), 84 (44100, 512, 8, 445), 85 (44100, 512, 4, 445), 86 (44100, 512, 2, 445), 87 (44100, 1024, 8, 445), 88 (44100, 1024, 4, 445), 89 (44100, 1024, 2, 445), 90 ( 8000, 1024, 2, 445), 91 (22050, 1024, 2, 445), 92 (22050, 256, 8, 445), 93 (96000, 1024, 8, 47000), 94 (96000, 1024, 8, 20), 95 ) 96 def test_resynth_steps_sine(self, samplerate, hop_s, ratio, freq): 97 """ check the resynthesis of a sine is correct """ 98 sigin = create_sine(hop_s, freq, samplerate) 99 self.reconstruction(sigin, hop_s, ratio) 100 101 def reconstruction(self, sigin, hop_s, ratio): 102 buf_s = hop_s * ratio 45 103 f = pvoc(buf_s, hop_s) 46 sigin = fvec(hop_s)47 104 zeros = fvec(hop_s) 48 # negative step 49 sigin[20:50] = -.1 50 # positive step 51 sigin[100:200] = .1 52 s1 = f(sigin) 53 r1 = f.rdo(s1) 54 s2 = f(zeros) 55 r2 = f.rdo(s2) 56 #self.plot_this ( s2.norm.T ) 57 assert_almost_equal ( r2, sigin, decimal = precision ) 58 59 def test_resynth_three_steps(self): 60 """ check the resynthesis of steps is correct with 25% overlap """ 61 hop_s = 16 62 buf_s = hop_s * 4 63 sigin = fvec(hop_s) 64 zeros = fvec(hop_s) 65 f = pvoc(buf_s, hop_s) 66 for i in xrange(hop_s): 67 sigin[i] = random() * 2. - 1. 68 t2 = f.rdo( f(sigin) ) 69 t2 = f.rdo( f(zeros) ) 70 t2 = f.rdo( f(zeros) ) 71 t2 = f.rdo( f(zeros) ) 72 assert_almost_equal( sigin, t2, decimal = precision ) 73 74 def plot_this( self, this ): 75 from pylab import semilogy, show 76 semilogy ( this ) 77 show () 105 r2 = f.rdo( f(sigin) ) 106 for _ in range(1, ratio): 107 r2 = f.rdo( f(zeros) ) 108 # compute square errors 109 sq_error = (r2 - sigin)**2 110 # make sure all square errors are less than desired precision 111 assert_array_less(sq_error, max_sq_error) 112 113 class aubio_pvoc_strange_params(TestCase): 114 115 def test_win_size_short(self): 116 with self.assertRaises(RuntimeError): 117 pvoc(1, 1) 118 119 def test_hop_size_long(self): 120 with self.assertRaises(RuntimeError): 121 pvoc(1024, 1025) 122 123 def test_large_input_timegrain(self): 124 win_s = 1024 125 f = pvoc(win_s) 126 t = fvec(win_s + 1) 127 with self.assertRaises(ValueError): 128 f(t) 129 130 def test_small_input_timegrain(self): 131 win_s = 1024 132 f = pvoc(win_s) 133 t = fvec(1) 134 with self.assertRaises(ValueError): 135 f(t) 136 137 def test_large_input_fftgrain(self): 138 win_s = 1024 139 f = pvoc(win_s) 140 s = cvec(win_s + 5) 141 with self.assertRaises(ValueError): 142 f.rdo(s) 143 144 def test_small_input_fftgrain(self): 145 win_s = 1024 146 f = pvoc(win_s) 147 s = cvec(16) 148 with self.assertRaises(ValueError): 149 f.rdo(s) 150 151 class aubio_pvoc_wrong_params(TestCase): 152 153 def test_wrong_buf_size(self): 154 win_s = -1 155 with self.assertRaises(ValueError): 156 pvoc(win_s) 157 158 def test_buf_size_too_small(self): 159 win_s = 1 160 with self.assertRaises(RuntimeError): 161 pvoc(win_s) 162 163 def test_hop_size_negative(self): 164 win_s = 512 165 hop_s = -2 166 with self.assertRaises(ValueError): 167 pvoc(win_s, hop_s) 168 169 def test_hop_size_too_small(self): 170 win_s = 1 171 hop_s = 1 172 with self.assertRaises(RuntimeError): 173 pvoc(win_s, hop_s) 174 175 def test_buf_size_not_power_of_two(self): 176 win_s = 320 177 hop_s = win_s // 2 178 try: 179 with self.assertRaises(RuntimeError): 180 pvoc(win_s, hop_s) 181 except AssertionError: 182 # when compiled with fftw3, aubio supports non power of two fft sizes 183 self.skipTest('creating aubio.pvoc with size %d did not fail' % win_s) 78 184 79 185 if __name__ == '__main__': 80 from unittest import main 81 main() 186 main() 82 187 -
python/tests/test_pitch.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from unittest import TestCase 4 from numpy.testing import assert_equal, assert_almost_equal 5 from numpy import random, sin, arange, mean, median, isnan 6 from math import pi 7 from aubio import fvec, pitch, freqtomidi 3 from unittest import TestCase, main 4 from numpy.testing import assert_equal 5 from numpy import sin, arange, mean, median, isnan, pi 6 from aubio import fvec, pitch, freqtomidi, float_type 8 7 9 8 class aubio_pitch_Good_Values(TestCase): … … 25 24 p = pitch('default', 2048, 512, 32000) 26 25 f = fvec (512) 27 for i in xrange(10): assert_equal (p(f), 0.)26 for _ in range(10): assert_equal (p(f), 0.) 28 27 29 28 def test_run_on_ones(self): … … 32 31 f = fvec (512) 33 32 f[:] = 1 34 for i in xrange(10): assert_equal (p(f), 0.)33 for _ in range(10): assert_equal (p(f), 0.) 35 34 36 35 class aubio_pitch_Sinusoid(TestCase): … … 51 50 52 51 def build_sinusoid(self, length, freq, samplerate): 53 return sin( 2. * pi * arange(length).astype( 'float32') * freq / samplerate)52 return sin( 2. * pi * arange(length).astype(float_type) * freq / samplerate) 54 53 55 54 def run_pitch(self, p, input_vec, freq): 56 count = 057 55 pitches, errors = [], [] 58 56 input_blocks = input_vec.reshape((-1, p.hop_size)) … … 64 62 assert_equal ( isnan(pitches), False ) 65 63 # cut the first candidates 66 cut = ( p.buf_size - p.hop_size ) / p.hop_size64 #cut = ( p.buf_size - p.hop_size ) / p.hop_size 67 65 pitches = pitches[2:] 68 66 errors = errors[2:] … … 125 123 126 124 if __name__ == '__main__': 127 from unittest import main128 125 main() -
python/tests/test_sink.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, assert_equal, assert_almost_equal 3 from nose2 import main 4 from nose2.tools import params 5 from numpy.testing import TestCase 4 6 from aubio import fvec, source, sink 5 from numpy import array6 7 from utils import list_all_sounds, get_tmp_sink_path, del_tmp_sink_path 7 8 8 9 list_of_sounds = list_all_sounds('sounds') 10 samplerates = [0, 44100, 8000, 32000] 11 hop_sizes = [512, 1024, 64] 12 9 13 path = None 10 14 11 15 many_files = 300 # 256 opened files is too much 12 16 17 all_params = [] 18 for soundfile in list_of_sounds: 19 for hop_size in hop_sizes: 20 for samplerate in samplerates: 21 all_params.append((hop_size, samplerate, soundfile)) 22 13 23 class aubio_sink_test_case(TestCase): 24 25 def setUp(self): 26 if not len(list_of_sounds): 27 self.skipTest('add some sound files in \'python/tests/sounds\'') 14 28 15 29 def test_many_sinks(self): … … 24 38 sink_list.append(g) 25 39 write = 32 26 for nin range(200):40 for _ in range(200): 27 41 vec = fvec(write) 28 42 g(vec, write) … … 30 44 shutil.rmtree(tmpdir) 31 45 32 def test_many_sinks_not_closed(self): 33 from tempfile import mkdtemp 34 import os.path 35 import shutil 36 tmpdir = mkdtemp() 37 sink_list = [] 46 @params(*all_params) 47 def test_read_and_write(self, hop_size, samplerate, path): 48 38 49 try: 39 for i in range(many_files): 40 path = os.path.join(tmpdir, 'f-' + str(i) + '.wav') 41 g = sink(path, 0) 42 sink_list.append(g) 43 write = 256 44 for n in range(200): 45 vec = fvec(write) 46 g(vec, write) 47 except StandardError: 48 pass 49 else: 50 self.fail("does not fail on too many files open") 51 for g in sink_list: 52 g.close() 53 shutil.rmtree(tmpdir) 50 f = source(path, samplerate, hop_size) 51 except RuntimeError as e: 52 self.skipTest('failed opening with hop_s = {:d}, samplerate = {:d} ({:s})'.format(hop_size, samplerate, str(e))) 53 if samplerate == 0: samplerate = f.samplerate 54 sink_path = get_tmp_sink_path() 55 g = sink(sink_path, samplerate) 56 total_frames = 0 57 while True: 58 vec, read = f() 59 g(vec, read) 60 total_frames += read 61 if read < f.hop_size: break 62 del_tmp_sink_path(sink_path) 54 63 55 def test_read_and_write(self): 56 57 if not len(list_of_sounds): 58 self.skipTest('add some sound files in \'python/tests/sounds\'') 59 60 for path in list_of_sounds: 61 for samplerate, hop_size in zip([0, 44100, 8000, 32000], [512, 1024, 64, 256]): 62 f = source(path, samplerate, hop_size) 63 if samplerate == 0: samplerate = f.samplerate 64 sink_path = get_tmp_sink_path() 65 g = sink(sink_path, samplerate) 66 total_frames = 0 67 while True: 68 vec, read = f() 69 g(vec, read) 70 total_frames += read 71 if read < f.hop_size: break 72 if 0: 73 print "read", "%.2fs" % (total_frames / float(f.samplerate) ), 74 print "(", total_frames, "frames", "in", 75 print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")", 76 print "from", f.uri, 77 print "to", g.uri 78 del_tmp_sink_path(sink_path) 79 80 def test_read_and_write_multi(self): 81 82 if not len(list_of_sounds): 83 self.skipTest('add some sound files in \'python/tests/sounds\'') 84 85 for path in list_of_sounds: 86 for samplerate, hop_size in zip([0, 44100, 8000, 32000], [512, 1024, 64, 256]): 87 f = source(path, samplerate, hop_size) 88 if samplerate == 0: samplerate = f.samplerate 89 sink_path = get_tmp_sink_path() 90 g = sink(sink_path, samplerate, channels = f.channels) 91 total_frames = 0 92 while True: 93 vec, read = f.do_multi() 94 g.do_multi(vec, read) 95 total_frames += read 96 if read < f.hop_size: break 97 if 0: 98 print "read", "%.2fs" % (total_frames / float(f.samplerate) ), 99 print "(", total_frames, "frames", "in", 100 print f.channels, "channels", "in", 101 print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")", 102 print "from", f.uri, 103 print "to", g.uri, 104 print "in", g.channels, "channels" 105 del_tmp_sink_path(sink_path) 64 @params(*all_params) 65 def test_read_and_write_multi(self, hop_size, samplerate, path): 66 try: 67 f = source(path, samplerate, hop_size) 68 except RuntimeError as e: 69 self.skipTest('failed opening with hop_s = {:d}, samplerate = {:d} ({:s})'.format(hop_size, samplerate, str(e))) 70 if samplerate == 0: samplerate = f.samplerate 71 sink_path = get_tmp_sink_path() 72 g = sink(sink_path, samplerate, channels = f.channels) 73 total_frames = 0 74 while True: 75 vec, read = f.do_multi() 76 g.do_multi(vec, read) 77 total_frames += read 78 if read < f.hop_size: break 79 del_tmp_sink_path(sink_path) 106 80 107 81 def test_close_file(self): … … 121 95 122 96 if __name__ == '__main__': 123 from unittest import main124 97 main() -
python/tests/test_slicing.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, run_module_suite 4 from numpy.testing import assert_equal, assert_almost_equal 5 3 from unittest import main 4 from numpy.testing import TestCase, assert_equal 6 5 from aubio import slice_source_at_stamps 7 from utils import * 6 from utils import count_files_in_directory, get_default_test_sound 7 from utils import count_samples_in_directory, count_samples_in_file 8 8 9 9 import tempfile … … 147 147 148 148 if __name__ == '__main__': 149 from unittest import main150 149 main() -
python/tests/test_source.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from numpy.testing import TestCase, assert_equal, assert_almost_equal 4 from aubio import fvec, source 5 from numpy import array 3 from nose2 import main 4 from nose2.tools import params 5 from numpy.testing import TestCase 6 from aubio import source 6 7 from utils import list_all_sounds 7 8 8 9 list_of_sounds = list_all_sounds('sounds') 10 samplerates = [0, 44100, 8000, 32000] 11 hop_sizes = [512, 1024, 64] 12 9 13 path = None 14 15 all_params = [] 16 for soundfile in list_of_sounds: 17 for hop_size in hop_sizes: 18 for samplerate in samplerates: 19 all_params.append((hop_size, samplerate, soundfile)) 20 10 21 11 22 class aubio_source_test_case_base(TestCase): … … 13 24 def setUp(self): 14 25 if not len(list_of_sounds): self.skipTest('add some sound files in \'python/tests/sounds\'') 26 self.default_test_sound = list_of_sounds[0] 15 27 16 28 class aubio_source_test_case(aubio_source_test_case_base): … … 36 48 total_frames = 0 37 49 while True: 38 vec, read = f()50 _ , read = f() 39 51 total_frames += read 40 52 if read < f.hop_size: break 41 print "read", "%.2fs" % (total_frames / float(f.samplerate) ), 42 print "(", total_frames, "frames", "in", 43 print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")", 44 print "from", f.uri 53 #result_str = "read {:.2f}s ({:d} frames in {:d} blocks at {:d}Hz) from {:s}" 54 #result_params = total_frames / float(f.samplerate), total_frames, total_frames//f.hop_size, f.samplerate, f.uri 55 #print (result_str.format(*result_params)) 45 56 return total_frames 46 57 47 def test_samplerate_hopsize(self): 48 for p in list_of_sounds: 49 for samplerate, hop_size in zip([0, 44100, 8000, 32000], [ 512, 512, 64, 256]): 50 f = source(p, samplerate, hop_size) 51 assert f.samplerate != 0 52 self.read_from_source(f) 58 @params(*all_params) 59 def test_samplerate_hopsize(self, hop_size, samplerate, soundfile): 60 try: 61 f = source(soundfile, samplerate, hop_size) 62 except RuntimeError as e: 63 self.skipTest('failed opening with hop_s = {:d}, samplerate = {:d} ({:s})'.format(hop_size, samplerate, str(e))) 64 assert f.samplerate != 0 65 self.read_from_source(f) 53 66 54 def test_samplerate_none(self):55 for p in list_of_sounds:56 57 58 67 @params(*list_of_sounds) 68 def test_samplerate_none(self, p): 69 f = source(p) 70 assert f.samplerate != 0 71 self.read_from_source(f) 59 72 60 def test_samplerate_0(self): 61 for p in list_of_sounds: 62 f = source(p, 0) 63 assert f.samplerate != 0 64 self.read_from_source(f) 73 @params(*list_of_sounds) 74 def test_samplerate_0(self, p): 75 f = source(p, 0) 76 assert f.samplerate != 0 77 self.read_from_source(f) 78 79 @params(*list_of_sounds) 80 def test_zero_hop_size(self, p): 81 f = source(p, 0, 0) 82 assert f.samplerate != 0 83 assert f.hop_size != 0 84 self.read_from_source(f) 85 86 @params(*list_of_sounds) 87 def test_seek_to_half(self, p): 88 from random import randint 89 f = source(p, 0, 0) 90 assert f.samplerate != 0 91 assert f.hop_size != 0 92 a = self.read_from_source(f) 93 c = randint(0, a) 94 f.seek(c) 95 b = self.read_from_source(f) 96 assert a == b + c 97 98 @params(*list_of_sounds) 99 def test_duration(self, p): 100 total_frames = 0 101 f = source(p) 102 duration = f.duration 103 while True: 104 _, read = f() 105 total_frames += read 106 if read < f.hop_size: break 107 self.assertEqual(duration, total_frames) 108 109 110 class aubio_source_test_wrong_params(TestCase): 111 112 def test_wrong_file(self): 113 with self.assertRaises(RuntimeError): 114 source('path_to/unexisting file.mp3') 115 116 class aubio_source_test_wrong_params_with_file(aubio_source_test_case_base): 65 117 66 118 def test_wrong_samplerate(self): 67 for p in list_of_sounds: 68 try: 69 f = source(p, -1) 70 except ValueError, e: 71 pass 72 else: 73 self.fail('negative samplerate does not raise ValueError') 119 with self.assertRaises(ValueError): 120 source(self.default_test_sound, -1) 74 121 75 122 def test_wrong_hop_size(self): 76 for p in list_of_sounds: 77 try: 78 f = source(p, 0, -1) 79 except ValueError, e: 80 pass 81 else: 82 self.fail('negative hop_size does not raise ValueError') 123 with self.assertRaises(ValueError): 124 source(self.default_test_sound, 0, -1) 83 125 84 def test_zero_hop_size(self): 85 for p in list_of_sounds: 86 f = source(p, 0, 0) 87 assert f.samplerate != 0 88 assert f.hop_size != 0 89 self.read_from_source(f) 126 def test_wrong_channels(self): 127 with self.assertRaises(ValueError): 128 source(self.default_test_sound, 0, 0, -1) 90 129 91 def test_seek_to_half(self): 92 from random import randint 93 for p in list_of_sounds: 94 f = source(p, 0, 0) 95 assert f.samplerate != 0 96 assert f.hop_size != 0 97 a = self.read_from_source(f) 98 c = randint(0, a) 99 f.seek(c) 100 b = self.read_from_source(f) 101 assert a == b + c 130 def test_wrong_seek(self): 131 f = source(self.default_test_sound) 132 with self.assertRaises(ValueError): 133 f.seek(-1) 134 135 def test_wrong_seek_too_large(self): 136 f = source(self.default_test_sound) 137 try: 138 with self.assertRaises(ValueError): 139 f.seek(f.duration + f.samplerate * 10) 140 except AssertionError: 141 self.skipTest('seeking after end of stream failed raising ValueError') 102 142 103 143 class aubio_source_readmulti_test_case(aubio_source_read_test_case): … … 106 146 total_frames = 0 107 147 while True: 108 vec, read = f.do_multi()148 _, read = f.do_multi() 109 149 total_frames += read 110 150 if read < f.hop_size: break 111 print "read", "%.2fs" % (total_frames / float(f.samplerate) ), 112 print "(", total_frames, "frames", "in", 113 print f.channels, "channels and", 114 print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")", 115 print "from", f.uri 151 #result_str = "read {:.2f}s ({:d} frames in {:d} channels and {:d} blocks at {:d}Hz) from {:s}" 152 #result_params = total_frames / float(f.samplerate), total_frames, f.channels, int(total_frames/f.hop_size), f.samplerate, f.uri 153 #print (result_str.format(*result_params)) 116 154 return total_frames 117 155 118 156 if __name__ == '__main__': 119 from unittest import main120 157 main() -
python/tests/test_specdesc.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from unittest import main 3 4 from numpy.testing import TestCase, assert_equal, assert_almost_equal 4 5 from numpy import random, arange, log, zeros 5 from aubio import specdesc, cvec 6 from math import pi 6 from aubio import specdesc, cvec, float_type 7 7 8 8 methods = ["default", … … 30 30 31 31 for method in methods: 32 o = specdesc(method, buf_size) 33 assert_equal ([o.buf_size, o.method], [buf_size, method]) 34 35 spec = cvec(buf_size) 36 spec.norm[0] = 1 37 spec.norm[1] = 1./2. 38 #print "%20s" % method, str(o(spec)) 39 o(spec) 40 spec.norm = random.random_sample((len(spec.norm),)).astype('float32') 41 spec.phas = random.random_sample((len(spec.phas),)).astype('float32') 42 #print "%20s" % method, str(o(spec)) 43 assert (o(spec) != 0.) 44 45 def test_hfc(self): 46 o = specdesc("hfc", buf_size) 47 spec = cvec(buf_size) 48 # hfc of zeros is zero 49 assert_equal (o(spec), 0.) 50 # hfc of ones is sum of all bin numbers 51 spec.norm[:] = 1 52 expected = sum(range(buf_size/2 + 2)) 53 assert_equal (o(spec), expected) 54 # changing phase doesn't change anything 55 spec.phas[:] = 1 56 assert_equal (o(spec), sum(range(buf_size/2 + 2))) 32 o = specdesc(method, buf_size) 33 assert_equal ([o.buf_size, o.method], [buf_size, method]) 34 35 spec = cvec(buf_size) 36 spec.norm[0] = 1 37 spec.norm[1] = 1./2. 38 #print "%20s" % method, str(o(spec)) 39 o(spec) 40 spec.norm = random.random_sample((len(spec.norm),)).astype(float_type) 41 spec.phas = random.random_sample((len(spec.phas),)).astype(float_type) 42 #print "%20s" % method, str(o(spec)) 43 assert (o(spec) != 0.) 57 44 58 45 def test_phase(self): … … 61 48 # phase of zeros is zero 62 49 assert_equal (o(spec), 0.) 63 spec.phas = random.random_sample((len(spec.phas),)).astype( 'float32')50 spec.phas = random.random_sample((len(spec.phas),)).astype(float_type) 64 51 # phase of random is not zero 65 52 spec.norm[:] = 1 … … 71 58 # specdiff of zeros is zero 72 59 assert_equal (o(spec), 0.) 73 spec.phas = random.random_sample((len(spec.phas),)).astype( 'float32')60 spec.phas = random.random_sample((len(spec.phas),)).astype(float_type) 74 61 # phase of random is not zero 75 62 spec.norm[:] = 1 … … 80 67 c = cvec() 81 68 assert_equal( 0., o(c)) 82 a = arange(c.length, dtype= 'float32')69 a = arange(c.length, dtype=float_type) 83 70 c.norm = a 84 71 assert_equal (a, c.norm) … … 89 76 c = cvec() 90 77 assert_equal( 0., o(c)) 91 a = arange(c.length, dtype= 'float32')78 a = arange(c.length, dtype=float_type) 92 79 c.norm = a 93 80 assert_equal (a, c.norm) … … 102 89 c = cvec() 103 90 assert_equal( 0., o(c)) 104 a = arange(c.length, dtype= 'float32')91 a = arange(c.length, dtype=float_type) 105 92 c.norm = a 106 93 assert_almost_equal( sum(a * log(1.+ a/1.e-1 ) ) / o(c), 1., decimal=6) … … 110 97 c = cvec() 111 98 assert_equal( 0., o(c)) 112 a = arange(c.length, dtype= 'float32')99 a = arange(c.length, dtype=float_type) 113 100 c.norm = a 114 101 assert_almost_equal( sum(log(1.+ a/1.e-1 ) ) / o(c), 1, decimal=6) … … 118 105 c = cvec() 119 106 assert_equal( 0., o(c)) 120 a = arange(c.length, dtype= 'float32')107 a = arange(c.length, dtype=float_type) 121 108 c.norm = a 122 109 assert_equal( sum(a), o(c)) 123 110 assert_equal( 0, o(c)) 124 c.norm = zeros(c.length, dtype= 'float32')111 c.norm = zeros(c.length, dtype=float_type) 125 112 assert_equal( 0, o(c)) 126 113 … … 130 117 # make sure centroid of zeros is zero 131 118 assert_equal( 0., o(c)) 132 a = arange(c.length, dtype= 'float32')119 a = arange(c.length, dtype=float_type) 133 120 c.norm = a 134 121 centroid = sum(a*a) / sum(a) … … 141 128 o = specdesc("spread") 142 129 c = cvec(2048) 143 ramp = arange(c.length, dtype= 'float32')130 ramp = arange(c.length, dtype=float_type) 144 131 assert_equal( 0., o(c)) 145 132 … … 154 141 c = cvec() 155 142 assert_equal( 0., o(c)) 156 a = arange(c.length, dtype= 'float32')143 a = arange(c.length, dtype=float_type) 157 144 c.norm = a 158 145 centroid = sum(a*a) / sum(a) … … 168 155 c = cvec() 169 156 assert_equal( 0., o(c)) 170 a = arange(c.length, dtype= 'float32')157 a = arange(c.length, dtype=float_type) 171 158 c.norm = a 172 159 centroid = sum(a*a) / sum(a) … … 179 166 c = cvec() 180 167 assert_equal( 0., o(c)) 181 a = arange(c.length * 2, 0, -2, dtype= 'float32')182 k = arange(c.length, dtype= 'float32')168 a = arange(c.length * 2, 0, -2, dtype=float_type) 169 k = arange(c.length, dtype=float_type) 183 170 c.norm = a 184 171 num = len(a) * sum(k*a) - sum(k)*sum(a) … … 187 174 assert_almost_equal (slope, o(c), decimal = 5) 188 175 189 a = arange(0, c.length * 2, +2, dtype= 'float32')176 a = arange(0, c.length * 2, +2, dtype=float_type) 190 177 c.norm = a 191 178 num = len(a) * sum(k*a) - sum(k)*sum(a) … … 194 181 assert_almost_equal (slope, o(c), decimal = 5) 195 182 196 a = arange(0, c.length * 2, +2, dtype= 'float32')183 a = arange(0, c.length * 2, +2, dtype=float_type) 197 184 c.norm = a * 2 198 185 assert_almost_equal (slope, o(c), decimal = 5) … … 202 189 c = cvec() 203 190 assert_equal( 0., o(c)) 204 a = arange(c.length * 2, 0, -2, dtype= 'float32')205 k = arange(c.length, dtype= 'float32')191 a = arange(c.length * 2, 0, -2, dtype=float_type) 192 k = arange(c.length, dtype=float_type) 206 193 c.norm = a 207 194 decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:]) 208 195 assert_almost_equal (decrease, o(c), decimal = 5) 209 196 210 a = arange(0, c.length * 2, +2, dtype= 'float32')197 a = arange(0, c.length * 2, +2, dtype=float_type) 211 198 c.norm = a 212 199 decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:]) 213 200 assert_almost_equal (decrease, o(c), decimal = 5) 214 201 215 a = arange(0, c.length * 2, +2, dtype= 'float32')202 a = arange(0, c.length * 2, +2, dtype=float_type) 216 203 c.norm = a * 2 217 204 decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:]) … … 222 209 c = cvec() 223 210 assert_equal( 0., o(c)) 224 a = arange(c.length * 2, 0, -2, dtype='float32') 225 k = arange(c.length, dtype='float32') 211 a = arange(c.length * 2, 0, -2, dtype=float_type) 226 212 c.norm = a 227 213 cumsum = .95*sum(a*a) 228 214 i = 0; rollsum = 0 229 215 while rollsum < cumsum: 230 rollsum += a[i]*a[i]231 i+=1216 rollsum += a[i]*a[i] 217 i+=1 232 218 rolloff = i 233 219 assert_equal (rolloff, o(c)) 234 220 221 class aubio_specdesc_wrong(TestCase): 222 223 def test_negative(self): 224 with self.assertRaises(ValueError): 225 specdesc("default", -10) 226 227 def test_unknown(self): 228 # FIXME should fail? 229 with self.assertRaises(ValueError): 230 specdesc("unknown", 512) 231 self.skipTest('todo: new_specdesc should fail on wrong method') 235 232 236 233 if __name__ == '__main__': 237 from unittest import main238 234 main() -
python/tests/test_zero_crossing_rate.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 from unittest import main 3 4 from numpy.testing import TestCase 4 5 5 from aubio import fvec, zero_crossing_rate 6 6 … … 23 23 def test_impulse(self): 24 24 """ check zero crossing rate on a buffer with an impulse """ 25 self.vector[ buf_size / 2] = 1.25 self.vector[int(buf_size / 2)] = 1. 26 26 self.assertEqual(0., zero_crossing_rate(self.vector)) 27 27 28 28 def test_negative_impulse(self): 29 29 """ check zero crossing rate on a buffer with a negative impulse """ 30 self.vector[ buf_size / 2] = -1.30 self.vector[int(buf_size / 2)] = -1. 31 31 self.assertEqual(2./buf_size, zero_crossing_rate(self.vector)) 32 32 33 33 def test_single(self): 34 34 """ check zero crossing rate on single crossing """ 35 self.vector[ buf_size / 2- 1] = 1.36 self.vector[ buf_size / 2] = -1.35 self.vector[int(buf_size / 2) - 1] = 1. 36 self.vector[int(buf_size / 2)] = -1. 37 37 self.assertEqual(2./buf_size, zero_crossing_rate(self.vector)) 38 38 39 39 def test_single_with_gap(self): 40 40 """ check zero crossing rate on single crossing with a gap""" 41 self.vector[ buf_size / 2- 2] = 1.42 self.vector[ buf_size / 2] = -1.41 self.vector[int(buf_size / 2) - 2] = 1. 42 self.vector[int(buf_size / 2)] = -1. 43 43 self.assertEqual(2./buf_size, zero_crossing_rate(self.vector)) 44 44 45 45 if __name__ == '__main__': 46 from unittest import main47 46 main() -
python/tests/utils.py
r60fc05b rf264b17 1 1 #! /usr/bin/env python 2 2 3 import os 4 import glob 5 import numpy as np 6 from tempfile import mkstemp 7 3 8 def array_from_text_file(filename, dtype = 'float'): 4 import os.path5 from numpy import array6 9 filename = os.path.join(os.path.dirname(__file__), filename) 7 return array([line.split() for line in open(filename).readlines()], 8 dtype = dtype) 10 with open(filename) as f: 11 lines = f.readlines() 12 return np.array([line.split() for line in lines], 13 dtype = dtype) 9 14 10 15 def list_all_sounds(rel_dir): 11 import os.path, glob12 16 datadir = os.path.join(os.path.dirname(__file__), rel_dir) 13 17 return glob.glob(os.path.join(datadir,'*.*')) … … 21 25 22 26 def get_tmp_sink_path(): 23 from tempfile import mkstemp24 import os25 27 fd, path = mkstemp() 26 28 os.close(fd) … … 28 30 29 31 def del_tmp_sink_path(path): 30 import os 31 os.unlink(path) 32 try: 33 os.unlink(path) 34 except WindowsError as e: 35 print("deleting {:s} failed ({:s}), reopening".format(path, repr(e))) 36 with open(path, 'wb') as f: 37 f.close() 38 try: 39 os.unlink(path) 40 except WindowsError as f: 41 print("deleting {:s} failed ({:s}), aborting".format(path, repr(e))) 32 42 33 43 def array_from_yaml_file(filename): … … 44 54 total_frames = 0 45 55 while True: 46 samples, read = s()56 _, read = s() 47 57 total_frames += read 48 58 if read < hopsize: break … … 50 60 51 61 def count_samples_in_directory(samples_dir): 52 import os53 62 total_frames = 0 54 63 for f in os.walk(samples_dir): … … 61 70 62 71 def count_files_in_directory(samples_dir): 63 import os64 72 total_files = 0 65 73 for f in os.walk(samples_dir):
Note: See TracChangeset
for help on using the changeset viewer.