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

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

Popup dialog on status event with error

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