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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249unittest-saveload
Last change on this file since 44e8f48 was fa412df, checked in by krzywon, 6 years ago

Simplify calling image handler and add documentation.

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