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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249unittest-saveload
Last change on this file since ec4b19c was 0cf4f84, checked in by krzywon, 6 years ago

Create base report image handler for all images and modify fitting to perspective to use the image handler.

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