source: sasview/src/sas/sasgui/perspectives/fitting/basepage.py @ 8bd5840

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.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 8bd5840 was 8bd5840, checked in by krzywon, 7 years ago

Incorporate name and parameter name conversions and fix bug involving on loading v3.x fits.

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