source: sasview/guiframe/data_panel.py @ ea4dfe0

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 ea4dfe0 was ea4dfe0, checked in by Gervaise Alina <gervyh@…>, 13 years ago

change the size of panels

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