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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249unittest-saveload
Last change on this file since a4a1ac9 was a4a1ac9, checked in by GitHub <noreply@…>, 6 years ago

Merge pull request #172 from SasView?/ticket-1166

Fix for report generation issue. Refs #1166.

  • Property mode set to 100644
File size: 146.5 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
[b4398819]2780        documentation_window.py. It will load the top level of the html model
2781        help documenation sphinx generated if either a plugin model (which
2782        normally does not have an html help help file) is selected or if no
2783        model is selected. Otherwise, if a regula model is selected, the
2784        documention for that model will be sent to a browser window.
2785
2786        :todo the quick fix for no documentation in plugins is the if statment.
2787        However, the right way to do this would be to check whether the hmtl
2788        file exists and load the model docs if it does and the general docs if
2789        it doesn't - this will become important if we ever figure out how to
2790        build docs for plugins on the fly.  Sep 9, 2018 -PDB
[5ce7f17]2791
[c8e1996]2792        :param event: on Help Button pressed event
[5ce7f17]2793        """
2794
[b4398819]2795        if (self.model is not None) and (self.categorybox.GetValue()
2796                                         != "Plugin Models"):
[3db44fb]2797            name = self.formfactorbox.GetValue()
[58a8f76]2798            _TreeLocation = 'user/models/%s.html' % name
[6f16e25]2799            _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation,
[15fb4fa]2800                                              "", name + " Help")
[5ce7f17]2801        else:
[3bd677b]2802            _TreeLocation = 'user/sasgui/perspectives/fitting/models/index.html'
[6f16e25]2803            _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation,
2804                                              "", "General Model Help")
[5ce7f17]2805
[f0d720b]2806    def on_model_help_clicked(self, event):
2807        """
[5ce7f17]2808        Function called when 'Description' button is pressed next to model
2809        of interest.  This calls the Description embedded in the model. This
2810        should work with either Wx2.8 and lower or higher. If no model is
2811        selected it will give the message that a model must be chosen first
2812        in the box that would normally contain the description.  If a badly
2813        behaved model is encountered which has no description then it will
2814        give the message that none is available.
2815
[c8e1996]2816        :param event: on Description Button pressed event
[f0d720b]2817        """
[5ce7f17]2818
[c8e1996]2819        if self.model is None:
[5ce7f17]2820            name = 'index.html'
[f0d720b]2821        else:
2822            name = self.formfactorbox.GetValue()
[5ce7f17]2823
2824        msg = 'Model description:\n'
2825        info = "Info"
[c8e1996]2826        if self.model is not None:
2827            # frame.Destroy()
[5ce7f17]2828            if str(self.model.description).rstrip().lstrip() == '':
2829                msg += "Sorry, no information is available for this model."
[f0d720b]2830            else:
[5ce7f17]2831                msg += self.model.description + '\n'
2832            wx.MessageBox(msg, info)
2833        else:
2834            msg += "You must select a model to get information on this"
2835            wx.MessageBox(msg, info)
2836
[7116dffd]2837    def _on_mag_angle_help(self, event):
[5ce7f17]2838        """
[6aad2e8]2839        Bring up Magnetic Angle definition.png image whenever the ? button
[5ce7f17]2840        is clicked. Calls DocumentationWindow with the path of the location
2841        within the documentation tree (after /doc/ ....". When using old
2842        versions of Wx (i.e. before 2.9 and therefore not part of release
2843        versions distributed via installer) it brings up an image viewer
2844        box which allows the user to click through the rest of the images in
2845        the directory.  Not ideal but probably better than alternative which
2846        would bring up the entire discussion of how magnetic models work?
2847        Specially since it is not likely to be accessed.  The normal release
2848        versions bring up the normal image box.
2849
2850        :param evt: Triggers on clicking ? in Magnetic Angles? box
2851        """
2852
[6aad2e8]2853        _TreeLocation = "_images/M_angles_pic.png"
[6f16e25]2854        _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation, "",
[3db44fb]2855                                          "Magnetic Angle Defintions")
[f0d720b]2856
[7116dffd]2857    def _on_mag_help(self, event):
[f0d720b]2858        """
[6aad2e8]2859        Bring up Magnetic Angle definition.png image whenever the ? button
[7116dffd]2860        is clicked. Calls DocumentationWindow with the path of the location
2861        within the documentation tree (after /doc/ ....". When using old
2862        versions of Wx (i.e. before 2.9 and therefore not part of release
2863        versions distributed via installer) it brings up an image viewer
2864        box which allows the user to click through the rest of the images in
2865        the directory.  Not ideal but probably better than alternative which
2866        would bring up the entire discussion of how magnetic models work?
2867        Specially since it is not likely to be accessed.  The normal release
2868        versions bring up the normal image box.
2869
2870        :param evt: Triggers on clicking ? in Magnetic Angles? box
[f0d720b]2871        """
2872
[3bd677b]2873        _TreeLocation = "user/sasgui/perspectives/fitting/magnetism/magnetism.html"
[6f16e25]2874        _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation, "",
[7116dffd]2875                                          "Polarized Beam/Magnetc Help")
[f0d720b]2876
[5ce7f17]2877    def _on_mag_on(self, event):
[f0d720b]2878        """
2879        Magnetic Parameters ON/OFF
2880        """
2881        button = event.GetEventObject()
2882
2883        if button.GetLabel().count('ON') > 0:
2884            self.magnetic_on = True
2885            button.SetLabel("Magnetic OFF")
2886            m_value = 1.0e-06
2887            for key in self.model.magnetic_params:
2888                if key.count('M0') > 0:
2889                    self.model.setParam(key, m_value)
2890                    m_value += 0.5e-06
2891        else:
2892            self.magnetic_on = False
2893            button.SetLabel("Magnetic ON")
2894            for key in self.model.magnetic_params:
2895                if key.count('M0') > 0:
[c8e1996]2896                    # reset mag value to zero fo safety
[f0d720b]2897                    self.model.setParam(key, 0.0)
[5ce7f17]2898
2899        self.Show(False)
[f0d720b]2900        self.set_model_param_sizer(self.model)
[c8e1996]2901        # self._set_sizer_dispersion()
[f0d720b]2902        self.state.magnetic_on = self.magnetic_on
2903        self.SetupScrolling()
2904        self.Show(True)
[5ce7f17]2905
[f0d720b]2906    def on_pd_help_clicked(self, event):
2907        """
[5ce7f17]2908        Bring up Polydispersity Documentation whenever the ? button is clicked.
2909        Calls DocumentationWindow with the path of the location within the
2910        documentation tree (after /doc/ ....".  Note that when using old
2911        versions of Wx (before 2.9) and thus not the release version of
2912        istallers, the help comes up at the top level of the file as
2913        webbrowser does not pass anything past the # to the browser when it is
2914        running "file:///...."
2915
[c8e1996]2916        :param event: Triggers on clicking ? in polydispersity box
[5ce7f17]2917        """
[f0d720b]2918
[3bd677b]2919        _TreeLocation = "user/sasgui/perspectives/fitting/pd/polydispersity.html"
[7801df8]2920        _PageAnchor = ""
[6f16e25]2921        _doc_viewer = DocumentationWindow(self, wx.ID_ANY, _TreeLocation,
[3db44fb]2922                                          _PageAnchor, "Polydispersity Help")
[5ce7f17]2923
[f0d720b]2924    def on_left_down(self, event):
2925        """
2926        Get key stroke event
2927        """
2928        # Figuring out key combo: Cmd for copy, Alt for paste
2929        if event.CmdDown() and event.ShiftDown():
2930            self.get_paste()
2931        elif event.CmdDown():
2932            self.get_copy()
2933        else:
2934            event.Skip()
2935            return
2936        # make event free
2937        event.Skip()
[5ce7f17]2938
[f0d720b]2939    def get_copy(self):
2940        """
2941        Get copy params to clipboard
2942        """
2943        content = self.get_copy_params()
2944        flag = self.set_clipboard(content)
2945        self._copy_info(flag)
2946        return flag
[5ce7f17]2947
[f0d720b]2948    def get_copy_params(self):
2949        """
2950        Get the string copies of the param names and values in the tap
2951        """
2952        content = 'sasview_parameter_values:'
2953        # Do it if params exist
[c8e1996]2954        if self.parameters:
[5ce7f17]2955
[f0d720b]2956            # go through the parameters
2957            strings = self._get_copy_helper(self.parameters,
[ba8d326]2958                                            self.orientation_params)
[f0d720b]2959            content += strings
[5ce7f17]2960
[f0d720b]2961            # go through the fittables
2962            strings = self._get_copy_helper(self.fittable_param,
[ba8d326]2963                                            self.orientation_params_disp)
[f0d720b]2964            content += strings
2965
2966            # go through the fixed params
2967            strings = self._get_copy_helper(self.fixed_param,
[ba8d326]2968                                            self.orientation_params_disp)
[f0d720b]2969            content += strings
[5ce7f17]2970
[f0d720b]2971            # go through the str params
2972            strings = self._get_copy_helper(self.str_parameters,
[ba8d326]2973                                            self.orientation_params)
[f0d720b]2974            content += strings
2975            return content
2976        else:
2977            return False
2978
[b76e65a]2979
2980    def _get_copy_params_details(self):
2981        """
2982        Combines polydisperse parameters with self.parameters so that they can
2983        be written to the clipboard (for Excel or LaTeX). Also returns a list of
2984        the names of parameters that have been fitted
2985
[69363c7]2986        :returns: all_params - A list of all parameters, in the format of
[b76e65a]2987        self.parameters
2988        :returns: fitted_par_names - A list of the names of parameters that have
2989        been fitted
2990        """
2991        # Names of params that are being fitted
2992        fitted_par_names = [param[1] for param in self.param_toFit]
2993        # Names of params with associated polydispersity
2994        disp_params = [param[1].split('.')[0] for param in self.fittable_param]
2995
2996        # Create array of all parameters
2997        all_params = copy.copy(self.parameters)
2998        for param in self.parameters:
2999            if param[1] in disp_params:
3000                # Polydisperse params aren't in self.parameters, so need adding
3001                # to all_params
3002                name = param[1] + ".width"
3003                index = all_params.index(param) + 1
3004                to_insert = []
3005                if name in fitted_par_names:
3006                    # Param is fitted, so already has a param list in self.param_toFit
3007                    to_insert = self.param_toFit[fitted_par_names.index(name)]
3008                else:
3009                    # Param isn't fitted, so mockup a param list
3010                    to_insert = [None, name, self.model.getParam(name), None, None]
3011                all_params.insert(index, to_insert)
3012        return all_params, fitted_par_names
3013
[f0d720b]3014    def get_copy_excel(self):
3015        """
3016        Get copy params to clipboard
3017        """
3018        content = self.get_copy_params_excel()
3019        flag = self.set_clipboard(content)
3020        self._copy_info(flag)
3021        return flag
3022
3023    def get_copy_params_excel(self):
3024        """
3025        Get the string copies of the param names and values in the tap
3026        """
[b76e65a]3027        if not self.parameters:
3028            # Do nothing if parameters doesn't exist
3029            return False
[f0d720b]3030
[b76e65a]3031        content = ''
[f0d720b]3032        crlf = chr(13) + chr(10)
3033        tab = chr(9)
3034
[b76e65a]3035        all_params, fitted_param_names = self._get_copy_params_details()
[f0d720b]3036
[b76e65a]3037        # Construct row of parameter names
3038        for param in all_params:
3039            name = param[1] # Parameter name
3040            content += name
3041            content += tab
3042            if name in fitted_param_names:
3043                # Only print errors for fitted parameters
3044                content += name + "_err"
[f0d720b]3045                content += tab
3046
[b76e65a]3047        content += crlf
[f0d720b]3048
[b76e65a]3049        # Construct row of parameter values and errors
3050        for param in all_params:
3051            value = param[2]
3052            if hasattr(value, 'GetValue'):
3053                # param[2] is a text box
3054                value = value.GetValue()
3055            else:
3056                # param[2] is a float (from our self._get_copy_params_details)
3057                value = str(value)
3058            content += value
3059            content += tab
3060            if param[1] in fitted_param_names:
3061                # Only print errors for fitted parameters
3062                content += param[4].GetValue()
[5ce7f17]3063                content += tab
[f0d720b]3064
[b76e65a]3065        return content
[f0d720b]3066
3067    def get_copy_latex(self):
3068        """
3069        Get copy params to clipboard
3070        """
3071        content = self.get_copy_params_latex()
3072        flag = self.set_clipboard(content)
3073        self._copy_info(flag)
3074        return flag
3075
3076    def get_copy_params_latex(self):
3077        """
3078        Get the string copies of the param names and values in the tap
3079        """
[b76e65a]3080        if not self.parameters:
3081            # Do nothing if self.parameters doesn't exist
3082            return False
[69363c7]3083
[ba8d326]3084        content = r'\begin{table}'
3085        content += r'\begin{tabular}[h]'
[f0d720b]3086
3087        crlf = chr(13) + chr(10)
3088        tab = chr(9)
3089
[b76e65a]3090        all_params, fitted_param_names = self._get_copy_params_details()
[f0d720b]3091
[b76e65a]3092        content += '{|'
3093        for param in all_params:
3094            content += 'l|l|'
[69363c7]3095        content += r'}\hline'
[b76e65a]3096        content += crlf
[f0d720b]3097
[b76e65a]3098        # Construct row of parameter names
3099        for index, param in enumerate(all_params):
3100            name = param[1] # Parameter name
[69363c7]3101            content += name.replace('_', r'\_')  # Escape underscores
[b76e65a]3102            if name in fitted_param_names:
3103                # Only print errors for fitted parameters
[f0d720b]3104                content += ' & '
[69363c7]3105                content += name.replace('_', r'\_') + r"\_err"
[b76e65a]3106            if index < len(all_params) - 1:
[f0d720b]3107                content += ' & '
[b76e65a]3108
[69363c7]3109        content += r'\\ \hline'
[b76e65a]3110        content += crlf
3111
3112        # Construct row of values and errors
3113        for index, param in enumerate(all_params):
3114            value = param[2]
3115            if hasattr(value, "GetValue"):
3116                # value is a text box
3117                value = value.GetValue()
3118            else:
3119                # value is a float (from self._get_copy_params_details)
3120                value = str(value)
3121            content += value
3122            if param[1] in fitted_param_names:
3123                # Only print errors for fitted params
3124                content += ' & '
3125                content += param[4].GetValue()
3126            if index < len(all_params) - 1:
3127                content += ' & '
[69363c7]3128
3129        content += r'\\ \hline'
[b76e65a]3130        content += crlf
[69363c7]3131        content += r'\end{tabular}'
3132        content += r'\end{table}'
[b76e65a]3133
3134        return content
[f0d720b]3135
3136    def set_clipboard(self, content=None):
3137        """
3138        Put the string to the clipboard
3139        """
3140        if not content:
3141            return False
3142        if wx.TheClipboard.Open():
3143            wx.TheClipboard.SetData(wx.TextDataObject(str(content)))
3144            wx.TheClipboard.Close()
3145            return True
3146        return None
[5ce7f17]3147
[f0d720b]3148    def _get_copy_helper(self, param, orient_param):
3149        """
3150        Helping get value and name of the params
[5ce7f17]3151
[f0d720b]3152        : param param:  parameters
3153        : param orient_param = oritational params
3154        : return content: strings [list] [name,value:....]
3155        """
3156        content = ''
[5223602]3157        bound_hi = ''
3158        bound_lo = ''
[f0d720b]3159        # go through the str params
3160        for item in param:
3161            # copy only the params shown
3162            if not item[2].IsShown():
3163                continue
3164            disfunc = ''
3165            try:
3166                if item[7].__class__.__name__ == 'ComboBox':
3167                    disfunc = str(item[7].GetValue())
[7673ecd]3168            except Exception:
[c155a16]3169                logger.error(traceback.format_exc())
[5ce7f17]3170
[f0d720b]3171            # 2D
3172            if self.data.__class__.__name__ == "Data2D":
3173                try:
3174                    check = item[0].GetValue()
[7673ecd]3175                except Exception:
[f0d720b]3176                    check = None
3177                name = item[1]
3178                value = item[2].GetValue()
3179            # 1D
3180            else:
[c8e1996]3181                # for 1D all parameters except orientation
[f0d720b]3182                if not item[1] in orient_param:
3183                    try:
3184                        check = item[0].GetValue()
3185                    except:
3186                        check = None
3187                    name = item[1]
3188                    value = item[2].GetValue()
3189
[5223602]3190            # Bounds
3191            try:
3192                bound_lo = item[5].GetValue()
3193                bound_hi = item[6].GetValue()
3194            except Exception:
3195                # harmless - need to just pass
3196                pass
3197
[f0d720b]3198            # add to the content
3199            if disfunc != '':
[5ce7f17]3200
[f0d720b]3201                disfunc = ',' + disfunc
3202            # Need to support array func for copy/paste
3203            try:
3204                if disfunc.count('array') > 0:
3205                    disfunc += ','
3206                    for val in self.values[name]:
3207                        disfunc += ' ' + str(val)
3208                    disfunc += ','
3209                    for weight in self.weights[name]:
3210                        disfunc += ' ' + str(weight)
[7673ecd]3211            except Exception:
[c155a16]3212                logger.error(traceback.format_exc())
[c8e1996]3213            content += name + ',' + str(check) + ',' + value + disfunc + ',' + \
3214                       bound_lo + ',' + bound_hi + ':'
[f0d720b]3215
3216        return content
[5ce7f17]3217
[f0d720b]3218    def get_clipboard(self):
3219        """
3220        Get strings in the clipboard
3221        """
3222        text = ""
3223        # Get text from the clip board
3224        if wx.TheClipboard.Open():
3225            if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
3226                data = wx.TextDataObject()
3227                # get wx dataobject
3228                success = wx.TheClipboard.GetData(data)
3229                # get text
3230                if success:
3231                    text = data.GetText()
3232                else:
3233                    text = ''
3234            # close clipboard
3235            wx.TheClipboard.Close()
3236        return text
[5ce7f17]3237
[f0d720b]3238    def get_paste(self):
3239        """
3240        Paste params from the clipboard
3241        """
3242        text = self.get_clipboard()
3243        flag = self.get_paste_params(text)
3244        self._copy_info(flag)
3245        return flag
[5ce7f17]3246
[f0d720b]3247    def get_paste_params(self, text=''):
3248        """
3249        Get the string copies of the param names and values in the tap
3250        """
3251        context = {}
3252        # put the text into dictionary
3253        lines = text.split(':')
3254        if lines[0] != 'sasview_parameter_values':
3255            self._copy_info(False)
3256            return False
3257        for line in lines[1:-1]:
3258            if len(line) != 0:
3259                item = line.split(',')
3260                check = item[1]
3261                name = item[0]
3262                value = item[2]
3263                # Transfer the text to content[dictionary]
3264                context[name] = [check, value]
[5223602]3265
3266                # limits
3267                limit_lo = item[3]
3268                context[name].append(limit_lo)
3269                limit_hi = item[4]
3270                context[name].append(limit_hi)
3271
[f0d720b]3272            # ToDo: PlugIn this poly disp function for pasting
3273            try:
[5223602]3274                poly_func = item[5]
[f0d720b]3275                context[name].append(poly_func)
3276                try:
3277                    # take the vals and weights for  array
[5223602]3278                    array_values = item[6].split(' ')
3279                    array_weights = item[7].split(' ')
[f0d720b]3280                    val = [float(a_val) for a_val in array_values[1:]]
3281                    weit = [float(a_weit) for a_weit in array_weights[1:]]
[5ce7f17]3282
[f0d720b]3283                    context[name].append(val)
3284                    context[name].append(weit)
3285                except:
3286                    raise
3287            except:
3288                poly_func = ''
3289                context[name].append(poly_func)
3290
3291        # Do it if params exist
[c8e1996]3292        if self.parameters:
[f0d720b]3293            # go through the parameters
3294            self._get_paste_helper(self.parameters,
3295                                   self.orientation_params, context)
3296
3297            # go through the fittables
3298            self._get_paste_helper(self.fittable_param,
3299                                   self.orientation_params_disp,
3300                                   context)
3301
3302            # go through the fixed params
3303            self._get_paste_helper(self.fixed_param,
3304                                   self.orientation_params_disp, context)
[5ce7f17]3305
[f0d720b]3306            # go through the str params
3307            self._get_paste_helper(self.str_parameters,
3308                                   self.orientation_params, context)
[5ce7f17]3309
[f0d720b]3310            return True
3311        return None
[5ce7f17]3312
[f0d720b]3313    def _get_paste_helper(self, param, orient_param, content):
3314        """
3315        Helping set values of the params
[5ce7f17]3316
[f0d720b]3317        : param param:  parameters
3318        : param orient_param: oritational params
3319        : param content: dictionary [ name, value: name1.value1,...]
3320        """
3321        # go through the str params
3322        for item in param:
3323            # 2D
3324            if self.data.__class__.__name__ == "Data2D":
3325                name = item[1]
3326                if name in content.keys():
[5223602]3327                    values = content[name]
3328                    check = values[0]
3329                    pd = values[1]
3330
[f0d720b]3331                    if name.count('.') > 0:
[6c382da]3332                        # If this is parameter.width, then pd may be a floating
3333                        # point value or it may be an array distribution.
3334                        # Nothing to do for parameter.npts or parameter.nsigmas.
[f0d720b]3335                        try:
3336                            float(pd)
[6c382da]3337                            if name.endswith('.npts'):
3338                                pd = int(pd)
3339                        except Exception:
[c8e1996]3340                            # continue
[f0d720b]3341                            if not pd and pd != '':
3342                                continue
3343                    item[2].SetValue(str(pd))
3344                    if item in self.fixed_param and pd == '':
3345                        # Only array func has pd == '' case.
3346                        item[2].Enable(False)
[6c382da]3347                    else:
3348                        item[2].Enable(True)
[f0d720b]3349                    if item[2].__class__.__name__ == "ComboBox":
3350                        if content[name][1] in self.model.fun_list:
[ee6ab94]3351                            fun_val = self.model.fun_list.index(content[name][1])
[f0d720b]3352                            self.model.setParam(name, fun_val)
[5223602]3353                    try:
3354                        item[5].SetValue(str(values[-3]))
3355                        item[6].SetValue(str(values[-2]))
3356                    except Exception:
3357                        # passing as harmless non-update
3358                        pass
[5ce7f17]3359
[f0d720b]3360                    value = content[name][1:]
3361                    self._paste_poly_help(item, value)
3362                    if check == 'True':
3363                        is_true = True
3364                    elif check == 'False':
3365                        is_true = False
3366                    else:
3367                        is_true = None
[c8e1996]3368                    if is_true is not None:
[f0d720b]3369                        item[0].SetValue(is_true)
3370            # 1D
3371            else:
[c8e1996]3372                # for 1D all parameters except orientation
[f0d720b]3373                if not item[1] in orient_param:
3374                    name = item[1]
3375                    if name in content.keys():
3376                        check = content[name][0]
3377                        # Avoid changing combox content
3378                        value = content[name][1:]
3379                        pd = value[0]
3380                        if name.count('.') > 0:
[c8e1996]3381                            # If this is parameter.width, then pd may be a
3382                            # floating point value or it may be an array
3383                            # distribution. Nothing to do for parameter.npts or
3384                            # parameter.nsigmas.
[f0d720b]3385                            try:
3386                                pd = float(pd)
[6c382da]3387                                if name.endswith('.npts'):
3388                                    pd = int(pd)
[ba8d326]3389                            except Exception:
[c8e1996]3390                                # continue
[f0d720b]3391                                if not pd and pd != '':
3392                                    continue
3393                        item[2].SetValue(str(pd))
3394                        if item in self.fixed_param and pd == '':
3395                            # Only array func has pd == '' case.
3396                            item[2].Enable(False)
[6c382da]3397                        else:
3398                            item[2].Enable(True)
[f0d720b]3399                        if item[2].__class__.__name__ == "ComboBox":
3400                            if value[0] in self.model.fun_list:
[ee6ab94]3401                                fun_val = self.model.fun_list.index(value[0])
3402                                self.model.setParam(name, fun_val)
[f0d720b]3403                                # save state
[5223602]3404                        try:
3405                            item[5].SetValue(str(value[-3]))
3406                            item[6].SetValue(str(value[-2]))
3407                        except Exception:
3408                            # passing as harmless non-update
3409                            pass
3410
[f0d720b]3411                        self._paste_poly_help(item, value)
3412                        if check == 'True':
3413                            is_true = True
3414                        elif check == 'False':
3415                            is_true = False
3416                        else:
3417                            is_true = None
[c8e1996]3418                        if is_true is not None:
[f0d720b]3419                            item[0].SetValue(is_true)
[5ce7f17]3420
[01cfd13]3421        self.select_param(event=None)
3422        self.Refresh()
3423
[f0d720b]3424    def _paste_poly_help(self, item, value):
3425        """
3426        Helps get paste for poly function
[5ce7f17]3427
[6c382da]3428        *item* is the parameter name
3429
3430        *value* depends on which parameter is being processed, and whether it
3431        has array polydispersity.
3432
3433        For parameters without array polydispersity:
3434
3435            parameter => ['FLOAT', '']
3436            parameter.width => ['FLOAT', 'DISTRIBUTION', '']
3437            parameter.npts => ['FLOAT', '']
3438            parameter.nsigmas => ['FLOAT', '']
3439
3440        For parameters with array polydispersity:
3441
3442            parameter => ['FLOAT', '']
3443            parameter.width => ['FILENAME', 'array', [x1, ...], [w1, ...]]
3444            parameter.npts => ['FLOAT', '']
3445            parameter.nsigmas => ['FLOAT', '']
[f0d720b]3446        """
[6c382da]3447        # Do nothing if not setting polydispersity
[5223602]3448        if len(value[3]) == 0:
[6c382da]3449            return
[5ce7f17]3450
[6c382da]3451        try:
3452            name = item[7].Name
3453            param_name = name.split('.')[0]
3454            item[7].SetValue(value[1])
3455            selection = item[7].GetCurrentSelection()
3456            dispersity = item[7].GetClientData(selection)
3457            disp_model = dispersity()
3458
3459            if value[1] == 'array':
[9a5097c]3460                pd_vals = np.array(value[2])
3461                pd_weights = np.array(value[3])
[6c382da]3462                if len(pd_vals) == 0 or len(pd_vals) != len(pd_weights):
3463                    msg = ("bad array distribution parameters for %s"
3464                           % param_name)
3465                    raise ValueError(msg)
3466                self._set_disp_cb(True, item=item)
3467                self._set_array_disp_model(name=name,
3468                                           disp=disp_model,
3469                                           values=pd_vals,
3470                                           weights=pd_weights)
3471            else:
3472                self._set_disp_cb(False, item=item)
3473                self._disp_obj_dict[name] = disp_model
3474                self.model.set_dispersion(param_name, disp_model)
[ba8d326]3475                self.state.disp_obj_dict[name] = disp_model.type
[6c382da]3476                # TODO: It's not an array, why update values and weights?
3477                self.model._persistency_dict[param_name] = \
3478                    [self.values, self.weights]
3479                self.state.values = self.values
3480                self.state.weights = self.weights
[5ce7f17]3481
[6c382da]3482        except Exception:
[c155a16]3483            logger.error(traceback.format_exc())
[9c3d784]3484            print("Error in BasePage._paste_poly_help: %s" % \
3485                  sys.exc_info()[1])
[6c382da]3486
3487    def _set_disp_cb(self, isarray, item):
[f0d720b]3488        """
3489        Set cb for array disp
3490        """
[6c382da]3491        if isarray:
3492            item[0].SetValue(False)
3493            item[0].Enable(False)
3494            item[2].Enable(False)
3495            item[3].Show(False)
3496            item[4].Show(False)
3497            item[5].SetValue('')
3498            item[5].Enable(False)
3499            item[6].SetValue('')
3500            item[6].Enable(False)
3501        else:
3502            item[0].Enable()
3503            item[2].Enable()
3504            item[3].Show(True)
3505            item[4].Show(True)
3506            item[5].Enable()
3507            item[6].Enable()
[5ce7f17]3508
[f0d720b]3509    def update_pinhole_smear(self):
3510        """
3511            Method to be called by sub-classes
3512            Moveit; This method doesn't belong here
3513        """
[9c3d784]3514        print("BasicPage.update_pinhole_smear was called: skipping")
[f0d720b]3515        return
3516
3517    def _read_category_info(self):
3518        """
3519        Reads the categories in from file
3520        """
3521        # # ILL mod starts here - July 2012 kieranrcampbell@gmail.com
3522        self.master_category_dict = defaultdict(list)
3523        self.by_model_dict = defaultdict(list)
3524        self.model_enabled_dict = defaultdict(bool)
[212bfc2]3525        categorization_file = CategoryInstaller.get_user_file()
3526        with open(categorization_file, 'rb') as f:
3527            self.master_category_dict = json.load(f)
3528        self._regenerate_model_dict()
[f0d720b]3529
3530    def _regenerate_model_dict(self):
3531        """
[5ce7f17]3532        regenerates self.by_model_dict which has each model name as the
[f0d720b]3533        key and the list of categories belonging to that model
3534        along with the enabled mapping
3535        """
3536        self.by_model_dict = defaultdict(list)
3537        for category in self.master_category_dict:
3538            for (model, enabled) in self.master_category_dict[category]:
3539                self.by_model_dict[model].append(category)
3540                self.model_enabled_dict[model] = enabled
[5ce7f17]3541
[f0d720b]3542    def _populate_listbox(self):
3543        """
3544        fills out the category list box
3545        """
[e92a352]3546        uncat_str = 'Plugin Models'
[f0d720b]3547        self._read_category_info()
3548
3549        self.categorybox.Clear()
3550        cat_list = sorted(self.master_category_dict.keys())
[c8e1996]3551        if uncat_str not in cat_list:
[f0d720b]3552            cat_list.append(uncat_str)
[5ce7f17]3553
[f0d720b]3554        for category in cat_list:
3555            if category != '':
3556                self.categorybox.Append(category)
3557
3558        if self.categorybox.GetSelection() == wx.NOT_FOUND:
3559            self.categorybox.SetSelection(0)
3560        else:
[c8e1996]3561            self.categorybox.SetSelection(
[f0d720b]3562                self.categorybox.GetSelection())
[c8e1996]3563        # self._on_change_cat(None)
[f0d720b]3564
3565    def _on_change_cat(self, event):
3566        """
3567        Callback for category change action
3568        """
3569        self.model_name = None
3570        category = self.categorybox.GetStringSelection()
[c8e1996]3571        if category is None:
[f0d720b]3572            return
3573        self.model_box.Clear()
3574
[277257f]3575        if category == CUSTOM_MODEL:
[f0d720b]3576            for model in self.model_list_box[category]:
3577                str_m = str(model).split(".")[0]
3578                self.model_box.Append(str_m)
3579
3580        else:
[ba8d326]3581            for model, enabled in sorted(self.master_category_dict[category],
3582                                         key=lambda name: name[0]):
3583                if enabled:
[f0d720b]3584                    self.model_box.Append(model)
3585
3586    def _fill_model_sizer(self, sizer):
3587        """
3588        fill sizer containing model info
3589        """
[6f16e25]3590        # This should only be called once per fit tab
[c8e1996]3591        # print "==== Entering _fill_model_sizer"
3592        # Add model function Details button in fitpanel.
3593        # The following 3 lines are for Mac. Let JHC know before modifying...
[f0d720b]3594        title = "Model"
3595        self.formfactorbox = None
3596        self.multifactorbox = None
[6f16e25]3597        self.mbox_description = wx.StaticBox(self, wx.ID_ANY, str(title))
[f0d720b]3598        boxsizer1 = wx.StaticBoxSizer(self.mbox_description, wx.VERTICAL)
3599        sizer_cat = wx.BoxSizer(wx.HORIZONTAL)
3600        self.mbox_description.SetForegroundColour(wx.RED)
[6f16e25]3601        wx_id = self._ids.next()
3602        self.model_func = wx.Button(self, wx_id, 'Help', size=(80, 23))
3603        self.model_func.Bind(wx.EVT_BUTTON, self.on_function_help_clicked,
3604                             id=wx_id)
[5ce7f17]3605        self.model_func.SetToolTipString("Full Model Function Help")
[6f16e25]3606        wx_id = self._ids.next()
3607        self.model_help = wx.Button(self, wx_id, 'Description', size=(80, 23))
3608        self.model_help.Bind(wx.EVT_BUTTON, self.on_model_help_clicked,
3609                             id=wx_id)
[5ce7f17]3610        self.model_help.SetToolTipString("Short Model Function Description")
[6f16e25]3611        wx_id = self._ids.next()
3612        self.model_view = wx.Button(self, wx_id, "Show 2D", size=(80, 23))
3613        self.model_view.Bind(wx.EVT_BUTTON, self._onModel2D, id=wx_id)
[f0d720b]3614        hint = "toggle view of model from 1D to 2D  or 2D to 1D"
3615        self.model_view.SetToolTipString(hint)
[5ce7f17]3616
[6f16e25]3617        cat_set_box = wx.StaticBox(self, wx.ID_ANY, 'Category')
[f0d720b]3618        sizer_cat_box = wx.StaticBoxSizer(cat_set_box, wx.HORIZONTAL)
3619        sizer_cat_box.SetMinSize((200, 50))
[6f16e25]3620        self.categorybox = wx.ComboBox(self, wx.ID_ANY,
3621                                       style=wx.CB_READONLY)
[5ce7f17]3622        self.categorybox.SetToolTip(wx.ToolTip("Select a Category/Type"))
[f0d720b]3623        self._populate_listbox()
[6f16e25]3624        wx.EVT_COMBOBOX(self.categorybox, wx.ID_ANY, self._show_combox)
[c8e1996]3625        # self.shape_rbutton = wx.RadioButton(self, wx.ID_ANY, 'Shapes',
[f0d720b]3626        #                                     style=wx.RB_GROUP)
[c8e1996]3627        # self.shape_indep_rbutton = wx.RadioButton(self, wx.ID_ANY,
[f0d720b]3628        #                                          "Shape-Independent")
[c8e1996]3629        # self.struct_rbutton = wx.RadioButton(self, wx.ID_ANY,
[6f16e25]3630        #                                     "Structure Factor ")
[c8e1996]3631        # self.plugin_rbutton = wx.RadioButton(self, wx.ID_ANY,
[6f16e25]3632        #                                     "Uncategorized")
[5ce7f17]3633
[c8e1996]3634        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
[f0d720b]3635        #                   id=self.shape_rbutton.GetId())
[c8e1996]3636        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
[f0d720b]3637        #                    id=self.shape_indep_rbutton.GetId())
[c8e1996]3638        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
[f0d720b]3639        #                    id=self.struct_rbutton.GetId())
[c8e1996]3640        # self.Bind(wx.EVT_RADIOBUTTON, self._show_combox,
[f0d720b]3641        #                    id=self.plugin_rbutton.GetId())
[c8e1996]3642        # MAC needs SetValue
[5ce7f17]3643
[6f16e25]3644        show_cat_button = wx.Button(self, wx.ID_ANY, "Modify")
[f0d720b]3645        cat_tip = "Modify model categories \n"
3646        cat_tip += "(also accessible from the menu bar)."
[c8e1996]3647        show_cat_button.SetToolTip(wx.ToolTip(cat_tip))
[f0d720b]3648        show_cat_button.Bind(wx.EVT_BUTTON, self._on_modify_cat)
3649        sizer_cat_box.Add(self.categorybox, 1, wx.RIGHT, 3)
[c8e1996]3650        sizer_cat_box.Add((10, 10))
[f0d720b]3651        sizer_cat_box.Add(show_cat_button)
[c8e1996]3652        # self.shape_rbutton.SetValue(True)
[bac3988]3653
[f0d720b]3654        sizer_radiobutton = wx.GridSizer(2, 2, 5, 5)
[c8e1996]3655        # sizer_radiobutton.Add(self.shape_rbutton)
3656        # sizer_radiobutton.Add(self.shape_indep_rbutton)
3657        sizer_radiobutton.Add((5, 5))
[5ce7f17]3658        sizer_radiobutton.Add(self.model_view, 1, wx.RIGHT, 5)
[c8e1996]3659        # sizer_radiobutton.Add(self.plugin_rbutton)
3660        # sizer_radiobutton.Add(self.struct_rbutton)
3661        # sizer_radiobutton.Add((5,5))
[5ce7f17]3662        sizer_radiobutton.Add(self.model_help, 1, wx.RIGHT | wx.LEFT, 5)
[c8e1996]3663        # sizer_radiobutton.Add((5,5))
[5ce7f17]3664        sizer_radiobutton.Add(self.model_func, 1, wx.RIGHT, 5)
[f0d720b]3665        sizer_cat.Add(sizer_cat_box, 1, wx.LEFT, 2.5)
3666        sizer_cat.Add(sizer_radiobutton)
3667        sizer_selection = wx.BoxSizer(wx.HORIZONTAL)
3668        mutifactor_selection = wx.BoxSizer(wx.HORIZONTAL)
[5ce7f17]3669
[6f16e25]3670        self.text1 = wx.StaticText(self, wx.ID_ANY, "")
3671        self.text2 = wx.StaticText(self, wx.ID_ANY, "P(Q)*S(Q)")
3672        self.mutifactor_text = wx.StaticText(self, wx.ID_ANY, "No. of Shells: ")
3673        self.mutifactor_text1 = wx.StaticText(self, wx.ID_ANY, "")
3674        self.show_sld_button = wx.Button(self, wx.ID_ANY, "Show SLD Profile")
[f0d720b]3675        self.show_sld_button.Bind(wx.EVT_BUTTON, self._on_show_sld)
3676
[6f16e25]3677        self.formfactorbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
[5ce7f17]3678        self.formfactorbox.SetToolTip(wx.ToolTip("Select a Model"))
[c8e1996]3679        if self.model is not None:
[f0d720b]3680            self.formfactorbox.SetValue(self.model.name)
[6f16e25]3681        self.structurebox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
3682        self.multifactorbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
[f0d720b]3683        self.initialize_combox()
[6f16e25]3684        wx.EVT_COMBOBOX(self.formfactorbox, wx.ID_ANY, self._on_select_model)
[f0d720b]3685
[6f16e25]3686        wx.EVT_COMBOBOX(self.structurebox, wx.ID_ANY, self._on_select_model)
3687        wx.EVT_COMBOBOX(self.multifactorbox, wx.ID_ANY, self._on_select_model)
[c8e1996]3688        # check model type to show sizer
3689        if self.model is not None:
[9c3d784]3690            print("_set_model_sizer_selection: disabled.")
[c8e1996]3691            # self._set_model_sizer_selection(self.model)
[5ce7f17]3692
[f0d720b]3693        sizer_selection.Add(self.text1)
3694        sizer_selection.Add((10, 5))
3695        sizer_selection.Add(self.formfactorbox)
3696        sizer_selection.Add((5, 5))
3697        sizer_selection.Add(self.text2)
3698        sizer_selection.Add((5, 5))
3699        sizer_selection.Add(self.structurebox)
[5ce7f17]3700
[f0d720b]3701        mutifactor_selection.Add((13, 5))
3702        mutifactor_selection.Add(self.mutifactor_text)
3703        mutifactor_selection.Add(self.multifactorbox)
3704        mutifactor_selection.Add((5, 5))
3705        mutifactor_selection.Add(self.mutifactor_text1)
3706        mutifactor_selection.Add((10, 5))
3707        mutifactor_selection.Add(self.show_sld_button)
3708
3709        boxsizer1.Add(sizer_cat)
3710        boxsizer1.Add((10, 10))
3711        boxsizer1.Add(sizer_selection)
3712        boxsizer1.Add((10, 10))
3713        boxsizer1.Add(mutifactor_selection)
[5ce7f17]3714
[f0d720b]3715        self._set_multfactor_combobox()
3716        self.multifactorbox.SetSelection(1)
3717        self.show_sld_button.Hide()
3718        sizer.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)
3719        sizer.Layout()
[5ce7f17]3720
[f0d720b]3721    def on_smear_helper(self, update=False):
3722        """
3723        Help for onSmear if implemented
[5ce7f17]3724
[f0d720b]3725        :param update: force or not to update
3726        """
3727    def reset_page(self, state, first=False):
3728        """
3729        reset the state  if implemented
3730        """
3731    def onSmear(self, event):
3732        """
[5ce7f17]3733        Create a smear object if implemented
[f0d720b]3734        """
3735    def onPinholeSmear(self, event):
3736        """
3737        Create a custom pinhole smear object if implemented
3738        """
3739    def onSlitSmear(self, event):
3740        """
3741        Create a custom slit smear object if implemented
3742        """
3743    def update_slit_smear(self):
3744        """
3745        called by kill_focus on pinhole TextCntrl
3746        to update the changes if implemented
3747        """
3748    def select_param(self, event):
3749        """
3750        Select TextCtrl  checked if implemented
3751        """
3752    def set_data(self, data=None):
3753        """
3754        Sets data if implemented
3755        """
3756    def _is_2D(self):
3757        """
3758        Check if data_name is Data2D if implemented
3759        """
3760    def _on_select_model(self, event=None):
3761        """
3762        call back for model selection if implemented
3763        """
3764    def get_weight_flag(self):
3765        """
3766        Get flag corresponding to a given weighting dI data if implemented
3767        """
3768    def _set_sizer_dispersion(self):
3769        """
3770        draw sizer for dispersity if implemented
3771        """
3772    def get_all_checked_params(self):
3773        """
3774        Found all parameters current check and add them to list of parameters
3775        to fit if implemented
3776        """
3777    def show_npts2fit(self):
3778        """
3779        setValue Npts for fitting if implemented
3780        """
3781    def _onModel2D(self, event):
3782        """
3783        toggle view of model from 1D to 2D  or 2D from 1D if implemented
3784        """
[373d4ee]3785
[c8e1996]3786
[373d4ee]3787class ModelTextCtrl(wx.TextCtrl):
3788    """
3789    Text control for model and fit parameters.
3790    Binds the appropriate events for user interactions.
3791    Default callback methods can be overwritten on initialization
3792
3793    :param kill_focus_callback: callback method for EVT_KILL_FOCUS event
3794    :param set_focus_callback:  callback method for EVT_SET_FOCUS event
3795    :param mouse_up_callback:   callback method for EVT_LEFT_UP event
3796    :param text_enter_callback: callback method for EVT_TEXT_ENTER event
3797
3798    """
[c8e1996]3799    # Set to True when the mouse is clicked while whole string is selected
[373d4ee]3800    full_selection = False
[c8e1996]3801    # Call back for EVT_SET_FOCUS events
[373d4ee]3802    _on_set_focus_callback = None
3803
3804    def __init__(self, parent, id=-1,
3805                 value=wx.EmptyString,
3806                 pos=wx.DefaultPosition,
3807                 size=wx.DefaultSize,
3808                 style=0,
3809                 validator=wx.DefaultValidator,
3810                 name=wx.TextCtrlNameStr,
3811                 kill_focus_callback=None,
3812                 set_focus_callback=None,
3813                 mouse_up_callback=None,
3814                 text_enter_callback=None):
3815
3816        wx.TextCtrl.__init__(self, parent, id, value, pos,
3817                             size, style, validator, name)
3818
3819        # Bind appropriate events
3820        self._on_set_focus_callback = parent.onSetFocus \
3821            if set_focus_callback is None else set_focus_callback
3822        self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus)
[c8e1996]3823        self.Bind(wx.EVT_KILL_FOCUS, self._silent_kill_focus
[ba8d326]3824                  if kill_focus_callback is None else kill_focus_callback)
[c8e1996]3825        self.Bind(wx.EVT_TEXT_ENTER, parent._onparamEnter
[ba8d326]3826                  if text_enter_callback is None else text_enter_callback)
[373d4ee]3827        if not ON_MAC:
[c8e1996]3828            self.Bind(wx.EVT_LEFT_UP, self._highlight_text
[ba8d326]3829                      if mouse_up_callback is None else mouse_up_callback)
[373d4ee]3830
3831    def _on_set_focus(self, event):
3832        """
3833        Catch when the text control is set in focus to highlight the whole
3834        text if necessary
3835
3836        :param event: mouse event
3837
3838        """
3839        event.Skip()
3840        self.full_selection = True
3841        return self._on_set_focus_callback(event)
3842
3843    def _highlight_text(self, event):
3844        """
3845        Highlight text of a TextCtrl only of no text has be selected
3846
3847        :param event: mouse event
3848
3849        """
3850        # Make sure the mouse event is available to other listeners
3851        event.Skip()
3852        control = event.GetEventObject()
3853        if self.full_selection:
3854            self.full_selection = False
3855            # Check that we have a TextCtrl
3856            if issubclass(control.__class__, wx.TextCtrl):
3857                # Check whether text has been selected,
3858                # if not, select the whole string
3859                (start, end) = control.GetSelection()
3860                if start == end:
3861                    control.SetSelection(-1, -1)
3862
3863    def _silent_kill_focus(self, event):
3864        """
3865        Save the state of the page
3866        """
3867
3868        event.Skip()
[9c9fae1]3869        # pass
Note: See TracBrowser for help on using the repository browser.