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
Line 
1
2
3import wx
4import wx.lib.newevent
5import time
6from sas.sascalc.dataloader.readers.cansas_reader import Reader
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
10from sas.sasgui.guiframe.events import SlicerParameterEvent, SlicerEvent
11from Plotter1D import ModelPanel1D
12from Plotter2D import ModelPanel2D
13from sas.sascalc.dataloader.data_info import Data1D, Data2D
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()
17
18
19class SlicerParameterPanel(wx.Dialog):
20    """
21    Panel class to show the slicer parameters
22    """
23    # TODO: show units
24    # TODO: order parameters properly
25
26    def __init__(self, parent, *args, **kwargs):
27        """
28        Dialog window that allow to edit parameters slicer
29        by entering new values
30        """
31        wx.Dialog.__init__(self, parent, *args, **kwargs)
32        self.params = {}
33        self.parent = parent
34        self.type = None
35        self.listeners = []
36        self.parameters = []
37        self.bck = wx.GridBagSizer(5, 5)
38        self.SetSizer(self.bck)
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
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),
50                     flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15)
51        # Bindings
52        self.parent.Bind(EVT_SLICER, self.onEVT_SLICER)
53        self.parent.Bind(EVT_SLICER_PARS, self.onParamChange)
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)
57
58    def onEVT_SLICER(self, event):
59        """
60        Process EVT_SLICER events
61        When the slicer changes, update the panel
62
63        :param event: EVT_SLICER event
64        """
65        event.Skip()
66        if event.obj_class is None:
67            self.set_slicer(None, None)
68        else:
69            self.set_slicer(event.type, event.params)
70
71    def set_slicer(self, type, params):
72        """
73        Rebuild the panel
74        """
75        self.bck.Clear(True)
76        self.bck.Add((5, 5), (0, 0), (1, 1),
77                     wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
78        self.type = type
79        if type is None:
80            label = "Right-click on 2D plot for slicer options"
81            title = wx.StaticText(self, -1, label, style=wx.ALIGN_LEFT)
82            self.bck.Add(title, (1, 0), (1, 2),
83                         flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15)
84        else:
85            title = wx.StaticText(self, -1,
86                                  "Slicer Parameters:", style=wx.ALIGN_LEFT)
87            self.bck.Add(title, (1, 0), (1, 2),
88                         flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15)
89            iy = 1
90            self.parameters = []
91            keys = params.keys()
92            keys.sort()
93            for item in keys:
94                iy += 1
95                ix = 0
96                if not item in ["count", "errors"]:
97                    text = wx.StaticText(self, -1, item, style=wx.ALIGN_LEFT)
98                    self.bck.Add(text, (iy, ix), (1, 1),
99                                 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
100                    ctl = wx.TextCtrl(self, -1, size=(80, 20),
101                                      style=wx.TE_PROCESS_ENTER)
102                    hint_msg = "Modify the value of %s to change" % item
103                    hint_msg += " the 2D slicer"
104                    ctl.SetToolTipString(hint_msg)
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])
109                    self.bck.Add(ctl, (iy, ix), (1, 1),
110                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0)
111                    ix = 3
112                    self.bck.Add((20, 20), (iy, ix), (1, 1),
113                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0)
114                else:
115                    text = wx.StaticText(self, -1, item + " : ",
116                                         style=wx.ALIGN_LEFT)
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)
122                    ix = 1
123                    self.bck.Add(ctl, (iy, ix), (1, 1),
124                                 wx.EXPAND | wx.ADJUST_MINSIZE, 0)
125
126            # Change slicer within the window
127            ix = 0
128            iy += 1
129            txt = "Slicer type:"
130            text = wx.StaticText(self, -1, txt, style=wx.ALIGN_LEFT)
131            self.bck.Add(text, (iy, ix), (1, 1),
132                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
133            self.Bind(wx.EVT_COMBOBOX, self.onChangeSlicer)
134            index = self.type_select.FindString(type)
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
140            title_text = "Batch Slicing Options:"
141            title = wx.StaticText(self, -1, title_text, style=wx.ALIGN_LEFT)
142            iy += 1
143            line = wx.StaticLine(self, -1, style=wx.LI_VERTICAL)
144            line.SetSize((60, 60))
145            self.bck.Add(line, (iy, ix), (1, 2),
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)
150
151            # Create a list box with all of the 2D plots
152            iy += 1
153            self.process_list()
154            self.bck.Add(self.data_list, (iy, ix), (1, 1),
155                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
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
166            # TODO: Get list of loaded data, not plots - plot again
167            # TODO: try/catch block to catch wx._core.PyDeadObjectError (pass)
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
179            iy += 1
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
205            # Button to start batch slicing
206            iy += 1
207            button_label = "Apply Slicer to Selected Plots"
208            self.batch_slicer_button = wx.Button(parent=self,
209                                                 label=button_label)
210            self.Bind(wx.EVT_BUTTON, self.on_batch_slicer)
211            self.bck.Add(self.batch_slicer_button, (iy, ix), (1, 1),
212                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
213            iy += 1
214            self.bck.Add((5, 5), (iy, ix), (1, 1),
215                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
216        self.bck.Layout()
217        self.bck.Fit(self)
218        self.parent.GetSizer().Layout()
219
220    def onParamChange(self, evt):
221        """
222        receive an event end reset value text fields
223        inside self.parameters
224        """
225        evt.Skip()
226        if evt.type == "UPDATE":
227            for item in self.parameters:
228                if item[0] in evt.params:
229                    item[1].SetValue("%-5.3g" % evt.params[item[0]])
230                    item[1].Refresh()
231
232    def onTextEnter(self, evt):
233        """
234        Parameters have changed
235        """
236        params = {}
237        has_error = False
238        for item in self.parameters:
239            try:
240                params[item[0]] = float(item[1].GetValue())
241                item[1].SetBackgroundColour(
242                    wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
243                item[1].Refresh()
244            except:
245                has_error = True
246                item[1].SetBackgroundColour("pink")
247                item[1].Refresh()
248
249        if not has_error:
250            # Post parameter event
251            # parent here is plotter2D
252            event = SlicerParameterEvent(type=self.type, params=params)
253            wx.PostEvent(self, event)
254
255    def on_batch_slicer(self, evt=None):
256        """
257        Method invoked with batch slicing button is pressed
258        :param evt: Event triggering hide/show of the batch slicer parameters
259        """
260        apply_to_list = []
261        spp = self.parent.parent
262        params = self.parent.slicer.get_params()
263        type = self.type_select.GetStringSelection()
264        save = self.auto_save.IsChecked()
265        append = self.append_name.GetValue()
266        path = self.path.GetPath()
267
268        # Find desired 2D data panels
269        for key, mgr in spp.plot_panels.iteritems():
270            if mgr.graph.prop['title'] in self.data_list.CheckedStrings:
271                apply_to_list.append(mgr)
272
273        # Apply slicer type to selected panels
274        for item in apply_to_list:
275            self._apply_slicer_to_plot(item, type)
276
277        # Post an event to apply appropriate slicer params to each slicer
278        # Event needed due to how apply_slicer_to_plot works
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()
284        wx.PostEvent(self, event)
285
286    def onChangeSlicer(self, evt):
287        """
288        Event driven slicer change when self.type_select changes
289        :param evt: Event triggering this change
290        """
291        self._apply_slicer_to_plot(self.parent)
292
293    def _apply_slicer_to_plot(self, plot, type=None):
294        """
295        Apply a slicer to *any* plot window, not just parent window
296        :param plot: 2D plot panel to apply a slicer to
297        :param type: The type of slicer to apply to the panel
298        """
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)
309
310    def process_list(self):
311        """
312        Populate the check list from the currently plotted 2D data
313        """
314        self.checkme = None
315        main_window = self.parent.parent
316        self.loaded_data = []
317        id = wx.NewId()
318        # Iterate over the loaded plots and find all 2D panels
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:
323                    # Set current plot panel as uncheckable
324                    self.checkme = self.loaded_data.index(value.data2D.name)
325        self.data_list = wx.CheckListBox(parent=self, id=id,
326                                         choices=self.loaded_data,
327                                         name="Apply Slicer to 2D Plots:")
328        # Check all items by default
329        for item in range(len(self.data_list.Items)):
330            self.data_list.Check(item)
331        self.data_list.Bind(wx.EVT_CHECKLISTBOX, self.on_check_box_list)
332
333    def on_check_box_list(self, evt=None):
334        """
335        Prevent a checkbox item from being unchecked
336        :param e: Event triggered when a checkbox list item is checked
337        """
338        if evt is None:
339            return
340        index = evt.GetSelection()
341        if index == self.checkme:
342            self.data_list.Check(index)
343
344    def apply_params_list_and_process(self, evt=None):
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
351        for item in evt.plot_list:
352            item.slicer.set_params(evt.params)
353            item.slicer.base.update()
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
370        data_dic = {}
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:
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)
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        """
394        self.Destroy()
Note: See TracBrowser for help on using the repository browser.