source: sasview/sansguiframe/src/sans/guiframe/data_panel.py @ c9579e0

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 c9579e0 was 5cf5f51, checked in by Jae Cho <jhjcho@…>, 13 years ago

add mask to data panel for 2D

  • Property mode set to 100644
File size: 49.1 KB
Line 
1################################################################################
2#This software was developed by the University of Tennessee as part of the
3#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4#project funded by the US National Science Foundation.
5#
6#See the license text in license.txt
7#
8#copyright 2010, University of Tennessee
9################################################################################
10"""
11This module provides Graphic interface for the data_manager module.
12"""
13import os
14import wx
15# Check version
16toks = wx.__version__.split('.')
17if int(toks[1]) < 9:
18    if int(toks[2]) < 12:
19        wx_version = 811
20    else:
21        wx_version = 812
22else:
23    wx_version = 900
24import sys
25import warnings
26import logging
27from wx.lib.scrolledpanel import ScrolledPanel
28import  wx.lib.agw.customtreectrl as CT
29from sans.guiframe.dataFitting import Data1D
30from sans.guiframe.dataFitting import Data2D
31from sans.guiframe.panel_base import PanelBase
32from sans.guiframe.events import StatusEvent
33from sans.guiframe.events import EVT_DELETE_PLOTPANEL
34from sans.guiframe.events import NewLoadDataEvent
35from sans.guiframe.events import NewPlotEvent
36from sans.guiframe.gui_style import GUIFRAME
37from sans.guiframe.events import NewBatchEvent
38from sans.dataloader.loader import Loader
39
40import sans.guiframe.config as config
41 
42extension_list = []
43if config.APPLICATION_STATE_EXTENSION is not None:
44    extension_list.append(config.APPLICATION_STATE_EXTENSION)
45EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS + extension_list   
46PLUGINS_WLIST = config.PLUGINS_WLIST
47APPLICATION_WLIST = config.APPLICATION_WLIST
48
49#Control panel width
50if sys.platform.count("win32") > 0:
51    PANEL_WIDTH = 235
52    PANEL_HEIGHT = 700
53    CBOX_WIDTH = 140
54    BUTTON_WIDTH = 80
55    FONT_VARIANT = 0
56    IS_MAC = False
57else:
58    PANEL_WIDTH = 255
59    PANEL_HEIGHT = 750
60    CBOX_WIDTH = 155
61    BUTTON_WIDTH = 100
62    FONT_VARIANT = 1
63    IS_MAC = True
64
65STYLE_FLAG =wx.RAISED_BORDER|CT.TR_HAS_BUTTONS| CT.TR_HIDE_ROOT|\
66                    wx.WANTS_CHARS|CT.TR_HAS_VARIABLE_ROW_HEIGHT
67                   
68                   
69class DataTreeCtrl(CT.CustomTreeCtrl):
70    """
71    Check list control to be used for Data Panel
72    """
73    def __init__(self, parent,*args, **kwds):
74        #agwstyle is introduced in wx.2.8.11 but is not working for mac
75        if IS_MAC and wx_version < 812:
76            try:
77                kwds['style'] = STYLE_FLAG
78                CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
79            except:
80                del kwds['style']
81                CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
82        else:
83            #agwstyle is introduced in wx.2.8.11 .argument working only for windows
84            try:
85                kwds['agwStyle'] = STYLE_FLAG
86                CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
87            except:
88                try:
89                    del kwds['agwStyle']
90                    kwds['style'] = STYLE_FLAG
91                    CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
92                except:
93                    del kwds['style']
94                    CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
95        self.root = self.AddRoot("Available Data")
96       
97class DataPanel(ScrolledPanel, PanelBase):
98    """
99    This panel displays data available in the application and widgets to
100    interact with data.
101    """
102    ## Internal name for the AUI manager
103    window_name = "Data Panel"
104    ## Title to appear on top of the window
105    window_caption = "Data Explorer"
106    #type of window
107    window_type = "Data Panel"
108    ## Flag to tell the GUI manager that this panel is not
109    #  tied to any perspective
110    #ALWAYS_ON = True
111    def __init__(self, parent, 
112                 list=None,
113                 size=(PANEL_WIDTH, PANEL_HEIGHT),
114                 list_of_perspective=None, manager=None, *args, **kwds):
115        kwds['size']= size
116        kwds['style'] = STYLE_FLAG
117        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
118        PanelBase.__init__(self)
119        self.SetupScrolling()
120        #Set window's font size
121        self.SetWindowVariant(variant=FONT_VARIANT)
122        self.loader = Loader() 
123        #Default location
124        self._default_save_location = None 
125        self.all_data1d = True
126        self.parent = parent
127        self.manager = manager
128        if list is None:
129            list = []
130        self.list_of_data = list
131        if list_of_perspective is None:
132            list_of_perspective = []
133        self.list_of_perspective = list_of_perspective
134        self.list_rb_perspectives= []
135        self.list_cb_data = {}
136        self.list_cb_theory = {}
137        self.tree_ctrl = None
138        self.tree_ctrl_theory = None
139        self.perspective_cbox = None
140        ## Create context menu for page
141        self.data_menu = None
142       
143        self.owner = None
144        self.do_layout()
145        self.fill_cbox_analysis(self.list_of_perspective)
146        self.Bind(wx.EVT_SHOW, self.on_close_page)
147        if self.parent is not None:
148            self.parent.Bind(EVT_DELETE_PLOTPANEL, self._on_delete_plot_panel)
149     
150    def do_layout(self):
151        """
152        """
153        self.define_panel_structure()
154        self.layout_selection()
155        self.layout_data_list()
156        self.layout_batch()
157        self.layout_button()
158       
159   
160    def define_panel_structure(self):
161        """
162        Define the skeleton of the panel
163        """
164        w, h = self.parent.GetSize()
165        self.vbox  = wx.BoxSizer(wx.VERTICAL)
166        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
167        self.sizer1.SetMinSize(wx.Size(w/13, h*2/5))
168     
169        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
170        self.sizer3 = wx.FlexGridSizer(7, 2, 4, 1)
171        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
172        self.sizer5 = wx.BoxSizer(wx.VERTICAL)
173       
174        self.vbox.Add(self.sizer5, 0, wx.EXPAND|wx.ALL,1)
175        self.vbox.Add(self.sizer1, 1, wx.EXPAND|wx.ALL,0)
176        self.vbox.Add(self.sizer2, 0, wx.EXPAND|wx.ALL,1)
177        self.vbox.Add(self.sizer3, 0, wx.EXPAND|wx.ALL,10)
178        #self.vbox.Add(self.sizer4, 0, wx.EXPAND|wx.ALL,5)
179       
180        self.SetSizer(self.vbox)
181       
182    def layout_selection(self):
183        """
184        """
185        select_txt = wx.StaticText(self, -1, 'Selection Options')
186        select_txt.SetForegroundColour('blue')
187        self.selection_cbox = wx.ComboBox(self, -1, style=wx.CB_READONLY)
188        list_of_options = ['Select all Data',
189                            'Unselect all Data',
190                           'Select all Data 1D',
191                           'Unselect all Data 1D',
192                           'Select all Data 2D',
193                           'Unselect all Data 2D' ]
194        for option in list_of_options:
195            self.selection_cbox.Append(str(option))
196        self.selection_cbox.SetValue('Select all Data')
197        wx.EVT_COMBOBOX(self.selection_cbox,-1, self._on_selection_type)
198        self.sizer5.AddMany([(select_txt,0, wx.ALL,5),
199                            (self.selection_cbox,0, wx.ALL,5)])
200        self.enable_selection()
201       
202   
203    def _on_selection_type(self, event):
204        """
205        Select data according to patterns
206        """
207       
208        list_of_options = ['Select all Data',
209                            'Unselect all Data',
210                           'Select all Data 1D',
211                           'Unselect all Data 1D',
212                           'Select all Data 2D',
213                           'Unselect all Data 2D' ]
214        option = self.selection_cbox.GetValue()
215       
216        pos = self.selection_cbox.GetSelection()
217        if pos == wx.NOT_FOUND:
218            return 
219        option = self.selection_cbox.GetString(pos)
220        for item in self.list_cb_data.values():
221            data_ctrl, _, _, _,_, _,_,_= item
222            data_id, data_class, _ = self.tree_ctrl.GetItemPyData(data_ctrl) 
223            if option == 'Select all Data':
224                self.tree_ctrl.CheckItem(data_ctrl, True) 
225            elif option == 'Unselect all Data':
226                self.tree_ctrl.CheckItem(data_ctrl, False)
227            elif option == 'Select all Data 1D':
228                if data_class == 'Data1D':
229                    self.tree_ctrl.CheckItem(data_ctrl, True) 
230            elif option == 'Unselect all Data 1D':
231                if data_class == 'Data1D':
232                    self.tree_ctrl.CheckItem(data_ctrl, False) 
233            elif option == 'Select all Data 1D':
234                if data_class == 'Data1D':
235                    self.tree_ctrl.CheckItem(data_ctrl, True) 
236            elif option == 'Select all Data 2D':
237                if data_class == 'Data2D':
238                    self.tree_ctrl.CheckItem(data_ctrl, True) 
239            elif option == 'Unselect all Data 2D':
240                if data_class == 'Data2D':
241                    self.tree_ctrl.CheckItem(data_ctrl, False) 
242        self.enable_append()
243        self.enable_freeze()
244        self.enable_plot()
245        self.enable_import()
246        self.enable_remove()
247               
248    def layout_button(self):
249        """
250        Layout widgets related to buttons
251        """
252        w, _ = self.GetSize()
253       
254        self.bt_add = wx.Button(self, wx.NewId(), "Load Data", 
255                                size=(BUTTON_WIDTH, -1))
256        self.bt_add.SetToolTipString("Load data files")
257        wx.EVT_BUTTON(self, self.bt_add.GetId(), self._load_data)
258        self.bt_remove = wx.Button(self, wx.NewId(), "Delete Data",
259         size=(BUTTON_WIDTH, -1))
260        self.bt_remove.SetToolTipString("Delete data from the application")
261        wx.EVT_BUTTON(self, self.bt_remove.GetId(), self.on_remove)
262        self.bt_import = wx.Button(self, wx.NewId(), "Send To",
263                                    size=(BUTTON_WIDTH, -1))
264        self.bt_import.SetToolTipString("Send set of Data to active perspective")
265        wx.EVT_BUTTON(self, self.bt_import.GetId(), self.on_import)
266        self.perspective_cbox = wx.ComboBox(self, -1,
267                                style=wx.CB_READONLY)
268        if not IS_MAC:
269            self.perspective_cbox.SetMinSize((BUTTON_WIDTH*1.6, -1))
270        wx.EVT_COMBOBOX(self.perspective_cbox,-1, 
271                        self._on_perspective_selection)
272   
273        self.bt_append_plot = wx.Button(self, wx.NewId(), "Append Plot To",
274                                        size=(BUTTON_WIDTH, -1))
275        self.bt_append_plot.SetToolTipString("Plot the selected data in the active panel")
276        wx.EVT_BUTTON(self, self.bt_append_plot.GetId(), self.on_append_plot)
277       
278        self.bt_plot = wx.Button(self, wx.NewId(), "New Plot", 
279                                 size=(BUTTON_WIDTH, -1))
280        self.bt_plot.SetToolTipString("To trigger plotting")
281        wx.EVT_BUTTON(self, self.bt_plot.GetId(), self.on_plot)
282       
283        self.bt_freeze = wx.Button(self, wx.NewId(), "Freeze Theory", 
284                                   size=(BUTTON_WIDTH, -1))
285        freeze_tip = "To trigger freeze a theory: making a copy\n"
286        freeze_tip += "of the theory checked to Data box,\n"
287        freeze_tip += "     so that it can act like a real data set."
288        self.bt_freeze.SetToolTipString(freeze_tip)
289        wx.EVT_BUTTON(self, self.bt_freeze.GetId(), self.on_freeze)
290        #hide plot
291        #self.bt_close_plot = wx.Button(self, wx.NewId(), "Delete Plot",
292        #                           size=(BUTTON_WIDTH, -1))
293        #self.bt_close_plot.SetToolTipString("Delete the plot panel on focus")
294        #wx.EVT_BUTTON(self, self.bt_close_plot.GetId(), self.on_close_plot)
295       
296        self.cb_plotpanel = wx.ComboBox(self, -1, 
297                                style=wx.CB_READONLY|wx.CB_SORT)
298        #self.cb_plotpanel.SetMinSize((BUTTON_WIDTH*2, -1))
299        wx.EVT_COMBOBOX(self.cb_plotpanel,-1, self._on_plot_selection)
300        self.cb_plotpanel.Disable()
301
302        self.sizer3.AddMany([(self.bt_add),
303                             ((10, 10)),
304                             (self.bt_remove),
305                             ((10, 10)),
306                             (self.bt_freeze),
307                             ((10, 10)),
308                             (self.bt_plot),
309                             ((10, 10)),
310                             (self.bt_append_plot),
311                             (self.cb_plotpanel, wx.EXPAND|wx.ADJUST_MINSIZE, 5),
312                             ((5, 5)),
313                             ((5, 5)),
314                             (self.bt_import, 0, wx.EXPAND|wx.RIGHT, 5),
315                             (self.perspective_cbox, wx.EXPAND|wx.ADJUST_MINSIZE, 5),
316                             ((10, 10)),
317                             (self.sizer4),
318                             ((10, 40)),
319                             ((10, 40))])
320
321        self.sizer3.AddGrowableCol(1, 1)
322        self.show_data_button()
323        self.enable_remove()
324        self.enable_import()
325        self.enable_plot()
326        self.enable_append()
327        self.enable_freeze()
328        self.enable_remove_plot()
329       
330    def layout_batch(self):
331        """
332        """
333        self.rb_single_mode = wx.RadioButton(self, -1, 'Single Mode',
334                                             style=wx.RB_GROUP)
335        self.rb_batch_mode = wx.RadioButton(self, -1, 'Batch Mode')
336        self.Bind(wx.EVT_RADIOBUTTON, self.on_single_mode,
337                     id=self.rb_single_mode.GetId())
338        self.Bind(wx.EVT_RADIOBUTTON, self.on_batch_mode,
339                   id=self.rb_batch_mode.GetId())
340       
341        self.rb_single_mode.SetValue(not self.parent.batch_on)
342        self.rb_batch_mode.SetValue(self.parent.batch_on)
343        self.sizer4.AddMany([(self.rb_single_mode,0, wx.ALL, 4),
344                             (self.rb_batch_mode,0, wx.ALL, 4)])
345       
346    def on_single_mode(self, event):
347        """
348        change guiframe to its single mode
349        """
350        if self.parent is not None:
351                wx.PostEvent(self.parent, 
352                             NewBatchEvent(enable=False))
353       
354    def on_batch_mode(self, event):
355        """
356        change guiframe to its batch mode
357        """
358        if self.parent is not None:
359                wx.PostEvent(self.parent, 
360                             NewBatchEvent(enable=True))
361     
362    def on_edit_data(self, event):
363        """
364        Pop Up Data Editor
365        """
366        selection = event.GetSelection()
367        id, _, _ = self.tree_ctrl.GetSelection().GetData()
368        data_list, _= self.parent._data_manager.get_by_id(id_list=[id])
369       
370        data = data_list.values()[0]
371        from sans.guiframe.local_perspectives.plotting.masking \
372            import MaskPanel as MaskDialog
373       
374        panel = MaskDialog(base=self, data=data, id=wx.NewId())
375        #self.panel.Bind(wx.EVT_CLOSE, self._draw_masked_model)
376        panel.ShowModal()
377       
378    def layout_data_list(self):
379        """
380        Add a listcrtl in the panel
381        """
382        tree_ctrl_label = wx.StaticText(self, -1, "Data")
383        tree_ctrl_label.SetForegroundColour('blue')
384        self.tree_ctrl = DataTreeCtrl(parent=self, style=wx.SUNKEN_BORDER)
385        self.tree_ctrl.Bind(CT.EVT_TREE_ITEM_CHECKING, self.on_check_item)
386        self.tree_ctrl.Bind(CT.EVT_TREE_ITEM_MENU, self.on_right_click)
387        ## Create context menu for page
388        self.data_menu = wx.Menu()
389        id = wx.NewId()
390        name = "Edit Mask"
391        msg = "Edit the current Data"
392        self.data_menu.Append(id, name, msg)
393        wx.EVT_MENU(self, id, self.on_edit_data)
394   
395        tree_ctrl_theory_label = wx.StaticText(self, -1, "Theory")
396        tree_ctrl_theory_label.SetForegroundColour('blue')
397        self.tree_ctrl_theory = DataTreeCtrl(parent=self, 
398                                                    style=wx.SUNKEN_BORDER)
399        self.tree_ctrl_theory.Bind(CT.EVT_TREE_ITEM_CHECKING, 
400                                                    self.on_check_item)
401        self.sizer1.Add(tree_ctrl_label, 0, wx.LEFT, 10)
402        self.sizer1.Add(self.tree_ctrl, 1, wx.EXPAND|wx.ALL, 10)
403        self.sizer1.Add(tree_ctrl_theory_label, 0,  wx.LEFT, 10)
404        self.sizer1.Add(self.tree_ctrl_theory, 1, wx.EXPAND|wx.ALL, 10)
405           
406           
407    def on_right_click(self, event):
408        """
409        Allow Editing Data
410        """
411        selection = event.GetSelection()
412        _, data_class_name, _ = self.tree_ctrl.GetSelection().GetData()
413        if data_class_name == "Data2D" and self.data_menu is not None:
414            self.PopupMenu(self.data_menu) 
415       
416    def onContextMenu(self, event): 
417        """
418        Retrieve the state selected state
419        """
420        # Skipping the save state functionality for release 0.9.0
421        #return
422        pos = event.GetPosition()
423        pos = self.ScreenToClient(pos)
424        self.PopupMenu(self.popUpMenu, pos) 
425     
426 
427    def on_check_item(self, event):
428        """
429        """
430        item = event.GetItem()
431        item.Check(not item.IsChecked()) 
432        self.enable_append()
433        self.enable_freeze()
434        self.enable_plot()
435        self.enable_import()
436        self.enable_remove()
437        event.Skip()
438       
439    def fill_cbox_analysis(self, plugin):
440        """
441        fill the combobox with analysis name
442        """
443        self.list_of_perspective = plugin
444        if self.parent is None or \
445            not hasattr(self.parent, "get_current_perspective") or \
446            len(self.list_of_perspective) == 0:
447            return
448        if self.parent is not None and self.perspective_cbox  is not None:
449            for plug in self.list_of_perspective:
450                if plug.get_perspective():
451                    self.perspective_cbox.Append(plug.sub_menu, plug)
452           
453            curr_pers = self.parent.get_current_perspective()
454            self.perspective_cbox.SetStringSelection(curr_pers.sub_menu)
455        self.enable_import()
456                       
457    def load_data_list(self, list):
458        """
459        add need data with its theory under the tree
460        """
461        if list:
462            for state_id, dstate in list.iteritems():
463                data = dstate.get_data()
464                theory_list = dstate.get_theory()
465                if data is not None:
466                    data_name = str(data.name)
467                    data_title = str(data.title)
468                    data_run = str(data.run)
469                    data_class = data.__class__.__name__
470                    path = dstate.get_path() 
471                    process_list = data.process
472                    data_id = data.id
473                    s_path = str(path)
474                    if state_id not in self.list_cb_data:
475                        #new state
476                        data_c = self.tree_ctrl.InsertItem(self.tree_ctrl.root,0,
477                                                           data_name, ct_type=1, 
478                                             data=(data_id, data_class, state_id))
479                        data_c.Check(True)
480                        d_i_c = self.tree_ctrl.AppendItem(data_c, 'Info')
481                        d_t_c = self.tree_ctrl.AppendItem(d_i_c, 
482                                                      'Title: %s' % data_title)
483                        r_n_c = self.tree_ctrl.AppendItem(d_i_c, 
484                                                      'Run: %s' % data_run)
485                        i_c_c = self.tree_ctrl.AppendItem(d_i_c, 
486                                                      'Type: %s' % data_class)
487                        p_c_c = self.tree_ctrl.AppendItem(d_i_c,
488                                                      "Path: '%s'" % s_path)
489                        d_p_c = self.tree_ctrl.AppendItem(d_i_c, 'Process')
490                       
491                        for process in process_list:
492                            process_str = str(process).replace('\n',' ')
493                            if len(process_str)>20:
494                                process_str = process_str[:20]+' [...]'
495                            i_t_c = self.tree_ctrl.AppendItem(d_p_c,
496                                                              process_str)
497                        theory_child = self.tree_ctrl.AppendItem(data_c, "THEORIES")
498                       
499                        self.list_cb_data[state_id] = [data_c, 
500                                                       d_i_c,
501                                                       d_t_c,
502                                                       r_n_c,
503                                                       i_c_c,
504                                                        p_c_c,
505                                                         d_p_c,
506                                                         theory_child]
507                    else:
508                        data_ctrl_list =  self.list_cb_data[state_id]
509                        #This state is already display replace it contains
510                        data_c, d_i_c, d_t_c, r_n_c,  i_c_c, p_c_c, d_p_c, t_c = data_ctrl_list
511                        self.tree_ctrl.SetItemText(data_c, data_name) 
512                        temp = (data_id, data_class, state_id)
513                        self.tree_ctrl.SetItemPyData(data_c, temp) 
514                        self.tree_ctrl.SetItemText(i_c_c, 'Type: %s' % data_class)
515                        self.tree_ctrl.SetItemText(p_c_c, 'Path: %s' % s_path) 
516                        self.tree_ctrl.DeleteChildren(d_p_c) 
517                        for process in process_list:
518                            i_t_c = self.tree_ctrl.AppendItem(d_p_c,
519                                                              process.__str__())
520                self.append_theory(state_id, theory_list)
521        self.enable_remove()
522        self.enable_import()
523        self.enable_plot()
524        self.enable_freeze()
525        self.enable_selection()
526       
527    def _uncheck_all(self):
528        """
529        Uncheck all check boxes
530        """
531        for item in self.list_cb_data.values():
532            data_ctrl, _, _, _, _, _,_, _ = item
533            self.tree_ctrl.CheckItem(data_ctrl, False) 
534        self.enable_append()
535        self.enable_freeze()
536        self.enable_plot()
537        self.enable_import()
538        self.enable_remove()
539   
540    def append_theory(self, state_id, theory_list):
541        """
542        append theory object under data from a state of id = state_id
543        replace that theory if  already displayed
544        """
545        if not theory_list:
546            return 
547        if state_id not in self.list_cb_data.keys():
548            root = self.tree_ctrl_theory.root
549            tree = self.tree_ctrl_theory
550        else:
551            item = self.list_cb_data[state_id]
552            data_c, _, _, _, _, _, _, _ = item
553            root = data_c
554            tree = self.tree_ctrl
555        if root is not None:
556             self.append_theory_helper(tree=tree, root=root, 
557                                       state_id=state_id, 
558                                       theory_list=theory_list)
559     
560     
561    def append_theory_helper(self, tree, root, state_id, theory_list):
562        """
563        """
564        if state_id in self.list_cb_theory.keys():
565            #update current list of theory for this data
566            theory_list_ctrl = self.list_cb_theory[state_id]
567
568            for theory_id, item in theory_list.iteritems():
569                theory_data, theory_state = item
570                if theory_data is None:
571                    name = "Unknown"
572                    theory_class = "Unknown"
573                    theory_id = "Unknown"
574                    temp = (None, None, None)
575                else:
576                    name = theory_data.name
577                    theory_class = theory_data.__class__.__name__
578                    theory_id = theory_data.id
579                    #if theory_state is not None:
580                    #    name = theory_state.model.name
581                    temp = (theory_id, theory_class, state_id)
582                if theory_id not in theory_list_ctrl:
583                    #add new theory
584                    t_child = tree.AppendItem(root,
585                                                    name, ct_type=1, data=temp)
586                    t_i_c = tree.AppendItem(t_child, 'Info')
587                    i_c_c = tree.AppendItem(t_i_c, 
588                                                  'Type: %s' % theory_class)
589                    t_p_c = tree.AppendItem(t_i_c, 'Process')
590                   
591                    for process in theory_data.process:
592                        i_t_c = tree.AppendItem(t_p_c,
593                                                          process.__str__())
594                    theory_list_ctrl[theory_id] = [t_child, 
595                                                   i_c_c, 
596                                                   t_p_c]
597                else:
598                    #replace theory
599                    t_child, i_c_c, t_p_c = theory_list_ctrl[theory_id]
600                    tree.SetItemText(t_child, name) 
601                    tree.SetItemPyData(t_child, temp) 
602                    tree.SetItemText(i_c_c, 'Type: %s' % theory_class) 
603                    tree.DeleteChildren(t_p_c) 
604                    for process in theory_data.process:
605                        i_t_c = tree.AppendItem(t_p_c,
606                                                          process.__str__())
607             
608        else:
609            #data didn't have a theory associated it before
610            theory_list_ctrl = {}
611            for theory_id, item in theory_list.iteritems():
612                theory_data, theory_state = item
613                if theory_data is not None:
614                    name = theory_data.name
615                    theory_class = theory_data.__class__.__name__
616                    theory_id = theory_data.id
617                    #if theory_state is not None:
618                    #    name = theory_state.model.name
619                    temp = (theory_id, theory_class, state_id)
620                    t_child = tree.AppendItem(root,
621                            name, ct_type=1, 
622                            data=(theory_data.id, theory_class, state_id))
623                    t_i_c = tree.AppendItem(t_child, 'Info')
624                    i_c_c = tree.AppendItem(t_i_c, 
625                                                  'Type: %s' % theory_class)
626                    t_p_c = tree.AppendItem(t_i_c, 'Process')
627                   
628                    for process in theory_data.process:
629                        i_t_c = tree.AppendItem(t_p_c,
630                                                          process.__str__())
631           
632                    theory_list_ctrl[theory_id] = [t_child, i_c_c, t_p_c]
633                #self.list_cb_theory[data_id] = theory_list_ctrl
634                self.list_cb_theory[state_id] = theory_list_ctrl
635       
636           
637   
638    def set_data_helper(self):
639        """
640        """
641        data_to_plot = []
642        state_to_plot = []
643        theory_to_plot = []
644        for value in self.list_cb_data.values():
645            item, _, _, _, _, _, _,  _ = value
646            if item.IsChecked():
647                data_id, _, state_id = self.tree_ctrl.GetItemPyData(item)
648                data_to_plot.append(data_id)
649                if state_id not in state_to_plot:
650                    state_to_plot.append(state_id)
651           
652        for theory_dict in self.list_cb_theory.values():
653            for key, value in theory_dict.iteritems():
654                item, _, _ = value
655                if item.IsChecked():
656                    theory_id, _, state_id = self.tree_ctrl.GetItemPyData(item)
657                    theory_to_plot.append(theory_id)
658                    if state_id not in state_to_plot:
659                        state_to_plot.append(state_id)
660        return data_to_plot, theory_to_plot, state_to_plot
661   
662    def remove_by_id(self, id):
663        """
664        """
665        for item in self.list_cb_data.values():
666            data_c, _, _, _, _, _,  _, theory_child = item
667            data_id, _, state_id = self.tree_ctrl.GetItemPyData(data_c) 
668            if id == data_id:
669                self.tree_ctrl.Delete(data_c)
670                del self.list_cb_data[state_id]
671                del self.list_cb_theory[data_id]
672             
673    def load_error(self, error=None):
674        """
675        Pop up an error message.
676       
677        :param error: details error message to be displayed
678        """
679        if error is not None or str(error).strip() != "":
680            dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File',
681                                wx.OK | wx.ICON_EXCLAMATION)
682            dial.ShowModal() 
683       
684    def _load_data(self, event):
685        """
686        send an event to the parent to trigger load from plugin module
687        """
688        if self.parent is not None:
689            wx.PostEvent(self.parent, NewLoadDataEvent())
690           
691
692    def on_remove(self, event):
693        """
694        Get a list of item checked and remove them from the treectrl
695        Ask the parent to remove reference to this item
696        """
697        msg = "This operation will delete the data sets checked "
698        msg += "and all the dependents."
699        msg_box = wx.MessageDialog(None, msg, 'Warning', wx.OK|wx.CANCEL)
700        if msg_box.ShowModal() != wx.ID_OK:
701            return
702       
703        data_to_remove, theory_to_remove, _ = self.set_data_helper()
704        data_key = []
705        theory_key = []
706        #remove  data from treectrl
707        for d_key, item in self.list_cb_data.iteritems():
708            data_c, d_i_c, d_t_c, r_n_c,  i_c_c, p_c_c, d_p_c, t_c = item
709            if data_c.IsChecked():
710                self.tree_ctrl.Delete(data_c)
711                data_key.append(d_key)
712                if d_key in self.list_cb_theory.keys():
713                    theory_list_ctrl = self.list_cb_theory[d_key]
714                    theory_to_remove += theory_list_ctrl.keys()
715        # Remove theory from treectrl       
716        for t_key, theory_dict in self.list_cb_theory.iteritems():
717            for  key, value in theory_dict.iteritems():
718                item, _, _ = value
719                if item.IsChecked():
720                    try:
721                        self.tree_ctrl.Delete(item)
722                    except:
723                        pass
724                    theory_key.append(key)
725                   
726        #Remove data and related theory references
727        for key in data_key:
728            del self.list_cb_data[key]
729            if key in theory_key:
730                del self.list_cb_theory[key]
731        #remove theory  references independently of data
732        for key in theory_key:
733            for t_key, theory_dict in self.list_cb_theory.iteritems():
734                if key in theory_dict:
735                    for  key, value in theory_dict.iteritems():
736                        item, _, _ = value
737                        if item.IsChecked():
738                            try:
739                                self.tree_ctrl_theory.Delete(item)
740                            except:
741                                pass
742                    del theory_dict[key]
743                   
744           
745        self.parent.remove_data(data_id=data_to_remove,
746                                  theory_id=theory_to_remove)
747        self.enable_remove()
748        self.enable_freeze()
749        self.enable_remove_plot()
750       
751    def on_import(self, event=None):
752        """
753        Get all select data and set them to the current active perspetive
754        """
755        if event != None:
756            event.Skip()
757        data_id, theory_id, state_id = self.set_data_helper()
758        temp = data_id + state_id
759        self.parent.set_data(data_id=temp, theory_id=theory_id)
760       
761    def on_append_plot(self, event=None):
762        """
763        append plot to plot panel on focus
764        """
765        self._on_plot_selection()
766        data_id, theory_id, state_id = self.set_data_helper()
767        self.parent.plot_data(data_id=data_id, 
768                              state_id=state_id,
769                              theory_id=theory_id,
770                              append=True)
771   
772    def on_plot(self, event=None):
773        """
774        Send a list of data names to plot
775        """
776        data_id, theory_id, state_id = self.set_data_helper()
777        self.parent.plot_data(data_id=data_id, 
778                              state_id=state_id,
779                              theory_id=theory_id,
780                              append=False)
781        self.enable_remove_plot()
782         
783    def on_close_page(self, event=None):
784        """
785        On close
786        """
787        if event != None:
788            event.Skip()
789        # send parent to update menu with no show nor hide action
790        self.parent.show_data_panel(action=False)
791   
792    def on_freeze(self, event):
793        """
794        On freeze to make a theory to a data set
795        """
796        _, theory_id, state_id = self.set_data_helper()
797        if len(theory_id) > 0:
798            self.parent.freeze(data_id=state_id, theory_id=theory_id)
799            msg = "Freeze Theory:"
800            msg += " The theory(s) copied to the Data box as a data set."
801        else:
802            msg = "Freeze Theory: Requires at least one theory checked."
803        wx.PostEvent(self.parent, StatusEvent(status=msg))
804           
805    def set_active_perspective(self, name):
806        """
807        set the active perspective
808        """
809        self.perspective_cbox.SetStringSelection(name)
810        self.enable_import()
811       
812    def _on_delete_plot_panel(self, event):
813        """
814        get an event with attribute name and caption to delete existing name
815        from the combobox of the current panel
816        """
817        name = event.name
818        caption = event.caption
819        if self.cb_plotpanel is not None:
820            pos = self.cb_plotpanel.FindString(str(caption)) 
821            if pos != wx.NOT_FOUND:
822                self.cb_plotpanel.Delete(pos)
823        self.enable_append()
824       
825    def set_panel_on_focus(self, name=None):
826        """
827        set the plot panel on focus
828        """
829        for key, value in self.parent.plot_panels.iteritems():
830            name_plot_panel = str(value.window_caption)
831            if name_plot_panel not in self.cb_plotpanel.GetItems():
832                self.cb_plotpanel.Append(name_plot_panel, value)
833            if name != None and name == name_plot_panel:
834                self.cb_plotpanel.SetStringSelection(name_plot_panel)
835                break
836        self.enable_append()
837        self.enable_remove_plot()
838       
839    def _on_perspective_selection(self, event=None):
840        """
841        select the current perspective for guiframe
842        """
843        selection = self.perspective_cbox.GetSelection()
844
845        if self.perspective_cbox.GetValue() != 'None':
846            perspective = self.perspective_cbox.GetClientData(selection)
847            perspective.on_perspective(event=None)
848            flag = perspective.get_batch_capable()
849            flag_on = perspective.batch_on
850            if flag:
851                self.rb_single_mode.SetValue(not flag_on)
852                self.rb_batch_mode.SetValue(flag_on)
853            else:
854                self.rb_single_mode.SetValue(True)
855                self.rb_batch_mode.SetValue(False)
856            self.rb_single_mode.Enable(flag)
857            self.rb_batch_mode.Enable(flag)
858               
859    def _on_plot_selection(self, event=None):
860        """
861        On source combobox selection
862        """
863        if event != None:
864            combo = event.GetEventObject()
865            event.Skip()
866        else:
867            combo = self.cb_plotpanel
868        selection = combo.GetSelection()
869
870        if combo.GetValue() != 'None':
871            panel = combo.GetClientData(selection)
872            self.parent.on_set_plot_focus(panel)   
873           
874    def on_close_plot(self, event):
875        """
876        clseo the panel on focus
877        """ 
878        self.enable_append()
879        selection = self.cb_plotpanel.GetSelection()
880        if self.cb_plotpanel.GetValue() != 'None':
881            panel = self.cb_plotpanel.GetClientData(selection)
882            if self.parent is not None and panel is not None:
883                wx.PostEvent(self.parent, 
884                             NewPlotEvent(group_id=panel.group_id,
885                                          action="delete"))
886        self.enable_remove_plot()
887       
888    def enable_remove_plot(self):
889        """
890        enable remove plot button if there is a plot panel on focus
891        """
892        pass
893        #if self.cb_plotpanel.GetCount() == 0:
894        #    self.bt_close_plot.Disable()
895        #else:
896        #    self.bt_close_plot.Enable()
897           
898    def enable_remove(self):
899        """
900        enable or disable remove button
901        """
902        n_t = self.tree_ctrl.GetCount()
903        n_t_t = self.tree_ctrl_theory.GetCount()
904        if n_t + n_t_t <= 0:
905            self.bt_remove.Disable()
906        else:
907            self.bt_remove.Enable()
908           
909    def enable_import(self):
910        """
911        enable or disable send button
912        """
913        n_t = 0
914        if self.tree_ctrl != None:
915            n_t = self.tree_ctrl.GetCount()
916        if n_t > 0 and len(self.list_of_perspective) > 0:
917            self.bt_import.Enable()
918        else:
919            self.bt_import.Disable()
920        if len(self.list_of_perspective) <= 0 or \
921            self.perspective_cbox.GetValue()  in ["None",
922                                                "No Active Application"]:
923            self.perspective_cbox.Disable()
924        else:
925            self.perspective_cbox.Enable()
926           
927    def enable_plot(self):
928        """
929        enable or disable plot button
930        """
931        n_t = 0 
932        n_t_t = 0
933        if self.tree_ctrl != None:
934            n_t = self.tree_ctrl.GetCount()
935        if self.tree_ctrl_theory != None:
936            n_t_t = self.tree_ctrl_theory.GetCount()
937        if n_t + n_t_t <= 0:
938            self.bt_plot.Disable()
939        else:
940            self.bt_plot.Enable()
941        self.enable_append()
942       
943    def enable_append(self):
944        """
945        enable or disable append button
946        """
947        n_t = 0 
948        n_t_t = 0
949        if self.tree_ctrl != None:
950            n_t = self.tree_ctrl.GetCount()
951        if self.tree_ctrl_theory != None:
952            n_t_t = self.tree_ctrl_theory.GetCount()
953        if n_t + n_t_t <= 0: 
954            self.bt_append_plot.Disable()
955            self.cb_plotpanel.Disable()
956        elif self.cb_plotpanel.GetCount() <= 0:
957                self.cb_plotpanel.Disable()
958                self.bt_append_plot.Disable()
959        else:
960            self.bt_append_plot.Enable()
961            self.cb_plotpanel.Enable()
962           
963    def check_theory_to_freeze(self):
964        """
965        """
966    def enable_freeze(self):
967        """
968        enable or disable the freeze button
969        """
970        n_t_t = 0
971        n_l = 0
972        if self.tree_ctrl_theory != None:
973            n_t_t = self.tree_ctrl_theory.GetCount()
974        n_l = len(self.list_cb_theory)
975        if (n_t_t + n_l > 0):
976            self.bt_freeze.Enable()
977        else:
978            self.bt_freeze.Disable()
979       
980    def enable_selection(self):
981        """
982        enable or disable combobo box selection
983        """
984        n_t = 0
985        n_t_t = 0
986        if self.tree_ctrl != None:
987            n_t = self.tree_ctrl.GetCount()
988        if self.tree_ctrl_theory != None:
989            n_t_t = self.tree_ctrl_theory.GetCount()
990        if n_t + n_t_t > 0 and self.selection_cbox != None:
991            self.selection_cbox.Enable()
992        else:
993            self.selection_cbox.Disable()
994           
995    def show_data_button(self):
996        """
997        show load data and remove data button if
998        dataloader on else hide them
999        """
1000        try:
1001            gui_style = self.parent.get_style()
1002            style = gui_style & GUIFRAME.DATALOADER_ON
1003            if style == GUIFRAME.DATALOADER_ON: 
1004                #self.bt_remove.Show(True)
1005                self.bt_add.Show(True) 
1006            else:
1007                #self.bt_remove.Hide()
1008                self.bt_add.Hide()
1009        except: 
1010            #self.bt_remove.Hide()
1011            self.bt_add.Hide() 
1012   
1013
1014
1015WIDTH = 400
1016HEIGHT = 300
1017
1018
1019class DataDialog(wx.Dialog):
1020    """
1021    Allow file selection at loading time
1022    """
1023    def __init__(self, data_list, parent=None, text='', *args, **kwds):
1024        wx.Dialog.__init__(self, parent, *args, **kwds)
1025        self.SetTitle("Data Selection")
1026        self.SetSize((WIDTH, HEIGHT))
1027        self.list_of_ctrl = []
1028        if not data_list:
1029            return 
1030        self._sizer_main = wx.BoxSizer(wx.VERTICAL)
1031        self._sizer_txt = wx.BoxSizer(wx.VERTICAL)
1032        self._sizer_button = wx.BoxSizer(wx.HORIZONTAL)
1033        self.sizer = wx.GridBagSizer(5, 5)
1034        self._panel = ScrolledPanel(self, style=wx.RAISED_BORDER,
1035                               size=(WIDTH-20, HEIGHT-50))
1036        self._panel.SetupScrolling()
1037        self.__do_layout(data_list, text=text)
1038       
1039    def __do_layout(self, data_list, text=''):
1040        """
1041        layout the dialog
1042        """
1043        if not data_list or len(data_list) <= 1:
1044            return 
1045        #add text
1046       
1047        text = "Deleting these file reset some panels.\n"
1048        text += "Do you want to proceed?\n"
1049        text_ctrl = wx.StaticText(self, -1, str(text))
1050        self._sizer_txt.Add(text_ctrl)
1051        iy = 0
1052        ix = 0
1053        data_count = 0
1054        for (data_name, in_use, sub_menu) in range(len(data_list)):
1055            if in_use == True:
1056                ctrl_name = wx.StaticBox(self, -1, str(data_name))
1057                ctrl_in_use = wx.StaticBox(self, -1, " is used by ")
1058                plug_name = str(sub_menu) + "\n"
1059                ctrl_sub_menu = wx.StaticBox(self, -1, plug_name)
1060                self.sizer.Add(ctrl_name, (iy, ix),
1061                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1062                ix += 1
1063                self._sizer_button.Add(ctrl_in_use, 1,
1064                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1065                ix += 1
1066                self._sizer_button.Add(plug_name, 1,
1067                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1068            iy += 1
1069        self._panel.SetSizer(self.sizer)
1070        #add sizer
1071        self._sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1072        button_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
1073        self._sizer_button.Add(button_cancel, 0,
1074                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
1075        button_OK = wx.Button(self, wx.ID_OK, "Ok")
1076        button_OK.SetFocus()
1077        self._sizer_button.Add(button_OK, 0,
1078                                wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
1079        static_line = wx.StaticLine(self, -1)
1080       
1081        self._sizer_txt.Add(self._panel, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
1082        self._sizer_main.Add(self._sizer_txt, 1, wx.EXPAND|wx.ALL, 10)
1083        self._sizer_main.Add(self._data_text_ctrl, 0, 
1084                             wx.EXPAND|wx.LEFT|wx.RIGHT, 10)
1085        self._sizer_main.Add(static_line, 0, wx.EXPAND, 0)
1086        self._sizer_main.Add(self._sizer_button, 0, wx.EXPAND|wx.ALL, 10)
1087        self.SetSizer(self._sizer_main)
1088        self.Layout()
1089       
1090    def get_data(self):
1091        """
1092        return the selected data
1093        """
1094        temp = []
1095        for item in self.list_of_ctrl:
1096            cb, data = item
1097            if cb.GetValue():
1098                temp.append(data)
1099        return temp
1100   
1101    def _count_selected_data(self, event):
1102        """
1103        count selected data
1104        """
1105        if event.GetEventObject().GetValue():
1106            self._nb_selected_data += 1
1107        else:
1108            self._nb_selected_data -= 1
1109        select_data_text = " %s Data selected.\n" % str(self._nb_selected_data)
1110        self._data_text_ctrl.SetLabel(select_data_text)
1111        if self._nb_selected_data <= self._max_data:
1112            self._data_text_ctrl.SetForegroundColour('blue')
1113        else:
1114            self._data_text_ctrl.SetForegroundColour('red')
1115       
1116                 
1117       
1118class DataFrame(wx.Frame):
1119    ## Internal name for the AUI manager
1120    window_name = "Data Panel"
1121    ## Title to appear on top of the window
1122    window_caption = "Data Panel"
1123    ## Flag to tell the GUI manager that this panel is not
1124    #  tied to any perspective
1125    ALWAYS_ON = True
1126   
1127    def __init__(self, parent=None, owner=None, manager=None,size=(300, 800),
1128                         list_of_perspective=[],list=[], *args, **kwds):
1129        kwds['size'] = size
1130        kwds['id'] = -1
1131        kwds['title']= "Loaded Data"
1132        wx.Frame.__init__(self, parent=parent, *args, **kwds)
1133        self.parent = parent
1134        self.owner = owner
1135        self.manager = manager
1136        self.panel = DataPanel(parent=self, 
1137                               #size=size,
1138                               list_of_perspective=list_of_perspective)
1139     
1140    def load_data_list(self, list=[]):
1141        """
1142        Fill the list inside its panel
1143        """
1144        self.panel.load_data_list(list=list)
1145       
1146   
1147   
1148from dataFitting import Data1D
1149from dataFitting import Data2D, Theory1D
1150from data_state import DataState
1151import sys
1152class State():
1153    def __init__(self):
1154        self.msg = ""
1155    def __str__(self):
1156        self.msg = "model mane : model1\n"
1157        self.msg += "params : \n"
1158        self.msg += "name  value\n"
1159        return msg
1160def set_data_state(data=None, path=None, theory=None, state=None):
1161    dstate = DataState(data=data)
1162    dstate.set_path(path=path)
1163    dstate.set_theory(theory, state)
1164 
1165    return dstate
1166"""'
1167data_list = [1:('Data1', 'Data1D', '07/01/2010', "theory1d", "state1"),
1168            ('Data2', 'Data2D', '07/03/2011', "theory2d", "state1"),
1169            ('Data3', 'Theory1D', '06/01/2010', "theory1d", "state1"),
1170            ('Data4', 'Theory2D', '07/01/2010', "theory2d", "state1"),
1171            ('Data5', 'Theory2D', '07/02/2010', "theory2d", "state1")]
1172"""     
1173if __name__ == "__main__":
1174   
1175    app = wx.App()
1176    try:
1177        list_of_perspective = [('perspective2', False), ('perspective1', True)]
1178        data_list = {}
1179        # state 1
1180        data = Data2D()
1181        data.name = "data2"
1182        data.id = 1
1183        data.append_empty_process()
1184        process = data.process[len(data.process)-1]
1185        process.data = "07/01/2010"
1186        theory = Data2D()
1187        theory.id = 34
1188        theory.name = "theory1"
1189        path = "path1"
1190        state = State()
1191        data_list['1']=set_data_state(data, path,theory, state)
1192        #state 2
1193        data = Data2D()
1194        data.name = "data2"
1195        data.id = 76
1196        theory = Data2D()
1197        theory.id = 78
1198        theory.name = "CoreShell 07/24/25"
1199        path = "path2"
1200        #state3
1201        state = State()
1202        data_list['2']=set_data_state(data, path,theory, state)
1203        data = Data1D()
1204        data.id = 3
1205        data.name = "data2"
1206        theory = Theory1D()
1207        theory.name = "CoreShell"
1208        theory.id = 4
1209        theory.append_empty_process()
1210        process = theory.process[len(theory.process)-1]
1211        process.description = "this is my description"
1212        path = "path3"
1213        data.append_empty_process()
1214        process = data.process[len(data.process)-1]
1215        process.data = "07/22/2010"
1216        data_list['4']=set_data_state(data, path,theory, state)
1217        #state 4
1218        temp_data_list = {}
1219        data.name = "data5 erasing data2"
1220        temp_data_list['4'] = set_data_state(data, path,theory, state)
1221        #state 5
1222        data = Data2D()
1223        data.name = "data3"
1224        data.id = 5
1225        data.append_empty_process()
1226        process = data.process[len(data.process)-1]
1227        process.data = "07/01/2010"
1228        theory = Theory1D()
1229        theory.name = "Cylinder"
1230        path = "path2"
1231        state = State()
1232        dstate= set_data_state(data, path,theory, state)
1233        theory = Theory1D()
1234        theory.id = 6
1235        theory.name = "CoreShell"
1236        dstate.set_theory(theory)
1237        theory = Theory1D()
1238        theory.id = 6
1239        theory.name = "CoreShell replacing coreshell in data3"
1240        dstate.set_theory(theory)
1241        data_list['3'] = dstate
1242        #state 6
1243        data_list['6']=set_data_state(None, path,theory, state)
1244        data_list['6']=set_data_state(theory=theory, state=None)
1245        theory = Theory1D()
1246        theory.id = 7
1247        data_list['6']=set_data_state(theory=theory, state=None)
1248        data_list['7']=set_data_state(theory=theory, state=None)
1249        window = DataFrame(list=data_list)
1250        window.load_data_list(list=data_list)
1251        window.Show(True)
1252        window.load_data_list(list=temp_data_list)
1253    except:
1254        #raise
1255        print "error",sys.exc_value
1256       
1257    app.MainLoop() 
1258   
1259   
Note: See TracBrowser for help on using the repository browser.