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

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 b99a4552 was b99a4552, checked in by Paul Kienzle <pkienzle@…>, 9 years ago

avoid moving qrange bars beyond the edge of the data. Fixes #417

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