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

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

mask button disabled for batch

  • Property mode set to 100644
File size: 128.1 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    def old_on_bookmark(self, event):
774        """
775        save history of the data and model
776        """
777        if self.model==None:
778            msg="Can not bookmark; Please select Data and Model first..."
779            wx.MessageBox(msg, 'Info')
780            return 
781        if hasattr(self,"enable_disp"):
782            self.state.enable_disp = copy.deepcopy(self.enable_disp.GetValue())
783        if hasattr(self, "disp_box"):
784            self.state.disp_box = copy.deepcopy(self.disp_box.GetSelection())
785
786        self.state.model.name= self.model.name
787       
788        #Remember fit engine_type for fit panel
789        if self.engine_type == None: 
790            self.engine_type = "scipy"
791        if self._manager !=None:
792            self._manager._on_change_engine(engine=self.engine_type)
793       
794            self.state.engine_type = self.engine_type
795
796        new_state = self.state.clone()
797        new_state.model.name = self.state.model.name
798       
799        new_state.enable2D = copy.deepcopy(self.enable2D)
800        ##Add model state on context menu
801        self.number_saved_state += 1
802        #name= self.model.name+"[%g]"%self.number_saved_state
803        name= self.model.__class__.__name__+"[%g]"%self.number_saved_state
804        self.saved_states[name]= new_state
805       
806        ## Add item in the context menu
807       
808        year, month, day,hour,minute,second,tda,ty,tm_isdst= time.localtime()
809        my_time= str(hour)+" : "+str(minute)+" : "+str(second)+" "
810        date= str( month)+"|"+str(day)+"|"+str(year)
811        msg=  "Model saved at %s on %s"%(my_time, date)
812         ## post help message for the selected model
813        msg +=" Saved! right click on this page to retrieve this model"
814        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
815       
816        id = wx.NewId()
817        self.popUpMenu.Append(id,name,str(msg))
818        wx.EVT_MENU(self, id, self.onResetModel)
819       
820    def onSetFocus(self, evt):
821        """
822        highlight the current textcrtl and hide the error text control shown
823        after fitting
824        """
825        return
826   
827    def read_file(self, path):
828        """
829        Read two columns file
830       
831        :param path: the path to the file to read
832       
833        """
834        try:
835            if path==None:
836                wx.PostEvent(self.parent.parent, StatusEvent(status=\
837                            " Selected Distribution was not loaded: %s"%path))
838                return None, None
839            input_f = open(path, 'r')
840            buff = input_f.read()
841            lines = buff.split('\n')
842           
843            angles = []
844            weights=[]
845            for line in lines:
846                toks = line.split()
847                try:
848                    angle = float(toks[0])
849                    weight = float(toks[1])
850                except:
851                    # Skip non-data lines
852                    pass
853                angles.append(angle)
854                weights.append(weight)
855            return numpy.array(angles), numpy.array(weights)
856        except:
857            raise 
858
859    def createMemento(self):
860        """
861        return the current state of the page
862        """
863        return self.state.clone()
864   
865   
866    def save_current_state(self):
867        """
868        Store current state
869        """
870        self.state.engine_type = copy.deepcopy(self.engine_type)
871        ## save model option
872        if self.model!= None:
873            self.disp_list= self.model.getDispParamList()
874            self.state.disp_list= copy.deepcopy(self.disp_list)
875            self.state.model = self.model.clone()
876        #save radiobutton state for model selection
877        self.state.shape_rbutton = self.shape_rbutton.GetValue()
878        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
879        self.state.struct_rbutton = self.struct_rbutton.GetValue()
880        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
881        #model combobox
882        self.state.structurebox = self.structurebox.GetSelection()
883        self.state.formfactorbox = self.formfactorbox.GetSelection()
884       
885        self.state.enable2D = copy.deepcopy(self.enable2D)
886        self.state.values= copy.deepcopy(self.values)
887        self.state.weights = copy.deepcopy( self.weights)
888        ## save data   
889        self.state.data= copy.deepcopy(self.data)
890        self.state.qmax_x = self.qmax_x
891        self.state.qmin_x = self.qmin_x
892        self.state.dI_noweight = copy.deepcopy(self.dI_noweight.GetValue())
893        self.state.dI_didata = copy.deepcopy(self.dI_didata.GetValue())
894        self.state.dI_sqrdata = copy.deepcopy(self.dI_sqrdata.GetValue())
895        self.state.dI_idata = copy.deepcopy(self.dI_idata.GetValue())
896        if hasattr(self,"enable_disp"):
897            self.state.enable_disp= self.enable_disp.GetValue()
898            self.state.disable_disp = self.disable_disp.GetValue()
899           
900        self.state.smearer = copy.deepcopy(self.current_smearer)
901        if hasattr(self,"enable_smearer"):
902            self.state.enable_smearer = \
903                                copy.deepcopy(self.enable_smearer.GetValue())
904            self.state.disable_smearer = \
905                                copy.deepcopy(self.disable_smearer.GetValue())
906
907        self.state.pinhole_smearer = \
908                                copy.deepcopy(self.pinhole_smearer.GetValue())
909        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 
910                 
911        if len(self._disp_obj_dict)>0:
912            for k , v in self._disp_obj_dict.iteritems():
913                self.state._disp_obj_dict[k]= v
914                       
915           
916            self.state.values = copy.deepcopy(self.values)
917            self.state.weights = copy.deepcopy(self.weights)
918        ## save plotting range
919        self._save_plotting_range()
920       
921        self.state.orientation_params = []
922        self.state.orientation_params_disp = []
923        self.state.parameters = []
924        self.state.fittable_param = []
925        self.state.fixed_param = []
926        self.state.str_parameters = []
927
928       
929        ## save checkbutton state and txtcrtl values
930        self._copy_parameters_state(self.str_parameters, 
931                                    self.state.str_parameters)
932        self._copy_parameters_state(self.orientation_params,
933                                     self.state.orientation_params)
934        self._copy_parameters_state(self.orientation_params_disp,
935                                     self.state.orientation_params_disp)
936       
937        self._copy_parameters_state(self.parameters, self.state.parameters)
938        self._copy_parameters_state(self.fittable_param,
939                                     self.state.fittable_param)
940        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
941        #save chisqr
942        self.state.tcChi = self.tcChi.GetValue()
943       
944    def save_current_state_fit(self):
945        """
946        Store current state for fit_page
947        """
948        ## save model option
949        if self.model!= None:
950            self.disp_list= self.model.getDispParamList()
951            self.state.disp_list= copy.deepcopy(self.disp_list)
952            self.state.model = self.model.clone()
953        if hasattr(self, "engine_type"):
954            self.state.engine_type = copy.deepcopy(self.engine_type)
955           
956        self.state.enable2D = copy.deepcopy(self.enable2D)
957        self.state.values= copy.deepcopy(self.values)
958        self.state.weights = copy.deepcopy( self.weights)
959        ## save data   
960        self.state.data= copy.deepcopy(self.data)
961       
962        if hasattr(self,"enable_disp"):
963            self.state.enable_disp= self.enable_disp.GetValue()
964            self.state.disable_disp = self.disable_disp.GetValue()
965           
966        self.state.smearer = copy.deepcopy(self.current_smearer)
967        if hasattr(self,"enable_smearer"):
968            self.state.enable_smearer = \
969                                copy.deepcopy(self.enable_smearer.GetValue())
970            self.state.disable_smearer = \
971                                copy.deepcopy(self.disable_smearer.GetValue())
972           
973        self.state.pinhole_smearer = \
974                                copy.deepcopy(self.pinhole_smearer.GetValue())
975        self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) 
976        self.state.dI_noweight = copy.deepcopy(self.dI_noweight.GetValue())
977        self.state.dI_didata = copy.deepcopy(self.dI_didata.GetValue())
978        self.state.dI_sqrdata = copy.deepcopy(self.dI_sqrdata.GetValue())
979        self.state.dI_idata = copy.deepcopy(self.dI_idata.GetValue()) 
980        if hasattr(self,"disp_box"):
981            self.state.disp_box = self.disp_box.GetCurrentSelection()
982
983            if len(self.disp_cb_dict) > 0:
984                for k, v in self.disp_cb_dict.iteritems():
985         
986                    if v == None :
987                        self.state.disp_cb_dict[k] = v
988                    else:
989                        try:
990                            self.state.disp_cb_dict[k] = v.GetValue()
991                        except:
992                            self.state.disp_cb_dict[k] = None
993           
994            if len(self._disp_obj_dict) > 0:
995                for k , v in self._disp_obj_dict.iteritems():
996     
997                    self.state._disp_obj_dict[k] = v
998                       
999           
1000            self.state.values = copy.deepcopy(self.values)
1001            self.state.weights = copy.deepcopy(self.weights)
1002           
1003        ## save plotting range
1004        self._save_plotting_range()
1005       
1006        ## save checkbutton state and txtcrtl values
1007        self._copy_parameters_state(self.orientation_params,
1008                                     self.state.orientation_params)
1009        self._copy_parameters_state(self.orientation_params_disp,
1010                                     self.state.orientation_params_disp)
1011        self._copy_parameters_state(self.parameters, self.state.parameters)
1012        self._copy_parameters_state(self.fittable_param,
1013                                             self.state.fittable_param)
1014        self._copy_parameters_state(self.fixed_param, self.state.fixed_param)
1015   
1016         
1017    def check_invalid_panel(self): 
1018        """
1019        check if the user can already perform some action with this panel
1020        """ 
1021        flag = False
1022        if self.data is None:
1023            self.disable_smearer.SetValue(True)
1024            self.disable_disp.SetValue(True)
1025            msg = "Please load Data and select Model to start..."
1026            wx.MessageBox(msg, 'Info')
1027            return  True
1028       
1029    def set_model_state(self, state):
1030        """
1031        reset page given a model state
1032        """
1033        self.disp_cb_dict = state.disp_cb_dict
1034        self.disp_list = state.disp_list
1035     
1036        ## set the state of the radio box
1037        self.shape_rbutton.SetValue(state.shape_rbutton )
1038        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
1039        self.struct_rbutton.SetValue(state.struct_rbutton)
1040        self.plugin_rbutton.SetValue(state.plugin_rbutton)
1041       
1042        ## fill model combobox
1043        self._show_combox_helper()
1044        #select the current model
1045        self.formfactorbox.Select(int(state.formfactorcombobox))
1046        self.structurebox.SetSelection(state.structurecombobox )
1047        if state.multi_factor != None:
1048            self.multifactorbox.SetSelection(state.multi_factor)
1049           
1050         ## reset state of checkbox,textcrtl  and  regular parameters value
1051        self._reset_parameters_state(self.orientation_params_disp,
1052                                     state.orientation_params_disp)
1053        self._reset_parameters_state(self.orientation_params,
1054                                     state.orientation_params)
1055        self._reset_parameters_state(self.str_parameters,
1056                                     state.str_parameters)
1057        self._reset_parameters_state(self.parameters,state.parameters)
1058         ## display dispersion info layer       
1059        self.enable_disp.SetValue(state.enable_disp)
1060        self.disable_disp.SetValue(state.disable_disp)
1061       
1062        if hasattr(self, "disp_box"):
1063           
1064            self.disp_box.SetSelection(state.disp_box) 
1065            n= self.disp_box.GetCurrentSelection()
1066            dispersity= self.disp_box.GetClientData(n)
1067            name = dispersity.__name__     
1068
1069            self._set_dipers_Param(event=None)
1070       
1071            if name == "ArrayDispersion":
1072               
1073                for item in self.disp_cb_dict.keys():
1074                   
1075                    if hasattr(self.disp_cb_dict[item], "SetValue") :
1076                        self.disp_cb_dict[item].SetValue(\
1077                                                    state.disp_cb_dict[item])
1078                        # Create the dispersion objects
1079                        from sans.models.dispersion_models import ArrayDispersion
1080                        disp_model = ArrayDispersion()
1081                        if hasattr(state,"values")and\
1082                                 self.disp_cb_dict[item].GetValue() == True:
1083                            if len(state.values)>0:
1084                                self.values=state.values
1085                                self.weights=state.weights
1086                                disp_model.set_weights(self.values,
1087                                                        state.weights)
1088                            else:
1089                                self._reset_dispersity()
1090                       
1091                        self._disp_obj_dict[item] = disp_model
1092                        # Set the new model as the dispersion object
1093                        #for the selected parameter
1094                        self.model.set_dispersion(item, disp_model)
1095                   
1096                        self.model._persistency_dict[item] = \
1097                                                [state.values, state.weights]
1098                   
1099            else:
1100                keys = self.model.getParamList()
1101                for item in keys:
1102                    if item in self.disp_list and \
1103                        not self.model.details.has_key(item):
1104                        self.model.details[item] = ["", None, None]
1105                for k,v in self.state.disp_cb_dict.iteritems():
1106                    self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1107                    self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1108         ## smearing info  restore
1109        if hasattr(self, "enable_smearer"):
1110            ## set smearing value whether or not the data
1111            #contain the smearing info
1112            self.enable_smearer.SetValue(state.enable_smearer)
1113            self.disable_smearer.SetValue(state.disable_smearer)
1114            self.onSmear(event=None)           
1115        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1116        self.slit_smearer.SetValue(state.slit_smearer)
1117       
1118        self.dI_noweight.SetValue(state.dI_noweight)
1119        self.dI_didata.SetValue(state.dI_didata)
1120        self.dI_sqrdata.SetValue(state.dI_sqrdata)
1121        self.dI_idata.SetValue(state.dI_idata)
1122       
1123        ## we have two more options for smearing
1124        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1125        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1126       
1127        ## reset state of checkbox,textcrtl  and dispersity parameters value
1128        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1129        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1130       
1131        ## draw the model with previous parameters value
1132        self._onparamEnter_helper()
1133        self.select_param(event=None) 
1134        #Save state_fit
1135        self.save_current_state_fit()
1136        self._lay_out()
1137        self.Refresh()
1138       
1139    def reset_page_helper(self, state):
1140        """
1141        Use page_state and change the state of existing page
1142       
1143        :precondition: the page is already drawn or created
1144       
1145        :postcondition: the state of the underlying data change as well as the
1146            state of the graphic interface
1147        """
1148        if state == None:
1149            #self._undo.Enable(False)
1150            return 
1151        # set data, etc. from the state
1152        # reset page between theory and fitting from bookmarking
1153        #if state.data == None:
1154        #    data = None
1155        #else:
1156        data = state.data
1157
1158        #if data != None:
1159       
1160        if data == None:
1161            data_min = state.qmin
1162            data_max = state.qmax
1163            self.qmin_x = data_min
1164            self.qmax_x = data_max
1165            #self.minimum_q.SetValue(str(data_min))
1166            #self.maximum_q.SetValue(str(data_max))
1167            self.qmin.SetValue(str(data_min))
1168            self.qmax.SetValue(str(data_max))
1169
1170            self.state.data = data
1171            self.state.qmin = self.qmin_x
1172            self.state.qmax = self.qmax_x
1173        else:
1174            self.set_data(data)
1175           
1176        self.enable2D= state.enable2D
1177        self.engine_type = state.engine_type
1178
1179        self.disp_cb_dict = state.disp_cb_dict
1180        self.disp_list = state.disp_list
1181     
1182        ## set the state of the radio box
1183        self.shape_rbutton.SetValue(state.shape_rbutton )
1184        self.shape_indep_rbutton.SetValue(state.shape_indep_rbutton)
1185        self.struct_rbutton.SetValue(state.struct_rbutton)
1186        self.plugin_rbutton.SetValue(state.plugin_rbutton)
1187       
1188        ## fill model combobox
1189        self._show_combox_helper()
1190        #select the current model
1191        self.formfactorbox.Select(int(state.formfactorcombobox))
1192        self.structurebox.SetSelection(state.structurecombobox )
1193        if state.multi_factor != None:
1194            self.multifactorbox.SetSelection(state.multi_factor)
1195
1196        #reset the fitting engine type
1197        self.engine_type = state.engine_type
1198        #draw the pnael according to the new model parameter
1199        self._on_select_model(event=None)
1200        # take care of 2D button
1201        if data == None and self.model_view.IsEnabled():
1202            if self.enable2D:
1203                self.model_view.SetLabel("2D Mode")
1204            else:
1205                self.model_view.SetLabel("1D Mode")
1206        # else:
1207               
1208        if self._manager !=None:
1209            self._manager._on_change_engine(engine=self.engine_type)
1210        ## set the select all check box to the a given state
1211        self.cb1.SetValue(state.cb1)
1212     
1213        ## reset state of checkbox,textcrtl  and  regular parameters value
1214        self._reset_parameters_state(self.orientation_params_disp,
1215                                     state.orientation_params_disp)
1216        self._reset_parameters_state(self.orientation_params,
1217                                     state.orientation_params)
1218        self._reset_parameters_state(self.str_parameters,
1219                                     state.str_parameters)
1220        self._reset_parameters_state(self.parameters,state.parameters)   
1221         ## display dispersion info layer       
1222        self.enable_disp.SetValue(state.enable_disp)
1223        self.disable_disp.SetValue(state.disable_disp)
1224        # If the polydispersion is ON
1225        if state.enable_disp:
1226            # reset dispersion according the state
1227            self._set_dipers_Param(event=None)
1228            self._reset_page_disp_helper(state)
1229        ##plotting range restore   
1230        self._reset_plotting_range(state)
1231        ## smearing info  restore
1232        if hasattr(self, "enable_smearer"):
1233            ## set smearing value whether or not the data
1234            #contain the smearing info
1235            self.enable_smearer.SetValue(state.enable_smearer)
1236            self.disable_smearer.SetValue(state.disable_smearer)
1237            self.onSmear(event=None)           
1238        self.pinhole_smearer.SetValue(state.pinhole_smearer)
1239        self.slit_smearer.SetValue(state.slit_smearer)
1240        try:
1241            self.dI_noweight.SetValue(state.dI_noweight)
1242            self.dI_didata.SetValue(state.dI_didata)
1243            self.dI_sqrdata.SetValue(state.dI_sqrdata)
1244            self.dI_idata.SetValue(state.dI_idata)
1245        except:
1246            # to support older state file formats
1247            self.dI_noweight.SetValue(False)
1248            self.dI_didata.SetValue(True)
1249            self.dI_sqrdata.SetValue(False)
1250            self.dI_idata.SetValue(False)
1251 
1252        ## we have two more options for smearing
1253        if self.pinhole_smearer.GetValue(): self.onPinholeSmear(event=None)
1254        elif self.slit_smearer.GetValue(): self.onSlitSmear(event=None)
1255       
1256        ## reset state of checkbox,textcrtl  and dispersity parameters value
1257        self._reset_parameters_state(self.fittable_param,state.fittable_param)
1258        self._reset_parameters_state(self.fixed_param,state.fixed_param)
1259       
1260        ## draw the model with previous parameters value
1261        self._onparamEnter_helper()
1262        #reset the value of chisqr when not consistent with the value computed
1263        self.tcChi.SetValue(str(self.state.tcChi))
1264        ## reset context menu items
1265        self._reset_context_menu()
1266       
1267        ## set the value of the current state to the state given as parameter
1268        self.state = state.clone() 
1269   
1270    def _reset_page_disp_helper(self, state):
1271        """
1272        Help to rest page for dispersions
1273        """
1274        keys = self.model.getParamList()
1275        for item in keys:
1276            if item in self.disp_list and \
1277                not self.model.details.has_key(item):
1278                self.model.details[item] = ["", None, None]
1279        #for k,v in self.state.disp_cb_dict.iteritems():
1280        self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 
1281        self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict)
1282        self.values = copy.deepcopy(state.values)
1283        self.weights = copy.deepcopy(state.weights)
1284       
1285        for key, disp in state._disp_obj_dict.iteritems():
1286            # From saved file, disp_model can not be sent in model obj.
1287            # it will be sent as a string here, then converted to model object.
1288            if disp.__class__.__name__ == 'str':
1289                com_str  = "from sans.models.dispersion_models "
1290                com_str += "import %s as disp_func"
1291                exec com_str % disp
1292                disp_model = disp_func()
1293            else:
1294                disp_model = disp
1295
1296            self._disp_obj_dict[key] = disp_model
1297            param_name = key.split('.')[0]
1298            # Try to set dispersion only when available
1299            # for eg., pass the orient. angles for 1D Cal
1300            try:
1301                self.model.set_dispersion(param_name, disp_model)
1302                self.model._persistency_dict[key] = \
1303                                 [state.values, state.weights]
1304            except:
1305                pass
1306            selection = self._find_polyfunc_selection(disp_model)
1307            for list in self.fittable_param:
1308                if list[1] == key and list[7] != None:
1309                    list[7].SetSelection(selection)
1310                    # For the array disp_model, set the values and weights
1311                    if selection == 1:
1312                        disp_model.set_weights(self.values[key], 
1313                                              self.weights[key])
1314                        try:
1315                            # Diables all fittable params for array
1316                            list[0].SetValue(False)
1317                            list[0].Disable()
1318                            list[2].Disable()
1319                            list[5].Disable()
1320                            list[6].Disable()
1321                        except:
1322                            pass
1323            # For array, disable all fixed params
1324            if selection == 1:
1325                for item in self.fixed_param:
1326                    if item[1].split(".")[0] == key.split(".")[0]:
1327                        # try it and pass it for the orientation for 1D
1328                        try:
1329                            item[2].Disable()
1330                        except:
1331                            pass
1332   
1333        # Make sure the check box updated when all checked
1334        if self.cb1.GetValue():
1335            self.select_all_param(None)       
1336     
1337    def _selectDlg(self):
1338        """
1339        open a dialog file to selected the customized dispersity
1340        """
1341        import os
1342        if self.parent !=  None:
1343            self._default_save_location = \
1344                        self.parent.parent._default_save_location
1345        dlg = wx.FileDialog(self, "Choose a weight file",
1346                                self._default_save_location , "", 
1347                                "*.*", wx.OPEN)
1348        path = None
1349        if dlg.ShowModal() == wx.ID_OK:
1350            path = dlg.GetPath()
1351        dlg.Destroy()
1352        return path
1353
1354    def _reset_context_menu(self):
1355        """
1356        reset the context menu
1357        """
1358        for name, state in self.state.saved_states.iteritems():
1359            self.number_saved_state += 1
1360            ## Add item in the context menu
1361            id = wx.NewId()
1362            msg = 'Save model and state %g' % self.number_saved_state
1363            self.popUpMenu.Append(id, name, msg)
1364            wx.EVT_MENU(self, id, self.onResetModel)
1365   
1366    def _reset_plotting_range(self, state):
1367        """
1368        Reset the plotting range to a given state
1369        """
1370        # if self.check_invalid_panel():
1371        #    return
1372        self.qmin.SetValue(str(state.qmin))
1373        self.qmax.SetValue(str(state.qmax)) 
1374
1375    def _save_typeOfmodel(self):
1376        """
1377        save radiobutton containing the type model that can be selected
1378        """
1379        self.state.shape_rbutton = self.shape_rbutton.GetValue()
1380        self.state.shape_indep_rbutton = self.shape_indep_rbutton.GetValue()
1381        self.state.struct_rbutton = self.struct_rbutton.GetValue()
1382        self.state.plugin_rbutton = self.plugin_rbutton.GetValue()
1383        self.state.structurebox= self.structurebox.GetCurrentSelection()
1384        self.state.formfactorbox = self.formfactorbox.GetCurrentSelection()
1385       
1386        #self._undo.Enable(True)
1387        ## post state to fit panel
1388        event = PageInfoEvent(page = self)
1389        wx.PostEvent(self.parent, event)
1390       
1391    def _save_plotting_range(self ):
1392        """
1393        save the state of plotting range
1394        """
1395        self.state.qmin = self.qmin_x
1396        self.state.qmax = self.qmax_x
1397        self.state.npts = self.npts_x
1398           
1399    def _onparamEnter_helper(self):
1400        """
1401        check if values entered by the user are changed and valid to replot
1402        model
1403        """
1404        # Flag to register when a parameter has changed.   
1405        is_modified = False
1406        self.fitrange = True
1407        is_2Ddata = False
1408        #self._undo.Enable(True)
1409        # check if 2d data
1410        if self.data.__class__.__name__ == "Data2D":
1411            is_2Ddata = True
1412        if self.model !=None:
1413            try:
1414                is_modified = self._check_value_enter(self.fittable_param,
1415                                                     is_modified)
1416                is_modified = self._check_value_enter(self.fixed_param,
1417                                                      is_modified)
1418                is_modified = self._check_value_enter(self.parameters,
1419                                                      is_modified) 
1420            except:
1421                pass
1422            #if is_modified:
1423
1424            # Here we should check whether the boundaries have been modified.
1425            # If qmin and qmax have been modified, update qmin and qmax and
1426            # set the is_modified flag to True
1427            if self._validate_qrange(self.qmin, self.qmax):
1428                tempmin = float(self.qmin.GetValue())
1429                if tempmin != self.qmin_x:
1430                    self.qmin_x = tempmin
1431                    is_modified = True
1432                tempmax = float(self.qmax.GetValue())
1433                if tempmax != self.qmax_x:
1434                    self.qmax_x = tempmax
1435                    is_modified = True
1436           
1437                if is_2Ddata:
1438                    # set mask   
1439                    is_modified = self._validate_Npts()
1440                   
1441            else:
1442                self.fitrange = False   
1443            ## if any value is modify draw model with new value
1444            if not self.fitrange:
1445                #self.btFit.Disable()
1446                if is_2Ddata: self.btEditMask.Disable()
1447            else:
1448                #self.btFit.Enable(True)
1449                if is_2Ddata  and not self.batch_on: 
1450                    self.btEditMask.Enable(True)
1451            if is_modified and self.fitrange:
1452                #if self.data == None:
1453                # Theory case: need to get npts value to draw
1454                self.npts_x = float(self.Npts_total.GetValue())
1455                self.create_default_data()
1456                self.state_change= True
1457                self._draw_model() 
1458                self.Refresh()
1459        return is_modified
1460   
1461    def _update_paramv_on_fit(self):
1462        """
1463        make sure that update param values just before the fitting
1464        """
1465        #flag for qmin qmax check values
1466        flag = True
1467        self.fitrange = True
1468        is_modified = False
1469
1470        #wx.PostEvent(self._manager.parent, StatusEvent(status=" \
1471        #updating ... ",type="update"))
1472
1473        ##So make sure that update param values on_Fit.
1474        #self._undo.Enable(True)
1475        if self.model !=None:           
1476            ##Check the values
1477            self._check_value_enter( self.fittable_param ,is_modified)
1478            self._check_value_enter( self.fixed_param ,is_modified)
1479            self._check_value_enter( self.parameters ,is_modified)
1480
1481            # If qmin and qmax have been modified, update qmin and qmax and
1482             # Here we should check whether the boundaries have been modified.
1483            # If qmin and qmax have been modified, update qmin and qmax and
1484            # set the is_modified flag to True
1485            self.fitrange = self._validate_qrange(self.qmin, self.qmax)
1486            if self.fitrange:
1487                tempmin = float(self.qmin.GetValue())
1488                if tempmin != self.qmin_x:
1489                    self.qmin_x = tempmin
1490                tempmax = float(self.qmax.GetValue())
1491                if tempmax != self.qmax_x:
1492                    self.qmax_x = tempmax
1493                if tempmax == tempmin:
1494                    flag = False   
1495                temp_smearer = None
1496                if not self.disable_smearer.GetValue():
1497                    temp_smearer= self.current_smearer
1498                    if self.slit_smearer.GetValue():
1499                        flag = self.update_slit_smear()
1500                    elif self.pinhole_smearer.GetValue():
1501                        flag = self.update_pinhole_smear()
1502                    else:
1503                        self._manager.set_smearer(smearer=temp_smearer,
1504                                                  uid=self.uid,
1505                                                  fid=self.data.id,
1506                                                     qmin=float(self.qmin_x),
1507                                                      qmax=float(self.qmax_x),
1508                            enable_smearer=not self.disable_smearer.GetValue(),
1509                                                      draw=False)
1510                elif not self._is_2D():
1511                    self._manager.set_smearer(smearer=temp_smearer,
1512                                              qmin=float(self.qmin_x),
1513                                              uid=self.uid, 
1514                                              fid=self.data.id,
1515                                                 qmax= float(self.qmax_x),
1516                            enable_smearer=not self.disable_smearer.GetValue(),
1517                                                 draw=False)
1518                    if self.data != None:
1519                        index_data = ((self.qmin_x <= self.data.x)&\
1520                                      (self.data.x <= self.qmax_x))
1521                        val = str(len(self.data.x[index_data==True]))
1522                        self.Npts_fit.SetValue(val)
1523                    else:
1524                        # No data in the panel
1525                        try:
1526                            self.npts_x = float(self.Npts_total.GetValue())
1527                        except:
1528                            flag = False
1529                            return flag
1530                    flag = True
1531                if self._is_2D():
1532                    # only 2D case set mask 
1533                    flag = self._validate_Npts()
1534                    if not flag:
1535                        return flag
1536            else: flag = False
1537        else: 
1538            flag = False
1539
1540        #For invalid q range, disable the mask editor and fit button, vs.   
1541        if not self.fitrange:
1542            #self.btFit.Disable()
1543            if self._is_2D():
1544                self.btEditMask.Disable()
1545        else:
1546            #self.btFit.Enable(True)
1547            if self._is_2D() and  self.data != None and not self.batch_on:
1548                self.btEditMask.Enable(True)
1549
1550        if not flag:
1551            msg = "Cannot Plot or Fit :Must select a "
1552            msg += " model or Fitting range is not valid!!!  "
1553            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
1554       
1555        self.save_current_state()
1556   
1557        return flag                           
1558               
1559    def _is_modified(self, is_modified):
1560        """
1561        return to self._is_modified
1562        """
1563        return is_modified
1564                       
1565    def _reset_parameters_state(self, listtorestore, statelist):
1566        """
1567        Reset the parameters at the given state
1568        """
1569        if len(statelist) == 0 or len(listtorestore) == 0:
1570            return
1571        if len(statelist) !=  len(listtorestore):
1572            return
1573
1574        for j in range(len(listtorestore)):
1575            item_page = listtorestore[j]
1576            item_page_info = statelist[j]
1577            ##change the state of the check box for simple parameters
1578            if item_page[0]!=None:   
1579                item_page[0].SetValue(item_page_info[0])
1580            if item_page[2]!=None:
1581                item_page[2].SetValue(item_page_info[2])
1582                if item_page[2].__class__.__name__ == "ComboBox":
1583                   if self.model.fun_list.has_key(item_page_info[2]):
1584                       fun_val = self.model.fun_list[item_page_info[2]]
1585                       self.model.setParam(item_page_info[1],fun_val)
1586            if item_page[3]!=None:
1587                ## show or hide text +/-
1588                if item_page_info[2]:
1589                    item_page[3].Show(True)
1590                else:
1591                    item_page[3].Hide()
1592            if item_page[4]!=None:
1593                ## show of hide the text crtl for fitting error
1594                if item_page_info[4][0]:
1595                    item_page[4].Show(True)
1596                    item_page[4].SetValue(item_page_info[4][1])
1597                else:
1598                    item_page[3].Hide()
1599            if item_page[5]!=None:
1600                ## show of hide the text crtl for fitting error
1601                item_page[5].Show(item_page_info[5][0])
1602                item_page[5].SetValue(item_page_info[5][1])
1603               
1604            if item_page[6]!=None:
1605                ## show of hide the text crtl for fitting error
1606                item_page[6].Show(item_page_info[6][0])
1607                item_page[6].SetValue(item_page_info[6][1])
1608
1609                   
1610    def _reset_strparam_state(self, listtorestore, statelist):
1611        """
1612        Reset the string parameters at the given state
1613        """
1614        if len(statelist) == 0:
1615            return
1616
1617        listtorestore = copy.deepcopy(statelist)
1618       
1619        for j in range(len(listtorestore)):
1620            item_page = listtorestore[j]
1621            item_page_info = statelist[j]
1622            ##change the state of the check box for simple parameters
1623           
1624            if item_page[0] != None:   
1625                item_page[0].SetValue(format_number(item_page_info[0], True))
1626
1627            if item_page[2] != None:
1628                param_name = item_page_info[1]
1629                value = item_page_info[2]
1630                selection = value
1631                if self.model.fun_list.has_key(value):
1632                    selection = self.model.fun_list[value]
1633                item_page[2].SetValue(selection)
1634                self.model.setParam(param_name, selection)
1635                                     
1636    def _copy_parameters_state(self, listtocopy, statelist):
1637        """
1638        copy the state of button
1639       
1640        :param listtocopy: the list of check button to copy
1641        :param statelist: list of state object to store the current state
1642       
1643        """
1644        if len(listtocopy)==0:
1645            return
1646       
1647        for item in listtocopy:
1648 
1649            checkbox_state = None
1650            if item[0]!= None:
1651                checkbox_state= item[0].GetValue()
1652            parameter_name = item[1]
1653            parameter_value = None
1654            if item[2]!=None:
1655                parameter_value = item[2].GetValue()
1656            static_text = None
1657            if item[3]!=None:
1658                static_text = item[3].IsShown()
1659            error_value = None
1660            error_state = None
1661            if item[4]!= None:
1662                error_value = item[4].GetValue()
1663                error_state = item[4].IsShown()
1664               
1665            min_value = None
1666            min_state = None
1667            if item[5]!= None:
1668                min_value = item[5].GetValue()
1669                min_state = item[5].IsShown()
1670               
1671            max_value = None
1672            max_state = None
1673            if item[6]!= None:
1674                max_value = item[6].GetValue()
1675                max_state = item[6].IsShown()
1676            unit=None
1677            if item[7]!=None:
1678                unit = item[7].GetLabel()
1679               
1680            statelist.append([checkbox_state, parameter_name, parameter_value,
1681                              static_text ,[error_state, error_value],
1682                                [min_state, min_value],
1683                                [max_state, max_value], unit])
1684           
1685    def _set_model_sizer_selection(self, model):
1686        """
1687        Display the sizer according to the type of the current model
1688        """
1689        if model == None:
1690            return
1691        if hasattr(model ,"s_model"):
1692           
1693            class_name = model.s_model.__class__
1694            name = model.s_model.name
1695            flag = (name != "NoStructure")
1696            if flag and \
1697                (class_name in self.model_list_box["Structure Factors"]):
1698                self.structurebox.Show()
1699                self.text2.Show()               
1700                self.structurebox.Enable()
1701                self.text2.Enable()
1702                items = self.structurebox.GetItems()
1703                self.sizer1.Layout()
1704               
1705                for i in range(len(items)):
1706                    if items[i]== str(name):
1707                        self.structurebox.SetSelection(i)
1708                        break
1709                   
1710        if hasattr(model ,"p_model"):
1711            class_name = model.p_model.__class__
1712            name = model.p_model.name
1713            self.formfactorbox.Clear()
1714           
1715            for k, list in self.model_list_box.iteritems():
1716                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
1717                    self.shape_rbutton.SetValue(True)
1718                    ## fill the form factor list with new model
1719                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
1720                    items = self.formfactorbox.GetItems()
1721                    ## set comboxbox to the selected item
1722                    for i in range(len(items)):
1723                        if items[i]== str(name):
1724                            self.formfactorbox.SetSelection(i)
1725                            break
1726                    return
1727                elif k == "Shape-Independent":
1728                    self.shape_indep_rbutton.SetValue(True)
1729                elif k == "Structure Factors":
1730                     self.struct_rbutton.SetValue(True)
1731                elif  k == "Multi-Functions":
1732                    continue
1733                else:
1734                    self.plugin_rbutton.SetValue(True)
1735               
1736                if class_name in list:
1737                    ## fill the form factor list with new model
1738                    self._populate_box(self.formfactorbox, list)
1739                    items = self.formfactorbox.GetItems()
1740                    ## set comboxbox to the selected item
1741                    for i in range(len(items)):
1742                        if items[i]== str(name):
1743                            self.formfactorbox.SetSelection(i)
1744                            break
1745                    break
1746        else:
1747
1748            ## Select the model from the menu
1749            class_name = model.__class__
1750            name = model.name
1751            self.formfactorbox.Clear()
1752            items = self.formfactorbox.GetItems()
1753   
1754            for k, list in self.model_list_box.iteritems():         
1755                if k in["P(Q)*S(Q)","Shapes" ] and class_name in self.model_list_box["Shapes"]:
1756                    if class_name in self.model_list_box["P(Q)*S(Q)"]:
1757                        self.structurebox.Show()
1758                        self.text2.Show()
1759                        self.structurebox.Enable()
1760                        self.structurebox.SetSelection(0)
1761                        self.text2.Enable()
1762                    else:
1763                        self.structurebox.Hide()
1764                        self.text2.Hide()
1765                        self.structurebox.Disable()
1766                        self.structurebox.SetSelection(0)
1767                        self.text2.Disable()
1768                       
1769                    self.shape_rbutton.SetValue(True)
1770                    ## fill the form factor list with new model
1771                    self._populate_box(self.formfactorbox,self.model_list_box["Shapes"])
1772                    items = self.formfactorbox.GetItems()
1773                    ## set comboxbox to the selected item
1774                    for i in range(len(items)):
1775                        if items[i]== str(name):
1776                            self.formfactorbox.SetSelection(i)
1777                            break
1778                    return
1779                elif k == "Shape-Independent":
1780                    self.shape_indep_rbutton.SetValue(True)
1781                elif k == "Structure Factors":
1782                    self.struct_rbutton.SetValue(True)
1783                elif  k == "Multi-Functions":
1784                    continue
1785                else:
1786                    self.plugin_rbutton.SetValue(True)
1787                if class_name in list:
1788                    self.structurebox.SetSelection(0)
1789                    self.structurebox.Disable()
1790                    self.text2.Disable()                   
1791                    ## fill the form factor list with new model
1792                    self._populate_box(self.formfactorbox, list)
1793                    items = self.formfactorbox.GetItems()
1794                    ## set comboxbox to the selected item
1795                    for i in range(len(items)):
1796                        if items[i]== str(name):
1797                            self.formfactorbox.SetSelection(i)
1798                            break
1799                    break
1800   
1801    def _draw_model(self, update_chisqr=True, source='model'):
1802        """
1803        Method to draw or refresh a plotted model.
1804        The method will use the data member from the model page
1805        to build a call to the fitting perspective manager.
1806       
1807        :param chisqr: update chisqr value [bool]
1808        """
1809        #if self.check_invalid_panel():
1810        #    return
1811        if self.model !=None:
1812            temp_smear=None
1813            if hasattr(self, "enable_smearer"):
1814                if not self.disable_smearer.GetValue():
1815                    temp_smear= self.current_smearer
1816            # compute weight for the current data
1817            from .utils import get_weight
1818            flag = self.get_weight_flag()
1819            weight = get_weight(data=self.data, is2d=self._is_2D(), flag=flag)
1820            toggle_mode_on = self.model_view.IsEnabled()
1821            is_2d = self._is_2D()
1822            self._manager.draw_model(self.model, 
1823                                    data=self.data,
1824                                    smearer= temp_smear,
1825                                    qmin=float(self.qmin_x), 
1826                                    qmax=float(self.qmax_x),
1827                                    page_id=self.uid,
1828                                    toggle_mode_on=toggle_mode_on, 
1829                                    state = self.state,
1830                                    enable2D=is_2d,
1831                                    update_chisqr=update_chisqr,
1832                                    source='model',
1833                                    weight=weight)
1834       
1835       
1836    def _on_show_sld(self, event=None):
1837        """
1838        Plot SLD profile
1839        """
1840        # get profile data
1841        x,y=self.model.getProfile()
1842
1843        from danse.common.plottools import Data1D
1844        #from sans.perspectives.theory.profile_dialog import SLDPanel
1845        from sans.guiframe.local_perspectives.plotting.profile_dialog \
1846        import SLDPanel
1847        sld_data = Data1D(x,y)
1848        sld_data.name = 'SLD'
1849        sld_data.axes = self.sld_axes
1850        self.panel = SLDPanel(self, data=sld_data, axes =self.sld_axes,id =-1)
1851        self.panel.ShowModal()   
1852       
1853    def _set_multfactor_combobox(self, multiplicity=10):   
1854        """
1855        Set comboBox for muitfactor of CoreMultiShellModel
1856        :param multiplicit: no. of multi-functionality
1857        """
1858        # build content of the combobox
1859        for idx in range(0,multiplicity):
1860            self.multifactorbox.Append(str(idx),int(idx))
1861            #self.multifactorbox.SetSelection(1)
1862        self._hide_multfactor_combobox()
1863       
1864    def _show_multfactor_combobox(self):   
1865        """
1866        Show the comboBox of muitfactor of CoreMultiShellModel
1867        """ 
1868        if not self.mutifactor_text.IsShown():
1869            self.mutifactor_text.Show(True)
1870            self.mutifactor_text1.Show(True)
1871        if not self.multifactorbox.IsShown():
1872            self.multifactorbox.Show(True) 
1873             
1874    def _hide_multfactor_combobox(self):   
1875        """
1876        Hide the comboBox of muitfactor of CoreMultiShellModel
1877        """ 
1878        if self.mutifactor_text.IsShown():
1879            self.mutifactor_text.Hide()
1880            self.mutifactor_text1.Hide()
1881        if self.multifactorbox.IsShown():
1882            self.multifactorbox.Hide()   
1883
1884       
1885    def _show_combox_helper(self):
1886        """
1887        Fill panel's combo box according to the type of model selected
1888        """
1889        if self.shape_rbutton.GetValue():
1890            ##fill the combobox with form factor list
1891            self.structurebox.SetSelection(0)
1892            self.structurebox.Disable()
1893            self.formfactorbox.Clear()
1894            self._populate_box( self.formfactorbox,self.model_list_box["Shapes"])
1895        if self.shape_indep_rbutton.GetValue():
1896            ##fill the combobox with shape independent  factor list
1897            self.structurebox.SetSelection(0)
1898            self.structurebox.Disable()
1899            self.formfactorbox.Clear()
1900            self._populate_box( self.formfactorbox,
1901                                self.model_list_box["Shape-Independent"])
1902        if self.struct_rbutton.GetValue():
1903            ##fill the combobox with structure factor list
1904            self.structurebox.SetSelection(0)
1905            self.structurebox.Disable()
1906            self.formfactorbox.Clear()
1907            self._populate_box( self.formfactorbox,
1908                                self.model_list_box["Structure Factors"])
1909        if self.plugin_rbutton.GetValue():
1910            ##fill the combobox with form factor list
1911            self.structurebox.Disable()
1912            self.formfactorbox.Clear()
1913            self._populate_box( self.formfactorbox,
1914                                self.model_list_box["Customized Models"])
1915       
1916    def _show_combox(self, event=None):
1917        """
1918        Show combox box associate with type of model selected
1919        """
1920        #if self.check_invalid_panel():
1921        #    self.shape_rbutton.SetValue(True)
1922        #    return
1923        self.Show(False)
1924        self._show_combox_helper()
1925        self._on_select_model(event=None)
1926        self.Show(True)
1927        self._save_typeOfmodel()
1928        self.sizer4_4.Layout()
1929        self.sizer4.Layout()
1930        self.Layout()
1931        self.Refresh()
1932 
1933    def _populate_box(self, combobox, list):
1934        """
1935        fill combox box with dict item
1936       
1937        :param list: contains item to fill the combox
1938            item must model class
1939        """
1940        for models in list:
1941            model= models()
1942            name = model.__class__.__name__
1943            if models.__name__!="NoStructure":
1944                if hasattr(model, "name"):
1945                    name = model.name
1946                combobox.Append(name,models)
1947        return 0
1948   
1949    def _onQrangeEnter(self, event):
1950        """
1951        Check validity of value enter in the Q range field
1952       
1953        """
1954        tcrtl = event.GetEventObject()
1955        #Clear msg if previously shown.
1956        msg = ""
1957        wx.PostEvent(self.parent, StatusEvent(status=msg))
1958        # Flag to register when a parameter has changed.
1959        is_modified = False
1960        if tcrtl.GetValue().lstrip().rstrip() != "":
1961            try:
1962                value = float(tcrtl.GetValue())
1963                tcrtl.SetBackgroundColour(wx.WHITE)
1964                # If qmin and qmax have been modified, update qmin and qmax
1965                if self._validate_qrange(self.qmin, self.qmax):
1966                    tempmin = float(self.qmin.GetValue())
1967                    if tempmin != self.qmin_x:
1968                        self.qmin_x = tempmin
1969                    tempmax = float(self.qmax.GetValue())
1970                    if tempmax != self.qmax_x:
1971                        self.qmax_x = tempmax
1972                else:
1973                    tcrtl.SetBackgroundColour("pink")
1974                    msg = "Model Error:wrong value entered : %s" % sys.exc_value
1975                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1976                    return 
1977            except:
1978                tcrtl.SetBackgroundColour("pink")
1979                msg = "Model Error:wrong value entered : %s" % sys.exc_value
1980                wx.PostEvent(self.parent, StatusEvent(status=msg))
1981                return 
1982            #Check if # of points for theory model are valid(>0).
1983            if self.npts != None:
1984                if check_float(self.npts):
1985                    temp_npts = float(self.npts.GetValue())
1986                    if temp_npts !=  self.num_points:
1987                        self.num_points = temp_npts
1988                        is_modified = True
1989                else:
1990                    msg = "Cannot Plot :No npts in that Qrange!!!  "
1991                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1992        else:
1993           tcrtl.SetBackgroundColour("pink")
1994           msg = "Model Error:wrong value entered!!!"
1995           wx.PostEvent(self.parent, StatusEvent(status=msg))
1996        #self._undo.Enable(True)
1997        self.save_current_state()
1998        event = PageInfoEvent(page=self)
1999        wx.PostEvent(self.parent, event)
2000        self.state_change = False
2001        #Draw the model for a different range
2002        self.create_default_data()
2003        self._draw_model()
2004                   
2005    def _theory_qrange_enter(self, event):
2006        """
2007        Check validity of value enter in the Q range field
2008        """
2009       
2010        tcrtl= event.GetEventObject()
2011        #Clear msg if previously shown.
2012        msg= ""
2013        wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2014        # Flag to register when a parameter has changed.
2015        is_modified = False
2016        if tcrtl.GetValue().lstrip().rstrip()!="":
2017            try:
2018                value = float(tcrtl.GetValue())
2019                tcrtl.SetBackgroundColour(wx.WHITE)
2020
2021                # If qmin and qmax have been modified, update qmin and qmax
2022                if self._validate_qrange(self.theory_qmin, self.theory_qmax):
2023                    tempmin = float(self.theory_qmin.GetValue())
2024                    if tempmin != self.theory_qmin_x:
2025                        self.theory_qmin_x = tempmin
2026                    tempmax = float(self.theory_qmax.GetValue())
2027                    if tempmax != self.qmax_x:
2028                        self.theory_qmax_x = tempmax
2029                else:
2030                    tcrtl.SetBackgroundColour("pink")
2031                    msg= "Model Error:wrong value entered : %s"% sys.exc_value
2032                    wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
2033                    return 
2034            except:
2035                tcrtl.SetBackgroundColour("pink")
2036                msg= "Model Error:wrong value entered : %s"% sys.exc_value
2037                wx.PostEvent(self._manager.parent, StatusEvent(status = msg ))
2038                return 
2039            #Check if # of points for theory model are valid(>0).
2040            if self.Npts_total.IsEditable() :
2041                if check_float(self.Npts_total):
2042                    temp_npts = float(self.Npts_total.GetValue())
2043                    if temp_npts !=  self.num_points:
2044                        self.num_points = temp_npts
2045                        is_modified = True
2046                else:
2047                    msg= "Cannot Plot :No npts in that Qrange!!!  "
2048                    wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2049        else:
2050           tcrtl.SetBackgroundColour("pink")
2051           msg = "Model Error:wrong value entered!!!"
2052           wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
2053        #self._undo.Enable(True)
2054        self.save_current_state()
2055        event = PageInfoEvent(page = self)
2056        wx.PostEvent(self.parent, event)
2057        self.state_change= False
2058        #Draw the model for a different range
2059        self.create_default_data()
2060        self._draw_model()
2061                   
2062    def _on_select_model_helper(self): 
2063        """
2064        call back for model selection
2065        """
2066        ## reset dictionary containing reference to dispersion
2067        self._disp_obj_dict = {}
2068        self.disp_cb_dict ={}
2069        self.temp_multi_functional = False
2070        f_id = self.formfactorbox.GetCurrentSelection()
2071        #For MAC
2072        form_factor = None
2073        if f_id >= 0:
2074            form_factor = self.formfactorbox.GetClientData(f_id)
2075
2076        if not form_factor in  self.model_list_box["multiplication"]:
2077            self.structurebox.Hide()
2078            self.text2.Hide()           
2079            self.structurebox.Disable()
2080            self.structurebox.SetSelection(0)
2081            self.text2.Disable()
2082        else:
2083            self.structurebox.Show()
2084            self.text2.Show()
2085            self.structurebox.Enable()
2086            self.text2.Enable()
2087           
2088        if form_factor != None:   
2089            # set multifactor for Mutifunctional models   
2090            if form_factor().__class__ in self.model_list_box["Multi-Functions"]:
2091                m_id = self.multifactorbox.GetCurrentSelection()
2092                multiplicity = form_factor().multiplicity_info[0]
2093                self.multifactorbox.Clear()
2094                #self.mutifactor_text.SetLabel(form_factor().details[])
2095                self._set_multfactor_combobox(multiplicity)
2096                self._show_multfactor_combobox()
2097                #ToDo:  this info should be called directly from the model
2098                text = form_factor().multiplicity_info[1]#'No. of Shells: '
2099
2100                #self.mutifactor_text.Clear()
2101                self.mutifactor_text.SetLabel(text)
2102                if m_id > multiplicity -1:
2103                    # default value
2104                    m_id = 1
2105                   
2106                self.multi_factor = self.multifactorbox.GetClientData(m_id)
2107                if self.multi_factor == None: self.multi_factor =0
2108                form_factor = form_factor(int(self.multi_factor))
2109                self.multifactorbox.SetSelection(m_id)
2110                # Check len of the text1 and max_multiplicity
2111                text = ''
2112                if form_factor.multiplicity_info[0] == len(form_factor.multiplicity_info[2]):
2113                    text = form_factor.multiplicity_info[2][self.multi_factor]
2114                self.mutifactor_text1.SetLabel(text)
2115                # Check if model has  get sld profile.
2116                if len(form_factor.multiplicity_info[3]) > 0:
2117                    self.sld_axes = form_factor.multiplicity_info[3]
2118                    self.show_sld_button.Show(True)
2119                else:
2120                    self.sld_axes = ""
2121
2122            else:
2123                self._hide_multfactor_combobox()
2124                self.show_sld_button.Hide()
2125                form_factor = form_factor()
2126                self.multi_factor = None
2127        else:
2128            self._hide_multfactor_combobox()
2129            self.show_sld_button.Hide()
2130            self.multi_factor = None 
2131             
2132        s_id = self.structurebox.GetCurrentSelection()
2133        struct_factor = self.structurebox.GetClientData( s_id )
2134       
2135        if  struct_factor !=None:
2136            from sans.models.MultiplicationModel import MultiplicationModel
2137            self.model= MultiplicationModel(form_factor,struct_factor())
2138            # multifunctional form factor
2139            if len(form_factor.non_fittable) > 0:
2140                self.temp_multi_functional = True
2141        else:
2142            if form_factor != None:
2143                self.model= form_factor
2144            else:
2145                self.model = None
2146                return self.model
2147           
2148        ## post state to fit panel
2149        self.state.parameters =[]
2150        self.state.model =self.model
2151        self.state.qmin = self.qmin_x
2152        self.state.multi_factor = self.multi_factor
2153        self.disp_list =self.model.getDispParamList()
2154        self.state.disp_list = self.disp_list
2155        self.on_set_focus(None)
2156        self.Layout()     
2157       
2158    def _validate_qrange(self, qmin_ctrl, qmax_ctrl):
2159        """
2160        Verify that the Q range controls have valid values
2161        and that Qmin < Qmax.
2162       
2163        :param qmin_ctrl: text control for Qmin
2164        :param qmax_ctrl: text control for Qmax
2165       
2166        :return: True is the Q range is value, False otherwise
2167       
2168        """
2169        qmin_validity = check_float(qmin_ctrl)
2170        qmax_validity = check_float(qmax_ctrl)
2171        if not (qmin_validity and qmax_validity):
2172            return False
2173        else:
2174            qmin = float(qmin_ctrl.GetValue())
2175            qmax = float(qmax_ctrl.GetValue())
2176            if qmin < qmax:
2177                #Make sure to set both colours white. 
2178                qmin_ctrl.SetBackgroundColour(wx.WHITE)
2179                qmin_ctrl.Refresh()
2180                qmax_ctrl.SetBackgroundColour(wx.WHITE)
2181                qmax_ctrl.Refresh()
2182            else:
2183                qmin_ctrl.SetBackgroundColour("pink")
2184                qmin_ctrl.Refresh()
2185                qmax_ctrl.SetBackgroundColour("pink")
2186                qmax_ctrl.Refresh()
2187                msg= "Invalid Q range: Q min must be smaller than Q max"
2188                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2189                return False
2190        return True
2191   
2192    def _validate_Npts(self): 
2193        """
2194        Validate the number of points for fitting is more than 10 points.
2195        If valid, setvalues Npts_fit otherwise post msg.
2196        """
2197        #default flag
2198        flag = True
2199        # Theory
2200        if self.data == None and self.enable2D:
2201            return flag
2202        for data in self.data_list:
2203            # q value from qx and qy
2204            radius= numpy.sqrt( data.qx_data * data.qx_data + 
2205                                data.qy_data * data.qy_data )
2206            #get unmasked index
2207            index_data = (float(self.qmin.GetValue()) <= radius) & \
2208                            (radius <= float(self.qmax.GetValue()))
2209            index_data = (index_data) & (data.mask) 
2210            index_data = (index_data) & (numpy.isfinite(data.data))
2211
2212            if len(index_data[index_data]) < 10:
2213                # change the color pink.
2214                self.qmin.SetBackgroundColour("pink")
2215                self.qmin.Refresh()
2216                self.qmax.SetBackgroundColour("pink")
2217                self.qmax.Refresh()
2218                msg= "Npts of Data Error :No or too little npts of %s."% data.name
2219                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2220                self.fitrange = False
2221                flag = False
2222            else:
2223                self.Npts_fit.SetValue(str(len(index_data[index_data==True])))
2224                self.fitrange = True
2225           
2226        return flag
2227
2228    def _validate_Npts_1D(self): 
2229        """
2230        Validate the number of points for fitting is more than 5 points.
2231        If valid, setvalues Npts_fit otherwise post msg.
2232        """
2233        #default flag
2234        flag = True
2235        # Theory
2236        if self.data == None:
2237            return flag
2238        for data in self.data_list:
2239            # q value from qx and qy
2240            radius= data.x
2241            #get unmasked index
2242            index_data = (float(self.qmin.GetValue()) <= radius) & \
2243                            (radius <= float(self.qmax.GetValue()))
2244            index_data = (index_data) & (numpy.isfinite(data.y))
2245
2246            if len(index_data[index_data]) < 5:
2247                # change the color pink.
2248                self.qmin.SetBackgroundColour("pink")
2249                self.qmin.Refresh()
2250                self.qmax.SetBackgroundColour("pink")
2251                self.qmax.Refresh()
2252                msg= "Npts of Data Error :No or too little npts of %s."% data.name
2253                wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2254                self.fitrange = False
2255                flag = False
2256            else:
2257                self.Npts_fit.SetValue(str(len(index_data[index_data==True])))
2258                self.fitrange = True
2259           
2260        return flag
2261
2262
2263   
2264    def _check_value_enter(self, list, modified):
2265        """
2266        :param list: model parameter and panel info
2267        :Note: each item of the list should be as follow:
2268            item=[check button state, parameter's name,
2269                paramater's value, string="+/-",
2270                parameter's error of fit,
2271                parameter's minimum value,
2272                parrameter's maximum value ,
2273                parameter's units]
2274        """ 
2275        is_modified =  modified
2276        if len(list)==0:
2277            return is_modified
2278        for item in list:
2279            #skip angle parameters for 1D
2280            if not self.enable2D:#self.data.__class__.__name__ !="Data2D":
2281                if item in self.orientation_params:
2282                    continue
2283            #try:
2284            name = str(item[1])
2285           
2286            if string.find(name,".npts") ==-1 and \
2287                                        string.find(name,".nsigmas")==-1:     
2288                ## check model parameters range             
2289                param_min= None
2290                param_max= None
2291               
2292                ## check minimun value
2293                if item[5]!= None and item[5]!= "":
2294                    if item[5].GetValue().lstrip().rstrip()!="":
2295                        try:
2296                           
2297                            param_min = float(item[5].GetValue())
2298                            if not self._validate_qrange(item[5],item[2]):
2299                                if numpy.isfinite(param_min):
2300                                    item[2].SetValue(format_number(param_min))
2301                           
2302                            item[5].SetBackgroundColour(wx.WHITE)
2303                            item[2].SetBackgroundColour(wx.WHITE)
2304                                           
2305                        except:
2306                            msg = "Wrong Fit parameter range entered "
2307                            wx.PostEvent(self.parent.parent, 
2308                                         StatusEvent(status = msg))
2309                            raise ValueError, msg
2310                        is_modified = True
2311                ## check maximum value
2312                if item[6]!= None and item[6]!= "":
2313                    if item[6].GetValue().lstrip().rstrip()!="":
2314                        try:                         
2315                            param_max = float(item[6].GetValue())
2316                            if not self._validate_qrange(item[2],item[6]):
2317                                if numpy.isfinite(param_max):
2318                                    item[2].SetValue(format_number(param_max)) 
2319                           
2320                            item[6].SetBackgroundColour(wx.WHITE)
2321                            item[2].SetBackgroundColour(wx.WHITE)
2322                        except:
2323                            msg = "Wrong Fit parameter range entered "
2324                            wx.PostEvent(self.parent.parent, 
2325                                         StatusEvent(status = msg))
2326                            raise ValueError, msg
2327                        is_modified = True
2328               
2329
2330                if param_min != None and param_max !=None:
2331                    if not self._validate_qrange(item[5], item[6]):
2332                        msg= "Wrong Fit range entered for parameter "
2333                        msg+= "name %s of model %s "%(name, self.model.name)
2334                        wx.PostEvent(self.parent.parent, 
2335                                     StatusEvent(status = msg))
2336               
2337                if name in self.model.details.keys():   
2338                        self.model.details[name][1:3] = param_min, param_max
2339                        is_modified = True
2340             
2341                else:
2342                        self.model.details [name] = ["", param_min, param_max] 
2343                        is_modified = True
2344            try:   
2345                # Check if the textctr is enabled
2346                if item[2].IsEnabled():
2347                    value= float(item[2].GetValue())
2348                    item[2].SetBackgroundColour("white")
2349                    # If the value of the parameter has changed,
2350                    # +update the model and set the is_modified flag
2351                    if value != self.model.getParam(name) and \
2352                                                numpy.isfinite(value):
2353                        self.model.setParam(name, value)
2354                       
2355            except:
2356                item[2].SetBackgroundColour("pink")
2357                msg = "Wrong Fit parameter value entered "
2358                wx.PostEvent(self.parent.parent, StatusEvent(status = msg))
2359               
2360        return is_modified
2361       
2362 
2363    def _set_dipers_Param(self, event):
2364        """
2365        respond to self.enable_disp and self.disable_disp radio box.
2366        The dispersity object is reset inside the model into Gaussian.
2367        When the user select yes , this method display a combo box for more selection
2368        when the user selects No,the combo box disappears.
2369        Redraw the model with the default dispersity (Gaussian)
2370        """
2371        #if self.check_invalid_panel():
2372        #    return
2373        ## On selction if no model exists.
2374        if self.model ==None:
2375            self.disable_disp.SetValue(True)
2376            msg="Please select a Model first..."
2377            wx.MessageBox(msg, 'Info')
2378            wx.PostEvent(self._manager.parent, StatusEvent(status=\
2379                            "Polydispersion: %s"%msg))
2380            return
2381
2382        self._reset_dispersity()
2383   
2384        if self.model ==None:
2385            self.model_disp.Hide()
2386            self.sizer4_4.Clear(True)
2387            return
2388
2389        if self.enable_disp.GetValue():
2390            ## layout for model containing no dispersity parameters
2391           
2392            self.disp_list= self.model.getDispParamList()
2393             
2394            if len(self.disp_list)==0 and len(self.disp_cb_dict)==0:
2395                self._layout_sizer_noDipers() 
2396            else:
2397                ## set gaussian sizer
2398                self._on_select_Disp(event=None)
2399        else:
2400            self.sizer4_4.Clear(True)
2401           
2402        ## post state to fit panel
2403        self.save_current_state()
2404        if event !=None:
2405            #self._undo.Enable(True)
2406            event = PageInfoEvent(page = self)
2407            wx.PostEvent(self.parent, event)
2408        #draw the model with the current dispersity
2409        self._draw_model()
2410        self.sizer4_4.Layout()
2411        self.sizer5.Layout()
2412        self.Layout()
2413        self.Refresh()     
2414         
2415       
2416    def _layout_sizer_noDipers(self):
2417        """
2418        Draw a sizer with no dispersity info
2419        """
2420        ix=0
2421        iy=1
2422        self.fittable_param=[]
2423        self.fixed_param=[]
2424        self.orientation_params_disp=[]
2425       
2426        self.sizer4_4.Clear(True)
2427        text = "No polydispersity available for this model"
2428        text = "No polydispersity available for this model"
2429        model_disp = wx.StaticText(self, -1, text)
2430        self.sizer4_4.Add(model_disp,( iy, ix),(1,1), 
2431                            wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 10)
2432        self.sizer4_4.Layout()
2433        self.sizer4.Layout()
2434   
2435    def _reset_dispersity(self):
2436        """
2437        put gaussian dispersity into current model
2438        """
2439        if len(self.param_toFit)>0:
2440            for item in self.fittable_param:
2441                if item in self.param_toFit:
2442                    self.param_toFit.remove(item)
2443
2444            for item in self.orientation_params_disp:
2445                if item in self.param_toFit:
2446                    self.param_toFit.remove(item)
2447         
2448        self.fittable_param=[]
2449        self.fixed_param=[]
2450        self.orientation_params_disp=[]
2451        self.values={}
2452        self.weights={}
2453     
2454        from sans.models.dispersion_models import GaussianDispersion, ArrayDispersion
2455        if len(self.disp_cb_dict)==0:
2456            self.save_current_state()
2457            self.sizer4_4.Clear(True)
2458            self.Layout()
2459 
2460            return 
2461        if (len(self.disp_cb_dict)>0) :
2462            for p in self.disp_cb_dict:
2463                # The parameter was un-selected. Go back to Gaussian model (with 0 pts)                   
2464                disp_model = GaussianDispersion()
2465               
2466                self._disp_obj_dict[p] = disp_model
2467                # Set the new model as the dispersion object for the selected parameter
2468                try:
2469                   self.model.set_dispersion(p, disp_model)
2470                except:
2471
2472                    pass
2473
2474        ## save state into
2475        self.save_current_state()
2476        self.Layout() 
2477        self.Refresh()
2478                 
2479    def _on_select_Disp(self,event):
2480        """
2481        allow selecting different dispersion
2482        self.disp_list should change type later .now only gaussian
2483        """
2484        self._set_sizer_dispersion()
2485
2486        ## Redraw the model
2487        self._draw_model() 
2488        #self._undo.Enable(True)
2489        event = PageInfoEvent(page = self)
2490        wx.PostEvent(self.parent, event)
2491       
2492        self.sizer4_4.Layout()
2493        self.sizer4.Layout()
2494        self.SetupScrolling()
2495   
2496    def _on_disp_func(self, event=None): 
2497        """
2498        Select a distribution function for the polydispersion
2499       
2500        :Param event: ComboBox event
2501        """
2502        # get ready for new event
2503        if event != None:
2504            event.Skip()
2505        # Get event object
2506        disp_box =  event.GetEventObject() 
2507
2508        # Try to select a Distr. function
2509        try:   
2510            disp_box.SetBackgroundColour("white")
2511            selection = disp_box.GetCurrentSelection()
2512            param_name = disp_box.Name.split('.')[0]
2513            disp_name = disp_box.GetValue()
2514            dispersity= disp_box.GetClientData(selection)
2515   
2516            #disp_model =  GaussianDispersion()
2517            disp_model = dispersity()
2518            # Get param names to reset the values of the param
2519            name1 = param_name + ".width"
2520            name2 = param_name + ".npts"
2521            name3 = param_name + ".nsigmas"
2522            # Check Disp. function whether or not it is 'array'
2523            if disp_name.lower() == "array":
2524                value2= ""
2525                value3= ""
2526                value1 = self._set_array_disp(name=name1, disp=disp_model)
2527            else:
2528                self._del_array_values(name1)
2529                #self._reset_array_disp(param_name)
2530                self._disp_obj_dict[name1] = disp_model
2531                self.model.set_dispersion(param_name, disp_model)
2532                self.state._disp_obj_dict[name1]= disp_model
2533 
2534                value1= str(format_number(self.model.getParam(name1), True))
2535                value2= str(format_number(self.model.getParam(name2)))
2536                value3= str(format_number(self.model.getParam(name3)))
2537            # Reset fittable polydispersin parameter value
2538            for item in self.fittable_param:
2539                 if item[1] == name1:
2540                    item[2].SetValue(value1) 
2541                    item[5].SetValue("")
2542                    item[6].SetValue("")
2543                    # Disable for array
2544                    if disp_name.lower() == "array":
2545                        item[0].SetValue(False)
2546                        item[0].Disable()
2547                        item[2].Disable()
2548                        item[3].Show(False)
2549                        item[4].Show(False)
2550                        item[5].Disable()
2551                        item[6].Disable()
2552                    else:
2553                        item[0].Enable()
2554                        item[2].Enable()
2555                        item[5].Enable()
2556                        item[6].Enable()                       
2557                    break
2558            # Reset fixed polydispersion params
2559            for item in self.fixed_param:
2560                if item[1] == name2:
2561                    item[2].SetValue(value2) 
2562                    # Disable Npts for array
2563                    if disp_name.lower() == "array":
2564                        item[2].Disable()
2565                    else:
2566                        item[2].Enable()
2567                if item[1] == name3:
2568                    item[2].SetValue(value3) 
2569                    # Disable Nsigs for array
2570                    if disp_name.lower() == "array":
2571                        item[2].Disable()
2572                    else:
2573                        item[2].Enable()
2574               
2575            # Make sure the check box updated when all checked
2576            if self.cb1.GetValue():
2577                #self.select_all_param(None)
2578                self.get_all_checked_params()
2579
2580            # update params
2581            self._update_paramv_on_fit() 
2582            # draw
2583            self._draw_model()
2584            self.Refresh()
2585        except:
2586            # Error msg
2587            msg = "Error occurred:"
2588            msg += " Could not select the distribution function..."
2589            msg += " Please select another distribution function."
2590            disp_box.SetBackgroundColour("pink")
2591            # Focus on Fit button so that users can see the pinky box
2592            self.btFit.SetFocus()
2593            wx.PostEvent(self.parent.parent, 
2594                         StatusEvent(status=msg, info="error"))
2595       
2596       
2597    def _set_array_disp(self, name=None, disp=None):
2598        """
2599        Set array dispersion
2600       
2601        :param name: name of the parameter for the dispersion to be set
2602        :param disp: the polydisperion object
2603        """
2604        # The user wants this parameter to be averaged.
2605        # Pop up the file selection dialog.
2606        path = self._selectDlg()
2607        # Array data
2608        values = []
2609        weights = []
2610        # If nothing was selected, just return
2611        if path is None:
2612            self.disp_cb_dict[name].SetValue(False)
2613            #self.noDisper_rbox.SetValue(True)
2614            return
2615        self._default_save_location = os.path.dirname(path)
2616        if self.parent != None:
2617            self.parent.parent._default_save_location =\
2618                             self._default_save_location
2619
2620        basename  = os.path.basename(path)
2621        values,weights = self.read_file(path)
2622       
2623        # If any of the two arrays is empty, notify the user that we won't
2624        # proceed
2625        if len(self.param_toFit)>0:
2626            if name in self.param_toFit:
2627                self.param_toFit.remove(name)
2628
2629        # Tell the user that we are about to apply the distribution
2630        msg = "Applying loaded %s distribution: %s" % (name, path)
2631        wx.PostEvent(self.parent.parent, StatusEvent(status=msg)) 
2632        self._set_array_disp_model(name=name, disp=disp,
2633                                    values=values, weights=weights)
2634        return basename
2635   
2636    def _set_array_disp_model(self, name=None, disp=None, 
2637                              values=[], weights=[]):
2638        """
2639        Set array dispersion model
2640       
2641        :param name: name of the parameter for the dispersion to be set
2642        :param disp: the polydisperion object
2643        """
2644        disp.set_weights(values, weights)
2645        self._disp_obj_dict[name] = disp
2646        self.model.set_dispersion(name.split('.')[0], disp)
2647        self.state._disp_obj_dict[name]= disp
2648        self.values[name] = values
2649        self.weights[name] = weights
2650        # Store the object to make it persist outside the
2651        # scope of this method
2652        #TODO: refactor model to clean this up?
2653        self.state.values = {}
2654        self.state.weights = {}
2655        self.state.values = copy.deepcopy(self.values)
2656        self.state.weights = copy.deepcopy(self.weights)
2657
2658        # Set the new model as the dispersion object for the
2659        #selected parameter
2660        #self.model.set_dispersion(p, disp_model)
2661        # Store a reference to the weights in the model object
2662        #so that
2663        # it's not lost when we use the model within another thread.
2664        #TODO: total hack - fix this
2665        self.state.model= self.model.clone()
2666        self.model._persistency_dict[name.split('.')[0]] = \
2667                                        [values, weights]
2668        self.state.model._persistency_dict[name.split('.')[0]] = \
2669                                        [values,weights]
2670                                       
2671
2672    def _del_array_values(self, name=None): 
2673        """
2674        Reset array dispersion
2675       
2676        :param name: name of the parameter for the dispersion to be set
2677        """
2678        # Try to delete values and weight of the names array dic if exists
2679        try:
2680            del self.values[name]
2681            del self.weights[name]
2682            # delete all other dic
2683            del self.state.values[name]
2684            del self.state.weights[name]
2685            del self.model._persistency_dict[name.split('.')[0]] 
2686            del self.state.model._persistency_dict[name.split('.')[0]]
2687        except:
2688            pass
2689                                           
2690    def _lay_out(self):
2691        """
2692        returns self.Layout
2693       
2694        :Note: Mac seems to like this better when self.
2695            Layout is called after fitting.
2696        """
2697        self._sleep4sec()
2698        self.Layout()
2699        return 
2700   
2701    def _sleep4sec(self):
2702        """
2703            sleep for 1 sec only applied on Mac
2704            Note: This 1sec helps for Mac not to crash on self.:ayout after self._draw_model
2705        """
2706        if ON_MAC == True:
2707            time.sleep(1)
2708           
2709    def _find_polyfunc_selection(self, disp_func = None):
2710        """
2711        FInd Comboox selection from disp_func
2712       
2713        :param disp_function: dispersion distr. function
2714        """
2715        # List of the poly_model name in the combobox
2716        list = ["RectangleDispersion", "ArrayDispersion", 
2717                    "LogNormalDispersion", "GaussianDispersion", 
2718                    "SchulzDispersion"]
2719
2720        # Find the selection
2721        try:
2722            selection = list.index(disp_func.__class__.__name__)
2723            return selection
2724        except:
2725             return 3
2726                           
2727    def on_reset_clicked(self,event):
2728        """
2729        On 'Reset' button  for Q range clicked
2730        """
2731        flag = True
2732        #if self.check_invalid_panel():
2733        #    return
2734        ##For 3 different cases: Data2D, Data1D, and theory
2735        if self.model == None:
2736            msg="Please select a model first..."
2737            wx.MessageBox(msg, 'Info')
2738            flag = False
2739            return
2740           
2741        elif self.data.__class__.__name__ == "Data2D":
2742            data_min= 0
2743            x= max(math.fabs(self.data.xmin), math.fabs(self.data.xmax)) 
2744            y= max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
2745            self.qmin_x = data_min
2746            self.qmax_x = math.sqrt(x*x + y*y)
2747            #self.data.mask = numpy.ones(len(self.data.data),dtype=bool)
2748            # check smearing
2749            if not self.disable_smearer.GetValue():
2750                temp_smearer= self.current_smearer
2751                ## set smearing value whether or not the data contain the smearing info
2752                if self.pinhole_smearer.GetValue():
2753                    flag = self.update_pinhole_smear()
2754                else:
2755                    flag = True
2756                   
2757        elif self.data == None:
2758            self.qmin_x = _QMIN_DEFAULT
2759            self.qmax_x = _QMAX_DEFAULT
2760            self.num_points = _NPTS_DEFAULT           
2761            self.state.npts = self.num_points
2762           
2763        elif self.data.__class__.__name__ != "Data2D":
2764            self.qmin_x = min(self.data.x)
2765            self.qmax_x = max(self.data.x)
2766            # check smearing
2767            if not self.disable_smearer.GetValue():
2768                temp_smearer= self.current_smearer
2769                ## set smearing value whether or not the data contain the smearing info
2770                if self.slit_smearer.GetValue():
2771                    flag = self.update_slit_smear()
2772                elif self.pinhole_smearer.GetValue():
2773                    flag = self.update_pinhole_smear()
2774                else:
2775                    flag = True
2776        else:
2777            flag = False
2778           
2779        if flag == False:
2780            msg= "Cannot Plot :Must enter a number!!!  "
2781            wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))
2782        else:
2783            # set relative text ctrs.
2784            self.qmin.SetValue(str(self.qmin_x))
2785            self.qmax.SetValue(str(self.qmax_x))
2786            self.set_npts2fit()
2787            # At this point, some button and variables satatus (disabled?) should be checked
2788            # such as color that should be reset to white in case that it was pink.
2789            self._onparamEnter_helper()
2790
2791        self.save_current_state()
2792        self.state.qmin = self.qmin_x
2793        self.state.qmax = self.qmax_x
2794       
2795        #reset the q range values
2796        self._reset_plotting_range(self.state)
2797        #self.compute_chisqr(smearer=self.current_smearer)
2798        #Re draw plot
2799        self._draw_model()
2800       
2801    def get_images(self):
2802        """
2803        Get the images of the plots corresponding this panel for report
2804       
2805        : return graphs: list of figures
2806        : TODO: Move to guiframe
2807        """
2808        # set list of graphs
2809        graphs = []
2810        canvases = []
2811        # call gui_manager
2812        gui_manager = self.parent.parent
2813        # loops through the panels [dic]
2814        for item1, item2 in gui_manager.plot_panels.iteritems():
2815             data_title = self.data.group_id
2816             data_name = str(self.data.name).split(" [")[0]
2817            # try to get all plots belonging to this control panel
2818             try:
2819                 title = ''
2820                 # check titles (main plot)
2821                 if hasattr(item2,"data2D"):
2822                     title = item2.data2D.title
2823                 # and data_names (model plot[2D], and residuals)
2824                 if item2.group_id == data_title or \
2825                        item2.group_id.count("res" + str(self.graph_id)) or \
2826                        item2.group_id.count(str(self.uid)) > 0:
2827                     #panel = gui_manager._mgr.GetPane(item2.window_name)
2828                     # append to the list
2829                     graphs.append(item2.figure) 
2830                     canvases.append(item2.canvas)     
2831             except:
2832                 # Not for control panels
2833                 pass
2834        # return the list of graphs
2835        return graphs, canvases
2836
2837    def on_model_help_clicked(self,event):
2838        """
2839        on 'More details' button
2840        """
2841        from help_panel import  HelpWindow
2842        from sans.models import get_data_path
2843       
2844        # Get models help model_function path
2845        path = get_data_path(media='media')
2846        model_path = os.path.join(path,"model_functions.html")
2847        if self.model == None:
2848            name = 'FuncHelp'
2849        else:
2850            name = self.formfactorbox.GetValue()
2851            #name = self.model.__class__.__name__
2852        frame = HelpWindow(None, -1,  pageToOpen=model_path)   
2853        frame.Show(True)
2854        if frame.rhelp.HasAnchor(name):
2855            frame.rhelp.ScrollToAnchor(name)
2856        else:
2857           msg= "Model does not contains an available description "
2858           msg +="Please try searching in the Help window"
2859           wx.PostEvent(self.parent.parent, StatusEvent(status = msg ))     
2860   
2861    def on_pd_help_clicked(self, event):
2862        """
2863        Button event for PD help
2864        """
2865        from help_panel import  HelpWindow
2866        import sans.models as models 
2867       
2868        # Get models help model_function path
2869        path = models.get_data_path(media='media')
2870        pd_path = os.path.join(path,"pd_help.html")
2871
2872        frame = HelpWindow(None, -1,  pageToOpen=pd_path)   
2873        frame.Show(True)
2874       
2875    def on_left_down(self, event):
2876        """
2877        Get key stroke event
2878        """
2879        # Figuring out key combo: Cmd for copy, Alt for paste
2880        if event.CmdDown() and event.ShiftDown():
2881            flag = self.get_paste()
2882        elif event.CmdDown():
2883            flag = self.get_copy()
2884        else:
2885            event.Skip()
2886            return
2887        # make event free
2888        event.Skip()
2889       
2890    def get_copy(self):
2891        """
2892        Get copy params to clipboard
2893        """
2894        content = self.get_copy_params() 
2895        flag = self.set_clipboard(content)
2896        self._copy_info(flag) 
2897        return flag
2898           
2899    def get_copy_params(self): 
2900        """
2901        Get the string copies of the param names and values in the tap
2902        """ 
2903        content = 'sansview_parameter_values:'
2904        # Do it if params exist       
2905        if  self.parameters !=[]:
2906           
2907            # go through the parameters
2908            string = self._get_copy_helper(self.parameters, 
2909                                           self.orientation_params)
2910            content += string
2911           
2912            # go through the fittables
2913            string = self._get_copy_helper(self.fittable_param, 
2914                                           self.orientation_params_disp)
2915            content += string
2916
2917            # go through the fixed params
2918            string = self._get_copy_helper(self.fixed_param, 
2919                                           self.orientation_params_disp)
2920            content += string
2921               
2922            # go through the str params
2923            string = self._get_copy_helper(self.str_parameters, 
2924                                           self.orientation_params)
2925            content += string
2926            return content
2927        else:
2928            return False
2929   
2930    def set_clipboard(self, content=None): 
2931        """
2932        Put the string to the clipboard
2933        """   
2934        if not content:
2935            return False
2936        if wx.TheClipboard.Open():
2937            wx.TheClipboard.SetData(wx.TextDataObject(str(content)))
2938            data = wx.TextDataObject()
2939            success = wx.TheClipboard.GetData(data)
2940            text = data.GetText()
2941            wx.TheClipboard.Close()
2942            return True
2943        return None
2944   
2945    def _get_copy_helper(self, param, orient_param):
2946        """
2947        Helping get value and name of the params
2948       
2949        : param param:  parameters
2950        : param orient_param = oritational params
2951        : return content: strings [list] [name,value:....]
2952        """
2953        content = ''
2954        # go through the str params
2955        for item in param: 
2956            disfunc = ''
2957            try:
2958                if item[7].__class__.__name__ == 'ComboBox':
2959                    disfunc = str(item[7].GetValue())
2960            except:
2961                pass
2962           
2963            # 2D
2964            if self.data.__class__.__name__== "Data2D":
2965                try:
2966                    check = item[0].GetValue()
2967                except:
2968                    check = None
2969                name = item[1]
2970                value = item[2].GetValue()
2971            # 1D
2972            else:
2973                ## for 1D all parameters except orientation
2974                if not item[1] in orient_param:
2975                    try:
2976                        check = item[0].GetValue()
2977                    except:
2978                        check = None
2979                    name = item[1]
2980                    value = item[2].GetValue()
2981
2982            # add to the content
2983            if disfunc != '':
2984               
2985                disfunc = ',' + disfunc
2986            # TODO: to support array func for copy/paste
2987            try:
2988                if disfunc.count('array') > 0:
2989                    disfunc += ','
2990                    for val in self.values[name]:
2991                        disfunc += ' ' + str(val)
2992                    disfunc += ','
2993                    for weight in self.weights[name]:
2994                        disfunc += ' ' + str(weight)
2995            except:
2996                pass
2997            #if disfunc.count('array') == 0:
2998            content +=  name + ',' + str(check) + ',' + value + disfunc + ':'
2999
3000        return content
3001   
3002    def get_clipboard(self):   
3003        """
3004        Get strings in the clipboard
3005        """
3006        text = "" 
3007        # Get text from the clip board       
3008        if wx.TheClipboard.Open():
3009           if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
3010               data = wx.TextDataObject()
3011               # get wx dataobject
3012               success = wx.TheClipboard.GetData(data)
3013               # get text
3014               text = data.GetText()
3015           # close clipboard
3016           wx.TheClipboard.Close()
3017           
3018        return text
3019   
3020    def get_paste(self):
3021        """
3022        Paste params from the clipboard
3023        """
3024        text = self.get_clipboard()
3025        flag = self.get_paste_params(text)
3026        self._copy_info(flag)
3027        return flag
3028       
3029    def get_paste_params(self, text=''): 
3030        """
3031        Get the string copies of the param names and values in the tap
3032        """ 
3033        context = {}   
3034        # put the text into dictionary   
3035        lines = text.split(':')
3036        if lines[0] != 'sansview_parameter_values':
3037            self._copy_info(False)
3038            return False
3039        for line in lines[1:-1]:
3040            if len(line) != 0:
3041                item =line.split(',')
3042                check = item[1]
3043                name = item[0]
3044                value = item[2]
3045                # Transfer the text to content[dictionary]
3046                context[name] = [check, value]
3047            # ToDo: PlugIn this poly disp function for pasting
3048            try:
3049                poly_func = item[3]
3050                context[name].append(poly_func)
3051                try:
3052                    # take the vals and weights for  array
3053                    array_values = item[4].split(' ')
3054                    array_weights = item[5].split(' ')
3055                    val = [float(a_val) for a_val in array_values[1:]]
3056                    weit = [float(a_weit) for a_weit in array_weights[1:]]
3057                   
3058                    context[name].append(val)
3059                    context[name].append(weit)
3060                except:
3061                    raise
3062            except:
3063                poly_func = ''
3064                context[name].append(poly_func)
3065
3066        # Do it if params exist       
3067        if  self.parameters != []:
3068            # go through the parameters 
3069            self._get_paste_helper(self.parameters, 
3070                                   self.orientation_params, context)
3071
3072            # go through the fittables
3073            self._get_paste_helper(self.fittable_param, 
3074                                   self.orientation_params_disp, 
3075                                   context)
3076
3077            # go through the fixed params
3078            self._get_paste_helper(self.fixed_param, 
3079                                   self.orientation_params_disp, context)
3080           
3081            # go through the str params
3082            self._get_paste_helper(self.str_parameters, 
3083                                   self.orientation_params, context)
3084               
3085            return True
3086        return None
3087   
3088    def _get_paste_helper(self, param, orient_param, content):
3089        """
3090        Helping set values of the params
3091       
3092        : param param:  parameters
3093        : param orient_param: oritational params
3094        : param content: dictionary [ name, value: name1.value1,...]
3095        """
3096        # go through the str params
3097        for item in param: 
3098            # 2D
3099            if self.data.__class__.__name__== "Data2D":
3100                name = item[1]
3101                if name in content.keys():
3102                    check = content[name][0]
3103                    pd = content[name][1]
3104                    if name.count('.') > 0:
3105                        try:
3106                            float(pd)
3107                        except:
3108                            #continue
3109                            if not pd and pd != '':
3110                                continue
3111                    item[2].SetValue(str(pd))
3112                    if item in self.fixed_param and pd == '':
3113                        # Only array func has pd == '' case.
3114                        item[2].Enable(False)
3115                    if item[2].__class__.__name__ == "ComboBox":
3116                        if self.model.fun_list.has_key(content[name][1]):
3117                            fun_val = self.model.fun_list[content[name][1]]
3118                            self.model.setParam(name,fun_val)
3119                   
3120                    value = content[name][1:]
3121                    self._paste_poly_help(item, value)
3122                    if check == 'True':
3123                        is_true = True
3124                    elif check == 'False':
3125                        is_true = False
3126                    else:
3127                        is_true = None
3128                    if is_true != None:
3129                        item[0].SetValue(is_true)
3130            # 1D
3131            else:
3132                ## for 1D all parameters except orientation
3133                if not item[1] in orient_param:
3134                    name = item[1]
3135                    if name in content.keys():
3136                        check = content[name][0]
3137                        # Avoid changing combox content which needs special care
3138                        value = content[name][1:]
3139                        pd = value[0]
3140                        if name.count('.') > 0:
3141                            try:
3142                                pd = float(pd)
3143                            except:
3144                                #continue
3145                                if not pd and pd != '':
3146                                    continue
3147                        item[2].SetValue(str(pd))
3148                        if item in self.fixed_param and pd == '':
3149                            # Only array func has pd == '' case.
3150                            item[2].Enable(False)
3151                        if item[2].__class__.__name__ == "ComboBox":
3152                            if self.model.fun_list.has_key(value[0]):
3153                                fun_val = self.model.fun_list[value[0]]
3154                                self.model.setParam(name,fun_val)
3155                                # save state
3156                                #self._copy_parameters_state(self.str_parameters,
3157                                #    self.state.str_parameters)
3158                        self._paste_poly_help(item, value)
3159                        if check == 'True':
3160                            is_true = True
3161                        elif check == 'False':
3162                            is_true = False
3163                        else:
3164                            is_true = None
3165                        if is_true != None:
3166                            item[0].SetValue(is_true)
3167                       
3168    def _paste_poly_help(self, item, value):
3169        """
3170        Helps get paste for poly function
3171       
3172        :param item: Gui param items
3173        :param value: the values for parameter ctrols
3174        """
3175        is_array = False
3176        if len(value[1]) > 0:
3177            # Only for dispersion func.s
3178            try:
3179                item[7].SetValue(value[1])
3180                selection = item[7].GetCurrentSelection()
3181                name = item[7].Name
3182                param_name = name.split('.')[0]
3183                disp_name = item[7].GetValue()
3184                dispersity= item[7].GetClientData(selection)
3185                disp_model = dispersity()
3186                # Only for array disp
3187                try:
3188                    pd_vals = numpy.array(value[2])
3189                    pd_weights = numpy.array(value[3])
3190                    if len(pd_vals) > 0 and len(pd_vals) > 0:
3191                        if len(pd_vals) == len(pd_weights):
3192                            self._set_disp_array_cb(item=item)
3193                            self._set_array_disp_model(name=name, 
3194                                                       disp=disp_model,
3195                                                       values=pd_vals, 
3196                                                       weights=pd_weights)
3197                            is_array = True
3198                except:
3199                    pass 
3200                if not is_array:
3201                    self._disp_obj_dict[name] = disp_model
3202                    self.model.set_dispersion(name, 
3203                                              disp_model)
3204                    self.state._disp_obj_dict[name] = \
3205                                              disp_model
3206                    self.model.set_dispersion(param_name, disp_model)
3207                    self.state.values = self.values
3208                    self.state.weights = self.weights   
3209                    self.model._persistency_dict[param_name] = \
3210                                            [state.values, state.weights]
3211                         
3212            except:
3213                pass 
3214   
3215    def _set_disp_array_cb(self, item):
3216        """
3217        Set cb for array disp
3218        """
3219        item[0].SetValue(False)
3220        item[0].Enable(False)
3221        item[2].Enable(False)
3222        item[3].Show(False)
3223        item[4].Show(False)
3224        item[5].SetValue('')
3225        item[5].Enable(False)
3226        item[6].SetValue('')
3227        item[6].Enable(False)
3228
3229       
Note: See TracBrowser for help on using the repository browser.