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

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 0b0b7de was 0b0b7de, checked in by Mathieu Doucet <doucetm@…>, 13 years ago

Fix problem with multi-line process entries in CanSAS1D format.

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