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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 53b8266 was 53b8266, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'master' into ticket-869

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