source: python/aubio/gnuplot.py @ c721874

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

fix gnuplot_create without options, add envelope draft, remove useless list
fix gnuplot_create without options, add envelope draft, remove useless list

  • Property mode set to 100644
File size: 7.5 KB
Line 
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.
21"""
22
23
24def audio_to_array(filename):
25        import aubio.aubioclass
26        import numarray
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
42        time = numarray.arange(len(data))*framestep
43        return time,data
44
45def plot_audio(filenames, g, options):
46        todraw = len(filenames)
47        xorig = 0.
48        xratio = 1./todraw
49        g('set multiplot;')
50        while (len(filenames)):
51                time,data = audio_to_array(filenames.pop(0))
52                if todraw==1:
53                        if max(time) < 1.:
54                                time = [t*1000. for t in time]
55                                g.xlabel('Time (ms)')
56                        else:
57                                g.xlabel('Time (s)')
58                        g.ylabel('Amplitude')
59                curplot = make_audio_plot(time,data)
60                g('set size %f,%f;' % (options.xsize*xratio,options.ysize) )
61                g('set origin %f,0.;' % (xorig) )
62                g('set style data lines; \
63                        set yrange [-1.:1.]; \
64                        set xrange [0:%f]' % time[-1]) 
65                g.plot(curplot)
66                xorig += options.xsize*xratio
67        g('unset multiplot;')
68
69def audio_to_spec(filename,minf = 0, maxf = 0, lowthres = -20., 
70                bufsize= 8192, hopsize = 1024):
71        from aubioclass import fvec,cvec,pvoc,sndfile
72        from math import log10
73        filei     = sndfile(filename)
74        srate     = float(filei.samplerate())
75        framestep = hopsize/srate
76        freqstep  = srate/bufsize
77        channels  = filei.channels()
78        myvec = fvec(hopsize,channels)
79        myfft = cvec(bufsize,channels)
80        pv    = pvoc(bufsize,hopsize,channels)
81        data,time,freq = [],[],[]
82
83        if maxf == 0.: maxf = bufsize/2
84        else: maxf = int(maxf/freqstep)
85        if minf: minf = int(minf/freqstep)
86        else: minf = 0 
87
88        for f in range(minf,maxf):
89                freq.append(f*freqstep)
90        readsize = hopsize
91        frameread = 0
92        while (readsize==hopsize):
93                readsize = filei.read(hopsize,myvec)
94                pv.do(myvec,myfft)
95                frame = []
96                i = 0 #for i in range(channels):
97                curpos = minf
98                while (curpos < maxf):
99                        frame.append(max(lowthres,20.*log10(myfft.get(curpos,i)**2+0.00001)))
100                        curpos+=1
101                time.append(frameread*framestep)
102                data.append(frame)
103                frameread += 1
104        # crop data if unfinished frames
105        if len(data[-1]) != len(data[0]):
106                data = data[0:-2]
107                time = time[0:-2]
108        # verify size consistency
109        assert len(data) == len(time)
110        assert len(data[0]) == len(freq)
111        return data,time,freq
112
113def plot_spec(filename, g, options):
114        import Gnuplot
115        data,time,freq = audio_to_spec(filename,
116    minf=options.minf,maxf=options.maxf,
117    bufsize=options.bufsize,hopsize=options.hopsize)
118        xorig = 0.
119        if max(time) < 1.:
120                time = [t*1000. for t in time]
121                g.xlabel('Time (ms)')
122        else:
123                g.xlabel('Time (s)')
124        if options.xsize < 0.5 and not options.log and max(time) > 1.:
125                freq = [f/1000. for f in freq]
126                options.minf /= 1000.
127                options.maxf /= 1000.
128                g.ylabel('Frequency (kHz)')
129        else:
130                g.ylabel('Frequency (Hz)')
131        g('set pm3d map')
132        g('set palette rgbformulae -25,-24,-32')
133        g('set cbtics 20')
134        #g('set colorbox horizontal')
135        g('set xrange [0.:%f]' % time[-1]) 
136        if options.log:
137                g('set log y')
138                g('set yrange [%f:%f]' % (max(10,options.minf),options.maxf))
139        else:
140                g('set yrange [%f:%f]' % (options.minf,options.maxf))
141        g.splot(Gnuplot.GridData(data,time,freq, binary=1))
142        #xorig += 1./todraw
143
144def downsample_audio(time,data,maxpoints=10000):
145  """ resample audio data to last only maxpoints """
146  import numarray
147  length = len(time)
148  downsample = length/maxpoints
149  if downsample == 0: downsample = 1
150  x = numarray.array(time).resize(length)[0:-1:downsample]
151  y = numarray.array(data).resize(length)[0:-1:downsample]
152  return x,y
153
154def make_audio_plot(time,data,maxpoints=10000):
155  """ create gnuplot plot from an audio file """
156  import Gnuplot, Gnuplot.funcutils
157  x,y = downsample_audio(time,data,maxpoints=maxpoints)
158  return Gnuplot.Data(x,y,with='lines')
159
160def make_audio_envelope(time,data,maxpoints=10000):
161  """ create gnuplot plot from an audio file """
162  import numarray
163  import Gnuplot, Gnuplot.funcutils
164  bufsize = 500
165  x = [i.mean() for i in numarray.array(time).resize(len(time)/bufsize,bufsize)] 
166  y = [i.mean() for i in numarray.array(data).resize(len(time)/bufsize,bufsize)] 
167  x,y = downsample_audio(x,y,maxpoints=maxpoints)
168  return Gnuplot.Data(x,y,with='lines')
169
170def gnuplot_addargs(parser):
171  """ add common gnuplot argument to OptParser object """
172  parser.add_option("-x","--xsize",
173          action="store", dest="xsize", default=1., 
174          type='float',help="define xsize for plot")
175  parser.add_option("-y","--ysize",
176          action="store", dest="ysize", default=1., 
177          type='float',help="define ysize for plot")
178  parser.add_option("--debug",
179          action="store_true", dest="debug", default=False, 
180          help="use gnuplot debug mode")
181  parser.add_option("--persist",
182          action="store_false", dest="persist", default=True, 
183          help="do not use gnuplot persistant mode")
184  parser.add_option("--lmargin",
185          action="store", dest="lmargin", default=None, 
186          type='int',help="define left margin for plot")
187  parser.add_option("--rmargin",
188          action="store", dest="rmargin", default=None, 
189          type='int',help="define right margin for plot")
190  parser.add_option("--bmargin",
191          action="store", dest="bmargin", default=None, 
192          type='int',help="define bottom margin for plot")
193  parser.add_option("--tmargin",
194          action="store", dest="tmargin", default=None, 
195          type='int',help="define top margin for plot")
196  parser.add_option("-O","--outplot",
197          action="store", dest="outplot", default=None, 
198          help="save plot to output.{ps,png}")
199
200def gnuplot_create(outplot='',extension='', options=None):
201  import Gnuplot
202  if options:
203    g = Gnuplot.Gnuplot(debug=options.debug, persist=options.persist)
204  else:
205    g = Gnuplot.Gnuplot(persist=1)
206  if not extension or not outplot: return g
207  if   extension == 'ps':  ext, extension = '.ps' , 'postscript'
208  elif extension == 'eps': ext, extension = '.eps' , 'postscript enhanced'
209  elif extension == 'epsc': ext, extension = '.eps' , 'postscript enhanced color'
210  elif extension == 'png': ext, extension = '.png', 'png'
211  elif extension == 'svg': ext, extension = '.svg', 'svg'
212  else: exit("ERR: unknown plot extension")
213  g('set terminal %s' % extension)
214  if options and options.lmargin: g('set lmargin %i' % options.lmargin)
215  if options and options.rmargin: g('set rmargin %i' % options.rmargin)
216  if options and options.bmargin: g('set bmargin %i' % options.bmargin)
217  if options and options.tmargin: g('set tmargin %i' % options.tmargin)
218  if outplot != "stdout":
219    g('set output \'%s%s\'' % (outplot,ext))
220  if options: g('set size %f,%f' % (options.xsize, options.ysize))
221  return g
Note: See TracBrowser for help on using the repository browser.