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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since ee6ab94 was ee6ab94, checked in by Gonzalez, Miguel <gonzalez@…>, 7 years ago

Fixing ticket1007 and hopefully other similar sources of error

  • Property mode set to 100644
File size: 147.9 KB
Line 
1"""
2Base Page for fitting
3"""
4from __future__ import print_function
5
6import sys
7import os
8import time
9import copy
10import math
11import json
12import logging
13import traceback
14from Queue import Queue
15from threading import Thread
16from collections import defaultdict
17
18import numpy as np
19
20import wx
21from wx.lib.scrolledpanel import ScrolledPanel
22
23from sasmodels.sasview_model import MultiplicationModel
24from sasmodels.weights import MODELS as POLYDISPERSITY_MODELS
25from sasmodels.weights import GaussianDispersion
26
27from sas.sascalc.dataloader.data_info import Detector
28from sas.sascalc.dataloader.data_info import Source
29from sas.sascalc.fit.pagestate import PageState
30from sas.sascalc.fit.models import PLUGIN_NAME_BASE
31
32from sas.sasgui.guiframe.panel_base import PanelBase
33from sas.sasgui.guiframe.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 = self._ids.next()
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 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.iteritems():
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.iteritems():
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.iteritems():
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 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.iteritems():
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 = unicode(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 = unicode(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.iteritems():
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.iteritems():
1418            self.number_saved_state += 1
1419            # Add item in the context menu
1420            wx_id = ids.next()
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        is_modified = False
1526
1527        # wx.PostEvent(self._manager.parent, StatusEvent(status=" \
1528        # updating ... ",type="update"))
1529
1530        # So make sure that update param values on_Fit.
1531        # self._undo.Enable(True)
1532        if self.model is not None:
1533            if self.Npts_total.GetValue() != self.Npts_fit.GetValue():
1534                if not self.data.is_data:
1535                    self._manager.page_finder[self.uid].set_fit_data(
1536                        data=[self.data])
1537            # Check the values
1538            is_modified = (self._check_value_enter(self.fittable_param)
1539                           or self._check_value_enter(self.fixed_param)
1540                           or self._check_value_enter(self.parameters))
1541
1542            # If qmin and qmax have been modified, update qmin and qmax and
1543            # Here we should check whether the boundaries have been modified.
1544            # If qmin and qmax have been modified, update qmin and qmax and
1545            # set the is_modified flag to True
1546            self.fitrange = self._validate_qrange(self.qmin, self.qmax)
1547            if self.fitrange:
1548                tempmin = float(self.qmin.GetValue())
1549                if tempmin != self.qmin_x:
1550                    self.qmin_x = tempmin
1551                tempmax = float(self.qmax.GetValue())
1552                if tempmax != self.qmax_x:
1553                    self.qmax_x = tempmax
1554                if tempmax == tempmin:
1555                    flag = False
1556                temp_smearer = None
1557                if not self.disable_smearer.GetValue():
1558                    temp_smearer = self.current_smearer
1559                    if self.slit_smearer.GetValue():
1560                        flag = self.update_slit_smear()
1561                    elif self.pinhole_smearer.GetValue():
1562                        flag = self.update_pinhole_smear()
1563                    else:
1564                        enable_smearer = not self.disable_smearer.GetValue()
1565                        self._manager.set_smearer(smearer=temp_smearer,
1566                                                  uid=self.uid,
1567                                                  fid=self.data.id,
1568                                                  qmin=float(self.qmin_x),
1569                                                  qmax=float(self.qmax_x),
1570                                                  enable_smearer=enable_smearer,
1571                                                  draw=False)
1572                elif not self._is_2D():
1573                    enable_smearer = not self.disable_smearer.GetValue()
1574                    self._manager.set_smearer(smearer=temp_smearer,
1575                                              qmin=float(self.qmin_x),
1576                                              uid=self.uid,
1577                                              fid=self.data.id,
1578                                              qmax=float(self.qmax_x),
1579                                              enable_smearer=enable_smearer,
1580                                              draw=False)
1581                    if self.data is not None:
1582                        index_data = ((self.qmin_x <= self.data.x) &
1583                                      (self.data.x <= self.qmax_x))
1584                        val = str(len(self.data.x[index_data]))
1585                        self.Npts_fit.SetValue(val)
1586                    else:
1587                        # No data in the panel
1588                        try:
1589                            self.npts_x = float(self.Npts_total.GetValue())
1590                        except Exception:
1591                            flag = False
1592                            return flag
1593                    flag = True
1594                if self._is_2D():
1595                    # only 2D case set mask
1596                    flag = self._validate_Npts()
1597                    if not flag:
1598                        return flag
1599            else:
1600                flag = False
1601        else:
1602            flag = False
1603
1604        # For invalid q range, disable the mask editor and fit button, vs.
1605        if not self.fitrange:
1606            if self._is_2D():
1607                self.btEditMask.Disable()
1608        else:
1609            if self._is_2D() and self.data.is_data and not self.batch_on:
1610                self.btEditMask.Enable(True)
1611
1612        if not flag:
1613            msg = "Cannot Plot or Fit :Must select a "
1614            msg += " model or Fitting range is not valid!!!  "
1615            wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
1616
1617        try:
1618            self.save_current_state()
1619        except Exception:
1620            logger.error(traceback.format_exc())
1621
1622        return flag, is_modified
1623
1624    def _reset_parameters_state(self, listtorestore, statelist):
1625        """
1626        Reset the parameters at the given state
1627        """
1628        if len(statelist) == 0 or len(listtorestore) == 0:
1629            return
1630
1631        for item_page in listtorestore:
1632            for param in statelist:
1633                if param[1] == item_page[1]:
1634                    item_page_info = param
1635                    if (item_page_info[1] == "theta" or item_page_info[1] ==
1636                            "phi") and not self._is_2D():
1637                        break
1638                    # change the state of the check box for simple parameters
1639                    if item_page[0] is not None:
1640                        item_page[0].SetValue(item_page_info[0])
1641                    if item_page[2] is not None:
1642                        item_page[2].SetValue(item_page_info[2])
1643                        if item_page[2].__class__.__name__ == "ComboBox":
1644                            if item_page_info[2] in self.model.fun_list:
1645                                # to fix: fun_list is not a dictionary, but a tuple
1646                                # so the following line (commented) will fail
1647                                # fun_val = self.model.fun_list[item_page_info[2]]
1648                                # I guess the following should work, but
1649                                # could not test as I don't know when this
1650                                # part is used by SasView.
1651                                fun_val = self.model.fun_list.index(item_page_info[2])
1652                                self.model.setParam(item_page_info[1], fun_val)
1653                    if item_page[3] is not None:
1654                        # show or hide text +/-
1655                        if item_page_info[2]:
1656                            item_page[3].Show(True)
1657                        else:
1658                            item_page[3].Hide()
1659                    if item_page[4] is not None:
1660                        # show of hide the text crtl for fitting error
1661                        if item_page_info[4][0]:
1662                            item_page[4].Show(True)
1663                            item_page[4].SetValue(str(item_page_info[4][1]))
1664                        else:
1665                            item_page[3].Hide()
1666                    if item_page[5] is not None:
1667                        # show of hide the text crtl for fitting error
1668                        item_page[5].Show(True)
1669                        item_page[5].SetValue(str(item_page_info[5][1]))
1670                    if item_page[6] is not None:
1671                        # show of hide the text crtl for fitting error
1672                        item_page[6].Show(True)
1673                        item_page[6].SetValue(str(item_page_info[6][1]))
1674                    break
1675
1676    def _reset_strparam_state(self, listtorestore, statelist):
1677        """
1678        Reset the string parameters at the given state
1679        """
1680        if len(statelist) == 0:
1681            return
1682
1683        listtorestore = copy.deepcopy(statelist)
1684
1685        for item_page, item_page_info in zip(listtorestore, statelist):
1686            # change the state of the check box for simple parameters
1687            if item_page[0] is not None:
1688                item_page[0].SetValue(format_number(item_page_info[0], True))
1689
1690            if item_page[2] is not None:
1691                param_name = item_page_info[1]
1692                value = item_page_info[2]
1693                selection = value
1694                if value in self.model.fun_list:
1695                    # to fix: fun_list is not a dictionary, so
1696                    # I commented the following original line
1697                    #selection = self.model.fun_list[value]
1698                    # and replaced by this.
1699                    # I think this should work, but could not test it.
1700                    selection = self.model.fun_list.index(value)
1701                item_page[2].SetValue(selection)
1702                self.model.setParam(param_name, selection)
1703
1704    def _copy_parameters_state(self, listtocopy, statelist):
1705        """
1706        copy the state of button
1707
1708        :param listtocopy: the list of check button to copy
1709        :param statelist: list of state object to store the current state
1710
1711        """
1712        if len(listtocopy) == 0:
1713            return
1714
1715        for item in listtocopy:
1716
1717            checkbox_state = None
1718            if item[0] is not None:
1719                checkbox_state = item[0].GetValue()
1720            parameter_name = item[1]
1721            parameter_value = None
1722            if item[2] is not None:
1723                parameter_value = item[2].GetValue()
1724            static_text = None
1725            if item[3] is not None:
1726                static_text = item[3].IsShown()
1727            error_value = None
1728            error_state = None
1729            if item[4] is not None:
1730                error_value = item[4].GetValue()
1731                error_state = item[4].IsShown()
1732
1733            min_value = None
1734            min_state = None
1735            if item[5] is not None:
1736                min_value = item[5].GetValue()
1737                min_state = item[5].IsShown()
1738
1739            max_value = None
1740            max_state = None
1741            if item[6] is not None:
1742                max_value = item[6].GetValue()
1743                max_state = item[6].IsShown()
1744            unit = None
1745            if item[7] is not None:
1746                unit = item[7].GetLabel()
1747
1748            statelist.append([checkbox_state, parameter_name, parameter_value,
1749                              static_text, [error_state, error_value],
1750                              [min_state, min_value],
1751                              [max_state, max_value], unit])
1752
1753    def _draw_model(self, update_chisqr=True, source='model'):
1754        """
1755        Method to draw or refresh a plotted model.
1756        The method will use the data member from the model page
1757        to build a call to the fitting perspective manager.
1758
1759        :param chisqr: update chisqr value [bool]
1760        """
1761        self.threaded_draw_queue.put([copy.copy(update_chisqr), copy.copy(source)])
1762
1763    def _threaded_draw_worker(self, threaded_draw_queue):
1764        while True:
1765            # sit and wait for the next task
1766            next_task = threaded_draw_queue.get()
1767
1768            # sleep for 1/10th second in case some other tasks accumulate
1769            time.sleep(0.1)
1770
1771            # skip all intermediate tasks
1772            while self.threaded_draw_queue.qsize() > 0:
1773                self.threaded_draw_queue.task_done()
1774                next_task = self.threaded_draw_queue.get()
1775
1776            # and finally, do the task
1777            self._draw_model_after(*next_task)
1778            threaded_draw_queue.task_done()
1779
1780    def _draw_model_after(self, update_chisqr=True, source='model'):
1781        """
1782        Method to draw or refresh a plotted model.
1783        The method will use the data member from the model page
1784        to build a call to the fitting perspective manager.
1785
1786        :param chisqr: update chisqr value [bool]
1787        """
1788        # if self.check_invalid_panel():
1789        #    return
1790        if self.model is not None:
1791            temp_smear = None
1792            if hasattr(self, "enable_smearer"):
1793                if not self.disable_smearer.GetValue():
1794                    temp_smear = self.current_smearer
1795            # compute weight for the current data
1796            flag = self.get_weight_flag()
1797            weight = get_weight(data=self.data, is2d=self._is_2D(), flag=flag)
1798            toggle_mode_on = self.model_view.IsEnabled()
1799            is_2d = self._is_2D()
1800
1801            self._manager.draw_model(self.model,
1802                                     data=self.data,
1803                                     smearer=temp_smear,
1804                                     qmin=float(self.qmin_x),
1805                                     qmax=float(self.qmax_x),
1806                                     page_id=self.uid,
1807                                     toggle_mode_on=toggle_mode_on,
1808                                     state=self.state,
1809                                     enable2D=is_2d,
1810                                     update_chisqr=update_chisqr,
1811                                     source='model',
1812                                     weight=weight)
1813
1814    def _on_show_sld(self, event=None):
1815        """
1816        Plot SLD profile
1817        """
1818        # get profile data
1819        x, y = self.model.getProfile()
1820
1821        from sas.sasgui.plottools import Data1D as pf_data1d
1822        from sas.sasgui.guiframe.local_perspectives.plotting.profile_dialog \
1823            import SLDPanel
1824        sld_data = pf_data1d(x, y)
1825        sld_data.name = 'SLD'
1826        sld_data.axes = self.sld_axes
1827        self.panel = SLDPanel(self, data=sld_data, axes=self.sld_axes,
1828                              id=wx.ID_ANY)
1829        self.panel.ShowModal()
1830
1831    def _set_multfactor_combobox(self, multiplicity=10):
1832        """
1833        Set comboBox for multitfactor of CoreMultiShellModel
1834        :param multiplicit: no. of multi-functionality
1835        """
1836        # build content of the combobox
1837        for idx in range(0, multiplicity):
1838            self.multifactorbox.Append(str(idx), int(idx))
1839        self._hide_multfactor_combobox()
1840
1841    def _show_multfactor_combobox(self):
1842        """
1843        Show the comboBox of muitfactor of CoreMultiShellModel
1844        """
1845        if not self.mutifactor_text.IsShown():
1846            self.mutifactor_text.Show(True)
1847            self.mutifactor_text1.Show(True)
1848        if not self.multifactorbox.IsShown():
1849            self.multifactorbox.Show(True)
1850
1851    def _hide_multfactor_combobox(self):
1852        """
1853        Hide the comboBox of muitfactor of CoreMultiShellModel
1854        """
1855        if self.mutifactor_text.IsShown():
1856            self.mutifactor_text.Hide()
1857            self.mutifactor_text1.Hide()
1858        if self.multifactorbox.IsShown():
1859            self.multifactorbox.Hide()
1860
1861    def formfactor_combo_init(self):
1862        """
1863        First time calls _show_combox_helper
1864        """
1865        self._show_combox(None)
1866
1867    def _show_combox_helper(self):
1868        """
1869        Fill panel's combo box according to the type of model selected
1870        """
1871
1872        mod_cat = self.categorybox.GetStringSelection()
1873        self.structurebox.SetSelection(0)
1874        self.structurebox.Disable()
1875        self.formfactorbox.Clear()
1876        if mod_cat is None:
1877            return
1878        m_list = []
1879        try:
1880            if mod_cat == CUSTOM_MODEL:
1881                for model in self.model_list_box[mod_cat]:
1882                    m_list.append(self.model_dictionary[model.name])
1883            else:
1884                cat_dic = self.master_category_dict[mod_cat]
1885                for model, enabled in cat_dic:
1886                    if enabled:
1887                        m_list.append(self.model_dictionary[model])
1888        except Exception:
1889            msg = traceback.format_exc()
1890            wx.PostEvent(self._manager.parent,
1891                         StatusEvent(status=msg, info="error"))
1892        self._populate_box(self.formfactorbox, m_list)
1893
1894    def _on_modify_cat(self, event=None):
1895        """
1896        Called when category manager is opened
1897        """
1898        self._manager.parent.on_category_panel(event)
1899
1900    def _show_combox(self, event=None):
1901        """
1902        Show combox box associate with type of model selected
1903        """
1904        self.Show(False)
1905        self._show_combox_helper()
1906        self._on_select_model(event=None)
1907        self.Show(True)
1908        self._save_typeOfmodel()
1909        self.sizer4_4.Layout()
1910        self.sizer4.Layout()
1911        self.Layout()
1912        self.Refresh()
1913
1914    def _populate_box(self, combobox, list):
1915        """
1916        fill combox box with dict item
1917
1918        :param list: contains item to fill the combox
1919            item must model class
1920        """
1921        mlist = []
1922        for models in list:
1923            if models.name != "NoStructure":
1924                mlist.append((models.name, models))
1925        # Sort the models
1926        mlist_sorted = sorted(mlist)
1927        for item in mlist_sorted:
1928            combobox.Append(item[0], item[1])
1929        return 0
1930
1931    def _onQrangeEnter(self, event):
1932        """
1933        Check validity of value enter in the Q range field
1934
1935        """
1936        tcrtl = event.GetEventObject()
1937        # Clear msg if previously shown.
1938        msg = ""
1939        wx.PostEvent(self.parent, StatusEvent(status=msg))
1940        # Flag to register when a parameter has changed.
1941        if tcrtl.GetValue().lstrip().rstrip() != "":
1942            try:
1943                float(tcrtl.GetValue())
1944                tcrtl.SetBackgroundColour(wx.WHITE)
1945                # If qmin and qmax have been modified, update qmin and qmax
1946                if self._validate_qrange(self.qmin, self.qmax):
1947                    tempmin = float(self.qmin.GetValue())
1948                    if tempmin != self.qmin_x:
1949                        self.qmin_x = tempmin
1950                    tempmax = float(self.qmax.GetValue())
1951                    if tempmax != self.qmax_x:
1952                        self.qmax_x = tempmax
1953                else:
1954                    tcrtl.SetBackgroundColour("pink")
1955                    msg = "Model Error: wrong value entered: %s" % \
1956                          sys.exc_info()[1]
1957                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1958                    return
1959            except Exception:
1960                tcrtl.SetBackgroundColour("pink")
1961                msg = "Model Error: wrong value entered: %s" % sys.exc_info()[1]
1962                wx.PostEvent(self.parent, StatusEvent(status=msg))
1963                return
1964            # Check if # of points for theory model are valid(>0).
1965            if self.npts is not None:
1966                if check_float(self.npts):
1967                    temp_npts = float(self.npts.GetValue())
1968                    if temp_npts != self.num_points:
1969                        self.num_points = temp_npts
1970                else:
1971                    msg = "Cannot plot: No points in Q range!!!  "
1972                    wx.PostEvent(self.parent, StatusEvent(status=msg))
1973        else:
1974            tcrtl.SetBackgroundColour("pink")
1975            msg = "Model Error: wrong value entered!!!"
1976            wx.PostEvent(self.parent, StatusEvent(status=msg))
1977        self.save_current_state()
1978        event = PageInfoEvent(page=self)
1979        wx.PostEvent(self.parent, event)
1980        self.state_change = False
1981        # Draw the model for a different range
1982        if not self.data.is_data:
1983            self.create_default_data()
1984        self._draw_model()
1985
1986    def _theory_qrange_enter(self, event):
1987        """
1988        Check validity of value enter in the Q range field
1989        """
1990
1991        tcrtl = event.GetEventObject()
1992        # Clear msg if previously shown.
1993        msg = ""
1994        wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
1995        # Flag to register when a parameter has changed.
1996        is_modified = False
1997        if tcrtl.GetValue().lstrip().rstrip() != "":
1998            try:
1999                value = float(tcrtl.GetValue())
2000                tcrtl.SetBackgroundColour(wx.WHITE)
2001
2002                # If qmin and qmax have been modified, update qmin and qmax
2003                if self._validate_qrange(self.theory_qmin, self.theory_qmax):
2004                    tempmin = float(self.theory_qmin.GetValue())
2005                    if tempmin != self.theory_qmin_x:
2006                        self.theory_qmin_x = tempmin
2007                    tempmax = float(self.theory_qmax.GetValue())
2008                    if tempmax != self.qmax_x:
2009                        self.theory_qmax_x = tempmax
2010                else:
2011                    tcrtl.SetBackgroundColour("pink")
2012                    msg = "Model Error: wrong value entered: %s" % \
2013                          sys.exc_info()[1]
2014                    wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2015                    return
2016            except Exception:
2017                tcrtl.SetBackgroundColour("pink")
2018                msg = "Model Error: wrong value entered: %s" % sys.exc_info()[1]
2019                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2020                return
2021            # Check if # of points for theory model are valid(>0).
2022            if self.Npts_total.IsEditable():
2023                if check_float(self.Npts_total):
2024                    temp_npts = float(self.Npts_total.GetValue())
2025                    if temp_npts != self.num_points:
2026                        self.num_points = temp_npts
2027                        is_modified = True
2028                else:
2029                    msg = "Cannot Plot: No points in Q range!!!  "
2030                    wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2031        else:
2032            tcrtl.SetBackgroundColour("pink")
2033            msg = "Model Error: wrong value entered!!!"
2034            wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2035        self.save_current_state()
2036        event = PageInfoEvent(page=self)
2037        wx.PostEvent(self.parent, event)
2038        self.state_change = False
2039        # Draw the model for a different range
2040        self.create_default_data()
2041        self._draw_model()
2042
2043    def _on_select_model_helper(self):
2044        """
2045        call back for model selection
2046        """
2047        # reset dictionary containing reference to dispersion
2048        self._disp_obj_dict = {}
2049        self.disp_cb_dict = {}
2050        self.temp_multi_functional = False
2051        f_id = self.formfactorbox.GetCurrentSelection()
2052        # For MAC
2053        form_factor = None
2054        if f_id >= 0:
2055            form_factor = self.formfactorbox.GetClientData(f_id)
2056
2057        if form_factor is None or \
2058            not hasattr(form_factor, 'is_form_factor') or \
2059                not form_factor.is_form_factor:
2060            self.structurebox.Hide()
2061            self.text2.Hide()
2062            self.structurebox.Disable()
2063            self.structurebox.SetSelection(0)
2064            self.text2.Disable()
2065        else:
2066            self.structurebox.Show()
2067            self.text2.Show()
2068            self.structurebox.Enable()
2069            self.text2.Enable()
2070
2071        if form_factor is not None:
2072            # set multifactor for Mutifunctional models
2073            if form_factor.is_multiplicity_model:
2074                m_id = self.multifactorbox.GetCurrentSelection()
2075                multiplicity = form_factor.multiplicity_info[0]
2076                self.multifactorbox.Clear()
2077                self._set_multfactor_combobox(multiplicity)
2078                self._show_multfactor_combobox()
2079                # ToDo: this info should be called directly from the model
2080                text = form_factor.multiplicity_info[1]  # 'No. of Shells: '
2081
2082                self.mutifactor_text.SetLabel(text)
2083                if m_id > multiplicity - 1:
2084                    # default value
2085                    m_id = 1
2086
2087                self.multi_factor = self.multifactorbox.GetClientData(m_id)
2088                if self.multi_factor is None:
2089                    self.multi_factor = 0
2090                self.multifactorbox.SetSelection(m_id)
2091                # Check len of the text1 and max_multiplicity
2092                text = ''
2093                if form_factor.multiplicity_info[0] == \
2094                        len(form_factor.multiplicity_info[2]):
2095                    text = form_factor.multiplicity_info[2][self.multi_factor]
2096                self.mutifactor_text1.SetLabel(text)
2097                # Check if model has  get sld profile.
2098                if len(form_factor.multiplicity_info[3]) > 0:
2099                    self.sld_axes = form_factor.multiplicity_info[3]
2100                    self.show_sld_button.Show(True)
2101                else:
2102                    self.sld_axes = ""
2103            else:
2104                self._hide_multfactor_combobox()
2105                self.show_sld_button.Hide()
2106                self.multi_factor = None
2107        else:
2108            self._hide_multfactor_combobox()
2109            self.show_sld_button.Hide()
2110            self.multi_factor = None
2111
2112        s_id = self.structurebox.GetCurrentSelection()
2113        struct_factor = self.structurebox.GetClientData(s_id)
2114
2115        if struct_factor is not None:
2116            self.model = MultiplicationModel(form_factor(self.multi_factor),
2117                                             struct_factor())
2118            # multifunctional form factor
2119            if len(form_factor.non_fittable) > 0:
2120                self.temp_multi_functional = True
2121        elif form_factor is not None:
2122            if self.multi_factor is not None:
2123                self.model = form_factor(self.multi_factor)
2124            else:
2125                # old style plugin models do not accept a multiplicity argument
2126                self.model = form_factor()
2127        else:
2128            self.model = None
2129            return
2130
2131        # check if model has magnetic parameters
2132        if len(self.model.magnetic_params) > 0:
2133            self._has_magnetic = True
2134        else:
2135            self._has_magnetic = False
2136        # post state to fit panel
2137        self.state.parameters = []
2138        self.state.model = self.model
2139        self.state.qmin = self.qmin_x
2140        self.state.multi_factor = self.multi_factor
2141        self.disp_list = self.model.getDispParamList()
2142        self.state.disp_list = self.disp_list
2143        self.on_set_focus(None)
2144        self.Layout()
2145
2146    def _validate_qrange(self, qmin_ctrl, qmax_ctrl):
2147        """
2148        Verify that the Q range controls have valid values
2149        and that Qmin < Qmax.
2150
2151        :param qmin_ctrl: text control for Qmin
2152        :param qmax_ctrl: text control for Qmax
2153
2154        :return: True is the Q range is value, False otherwise
2155
2156        """
2157        qmin_validity = check_float(qmin_ctrl)
2158        qmax_validity = check_float(qmax_ctrl)
2159        if not (qmin_validity and qmax_validity):
2160            return False
2161        else:
2162            qmin = float(qmin_ctrl.GetValue())
2163            qmax = float(qmax_ctrl.GetValue())
2164            if qmin < qmax:
2165                # Make sure to set both colours white.
2166                qmin_ctrl.SetBackgroundColour(wx.WHITE)
2167                qmin_ctrl.Refresh()
2168                qmax_ctrl.SetBackgroundColour(wx.WHITE)
2169                qmax_ctrl.Refresh()
2170            else:
2171                qmin_ctrl.SetBackgroundColour("pink")
2172                qmin_ctrl.Refresh()
2173                qmax_ctrl.SetBackgroundColour("pink")
2174                qmax_ctrl.Refresh()
2175                msg = "Invalid Q range: Q min must be smaller than Q max"
2176                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2177                return False
2178        return True
2179
2180    def _validate_Npts(self):
2181        """
2182        Validate the number of points for fitting is more than 10 points.
2183        If valid, setvalues Npts_fit otherwise post msg.
2184        """
2185        # default flag
2186        flag = True
2187        # Theory
2188        if self.data is None and self.enable2D:
2189            return flag
2190        for data in self.data_list:
2191            # q value from qx and qy
2192            radius = np.sqrt(data.qx_data * data.qx_data +
2193                             data.qy_data * data.qy_data)
2194            # get unmasked index
2195            index_data = (float(self.qmin.GetValue()) <= radius) & \
2196                         (radius <= float(self.qmax.GetValue()))
2197            index_data = (index_data) & (data.mask)
2198            index_data = (index_data) & (np.isfinite(data.data))
2199
2200            if len(index_data[index_data]) < 10:
2201                # change the color pink.
2202                self.qmin.SetBackgroundColour("pink")
2203                self.qmin.Refresh()
2204                self.qmax.SetBackgroundColour("pink")
2205                self.qmax.Refresh()
2206                msg = "Data Error: "
2207                msg += "Too few points in %s." % data.name
2208                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2209                self.fitrange = False
2210                flag = False
2211            else:
2212                self.Npts_fit.SetValue(str(len(index_data[index_data])))
2213                self.fitrange = True
2214
2215        return flag
2216
2217    def _validate_Npts_1D(self):
2218        """
2219        Validate the number of points for fitting is more than 5 points.
2220        If valid, setvalues Npts_fit otherwise post msg.
2221        """
2222        # default flag
2223        flag = True
2224        # Theory
2225        if self.data is None:
2226            return flag
2227        for data in self.data_list:
2228            # q value from qx and qy
2229            radius = data.x
2230            # get unmasked index
2231            index_data = (float(self.qmin.GetValue()) <= radius) & \
2232                         (radius <= float(self.qmax.GetValue()))
2233            index_data = (index_data) & (np.isfinite(data.y))
2234
2235            if len(index_data[index_data]) < 5:
2236                # change the color pink.
2237                self.qmin.SetBackgroundColour("pink")
2238                self.qmin.Refresh()
2239                self.qmax.SetBackgroundColour("pink")
2240                self.qmax.Refresh()
2241                msg = "Data Error: "
2242                msg += "Too few points in %s." % data.name
2243                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2244                self.fitrange = False
2245                flag = False
2246            else:
2247                self.Npts_fit.SetValue(str(len(index_data[index_data])))
2248                self.fitrange = True
2249
2250        return flag
2251
2252    def _check_value_enter(self, list):
2253        """
2254        :param list: model parameter and panel info
2255        :Note: each item of the list should be as follow:
2256            item=[check button state, parameter's name,
2257                paramater's value, string="+/-",
2258                parameter's error of fit,
2259                parameter's minimum value,
2260                parameter's maximum value ,
2261                parameter's units]
2262
2263        Returns True if the model parameters have changed.
2264        """
2265        is_modified = False
2266        for item in list:
2267            # skip angle parameters for 1D
2268            if not self.enable2D and item in self.orientation_params:
2269                continue
2270
2271            value_ctrl = item[2]
2272            if not value_ctrl.IsEnabled():
2273                # ArrayDispersion disables PD, Min, Max, Npts, Nsigs
2274                continue
2275
2276            name = item[1]
2277            value_str = value_ctrl.GetValue().strip()
2278            if name.endswith(".npts"):
2279                validity = check_int(value_ctrl)
2280                if not validity:
2281                    continue
2282                value = int(value_str)
2283
2284            elif name.endswith(".nsigmas"):
2285                validity = check_float(value_ctrl)
2286                if not validity:
2287                    continue
2288                value = float(value_str)
2289
2290            else:  # value or polydispersity
2291
2292                # Check that min, max and value are floats
2293                min_ctrl, max_ctrl = item[5], item[6]
2294                min_str = min_ctrl.GetValue().strip()
2295                max_str = max_ctrl.GetValue().strip()
2296                validity = check_float(value_ctrl)
2297                if min_str != "":
2298                    validity = validity and check_float(min_ctrl)
2299                if max_str != "":
2300                    validity = validity and check_float(max_ctrl)
2301                if not validity:
2302                    continue
2303
2304                # Check that min is less than max
2305                low = -np.inf if min_str == "" else float(min_str)
2306                high = np.inf if max_str == "" else float(max_str)
2307                if high < low:
2308                    min_ctrl.SetBackgroundColour("pink")
2309                    min_ctrl.Refresh()
2310                    max_ctrl.SetBackgroundColour("pink")
2311                    max_ctrl.Refresh()
2312                    # msg = "Invalid fit range for %s: min must be smaller
2313                    # than max"%name
2314                    # wx.PostEvent(self._manager.parent,
2315                    # StatusEvent(status=msg))
2316                    continue
2317
2318                # Force value between min and max
2319                value = float(value_str)
2320                if value < low:
2321                    value = low
2322                    value_ctrl.SetValue(format_number(value))
2323                elif value > high:
2324                    value = high
2325                    value_ctrl.SetValue(format_number(value))
2326
2327                if name not in self.model.details.keys():
2328                    self.model.details[name] = ["", None, None]
2329                old_low, old_high = self.model.details[name][1:3]
2330                if old_low != low or old_high != high:
2331                    # The configuration has changed but it won't change the
2332                    # computed curve so no need to set is_modified to True
2333                    # is_modified = True
2334                    self.model.details[name][1:3] = low, high
2335
2336            # Update value in model if it has changed
2337            if value != self.model.getParam(name):
2338                self.model.setParam(name, value)
2339                is_modified = True
2340
2341        return is_modified
2342
2343    def _set_dipers_Param(self, event):
2344        """
2345        respond to self.enable_disp and self.disable_disp radio box.
2346        The dispersity object is reset inside the model into Gaussian.
2347        When the user select yes , this method display a combo box for
2348        more selection when the user selects No,the combo box disappears.
2349        Redraw the model with the default dispersity (Gaussian)
2350        """
2351        # On selction if no model exists.
2352        if self.model is None:
2353            self.disable_disp.SetValue(True)
2354            msg = "Please select a Model first..."
2355            wx.MessageBox(msg, 'Info')
2356            wx.PostEvent(self._manager.parent,
2357                         StatusEvent(status="Polydispersion: %s" % msg))
2358            return
2359
2360        self._reset_dispersity()
2361
2362        if self.model is None:
2363            self.model_disp.Hide()
2364            self.sizer4_4.Clear(True)
2365            return
2366
2367        if self.enable_disp.GetValue():
2368            # layout for model containing no dispersity parameters
2369
2370            self.disp_list = self.model.getDispParamList()
2371
2372            if len(self.disp_list) == 0 and len(self.disp_cb_dict) == 0:
2373                self._layout_sizer_noDipers()
2374            else:
2375                # set gaussian sizer
2376                self._on_select_Disp(event=None)
2377        else:
2378            self.sizer4_4.Clear(True)
2379
2380        # post state to fit panel
2381        self.save_current_state()
2382        if event is not None:
2383            event = PageInfoEvent(page=self)
2384            wx.PostEvent(self.parent, event)
2385        # draw the model with the current dispersity
2386
2387        # Wojtek P, Oct 8, 2016: Calling draw_model seems to be unessecary.
2388        # By comenting it we save an extra Iq calculation
2389        # self._draw_model()
2390
2391        # Need to use FitInside again here to replace the next four lines.
2392        # Otherwised polydispersity off does not resize the scrollwindow.
2393        # PDB Nov 28, 2015
2394        self.FitInside()
2395#        self.sizer4_4.Layout()
2396#        self.sizer5.Layout()
2397#        self.Layout()
2398#        self.Refresh()
2399
2400    def _layout_sizer_noDipers(self):
2401        """
2402        Draw a sizer with no dispersity info
2403        """
2404        ix = 0
2405        iy = 1
2406        self.fittable_param = []
2407        self.fixed_param = []
2408        self.orientation_params_disp = []
2409
2410        self.sizer4_4.Clear(True)
2411        text = "No polydispersity available for this model"
2412        model_disp = wx.StaticText(self, wx.ID_ANY, text)
2413        self.sizer4_4.Add(model_disp, (iy, ix), (1, 1),
2414                          wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
2415        self.sizer4_4.Layout()
2416        self.sizer4.Layout()
2417
2418    def _reset_dispersity(self):
2419        """
2420        put gaussian dispersity into current model
2421        """
2422        if self.param_toFit:
2423            for item in self.fittable_param:
2424                if item in self.param_toFit:
2425                    self.param_toFit.remove(item)
2426
2427            for item in self.orientation_params_disp:
2428                if item in self.param_toFit:
2429                    self.param_toFit.remove(item)
2430
2431        self.fittable_param = []
2432        self.fixed_param = []
2433        self.orientation_params_disp = []
2434        self.values = {}
2435        self.weights = {}
2436
2437        if not self.disp_cb_dict:
2438            self.sizer4_4.Clear(True)
2439        else:
2440            for p in self.disp_cb_dict:
2441                # The parameter was un-selected.
2442                # Go back to Gaussian model (with 0 pts)
2443                disp_model = GaussianDispersion()
2444
2445                self._disp_obj_dict[p] = disp_model
2446                # Set the new model as the dispersion object
2447                # for the selected parameter
2448                try:
2449                    self.model.set_dispersion(p, disp_model)
2450                except Exception:
2451                    logger.error(traceback.format_exc())
2452
2453        # save state into
2454        self.save_current_state()
2455        self.Layout()
2456        self.Refresh()
2457
2458    def _on_select_Disp(self, event):
2459        """
2460        allow selecting different dispersion
2461        self.disp_list should change type later .now only gaussian
2462        """
2463        self._set_sizer_dispersion()
2464
2465        # Redraw the model
2466        #  Wojtek P. Nov 7, 2016: Redrawing seems to be unnecessary here
2467        # self._draw_model()
2468        # self._undo.Enable(True)
2469        event = PageInfoEvent(page=self)
2470        wx.PostEvent(self.parent, event)
2471
2472        self.sizer4_4.Layout()
2473        self.sizer4.Layout()
2474        self.SetupScrolling()
2475
2476    def _on_disp_func(self, event=None):
2477        """
2478        Select a distribution function for the polydispersion
2479
2480        :Param event: ComboBox event
2481        """
2482        # get ready for new event
2483        if event is not None:
2484            event.Skip()
2485        # Get event object
2486        disp_box = event.GetEventObject()
2487
2488        # Try to select a Distr. function
2489        try:
2490            disp_box.SetBackgroundColour("white")
2491            selection = disp_box.GetCurrentSelection()
2492            param_name = disp_box.Name.split('.')[0]
2493            disp_name = disp_box.GetValue()
2494            dispersity = disp_box.GetClientData(selection)
2495
2496            # disp_model =  GaussianDispersion()
2497            disp_model = dispersity()
2498            # Get param names to reset the values of the param
2499            name1 = param_name + ".width"
2500            name2 = param_name + ".npts"
2501            name3 = param_name + ".nsigmas"
2502            # Check Disp. function whether or not it is 'array'
2503            if disp_name.lower() == "array":
2504                value2 = ""
2505                value3 = ""
2506                value1 = self._set_array_disp(name=name1, disp=disp_model)
2507            else:
2508                self._del_array_values(name1)
2509                # self._reset_array_disp(param_name)
2510                self._disp_obj_dict[name1] = disp_model
2511                self.model.set_dispersion(param_name, disp_model)
2512                self.state.disp_obj_dict[name1] = disp_model.type
2513
2514                value1 = str(format_number(self.model.getParam(name1), True))
2515                value2 = str(format_number(self.model.getParam(name2)))
2516                value3 = str(format_number(self.model.getParam(name3)))
2517            # Reset fittable polydispersin parameter value
2518            for item in self.fittable_param:
2519                if item[1] == name1:
2520                    item[2].SetValue(value1)
2521                    item[5].SetValue("")
2522                    item[6].SetValue("")
2523                    # Disable for array
2524                    if disp_name.lower() == "array":
2525                        item[0].SetValue(False)
2526                        item[0].Disable()
2527                        item[2].Disable()
2528                        item[3].Show(False)
2529                        item[4].Show(False)
2530                        item[5].Disable()
2531                        item[6].Disable()
2532                    else:
2533                        item[0].Enable()
2534                        item[2].Enable()
2535                        item[3].Show(True)
2536                        item[4].Show(True)
2537                        item[5].Enable()
2538                        item[6].Enable()
2539                    break
2540            # Reset fixed polydispersion params
2541            for item in self.fixed_param:
2542                if item[1] == name2:
2543                    item[2].SetValue(value2)
2544                    # Disable Npts for array
2545                    if disp_name.lower() == "array":
2546                        item[2].Disable()
2547                    else:
2548                        item[2].Enable()
2549                if item[1] == name3:
2550                    item[2].SetValue(value3)
2551                    # Disable Nsigs for array
2552                    if disp_name.lower() == "array":
2553                        item[2].Disable()
2554                    else:
2555                        item[2].Enable()
2556
2557            # Make sure the check box updated
2558            self.get_all_checked_params()
2559
2560            # update params
2561            self._update_paramv_on_fit()
2562            # draw
2563            self._draw_model()
2564            self.Refresh()
2565        except Exception:
2566            logger.error(traceback.format_exc())
2567            # Error msg
2568            msg = "Error occurred:"
2569            msg += " Could not select the distribution function..."
2570            msg += " Please select another distribution function."
2571            disp_box.SetBackgroundColour("pink")
2572            # Focus on Fit button so that users can see the pinky box
2573            self.btFit.SetFocus()
2574            wx.PostEvent(self._manager.parent,
2575                         StatusEvent(status=msg, info="error"))
2576
2577    def _set_array_disp(self, name=None, disp=None):
2578        """
2579        Set array dispersion
2580
2581        :param name: name of the parameter for the dispersion to be set
2582        :param disp: the polydisperion object
2583        """
2584        # The user wants this parameter to be averaged.
2585        # Pop up the file selection dialog.
2586        path = self._selectDlg()
2587        # Array data
2588        values = []
2589        weights = []
2590        # If nothing was selected, just return
2591        if path is None:
2592            self.disp_cb_dict[name].SetValue(False)
2593            # self.noDisper_rbox.SetValue(True)
2594            return
2595        self._default_save_location = os.path.dirname(path)
2596        if self._manager is not None:
2597            self._manager.parent._default_save_location = \
2598                             self._default_save_location
2599
2600        basename = os.path.basename(path)
2601        values, weights = self.read_file(path)
2602
2603        # If any of the two arrays is empty, notify the user that we won't
2604        # proceed
2605        if len(self.param_toFit) > 0:
2606            if name in self.param_toFit:
2607                self.param_toFit.remove(name)
2608
2609        # Tell the user that we are about to apply the distribution
2610        msg = "Applying loaded %s distribution: %s" % (name, path)
2611        wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2612        self._set_array_disp_model(name=name, disp=disp,
2613                                   values=values, weights=weights)
2614        return basename
2615
2616    def _set_array_disp_model(self, name=None, disp=None,
2617                              values=[], weights=[]):
2618        """
2619        Set array dispersion model
2620
2621        :param name: name of the parameter for the dispersion to be set
2622        :param disp: the polydisperion object
2623        """
2624        disp.set_weights(values, weights)
2625        self._disp_obj_dict[name] = disp
2626        self.model.set_dispersion(name.split('.')[0], disp)
2627        self.state.disp_obj_dict[name] = disp.type
2628        self.values[name] = values
2629        self.weights[name] = weights
2630        # Store the object to make it persist outside the
2631        # scope of this method
2632        # TODO: refactor model to clean this up?
2633        self.state.values = {}
2634        self.state.weights = {}
2635        self.state.values = copy.deepcopy(self.values)
2636        self.state.weights = copy.deepcopy(self.weights)
2637
2638        # Set the new model as the dispersion object for the
2639        # selected parameter
2640        # self.model.set_dispersion(p, disp_model)
2641        # Store a reference to the weights in the model object
2642        # so that
2643        # it's not lost when we use the model within another thread.
2644        self.state.model = self.model.clone()
2645        self.model._persistency_dict[name.split('.')[0]] = \
2646            [values, weights]
2647        self.state.model._persistency_dict[name.split('.')[0]] = \
2648            [values, weights]
2649
2650    def _del_array_values(self, name=None):
2651        """
2652        Reset array dispersion
2653
2654        :param name: name of the parameter for the dispersion to be set
2655        """
2656        # Try to delete values and weight of the names array dic if exists
2657        try:
2658            if name in self.values:
2659                del self.values[name]
2660                del self.weights[name]
2661                # delete all other dic
2662                del self.state.values[name]
2663                del self.state.weights[name]
2664                del self.model._persistency_dict[name.split('.')[0]]
2665                del self.state.model._persistency_dict[name.split('.')[0]]
2666        except Exception:
2667            logger.error(traceback.format_exc())
2668
2669    def _lay_out(self):
2670        """
2671        returns self.Layout
2672
2673        :Note: Mac seems to like this better when self.
2674            Layout is called after fitting.
2675        """
2676        self.Layout()
2677        return
2678
2679    def _find_polyfunc_selection(self, disp_func=None):
2680        """
2681        FInd Comboox selection from disp_func
2682
2683        :param disp_function: dispersion distr. function
2684        """
2685        # Find the selection
2686        if disp_func is not None:
2687            try:
2688                return POLYDISPERSITY_MODELS.values().index(disp_func.__class__)
2689            except ValueError:
2690                pass  # Fall through to default class
2691        return POLYDISPERSITY_MODELS.keys().index('gaussian')
2692
2693    def on_reset_clicked(self, event):
2694        """
2695        On 'Reset' button  for Q range clicked
2696        """
2697        flag = True
2698        # For 3 different cases: Data2D, Data1D, and theory
2699        if self.model is None:
2700            msg = "Please select a model first..."
2701            wx.MessageBox(msg, 'Info')
2702            flag = False
2703            return
2704
2705        elif self.data.__class__.__name__ == "Data2D":
2706            data_min = 0
2707            x = max(math.fabs(self.data.xmin), math.fabs(self.data.xmax))
2708            y = max(math.fabs(self.data.ymin), math.fabs(self.data.ymax))
2709            self.qmin_x = data_min
2710            self.qmax_x = math.sqrt(x * x + y * y)
2711            # self.data.mask = np.ones(len(self.data.data),dtype=bool)
2712            # check smearing
2713            if not self.disable_smearer.GetValue():
2714                # set smearing value whether or
2715                # not the data contain the smearing info
2716                if self.pinhole_smearer.GetValue():
2717                    flag = self.update_pinhole_smear()
2718                else:
2719                    flag = True
2720
2721        elif self.data is None:
2722            self.qmin_x = _QMIN_DEFAULT
2723            self.qmax_x = _QMAX_DEFAULT
2724            self.num_points = _NPTS_DEFAULT
2725            self.state.npts = self.num_points
2726
2727        elif self.data.__class__.__name__ != "Data2D":
2728            self.qmin_x = min(self.data.x)
2729            self.qmax_x = max(self.data.x)
2730            # check smearing
2731            if not self.disable_smearer.GetValue():
2732                # set smearing value whether or
2733                # not the data contain the smearing info
2734                if self.slit_smearer.GetValue():
2735                    flag = self.update_slit_smear()
2736                elif self.pinhole_smearer.GetValue():
2737                    flag = self.update_pinhole_smear()
2738                else:
2739                    flag = True
2740        else:
2741            flag = False
2742
2743        if flag is False:
2744            msg = "Cannot Plot :Must enter a number!!!  "
2745            wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
2746        else:
2747            # set relative text ctrs.
2748            self.qmin.SetValue(str(self.qmin_x))
2749            self.qmax.SetValue(str(self.qmax_x))
2750            self.show_npts2fit()
2751            # At this point, some button and variables satatus (disabled?)
2752            # should be checked such as color that should be reset to
2753            # white in case that it was pink.
2754            self._onparamEnter_helper()
2755
2756        self.save_current_state()
2757        self.state.qmin = self.qmin_x
2758        self.state.qmax = self.qmax_x
2759
2760        # reset the q range values
2761        self._reset_plotting_range(self.state)
2762        self._draw_model()
2763
2764    def select_log(self, event):
2765        """
2766        Log checked to generate log spaced points for theory model
2767        """
2768
2769    def get_images(self):
2770        """
2771        Get the images of the plots corresponding this panel for report
2772
2773        : return graphs: list of figures
2774        : Need Move to guiframe
2775        """
2776        # set list of graphs
2777        graphs = []
2778        canvases = []
2779        res_item = None
2780        # call gui_manager
2781        gui_manager = self._manager.parent
2782        # loops through the panels [dic]
2783        for _, item2 in gui_manager.plot_panels.iteritems():
2784            data_title = self.data.group_id
2785            # try to get all plots belonging to this control panel
2786            try:
2787                g_id = item2.group_id
2788                if g_id == data_title or \
2789                        str(g_id).count("res" + str(self.graph_id)) or \
2790                        str(g_id).count(str(self.uid)) > 0:
2791                    if str(g_id).count("res" + str(self.graph_id)) > 0:
2792                        res_item = [item2.figure, item2.canvas]
2793                    else:
2794                        # append to the list
2795                        graphs.append(item2.figure)
2796                        canvases.append(item2.canvas)
2797            except Exception:
2798                # Not for control panels
2799                logger.error(traceback.format_exc())
2800        # Make sure the resduals plot goes to the last
2801        if res_item is not None:
2802            graphs.append(res_item[0])
2803            canvases.append(res_item[1])
2804        # return the list of graphs
2805        return graphs, canvases
2806
2807    def on_function_help_clicked(self, event):
2808        """
2809        Function called when 'Help' button is pressed next to model
2810        of interest.  This calls DocumentationWindow from
2811        documentation_window.py. It will load the top level of the model
2812        help documenation sphinx generated html if no model is presented.
2813        If a model IS present then if documention for that model exists
2814        it will load to that  point otherwise again it will go to the top.
2815        For Wx2.8 and below is used (i.e. non-released through installer)
2816        a browser is loaded and the top of the model documentation only is
2817        accessible because webbrowser module does not pass anything after
2818        the # to the browser.
2819
2820        :param event: on Help Button pressed event
2821        """
2822
2823        if self.model is not None:
2824            name = self.formfactorbox.GetValue()
2825            _TreeLocation = 'user/models/' + name.lower()+'.html'
2826            _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation,
2827                                              "", name + " Help")
2828        else:
2829            _TreeLocation = 'user/sasgui/perspectives/fitting/models/index.html'
2830            _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation,
2831                                              "", "General Model Help")
2832
2833    def on_model_help_clicked(self, event):
2834        """
2835        Function called when 'Description' button is pressed next to model
2836        of interest.  This calls the Description embedded in the model. This
2837        should work with either Wx2.8 and lower or higher. If no model is
2838        selected it will give the message that a model must be chosen first
2839        in the box that would normally contain the description.  If a badly
2840        behaved model is encountered which has no description then it will
2841        give the message that none is available.
2842
2843        :param event: on Description Button pressed event
2844        """
2845
2846        if self.model is None:
2847            name = 'index.html'
2848        else:
2849            name = self.formfactorbox.GetValue()
2850
2851        msg = 'Model description:\n'
2852        info = "Info"
2853        if self.model is not None:
2854            # frame.Destroy()
2855            if str(self.model.description).rstrip().lstrip() == '':
2856                msg += "Sorry, no information is available for this model."
2857            else:
2858                msg += self.model.description + '\n'
2859            wx.MessageBox(msg, info)
2860        else:
2861            msg += "You must select a model to get information on this"
2862            wx.MessageBox(msg, info)
2863
2864    def _on_mag_angle_help(self, event):
2865        """
2866        Bring up Magnetic Angle definition.png image whenever the ? button
2867        is clicked. Calls DocumentationWindow with the path of the location
2868        within the documentation tree (after /doc/ ....". When using old
2869        versions of Wx (i.e. before 2.9 and therefore not part of release
2870        versions distributed via installer) it brings up an image viewer
2871        box which allows the user to click through the rest of the images in
2872        the directory.  Not ideal but probably better than alternative which
2873        would bring up the entire discussion of how magnetic models work?
2874        Specially since it is not likely to be accessed.  The normal release
2875        versions bring up the normal image box.
2876
2877        :param evt: Triggers on clicking ? in Magnetic Angles? box
2878        """
2879
2880        _TreeLocation = "_images/M_angles_pic.png"
2881        _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation, "",
2882                                          "Magnetic Angle Defintions")
2883
2884    def _on_mag_help(self, event):
2885        """
2886        Bring up Magnetic Angle definition.png image whenever the ? button
2887        is clicked. Calls DocumentationWindow with the path of the location
2888        within the documentation tree (after /doc/ ....". When using old
2889        versions of Wx (i.e. before 2.9 and therefore not part of release
2890        versions distributed via installer) it brings up an image viewer
2891        box which allows the user to click through the rest of the images in
2892        the directory.  Not ideal but probably better than alternative which
2893        would bring up the entire discussion of how magnetic models work?
2894        Specially since it is not likely to be accessed.  The normal release
2895        versions bring up the normal image box.
2896
2897        :param evt: Triggers on clicking ? in Magnetic Angles? box
2898        """
2899
2900        _TreeLocation = "user/sasgui/perspectives/fitting/magnetism/magnetism.html"
2901        _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation, "",
2902                                          "Polarized Beam/Magnetc Help")
2903
2904    def _on_mag_on(self, event):
2905        """
2906        Magnetic Parameters ON/OFF
2907        """
2908        button = event.GetEventObject()
2909
2910        if button.GetLabel().count('ON') > 0:
2911            self.magnetic_on = True
2912            button.SetLabel("Magnetic OFF")
2913            m_value = 1.0e-06
2914            for key in self.model.magnetic_params:
2915                if key.count('M0') > 0:
2916                    self.model.setParam(key, m_value)
2917                    m_value += 0.5e-06
2918        else:
2919            self.magnetic_on = False
2920            button.SetLabel("Magnetic ON")
2921            for key in self.model.magnetic_params:
2922                if key.count('M0') > 0:
2923                    # reset mag value to zero fo safety
2924                    self.model.setParam(key, 0.0)
2925
2926        self.Show(False)
2927        self.set_model_param_sizer(self.model)
2928        # self._set_sizer_dispersion()
2929        self.state.magnetic_on = self.magnetic_on
2930        self.SetupScrolling()
2931        self.Show(True)
2932
2933    def on_pd_help_clicked(self, event):
2934        """
2935        Bring up Polydispersity Documentation whenever the ? button is clicked.
2936        Calls DocumentationWindow with the path of the location within the
2937        documentation tree (after /doc/ ....".  Note that when using old
2938        versions of Wx (before 2.9) and thus not the release version of
2939        istallers, the help comes up at the top level of the file as
2940        webbrowser does not pass anything past the # to the browser when it is
2941        running "file:///...."
2942
2943        :param event: Triggers on clicking ? in polydispersity box
2944        """
2945
2946        _TreeLocation = "user/sasgui/perspectives/fitting/pd/polydispersity.html"
2947        _PageAnchor = ""
2948        _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation,
2949                                          _PageAnchor, "Polydispersity Help")
2950
2951    def on_left_down(self, event):
2952        """
2953        Get key stroke event
2954        """
2955        # Figuring out key combo: Cmd for copy, Alt for paste
2956        if event.CmdDown() and event.ShiftDown():
2957            self.get_paste()
2958        elif event.CmdDown():
2959            self.get_copy()
2960        else:
2961            event.Skip()
2962            return
2963        # make event free
2964        event.Skip()
2965
2966    def get_copy(self):
2967        """
2968        Get copy params to clipboard
2969        """
2970        content = self.get_copy_params()
2971        flag = self.set_clipboard(content)
2972        self._copy_info(flag)
2973        return flag
2974
2975    def get_copy_params(self):
2976        """
2977        Get the string copies of the param names and values in the tap
2978        """
2979        content = 'sasview_parameter_values:'
2980        # Do it if params exist
2981        if self.parameters:
2982
2983            # go through the parameters
2984            strings = self._get_copy_helper(self.parameters,
2985                                            self.orientation_params)
2986            content += strings
2987
2988            # go through the fittables
2989            strings = self._get_copy_helper(self.fittable_param,
2990                                            self.orientation_params_disp)
2991            content += strings
2992
2993            # go through the fixed params
2994            strings = self._get_copy_helper(self.fixed_param,
2995                                            self.orientation_params_disp)
2996            content += strings
2997
2998            # go through the str params
2999            strings = self._get_copy_helper(self.str_parameters,
3000                                            self.orientation_params)
3001            content += strings
3002            return content
3003        else:
3004            return False
3005
3006
3007    def _get_copy_params_details(self):
3008        """
3009        Combines polydisperse parameters with self.parameters so that they can
3010        be written to the clipboard (for Excel or LaTeX). Also returns a list of
3011        the names of parameters that have been fitted
3012
3013        :returns: all_params - A list of all parameters, in the format of
3014        self.parameters
3015        :returns: fitted_par_names - A list of the names of parameters that have
3016        been fitted
3017        """
3018        # Names of params that are being fitted
3019        fitted_par_names = [param[1] for param in self.param_toFit]
3020        # Names of params with associated polydispersity
3021        disp_params = [param[1].split('.')[0] for param in self.fittable_param]
3022
3023        # Create array of all parameters
3024        all_params = copy.copy(self.parameters)
3025        for param in self.parameters:
3026            if param[1] in disp_params:
3027                # Polydisperse params aren't in self.parameters, so need adding
3028                # to all_params
3029                name = param[1] + ".width"
3030                index = all_params.index(param) + 1
3031                to_insert = []
3032                if name in fitted_par_names:
3033                    # Param is fitted, so already has a param list in self.param_toFit
3034                    to_insert = self.param_toFit[fitted_par_names.index(name)]
3035                else:
3036                    # Param isn't fitted, so mockup a param list
3037                    to_insert = [None, name, self.model.getParam(name), None, None]
3038                all_params.insert(index, to_insert)
3039        return all_params, fitted_par_names
3040
3041    def get_copy_excel(self):
3042        """
3043        Get copy params to clipboard
3044        """
3045        content = self.get_copy_params_excel()
3046        flag = self.set_clipboard(content)
3047        self._copy_info(flag)
3048        return flag
3049
3050    def get_copy_params_excel(self):
3051        """
3052        Get the string copies of the param names and values in the tap
3053        """
3054        if not self.parameters:
3055            # Do nothing if parameters doesn't exist
3056            return False
3057
3058        content = ''
3059        crlf = chr(13) + chr(10)
3060        tab = chr(9)
3061
3062        all_params, fitted_param_names = self._get_copy_params_details()
3063
3064        # Construct row of parameter names
3065        for param in all_params:
3066            name = param[1] # Parameter name
3067            content += name
3068            content += tab
3069            if name in fitted_param_names:
3070                # Only print errors for fitted parameters
3071                content += name + "_err"
3072                content += tab
3073
3074        content += crlf
3075
3076        # Construct row of parameter values and errors
3077        for param in all_params:
3078            value = param[2]
3079            if hasattr(value, 'GetValue'):
3080                # param[2] is a text box
3081                value = value.GetValue()
3082            else:
3083                # param[2] is a float (from our self._get_copy_params_details)
3084                value = str(value)
3085            content += value
3086            content += tab
3087            if param[1] in fitted_param_names:
3088                # Only print errors for fitted parameters
3089                content += param[4].GetValue()
3090                content += tab
3091
3092        return content
3093
3094    def get_copy_latex(self):
3095        """
3096        Get copy params to clipboard
3097        """
3098        content = self.get_copy_params_latex()
3099        flag = self.set_clipboard(content)
3100        self._copy_info(flag)
3101        return flag
3102
3103    def get_copy_params_latex(self):
3104        """
3105        Get the string copies of the param names and values in the tap
3106        """
3107        if not self.parameters:
3108            # Do nothing if self.parameters doesn't exist
3109            return False
3110
3111        content = r'\begin{table}'
3112        content += r'\begin{tabular}[h]'
3113
3114        crlf = chr(13) + chr(10)
3115        tab = chr(9)
3116
3117        all_params, fitted_param_names = self._get_copy_params_details()
3118
3119        content += '{|'
3120        for param in all_params:
3121            content += 'l|l|'
3122        content += r'}\hline'
3123        content += crlf
3124
3125        # Construct row of parameter names
3126        for index, param in enumerate(all_params):
3127            name = param[1] # Parameter name
3128            content += name.replace('_', r'\_')  # Escape underscores
3129            if name in fitted_param_names:
3130                # Only print errors for fitted parameters
3131                content += ' & '
3132                content += name.replace('_', r'\_') + r"\_err"
3133            if index < len(all_params) - 1:
3134                content += ' & '
3135
3136        content += r'\\ \hline'
3137        content += crlf
3138
3139        # Construct row of values and errors
3140        for index, param in enumerate(all_params):
3141            value = param[2]
3142            if hasattr(value, "GetValue"):
3143                # value is a text box
3144                value = value.GetValue()
3145            else:
3146                # value is a float (from self._get_copy_params_details)
3147                value = str(value)
3148            content += value
3149            if param[1] in fitted_param_names:
3150                # Only print errors for fitted params
3151                content += ' & '
3152                content += param[4].GetValue()
3153            if index < len(all_params) - 1:
3154                content += ' & '
3155
3156        content += r'\\ \hline'
3157        content += crlf
3158        content += r'\end{tabular}'
3159        content += r'\end{table}'
3160
3161        return content
3162
3163    def set_clipboard(self, content=None):
3164        """
3165        Put the string to the clipboard
3166        """
3167        if not content:
3168            return False
3169        if wx.TheClipboard.Open():
3170            wx.TheClipboard.SetData(wx.TextDataObject(str(content)))
3171            wx.TheClipboard.Close()
3172            return True
3173        return None
3174
3175    def _get_copy_helper(self, param, orient_param):
3176        """
3177        Helping get value and name of the params
3178
3179        : param param:  parameters
3180        : param orient_param = oritational params
3181        : return content: strings [list] [name,value:....]
3182        """
3183        content = ''
3184        bound_hi = ''
3185        bound_lo = ''
3186        # go through the str params
3187        for item in param:
3188            # copy only the params shown
3189            if not item[2].IsShown():
3190                continue
3191            disfunc = ''
3192            try:
3193                if item[7].__class__.__name__ == 'ComboBox':
3194                    disfunc = str(item[7].GetValue())
3195            except Exception:
3196                logger.error(traceback.format_exc())
3197
3198            # 2D
3199            if self.data.__class__.__name__ == "Data2D":
3200                try:
3201                    check = item[0].GetValue()
3202                except Exception:
3203                    check = None
3204                name = item[1]
3205                value = item[2].GetValue()
3206            # 1D
3207            else:
3208                # for 1D all parameters except orientation
3209                if not item[1] in orient_param:
3210                    try:
3211                        check = item[0].GetValue()
3212                    except:
3213                        check = None
3214                    name = item[1]
3215                    value = item[2].GetValue()
3216
3217            # Bounds
3218            try:
3219                bound_lo = item[5].GetValue()
3220                bound_hi = item[6].GetValue()
3221            except Exception:
3222                # harmless - need to just pass
3223                pass
3224
3225            # add to the content
3226            if disfunc != '':
3227
3228                disfunc = ',' + disfunc
3229            # Need to support array func for copy/paste
3230            try:
3231                if disfunc.count('array') > 0:
3232                    disfunc += ','
3233                    for val in self.values[name]:
3234                        disfunc += ' ' + str(val)
3235                    disfunc += ','
3236                    for weight in self.weights[name]:
3237                        disfunc += ' ' + str(weight)
3238            except Exception:
3239                logger.error(traceback.format_exc())
3240            content += name + ',' + str(check) + ',' + value + disfunc + ',' + \
3241                       bound_lo + ',' + bound_hi + ':'
3242
3243        return content
3244
3245    def get_clipboard(self):
3246        """
3247        Get strings in the clipboard
3248        """
3249        text = ""
3250        # Get text from the clip board
3251        if wx.TheClipboard.Open():
3252            if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
3253                data = wx.TextDataObject()
3254                # get wx dataobject
3255                success = wx.TheClipboard.GetData(data)
3256                # get text
3257                if success:
3258                    text = data.GetText()
3259                else:
3260                    text = ''
3261            # close clipboard
3262            wx.TheClipboard.Close()
3263        return text
3264
3265    def get_paste(self):
3266        """
3267        Paste params from the clipboard
3268        """
3269        text = self.get_clipboard()
3270        flag = self.get_paste_params(text)
3271        self._copy_info(flag)
3272        return flag
3273
3274    def get_paste_params(self, text=''):
3275        """
3276        Get the string copies of the param names and values in the tap
3277        """
3278        context = {}
3279        # put the text into dictionary
3280        lines = text.split(':')
3281        if lines[0] != 'sasview_parameter_values':
3282            self._copy_info(False)
3283            return False
3284        for line in lines[1:-1]:
3285            if len(line) != 0:
3286                item = line.split(',')
3287                check = item[1]
3288                name = item[0]
3289                value = item[2]
3290                # Transfer the text to content[dictionary]
3291                context[name] = [check, value]
3292
3293                # limits
3294                limit_lo = item[3]
3295                context[name].append(limit_lo)
3296                limit_hi = item[4]
3297                context[name].append(limit_hi)
3298
3299            # ToDo: PlugIn this poly disp function for pasting
3300            try:
3301                poly_func = item[5]
3302                context[name].append(poly_func)
3303                try:
3304                    # take the vals and weights for  array
3305                    array_values = item[6].split(' ')
3306                    array_weights = item[7].split(' ')
3307                    val = [float(a_val) for a_val in array_values[1:]]
3308                    weit = [float(a_weit) for a_weit in array_weights[1:]]
3309
3310                    context[name].append(val)
3311                    context[name].append(weit)
3312                except:
3313                    raise
3314            except:
3315                poly_func = ''
3316                context[name].append(poly_func)
3317
3318        # Do it if params exist
3319        if self.parameters:
3320            # go through the parameters
3321            self._get_paste_helper(self.parameters,
3322                                   self.orientation_params, context)
3323
3324            # go through the fittables
3325            self._get_paste_helper(self.fittable_param,
3326                                   self.orientation_params_disp,
3327                                   context)
3328
3329            # go through the fixed params
3330            self._get_paste_helper(self.fixed_param,
3331                                   self.orientation_params_disp, context)
3332
3333            # go through the str params
3334            self._get_paste_helper(self.str_parameters,
3335                                   self.orientation_params, context)
3336
3337            return True
3338        return None
3339
3340    def _get_paste_helper(self, param, orient_param, content):
3341        """
3342        Helping set values of the params
3343
3344        : param param:  parameters
3345        : param orient_param: oritational params
3346        : param content: dictionary [ name, value: name1.value1,...]
3347        """
3348        # go through the str params
3349        for item in param:
3350            # 2D
3351            if self.data.__class__.__name__ == "Data2D":
3352                name = item[1]
3353                if name in content.keys():
3354                    values = content[name]
3355                    check = values[0]
3356                    pd = values[1]
3357
3358                    if name.count('.') > 0:
3359                        # If this is parameter.width, then pd may be a floating
3360                        # point value or it may be an array distribution.
3361                        # Nothing to do for parameter.npts or parameter.nsigmas.
3362                        try:
3363                            float(pd)
3364                            if name.endswith('.npts'):
3365                                pd = int(pd)
3366                        except Exception:
3367                            # continue
3368                            if not pd and pd != '':
3369                                continue
3370                    item[2].SetValue(str(pd))
3371                    if item in self.fixed_param and pd == '':
3372                        # Only array func has pd == '' case.
3373                        item[2].Enable(False)
3374                    else:
3375                        item[2].Enable(True)
3376                    if item[2].__class__.__name__ == "ComboBox":
3377                        if content[name][1] in self.model.fun_list:
3378                            # to fix: fun_list is not a dictionary, but a tuple
3379                            # so the following line (commented) will fail
3380                            # fun_val = self.model.fun_list[content[name][1]]
3381                            # I guess the following should work, but
3382                            # could not test as I don't know when this
3383                            # part is used by SasView.
3384                            fun_val = self.model.fun_list.index(content[name][1])
3385                            self.model.setParam(name, fun_val)
3386                    try:
3387                        item[5].SetValue(str(values[-3]))
3388                        item[6].SetValue(str(values[-2]))
3389                    except Exception:
3390                        # passing as harmless non-update
3391                        pass
3392
3393                    value = content[name][1:]
3394                    self._paste_poly_help(item, value)
3395                    if check == 'True':
3396                        is_true = True
3397                    elif check == 'False':
3398                        is_true = False
3399                    else:
3400                        is_true = None
3401                    if is_true is not None:
3402                        item[0].SetValue(is_true)
3403            # 1D
3404            else:
3405                # for 1D all parameters except orientation
3406                if not item[1] in orient_param:
3407                    name = item[1]
3408                    if name in content.keys():
3409                        check = content[name][0]
3410                        # Avoid changing combox content
3411                        value = content[name][1:]
3412                        pd = value[0]
3413                        if name.count('.') > 0:
3414                            # If this is parameter.width, then pd may be a
3415                            # floating point value or it may be an array
3416                            # distribution. Nothing to do for parameter.npts or
3417                            # parameter.nsigmas.
3418                            try:
3419                                pd = float(pd)
3420                                if name.endswith('.npts'):
3421                                    pd = int(pd)
3422                            except Exception:
3423                                # continue
3424                                if not pd and pd != '':
3425                                    continue
3426                        item[2].SetValue(str(pd))
3427                        if item in self.fixed_param and pd == '':
3428                            # Only array func has pd == '' case.
3429                            item[2].Enable(False)
3430                        else:
3431                            item[2].Enable(True)
3432                        if item[2].__class__.__name__ == "ComboBox":
3433                            if value[0] in self.model.fun_list:
3434                                # Fixed: fun_list not a dictionary!
3435                                # Arrives here when spherical_sld model is
3436                                # selected and number of shells modified.
3437                                fun_val = self.model.fun_list.index(value[0])
3438                                self.model.setParam(name, fun_val)
3439                                # save state
3440                        try:
3441                            item[5].SetValue(str(value[-3]))
3442                            item[6].SetValue(str(value[-2]))
3443                        except Exception:
3444                            # passing as harmless non-update
3445                            pass
3446
3447                        self._paste_poly_help(item, value)
3448                        if check == 'True':
3449                            is_true = True
3450                        elif check == 'False':
3451                            is_true = False
3452                        else:
3453                            is_true = None
3454                        if is_true is not None:
3455                            item[0].SetValue(is_true)
3456
3457        self.select_param(event=None)
3458        self.Refresh()
3459
3460    def _paste_poly_help(self, item, value):
3461        """
3462        Helps get paste for poly function
3463
3464        *item* is the parameter name
3465
3466        *value* depends on which parameter is being processed, and whether it
3467        has array polydispersity.
3468
3469        For parameters without array polydispersity:
3470
3471            parameter => ['FLOAT', '']
3472            parameter.width => ['FLOAT', 'DISTRIBUTION', '']
3473            parameter.npts => ['FLOAT', '']
3474            parameter.nsigmas => ['FLOAT', '']
3475
3476        For parameters with array polydispersity:
3477
3478            parameter => ['FLOAT', '']
3479            parameter.width => ['FILENAME', 'array', [x1, ...], [w1, ...]]
3480            parameter.npts => ['FLOAT', '']
3481            parameter.nsigmas => ['FLOAT', '']
3482        """
3483        # Do nothing if not setting polydispersity
3484        if len(value[3]) == 0:
3485            return
3486
3487        try:
3488            name = item[7].Name
3489            param_name = name.split('.')[0]
3490            item[7].SetValue(value[1])
3491            selection = item[7].GetCurrentSelection()
3492            dispersity = item[7].GetClientData(selection)
3493            disp_model = dispersity()
3494
3495            if value[1] == 'array':
3496                pd_vals = np.array(value[2])
3497                pd_weights = np.array(value[3])
3498                if len(pd_vals) == 0 or len(pd_vals) != len(pd_weights):
3499                    msg = ("bad array distribution parameters for %s"
3500                           % param_name)
3501                    raise ValueError(msg)
3502                self._set_disp_cb(True, item=item)
3503                self._set_array_disp_model(name=name,
3504                                           disp=disp_model,
3505                                           values=pd_vals,
3506                                           weights=pd_weights)
3507            else:
3508                self._set_disp_cb(False, item=item)
3509                self._disp_obj_dict[name] = disp_model
3510                self.model.set_dispersion(param_name, disp_model)
3511                self.state.disp_obj_dict[name] = disp_model.type
3512                # TODO: It's not an array, why update values and weights?
3513                self.model._persistency_dict[param_name] = \
3514                    [self.values, self.weights]
3515                self.state.values = self.values
3516                self.state.weights = self.weights
3517
3518        except Exception:
3519            logger.error(traceback.format_exc())
3520            print("Error in BasePage._paste_poly_help: %s" % \
3521                  sys.exc_info()[1])
3522
3523    def _set_disp_cb(self, isarray, item):
3524        """
3525        Set cb for array disp
3526        """
3527        if isarray:
3528            item[0].SetValue(False)
3529            item[0].Enable(False)
3530            item[2].Enable(False)
3531            item[3].Show(False)
3532            item[4].Show(False)
3533            item[5].SetValue('')
3534            item[5].Enable(False)
3535            item[6].SetValue('')
3536            item[6].Enable(False)
3537        else:
3538            item[0].Enable()
3539            item[2].Enable()
3540            item[3].Show(True)
3541            item[4].Show(True)
3542            item[5].Enable()
3543            item[6].Enable()
3544
3545    def update_pinhole_smear(self):
3546        """
3547            Method to be called by sub-classes
3548            Moveit; This method doesn't belong here
3549        """
3550        print("BasicPage.update_pinhole_smear was called: skipping")
3551        return
3552
3553    def _read_category_info(self):
3554        """
3555        Reads the categories in from file
3556        """
3557        # # ILL mod starts here - July 2012 kieranrcampbell@gmail.com
3558        self.master_category_dict = defaultdict(list)
3559        self.by_model_dict = defaultdict(list)
3560        self.model_enabled_dict = defaultdict(bool)
3561        categorization_file = CategoryInstaller.get_user_file()
3562        with open(categorization_file, 'rb') as f:
3563            self.master_category_dict = json.load(f)
3564        self._regenerate_model_dict()
3565
3566    def _regenerate_model_dict(self):
3567        """
3568        regenerates self.by_model_dict which has each model name as the
3569        key and the list of categories belonging to that model
3570        along with the enabled mapping
3571        """
3572        self.by_model_dict = defaultdict(list)
3573        for category in self.master_category_dict:
3574            for (model, enabled) in self.master_category_dict[category]:
3575                self.by_model_dict[model].append(category)
3576                self.model_enabled_dict[model] = enabled
3577
3578    def _populate_listbox(self):
3579        """
3580        fills out the category list box
3581        """
3582        uncat_str = 'Plugin Models'
3583        self._read_category_info()
3584
3585        self.categorybox.Clear()
3586        cat_list = sorted(self.master_category_dict.keys())
3587        if uncat_str not in cat_list:
3588            cat_list.append(uncat_str)
3589
3590        for category in cat_list:
3591            if category != '':
3592                self.categorybox.Append(category)
3593
3594        if self.categorybox.GetSelection() == wx.NOT_FOUND:
3595            self.categorybox.SetSelection(0)
3596        else:
3597            self.categorybox.SetSelection(
3598                self.categorybox.GetSelection())
3599        # self._on_change_cat(None)
3600
3601    def _on_change_cat(self, event):
3602        """
3603        Callback for category change action
3604        """
3605        self.model_name = None
3606        category = self.categorybox.GetStringSelection()
3607        if category is None:
3608            return
3609        self.model_box.Clear()
3610
3611        if category == CUSTOM_MODEL:
3612            for model in self.model_list_box[category]:
3613                str_m = str(model).split(".")[0]
3614                self.model_box.Append(str_m)
3615
3616        else:
3617            for model, enabled in sorted(self.master_category_dict[category],
3618                                         key=lambda name: name[0]):
3619                if enabled:
3620                    self.model_box.Append(model)
3621
3622    def _fill_model_sizer(self, sizer):
3623        """
3624        fill sizer containing model info
3625        """
3626        # This should only be called once per fit tab
3627        # print "==== Entering _fill_model_sizer"
3628        # Add model function Details button in fitpanel.
3629        # The following 3 lines are for Mac. Let JHC know before modifying...
3630        title = "Model"
3631        self.formfactorbox = None
3632        self.multifactorbox = None
3633        self.mbox_description = wx.StaticBox(self, wx.ID_ANY, str(title))
3634        boxsizer1 = wx.StaticBoxSizer(self.mbox_description, wx.VERTICAL)
3635        sizer_cat = wx.BoxSizer(wx.HORIZONTAL)
3636        self.mbox_description.SetForegroundColour(wx.RED)
3637        wx_id = self._ids.next()
3638        self.model_func = wx.Button(self, wx_id, 'Help', size=(80, 23))
3639        self.model_func.Bind(wx.EVT_BUTTON, self.on_function_help_clicked,
3640                             id=wx_id)
3641        self.model_func.SetToolTipString("Full Model Function Help")
3642        wx_id = self._ids.next()
3643        self.model_help = wx.Button(self, wx_id, 'Description', size=(80, 23))
3644        self.model_help.Bind(wx.EVT_BUTTON, self.on_model_help_clicked,
3645                             id=wx_id)
3646        self.model_help.SetToolTipString("Short Model Function Description")
3647        wx_id = self._ids.next()
3648        self.model_view = wx.Button(self, wx_id, "Show 2D", size=(80, 23))
3649        self.model_view.Bind(wx.EVT_BUTTON, self._onModel2D, id=wx_id)
3650        hint = "toggle view of model from 1D to 2D  or 2D to 1D"
3651        self.model_view.SetToolTipString(hint)
3652
3653        cat_set_box = wx.StaticBox(self, wx.ID_ANY, 'Category')
3654        sizer_cat_box = wx.StaticBoxSizer(cat_set_box, wx.HORIZONTAL)
3655        sizer_cat_box.SetMinSize((200, 50))
3656        self.categorybox = wx.ComboBox(self, wx.ID_ANY,
3657                                       style=wx.CB_READONLY)
3658        self.categorybox.SetToolTip(wx.ToolTip("Select a Category/Type"))
3659        self._populate_listbox()
3660        wx.EVT_COMBOBOX(self.categorybox, wx.ID_ANY, self._show_combox)
3661        # self.shape_rbutton = wx.RadioButton(self, wx.ID_ANY, 'Shapes',
3662        #                                     style=wx.RB_GROUP)
3663        # self.shape_indep_rbutton = wx.RadioButton(self, wx.ID_ANY,
3664        #                                          "Shape-Independent")
3665        # self.struct_rbutton = wx.RadioButton(self, wx.ID_ANY,
3666        #                                     "Structure Factor ")
3667        # self.plugin_rbutton = wx.RadioButton(self, wx.ID_ANY,
3668        #                                     "Uncategorized")
3669
3670        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
3671        #                   id=self.shape_rbutton.GetId())
3672        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
3673        #                    id=self.shape_indep_rbutton.GetId())
3674        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
3675        #                    id=self.struct_rbutton.GetId())
3676        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
3677        #                    id=self.plugin_rbutton.GetId())
3678        # MAC needs SetValue
3679
3680        show_cat_button = wx.Button(self, wx.ID_ANY, "Modify")
3681        cat_tip = "Modify model categories \n"
3682        cat_tip += "(also accessible from the menu bar)."
3683        show_cat_button.SetToolTip(wx.ToolTip(cat_tip))
3684        show_cat_button.Bind(wx.EVT_BUTTON, self._on_modify_cat)
3685        sizer_cat_box.Add(self.categorybox, 1, wx.RIGHT, 3)
3686        sizer_cat_box.Add((10, 10))
3687        sizer_cat_box.Add(show_cat_button)
3688        # self.shape_rbutton.SetValue(True)
3689
3690        sizer_radiobutton = wx.GridSizer(2, 2, 5, 5)
3691        # sizer_radiobutton.Add(self.shape_rbutton)
3692        # sizer_radiobutton.Add(self.shape_indep_rbutton)
3693        sizer_radiobutton.Add((5, 5))
3694        sizer_radiobutton.Add(self.model_view, 1, wx.RIGHT, 5)
3695        # sizer_radiobutton.Add(self.plugin_rbutton)
3696        # sizer_radiobutton.Add(self.struct_rbutton)
3697        # sizer_radiobutton.Add((5,5))
3698        sizer_radiobutton.Add(self.model_help, 1, wx.RIGHT | wx.LEFT, 5)
3699        # sizer_radiobutton.Add((5,5))
3700        sizer_radiobutton.Add(self.model_func, 1, wx.RIGHT, 5)
3701        sizer_cat.Add(sizer_cat_box, 1, wx.LEFT, 2.5)
3702        sizer_cat.Add(sizer_radiobutton)
3703        sizer_selection = wx.BoxSizer(wx.HORIZONTAL)
3704        mutifactor_selection = wx.BoxSizer(wx.HORIZONTAL)
3705
3706        self.text1 = wx.StaticText(self, wx.ID_ANY, "")
3707        self.text2 = wx.StaticText(self, wx.ID_ANY, "P(Q)*S(Q)")
3708        self.mutifactor_text = wx.StaticText(self, wx.ID_ANY, "No. of Shells: ")
3709        self.mutifactor_text1 = wx.StaticText(self, wx.ID_ANY, "")
3710        self.show_sld_button = wx.Button(self, wx.ID_ANY, "Show SLD Profile")
3711        self.show_sld_button.Bind(wx.EVT_BUTTON, self._on_show_sld)
3712
3713        self.formfactorbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
3714        self.formfactorbox.SetToolTip(wx.ToolTip("Select a Model"))
3715        if self.model is not None:
3716            self.formfactorbox.SetValue(self.model.name)
3717        self.structurebox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
3718        self.multifactorbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
3719        self.initialize_combox()
3720        wx.EVT_COMBOBOX(self.formfactorbox, wx.ID_ANY, self._on_select_model)
3721
3722        wx.EVT_COMBOBOX(self.structurebox, wx.ID_ANY, self._on_select_model)
3723        wx.EVT_COMBOBOX(self.multifactorbox, wx.ID_ANY, self._on_select_model)
3724        # check model type to show sizer
3725        if self.model is not None:
3726            print("_set_model_sizer_selection: disabled.")
3727            # self._set_model_sizer_selection(self.model)
3728
3729        sizer_selection.Add(self.text1)
3730        sizer_selection.Add((10, 5))
3731        sizer_selection.Add(self.formfactorbox)
3732        sizer_selection.Add((5, 5))
3733        sizer_selection.Add(self.text2)
3734        sizer_selection.Add((5, 5))
3735        sizer_selection.Add(self.structurebox)
3736
3737        mutifactor_selection.Add((13, 5))
3738        mutifactor_selection.Add(self.mutifactor_text)
3739        mutifactor_selection.Add(self.multifactorbox)
3740        mutifactor_selection.Add((5, 5))
3741        mutifactor_selection.Add(self.mutifactor_text1)
3742        mutifactor_selection.Add((10, 5))
3743        mutifactor_selection.Add(self.show_sld_button)
3744
3745        boxsizer1.Add(sizer_cat)
3746        boxsizer1.Add((10, 10))
3747        boxsizer1.Add(sizer_selection)
3748        boxsizer1.Add((10, 10))
3749        boxsizer1.Add(mutifactor_selection)
3750
3751        self._set_multfactor_combobox()
3752        self.multifactorbox.SetSelection(1)
3753        self.show_sld_button.Hide()
3754        sizer.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)
3755        sizer.Layout()
3756
3757    def on_smear_helper(self, update=False):
3758        """
3759        Help for onSmear if implemented
3760
3761        :param update: force or not to update
3762        """
3763    def reset_page(self, state, first=False):
3764        """
3765        reset the state  if implemented
3766        """
3767    def onSmear(self, event):
3768        """
3769        Create a smear object if implemented
3770        """
3771    def onPinholeSmear(self, event):
3772        """
3773        Create a custom pinhole smear object if implemented
3774        """
3775    def onSlitSmear(self, event):
3776        """
3777        Create a custom slit smear object if implemented
3778        """
3779    def update_slit_smear(self):
3780        """
3781        called by kill_focus on pinhole TextCntrl
3782        to update the changes if implemented
3783        """
3784    def select_param(self, event):
3785        """
3786        Select TextCtrl  checked if implemented
3787        """
3788    def set_data(self, data=None):
3789        """
3790        Sets data if implemented
3791        """
3792    def _is_2D(self):
3793        """
3794        Check if data_name is Data2D if implemented
3795        """
3796    def _on_select_model(self, event=None):
3797        """
3798        call back for model selection if implemented
3799        """
3800    def get_weight_flag(self):
3801        """
3802        Get flag corresponding to a given weighting dI data if implemented
3803        """
3804    def _set_sizer_dispersion(self):
3805        """
3806        draw sizer for dispersity if implemented
3807        """
3808    def get_all_checked_params(self):
3809        """
3810        Found all parameters current check and add them to list of parameters
3811        to fit if implemented
3812        """
3813    def show_npts2fit(self):
3814        """
3815        setValue Npts for fitting if implemented
3816        """
3817    def _onModel2D(self, event):
3818        """
3819        toggle view of model from 1D to 2D  or 2D from 1D if implemented
3820        """
3821
3822
3823class ModelTextCtrl(wx.TextCtrl):
3824    """
3825    Text control for model and fit parameters.
3826    Binds the appropriate events for user interactions.
3827    Default callback methods can be overwritten on initialization
3828
3829    :param kill_focus_callback: callback method for EVT_KILL_FOCUS event
3830    :param set_focus_callback:  callback method for EVT_SET_FOCUS event
3831    :param mouse_up_callback:   callback method for EVT_LEFT_UP event
3832    :param text_enter_callback: callback method for EVT_TEXT_ENTER event
3833
3834    """
3835    # Set to True when the mouse is clicked while whole string is selected
3836    full_selection = False
3837    # Call back for EVT_SET_FOCUS events
3838    _on_set_focus_callback = None
3839
3840    def __init__(self, parent, id=-1,
3841                 value=wx.EmptyString,
3842                 pos=wx.DefaultPosition,
3843                 size=wx.DefaultSize,
3844                 style=0,
3845                 validator=wx.DefaultValidator,
3846                 name=wx.TextCtrlNameStr,
3847                 kill_focus_callback=None,
3848                 set_focus_callback=None,
3849                 mouse_up_callback=None,
3850                 text_enter_callback=None):
3851
3852        wx.TextCtrl.__init__(self, parent, id, value, pos,
3853                             size, style, validator, name)
3854
3855        # Bind appropriate events
3856        self._on_set_focus_callback = parent.onSetFocus \
3857            if set_focus_callback is None else set_focus_callback
3858        self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus)
3859        self.Bind(wx.EVT_KILL_FOCUS, self._silent_kill_focus
3860                  if kill_focus_callback is None else kill_focus_callback)
3861        self.Bind(wx.EVT_TEXT_ENTER, parent._onparamEnter
3862                  if text_enter_callback is None else text_enter_callback)
3863        if not ON_MAC:
3864            self.Bind(wx.EVT_LEFT_UP, self._highlight_text
3865                      if mouse_up_callback is None else mouse_up_callback)
3866
3867    def _on_set_focus(self, event):
3868        """
3869        Catch when the text control is set in focus to highlight the whole
3870        text if necessary
3871
3872        :param event: mouse event
3873
3874        """
3875        event.Skip()
3876        self.full_selection = True
3877        return self._on_set_focus_callback(event)
3878
3879    def _highlight_text(self, event):
3880        """
3881        Highlight text of a TextCtrl only of no text has be selected
3882
3883        :param event: mouse event
3884
3885        """
3886        # Make sure the mouse event is available to other listeners
3887        event.Skip()
3888        control = event.GetEventObject()
3889        if self.full_selection:
3890            self.full_selection = False
3891            # Check that we have a TextCtrl
3892            if issubclass(control.__class__, wx.TextCtrl):
3893                # Check whether text has been selected,
3894                # if not, select the whole string
3895                (start, end) = control.GetSelection()
3896                if start == end:
3897                    control.SetSelection(-1, -1)
3898
3899    def _silent_kill_focus(self, event):
3900        """
3901        Save the state of the page
3902        """
3903
3904        event.Skip()
3905        # pass
Note: See TracBrowser for help on using the repository browser.