1 | import os
|
---|
2 | import matplotlib, numpy
|
---|
3 | from matplotlib.patches import Rectangle
|
---|
4 | from asap.parameters import rcParams
|
---|
5 | from asap.logging import asaplog, asaplog_post_dec
|
---|
6 | from asap import scantable
|
---|
7 | from asap._asap import stmath
|
---|
8 |
|
---|
9 | ###########################################
|
---|
10 | ## Add CASA custom Flag toolbar ##
|
---|
11 | ###########################################
|
---|
12 | class CustomFlagToolbarCommon:
|
---|
13 | def __init__(self,parent):
|
---|
14 | self.plotter=parent
|
---|
15 | #self.figmgr=self.plotter._plotter.figmgr
|
---|
16 | self._selregions = {}
|
---|
17 | self._selpanels = []
|
---|
18 | self._polygons = []
|
---|
19 | self._thisregion = None
|
---|
20 | self.xdataold=None
|
---|
21 |
|
---|
22 | ### select the nearest spectrum in pick radius
|
---|
23 | ### and display spectral value on the toolbar.
|
---|
24 | def _select_spectrum(self,event):
|
---|
25 | # Do not fire event when in zooming/panning mode
|
---|
26 | mode = self.figmgr.toolbar.mode
|
---|
27 | if not mode == '':
|
---|
28 | return
|
---|
29 | # When selected point is out of panels
|
---|
30 | if event.inaxes == None:
|
---|
31 | return
|
---|
32 | # If not left button
|
---|
33 | if event.button != 1:
|
---|
34 | return
|
---|
35 |
|
---|
36 | xclick = event.xdata
|
---|
37 | yclick = event.ydata
|
---|
38 | dist2 = 1000.
|
---|
39 | pickline = None
|
---|
40 | # If the pannel has picable objects
|
---|
41 | pflag = False
|
---|
42 | for lin in event.inaxes.lines:
|
---|
43 | if not lin.pickable():
|
---|
44 | continue
|
---|
45 | pflag = True
|
---|
46 | flag,pind = lin.contains(event)
|
---|
47 | if not flag:
|
---|
48 | continue
|
---|
49 | # Get nearest point
|
---|
50 | inds = pind['ind']
|
---|
51 | xlin = lin.get_xdata()
|
---|
52 | ylin = lin.get_ydata()
|
---|
53 | for i in inds:
|
---|
54 | d2=(xlin[i]-xclick)**2+(ylin[i]-yclick)**2
|
---|
55 | if dist2 >= d2:
|
---|
56 | dist2 = d2
|
---|
57 | pickline = lin
|
---|
58 | # No pickcable line in the pannel
|
---|
59 | if not pflag:
|
---|
60 | return
|
---|
61 | # Pickable but too far from mouse position
|
---|
62 | elif pickline is None:
|
---|
63 | picked = 'No line selected.'
|
---|
64 | self.figmgr.toolbar.set_message(picked)
|
---|
65 | return
|
---|
66 | del pind, inds, xlin, ylin
|
---|
67 | # Spectra are Picked
|
---|
68 | theplot = self.plotter._plotter
|
---|
69 | thetoolbar = self.figmgr.toolbar
|
---|
70 | thecanvas = self.figmgr.canvas
|
---|
71 | # Disconnect the default motion notify event
|
---|
72 | # Notice! the other buttons are also diabled!!!
|
---|
73 | thecanvas.mpl_disconnect(thetoolbar._idDrag)
|
---|
74 | # Get picked spectrum
|
---|
75 | xdata = pickline.get_xdata()
|
---|
76 | ydata = pickline.get_ydata()
|
---|
77 | titl = pickline.get_label()
|
---|
78 | titp = event.inaxes.title.get_text()
|
---|
79 | panel0 = event.inaxes
|
---|
80 | picked = "Selected: '"+titl+"' in panel '"+titp+"'."
|
---|
81 | thetoolbar.set_message(picked)
|
---|
82 | # Generate a navigation window
|
---|
83 | #naviwin=Navigationwindow(titp,titl)
|
---|
84 | #------------------------------------------------------#
|
---|
85 | # Show spectrum data at mouse position
|
---|
86 | def spec_data(event):
|
---|
87 | # Getting spectrum data of neiboring point
|
---|
88 | xclick = event.xdata
|
---|
89 | if event.inaxes != panel0:
|
---|
90 | return
|
---|
91 | ipoint = len(xdata)-1
|
---|
92 | for i in range(len(xdata)-1):
|
---|
93 | xl = xclick-xdata[i]
|
---|
94 | xr = xclick-xdata[i+1]
|
---|
95 | if xl*xr <= 0.:
|
---|
96 | ipoint = i
|
---|
97 | break
|
---|
98 | # Output spectral value on the navigation window
|
---|
99 | posi = '[ %s, %s ]: x = %.2f value = %.2f'\
|
---|
100 | %(titl,titp,xdata[ipoint],ydata[ipoint])
|
---|
101 | #naviwin.posi.set(posi)
|
---|
102 | thetoolbar.set_message(posi)
|
---|
103 | #------------------------------------------------------#
|
---|
104 | # Disconnect from mouse events
|
---|
105 | def discon(event):
|
---|
106 | #naviwin.window.destroy()
|
---|
107 | theplot.register('motion_notify',None)
|
---|
108 | # Re-activate the default motion_notify_event
|
---|
109 | thetoolbar._idDrag=thecanvas.mpl_connect('motion_notify_event',
|
---|
110 | thetoolbar.mouse_move)
|
---|
111 | theplot.register('button_release',None)
|
---|
112 | return
|
---|
113 | #------------------------------------------------------#
|
---|
114 | # Show data value along with mouse movement
|
---|
115 | theplot.register('motion_notify',spec_data)
|
---|
116 | # Finish events when mouse button is released
|
---|
117 | theplot.register('button_release',discon)
|
---|
118 |
|
---|
119 |
|
---|
120 | ### Notation
|
---|
121 | def _mod_note(self,event):
|
---|
122 | # Do not fire event when in zooming/panning mode
|
---|
123 | if not self.figmgr.toolbar.mode == '':
|
---|
124 | return
|
---|
125 | if event.button == 1:
|
---|
126 | self.notewin.load_textwindow(event)
|
---|
127 | elif event.button == 3 and self._note_picked(event):
|
---|
128 | self.notewin.load_modmenu(event)
|
---|
129 | return
|
---|
130 |
|
---|
131 | def _note_picked(self,event):
|
---|
132 | # just briefly check if any texts are picked
|
---|
133 | for textobj in self.canvas.figure.texts:
|
---|
134 | if textobj.contains(event)[0]:
|
---|
135 | return True
|
---|
136 | for ax in self.canvas.figure.axes:
|
---|
137 | for textobj in ax.texts:
|
---|
138 | if textobj.contains(event)[0]:
|
---|
139 | return True
|
---|
140 | return False
|
---|
141 |
|
---|
142 | ### Region/Panel selection & oparations
|
---|
143 | ### add regions to selections
|
---|
144 | @asaplog_post_dec
|
---|
145 | def _add_region(self,event):
|
---|
146 | if not self.figmgr.toolbar.mode == '':
|
---|
147 | return
|
---|
148 | if event.button != 1 or event.inaxes == None:
|
---|
149 | return
|
---|
150 | # this row resolution assumes row panelling
|
---|
151 | irow = int(self._getrownum(event.inaxes))
|
---|
152 | if irow in self._selpanels:
|
---|
153 | msg = "The whole spectrum is already selected"
|
---|
154 | asaplog.post()
|
---|
155 | asaplog.push(msg)
|
---|
156 | asaplog.post('WARN')
|
---|
157 | return
|
---|
158 | self._thisregion = {'axes': event.inaxes,'xs': event.x,
|
---|
159 | 'worldx': [event.xdata,event.xdata]}
|
---|
160 | self.plotter._plotter.register('button_press',None)
|
---|
161 | self.plotter._plotter.register('motion_notify', self._xspan_draw)
|
---|
162 | self.plotter._plotter.register('button_press', self._xspan_end)
|
---|
163 |
|
---|
164 | def _xspan_draw(self,event):
|
---|
165 | if event.inaxes == self._thisregion['axes']:
|
---|
166 | xnow = event.x
|
---|
167 | self.xdataold = xnow
|
---|
168 | else:
|
---|
169 | xnow = self.xdataold
|
---|
170 | try: self.lastspan
|
---|
171 | except AttributeError: pass
|
---|
172 | else: self._remove_span(self.lastspan)
|
---|
173 |
|
---|
174 | #self.lastspan = self._draw_span(self._thisregion['axes'],self._thisregion['xs'],xnow,fill="#555555",stipple="gray50")
|
---|
175 | self.lastspan = self._draw_span(self._thisregion['axes'],self._thisregion['xs'],xnow,fill="")
|
---|
176 | del xnow
|
---|
177 |
|
---|
178 | def _draw_span(self,axes,x0,x1,**kwargs):
|
---|
179 | pass
|
---|
180 |
|
---|
181 | def _remove_span(self,span):
|
---|
182 | pass
|
---|
183 |
|
---|
184 | @asaplog_post_dec
|
---|
185 | def _xspan_end(self,event):
|
---|
186 | if not self.figmgr.toolbar.mode == '':
|
---|
187 | return
|
---|
188 | if event.button != 1:
|
---|
189 | return
|
---|
190 |
|
---|
191 | try: self.lastspan
|
---|
192 | except AttributeError: pass
|
---|
193 | else:
|
---|
194 | self._remove_span(self.lastspan)
|
---|
195 | del self.lastspan
|
---|
196 | if event.inaxes == self._thisregion['axes']:
|
---|
197 | xdataend = event.xdata
|
---|
198 | else:
|
---|
199 | xdataend=self.xdataold
|
---|
200 |
|
---|
201 | self._thisregion['worldx'][1] = xdataend
|
---|
202 | lregion = self._thisregion['worldx']
|
---|
203 | pregion = self._thisregion['axes'].axvspan(lregion[0],lregion[1],
|
---|
204 | facecolor='0.7')
|
---|
205 | self.plotter._plotter.canvas.draw()
|
---|
206 | self._polygons.append(pregion)
|
---|
207 | srow = self._getrownum(self._thisregion['axes'])
|
---|
208 | irow = int(srow)
|
---|
209 | if not self._selregions.has_key(srow):
|
---|
210 | self._selregions[srow] = []
|
---|
211 | self._selregions[srow].append(lregion)
|
---|
212 | del lregion, pregion, xdataend
|
---|
213 | sout = "selected region: "+str(self._thisregion['worldx'])+\
|
---|
214 | "(@row "+str(self._getrownum(self._thisregion['axes']))+")"
|
---|
215 | asaplog.push(sout)
|
---|
216 |
|
---|
217 | # release event
|
---|
218 | self.plotter._plotter.register('button_press',None)
|
---|
219 | self.plotter._plotter.register('motion_notify',None)
|
---|
220 | # Clear up region selection
|
---|
221 | self._thisregion = None
|
---|
222 | self.xdataold = None
|
---|
223 | # finally recover region selection event
|
---|
224 | self.plotter._plotter.register('button_press',self._add_region)
|
---|
225 |
|
---|
226 | ### add panels to selections
|
---|
227 | @asaplog_post_dec
|
---|
228 | def _add_panel(self,event):
|
---|
229 | if not self.figmgr.toolbar.mode == '':
|
---|
230 | return
|
---|
231 | if event.button != 1 or event.inaxes == None:
|
---|
232 | return
|
---|
233 | selax = event.inaxes
|
---|
234 | # this row resolution assumes row panelling
|
---|
235 | srow = self._getrownum(selax)
|
---|
236 | irow = int(srow)
|
---|
237 | if srow:
|
---|
238 | self._selpanels.append(irow)
|
---|
239 | shadow = Rectangle((0,0),1,1,facecolor='0.7',transform=selax.transAxes,visible=True)
|
---|
240 | self._polygons.append(selax.add_patch(shadow))
|
---|
241 | #self.plotter._plotter.show(False)
|
---|
242 | self.plotter._plotter.canvas.draw()
|
---|
243 | asaplog.push("row "+str(irow)+" is selected")
|
---|
244 | ## check for region selection of the spectra and overwrite it.
|
---|
245 | ##!!!! currently disabled for consistency with flag tools !!!!
|
---|
246 | #if self._selregions.has_key(srow):
|
---|
247 | # self._selregions.pop(srow)
|
---|
248 | # msg = "The whole spectrum is selected for row="+srow+". Region selection will be overwritten."
|
---|
249 | # asaplog.push(msg)
|
---|
250 |
|
---|
251 | def _getrownum(self,axis):
|
---|
252 | ### returns the row number of selected spectrum as a string ###
|
---|
253 | plabel = axis.get_title()
|
---|
254 | if plabel.startswith("row "):
|
---|
255 | return plabel.strip("row ")
|
---|
256 | return None
|
---|
257 |
|
---|
258 | def _any_selection(self):
|
---|
259 | ### returns if users have selected any spectrum or region ###
|
---|
260 | if len(self._selpanels) or len(self._selregions):
|
---|
261 | return True
|
---|
262 | return False
|
---|
263 |
|
---|
264 | def _plot_selections(self,regions=None,panels=None):
|
---|
265 | ### mark panels/spectra selections in the page
|
---|
266 | if not self._any_selection() and not (regions or panels):
|
---|
267 | return
|
---|
268 | regions = regions or self._selregions.copy() or {}
|
---|
269 | panels = panels or self._selpanels or []
|
---|
270 | if not isinstance(regions,dict):
|
---|
271 | asaplog.post()
|
---|
272 | asaplog.push("Invalid region specification")
|
---|
273 | asaplog.post('ERROR')
|
---|
274 | if not isinstance(panels,list):
|
---|
275 | asaplog.post()
|
---|
276 | asaplog.push("Invalid panel specification")
|
---|
277 | asaplog.post('ERROR')
|
---|
278 | strow = self._getrownum(self.plotter._plotter.subplots[0]['axes'])
|
---|
279 | enrow = self._getrownum(self.plotter._plotter.subplots[-1]['axes'])
|
---|
280 | for irow in range(int(strow),int(enrow)+1):
|
---|
281 | if regions.has_key(str(irow)):
|
---|
282 | ax = self.plotter._plotter.subplots[irow - int(strow)]['axes']
|
---|
283 | mlist = regions.pop(str(irow))
|
---|
284 | for i in range(len(mlist)):
|
---|
285 | self._polygons.append(ax.axvspan(mlist[i][0],mlist[i][1],
|
---|
286 | facecolor='0.7'))
|
---|
287 | del ax,mlist
|
---|
288 | if irow in panels:
|
---|
289 | ax = self.plotter._plotter.subplots[irow - int(strow)]['axes']
|
---|
290 | shadow = Rectangle((0,0),1,1,facecolor='0.7',
|
---|
291 | transform=ax.transAxes,visible=True)
|
---|
292 | self._polygons.append(ax.add_patch(shadow))
|
---|
293 | del ax,shadow
|
---|
294 | self.plotter._plotter.canvas.draw()
|
---|
295 | del regions,panels,strow,enrow
|
---|
296 |
|
---|
297 | def _clear_selection_plot(self, refresh=True):
|
---|
298 | ### clear up polygons which mark selected spectra and regions ###
|
---|
299 | if len(self._polygons) > 0:
|
---|
300 | for shadow in self._polygons:
|
---|
301 | shadow.remove()
|
---|
302 | if refresh: self.plotter._plotter.canvas.draw()
|
---|
303 | self._polygons = []
|
---|
304 |
|
---|
305 | def _clearup_selections(self, refresh=True):
|
---|
306 | # clear-up selection and polygons
|
---|
307 | self._selpanels = []
|
---|
308 | self._selregions = {}
|
---|
309 | self._clear_selection_plot(refresh=refresh)
|
---|
310 |
|
---|
311 | ### clear up selections
|
---|
312 | def cancel_select(self):
|
---|
313 | self.figmgr.toolbar.set_message('selections canceled')
|
---|
314 | # clear-up selection and polygons
|
---|
315 | self._clearup_selections(refresh=True)
|
---|
316 |
|
---|
317 | ### flag selected spectra/regions
|
---|
318 | @asaplog_post_dec
|
---|
319 | def flag(self):
|
---|
320 | if not self._any_selection():
|
---|
321 | msg = "No selection to be Flagged"
|
---|
322 | asaplog.post()
|
---|
323 | asaplog.push(msg)
|
---|
324 | asaplog.post('WARN')
|
---|
325 | return
|
---|
326 | self._pause_buttons(operation="start",msg="Flagging data...")
|
---|
327 | self._flag_operation(rows=self._selpanels,
|
---|
328 | regions=self._selregions,unflag=False)
|
---|
329 | sout = "Flagged:\n"
|
---|
330 | sout += " rows = "+str(self._selpanels)+"\n"
|
---|
331 | sout += " regions: "+str(self._selregions)
|
---|
332 | asaplog.push(sout)
|
---|
333 | del sout
|
---|
334 | self.plotter._ismodified = True
|
---|
335 | self._clearup_selections(refresh=False)
|
---|
336 | self._plot_page(pagemode="current")
|
---|
337 | self._pause_buttons(operation="end")
|
---|
338 |
|
---|
339 | ### unflag selected spectra/regions
|
---|
340 | @asaplog_post_dec
|
---|
341 | def unflag(self):
|
---|
342 | if not self._any_selection():
|
---|
343 | msg = "No selection to be Flagged"
|
---|
344 | asaplog.push(msg)
|
---|
345 | asaplog.post('WARN')
|
---|
346 | return
|
---|
347 | self._pause_buttons(operation="start",msg="Unflagging data...")
|
---|
348 | self._flag_operation(rows=self._selpanels,
|
---|
349 | regions=self._selregions,unflag=True)
|
---|
350 | sout = "Unflagged:\n"
|
---|
351 | sout += " rows = "+str(self._selpanels)+"\n"
|
---|
352 | sout += " regions: "+str(self._selregions)
|
---|
353 | asaplog.push(sout)
|
---|
354 | del sout
|
---|
355 | self.plotter._ismodified = True
|
---|
356 | self._clearup_selections(refresh=False)
|
---|
357 | self._plot_page(pagemode="current")
|
---|
358 | self._pause_buttons(operation="end")
|
---|
359 |
|
---|
360 | ### actual flag operation
|
---|
361 | @asaplog_post_dec
|
---|
362 | def _flag_operation(self,rows=None,regions=None,unflag=False):
|
---|
363 | scan = self.plotter._data
|
---|
364 | if not scan:
|
---|
365 | asaplog.post()
|
---|
366 | asaplog.push("Invalid scantable")
|
---|
367 | asaplog.post("ERROR")
|
---|
368 | if isinstance(rows,list) and len(rows) > 0:
|
---|
369 | scan.flag_row(rows=rows,unflag=unflag)
|
---|
370 | if isinstance(regions,dict) and len(regions) > 0:
|
---|
371 | for srow, masklist in regions.iteritems():
|
---|
372 | if not isinstance(masklist,list) or len(masklist) ==0:
|
---|
373 | msg = "Ignoring invalid region selection for row = "+srow
|
---|
374 | asaplog.post()
|
---|
375 | asaplog.push(msg)
|
---|
376 | asaplog.post("WARN")
|
---|
377 | continue
|
---|
378 | irow = int(srow)
|
---|
379 | mask = scan.create_mask(masklist,invert=False,row=irow)
|
---|
380 | scan.flag(row=irow,mask=mask,unflag=unflag)
|
---|
381 | del irow, mask
|
---|
382 | del srow, masklist
|
---|
383 | del scan
|
---|
384 |
|
---|
385 | ### show statistics of selected spectra/regions
|
---|
386 | @asaplog_post_dec
|
---|
387 | def stat_cal(self):
|
---|
388 | if not self._any_selection():
|
---|
389 | msg = "No selection to be calculated"
|
---|
390 | asaplog.push(msg)
|
---|
391 | asaplog.post('WARN')
|
---|
392 | return
|
---|
393 | self._selected_stats(rows=self._selpanels,regions=self._selregions)
|
---|
394 | self._clearup_selections(refresh=True)
|
---|
395 |
|
---|
396 | @asaplog_post_dec
|
---|
397 | def _selected_stats(self,rows=None,regions=None):
|
---|
398 | scan = self.plotter._data
|
---|
399 | if not scan:
|
---|
400 | asaplog.post()
|
---|
401 | asaplog.push("Invalid scantable")
|
---|
402 | asaplog.post("ERROR")
|
---|
403 | mathobj = stmath( rcParams['insitu'] )
|
---|
404 | statval = {}
|
---|
405 | statstr = ['max', 'min', 'mean', 'median', 'sum', 'stddev', 'rms']
|
---|
406 | if isinstance(rows,list) and len(rows) > 0:
|
---|
407 | for irow in rows:
|
---|
408 | for stat in statstr:
|
---|
409 | statval[stat] = mathobj._statsrow(scan,[],stat,irow)[0]
|
---|
410 | self._print_stats(scan,irow,statval,statstr=statstr)
|
---|
411 | del irow
|
---|
412 | if isinstance(regions,dict) and len(regions) > 0:
|
---|
413 | for srow, masklist in regions.iteritems():
|
---|
414 | if not isinstance(masklist,list) or len(masklist) ==0:
|
---|
415 | msg = "Ignoring invalid region selection for row = "+srow
|
---|
416 | asaplog.post()
|
---|
417 | asaplog.push(msg)
|
---|
418 | asaplog.post("WARN")
|
---|
419 | continue
|
---|
420 | irow = int(srow)
|
---|
421 | mask = scan.create_mask(masklist,invert=False,row=irow)
|
---|
422 | for stat in statstr:
|
---|
423 | statval[stat] = mathobj._statsrow(scan,mask,stat,irow)[0]
|
---|
424 | self._print_stats(scan,irow,statval,statstr=statstr,mask=masklist)
|
---|
425 | del irow, mask
|
---|
426 | del srow, masklist
|
---|
427 | del scan, statval, mathobj
|
---|
428 |
|
---|
429 | @asaplog_post_dec
|
---|
430 | def _print_stats(self,scan,row,stats,statstr=None,mask=None):
|
---|
431 | if not isinstance(scan, scantable):
|
---|
432 | asaplog.post()
|
---|
433 | asaplog.push("Invalid scantable")
|
---|
434 | asaplog.post("ERROR")
|
---|
435 | if row < 0 or row > scan.nrow():
|
---|
436 | asaplog.post()
|
---|
437 | asaplog.push("Invalid row number")
|
---|
438 | asaplog.post("ERROR")
|
---|
439 | if not isinstance(stats,dict) or len(stats) == 0:
|
---|
440 | asaplog.post()
|
---|
441 | asaplog.push("Invalid statistic value")
|
---|
442 | asaplog.post("ERROR")
|
---|
443 | maskstr = "All"
|
---|
444 | if mask:
|
---|
445 | maskstr = str(mask)
|
---|
446 | ssep = "-"*70+"\n"
|
---|
447 | sout = ssep
|
---|
448 | sout += ("Row=%d Scan=%d IF=%d Pol=%d Time=%s mask=%s" % \
|
---|
449 | (row, scan.getscan(row), scan.getif(row), scan.getpol(row), scan.get_time(row),maskstr))
|
---|
450 | sout += "\n"
|
---|
451 | statvals = []
|
---|
452 | if not len(statstr):
|
---|
453 | statstr = stats.keys()
|
---|
454 | for key in statstr:
|
---|
455 | sout += key.ljust(10)
|
---|
456 | statvals.append(stats.pop(key))
|
---|
457 | sout += "\n"
|
---|
458 | sout += ("%f "*len(statstr) % tuple(statvals))
|
---|
459 | sout += "\n"+ssep
|
---|
460 | asaplog.push(sout)
|
---|
461 | del sout, ssep, maskstr, statvals, key, scan, row, stats, statstr, mask
|
---|
462 |
|
---|
463 | ### Page chages
|
---|
464 | ### go to the previous page
|
---|
465 | def prev_page(self):
|
---|
466 | self._pause_buttons(operation="start",msg='plotting the previous page')
|
---|
467 | self._clear_selection_plot(refresh=False)
|
---|
468 | self._plot_page(pagemode="prev")
|
---|
469 | self._plot_selections()
|
---|
470 | self._pause_buttons(operation="end")
|
---|
471 |
|
---|
472 | ### go to the next page
|
---|
473 | def next_page(self):
|
---|
474 | self._pause_buttons(operation="start",msg='plotting the next page')
|
---|
475 | self._clear_selection_plot(refresh=False)
|
---|
476 | self._plot_page(pagemode="next")
|
---|
477 | self._plot_selections()
|
---|
478 | self._pause_buttons(operation="end")
|
---|
479 |
|
---|
480 | ### actual plotting of the new page
|
---|
481 | def _plot_page(self,pagemode="next"):
|
---|
482 | if self.plotter._startrow <= 0:
|
---|
483 | msg = "The page counter is reset due to chages of plot settings. "
|
---|
484 | msg += "Plotting from the first page."
|
---|
485 | asaplog.post()
|
---|
486 | asaplog.push(msg)
|
---|
487 | asaplog.post('WARN')
|
---|
488 | goback = False
|
---|
489 |
|
---|
490 | self.plotter._plotter.hold()
|
---|
491 | self.plotter._plotter.legend(1)
|
---|
492 | self._set_plot_counter(pagemode)
|
---|
493 | self.plotter._plot(self.plotter._data)
|
---|
494 | self.set_pagecounter(self._get_pagenum())
|
---|
495 | self.plotter._plotter.release()
|
---|
496 | self.plotter._plotter.tidy()
|
---|
497 | self.plotter._plotter.show(hardrefresh=False)
|
---|
498 |
|
---|
499 | ### calculate the panel ID and start row to plot a page
|
---|
500 | #def _set_prevpage_counter(self):
|
---|
501 | def _set_plot_counter(self, pagemode):
|
---|
502 | ## page operation should be either "previous", "current", or "next"
|
---|
503 | availpage = ["p","c","n"]
|
---|
504 | pageop = pagemode[0].lower()
|
---|
505 | if not (pageop in availpage):
|
---|
506 | asaplog.post()
|
---|
507 | asaplog.push("Invalid page operation")
|
---|
508 | asaplog.post("ERROR")
|
---|
509 | if pageop == "n":
|
---|
510 | # nothing necessary to plot the next page
|
---|
511 | return
|
---|
512 | # set row and panel counters to those of the 1st panel of previous page
|
---|
513 | maxpanel = 16
|
---|
514 | # the ID of the last panel in current plot
|
---|
515 | lastpanel = self.plotter._ipanel
|
---|
516 | # the number of current subplots
|
---|
517 | currpnum = len(self.plotter._plotter.subplots)
|
---|
518 |
|
---|
519 | # the nuber of previous subplots
|
---|
520 | start_ipanel = None
|
---|
521 | if pageop == "c":
|
---|
522 | start_ipanel = max(lastpanel-currpnum+1, 0)
|
---|
523 | else:
|
---|
524 | ## previous page
|
---|
525 | prevpnum = None
|
---|
526 | if self.plotter._rows and self.plotter._cols:
|
---|
527 | # when user set layout
|
---|
528 | prevpnum = self.plotter._rows*self.plotter._cols
|
---|
529 | else:
|
---|
530 | # no user specification
|
---|
531 | prevpnum = maxpanel
|
---|
532 | start_ipanel = max(lastpanel-currpnum-prevpnum+1, 0)
|
---|
533 | del prevpnum
|
---|
534 |
|
---|
535 | # set the pannel ID of the last panel of the prev(-prev) page
|
---|
536 | self.plotter._ipanel = start_ipanel-1
|
---|
537 | if self.plotter._panelling == 'r':
|
---|
538 | self.plotter._startrow = start_ipanel
|
---|
539 | else:
|
---|
540 | # the start row number of the next panel
|
---|
541 | self.plotter._startrow = self.plotter._panelrows[start_ipanel]
|
---|
542 | del lastpanel,currpnum,start_ipanel
|
---|
543 |
|
---|
544 | ### refresh the page counter
|
---|
545 | def set_pagecounter(self,page):
|
---|
546 | nwidth = int(numpy.ceil(numpy.log10(max(page,1))))+1
|
---|
547 | nwidth = max(nwidth,4)
|
---|
548 | formatstr = '%'+str(nwidth)+'d'
|
---|
549 | self.show_pagenum(page,formatstr)
|
---|
550 |
|
---|
551 | def show_pagenum(self,pagenum,formatstr):
|
---|
552 | # passed to backend dependent class
|
---|
553 | pass
|
---|
554 |
|
---|
555 | def _get_pagenum(self):
|
---|
556 | maxpanel = 16
|
---|
557 | # get the ID of last panel in the current page
|
---|
558 | idlastpanel = self.plotter._ipanel
|
---|
559 | if self.plotter._rows and self.plotter._cols:
|
---|
560 | ppp = self.plotter._rows*self.plotter._cols
|
---|
561 | else:
|
---|
562 | ppp = maxpanel
|
---|
563 | return int(idlastpanel/ppp)+1
|
---|
564 |
|
---|
565 | # pause buttons for slow operations. implemented at a backend dependent class
|
---|
566 | def _pause_buttons(self,operation="end",msg=""):
|
---|
567 | pass
|
---|
568 |
|
---|
569 | #####################################
|
---|
570 | ## Backend dependent Classes ##
|
---|
571 | #####################################
|
---|
572 | ### TkAgg
|
---|
573 | if matplotlib.get_backend() == 'TkAgg':
|
---|
574 | import Tkinter as Tk
|
---|
575 | from notationwindow import NotationWindowTkAgg
|
---|
576 |
|
---|
577 | class CustomFlagToolbarTkAgg(CustomFlagToolbarCommon, Tk.Frame):
|
---|
578 | def __init__(self,parent):
|
---|
579 | from asap.asapplotter import asapplotter
|
---|
580 | if not isinstance(parent,asapplotter):
|
---|
581 | return False
|
---|
582 | if not parent._plotter:
|
---|
583 | return False
|
---|
584 | self._p = parent._plotter
|
---|
585 | self.figmgr = self._p.figmgr
|
---|
586 | self.canvas = self.figmgr.canvas
|
---|
587 | self.mode = ''
|
---|
588 | self.button = True
|
---|
589 | self.pagecount = None
|
---|
590 | CustomFlagToolbarCommon.__init__(self,parent)
|
---|
591 | self.notewin=NotationWindowTkAgg(master=self.canvas)
|
---|
592 | self._add_custom_toolbar()
|
---|
593 |
|
---|
594 | def _add_custom_toolbar(self):
|
---|
595 | Tk.Frame.__init__(self,master=self.figmgr.window)
|
---|
596 | #self.bSpec = self._NewButton(master=self,
|
---|
597 | # text='spec value',
|
---|
598 | # command=self.spec_show)
|
---|
599 |
|
---|
600 | self.bRegion = self._NewButton(master=self,
|
---|
601 | text='region',
|
---|
602 | command=self.select_region)
|
---|
603 | self.bPanel = self._NewButton(master=self,
|
---|
604 | text='panel',
|
---|
605 | command=self.select_panel)
|
---|
606 | self.bClear = self._NewButton(master=self,
|
---|
607 | text='clear',
|
---|
608 | command=self.cancel_select)
|
---|
609 | self.bFlag = self._NewButton(master=self,
|
---|
610 | text='flag',
|
---|
611 | command=self.flag)
|
---|
612 | self.bUnflag = self._NewButton(master=self,
|
---|
613 | text='unflag',
|
---|
614 | command=self.unflag)
|
---|
615 |
|
---|
616 | self.bStat = self._NewButton(master=self,
|
---|
617 | text='statistics',
|
---|
618 | command=self.stat_cal)
|
---|
619 |
|
---|
620 | self.bNote = self._NewButton(master=self,
|
---|
621 | text='notation',
|
---|
622 | command=self.modify_note)
|
---|
623 |
|
---|
624 | self.bQuit = self._NewButton(master=self,
|
---|
625 | text='Quit',
|
---|
626 | #file="stock_close.ppm",
|
---|
627 | command=self.quit,
|
---|
628 | side=Tk.RIGHT)
|
---|
629 |
|
---|
630 | # page change oparations
|
---|
631 | frPage = Tk.Frame(master=self,borderwidth=2,relief=Tk.GROOVE)
|
---|
632 | frPage.pack(ipadx=2,padx=10,side=Tk.RIGHT)
|
---|
633 | self.lPagetitle = Tk.Label(master=frPage,text='Page:',padx=5)
|
---|
634 | #width=8,anchor=Tk.E,padx=5)
|
---|
635 | self.lPagetitle.pack(side=Tk.LEFT)
|
---|
636 | self.pagecount = Tk.StringVar(master=frPage)
|
---|
637 | self.lPagecount = Tk.Label(master=frPage,
|
---|
638 | textvariable=self.pagecount,
|
---|
639 | padx=5,bg='white')
|
---|
640 | self.lPagecount.pack(side=Tk.LEFT,padx=3)
|
---|
641 |
|
---|
642 | self.bNext=self._NewButton(master=frPage,
|
---|
643 | text=' + ',
|
---|
644 | #file="hand.ppm",
|
---|
645 | command=self.next_page)
|
---|
646 | self.bPrev=self._NewButton(master=frPage,
|
---|
647 | text=' - ',
|
---|
648 | command=self.prev_page)
|
---|
649 |
|
---|
650 | if os.uname()[0] != 'Darwin':
|
---|
651 | self.bPrev.config(padx=5)
|
---|
652 | self.bNext.config(padx=5)
|
---|
653 |
|
---|
654 | self.pack(side=Tk.BOTTOM,fill=Tk.BOTH)
|
---|
655 | self.pagecount.set(' '*4)
|
---|
656 |
|
---|
657 | self.disable_button()
|
---|
658 | return #self
|
---|
659 |
|
---|
660 | def _NewButton(self, master, text, command, side=Tk.LEFT,file=None):
|
---|
661 | img = None
|
---|
662 | if file:
|
---|
663 | file = os.path.join(matplotlib.rcParams['datapath'], 'images', file)
|
---|
664 | img = Tk.PhotoImage(master=master, file=file)
|
---|
665 |
|
---|
666 | if os.uname()[0] == 'Darwin':
|
---|
667 | b = Tk.Button(master=master, text=text, image=img,
|
---|
668 | command=command)
|
---|
669 | if img: b.image = img
|
---|
670 | else:
|
---|
671 | b = Tk.Button(master=master, text=text, image=img, padx=2, pady=2,
|
---|
672 | command=command)
|
---|
673 | if img: b.image = img
|
---|
674 | b.pack(side=side)
|
---|
675 | return b
|
---|
676 |
|
---|
677 | def show_pagenum(self,pagenum,formatstr):
|
---|
678 | self.pagecount.set(formatstr % (pagenum))
|
---|
679 |
|
---|
680 | def spec_show(self):
|
---|
681 | if not self.figmgr.toolbar.mode == '' or not self.button: return
|
---|
682 | self.figmgr.toolbar.set_message('spec value: drag on a spec')
|
---|
683 | if self.mode == 'spec': return
|
---|
684 | self.mode = 'spec'
|
---|
685 | self.notewin.close_widgets()
|
---|
686 | self.__disconnect_event()
|
---|
687 | self._p.register('button_press',self._select_spectrum)
|
---|
688 |
|
---|
689 | def modify_note(self):
|
---|
690 | if not self.figmgr.toolbar.mode == '': return
|
---|
691 | self.figmgr.toolbar.set_message('text: select a position/text')
|
---|
692 | if self.mode == 'note':
|
---|
693 | self.bNote.config(relief='raised')
|
---|
694 | self.mode = 'none'
|
---|
695 | self.spec_show()
|
---|
696 | return
|
---|
697 | self.bNote.config(relief='sunken')
|
---|
698 | self.bRegion.config(relief='raised')
|
---|
699 | self.bPanel.config(relief='raised')
|
---|
700 | self.mode = 'note'
|
---|
701 | self.__disconnect_event()
|
---|
702 | self._p.register('button_press',self._mod_note)
|
---|
703 |
|
---|
704 | def select_region(self):
|
---|
705 | if not self.figmgr.toolbar.mode == '' or not self.button: return
|
---|
706 | self.figmgr.toolbar.set_message('select rectangle regions')
|
---|
707 | if self.mode == 'region':
|
---|
708 | self.bRegion.config(relief='raised')
|
---|
709 | self.mode = 'none'
|
---|
710 | self.spec_show()
|
---|
711 | return
|
---|
712 | self.bNote.config(relief='raised')
|
---|
713 | self.bRegion.config(relief='sunken')
|
---|
714 | self.bPanel.config(relief='raised')
|
---|
715 | self.mode = 'region'
|
---|
716 | self.notewin.close_widgets()
|
---|
717 | self.__disconnect_event()
|
---|
718 | self._p.register('button_press',self._add_region)
|
---|
719 |
|
---|
720 | def select_panel(self):
|
---|
721 | if not self.figmgr.toolbar.mode == '' or not self.button: return
|
---|
722 | self.figmgr.toolbar.set_message('select panels')
|
---|
723 | if self.mode == 'panel':
|
---|
724 | self.bPanel.config(relief='raised')
|
---|
725 | self.mode = 'none'
|
---|
726 | self.spec_show()
|
---|
727 | return
|
---|
728 | self.bNote.config(relief='raised')
|
---|
729 | self.bRegion.config(relief='raised')
|
---|
730 | self.bPanel.config(relief='sunken')
|
---|
731 | self.mode = 'panel'
|
---|
732 | self.notewin.close_widgets()
|
---|
733 | self.__disconnect_event()
|
---|
734 | self._p.register('button_press',self._add_panel)
|
---|
735 |
|
---|
736 | def quit(self):
|
---|
737 | self.__disconnect_event()
|
---|
738 | self.disable_button()
|
---|
739 | self.figmgr.window.wm_withdraw()
|
---|
740 |
|
---|
741 | def enable_button(self):
|
---|
742 | if self.button: return
|
---|
743 | self.bRegion.config(state=Tk.NORMAL)
|
---|
744 | self.bPanel.config(state=Tk.NORMAL)
|
---|
745 | self.bClear.config(state=Tk.NORMAL)
|
---|
746 | self.bFlag.config(state=Tk.NORMAL)
|
---|
747 | self.bUnflag.config(state=Tk.NORMAL)
|
---|
748 | self.bStat.config(state=Tk.NORMAL)
|
---|
749 | self.button = True
|
---|
750 | self.spec_show()
|
---|
751 |
|
---|
752 | def disable_button(self):
|
---|
753 | ## disable buttons which don't work for plottp
|
---|
754 | if not self.button: return
|
---|
755 | self.bRegion.config(relief='raised')
|
---|
756 | self.bPanel.config(relief='raised')
|
---|
757 | self.bRegion.config(state=Tk.DISABLED)
|
---|
758 | self.bPanel.config(state=Tk.DISABLED)
|
---|
759 | self.bClear.config(state=Tk.DISABLED)
|
---|
760 | self.bFlag.config(state=Tk.DISABLED)
|
---|
761 | self.bUnflag.config(state=Tk.DISABLED)
|
---|
762 | self.bStat.config(state=Tk.DISABLED)
|
---|
763 | self.bNext.config(state=Tk.DISABLED)
|
---|
764 | self.bPrev.config(state=Tk.DISABLED)
|
---|
765 | self.button = False
|
---|
766 | self.mode = ''
|
---|
767 | self.notewin.close_widgets()
|
---|
768 | self.__disconnect_event()
|
---|
769 |
|
---|
770 | def enable_next(self):
|
---|
771 | self.bNext.config(state=Tk.NORMAL)
|
---|
772 |
|
---|
773 | def disable_next(self):
|
---|
774 | self.bNext.config(state=Tk.DISABLED)
|
---|
775 |
|
---|
776 | def enable_prev(self):
|
---|
777 | self.bPrev.config(state=Tk.NORMAL)
|
---|
778 |
|
---|
779 | def disable_prev(self):
|
---|
780 | self.bPrev.config(state=Tk.DISABLED)
|
---|
781 |
|
---|
782 | # pause buttons for slow operations
|
---|
783 | def _pause_buttons(self,operation="end",msg=""):
|
---|
784 | buttons = ["bRegion","bPanel","bClear","bFlag","bUnflag","bStat",
|
---|
785 | "bNote","bQuit"]
|
---|
786 | if operation == "start":
|
---|
787 | state=Tk.DISABLED
|
---|
788 | else:
|
---|
789 | state=Tk.NORMAL
|
---|
790 | for btn in buttons:
|
---|
791 | getattr(self,btn).config(state=state)
|
---|
792 | self.figmgr.toolbar.set_message(msg)
|
---|
793 |
|
---|
794 | def delete_bar(self):
|
---|
795 | self.__disconnect_event()
|
---|
796 | self.destroy()
|
---|
797 |
|
---|
798 | def __disconnect_event(self):
|
---|
799 | self._p.register('button_press',None)
|
---|
800 | self._p.register('button_release',None)
|
---|
801 |
|
---|
802 | def _draw_span(self,axes,x0,x1,**kwargs):
|
---|
803 | height = self._p.figure.bbox.height
|
---|
804 | y0 = height - axes.bbox.y0
|
---|
805 | y1 = height - axes.bbox.y1
|
---|
806 | return self._p.canvas._tkcanvas.create_rectangle(x0,y0,x1,y1,**kwargs)
|
---|
807 |
|
---|
808 | def _remove_span(self,span):
|
---|
809 | self._p.canvas._tkcanvas.delete(span)
|
---|