source: sasview/src/sas/perspectives/fitting/simfitpage.py @ d7b4decd

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d7b4decd was d7b4decd, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

fix constraint Remove button. Fixes #468. Refs #448.

  • Property mode set to 100644
File size: 36.2 KB
Line 
1"""
2    Simultaneous fit page
3"""
4import sys
5from collections import namedtuple
6
7import wx
8import wx.lib.newevent
9from wx.lib.scrolledpanel import ScrolledPanel
10
11from sas.guiframe.events import StatusEvent
12from sas.guiframe.panel_base import PanelBase
13from sas.guiframe.events import PanelOnFocusEvent
14from sas.guiframe.utils import IdList
15
16#Control panel width
17if sys.platform.count("darwin") == 0:
18    PANEL_WID = 420
19    FONT_VARIANT = 0
20else:
21    PANEL_WID = 490
22    FONT_VARIANT = 1
23
24
25# Each constraint requires five widgets and sizer.  Package them in
26# a named tuple for easy access.
27ConstraintLine = namedtuple('ConstraintLine',
28        'model_cbox param_cbox egal_txt constraint btRemove sizer')
29
30def get_fittableParam(model):
31    """
32    return list of fittable parameters name of a model
33
34    :param model: the model used
35
36    """
37    fittable_param = []
38    for item in model.getParamList():
39        if not item  in model.getDispParamList():
40            if not item in model.non_fittable:
41                fittable_param.append(item)
42
43    for item in model.fixed:
44        fittable_param.append(item)
45
46    return fittable_param
47
48class SimultaneousFitPage(ScrolledPanel, PanelBase):
49    """
50    Simultaneous fitting panel
51    All that needs to be defined are the
52    two data members window_name and window_caption
53    """
54    ## Internal name for the AUI manager
55    window_name = "simultaneous Fit page"
56    ## Title to appear on top of the window
57    window_caption = "Simultaneous Fit Page"
58    ID_SET_ALL = wx.NewId()
59    ID_FIT = wx.NewId()
60    ID_ADD = wx.NewId()
61    _id_pool = IdList()
62
63    def __init__(self, parent, page_finder={}, id=wx.ID_ANY, batch_on=False,
64                 *args, **kwargs):
65        ScrolledPanel.__init__(self, parent, id=id,
66                               style=wx.FULL_REPAINT_ON_RESIZE,
67                               *args, **kwargs)
68        PanelBase.__init__(self, parent)
69        """
70        Simultaneous page display
71        """
72        self._ids = iter(self._id_pool)
73        self.SetupScrolling()
74        ##Font size
75        self.SetWindowVariant(variant=FONT_VARIANT)
76        self.uid = wx.NewId()
77        self.parent = parent
78        self.batch_on = batch_on
79        ## store page_finder
80        self.page_finder = page_finder
81        ## list contaning info to set constraint
82        ## look like self.constraint_dict[page_id]= page
83        self.constraint_dict = {}
84        ## item list
85        # self.constraints_list=[combobox1, combobox2,=,textcrtl, button ]
86        self.constraints_list = []
87        ## list of current model
88        self.model_list = []
89        ## selected mdoel to fit
90        self.model_toFit = []
91        ## number of constraint
92        self.nb_constraint = 0
93        self.model_cbox_left = None
94        self.model_cbox_right = None
95        ## draw page
96        self.define_page_structure()
97        self.draw_page()
98        self.set_layout()
99        self._set_save_flag(False)
100
101    def define_page_structure(self):
102        """
103        Create empty sizer for a panel
104        """
105        self.vbox = wx.BoxSizer(wx.VERTICAL)
106        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
107        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
108        self.sizer3 = wx.BoxSizer(wx.VERTICAL)
109
110        self.sizer1.SetMinSize((PANEL_WID, -1))
111        self.sizer2.SetMinSize((PANEL_WID, -1))
112        self.sizer3.SetMinSize((PANEL_WID, -1))
113        self.vbox.Add(self.sizer1)
114        self.vbox.Add(self.sizer2)
115        self.vbox.Add(self.sizer3)
116
117    def set_scroll(self):
118        """
119        """
120        self.Layout()
121
122    def set_layout(self):
123        """
124        layout
125        """
126        self.vbox.Layout()
127        self.vbox.Fit(self)
128        self.SetSizer(self.vbox)
129        self.set_scroll()
130        self.Centre()
131
132    def onRemove(self, event):
133        """
134        Remove constraint fields
135        """
136        if len(self.constraints_list) == 1:
137            self.hide_constraint.SetValue(True)
138            self._hide_constraint()
139            return
140        if len(self.constraints_list) == 0:
141            return
142        wx.CallAfter(self._remove_after, event.GetId())
143        #self._onAdd_constraint(None)
144
145    def _remove_after(self, id):
146        for item in self.constraints_list:
147            if id == item.btRemove.GetId():
148                self.sizer_constraints.Hide(item.sizer)
149                item.sizer.Clear(True)
150                self.sizer_constraints.Remove(item.sizer)
151                ##self.SetScrollbars(20,20,25,65)
152                self.constraints_list.remove(item)
153                self.nb_constraint -= 1
154                self.sizer2.Layout()
155                self.Layout()
156                break
157
158    def onFit(self, event):
159        """
160        signal for fitting
161
162        """
163        flag = False
164        # check if the current page a simultaneous fit page or a batch page
165        if self == self._manager.sim_page:
166            flag = (self._manager.sim_page.uid == self.uid)
167
168        ## making sure all parameters content a constraint
169        if not self.batch_on and self.show_constraint.GetValue():
170            if not self._set_constraint():
171                return
172        ## model was actually selected from this page to be fit
173        if len(self.model_toFit) >= 1:
174            self.manager._reset_schedule_problem(value=0)
175            for item in self.model_list:
176                if item[0].GetValue():
177                    self.manager.schedule_for_fit(value=1, uid=item[2])
178            try:
179                if not self.manager.onFit(uid=self.uid):
180                    return
181            except:
182                msg = "Select at least one parameter to fit in the FitPages."
183                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
184        else:
185            msg = "Select at least one model check box to fit "
186            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
187
188    def set_manager(self, manager):
189        """
190        set panel manager
191
192        :param manager: instance of plugin fitting
193
194        """
195        self.manager = manager
196
197    def check_all_model_name(self, event=None):
198        """
199        check all models names
200        """
201        self.model_toFit = []
202        if self.cb1.GetValue() == True:
203            for item in self.model_list:
204                if item[0].IsEnabled():
205                    item[0].SetValue(True)
206                    self.model_toFit.append(item)
207
208            ## constraint info
209            self._store_model()
210            if not self.batch_on:
211                ## display constraint fields
212                if (self.show_constraint.GetValue() and
213                                 len(self.constraints_list) == 0):
214                    self._show_all_constraint()
215                    self._show_constraint()
216        else:
217            for item in self.model_list:
218                item[0].SetValue(False)
219
220            if not self.batch_on:
221                ##constraint info
222                self._hide_constraint()
223
224        self._update_easy_setup_cb()
225        self.Layout()
226        self.Refresh()
227
228    def check_model_name(self, event):
229        """
230        Save information related to checkbox and their states
231        """
232        self.model_toFit = []
233        cbox = event.GetEventObject()
234        for item in self.model_list:
235            if item[0].GetValue() == True:
236                self.model_toFit.append(item)
237            else:
238                if item in self.model_toFit:
239                    self.model_toFit.remove(item)
240                    self.cb1.SetValue(False)
241
242        ## display constraint fields
243        if len(self.model_toFit) >= 1:
244            self._store_model()
245            if not self.batch_on and self.show_constraint.GetValue() and\
246                             len(self.constraints_list) == 0:
247                self._show_all_constraint()
248                self._show_constraint()
249
250        elif len(self.model_toFit) < 1:
251            ##constraint info
252            self._hide_constraint()
253
254        self._update_easy_setup_cb()
255        ## set the value of the main check button
256        if len(self.model_list) == len(self.model_toFit):
257            self.cb1.SetValue(True)
258            self.Layout()
259            return
260        else:
261            self.cb1.SetValue(False)
262            self.Layout()
263
264    def _update_easy_setup_cb(self):
265        """
266        Update easy setup combobox on selecting a model
267        """
268        if self.model_cbox_left == None or self.model_cbox_right == None:
269            return
270
271        models = [(item[3].name, item[3]) for item in self.model_toFit]
272        setComboBoxItems(self.model_cbox_left, models)
273        setComboBoxItems(self.model_cbox_right, models)
274        for item in self.constraints_list:
275            setComboBoxItems(item[0], models)
276        if self.model_cbox_left.GetSelection() == wx.NOT_FOUND:
277            self.model_cbox_left.SetSelection(0)
278        self.sizer2.Layout()
279        self.sizer3.Layout()
280
281    def draw_page(self):
282        """
283        Draw a sizer containing couples of data and model
284        """
285        self.model_list = []
286        self.model_toFit = []
287        self.constraints_list = []
288        self.constraint_dict = {}
289        self.nb_constraint = 0
290        self.model_cbox_left = None
291        self.model_cbox_right = None
292
293        if len(self.model_list) > 0:
294            for item in self.model_list:
295                item[0].SetValue(False)
296                self.manager.schedule_for_fit(value=0, uid=item[2])
297
298        self.sizer1.Clear(True)
299        box_description = wx.StaticBox(self, wx.ID_ANY, "Fit Combinations")
300        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
301        sizer_title = wx.BoxSizer(wx.HORIZONTAL)
302        sizer_couples = wx.GridBagSizer(5, 5)
303        #------------------------------------------------------
304        if len(self.page_finder) == 0:
305            msg = " No fit combinations are found! \n\n"
306            msg += " Please load data and set up "
307            msg += "at least two fit panels first..."
308            sizer_title.Add(wx.StaticText(self, wx.ID_ANY, msg))
309        else:
310            ## store model
311            self._store_model()
312
313            self.cb1 = wx.CheckBox(self, wx.ID_ANY, 'Select all')
314            self.cb1.SetValue(False)
315
316            wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.check_all_model_name)
317
318            sizer_title.Add((10, 10), 0,
319                wx.TOP | wx.BOTTOM | wx.EXPAND | wx.ADJUST_MINSIZE, border=5)
320            sizer_title.Add(self.cb1, 0,
321                wx.TOP | wx.BOTTOM | wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, border=5)
322
323            ## draw list of model and data name
324            self._fill_sizer_model_list(sizer_couples)
325            ## draw the sizer containing constraint info
326            if not self.batch_on:
327                self._fill_sizer_constraint()
328            ## draw fit button
329            self._fill_sizer_fit()
330        #--------------------------------------------------------
331        boxsizer1.Add(sizer_title, flag=wx.TOP | wx.BOTTOM, border=5)
332        boxsizer1.Add(sizer_couples, 1, flag=wx.TOP | wx.BOTTOM, border=5)
333
334        self.sizer1.Add(boxsizer1, 1, wx.EXPAND | wx.ALL, 10)
335        self.sizer1.Layout()
336        #self.SetScrollbars(20,20,25,65)
337        self.AdjustScrollbars()
338        self.Layout()
339
340    def _store_model(self):
341        """
342         Store selected model
343        """
344        if len(self.model_toFit) < 1:
345            return
346        for item in self.model_toFit:
347            model = item[3]
348            page_id = item[2]
349            self.constraint_dict[page_id] = model
350
351    def _display_constraint(self, event):
352        """
353        Show fields to add constraint
354        """
355        if len(self.model_toFit) < 1:
356            msg = "Select at least 1 model to add constraint "
357            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
358            ## hide button
359            self._hide_constraint()
360            return
361        if self.show_constraint.GetValue():
362            self._show_all_constraint()
363            self._show_constraint()
364            self.Layout()
365            return
366        else:
367            self._hide_constraint()
368            self.Layout()
369            return
370
371    def _show_all_constraint(self):
372        """
373        Show constraint fields
374        """
375        box_description = wx.StaticBox(self, wx.ID_ANY, "Easy Setup ")
376        boxsizer = wx.StaticBoxSizer(box_description, wx.HORIZONTAL)
377        sizer_constraint = wx.BoxSizer(wx.HORIZONTAL)
378        self.model_cbox_left = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
379        self.model_cbox_left.Clear()
380        self.model_cbox_right = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
381        self.model_cbox_right.Clear()
382        wx.EVT_COMBOBOX(self.model_cbox_left, wx.ID_ANY, self._on_select_modelcb)
383        wx.EVT_COMBOBOX(self.model_cbox_right, wx.ID_ANY, self._on_select_modelcb)
384        egal_txt = wx.StaticText(self, wx.ID_ANY, " = ")
385        self.set_button = wx.Button(self, self.ID_SET_ALL, 'Set All')
386        self.set_button.Bind(wx.EVT_BUTTON, self._on_set_all_equal,
387                             id=self.set_button.GetId())
388        set_tip = "Add constraints for all the adjustable parameters "
389        set_tip += "(checked in FitPages) if exist."
390        self.set_button.SetToolTipString(set_tip)
391        self.set_button.Disable()
392
393        for id, model in self.constraint_dict.iteritems():
394            ## check if all parameters have been selected for constraint
395            ## then do not allow add constraint on parameters
396            self.model_cbox_left.Append(str(model.name), model)
397        self.model_cbox_left.Select(0)
398        for id, model in self.constraint_dict.iteritems():
399            ## check if all parameters have been selected for constraint
400            ## then do not allow add constraint on parameters
401            self.model_cbox_right.Append(str(model.name), model)
402        boxsizer.Add(self.model_cbox_left,
403                             flag=wx.RIGHT | wx.EXPAND, border=10)
404        #boxsizer.Add(wx.StaticText(self, wx.ID_ANY, ".parameters"),
405        #                     flag=wx.RIGHT | wx.EXPAND, border=5)
406        boxsizer.Add(egal_txt, flag=wx.RIGHT | wx.EXPAND, border=5)
407        boxsizer.Add(self.model_cbox_right,
408                             flag=wx.RIGHT | wx.EXPAND, border=10)
409        #boxsizer.Add(wx.StaticText(self, wx.ID_ANY, ".parameters"),
410        #                     flag=wx.RIGHT | wx.EXPAND, border=5)
411        boxsizer.Add((20, -1))
412        boxsizer.Add(self.set_button, flag=wx.RIGHT | wx.EXPAND, border=5)
413        sizer_constraint.Add(boxsizer, flag=wx.RIGHT | wx.EXPAND, border=5)
414        self.sizer_all_constraints.Insert(before=0,
415                             item=sizer_constraint,
416                             flag=wx.TOP | wx.BOTTOM | wx.EXPAND, border=5)
417
418        self.sizer_all_constraints.Layout()
419        self.sizer2.Layout()
420        #self.SetScrollbars(20,20,25,65)
421
422    def _on_select_modelcb(self, event):
423        """
424        On select model left or right combobox
425        """
426        event.Skip()
427        flag = True
428        if self.model_cbox_left.GetValue().strip() == '':
429            flag = False
430        if self.model_cbox_right.GetValue().strip() == '':
431            flag = False
432        if (self.model_cbox_left.GetValue() ==
433                self.model_cbox_right.GetValue()):
434            flag = False
435        self.set_button.Enable(flag)
436
437    def _on_set_all_equal(self, event):
438        """
439        On set button
440        """
441        event.Skip()
442        length = len(self.constraints_list)
443        if length < 1:
444            return
445        param_list = []
446        param_listB = []
447        selection = self.model_cbox_left.GetCurrentSelection()
448        model_left = self.model_cbox_left.GetValue()
449        model = self.model_cbox_left.GetClientData(selection)
450        selectionB = self.model_cbox_right.GetCurrentSelection()
451        model_right = self.model_cbox_right.GetValue()
452        modelB = self.model_cbox_right.GetClientData(selectionB)
453        for id, dic_model in self.constraint_dict.iteritems():
454            if model == dic_model:
455                param_list = self.page_finder[id].get_param2fit()
456            if modelB == dic_model:
457                param_listB = self.page_finder[id].get_param2fit()
458            if len(param_list) > 0 and len(param_listB) > 0:
459                break
460        num_cbox = 0
461        has_param = False
462        for param in param_list:
463            num_cbox += 1
464            if param in param_listB:
465                item = self.constraints_list[-1]
466                item.model_cbox.SetStringSelection(model_left)
467                self._on_select_model(None)
468                item.param_cbox.Clear()
469                item.param_cbox.Append(str(param), model)
470                item.param_cbox.SetStringSelection(str(param))
471                item.constraint.SetValue(str(model_right + "." + str(param)))
472                has_param = True
473                if num_cbox == (len(param_list) + 1):
474                    break
475                self._show_constraint()
476
477        self.sizer_constraints.Layout()
478        self.sizer2.Layout()
479        self.SetScrollbars(20, 20, 25, 65)
480        self.Layout()
481        if not has_param:
482            msg = " There is no adjustable parameter (checked to fit)"
483            msg += " either one of the models."
484            wx.PostEvent(self.parent.parent, StatusEvent(info="warning",
485                                                         status=msg))
486        else:
487            msg = " The constraints are added."
488            wx.PostEvent(self.parent.parent, StatusEvent(info="info",
489                                                         status=msg))
490
491    def _show_constraint(self):
492        """
493        Show constraint fields
494        """
495        self.btAdd.Show(True)
496        if len(self.constraints_list) != 0:
497            nb_fit_param = 0
498            for id, model in self.constraint_dict.iteritems():
499                nb_fit_param += len(self.page_finder[id].get_param2fit())
500            ##Don't add anymore
501            if len(self.constraints_list) == nb_fit_param:
502                msg = "Cannot add another constraint. Maximum of number "
503                msg += "Parameters name reached %s" % str(nb_fit_param)
504                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
505                self.sizer_constraints.Layout()
506                self.sizer2.Layout()
507                return
508        if len(self.model_toFit) < 1:
509            msg = "Select at least 1 model to add constraint "
510            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
511            self.sizer_constraints.Layout()
512            self.sizer2.Layout()
513            return
514
515        sizer_constraint = wx.BoxSizer(wx.HORIZONTAL)
516
517        # Model list
518        model_cbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
519        model_cbox.Clear()
520        for id, model in self.constraint_dict.iteritems():
521            ## check if all parameters have been selected for constraint
522            ## then do not allow add constraint on parameters
523            model_cbox.Append(str(model.name), model)
524        wx.EVT_COMBOBOX(model_cbox, wx.ID_ANY, self._on_select_model)
525
526        # Parameters in model
527        param_cbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY,
528                                 size=(100, -1))
529        param_cbox.Hide()
530        wx.EVT_COMBOBOX(param_cbox, wx.ID_ANY, self._on_select_param)
531
532        egal_txt = wx.StaticText(self, wx.ID_ANY, " = ")
533
534        # Parameter constraint
535        constraint = wx.TextCtrl(self, wx.ID_ANY)
536
537        # Remove button
538        #btRemove = wx.Button(self, self.ID_REMOVE, 'Remove')
539        btRemove = wx.Button(self, self._ids.next(), 'Remove')
540        btRemove.Bind(wx.EVT_BUTTON, self.onRemove,
541                      id=btRemove.GetId())
542        btRemove.SetToolTipString("Remove constraint.")
543        btRemove.Hide()
544
545        # Hid the add button, if it exists
546        if hasattr(self, "btAdd"):
547            self.btAdd.Hide()
548
549        sizer_constraint.Add((5, -1))
550        sizer_constraint.Add(model_cbox, flag=wx.RIGHT | wx.EXPAND, border=10)
551        sizer_constraint.Add(param_cbox, flag=wx.RIGHT | wx.EXPAND, border=5)
552        sizer_constraint.Add(egal_txt, flag=wx.RIGHT | wx.EXPAND, border=5)
553        sizer_constraint.Add(constraint, flag=wx.RIGHT | wx.EXPAND, border=10)
554        sizer_constraint.Add(btRemove, flag=wx.RIGHT | wx.EXPAND, border=10)
555
556        self.sizer_constraints.Insert(before=self.nb_constraint,
557                item=sizer_constraint, flag=wx.TOP | wx.BOTTOM | wx.EXPAND,
558                border=5)
559        c = ConstraintLine(model_cbox, param_cbox, egal_txt,
560                           constraint, btRemove, sizer_constraint)
561        self.constraints_list.append(c)
562
563        self.nb_constraint += 1
564        self.sizer_constraints.Layout()
565        self.sizer2.Layout()
566
567    def _hide_constraint(self):
568        """
569        hide buttons related constraint
570        """
571        for id in self.page_finder.iterkeys():
572            self.page_finder[id].clear_model_param()
573
574        self.nb_constraint = 0
575        self.constraint_dict = {}
576        if hasattr(self, "btAdd"):
577            self.btAdd.Hide()
578        self._store_model()
579        if self.model_cbox_left is not None:
580            self.model_cbox_left.Clear()
581            self.model_cbox_left = None
582        if self.model_cbox_right is not None:
583            self.model_cbox_right.Clear()
584            self.model_cbox_right = None
585        self.constraints_list = []
586        self.sizer_all_constraints.Clear(True)
587        self.sizer_all_constraints.Layout()
588        self.sizer_constraints.Clear(True)
589        self.sizer_constraints.Layout()
590        self.sizer2.Layout()
591
592    def _on_select_model(self, event):
593        """
594        fill combox box with list of parameters
595        """
596        if not self.constraints_list:
597            return
598
599        ##This way PC/MAC both work, instead of using event.GetClientData().
600        model_cbox = self.constraints_list[-1].model_cbox
601        n = model_cbox.GetCurrentSelection()
602        if n == wx.NOT_FOUND:
603            return
604
605        model = model_cbox.GetClientData(n)
606        param_list = []
607        for id, dic_model in self.constraint_dict.iteritems():
608            if model == dic_model:
609                param_list = self.page_finder[id].get_param2fit()
610                break
611
612        param_cbox = self.constraints_list[-1].param_cbox
613        param_cbox.Clear()
614        ## insert only fittable paramaters
615        for param in param_list:
616            param_cbox.Append(str(param), model)
617        param_cbox.Show(True)
618
619        btRemove = self.constraints_list[-1].btRemove
620        btRemove.Show(True)
621        self.btAdd.Show(True)
622        self.sizer2.Layout()
623
624    def _on_select_param(self, event):
625        """
626        Store the appropriate constraint in the page_finder
627        """
628        ##This way PC/MAC both work, instead of using event.GetClientData().
629        #n = self.param_cbox.GetCurrentSelection()
630        #model = self.param_cbox.GetClientData(n)
631        #param = event.GetString()
632
633        if self.constraints_list:
634            self.constraints_list[-1].egal_txt.Show(True)
635            self.constraints_list[-1].constraint.Show(True)
636
637    def _onAdd_constraint(self, event):
638        """
639        Add another line for constraint
640        """
641        if not self.show_constraint.GetValue():
642            msg = " Select Yes to add Constraint "
643            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
644            return
645        ## check that a constraint is added
646        # before allow to add another constraint
647        for item in self.constraints_list:
648            if item.model_cbox.GetString(0) == "":
649                msg = " Select a model Name! "
650                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
651                return
652            if item.param_cbox.GetString(0) == "":
653                msg = " Select a parameter Name! "
654                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
655                return
656            if item.constraint.GetValue().lstrip().rstrip() == "":
657                model = item.param_cbox.GetClientData(
658                                        item.param_cbox.GetCurrentSelection())
659                if model != None:
660                    msg = " Enter a constraint for %s.%s! " % (model.name,
661                                        item.param_cbox.GetString(0))
662                else:
663                    msg = " Enter a constraint"
664                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
665                return
666        ## some model or parameters can be constrained
667        self._show_constraint()
668        self.sizer3.Layout()
669        self.Layout()
670        self.Refresh()
671
672    def _fill_sizer_fit(self):
673        """
674        Draw fit button
675        """
676        self.sizer3.Clear(True)
677        box_description = wx.StaticBox(self, wx.ID_ANY, "Fit ")
678        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
679        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
680
681        self.btFit = wx.Button(self, self.ID_FIT, 'Fit', size=wx.DefaultSize)
682        self.btFit.Bind(wx.EVT_BUTTON, self.onFit, id=self.btFit.GetId())
683        self.btFit.SetToolTipString("Perform fit.")
684        if self.batch_on:
685            text = " Fit in Parallel all Data set and model selected.\n"
686        else:
687            text = " This page requires at least one FitPage with a data\n"
688            text = " and a model for fitting."
689        text_hint = wx.StaticText(self, wx.ID_ANY, text)
690
691        sizer_button.Add(text_hint, wx.RIGHT | wx.EXPAND, 10)
692        sizer_button.Add(self.btFit, 0, wx.LEFT | wx.ADJUST_MINSIZE, 10)
693
694        boxsizer1.Add(sizer_button, flag=wx.TOP | wx.BOTTOM, border=10)
695        self.sizer3.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)
696        self.sizer3.Layout()
697
698    def _fill_sizer_constraint(self):
699        """
700        Fill sizer containing constraint info
701        """
702        msg = "Select at least 2 model to add constraint "
703        wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
704
705        self.sizer2.Clear(True)
706        if self.batch_on:
707            if self.sizer2.IsShown():
708                self.sizer2.Show(False)
709            return
710        box_description = wx.StaticBox(self, wx.ID_ANY, "Fit Constraints")
711        boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)
712        sizer_title = wx.BoxSizer(wx.HORIZONTAL)
713        self.sizer_all_constraints = wx.BoxSizer(wx.HORIZONTAL)
714        self.sizer_constraints = wx.BoxSizer(wx.VERTICAL)
715        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
716
717        self.hide_constraint = wx.RadioButton(self, wx.ID_ANY, 'No', (10, 10),
718                                              style=wx.RB_GROUP)
719        self.show_constraint = wx.RadioButton(self, wx.ID_ANY, 'Yes', (10, 30))
720        self.Bind(wx.EVT_RADIOBUTTON, self._display_constraint,
721                  id=self.hide_constraint.GetId())
722        self.Bind(wx.EVT_RADIOBUTTON, self._display_constraint,
723                  id=self.show_constraint.GetId())
724        if self.batch_on:
725            self.hide_constraint.Enable(False)
726            self.show_constraint.Enable(False)
727        self.hide_constraint.SetValue(True)
728        self.show_constraint.SetValue(False)
729
730        sizer_title.Add(wx.StaticText(self, wx.ID_ANY, " Model"))
731        sizer_title.Add((10, 10))
732        sizer_title.Add(wx.StaticText(self, wx.ID_ANY, " Parameter"))
733        sizer_title.Add((10, 10))
734        sizer_title.Add(wx.StaticText(self, wx.ID_ANY, " Add Constraint?"))
735        sizer_title.Add((10, 10))
736        sizer_title.Add(self.show_constraint)
737        sizer_title.Add(self.hide_constraint)
738        sizer_title.Add((10, 10))
739
740        self.btAdd = wx.Button(self, self.ID_ADD, 'Add')
741        self.btAdd.Bind(wx.EVT_BUTTON, self._onAdd_constraint,
742                        id=self.btAdd.GetId())
743        self.btAdd.SetToolTipString("Add another constraint?")
744        self.btAdd.Hide()
745
746        text_hint = wx.StaticText(self, wx.ID_ANY,
747                                  "Example: [M0][paramter] = M1.parameter")
748        sizer_button.Add(text_hint, 0,
749                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
750        sizer_button.Add(self.btAdd, 0,
751                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
752
753        boxsizer1.Add(sizer_title, flag=wx.TOP | wx.BOTTOM, border=10)
754        boxsizer1.Add(self.sizer_all_constraints, flag=wx.TOP | wx.BOTTOM,
755                      border=10)
756        boxsizer1.Add(self.sizer_constraints, flag=wx.TOP | wx.BOTTOM,
757                      border=10)
758        boxsizer1.Add(sizer_button, flag=wx.TOP | wx.BOTTOM, border=10)
759
760        self.sizer2.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)
761        self.sizer2.Layout()
762
763        #self.SetScrollbars(20,20,25,65)
764
765    def _set_constraint(self):
766        """
767        get values from the constrainst textcrtl ,parses them into model name
768        parameter name and parameters values.
769        store them in a list self.params .when when params is not empty
770        set_model uses it to reset the appropriate model
771        and its appropriates parameters
772        """
773        for item in self.constraints_list:
774            select0 = item.model_cbox.GetSelection()
775            if select0 == wx.NOT_FOUND:
776                continue
777            model = item.model_cbox.GetClientData(select0)
778            select1 = item.param_cbox.GetSelection()
779            if select1 == wx.NOT_FOUND:
780                continue
781            param = item.param_cbox.GetString(select1)
782            constraint = item.constraint.GetValue().lstrip().rstrip()
783            if param.lstrip().rstrip() == "":
784                param = None
785                msg = " Constraint will be ignored!. missing parameters"
786                msg += " in combobox to set constraint! "
787                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
788            for id, value in self.constraint_dict.iteritems():
789                if model == value:
790                    if constraint == "":
791                        msg = " Constraint will be ignored!. missing value"
792                        msg += " in textcrtl to set constraint! "
793                        wx.PostEvent(self.parent.parent,
794                                     StatusEvent(status=msg))
795                        constraint = None
796                    if str(param) in self.page_finder[id].get_param2fit():
797                        msg = " Checking constraint for parameter: %s ", param
798                        wx.PostEvent(self.parent.parent,
799                                     StatusEvent(info="info", status=msg))
800                    else:
801                        model_name = item[0].GetLabel()
802                        fitpage = self.page_finder[id].get_fit_tab_caption()
803                        msg = "All constrainted parameters must be set "
804                        msg += " adjustable: '%s.%s' " % (model_name, param)
805                        msg += "is NOT checked in '%s'. " % fitpage
806                        msg += " Please check it to fit or"
807                        msg += " remove the line of the constraint."
808                        wx.PostEvent(self.parent.parent,
809                                StatusEvent(info="error", status=msg))
810                        return False
811
812                    for fid in self.page_finder[id].iterkeys():
813                        # wrap in param/constraint in str() to remove unicode
814                        self.page_finder[id].set_model_param(str(param),
815                                str(constraint), fid=fid)
816                    break
817        return True
818
819    def _fill_sizer_model_list(self, sizer):
820        """
821        Receive a dictionary containing information to display model name
822        """
823        ix = 0
824        iy = 0
825        list = []
826        sizer.Clear(True)
827
828        new_name = wx.StaticText(self, wx.ID_ANY, '  Model Title ',
829                                 style=wx.ALIGN_CENTER)
830        new_name.SetBackgroundColour('orange')
831        new_name.SetForegroundColour(wx.WHITE)
832        sizer.Add(new_name, (iy, ix), (1, 1),
833                            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
834        ix += 2
835        model_type = wx.StaticText(self, wx.ID_ANY, '  Model ')
836        model_type.SetBackgroundColour('grey')
837        model_type.SetForegroundColour(wx.WHITE)
838        sizer.Add(model_type, (iy, ix), (1, 1),
839                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
840        ix += 1
841        data_used = wx.StaticText(self, wx.ID_ANY, '  Data ')
842        data_used.SetBackgroundColour('grey')
843        data_used.SetForegroundColour(wx.WHITE)
844        sizer.Add(data_used, (iy, ix), (1, 1),
845                            wx.EXPAND | wx.ADJUST_MINSIZE, 0)
846        ix += 1
847        tab_used = wx.StaticText(self, wx.ID_ANY, '  FitPage ')
848        tab_used.SetBackgroundColour('grey')
849        tab_used.SetForegroundColour(wx.WHITE)
850        sizer.Add(tab_used, (iy, ix), (1, 1),
851                  wx.EXPAND | wx.ADJUST_MINSIZE, 0)
852        for id, value in self.page_finder.iteritems():
853            if id not in self.parent.opened_pages:
854                continue
855
856            if self.batch_on != self.parent.get_page_by_id(id).batch_on:
857                continue
858
859            data_list = []
860            model_list = []
861            # get data name and model objetta
862            for fitproblem in value.get_fit_problem():
863
864                data = fitproblem.get_fit_data()
865                if not data.is_data:
866                    continue
867                name = '-'
868                if data is not None and data.is_data:
869                    name = str(data.name)
870                data_list.append(name)
871
872                model = fitproblem.get_model()
873                if model is None:
874                    continue
875                model_list.append(model)
876
877            if len(model_list) == 0:
878                continue
879            # Draw sizer
880            ix = 0
881            iy += 1
882            model = model_list[0]
883            name = '_'
884            if model is not None:
885                name = str(model.name)
886            cb = wx.CheckBox(self, wx.ID_ANY, name)
887            cb.SetValue(False)
888            cb.Enable(model is not None and data.is_data)
889            sizer.Add(cb, (iy, ix), (1, 1),
890                      wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
891            wx.EVT_CHECKBOX(self, cb.GetId(), self.check_model_name)
892            ix += 2
893            model_type = wx.StaticText(self, wx.ID_ANY,
894                                       model.__class__.__name__)
895            sizer.Add(model_type, (iy, ix), (1, 1),
896                      wx.EXPAND | wx.ADJUST_MINSIZE, 0)
897            if self.batch_on:
898                data_used = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
899                data_used.AppendItems(data_list)
900                data_used.SetSelection(0)
901            else:
902                data_used = wx.StaticText(self, wx.ID_ANY, data_list[0])
903
904            ix += 1
905            sizer.Add(data_used, (iy, ix), (1, 1),
906                      wx.EXPAND | wx.ADJUST_MINSIZE, 0)
907            ix += 1
908            caption = value.get_fit_tab_caption()
909            tab_caption_used = wx.StaticText(self, wx.ID_ANY, str(caption))
910            sizer.Add(tab_caption_used, (iy, ix), (1, 1),
911                      wx.EXPAND | wx.ADJUST_MINSIZE, 0)
912
913            self.model_list.append([cb, value, id, model])
914
915        iy += 1
916        sizer.Add((20, 20), (iy, ix), (1, 1),
917                  wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
918        sizer.Layout()
919
920    def on_set_focus(self, event=None):
921        """
922        The  derivative class is on focus if implemented
923        """
924        if self.parent is not None:
925            if self.parent.parent is not None:
926                wx.PostEvent(self.parent.parent, PanelOnFocusEvent(panel=self))
927            self.page_finder = self.parent._manager.get_page_finder()
928
929
930def setComboBoxItems(cbox, items):
931    assert isinstance(cbox, wx.ComboBox)
932    selected = cbox.GetStringSelection()
933    cbox.Clear()
934    for k, (name, value) in enumerate(items):
935        cbox.Append(name, value)
936    cbox.SetStringSelection(selected)
Note: See TracBrowser for help on using the repository browser.