source: fact/tools/pyscripts/sandbox/vogler/plotters.py@ 17548

Last change on this file since 17548 was 14173, checked in by vogler, 13 years ago
inital filling of my sandbox
  • 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,ye,xe,yh,xh,softid,hardid = np.loadtxt(map_file_path ,unpack=True)
117
118 self.xe = xe
119 self.ye = ye
120
121 self.H = (6,0,30./180.*3.1415926)
122
123 self.figure = plt.figure(figsize=(6, 6), dpi=80)
124 self.fig_id = self.figure.number
125
126 self.grid = grid
127 self.fname = fname
128 self.vmin = vmin
129 self.vmax = vmax
130
131 def __call__(self, data, mask=None):
132 # define some shortcuts
133 xe = self.xe
134 ye = self.ye
135 H = self.H
136 name = self.name
137 grid = self.grid
138 vmin = self.vmin
139 vmax = self.vmax
140
141 # get the figure, clean it, and set it up nicely.
142 # maybe cleaning is not necessary and takes long, but
143 # I've got no time to test it at the moment.
144 plt.figure(self.fig_id)
145 plt.clf()
146 self.ax = self.figure.add_subplot(111, aspect='equal')
147 self.ax.axis([-22,22,-22,22])
148 self.ax.set_title(name)
149 self.ax.grid(grid)
150
151 # throw data into numpy array for simplicity
152 data = np.array(data)
153
154 #handle masked case specially
155 if mask!= None:
156 if len(mask)==0:
157 return
158
159 elif mask.dtype == bool and data.ndim ==1 and len(mask)==1440:
160 length = mask.sum()
161 mask = np.where(mask)[0]
162 mxe = np.empty( length )
163 mye = np.empty( length )
164 mdata = np.empty( length )
165 for i,chid in enumerate(mask):
166 #print i , chid
167 mxe[i] = xe[chid]
168 mye[i] = ye[chid]
169 mdata[i] = data[chid]
170 #print 'mxe', mxe, 'len', len(mxe)
171 #print 'mye', mye, 'len', len(mye)
172 #print 'mxe', mdata, 'len', len(mdata)
173
174 self.ax.axis([-22,22,-22,22])
175 self.ax.set_title(name)
176 self.ax.grid(grid)
177 # the next line is a stupid hack
178 # I plot invisible pixels, so that the axes show look ok.
179 # this must be possible differently, but I don't know how...
180 self.ax.scatter(xe,ye,s=25,alpha=0,marker=H)
181
182 result = self.ax.scatter(mxe,mye,s=25,alpha=1.,
183 c=mdata, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
184 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
185 plt.draw()
186
187
188 elif mask.dtype == int and data.ndim ==1:
189 length = len(mask)
190 mxe = np.empty( length )
191 mye = np.empty( length )
192 mdata = np.empty( length )
193 for i,chid in enumerate(mask):
194 mxe[i] = xe[chid]
195 mye[i] = ye[chid]
196 mdata[i] = data[chid]
197
198 self.ax.axis([-22,22,-22,22])
199 self.ax.set_title(name)
200 self.ax.grid(grid)
201 # the next line is a stupid hack
202 # I plot invisible pixels, so that the axes look ok.
203 # this must be possible differently, but I don't know how...
204 self.ax.scatter(xe,ye,s=25,alpha=0,marker=H)
205
206 result = self.ax.scatter(mxe,mye,s=25,alpha=1.,
207 c=mdata, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
208 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
209 plt.draw()
210
211 else:
212 print "there is a mask, but I don't know how to treat it!!!"
213 sys.exit(-1)
214 else: # i.e. when mask is None
215 # handle 1D and 2D case differently
216 if data.ndim == 1 and len(data)==1440:
217 result = self.ax.scatter(xe,ye,s=25,alpha=1,
218 c=data, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
219 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
220 plt.draw()
221
222 elif data.ndim == 2 and data.shape[0] == 2 and data.shape[1] <=1440:
223 # I assume the first row of data, contains the CHIDs
224 # and the 2nd row contains the actual data.
225 chids = data[0]
226 # check if there are double chids in chids
227 if len(chids)!=len(set(chids)):
228 print 'warning: there are doubled chids in input data',
229 print 'you might want to plot something else, but I plot it anyway...'
230 print chids
231 data = data[1]
232 # now I have to mask the xe, and ye vectors accordingly
233 mxe = np.empty( len(chids) )
234 mye = np.empty( len(chids) )
235 for i,chid in enumerate(chids):
236 mxe[i] = xe[chid]
237 mye[i] = ye[chid]
238
239 # check if I did it right
240 if len(mxe)!=len(data) or len(mye)!=len(data):
241 print 'the masking did not work:'
242 print 'len(mxe)', len(mxe)
243 print 'len(mye)', len(mye)
244 print 'len(data)', len(data)
245
246 self.ax.axis([-22,22,-22,22])
247 self.ax.set_title(name)
248 self.ax.grid(grid)
249 # the next line is a stupid hack
250 # I plot invisible pixels, so that the axes show look ok.
251 # this must be possible differently, but I don't know how...
252 self.ax.scatter(xe,ye,s=25,alpha=0,marker=H)
253
254 result = self.ax.scatter(mxe,mye,s=25,alpha=1.,
255 c=data, marker=H, linewidths=0., vmin=vmin, vmax=vmax)
256 self.figure.colorbar( result, shrink=0.8, pad=-0.04 )
257 plt.draw()
258
259 else:
260 print 'CamPlotter call input data has bad format'
261 print 'data.ndim', data.ndim
262 print 'data.shape', data.shape
263 print 'data:----------------------------------'
264 print data
265
266
267
268
269class HistPlotter(object):
270
271 def __init__(self, name, bins, range, grid=True, ion=True):
272 """ initialize the object """
273 self.bins = bins
274 self.range = range
275 self.name = name
276 self.figure = plt.figure()
277 self.fig_id = self.figure.number
278 self.grid = grid
279
280 if ion:
281 plt.ion()
282
283 def __call__(self, ydata, label=None, log=False):
284 plt.figure(self.fig_id)
285 plt.cla()
286
287 bins = self.bins
288 range = self.range
289 grid = self.grid
290
291 ydata = np.array(ydata)
292
293 if ydata.ndim > 1:
294 ydata = ydata.flatten()
295 if label:
296 plt.hist(ydata, bins, range, label=label, log=log)
297 plt.legend()
298 else:
299 plt.hist(ydata, bins, range, log=log)
300
301 plt.title(self.name)
302
303 plt.draw()
304
305def _test_SimplePlotter():
306 """ test of maintaining two independant plotter instances """
307 plt.ion()
308
309 x = np.linspace(0., 10.)
310 plot1 = SimplePlotter('plot1', x, 'r')
311 print 'plot1.fig.number: ', plot1.fig.number
312 plot2 = SimplePlotter('plot2', x, 'g.')
313 print 'plot2.fig.number: ', plot2.fig.number
314
315 plot1(np.sin(x) * 7.)
316 plot2(x*x)
317
318 raw_input('next')
319
320 plot1(np.cos(x) * 3.)
321 plot2(x)
322
323 raw_input('next')
324
325
326def _test_Plotter():
327 """ test of maintaining two independant plotter instances
328 with different examples for init and call
329 """
330 x = np.linspace(0., 2*np.pi , 100)
331 plot1 = Plotter('plot1', x, 'r.:')
332 plot2 = Plotter('plot2')
333
334 y1 = np.sin(x) * 7
335 plot1(y1)
336
337 number_of_graphs_in_plot2 = 3
338 no = number_of_graphs_in_plot2 # short form
339
340 # this is where you do your analysis...
341 y2 = np.empty( (no, len(x)) ) # prepare some space
342 y2_labels = [] # prepare labels
343 for k in range(no):
344 y2[k] = np.sin( (k+1)*x )
345 y2_labels.append('sin(%d*x)' % (k+1) )
346
347 # plot the result of your analysis
348 plot2(y2, y2_labels)
349 raw_input('next') # do not forget this line, or your graph is lost
350
351 plot1(np.cos(x) * 3.)
352 plot2.name += ' without labels!!!' # changing titles 'on the fly' is possible
353 plot2(y2)
354 raw_input('next') # DO NOT forget
355
356
357def _test_CamPlotter():
358 """ test of CamPlotter """
359
360 c1 = np.array(range(20))
361 chids1 = np.empty( len(c1) , dtype=int)
362 for i in range(len(chids1)-2):
363 chids1[i] = np.random.randint(1440)
364 chids1[-1] = 15
365 chids1[-2] = 15
366
367 c2 = np.linspace(0., 1., num=1440)
368 plot1 = CamPlotter('plot1')
369 plot2 = CamPlotter('plot2')
370
371 plot1( (chids1,c1) )
372 plot2(c2)
373 raw_input('next')
374
375def _test_HistPlotter():
376 """ test of the HistPlotter """
377 plt.ion()
378
379 data = np.random.randn(1000)
380 hp = HistPlotter('test hist plotter',34, (-5,4))
381
382 hp(data, 'test-label')
383 raw_input('next')
384
385if __name__ == '__main__':
386 """ test the class """
387 print ' testing SimplePlotter'
388 _test_SimplePlotter()
389 print ' testing Plotter'
390 _test_Plotter()
391 print 'testing CamPlotter ... testing what happens if doubled IDs in mask'
392 _test_CamPlotter()
393 print 'testing basic HistPlotter functionality'
394 _test_HistPlotter()
395
Note: See TracBrowser for help on using the repository browser.