source: fact/tools/pyscripts/pyfact/plotters.py@ 13358

Last change on this file since 13358 was 13174, checked in by neise, 13 years ago
Plotter was not correctly plotting the grid, introduced the plotting of the grid into the __call__ now it works
  • Property svn:executable set to *
File size: 12.7 KB
Line 
1#!/usr/bin/python -tt
2#
3# Werner Lustermann, Dominik Neise
4# ETH Zurich, TU Dortmund
5#
6# plotter.py
7
8import numpy as np
9import matplotlib.pyplot as plt
10import os.path
11import sys
12
13# this class was formerly called Plotter in the depricated
14# module plotter.py
15class SimplePlotter(object):
16 """ simple x-y plot """
17 def __init__(self, name, x, style = 'b', xlabel='x', ylabel='y'):
18 """ initialize the object """
19
20 self.name = name
21 self.fig = plt.figure()
22 self.line, = plt.plot(x, style)
23
24 plt.title(name)
25 plt.xlabel(xlabel)
26 plt.ylabel(ylabel)
27 plt.grid(True)
28
29 def __call__(self, ydata):
30 """ set ydata of plot """
31 plt.figure(self.fig.number)
32 plt.ylim( np.min(ydata), np.max(ydata) )
33 self.line.set_ydata(ydata)
34 plt.draw()
35
36class Plotter(object):
37 """ simple x-y plot """
38 def __init__(self, name, x=None, style = '.:', xlabel='x', ylabel='y', ion=True, grid=True, fname=None):
39 """ initialize the object """
40
41 self.name = name
42 self.x = x
43 self.style = style
44 self.xlabel = xlabel
45 self.ylabel = ylabel
46
47 #not sure if this should go here
48 if ion:
49 plt.ion()
50
51 self.figure = plt.figure()
52 self.fig_id = self.figure.number
53
54 plt.grid(grid)
55 self.grid = grid
56 self.fname = fname
57
58 def __call__(self, ydata, label=None):
59 """ set ydata of plot """
60 style = self.style
61
62 # make acitve and clear
63 plt.figure(self.fig_id)
64 plt.cla()
65
66 # the following if else stuff is horrible,
67 # but I want all those possibilities, .... still working on it.
68
69 # check if 1Dim oder 2Dim
70 ydata = np.array(ydata)
71 if ydata.ndim ==1:
72 if self.x==None:
73 plt.plot(ydata, self.style, label=label)
74 else:
75 plt.plot(self.x, ydata, self.style, label=label)
76 else:
77 for i in range(len(ydata)):
78 if self.x==None:
79 if label:
80 plt.plot(ydata[i], style, label=label[i])
81 else:
82 plt.plot(ydata[i], style)
83 else:
84 if label:
85 plt.plot(self.x, ydata[i], style, label=label[i])
86 else:
87 plt.plot(self.x, ydata[i], style)
88 plt.title(self.name)
89 plt.xlabel(self.xlabel)
90 plt.ylabel(self.ylabel)
91 if label:
92 plt.legend()
93
94 if self.fname != None:
95 plt.savefig(self.fname)
96
97 plt.grid(self.grid)
98 plt.draw()
99
100
101class CamPlotter(object):
102 """ plotting data color-coded into FACT-camera """
103 def __init__(self, name, ion=True, grid=True, fname=None, map_file_path = '../map_dn.txt', vmin=None, vmax=None):
104 """ initialize the object """
105 path = os.path.abspath(__file__)
106 path = os.path.dirname(path)
107 map_file_path = os.path.join(path, map_file_path)
108 if not os.path.isfile(map_file_path):
109 print 'not able to find file:', map_file_path
110 sys.exit(-2)
111
112 self.name = name
113 if ion:
114 plt.ion()
115
116 chid, y,x,xe,ye,yh,xh,softid,hardid = np.loadtxt(map_file_path ,unpack=True)
117 self.xe = xe
118 self.ye = ye
119
120 self.H = (6,0,30./180.*3.1415926)
121
122 self.figure = plt.figure(figsize=(6, 6), dpi=80)
123 self.fig_id = self.figure.number
124
125 self.grid = grid
126 self.fname = fname
127 self.vmin = vmin
128 self.vmax = vmax
129
130 def __call__(self, data, mask=None):
131 # define some shortcuts
132 xe = self.xe
133 ye = self.ye
134 H = self.H
135 name = self.name
136 grid = self.grid
137 vmin = self.vmin
138 vmax = self.vmax
139
140 # get the figure, clean it, and set it up nicely.
141 # maybe cleaning is not necessary and takes long, but
142 # I've got no time to test it at the moment.
143 plt.figure(self.fig_id)
144 plt.clf()
145 self.ax = self.figure.add_subplot(111, aspect='equal')
146 self.ax.axis([-22,22,-22,22])
147 self.ax.set_title(name)
148 self.ax.grid(grid)
149
150 # throw data into numpy array for simplicity
151 data = np.array(data)
152
153 #handle masked case specially
154 if mask!= None:
155 if len(mask)==0:
156 return
157
158 elif mask.dtype == bool and data.ndim ==1 and len(mask)==1440:
159 length = mask.sum()
160 mask = np.where(mask)[0]
161 mxe = np.empty( length )
162 mye = np.empty( length )
163 mdata = np.empty( length )
164 for i,chid in enumerate(mask):
165 #print i , chid
166 mxe[i] = xe[chid]
167 mye[i] = ye[chid]
168 mdata[i] = data[chid]
169 #print 'mxe', mxe, 'len', len(mxe)
170 #print 'mye', mye, 'len', len(mye)
171 #print 'mxe', mdata, 'len', len(mdata)
172
173 self.ax.axis([-22,22,-22,22])
174 self.ax.set_title(name)
175 self.ax.grid(grid)
176 # the next line is a stupid hack
177 # I plot invisible pixels, so that the axes show look ok.
178 # this must be possible differently, but I don't know how...
179 self.ax.scatter(xe,ye,s=25,alpha=0,marker=H)
180
181 result = self.ax.scatter(mxe,mye,s=25,alpha=1.,
182 c=mdata, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
183 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
184 plt.draw()
185
186
187 elif mask.dtype == int and data.ndim ==1:
188 length = len(mask)
189 mxe = np.empty( length )
190 mye = np.empty( length )
191 mdata = np.empty( length )
192 for i,chid in enumerate(mask):
193 mxe[i] = xe[chid]
194 mye[i] = ye[chid]
195 mdata[i] = data[chid]
196
197 self.ax.axis([-22,22,-22,22])
198 self.ax.set_title(name)
199 self.ax.grid(grid)
200 # the next line is a stupid hack
201 # I plot invisible pixels, so that the axes show look ok.
202 # this must be possible differently, but I don't know how...
203 self.ax.scatter(xe,ye,s=25,alpha=0,marker=H)
204
205 result = self.ax.scatter(mxe,mye,s=25,alpha=1.,
206 c=mdata, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
207 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
208 plt.draw()
209
210 else:
211 print "there is a mask, but I don't know how to treat it!!!"
212 sys.exit(-1)
213 else: # i.e. when mask is None
214 # handle 1D and 2D case differently
215 if data.ndim == 1 and len(data)==1440:
216 result = self.ax.scatter(xe,ye,s=25,alpha=1,
217 c=data, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
218 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
219 plt.draw()
220
221 elif data.ndim == 2 and data.shape[0] == 2 and data.shape[1] <=1440:
222 # I assume the first row of data, contains the CHIDs
223 # and the 2nd row contains the actual data.
224 chids = data[0]
225 # check if there are double chids in chids
226 if len(chids)!=len(set(chids)):
227 print 'warning: there are doubled chids in input data',
228 print 'you might want to plot something else, but I plot it anyway...'
229 print chids
230 data = data[1]
231 # now I have to mask the xe, and ye vectors accordingly
232 mxe = np.empty( len(chids) )
233 mye = np.empty( len(chids) )
234 for i,chid in enumerate(chids):
235 mxe[i] = xe[chid]
236 mye[i] = ye[chid]
237
238 # check if I did it right
239 if len(mxe)!=len(data) or len(mye)!=len(data):
240 print 'the masking did not work:'
241 print 'len(mxe)', len(mxe)
242 print 'len(mye)', len(mye)
243 print 'len(data)', len(data)
244
245 self.ax.axis([-22,22,-22,22])
246 self.ax.set_title(name)
247 self.ax.grid(grid)
248 # the next line is a stupid hack
249 # I plot invisible pixels, so that the axes show look ok.
250 # this must be possible differently, but I don't know how...
251 self.ax.scatter(xe,ye,s=25,alpha=0,marker=H)
252
253 result = self.ax.scatter(mxe,mye,s=25,alpha=1.,
254 c=data, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
255 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
256 plt.draw()
257
258 else:
259 print 'CamPlotter call input data has bad format'
260 print 'data.ndim', data.ndim
261 print 'data.shape', data.shape
262 print 'data:----------------------------------'
263 print data
264
265
266
267
268class HistPlotter(object):
269
270 def __init__(self, name, bins, range, grid=True, ion=True):
271 """ initialize the object """
272 self.bins = bins
273 self.range = range
274 self.name = name
275 self.figure = plt.figure()
276 self.fig_id = self.figure.number
277 self.grid = grid
278
279 if ion:
280 plt.ion()
281
282 def __call__(self, ydata, label=None, log=False):
283 plt.figure(self.fig_id)
284 plt.cla()
285
286 bins = self.bins
287 range = self.range
288 grid = self.grid
289
290 ydata = np.array(ydata)
291
292 if ydata.ndim > 1:
293 ydata = ydata.flatten()
294 if label:
295 plt.hist(ydata, bins, range, label=label, log=log)
296 plt.legend()
297 else:
298 plt.hist(ydata, bins, range, log=log)
299
300 plt.title(self.name)
301
302 plt.draw()
303
304def _test_SimplePlotter():
305 """ test of maintaining two independant plotter instances """
306 plt.ion()
307
308 x = np.linspace(0., 10.)
309 plot1 = SimplePlotter('plot1', x, 'r')
310 print 'plot1.fig.number: ', plot1.fig.number
311 plot2 = SimplePlotter('plot2', x, 'g.')
312 print 'plot2.fig.number: ', plot2.fig.number
313
314 plot1(np.sin(x) * 7.)
315 plot2(x*x)
316
317 raw_input('next')
318
319 plot1(np.cos(x) * 3.)
320 plot2(x)
321
322 raw_input('next')
323
324
325def _test_Plotter():
326 """ test of maintaining two independant plotter instances
327 with different examples for init and call
328 """
329 x = np.linspace(0., 2*np.pi , 100)
330 plot1 = Plotter('plot1', x, 'r.:')
331 plot2 = Plotter('plot2')
332
333 y1 = np.sin(x) * 7
334 plot1(y1)
335
336 number_of_graphs_in_plot2 = 3
337 no = number_of_graphs_in_plot2 # short form
338
339 # this is where you do your analysis...
340 y2 = np.empty( (no, len(x)) ) # prepare some space
341 y2_labels = [] # prepare labels
342 for k in range(no):
343 y2[k] = np.sin( (k+1)*x )
344 y2_labels.append('sin(%d*x)' % (k+1) )
345
346 # plot the result of your analysis
347 plot2(y2, y2_labels)
348 raw_input('next') # do not forget this line, or your graph is lost
349
350 plot1(np.cos(x) * 3.)
351 plot2.name += ' without labels!!!' # changing titles 'on the fly' is possible
352 plot2(y2)
353 raw_input('next') # DO NOT forget
354
355
356def _test_CamPlotter():
357 """ test of CamPlotter """
358
359 c1 = np.array(range(20))
360 chids1 = np.empty( len(c1) , dtype=int)
361 for i in range(len(chids1)-2):
362 chids1[i] = np.random.randint(1440)
363 chids1[-1] = 15
364 chids1[-2] = 15
365
366 c2 = np.linspace(0., 1., num=1440)
367 plot1 = CamPlotter('plot1')
368 plot2 = CamPlotter('plot2')
369
370 plot1( (chids1,c1) )
371 plot2(c2)
372 raw_input('next')
373
374def _test_HistPlotter():
375 """ test of the HistPlotter """
376 plt.ion()
377
378 data = np.random.randn(1000)
379 hp = HistPlotter('test hist plotter',34, (-5,4))
380
381 hp(data, 'test-label')
382 raw_input('next')
383
384if __name__ == '__main__':
385 """ test the class """
386 print ' testing SimplePlotter'
387 _test_SimplePlotter()
388 print ' testing Plotter'
389 _test_Plotter()
390 print 'testing CamPlotter ... testing what happens if doubled IDs in mask'
391 _test_CamPlotter()
392 print 'testing basic HistPlotter functionality'
393 _test_HistPlotter()
394
Note: See TracBrowser for help on using the repository browser.