Changeset f264b17 for python


Ignore:
Timestamp:
Jun 22, 2016, 1:00:10 PM (9 years ago)
Author:
Paul Brossier <piem@piem.org>
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.
Message:

Merge branch 'master' into notes

Location:
python
Files:
11 added
7 deleted
65 edited

Legend:

Unmodified
Added
Removed
  • python/README

    r60fc05b rf264b17  
    4646    $ export PYTHONPATH=$PYTHONPATH:$PWD/`ls -rtd build/lib.* | head -1`:$PWD/tests
    4747
    48 Similarly, you can use the aubio module without installing libaubio by pointing
    49 LD_LIBRARY_PATH to the path libaubio can be found at:
    50 
    51     $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:PWD/../build/src
    52 
    53 Or on Mac OS X systems, setting DYLD_LIBRARY_PATH:
    54 
    55     $ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$PWD/../build/src
    56 
    5748Testing the Python module
    5849-------------------------
  • python/demos/demo_bpm_extract.py

    r60fc05b rf264b17  
    44from numpy import median, diff
    55
    6 def get_file_bpm(path, params = {}):
     6def get_file_bpm(path, params = None):
    77    """ Calculate the beats per minute (bpm) of a given file.
    88        path: path to the file
    99        param: dictionary of parameters
    1010    """
     11    if params is None:
     12        params = {}
    1113    try:
    1214        win_s = params['win_s']
    1315        samplerate = params['samplerate']
    1416        hop_s = params['hop_s']
    15     except:
     17    except KeyError:
    1618        """
    1719        # super fast
     
    4446
    4547    # 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))
    4856    return b
    4957
     
    5260    for f in sys.argv[1:]:
    5361        bpm = get_file_bpm(f)
    54         print "%6s" % ("%.2f" % bpm), f
     62        print("{:6s} {:s}".format("{:2f}".format(bpm), f))
  • python/demos/demo_filterbank.py

    r60fc05b rf264b17  
    22
    33from aubio import filterbank, fvec
    4 from pylab import loglog, show, subplot, xlim, ylim, xlabel, ylabel, title
     4from pylab import loglog, show, xlim, ylim, xlabel, ylabel, title
    55from numpy import vstack, arange
    66
     
    2020f.set_coeffs(coeffs)
    2121
    22 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
     22times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    2323title('Bank of filters built using a simple list of boundaries\nThe middle band has been amplified by 2.')
    2424loglog(times.T, f.get_coeffs().T, '.-')
  • python/demos/demo_filterbank_slaney.py

    r60fc05b rf264b17  
    22
    33from aubio import filterbank
    4 from numpy import array, arange, vstack
     4from numpy import arange, vstack
    55
    66win_s = 8192
     
    1212from pylab import loglog, title, show, xlim, ylim, xlabel, ylabel
    1313xlim([0,samplerate / 2])
    14 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * 40)
     14times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * 40)
    1515loglog(times.T, f.get_coeffs().T, '.-')
    1616title('Mel frequency bands coefficients')
  • python/demos/demo_filterbank_triangle_bands.py

    r60fc05b rf264b17  
    1717subplot(211)
    1818title('Examples of filterbank built with set_triangle_bands and set_coeffs')
    19 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
     19times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    2020loglog(times.T, f.get_coeffs().T, '.-')
    2121xlim([50, samplerate/2])
     
    3838
    3939subplot(212)
    40 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
     40times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    4141loglog(times.T, f.get_coeffs().T, '.-')
    4242xlim([50, samplerate/2])
  • python/demos/demo_keyboard.py

    r60fc05b rf264b17  
    2626
    2727def create_keyboard_patches(firstnote, lastnote, ax = None):
    28     import numpy as np
    2928    import matplotlib.pyplot as plt
    3029    from matplotlib.path import Path
  • python/demos/demo_mel-energy.py

    r60fc05b rf264b17  
    22
    33import sys
    4 from aubio import fvec, source, pvoc, filterbank
     4from aubio import source, pvoc, filterbank
    55from numpy import vstack, zeros
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 4           # hop size
     8hop_s = win_s // 4          # hop size
    99
    1010if len(sys.argv) < 2:
    11     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     11    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1212    sys.exit(1)
    1313
     
    3535    fftgrain = pv(samples)
    3636    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])))
    3939    energies = vstack( [energies, new_energies] )
    4040    total_frames += read
     
    4242
    4343if 1:
    44     print "done computing, now plotting"
     44    print("done computing, now plotting")
    4545    import matplotlib.pyplot as plt
    4646    from demo_waveform_plot import get_waveform_plot
  • python/demos/demo_mfcc.py

    r60fc05b rf264b17  
    33import sys
    44from aubio import source, pvoc, mfcc
    5 from numpy import array, vstack, zeros
     5from numpy import vstack, zeros
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 4           # hop size
     8hop_s = win_s // 4          # hop size
    99n_filters = 40              # must be 40 for mfcc
    1010n_coeffs = 13
     
    1212
    1313if len(sys.argv) < 2:
    14     print "Usage: %s <source_filename>" % sys.argv[0]
     14    print("Usage: %s <source_filename>" % sys.argv[0])
    1515    sys.exit(1)
    1616
  • python/demos/demo_onset.py

    r60fc05b rf264b17  
    55
    66win_s = 512                 # fft size
    7 hop_s = win_s / 2           # hop size
     7hop_s = win_s // 2          # hop size
    88
    99if len(sys.argv) < 2:
    10     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     10    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1111    sys.exit(1)
    1212
     
    2929    samples, read = s()
    3030    if o(samples):
    31         print "%f" % o.get_last_s()
     31        print("%f" % o.get_last_s())
    3232        onsets.append(o.get_last())
    3333    total_frames += read
  • python/demos/demo_onset_plot.py

    r60fc05b rf264b17  
    33import sys
    44from aubio import onset, source
    5 from numpy import array, hstack, zeros
     5from numpy import hstack, zeros
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 2           # hop size
     8hop_s = win_s // 2          # hop size
    99
    1010if len(sys.argv) < 2:
    11     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     11    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1212    sys.exit(1)
    1313
     
    3535    samples, read = s()
    3636    if o(samples):
    37         print "%f" % (o.get_last_s())
     37        print("%f" % (o.get_last_s()))
    3838        onsets.append(o.get_last())
    3939    # 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)
    4141    allsamples_max = hstack([allsamples_max, new_maxes])
    4242    desc.append(o.get_descriptor())
     
    4747if 1:
    4848    # do plotting
    49     from numpy import arange
    5049    import matplotlib.pyplot as plt
    5150    allsamples_max = (allsamples_max > 0) * allsamples_max
     
    6362    plt1.yaxis.set_visible(False)
    6463    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]
    6666    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]
    6868    for stamp in onsets:
    6969        stamp /= float(samplerate)
  • python/demos/demo_pitch.py

    r60fc05b rf264b17  
    22
    33import sys
    4 from aubio import source, pitch, freqtomidi
     4from aubio import source, pitch
    55
    66if len(sys.argv) < 2:
    7     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     7    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    88    sys.exit(1)
    99
     
    1111
    1212downsample = 1
    13 samplerate = 44100 / downsample
     13samplerate = 44100 // downsample
    1414if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
    1515
    16 win_s = 4096 / downsample # fft size
    17 hop_s = 512  / downsample # hop size
     16win_s = 4096 // downsample # fft size
     17hop_s = 512  // downsample # hop size
    1818
    1919s = source(filename, samplerate, hop_s)
     
    3737    confidence = pitch_o.get_confidence()
    3838    #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))
    4040    pitches += [pitch]
    4141    confidences += [confidence]
     
    4646
    4747#print pitches
     48import os.path
    4849from numpy import array, ma
    4950import matplotlib.pyplot as plt
     
    6465
    6566def array_from_text_file(filename, dtype = 'float'):
    66     import os.path
    67     from numpy import array
    6867    filename = os.path.join(os.path.dirname(__file__), filename)
    6968    return array([line.split() for line in open(filename).readlines()],
     
    7170
    7271ax2 = fig.add_subplot(312, sharex = ax1)
    73 import sys, os.path
    7472ground_truth = os.path.splitext(filename)[0] + '.f0.Corrected'
    7573if os.path.isfile(ground_truth):
  • python/demos/demo_pitch_sinusoid.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy import random, sin, arange, ones, zeros
    4 from math import pi
    5 from aubio import fvec, pitch
     3import numpy as np
     4import aubio
    65
    76def 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)
    98
    109def 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
    1815
    1916methods = ['default', 'schmitt', 'fcomb', 'mcomb', 'yin', 'yinfft']
     
    2421samplerate = 44100
    2522sin_length = (samplerate * 10) % 512 * 512
    26 freqs = zeros(sin_length)
     23freqs = np.zeros(sin_length)
    2724
    28 partition = sin_length / 8
     25partition = sin_length // 8
    2926pointer = 0
    3027
     
    4138pointer += partition
    4239pointer += partition
    43 freqs[ pointer : pointer + partition ] = 400 + 5 * random.random(sin_length/8)
     40freqs[ pointer : pointer + partition ] = 400 + 5 * np.random.random(sin_length/8)
    4441
    4542a = build_sinusoid(sin_length, freqs, samplerate)
    4643
    4744for 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])
    5049
    51 print "done computing"
     50print("done computing")
    5251
    5352if 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
    5854
    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
    6257
    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)
    6861
     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  
    1111    samplerate = f.samplerate
    1212
    13     s = Stream(sample_rate = samplerate, block_length = hop_size)
     13    s = Stream(samplerate = samplerate, blocksize = hop_size)
    1414    s.start()
    1515    read = 0
  • python/demos/demo_pysoundcard_record.py

    r60fc05b rf264b17  
    99    hop_size = 256
    1010    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))
    1313
    1414    s.start()
    1515    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)
    2226    s.stop()
    2327
  • python/demos/demo_simple_robot_voice.py

    r60fc05b rf264b17  
    55
    66if __name__ == '__main__':
    7   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
     7    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
    1414
    15   win_s = 512                 # fft size
    16   hop_s = win_s / 2           # hop size
    17   pv = pvoc(win_s, hop_s)                            # phase vocoder
     15    win_s = 512                          # fft size
     16    hop_s = win_s // 2                   # hop size
     17    pv = pvoc(win_s, hop_s)              # phase vocoder
    1818
    19   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
     19    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
    2727
    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  
    1414if __name__ == '__main__':
    1515    if len(sys.argv) < 2:
    16         print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]
     16        print('usage: %s <inputfile> <outputfile>' % sys.argv[0])
    1717        sys.exit(1)
    1818    samplerate = 0
     
    2323
    2424    win_s = 512 # fft size
    25     hop_s = win_s / 2 # hop size
     25    hop_s = win_s // 2 # hop size
    2626    pv = pvoc(win_s, hop_s) # phase vocoder
    2727
     
    3131        zeros( 50 ),
    3232        1.3 * hanningz(100),
    33         zeros (win_s / 2 + 1 - 40 - 50 - 100),
     33        zeros (win_s // 2 + 1 - 40 - 50 - 100),
    3434        ] )
    3535
     
    5353        total_frames += read
    5454
    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  
    66if __name__ == '__main__':
    77    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])
    99        sys.exit(1)
    1010
     
    2323        g(vec, read)
    2424        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  
    33import sys
    44from math import pi, e
    5 from aubio import sink
    6 from numpy import arange, resize, sin, exp, zeros
     5from aubio import sink, float_type
     6from numpy import arange, sin, exp, zeros
    77
    88if len(sys.argv) < 2:
    9     print 'usage: %s <outputfile> [samplerate]' % sys.argv[0]
     9    print('usage: %s <outputfile> [samplerate]' % sys.argv[0])
    1010    sys.exit(1)
    1111
     
    2626# create a sine lookup table
    2727tablelen = 1000
    28 sinetable = arange(tablelen + 1, dtype = 'float32')
     28sinetable = arange(tablelen + 1, dtype = float_type)
    2929sinetable = 0.7 * sin(twopi * sinetable/tablelen)
    30 sinetone = zeros((duration,), dtype = 'float32')
     30sinetone = zeros((duration,), dtype = float_type)
    3131
    3232# compute sinetone at floating point period
     
    4040
    4141# apply some envelope
    42 float_ramp = arange(duration, dtype = 'float32')
     42float_ramp = arange(duration, dtype = float_type)
    4343sinetone *= exp( - e * float_ramp / duration / decay)
    4444sinetone[:attack] *= exp( e * ( float_ramp[:attack] / attack - 1 ) )
  • python/demos/demo_sink_multi.py

    r60fc05b rf264b17  
    66if __name__ == '__main__':
    77    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])
    99        sys.exit(1)
    1010
     
    2323        g.do_multi(vec, read)
    2424        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  
    77if __name__ == '__main__':
    88    if len(sys.argv) < 3:
    9         print 'usage: %s <inputfile> <duration>' % sys.argv[0]
     9        print('usage: %s <inputfile> <duration>' % sys.argv[0])
    1010        sys.exit(1)
    1111    source_file = sys.argv[1]
     
    4545    total_duration = total_frames_written / float(samplerate)
    4646    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)
    4950    # close source and sink files
    5051    del f, g
  • python/demos/demo_source.py

    r60fc05b rf264b17  
    66if __name__ == '__main__':
    77    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])
    99        sys.exit(1)
    1010    samplerate = 0
     
    2121        total_frames += read
    2222        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  
    22
    33import sys
    4 from aubio import fvec, source, pvoc, specdesc
    5 from numpy import hstack
     4import numpy as np
     5from aubio import source, pvoc, specdesc
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 4           # hop size
     8hop_s = win_s // 4          # hop size
    99
    1010if len(sys.argv) < 2:
    11     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     11    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1212    sys.exit(1)
    1313
     
    3131for method in methods:
    3232    cands = []
    33     all_descs[method] = fvec(0)
     33    all_descs[method] = np.array([])
    3434    o[method] = specdesc(method, win_s)
    3535
     
    4040    samples, read = s()
    4141    fftgrain = pv(samples)
    42     #print "%f" % ( total_frames / float(samplerate) ),
     42    #outstr = "%f" % ( total_frames / float(samplerate) )
    4343    for method in methods:
    4444        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)
    4848    total_frames += read
    4949    if read < hop_s: break
    5050
    5151if 1:
    52     print "done computing, now plotting"
     52    print("done computing, now plotting")
    5353    import matplotlib.pyplot as plt
    5454    from demo_waveform_plot import get_waveform_plot
  • python/demos/demo_spectrogram.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 import sys
    4 from aubio import pvoc, source
    5 from numpy import array, arange, zeros, shape, log10, vstack
    6 from pylab import imshow, show, cm, axis, ylabel, xlabel, xticks, yticks
     3import sys, os.path
     4from aubio import pvoc, source, float_type
     5from numpy import zeros, log10, vstack
     6import matplotlib.pyplot as plt
    77
    88def get_spectrogram(filename, samplerate = 0):
    9   win_s = 512                                        # fft window size
    10   hop_s = win_s / 2                                  # hop size
    11   fft_s = win_s / 2 + 1                              # spectrum bins
     9    win_s = 512                                        # fft window size
     10    hop_s = win_s // 2                                 # hop size
     11    fft_s = win_s // 2 + 1                             # spectrum bins
    1212
    13   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='float32')      # numpy array to store spectrogram
     13    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
    1717
    18   # 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
     18    # 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
    2323
    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
    3435
    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
    5565
    5666if __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  
    55
    66win_s = 512                 # fft size
    7 hop_s = win_s / 2           # hop size
     7hop_s = win_s // 2          # hop size
    88
    99if len(sys.argv) < 2:
    10     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     10    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1111    sys.exit(1)
    1212
     
    3434    if is_beat:
    3535        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)))
    3737        beats.append(this_beat)
    3838    total_frames += read
  • python/demos/demo_tempo_plot.py

    r60fc05b rf264b17  
    55
    66win_s = 512                 # fft size
    7 hop_s = win_s / 2           # hop size
     7hop_s = win_s // 2          # hop size
    88
    99if len(sys.argv) < 2:
    10     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     10    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1111    sys.exit(1)
    1212
     
    4040if len(beats) > 1:
    4141    # do plotting
    42     from numpy import array, arange, mean, median, diff
     42    from numpy import mean, median, diff
    4343    import matplotlib.pyplot as plt
    4444    bpms = 60./ diff(beats)
    45     print 'mean period:', "%.2f" % mean(bpms), 'bpm', 'median', "%.2f" % median(bpms), 'bpm'
    46     print 'plotting', filename
     45    print('mean period: %.2fbpm, median: %.2fbpm' % (mean(bpms), median(bpms)))
     46    print('plotting %s' % filename)
    4747    plt1 = plt.axes([0.1, 0.75, 0.8, 0.19])
    4848    plt2 = plt.axes([0.1, 0.1, 0.8, 0.65], sharex = plt1)
     
    7676
    7777else:
    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  
    55
    66if __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)
    1010
    11   samplerate = 44100
    12   win_s = 1024      # fft size
    13   hop_s = win_s / 4 # block size
    14   threshold = 0.5
     11    samplerate = 44100
     12    win_s = 1024       # fft size
     13    hop_s = win_s // 4 # block size
     14    threshold = 0.5
    1515
    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)
    1919
    20   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
     20    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
    2323
    24   t.set_threshold(threshold)
     24    t.set_threshold(threshold)
    2525
    26   read = hop_s
     26    read = hop_s
    2727
    28   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
     28    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
    3636
    37   del f, g, h                         # finish writing the files now
     37    del f, g, h                           # finish writing the files now
    3838
    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()
     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  
    22
    33import sys
    4 from aubio import pvoc, source
     4from aubio import source
    55from numpy import zeros, hstack
    66
     
    2222        samples, read = a()
    2323        # 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)
    2525        allsamples_max = hstack([allsamples_max, new_maxes])
    2626        total_frames += read
     
    4949    import matplotlib.pyplot as plt
    5050    if len(sys.argv) < 2:
    51         print "Usage: %s <filename>" % sys.argv[0]
     51        print("Usage: %s <filename>" % sys.argv[0])
    5252    else:
    5353        for soundfile in sys.argv[1:]:
  • python/ext/aubio-types.h

    r60fc05b rf264b17  
    11#include <Python.h>
    22#include <structmember.h>
     3
     4#include "aubio-generated.h"
    35
    46#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
     
    3436
    3537#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
    3739#define AUBIO_NPY_SMPL NPY_DOUBLE
     40#define AUBIO_NPY_SMPL_STR "float64"
     41#define AUBIO_NPY_SMPL_CHR "d"
    3842#else
     43// default is 32 bit precision
    3944#define AUBIO_NPY_SMPL NPY_FLOAT
     45#define AUBIO_NPY_SMPL_STR "float32"
     46#define AUBIO_NPY_SMPL_CHR "f"
    4047#endif
    4148
    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
    5054extern PyTypeObject Py_cvecType;
    5155
     56PyObject * new_py_fvec(uint_t length);
     57PyObject * new_py_cvec(uint_t length);
     58PyObject * new_py_fmat(uint_t height, uint_t length);
     59
    5260// defined in aubio-proxy.c
     61extern int PyAubio_IsValidVector (PyObject *input);
     62
    5363extern PyObject *PyAubio_CFvecToArray (fvec_t * self);
    54 extern fvec_t *PyAubio_ArrayToCFvec (PyObject * self);
     64extern int PyAubio_ArrayToCFvec (PyObject * self, fvec_t *out);
    5565
    56 extern Py_cvec *PyAubio_CCvecToPyCvec (cvec_t * self);
    57 extern cvec_t *PyAubio_ArrayToCCvec (PyObject *input);
     66extern int PyAubio_PyCvecToCCvec (PyObject *input, cvec_t *i);
    5867
    5968extern PyObject *PyAubio_CFmatToArray (fmat_t * self);
    60 extern fmat_t *PyAubio_ArrayToCFmat (PyObject *input);
     69extern int PyAubio_ArrayToCFmat (PyObject *input, fmat_t *out);
    6170
    6271// hand written wrappers
  • python/ext/aubiomodule.c

    r60fc05b rf264b17  
    11#define PY_AUBIO_MODULE_MAIN
    22#include "aubio-types.h"
    3 #include "aubio-generated.h"
    43#include "py-musicutils.h"
    54
     
    8483{
    8584  PyObject *input;
    86   fvec_t *vec;
     85  fvec_t vec;
    8786  smpl_t alpha;
    8887  PyObject *result;
    8988
    90   if (!PyArg_ParseTuple (args, "Of:alpha_norm", &input, &alpha)) {
     89  if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":alpha_norm", &input, &alpha)) {
    9190    return NULL;
    9291  }
     
    9695  }
    9796
    98   vec = PyAubio_ArrayToCFvec (input);
    99 
    100   if (vec == NULL) {
     97  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    10198    return NULL;
    10299  }
    103100
    104101  // 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));
    106103  if (result == NULL) {
    107104    return NULL;
     
    117114  smpl_t output;
    118115
    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)) {
    120117    return NULL;
    121118  }
     
    132129  smpl_t output;
    133130
    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)) {
    135132    return NULL;
    136133  }
     
    147144  smpl_t output;
    148145
    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)) {
    150147    return NULL;
    151148  }
     
    162159  smpl_t output;
    163160
    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)) {
    165162    return NULL;
    166163  }
     
    175172{
    176173  PyObject *input;
    177   fvec_t *vec;
     174  fvec_t vec;
    178175  PyObject *result;
    179176
     
    186183  }
    187184
    188   vec = PyAubio_ArrayToCFvec (input);
    189 
    190   if (vec == NULL) {
     185  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    191186    return NULL;
    192187  }
    193188
    194189  // 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));
    196191  if (result == NULL) {
    197192    return NULL;
     
    205200{
    206201  PyObject *input;
    207   fvec_t *vec;
     202  fvec_t vec;
    208203
    209204  if (!PyArg_ParseTuple (args, "O:min_removal", &input)) {
     
    215210  }
    216211
    217   vec = PyAubio_ArrayToCFvec (input);
    218 
    219   if (vec == NULL) {
     212  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    220213    return NULL;
    221214  }
    222215
    223216  // compute the function
    224   fvec_min_removal (vec);
     217  fvec_min_removal (&vec);
    225218
    226219  // since this function does not return, we could return None
    227220  //Py_RETURN_NONE;
    228221  // however it is convenient to return the modified vector
    229   return (PyObject *) PyAubio_CFvecToArray(vec);
     222  return (PyObject *) PyAubio_CFvecToArray(&vec);
    230223  // or even without converting it back to an array
    231224  //Py_INCREF(vec);
     
    246239  {"level_detection", Py_aubio_level_detection, METH_VARARGS, Py_aubio_level_detection_doc},
    247240  {"window", Py_aubio_window, METH_VARARGS, Py_aubio_window_doc},
    248   {NULL, NULL} /* Sentinel */
     241  {NULL, NULL, 0, NULL} /* Sentinel */
    249242};
    250243
    251 PyMODINIT_FUNC
    252 init_aubio (void)
    253 {
    254   PyObject *m;
     244#if PY_MAJOR_VERSION >= 3
     245// Python3 module definition
     246static 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
     259static PyObject *
     260initaubio (void)
     261{
     262  PyObject *m = NULL;
    255263  int err;
    256264
     
    266274      || (generated_types_ready() < 0 )
    267275  ) {
    268     return;
    269   }
    270 
     276    return m;
     277  }
     278
     279#if PY_MAJOR_VERSION >= 3
     280  m = PyModule_Create(&moduledef);
     281#else
    271282  m = Py_InitModule3 ("_aubio", aubio_methods, aubio_module_doc);
     283#endif
    272284
    273285  if (m == NULL) {
    274     return;
     286    return m;
    275287  }
    276288
     
    296308  PyModule_AddObject (m, "sink", (PyObject *) & Py_sinkType);
    297309
     310  PyModule_AddStringConstant(m, "float_type", AUBIO_NPY_SMPL_STR);
     311
    298312  // add generated objects
    299313  add_generated_objects(m);
     
    301315  // add ufunc
    302316  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  
    11#include "aubio-types.h"
    22
    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)) {
     3PyObject *
     4new_py_fvec(uint_t length) {
     5    npy_intp dims[] = { length, 1 };
     6    return PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0);
     7}
    138
    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;
     9PyObject *
     10new_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);
    5913}
    6014
     
    6620}
    6721
    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;
     22int
     23PyAubio_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;
    7564}
    7665
    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;
     66int
     67PyAubio_ArrayToCFvec (PyObject *input, fvec_t *out) {
     68
     69  if (!PyAubio_IsValidVector(input)){
     70    return 0;
    8471  }
     72
     73  out->length = (uint_t) PyArray_SIZE ((PyArrayObject *)input);
     74  out->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)input, 0);
     75  return 1;
    8576}
    8677
     
    10293}
    10394
    104 fmat_t *
    105 PyAubio_ArrayToCFmat (PyObject *input) {
    106   PyObject *array;
    107   fmat_t *mat;
    108   uint_t i;
     95int
     96PyAubio_ArrayToCFmat (PyObject *input, fmat_t *mat) {
     97  uint_t i, new_height;
     98  npy_intp length, height;
    10999  if (input == NULL) {
    110100    PyErr_SetString (PyExc_ValueError, "input array is not a python object");
    111     goto fail;
     101    return 0;
    112102  }
    113103  // parsing input object into a Py_fvec
     
    117107    if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
    118108      PyErr_SetString (PyExc_ValueError, "input array is a scalar");
    119       goto fail;
     109      return 0;
    120110    } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
    121111      PyErr_SetString (PyExc_ValueError,
    122112          "input array has more than two dimensions");
    123       goto fail;
     113      return 0;
    124114    }
    125115
    126116    if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
    127117      PyErr_SetString (PyExc_ValueError, "input array should be float");
    128       goto fail;
     118      return 0;
    129119    } 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;
    135122    }
    136123
    137124    // 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) {
    143127      PyErr_SetString (PyExc_ValueError, "input array dimension 1 should be greater than 0");
    144       goto fail;
     128      return 0;
    145129    }
    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) {
    150132      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;
    156134    }
    157135
    158136  } else if (PyObject_TypeCheck (input, &PyList_Type)) {
    159137    PyErr_SetString (PyExc_ValueError, "can not convert list to fmat");
    160     return NULL;
     138    return 0;
    161139  } else {
    162140    PyErr_SetString (PyExc_ValueError, "can only accept matrix of float as input");
    163     return NULL;
     141    return 0;
    164142  }
    165143
    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  }
    167151
    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;
    170158}
    171 
  • python/ext/py-cvec.c

    r60fc05b rf264b17  
    11#include "aubio-types.h"
    22
    3 /* cvec type definition 
     3/* cvec type definition
    44
    55class 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)
    1010
    1111*/
    1212
     13// special python type for cvec
     14typedef struct
     15{
     16  PyObject_HEAD
     17  PyObject *norm;
     18  PyObject *phas;
     19  uint_t length;
     20} Py_cvec;
     21
    1322static char Py_cvec_doc[] = "cvec object";
     23
     24
     25PyObject *
     26new_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
     35int
     36PyAubio_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}
    1448
    1549static PyObject *
     
    2458    return NULL;
    2559  }
    26 
    2760
    2861  self = (Py_cvec *) type->tp_alloc (type, 0);
     
    4881Py_cvec_init (Py_cvec * self, PyObject * args, PyObject * kwds)
    4982{
    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);
    5586  return 0;
    5687}
     
    5990Py_cvec_del (Py_cvec * self)
    6091{
    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);
    6395}
    6496
     
    70102  PyObject *result = NULL;
    71103
    72   format = PyString_FromString ("aubio cvec of %d elements");
     104  format = PyUnicode_FromString ("aubio cvec of %d elements");
    73105  if (format == NULL) {
    74106    goto fail;
     
    79111    goto fail;
    80112  }
    81   cvec_print ( self->o );
    82 
    83   result = PyString_Format (format, args);
     113  // hide actual norm / phas content
     114
     115  result = PyUnicode_Format (format, args);
    84116
    85117fail:
     
    91123
    92124PyObject *
    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 *
    114125Py_cvec_get_norm (Py_cvec * self, void *closure)
    115126{
    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);
    117130}
    118131
     
    120133Py_cvec_get_phas (Py_cvec * self, void *closure)
    121134{
    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);
    123138}
    124139
     
    126141Py_cvec_set_norm (Py_cvec * vec, PyObject *input, void * closure)
    127142{
    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);
    177158  return 0;
    178 
    179 fail:
    180   return 1;
    181159}
    182160
     
    184162Py_cvec_set_phas (Py_cvec * vec, PyObject *input, void * closure)
    185163{
    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);
    235179  return 0;
    236 
    237 fail:
    238   return 1;
    239180}
    240181
     
    261202
    262203PyTypeObject Py_cvecType = {
    263   PyObject_HEAD_INIT (NULL)
    264   0,                            /* ob_size           */
     204  PyVarObject_HEAD_INIT(NULL, 0)
    265205  "aubio.cvec",                 /* tp_name           */
    266206  sizeof (Py_cvec),             /* tp_basicsize      */
     
    273213  (reprfunc) Py_cvec_repr,      /* tp_repr           */
    274214  0,                            /* tp_as_number      */
    275   0, //&Py_cvec_tp_as_sequence,      /* tp_as_sequence    */
     215  0, //&Py_cvec_tp_as_sequence, /* tp_as_sequence    */
    276216  0,                            /* tp_as_mapping     */
    277217  0,                            /* tp_hash           */
     
    300240  0,                            /* tp_alloc          */
    301241  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 "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33static char Py_fft_doc[] = "fft object";
    44
    5 AUBIO_DECLARE(fft, uint_t win_s)
     5typedef 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;
    617
    7 //AUBIO_NEW(fft)
    818static PyObject *
    919Py_fft_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
     
    3747}
    3848
     49static int
     50Py_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  }
    3961
    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);
    4164
    42 AUBIO_DEL(fft)
     65  return 0;
     66}
    4367
    44 static PyObject *
    45 Py_fft_do(PyObject * self, PyObject * args)
     68static void
     69Py_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
     79static PyObject *
     80Py_fft_do(Py_fft * self, PyObject * args)
    4681{
    4782  PyObject *input;
    48   fvec_t *vec;
    49   cvec_t *output;
     83  cvec_t c_out;
    5084
    5185  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    5387  }
    5488
    55   vec = PyAubio_ArrayToCFvec (input);
    56 
    57   if (vec == NULL) {
     89  if (!PyAubio_ArrayToCFvec(input, &(self->vecin))) {
    5890    return NULL;
    5991  }
    6092
    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  }
    6299
     100  Py_INCREF(self->doout);
     101  if (!PyAubio_PyCvecToCCvec(self->doout, &c_out)) {
     102    return NULL;
     103  }
    63104  // 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;
    66107}
    67108
    68 AUBIO_MEMBERS_START(fft)
     109static PyMemberDef Py_fft_members[] = {
    69110  {"win_s", T_INT, offsetof (Py_fft, win_s), READONLY,
    70111    "size of the window"},
    71 AUBIO_MEMBERS_STOP(fft)
     112  {NULL}
     113};
    72114
    73 static PyObject * 
     115static PyObject *
    74116Py_fft_rdo(Py_fft * self, PyObject * args)
    75117{
    76118  PyObject *input;
    77   cvec_t *vec;
    78   fvec_t *output;
     119  fvec_t out;
    79120
    80121  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    82123  }
    83124
    84   vec = PyAubio_ArrayToCCvec (input);
    85 
    86   if (vec == NULL) {
     125  if (!PyAubio_PyCvecToCCvec (input, &(self->cvecin)) ) {
    87126    return NULL;
    88127  }
    89128
    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  }
    91135
     136  Py_INCREF(self->rdoout);
     137  if (!PyAubio_ArrayToCFvec(self->rdoout, &out) ) {
     138    return NULL;
     139  }
    92140  // 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;
    95143}
    96144
     
    101149};
    102150
    103 AUBIO_TYPEOBJECT(fft, "aubio.fft")
     151PyTypeObject 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  
    66  aubio_filter_t * o;
    77  uint_t order;
     8  fvec_t vec;
     9  PyObject *out;
     10  fvec_t c_out;
    811} Py_filter;
    912
     
    4851    return -1;
    4952  }
    50 
     53  self->out = NULL;
    5154  return 0;
    5255}
     
    5558Py_filter_del (Py_filter * self)
    5659{
     60  Py_XDECREF(self->out);
    5761  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
     65static PyObject *
    6266Py_filter_do(Py_filter * self, PyObject * args)
    6367{
    6468  PyObject *input;
    65   fvec_t *vec;
    6669
    6770  if (!PyArg_ParseTuple (args, "O:digital_filter.do", &input)) {
     
    7376  }
    7477
    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  }
    8191  // 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
     96static PyObject *
    8897Py_filter_set_c_weighting (Py_filter * self, PyObject *args)
    8998{
     
    103112}
    104113
    105 static PyObject * 
     114static PyObject *
    106115Py_filter_set_a_weighting (Py_filter * self, PyObject *args)
    107116{
     
    157166
    158167PyTypeObject Py_filterType = {
    159   PyObject_HEAD_INIT (NULL)
    160   0,                            /* ob_size           */
     168  PyVarObject_HEAD_INIT(NULL, 0)
    161169  "aubio.digital_filter",       /* tp_name           */
    162170  sizeof (Py_filter),           /* tp_basicsize      */
     
    196204  0,                            /* tp_alloc          */
    197205  Py_filter_new,                /* tp_new            */
     206  0,
     207  0,
     208  0,
     209  0,
     210  0,
     211  0,
     212  0,
     213  0,
     214  0,
    198215};
  • python/ext/py-filterbank.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33static char Py_filterbank_doc[] = "filterbank object";
    44
    5 AUBIO_DECLARE(filterbank, uint_t n_filters; uint_t win_s)
    6 
    7 //AUBIO_NEW(filterbank)
     5typedef 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
    818static PyObject *
    919Py_filterbank_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
     
    4555}
    4656
    47 
    48 AUBIO_INIT(filterbank, self->n_filters, self->win_s)
    49 
    50 AUBIO_DEL(filterbank)
     57static int
     58Py_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
     71static void
     72Py_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}
    5181
    5282static PyObject *
     
    5484{
    5585  PyObject *input;
    56   cvec_t *vec;
    57   fvec_t *out;
    5886
    5987  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    6189  }
    6290
    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  }
    71106  // 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
     111static PyMemberDef Py_filterbank_members[] = {
    77112  {"win_s", T_INT, offsetof (Py_filterbank, win_s), READONLY,
    78113    "size of the window"},
    79114  {"n_filters", T_INT, offsetof (Py_filterbank, n_filters), READONLY,
    80115    "number of filters"},
    81 AUBIO_MEMBERS_STOP(filterbank)
     116  {NULL} /* sentinel */
     117};
    82118
    83119static PyObject *
     
    88124  PyObject *input;
    89125  uint_t samplerate;
    90   fvec_t *freqs;
    91126  if (!PyArg_ParseTuple (args, "OI", &input, &samplerate)) {
    92127    return NULL;
     
    97132  }
    98133
    99   freqs = PyAubio_ArrayToCFvec (input);
    100 
    101   if (freqs == NULL) {
     134  if (!PyAubio_ArrayToCFvec(input, &(self->freqs) )) {
    102135    return NULL;
    103136  }
    104137
    105138  err = aubio_filterbank_set_triangle_bands (self->o,
    106       freqs, samplerate);
     139      &(self->freqs), samplerate);
    107140  if (err > 0) {
    108141    PyErr_SetString (PyExc_ValueError,
     
    138171
    139172  PyObject *input;
    140   fmat_t *coeffs;
    141 
    142173  if (!PyArg_ParseTuple (args, "O", &input)) {
    143174    return NULL;
    144175  }
    145176
    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));
    155182
    156183  if (err > 0) {
     
    181208};
    182209
    183 AUBIO_TYPEOBJECT(filterbank, "aubio.filterbank")
     210PyTypeObject 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  
    99
    1010  if (!PyArg_ParseTuple (args, "|sI", &wintype, &winlen)) {
    11     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
    1211    return NULL;
    1312  }
     
    2625{
    2726  PyObject *input;
    28   fvec_t *vec;
     27  fvec_t vec;
    2928  PyObject *level_lin;
    3029
    3130  if (!PyArg_ParseTuple (args, "O:level_lin", &input)) {
    32     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
    3331    return NULL;
    3432  }
     
    3836  }
    3937
    40   vec = PyAubio_ArrayToCFvec (input);
    41   if (vec == NULL) {
     38  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    4239    return NULL;
    4340  }
    4441
    45   level_lin = Py_BuildValue("f", aubio_level_lin(vec));
     42  level_lin = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_level_lin(&vec));
    4643  if (level_lin == NULL) {
    4744    PyErr_SetString (PyExc_ValueError, "failed computing level_lin");
     
    5653{
    5754  PyObject *input;
    58   fvec_t *vec;
     55  fvec_t vec;
    5956  PyObject *db_spl;
    6057
    6158  if (!PyArg_ParseTuple (args, "O:db_spl", &input)) {
    62     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
    6359    return NULL;
    6460  }
     
    6864  }
    6965
    70   vec = PyAubio_ArrayToCFvec (input);
    71   if (vec == NULL) {
     66  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    7267    return NULL;
    7368  }
    7469
    75   db_spl = Py_BuildValue("f", aubio_db_spl(vec));
     70  db_spl = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_db_spl(&vec));
    7671  if (db_spl == NULL) {
    7772    PyErr_SetString (PyExc_ValueError, "failed computing db_spl");
     
    8681{
    8782  PyObject *input;
    88   fvec_t *vec;
     83  fvec_t vec;
    8984  PyObject *silence_detection;
    9085  smpl_t threshold;
    9186
    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)) {
    9488    return NULL;
    9589  }
     
    9993  }
    10094
    101   vec = PyAubio_ArrayToCFvec (input);
    102   if (vec == NULL) {
     95  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    10396    return NULL;
    10497  }
    10598
    106   silence_detection = Py_BuildValue("I", aubio_silence_detection(vec, threshold));
     99  silence_detection = Py_BuildValue("I", aubio_silence_detection(&vec, threshold));
    107100  if (silence_detection == NULL) {
    108101    PyErr_SetString (PyExc_ValueError, "failed computing silence_detection");
     
    117110{
    118111  PyObject *input;
    119   fvec_t *vec;
     112  fvec_t vec;
    120113  PyObject *level_detection;
    121114  smpl_t threshold;
    122115
    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)) {
    125117    return NULL;
    126118  }
     
    130122  }
    131123
    132   vec = PyAubio_ArrayToCFvec (input);
    133   if (vec == NULL) {
     124  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    134125    return NULL;
    135126  }
    136127
    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));
    138129  if (level_detection == NULL) {
    139130    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
    33
    44static char Py_aubio_window_doc[] = ""
     
    7272PyObject * Py_aubio_level_detection(PyObject *self, PyObject *args);
    7373
    74 #endif /* _PY_AUBIO_MUSICUTILS_H_ */
     74#endif /* PY_AUBIO_MUSICUTILS_H */
  • python/ext/py-phasevoc.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33static char Py_pvoc_doc[] = "pvoc object";
    44
    5 AUBIO_DECLARE(pvoc, uint_t win_s; uint_t hop_s)
    6 
    7 //AUBIO_NEW(pvoc)
     5typedef 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
    820static PyObject *
    921Py_pvoc_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
     
    5062}
    5163
    52 
    53 AUBIO_INIT(pvoc, self->win_s, self->hop_s)
    54 
    55 AUBIO_DEL(pvoc)
    56 
    57 static PyObject *
     64static int
     65Py_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
     82static void
     83Py_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
     94static PyObject *
    5895Py_pvoc_do(Py_pvoc * self, PyObject * args)
    5996{
    6097  PyObject *input;
    61   fvec_t *vec;
    62   cvec_t *output;
    6398
    6499  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    66101  }
    67102
    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  }
    76118  // 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
     123static PyMemberDef Py_pvoc_members[] = {
    82124  {"win_s", T_INT, offsetof (Py_pvoc, win_s), READONLY,
    83125    "size of the window"},
    84126  {"hop_s", T_INT, offsetof (Py_pvoc, hop_s), READONLY,
    85127    "size of the hop"},
    86 AUBIO_MEMBERS_STOP(pvoc)
    87 
    88 static PyObject *
     128  { NULL } // sentinel
     129};
     130
     131static PyObject *
    89132Py_pvoc_rdo(Py_pvoc * self, PyObject * args)
    90133{
    91134  PyObject *input;
    92   cvec_t *vec;
    93   fvec_t *output;
    94 
    95135  if (!PyArg_ParseTuple (args, "O", &input)) {
    96136    return NULL;
    97137  }
    98138
    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  }
    107154  // 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;
    110157}
    111158
     
    116163};
    117164
    118 AUBIO_TYPEOBJECT(pvoc, "aubio.pvoc")
     165PyTypeObject 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 "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33typedef struct
     
    88  uint_t samplerate;
    99  uint_t channels;
     10  fvec_t write_data;
     11  fmat_t mwrite_data;
    1012} Py_sink;
    1113
     
    116118  }
    117119  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");
    119121    return -1;
    120122  }
     
    125127}
    126128
    127 AUBIO_DEL(sink)
     129static void
     130Py_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}
    128136
    129137/* function Py_sink_do */
     
    135143
    136144  /* input vectors prototypes */
    137   fvec_t* write_data;
    138145  uint_t write;
    139146
     
    143150  }
    144151
    145 
    146152  /* 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  }
    155156
    156157
    157158  /* compute _do function */
    158   aubio_sink_do (self->o, write_data, write);
     159  aubio_sink_do (self->o, &(self->write_data), write);
    159160
    160161  Py_RETURN_NONE;
     
    169170
    170171  /* input vectors prototypes */
    171   fmat_t * write_data;
    172172  uint_t write;
    173173
     
    179179
    180180  /* 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  }
    190184
    191185  /* compute _do function */
    192   aubio_sink_do_multi (self->o, write_data, write);
     186  aubio_sink_do_multi (self->o, &(self->mwrite_data), write);
    193187  Py_RETURN_NONE;
    194188}
    195189
    196 AUBIO_MEMBERS_START(sink)
     190static PyMemberDef Py_sink_members[] = {
    197191  {"uri", T_STRING, offsetof (Py_sink, uri), READONLY,
    198192    "path at which the sink was created"},
     
    201195  {"channels", T_INT, offsetof (Py_sink, channels), READONLY,
    202196    "number of channels with which the sink was created"},
    203 AUBIO_MEMBERS_STOP(sink)
     197  { NULL } // sentinel
     198};
    204199
    205200static PyObject *
     
    217212};
    218213
    219 AUBIO_TYPEOBJECT(sink, "aubio.sink")
     214PyTypeObject 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 "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33typedef struct
     
    99  uint_t channels;
    1010  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;
    1116} Py_source;
    1217
     
    136141  self->o = new_aubio_source ( self->uri, self->samplerate, self->hop_size );
    137142  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);
    141145    return -1;
    142146  }
     
    145149    self->channels = aubio_source_get_channels ( self->o );
    146150  }
     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);
    147155
    148156  return 0;
    149157}
    150158
    151 AUBIO_DEL(source)
     159static void
     160Py_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
    152171
    153172/* function Py_source_do */
     
    155174Py_source_do(Py_source * self, PyObject * args)
    156175{
    157 
    158 
    159   /* output vectors prototypes */
    160   fvec_t* read_to;
     176  PyObject *outputs;
    161177  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);
    170178  read = 0;
    171179
    172 
     180  Py_INCREF(self->read_to);
     181  if (!PyAubio_ArrayToCFvec(self->read_to, &(self->c_read_to))) {
     182    return NULL;
     183  }
    173184  /* 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));
    180190  return outputs;
    181191}
     
    185195Py_source_do_multi(Py_source * self, PyObject * args)
    186196{
    187 
    188 
    189   /* output vectors prototypes */
    190   fmat_t* read_to;
     197  PyObject *outputs;
    191198  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);
    200199  read = 0;
    201200
    202 
     201  Py_INCREF(self->mread_to);
     202  if (!PyAubio_ArrayToCFmat(self->mread_to,  &(self->c_mread_to))) {
     203    return NULL;
     204  }
    203205  /* 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));
    210211  return outputs;
    211212}
    212213
    213 AUBIO_MEMBERS_START(source)
     214static PyMemberDef Py_source_members[] = {
    214215  {"uri", T_STRING, offsetof (Py_source, uri), READONLY,
    215216    "path at which the source was created"},
     
    220221  {"hop_size", T_INT, offsetof (Py_source, hop_size), READONLY,
    221222    "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};
    224227
    225228static PyObject *
     
    227230{
    228231  uint_t tmp = aubio_source_get_samplerate (self->o);
    229   return (PyObject *)PyInt_FromLong (tmp);
     232  return (PyObject *)PyLong_FromLong (tmp);
    230233}
    231234
     
    234237{
    235238  uint_t tmp = aubio_source_get_channels (self->o);
    236   return (PyObject *)PyInt_FromLong (tmp);
     239  return (PyObject *)PyLong_FromLong (tmp);
    237240}
    238241
     
    249252  uint_t err = 0;
    250253
    251   uint_t position;
     254  int position;
    252255  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);
    253263    return NULL;
    254264  }
     
    279289};
    280290
    281 AUBIO_TYPEOBJECT(source, "aubio.source")
     291PyTypeObject 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  
    8585{
    8686  int err = 0;
     87  PyObject *dict, *f, *g, *h;
    8788
    8889  err = _import_umath ();
     
    9293  }
    9394
    94   PyObject *f, *dict;
    9595  dict = PyModule_GetDict(m);
    9696  f = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_unwrap2pi_data, Py_aubio_unary_types,
     
    100100  Py_DECREF(f);
    101101
    102   PyObject *g;
    103102  g = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_freqtomidi_data, Py_aubio_unary_types,
    104103          Py_aubio_unary_n_types, Py_aubio_unary_n_inputs, Py_aubio_unary_n_outputs,
     
    107106  Py_DECREF(g);
    108107
    109   PyObject *h;
    110108  h = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_miditofreq_data, Py_aubio_unary_types,
    111109          Py_aubio_unary_n_types, Py_aubio_unary_n_inputs, Py_aubio_unary_n_outputs,
  • python/lib/aubio/__init__.py

    r60fc05b rf264b17  
    22
    33import numpy
    4 from _aubio import *
    5 from midiconv import *
    6 from slicing import *
     4from ._aubio import *
     5from ._aubio import float_type
     6from .midiconv import *
     7from .slicing import *
    78
    89class 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  
    11# -*- coding: utf-8 -*-
     2""" utilities to convert midi note number to and from note names """
     3
     4__all__ = ['note2midi', 'midi2note', 'freq2note']
     5
     6import sys
     7py3 = sys.version_info[0] == 3
     8if py3:
     9    str_instances = str
     10    int_instances = int
     11else:
     12    str_instances = (str, unicode)
     13    int_instances = (int, long)
    214
    315def note2midi(note):
    416    " convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] "
    517    _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}
    720    _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))
    1226    notename, modifier, octave = [None]*3
    1327
     
    2741
    2842    if notename not in _valid_notenames:
    29         raise ValueError, "%s is not a valid note name" % notename
     43        raise ValueError("%s is not a valid note name" % notename)
    3044    if modifier not in _valid_modifiers:
    31         raise ValueError, "%s is not a valid modifier" % modifier
     45        raise ValueError("%s is not a valid modifier" % modifier)
    3246    if octave not in _valid_octaves:
    33         raise ValueError, "%s is not a valid octave" % octave
     47        raise ValueError("%s is not a valid octave" % octave)
    3448
    3549    midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier]
    3650    if midi > 127:
    37         raise ValueError, "%s is outside of the range C-2 to G8" % note
     51        raise ValueError("%s is outside of the range C-2 to G8" % note)
    3852    return midi
    3953
    4054def midi2note(midi):
    4155    " 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)
    4760    _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)
    4962
    5063def freq2note(freq):
     64    " convert frequency in Hz to nearest note name, e.g. [0, 22050.] -> [C-1, G9] "
    5165    from aubio import freqtomidi
    5266    return midi2note(int(freqtomidi(freq)))
  • python/lib/aubio/slicing.py

    r60fc05b rf264b17  
     1"""utility routines to slice sound files at given timestamps"""
     2
     3import os
    14from aubio import source, sink
    2 import os
    35
    4 max_timestamp = 1e120
     6_max_timestamp = 1e120
    57
    6 def slice_source_at_stamps(source_file, timestamps, timestamps_end = None,
    7         output_dir = None,
    8         samplerate = 0,
    9         hopsize = 256):
     8def 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 """
    1011
    11     if timestamps == None or len(timestamps) == 0:
    12         raise ValueError ("no timestamps given")
     12    if timestamps is None or len(timestamps) == 0:
     13        raise ValueError("no timestamps given")
    1314
    1415    if timestamps[0] != 0:
    1516        timestamps = [0] + timestamps
    16         if timestamps_end != None:
     17        if timestamps_end is not None:
    1718            timestamps_end = [timestamps[1] - 1] + timestamps_end
    1819
    19     if timestamps_end != None:
     20    if timestamps_end is not None:
    2021        if len(timestamps_end) != len(timestamps):
    21             raise ValueError ("len(timestamps_end) != len(timestamps)")
     22            raise ValueError("len(timestamps_end) != len(timestamps)")
    2223    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]
    2425
    25     regions = zip(timestamps, timestamps_end)
     26    regions = list(zip(timestamps, timestamps_end))
    2627    #print regions
    2728
    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:
    3031        if not os.path.isdir(output_dir):
    3132            os.makedirs(output_dir)
     
    3334
    3435    def new_sink_name(source_base_name, timestamp, samplerate):
     36        """ create a sink based on a timestamp in samples, converted in seconds """
    3537        timestamp_seconds = timestamp / float(samplerate)
    3638        return source_base_name + "_%011.6f" % timestamp_seconds + '.wav'
    3739
    38     # reopen source file
    39     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
    4143
    4244    total_frames = 0
     
    4547    while True:
    4648        # get hopsize new samples from source
    47         vec, read = s.do_multi()
     49        vec, read = _source.do_multi()
    4850        # if the total number of frames read will exceed the next region start
    4951        if len(regions) and total_frames + read >= regions[0][0]:
     
    5456            new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate)
    5557            # create its sink
    56             g = sink(new_sink_path, samplerate, s.channels)
     58            _sink = sink(new_sink_path, samplerate, _source.channels)
    5759            # 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}
    5961            # append the dictionary to the current list of slices
    6062            slices.append(new_slice)
     
    6365            start_stamp = current_slice['start_stamp']
    6466            end_stamp = current_slice['end_stamp']
    65             g = current_slice['sink']
     67            _sink = current_slice['sink']
    6668            # sample index to start writing from new source vector
    6769            start = max(start_stamp - total_frames, 0)
     
    7375                if remaining > start:
    7476                    # write remaining samples from current region
    75                     g.do_multi(vec[:,start:remaining], remaining - start)
     77                    _sink.do_multi(vec[:, start:remaining], remaining - start)
    7678                    #print "closing region", "remaining", remaining
    7779                    # close this file
    78                     g.close()
     80                    _sink.close()
    7981            elif read > start:
    8082                # write all the samples
    81                 g.do_multi(vec[:,start:read], read - start)
     83                _sink.do_multi(vec[:, start:read], read - start)
    8284        total_frames += read
    83         if read < hopsize: break
     85        if read < hopsize:
     86            break
  • python/scripts/aubiocut

    r60fc05b rf264b17  
    135135            options.source_file = args[0]
    136136        else:
    137             print "no file name given\n", usage
     137            print ("no file name given\n" + usage)
    138138            sys.exit(1)
    139139    return options, args
     
    172172        if o(samples):
    173173            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())
    175175        total_frames += read
    176176        if read < hopsize: break
     
    189189        timestamps_end = None
    190190        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")
    192192        if options.cut_until_nsamples:
    193193            timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]
  • python/tests/run_all_tests

    r60fc05b rf264b17  
    22
    33if __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  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45
    56class aubiomodule_test_case(TestCase):
    67
    7   def test_import(self):
    8     """ try importing aubio """
    9     import aubio
     8    def test_import(self):
     9        """ try importing aubio """
     10        import aubio
    1011
    1112if __name__ == '__main__':
    12   from unittest import main
    13   main()
     13    main()
    1414
  • python/tests/test_cvec.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    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
     3from unittest import main
     4import numpy as np
     5from numpy.testing import TestCase, assert_equal
     6from aubio import cvec, fvec, float_type
     7
     8wrong_type = 'float32' if float_type == 'float64' else 'float64'
    79
    810class aubio_cvec_test_case(TestCase):
     
    1012    def test_vector_created_with_zeroes(self):
    1113        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]
    1517        assert_equal(a.norm, 0.)
    1618        assert_equal(a.phas, 0.)
     
    4244    def test_assign_cvec_phas_slice(self):
    4345        spec = cvec(1024)
    44         spec.phas[39:-1] = -pi
     46        spec.phas[39:-1] = -np.pi
    4547        assert_equal(spec.phas[0:39], 0)
    46         assert_equal(spec.phas[39:-1], -pi)
     48        assert_equal(spec.phas[39:-1], -np.pi)
    4749        assert_equal(spec.norm, 0)
    4850
     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
     113class 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
    49144if __name__ == '__main__':
    50     from unittest import main
    51145    main()
  • python/tests/test_fft.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45from numpy.testing import assert_equal, assert_almost_equal
     6import numpy as np
    57from aubio import fvec, fft, cvec
    6 from numpy import array, shape
    7 from math import pi
     8from math import pi, floor
     9from random import random
    810
    911class aubio_fft_test_case(TestCase):
     
    2123        f = fft (win_s)
    2224        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,))
    2528
    2629    def test_zeros(self):
     
    3538    def test_impulse(self):
    3639        """ check the transform of one impulse at a random place """
    37         from random import random
    38         from math import floor
    3940        win_s = 256
    40         i = floor(random()*win_s)
     41        i = int(floor(random()*win_s))
    4142        impulse = pi * random()
    4243        f = fft(win_s)
     
    5051
    5152    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 """
    5554        win_s = 256
    56         i = 0
    57         impulse = -10.
     55        i = int(floor(random()*win_s))
     56        impulse = -.1
    5857        f = fft(win_s)
    5958        timegrain = fvec(win_s)
     59        timegrain[0] = 0
    6060        timegrain[i] = impulse
    6161        fftgrain = f ( timegrain )
    6262        #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 )
    6464        if impulse < 0:
    6565            # 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 )
    6767            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)
    6969        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)
    7373        # now check the resynthesis
    7474        synthgrain = f.rdo ( fftgrain )
     
    9696        """ check running fft.rdo before fft.do works """
    9797        win_s = 1024
    98         impulse = pi
    9998        f = fft(win_s)
    10099        fftgrain = cvec(win_s)
     
    107106        show ()
    108107
     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
     166class 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
    109187if __name__ == '__main__':
    110     from unittest import main
    111188    main()
    112 
  • python/tests/test_filter.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase, assert_equal, assert_almost_equal
    45from aubio import fvec, digital_filter
    5 from numpy import array
    66from utils import array_from_text_file
    77
    88class aubio_filter_test_case(TestCase):
    99
    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())
    3016
    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 )
    3930
    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)
     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)
    4839
    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)
     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)
    5748
    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
     80class aubio_filter_wrong_params(TestCase):
     81
     82    def test_negative_order(self):
     83        with self.assertRaises(ValueError):
     84            digital_filter(-1)
    7085
    7186if __name__ == '__main__':
    72   from unittest import main
    73   main()
    74 
     87    main()
  • python/tests/test_filterbank.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45from 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
     6import numpy as np
     7from aubio import cvec, filterbank, float_type
    98from utils import array_from_text_file
    109
    1110class aubio_filterbank_test_case(TestCase):
    1211
    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])
    1615
    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())
    2221
    23   def test_phase(self):
    24     f = filterbank(40, 512)
    25     c = cvec(512)
    26     c.phas[:] = pi
    27     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);
    2827
    29   def test_norm(self):
    30     f = filterbank(40, 512)
    31     c = cvec(512)
    32     c.norm[:] = 1
    33     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);
    3433
    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)
    4039
    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 )
    5050
    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 )
    5858
    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
     65class 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))
    6482
    6583if __name__ == '__main__':
    66   from unittest import main
    67   main()
    68 
     84    main()
  • python/tests/test_filterbank_mel.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45from numpy.testing import assert_equal, assert_almost_equal
    56from numpy import array, shape
    6 from aubio import cvec, filterbank
     7from aubio import cvec, filterbank, float_type
    78
    89class aubio_filterbank_mel_test_case(TestCase):
    910
    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) )
    1516
    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))
    2627
    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().T
    33     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)
    3435
    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().T
    41     spec = cvec(1024)
    42     spec.norm[:] = 1
    43     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])
    4647
    4748if __name__ == '__main__':
    48   from unittest import main
    49   main()
    50 
    51 
     49    main()
  • python/tests/test_fvec.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
     3from unittest import main
     4import numpy as np
     5from numpy.testing import TestCase, assert_equal, assert_almost_equal
    56from aubio import fvec, zero_crossing_rate, alpha_norm, min_removal
    6 from numpy import array, shape
     7from aubio import float_type
     8
     9wrong_type = 'float32' if float_type == 'float64' else 'float64'
    710
    811default_size = 512
     
    1215    def test_vector_created_with_zeroes(self):
    1316        a = fvec(10)
    14         assert a.dtype == 'float32'
     17        assert a.dtype == float_type
    1518        assert a.shape == (10,)
    16         assert_equal (a, 0)
     19        assert_equal(a, 0)
    1720
    1821    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
    2124        assert a.shape == (4,)
    22         assert_equal (range(4), a)
     25        assert_equal(list(range(4)), a)
    2326
    2427    def test_vector_assign_element(self):
     
    3538    def test_vector(self):
    3639        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)
    4044        a = fvec(10)
    41         a = fvec(1)
    42         a.T
    43         array(a).T
    44         a = range(len(a))
     45        _ = a.T
    4546
    46     def test_wrong_values(self):
    47         self.assertRaises (ValueError, fvec, -10)
    48  
     47class 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) """
    4959        a = fvec(2)
    50         self.assertRaises (IndexError, a.__getitem__, 3)
    51         self.assertRaises (IndexError, a.__getitem__, 2)
     60        self.assertRaises(IndexError, a.__getitem__, 3)
     61        self.assertRaises(IndexError, a.__getitem__, 2)
    5262
    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.)
     63class aubio_wrong_fvec_input(TestCase):
     64    """ uses min_removal to test PyAubio_IsValidVector """
    6365
    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)
    6668
    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)
    7771
    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)
    8575
    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
     95class 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
     103class aubio_zero_crossing_rate_test(TestCase):
    89104
    90105    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.)
    99108
    100     def test_alpha_norm_of_array_of_float64(self):
    101         # check scalar fail
    102         a = array(1, dtype = 'float64')
    103         self.assertRaises (ValueError, alpha_norm, a, 1)
    104         # check 3d array fail
    105         a = array([[[1,2],[3,4]]], dtype = 'float64')
    106         self.assertRaises (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 fail
    111         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
     121class aubio_fvec_min_removal(TestCase):
    113122
    114123    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)
    116125        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])
    122127
    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)
     128class aubio_fvec_test_memory(TestCase):
    126129
    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
    134141
    135142if __name__ == '__main__':
    136     from unittest import main
    137143    main()
  • python/tests/test_mathutils.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase, assert_equal
    45from numpy import array, arange, isnan, isinf
     
    1314        unwrap2pi(int(23))
    1415        unwrap2pi(float(23.))
    15         unwrap2pi(long(23.))
     16        unwrap2pi(int(23.))
    1617        unwrap2pi(arange(10))
    1718        unwrap2pi(arange(10).astype("int"))
     
    2425        unwrap2pi(a)
    2526        a = pi/100. * arange(-600,600).astype("float")
    26         b = unwrap2pi (a)
     27        unwrap2pi(a)
    2728        #print zip(a, b)
    2829
    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.])
    3333
    3434    def test_unwrap2pi_takes_fvec(self):
     
    5454
    5555    def test_freqtomidi(self):
    56         a = array(range(-20, 50000, 100) + [ -1e32, 1e32 ])
     56        a = array(list(range(-20, 50000, 100)) + [ -1e32, 1e32 ])
    5757        b = freqtomidi(a)
    5858        #print zip(a, b)
     
    6262
    6363    def test_miditofreq(self):
    64         a = range(-30, 200) + [-100000, 10000]
     64        a = list(range(-30, 200)) + [-100000, 10000]
    6565        b = miditofreq(a)
    6666        #print zip(a, b)
     
    7070
    7171    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 ]
    7474        #print zip(a, b)
    7575        assert_equal ( isnan(array(b)), False )
     
    7878
    7979    def test_bintomidi(self):
    80         a = range(-100, 512)
     80        a = list(range(-100, 512))
    8181        b = [ bintomidi(x, 44100, 512) for x in a ]
    8282        #print zip(a, b)
     
    8686
    8787    def test_freqtobin(self):
    88         a = range(-20, 50000, 100) + [ -1e32, 1e32 ]
     88        a = list(range(-20, 50000, 100)) + [ -1e32, 1e32 ]
    8989        b = [ freqtobin(x, 44100, 512) for x in a ]
    9090        #print zip(a, b)
     
    9494
    9595    def test_bintofreq(self):
    96         a = range(-20, 148)
     96        a = list(range(-20, 148))
    9797        b = [ bintofreq(x, 44100, 512) for x in a ]
    9898        #print zip(a, b)
     
    102102
    103103if __name__ == '__main__':
    104     from unittest import main
    105104    main()
  • python/tests/test_midi2note.py

    r60fc05b rf264b17  
    2828        self.assertRaises(ValueError, midi2note, -2)
    2929
    30     def test_midi2note_negative_value(self):
     30    def test_midi2note_large(self):
    3131        " fails when passed a value greater than 127 "
    3232        self.assertRaises(ValueError, midi2note, 128)
  • python/tests/test_musicutils.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
     4import numpy as np
    35from numpy.testing import TestCase
    46from numpy.testing.utils import assert_equal, assert_almost_equal
    5 from numpy import cos, arange
    6 from math import pi
    7 
    87from aubio import window, level_lin, db_spl, silence_detection, level_detection
    9 
    10 from aubio import fvec
     8from aubio import fvec, float_type
    119
    1210class aubio_window(TestCase):
     
    1614
    1715    def test_fail_name_not_string(self):
    18         try:
     16        with self.assertRaises(TypeError):
    1917            window(10, 1024)
    20         except ValueError, e:
    21             pass
    22         else:
    23             self.fail('non-string window type does not raise a ValueError')
    2418
    2519    def test_fail_size_not_int(self):
    26         try:
     20        with self.assertRaises(TypeError):
    2721            window("default", "default")
    28         except ValueError, e:
    29             pass
    30         else:
    31             self.fail('non-integer window length does not raise a ValueError')
    3222
    3323    def test_compute_hanning_1024(self):
    3424        size = 1024
    3525        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)
    3727        assert_almost_equal(aubio_window, numpy_window)
    3828
     
    4232
    4333    def test_fail_not_fvec(self):
    44         try:
     34        with self.assertRaises(ValueError):
    4535            level_lin("default")
    46         except ValueError, e:
    47             pass
    48         else:
    49             self.fail('non-number input phase does not raise a TypeError')
    5036
    5137    def test_zeros_is_zeros(self):
     
    5339
    5440    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.)
    5742
    5843class aubio_db_spl(TestCase):
     
    6146
    6247    def test_fail_not_fvec(self):
    63         try:
     48        with self.assertRaises(ValueError):
    6449            db_spl("default")
    65         except ValueError, e:
    66             pass
    67         else:
    68             self.fail('non-number input phase does not raise a TypeError')
    6950
    7051    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)))
    7353
    7454    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.)
    7756
    7857class aubio_silence_detection(TestCase):
     
    8160
    8261    def test_fail_not_fvec(self):
    83         try:
     62        with self.assertRaises(ValueError):
    8463            silence_detection("default", -70)
    85         except ValueError, e:
    86             pass
    87         else:
    88             self.fail('non-number input phase does not raise a TypeError')
    8964
    9065    def test_zeros_is_one(self):
    91         from math import isinf
    9266        assert silence_detection(fvec(1024), -70) == 1
    9367
    9468    def test_minus_ones_is_zero(self):
    9569        from numpy import ones
    96         assert silence_detection(ones(1024, dtype="float32"), -70) == 0
     70        assert silence_detection(ones(1024, dtype = float_type), -70) == 0
    9771
    9872class aubio_level_detection(TestCase):
     
    10175
    10276    def test_fail_not_fvec(self):
    103         try:
     77        with self.assertRaises(ValueError):
    10478            level_detection("default", -70)
    105         except ValueError, e:
    106             pass
    107         else:
    108             self.fail('non-number input phase does not raise a TypeError')
    10979
    11080    def test_zeros_is_one(self):
    111         from math import isinf
    11281        assert level_detection(fvec(1024), -70) == 1
    11382
    11483    def test_minus_ones_is_zero(self):
    11584        from numpy import ones
    116         assert level_detection(ones(1024, dtype="float32"), -70) == 0
     85        assert level_detection(ones(1024, dtype = float_type), -70) == 0
    11786
    11887if __name__ == '__main__':
    119     from unittest import main
    12088    main()
  • python/tests/test_note2midi.py

    r60fc05b rf264b17  
    22# -*- coding: utf-8 -*-
    33
    4 from aubio import note2midi
     4from __future__ import unicode_literals
     5
     6from aubio import note2midi, freq2note
    57import unittest
    68
     
    1517        ( 'A#4', 70 ),
    1618        ( 'Bb4', 70 ),
    17         ( u'B♭4', 70 ),
     19        ( 'B♭4', 70 ),
    1820        ( 'G8', 115 ),
    19         ( u'G♯8', 116 ),
     21        ( 'G♯8', 116 ),
    2022        ( '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 ),
    2426        )
    2527
     
    5052
    5153    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"
    5355        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')
    5464
    5565    def test_note2midi_wrong_data_type(self):
     
    5767        self.assertRaises(TypeError, note2midi, 123)
    5868
     69
     70class freq2note_simple_test(unittest.TestCase):
     71
     72    def test_freq2note(self):
     73        " make sure freq2note(441) == A4 "
     74        self.assertEqual("A4", freq2note(441))
     75
    5976if __name__ == '__main__':
    6077    unittest.main()
  • python/tests/test_onset.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
     3from unittest import main
     4from numpy.testing import TestCase, assert_equal, assert_almost_equal
    55from aubio import onset
    66
     
    8585
    8686if __name__ == '__main__':
    87     from unittest import main
    8887    main()
  • python/tests/test_phasevoc.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    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
     3from numpy.testing import TestCase, assert_equal, assert_array_less
     4from aubio import fvec, cvec, pvoc, float_type
     5from nose2 import main
     6from nose2.tools import params
     7import numpy as np
    78
    8 precision = 6
     9if float_type == 'float32':
     10    max_sq_error = 1.e-12
     11else:
     12    max_sq_error = 1.e-29
     13
     14def 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
     18def create_noise(hop_s):
     19    return np.random.rand(hop_s).astype(float_type) * 2. - 1.
    920
    1021class aubio_pvoc_test_case(TestCase):
     
    3142        f = pvoc (win_s, hop_s)
    3243        t = fvec (hop_s)
    33         for time in range( 4 * win_s / hop_s ):
     44        for _ in range( int ( 4 * win_s / hop_s ) ):
    3445            s = f(t)
    3546            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.)
    4051
    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
    45103        f = pvoc(buf_s, hop_s)
    46         sigin = fvec(hop_s)
    47104        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
     113class 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
     151class 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)
    78184
    79185if __name__ == '__main__':
    80   from unittest import main
    81   main()
     186    main()
    82187
  • python/tests/test_pitch.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    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
     3from unittest import TestCase, main
     4from numpy.testing import assert_equal
     5from numpy import sin, arange, mean, median, isnan, pi
     6from aubio import fvec, pitch, freqtomidi, float_type
    87
    98class aubio_pitch_Good_Values(TestCase):
     
    2524        p = pitch('default', 2048, 512, 32000)
    2625        f = fvec (512)
    27         for i in xrange(10): assert_equal (p(f), 0.)
     26        for _ in range(10): assert_equal (p(f), 0.)
    2827
    2928    def test_run_on_ones(self):
     
    3231        f = fvec (512)
    3332        f[:] = 1
    34         for i in xrange(10): assert_equal (p(f), 0.)
     33        for _ in range(10): assert_equal (p(f), 0.)
    3534
    3635class aubio_pitch_Sinusoid(TestCase):
     
    5150
    5251    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)
    5453
    5554    def run_pitch(self, p, input_vec, freq):
    56         count = 0
    5755        pitches, errors = [], []
    5856        input_blocks = input_vec.reshape((-1, p.hop_size))
     
    6462        assert_equal ( isnan(pitches), False )
    6563        # cut the first candidates
    66         cut = ( p.buf_size - p.hop_size ) / p.hop_size
     64        #cut = ( p.buf_size - p.hop_size ) / p.hop_size
    6765        pitches = pitches[2:]
    6866        errors = errors[2:]
     
    125123
    126124if __name__ == '__main__':
    127     from unittest import main
    128125    main()
  • python/tests/test_sink.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, assert_equal, assert_almost_equal
     3from nose2 import main
     4from nose2.tools import params
     5from numpy.testing import TestCase
    46from aubio import fvec, source, sink
    5 from numpy import array
    67from utils import list_all_sounds, get_tmp_sink_path, del_tmp_sink_path
    78
    89list_of_sounds = list_all_sounds('sounds')
     10samplerates = [0, 44100, 8000, 32000]
     11hop_sizes = [512, 1024, 64]
     12
    913path = None
    1014
    1115many_files = 300 # 256 opened files is too much
    1216
     17all_params = []
     18for 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
    1323class 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\'')
    1428
    1529    def test_many_sinks(self):
     
    2438            sink_list.append(g)
    2539            write = 32
    26             for n in range(200):
     40            for _ in range(200):
    2741                vec = fvec(write)
    2842                g(vec, write)
     
    3044        shutil.rmtree(tmpdir)
    3145
    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
    3849        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)
    5463
    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)
    10680
    10781    def test_close_file(self):
     
    12195
    12296if __name__ == '__main__':
    123     from unittest import main
    12497    main()
  • python/tests/test_slicing.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
    5 
     3from unittest import main
     4from numpy.testing import TestCase, assert_equal
    65from aubio import slice_source_at_stamps
    7 from utils import *
     6from utils import count_files_in_directory, get_default_test_sound
     7from utils import count_samples_in_directory, count_samples_in_file
    88
    99import tempfile
     
    147147
    148148if __name__ == '__main__':
    149     from unittest import main
    150149    main()
  • python/tests/test_source.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, assert_equal, assert_almost_equal
    4 from aubio import fvec, source
    5 from numpy import array
     3from nose2 import main
     4from nose2.tools import params
     5from numpy.testing import TestCase
     6from aubio import source
    67from utils import list_all_sounds
    78
    89list_of_sounds = list_all_sounds('sounds')
     10samplerates = [0, 44100, 8000, 32000]
     11hop_sizes = [512, 1024, 64]
     12
    913path = None
     14
     15all_params = []
     16for 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
    1021
    1122class aubio_source_test_case_base(TestCase):
     
    1324    def setUp(self):
    1425        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]
    1527
    1628class aubio_source_test_case(aubio_source_test_case_base):
     
    3648        total_frames = 0
    3749        while True:
    38             vec, read = f()
     50            _ , read = f()
    3951            total_frames += read
    4052            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))
    4556        return total_frames
    4657
    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)
    5366
    54     def test_samplerate_none(self):
    55         for p in list_of_sounds:
    56             f = source(p)
    57             assert f.samplerate != 0
    58             self.read_from_source(f)
     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)
    5972
    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
     110class 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
     116class aubio_source_test_wrong_params_with_file(aubio_source_test_case_base):
    65117
    66118    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)
    74121
    75122    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)
    83125
    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)
    90129
    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')
    102142
    103143class aubio_source_readmulti_test_case(aubio_source_read_test_case):
     
    106146        total_frames = 0
    107147        while True:
    108             vec, read = f.do_multi()
     148            _, read = f.do_multi()
    109149            total_frames += read
    110150            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))
    116154        return total_frames
    117155
    118156if __name__ == '__main__':
    119     from unittest import main
    120157    main()
  • python/tests/test_specdesc.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase, assert_equal, assert_almost_equal
    45from numpy import random, arange, log, zeros
    5 from aubio import specdesc, cvec
    6 from math import pi
     6from aubio import specdesc, cvec, float_type
    77
    88methods = ["default",
     
    3030
    3131        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.)
    5744
    5845    def test_phase(self):
     
    6148        # phase of zeros is zero
    6249        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)
    6451        # phase of random is not zero
    6552        spec.norm[:] = 1
     
    7158        # specdiff of zeros is zero
    7259        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)
    7461        # phase of random is not zero
    7562        spec.norm[:] = 1
     
    8067        c = cvec()
    8168        assert_equal( 0., o(c))
    82         a = arange(c.length, dtype='float32')
     69        a = arange(c.length, dtype=float_type)
    8370        c.norm = a
    8471        assert_equal (a, c.norm)
     
    8976        c = cvec()
    9077        assert_equal( 0., o(c))
    91         a = arange(c.length, dtype='float32')
     78        a = arange(c.length, dtype=float_type)
    9279        c.norm = a
    9380        assert_equal (a, c.norm)
     
    10289        c = cvec()
    10390        assert_equal( 0., o(c))
    104         a = arange(c.length, dtype='float32')
     91        a = arange(c.length, dtype=float_type)
    10592        c.norm = a
    10693        assert_almost_equal( sum(a * log(1.+ a/1.e-1 ) ) / o(c), 1., decimal=6)
     
    11097        c = cvec()
    11198        assert_equal( 0., o(c))
    112         a = arange(c.length, dtype='float32')
     99        a = arange(c.length, dtype=float_type)
    113100        c.norm = a
    114101        assert_almost_equal( sum(log(1.+ a/1.e-1 ) ) / o(c), 1, decimal=6)
     
    118105        c = cvec()
    119106        assert_equal( 0., o(c))
    120         a = arange(c.length, dtype='float32')
     107        a = arange(c.length, dtype=float_type)
    121108        c.norm = a
    122109        assert_equal( sum(a), o(c))
    123110        assert_equal( 0, o(c))
    124         c.norm = zeros(c.length, dtype='float32')
     111        c.norm = zeros(c.length, dtype=float_type)
    125112        assert_equal( 0, o(c))
    126113
     
    130117        # make sure centroid of zeros is zero
    131118        assert_equal( 0., o(c))
    132         a = arange(c.length, dtype='float32')
     119        a = arange(c.length, dtype=float_type)
    133120        c.norm = a
    134121        centroid = sum(a*a) / sum(a)
     
    141128        o = specdesc("spread")
    142129        c = cvec(2048)
    143         ramp = arange(c.length, dtype='float32')
     130        ramp = arange(c.length, dtype=float_type)
    144131        assert_equal( 0., o(c))
    145132
     
    154141        c = cvec()
    155142        assert_equal( 0., o(c))
    156         a = arange(c.length, dtype='float32')
     143        a = arange(c.length, dtype=float_type)
    157144        c.norm = a
    158145        centroid = sum(a*a) / sum(a)
     
    168155        c = cvec()
    169156        assert_equal( 0., o(c))
    170         a = arange(c.length, dtype='float32')
     157        a = arange(c.length, dtype=float_type)
    171158        c.norm = a
    172159        centroid = sum(a*a) / sum(a)
     
    179166        c = cvec()
    180167        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)
    183170        c.norm = a
    184171        num = len(a) * sum(k*a) - sum(k)*sum(a)
     
    187174        assert_almost_equal (slope, o(c), decimal = 5)
    188175
    189         a = arange(0, c.length * 2, +2, dtype='float32')
     176        a = arange(0, c.length * 2, +2, dtype=float_type)
    190177        c.norm = a
    191178        num = len(a) * sum(k*a) - sum(k)*sum(a)
     
    194181        assert_almost_equal (slope, o(c), decimal = 5)
    195182
    196         a = arange(0, c.length * 2, +2, dtype='float32')
     183        a = arange(0, c.length * 2, +2, dtype=float_type)
    197184        c.norm = a * 2
    198185        assert_almost_equal (slope, o(c), decimal = 5)
     
    202189        c = cvec()
    203190        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)
    206193        c.norm = a
    207194        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
    208195        assert_almost_equal (decrease, o(c), decimal = 5)
    209196
    210         a = arange(0, c.length * 2, +2, dtype='float32')
     197        a = arange(0, c.length * 2, +2, dtype=float_type)
    211198        c.norm = a
    212199        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
    213200        assert_almost_equal (decrease, o(c), decimal = 5)
    214201
    215         a = arange(0, c.length * 2, +2, dtype='float32')
     202        a = arange(0, c.length * 2, +2, dtype=float_type)
    216203        c.norm = a * 2
    217204        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
     
    222209        c = cvec()
    223210        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)
    226212        c.norm = a
    227213        cumsum = .95*sum(a*a)
    228214        i = 0; rollsum = 0
    229215        while rollsum < cumsum:
    230           rollsum += a[i]*a[i]
    231           i+=1
     216            rollsum += a[i]*a[i]
     217            i+=1
    232218        rolloff = i
    233219        assert_equal (rolloff, o(c))
    234220
     221class 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')
    235232
    236233if __name__ == '__main__':
    237     from unittest import main
    238234    main()
  • python/tests/test_zero_crossing_rate.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase
    4 
    55from aubio import fvec, zero_crossing_rate
    66
     
    2323    def test_impulse(self):
    2424        """ 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.
    2626        self.assertEqual(0., zero_crossing_rate(self.vector))
    2727
    2828    def test_negative_impulse(self):
    2929        """ 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.
    3131        self.assertEqual(2./buf_size, zero_crossing_rate(self.vector))
    3232
    3333    def test_single(self):
    3434        """ 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.
    3737        self.assertEqual(2./buf_size, zero_crossing_rate(self.vector))
    3838
    3939    def test_single_with_gap(self):
    4040        """ 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.
    4343        self.assertEqual(2./buf_size, zero_crossing_rate(self.vector))
    4444
    4545if __name__ == '__main__':
    46     from unittest import main
    4746    main()
  • python/tests/utils.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3import os
     4import glob
     5import numpy as np
     6from tempfile import mkstemp
     7
    38def array_from_text_file(filename, dtype = 'float'):
    4     import os.path
    5     from numpy import array
    69    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)
    914
    1015def list_all_sounds(rel_dir):
    11     import os.path, glob
    1216    datadir = os.path.join(os.path.dirname(__file__), rel_dir)
    1317    return glob.glob(os.path.join(datadir,'*.*'))
     
    2125
    2226def get_tmp_sink_path():
    23     from tempfile import mkstemp
    24     import os
    2527    fd, path = mkstemp()
    2628    os.close(fd)
     
    2830
    2931def 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)))
    3242
    3343def array_from_yaml_file(filename):
     
    4454    total_frames = 0
    4555    while True:
    46         samples, read = s()
     56        _, read = s()
    4757        total_frames += read
    4858        if read < hopsize: break
     
    5060
    5161def count_samples_in_directory(samples_dir):
    52     import os
    5362    total_frames = 0
    5463    for f in os.walk(samples_dir):
     
    6170
    6271def count_files_in_directory(samples_dir):
    63     import os
    6472    total_files = 0
    6573    for f in os.walk(samples_dir):
Note: See TracChangeset for help on using the changeset viewer.