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

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 090e07e was 090e07e, checked in by Mathieu Doucet <doucetm@…>, 9 years ago

pylint fixes

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