source: sasview/fittingview/src/sans/perspectives/fitting/basepage.py @ dcbd084f

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 dcbd084f was 8a5fecd, checked in by Jae Cho <jhjcho@…>, 13 years ago

fixed back2bookmark freezing on 3 time calls

  • Property mode set to 100644
File size: 128.7 KB
Line 
1
2import sys
3import os
4import wx
5import numpy
6import time
7import copy 
8import math
9import string
10from wx.lib.scrolledpanel import ScrolledPanel
11from sans.guiframe.panel_base import PanelBase
12from sans.guiframe.utils import format_number,check_float
13from sans.guiframe.events import PanelOnFocusEvent
14from sans.guiframe.events import StatusEvent
15from sans.guiframe.events import AppendBookmarkEvent
16from sans.guiframe.dataFitting import Data2D
17from sans.guiframe.dataFitting import Data1D
18from sans.guiframe.dataFitting import check_data_validity
19from sans.dataloader.data_info import Detector
20from sans.dataloader.data_info import Source
21import pagestate
22from pagestate import PageState
23
24(PageInfoEvent, EVT_PAGE_INFO)   = wx.lib.newevent.NewEvent()
25(PreviousStateEvent, EVT_PREVIOUS_STATE)   = wx.lib.newevent.NewEvent()
26(NextStateEvent, EVT_NEXT_STATE)   = wx.lib.newevent.NewEvent()
27
28_BOX_WIDTH = 76
29_QMIN_DEFAULT = 0.0005
30_QMAX_DEFAULT = 0.5
31_NPTS_DEFAULT = 50
32#Control panel width
33if sys.platform.count("win32")> 0:
34    PANEL_WIDTH = 450
35    FONT_VARIANT = 0
36    ON_MAC = False
37else:
38    PANEL_WIDTH = 500
39    FONT_VARIANT = 1
40    ON_MAC = True
41
42
43
44class BasicPage(ScrolledPanel, PanelBase):
45    """
46    This class provide general structure of  fitpanel page
47    """
48     ## Internal name for the AUI manager
49    window_name = "Fit Page"
50    ## Title to appear on top of the window
51    window_caption = "Fit Page "
52   
53    def __init__(self, parent,color='blue', **kwargs):
54        """
55        """
56        ScrolledPanel.__init__(self, parent, **kwargs)
57        PanelBase.__init__(self, parent)
58        self.SetupScrolling()
59        #Set window's font size
60        self.SetWindowVariant(variant=FONT_VARIANT)
61     
62        self.SetBackgroundColour(color)
63        ## parent of the page
64        self.parent = parent
65        ## manager is the fitting plugin
66        ## owner of the page (fitting plugin)
67        self.event_owner = None
68         ## current model
69        self.model = None
70        self.index_model = None
71        ## data
72        self.data = None
73        #list of available data
74        self.data_list = []
75        self.mask = None
76        self.uid = wx.NewId()
77        self.graph_id = None
78        #Q range for data set
79        self.qmin_data_set = numpy.inf
80        self.qmax_data_set = None
81        self.npts_data_set = 0
82        ## Q range
83        self.qmin = None
84        self.qmax = None
85        self.qmax_x = _QMAX_DEFAULT
86        self.qmin_x = _QMIN_DEFAULT
87        self.npts_x = _NPTS_DEFAULT
88        ## total number of point: float
89        self.npts = None
90        ## default fitengine type
91        self.engine_type = 'scipy'
92        ## smear default
93        self.current_smearer = None
94        ## 2D smear accuracy default
95        self.smear2d_accuracy = 'Low'
96        ## slit smear:
97        self.dxl = None
98        self.dxw = None
99        ## pinhole smear
100        self.dx_min = None
101        self.dx_max = None
102       
103        self.disp_cb_dict = {}
104   
105        self.state = PageState(parent=parent)
106        ## dictionary containing list of models
107        self.model_list_box = {}
108       
109        ## Data member to store the dispersion object created
110        self._disp_obj_dict = {}
111        ## selected parameters to apply dispersion
112        self.disp_cb_dict ={}
113        ## smearer object
114        self.enable2D = False
115        self.is_mac = ON_MAC
116       
117        ##list of model parameters. each item must have same length
118        ## each item related to a given parameters
119        ##[cb state, name, value, "+/-", error of fit, min, max , units]
120        self.parameters = []
121        # non-fittable parameter whose value is astring
122        self.str_parameters = []
123        ## list of parameters to fit , must be like self.parameters
124        self.param_toFit = []
125        ## list of looking like parameters but with non fittable parameters info
126        self.fixed_param = []
127        ## list of looking like parameters but with  fittable parameters info
128        self.fittable_param = []
129        ##list of dispersion parameters
130        self.disp_list = []
131        self.disp_name = ""
132       
133        ## list of orientation parameters
134        self.orientation_params = []
135        self.orientation_params_disp = []
136        if self.model != None:
137            self.disp_list = self.model.getDispParamList()
138        self.temp_multi_functional = False
139        ##enable model 2D draw
140        self.enable2D = False
141        ## check that the fit range is correct to plot the model again
142        self.fitrange = True
143        ## Create memento to save the current state
144        self.state = PageState(parent=self.parent,
145                               model=self.model, data=self.data)
146        ## flag to determine if state has change
147        self.state_change = False
148        ## save customized array
149        self.values = []
150        self.weights = []
151        ## retrieve saved state
152        self.number_saved_state = 0
153        ## dictionary of saved state
154        self.saved_states = {} 
155        ## Create context menu for page
156        self.popUpMenu = wx.Menu()
157   
158        id = wx.NewId()
159        self._keep = wx.MenuItem(self.popUpMenu,id,"Add bookmark",
160                                 " Keep the panel status to recall it later")
161        self.popUpMenu.AppendItem(self._keep)
162        self._keep.Enable(False)
163        self._set_bookmark_flag(False)
164        self._set_save_flag(False)
165        wx.EVT_MENU(self, id, self.on_bookmark)
166        self.popUpMenu.AppendSeparator()
167   
168        ## Default locations
169        self._default_save_location = os.getcwd()     
170        ## save initial state on context menu
171        #self.onSave(event=None)
172        self.Bind(wx.EVT_CONTEXT_MENU, self.onContextMenu)
173       
174        # bind key event
175        self.Bind(wx.EVT_LEFT_DOWN, self.on_left_down)
176       
177        ## create the basic structure of the panel with empty sizer
178        self.define_page_structure()
179        ## drawing Initial dispersion parameters sizer
180        self.set_dispers_sizer()
181       
182        ## layout
183        self.set_layout()
184   
185    def set_index_model(self, index):
186        """
187        Index related to this page
188        """
189        self.index_model = index
190       
191    def create_default_data(self):
192        """
193        Given the user selection, creates a 1D or 2D data
194        Only when the page is on theory mode.
195        """
196        if not hasattr(self, "model_view"):
197            return
198        toggle_mode_on = self.model_view.IsEnabled()
199        if toggle_mode_on:
200            if self.enable2D and not check_data_validity(self.data):
201                self._create_default_2d_data()
202            else:
203                self._create_default_1d_data()
204       
205    def _create_default_1d_data(self):
206        """
207        Create default data for fitting perspective
208        Only when the page is on theory mode.
209        :warning: This data is never plotted.
210       
211        """
212        x = numpy.linspace(start=self.qmin_x, stop=self.qmax_x, 
213                           num=self.npts_x, endpoint=True)
214        self.data = Data1D(x=x)
215        self.data.xaxis('\\rm{Q}',"A^{-1}")
216        self.data.yaxis('\\rm{Intensity}', "cm^{-1}")
217        self.data.is_data = False
218        self.data.id = str(self.uid) + " data" 
219        self.data.group_id = str(self.uid) + " Model1D" 
220       
221    def _create_default_2d_data(self):
222        """
223        Create 2D data by default
224        Only when the page is on theory mode.
225        :warning: This data is never plotted.
226        """
227        self.data = Data2D()
228        qmax = self.qmax_x / math.sqrt(2)
229        self.data.xaxis('\\rm{Q_{x}}', 'A^{-1}')
230        self.data.yaxis('\\rm{Q_{y}}', 'A^{-1}')
231        self.data.is_data = False
232        self.data.id = str(self.uid) + " data" 
233        self.data.group_id = str(self.uid) + " Model2D" 
234        ## Default values   
235        self.data.detector.append(Detector()) 
236        index = len(self.data.detector) - 1
237        self.data.detector[index].distance = 8000   # mm       
238        self.data.source.wavelength= 6         # A     
239        self.data.detector[index].pixel_size.x = 5  # mm
240        self.data.detector[index].pixel_size.y = 5  # mm
241        self.data.detector[index].beam_center.x = qmax
242        self.data.detector[index].beam_center.y = qmax
243        ## create x_bins and y_bins of the model 2D
244        pixel_width_x = self.data.detector[index].pixel_size.x
245        pixel_width_y = self.data.detector[index].pixel_size.y
246        center_x = self.data.detector[index].beam_center.x/pixel_width_x
247        center_y = self.data.detector[index].beam_center.y/pixel_width_y
248        # theory default: assume the beam
249        #center is located at the center of sqr detector
250        xmax = qmax
251        xmin = -qmax
252        ymax = qmax
253        ymin = -qmax
254        qstep = self.npts_x
255
256        x = numpy.linspace(start=xmin, stop=xmax, num=qstep, endpoint=True) 
257        y = numpy.linspace(start=ymin, stop=ymax, num=qstep, endpoint=True)
258        ## use data info instead
259        new_x = numpy.tile(x, (len(y), 1))
260        new_y = numpy.tile(y, (len(x), 1))
261        new_y = new_y.swapaxes(0,1)
262        # all data reuire now in 1d array
263        qx_data = new_x.flatten()
264        qy_data = new_y.flatten()
265        q_data = numpy.sqrt(qx_data*qx_data + qy_data*qy_data)
266        # set all True (standing for unmasked) as default
267        mask = numpy.ones(len(qx_data), dtype=bool)
268        # calculate the range of qx and qy: this way,
269        # it is a little more independent
270        x_size = xmax - xmin
271        y_size = ymax - ymin
272        # store x and y bin centers in q space
273        x_bins  = x
274        y_bins  = y
275        # bin size: x- & y-directions
276        xstep = x_size/len(x_bins-1)
277        ystep = y_size/len(y_bins-1)
278 
279        self.data.source = Source()
280        self.data.data = numpy.ones(len(mask))
281        self.data.err_data = numpy.ones(len(mask))
282        self.data.qx_data = qx_data
283        self.data.qy_data = qy_data 
284        self.data.q_data = q_data
285        self.data.mask = mask           
286        self.data.x_bins = x_bins 
287        self.data.y_bins = y_bins   
288        # max and min taking account of the bin sizes
289        self.data.xmin = xmin
290        self.data.xmax = xmax
291        self.data.ymin = ymin
292        self.data.ymax = ymax
293
294    def on_set_focus(self, event):
295        """
296        On Set Focus, update guimanger and menu
297        """
298        if self._manager is not None:
299            wx.PostEvent(self._manager.parent, PanelOnFocusEvent(panel=self))
300            self.on_tap_focus()
301               
302    def on_tap_focus(self):
303        """
304        Update menu1 on cliking the page tap
305        """
306        if self._manager.menu1 != None:
307            chain_menu = self._manager.menu1.FindItemById(\
308                                                    self._manager.id_reset_flag)
309            chain_menu.Enable(self.batch_on)
310            sim_menu = self._manager.menu1.FindItemById(self._manager.id_simfit)
311            sim_menu.Enable(not self.batch_on and self.data.is_data\
312                            and (self.model!=None)) 
313   
314    class ModelTextCtrl(wx.TextCtrl):
315        """
316        Text control for model and fit parameters.
317        Binds the appropriate events for user interactions.
318        Default callback methods can be overwritten on initialization
319       
320        :param kill_focus_callback: callback method for EVT_KILL_FOCUS event
321        :param set_focus_callback:  callback method for EVT_SET_FOCUS event
322        :param mouse_up_callback:   callback method for EVT_LEFT_UP event
323        :param text_enter_callback: callback method for EVT_TEXT_ENTER event
324       
325        """
326        ## Set to True when the mouse is clicked while the whole string is selected
327        full_selection = False
328        ## Call back for EVT_SET_FOCUS events
329        _on_set_focus_callback = None
330       
331        def __init__(self, parent, id=-1, 
332                     value=wx.EmptyString, 
333                     pos=wx.DefaultPosition, 
334                     size=wx.DefaultSize,
335                     style=0, 
336                     validator=wx.DefaultValidator,
337                     name=wx.TextCtrlNameStr,
338                     kill_focus_callback=None,
339                     set_focus_callback=None,
340                     mouse_up_callback=None,
341                     text_enter_callback = None):
342             
343            wx.TextCtrl.__init__(self, parent, id, value, pos,
344                                  size, style, validator, name)
345           
346            # Bind appropriate events
347            self._on_set_focus_callback = parent.onSetFocus \
348                      if set_focus_callback is None else set_focus_callback
349            self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus)
350            self.Bind(wx.EVT_KILL_FOCUS, self._silent_kill_focus \
351                      if kill_focus_callback is None else kill_focus_callback)               
352            self.Bind(wx.EVT_TEXT_ENTER, parent._onparamEnter \
353                      if text_enter_callback is None else text_enter_callback)
354            if not ON_MAC :
355                self.Bind(wx.EVT_LEFT_UP,    self._highlight_text \
356                          if mouse_up_callback is None else mouse_up_callback)
357           
358        def _on_set_focus(self, event):
359            """
360            Catch when the text control is set in focus to highlight the whole
361            text if necessary
362           
363            :param event: mouse event
364           
365            """
366            event.Skip()
367            self.full_selection = True
368            return self._on_set_focus_callback(event)
369       
370 
371           
372        def _highlight_text(self, event):
373            """
374            Highlight text of a TextCtrl only of no text has be selected
375           
376            :param event: mouse event
377           
378            """
379            # Make sure the mouse event is available to other listeners
380            event.Skip()
381            control  = event.GetEventObject()
382            if self.full_selection:
383                self.full_selection = False
384                # Check that we have a TextCtrl
385                if issubclass(control.__class__, wx.TextCtrl):
386                    # Check whether text has been selected,
387                    # if not, select the whole string
388                    (start, end) = control.GetSelection()
389                    if start==end:
390                        control.SetSelection(-1,-1)
391                       
392        def _silent_kill_focus(self,event):
393            """
394            Save the state of the page
395            """
396           
397            event.Skip()
398            pass
399   
400    def set_page_info(self, page_info):
401        """
402        set some page important information at once
403        """
404       ##window_name
405        self.window_name = page_info.window_name
406        ##window_caption
407        self.window_caption = page_info.window_caption
408        ## manager is the fitting plugin
409        self._manager= page_info.manager
410        ## owner of the page (fitting plugin)
411        self.event_owner= page_info.event_owner
412         ## current model
413        self.model = page_info.model
414        ## data
415        self.data = page_info.data
416        ## dictionary containing list of models
417        self.model_list_box = page_info.model_list_box
418        ## Data member to store the dispersion object created
419        self.populate_box(dict=self.model_list_box)
420       
421    def onContextMenu(self, event): 
422        """
423        Retrieve the state selected state
424        """
425        # Skipping the save state functionality for release 0.9.0
426        #return
427   
428        pos = event.GetPosition()
429        pos = self.ScreenToClient(pos)
430       
431        self.PopupMenu(self.popUpMenu, pos) 
432     
433       
434    def onUndo(self, event):
435        """
436        Cancel the previous action
437        """
438        event = PreviousStateEvent(page = self)
439        wx.PostEvent(self.parent, event)
440       
441    def onRedo(self, event):
442        """
443        Restore the previous action cancelled
444        """
445        event = NextStateEvent(page= self)
446        wx.PostEvent(self.parent, event)
447   
448    def define_page_structure(self):
449        """
450        Create empty sizer for a panel
451        """
452        self.vbox  = wx.BoxSizer(wx.VERTICAL)
453        self.sizer0 = wx.BoxSizer(wx.VERTICAL)
454        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
455        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
456        self.sizer3 = wx.BoxSizer(wx.VERTICAL)
457        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
458        self.sizer5 = wx.BoxSizer(wx.VERTICAL)
459        self.sizer6 = wx.BoxSizer(wx.VERTICAL)
460       
461        self.sizer0.SetMinSize((PANEL_WIDTH,-1))
462        self.sizer1.SetMinSize((PANEL_WIDTH,-1))
463        self.sizer2.SetMinSize((PANEL_WIDTH,-1))
464        self.sizer3.SetMinSize((PANEL_WIDTH,-1))
465        self.sizer4.SetMinSize((PANEL_WIDTH,-1))
466        self.sizer5.SetMinSize((PANEL_WIDTH,-1))
467        self.sizer6.SetMinSize((PANEL_WIDTH,-1))
468       
469        self.vbox.Add(self.sizer0)
470        self.vbox.Add(self.sizer1)
471        self.vbox.Add(self.sizer2)
472        self.vbox.Add(self.sizer3)
473        self.vbox.Add(self.sizer4)
474        self.vbox.Add(self.sizer5)
475        self.vbox.Add(self.sizer6)
476       
477    def set_layout(self):
478        """
479        layout
480        """
481        self.vbox.Layout()
482        self.vbox.Fit(self) 
483        self.SetSizer(self.vbox)
484        self.Centre()
485 
486    def set_owner(self,owner):
487        """
488        set owner of fitpage
489       
490        :param owner: the class responsible of plotting
491       
492        """
493        self.event_owner = owner   
494        self.state.event_owner = owner
495       
496    def get_state(self):
497        """
498        """
499        return self.state
500   
501    def get_data(self):
502        """
503        return the current data
504        """
505        return self.data 
506   
507    def get_data_list(self):
508        """
509        return the current data
510        """
511        return self.data_list 
512   
513    def set_manager(self, manager):
514        """
515        set panel manager
516       
517        :param manager: instance of plugin fitting
518       
519        """
520        self._manager = manager 
521        self.state.manager = manager
522       
523    def populate_box(self, dict):
524        """
525        Store list of model
526       
527        :param dict: dictionary containing list of models
528       
529        """
530        self.model_list_box = dict
531        self.state.model_list_box = self.model_list_box
532        self.initialize_combox()
533       
534    def initialize_combox(self): 
535        """
536        put default value in the combobox
537        """ 
538        ## fill combox box
539        if self.model_list_box is None:
540            return
541        if len(self.model_list_box) > 0:
542            self._populate_box(self.formfactorbox,
543                               self.model_list_box["Shapes"])
544       
545        if len(self.model_list_box) > 0:
546            self._populate_box(self.structurebox,
547                                self.model_list_box["Structure Factors"])
548            self.structurebox.Insert("None", 0, None)
549            self.structurebox.SetSelection(0)
550            self.structurebox.Hide()
551            self.text2.Hide()
552            self.structurebox.Disable()
553            self.text2.Disable()
554             
555            if self.model.__class__ in self.model_list_box["P(Q)*S(Q)"]:
556                self.structurebox.Show()
557                self.text2.Show()
558                self.structurebox.Enable()
559                self.text2.Enable()           
560               
561    def set_dispers_sizer(self):
562        """
563        fill sizer containing dispersity info
564        """
565        self.sizer4.Clear(True)
566        name="Polydispersity and Orientational Distribution"
567        box_description= wx.StaticBox(self, -1,name)
568        box_description.SetForegroundColour(wx.BLUE)
569        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
570        #----------------------------------------------------
571        self.disable_disp = wx.RadioButton(self, -1, 'Off', (10, 10),
572                                            style=wx.RB_GROUP)
573        self.enable_disp = wx.RadioButton(self, -1, 'On', (10, 30))
574        # best size for MAC and PC
575        if ON_MAC:
576            size_q = (30, 20)     
577        else:
578            size_q = (20, 15)   
579        self.disp_help_bt = wx.Button(self,wx.NewId(),'?', 
580                                      style = wx.BU_EXACTFIT,
581                                      size=size_q)
582        self.disp_help_bt.Bind(wx.EVT_BUTTON, 
583                        self.on_pd_help_clicked,id= self.disp_help_bt.GetId())
584        self.disp_help_bt.SetToolTipString("Helps for Polydispersion.")       
585       
586        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param,
587                     id=self.disable_disp.GetId())
588        self.Bind(wx.EVT_RADIOBUTTON, self._set_dipers_Param,
589                   id=self.enable_disp.GetId())
590        #MAC needs SetValue
591        self.disable_disp.SetValue(True)
592        sizer_dispersion = wx.BoxSizer(wx.HORIZONTAL)
593        sizer_dispersion.Add((20,20))
594        name=""#Polydispersity and \nOrientational Distribution "
595        sizer_dispersion.Add(wx.StaticText(self,-1,name))
596        sizer_dispersion.Add(self.enable_disp )
597        sizer_dispersion.Add((20,20))
598        sizer_dispersion.Add(self.disable_disp )
599        sizer_dispersion.Add((25,20))
600        sizer_dispersion.Add(self.disp_help_bt)
601       
602        ## fill a sizer for dispersion         
603        boxsizer1.Add( sizer_dispersion,0,
604                wx.TOP|wx.BOTTOM|wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE,border=5)
605        #boxsizer1.Add( (10,10) )
606        #boxsizer1.Add( sizer_select_dispers )
607        self.sizer4_4 = wx.GridBagSizer(6,5)
608
609        boxsizer1.Add( self.sizer4_4  )
610        #-----------------------------------------------------
611        self.sizer4.Add(boxsizer1,0, wx.EXPAND | wx.ALL, 10)
612        self.sizer4_4.Layout()
613        self.sizer4.Layout()
614        self.Layout()
615     
616        self.Refresh()
617        ## saving the state of enable dispersity button
618        self.state.enable_disp= self.enable_disp.GetValue()
619        self.state.disable_disp= self.disable_disp.GetValue()
620        self.SetupScrolling()
621
622   
623    def onResetModel(self, event):
624        """
625        Reset model state
626        """
627        menu = event.GetEventObject()
628        ## post help message for the selected model
629        msg = menu.GetHelpString(event.GetId())
630        msg +=" reloaded"
631        wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
632        self.Show(False)
633        name = menu.GetLabel(event.GetId())
634        self._on_select_model_helper()
635        if name in self.saved_states.keys():
636            previous_state = self.saved_states[name]
637            ## reset state of checkbox,textcrtl  and  regular parameters value
638           
639            self.reset_page(previous_state)   
640        self.Show(True)
641               
642    def on_preview(self, event):
643        """
644        Report the current fit results
645        """   
646        # Get plot image from plotpanel
647        images, canvases = self.get_images()
648        # get the report dialog
649        self.state.report(images, canvases)
650       
651         
652    def on_save(self, event):   
653        """
654        Save the current state into file
655        """ 
656        self.save_current_state()
657        new_state = self.state.clone()
658        # Ask the user the location of the file to write to.
659        path = None
660        if self.parent !=  None:
661            self._default_save_location = \
662                        self.parent.parent._default_save_location
663        dlg = wx.FileDialog(self, "Choose a file", self._default_save_location,
664                                        self.window_caption, "*.fitv", wx.SAVE)
665
666        if dlg.ShowModal() == wx.ID_OK:
667            path = dlg.GetPath()
668            self._default_save_location = os.path.dirname(path)
669            self.parent.parent._default_save_location =\
670                                 self._default_save_location
671        else:
672            return None
673        # MAC always needs the extension for saving
674        extens = ".fitv"
675        # Make sure the ext included in the file name
676        fName = os.path.splitext(path)[0] + extens
677        #the manager write the state into file
678        self._manager.save_fit_state(filepath=fName, fitstate=new_state)
679        return new_state 
680   
681    def on_copy(self, event):
682        """
683        Copy Parameter values to the clipboad
684        """
685        if event != None:
686            event.Skip()
687        # It seems MAC needs wxCallAfter
688        wx.CallAfter(self.get_copy)
689       
690        # messages depending on the flag
691        #self._copy_info(None)
692       
693    def on_paste(self, event):
694        """
695        Paste Parameter values to the panel if possible
696        """
697        if event != None:
698            event.Skip()
699        # It seems MAC needs wxCallAfter for the setvalues
700        # for multiple textctrl items, otherwise it tends to crash once a while.
701        wx.CallAfter(self.get_paste)
702        # messages depending on the flag
703        #self._copy_info(True)
704       
705    def _copy_info(self, flag):
706        """
707        Send event dpemding on flag
708       
709        : Param flag: flag that distinguish event
710        """
711        # messages depending on the flag
712        if flag == None:
713            msg = " Parameter values are copied to the clipboard..."
714            infor = 'warning'
715        elif flag:
716            msg = " Parameter values are pasted from the clipboad..."
717            infor = "warning"
718        else:
719            msg = "Error was occured "
720            msg += ": No valid parameter values to paste from the clipboard..."
721            infor = "error"
722        # inform msg to wx
723        wx.PostEvent( self.parent.parent, 
724                      StatusEvent(status= msg, info=infor))
725       
726    def _get_time_stamp(self):
727        """
728        return time and date stings
729        """
730        # date and time
731        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
732        current_time= str(hour)+":"+str(minute)+":"+str(second)
733        current_date= str( month)+"/"+str(day)+"/"+str(year)
734        return current_time, current_date
735     
736    def on_bookmark(self, event):
737        """
738        save history of the data and model
739        """
740        if self.model==None:
741            msg="Can not bookmark; Please select Data and Model first..."
742            wx.MessageBox(msg, 'Info')
743            return 
744        self.save_current_state()
745        new_state = self.state.clone()
746        ##Add model state on context menu
747        self.number_saved_state += 1
748        current_time, current_date = self._get_time_stamp()
749        #name= self.model.name+"[%g]"%self.number_saved_state
750        name = "Fitting: %g]" % self.number_saved_state
751        name += self.model.__class__.__name__
752        name += "bookmarked at %s on %s" % (current_time, current_date)
753        self.saved_states[name]= new_state
754       
755        ## Add item in the context menu
756        msg =  "Model saved at %s on %s"%(current_time, current_date)
757         ## post help message for the selected model
758        msg +=" Saved! right click on this page to retrieve this model"
759        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
760       
761        id = wx.NewId()
762        self.popUpMenu.Append(id,name,str(msg))
763        wx.EVT_MENU(self, id, self.onResetModel)
764        wx.PostEvent(self.parent.parent, 
765                     AppendBookmarkEvent(title=name, 
766                                         hint=str(msg), handler=self._back_to_bookmark))
767    def _back_to_bookmark(self, event): 
768        """
769        Back to bookmark
770        """
771        self._manager.on_perspective(event)
772        self.onResetModel(event)
773        self._draw_model()
774        #self.save_current_state()
775       
776       
777    def old_on_bookmark(self, event):
778        """
779        save history of the data and model
780        """
781        if self.model==None:
782            msg="Can not bookmark; Please select Data and Model first..."
783            wx.MessageBox(msg, 'Info')
784            return 
785        if hasattr(self,"enable_disp"):
786            self.state.enable_disp = copy.deepcopy(self.enable_disp.GetValue())
787        if hasattr(self, "disp_box"):
788            self.state.disp_box = copy.deepcopy(self.disp_box.GetSelection())
789
790        self.state.model.name= self.model.name
791       
792        #Remember fit engine_type for fit panel
793        if self.engine_type == None: 
794            self.engine_type = "scipy"
795        if self._manager !=None:
796            self._manager._on_change_engine(engine=self.engine_type)
797       
798            self.state.engine_type = self.engine_type
799
800        new_state = self.state.clone()
801        new_state.model.name = self.state.model.name
802       
803        new_state.enable2D = copy.deepcopy(self.enable2D)
804        ##Add model state on context menu
805        self.number_saved_state += 1
806        #name= self.model.name+"[%g]"%self.number_saved_state
807        name= self.model.__class__.__name__+"[%g]"%self.number_saved_state
808        self.saved_states[name]= new_state
809       
810        ## Add item in the context menu
811       
812        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
813        my_time= str(hour)+" : "+str(minute)+" : "+str(second)+" "
814        date= str( month)+"|"+str(day)+"|"+str(year)
815        msg=  "Model saved at %s on %s"%(my_time, date)
816         ## post help message for the selected model
817        msg +=" Saved! right click on this page to retrieve this model"
818        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
819       
820        id = wx.NewId()
821        self.popUpMenu.Append(id,name,str(msg))
822        wx.EVT_MENU(self, id, self.onResetModel)
823       
824    def onSetFocus(self, evt):
825        """
826        highlight the current textcrtl and hide the error text control shown
827        after fitting
828        """
829        return
830   
831    def read_file(self, path):
832        """
833        Read two columns file
834       
835        :param path: the path to the file to read
836       
837        """
838        try:
839            if path==None:
840                wx.PostEvent(self.parent.parent, StatusEvent(status=\
841                            " Selected Distribution was not loaded: %s"%path))
842                return None, None
843            input_f = open(path, 'r')
844            buff = input_f.read()
845            lines = buff.split('\n')
846           
847            angles = []
848            weights=[]
849            for line in lines:
850                toks = line.split()
851                try:
852                    angle = float(toks[0])
853                    weight = float(toks[1])
854                except:
855                    # Skip non-data lines
856                    pass
857                angles.append(angle)
858                weights.append(weight)
859            return numpy.array(angles), numpy.array(weights)
860        except:
861            raise 
862
863    def createMemento(self):
864        """
865        return the current state of the page
866        """
867        return self.state.clone()
868   
869   
870    def save_current_state(self):
871        """
872        Store current state
873        """
874        self.state.engine_type = copy.deepcopy(self.engine_type)
875        ## save model option
876        if self.model!= None:
877            self.disp_list= self.model.getDispParamList()
878            self.state.disp_list= copy.deepcopy(self.disp_list)
879            self.state.model = self.model.clone()
880        #save radiobutton state for model selection
881        self.state.shape_rbutton = self.shape_rbutton.GetValue()
882        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
883        self.state.struct_rbutton = self.struct_rbutton.GetValue()
884        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
885        #model combobox
886        self.state.structurebox = self.structurebox.GetSelection()
887        self.state.formfactorbox = self.formfactorbox.GetSelection()
888       
889        self.state.enable2D = copy.deepcopy(self.enable2D)
890        self.state.values= copy.deepcopy(self.values)
891        self.state.weights = copy.deepcopy( self.weights)
892        ## save data   
893        self.state.data= copy.deepcopy(self.data)
894        self.state.qmax_x = self.qmax_x
895        self.state.qmin_x = self.qmin_x
896        self.state.dI_noweight = copy.deepcopy(self.dI_noweight.GetValue())
897        self.state.dI_didata = copy.deepcopy(self.dI_didata.GetValue())
898        self.state.dI_sqrdata = copy.deepcopy(self.dI_sqrdata.GetValue())
899        self.state.dI_idata = copy.deepcopy(self.dI_idata.GetValue())
900        self.state.dq_l = self.dq_l
901        self.state.dq_r = self.dq_r
902        if hasattr(self,"enable_disp"):
903            self.state.enable_disp= self.enable_disp.GetValue()
904            self.state.disable_disp = self.disable_disp.GetValue()
905           
906        self.state.smearer = copy.deepcopy(self.current_smearer)
907        if hasattr(self,"enable_smearer"):
908            self.state.enable_smearer = \
909                                copy.deepcopy(self.enable_smearer.GetValue())
910            self.state.disable_smearer = \
911                                copy.deepcopy(self.disable_smearer.GetValue())
912
913        self.state.pinhole_smearer = \
914                                copy.deepcopy(self.pinhole_smearer.GetValue())
915        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 
916                 
917        if len(self._disp_obj_dict)>0:
918            for k , v in self._disp_obj_dict.iteritems():
919                self.state._disp_obj_dict[k]= v
920                       
921           
922            self.state.values = copy.deepcopy(self.values)
923            self.state.weights = copy.deepcopy(self.weights)
924        ## save plotting range
925        self._save_plotting_range()
926       
927        self.state.orientation_params = []
928        self.state.orientation_params_disp = []
929        self.state.parameters = []
930        self.state.fittable_param = []
931        self.state.fixed_param = []
932        self.state.str_parameters = []
933
934       
935        ## save checkbutton state and txtcrtl values
936        self._copy_parameters_state(self.str_parameters, 
937                                    self.state.str_parameters)
938        self._copy_parameters_state(self.orientation_params,
939                                     self.state.orientation_params)
940        self._copy_parameters_state(self.orientation_params_disp,
941                                     self.state.orientation_params_disp)
942       
943        self._copy_parameters_state(self.parameters, self.state.parameters)
944        self._copy_parameters_state(self.fittable_param,
945                                     self.state.fittable_param)
946        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
947        #save chisqr
948        self.state.tcChi = self.tcChi.GetValue()
949       
950    def save_current_state_fit(self):
951        """
952        Store current state for fit_page
953        """
954        ## save model option
955        if self.model!= None:
956            self.disp_list= self.model.getDispParamList()
957            self.state.disp_list= copy.deepcopy(self.disp_list)
958            self.state.model = self.model.clone()
959        if hasattr(self, "engine_type"):
960            self.state.engine_type = copy.deepcopy(self.engine_type)
961           
962        self.state.enable2D = copy.deepcopy(self.enable2D)
963        self.state.values= copy.deepcopy(self.values)
964        self.state.weights = copy.deepcopy( self.weights)
965        ## save data   
966        self.state.data= copy.deepcopy(self.data)
967       
968        if hasattr(self,"enable_disp"):
969            self.state.enable_disp= self.enable_disp.GetValue()
970            self.state.disable_disp = self.disable_disp.GetValue()
971           
972        self.state.smearer = copy.deepcopy(self.current_smearer)
973        if hasattr(self,"enable_smearer"):
974            self.state.enable_smearer = \
975                                copy.deepcopy(self.enable_smearer.GetValue())
976            self.state.disable_smearer = \
977                                copy.deepcopy(self.disable_smearer.GetValue())
978           
979        self.state.pinhole_smearer = \
980                                copy.deepcopy(self.pinhole_smearer.GetValue())
981        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 
982        self.state.dI_noweight = copy.deepcopy(self.dI_noweight.GetValue())
983        self.state.dI_didata = copy.deepcopy(self.dI_didata.GetValue())
984        self.state.dI_sqrdata = copy.deepcopy(self.dI_sqrdata.GetValue())
985        self.state.dI_idata = copy.deepcopy(self.dI_idata.GetValue()) 
986        if hasattr(self,"disp_box"):
987            self.state.disp_box = self.disp_box.GetCurrentSelection()
988
989            if len(self.disp_cb_dict) > 0:
990                for k, v in self.disp_cb_dict.iteritems():
991         
992                    if v == None :
993                        self.state.disp_cb_dict[k] = v
994                    else:
995                        try:
996                            self.state.disp_cb_dict[k] = v.GetValue()
997                        except:
998                            self.state.disp_cb_dict[k] = None
999           
1000            if len(self._disp_obj_dict) > 0:
1001                for k , v in self._disp_obj_dict.iteritems():
1002     
1003                    self.state._disp_obj_dict[k] = v
1004                       
1005           
1006            self.state.values = copy.deepcopy(self.values)
1007            self.state.weights = copy.deepcopy(self.weights)
1008           
1009        ## save plotting range
1010        self._save_plotting_range()
1011       
1012        ## save checkbutton state and txtcrtl values
1013        self._copy_parameters_state(self.orientation_params,
1014                                     self.state.orientation_params)
1015        self._copy_parameters_state(self.orientation_params_disp,
1016                                     self.state.orientation_params_disp)
1017        self._copy_parameters_state(self.parameters, self.state.parameters)
1018        self._copy_parameters_state(self.fittable_param,
1019                                             self.state.fittable_param)
1020        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
1021   
1022         
1023    def check_invalid_panel(self): 
1024        """
1025        check if the user can already perform some action with this panel
1026        """ 
1027        flag = False
1028        if self.data is None:
1029            self.disable_smearer.SetValue(True)
1030            self.disable_disp.SetValue(True)
1031            msg = "Please load Data and select Model to start..."
1032            wx.MessageBox(msg, 'Info')
1033            return  True
1034       
1035    def set_model_state(self, state):
1036        """
1037        reset page given a model state
1038        """
1039        self.disp_cb_dict = state.disp_cb_dict
1040        self.disp_list = state.disp_list
1041     
1042        ## set the state of the radio box
1043        self.shape_rbutton.SetValue(state.shape_rbutton )
1044        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
1045        self.struct_rbutton.SetValue(state.struct_rbutton)
1046        self.plugin_rbutton.SetValue(state.plugin_rbutton)
1047       
1048        ## fill model combobox
1049        self._show_combox_helper()
1050        #select the current model
1051        self.formfactorbox.Select(int(state.formfactorcombobox))
1052        self.structurebox.SetSelection(state.structurecombobox )
1053        if state.multi_factor != None:
1054            self.multifactorbox.SetSelection(state.multi_factor)
1055           
1056         ## reset state of checkbox,textcrtl  and  regular parameters value
1057        self._reset_parameters_state(self.orientation_params_disp,
1058                                     state.orientation_params_disp)
1059        self._reset_parameters_state(self.orientation_params,
1060                                     state.orientation_params)
1061        self._reset_parameters_state(self.str_parameters,
1062                                     state.str_parameters)
1063        self._reset_parameters_state(self.parameters,state.parameters)
1064         ## display dispersion info layer       
1065        self.enable_disp.SetValue(state.enable_disp)
1066        self.disable_disp.SetValue(state.disable_disp)
1067       
1068        if hasattr(self, "disp_box"):
1069           
1070            self.disp_box.SetSelection(state.disp_box) 
1071            n= self.disp_box.GetCurrentSelection()
1072            dispersity= self.disp_box.GetClientData(n)
1073            name = dispersity.__name__     
1074
1075            self._set_dipers_Param(event=None)
1076       
1077            if name == "ArrayDispersion":
1078               
1079                for item in self.disp_cb_dict.keys():
1080                   
1081                    if hasattr(self.disp_cb_dict[item], "SetValue") :
1082                        self.disp_cb_dict[item].SetValue(\
1083                                                    state.disp_cb_dict[item])
1084                        # Create the dispersion objects
1085                        from sans.models.dispersion_models import ArrayDispersion
1086                        disp_model = ArrayDispersion()
1087                        if hasattr(state,"values")and\
1088                                 self.disp_cb_dict[item].GetValue() == True:
1089                            if len(state.values)>0:
1090                                self.values=state.values
1091                                self.weights=state.weights
1092                                disp_model.set_weights(self.values,
1093                                                        state.weights)
1094                            else:
1095                                self._reset_dispersity()
1096                       
1097                        self._disp_obj_dict[item] = disp_model
1098                        # Set the new model as the dispersion object
1099                        #for the selected parameter
1100                        self.model.set_dispersion(item, disp_model)
1101                   
1102                        self.model._persistency_dict[item] = \
1103                                                [state.values, state.weights]
1104                   
1105            else:
1106                keys = self.model.getParamList()
1107                for item in keys:
1108                    if item in self.disp_list and \
1109                        not self.model.details.has_key(item):
1110                        self.model.details[item] = ["", None, None]
1111                for k,v in self.state.disp_cb_dict.iteritems():
1112                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1113                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1114         ## smearing info  restore
1115        if hasattr(self, "enable_smearer"):
1116            ## set smearing value whether or not the data
1117            #contain the smearing info
1118            self.enable_smearer.SetValue(state.enable_smearer)
1119            self.disable_smearer.SetValue(state.disable_smearer)
1120            self.onSmear(event=None)           
1121        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1122        self.slit_smearer.SetValue(state.slit_smearer)
1123       
1124        self.dI_noweight.SetValue(state.dI_noweight)
1125        self.dI_didata.SetValue(state.dI_didata)
1126        self.dI_sqrdata.SetValue(state.dI_sqrdata)
1127        self.dI_idata.SetValue(state.dI_idata)
1128       
1129        ## we have two more options for smearing
1130        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1131        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1132       
1133        ## reset state of checkbox,textcrtl  and dispersity parameters value
1134        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1135        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1136       
1137        ## draw the model with previous parameters value
1138        self._onparamEnter_helper()
1139        self.select_param(event=None) 
1140        #Save state_fit
1141        self.save_current_state_fit()
1142        self._lay_out()
1143        self.Refresh()
1144       
1145    def reset_page_helper(self, state):
1146        """
1147        Use page_state and change the state of existing page
1148       
1149        :precondition: the page is already drawn or created
1150       
1151        :postcondition: the state of the underlying data change as well as the
1152            state of the graphic interface
1153        """
1154        if state == None:
1155            #self._undo.Enable(False)
1156            return 
1157        # set data, etc. from the state
1158        # reset page between theory and fitting from bookmarking
1159        #if state.data == None:
1160        #    data = None
1161        #else:
1162        data = state.data
1163
1164        #if data != None:
1165       
1166        if data == None:
1167            data_min = state.qmin
1168            data_max = state.qmax
1169            self.qmin_x = data_min
1170            self.qmax_x = data_max
1171            #self.minimum_q.SetValue(str(data_min))
1172            #self.maximum_q.SetValue(str(data_max))
1173            self.qmin.SetValue(str(data_min))
1174            self.qmax.SetValue(str(data_max))
1175
1176            self.state.data = data
1177            self.state.qmin = self.qmin_x
1178            self.state.qmax = self.qmax_x
1179        else:
1180            self.set_data(data)
1181           
1182        self.enable2D= state.enable2D
1183        self.engine_type = state.engine_type
1184
1185        self.disp_cb_dict = state.disp_cb_dict
1186        self.disp_list = state.disp_list
1187     
1188        ## set the state of the radio box
1189        self.shape_rbutton.SetValue(state.shape_rbutton )
1190        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
1191        self.struct_rbutton.SetValue(state.struct_rbutton)
1192        self.plugin_rbutton.SetValue(state.plugin_rbutton)
1193       
1194        ## fill model combobox
1195        self._show_combox_helper()
1196        #select the current model
1197        self.formfactorbox.Select(int(state.formfactorcombobox))
1198        self.structurebox.SetSelection(state.structurecombobox )
1199        if state.multi_factor != None:
1200            self.multifactorbox.SetSelection(state.multi_factor)
1201
1202        #reset the fitting engine type
1203        self.engine_type = state.engine_type
1204        #draw the pnael according to the new model parameter
1205        self._on_select_model(event=None)
1206        # take care of 2D button
1207        if data == None and self.model_view.IsEnabled():
1208            if self.enable2D:
1209                self.model_view.SetLabel("2D Mode")
1210            else:
1211                self.model_view.SetLabel("1D Mode")
1212        # else:
1213               
1214        if self._manager !=None and self.engine_type != None:
1215            self._manager._on_change_engine(engine=self.engine_type)
1216        ## set the select all check box to the a given state
1217        self.cb1.SetValue(state.cb1)
1218     
1219        ## reset state of checkbox,textcrtl  and  regular parameters value
1220        self._reset_parameters_state(self.orientation_params_disp,
1221                                     state.orientation_params_disp)
1222        self._reset_parameters_state(self.orientation_params,
1223                                     state.orientation_params)
1224        self._reset_parameters_state(self.str_parameters,
1225                                     state.str_parameters)
1226        self._reset_parameters_state(self.parameters,state.parameters)   
1227         ## display dispersion info layer       
1228        self.enable_disp.SetValue(state.enable_disp)
1229        self.disable_disp.SetValue(state.disable_disp)
1230        # If the polydispersion is ON
1231        if state.enable_disp:
1232            # reset dispersion according the state
1233            self._set_dipers_Param(event=None)
1234            self._reset_page_disp_helper(state)
1235        ##plotting range restore   
1236        self._reset_plotting_range(state)
1237        ## smearing info  restore
1238        if hasattr(self, "enable_smearer"):
1239            ## set smearing value whether or not the data
1240            #contain the smearing info
1241            self.enable_smearer.SetValue(state.enable_smearer)
1242            self.disable_smearer.SetValue(state.disable_smearer)
1243            self.onSmear(event=None)           
1244        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1245        self.slit_smearer.SetValue(state.slit_smearer)
1246        try:
1247            self.dI_noweight.SetValue(state.dI_noweight)
1248            self.dI_didata.SetValue(state.dI_didata)
1249            self.dI_sqrdata.SetValue(state.dI_sqrdata)
1250            self.dI_idata.SetValue(state.dI_idata)
1251        except:
1252            # to support older state file formats
1253            self.dI_noweight.SetValue(False)
1254            self.dI_didata.SetValue(True)
1255            self.dI_sqrdata.SetValue(False)
1256            self.dI_idata.SetValue(False)
1257 
1258        ## we have two more options for smearing
1259        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1260        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1261       
1262        ## reset state of checkbox,textcrtl  and dispersity parameters value
1263        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1264        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1265       
1266        ## draw the model with previous parameters value
1267        self._onparamEnter_helper()
1268        #reset the value of chisqr when not consistent with the value computed
1269        self.tcChi.SetValue(str(self.state.tcChi))
1270        ## reset context menu items
1271        self._reset_context_menu()
1272       
1273        ## set the value of the current state to the state given as parameter
1274        self.state = state.clone() 
1275   
1276    def _reset_page_disp_helper(self, state):
1277        """
1278        Help to rest page for dispersions
1279        """
1280        keys = self.model.getParamList()
1281        for item in keys:
1282            if item in self.disp_list and \
1283                not self.model.details.has_key(item):
1284                self.model.details[item] = ["", None, None]
1285        #for k,v in self.state.disp_cb_dict.iteritems():
1286        self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1287        self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1288        self.values = copy.deepcopy(state.values)
1289        self.weights = copy.deepcopy(state.weights)
1290       
1291        for key, disp in state._disp_obj_dict.iteritems():
1292            # From saved file, disp_model can not be sent in model obj.
1293            # it will be sent as a string here, then converted to model object.
1294            if disp.__class__.__name__ == 'str':
1295                com_str  = "from sans.models.dispersion_models "
1296                com_str += "import %s as disp_func"
1297                exec com_str % disp
1298                disp_model = disp_func()
1299            else:
1300                disp_model = disp
1301
1302            self._disp_obj_dict[key] = disp_model
1303            param_name = key.split('.')[0]
1304            # Try to set dispersion only when available
1305            # for eg., pass the orient. angles for 1D Cal
1306            try:
1307                self.model.set_dispersion(param_name, disp_model)
1308                self.model._persistency_dict[key] = \
1309                                 [state.values, state.weights]
1310            except:
1311                pass
1312            selection = self._find_polyfunc_selection(disp_model)
1313            for list in self.fittable_param:
1314                if list[1] == key and list[7] != None:
1315                    list[7].SetSelection(selection)
1316                    # For the array disp_model, set the values and weights
1317                    if selection == 1:
1318                        disp_model.set_weights(self.values[key], 
1319                                              self.weights[key])
1320                        try:
1321                            # Diables all fittable params for array
1322                            list[0].SetValue(False)
1323                            list[0].Disable()
1324                            list[2].Disable()
1325                            list[5].Disable()
1326                            list[6].Disable()
1327                        except:
1328                            pass
1329            # For array, disable all fixed params
1330            if selection == 1:
1331                for item in self.fixed_param:
1332                    if item[1].split(".")[0] == key.split(".")[0]:
1333                        # try it and pass it for the orientation for 1D
1334                        try:
1335                            item[2].Disable()
1336                        except:
1337                            pass
1338   
1339        # Make sure the check box updated when all checked
1340        if self.cb1.GetValue():
1341            self.select_all_param(None)       
1342     
1343    def _selectDlg(self):
1344        """
1345        open a dialog file to selected the customized dispersity
1346        """
1347        import os
1348        if self.parent !=  None:
1349            self._default_save_location = \
1350                        self.parent.parent._default_save_location
1351        dlg = wx.FileDialog(self, "Choose a weight file",
1352                                self._default_save_location , "", 
1353                                "*.*", wx.OPEN)
1354        path = None
1355        if dlg.ShowModal() == wx.ID_OK:
1356            path = dlg.GetPath()
1357        dlg.Destroy()
1358        return path
1359
1360    def _reset_context_menu(self):
1361        """
1362        reset the context menu
1363        """
1364        for name, state in self.state.saved_states.iteritems():
1365            self.number_saved_state += 1
1366            ## Add item in the context menu
1367            id = wx.NewId()
1368            msg = 'Save model and state %g' % self.number_saved_state
1369            self.popUpMenu.Append(id, name, msg)
1370            wx.EVT_MENU(self, id, self.onResetModel)
1371   
1372    def _reset_plotting_range(self, state):
1373        """
1374        Reset the plotting range to a given state
1375        """
1376        # if self.check_invalid_panel():
1377        #    return
1378        self.qmin.SetValue(str(state.qmin))
1379        self.qmax.SetValue(str(state.qmax)) 
1380
1381    def _save_typeOfmodel(self):
1382        """
1383        save radiobutton containing the type model that can be selected
1384        """
1385        self.state.shape_rbutton = self.shape_rbutton.GetValue()
1386        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
1387        self.state.struct_rbutton = self.struct_rbutton.GetValue()
1388        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
1389        self.state.structurebox= self.structurebox.GetCurrentSelection()
1390        self.state.formfactorbox = self.formfactorbox.GetCurrentSelection()
1391       
1392        #self._undo.Enable(True)
1393        ## post state to fit panel
1394        event = PageInfoEvent(page = self)
1395        wx.PostEvent(self.parent, event)
1396       
1397    def _save_plotting_range(self ):
1398        """
1399        save the state of plotting range
1400        """
1401        self.state.qmin = self.qmin_x
1402        self.state.qmax = self.qmax_x
1403        self.state.npts = self.npts_x
1404           
1405    def _onparamEnter_helper(self):
1406        """
1407        check if values entered by the user are changed and valid to replot
1408        model
1409        """
1410        # Flag to register when a parameter has changed.   
1411        is_modified = False
1412        self.fitrange = True
1413        is_2Ddata = False
1414        #self._undo.Enable(True)
1415        # check if 2d data
1416        if self.data.__class__.__name__ == "Data2D":
1417            is_2Ddata = True
1418        if self.model !=None:
1419            try:
1420                is_modified = self._check_value_enter(self.fittable_param,
1421                                                     is_modified)
1422                is_modified = self._check_value_enter(self.fixed_param,
1423                                                      is_modified)
1424                is_modified = self._check_value_enter(self.parameters,
1425                                                      is_modified) 
1426            except:
1427                pass
1428            #if is_modified:
1429
1430            # Here we should check whether the boundaries have been modified.
1431            # If qmin and qmax have been modified, update qmin and qmax and
1432            # set the is_modified flag to True
1433            if self._validate_qrange(self.qmin, self.qmax):
1434                tempmin = float(self.qmin.GetValue())
1435                if tempmin != self.qmin_x:
1436                    self.qmin_x = tempmin
1437                    is_modified = True
1438                tempmax = float(self.qmax.GetValue())
1439                if tempmax != self.qmax_x:
1440                    self.qmax_x = tempmax
1441                    is_modified = True
1442           
1443                if is_2Ddata:
1444                    # set mask   
1445                    is_modified = self._validate_Npts()
1446                   
1447            else:
1448                self.fitrange = False   
1449            ## if any value is modify draw model with new value
1450            if not self.fitrange:
1451                #self.btFit.Disable()
1452                if is_2Ddata: self.btEditMask.Disable()
1453            else:
1454                #self.btFit.Enable(True)
1455                if is_2Ddata  and not self.batch_on: 
1456                    self.btEditMask.Enable(True)
1457            if is_modified and self.fitrange:
1458                #if self.data == None:
1459                # Theory case: need to get npts value to draw
1460                self.npts_x = float(self.Npts_total.GetValue())
1461                self.create_default_data()
1462                self.state_change= True
1463                self._draw_model() 
1464                self.Refresh()
1465        return is_modified
1466   
1467    def _update_paramv_on_fit(self):
1468        """
1469        make sure that update param values just before the fitting
1470        """
1471        #flag for qmin qmax check values
1472        flag = True
1473        self.fitrange = True
1474        is_modified = False
1475
1476        #wx.PostEvent(self._manager.parent, StatusEvent(status=" \
1477        #updating ... ",type="update"))
1478
1479        ##So make sure that update param values on_Fit.
1480        #self._undo.Enable(True)
1481        if self.model !=None:           
1482            ##Check the values
1483            self._check_value_enter( self.fittable_param ,is_modified)
1484            self._check_value_enter( self.fixed_param ,is_modified)
1485            self._check_value_enter( self.parameters ,is_modified)
1486
1487            # If qmin and qmax have been modified, update qmin and qmax and
1488             # Here we should check whether the boundaries have been modified.
1489            # If qmin and qmax have been modified, update qmin and qmax and
1490            # set the is_modified flag to True
1491            self.fitrange = self._validate_qrange(self.qmin, self.qmax)
1492            if self.fitrange:
1493                tempmin = float(self.qmin.GetValue())
1494                if tempmin != self.qmin_x:
1495                    self.qmin_x = tempmin
1496                tempmax = float(self.qmax.GetValue())
1497                if tempmax != self.qmax_x:
1498                    self.qmax_x = tempmax
1499                if tempmax == tempmin:
1500                    flag = False   
1501                temp_smearer = None
1502                if not self.disable_smearer.GetValue():
1503                    temp_smearer= self.current_smearer
1504                    if self.slit_smearer.GetValue():
1505                        flag = self.update_slit_smear()
1506                    elif self.pinhole_smearer.GetValue():
1507                        flag = self.update_pinhole_smear()
1508                    else:
1509                        self._manager.set_smearer(smearer=temp_smearer,
1510                                                  uid=self.uid,
1511                                                  fid=self.data.id,
1512                                                     qmin=float(self.qmin_x),
1513                                                      qmax=float(self.qmax_x),
1514                            enable_smearer=not self.disable_smearer.GetValue(),
1515                                                      draw=False)
1516                elif not self._is_2D():
1517                    self._manager.set_smearer(smearer=temp_smearer,
1518                                              qmin=float(self.qmin_x),
1519                                              uid=self.uid, 
1520                                              fid=self.data.id,
1521                                                 qmax= float(self.qmax_x),
1522                            enable_smearer=not self.disable_smearer.GetValue(),
1523                                                 draw=False)
1524                    if self.data != None:
1525                        index_data = ((self.qmin_x <= self.data.x)&\
1526                                      (self.data.x <= self.qmax_x))
1527                        val = str(len(self.data.x[index_data==True]))
1528                        self.Npts_fit.SetValue(val)
1529                    else:
1530                        # No data in the panel
1531                        try:
1532                            self.npts_x = float(self.Npts_total.GetValue())
1533                        except:
1534                            flag = False
1535                            return flag
1536                    flag = True
1537                if self._is_2D():
1538                    # only 2D case set mask 
1539                    flag = self._validate_Npts()
1540                    if not flag:
1541                        return flag
1542            else: flag = False
1543        else: 
1544            flag = False
1545
1546        #For invalid q range, disable the mask editor and fit button, vs.   
1547        if not self.fitrange:
1548            #self.btFit.Disable()
1549            if self._is_2D():
1550                self.btEditMask.Disable()
1551        else:
1552            #self.btFit.Enable(True)
1553            if self._is_2D() and  self.data != None and not self.batch_on:
1554                self.btEditMask.Enable(True)
1555
1556        if not flag:
1557            msg = "Cannot Plot or Fit :Must select a "
1558            msg += " model or Fitting range is not valid!!!  "
1559            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
1560       
1561        self.save_current_state()
1562   
1563        return flag                           
1564               
1565    def _is_modified(self, is_modified):
1566        """
1567        return to self._is_modified
1568        """
1569        return is_modified
1570                       
1571    def _reset_parameters_state(self, listtorestore, statelist):
1572        """
1573        Reset the parameters at the given state
1574        """
1575        if len(statelist) == 0 or len(listtorestore) == 0:
1576            return
1577        if len(statelist) !=  len(listtorestore):
1578            return
1579
1580        for j in range(len(listtorestore)):
1581            item_page = listtorestore[j]
1582            item_page_info = statelist[j]
1583            ##change the state of the check box for simple parameters
1584            if item_page[0]!=None:   
1585                item_page[0].SetValue(item_page_info[0])
1586            if item_page[2]!=None:
1587                item_page[2].SetValue(item_page_info[2])
1588                if item_page[2].__class__.__name__ == "ComboBox":
1589                   if self.model.fun_list.has_key(item_page_info[2]):
1590                       fun_val = self.model.fun_list[item_page_info[2]]
1591                       self.model.setParam(item_page_info[1],fun_val)
1592            if item_page[3]!=None:
1593                ## show or hide text +/-
1594                if item_page_info[2]:
1595                    item_page[3].Show(True)
1596                else:
1597                    item_page[3].Hide()
1598            if item_page[4]!=None:
1599                ## show of hide the text crtl for fitting error
1600                if item_page_info[4][0]:
1601                    item_page[4].Show(True)
1602                    item_page[4].SetValue(item_page_info[4][1])
1603                else:
1604                    item_page[3].Hide()
1605            if item_page[5]!=None:
1606                ## show of hide the text crtl for fitting error
1607                item_page[5].Show(item_page_info[5][0])
1608                item_page[5].SetValue(item_page_info[5][1])
1609               
1610            if item_page[6]!=None:
1611                ## show of hide the text crtl for fitting error
1612                item_page[6].Show(item_page_info[6][0])
1613                item_page[6].SetValue(item_page_info[6][1])
1614
1615                   
1616    def _reset_strparam_state(self, listtorestore, statelist):
1617        """
1618        Reset the string parameters at the given state
1619        """
1620        if len(statelist) == 0:
1621            return
1622
1623        listtorestore = copy.deepcopy(statelist)
1624       
1625        for j in range(len(listtorestore)):
1626            item_page = listtorestore[j]
1627            item_page_info = statelist[j]
1628            ##change the state of the check box for simple parameters
1629           
1630            if item_page[0] != None:   
1631                item_page[0].SetValue(format_number(item_page_info[0], True))
1632
1633            if item_page[2] != None:
1634                param_name = item_page_info[1]
1635                value = item_page_info[2]
1636                selection = value
1637                if self.model.fun_list.has_key(value):
1638                    selection = self.model.fun_list[value]
1639                item_page[2].SetValue(selection)
1640                self.model.setParam(param_name, selection)
1641                                     
1642    def _copy_parameters_state(self, listtocopy, statelist):
1643        """
1644        copy the state of button
1645       
1646        :param listtocopy: the list of check button to copy
1647        :param statelist: list of state object to store the current state
1648       
1649        """
1650        if len(listtocopy)==0:
1651            return
1652       
1653        for item in listtocopy:
1654 
1655            checkbox_state = None
1656            if item[0]!= None:
1657                checkbox_state= item[0].GetValue()
1658            parameter_name = item[1]
1659            parameter_value = None
1660            if item[2]!=None:
1661                parameter_value = item[2].GetValue()
1662            static_text = None
1663            if item[3]!=None:
1664                static_text = item[3].IsShown()
1665            error_value = None
1666            error_state = None
1667            if item[4]!= None:
1668                error_value = item[4].GetValue()
1669                error_state = item[4].IsShown()
1670               
1671            min_value = None
1672            min_state = None
1673            if item[5]!= None:
1674                min_value = item[5].GetValue()
1675                min_state = item[5].IsShown()
1676               
1677            max_value = None
1678            max_state = None
1679            if item[6]!= None:
1680                max_value = item[6].GetValue()
1681                max_state = item[6].IsShown()
1682            unit=None
1683            if item[7]!=None:
1684                unit = item[7].GetLabel()
1685               
1686            statelist.append([checkbox_state, parameter_name, parameter_value,
1687                              static_text ,[error_state, error_value],
1688                                [min_state, min_value],
1689                                [max_state, max_value], unit])
1690           
1691    def _set_model_sizer_selection(self, model):
1692        """
1693        Display the sizer according to the type of the current model
1694        """
1695        if model == None:
1696            return
1697        if hasattr(model ,"s_model"):
1698           
1699            class_name = model.s_model.__class__
1700            name = model.s_model.name
1701            flag = (name != "NoStructure")
1702            if flag and \
1703                (class_name in self.model_list_box["Structure Factors"]):
1704                self.structurebox.Show()
1705                self.text2.Show()               
1706                self.structurebox.Enable()
1707                self.text2.Enable()
1708                items = self.structurebox.GetItems()
1709                self.sizer1.Layout()
1710               
1711                for i in range(len(items)):
1712                    if items[i]== str(name):
1713                        self.structurebox.SetSelection(i)
1714                        break
1715                   
1716        if hasattr(model ,"p_model"):
1717            class_name = model.p_model.__class__
1718            name = model.p_model.name
1719            self.formfactorbox.Clear()
1720           
1721            for k, list in self.model_list_box.iteritems():
1722                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
1723                    self.shape_rbutton.SetValue(True)
1724                    ## fill the form factor list with new model
1725                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
1726                    items = self.formfactorbox.GetItems()
1727                    ## set comboxbox to the selected item
1728                    for i in range(len(items)):
1729                        if items[i]== str(name):
1730                            self.formfactorbox.SetSelection(i)
1731                            break
1732                    return
1733                elif k == "Shape-Independent":
1734                    self.shape_indep_rbutton.SetValue(True)
1735                elif k == "Structure Factors":
1736                     self.struct_rbutton.SetValue(True)
1737                elif  k == "Multi-Functions":
1738                    continue
1739                else:
1740                    self.plugin_rbutton.SetValue(True)
1741               
1742                if class_name in list:
1743                    ## fill the form factor list with new model
1744                    self._populate_box(self.formfactorbox, list)
1745                    items = self.formfactorbox.GetItems()
1746                    ## set comboxbox to the selected item
1747                    for i in range(len(items)):
1748                        if items[i]== str(name):
1749                            self.formfactorbox.SetSelection(i)
1750                            break
1751                    break
1752        else:
1753
1754            ## Select the model from the menu
1755            class_name = model.__class__
1756            name = model.name
1757            self.formfactorbox.Clear()
1758            items = self.formfactorbox.GetItems()
1759   
1760            for k, list in self.model_list_box.iteritems():         
1761                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
1762                    if class_name in self.model_list_box["P(Q)*S(Q)"]:
1763                        self.structurebox.Show()
1764                        self.text2.Show()
1765                        self.structurebox.Enable()
1766                        self.structurebox.SetSelection(0)
1767                        self.text2.Enable()
1768                    else:
1769                        self.structurebox.Hide()
1770                        self.text2.Hide()
1771                        self.structurebox.Disable()
1772                        self.structurebox.SetSelection(0)
1773                        self.text2.Disable()
1774                       
1775                    self.shape_rbutton.SetValue(True)
1776                    ## fill the form factor list with new model
1777                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
1778                    items = self.formfactorbox.GetItems()
1779                    ## set comboxbox to the selected item
1780                    for i in range(len(items)):
1781                        if items[i]== str(name):
1782                            self.formfactorbox.SetSelection(i)
1783                            break
1784                    return
1785                elif k == "Shape-Independent":
1786                    self.shape_indep_rbutton.SetValue(True)
1787                elif k == "Structure Factors":
1788                    self.struct_rbutton.SetValue(True)
1789                elif  k == "Multi-Functions":
1790                    continue
1791                else:
1792                    self.plugin_rbutton.SetValue(True)
1793                if class_name in list:
1794                    self.structurebox.SetSelection(0)
1795                    self.structurebox.Disable()
1796                    self.text2.Disable()                   
1797                    ## fill the form factor list with new model
1798                    self._populate_box(self.formfactorbox, list)
1799                    items = self.formfactorbox.GetItems()
1800                    ## set comboxbox to the selected item
1801                    for i in range(len(items)):
1802                        if items[i]== str(name):
1803                            self.formfactorbox.SetSelection(i)
1804                            break
1805                    break
1806               
1807    def _draw_model(self, update_chisqr=True, source='model'):
1808        """
1809        Method to draw or refresh a plotted model.
1810        The method will use the data member from the model page
1811        to build a call to the fitting perspective manager.
1812       
1813        :param chisqr: update chisqr value [bool]
1814        """
1815        wx.CallAfter(self._draw_model_after, update_chisqr, source)
1816       
1817    def _draw_model_after(self, update_chisqr=True, source='model'):
1818        """
1819        Method to draw or refresh a plotted model.
1820        The method will use the data member from the model page
1821        to build a call to the fitting perspective manager.
1822       
1823        :param chisqr: update chisqr value [bool]
1824        """
1825        #if self.check_invalid_panel():
1826        #    return
1827        if self.model !=None:
1828            temp_smear=None
1829            if hasattr(self, "enable_smearer"):
1830                if not self.disable_smearer.GetValue():
1831                    temp_smear= self.current_smearer
1832            # compute weight for the current data
1833            from .utils import get_weight
1834            flag = self.get_weight_flag()
1835            weight = get_weight(data=self.data, is2d=self._is_2D(), flag=flag)
1836            toggle_mode_on = self.model_view.IsEnabled()
1837            is_2d = self._is_2D()
1838            self._manager.draw_model(self.model, 
1839                                    data=self.data,
1840                                    smearer= temp_smear,
1841                                    qmin=float(self.qmin_x), 
1842                                    qmax=float(self.qmax_x),
1843                                    page_id=self.uid,
1844                                    toggle_mode_on=toggle_mode_on, 
1845                                    state = self.state,
1846                                    enable2D=is_2d,
1847                                    update_chisqr=update_chisqr,
1848                                    source='model',
1849                                    weight=weight)
1850       
1851       
1852    def _on_show_sld(self, event=None):
1853        """
1854        Plot SLD profile
1855        """
1856        # get profile data
1857        x,y=self.model.getProfile()
1858
1859        from danse.common.plottools import Data1D
1860        #from sans.perspectives.theory.profile_dialog import SLDPanel
1861        from sans.guiframe.local_perspectives.plotting.profile_dialog \
1862        import SLDPanel
1863        sld_data = Data1D(x,y)
1864        sld_data.name = 'SLD'
1865        sld_data.axes = self.sld_axes
1866        self.panel = SLDPanel(self, data=sld_data, axes =self.sld_axes,id =-1)
1867        self.panel.ShowModal()   
1868       
1869    def _set_multfactor_combobox(self, multiplicity=10):   
1870        """
1871        Set comboBox for muitfactor of CoreMultiShellModel
1872        :param multiplicit: no. of multi-functionality
1873        """
1874        # build content of the combobox
1875        for idx in range(0,multiplicity):
1876            self.multifactorbox.Append(str(idx),int(idx))
1877            #self.multifactorbox.SetSelection(1)
1878        self._hide_multfactor_combobox()
1879       
1880    def _show_multfactor_combobox(self):   
1881        """
1882        Show the comboBox of muitfactor of CoreMultiShellModel
1883        """ 
1884        if not self.mutifactor_text.IsShown():
1885            self.mutifactor_text.Show(True)
1886            self.mutifactor_text1.Show(True)
1887        if not self.multifactorbox.IsShown():
1888            self.multifactorbox.Show(True) 
1889             
1890    def _hide_multfactor_combobox(self):   
1891        """
1892        Hide the comboBox of muitfactor of CoreMultiShellModel
1893        """ 
1894        if self.mutifactor_text.IsShown():
1895            self.mutifactor_text.Hide()
1896            self.mutifactor_text1.Hide()
1897        if self.multifactorbox.IsShown():
1898            self.multifactorbox.Hide()   
1899
1900       
1901    def _show_combox_helper(self):
1902        """
1903        Fill panel's combo box according to the type of model selected
1904        """
1905        if self.shape_rbutton.GetValue():
1906            ##fill the combobox with form factor list
1907            self.structurebox.SetSelection(0)
1908            self.structurebox.Disable()
1909            self.formfactorbox.Clear()
1910            self._populate_box( self.formfactorbox,self.model_list_box["Shapes"])
1911        if self.shape_indep_rbutton.GetValue():
1912            ##fill the combobox with shape independent  factor list
1913            self.structurebox.SetSelection(0)
1914            self.structurebox.Disable()
1915            self.formfactorbox.Clear()
1916            self._populate_box( self.formfactorbox,
1917                                self.model_list_box["Shape-Independent"])
1918        if self.struct_rbutton.GetValue():
1919            ##fill the combobox with structure factor list
1920            self.structurebox.SetSelection(0)
1921            self.structurebox.Disable()
1922            self.formfactorbox.Clear()
1923            self._populate_box( self.formfactorbox,
1924                                self.model_list_box["Structure Factors"])
1925        if self.plugin_rbutton.GetValue():
1926            ##fill the combobox with form factor list
1927            self.structurebox.Disable()
1928            self.formfactorbox.Clear()
1929            self._populate_box( self.formfactorbox,
1930                                self.model_list_box["Customized Models"])
1931       
1932    def _show_combox(self, event=None):
1933        """
1934        Show combox box associate with type of model selected
1935        """
1936        #if self.check_invalid_panel():
1937        #    self.shape_rbutton.SetValue(True)
1938        #    return
1939        self.Show(False)
1940        self._show_combox_helper()
1941        self._on_select_model(event=None)
1942        self.Show(True)
1943        self._save_typeOfmodel()
1944        self.sizer4_4.Layout()
1945        self.sizer4.Layout()
1946        self.Layout()
1947        self.Refresh()
1948 
1949    def _populate_box(self, combobox, list):
1950        """
1951        fill combox box with dict item
1952       
1953        :param list: contains item to fill the combox
1954            item must model class
1955        """
1956        for models in list:
1957            model= models()
1958            name = model.__class__.__name__
1959            if models.__name__!="NoStructure":
1960                if hasattr(model, "name"):
1961                    name = model.name
1962                combobox.Append(name,models)
1963        return 0
1964   
1965    def _onQrangeEnter(self, event):
1966        """
1967        Check validity of value enter in the Q range field
1968       
1969        """
1970        tcrtl = event.GetEventObject()
1971        #Clear msg if previously shown.
1972        msg = ""
1973        wx.PostEvent(self.parent, StatusEvent(status=msg))
1974        # Flag to register when a parameter has changed.
1975        is_modified = False
1976        if tcrtl.GetValue().lstrip().rstrip() != "":
1977            try:
1978                value = float(tcrtl.GetValue())
1979                tcrtl.SetBackgroundColour(wx.WHITE)
1980                # If qmin and qmax have been modified, update qmin and qmax
1981                if self._validate_qrange(self.qmin, self.qmax):
1982                    tempmin = float(self.qmin.GetValue())
1983                    if tempmin != self.qmin_x:
1984                        self.qmin_x = tempmin
1985                    tempmax = float(self.qmax.GetValue())
1986                    if tempmax != self.qmax_x:
1987                        self.qmax_x = tempmax
1988                else:
1989                    tcrtl.SetBackgroundColour("pink")
1990                    msg = "Model Error:wrong value entered : %s" % sys.exc_value
1991                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1992                    return 
1993            except:
1994                tcrtl.SetBackgroundColour("pink")
1995                msg = "Model Error:wrong value entered : %s" % sys.exc_value
1996                wx.PostEvent(self.parent, StatusEvent(status=msg))
1997                return 
1998            #Check if # of points for theory model are valid(>0).
1999            if self.npts != None:
2000                if check_float(self.npts):
2001                    temp_npts = float(self.npts.GetValue())
2002                    if temp_npts !=  self.num_points:
2003                        self.num_points = temp_npts
2004                        is_modified = True
2005                else:
2006                    msg = "Cannot Plot :No npts in that Qrange!!!  "
2007                    wx.PostEvent(self.parent, StatusEvent(status=msg))
2008        else:
2009           tcrtl.SetBackgroundColour("pink")
2010           msg = "Model Error:wrong value entered!!!"
2011           wx.PostEvent(self.parent, StatusEvent(status=msg))
2012        #self._undo.Enable(True)
2013        self.save_current_state()
2014        event = PageInfoEvent(page=self)
2015        wx.PostEvent(self.parent, event)
2016        self.state_change = False
2017        #Draw the model for a different range
2018        self.create_default_data()
2019        self._draw_model()
2020                   
2021    def _theory_qrange_enter(self, event):
2022        """
2023        Check validity of value enter in the Q range field
2024        """
2025       
2026        tcrtl= event.GetEventObject()
2027        #Clear msg if previously shown.
2028        msg= ""
2029        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2030        # Flag to register when a parameter has changed.
2031        is_modified = False
2032        if tcrtl.GetValue().lstrip().rstrip()!="":
2033            try:
2034                value = float(tcrtl.GetValue())
2035                tcrtl.SetBackgroundColour(wx.WHITE)
2036
2037                # If qmin and qmax have been modified, update qmin and qmax
2038                if self._validate_qrange(self.theory_qmin, self.theory_qmax):
2039                    tempmin = float(self.theory_qmin.GetValue())
2040                    if tempmin != self.theory_qmin_x:
2041                        self.theory_qmin_x = tempmin
2042                    tempmax = float(self.theory_qmax.GetValue())
2043                    if tempmax != self.qmax_x:
2044                        self.theory_qmax_x = tempmax
2045                else:
2046                    tcrtl.SetBackgroundColour("pink")
2047                    msg= "Model Error:wrong value entered : %s"% sys.exc_value
2048                    wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
2049                    return 
2050            except:
2051                tcrtl.SetBackgroundColour("pink")
2052                msg= "Model Error:wrong value entered : %s"% sys.exc_value
2053                wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
2054                return 
2055            #Check if # of points for theory model are valid(>0).
2056            if self.Npts_total.IsEditable() :
2057                if check_float(self.Npts_total):
2058                    temp_npts = float(self.Npts_total.GetValue())
2059                    if temp_npts !=  self.num_points:
2060                        self.num_points = temp_npts
2061                        is_modified = True
2062                else:
2063                    msg= "Cannot Plot :No npts in that Qrange!!!  "
2064                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2065        else:
2066           tcrtl.SetBackgroundColour("pink")
2067           msg = "Model Error:wrong value entered!!!"
2068           wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
2069        #self._undo.Enable(True)
2070        self.save_current_state()
2071        event = PageInfoEvent(page = self)
2072        wx.PostEvent(self.parent, event)
2073        self.state_change= False
2074        #Draw the model for a different range
2075        self.create_default_data()
2076        self._draw_model()
2077                   
2078    def _on_select_model_helper(self): 
2079        """
2080        call back for model selection
2081        """
2082        ## reset dictionary containing reference to dispersion
2083        self._disp_obj_dict = {}
2084        self.disp_cb_dict ={}
2085        self.temp_multi_functional = False
2086        f_id = self.formfactorbox.GetCurrentSelection()
2087        #For MAC
2088        form_factor = None
2089        if f_id >= 0:
2090            form_factor = self.formfactorbox.GetClientData(f_id)
2091
2092        if not form_factor in  self.model_list_box["multiplication"]:
2093            self.structurebox.Hide()
2094            self.text2.Hide()           
2095            self.structurebox.Disable()
2096            self.structurebox.SetSelection(0)
2097            self.text2.Disable()
2098        else:
2099            self.structurebox.Show()
2100            self.text2.Show()
2101            self.structurebox.Enable()
2102            self.text2.Enable()
2103           
2104        if form_factor != None:   
2105            # set multifactor for Mutifunctional models   
2106            if form_factor().__class__ in self.model_list_box["Multi-Functions"]:
2107                m_id = self.multifactorbox.GetCurrentSelection()
2108                multiplicity = form_factor().multiplicity_info[0]
2109                self.multifactorbox.Clear()
2110                #self.mutifactor_text.SetLabel(form_factor().details[])
2111                self._set_multfactor_combobox(multiplicity)
2112                self._show_multfactor_combobox()
2113                #ToDo:  this info should be called directly from the model
2114                text = form_factor().multiplicity_info[1]#'No. of Shells: '
2115
2116                #self.mutifactor_text.Clear()
2117                self.mutifactor_text.SetLabel(text)
2118                if m_id > multiplicity -1:
2119                    # default value
2120                    m_id = 1
2121                   
2122                self.multi_factor = self.multifactorbox.GetClientData(m_id)
2123                if self.multi_factor == None: self.multi_factor =0
2124                form_factor = form_factor(int(self.multi_factor))
2125                self.multifactorbox.SetSelection(m_id)
2126                # Check len of the text1 and max_multiplicity
2127                text = ''
2128                if form_factor.multiplicity_info[0] == len(form_factor.multiplicity_info[2]):
2129                    text = form_factor.multiplicity_info[2][self.multi_factor]
2130                self.mutifactor_text1.SetLabel(text)
2131                # Check if model has  get sld profile.
2132                if len(form_factor.multiplicity_info[3]) > 0:
2133                    self.sld_axes = form_factor.multiplicity_info[3]
2134                    self.show_sld_button.Show(True)
2135                else:
2136                    self.sld_axes = ""
2137
2138            else:
2139                self._hide_multfactor_combobox()
2140                self.show_sld_button.Hide()
2141                form_factor = form_factor()
2142                self.multi_factor = None
2143        else:
2144            self._hide_multfactor_combobox()
2145            self.show_sld_button.Hide()
2146            self.multi_factor = None 
2147             
2148        s_id = self.structurebox.GetCurrentSelection()
2149        struct_factor = self.structurebox.GetClientData( s_id )
2150       
2151        if  struct_factor !=None:
2152            from sans.models.MultiplicationModel import MultiplicationModel
2153            self.model= MultiplicationModel(form_factor,struct_factor())
2154            # multifunctional form factor
2155            if len(form_factor.non_fittable) > 0:
2156                self.temp_multi_functional = True
2157        else:
2158            if form_factor != None:
2159                self.model= form_factor
2160            else:
2161                self.model = None
2162                return self.model
2163           
2164        ## post state to fit panel
2165        self.state.parameters =[]
2166        self.state.model =self.model
2167        self.state.qmin = self.qmin_x
2168        self.state.multi_factor = self.multi_factor
2169        self.disp_list =self.model.getDispParamList()
2170        self.state.disp_list = self.disp_list
2171        self.on_set_focus(None)
2172        self.Layout()     
2173       
2174    def _validate_qrange(self, qmin_ctrl, qmax_ctrl):
2175        """
2176        Verify that the Q range controls have valid values
2177        and that Qmin < Qmax.
2178       
2179        :param qmin_ctrl: text control for Qmin
2180        :param qmax_ctrl: text control for Qmax
2181       
2182        :return: True is the Q range is value, False otherwise
2183       
2184        """
2185        qmin_validity = check_float(qmin_ctrl)
2186        qmax_validity = check_float(qmax_ctrl)
2187        if not (qmin_validity and qmax_validity):
2188            return False
2189        else:
2190            qmin = float(qmin_ctrl.GetValue())
2191            qmax = float(qmax_ctrl.GetValue())
2192            if qmin < qmax:
2193                #Make sure to set both colours white. 
2194                qmin_ctrl.SetBackgroundColour(wx.WHITE)
2195                qmin_ctrl.Refresh()
2196                qmax_ctrl.SetBackgroundColour(wx.WHITE)
2197                qmax_ctrl.Refresh()
2198            else:
2199                qmin_ctrl.SetBackgroundColour("pink")
2200                qmin_ctrl.Refresh()
2201                qmax_ctrl.SetBackgroundColour("pink")
2202                qmax_ctrl.Refresh()
2203                msg= "Invalid Q range: Q min must be smaller than Q max"
2204                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2205                return False
2206        return True
2207   
2208    def _validate_Npts(self): 
2209        """
2210        Validate the number of points for fitting is more than 10 points.
2211        If valid, setvalues Npts_fit otherwise post msg.
2212        """
2213        #default flag
2214        flag = True
2215        # Theory
2216        if self.data == None and self.enable2D:
2217            return flag
2218        for data in self.data_list:
2219            # q value from qx and qy
2220            radius= numpy.sqrt( data.qx_data * data.qx_data + 
2221                                data.qy_data * data.qy_data )
2222            #get unmasked index
2223            index_data = (float(self.qmin.GetValue()) <= radius) & \
2224                            (radius <= float(self.qmax.GetValue()))
2225            index_data = (index_data) & (data.mask) 
2226            index_data = (index_data) & (numpy.isfinite(data.data))
2227
2228            if len(index_data[index_data]) < 10:
2229                # change the color pink.
2230                self.qmin.SetBackgroundColour("pink")
2231                self.qmin.Refresh()
2232                self.qmax.SetBackgroundColour("pink")
2233                self.qmax.Refresh()
2234                msg= "Npts of Data Error :No or too little npts of %s."% data.name
2235                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2236                self.fitrange = False
2237                flag = False
2238            else:
2239                self.Npts_fit.SetValue(str(len(index_data[index_data==True])))
2240                self.fitrange = True
2241           
2242        return flag
2243
2244    def _validate_Npts_1D(self): 
2245        """
2246        Validate the number of points for fitting is more than 5 points.
2247        If valid, setvalues Npts_fit otherwise post msg.
2248        """
2249        #default flag
2250        flag = True
2251        # Theory
2252        if self.data == None:
2253            return flag
2254        for data in self.data_list:
2255            # q value from qx and qy
2256            radius= data.x
2257            #get unmasked index
2258            index_data = (float(self.qmin.GetValue()) <= radius) & \
2259                            (radius <= float(self.qmax.GetValue()))
2260            index_data = (index_data) & (numpy.isfinite(data.y))
2261
2262            if len(index_data[index_data]) < 5:
2263                # change the color pink.
2264                self.qmin.SetBackgroundColour("pink")
2265                self.qmin.Refresh()
2266                self.qmax.SetBackgroundColour("pink")
2267                self.qmax.Refresh()
2268                msg= "Npts of Data Error :No or too little npts of %s."% data.name
2269                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2270                self.fitrange = False
2271                flag = False
2272            else:
2273                self.Npts_fit.SetValue(str(len(index_data[index_data==True])))
2274                self.fitrange = True
2275           
2276        return flag
2277
2278
2279   
2280    def _check_value_enter(self, list, modified):
2281        """
2282        :param list: model parameter and panel info
2283        :Note: each item of the list should be as follow:
2284            item=[check button state, parameter's name,
2285                paramater's value, string="+/-",
2286                parameter's error of fit,
2287                parameter's minimum value,
2288                parrameter's maximum value ,
2289                parameter's units]
2290        """ 
2291        is_modified =  modified
2292        if len(list)==0:
2293            return is_modified
2294        for item in list:
2295            #skip angle parameters for 1D
2296            if not self.enable2D:#self.data.__class__.__name__ !="Data2D":
2297                if item in self.orientation_params:
2298                    continue
2299            #try:
2300            name = str(item[1])
2301           
2302            if string.find(name,".npts") ==-1 and \
2303                                        string.find(name,".nsigmas")==-1:     
2304                ## check model parameters range             
2305                param_min= None
2306                param_max= None
2307               
2308                ## check minimun value
2309                if item[5]!= None and item[5]!= "":
2310                    if item[5].GetValue().lstrip().rstrip()!="":
2311                        try:
2312                           
2313                            param_min = float(item[5].GetValue())
2314                            if not self._validate_qrange(item[5],item[2]):
2315                                if numpy.isfinite(param_min):
2316                                    item[2].SetValue(format_number(param_min))
2317                           
2318                            item[5].SetBackgroundColour(wx.WHITE)
2319                            item[2].SetBackgroundColour(wx.WHITE)
2320                                           
2321                        except:
2322                            msg = "Wrong Fit parameter range entered "
2323                            wx.PostEvent(self.parent.parent, 
2324                                         StatusEvent(status = msg))
2325                            raise ValueError, msg
2326                        is_modified = True
2327                ## check maximum value
2328                if item[6]!= None and item[6]!= "":
2329                    if item[6].GetValue().lstrip().rstrip()!="":
2330                        try:                         
2331                            param_max = float(item[6].GetValue())
2332                            if not self._validate_qrange(item[2],item[6]):
2333                                if numpy.isfinite(param_max):
2334                                    item[2].SetValue(format_number(param_max)) 
2335                           
2336                            item[6].SetBackgroundColour(wx.WHITE)
2337                            item[2].SetBackgroundColour(wx.WHITE)
2338                        except:
2339                            msg = "Wrong Fit parameter range entered "
2340                            wx.PostEvent(self.parent.parent, 
2341                                         StatusEvent(status = msg))
2342                            raise ValueError, msg
2343                        is_modified = True
2344               
2345
2346                if param_min != None and param_max !=None:
2347                    if not self._validate_qrange(item[5], item[6]):
2348                        msg= "Wrong Fit range entered for parameter "
2349                        msg+= "name %s of model %s "%(name, self.model.name)
2350                        wx.PostEvent(self.parent.parent, 
2351                                     StatusEvent(status = msg))
2352               
2353                if name in self.model.details.keys():   
2354                        self.model.details[name][1:3] = param_min, param_max
2355                        is_modified = True
2356             
2357                else:
2358                        self.model.details [name] = ["", param_min, param_max] 
2359                        is_modified = True
2360            try:   
2361                # Check if the textctr is enabled
2362                if item[2].IsEnabled():
2363                    value= float(item[2].GetValue())
2364                    item[2].SetBackgroundColour("white")
2365                    # If the value of the parameter has changed,
2366                    # +update the model and set the is_modified flag
2367                    if value != self.model.getParam(name) and \
2368                                                numpy.isfinite(value):
2369                        self.model.setParam(name, value)
2370                       
2371            except:
2372                item[2].SetBackgroundColour("pink")
2373                msg = "Wrong Fit parameter value entered "
2374                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2375               
2376        return is_modified
2377       
2378 
2379    def _set_dipers_Param(self, event):
2380        """
2381        respond to self.enable_disp and self.disable_disp radio box.
2382        The dispersity object is reset inside the model into Gaussian.
2383        When the user select yes , this method display a combo box for more selection
2384        when the user selects No,the combo box disappears.
2385        Redraw the model with the default dispersity (Gaussian)
2386        """
2387        #if self.check_invalid_panel():
2388        #    return
2389        ## On selction if no model exists.
2390        if self.model ==None:
2391            self.disable_disp.SetValue(True)
2392            msg="Please select a Model first..."
2393            wx.MessageBox(msg, 'Info')
2394            wx.PostEvent(self._manager.parent, StatusEvent(status=\
2395                            "Polydispersion: %s"%msg))
2396            return
2397
2398        self._reset_dispersity()
2399   
2400        if self.model ==None:
2401            self.model_disp.Hide()
2402            self.sizer4_4.Clear(True)
2403            return
2404
2405        if self.enable_disp.GetValue():
2406            ## layout for model containing no dispersity parameters
2407           
2408            self.disp_list= self.model.getDispParamList()
2409             
2410            if len(self.disp_list)==0 and len(self.disp_cb_dict)==0:
2411                self._layout_sizer_noDipers() 
2412            else:
2413                ## set gaussian sizer
2414                self._on_select_Disp(event=None)
2415        else:
2416            self.sizer4_4.Clear(True)
2417           
2418        ## post state to fit panel
2419        self.save_current_state()
2420        if event !=None:
2421            #self._undo.Enable(True)
2422            event = PageInfoEvent(page = self)
2423            wx.PostEvent(self.parent, event)
2424        #draw the model with the current dispersity
2425        self._draw_model()
2426        self.sizer4_4.Layout()
2427        self.sizer5.Layout()
2428        self.Layout()
2429        self.Refresh()     
2430         
2431       
2432    def _layout_sizer_noDipers(self):
2433        """
2434        Draw a sizer with no dispersity info
2435        """
2436        ix=0
2437        iy=1
2438        self.fittable_param=[]
2439        self.fixed_param=[]
2440        self.orientation_params_disp=[]
2441       
2442        self.sizer4_4.Clear(True)
2443        text = "No polydispersity available for this model"
2444        text = "No polydispersity available for this model"
2445        model_disp = wx.StaticText(self, -1, text)
2446        self.sizer4_4.Add(model_disp,( iy, ix),(1,1), 
2447                            wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 10)
2448        self.sizer4_4.Layout()
2449        self.sizer4.Layout()
2450   
2451    def _reset_dispersity(self):
2452        """
2453        put gaussian dispersity into current model
2454        """
2455        if len(self.param_toFit)>0:
2456            for item in self.fittable_param:
2457                if item in self.param_toFit:
2458                    self.param_toFit.remove(item)
2459
2460            for item in self.orientation_params_disp:
2461                if item in self.param_toFit:
2462                    self.param_toFit.remove(item)
2463         
2464        self.fittable_param=[]
2465        self.fixed_param=[]
2466        self.orientation_params_disp=[]
2467        self.values={}
2468        self.weights={}
2469     
2470        from sans.models.dispersion_models import GaussianDispersion, ArrayDispersion
2471        if len(self.disp_cb_dict)==0:
2472            self.save_current_state()
2473            self.sizer4_4.Clear(True)
2474            self.Layout()
2475 
2476            return 
2477        if (len(self.disp_cb_dict)>0) :
2478            for p in self.disp_cb_dict:
2479                # The parameter was un-selected. Go back to Gaussian model (with 0 pts)                   
2480                disp_model = GaussianDispersion()
2481               
2482                self._disp_obj_dict[p] = disp_model
2483                # Set the new model as the dispersion object for the selected parameter
2484                try:
2485                   self.model.set_dispersion(p, disp_model)
2486                except:
2487
2488                    pass
2489
2490        ## save state into
2491        self.save_current_state()
2492        self.Layout() 
2493        self.Refresh()
2494                 
2495    def _on_select_Disp(self,event):
2496        """
2497        allow selecting different dispersion
2498        self.disp_list should change type later .now only gaussian
2499        """
2500        self._set_sizer_dispersion()
2501
2502        ## Redraw the model
2503        self._draw_model() 
2504        #self._undo.Enable(True)
2505        event = PageInfoEvent(page = self)
2506        wx.PostEvent(self.parent, event)
2507       
2508        self.sizer4_4.Layout()
2509        self.sizer4.Layout()
2510        self.SetupScrolling()
2511   
2512    def _on_disp_func(self, event=None): 
2513        """
2514        Select a distribution function for the polydispersion
2515       
2516        :Param event: ComboBox event
2517        """
2518        # get ready for new event
2519        if event != None:
2520            event.Skip()
2521        # Get event object
2522        disp_box =  event.GetEventObject() 
2523
2524        # Try to select a Distr. function
2525        try:   
2526            disp_box.SetBackgroundColour("white")
2527            selection = disp_box.GetCurrentSelection()
2528            param_name = disp_box.Name.split('.')[0]
2529            disp_name = disp_box.GetValue()
2530            dispersity= disp_box.GetClientData(selection)
2531   
2532            #disp_model =  GaussianDispersion()
2533            disp_model = dispersity()
2534            # Get param names to reset the values of the param
2535            name1 = param_name + ".width"
2536            name2 = param_name + ".npts"
2537            name3 = param_name + ".nsigmas"
2538            # Check Disp. function whether or not it is 'array'
2539            if disp_name.lower() == "array":
2540                value2= ""
2541                value3= ""
2542                value1 = self._set_array_disp(name=name1, disp=disp_model)
2543            else:
2544                self._del_array_values(name1)
2545                #self._reset_array_disp(param_name)
2546                self._disp_obj_dict[name1] = disp_model
2547                self.model.set_dispersion(param_name, disp_model)
2548                self.state._disp_obj_dict[name1]= disp_model
2549 
2550                value1= str(format_number(self.model.getParam(name1), True))
2551                value2= str(format_number(self.model.getParam(name2)))
2552                value3= str(format_number(self.model.getParam(name3)))
2553            # Reset fittable polydispersin parameter value
2554            for item in self.fittable_param:
2555                 if item[1] == name1:
2556                    item[2].SetValue(value1) 
2557                    item[5].SetValue("")
2558                    item[6].SetValue("")
2559                    # Disable for array
2560                    if disp_name.lower() == "array":
2561                        item[0].SetValue(False)
2562                        item[0].Disable()
2563                        item[2].Disable()
2564                        item[3].Show(False)
2565                        item[4].Show(False)
2566                        item[5].Disable()
2567                        item[6].Disable()
2568                    else:
2569                        item[0].Enable()
2570                        item[2].Enable()
2571                        item[5].Enable()
2572                        item[6].Enable()                       
2573                    break
2574            # Reset fixed polydispersion params
2575            for item in self.fixed_param:
2576                if item[1] == name2:
2577                    item[2].SetValue(value2) 
2578                    # Disable Npts for array
2579                    if disp_name.lower() == "array":
2580                        item[2].Disable()
2581                    else:
2582                        item[2].Enable()
2583                if item[1] == name3:
2584                    item[2].SetValue(value3) 
2585                    # Disable Nsigs for array
2586                    if disp_name.lower() == "array":
2587                        item[2].Disable()
2588                    else:
2589                        item[2].Enable()
2590               
2591            # Make sure the check box updated when all checked
2592            if self.cb1.GetValue():
2593                #self.select_all_param(None)
2594                self.get_all_checked_params()
2595
2596            # update params
2597            self._update_paramv_on_fit() 
2598            # draw
2599            self._draw_model()
2600            self.Refresh()
2601        except:
2602            # Error msg
2603            msg = "Error occurred:"
2604            msg += " Could not select the distribution function..."
2605            msg += " Please select another distribution function."
2606            disp_box.SetBackgroundColour("pink")
2607            # Focus on Fit button so that users can see the pinky box
2608            self.btFit.SetFocus()
2609            wx.PostEvent(self.parent.parent, 
2610                         StatusEvent(status=msg, info="error"))
2611       
2612       
2613    def _set_array_disp(self, name=None, disp=None):
2614        """
2615        Set array dispersion
2616       
2617        :param name: name of the parameter for the dispersion to be set
2618        :param disp: the polydisperion object
2619        """
2620        # The user wants this parameter to be averaged.
2621        # Pop up the file selection dialog.
2622        path = self._selectDlg()
2623        # Array data
2624        values = []
2625        weights = []
2626        # If nothing was selected, just return
2627        if path is None:
2628            self.disp_cb_dict[name].SetValue(False)
2629            #self.noDisper_rbox.SetValue(True)
2630            return
2631        self._default_save_location = os.path.dirname(path)
2632        if self.parent != None:
2633            self.parent.parent._default_save_location =\
2634                             self._default_save_location
2635
2636        basename  = os.path.basename(path)
2637        values,weights = self.read_file(path)
2638       
2639        # If any of the two arrays is empty, notify the user that we won't
2640        # proceed
2641        if len(self.param_toFit)>0:
2642            if name in self.param_toFit:
2643                self.param_toFit.remove(name)
2644
2645        # Tell the user that we are about to apply the distribution
2646        msg = "Applying loaded %s distribution: %s" % (name, path)
2647        wx.PostEvent(self.parent.parent, StatusEvent(status=msg)) 
2648        self._set_array_disp_model(name=name, disp=disp,
2649                                    values=values, weights=weights)
2650        return basename
2651   
2652    def _set_array_disp_model(self, name=None, disp=None, 
2653                              values=[], weights=[]):
2654        """
2655        Set array dispersion model
2656       
2657        :param name: name of the parameter for the dispersion to be set
2658        :param disp: the polydisperion object
2659        """
2660        disp.set_weights(values, weights)
2661        self._disp_obj_dict[name] = disp
2662        self.model.set_dispersion(name.split('.')[0], disp)
2663        self.state._disp_obj_dict[name]= disp
2664        self.values[name] = values
2665        self.weights[name] = weights
2666        # Store the object to make it persist outside the
2667        # scope of this method
2668        #TODO: refactor model to clean this up?
2669        self.state.values = {}
2670        self.state.weights = {}
2671        self.state.values = copy.deepcopy(self.values)
2672        self.state.weights = copy.deepcopy(self.weights)
2673
2674        # Set the new model as the dispersion object for the
2675        #selected parameter
2676        #self.model.set_dispersion(p, disp_model)
2677        # Store a reference to the weights in the model object
2678        #so that
2679        # it's not lost when we use the model within another thread.
2680        #TODO: total hack - fix this
2681        self.state.model= self.model.clone()
2682        self.model._persistency_dict[name.split('.')[0]] = \
2683                                        [values, weights]
2684        self.state.model._persistency_dict[name.split('.')[0]] = \
2685                                        [values,weights]
2686                                       
2687
2688    def _del_array_values(self, name=None): 
2689        """
2690        Reset array dispersion
2691       
2692        :param name: name of the parameter for the dispersion to be set
2693        """
2694        # Try to delete values and weight of the names array dic if exists
2695        try:
2696            del self.values[name]
2697            del self.weights[name]
2698            # delete all other dic
2699            del self.state.values[name]
2700            del self.state.weights[name]
2701            del self.model._persistency_dict[name.split('.')[0]] 
2702            del self.state.model._persistency_dict[name.split('.')[0]]
2703        except:
2704            pass
2705                                           
2706    def _lay_out(self):
2707        """
2708        returns self.Layout
2709       
2710        :Note: Mac seems to like this better when self.
2711            Layout is called after fitting.
2712        """
2713        self._sleep4sec()
2714        self.Layout()
2715        return 
2716   
2717    def _sleep4sec(self):
2718        """
2719            sleep for 1 sec only applied on Mac
2720            Note: This 1sec helps for Mac not to crash on self.:ayout after self._draw_model
2721        """
2722        if ON_MAC == True:
2723            time.sleep(1)
2724           
2725    def _find_polyfunc_selection(self, disp_func = None):
2726        """
2727        FInd Comboox selection from disp_func
2728       
2729        :param disp_function: dispersion distr. function
2730        """
2731        # List of the poly_model name in the combobox
2732        list = ["RectangleDispersion", "ArrayDispersion", 
2733                    "LogNormalDispersion", "GaussianDispersion", 
2734                    "SchulzDispersion"]
2735
2736        # Find the selection
2737        try:
2738            selection = list.index(disp_func.__class__.__name__)
2739            return selection
2740        except:
2741             return 3
2742                           
2743    def on_reset_clicked(self,event):
2744        """
2745        On 'Reset' button  for Q range clicked
2746        """
2747        flag = True
2748        #if self.check_invalid_panel():
2749        #    return
2750        ##For 3 different cases: Data2D, Data1D, and theory
2751        if self.model == None:
2752            msg="Please select a model first..."
2753            wx.MessageBox(msg, 'Info')
2754            flag = False
2755            return
2756           
2757        elif self.data.__class__.__name__ == "Data2D":
2758            data_min= 0
2759            x= max(math.fabs(self.data.xmin), math.fabs(self.data.xmax)) 
2760            y= max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
2761            self.qmin_x = data_min
2762            self.qmax_x = math.sqrt(x*x + y*y)
2763            #self.data.mask = numpy.ones(len(self.data.data),dtype=bool)
2764            # check smearing
2765            if not self.disable_smearer.GetValue():
2766                temp_smearer= self.current_smearer
2767                ## set smearing value whether or not the data contain the smearing info
2768                if self.pinhole_smearer.GetValue():
2769                    flag = self.update_pinhole_smear()
2770                else:
2771                    flag = True
2772                   
2773        elif self.data == None:
2774            self.qmin_x = _QMIN_DEFAULT
2775            self.qmax_x = _QMAX_DEFAULT
2776            self.num_points = _NPTS_DEFAULT           
2777            self.state.npts = self.num_points
2778           
2779        elif self.data.__class__.__name__ != "Data2D":
2780            self.qmin_x = min(self.data.x)
2781            self.qmax_x = max(self.data.x)
2782            # check smearing
2783            if not self.disable_smearer.GetValue():
2784                temp_smearer= self.current_smearer
2785                ## set smearing value whether or not the data contain the smearing info
2786                if self.slit_smearer.GetValue():
2787                    flag = self.update_slit_smear()
2788                elif self.pinhole_smearer.GetValue():
2789                    flag = self.update_pinhole_smear()
2790                else:
2791                    flag = True
2792        else:
2793            flag = False
2794           
2795        if flag == False:
2796            msg= "Cannot Plot :Must enter a number!!!  "
2797            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2798        else:
2799            # set relative text ctrs.
2800            self.qmin.SetValue(str(self.qmin_x))
2801            self.qmax.SetValue(str(self.qmax_x))
2802            self.set_npts2fit()
2803            # At this point, some button and variables satatus (disabled?) should be checked
2804            # such as color that should be reset to white in case that it was pink.
2805            self._onparamEnter_helper()
2806
2807        self.save_current_state()
2808        self.state.qmin = self.qmin_x
2809        self.state.qmax = self.qmax_x
2810       
2811        #reset the q range values
2812        self._reset_plotting_range(self.state)
2813        #self.compute_chisqr(smearer=self.current_smearer)
2814        #Re draw plot
2815        self._draw_model()
2816       
2817    def get_images(self):
2818        """
2819        Get the images of the plots corresponding this panel for report
2820       
2821        : return graphs: list of figures
2822        : TODO: Move to guiframe
2823        """
2824        # set list of graphs
2825        graphs = []
2826        canvases = []
2827        # call gui_manager
2828        gui_manager = self.parent.parent
2829        # loops through the panels [dic]
2830        for item1, item2 in gui_manager.plot_panels.iteritems():
2831             data_title = self.data.group_id
2832             data_name = str(self.data.name).split(" [")[0]
2833            # try to get all plots belonging to this control panel
2834             try:
2835                 title = ''
2836                 # check titles (main plot)
2837                 if hasattr(item2,"data2D"):
2838                     title = item2.data2D.title
2839                 # and data_names (model plot[2D], and residuals)
2840                 if item2.group_id == data_title or \
2841                        item2.group_id.count("res" + str(self.graph_id)) or \
2842                        item2.group_id.count(str(self.uid)) > 0:
2843                     #panel = gui_manager._mgr.GetPane(item2.window_name)
2844                     # append to the list
2845                     graphs.append(item2.figure) 
2846                     canvases.append(item2.canvas)     
2847             except:
2848                 # Not for control panels
2849                 pass
2850        # return the list of graphs
2851        return graphs, canvases
2852
2853    def on_model_help_clicked(self,event):
2854        """
2855        on 'More details' button
2856        """
2857        from help_panel import  HelpWindow
2858        from sans.models import get_data_path
2859       
2860        # Get models help model_function path
2861        path = get_data_path(media='media')
2862        model_path = os.path.join(path,"model_functions.html")
2863        if self.model == None:
2864            name = 'FuncHelp'
2865        else:
2866            name = self.formfactorbox.GetValue()
2867            #name = self.model.__class__.__name__
2868        frame = HelpWindow(None, -1,  pageToOpen=model_path)   
2869        frame.Show(True)
2870        if frame.rhelp.HasAnchor(name):
2871            frame.rhelp.ScrollToAnchor(name)
2872        else:
2873           msg= "Model does not contains an available description "
2874           msg +="Please try searching in the Help window"
2875           wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))     
2876   
2877    def on_pd_help_clicked(self, event):
2878        """
2879        Button event for PD help
2880        """
2881        from help_panel import  HelpWindow
2882        import sans.models as models 
2883       
2884        # Get models help model_function path
2885        path = models.get_data_path(media='media')
2886        pd_path = os.path.join(path,"pd_help.html")
2887
2888        frame = HelpWindow(None, -1,  pageToOpen=pd_path)   
2889        frame.Show(True)
2890       
2891    def on_left_down(self, event):
2892        """
2893        Get key stroke event
2894        """
2895        # Figuring out key combo: Cmd for copy, Alt for paste
2896        if event.CmdDown() and event.ShiftDown():
2897            flag = self.get_paste()
2898        elif event.CmdDown():
2899            flag = self.get_copy()
2900        else:
2901            event.Skip()
2902            return
2903        # make event free
2904        event.Skip()
2905       
2906    def get_copy(self):
2907        """
2908        Get copy params to clipboard
2909        """
2910        content = self.get_copy_params() 
2911        flag = self.set_clipboard(content)
2912        self._copy_info(flag) 
2913        return flag
2914           
2915    def get_copy_params(self): 
2916        """
2917        Get the string copies of the param names and values in the tap
2918        """ 
2919        content = 'sansview_parameter_values:'
2920        # Do it if params exist       
2921        if  self.parameters !=[]:
2922           
2923            # go through the parameters
2924            string = self._get_copy_helper(self.parameters, 
2925                                           self.orientation_params)
2926            content += string
2927           
2928            # go through the fittables
2929            string = self._get_copy_helper(self.fittable_param, 
2930                                           self.orientation_params_disp)
2931            content += string
2932
2933            # go through the fixed params
2934            string = self._get_copy_helper(self.fixed_param, 
2935                                           self.orientation_params_disp)
2936            content += string
2937               
2938            # go through the str params
2939            string = self._get_copy_helper(self.str_parameters, 
2940                                           self.orientation_params)
2941            content += string
2942            return content
2943        else:
2944            return False
2945   
2946    def set_clipboard(self, content=None): 
2947        """
2948        Put the string to the clipboard
2949        """   
2950        if not content:
2951            return False
2952        if wx.TheClipboard.Open():
2953            wx.TheClipboard.SetData(wx.TextDataObject(str(content)))
2954            data = wx.TextDataObject()
2955            success = wx.TheClipboard.GetData(data)
2956            text = data.GetText()
2957            wx.TheClipboard.Close()
2958            return True
2959        return None
2960   
2961    def _get_copy_helper(self, param, orient_param):
2962        """
2963        Helping get value and name of the params
2964       
2965        : param param:  parameters
2966        : param orient_param = oritational params
2967        : return content: strings [list] [name,value:....]
2968        """
2969        content = ''
2970        # go through the str params
2971        for item in param: 
2972            disfunc = ''
2973            try:
2974                if item[7].__class__.__name__ == 'ComboBox':
2975                    disfunc = str(item[7].GetValue())
2976            except:
2977                pass
2978           
2979            # 2D
2980            if self.data.__class__.__name__== "Data2D":
2981                try:
2982                    check = item[0].GetValue()
2983                except:
2984                    check = None
2985                name = item[1]
2986                value = item[2].GetValue()
2987            # 1D
2988            else:
2989                ## for 1D all parameters except orientation
2990                if not item[1] in orient_param:
2991                    try:
2992                        check = item[0].GetValue()
2993                    except:
2994                        check = None
2995                    name = item[1]
2996                    value = item[2].GetValue()
2997
2998            # add to the content
2999            if disfunc != '':
3000               
3001                disfunc = ',' + disfunc
3002            # TODO: to support array func for copy/paste
3003            try:
3004                if disfunc.count('array') > 0:
3005                    disfunc += ','
3006                    for val in self.values[name]:
3007                        disfunc += ' ' + str(val)
3008                    disfunc += ','
3009                    for weight in self.weights[name]:
3010                        disfunc += ' ' + str(weight)
3011            except:
3012                pass
3013            #if disfunc.count('array') == 0:
3014            content +=  name + ',' + str(check) + ',' + value + disfunc + ':'
3015
3016        return content
3017   
3018    def get_clipboard(self):   
3019        """
3020        Get strings in the clipboard
3021        """
3022        text = "" 
3023        # Get text from the clip board       
3024        if wx.TheClipboard.Open():
3025           if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
3026               data = wx.TextDataObject()
3027               # get wx dataobject
3028               success = wx.TheClipboard.GetData(data)
3029               # get text
3030               text = data.GetText()
3031           # close clipboard
3032           wx.TheClipboard.Close()
3033           
3034        return text
3035   
3036    def get_paste(self):
3037        """
3038        Paste params from the clipboard
3039        """
3040        text = self.get_clipboard()
3041        flag = self.get_paste_params(text)
3042        self._copy_info(flag)
3043        return flag
3044       
3045    def get_paste_params(self, text=''): 
3046        """
3047        Get the string copies of the param names and values in the tap
3048        """ 
3049        context = {}   
3050        # put the text into dictionary   
3051        lines = text.split(':')
3052        if lines[0] != 'sansview_parameter_values':
3053            self._copy_info(False)
3054            return False
3055        for line in lines[1:-1]:
3056            if len(line) != 0:
3057                item =line.split(',')
3058                check = item[1]
3059                name = item[0]
3060                value = item[2]
3061                # Transfer the text to content[dictionary]
3062                context[name] = [check, value]
3063            # ToDo: PlugIn this poly disp function for pasting
3064            try:
3065                poly_func = item[3]
3066                context[name].append(poly_func)
3067                try:
3068                    # take the vals and weights for  array
3069                    array_values = item[4].split(' ')
3070                    array_weights = item[5].split(' ')
3071                    val = [float(a_val) for a_val in array_values[1:]]
3072                    weit = [float(a_weit) for a_weit in array_weights[1:]]
3073                   
3074                    context[name].append(val)
3075                    context[name].append(weit)
3076                except:
3077                    raise
3078            except:
3079                poly_func = ''
3080                context[name].append(poly_func)
3081
3082        # Do it if params exist       
3083        if  self.parameters != []:
3084            # go through the parameters 
3085            self._get_paste_helper(self.parameters, 
3086                                   self.orientation_params, context)
3087
3088            # go through the fittables
3089            self._get_paste_helper(self.fittable_param, 
3090                                   self.orientation_params_disp, 
3091                                   context)
3092
3093            # go through the fixed params
3094            self._get_paste_helper(self.fixed_param, 
3095                                   self.orientation_params_disp, context)
3096           
3097            # go through the str params
3098            self._get_paste_helper(self.str_parameters, 
3099                                   self.orientation_params, context)
3100               
3101            return True
3102        return None
3103   
3104    def _get_paste_helper(self, param, orient_param, content):
3105        """
3106        Helping set values of the params
3107       
3108        : param param:  parameters
3109        : param orient_param: oritational params
3110        : param content: dictionary [ name, value: name1.value1,...]
3111        """
3112        # go through the str params
3113        for item in param: 
3114            # 2D
3115            if self.data.__class__.__name__== "Data2D":
3116                name = item[1]
3117                if name in content.keys():
3118                    check = content[name][0]
3119                    pd = content[name][1]
3120                    if name.count('.') > 0:
3121                        try:
3122                            float(pd)
3123                        except:
3124                            #continue
3125                            if not pd and pd != '':
3126                                continue
3127                    item[2].SetValue(str(pd))
3128                    if item in self.fixed_param and pd == '':
3129                        # Only array func has pd == '' case.
3130                        item[2].Enable(False)
3131                    if item[2].__class__.__name__ == "ComboBox":
3132                        if self.model.fun_list.has_key(content[name][1]):
3133                            fun_val = self.model.fun_list[content[name][1]]
3134                            self.model.setParam(name,fun_val)
3135                   
3136                    value = content[name][1:]
3137                    self._paste_poly_help(item, value)
3138                    if check == 'True':
3139                        is_true = True
3140                    elif check == 'False':
3141                        is_true = False
3142                    else:
3143                        is_true = None
3144                    if is_true != None:
3145                        item[0].SetValue(is_true)
3146            # 1D
3147            else:
3148                ## for 1D all parameters except orientation
3149                if not item[1] in orient_param:
3150                    name = item[1]
3151                    if name in content.keys():
3152                        check = content[name][0]
3153                        # Avoid changing combox content which needs special care
3154                        value = content[name][1:]
3155                        pd = value[0]
3156                        if name.count('.') > 0:
3157                            try:
3158                                pd = float(pd)
3159                            except:
3160                                #continue
3161                                if not pd and pd != '':
3162                                    continue
3163                        item[2].SetValue(str(pd))
3164                        if item in self.fixed_param and pd == '':
3165                            # Only array func has pd == '' case.
3166                            item[2].Enable(False)
3167                        if item[2].__class__.__name__ == "ComboBox":
3168                            if self.model.fun_list.has_key(value[0]):
3169                                fun_val = self.model.fun_list[value[0]]
3170                                self.model.setParam(name,fun_val)
3171                                # save state
3172                                #self._copy_parameters_state(self.str_parameters,
3173                                #    self.state.str_parameters)
3174                        self._paste_poly_help(item, value)
3175                        if check == 'True':
3176                            is_true = True
3177                        elif check == 'False':
3178                            is_true = False
3179                        else:
3180                            is_true = None
3181                        if is_true != None:
3182                            item[0].SetValue(is_true)
3183                       
3184    def _paste_poly_help(self, item, value):
3185        """
3186        Helps get paste for poly function
3187       
3188        :param item: Gui param items
3189        :param value: the values for parameter ctrols
3190        """
3191        is_array = False
3192        if len(value[1]) > 0:
3193            # Only for dispersion func.s
3194            try:
3195                item[7].SetValue(value[1])
3196                selection = item[7].GetCurrentSelection()
3197                name = item[7].Name
3198                param_name = name.split('.')[0]
3199                disp_name = item[7].GetValue()
3200                dispersity= item[7].GetClientData(selection)
3201                disp_model = dispersity()
3202                # Only for array disp
3203                try:
3204                    pd_vals = numpy.array(value[2])
3205                    pd_weights = numpy.array(value[3])
3206                    if len(pd_vals) > 0 and len(pd_vals) > 0:
3207                        if len(pd_vals) == len(pd_weights):
3208                            self._set_disp_array_cb(item=item)
3209                            self._set_array_disp_model(name=name, 
3210                                                       disp=disp_model,
3211                                                       values=pd_vals, 
3212                                                       weights=pd_weights)
3213                            is_array = True
3214                except:
3215                    pass 
3216                if not is_array:
3217                    self._disp_obj_dict[name] = disp_model
3218                    self.model.set_dispersion(name, 
3219                                              disp_model)
3220                    self.state._disp_obj_dict[name] = \
3221                                              disp_model
3222                    self.model.set_dispersion(param_name, disp_model)
3223                    self.state.values = self.values
3224                    self.state.weights = self.weights   
3225                    self.model._persistency_dict[param_name] = \
3226                                            [state.values, state.weights]
3227                         
3228            except:
3229                pass 
3230   
3231    def _set_disp_array_cb(self, item):
3232        """
3233        Set cb for array disp
3234        """
3235        item[0].SetValue(False)
3236        item[0].Enable(False)
3237        item[2].Enable(False)
3238        item[3].Show(False)
3239        item[4].Show(False)
3240        item[5].SetValue('')
3241        item[5].Enable(False)
3242        item[6].SetValue('')
3243        item[6].Enable(False)
3244
3245       
Note: See TracBrowser for help on using the repository browser.