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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249unittest-saveload
Last change on this file since 1176137 was 5818dae, checked in by wojciech, 6 years ago

Reverted save button as potential solution to the problem has been found

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