<commit_before>"""
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation. 

See the license text in license.txt

copyright 2008, University of Tennessee
"""


import wx
import sys, math
import pylab

import danse.common.plottools
from danse.common.plottools.PlotPanel import PlotPanel
from danse.common.plottools.plottables import Graph,Data1D
from sans.guicomm.events import EVT_NEW_PLOT
from sans.guicomm.events import EVT_SLICER_PARS
from sans.guicomm.events import StatusEvent ,NewPlotEvent,SlicerEvent
from sans.guiframe.utils import PanelMenu
from binder import BindArtist
from Plotter1D import ModelPanel1D
(InternalEvent, EVT_INTERNAL)   = wx.lib.newevent.NewEvent()



DEFAULT_QMAX = 0.05
DEFAULT_QSTEP = 0.001
DEFAULT_BEAM = 0.005
BIN_WIDTH = 1.0




class ModelPanel2D( ModelPanel1D):
    """
        Plot panel for use with the GUI manager
    """
    
    ## Internal name for the AUI manager
    window_name = "plotpanel"
    ## Title to appear on top of the window
    window_caption = "Plot Panel"
    ## Flag to tell the GUI manager that this panel is not
    #  tied to any perspective
    ALWAYS_ON = True
    ## Group ID
    group_id = None
    
    
    def __init__(self, parent, id = -1,data2d=None, color = None,\
        dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
        """
            Initialize the panel
        """
        ModelPanel1D.__init__(self, parent, id = id, style = style, **kwargs)
        
        ## Reference to the parent window
        self.parent = parent
        ## Dictionary containing Plottables
        self.plots = {}
        ## Save reference of the current plotted 
        self.data2D = data2d
        ## Unique ID (from gui_manager)
        self.uid = None
        ## Action IDs for internal call-backs
        self.action_ids = {}
        ## Create Artist and bind it
        self.connect = BindArtist(self.subplot.figure)
        ## Beam stop
        self.beamstop_radius = DEFAULT_BEAM
        ## to set the order of lines drawn first.
        self.slicer_z = 5
        ## Reference to the current slicer
        self.slicer = None
        ## event to send slicer info 
        self.Bind(EVT_INTERNAL, self._onEVT_INTERNAL)
        
        self.axes_frozen = False
        ## panel that contains result from slicer motion (ex: Boxsum info)
        self.panel_slicer=None
        ## Graph        
        self.graph = Graph()
        self.graph.xaxis("\\rm{Q}", 'A^{-1}')
        self.graph.yaxis("\\rm{Intensity} ","cm^{-1}")
        self.graph.render(self)
        
        
    def _onEVT_1DREPLOT(self, event):
        """
            Data is ready to be displayed
            
            #TODO: this name should be changed to something more appropriate
            # Don't forget that changing this name will mean changing code
            # in plotting.py
             
            @param event: data event
        """
        ## Update self.data2d with the current plot
        self.data2D = event.plot
        
        #TODO: Check for existence of plot attribute
        
        # Check whether this is a replot. If we ask for a replot
        # and the plottable no longer exists, ignore the event.
        if hasattr(event, "update") and event.update==True \
            and event.plot.name not in self.plots.keys():
            return
        
        if hasattr(event, "reset"):
            self._reset()
        is_new = True
        if event.plot.name in self.plots.keys():
            # Check whether the class of plottable changed
            if not event.plot.__class__==self.plots[event.plot.name].__class__:
                #overwrite a plottable using the same name
                self.graph.delete(self.plots[event.plot.name])
            else:
                # plottable is already draw on the panel
                is_new = False
           
        if is_new:
            # a new plottable overwrites a plotted one  using the same id
            for plottable in self.plots.itervalues():
                if hasattr(event.plot,"id"):
                    if event.plot.id==plottable.id :
                        self.graph.delete(plottable)
            
            self.plots[event.plot.name] = event.plot
            self.graph.add(self.plots[event.plot.name])
        else:
            # Update the plottable with the new data
            
            #TODO: we should have a method to do this, 
            #      something along the lines of:
            #      plottable1.update_data_from_plottable(plottable2)
            
            self.plots[event.plot.name].xmin = event.plot.xmin
            self.plots[event.plot.name].xmax = event.plot.xmax
            self.plots[event.plot.name].ymin = event.plot.ymin
            self.plots[event.plot.name].ymax = event.plot.ymax
            self.plots[event.plot.name].data = event.plot.data
            self.plots[event.plot.name].err_data = event.plot.err_data
            # update qmax with the new xmax of data plotted
            self.qmax= event.plot.xmax
            
        self.slicer= None
        # Check axis labels
        #TODO: Should re-factor this
        ## render the graph with its new content
        self.graph.xaxis(event.plot._xaxis, event.plot._xunit)
        self.graph.yaxis(event.plot._yaxis, event.plot._yunit)
        self.graph.title(self.data2D.name)
        self.graph.render(self)
        self.subplot.figure.canvas.draw_idle()


    def onContextMenu(self, event):
        """
            2D plot context menu
            @param event: wx context event
        """
        
        slicerpop = PanelMenu()
        slicerpop.set_plots(self.plots)
        slicerpop.set_graph(self.graph)
             
        id = wx.NewId()
        slicerpop.Append(id, '&Save image')
        wx.EVT_MENU(self, id, self.onSaveImage)
        
        id = wx.NewId()
        slicerpop.Append(id,'&Print image', 'Print image ')
        wx.EVT_MENU(self, id, self.onPrint)
        
        id = wx.NewId()
        slicerpop.Append(id,'&Print Preview', 'image preview for print')
        wx.EVT_MENU(self, id, self.onPrinterPreview)
        
        slicerpop.AppendSeparator()
        if len(self.data2D.detector) == 1:        
            
            item_list = self.parent.get_context_menu(self.graph)
            if (not item_list==None) and (not len(item_list)==0):
                    
                    for item in item_list:
                        try:
                            id = wx.NewId()
                            slicerpop.Append(id, item[0], item[1])
                            wx.EVT_MENU(self, id, item[2])
                        except:
                            wx.PostEvent(self.parent, StatusEvent(status=\
                            "ModelPanel1D.onContextMenu: bad menu item  %s"%sys.exc_value))
                            pass
                    slicerpop.AppendSeparator()
            
            id = wx.NewId()
            slicerpop.Append(id, '&Perform circular average')
            wx.EVT_MENU(self, id, self.onCircular) 
            
            id = wx.NewId()
            slicerpop.Append(id, '&Sector [Q view]')
            wx.EVT_MENU(self, id, self.onSectorQ) 
            
            id = wx.NewId()
            slicerpop.Append(id, '&Annulus [Phi view ]')
            wx.EVT_MENU(self, id, self.onSectorPhi) <commit_msg>change if statement<commit_after>"""
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation. 

See the license text in license.txt

copyright 2008, University of Tennessee
"""


import wx
import sys, math
import pylab

import danse.common.plottools
from danse.common.plottools.PlotPanel import PlotPanel
from danse.common.plottools.plottables import Graph,Data1D
from sans.guicomm.events import EVT_NEW_PLOT
from sans.guicomm.events import EVT_SLICER_PARS
from sans.guicomm.events import StatusEvent ,NewPlotEvent,SlicerEvent
from sans.guiframe.utils import PanelMenu
from binder import BindArtist
from Plotter1D import ModelPanel1D
(InternalEvent, EVT_INTERNAL)   = wx.lib.newevent.NewEvent()



DEFAULT_QMAX = 0.05
DEFAULT_QSTEP = 0.001
DEFAULT_BEAM = 0.005
BIN_WIDTH = 1.0




class ModelPanel2D( ModelPanel1D):
    """
        Plot panel for use with the GUI manager
    """
    
    ## Internal name for the AUI manager
    window_name = "plotpanel"
    ## Title to appear on top of the window
    window_caption = "Plot Panel"
    ## Flag to tell the GUI manager that this panel is not
    #  tied to any perspective
    ALWAYS_ON = True
    ## Group ID
    group_id = None
    
    
    def __init__(self, parent, id = -1,data2d=None, color = None,\
        dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
        """
            Initialize the panel
        """
        ModelPanel1D.__init__(self, parent, id = id, style = style, **kwargs)
        
        ## Reference to the parent window
        self.parent = parent
        ## Dictionary containing Plottables
        self.plots = {}
        ## Save reference of the current plotted 
        self.data2D = data2d
        ## Unique ID (from gui_manager)
        self.uid = None
        ## Action IDs for internal call-backs
        self.action_ids = {}
        ## Create Artist and bind it
        self.connect = BindArtist(self.subplot.figure)
        ## Beam stop
        self.beamstop_radius = DEFAULT_BEAM
        ## to set the order of lines drawn first.
        self.slicer_z = 5
        ## Reference to the current slicer
        self.slicer = None
        ## event to send slicer info 
        self.Bind(EVT_INTERNAL, self._onEVT_INTERNAL)
        
        self.axes_frozen = False
        ## panel that contains result from slicer motion (ex: Boxsum info)
        self.panel_slicer=None
        ## Graph        
        self.graph = Graph()
        self.graph.xaxis("\\rm{Q}", 'A^{-1}')
        self.graph.yaxis("\\rm{Intensity} ","cm^{-1}")
        self.graph.render(self)
        
        
    def _onEVT_1DREPLOT(self, event):
        """
            Data is ready to be displayed
            
            #TODO: this name should be changed to something more appropriate
            # Don't forget that changing this name will mean changing code
            # in plotting.py
             
            @param event: data event
        """
        ## Update self.data2d with the current plot
        self.data2D = event.plot
        
        #TODO: Check for existence of plot attribute
        
        # Check whether this is a replot. If we ask for a replot
        # and the plottable no longer exists, ignore the event.
        if hasattr(event, "update") and event.update==True \
            and event.plot.name not in self.plots.keys():
            return
        
        if hasattr(event, "reset"):
            self._reset()
        is_new = True
        if event.plot.name in self.plots.keys():
            # Check whether the class of plottable changed
            if not event.plot.__class__==self.plots[event.plot.name].__class__:
                #overwrite a plottable using the same name
                self.graph.delete(self.plots[event.plot.name])
            else:
                # plottable is already draw on the panel
                is_new = False
           
        if is_new:
            # a new plottable overwrites a plotted one  using the same id
            for plottable in self.plots.itervalues():
                if hasattr(event.plot,"id"):
                    if event.plot.id==plottable.id :
                        self.graph.delete(plottable)
            
            self.plots[event.plot.name] = event.plot
            self.graph.add(self.plots[event.plot.name])
        else:
            # Update the plottable with the new data
            
            #TODO: we should have a method to do this, 
            #      something along the lines of:
            #      plottable1.update_data_from_plottable(plottable2)
            
            self.plots[event.plot.name].xmin = event.plot.xmin
            self.plots[event.plot.name].xmax = event.plot.xmax
            self.plots[event.plot.name].ymin = event.plot.ymin
            self.plots[event.plot.name].ymax = event.plot.ymax
            self.plots[event.plot.name].data = event.plot.data
            self.plots[event.plot.name].err_data = event.plot.err_data
            # update qmax with the new xmax of data plotted
            self.qmax= event.plot.xmax
            
        self.slicer= None
        # Check axis labels
        #TODO: Should re-factor this
        ## render the graph with its new content
        self.graph.xaxis(event.plot._xaxis, event.plot._xunit)
        self.graph.yaxis(event.plot._yaxis, event.plot._yunit)
        self.graph.title(self.data2D.name)
        self.graph.render(self)
        self.subplot.figure.canvas.draw_idle()


    def onContextMenu(self, event):
        """
            2D plot context menu
            @param event: wx context event
        """
        
        slicerpop = PanelMenu()
        slicerpop.set_plots(self.plots)
        slicerpop.set_graph(self.graph)
             
        id = wx.NewId()
        slicerpop.Append(id, '&Save image')
        wx.EVT_MENU(self, id, self.onSaveImage)
        
        id = wx.NewId()
        slicerpop.Append(id,'&Print image', 'Print image ')
        wx.EVT_MENU(self, id, self.onPrint)
        
        id = wx.NewId()
        slicerpop.Append(id,'&Print Preview', 'image preview for print')
        wx.EVT_MENU(self, id, self.onPrinterPreview)
        
        slicerpop.AppendSeparator()
        if len(self.data2D.detector) >0 :        
            
            item_list = self.parent.get_context_menu(self.graph)
            if (not item_list==None) and (not len(item_list)==0):
                    
                    for item in item_list:
                        try:
                            id = wx.NewId()
                            slicerpop.Append(id, item[0], item[1])
                            wx.EVT_MENU(self, id, item[2])
                        except:
                            wx.PostEvent(self.parent, StatusEvent(status=\
                            "ModelPanel1D.onContextMenu: bad menu item  %s"%sys.exc_value))
                            pass
                    slicerpop.AppendSeparator()
            
            id = wx.NewId()
            slicerpop.Append(id, '&Perform circular average')
            wx.EVT_MENU(self, id, self.onCircular) 
            
            id = wx.NewId()
            slicerpop.Append(id, '&Sector [Q view]')
            wx.EVT_MENU(self, id, self.onSectorQ) 
            
            id = wx.NewId()
            slicerpop.Append(id, '&Annulus [Phi view ]')
            wx.EVT_MENU(self, id, self.onSectorPhi) 
{'fraction_non_alphanumeric': 0.08892001867787339, 'fraction_numerical': 0.0058701887799346274, 'mean_word_length': 1.7584176632934683, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4816910', 'n_tokens_mistral': 4469, 'n_tokens_neox': 4347, 'n_words': 1150}