source: sasview/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_slicer.py @ 982577b

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 982577b was 982577b, checked in by krzywon, 7 years ago

File from the box loaded. Events not triggering in proper order.

  • Property mode set to 100644
File size: 15.9 KB
RevLine 
[d955bf19]1
[b06ef8c]2
3import wx
4import wx.lib.newevent
[a099131]5import time
[54557b5]6from sas.sascalc.dataloader.readers.cansas_reader import Reader
[d85c194]7from sas.sasgui.guiframe.events import EVT_SLICER_PARS
8from sas.sasgui.guiframe.utils import format_number
9from sas.sasgui.guiframe.events import EVT_SLICER
[39f0bf4]10from sas.sasgui.guiframe.events import SlicerParameterEvent, SlicerEvent
[54557b5]11from Plotter1D import ModelPanel1D
[df27aa8]12from Plotter2D import ModelPanel2D
[dfa1579]13from sas.sascalc.dataloader.data_info import Data1D, Data2D
[54557b5]14apply_params, EVT_APPLY_PARAMS = wx.lib.newevent.NewEvent()
15auto_save, EVT_AUTO_SAVE = wx.lib.newevent.NewEvent()
16auto_close, EVT_ON_CLOSE = wx.lib.newevent.NewEvent()
[32c0841]17
[0d9dae8]18
[ef0c170]19class SlicerParameterPanel(wx.Dialog):
[d955bf19]20    """
[b40ad40]21    Panel class to show the slicer parameters
[d955bf19]22    """
[f15da54]23    # TODO: show units
24    # TODO: order parameters properly
[b40ad40]25
[cd84dca]26    def __init__(self, parent, *args, **kwargs):
[12aa9b5]27        """
[b40ad40]28        Dialog window that allow to edit parameters slicer
[d955bf19]29        by entering new values
[12aa9b5]30        """
[b40ad40]31        wx.Dialog.__init__(self, parent, *args, **kwargs)
[b06ef8c]32        self.params = {}
33        self.parent = parent
34        self.type = None
35        self.listeners = []
36        self.parameters = []
[32c0841]37        self.bck = wx.GridBagSizer(5, 5)
[b06ef8c]38        self.SetSizer(self.bck)
[54557b5]39        self.auto_save = None
40        self.path = None
41        self.type_list = ["SectorInteractor", "AnnulusInteractor",
42                          "BoxInteractorX", "BoxInteractorY"]
43        self.type_select = wx.ComboBox(parent=self, choices=self.type_list)
44        self.append_name = wx.TextCtrl(parent=self, id=wx.NewId(),
45                                       name="Append to file name:")
46        self.data_list = None
[32c0841]47        label = "Right-click on 2D plot for slicer options"
48        title = wx.StaticText(self, -1, label, style=wx.ALIGN_LEFT)
49        self.bck.Add(title, (0, 0), (1, 2),
[b40ad40]50                     flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15)
[b06ef8c]51        # Bindings
52        self.parent.Bind(EVT_SLICER, self.onEVT_SLICER)
53        self.parent.Bind(EVT_SLICER_PARS, self.onParamChange)
[54557b5]54        self.Bind(EVT_APPLY_PARAMS, self.apply_params_list_and_process)
55        self.Bind(EVT_AUTO_SAVE, self.save_files)
56        self.Bind(EVT_ON_CLOSE, self.on_close)
[b06ef8c]57
58    def onEVT_SLICER(self, event):
59        """
[d955bf19]60        Process EVT_SLICER events
61        When the slicer changes, update the panel
[b40ad40]62
[d955bf19]63        :param event: EVT_SLICER event
[b06ef8c]64        """
65        event.Skip()
[e075203]66        if event.obj_class is None:
[b06ef8c]67            self.set_slicer(None, None)
68        else:
69            self.set_slicer(event.type, event.params)
[b40ad40]70
[b06ef8c]71    def set_slicer(self, type, params):
72        """
[d955bf19]73        Rebuild the panel
[b06ef8c]74        """
[b40ad40]75        self.bck.Clear(True)
[39f0bf4]76        self.bck.Add((5, 5), (0, 0), (1, 1),
77                     wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
[b40ad40]78        self.type = type
[e075203]79        if type is None:
[32c0841]80            label = "Right-click on 2D plot for slicer options"
81            title = wx.StaticText(self, -1, label, style=wx.ALIGN_LEFT)
[39f0bf4]82            self.bck.Add(title, (1, 0), (1, 2),
[b40ad40]83                         flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15)
[b06ef8c]84        else:
[b40ad40]85            title = wx.StaticText(self, -1,
[f6bb24d]86                                  "Slicer Parameters:", style=wx.ALIGN_LEFT)
[39f0bf4]87            self.bck.Add(title, (1, 0), (1, 2),
[b40ad40]88                         flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15)
[39f0bf4]89            iy = 1
[b06ef8c]90            self.parameters = []
91            keys = params.keys()
92            keys.sort()
93            for item in keys:
[ef0c170]94                iy += 1
95                ix = 0
[32c0841]96                if not item in ["count", "errors"]:
[0f6d05f8]97                    text = wx.StaticText(self, -1, item, style=wx.ALIGN_LEFT)
[b40ad40]98                    self.bck.Add(text, (iy, ix), (1, 1),
99                                 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[32c0841]100                    ctl = wx.TextCtrl(self, -1, size=(80, 20),
101                                      style=wx.TE_PROCESS_ENTER)
[88989768]102                    hint_msg = "Modify the value of %s to change" % item
103                    hint_msg += " the 2D slicer"
[32c0841]104                    ctl.SetToolTipString(hint_msg)
[0f6d05f8]105                    ix = 1
106                    ctl.SetValue(format_number(str(params[item])))
107                    self.Bind(wx.EVT_TEXT_ENTER, self.onTextEnter)
108                    self.parameters.append([item, ctl])
[b40ad40]109                    self.bck.Add(ctl, (iy, ix), (1, 1),
110                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[32c0841]111                    ix = 3
[b40ad40]112                    self.bck.Add((20, 20), (iy, ix), (1, 1),
113                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[0f6d05f8]114                else:
[b40ad40]115                    text = wx.StaticText(self, -1, item + " : ",
[32c0841]116                                         style=wx.ALIGN_LEFT)
[b40ad40]117                    self.bck.Add(text, (iy, ix), (1, 1),
118                                 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
119                    ctl = wx.StaticText(self, -1,
120                                        format_number(str(params[item])),
121                                        style=wx.ALIGN_LEFT)
[32c0841]122                    ix = 1
[b40ad40]123                    self.bck.Add(ctl, (iy, ix), (1, 1),
124                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[39f0bf4]125
126            # Change slicer within the window
[54557b5]127            ix = 0
128            iy += 1
129            txt = "Slicer type:"
[39f0bf4]130            text = wx.StaticText(self, -1, txt, style=wx.ALIGN_LEFT)
131            self.bck.Add(text, (iy, ix), (1, 1),
[b40ad40]132                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[39f0bf4]133            self.Bind(wx.EVT_COMBOBOX, self.onChangeSlicer)
[54557b5]134            index = self.type_select.FindString(type)
[39f0bf4]135            self.type_select.SetSelection(index)
136            self.bck.Add(self.type_select, (iy, 1), (1, 1),
137                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
138
139            # batch slicing parameters
[f6bb24d]140            title_text = "Batch Slicing Options:"
141            title = wx.StaticText(self, -1, title_text, style=wx.ALIGN_LEFT)
[39f0bf4]142            iy += 1
[54557b5]143            line = wx.StaticLine(self, -1, style=wx.LI_VERTICAL)
144            line.SetSize((60, 60))
145            self.bck.Add(line, (iy, ix), (1, 2),
[f6bb24d]146                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
147            iy += 1
148            self.bck.Add(title, (iy, ix), (1, 1),
149                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[54557b5]150
[b697396b]151            # Create a list box with all of the 2D plots
[54557b5]152            iy += 1
[dfa1579]153            self.process_list()
[f6bb24d]154            self.bck.Add(self.data_list, (iy, ix), (1, 1),
[39f0bf4]155                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[54557b5]156
157            # Checkbox for autosaving data
158            iy += 1
159
160            self.auto_save = wx.CheckBox(parent=self, id=wx.NewId(),
161                                         label="Auto save generated 1D:")
162            self.Bind(wx.EVT_CHECKBOX, self.on_auto_save_checked)
163            self.bck.Add(self.auto_save, (iy, ix), (1, 1),
164                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
165            iy += 1
[982577b]166            # TODO: Get list of loaded data, not plots - plot again
167            # TODO: try/catch block to catch wx._core.PyDeadObjectError (pass)
[54557b5]168            # File browser
169            save_to = "Save files to:"
170            save = wx.StaticText(self, -1, save_to, style=wx.ALIGN_LEFT)
171            self.path = wx.DirPickerCtrl(self, id=wx.NewId(), path="",
172                                         message=save_to)
173            self.path.Enable(False)
174            self.bck.Add(save, (iy, ix), (1, 1),
175                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
176            self.bck.Add(self.path, (iy, 1), (1, 1),
177                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
178            # Append to file
[39f0bf4]179            iy += 1
[54557b5]180            default_value = "_{0}".format(self.type)
181            for key in params:
182                default_value += "_%d.2" % params[key]
183            append_text = "Append to file name:"
184            append = wx.StaticText(self, -1, append_text, style=wx.ALIGN_LEFT)
185            self.append_name.SetValue(default_value)
186            self.append_name.Enable(False)
187            self.bck.Add(append, (iy, ix), (1, 1),
188                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
189            self.bck.Add(self.append_name, (iy, 1), (1, 1),
190                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
191
192            # TODO: Fix fitting options combobox/radiobox
193            # Combobox for selecting fitting options
194            # iy += 1
195            # self.fitting_radio = wx.RadioBox(parent=self, id=wx.NewId(),
196            #                                  size=(4,1))
197            # self.fitting_radio.SetString(0, "No fitting")
198            # self.fitting_radio.SetString(1, "Batch Fitting")
199            # self.fitting_radio.SetString(2, "Fitting")
200            # self.fitting_radio.SetString(3, "Simultaneous and Constrained Fit")
201            # self.fitting_radio.SetValue(0)
202            # self.bck.Add(self.fitting_radio, (iy, ix), (1, 1),
203            #              wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
204
[b697396b]205            # Button to start batch slicing
[54557b5]206            iy += 1
[f15da54]207            button_label = "Apply Slicer to Selected Plots"
[f6bb24d]208            self.batch_slicer_button = wx.Button(parent=self,
209                                                 label=button_label)
[54557b5]210            self.Bind(wx.EVT_BUTTON, self.on_batch_slicer)
[f6bb24d]211            self.bck.Add(self.batch_slicer_button, (iy, ix), (1, 1),
[54557b5]212                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[f6bb24d]213            iy += 1
[39f0bf4]214            self.bck.Add((5, 5), (iy, ix), (1, 1),
215                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
[b06ef8c]216        self.bck.Layout()
217        self.bck.Fit(self)
218        self.parent.GetSizer().Layout()
219
220    def onParamChange(self, evt):
[12aa9b5]221        """
[d955bf19]222        receive an event end reset value text fields
223        inside self.parameters
[12aa9b5]224        """
[b06ef8c]225        evt.Skip()
226        if evt.type == "UPDATE":
[b40ad40]227            for item in self.parameters:
[b06ef8c]228                if item[0] in evt.params:
[32c0841]229                    item[1].SetValue("%-5.3g" % evt.params[item[0]])
[b06ef8c]230                    item[1].Refresh()
[b40ad40]231
232    def onTextEnter(self, evt):
[b06ef8c]233        """
[d955bf19]234        Parameters have changed
[b40ad40]235        """
[b06ef8c]236        params = {}
237        has_error = False
238        for item in self.parameters:
239            try:
240                params[item[0]] = float(item[1].GetValue())
[e075203]241                item[1].SetBackgroundColour(
242                    wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
[b06ef8c]243                item[1].Refresh()
244            except:
245                has_error = True
246                item[1].SetBackgroundColour("pink")
247                item[1].Refresh()
248
[e075203]249        if not has_error:
[b06ef8c]250            # Post parameter event
[e075203]251            # parent here is plotter2D
[b06ef8c]252            event = SlicerParameterEvent(type=self.type, params=params)
[982577b]253            wx.PostEvent(self, event)
[39f0bf4]254
[54557b5]255    def on_batch_slicer(self, evt=None):
[39f0bf4]256        """
[f15da54]257        Method invoked with batch slicing button is pressed
[39f0bf4]258        :param evt: Event triggering hide/show of the batch slicer parameters
259        """
[a099131]260        apply_to_list = []
261        spp = self.parent.parent
262        params = self.parent.slicer.get_params()
263        type = self.type_select.GetStringSelection()
[54557b5]264        save = self.auto_save.IsChecked()
265        append = self.append_name.GetValue()
266        path = self.path.GetPath()
[a099131]267
[b697396b]268        # Find desired 2D data panels
[a099131]269        for key, mgr in spp.plot_panels.iteritems():
[f15da54]270            if mgr.graph.prop['title'] in self.data_list.CheckedStrings:
[a099131]271                apply_to_list.append(mgr)
272
[b697396b]273        # Apply slicer type to selected panels
[a099131]274        for item in apply_to_list:
275            self._apply_slicer_to_plot(item, type)
[f15da54]276
[b697396b]277        # Post an event to apply appropriate slicer params to each slicer
278        # Event needed due to how apply_slicer_to_plot works
[54557b5]279        event = apply_params(params=params, plot_list=apply_to_list,
280                             auto_save=save, append=append,
281                             path=path)
282        wx.PostEvent(self, event)
283        event = auto_close()
[f15da54]284        wx.PostEvent(self, event)
[39f0bf4]285
286    def onChangeSlicer(self, evt):
287        """
[df27aa8]288        Event driven slicer change when self.type_select changes
[39f0bf4]289        :param evt: Event triggering this change
290        """
[df27aa8]291        self._apply_slicer_to_plot(self.parent)
292
[a099131]293    def _apply_slicer_to_plot(self, plot, type=None):
[df27aa8]294        """
295        Apply a slicer to *any* plot window, not just parent window
[f15da54]296        :param plot: 2D plot panel to apply a slicer to
297        :param type: The type of slicer to apply to the panel
[df27aa8]298        """
[a099131]299        if type is None:
300            type = self.type_select.GetStringSelection()
301        if type == "SectorInteractor":
302            plot.onSectorQ(None)
303        elif type == "AnnulusInteractor":
304            plot.onSectorPhi(None)
305        elif type == "BoxInteractorX":
306            plot.onBoxavgX(None)
307        elif type == "BoxInteractorY":
308            plot.onBoxavgY(None)
[df27aa8]309
[dfa1579]310    def process_list(self):
[b697396b]311        """
312        Populate the check list from the currently plotted 2D data
313        """
[f15da54]314        self.checkme = None
[dfa1579]315        main_window = self.parent.parent
316        self.loaded_data = []
317        id = wx.NewId()
[b697396b]318        # Iterate over the loaded plots and find all 2D panels
[f15da54]319        for key, value in main_window.plot_panels.iteritems():
320            if isinstance(value, ModelPanel2D):
321                self.loaded_data.append(value.data2D.name)
322                if value.data2D.id == self.parent.data2D.id:
[b697396b]323                    # Set current plot panel as uncheckable
[f15da54]324                    self.checkme = self.loaded_data.index(value.data2D.name)
[dfa1579]325        self.data_list = wx.CheckListBox(parent=self, id=id,
326                                         choices=self.loaded_data,
[f15da54]327                                         name="Apply Slicer to 2D Plots:")
[54557b5]328        # Check all items by default
[b697396b]329        for item in range(len(self.data_list.Items)):
330            self.data_list.Check(item)
[54557b5]331        self.data_list.Bind(wx.EVT_CHECKLISTBOX, self.on_check_box_list)
[dfa1579]332
[54557b5]333    def on_check_box_list(self, evt=None):
[f15da54]334        """
[b697396b]335        Prevent a checkbox item from being unchecked
[f15da54]336        :param e: Event triggered when a checkbox list item is checked
337        """
[54557b5]338        if evt is None:
339            return
340        index = evt.GetSelection()
[dfa1579]341        if index == self.checkme:
342            self.data_list.Check(index)
[f15da54]343
[54557b5]344    def apply_params_list_and_process(self, evt=None):
[b697396b]345        """
346        Event based parameter setting.
347        :param evt: Event triggered to apply parameters to a list of plots
348                    evt should have attrs plot_list and params
349        """
350        # Apply parameter list to each plot as desired
[f15da54]351        for item in evt.plot_list:
352            item.slicer.set_params(evt.params)
353            item.slicer.base.update()
[54557b5]354        # Post an event to save each data set to file
355        if evt.auto_save:
356            event = auto_save(append_to_name=evt.append,
357                              file_list=evt.plot_list,
358                              path=evt.path)
359            wx.PostEvent(self, event)
360
361    def save_files(self, evt=None):
362        """
363        Automatically save the sliced data to file.
364        :param evt: Event that triggered the call to the method
365        """
366        if evt is None:
367            return
368        writer = Reader()
369        main_window = self.parent.parent
[982577b]370        data_dic = {}
[54557b5]371        append = evt.append_to_name
372        for key, plot in main_window.plot_panels.iteritems():
373            if not hasattr(plot, "data2D"):
374                for item in plot.plots:
[982577b]375                    data_dic[item] = plot.plots[item]
376        for item, data1d in data_dic.iteritems():
377            base = item.split(".")[0]
378            save_to = evt.path + "\\" + base + append + ".xml"
379            writer.write(save_to, data1d)
[54557b5]380        # TODO: save all files
381
382    def on_auto_save_checked(self, evt=None):
383        """
384        Enable/Disable auto append when checkbox is checked
385        :param evt: Event
386        """
387        self.append_name.Enable(self.auto_save.IsChecked())
388        self.path.Enable(self.auto_save.IsChecked())
389   
390    def on_close(self, evt=None):
391        """
392        Auto close the panel
393        """
[f15da54]394        self.Destroy()
Note: See TracBrowser for help on using the repository browser.