source: trunk/python/customgui_base.py@ 2171

Last change on this file since 2171 was 2171, checked in by Kana Sugimoto, 14 years ago

New Development: No

JIRA Issue: No (a bug fix)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: interactive test

Put in Release Notes: No

Module(s): flagplotter

Description:

fixed a bug in CustomFlagToolbarCommon class, which caused unexpected flag region in
interactive flagging if end of mask region is outside of subplot.


File size: 41.6 KB
Line 
1import os
2import matplotlib, numpy
3from asap.logging import asaplog, asaplog_post_dec
4from matplotlib.patches import Rectangle
5from asap.parameters import rcParams
6from asap import scantable
7from asap._asap import stmath
8
9######################################
10## Add CASA custom toolbar ##
11######################################
12class CustomToolbarCommon:
13 def __init__(self,parent):
14 self.plotter = parent
15 #self.figmgr=self.plotter._plotter.figmgr
16
17 ### select the nearest spectrum in pick radius
18 ### and display spectral value on the toolbar.
19 def _select_spectrum(self,event):
20 # Do not fire event when in zooming/panning mode
21 mode = self.figmgr.toolbar.mode
22 if not mode == '':
23 return
24 # When selected point is out of panels
25 if event.inaxes == None:
26 return
27 # If not left button
28 if event.button != 1:
29 return
30
31 xclick = event.xdata
32 yclick = event.ydata
33 dist2 = 1000.
34 pickline = None
35 # If the pannel has picable objects
36 pflag = False
37 for lin in event.inaxes.lines:
38 if not lin.pickable():
39 continue
40 pflag = True
41 flag,pind = lin.contains(event)
42 if not flag:
43 continue
44 # Get nearest point
45 inds = pind['ind']
46 xlin = lin.get_xdata()
47 ylin = lin.get_ydata()
48 for i in inds:
49 d2=(xlin[i]-xclick)**2+(ylin[i]-yclick)**2
50 if dist2 >= d2:
51 dist2 = d2
52 pickline = lin
53 # No pickcable line in the pannel
54 if not pflag:
55 return
56 # Pickable but too far from mouse position
57 elif pickline is None:
58 picked = 'No line selected.'
59 self.figmgr.toolbar.set_message(picked)
60 return
61 del pind, inds, xlin, ylin
62 # Spectra are Picked
63 theplot = self.plotter._plotter
64 thetoolbar = self.figmgr.toolbar
65 thecanvas = self.figmgr.canvas
66 # Disconnect the default motion notify event
67 # Notice! the other buttons are also diabled!!!
68 thecanvas.mpl_disconnect(thetoolbar._idDrag)
69 # Get picked spectrum
70 xdata = pickline.get_xdata()
71 ydata = pickline.get_ydata()
72 titl = pickline.get_label()
73 titp = event.inaxes.title.get_text()
74 panel0 = event.inaxes
75 picked = "Selected: '"+titl+"' in panel '"+titp+"'."
76 thetoolbar.set_message(picked)
77 # Generate a navigation window
78 #naviwin=Navigationwindow(titp,titl)
79 #------------------------------------------------------#
80 # Show spectrum data at mouse position
81 def spec_data(event):
82 # Getting spectrum data of neiboring point
83 xclick = event.xdata
84 if event.inaxes != panel0:
85 return
86 ipoint = len(xdata)-1
87 for i in range(len(xdata)-1):
88 xl = xclick - xdata[i]
89 xr = xclick - xdata[i+1]
90 if xl*xr <= 0.:
91 ipoint = i
92 break
93 # Output spectral value on the navigation window
94 posi = '[ %s, %s ]: x = %.2f value = %.2f'\
95 %(titl,titp,xdata[ipoint],ydata[ipoint])
96 #naviwin.posi.set(posi)
97 thetoolbar.set_message(posi)
98 #------------------------------------------------------#
99 # Disconnect from mouse events
100 def discon(event):
101 #naviwin.window.destroy()
102 theplot.register('motion_notify',None)
103 # Re-activate the default motion_notify_event
104 thetoolbar._idDrag = thecanvas.mpl_connect('motion_notify_event',
105 thetoolbar.mouse_move)
106 theplot.register('button_release',None)
107 return
108 #------------------------------------------------------#
109 # Show data value along with mouse movement
110 theplot.register('motion_notify',spec_data)
111 # Finish events when mouse button is released
112 theplot.register('button_release',discon)
113
114
115 ### Calculate statistics of the selected area.
116 def _single_mask(self,event):
117 # Do not fire event when in zooming/panning mode
118 if not self.figmgr.toolbar.mode == '':
119 return
120 # When selected point is out of panels
121 if event.inaxes == None:
122 return
123 if event.button == 1:
124 baseinv=True
125 elif event.button == 3:
126 baseinv=False
127 else:
128 return
129
130 def _calc_stats():
131 msk=mymask.get_mask()
132 statstr = ['max', 'min', 'mean', 'median', 'sum', 'stddev', 'rms']
133 for stat in statstr:
134 mymask.scan.stats(stat=stat,mask=msk)
135
136 # Interactive mask definition
137 from asap.interactivemask import interactivemask
138 mymask = interactivemask(plotter=self.plotter,scan=self.plotter._data)
139 # Create initial mask
140 mymask.set_basemask(invert=baseinv)
141 # Inherit event
142 mymask.set_startevent(event)
143 # Set callback func
144 mymask.set_callback(_calc_stats)
145 # Selected mask
146 mymask.select_mask(once=True,showmask=False)
147
148 def _mod_note(self,event):
149 # Do not fire event when in zooming/panning mode
150 if not self.figmgr.toolbar.mode == '':
151 return
152 if event.button == 1:
153 self.notewin.load_textwindow(event)
154 elif event.button == 3 and self._note_picked(event):
155 self.notewin.load_modmenu(event)
156 return
157
158 def _note_picked(self,event):
159 # just briefly check if any texts are picked
160 for textobj in self.canvas.figure.texts:
161 if textobj.contains(event)[0]:
162 return True
163 for ax in self.canvas.figure.axes:
164 for textobj in ax.texts:
165 if textobj.contains(event)[0]:
166 return True
167 #print "No text picked"
168 return False
169
170 ### Page chages
171 ### go to the previous page
172 def prev_page(self):
173 self.figmgr.toolbar.set_message('plotting the previous page')
174 #self._pause_buttons(operation="start",msg='plotting the previous page')
175 self._new_page(goback=True)
176 #self._pause_buttons(operation="end")
177
178 ### go to the next page
179 def next_page(self):
180 self.figmgr.toolbar.set_message('plotting the next page')
181 #self._pause_buttons(operation="start",msg='plotting the next page')
182 self._new_page(goback=False)
183 #self._pause_buttons(operation="end")
184
185 ### actual plotting of the new page
186 def _new_page(self,goback=False):
187 top = None
188 header = self.plotter._headtext
189 reset = False
190 doheader = (isinstance(header['textobj'],list) and \
191 len(header['textobj']) > 0)
192 if self.plotter._startrow <= 0:
193 msg = "The page counter is reset due to chages of plot settings. "
194 msg += "Plotting from the first page."
195 asaplog.push(msg)
196 asaplog.post('WARN')
197 reset = True
198 goback = False
199 if doheader:
200 extrastr = selstr = ''
201 if header.has_key('extrastr'):
202 extrastr = header['extrastr']
203 if header.has_key('selstr'):
204 selstr = header['selstr']
205 self.plotter._reset_header()
206 if doheader:
207 top = self.plotter._plotter.figure.subplotpars.top
208 fontsize = header['textobj'][0].get_fontproperties().get_size()
209
210 self.plotter._plotter.hold()
211 if goback:
212 self._set_prevpage_counter()
213 #self.plotter._plotter.clear()
214 self.plotter._plot(self.plotter._data)
215 self.set_pagecounter(self._get_pagenum())
216 # Plot header information
217 if header['textobj']:
218 if top and top != self.plotter._margins[3]:
219 # work around for sdplot in CASA. complete checking in future?
220 self.plotter._plotter.figure.subplots_adjust(top=top)
221 if reset:
222 self.plotter.print_header(plot=True,fontsize=fontsize,selstr=selstr, extrastr=extrastr)
223 else:
224 self.plotter._header_plot(header['string'],fontsize=fontsize)
225 self.plotter._plotter.release()
226 self.plotter._plotter.tidy()
227 self.plotter._plotter.show(hardrefresh=False)
228 del top
229
230 ### calculate the panel ID and start row to plot the previous page
231 def _set_prevpage_counter(self):
232 # set row and panel counters to those of the 1st panel of previous page
233 maxpanel = 16
234 # the ID of the last panel in current plot
235 lastpanel = self.plotter._ipanel
236 # the number of current subplots
237 currpnum = len(self.plotter._plotter.subplots)
238 # the nuber of previous subplots
239 prevpnum = None
240 if self.plotter._rows and self.plotter._cols:
241 # when user set layout
242 prevpnum = self.plotter._rows*self.plotter._cols
243 else:
244 # no user specification
245 prevpnum = maxpanel
246
247 start_ipanel = max(lastpanel-currpnum-prevpnum+1, 0)
248 # set the pannel ID of the last panel of prev-prev page
249 self.plotter._ipanel = start_ipanel-1
250 if self.plotter._panelling == 'r':
251 self.plotter._startrow = start_ipanel
252 else:
253 # the start row number of the next panel
254 self.plotter._startrow = self.plotter._panelrows[start_ipanel]
255 del lastpanel,currpnum,prevpnum,start_ipanel
256
257 ### refresh the page counter
258 ### refresh the page counter
259 def set_pagecounter(self,page):
260 nwidth = int(numpy.ceil(numpy.log10(max(page,1))))+1
261 nwidth = max(nwidth,4)
262 formatstr = '%'+str(nwidth)+'d'
263 self.show_pagenum(page,formatstr)
264
265 def show_pagenum(self,pagenum,formatstr):
266 # passed to backend dependent class
267 pass
268
269 def _get_pagenum(self):
270 maxpanel = 16
271 # get the ID of last panel in the current page
272 idlastpanel = self.plotter._ipanel
273 if self.plotter._rows and self.plotter._cols:
274 ppp = self.plotter._rows*self.plotter._cols
275 else:
276 ppp = maxpanel
277 return int(idlastpanel/ppp)+1
278
279 # pause buttons for slow operations. implemented at a backend dependent class
280 def _pause_buttons(self,operation="end",msg=""):
281 pass
282
283
284
285
286######################################
287## Notation box window ##
288######################################
289class NotationWindowCommon:
290 """
291 A base class to define the functions that the backend-based
292 GUI notation class must implement to print/modify/delete notes on a canvas.
293
294 The following methods *must* be implemented in the backend-based
295 parent class:
296 _get_note : get text in text box
297 _get_anchval : get anchor value selected
298 """
299 def __init__(self,master=None):
300 #self.parent = master
301 self.canvas = master
302 self.event = None
303 self.note = None
304 self.anchors = ["figure","axes","data"]
305 self.seltext = {}
306 self.numnote = 0
307
308 @asaplog_post_dec
309 def print_text(self):
310 """
311 Print a note on a canvas specified with the Notation window.
312 Called when 'print' button selected on the window.
313 """
314 anchor = self.anchors[self._get_anchval()]
315 notestr = self._get_note().rstrip("\n")
316 if len(notestr.strip()) == 0:
317 #self._clear_textbox()
318 #print "Empty string!"
319 return
320
321 myaxes = None
322 calcpos = True
323 xpos = None
324 ypos = None
325 if self.seltext:
326 # You are modifying a text
327 mycanvas = self.canvas
328 oldanch = self.seltext['anchor']
329 if oldanch != 'figure':
330 myaxes = self.seltext['parent']
331 calcpos = (anchor != oldanch)
332 if not calcpos:
333 # printing text in the same coord.
334 # you don't have to recalc position
335 parent = self.seltext['parent']
336 transform = self.seltext['textobj'].get_transform()
337 (xpos, ypos) = self.seltext['textobj'].get_position()
338 elif anchor == "figure":
339 # converting from "axes"/"data" -> "figure"
340 (x, y) = self.seltext['textobj']._get_xy_display()
341 elif oldanch == "data":
342 # converting from "data" -> "axes".
343 # need xdata & ydata in the axes
344 (x, y) = self.seltext['textobj'].get_position()
345 else:
346 # converting "figure"/"axes" -> "data"
347 # need to calculate xdata & ydata in the axes
348 pixpos = self.seltext['textobj']._get_xy_display()
349 (w,h) = mycanvas.get_width_height()
350 relpos = (pixpos[0]/float(w), pixpos[1]/float(h))
351 if not myaxes:
352 myaxes = self._get_axes_from_pos(relpos,mycanvas)
353 if not myaxes:
354 raise RuntimeError, "Axes resolution failed!"
355 (x, y) = self._convert_pix2dat(relpos,myaxes)
356 self._remove_seltext()
357 elif self.event:
358 mycanvas = self.event.canvas
359 myaxes = self.event.inaxes
360 if myaxes and (anchor != "figure"):
361 x = self.event.xdata
362 y = self.event.ydata
363 else:
364 x = self.event.x
365 y = self.event.y
366 else:
367 raise RuntimeError, "No valid position to print data"
368 return
369
370 # now you know
371 picker = True
372 # alignment of the text: ha (horizontal), va (vertical)
373 ha = 'left'
374 #va = 'center'
375 va = 'top'
376 if not calcpos:
377 # you aready know parent, tansform, xpos and ypos
378 pass
379 elif anchor == "figure":
380 # text instance will be appended to mycanvas.figure.texts
381 parent = mycanvas.figure
382 transform = parent.transFigure
383 (w,h) = mycanvas.get_width_height()
384 xpos = x/float(w)
385 ypos = y/float(h)
386 elif myaxes:
387 ## text instance will be appended to myaxes.texts
388 parent = myaxes
389 if anchor == "axes":
390 transform = myaxes.transAxes
391 lims = myaxes.get_xlim()
392 xpos = (x-lims[0])/(lims[1]-lims[0])
393 lims = myaxes.get_ylim()
394 ypos = (y-lims[0])/(lims[1]-lims[0])
395 else:
396 # anchored on "data"
397 transform = myaxes.transData
398 xpos = x
399 ypos = y
400 parent.text(xpos,ypos,notestr,transform=transform,
401 ha=ha,va=va,picker=picker)
402 mycanvas.draw()
403
404 self.numnote += 1
405
406 #self._clear_textbox()
407 msg = "Added note: '"+notestr+"'"
408 msg += " @["+str(xpos)+", "+str(ypos)+"] ("+anchor+"-coord)"
409 msg += "\ntotal number of notes are "+str(self.numnote)
410 asaplog.push( msg )
411
412 def _get_axes_from_pos(self,pos,canvas):
413 """helper function to get axes of a position in a plot (fig-coord)"""
414 if len(pos) != 2:
415 raise ValueError, "pixel position should have 2 elements"
416 for axes in canvas.figure.axes:
417 ##check if pos is in the axes
418 #if axes.contains_point(pos): ### seems not working
419 # return axes
420 try:
421 axbox = axes.get_position().get_points()
422 except AttributeError: ### WORKAROUND for old matplotlib
423 axbox = self._oldpos2new(axes.get_position())
424 if (axbox[0][0] <= pos[0] <= axbox[1][0]) and \
425 (axbox[0][1] <= pos[1] <= axbox[1][1]):
426 return axes
427 return None
428
429 ### WORKAROUND for old matplotlib
430 def _oldpos2new(self,oldpos=None):
431 return [[oldpos[0],oldpos[1]],[oldpos[0]+oldpos[2],oldpos[1]+oldpos[3]]]
432
433 def _convert_pix2dat(self,pos,axes):
434 """
435 helper function to convert a position in figure-coord (0-1) to
436 data-coordinate of the axes
437 """
438 # convert a relative position from lower-left of the canvas
439 # to a data in axes
440 if len(pos) != 2:
441 raise ValueError, "pixel position should have 2 elements"
442 # left-/bottom-pixel, and pixel width & height of the axes
443 bbox = axes.get_position()
444 try:
445 axpos = bbox.get_points()
446 except AttributeError: ### WORKAROUND for old matplotlib
447 axpos = self._oldpos2new(bbox)
448 # check pos value
449 if (pos[0] < axpos[0][0]) or (pos[1] < axpos[0][1]) \
450 or (pos[0] > axpos[1][0]) or (pos[1] > axpos[1][1]):
451 raise ValueError, "The position is out of the axes"
452 xlims = axes.get_xlim()
453 ylims = axes.get_ylim()
454 wdat = xlims[1] - xlims[0]
455 hdat = ylims[1] - ylims[0]
456 xdat = xlims[0] + wdat*(pos[0] - axpos[0][0])/(axpos[1][0] - axpos[0][0])
457 ydat = ylims[0] + hdat*(pos[1] - axpos[0][1])/(axpos[1][1] - axpos[0][1])
458 return (xdat, ydat)
459
460 @asaplog_post_dec
461 def _get_selected_text(self,event):
462 """helper function to return a dictionary of the nearest note to the event."""
463 (w,h) = event.canvas.get_width_height()
464 dist2 = w*w+h*h
465 selected = {}
466 for textobj in self.canvas.figure.texts:
467 if textobj.contains(event)[0]:
468 d2 = self._get_text_dist2(event,textobj)
469 if dist2 >= d2:
470 dist2 = d2
471 selected = {'anchor': 'figure', \
472 'parent': event.canvas.figure, 'textobj': textobj}
473 msg = "Fig loop: a text, '"+textobj.get_text()+"', at "
474 msg += str(textobj.get_position())+" detected"
475 #print msg
476 for ax in self.canvas.figure.axes:
477 for textobj in ax.texts:
478 if textobj.contains(event)[0]:
479 d2 = self._get_text_dist2(event,textobj)
480 if dist2 >= d2:
481 anchor='axes'
482 if ax.transData == textobj.get_transform():
483 anchor = 'data'
484 selected = {'anchor': anchor, \
485 'parent': ax, 'textobj': textobj}
486 msg = "Ax loop: a text, '"+textobj.get_text()+"', at "
487 msg += str(textobj.get_position())+" detected"
488 #print msg
489
490 if selected:
491 msg = "Selected (modify/delete): '"+selected['textobj'].get_text()
492 msg += "' @"+str(selected['textobj'].get_position())
493 msg += " ("+selected['anchor']+"-coord)"
494 asaplog.push(msg)
495
496 return selected
497
498 def _get_text_dist2(self,event,textobj):
499 """
500 helper function to calculate square of distance between
501 a event position and a text object.
502 """
503 (x,y) = textobj._get_xy_display()
504 return (x-event.x)**2+(y-event.y)**2
505
506 def delete_note(self):
507 """
508 Remove selected note.
509 """
510 #print "You selected 'OK'"
511 self._remove_seltext()
512 self.canvas.draw()
513
514 @asaplog_post_dec
515 def _remove_seltext(self):
516 """helper function to remove the selected note"""
517 if len(self.seltext) < 3:
518 raise ValueError, "Don't under stand selected text obj."
519 return
520 try:
521 self.seltext['textobj'].remove()
522 except NotImplementedError:
523 self.seltext['parent'].texts.pop(self.seltext['parent'].texts.index(self.seltext['textobj']))
524 self.numnote -= 1
525
526 textobj = self.seltext['textobj']
527 msg = "Deleted note: '"+textobj.get_text()+"'"
528 msg += "@"+str(textobj.get_position())\
529 +" ("+self.seltext['anchor']+"-coord)"
530 msg += "\ntotal number of notes are "+str(self.numnote)
531 asaplog.push( msg )
532
533 self.seltext = {}
534
535 @asaplog_post_dec
536 def cancel_delete(self):
537 """
538 Cancel deleting the selected note.
539 Called when 'cancel' button selected on confirmation dialog.
540 """
541 asaplog.push( "Cancel deleting: '"+self.seltext['textobj'].get_text()+"'" )
542 self.seltext = {}
543
544
545
546###########################################
547## Add CASA custom Flag toolbar ##
548###########################################
549class CustomFlagToolbarCommon:
550 def __init__(self,parent):
551 self.plotter=parent
552 #self.figmgr=self.plotter._plotter.figmgr
553 self._selregions = {}
554 self._selpanels = []
555 self._polygons = []
556 self._thisregion = None
557 self.xdataold=None
558
559 ### select the nearest spectrum in pick radius
560 ### and display spectral value on the toolbar.
561 def _select_spectrum(self,event):
562 # Do not fire event when in zooming/panning mode
563 mode = self.figmgr.toolbar.mode
564 if not mode == '':
565 return
566 # When selected point is out of panels
567 if event.inaxes == None:
568 return
569 # If not left button
570 if event.button != 1:
571 return
572
573 xclick = event.xdata
574 yclick = event.ydata
575 dist2 = 1000.
576 pickline = None
577 # If the pannel has picable objects
578 pflag = False
579 for lin in event.inaxes.lines:
580 if not lin.pickable():
581 continue
582 pflag = True
583 flag,pind = lin.contains(event)
584 if not flag:
585 continue
586 # Get nearest point
587 inds = pind['ind']
588 xlin = lin.get_xdata()
589 ylin = lin.get_ydata()
590 for i in inds:
591 d2=(xlin[i]-xclick)**2+(ylin[i]-yclick)**2
592 if dist2 >= d2:
593 dist2 = d2
594 pickline = lin
595 # No pickcable line in the pannel
596 if not pflag:
597 return
598 # Pickable but too far from mouse position
599 elif pickline is None:
600 picked = 'No line selected.'
601 self.figmgr.toolbar.set_message(picked)
602 return
603 del pind, inds, xlin, ylin
604 # Spectra are Picked
605 theplot = self.plotter._plotter
606 thetoolbar = self.figmgr.toolbar
607 thecanvas = self.figmgr.canvas
608 # Disconnect the default motion notify event
609 # Notice! the other buttons are also diabled!!!
610 thecanvas.mpl_disconnect(thetoolbar._idDrag)
611 # Get picked spectrum
612 xdata = pickline.get_xdata()
613 ydata = pickline.get_ydata()
614 titl = pickline.get_label()
615 titp = event.inaxes.title.get_text()
616 panel0 = event.inaxes
617 picked = "Selected: '"+titl+"' in panel '"+titp+"'."
618 thetoolbar.set_message(picked)
619 # Generate a navigation window
620 #naviwin=Navigationwindow(titp,titl)
621 #------------------------------------------------------#
622 # Show spectrum data at mouse position
623 def spec_data(event):
624 # Getting spectrum data of neiboring point
625 xclick = event.xdata
626 if event.inaxes != panel0:
627 return
628 ipoint = len(xdata)-1
629 for i in range(len(xdata)-1):
630 xl = xclick-xdata[i]
631 xr = xclick-xdata[i+1]
632 if xl*xr <= 0.:
633 ipoint = i
634 break
635 # Output spectral value on the navigation window
636 posi = '[ %s, %s ]: x = %.2f value = %.2f'\
637 %(titl,titp,xdata[ipoint],ydata[ipoint])
638 #naviwin.posi.set(posi)
639 thetoolbar.set_message(posi)
640 #------------------------------------------------------#
641 # Disconnect from mouse events
642 def discon(event):
643 #naviwin.window.destroy()
644 theplot.register('motion_notify',None)
645 # Re-activate the default motion_notify_event
646 thetoolbar._idDrag=thecanvas.mpl_connect('motion_notify_event',
647 thetoolbar.mouse_move)
648 theplot.register('button_release',None)
649 return
650 #------------------------------------------------------#
651 # Show data value along with mouse movement
652 theplot.register('motion_notify',spec_data)
653 # Finish events when mouse button is released
654 theplot.register('button_release',discon)
655
656
657 ### Notation
658 def _mod_note(self,event):
659 # Do not fire event when in zooming/panning mode
660 if not self.figmgr.toolbar.mode == '':
661 return
662 if event.button == 1:
663 self.notewin.load_textwindow(event)
664 elif event.button == 3 and self._note_picked(event):
665 self.notewin.load_modmenu(event)
666 return
667
668 def _note_picked(self,event):
669 # just briefly check if any texts are picked
670 for textobj in self.canvas.figure.texts:
671 if textobj.contains(event)[0]:
672 return True
673 for ax in self.canvas.figure.axes:
674 for textobj in ax.texts:
675 if textobj.contains(event)[0]:
676 return True
677 return False
678
679 ### Region/Panel selection & oparations
680 ### add regions to selections
681 @asaplog_post_dec
682 def _add_region(self,event):
683 if not self.figmgr.toolbar.mode == '':
684 return
685 if event.button != 1 or event.inaxes == None:
686 return
687 # this row resolution assumes row panelling
688 irow = int(self._getrownum(event.inaxes))
689 if irow in self._selpanels:
690 msg = "The whole spectrum is already selected"
691 asaplog.post()
692 asaplog.push(msg)
693 asaplog.post('WARN')
694 return
695 self._thisregion = {'axes': event.inaxes,'xs': event.x,
696 'worldx': [event.xdata,event.xdata]}
697 self.plotter._plotter.register('button_press',None)
698 self.xold = event.x
699 self.xdataold = event.xdata
700 self.plotter._plotter.register('motion_notify', self._xspan_draw)
701 self.plotter._plotter.register('button_press', self._xspan_end)
702
703 def _xspan_draw(self,event):
704 if event.inaxes == self._thisregion['axes']:
705 xnow = event.x
706 self.xold = xnow
707 self.xdataold = event.xdata
708 else:
709 xnow = self.xold
710 try: self.lastspan
711 except AttributeError: pass
712 else: self._remove_span(self.lastspan)
713
714 #self.lastspan = self._draw_span(self._thisregion['axes'],self._thisregion['xs'],xnow,fill="#555555",stipple="gray50")
715 self.lastspan = self._draw_span(self._thisregion['axes'],self._thisregion['xs'],xnow,fill="")
716 del xnow
717
718 def _draw_span(self,axes,x0,x1,**kwargs):
719 pass
720
721 def _remove_span(self,span):
722 pass
723
724 @asaplog_post_dec
725 def _xspan_end(self,event):
726 if not self.figmgr.toolbar.mode == '':
727 return
728 if event.button != 1:
729 return
730
731 try: self.lastspan
732 except AttributeError: pass
733 else:
734 self._remove_span(self.lastspan)
735 del self.lastspan
736 if event.inaxes == self._thisregion['axes']:
737 xdataend = event.xdata
738 else:
739 xdataend=self.xdataold
740
741 self._thisregion['worldx'][1] = xdataend
742 lregion = self._thisregion['worldx']
743 pregion = self._thisregion['axes'].axvspan(lregion[0],lregion[1],
744 facecolor='0.7')
745 self.plotter._plotter.canvas.draw()
746 self._polygons.append(pregion)
747 srow = self._getrownum(self._thisregion['axes'])
748 irow = int(srow)
749 if not self._selregions.has_key(srow):
750 self._selregions[srow] = []
751 self._selregions[srow].append(lregion)
752 del lregion, pregion, xdataend, self.xold, self.xdataold
753 sout = "selected region: "+str(self._thisregion['worldx'])+\
754 "(@row "+str(self._getrownum(self._thisregion['axes']))+")"
755 asaplog.push(sout)
756
757 # release event
758 self.plotter._plotter.register('button_press',None)
759 self.plotter._plotter.register('motion_notify',None)
760 # Clear up region selection
761 self._thisregion = None
762 self.xdataold = None
763 # finally recover region selection event
764 self.plotter._plotter.register('button_press',self._add_region)
765
766 ### add panels to selections
767 @asaplog_post_dec
768 def _add_panel(self,event):
769 if not self.figmgr.toolbar.mode == '':
770 return
771 if event.button != 1 or event.inaxes == None:
772 return
773 selax = event.inaxes
774 # this row resolution assumes row panelling
775 srow = self._getrownum(selax)
776 irow = int(srow)
777 if srow:
778 self._selpanels.append(irow)
779 shadow = Rectangle((0,0),1,1,facecolor='0.7',transform=selax.transAxes,visible=True)
780 self._polygons.append(selax.add_patch(shadow))
781 #self.plotter._plotter.show(False)
782 self.plotter._plotter.canvas.draw()
783 asaplog.push("row "+str(irow)+" is selected")
784 ## check for region selection of the spectra and overwrite it.
785 ##!!!! currently disabled for consistency with flag tools !!!!
786 #if self._selregions.has_key(srow):
787 # self._selregions.pop(srow)
788 # msg = "The whole spectrum is selected for row="+srow+". Region selection will be overwritten."
789 # asaplog.push(msg)
790
791 def _getrownum(self,axis):
792 ### returns the row number of selected spectrum as a string ###
793 plabel = axis.get_title()
794 if plabel.startswith("row "):
795 return plabel.strip("row ")
796 return None
797
798 def _any_selection(self):
799 ### returns if users have selected any spectrum or region ###
800 if len(self._selpanels) or len(self._selregions):
801 return True
802 return False
803
804 def _plot_selections(self,regions=None,panels=None):
805 ### mark panels/spectra selections in the page
806 if not self._any_selection() and not (regions or panels):
807 return
808 regions = regions or self._selregions.copy() or {}
809 panels = panels or self._selpanels or []
810 if not isinstance(regions,dict):
811 asaplog.post()
812 asaplog.push("Invalid region specification")
813 asaplog.post('ERROR')
814 if not isinstance(panels,list):
815 asaplog.post()
816 asaplog.push("Invalid panel specification")
817 asaplog.post('ERROR')
818 strow = self._getrownum(self.plotter._plotter.subplots[0]['axes'])
819 enrow = self._getrownum(self.plotter._plotter.subplots[-1]['axes'])
820 for irow in range(int(strow),int(enrow)+1):
821 if regions.has_key(str(irow)):
822 ax = self.plotter._plotter.subplots[irow - int(strow)]['axes']
823 mlist = regions.pop(str(irow))
824 for i in range(len(mlist)):
825 self._polygons.append(ax.axvspan(mlist[i][0],mlist[i][1],
826 facecolor='0.7'))
827 del ax,mlist
828 if irow in panels:
829 ax = self.plotter._plotter.subplots[irow - int(strow)]['axes']
830 shadow = Rectangle((0,0),1,1,facecolor='0.7',
831 transform=ax.transAxes,visible=True)
832 self._polygons.append(ax.add_patch(shadow))
833 del ax,shadow
834 self.plotter._plotter.canvas.draw()
835 del regions,panels,strow,enrow
836
837 def _clear_selection_plot(self, refresh=True):
838 ### clear up polygons which mark selected spectra and regions ###
839 if len(self._polygons) > 0:
840 for shadow in self._polygons:
841 shadow.remove()
842 if refresh: self.plotter._plotter.canvas.draw()
843 self._polygons = []
844
845 def _clearup_selections(self, refresh=True):
846 # clear-up selection and polygons
847 self._selpanels = []
848 self._selregions = {}
849 self._clear_selection_plot(refresh=refresh)
850
851 ### clear up selections
852 def cancel_select(self):
853 self.figmgr.toolbar.set_message('selections canceled')
854 # clear-up selection and polygons
855 self._clearup_selections(refresh=True)
856
857 ### flag selected spectra/regions
858 @asaplog_post_dec
859 def flag(self):
860 if not self._any_selection():
861 msg = "No selection to be Flagged"
862 asaplog.post()
863 asaplog.push(msg)
864 asaplog.post('WARN')
865 return
866 self._pause_buttons(operation="start",msg="Flagging data...")
867 self._flag_operation(rows=self._selpanels,
868 regions=self._selregions,unflag=False)
869 sout = "Flagged:\n"
870 sout += " rows = "+str(self._selpanels)+"\n"
871 sout += " regions: "+str(self._selregions)
872 asaplog.push(sout)
873 del sout
874 self.plotter._ismodified = True
875 self._clearup_selections(refresh=False)
876 self._plot_page(pagemode="current")
877 self._pause_buttons(operation="end")
878
879 ### unflag selected spectra/regions
880 @asaplog_post_dec
881 def unflag(self):
882 if not self._any_selection():
883 msg = "No selection to be Flagged"
884 asaplog.push(msg)
885 asaplog.post('WARN')
886 return
887 self._pause_buttons(operation="start",msg="Unflagging data...")
888 self._flag_operation(rows=self._selpanels,
889 regions=self._selregions,unflag=True)
890 sout = "Unflagged:\n"
891 sout += " rows = "+str(self._selpanels)+"\n"
892 sout += " regions: "+str(self._selregions)
893 asaplog.push(sout)
894 del sout
895 self.plotter._ismodified = True
896 self._clearup_selections(refresh=False)
897 self._plot_page(pagemode="current")
898 self._pause_buttons(operation="end")
899
900 ### actual flag operation
901 @asaplog_post_dec
902 def _flag_operation(self,rows=None,regions=None,unflag=False):
903 scan = self.plotter._data
904 if not scan:
905 asaplog.post()
906 asaplog.push("Invalid scantable")
907 asaplog.post("ERROR")
908 if isinstance(rows,list) and len(rows) > 0:
909 scan.flag_row(rows=rows,unflag=unflag)
910 if isinstance(regions,dict) and len(regions) > 0:
911 for srow, masklist in regions.iteritems():
912 if not isinstance(masklist,list) or len(masklist) ==0:
913 msg = "Ignoring invalid region selection for row = "+srow
914 asaplog.post()
915 asaplog.push(msg)
916 asaplog.post("WARN")
917 continue
918 irow = int(srow)
919 mask = scan.create_mask(masklist,invert=False,row=irow)
920 scan.flag(row=irow,mask=mask,unflag=unflag)
921 del irow, mask
922 del srow, masklist
923 del scan
924
925 ### show statistics of selected spectra/regions
926 @asaplog_post_dec
927 def stat_cal(self):
928 if not self._any_selection():
929 msg = "No selection to be calculated"
930 asaplog.push(msg)
931 asaplog.post('WARN')
932 return
933 self._selected_stats(rows=self._selpanels,regions=self._selregions)
934 self._clearup_selections(refresh=True)
935
936 @asaplog_post_dec
937 def _selected_stats(self,rows=None,regions=None):
938 scan = self.plotter._data
939 if not scan:
940 asaplog.post()
941 asaplog.push("Invalid scantable")
942 asaplog.post("ERROR")
943 mathobj = stmath( rcParams['insitu'] )
944 statval = {}
945 statstr = ['max', 'min', 'mean', 'median', 'sum', 'stddev', 'rms']
946 if isinstance(rows,list) and len(rows) > 0:
947 for irow in rows:
948 for stat in statstr:
949 statval[stat] = mathobj._statsrow(scan,[],stat,irow)[0]
950 self._print_stats(scan,irow,statval,statstr=statstr)
951 del irow
952 if isinstance(regions,dict) and len(regions) > 0:
953 for srow, masklist in regions.iteritems():
954 if not isinstance(masklist,list) or len(masklist) ==0:
955 msg = "Ignoring invalid region selection for row = "+srow
956 asaplog.post()
957 asaplog.push(msg)
958 asaplog.post("WARN")
959 continue
960 irow = int(srow)
961 mask = scan.create_mask(masklist,invert=False,row=irow)
962 for stat in statstr:
963 statval[stat] = mathobj._statsrow(scan,mask,stat,irow)[0]
964 self._print_stats(scan,irow,statval,statstr=statstr,mask=masklist)
965 del irow, mask
966 del srow, masklist
967 del scan, statval, mathobj
968
969 @asaplog_post_dec
970 def _print_stats(self,scan,row,stats,statstr=None,mask=None):
971 if not isinstance(scan, scantable):
972 asaplog.post()
973 asaplog.push("Invalid scantable")
974 asaplog.post("ERROR")
975 if row < 0 or row > scan.nrow():
976 asaplog.post()
977 asaplog.push("Invalid row number")
978 asaplog.post("ERROR")
979 if not isinstance(stats,dict) or len(stats) == 0:
980 asaplog.post()
981 asaplog.push("Invalid statistic value")
982 asaplog.post("ERROR")
983 maskstr = "All"
984 if mask:
985 maskstr = str(mask)
986 ssep = "-"*70+"\n"
987 sout = ssep
988 sout += ("Row=%d Scan=%d IF=%d Pol=%d Time=%s mask=%s" % \
989 (row, scan.getscan(row), scan.getif(row), scan.getpol(row), scan.get_time(row),maskstr))
990 sout += "\n"
991 statvals = []
992 if not len(statstr):
993 statstr = stats.keys()
994 for key in statstr:
995 sout += key.ljust(10)
996 statvals.append(stats.pop(key))
997 sout += "\n"
998 sout += ("%f "*len(statstr) % tuple(statvals))
999 sout += "\n"+ssep
1000 asaplog.push(sout)
1001 del sout, ssep, maskstr, statvals, key, scan, row, stats, statstr, mask
1002
1003 ### Page chages
1004 ### go to the previous page
1005 def prev_page(self):
1006 self._pause_buttons(operation="start",msg='plotting the previous page')
1007 self._clear_selection_plot(refresh=False)
1008 self._plot_page(pagemode="prev")
1009 self._plot_selections()
1010 self._pause_buttons(operation="end")
1011
1012 ### go to the next page
1013 def next_page(self):
1014 self._pause_buttons(operation="start",msg='plotting the next page')
1015 self._clear_selection_plot(refresh=False)
1016 self._plot_page(pagemode="next")
1017 self._plot_selections()
1018 self._pause_buttons(operation="end")
1019
1020 ### actual plotting of the new page
1021 def _plot_page(self,pagemode="next"):
1022 if self.plotter._startrow <= 0:
1023 msg = "The page counter is reset due to chages of plot settings. "
1024 msg += "Plotting from the first page."
1025 asaplog.post()
1026 asaplog.push(msg)
1027 asaplog.post('WARN')
1028 goback = False
1029
1030 self.plotter._plotter.hold()
1031 self.plotter._plotter.legend(1)
1032 self._set_plot_counter(pagemode)
1033 self.plotter._plot(self.plotter._data)
1034 self.set_pagecounter(self._get_pagenum())
1035 self.plotter._plotter.release()
1036 self.plotter._plotter.tidy()
1037 self.plotter._plotter.show(hardrefresh=False)
1038
1039 ### calculate the panel ID and start row to plot a page
1040 #def _set_prevpage_counter(self):
1041 def _set_plot_counter(self, pagemode):
1042 ## page operation should be either "previous", "current", or "next"
1043 availpage = ["p","c","n"]
1044 pageop = pagemode[0].lower()
1045 if not (pageop in availpage):
1046 asaplog.post()
1047 asaplog.push("Invalid page operation")
1048 asaplog.post("ERROR")
1049 if pageop == "n":
1050 # nothing necessary to plot the next page
1051 return
1052 # set row and panel counters to those of the 1st panel of previous page
1053 maxpanel = 16
1054 # the ID of the last panel in current plot
1055 lastpanel = self.plotter._ipanel
1056 # the number of current subplots
1057 currpnum = len(self.plotter._plotter.subplots)
1058
1059 # the nuber of previous subplots
1060 start_ipanel = None
1061 if pageop == "c":
1062 start_ipanel = max(lastpanel-currpnum+1, 0)
1063 else:
1064 ## previous page
1065 prevpnum = None
1066 if self.plotter._rows and self.plotter._cols:
1067 # when user set layout
1068 prevpnum = self.plotter._rows*self.plotter._cols
1069 else:
1070 # no user specification
1071 prevpnum = maxpanel
1072 start_ipanel = max(lastpanel-currpnum-prevpnum+1, 0)
1073 del prevpnum
1074
1075 # set the pannel ID of the last panel of the prev(-prev) page
1076 self.plotter._ipanel = start_ipanel-1
1077 if self.plotter._panelling == 'r':
1078 self.plotter._startrow = start_ipanel
1079 else:
1080 # the start row number of the next panel
1081 self.plotter._startrow = self.plotter._panelrows[start_ipanel]
1082 del lastpanel,currpnum,start_ipanel
1083
1084 ### refresh the page counter
1085 def set_pagecounter(self,page):
1086 nwidth = int(numpy.ceil(numpy.log10(max(page,1))))+1
1087 nwidth = max(nwidth,4)
1088 formatstr = '%'+str(nwidth)+'d'
1089 self.show_pagenum(page,formatstr)
1090
1091 def show_pagenum(self,pagenum,formatstr):
1092 # passed to backend dependent class
1093 pass
1094
1095 def _get_pagenum(self):
1096 maxpanel = 16
1097 # get the ID of last panel in the current page
1098 idlastpanel = self.plotter._ipanel
1099 if self.plotter._rows and self.plotter._cols:
1100 ppp = self.plotter._rows*self.plotter._cols
1101 else:
1102 ppp = maxpanel
1103 return int(idlastpanel/ppp)+1
1104
1105 # pause buttons for slow operations. implemented at a backend dependent class
1106 def _pause_buttons(self,operation="end",msg=""):
1107 pass
Note: See TracBrowser for help on using the repository browser.