source: sasview/src/sas/guiframe/local_perspectives/plotting/Plotter1D.py @ 79492222

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 79492222 was 79492222, checked in by krzywon, 9 years ago

Changed the file and folder names to remove all SANS references.

  • Property mode set to 100644
File size: 31.4 KB
Line 
1
2################################################################################
3#This software was developed by the University of Tennessee as part of the
4#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
5#project funded by the US National Science Foundation.
6#
7#See the license text in license.txt
8#
9#copyright 2008, University of Tennessee
10################################################################################
11
12
13import wx
14import sys
15import math
16import numpy
17
18from sas.plottools.PlotPanel import PlotPanel
19from sas.guiframe.events import StatusEvent
20from sas.guiframe.events import PanelOnFocusEvent
21from sas.guiframe.utils import PanelMenu
22from sas.guiframe.panel_base import PanelBase
23from sas.guiframe.gui_style import GUIFRAME_ICON
24from appearanceDialog import appearanceDialog
25from graphAppearance import graphAppearance
26
27DEFAULT_QMAX = 0.05
28DEFAULT_QSTEP = 0.001
29DEFAULT_BEAM = 0.005
30BIN_WIDTH = 1
31IS_MAC = (sys.platform == 'darwin')
32
33
34def find_key(dic, val):
35    """return the key of dictionary dic given the value"""
36    return [k for k, v in dic.iteritems() if v == val][0]
37
38
39
40class ModelPanel1D(PlotPanel, PanelBase):
41    """
42    Plot panel for use with the GUI manager
43    """
44   
45    ## Internal name for the AUI manager
46    window_name = "plotpanel"
47    ## Title to appear on top of the window
48    window_caption = "Graph"
49    ## Flag to tell the GUI manager that this panel is not
50    #  tied to any perspective
51    ALWAYS_ON = True
52    ## Group ID
53    group_id = None
54   
55    def __init__(self, parent, id=-1, color = None,
56                 dpi=None, style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
57        PlotPanel.__init__(self, parent, id=id, style=style, **kwargs)
58        PanelBase.__init__(self, parent)
59        ## Reference to the parent window
60        self.parent = parent
61        if hasattr(parent, "parent"):
62            self.parent = self.parent.parent
63        ## Plottables
64        self.plots = {}
65        self.frame = None
66        #context menu
67        self._slicerpop = None
68       
69        self._available_data = []
70        self._menu_add_ids = []
71        self._symbol_labels = self.get_symbol_label()
72        self._color_labels = self.get_color_label()
73        self.currColorIndex = ""
74        self._is_changed_legend_label = False
75        self.is_xtick = False
76        self.is_ytick = False
77     
78        self.hide_menu = None
79        ## Unique ID (from gui_manager)
80        self.uid = None
81        self.x_size = None
82        ## Default locations
83        #self._default_save_location = os.getcwd()
84        self.size = None 
85        self.vl_ind = 0     
86        ## Graph       
87        #self.graph = Graph()
88        self.graph.xaxis("\\rm{Q}", 'A^{-1}')
89        self.graph.yaxis("\\rm{Intensity} ", "cm^{-1}")
90        self.graph.render(self)
91        self.cursor_id = None
92       
93        # In resizing event
94        self.resizing = False
95        self.canvas.set_resizing(self.resizing)
96        self.Bind(wx.EVT_SIZE, self._OnReSize)
97        self._add_more_tool()
98        self.parent.SetFocus()
99       
100       
101    def get_symbol_label(self):
102        """
103        Associates label to symbol
104        """
105        _labels = {}
106        i = 0
107        _labels['Circle'] = i
108        i += 1
109        _labels['Cross X '] = i
110        i += 1
111        _labels['Triangle Down'] = i
112        i += 1
113        _labels['Triangle Up'] = i
114        i += 1
115        _labels['Triangle Left'] = i
116        i += 1
117        _labels['Triangle Right'] = i
118        i += 1
119        _labels['Cross +'] = i
120        i += 1
121        _labels['Square'] = i
122        i += 1
123        _labels['diamond'] = i
124        i += 1
125        _labels['Diamond'] = i
126        i += 1
127        _labels['Hexagon1'] = i
128        i += 1
129        _labels['Hexagon2'] = i
130        i += 1
131        _labels['Pentagon'] = i
132        i += 1
133        _labels['Line'] = i
134        i += 1
135        _labels['Dash'] = i
136        i += 1
137        _labels['Vline'] = i
138        i += 1
139        _labels['Step'] = i
140        return _labels
141   
142    def get_color_label(self):
143        """
144        Associates label to a specific color
145        """
146        _labels = {}
147        i = 0
148        _labels['Blue'] = i
149        i += 1
150        _labels['Green'] = i
151        i += 1
152        _labels['Red'] = i
153        i += 1
154        _labels['Cyan'] = i
155        i += 1
156        _labels['Magenta'] = i
157        i += 1
158        _labels['Yellow'] = i
159        i += 1
160        _labels['Black'] = i
161        return _labels
162
163   
164    def set_data(self, list=None):
165        """
166        """
167        pass
168   
169    def _reset(self):
170        """
171        Resets internal data and graph
172        """   
173        self.graph.reset()
174        self.plots      = {}
175        self.is_zoomed = False
176       
177    def _OnReSize(self, event):   
178        """
179        On response of the resize of a panel, set axes_visiable False
180        """
181        # It was found that wx >= 2.9.3 sends an event even if no size changed.
182        # So manually recode the size (=x_size) and compare here.
183        # Massy code to work around:<
184        if self.parent._mgr != None:
185            max_panel = self.parent._mgr.GetPane(self)
186            if max_panel.IsMaximized():
187                self.parent._mgr.RestorePane(max_panel)
188                max_panel.Maximize()
189        if self.x_size != None:
190            if self.x_size == self.GetSize():
191                self.resizing = False
192                self.canvas.set_resizing(self.resizing)
193                return
194        self.x_size = self.GetSize()
195
196        # Ready for another event
197        # Do not remove this Skip. Otherwise it will get runtime error on wx>=2.9.
198        event.Skip() 
199        # set the resizing flag
200        self.resizing = True
201        self.canvas.set_resizing(self.resizing)
202        self.parent.set_schedule(True)
203        pos_x, pos_y = self.GetPositionTuple()
204        if pos_x != 0 and pos_y != 0:
205            self.size, _ = self.GetClientSizeTuple()
206        self.SetSizer(self.sizer)
207        wx.CallAfter(self.parent.disable_app_menu,self)
208       
209    def on_plot_qrange(self, event=None):
210        """
211        On Qmin Qmax vertical line event
212        """
213        if event == None:
214            return
215        event.Skip() 
216        active_ctrl = event.active
217        if active_ctrl == None:
218            return
219        if event.id in self.plots.keys():
220            # Set line position and color
221            colors = ['red', 'purple']
222            self.cursor_id = event.id
223            ctrl = event.ctrl
224            if self.ly == None:
225                self.ly = []
226                for ind_ly in range(len(colors)):
227                    self.ly.append(self.subplot.axvline(color=colors[ind_ly], 
228                                                        lw=2.5, alpha=0.7))
229                    self.ly[ind_ly].set_rasterized(True)     
230            try:
231                # Display x,y in the status bar if possible
232                xval = float(active_ctrl.GetValue())
233                position = self.get_data_xy_vals(xval)
234                if position != None:
235                    wx.PostEvent(self.parent, StatusEvent(status=position))
236            except:
237                pass
238            if not event.leftdown:
239                # text event
240                try:
241                    is_moved = False
242                    for idx in range(len(self.ly)):
243                        val = float(ctrl[idx].GetValue())
244                        # check if vline moved
245                        if self.ly[idx].get_xdata() != val:
246                            self.ly[idx].set_xdata(val)
247                            is_moved = True
248                    if is_moved:
249                        self.canvas.draw() 
250                except:
251                    pass
252                event.Skip() 
253                return
254            self.q_ctrl = ctrl
255            try:
256                pos_x_min = float(self.q_ctrl[0].GetValue())
257            except:
258                pos_x_min = xmin
259            try:
260                pos_x_max = float(self.q_ctrl[1].GetValue())
261            except:
262                pos_x_max = xmax
263            pos_x = [pos_x_min, pos_x_max]
264            for ind_ly in range(len(colors)):
265                self.ly[ind_ly].set_color(colors[ind_ly])
266                self.ly[ind_ly].set_xdata(pos_x[ind_ly])
267            self.canvas.draw()
268        else:
269            self.q_ctrl = None
270   
271    def get_data_xy_vals(self, xval):
272        """
273        Get x, y data values near x = x_val
274        """
275        try:
276            x_data = self.plots[self.cursor_id].x
277            y_data = self.plots[self.cursor_id].y
278            indx = self._find_nearest(x_data, xval)
279            pos_x = x_data[indx]
280            pos_y = y_data[indx]
281            position = str(pos_x), str(pos_y)
282            return position
283        except:
284            return None
285           
286    def _find_nearest(self, array, value):
287        """
288        Find and return the nearest value in array to the value.
289        Used in cusor_line()
290        :Param array: numpy array
291        :Param value: float
292        """
293        idx = (numpy.abs(array - value)).argmin()
294        return int(idx)#array.flat[idx]
295   
296    def _check_line_positions(self, pos_x=None, nop=None):
297        """
298        Check vertical line positions
299        :Param pos_x: position of the current line [float]
300        :Param nop: number of plots [int]
301        """
302        ly = self.ly
303        ly0x = ly[0].get_xdata()
304        ly1x = ly[1].get_xdata()
305        self.q_ctrl[0].SetBackgroundColour('white')
306        self.q_ctrl[1].SetBackgroundColour('white')
307        if ly0x >= ly1x:
308            if self.vl_ind == 0:
309                ly[1].set_xdata(pos_x)
310                ly[1].set_zorder(nop)
311                self.q_ctrl[1].SetValue(str(pos_x))
312                self.q_ctrl[0].SetBackgroundColour('pink')
313            elif self.vl_ind == 1:
314                ly[0].set_xdata(pos_x)
315                ly[0].set_zorder(nop)
316                self.q_ctrl[0].SetValue(str(pos_x))
317                self.q_ctrl[1].SetBackgroundColour('pink')
318               
319    def _get_cusor_lines(self, event):
320        """
321        Revmove or switch cursor line if drawn
322        :Param event: LeftClick mouse event
323        """ 
324        ax = event.inaxes
325        if hasattr(event, "action"):
326            dclick = event.action == 'dclick'
327            if ax == None or dclick:
328                # remove the vline
329                self._check_zoom_plot()
330                self.canvas.draw()
331                self.q_ctrl = None
332                return 
333        if self.ly != None and event.xdata != None:
334            # Selecting a new line if cursor lines are displayed already
335            dqmin = math.fabs(event.xdata - self.ly[0].get_xdata())
336            dqmax = math.fabs(event.xdata - self.ly[1].get_xdata())
337            is_qmax = dqmin > dqmax
338            if is_qmax:
339                self.vl_ind = 1
340            else:
341                self.vl_ind = 0 
342                     
343    def cusor_line(self, event):
344        """
345        Move the cursor line to write Q range
346        """
347        if self.q_ctrl == None:
348            return
349        #release a q range vline
350        if self.ly != None and not self.leftdown:
351            for ly in self.ly:
352                ly.set_alpha(0.7)
353                self.canvas.draw()
354            return
355        ax = event.inaxes
356        if ax == None or not hasattr(event, 'action'):
357            return
358        end_drag = event.action != 'drag' and event.xdata != None
359        nop = len(self.plots)
360        pos_x, pos_y = float(event.xdata), float(event.ydata)
361        try:
362            ly = self.ly
363            ly0x = ly[0].get_xdata()
364            ly1x = ly[1].get_xdata()
365            if ly0x == ly1x:
366                if ly[0].get_zorder() > ly[1].get_zorder():
367                    self.vl_ind = 0
368                else:
369                    self.vl_ind = 1
370            vl_ind = self.vl_ind
371            x_data = self.plots[self.cursor_id].x
372            y_data = self.plots[self.cursor_id].y
373            xmin = x_data.min()
374            xmax = x_data.max()
375            indx = self._find_nearest(x_data, pos_x)
376            #pos_x = self._find_nearest(x_data, pos_x)
377            #indx = int(numpy.searchsorted(x_data, [pos_x])[0])
378            # Need to hold LeftButton to drag
379            if end_drag:
380                if event.button:
381                    self._check_line_positions(pos_x, nop)
382                return   
383            if indx >= len(x_data):
384                indx = len(x_data) - 1
385            pos_x = x_data[indx]
386            pos_y = y_data[indx]
387            if xmin == ly1x:
388                vl_ind = 1
389            elif xmax == ly0x:
390                vl_ind = 0
391            else:
392                ly[vl_ind].set_xdata(pos_x)
393                ly[vl_ind].set_zorder(nop + 1)
394                self._check_line_positions(pos_x, nop)
395            ly[vl_ind].set_xdata(pos_x)
396            ly[vl_ind].set_alpha(1.0)
397            ly[vl_ind].set_zorder(nop + 1)
398            self.canvas.draw()
399            self.q_ctrl[vl_ind].SetValue(str(pos_x))
400        except:
401            pass
402               
403    def set_resizing(self, resizing=False):
404        """
405        Set the resizing (True/False)
406        """
407        self.resizing = resizing
408        #self.canvas.set_resizing(resizing)
409   
410    def schedule_full_draw(self, func='append'):   
411        """
412        Put self in schedule to full redraw list
413        """
414        # append/del this panel in the schedule list
415        self.parent.set_schedule_full_draw(self, func)
416       
417
418    def remove_data_by_id(self, id):
419        """
420            Remove data from plot
421        """
422        if id in self.plots.keys():
423            data =  self.plots[id]
424            self.graph.delete(data)
425            data_manager = self._manager.parent.get_data_manager()
426            data_list, theory_list = data_manager.get_by_id(id_list=[id])
427           
428            if id in data_list.keys():
429                data = data_list[id]
430            if id in theory_list.keys():
431                data = theory_list[id]
432               
433            del self.plots[id]
434            self.graph.render(self)
435            self.subplot.figure.canvas.draw_idle()   
436            if len(self.graph.plottables) == 0:
437                #onRemove: graph is empty must be the panel must be destroyed
438                self.parent.delete_panel(self.uid)
439       
440    def plot_data(self, data):
441        """
442        Data is ready to be displayed
443       
444        :param event: data event
445        """
446        if data.__class__.__name__ == 'Data2D':
447            return
448        plot_keys = self.plots.keys()
449        if data.id in plot_keys:
450            #Recover panel prop.s
451            xlo, xhi = self.subplot.get_xlim()
452            ylo, yhi = self.subplot.get_ylim()
453            old_data = self.plots[data.id]
454            if self._is_changed_legend_label:
455                data.label = old_data.label
456            if old_data.__class__.__name__ == 'Data1D':
457                data.custom_color = old_data.custom_color
458                data.symbol = old_data.symbol
459                data.markersize = old_data.markersize
460                data.zorder = len(plot_keys)
461            # Replace data
462            self.graph.replace(data)
463            self.plots[data.id] = data
464            ## Set the view scale for all plots
465            try:
466                self._onEVT_FUNC_PROPERTY()
467            except Exception, exc:
468                wx.PostEvent(self.parent, StatusEvent(status=\
469                    "Plotting Error: %s"% str(exc), info="error"))
470            if self.is_zoomed:
471                # Recover the x,y limits
472                self.subplot.set_xlim((xlo, xhi))     
473                self.subplot.set_ylim((ylo, yhi)) 
474        else:
475            self.plots[data.id] = data
476            self.graph.add(self.plots[data.id]) 
477            data.zorder = len(plot_keys)
478            ## Set the view scale for all plots
479            try:
480                self._onEVT_FUNC_PROPERTY()
481                if IS_MAC:
482                    # MAC: forcing to plot 2D avg
483                    self.canvas._onDrawIdle()
484            except Exception,exc:
485                wx.PostEvent(self.parent, StatusEvent(status=\
486                    "Plotting Error: %s"% str(exc), info="error"))
487            self.toolbar.update()
488            self.is_zoomed = False
489           
490    def draw_plot(self):
491        """
492        Draw plot
493        """
494        self.draw() 
495
496    def onLeftDown(self,event): 
497        """
498        left button down and ready to drag
499        Display the position of the mouse on the statusbar
500        """
501        #self.parent.set_plot_unfocus()
502        self._get_cusor_lines(event)
503        ax = event.inaxes
504        PlotPanel.onLeftDown(self, event)
505        if ax != None:
506            try:
507                pos_x = float(event.xdata)# / size_x
508                pos_y = float(event.ydata)# / size_y
509                pos_x = "%8.3g"% pos_x
510                pos_y = "%8.3g"% pos_y
511                self.position = str(pos_x), str(pos_y)
512                wx.PostEvent(self.parent, StatusEvent(status=self.position))
513            except:
514                self.position = None 
515        # unfocus all
516        self.parent.set_plot_unfocus() 
517        #post nd event to notify guiframe that this panel is on focus
518        wx.PostEvent(self.parent, PanelOnFocusEvent(panel=self))
519
520       
521    def _ontoggle_hide_error(self, event):
522        """
523        Toggle error display to hide or show
524        """
525        menu = event.GetEventObject()
526        id = event.GetId()
527        self.set_selected_from_menu(menu, id)
528        # Check zoom
529        xlo, xhi = self.subplot.get_xlim()
530        ylo, yhi = self.subplot.get_ylim()
531
532        selected_plot = self.plots[self.graph.selected_plottable]
533        if self.hide_menu.GetText() == "Hide Error Bar":
534            selected_plot.hide_error = True
535        else:
536            selected_plot.hide_error = False
537        ## increment graph color
538        self.graph.render(self)
539        self.subplot.figure.canvas.draw_idle() 
540        if self.is_zoomed:
541            # Recover the x,y limits
542            self.subplot.set_xlim((xlo, xhi))     
543            self.subplot.set_ylim((ylo, yhi)) 
544
545         
546    def _onRemove(self, event):
547        """
548        Remove a plottable from the graph and render the graph
549       
550        :param event: Menu event
551       
552        """
553        menu = event.GetEventObject()
554        id = event.GetId()
555        self.set_selected_from_menu(menu, id)
556        ## Check if there is a selected graph to remove
557        if self.graph.selected_plottable in self.plots.keys():
558            selected_plot = self.plots[self.graph.selected_plottable]
559            id = self.graph.selected_plottable
560            self.remove_data_by_id(id)
561           
562    def onContextMenu(self, event):
563        """
564        1D plot context menu
565       
566        :param event: wx context event
567       
568        """
569        self._slicerpop = PanelMenu()
570        self._slicerpop.set_plots(self.plots)
571        self._slicerpop.set_graph(self.graph)   
572        if not self.graph.selected_plottable in self.plots: 
573            # Various plot options
574            id = wx.NewId()
575            self._slicerpop.Append(id, '&Save Image', 'Save image as PNG')
576            wx.EVT_MENU(self, id, self.onSaveImage)
577            id = wx.NewId()
578            self._slicerpop.Append(id, '&Print Image', 'Print image ')
579            wx.EVT_MENU(self, id, self.onPrint)
580            id = wx.NewId()
581            self._slicerpop.Append(id, '&Print Preview', 'Print preview')
582            wx.EVT_MENU(self, id, self.onPrinterPreview)
583           
584            id = wx.NewId()
585            self._slicerpop.Append(id, '&Copy to Clipboard', 
586                                   'Copy to the clipboard')
587            wx.EVT_MENU(self, id, self.OnCopyFigureMenu)
588                   
589            self._slicerpop.AppendSeparator()
590
591        for plot in self.plots.values():
592            #title = plot.title
593            name = plot.name
594            plot_menu = wx.Menu()
595            if self.graph.selected_plottable:
596                if not self.graph.selected_plottable in self.plots.keys():
597                    continue
598                if plot != self.plots[self.graph.selected_plottable]:
599                    continue
600               
601            id = wx.NewId()
602            plot_menu.Append(id, "&DataInfo", name)
603            wx.EVT_MENU(self, id, self. _onDataShow)
604            id = wx.NewId()
605            plot_menu.Append(id, "&Save Points as a File", name)
606            wx.EVT_MENU(self, id, self._onSave)
607            plot_menu.AppendSeparator()
608           
609            #add menu of other plugins
610            item_list = self.parent.get_current_context_menu(self)
611             
612            if (not item_list == None) and (not len(item_list) == 0):
613                for item in item_list:
614
615                    try:
616                        id = wx.NewId()
617                        plot_menu.Append(id, item[0], name)
618                        wx.EVT_MENU(self, id, item[2])
619                    except:
620                        msg = "ModelPanel1D.onContextMenu: "
621                        msg += "bad menu item  %s" % sys.exc_value
622                        wx.PostEvent(self.parent, StatusEvent(status=msg))
623                        pass
624                plot_menu.AppendSeparator()
625           
626            if self.parent.ClassName.count('wxDialog') == 0: 
627                id = wx.NewId()
628                plot_menu.Append(id, '&Linear Fit', name)
629                wx.EVT_MENU(self, id, self.onFitting)
630                plot_menu.AppendSeparator()
631   
632                id = wx.NewId()
633                plot_menu.Append(id, "Remove", name)
634                wx.EVT_MENU(self, id, self._onRemove)
635                if not plot.is_data:
636                    id = wx.NewId()
637                    plot_menu.Append(id, '&Freeze', name)
638                    wx.EVT_MENU(self, id, self.onFreeze)
639                plot_menu.AppendSeparator()   
640                symbol_menu = wx.Menu()
641               
642                if plot.is_data:
643                    id = wx.NewId()
644                    self.hide_menu = plot_menu.Append(id, 
645                                                    "Hide Error Bar", name)
646       
647                    if plot.dy is not None and plot.dy != []:
648                        if plot.hide_error :
649                            self.hide_menu.SetText('Show Error Bar')
650                        else:
651                            self.hide_menu.SetText('Hide Error Bar')
652                    else:
653                        self.hide_menu.Enable(False)
654                    wx.EVT_MENU(self, id, self._ontoggle_hide_error)
655               
656                    plot_menu.AppendSeparator()
657
658                id = wx.NewId()
659                plot_menu.Append(id, '&Modify Plot Property', name)
660                wx.EVT_MENU(self, id, self.createAppDialog)
661
662
663
664            id = wx.NewId()
665            #plot_menu.SetTitle(name)
666            self._slicerpop.AppendMenu(id, '&%s'% name, plot_menu)
667            # Option to hide
668            #TODO: implement functionality to hide a plottable (legend click)
669        if not self.graph.selected_plottable in self.plots: 
670            self._slicerpop.AppendSeparator()
671            loc_menu = wx.Menu()
672            for label in self._loc_labels:
673                id = wx.NewId()
674                loc_menu.Append(id, str(label), str(label))
675                wx.EVT_MENU(self, id, self.onChangeLegendLoc)
676           
677            id = wx.NewId()
678            self._slicerpop.Append(id, '&Modify Graph Appearance',
679                                   'Modify graph appearance')
680            wx.EVT_MENU(self, id, self.modifyGraphAppearance)
681            self._slicerpop.AppendSeparator()
682
683           
684            if self.position != None:
685                id = wx.NewId()
686                self._slicerpop.Append(id, '&Add Text')
687                wx.EVT_MENU(self, id, self._on_addtext)
688                id = wx.NewId()
689                self._slicerpop.Append(id, '&Remove Text')
690                wx.EVT_MENU(self, id, self._on_removetext)
691                self._slicerpop.AppendSeparator()
692            id = wx.NewId()
693            self._slicerpop.Append(id, '&Change Scale')
694            wx.EVT_MENU(self, id, self._onProperties)
695            self._slicerpop.AppendSeparator()
696            id = wx.NewId()
697            self._slicerpop.Append(id, '&Reset Graph Range')
698            wx.EVT_MENU(self, id, self.onResetGraph) 
699           
700            if self.parent.ClassName.count('wxDialog') == 0:   
701                self._slicerpop.AppendSeparator()
702                id = wx.NewId()
703                self._slicerpop.Append(id, '&Window Title')
704                wx.EVT_MENU(self, id, self.onChangeCaption)
705        try:
706            pos_evt = event.GetPosition()
707            pos = self.ScreenToClient(pos_evt)
708        except:
709            pos_x, pos_y = self.toolbar.GetPositionTuple()
710            pos = (pos_x, pos_y + 5)
711        self.PopupMenu(self._slicerpop, pos)
712           
713    def onFreeze(self, event):
714        """
715        on Freeze data
716        """
717        menu = event.GetEventObject()
718        id = event.GetId()
719        self.set_selected_from_menu(menu, id)
720        plot = self.plots[self.graph.selected_plottable]
721        self.parent.onfreeze([plot.id])
722       
723                       
724    def _onSave(self, evt):
725        """
726        Save a data set to a text file
727       
728        :param evt: Menu event
729       
730        """
731        menu = evt.GetEventObject()
732        id = evt.GetId()
733        self.set_selected_from_menu(menu, id)
734        data = self.plots[self.graph.selected_plottable]
735        default_name = data.label
736        if default_name.count('.') > 0:
737            default_name = default_name.split('.')[0]
738        default_name += "_out"
739        if self.parent != None:
740            self.parent.save_data1d(data, default_name)
741
742                       
743    def _onDataShow(self, evt):
744        """
745        Show the data set in text
746       
747        :param evt: Menu event
748       
749        """
750        menu = evt.GetEventObject()
751        id = evt.GetId()
752        self.set_selected_from_menu(menu, id)
753        data = self.plots[self.graph.selected_plottable]
754        default_name = data.label
755        if default_name.count('.') > 0:
756            default_name = default_name.split('.')[0]
757        #default_name += "_out"
758        if self.parent != None:
759            self.parent.show_data1d(data, default_name)
760           
761    def _add_more_tool(self):
762        """
763        Add refresh, add/hide button in the tool bar
764        """
765        return
766        if self.parent.__class__.__name__ != 'ViewerFrame':
767            return
768        self.toolbar.AddSeparator()
769        id_hide = wx.NewId()
770        hide = wx.Bitmap(GUIFRAME_ICON.HIDE_ID_PATH, wx.BITMAP_TYPE_PNG)
771        self.toolbar.AddSimpleTool(id_hide, hide, 'Hide', 'Hide')
772        self.toolbar.Realize()
773        wx.EVT_TOOL(self, id_hide,  self._on_hide)
774       
775    def _on_hide(self, event):
776        """
777        Hides the plot when button is pressed
778        """     
779        if self.parent is not None:
780            self.parent.hide_panel(self.uid)
781
782    def on_close(self, event):
783        """
784        On Close Event
785        """
786        ID = self.uid
787        self.parent.delete_panel(ID)
788   
789    def createAppDialog(self, event):
790        """
791        Create the custom dialog for fit appearance modification
792        """
793        menu = event.GetEventObject()
794        id = event.GetId()
795        self.set_selected_from_menu(menu, id)
796        self.appearance_selected_plot = \
797                        self.plots[self.graph.selected_plottable]
798        # find current properties
799        curr_color = self.appearance_selected_plot.custom_color
800        curr_symbol = self.appearance_selected_plot.symbol
801        curr_size = self.appearance_selected_plot.markersize
802        curr_label = self.appearance_selected_plot.label
803
804        if curr_color == None:
805            curr_color = self._color_labels['Blue']
806            curr_symbol = 13
807
808        self.appD = appearanceDialog(self, 'Modify Plot Property')
809        icon = self.parent.GetIcon()
810        self.appD.SetIcon(icon)
811        self.appD.set_defaults(float(curr_size), int(curr_color), 
812                    str(appearanceDialog.find_key(self.get_symbol_label(), 
813                    int(curr_symbol))), curr_label)
814        self.appD.Bind(wx.EVT_CLOSE, self.on_AppDialog_close)   
815
816    def on_AppDialog_close(self, event):
817        """
818        on_Modify Plot Property_close
819        """
820        if(self.appD.okay_clicked == True):
821            # returns (size,color,symbol,datalabel)
822            info = self.appD.get_current_values() 
823            self.appearance_selected_plot.custom_color = \
824                        self._color_labels[info[1].encode('ascii', 'ignore')]
825
826            self.appearance_selected_plot.markersize = float(info[0])
827            self.appearance_selected_plot.symbol = \
828                        self.get_symbol_label()[info[2]] 
829            self.appearance_selected_plot.label = str(info[3])
830        self.appD.Destroy()
831        self._check_zoom_plot()
832
833    def modifyGraphAppearance(self, event):
834        """
835        On Modify Graph Appearance
836        """
837        self.graphApp = graphAppearance(self, 'Modify Graph Appearance')
838        icon = self.parent.GetIcon()
839        self.graphApp.SetIcon(icon)
840        self.graphApp.setDefaults(self.grid_on, self.legend_on, 
841                                  self.xaxis_label, self.yaxis_label, 
842                                  self.xaxis_unit, self.yaxis_unit, 
843                                  self.xaxis_font, self.yaxis_font, 
844                                  find_key(self.get_loc_label(), 
845                                  self.legendLoc), 
846                                  self.xcolor, self.ycolor, 
847                                  self.is_xtick, self.is_ytick)
848        self.graphApp.Bind(wx.EVT_CLOSE, self.on_graphApp_close)
849
850    def on_graphApp_close(self, event):
851        """
852        Gets values from graph appearance dialog and sends them off
853        to modify the plot
854        """
855        graph_app = self.graphApp
856        toggle_grid = graph_app.get_togglegrid()
857        legend_loc = graph_app.get_legend_loc()
858        toggle_legend = graph_app.get_togglelegend()
859       
860        self.onGridOnOff(toggle_grid )
861        self.ChangeLegendLoc(legend_loc)
862        self.onLegend(toggle_legend)
863
864        self.xaxis_label = graph_app.get_xlab()
865        self.yaxis_label = graph_app.get_ylab()
866        self.xaxis_unit = graph_app.get_xunit()
867        self.yaxis_unit = graph_app.get_yunit()
868        self.xaxis_font = graph_app.get_xfont()
869        self.yaxis_font = graph_app.get_yfont()
870        self.is_xtick =  graph_app.get_xtick_check()
871        self.is_ytick =  graph_app.get_ytick_check()
872        if self.is_xtick:
873            self.xaxis_tick = self.xaxis_font
874        if self.is_ytick:
875            self.yaxis_tick = self.yaxis_font
876
877        self.xaxis(self.xaxis_label, self.xaxis_unit, 
878                   graph_app.get_xfont(), graph_app.get_xcolor(), 
879                   self.xaxis_tick)
880        self.yaxis(self.yaxis_label, self.yaxis_unit, 
881                   graph_app.get_yfont(), graph_app.get_ycolor(),
882                   self.yaxis_tick)
883
884        graph_app.Destroy()
Note: See TracBrowser for help on using the repository browser.