source: sasview/calculatorview/src/sans/perspectives/calculator/model_editor.py @ 9ec0955

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 9ec0955 was 9ec0955, checked in by Jae Cho <jhjcho@…>, 12 years ago

expanding param sizer

  • Property mode set to 100644
File size: 48.5 KB
Line 
1################################################################################
2#This software was developed by the University of Tennessee as part of the
3#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4#project funded by the US National Science Foundation.
5#
6#See the license text in license.txt
7#
8#copyright 2009, University of Tennessee
9################################################################################
10import wx
11import sys
12import os
13from wx.py.editwindow import EditWindow
14
15if sys.platform.count("win32") > 0:
16    FONT_VARIANT = 0
17    PNL_WIDTH = 450
18    PNL_HITE = 320
19else:
20    FONT_VARIANT = 1
21    PNL_WIDTH = 590
22    PNL_HITE = 400
23M_NAME = 'Model'
24EDITOR_WIDTH = 800
25EDITOR_HEIGTH = 720
26PANEL_WIDTH = 500
27_BOX_WIDTH = 55
28
29   
30def _compileFile(path):
31    """
32    Compile the file in the path
33    """
34    try:
35        import py_compile
36        py_compile.compile(file=path, doraise=True)
37        return ''
38    except:
39        _, value, _ = sys.exc_info()
40        return value
41   
42def _deleteFile(path):
43    """
44    Delete file in the path
45    """
46    try:
47        os.remove(path)
48    except:
49        raise
50
51 
52class TextDialog(wx.Dialog):
53    """
54    Dialog for easy custom sum models 
55    """
56    def __init__(self, parent=None, base=None, id=None, title='', 
57                 model_list=[], plugin_dir=None):
58        """
59        Dialog window popup when selecting 'Easy Custom Sum/Multiply'
60        on the menu
61        """
62        wx.Dialog.__init__(self, parent=parent, id=id, 
63                           title=title, size=(PNL_WIDTH, PNL_HITE))
64        self.parent = base
65        #Font
66        self.SetWindowVariant(variant=FONT_VARIANT)
67        # default
68        self.font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
69        self.font.SetPointSize(10)
70        self.overwrite_name = False
71        self.plugin_dir = plugin_dir
72        self.model_list = model_list
73        self.model1_string = "SphereModel"
74        self.model2_string = "CylinderModel"
75        self.name = 'Sum' + M_NAME
76        self.factor = 'scale_factor'
77        self._notes = ''
78        self.operator = '+'
79        self.operator_cbox = None
80        self.explanation = ''
81        self.explanationctr = None
82        self.sizer = None
83        self.name_sizer = None
84        self.name_hsizer = None
85        self.desc_sizer = None
86        self.desc_tcl = None
87        self.model1 = None
88        self.model2 = None
89        self.static_line_1 = None
90        self.okButton = None
91        self.closeButton = None
92        self._msg_box = None
93        self.msg_sizer = None
94        self.fname = None
95        self.cm_list = None
96        self.is_p1_custom = False
97        self.is_p2_custom = False
98        self._build_sizer()
99        self.model1_name = str(self.model1.GetValue())
100        self.model2_name = str(self.model2.GetValue())
101        self.good_name = True
102        self.fill_oprator_combox()
103       
104    def _layout_name(self):
105        """
106        Do the layout for file/function name related widgets
107        """
108        self.name_sizer = wx.BoxSizer(wx.VERTICAL)
109        self.name_hsizer = wx.BoxSizer(wx.HORIZONTAL)
110        #title name [string]
111        name_txt = wx.StaticText(self, -1, 'Function Name : ') 
112        self.name_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
113        self.name_tcl.Bind(wx.EVT_TEXT_ENTER, self.on_change_name)
114        self.name_tcl.SetValue('')
115        self.name_tcl.SetFont(self.font)
116        hint_name = "Unique Sum/Multiply Model Function Name."
117        self.name_tcl.SetToolTipString(hint_name)
118        self.name_hsizer.AddMany([(name_txt, 0, wx.LEFT|wx.TOP, 10),
119                            (self.name_tcl, -1, 
120                             wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 10)])
121        self.name_sizer.AddMany([(self.name_hsizer, -1, 
122                                        wx.LEFT|wx.TOP, 10)])
123       
124       
125    def _layout_description(self):
126        """
127        Do the layout for description related widgets
128        """
129        self.desc_sizer = wx.BoxSizer(wx.HORIZONTAL)
130        #title name [string]
131        desc_txt = wx.StaticText(self, -1, 'Description (optional) : ') 
132        self.desc_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
133        self.desc_tcl.SetValue('')
134        #self.name_tcl.SetFont(self.font)
135        hint_desc = "Write a short description of this model function."
136        self.desc_tcl.SetToolTipString(hint_desc)
137        self.desc_sizer.AddMany([(desc_txt, 0, wx.LEFT|wx.TOP, 10),
138                                (self.desc_tcl, -1, 
139                                wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 10)])     
140 
141    def _build_sizer(self):
142        """
143        Build gui
144        """
145        box_width = 195 # combobox width
146        vbox  = wx.BoxSizer(wx.VERTICAL)
147        self.sizer = wx.GridBagSizer(1, 3)
148        self._layout_name()
149        self._layout_description()
150       
151       
152        sum_description = wx.StaticBox(self, -1, 'Select', 
153                                       size=(PNL_WIDTH-30, 70))
154        sum_box = wx.StaticBoxSizer(sum_description, wx.VERTICAL)
155        model1_box = wx.BoxSizer(wx.HORIZONTAL)
156        model2_box = wx.BoxSizer(wx.HORIZONTAL)
157        model_vbox = wx.BoxSizer(wx.VERTICAL)
158        self.model1 =  wx.ComboBox(self, -1, style=wx.CB_READONLY)
159        wx.EVT_COMBOBOX(self.model1, -1, self.on_model1)
160        self.model1.SetMinSize((box_width*5/6, -1))
161        self.model1.SetToolTipString("model1")
162       
163        self.operator_cbox = wx.ComboBox(self, -1, size=(50, -1), 
164                                         style=wx.CB_READONLY)
165        wx.EVT_COMBOBOX(self.operator_cbox, -1, self.on_select_operator)
166        operation_tip = "Add: +, Multiply: * "
167        self.operator_cbox.SetToolTipString(operation_tip)
168       
169        self.model2 =  wx.ComboBox(self, -1, style=wx.CB_READONLY)
170        wx.EVT_COMBOBOX(self.model2, -1, self.on_model2)
171        self.model2.SetMinSize((box_width*5/6, -1))
172        self.model2.SetToolTipString("model2")
173        self._set_model_list()
174       
175         # Buttons on the bottom
176        self.static_line_1 = wx.StaticLine(self, -1)
177        self.okButton = wx.Button(self,wx.ID_OK, 'Apply', size=(box_width/2, 25))
178        self.okButton.Bind(wx.EVT_BUTTON, self.check_name)
179        self.closeButton = wx.Button(self,wx.ID_CANCEL, 'Close', 
180                                     size=(box_width/2, 25))
181        # Intro
182        self.explanation  = "  custom model = %s %s "% (self.factor, '*')
183        self.explanation  += "(model1 %s model2)\n"% self.operator
184        #explanation  += "  Note: This will overwrite the previous sum model.\n"
185        model_string = " Model%s (p%s):"
186        # msg
187        self._msg_box = wx.StaticText(self, -1, self._notes)
188        self.msg_sizer = wx.BoxSizer(wx.HORIZONTAL)
189        self.msg_sizer.Add(self._msg_box, 0, wx.LEFT, 0)
190        vbox.Add(self.name_hsizer)
191        vbox.Add(self.desc_sizer)
192        vbox.Add(self.sizer)
193        ix = 0
194        iy = 1
195        self.explanationctr = wx.StaticText(self, -1, self.explanation)
196        self.sizer.Add(self.explanationctr , (iy, ix),
197                 (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
198        model1_box.Add(wx.StaticText(self, -1, model_string% (1, 1)), -1, 0)
199        model1_box.Add((box_width-15, 10))
200        model1_box.Add(wx.StaticText(self, -1, model_string% (2, 2)), -1, 0)
201        model2_box.Add(self.model1, -1, 0)
202        model2_box.Add((15, 10))
203        model2_box.Add(self.operator_cbox, 0, 0)
204        model2_box.Add((15, 10))
205        model2_box.Add(self.model2, -1, 0)
206        model_vbox.Add(model1_box, -1, 0)
207        model_vbox.Add(model2_box, -1, 0)
208        sum_box.Add(model_vbox, -1, 10)
209        iy += 1
210        ix = 0
211        self.sizer.Add(sum_box, (iy, ix),
212                  (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
213        vbox.Add((10, 10))
214        vbox.Add(self.static_line_1, 0, wx.EXPAND, 10)
215        vbox.Add(self.msg_sizer, 0, 
216                 wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE|wx.BOTTOM, 10)
217        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
218        sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
219        sizer_button.Add(self.okButton, 0, 
220                         wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 0)
221        sizer_button.Add(self.closeButton, 0,
222                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)       
223        vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
224         
225        self.SetSizer(vbox)
226        self.Centre()
227       
228    def on_change_name(self, event=None):
229        """
230        Change name
231        """
232        if event is not None:
233            event.Skip()
234        self.name_tcl.SetBackgroundColour('white')
235        self.Refresh()
236   
237    def check_name(self, event=None):
238        """
239        Check name if exist already
240        """
241        mname = M_NAME
242        self.on_change_name(None)
243        list_fnames = os.listdir(self.plugin_dir)
244        # fake existing regular model name list
245        m_list = [model + ".py" for model in self.model_list]
246        list_fnames.append(m_list)
247        # function/file name
248        title = self.name_tcl.GetValue().lstrip().rstrip()
249        if title == '':
250            text = self.operator_cbox.GetLabel().strip()
251            if text == '+':
252                mname = 'Sum'
253            else:
254                mname = 'Multi'
255            mname += M_NAME
256            title = mname
257        self.name = title
258        t_fname = title + '.py'
259        if not self.overwrite_name:
260            if t_fname in list_fnames and title != mname:
261                self.name_tcl.SetBackgroundColour('pink')
262                self.good_name = False
263                info = 'Error'
264                msg = "Name exists already."
265                wx.MessageBox(msg, info) 
266                self._notes = msg
267                color = 'red'
268                self._msg_box.SetLabel(msg)
269                self._msg_box.SetForegroundColour(color)
270                return self.good_name
271        self.fname = os.path.join(self.plugin_dir, t_fname)
272        s_title = title
273        if len(title) > 20:
274            s_title = title[0:19] + '...'
275        self._notes = "Model function (%s) has been set! \n" % str(s_title)
276        self.good_name = True
277        self.on_apply(self.fname)
278        return self.good_name
279   
280    def on_apply(self, path):
281        """
282        On Apply
283        """
284        try:
285            label = self.getText()
286            fname = path
287            name1 = label[0]
288            name2 = label[1]
289            self.write_string(fname, name1, name2)
290            self.compile_file(fname)
291            self.parent.update_custom_combo()
292            msg = self._notes
293            info = 'Info'
294            color = 'blue'
295        except:
296            msg= "Easy Custom Sum/Multipy: Error occurred..."
297            info = 'Error'
298            color = 'red'
299        self._msg_box.SetLabel(msg)
300        self._msg_box.SetForegroundColour(color)
301        if self.parent.parent != None:
302            from sans.guiframe.events import StatusEvent
303            wx.PostEvent(self.parent.parent, StatusEvent(status = msg, 
304                                                      info=info))
305        else:
306            raise
307                 
308    def _set_model_list(self):
309        """
310        Set the list of models
311        """
312        # list of model names
313        cm_list = []
314        # models
315        list = self.model_list
316        # custom models
317        al_list = os.listdir(self.plugin_dir)
318        for c_name in al_list:
319            if c_name.split('.')[-1] == 'py' and \
320                    c_name.split('.')[0] != '__init__':
321                name = str(c_name.split('.')[0])
322                cm_list.append(name)
323                if name not in list:
324                    list.append(name)
325        self.cm_list = cm_list
326        if len(list) > 1:
327            list.sort()
328        for idx in range(len(list)):
329            self.model1.Append(str(list[idx]), idx) 
330            self.model2.Append(str(list[idx]), idx)
331        self.model1.SetStringSelection(self.model1_string)
332        self.model2.SetStringSelection(self.model2_string)
333   
334    def update_cm_list(self):
335        """
336        Update custom model list
337        """
338        cm_list = []
339        al_list = os.listdir(self.plugin_dir)
340        for c_name in al_list:
341            if c_name.split('.')[-1] == 'py' and \
342                    c_name.split('.')[0] != '__init__':
343                name = str(c_name.split('.')[0])
344                cm_list.append(name)
345        self.cm_list = cm_list
346             
347    def on_model1(self, event):
348        """
349        Set model1
350        """
351        event.Skip()
352        self.update_cm_list()
353        self.model1_name = str(self.model1.GetValue())
354        self.model1_string = self.model1_name
355        if self.model1_name in self.cm_list:
356            self.is_p1_custom = True
357        else:
358            self.is_p1_custom = False
359           
360    def on_model2(self, event):
361        """
362        Set model2
363        """
364        event.Skip()
365        self.update_cm_list()
366        self.model2_name = str(self.model2.GetValue())
367        self.model2_string = self.model2_name
368        if self.model2_name in self.cm_list:
369            self.is_p2_custom = True
370        else:
371            self.is_p2_custom = False
372       
373    def on_select_operator(self, event=None):
374        """
375        On Select an Operator
376        """
377        item = event.GetEventObject()
378        text = item.GetLabel().strip()
379        if text == '+':
380            name = 'Sum'
381            factor = 'scale_factor'
382            f_oper = '*'
383        else:
384            name = 'Multi'
385            factor = 'BackGround'
386            f_oper = '+'
387        self.factor = str(factor)
388        self.operator = str(text)
389        self.explanation = "  custom model = %s %s "% (self.factor, 
390                                                       f_oper)
391        self.explanation += "(model1 %s model2)\n"% self.operator
392        self.explanationctr.SetLabel(self.explanation)
393        self.name = name + M_NAME
394        self.sizer.Layout()
395             
396    def fill_oprator_combox(self):
397        """
398        fill the current combobox with the operator
399        """   
400        operator_list = [' +', ' *']
401        for oper in operator_list:
402            pos = self.operator_cbox.Append(str(oper))
403            self.operator_cbox.SetClientData(pos, str(oper.strip()))
404        self.operator_cbox.SetSelection(0)
405           
406    def getText(self):
407        """
408        Returns model name string as list
409        """
410        return [self.model1_name, self.model2_name]
411   
412    def write_string(self, fname, name1, name2):
413        """
414        Write and Save file
415        """
416        self.fname = fname 
417        description = self.desc_tcl.GetValue().lstrip().rstrip()
418        if description == '':
419            description = name1 + self.operator + name2
420        name = self.name_tcl.GetValue().lstrip().rstrip()
421        text = self.operator_cbox.GetLabel().strip()
422        if text == '+':
423            factor = 'scale_factor'
424            f_oper = '*'
425            default_val = '1.0'
426        else:
427            factor = 'BackGround'
428            f_oper = '+'
429            default_val = '0.0'
430        path = self.fname
431        try:
432            out_f =  open(path,'w')
433        except :
434            raise
435        lines = SUM_TEMPLATE.split('\n')
436        for line in lines:
437            try:
438                if line.count("scale_factor"):
439                    line = line.replace('scale_factor', factor)
440                    #print "scale_factor", line
441                if line.count("= %s"):
442                    out_f.write(line % (default_val) + "\n")
443                elif line.count("import Model as P1"):
444                    if self.is_p1_custom:
445                        line = line.replace('#', '')
446                        out_f.write(line % name1 + "\n")
447                    else:
448                        out_f.write(line + "\n")
449                elif line.count("import %s as P1"):
450                    if not self.is_p1_custom:
451                        line = line.replace('#', '')
452                        out_f.write(line % (name1, name1) + "\n")
453                    else:
454                        out_f.write(line + "\n")
455                elif line.count("import Model as P2"):
456                    if self.is_p2_custom:
457                        line = line.replace('#', '')
458                        out_f.write(line % name2 + "\n")
459                    else:
460                        out_f.write(line + "\n")
461                elif line.count("import %s as P2"):
462                    if not self.is_p2_custom:
463                        line = line.replace('#', '')
464                        out_f.write(line % (name2, name2) + "\n")
465                    else:
466                        out_f.write(line + "\n")
467                elif line.count("self.description = '%s'"):
468                    out_f.write(line % description + "\n")
469                #elif line.count("run") and line.count("%s"):
470                #    out_f.write(line % self.operator + "\n")
471                #elif line.count("evalDistribution") and line.count("%s"):
472                #    out_f.write(line % self.operator + "\n")
473                elif line.count("return") and line.count("%s") == 2:
474                    #print "line return", line
475                    out_f.write(line % (f_oper, self.operator) + "\n")
476                elif line.count("out2")and line.count("%s"):
477                    out_f.write(line % self.operator + "\n")
478                else:
479                    out_f.write(line + "\n")
480            except:
481                raise
482        out_f.close()
483        #else:
484        #    msg = "Name exists already."
485       
486    def compile_file(self, path):
487        """
488        Compile the file in the path
489        """
490        path = self.fname
491        _compileFile(path)
492       
493    def delete_file(self, path):
494        """
495        Delete file in the path
496        """
497        _deleteFile(path)
498
499
500class EditorPanel(wx.ScrolledWindow):
501    """
502    Custom model function editor
503    """
504    def __init__(self, parent, base, path, title, *args, **kwds):
505        kwds['name'] = title
506        kwds["size"] = (EDITOR_WIDTH, EDITOR_HEIGTH)
507        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
508        wx.ScrolledWindow.__init__(self, parent, *args, **kwds)
509        #self.SetupScrolling()
510        self.parent = parent
511        self.base = base
512        self.path = path
513        self.font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
514        self.font.SetPointSize(10)
515        self.reader = None
516        self.name = 'untitled'
517        self.overwrite_name = False
518        self.is_2d = False
519        self.fname = None
520        self.param_strings = ''
521        self.function_strings = ''
522        self._notes = ""
523        self._msg_box = None
524        self.msg_sizer = None
525        self.warning = ""
526        self._description = "New Custom Model"
527        #self._default_save_location = os.getcwd()
528        self._do_layout()
529        #self.bt_apply.Disable()
530
531             
532    def _define_structure(self):
533        """
534        define initial sizer
535        """
536        #w, h = self.parent.GetSize()
537        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
538        self.name_sizer = wx.BoxSizer(wx.VERTICAL)
539        self.name_hsizer = wx.BoxSizer(wx.HORIZONTAL)
540        self.desc_sizer = wx.BoxSizer(wx.VERTICAL)
541        self.param_sizer = wx.BoxSizer(wx.VERTICAL)
542        self.function_sizer = wx.BoxSizer(wx.VERTICAL)
543        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
544        self.msg_sizer = wx.BoxSizer(wx.HORIZONTAL)
545       
546    def _layout_name(self):
547        """
548        Do the layout for file/function name related widgets
549        """
550        #title name [string]
551        name_txt = wx.StaticText(self, -1, 'Function Name : ') 
552        overwrite_cb = wx.CheckBox(self, -1, "Overwrite?", (10, 10))
553        overwrite_cb.SetValue(False)
554        overwrite_cb.SetToolTipString("Overwrite it if already exists?")
555        wx.EVT_CHECKBOX(self, overwrite_cb.GetId(), self.on_over_cb)
556        #overwrite_cb.Show(False)
557        self.name_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
558        self.name_tcl.Bind(wx.EVT_TEXT_ENTER, self.on_change_name)
559        self.name_tcl.SetValue('MyFunction')
560        self.name_tcl.SetFont(self.font)
561        hint_name = "Unique Model Function Name."
562        self.name_tcl.SetToolTipString(hint_name)
563        self.name_hsizer.AddMany([(self.name_tcl, 0, wx.LEFT|wx.TOP, 0),
564                                       (overwrite_cb, 0, wx.LEFT, 20)])
565        self.name_sizer.AddMany([(name_txt, 0, wx.LEFT|wx.TOP, 10),
566                                       (self.name_hsizer, 0, 
567                                        wx.LEFT|wx.TOP|wx.BOTTOM, 10)])
568       
569       
570    def _layout_description(self):
571        """
572        Do the layout for description related widgets
573        """
574        #title name [string]
575        desc_txt = wx.StaticText(self, -1, 'Description (optional) : ') 
576        self.desc_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
577        self.desc_tcl.SetValue('')
578        #self.name_tcl.SetFont(self.font)
579        hint_desc = "Write a short description of the model function."
580        self.desc_tcl.SetToolTipString(hint_desc)
581        self.desc_sizer.AddMany([(desc_txt, 0, wx.LEFT|wx.TOP, 10),
582                                       (self.desc_tcl, 0, 
583                                        wx.LEFT|wx.TOP|wx.BOTTOM, 10)])     
584    def _layout_param(self):
585        """
586        Do the layout for parameter related widgets
587        """
588        param_txt = wx.StaticText(self, -1, 'Fit Parameters (if any): ') 
589        param_tip = "#Set the parameters and initial values.\n"
590        param_tip += "#Example:\n"
591        param_tip += "A = 1\nB = 1"
592        #param_txt.SetToolTipString(param_tip)
593        id  = wx.NewId() 
594        self.param_tcl = EditWindow(self, id, wx.DefaultPosition, 
595                            wx.DefaultSize, wx.CLIP_CHILDREN|wx.SUNKEN_BORDER)
596        self.param_tcl.setDisplayLineNumbers(True)
597        self.param_tcl.SetToolTipString(param_tip)
598        self.param_sizer.AddMany([(param_txt, 0, wx.LEFT, 10),
599                        (self.param_tcl, 1, wx.EXPAND|wx.ALL, 10)])
600
601   
602    def _layout_function(self):
603        """
604        Do the layout for function related widgets
605        """
606        function_txt = wx.StaticText(self, -1, 'Function(x) : ') 
607        hint_function = "#Example:\n"
608        hint_function += "if x <= 0:\n"
609        hint_function += "    y = A + B\n"
610        hint_function += "else:\n"
611        hint_function += "    y = A + B * cos(2 * pi * x)\n"
612        hint_function += "return y\n"
613        id  = wx.NewId() 
614        self.function_tcl = EditWindow(self, id, wx.DefaultPosition, 
615                            wx.DefaultSize, wx.CLIP_CHILDREN|wx.SUNKEN_BORDER)
616        self.function_tcl.setDisplayLineNumbers(True)
617        self.function_tcl.SetToolTipString(hint_function)
618        self.function_sizer.Add(function_txt, 0, wx.LEFT, 10)
619        self.function_sizer.Add( self.function_tcl, 1, wx.EXPAND|wx.ALL, 10)
620       
621    def _layout_msg(self):
622        """
623        Layout msg
624        """
625        self._msg_box = wx.StaticText(self, -1, self._notes)
626        self.msg_sizer.Add(self._msg_box, 0, wx.LEFT, 10) 
627                   
628    def _layout_button(self): 
629        """
630        Do the layout for the button widgets
631        """         
632        self.bt_apply = wx.Button(self, -1, "Apply", size=(_BOX_WIDTH, -1))
633        self.bt_apply.SetToolTipString("Save changes into the imported data.")
634        self.bt_apply.Bind(wx.EVT_BUTTON, self.on_click_apply)
635       
636        self.bt_close = wx.Button(self, -1, 'Close', size=(_BOX_WIDTH, -1))
637        self.bt_close.Bind(wx.EVT_BUTTON, self.on_close)
638        self.bt_close.SetToolTipString("Close this panel.")
639       
640        self.button_sizer.AddMany([(self.bt_apply, 0, 
641                                    wx.LEFT, EDITOR_WIDTH * 0.8),
642                                   (self.bt_close, 0, 
643                                    wx.LEFT|wx.BOTTOM, 15)])
644         
645    def _do_layout(self):
646        """
647        Draw the current panel
648        """
649        self._define_structure()
650        self._layout_name()
651        self._layout_description()
652        self._layout_param()
653        self._layout_function()
654        self._layout_msg()
655        self._layout_button()
656        self.main_sizer.AddMany([(self.name_sizer, 0, 
657                                        wx.EXPAND|wx.ALL, 5),
658                                 (wx.StaticLine(self), 0, 
659                                       wx.ALL|wx.EXPAND, 5),
660                                 (self.desc_sizer, 0, 
661                                        wx.EXPAND|wx.ALL, 5),
662                                 (wx.StaticLine(self), 0, 
663                                       wx.ALL|wx.EXPAND, 5),
664                                (self.param_sizer, 1,
665                                         wx.EXPAND|wx.ALL, 5),
666                                 (wx.StaticLine(self), 0, 
667                                       wx.ALL|wx.EXPAND, 5),
668                                (self.function_sizer, 2,
669                                         wx.EXPAND|wx.ALL, 5),
670                                 (wx.StaticLine(self), 0, 
671                                       wx.ALL|wx.EXPAND, 5),
672                                 (self.msg_sizer, 0, 
673                                        wx.EXPAND|wx.ALL, 5),
674                                (self.button_sizer, 0,
675                                         wx.EXPAND|wx.ALL, 5)])
676        self.SetSizer(self.main_sizer)
677        self.SetAutoLayout(True)
678   
679    def get_notes(self):
680        """
681        return notes
682        """
683        return self._notes
684                 
685    def on_change_name(self, event=None):
686        """
687        Change name
688        """
689        if event is not None:
690            event.Skip()
691        self.name_tcl.SetBackgroundColour('white')
692        self.Refresh()
693   
694    def check_name(self):
695        """
696        Check name if exist already
697        """
698        self._notes = ''
699        self.on_change_name(None)
700        plugin_dir = self.path
701        list_fnames = os.listdir(plugin_dir)
702        # function/file name
703        title = self.name_tcl.GetValue().lstrip().rstrip()
704        self.name = title
705        t_fname = title + '.py'
706        if not self.overwrite_name:
707            if t_fname in list_fnames:
708                self.name_tcl.SetBackgroundColour('pink')
709                return False
710        self.fname = os.path.join(plugin_dir, t_fname)
711        s_title = title
712        if len(title) > 20:
713            s_title = title[0:19] + '...'
714        self._notes += "Model function name set "
715        self._notes += "to %s. \n" % str(s_title)
716        return True
717   
718    def on_over_cb(self, event):
719        """
720        Set overwrite name flag on cb event
721        """
722        if event is not None:
723            event.Skip()
724        cb = event.GetEventObject()
725        self.overwrite_name = cb.GetValue()
726       
727    def on_click_apply(self, event):
728        """   
729        Changes are saved in data object imported to edit
730        """
731        #must post event here
732        event.Skip()
733        info = 'Info'
734        # Sort out the errors if occur
735        if self.check_name():
736            name = self.name_tcl.GetValue().lstrip().rstrip()
737            description = self.desc_tcl.GetValue()
738            param_str = self.param_tcl.GetText()
739            func_str = self.function_tcl.GetText()
740            # No input for the model function
741            if func_str.lstrip().rstrip():
742                if func_str.count('return') > 0:
743                    self.write_file(self.fname, description, param_str, func_str)
744                    tr_msg = _compileFile(self.fname)
745                    msg = tr_msg.__str__()
746                    # Compile error
747                    if msg:
748                        _deleteFile(self.fname)
749                        msg +=  "\nCompile Failed"
750                    else:
751                        msg = ''
752                else:
753                    msg = "Error: The func(x) must 'return' a value at least.\n"
754                    msg += "For example: \n\nreturn 2*x"
755            else:
756                msg = 'Error: Function is not defined.'
757        else:
758            msg = "Name exists already."
759        # Prepare for the messagebox
760        if not msg:
761            if self.base != None:
762                self.base.update_custom_combo()
763            msg = "Successful!!!"
764            msg += "  " + self._notes
765            msg += " Please look for it in the 'Customized Models' box."
766            info = 'Info'
767            color = 'blue'
768        else:
769            info = 'Error'
770            color = 'red'
771            wx.MessageBox(msg, info) 
772       
773        self._msg_box.SetLabel(msg)
774        self._msg_box.SetForegroundColour(color)
775        # Send msg to the top window 
776        if self.base != None:
777                from sans.guiframe.events import StatusEvent
778                wx.PostEvent(self.base.parent, StatusEvent(status = msg, 
779                                                      info=info))
780        self.warning = msg
781
782               
783    def write_file(self, fname, desc_str, param_str, func_str): 
784        """
785        Write content in file
786       
787        :param fname: full file path
788        :param desc_str: content of the description strings
789        :param param_str: content of params; Strings 
790        :param func_str: content of func; Strings
791        """ 
792        try:
793            out_f =  open(fname,'w')
794        except :
795            raise
796        # Prepare the content of the function
797        lines = CUSTOM_TEMPLATE.split('\n')
798
799        has_scipy = func_str.count("scipy.")
800        self.is_2d = func_str.count("#self.ndim = 2")
801        line_2d = ''
802        if self.is_2d:
803            line_2d = CUSTOM_2D_TEMP.split('\n')
804        line_test = TEST_TEMPLATE.split('\n')
805        local_params = ''
806        spaces = '        '#8spaces
807        # write function here
808        for line in lines:
809            # The location where to put the strings is
810            # hard-coded in the template as shown below.
811            if line.count("#self.params here"):
812                for param_line in param_str.split('\n'):
813                    p_line = param_line.lstrip().rstrip()
814                    if p_line:
815                        p0_line = self.set_param_helper(p_line)
816                        local_params += self.set_function_helper(p_line)
817                        out_f.write(p0_line)
818            elif line.count("#local params here"):
819                if local_params:
820                    out_f.write(local_params)
821            elif line.count("self.description = "):
822                des0 = self.name + "\\n"
823                desc = str(desc_str.lstrip().rstrip().replace('\"', ''))
824                out_f.write(line% (des0 + desc) + "\n")
825            elif line.count("def function(self, x=0.0%s):"):
826                if self.is_2d:
827                    y_str = ', y=0.0'
828                    out_f.write(line% y_str + "\n")
829                else:
830                    out_f.write(line% '' + "\n")
831            elif line.count("#function here"):
832                for func_line in func_str.split('\n'):
833                    f_line = func_line.rstrip()
834                    if f_line:
835                        out_f.write(spaces + f_line + "\n")
836                if not func_str:
837                    dep_var = 'y'
838                    if self.is_2d:
839                        dep_var = 'z'
840                    out_f.write(spaces + 'return %s'% dep_var + "\n")
841            elif line.count("#import scipy?"):
842                if has_scipy:
843                    out_f.write("import scipy" + "\n")
844            #elif line.count("name = "):
845            #    out_f.write(line % self.name + "\n")
846            elif line:
847                out_f.write(line + "\n")
848        # run string for 2d
849        if line_2d:
850            for line in line_2d:
851                out_f.write(line + "\n")
852        # Test strins
853        for line in line_test:
854            out_f.write(line + "\n")
855   
856        out_f.close() 
857   
858    def set_param_helper(self, line):   
859        """
860        Get string in line to define the params dictionary
861       
862        :param line: one line of string got from the param_str
863        """
864        flag = True
865        params_str = ''
866        spaces = '        '#8spaces
867        items = line.split(";")
868        for item in items:
869            name = item.split("=")[0].lstrip().rstrip()
870            try:
871                value = item.split("=")[1].lstrip().rstrip()
872                float(value)
873            except:
874                value = 1.0 # default
875            params_str += spaces + "self.params['%s'] = %s\n"% (name, value)
876           
877        return params_str
878
879    def set_function_helper(self, line):   
880        """
881        Get string in line to define the local params
882       
883        :param line: one line of string got from the param_str
884        """
885        flag = True
886        params_str = ''
887        spaces = '        '#8spaces
888        items = line.split(";")
889        for item in items:
890            name = item.split("=")[0].lstrip().rstrip()
891            params_str += spaces + "%s = self.params['%s']\n"% (name, name)
892        return params_str
893   
894    def get_warning(self):
895        """
896        Get the warning msg
897        """
898        return self.warning
899       
900    def on_close(self, event):
901        """
902        leave data as it is and close
903        """
904        self.parent.Close()
905        event.Skip()
906       
907class EditorWindow(wx.Frame):
908    """
909    Editor Window
910    """
911    def __init__(self, parent, base, path, title, 
912                 size=(EDITOR_WIDTH, EDITOR_HEIGTH), *args, **kwds):
913        """
914        Init
915        """
916        kwds["title"] = title
917        kwds["size"] = size
918        wx.Frame.__init__(self, parent=None, *args, **kwds)
919        self.parent = parent
920        self.panel = EditorPanel(parent=self, base=parent, 
921                                 path=path, title=title)
922        self.Show(True)
923        wx.EVT_CLOSE(self, self.OnClose)
924   
925    def OnClose(self, event): 
926        """
927        On close event
928        """
929        if self.parent != None:
930            self.parent.new_model_frame = None
931        self.Destroy() 
932
933## Templates for custom models
934CUSTOM_TEMPLATE = """
935from sans.models.pluginmodel import Model1DPlugin
936from math import *
937import os
938import sys
939import numpy
940#import scipy?
941class Model(Model1DPlugin):
942    name = ""                             
943    def __init__(self):
944        Model1DPlugin.__init__(self, name=self.name) 
945        #set name same as file name
946        self.name = self.get_fname()                                                   
947        #self.params here
948        self.description = "%s"
949        self.set_details()
950    def function(self, x=0.0%s):
951        #local params here
952        #function here
953"""
954CUSTOM_2D_TEMP = """
955    def run(self, x=0.0, y=0.0):
956        if x.__class__.__name__ == 'list':
957            x_val = x[0]
958            y_val = y[0]*0.0
959            return self.function(x_val, y_val)
960        elif x.__class__.__name__ == 'tuple':
961            msg = "Tuples are not allowed as input to BaseComponent models"
962            raise ValueError, msg
963        else:
964            return self.function(x, 0.0)
965    def runXY(self, x=0.0, y=0.0):
966        if x.__class__.__name__ == 'list':
967            return self.function(x, y)
968        elif x.__class__.__name__ == 'tuple':
969            msg = "Tuples are not allowed as input to BaseComponent models"
970            raise ValueError, msg
971        else:
972            return self.function(x, y)
973    def evalDistribution(self, qdist):
974        if qdist.__class__.__name__ == 'list':
975            msg = "evalDistribution expects a list of 2 ndarrays"
976            if len(qdist)!=2:
977                raise RuntimeError, msg
978            if qdist[0].__class__.__name__ != 'ndarray':
979                raise RuntimeError, msg
980            if qdist[1].__class__.__name__ != 'ndarray':
981                raise RuntimeError, msg
982            v_model = numpy.vectorize(self.runXY, otypes=[float])
983            iq_array = v_model(qdist[0], qdist[1])
984            return iq_array
985        elif qdist.__class__.__name__ == 'ndarray':
986            v_model = numpy.vectorize(self.runXY, otypes=[float])
987            iq_array = v_model(qdist)
988            return iq_array
989"""
990TEST_TEMPLATE = """
991    def get_fname(self):
992        path = sys._getframe().f_code.co_filename
993        basename  = os.path.basename(path)
994        name, _ = os.path.splitext(basename)
995        return name
996######################################################################
997## THIS IS FOR TEST. DO NOT MODIFY THE FOLLOWING LINES!!!!!!!!!!!!!!!!       
998if __name__ == "__main__":
999    m= Model()
1000    out1 = m.runXY(0.0)
1001    out2 = m.runXY(0.01)
1002    isfine1 = numpy.isfinite(out1)
1003    isfine2 = numpy.isfinite(out2)
1004    print "Testing the value at Q = 0.0:"
1005    print out1, " : finite? ", isfine1
1006    print "Testing the value at Q = 0.01:"
1007    print out2, " : finite? ", isfine2
1008    if isfine1 and isfine2:
1009        print "===> Simple Test: Passed!"
1010    else:
1011        print "===> Simple Test: Failed!"
1012"""
1013SUM_TEMPLATE = """
1014# A sample of an experimental model function for Sum/Multiply(Pmodel1,Pmodel2)
1015import copy
1016from sans.models.pluginmodel import Model1DPlugin
1017# User can change the name of the model (only with single functional model)
1018#P1_model:
1019#from sans.models.%s import %s as P1
1020#from %s import Model as P1
1021
1022#P2_model:
1023#from sans.models.%s import %s as P2
1024#from %s import Model as P2
1025import os
1026import sys
1027
1028class Model(Model1DPlugin):
1029    name = ""
1030    def __init__(self):
1031        Model1DPlugin.__init__(self, name='')
1032        p_model1 = P1()
1033        p_model2 = P2()
1034        ## Setting  model name model description
1035        self.description = '%s'
1036        self.name = self.get_fname()
1037        if self.name.rstrip().lstrip() == '':
1038            self.name = self._get_name(p_model1.name, p_model2.name)
1039        if self.description.rstrip().lstrip() == '':
1040            self.description = p_model1.name
1041            self.description += p_model2.name
1042            self.fill_description(p_model1, p_model2)
1043
1044        ## Define parameters
1045        self.params = {}
1046
1047        ## Parameter details [units, min, max]
1048        self.details = {}
1049       
1050        # non-fittable parameters
1051        self.non_fittable = p_model1.non_fittable 
1052        self.non_fittable += p_model2.non_fittable 
1053           
1054        ##models
1055        self.p_model1= p_model1
1056        self.p_model2= p_model2
1057       
1058       
1059        ## dispersion
1060        self._set_dispersion()
1061        ## Define parameters
1062        self._set_params()
1063        ## New parameter:scaling_factor
1064        self.params['scale_factor'] = %s
1065       
1066        ## Parameter details [units, min, max]
1067        self._set_details()
1068        self.details['scale_factor'] = ['', None, None]
1069
1070       
1071        #list of parameter that can be fitted
1072        self._set_fixed_params() 
1073        ## parameters with orientation
1074        for item in self.p_model1.orientation_params:
1075            new_item = "p1_" + item
1076            if not new_item in self.orientation_params:
1077                self.orientation_params.append(new_item)
1078           
1079        for item in self.p_model2.orientation_params:
1080            new_item = "p2_" + item
1081            if not new_item in self.orientation_params:
1082                self.orientation_params.append(new_item)
1083        # get multiplicity if model provide it, else 1.
1084        try:
1085            multiplicity1 = p_model1.multiplicity
1086            try:
1087                multiplicity2 = p_model2.multiplicity
1088            except:
1089                multiplicity2 = 1
1090        except:
1091            multiplicity1 = 1
1092            multiplicity2 = 1
1093        ## functional multiplicity of the model
1094        self.multiplicity1 = multiplicity1 
1095        self.multiplicity2 = multiplicity2   
1096        self.multiplicity_info = []   
1097       
1098    def _clone(self, obj):
1099        obj.params     = copy.deepcopy(self.params)
1100        obj.description     = copy.deepcopy(self.description)
1101        obj.details    = copy.deepcopy(self.details)
1102        obj.dispersion = copy.deepcopy(self.dispersion)
1103        obj.p_model1  = self.p_model1.clone()
1104        obj.p_model2  = self.p_model2.clone()
1105        #obj = copy.deepcopy(self)
1106        return obj
1107   
1108    def _get_name(self, name1, name2):
1109        p1_name = self._get_upper_name(name1)
1110        if not p1_name:
1111            p1_name = name1
1112        name = p1_name
1113        name += "%s"% (self.operator)
1114        p2_name = self._get_upper_name(name2)
1115        if not p2_name:
1116            p2_name = name2
1117        name += p2_name
1118        return name
1119   
1120    def _get_upper_name(self, name=None):
1121        if name == None:
1122            return ""
1123        upper_name = ""
1124        str_name = str(name)
1125        for index in range(len(str_name)):
1126            if str_name[index].isupper():
1127                upper_name += str_name[index]
1128        return upper_name
1129       
1130    def _set_dispersion(self):
1131        ##set dispersion only from p_model
1132        for name , value in self.p_model1.dispersion.iteritems():
1133            #if name.lower() not in self.p_model1.orientation_params:
1134            new_name = "p1_" + name
1135            self.dispersion[new_name]= value
1136        for name , value in self.p_model2.dispersion.iteritems():
1137            #if name.lower() not in self.p_model2.orientation_params:
1138            new_name = "p2_" + name
1139            self.dispersion[new_name]= value
1140           
1141    def function(self, x=0.0):
1142        return 0
1143                               
1144    def getProfile(self):
1145        try:
1146            x,y = self.p_model1.getProfile()
1147        except:
1148            x = None
1149            y = None
1150           
1151        return x, y
1152   
1153    def _set_params(self):
1154        for name , value in self.p_model1.params.iteritems():
1155            # No 2D-supported
1156            #if name not in self.p_model1.orientation_params:
1157            new_name = "p1_" + name
1158            self.params[new_name]= value
1159           
1160        for name , value in self.p_model2.params.iteritems():
1161            # No 2D-supported
1162            #if name not in self.p_model2.orientation_params:
1163            new_name = "p2_" + name
1164            self.params[new_name]= value
1165               
1166        # Set "scale" as initializing
1167        self._set_scale_factor()
1168     
1169           
1170    def _set_details(self):
1171        for name ,detail in self.p_model1.details.iteritems():
1172            new_name = "p1_" + name
1173            #if new_name not in self.orientation_params:
1174            self.details[new_name]= detail
1175           
1176        for name ,detail in self.p_model2.details.iteritems():
1177            new_name = "p2_" + name
1178            #if new_name not in self.orientation_params:
1179            self.details[new_name]= detail
1180   
1181    def _set_scale_factor(self):
1182        pass
1183       
1184               
1185    def setParam(self, name, value):
1186        # set param to this (p1, p2) model
1187        self._setParamHelper(name, value)
1188       
1189        ## setParam to p model
1190        model_pre = name.split('_', 1)[0]
1191        new_name = name.split('_', 1)[1]
1192        if model_pre == "p1":
1193            if new_name in self.p_model1.getParamList():
1194                self.p_model1.setParam(new_name, value)
1195        elif model_pre == "p2":
1196             if new_name in self.p_model2.getParamList():
1197                self.p_model2.setParam(new_name, value)
1198        elif name.lower() == 'scale_factor':
1199            self.params['scale_factor'] = value
1200        else:
1201            raise ValueError, "Model does not contain parameter %s" % name
1202           
1203    def getParam(self, name):
1204        # Look for dispersion parameters
1205        toks = name.split('.')
1206        if len(toks)==2:
1207            for item in self.dispersion.keys():
1208                # 2D not supported
1209                if item.lower()==toks[0].lower():
1210                    for par in self.dispersion[item]:
1211                        if par.lower() == toks[1].lower():
1212                            return self.dispersion[item][par]
1213        else:
1214            # Look for standard parameter
1215            for item in self.params.keys():
1216                if item.lower()==name.lower():
1217                    return self.params[item]
1218        return 
1219        #raise ValueError, "Model does not contain parameter %s" % name
1220       
1221    def _setParamHelper(self, name, value):
1222        # Look for dispersion parameters
1223        toks = name.split('.')
1224        if len(toks)== 2:
1225            for item in self.dispersion.keys():
1226                if item.lower()== toks[0].lower():
1227                    for par in self.dispersion[item]:
1228                        if par.lower() == toks[1].lower():
1229                            self.dispersion[item][par] = value
1230                            return
1231        else:
1232            # Look for standard parameter
1233            for item in self.params.keys():
1234                if item.lower()== name.lower():
1235                    self.params[item] = value
1236                    return
1237           
1238        raise ValueError, "Model does not contain parameter %s" % name
1239             
1240   
1241    def _set_fixed_params(self):
1242        for item in self.p_model1.fixed:
1243            new_item = "p1" + item
1244            self.fixed.append(new_item)
1245        for item in self.p_model2.fixed:
1246            new_item = "p2" + item
1247            self.fixed.append(new_item)
1248
1249        self.fixed.sort()
1250               
1251                   
1252    def run(self, x = 0.0):
1253        self._set_scale_factor()
1254        return self.params['scale_factor'] %s \
1255(self.p_model1.run(x) %s self.p_model2.run(x))
1256   
1257    def runXY(self, x = 0.0):
1258        self._set_scale_factor()
1259        return self.params['scale_factor'] %s \
1260(self.p_model1.runXY(x) %s self.p_model2.runXY(x))
1261   
1262    ## Now (May27,10) directly uses the model eval function
1263    ## instead of the for-loop in Base Component.
1264    def evalDistribution(self, x = []):
1265        self._set_scale_factor()
1266        return self.params['scale_factor'] %s \
1267(self.p_model1.evalDistribution(x) %s \
1268self.p_model2.evalDistribution(x))
1269
1270    def set_dispersion(self, parameter, dispersion):
1271        value= None
1272        new_pre = parameter.split("_", 1)[0]
1273        new_parameter = parameter.split("_", 1)[1]
1274        try:
1275            if new_pre == 'p1' and \
1276new_parameter in self.p_model1.dispersion.keys():
1277                value= self.p_model1.set_dispersion(new_parameter, dispersion)
1278            if new_pre == 'p2' and \
1279new_parameter in self.p_model2.dispersion.keys():
1280                value= self.p_model2.set_dispersion(new_parameter, dispersion)
1281            self._set_dispersion()
1282            return value
1283        except:
1284            raise
1285
1286    def fill_description(self, p_model1, p_model2):
1287        description = ""
1288        description += "This model gives the summation or multiplication of"
1289        description += "%s and %s. "% ( p_model1.name, p_model2.name )
1290        self.description += description
1291         
1292    def get_fname(self):
1293        path = sys._getframe().f_code.co_filename
1294        basename  = os.path.basename(path)
1295        name, _ = os.path.splitext(basename)
1296        return name     
1297           
1298if __name__ == "__main__":
1299    m1= Model()
1300    #m1.setParam("p1_scale", 25) 
1301    #m1.setParam("p1_length", 1000)
1302    #m1.setParam("p2_scale", 100)
1303    #m1.setParam("p2_rg", 100)
1304    out1 = m1.runXY(0.01)
1305
1306    m2= Model()
1307    #m2.p_model1.setParam("scale", 25)
1308    #m2.p_model1.setParam("length", 1000)
1309    #m2.p_model2.setParam("scale", 100)
1310    #m2.p_model2.setParam("rg", 100)
1311    out2 = m2.p_model1.runXY(0.01) %s m2.p_model2.runXY(0.01)\n
1312    print "My name is %s."% m1.name
1313    print out1, " = ", out2
1314    if out1 == out2:
1315        print "===> Simple Test: Passed!"
1316    else:
1317        print "===> Simple Test: Failed!"
1318"""
1319     
1320#if __name__ == "__main__":
1321#    app = wx.PySimpleApp()
1322#    frame = TextDialog(id=1, model_list=["SphereModel", "CylinderModel"])   
1323#    frame.Show(True)
1324#    app.MainLoop()             
1325
1326if __name__ == "__main__":
1327    from sans.perspectives.fitting import models
1328    dir_path = models.find_plugins_dir()
1329    app  = wx.App()
1330    window = EditorWindow(parent=None, base=None, path=dir_path, title="Editor")
1331    app.MainLoop()         
Note: See TracBrowser for help on using the repository browser.