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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249unittest-saveload
Last change on this file since a4a1ac9 was a4a1ac9, checked in by GitHub <noreply@…>, 6 years ago

Merge pull request #172 from SasView?/ticket-1166

Fix for report generation issue. Refs #1166.

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