source: python/aubio/gnuplot.py @ dbd19ea

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since dbd19ea was 33cf541, checked in by Paul Brossier <piem@altern.org>, 18 years ago

use options structure for plot_audio plot_spec
use options structure for plot_audio plot_spec

  • Property mode set to 100644
File size: 7.0 KB
RevLine 
[96fb8ad]1"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
2print aubio.__LICENSE__ for the terms of use
3"""
4
5__LICENSE__ = """\
6         Copyright (C) 2004 Paul Brossier <piem@altern.org>
7
8         This program is free software; you can redistribute it and/or modify
9         it under the terms of the GNU General Public License as published by
10         the Free Software Foundation; either version 2 of the License, or
11         (at your option) any later version.
12
13         This program is distributed in the hope that it will be useful,
14         but WITHOUT ANY WARRANTY; without even the implied warranty of
15         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16         GNU General Public License for more details.
17
18         You should have received a copy of the GNU General Public License
19         along with this program; if not, write to the Free Software
20         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
[65ebf30]21"""
[96fb8ad]22
23
[65ebf30]24def audio_to_array(filename):
25        import aubio.aubioclass
[733c2f8]26        import numarray
[65ebf30]27        hopsize  = 2048
28        filei    = aubio.aubioclass.sndfile(filename)
29        framestep = 1/(filei.samplerate()+0.)
30        channels = filei.channels()
31        myvec    = aubio.aubioclass.fvec(hopsize,channels)
32        data = []
33        readsize = hopsize
34        while (readsize==hopsize):
35                readsize = filei.read(hopsize,myvec)
36                #for i in range(channels):
37                i = 0
38                curpos = 0
39                while (curpos < readsize):
40                        data.append(myvec.get(curpos,i))
41                        curpos+=1
[733c2f8]42        time = numarray.arange(len(data))*framestep
[65ebf30]43        return time,data
44
[33cf541]45def plot_audio(filenames, g, options):
[65ebf30]46        d = []
47        todraw = len(filenames)
48        xorig = 0.
[da6d9af]49        xratio = 1./todraw
[e5cc1ea]50        g('set multiplot;')
[65ebf30]51        while (len(filenames)):
[431e9d8]52                time,data = audio_to_array(filenames.pop(0))
[33cf541]53                if todraw==1:
[da6d9af]54                        if max(time) < 1.:
55                                time = [t*1000. for t in time]
56                                g.xlabel('Time (ms)')
57                        else:
58                                g.xlabel('Time (s)')
[65ebf30]59                        g.ylabel('Amplitude')
[da6d9af]60                d.append(make_audio_plot(time,data))
[33cf541]61                g('set size %f,%f;' % (options.xsize*xratio,options.ysize) )
[e5cc1ea]62                g('set origin %f,0.;' % (xorig) )
63                g('set style data lines; \
[65ebf30]64                        set yrange [-1.:1.]; \
[733c2f8]65                        set xrange [0:%f]' % time[-1]) 
[65ebf30]66                g.plot(d.pop(0))
[33cf541]67                xorig += options.xsize*xratio
[e5cc1ea]68        g('unset multiplot;')
[96fb8ad]69
[e638bcf]70def audio_to_spec(filename,minf = 0, maxf = 0, lowthres = -20., 
71                bufsize= 8192, hopsize = 1024):
[431e9d8]72        from aubioclass import fvec,cvec,pvoc,sndfile
[da6d9af]73        from math import log10
[431e9d8]74        filei     = sndfile(filename)
75        srate     = float(filei.samplerate())
76        framestep = hopsize/srate
77        freqstep  = srate/bufsize
78        channels  = filei.channels()
79        myvec = fvec(hopsize,channels)
[da6d9af]80        myfft = cvec(bufsize,channels)
81        pv    = pvoc(bufsize,hopsize,channels)
[431e9d8]82        data,time,freq = [],[],[]
[da6d9af]83
84        if maxf == 0.: maxf = bufsize/2
85        else: maxf = int(maxf/freqstep)
86        if minf: minf = int(minf/freqstep)
87        else: minf = 0 
88
89        for f in range(minf,maxf):
[431e9d8]90                freq.append(f*freqstep)
91        readsize = hopsize
92        frameread = 0
93        while (readsize==hopsize):
94                readsize = filei.read(hopsize,myvec)
95                pv.do(myvec,myfft)
96                frame = []
97                i = 0 #for i in range(channels):
[da6d9af]98                curpos = minf
99                while (curpos < maxf):
100                        frame.append(max(lowthres,20.*log10(myfft.get(curpos,i)**2+0.00001)))
[431e9d8]101                        curpos+=1
102                time.append(frameread*framestep)
103                data.append(frame)
104                frameread += 1
105        # crop data if unfinished frames
106        if len(data[-1]) != len(data[0]):
107                data = data[0:-2]
108                time = time[0:-2]
109        # verify size consistency
110        assert len(data) == len(time)
111        assert len(data[0]) == len(freq)
112        return data,time,freq
113
[33cf541]114def plot_spec(filename, g, options):
[431e9d8]115        import Gnuplot
[33cf541]116        data,time,freq = audio_to_spec(filename,
117    minf=options.minf,maxf=options.maxf,
118    bufsize=options.bufsize,hopsize=options.hopsize)
[431e9d8]119        xorig = 0.
[33cf541]120        if max(time) < 1.:
121                time = [t*1000. for t in time]
122                g.xlabel('Time (ms)')
123        else:
124                g.xlabel('Time (s)')
125        if options.xsize < 0.5 and not options.log and max(time) > 1.:
126                freq = [f/1000. for f in freq]
127                options.minf /= 1000.
128                options.maxf /= 1000.
129                g.ylabel('Frequency (kHz)')
130        else:
131                g.ylabel('Frequency (Hz)')
[da6d9af]132        g('set pm3d map')
133        g('set palette rgbformulae -25,-24,-32')
[e5cc1ea]134        g('set cbtics 20')
[da6d9af]135        #g('set colorbox horizontal')
136        g('set xrange [0.:%f]' % time[-1]) 
[33cf541]137        if options.log:
[da6d9af]138                g('set log y')
[33cf541]139                g('set yrange [%f:%f]' % (max(10,options.minf),options.maxf))
[e5cc1ea]140        else:
[33cf541]141                g('set yrange [%f:%f]' % (options.minf,options.maxf))
[9b138a8]142        g.splot(Gnuplot.GridData(data,time,freq, binary=1))
[7538ac5]143        #xorig += 1./todraw
[431e9d8]144
[2bd1a2a]145def downsample_audio(time,data,maxpoints=10000):
[32fa8e8]146  """ resample audio data to last only maxpoints """
147  import numarray
148  length = len(time)
149  downsample = length/maxpoints
150  if downsample == 0: downsample = 1
151  x = numarray.array(time).resize(length)[0:-1:downsample]
152  y = numarray.array(data).resize(length)[0:-1:downsample]
153  return x,y
[2bd1a2a]154
[a0fd4e4]155def make_audio_plot(time,data,maxpoints=10000):
[32fa8e8]156  """ create gnuplot plot from an audio file """
157  import Gnuplot, Gnuplot.funcutils
158  x,y = downsample_audio(time,data,maxpoints=maxpoints)
159  return Gnuplot.Data(x,y,with='lines')
[80c0417]160
[0ab19df]161def gnuplot_addargs(parser):
162  """ add common gnuplot argument to OptParser object """
163  parser.add_option("-x","--xsize",
164          action="store", dest="xsize", default=1., 
165          type='float',help="define xsize for plot")
166  parser.add_option("-y","--ysize",
167          action="store", dest="ysize", default=1., 
168          type='float',help="define ysize for plot")
[33cf541]169  parser.add_option("--debug",
[0ab19df]170          action="store_true", dest="debug", default=False, 
171          help="use gnuplot debug mode")
[33cf541]172  parser.add_option("--persist",
[0ab19df]173          action="store_false", dest="persist", default=True, 
174          help="do not use gnuplot persistant mode")
[33cf541]175  parser.add_option("--lmargin",
176          action="store", dest="lmargin", default=None, 
177          type='int',help="define left margin for plot")
178  parser.add_option("--rmargin",
179          action="store", dest="rmargin", default=None, 
180          type='int',help="define right margin for plot")
181  parser.add_option("--bmargin",
182          action="store", dest="bmargin", default=None, 
183          type='int',help="define bottom margin for plot")
184  parser.add_option("--tmargin",
185          action="store", dest="tmargin", default=None, 
186          type='int',help="define top margin for plot")
[0ab19df]187  parser.add_option("-O","--outplot",
188          action="store", dest="outplot", default=None, 
189          help="save plot to output.{ps,png}")
190
191def gnuplot_create(outplot='',extension='', options=None):
192  import Gnuplot
193  g = Gnuplot.Gnuplot(debug=options.debug, persist=options.persist)
194  if not extension or not outplot: return g
195  if   extension == 'ps':  ext, extension = '.ps' , 'postscript'
196  elif extension == 'eps': ext, extension = '.eps' , 'postscript enhanced'
197  elif extension == 'epsc': ext, extension = '.eps' , 'postscript enhanced color'
198  elif extension == 'png': ext, extension = '.png', 'png'
199  elif extension == 'svg': ext, extension = '.svg', 'svg'
200  else: exit("ERR: unknown plot extension")
201  g('set terminal %s' % extension)
[33cf541]202  if options.lmargin: g('set lmargin %i' % options.lmargin)
203  if options.rmargin: g('set rmargin %i' % options.rmargin)
204  if options.bmargin: g('set bmargin %i' % options.bmargin)
205  if options.tmargin: g('set tmargin %i' % options.tmargin)
[0ab19df]206  if outplot != "stdout":
207    g('set output \'%s%s\'' % (outplot,ext))
208  g('set size %f,%f' % (options.xsize, options.ysize))
209  return g
Note: See TracBrowser for help on using the repository browser.