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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since fa81e94 was fa81e94, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

Initial commit of the P(r) inversion perspective.
Code merged from Jeff Krzywon's ESS_GUI_Pr branch.
Also, minor 2to3 mods to sascalc/sasgui to enble error free setup.

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