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

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 f668101 was f668101, checked in by jhbakker, 7 years ago

Merge branch 'master' into Jurtest

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