source: python/aubio/gnuplot.py @ 733c2f8

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

remove obsolete function and factorise gnuplot init
remove obsolete function and factorise gnuplot init

  • Property mode set to 100644
File size: 7.7 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
24__notesheight = 0.25
25
26
27def audio_to_array(filename):
28        import aubio.aubioclass
29        import numarray
30        hopsize  = 2048
31        filei    = aubio.aubioclass.sndfile(filename)
32        framestep = 1/(filei.samplerate()+0.)
33        channels = filei.channels()
34        myvec    = aubio.aubioclass.fvec(hopsize,channels)
35        data = []
36        readsize = hopsize
37        while (readsize==hopsize):
38                readsize = filei.read(hopsize,myvec)
39                #for i in range(channels):
40                i = 0
41                curpos = 0
42                while (curpos < readsize):
43                        data.append(myvec.get(curpos,i))
44                        curpos+=1
45        time = numarray.arange(len(data))*framestep
46        return time,data
47
48def plot_audio(filenames, fileout=None, start=0, end=None, noaxis=None):
49        g = gnuplot_init(fileout)
50        d = []
51        todraw = len(filenames)
52        xorig = 0.
53        xsize = 1./todraw
54        g.gnuplot('set multiplot;')
55        while (len(filenames)):
56                time,data = audio_to_array(filenames.pop(0))
57                d.append(make_audio_plot(time,data))
58                if not noaxis and todraw==1:
59                        g.xlabel('Time (s)')
60                        g.ylabel('Amplitude')
61                g.gnuplot('set size %f,1.;' % (xsize) )
62                g.gnuplot('set origin %f,0.;' % (xorig) )
63                g.gnuplot('set style data lines; \
64                        set yrange [-1.:1.]; \
65                        set xrange [0:%f]' % time[-1]) 
66                g.plot(d.pop(0))
67                xorig += 1./todraw
68        g.gnuplot('unset multiplot;')
69
70def make_audio_plot(time,data,maxpoints=10000):
71        """ create gnuplot plot from an audio file """
72        import numarray
73        import Gnuplot, Gnuplot.funcutils
74        length = len(time)
75        downsample = length/maxpoints
76        if downsample == 0: downsample = 1
77        x = numarray.array(time).resize(length)[0:-1:downsample]
78        y = numarray.array(data).resize(length)[0:-1:downsample]
79        return Gnuplot.Data(x,y,with='lines')
80
81
82def plot_onsets(filename, onsets, ofunc, samplerate=44100., hopsize=512, outplot=None):
83        import Gnuplot, Gnuplot.funcutils
84        import aubio.txtfile
85        import os.path
86        import numarray
87        import re
88        from aubio.onsetcompare import onset_roc
89
90        d,d2 = [],[]
91        maxofunc = 0
92        for i in range(len(onsets)):
93                if len(onsets[i]) == 0: onsets[i] = [0.];
94
95                # onset detection function
96                downtime = (hopsize/samplerate)*numarray.arange(len(ofunc[i]))
97                d.append(Gnuplot.Data(downtime,ofunc[i],with='lines'))
98                maxofunc = max(max(ofunc[i]), maxofunc)
99
100        for i in range(len(onsets)):
101                # detected onsets
102                x1 = (hopsize/samplerate)*numarray.array(onsets[i])
103                y1 = maxofunc*numarray.ones(len(onsets[i]))
104                d.append(Gnuplot.Data(x1,y1,with='impulses'))
105                d2.append(Gnuplot.Data(x1,-y1,with='impulses'))
106
107        # check if datafile exists truth
108        datafile = filename.replace('.wav','.txt')
109        if not os.path.isfile(datafile):
110                title = "truth file not found"
111                t = Gnuplot.Data(0,0,with='impulses') 
112        else:
113                t_onsets = aubio.txtfile.read_datafile(datafile)
114                y2 = maxofunc*numarray.ones(len(t_onsets))
115                x2 = numarray.array(t_onsets).resize(len(t_onsets))
116                d2.append(Gnuplot.Data(x2,y2,with='impulses'))
117               
118                tol = 0.050 
119
120                orig, missed, merged, expc, bad, doubled = \
121                        onset_roc(x2,x1,tol)
122                title = "GD %2.3f%% FP %2.3f%%" % \
123                        ((100*float(orig-missed-merged)/(orig)),
124                         (100*float(bad+doubled)/(orig)))
125
126        # audio data
127        time,data = audio_to_array(filename)
128        d2.append(make_audio_plot(time,data))
129
130        # prepare the plot
131        g = gnuplot_init(outplot)
132
133        g('set title \'%s %s\'' % (re.sub('.*/','',filename),title))
134
135        g('set multiplot')
136
137        # hack to align left axis
138        g('set lmargin 15')
139
140        # plot waveform and onsets
141        g('set size 1,0.3')
142        g('set origin 0,0.7')
143        g('set xrange [0:%f]' % max(time)) 
144        g('set yrange [-1:1]') 
145        g.ylabel('amplitude')
146        g.plot(*d2)
147       
148        g('unset title')
149
150        # plot onset detection function
151        g('set size 1,0.7')
152        g('set origin 0,0')
153        g('set xrange [0:%f]' % (hopsize/samplerate*len(ofunc[0])))
154        g('set yrange [0:%f]' % (maxofunc*1.01))
155        g.xlabel('time')
156        g.ylabel('onset detection value')
157        g.plot(*d)
158
159        g('unset multiplot')
160
161
162def plot_pitch(filename, pitch, samplerate=44100., hopsize=512, outplot=None):
163        import aubio.txtfile
164        import os.path
165        import numarray
166        import Gnuplot
167        import re
168
169        d = []
170        maxpitch = 100
171        for i in range(len(pitch)):
172                downtime = (hopsize/samplerate)*numarray.arange(len(pitch[i]))
173                d.append(Gnuplot.Data(downtime,pitch[i],with='lines',
174                        title=('%d' % i)))
175                maxpitch = max(maxpitch,max(pitch[i][:])*1.1)
176
177        # check if ground truth exists
178        datafile = filename.replace('.wav','.txt')
179        if not os.path.isfile(datafile):
180                title = "truth file not found"
181                t = Gnuplot.Data(0,0,with='impulses') 
182        else:
183                title = "truth file plotting not implemented yet"
184                values = aubio.txtfile.read_datafile(datafile)
185                if (len(datafile[0])) > 1:
186                        time, pitch = [], []
187                        for i in range(len(values)):
188                                time.append(values[i][0])
189                                pitch.append(values[i][1])
190                        d.append(Gnuplot.Data(time,pitch,with='lines',
191                                title='ground truth'))
192               
193        # audio data
194        time,data = audio_to_array(filename)
195        f = make_audio_plot(time,data)
196
197        g = gnuplot_init(outplot)
198        g('set title \'%s %s\'' % (re.sub('.*/','',filename),title))
199        g('set multiplot')
200        # hack to align left axis
201        g('set lmargin 15')
202        # plot waveform and onsets
203        g('set size 1,0.3')
204        g('set origin 0,0.7')
205        g('set xrange [0:%f]' % max(time)) 
206        g('set yrange [-1:1]') 
207        g.ylabel('amplitude')
208        g.plot(f)
209        g('unset title')
210        # plot onset detection function
211        g('set size 1,0.7')
212        g('set origin 0,0')
213        g('set xrange [0:%f]' % max(time))
214        g('set yrange [40:%f]' % maxpitch) 
215        g('set key right top')
216        g.xlabel('time')
217        g.ylabel('frequency (Hz)')
218        g.plot(*d)
219        g('unset multiplot')
220
221def gnuplot_init(outplot,debug=0,persist=1):
222        import Gnuplot
223        # prepare the plot
224        g = Gnuplot.Gnuplot(debug=debug, persist=persist)
225        if outplot == 'stdout':
226                g("set terminal png fontfile 'p052023l.pfb'")
227                #g('set output \'%s\'' % outplot)
228        elif outplot:
229                extension = outplot.split('.')[-1]
230                if extension == 'ps': extension = 'postscript'
231                g('set terminal %s' % extension)
232                g('set output \'%s\'' % outplot)
233        return g
Note: See TracBrowser for help on using the repository browser.