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

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 4a4164c was 33477fd, checked in by Jae Cho <jhjcho@…>, 13 years ago

fixed custom smear without data

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