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

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

fixing mac bug on panel

  • Property mode set to 100644
File size: 48.6 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 = 350
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        # For Mac
378        if event != None:
379            event.Skip()
380           
381        item = event.GetEventObject()
382        text = item.GetValue().strip()
383        if text == '+':
384            name = 'Sum'
385            factor = 'scale_factor'
386            f_oper = '*'
387        elif text == '*':
388            name = 'Multi'
389            factor = 'BackGround'
390            f_oper = '+'
391        else:
392            raise
393        self.factor = str(factor)
394        self.operator = text
395        self.explanation = "  Custom Model = %s %s (model1 %s model2)\n"% \
396                    (self.factor, f_oper, self.operator)
397        self.explanationctr.SetLabel(self.explanation)
398        self.name = name + M_NAME
399        self.sizer.Layout()
400             
401    def fill_oprator_combox(self):
402        """
403        fill the current combobox with the operator
404        """   
405        operator_list = [' +', ' *']
406        for oper in operator_list:
407            pos = self.operator_cbox.Append(str(oper))
408            self.operator_cbox.SetClientData(pos, str(oper.strip()))
409        self.operator_cbox.SetSelection(0)
410           
411    def getText(self):
412        """
413        Returns model name string as list
414        """
415        return [self.model1_name, self.model2_name]
416   
417    def write_string(self, fname, name1, name2):
418        """
419        Write and Save file
420        """
421        self.fname = fname 
422        description = self.desc_tcl.GetValue().lstrip().rstrip()
423        if description == '':
424            description = name1 + self.operator + name2
425        name = self.name_tcl.GetValue().lstrip().rstrip()
426        text = self.operator_cbox.GetLabel().strip()
427        if text == '+':
428            factor = 'scale_factor'
429            f_oper = '*'
430            default_val = '1.0'
431        else:
432            factor = 'BackGround'
433            f_oper = '+'
434            default_val = '0.0'
435        path = self.fname
436        try:
437            out_f =  open(path,'w')
438        except :
439            raise
440        lines = SUM_TEMPLATE.split('\n')
441        for line in lines:
442            try:
443                if line.count("scale_factor"):
444                    line = line.replace('scale_factor', factor)
445                    #print "scale_factor", line
446                if line.count("= %s"):
447                    out_f.write(line % (default_val) + "\n")
448                elif line.count("import Model as P1"):
449                    if self.is_p1_custom:
450                        line = line.replace('#', '')
451                        out_f.write(line % name1 + "\n")
452                    else:
453                        out_f.write(line + "\n")
454                elif line.count("import %s as P1"):
455                    if not self.is_p1_custom:
456                        line = line.replace('#', '')
457                        out_f.write(line % (name1, name1) + "\n")
458                    else:
459                        out_f.write(line + "\n")
460                elif line.count("import Model as P2"):
461                    if self.is_p2_custom:
462                        line = line.replace('#', '')
463                        out_f.write(line % name2 + "\n")
464                    else:
465                        out_f.write(line + "\n")
466                elif line.count("import %s as P2"):
467                    if not self.is_p2_custom:
468                        line = line.replace('#', '')
469                        out_f.write(line % (name2, name2) + "\n")
470                    else:
471                        out_f.write(line + "\n")
472                elif line.count("self.description = '%s'"):
473                    out_f.write(line % description + "\n")
474                #elif line.count("run") and line.count("%s"):
475                #    out_f.write(line % self.operator + "\n")
476                #elif line.count("evalDistribution") and line.count("%s"):
477                #    out_f.write(line % self.operator + "\n")
478                elif line.count("return") and line.count("%s") == 2:
479                    #print "line return", line
480                    out_f.write(line % (f_oper, self.operator) + "\n")
481                elif line.count("out2")and line.count("%s"):
482                    out_f.write(line % self.operator + "\n")
483                else:
484                    out_f.write(line + "\n")
485            except:
486                raise
487        out_f.close()
488        #else:
489        #    msg = "Name exists already."
490       
491    def compile_file(self, path):
492        """
493        Compile the file in the path
494        """
495        path = self.fname
496        _compileFile(path)
497       
498    def delete_file(self, path):
499        """
500        Delete file in the path
501        """
502        _deleteFile(path)
503
504
505class EditorPanel(wx.ScrolledWindow):
506    """
507    Custom model function editor
508    """
509    def __init__(self, parent, base, path, title, *args, **kwds):
510        kwds['name'] = title
511        kwds["size"] = (EDITOR_WIDTH, EDITOR_HEIGTH)
512        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
513        wx.ScrolledWindow.__init__(self, parent, *args, **kwds)
514        #self.SetupScrolling()
515        self.parent = parent
516        self.base = base
517        self.path = path
518        self.font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
519        self.font.SetPointSize(10)
520        self.reader = None
521        self.name = 'untitled'
522        self.overwrite_name = False
523        self.is_2d = False
524        self.fname = None
525        self.param_strings = ''
526        self.function_strings = ''
527        self._notes = ""
528        self._msg_box = None
529        self.msg_sizer = None
530        self.warning = ""
531        self._description = "New Custom Model"
532        #self._default_save_location = os.getcwd()
533        self._do_layout()
534        #self.bt_apply.Disable()
535
536             
537    def _define_structure(self):
538        """
539        define initial sizer
540        """
541        #w, h = self.parent.GetSize()
542        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
543        self.name_sizer = wx.BoxSizer(wx.VERTICAL)
544        self.name_hsizer = wx.BoxSizer(wx.HORIZONTAL)
545        self.desc_sizer = wx.BoxSizer(wx.VERTICAL)
546        self.param_sizer = wx.BoxSizer(wx.VERTICAL)
547        self.function_sizer = wx.BoxSizer(wx.VERTICAL)
548        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
549        self.msg_sizer = wx.BoxSizer(wx.HORIZONTAL)
550       
551    def _layout_name(self):
552        """
553        Do the layout for file/function name related widgets
554        """
555        #title name [string]
556        name_txt = wx.StaticText(self, -1, 'Function Name : ') 
557        overwrite_cb = wx.CheckBox(self, -1, "Overwrite?", (10, 10))
558        overwrite_cb.SetValue(False)
559        overwrite_cb.SetToolTipString("Overwrite it if already exists?")
560        wx.EVT_CHECKBOX(self, overwrite_cb.GetId(), self.on_over_cb)
561        #overwrite_cb.Show(False)
562        self.name_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
563        self.name_tcl.Bind(wx.EVT_TEXT_ENTER, self.on_change_name)
564        self.name_tcl.SetValue('MyFunction')
565        self.name_tcl.SetFont(self.font)
566        hint_name = "Unique Model Function Name."
567        self.name_tcl.SetToolTipString(hint_name)
568        self.name_hsizer.AddMany([(self.name_tcl, 0, wx.LEFT|wx.TOP, 0),
569                                       (overwrite_cb, 0, wx.LEFT, 20)])
570        self.name_sizer.AddMany([(name_txt, 0, wx.LEFT|wx.TOP, 10),
571                                       (self.name_hsizer, 0, 
572                                        wx.LEFT|wx.TOP|wx.BOTTOM, 10)])
573       
574       
575    def _layout_description(self):
576        """
577        Do the layout for description related widgets
578        """
579        #title name [string]
580        desc_txt = wx.StaticText(self, -1, 'Description (optional) : ') 
581        self.desc_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
582        self.desc_tcl.SetValue('')
583        #self.name_tcl.SetFont(self.font)
584        hint_desc = "Write a short description of the model function."
585        self.desc_tcl.SetToolTipString(hint_desc)
586        self.desc_sizer.AddMany([(desc_txt, 0, wx.LEFT|wx.TOP, 10),
587                                       (self.desc_tcl, 0, 
588                                        wx.LEFT|wx.TOP|wx.BOTTOM, 10)])     
589    def _layout_param(self):
590        """
591        Do the layout for parameter related widgets
592        """
593        param_txt = wx.StaticText(self, -1, 'Fit Parameters (if any): ') 
594        param_tip = "#Set the parameters and initial values.\n"
595        param_tip += "#Example:\n"
596        param_tip += "A = 1\nB = 1"
597        #param_txt.SetToolTipString(param_tip)
598        id  = wx.NewId() 
599        self.param_tcl = EditWindow(self, id, wx.DefaultPosition, 
600                            wx.DefaultSize, wx.CLIP_CHILDREN|wx.SUNKEN_BORDER)
601        self.param_tcl.setDisplayLineNumbers(True)
602        self.param_tcl.SetToolTipString(param_tip)
603        self.param_sizer.AddMany([(param_txt, 0, wx.LEFT, 10),
604                        (self.param_tcl, 1, wx.EXPAND|wx.ALL, 10)])
605
606   
607    def _layout_function(self):
608        """
609        Do the layout for function related widgets
610        """
611        function_txt = wx.StaticText(self, -1, 'Function(x) : ') 
612        hint_function = "#Example:\n"
613        hint_function += "if x <= 0:\n"
614        hint_function += "    y = A + B\n"
615        hint_function += "else:\n"
616        hint_function += "    y = A + B * cos(2 * pi * x)\n"
617        hint_function += "return y\n"
618        id  = wx.NewId() 
619        self.function_tcl = EditWindow(self, id, wx.DefaultPosition, 
620                            wx.DefaultSize, wx.CLIP_CHILDREN|wx.SUNKEN_BORDER)
621        self.function_tcl.setDisplayLineNumbers(True)
622        self.function_tcl.SetToolTipString(hint_function)
623        self.function_sizer.Add(function_txt, 0, wx.LEFT, 10)
624        self.function_sizer.Add( self.function_tcl, 1, wx.EXPAND|wx.ALL, 10)
625       
626    def _layout_msg(self):
627        """
628        Layout msg
629        """
630        self._msg_box = wx.StaticText(self, -1, self._notes)
631        self.msg_sizer.Add(self._msg_box, 0, wx.LEFT, 10) 
632                   
633    def _layout_button(self): 
634        """
635        Do the layout for the button widgets
636        """         
637        self.bt_apply = wx.Button(self, -1, "Apply", size=(_BOX_WIDTH, -1))
638        self.bt_apply.SetToolTipString("Save changes into the imported data.")
639        self.bt_apply.Bind(wx.EVT_BUTTON, self.on_click_apply)
640       
641        self.bt_close = wx.Button(self, -1, 'Close', size=(_BOX_WIDTH, -1))
642        self.bt_close.Bind(wx.EVT_BUTTON, self.on_close)
643        self.bt_close.SetToolTipString("Close this panel.")
644       
645        self.button_sizer.AddMany([(self.bt_apply, 0, 
646                                    wx.LEFT, EDITOR_WIDTH * 0.8),
647                                   (self.bt_close, 0, 
648                                    wx.LEFT|wx.BOTTOM, 15)])
649         
650    def _do_layout(self):
651        """
652        Draw the current panel
653        """
654        self._define_structure()
655        self._layout_name()
656        self._layout_description()
657        self._layout_param()
658        self._layout_function()
659        self._layout_msg()
660        self._layout_button()
661        self.main_sizer.AddMany([(self.name_sizer, 0, 
662                                        wx.EXPAND|wx.ALL, 5),
663                                 (wx.StaticLine(self), 0, 
664                                       wx.ALL|wx.EXPAND, 5),
665                                 (self.desc_sizer, 0, 
666                                        wx.EXPAND|wx.ALL, 5),
667                                 (wx.StaticLine(self), 0, 
668                                       wx.ALL|wx.EXPAND, 5),
669                                (self.param_sizer, 1,
670                                         wx.EXPAND|wx.ALL, 5),
671                                 (wx.StaticLine(self), 0, 
672                                       wx.ALL|wx.EXPAND, 5),
673                                (self.function_sizer, 2,
674                                         wx.EXPAND|wx.ALL, 5),
675                                 (wx.StaticLine(self), 0, 
676                                       wx.ALL|wx.EXPAND, 5),
677                                 (self.msg_sizer, 0, 
678                                        wx.EXPAND|wx.ALL, 5),
679                                (self.button_sizer, 0,
680                                         wx.EXPAND|wx.ALL, 5)])
681        self.SetSizer(self.main_sizer)
682        self.SetAutoLayout(True)
683   
684    def get_notes(self):
685        """
686        return notes
687        """
688        return self._notes
689                 
690    def on_change_name(self, event=None):
691        """
692        Change name
693        """
694        if event is not None:
695            event.Skip()
696        self.name_tcl.SetBackgroundColour('white')
697        self.Refresh()
698   
699    def check_name(self):
700        """
701        Check name if exist already
702        """
703        self._notes = ''
704        self.on_change_name(None)
705        plugin_dir = self.path
706        list_fnames = os.listdir(plugin_dir)
707        # function/file name
708        title = self.name_tcl.GetValue().lstrip().rstrip()
709        self.name = title
710        t_fname = title + '.py'
711        if not self.overwrite_name:
712            if t_fname in list_fnames:
713                self.name_tcl.SetBackgroundColour('pink')
714                return False
715        self.fname = os.path.join(plugin_dir, t_fname)
716        s_title = title
717        if len(title) > 20:
718            s_title = title[0:19] + '...'
719        self._notes += "Model function name set "
720        self._notes += "to %s. \n" % str(s_title)
721        return True
722   
723    def on_over_cb(self, event):
724        """
725        Set overwrite name flag on cb event
726        """
727        if event is not None:
728            event.Skip()
729        cb = event.GetEventObject()
730        self.overwrite_name = cb.GetValue()
731       
732    def on_click_apply(self, event):
733        """   
734        Changes are saved in data object imported to edit
735        """
736        #must post event here
737        event.Skip()
738        info = 'Info'
739        # Sort out the errors if occur
740        if self.check_name():
741            name = self.name_tcl.GetValue().lstrip().rstrip()
742            description = self.desc_tcl.GetValue()
743            param_str = self.param_tcl.GetText()
744            func_str = self.function_tcl.GetText()
745            # No input for the model function
746            if func_str.lstrip().rstrip():
747                if func_str.count('return') > 0:
748                    self.write_file(self.fname, description, param_str, func_str)
749                    tr_msg = _compileFile(self.fname)
750                    msg = tr_msg.__str__()
751                    # Compile error
752                    if msg:
753                        _deleteFile(self.fname)
754                        msg +=  "\nCompile Failed"
755                    else:
756                        msg = ''
757                else:
758                    msg = "Error: The func(x) must 'return' a value at least.\n"
759                    msg += "For example: \n\nreturn 2*x"
760            else:
761                msg = 'Error: Function is not defined.'
762        else:
763            msg = "Name exists already."
764        # Prepare for the messagebox
765        if not msg:
766            if self.base != None:
767                self.base.update_custom_combo()
768            msg = "Successful!!!"
769            msg += "  " + self._notes
770            msg += " Please look for it in the 'Customized Models' box."
771            info = 'Info'
772            color = 'blue'
773        else:
774            info = 'Error'
775            color = 'red'
776            wx.MessageBox(msg, info) 
777       
778        self._msg_box.SetLabel(msg)
779        self._msg_box.SetForegroundColour(color)
780        # Send msg to the top window 
781        if self.base != None:
782                from sans.guiframe.events import StatusEvent
783                wx.PostEvent(self.base.parent, StatusEvent(status = msg, 
784                                                      info=info))
785        self.warning = msg
786
787               
788    def write_file(self, fname, desc_str, param_str, func_str): 
789        """
790        Write content in file
791       
792        :param fname: full file path
793        :param desc_str: content of the description strings
794        :param param_str: content of params; Strings 
795        :param func_str: content of func; Strings
796        """ 
797        try:
798            out_f =  open(fname,'w')
799        except :
800            raise
801        # Prepare the content of the function
802        lines = CUSTOM_TEMPLATE.split('\n')
803
804        has_scipy = func_str.count("scipy.")
805        self.is_2d = func_str.count("#self.ndim = 2")
806        line_2d = ''
807        if self.is_2d:
808            line_2d = CUSTOM_2D_TEMP.split('\n')
809        line_test = TEST_TEMPLATE.split('\n')
810        local_params = ''
811        spaces = '        '#8spaces
812        # write function here
813        for line in lines:
814            # The location where to put the strings is
815            # hard-coded in the template as shown below.
816            if line.count("#self.params here"):
817                for param_line in param_str.split('\n'):
818                    p_line = param_line.lstrip().rstrip()
819                    if p_line:
820                        p0_line = self.set_param_helper(p_line)
821                        local_params += self.set_function_helper(p_line)
822                        out_f.write(p0_line)
823            elif line.count("#local params here"):
824                if local_params:
825                    out_f.write(local_params)
826            elif line.count("self.description = "):
827                des0 = self.name + "\\n"
828                desc = str(desc_str.lstrip().rstrip().replace('\"', ''))
829                out_f.write(line% (des0 + desc) + "\n")
830            elif line.count("def function(self, x=0.0%s):"):
831                if self.is_2d:
832                    y_str = ', y=0.0'
833                    out_f.write(line% y_str + "\n")
834                else:
835                    out_f.write(line% '' + "\n")
836            elif line.count("#function here"):
837                for func_line in func_str.split('\n'):
838                    f_line = func_line.rstrip()
839                    if f_line:
840                        out_f.write(spaces + f_line + "\n")
841                if not func_str:
842                    dep_var = 'y'
843                    if self.is_2d:
844                        dep_var = 'z'
845                    out_f.write(spaces + 'return %s'% dep_var + "\n")
846            elif line.count("#import scipy?"):
847                if has_scipy:
848                    out_f.write("import scipy" + "\n")
849            #elif line.count("name = "):
850            #    out_f.write(line % self.name + "\n")
851            elif line:
852                out_f.write(line + "\n")
853        # run string for 2d
854        if line_2d:
855            for line in line_2d:
856                out_f.write(line + "\n")
857        # Test strins
858        for line in line_test:
859            out_f.write(line + "\n")
860   
861        out_f.close() 
862   
863    def set_param_helper(self, line):   
864        """
865        Get string in line to define the params dictionary
866       
867        :param line: one line of string got from the param_str
868        """
869        flag = True
870        params_str = ''
871        spaces = '        '#8spaces
872        items = line.split(";")
873        for item in items:
874            name = item.split("=")[0].lstrip().rstrip()
875            try:
876                value = item.split("=")[1].lstrip().rstrip()
877                float(value)
878            except:
879                value = 1.0 # default
880            params_str += spaces + "self.params['%s'] = %s\n"% (name, value)
881           
882        return params_str
883
884    def set_function_helper(self, line):   
885        """
886        Get string in line to define the local params
887       
888        :param line: one line of string got from the param_str
889        """
890        flag = True
891        params_str = ''
892        spaces = '        '#8spaces
893        items = line.split(";")
894        for item in items:
895            name = item.split("=")[0].lstrip().rstrip()
896            params_str += spaces + "%s = self.params['%s']\n"% (name, name)
897        return params_str
898   
899    def get_warning(self):
900        """
901        Get the warning msg
902        """
903        return self.warning
904       
905    def on_close(self, event):
906        """
907        leave data as it is and close
908        """
909        self.parent.Close()
910        event.Skip()
911       
912class EditorWindow(wx.Frame):
913    """
914    Editor Window
915    """
916    def __init__(self, parent, base, path, title, 
917                 size=(EDITOR_WIDTH, EDITOR_HEIGTH), *args, **kwds):
918        """
919        Init
920        """
921        kwds["title"] = title
922        kwds["size"] = size
923        wx.Frame.__init__(self, parent=None, *args, **kwds)
924        self.parent = parent
925        self.panel = EditorPanel(parent=self, base=parent, 
926                                 path=path, title=title)
927        self.Show(True)
928        wx.EVT_CLOSE(self, self.OnClose)
929   
930    def OnClose(self, event): 
931        """
932        On close event
933        """
934        if self.parent != None:
935            self.parent.new_model_frame = None
936        self.Destroy() 
937
938## Templates for custom models
939CUSTOM_TEMPLATE = """
940from sans.models.pluginmodel import Model1DPlugin
941from math import *
942import os
943import sys
944import numpy
945#import scipy?
946class Model(Model1DPlugin):
947    name = ""                             
948    def __init__(self):
949        Model1DPlugin.__init__(self, name=self.name) 
950        #set name same as file name
951        self.name = self.get_fname()                                                   
952        #self.params here
953        self.description = "%s"
954        self.set_details()
955    def function(self, x=0.0%s):
956        #local params here
957        #function here
958"""
959CUSTOM_2D_TEMP = """
960    def run(self, x=0.0, y=0.0):
961        if x.__class__.__name__ == 'list':
962            x_val = x[0]
963            y_val = y[0]*0.0
964            return self.function(x_val, y_val)
965        elif x.__class__.__name__ == 'tuple':
966            msg = "Tuples are not allowed as input to BaseComponent models"
967            raise ValueError, msg
968        else:
969            return self.function(x, 0.0)
970    def runXY(self, x=0.0, y=0.0):
971        if x.__class__.__name__ == 'list':
972            return self.function(x, y)
973        elif x.__class__.__name__ == 'tuple':
974            msg = "Tuples are not allowed as input to BaseComponent models"
975            raise ValueError, msg
976        else:
977            return self.function(x, y)
978    def evalDistribution(self, qdist):
979        if qdist.__class__.__name__ == 'list':
980            msg = "evalDistribution expects a list of 2 ndarrays"
981            if len(qdist)!=2:
982                raise RuntimeError, msg
983            if qdist[0].__class__.__name__ != 'ndarray':
984                raise RuntimeError, msg
985            if qdist[1].__class__.__name__ != 'ndarray':
986                raise RuntimeError, msg
987            v_model = numpy.vectorize(self.runXY, otypes=[float])
988            iq_array = v_model(qdist[0], qdist[1])
989            return iq_array
990        elif qdist.__class__.__name__ == 'ndarray':
991            v_model = numpy.vectorize(self.runXY, otypes=[float])
992            iq_array = v_model(qdist)
993            return iq_array
994"""
995TEST_TEMPLATE = """
996    def get_fname(self):
997        path = sys._getframe().f_code.co_filename
998        basename  = os.path.basename(path)
999        name, _ = os.path.splitext(basename)
1000        return name
1001######################################################################
1002## THIS IS FOR TEST. DO NOT MODIFY THE FOLLOWING LINES!!!!!!!!!!!!!!!!       
1003if __name__ == "__main__":
1004    m= Model()
1005    out1 = m.runXY(0.0)
1006    out2 = m.runXY(0.01)
1007    isfine1 = numpy.isfinite(out1)
1008    isfine2 = numpy.isfinite(out2)
1009    print "Testing the value at Q = 0.0:"
1010    print out1, " : finite? ", isfine1
1011    print "Testing the value at Q = 0.01:"
1012    print out2, " : finite? ", isfine2
1013    if isfine1 and isfine2:
1014        print "===> Simple Test: Passed!"
1015    else:
1016        print "===> Simple Test: Failed!"
1017"""
1018SUM_TEMPLATE = """
1019# A sample of an experimental model function for Sum/Multiply(Pmodel1,Pmodel2)
1020import copy
1021from sans.models.pluginmodel import Model1DPlugin
1022# User can change the name of the model (only with single functional model)
1023#P1_model:
1024#from sans.models.%s import %s as P1
1025#from %s import Model as P1
1026
1027#P2_model:
1028#from sans.models.%s import %s as P2
1029#from %s import Model as P2
1030import os
1031import sys
1032
1033class Model(Model1DPlugin):
1034    name = ""
1035    def __init__(self):
1036        Model1DPlugin.__init__(self, name='')
1037        p_model1 = P1()
1038        p_model2 = P2()
1039        ## Setting  model name model description
1040        self.description = '%s'
1041        self.name = self.get_fname()
1042        if self.name.rstrip().lstrip() == '':
1043            self.name = self._get_name(p_model1.name, p_model2.name)
1044        if self.description.rstrip().lstrip() == '':
1045            self.description = p_model1.name
1046            self.description += p_model2.name
1047            self.fill_description(p_model1, p_model2)
1048
1049        ## Define parameters
1050        self.params = {}
1051
1052        ## Parameter details [units, min, max]
1053        self.details = {}
1054       
1055        # non-fittable parameters
1056        self.non_fittable = p_model1.non_fittable 
1057        self.non_fittable += p_model2.non_fittable 
1058           
1059        ##models
1060        self.p_model1= p_model1
1061        self.p_model2= p_model2
1062       
1063       
1064        ## dispersion
1065        self._set_dispersion()
1066        ## Define parameters
1067        self._set_params()
1068        ## New parameter:scaling_factor
1069        self.params['scale_factor'] = %s
1070       
1071        ## Parameter details [units, min, max]
1072        self._set_details()
1073        self.details['scale_factor'] = ['', None, None]
1074
1075       
1076        #list of parameter that can be fitted
1077        self._set_fixed_params() 
1078        ## parameters with orientation
1079        for item in self.p_model1.orientation_params:
1080            new_item = "p1_" + item
1081            if not new_item in self.orientation_params:
1082                self.orientation_params.append(new_item)
1083           
1084        for item in self.p_model2.orientation_params:
1085            new_item = "p2_" + item
1086            if not new_item in self.orientation_params:
1087                self.orientation_params.append(new_item)
1088        # get multiplicity if model provide it, else 1.
1089        try:
1090            multiplicity1 = p_model1.multiplicity
1091            try:
1092                multiplicity2 = p_model2.multiplicity
1093            except:
1094                multiplicity2 = 1
1095        except:
1096            multiplicity1 = 1
1097            multiplicity2 = 1
1098        ## functional multiplicity of the model
1099        self.multiplicity1 = multiplicity1 
1100        self.multiplicity2 = multiplicity2   
1101        self.multiplicity_info = []   
1102       
1103    def _clone(self, obj):
1104        obj.params     = copy.deepcopy(self.params)
1105        obj.description     = copy.deepcopy(self.description)
1106        obj.details    = copy.deepcopy(self.details)
1107        obj.dispersion = copy.deepcopy(self.dispersion)
1108        obj.p_model1  = self.p_model1.clone()
1109        obj.p_model2  = self.p_model2.clone()
1110        #obj = copy.deepcopy(self)
1111        return obj
1112   
1113    def _get_name(self, name1, name2):
1114        p1_name = self._get_upper_name(name1)
1115        if not p1_name:
1116            p1_name = name1
1117        name = p1_name
1118        name += "%s"% (self.operator)
1119        p2_name = self._get_upper_name(name2)
1120        if not p2_name:
1121            p2_name = name2
1122        name += p2_name
1123        return name
1124   
1125    def _get_upper_name(self, name=None):
1126        if name == None:
1127            return ""
1128        upper_name = ""
1129        str_name = str(name)
1130        for index in range(len(str_name)):
1131            if str_name[index].isupper():
1132                upper_name += str_name[index]
1133        return upper_name
1134       
1135    def _set_dispersion(self):
1136        ##set dispersion only from p_model
1137        for name , value in self.p_model1.dispersion.iteritems():
1138            #if name.lower() not in self.p_model1.orientation_params:
1139            new_name = "p1_" + name
1140            self.dispersion[new_name]= value
1141        for name , value in self.p_model2.dispersion.iteritems():
1142            #if name.lower() not in self.p_model2.orientation_params:
1143            new_name = "p2_" + name
1144            self.dispersion[new_name]= value
1145           
1146    def function(self, x=0.0):
1147        return 0
1148                               
1149    def getProfile(self):
1150        try:
1151            x,y = self.p_model1.getProfile()
1152        except:
1153            x = None
1154            y = None
1155           
1156        return x, y
1157   
1158    def _set_params(self):
1159        for name , value in self.p_model1.params.iteritems():
1160            # No 2D-supported
1161            #if name not in self.p_model1.orientation_params:
1162            new_name = "p1_" + name
1163            self.params[new_name]= value
1164           
1165        for name , value in self.p_model2.params.iteritems():
1166            # No 2D-supported
1167            #if name not in self.p_model2.orientation_params:
1168            new_name = "p2_" + name
1169            self.params[new_name]= value
1170               
1171        # Set "scale" as initializing
1172        self._set_scale_factor()
1173     
1174           
1175    def _set_details(self):
1176        for name ,detail in self.p_model1.details.iteritems():
1177            new_name = "p1_" + name
1178            #if new_name not in self.orientation_params:
1179            self.details[new_name]= detail
1180           
1181        for name ,detail in self.p_model2.details.iteritems():
1182            new_name = "p2_" + name
1183            #if new_name not in self.orientation_params:
1184            self.details[new_name]= detail
1185   
1186    def _set_scale_factor(self):
1187        pass
1188       
1189               
1190    def setParam(self, name, value):
1191        # set param to this (p1, p2) model
1192        self._setParamHelper(name, value)
1193       
1194        ## setParam to p model
1195        model_pre = name.split('_', 1)[0]
1196        new_name = name.split('_', 1)[1]
1197        if model_pre == "p1":
1198            if new_name in self.p_model1.getParamList():
1199                self.p_model1.setParam(new_name, value)
1200        elif model_pre == "p2":
1201             if new_name in self.p_model2.getParamList():
1202                self.p_model2.setParam(new_name, value)
1203        elif name.lower() == 'scale_factor':
1204            self.params['scale_factor'] = value
1205        else:
1206            raise ValueError, "Model does not contain parameter %s" % name
1207           
1208    def getParam(self, name):
1209        # Look for dispersion parameters
1210        toks = name.split('.')
1211        if len(toks)==2:
1212            for item in self.dispersion.keys():
1213                # 2D not supported
1214                if item.lower()==toks[0].lower():
1215                    for par in self.dispersion[item]:
1216                        if par.lower() == toks[1].lower():
1217                            return self.dispersion[item][par]
1218        else:
1219            # Look for standard parameter
1220            for item in self.params.keys():
1221                if item.lower()==name.lower():
1222                    return self.params[item]
1223        return 
1224        #raise ValueError, "Model does not contain parameter %s" % name
1225       
1226    def _setParamHelper(self, name, value):
1227        # Look for dispersion parameters
1228        toks = name.split('.')
1229        if len(toks)== 2:
1230            for item in self.dispersion.keys():
1231                if item.lower()== toks[0].lower():
1232                    for par in self.dispersion[item]:
1233                        if par.lower() == toks[1].lower():
1234                            self.dispersion[item][par] = value
1235                            return
1236        else:
1237            # Look for standard parameter
1238            for item in self.params.keys():
1239                if item.lower()== name.lower():
1240                    self.params[item] = value
1241                    return
1242           
1243        raise ValueError, "Model does not contain parameter %s" % name
1244             
1245   
1246    def _set_fixed_params(self):
1247        for item in self.p_model1.fixed:
1248            new_item = "p1" + item
1249            self.fixed.append(new_item)
1250        for item in self.p_model2.fixed:
1251            new_item = "p2" + item
1252            self.fixed.append(new_item)
1253
1254        self.fixed.sort()
1255               
1256                   
1257    def run(self, x = 0.0):
1258        self._set_scale_factor()
1259        return self.params['scale_factor'] %s \
1260(self.p_model1.run(x) %s self.p_model2.run(x))
1261   
1262    def runXY(self, x = 0.0):
1263        self._set_scale_factor()
1264        return self.params['scale_factor'] %s \
1265(self.p_model1.runXY(x) %s self.p_model2.runXY(x))
1266   
1267    ## Now (May27,10) directly uses the model eval function
1268    ## instead of the for-loop in Base Component.
1269    def evalDistribution(self, x = []):
1270        self._set_scale_factor()
1271        return self.params['scale_factor'] %s \
1272(self.p_model1.evalDistribution(x) %s \
1273self.p_model2.evalDistribution(x))
1274
1275    def set_dispersion(self, parameter, dispersion):
1276        value= None
1277        new_pre = parameter.split("_", 1)[0]
1278        new_parameter = parameter.split("_", 1)[1]
1279        try:
1280            if new_pre == 'p1' and \
1281new_parameter in self.p_model1.dispersion.keys():
1282                value= self.p_model1.set_dispersion(new_parameter, dispersion)
1283            if new_pre == 'p2' and \
1284new_parameter in self.p_model2.dispersion.keys():
1285                value= self.p_model2.set_dispersion(new_parameter, dispersion)
1286            self._set_dispersion()
1287            return value
1288        except:
1289            raise
1290
1291    def fill_description(self, p_model1, p_model2):
1292        description = ""
1293        description += "This model gives the summation or multiplication of"
1294        description += "%s and %s. "% ( p_model1.name, p_model2.name )
1295        self.description += description
1296         
1297    def get_fname(self):
1298        path = sys._getframe().f_code.co_filename
1299        basename  = os.path.basename(path)
1300        name, _ = os.path.splitext(basename)
1301        return name     
1302           
1303if __name__ == "__main__":
1304    m1= Model()
1305    #m1.setParam("p1_scale", 25) 
1306    #m1.setParam("p1_length", 1000)
1307    #m1.setParam("p2_scale", 100)
1308    #m1.setParam("p2_rg", 100)
1309    out1 = m1.runXY(0.01)
1310
1311    m2= Model()
1312    #m2.p_model1.setParam("scale", 25)
1313    #m2.p_model1.setParam("length", 1000)
1314    #m2.p_model2.setParam("scale", 100)
1315    #m2.p_model2.setParam("rg", 100)
1316    out2 = m2.p_model1.runXY(0.01) %s m2.p_model2.runXY(0.01)\n
1317    print "My name is %s."% m1.name
1318    print out1, " = ", out2
1319    if out1 == out2:
1320        print "===> Simple Test: Passed!"
1321    else:
1322        print "===> Simple Test: Failed!"
1323"""
1324     
1325#if __name__ == "__main__":
1326#    app = wx.PySimpleApp()
1327#    frame = TextDialog(id=1, model_list=["SphereModel", "CylinderModel"])   
1328#    frame.Show(True)
1329#    app.MainLoop()             
1330
1331if __name__ == "__main__":
1332    from sans.perspectives.fitting import models
1333    dir_path = models.find_plugins_dir()
1334    app  = wx.App()
1335    window = EditorWindow(parent=None, base=None, path=dir_path, title="Editor")
1336    app.MainLoop()         
Note: See TracBrowser for help on using the repository browser.