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

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 2ee5c61 was 25c0def, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Fixing code style problems and bugs

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