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

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

batch window: distinguishes non-numeric/empty cells in hightlighed cells

  • Property mode set to 100644
File size: 49.2 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
14import subprocess
15
16if sys.platform.count("win32") > 0:
17    FONT_VARIANT = 0
18    PNL_WIDTH = 450
19    PNL_HITE = 320
20else:
21    FONT_VARIANT = 1
22    PNL_WIDTH = 590
23    PNL_HITE = 350
24M_NAME = 'Model'
25EDITOR_WIDTH = 800
26EDITOR_HEIGTH = 720
27PANEL_WIDTH = 500
28_BOX_WIDTH = 55
29
30   
31def _compileFile(path):
32    """
33    Compile the file in the path
34    """
35    try:
36        import py_compile
37        py_compile.compile(file=path, doraise=True)
38        return ''
39    except:
40        _, value, _ = sys.exc_info()
41        return value
42   
43def _deleteFile(path):
44    """
45    Delete file in the path
46    """
47    try:
48        os.remove(path)
49    except:
50        raise
51
52 
53class TextDialog(wx.Dialog):
54    """
55    Dialog for easy custom sum models 
56    """
57    def __init__(self, parent=None, base=None, id=None, title='', 
58                 model_list=[], plugin_dir=None):
59        """
60        Dialog window popup when selecting 'Easy Custom Sum/Multiply'
61        on the menu
62        """
63        wx.Dialog.__init__(self, parent=parent, id=id, 
64                           title=title, size=(PNL_WIDTH, PNL_HITE))
65        self.parent = base
66        #Font
67        self.SetWindowVariant(variant=FONT_VARIANT)
68        # default
69        self.font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
70        self.font.SetPointSize(10)
71        self.overwrite_name = False
72        self.plugin_dir = plugin_dir
73        self.model_list = model_list
74        self.model1_string = "SphereModel"
75        self.model2_string = "CylinderModel"
76        self.name = 'Sum' + M_NAME
77        self.factor = 'scale_factor'
78        self._notes = ''
79        self.operator = '+'
80        self.operator_cbox = None
81        self.explanation = ''
82        self.explanationctr = None
83        self.sizer = None
84        self.name_sizer = None
85        self.name_hsizer = None
86        self.desc_sizer = None
87        self.desc_tcl = None
88        self.model1 = None
89        self.model2 = None
90        self.static_line_1 = None
91        self.okButton = None
92        self.closeButton = None
93        self._msg_box = None
94        self.msg_sizer = None
95        self.fname = None
96        self.cm_list = None
97        self.is_p1_custom = False
98        self.is_p2_custom = False
99        self._build_sizer()
100        self.model1_name = str(self.model1.GetValue())
101        self.model2_name = str(self.model2.GetValue())
102        self.good_name = True
103        self.fill_oprator_combox()
104       
105    def _layout_name(self):
106        """
107        Do the layout for file/function name related widgets
108        """
109        self.name_sizer = wx.BoxSizer(wx.VERTICAL)
110        self.name_hsizer = wx.BoxSizer(wx.HORIZONTAL)
111        #title name [string]
112        name_txt = wx.StaticText(self, -1, 'Function Name : ') 
113        self.name_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
114        self.name_tcl.Bind(wx.EVT_TEXT_ENTER, self.on_change_name)
115        self.name_tcl.SetValue('')
116        self.name_tcl.SetFont(self.font)
117        hint_name = "Unique Sum/Multiply Model Function Name."
118        self.name_tcl.SetToolTipString(hint_name)
119        self.name_hsizer.AddMany([(name_txt, 0, wx.LEFT|wx.TOP, 10),
120                            (self.name_tcl, -1, 
121                             wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 10)])
122        self.name_sizer.AddMany([(self.name_hsizer, -1, 
123                                        wx.LEFT|wx.TOP, 10)])
124       
125       
126    def _layout_description(self):
127        """
128        Do the layout for description related widgets
129        """
130        self.desc_sizer = wx.BoxSizer(wx.HORIZONTAL)
131        #title name [string]
132        desc_txt = wx.StaticText(self, -1, 'Description (optional) : ') 
133        self.desc_tcl = wx.TextCtrl(self, -1, size=(PANEL_WIDTH*3/5, -1)) 
134        self.desc_tcl.SetValue('')
135        #self.name_tcl.SetFont(self.font)
136        hint_desc = "Write a short description of this model function."
137        self.desc_tcl.SetToolTipString(hint_desc)
138        self.desc_sizer.AddMany([(desc_txt, 0, wx.LEFT|wx.TOP, 10),
139                                (self.desc_tcl, -1, 
140                                wx.EXPAND|wx.RIGHT|wx.TOP|wx.BOTTOM, 10)])     
141 
142    def _build_sizer(self):
143        """
144        Build gui
145        """
146        box_width = 195 # combobox width
147        vbox  = wx.BoxSizer(wx.VERTICAL)
148        self.sizer = wx.GridBagSizer(1, 3)
149        self._layout_name()
150        self._layout_description()
151       
152       
153        sum_description = wx.StaticBox(self, -1, 'Select', 
154                                       size=(PNL_WIDTH-30, 70))
155        sum_box = wx.StaticBoxSizer(sum_description, wx.VERTICAL)
156        model1_box = wx.BoxSizer(wx.HORIZONTAL)
157        model2_box = wx.BoxSizer(wx.HORIZONTAL)
158        model_vbox = wx.BoxSizer(wx.VERTICAL)
159        self.model1 =  wx.ComboBox(self, -1, style=wx.CB_READONLY)
160        wx.EVT_COMBOBOX(self.model1, -1, self.on_model1)
161        self.model1.SetMinSize((box_width*5/6, -1))
162        self.model1.SetToolTipString("model1")
163       
164        self.operator_cbox = wx.ComboBox(self, -1, size=(50, -1), 
165                                         style=wx.CB_READONLY)
166        wx.EVT_COMBOBOX(self.operator_cbox, -1, self.on_select_operator)
167        operation_tip = "Add: +, Multiply: * "
168        self.operator_cbox.SetToolTipString(operation_tip)
169       
170        self.model2 =  wx.ComboBox(self, -1, style=wx.CB_READONLY)
171        wx.EVT_COMBOBOX(self.model2, -1, self.on_model2)
172        self.model2.SetMinSize((box_width*5/6, -1))
173        self.model2.SetToolTipString("model2")
174        self._set_model_list()
175       
176         # Buttons on the bottom
177        self.static_line_1 = wx.StaticLine(self, -1)
178        self.okButton = wx.Button(self,wx.ID_OK, 'Apply', size=(box_width/2, 25))
179        self.okButton.Bind(wx.EVT_BUTTON, self.check_name)
180        self.closeButton = wx.Button(self,wx.ID_CANCEL, 'Close', 
181                                     size=(box_width/2, 25))
182        # Intro
183        self.explanation  = "  custom model = %s %s "% (self.factor, '*')
184        self.explanation  += "(model1 %s model2)\n"% self.operator
185        #explanation  += "  Note: This will overwrite the previous sum model.\n"
186        model_string = " Model%s (p%s):"
187        # msg
188        self._msg_box = wx.StaticText(self, -1, self._notes)
189        self.msg_sizer = wx.BoxSizer(wx.HORIZONTAL)
190        self.msg_sizer.Add(self._msg_box, 0, wx.LEFT, 0)
191        vbox.Add(self.name_hsizer)
192        vbox.Add(self.desc_sizer)
193        vbox.Add(self.sizer)
194        ix = 0
195        iy = 1
196        self.explanationctr = wx.StaticText(self, -1, self.explanation)
197        self.sizer.Add(self.explanationctr , (iy, ix),
198                 (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
199        model1_box.Add(wx.StaticText(self, -1, model_string% (1, 1)), -1, 0)
200        model1_box.Add((box_width-15, 10))
201        model1_box.Add(wx.StaticText(self, -1, model_string% (2, 2)), -1, 0)
202        model2_box.Add(self.model1, -1, 0)
203        model2_box.Add((15, 10))
204        model2_box.Add(self.operator_cbox, 0, 0)
205        model2_box.Add((15, 10))
206        model2_box.Add(self.model2, -1, 0)
207        model_vbox.Add(model1_box, -1, 0)
208        model_vbox.Add(model2_box, -1, 0)
209        sum_box.Add(model_vbox, -1, 10)
210        iy += 1
211        ix = 0
212        self.sizer.Add(sum_box, (iy, ix),
213                  (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
214        vbox.Add((10, 10))
215        vbox.Add(self.static_line_1, 0, wx.EXPAND, 10)
216        vbox.Add(self.msg_sizer, 0, 
217                 wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE|wx.BOTTOM, 10)
218        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
219        sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
220        sizer_button.Add(self.okButton, 0, 
221                         wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 0)
222        sizer_button.Add(self.closeButton, 0,
223                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)       
224        vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
225         
226        self.SetSizer(vbox)
227        self.Centre()
228       
229    def on_change_name(self, event=None):
230        """
231        Change name
232        """
233        if event is not None:
234            event.Skip()
235        self.name_tcl.SetBackgroundColour('white')
236        self.Refresh()
237   
238    def check_name(self, event=None):
239        """
240        Check name if exist already
241        """
242        mname = M_NAME
243        self.on_change_name(None)
244        list_fnames = os.listdir(self.plugin_dir)
245        # fake existing regular model name list
246        m_list = [model + ".py" for model in self.model_list]
247        list_fnames.append(m_list)
248        # function/file name
249        title = self.name_tcl.GetValue().lstrip().rstrip()
250        if title == '':
251            text = self.operator
252            if text.count('+') > 0:
253                mname = 'Sum'
254            else:
255                mname = 'Multi'
256            mname += M_NAME
257            title = mname
258        self.name = title
259        t_fname = title + '.py'
260        if not self.overwrite_name:
261            if t_fname in list_fnames and title != mname:
262                self.name_tcl.SetBackgroundColour('pink')
263                self.good_name = False
264                info = 'Error'
265                msg = "Name exists already."
266                wx.MessageBox(msg, info) 
267                self._notes = msg
268                color = 'red'
269                self._msg_box.SetLabel(msg)
270                self._msg_box.SetForegroundColour(color)
271                return self.good_name
272        self.fname = os.path.join(self.plugin_dir, t_fname)
273        s_title = title
274        if len(title) > 20:
275            s_title = title[0:19] + '...'
276        self._notes = "Model function (%s) has been set! \n" % str(s_title)
277        self.good_name = True
278        self.on_apply(self.fname)
279        return self.good_name
280   
281    def on_apply(self, path):
282        """
283        On Apply
284        """
285        try:
286            label = self.getText()
287            fname = path
288            name1 = label[0]
289            name2 = label[1]
290            self.write_string(fname, name1, name2)
291            self.compile_file(fname)
292            self.parent.update_custom_combo()
293            msg = self._notes
294            info = 'Info'
295            color = 'blue'
296        except:
297            msg= "Easy Custom Sum/Multipy: Error occurred..."
298            info = 'Error'
299            color = 'red'
300        self._msg_box.SetLabel(msg)
301        self._msg_box.SetForegroundColour(color)
302        if self.parent.parent != None:
303            from sans.guiframe.events import StatusEvent
304            wx.PostEvent(self.parent.parent, StatusEvent(status = msg, 
305                                                      info=info))
306        else:
307            raise
308                 
309    def _set_model_list(self):
310        """
311        Set the list of models
312        """
313        # list of model names
314        cm_list = []
315        # models
316        list = self.model_list
317        # custom models
318        al_list = os.listdir(self.plugin_dir)
319        for c_name in al_list:
320            if c_name.split('.')[-1] == 'py' and \
321                    c_name.split('.')[0] != '__init__':
322                name = str(c_name.split('.')[0])
323                cm_list.append(name)
324                if name not in list:
325                    list.append(name)
326        self.cm_list = cm_list
327        if len(list) > 1:
328            list.sort()
329        for idx in range(len(list)):
330            self.model1.Append(str(list[idx]), idx) 
331            self.model2.Append(str(list[idx]), idx)
332        self.model1.SetStringSelection(self.model1_string)
333        self.model2.SetStringSelection(self.model2_string)
334   
335    def update_cm_list(self):
336        """
337        Update custom model list
338        """
339        cm_list = []
340        al_list = os.listdir(self.plugin_dir)
341        for c_name in al_list:
342            if c_name.split('.')[-1] == 'py' and \
343                    c_name.split('.')[0] != '__init__':
344                name = str(c_name.split('.')[0])
345                cm_list.append(name)
346        self.cm_list = cm_list
347             
348    def on_model1(self, event):
349        """
350        Set model1
351        """
352        event.Skip()
353        self.update_cm_list()
354        self.model1_name = str(self.model1.GetValue())
355        self.model1_string = self.model1_name
356        if self.model1_name in self.cm_list:
357            self.is_p1_custom = True
358        else:
359            self.is_p1_custom = False
360           
361    def on_model2(self, event):
362        """
363        Set model2
364        """
365        event.Skip()
366        self.update_cm_list()
367        self.model2_name = str(self.model2.GetValue())
368        self.model2_string = self.model2_name
369        if self.model2_name in self.cm_list:
370            self.is_p2_custom = True
371        else:
372            self.is_p2_custom = False
373       
374    def on_select_operator(self, event=None):
375        """
376        On Select an Operator
377        """
378        # For Mac
379        if event != None:
380            event.Skip()
381        name = ''   
382        item = event.GetEventObject()
383        text = item.GetValue()
384        if text.count('*') > 0:
385            name = 'Multi'
386            factor = 'BackGround'
387            f_oper = '+'
388        else:
389            name = 'Sum'
390            factor = 'scale_factor'
391            f_oper = '*'
392
393        self.factor = 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.GetValue()
427        if text.count('+') > 0:
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        msg = ''
740        # Sort out the errors if occur
741        if self.check_name():
742            name = self.name_tcl.GetValue().lstrip().rstrip()
743            description = self.desc_tcl.GetValue()
744            param_str = self.param_tcl.GetText()
745            func_str = self.function_tcl.GetText()
746            # No input for the model function
747            if func_str.lstrip().rstrip():     
748                if func_str.count('return') > 0:
749                    self.write_file(self.fname, description, param_str, 
750                                                                    func_str)
751                    tr_msg = _compileFile(self.fname)
752                    msg = str(tr_msg.__str__())
753                    # Compile error
754                    if msg:
755                        msg.replace("  ", "\n")
756                        msg +=  "\nCompiling Failed"
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 self.base != None and not msg:
766            self.base.update_custom_combo()
767            Model  = None
768            exec "from %s import Model"% name
769            try:
770                Model().run(0.01) 
771            except:
772                msg = "Error "
773                _, value, _ = sys.exc_info()
774                msg += "in %s:\n%s\n" % (name,  value)
775        if msg:
776            info = 'Error'
777            color = 'red' 
778            try:
779                # try to remove pyc file if exists
780                _deleteFile(self.fname)
781                _deleteFile(self.fname + "c")
782            except:
783                pass
784        else:
785            msg = "Successful!!!"
786            msg += "  " + self._notes
787            msg += " Please look for it in the 'Customized Models' box."
788            info = 'Info'
789            color = 'blue'
790        # Not to display long error msg
791        if info == 'Error':
792            mss = info
793        else:
794            mss = msg
795        self._msg_box.SetLabel(mss)
796        self._msg_box.SetForegroundColour(color)
797        # Send msg to the top window 
798        if self.base != None:
799                from sans.guiframe.events import StatusEvent
800                wx.PostEvent(self.base.parent, StatusEvent(status = msg, 
801                                                      info=info))
802        self.warning = msg
803
804               
805    def write_file(self, fname, desc_str, param_str, func_str): 
806        """
807        Write content in file
808       
809        :param fname: full file path
810        :param desc_str: content of the description strings
811        :param param_str: content of params; Strings 
812        :param func_str: content of func; Strings
813        """ 
814        try:
815            out_f =  open(fname,'w')
816        except :
817            raise
818        # Prepare the content of the function
819        lines = CUSTOM_TEMPLATE.split('\n')
820
821        has_scipy = func_str.count("scipy.")
822        self.is_2d = func_str.count("#self.ndim = 2")
823        line_2d = ''
824        if self.is_2d:
825            line_2d = CUSTOM_2D_TEMP.split('\n')
826        line_test = TEST_TEMPLATE.split('\n')
827        local_params = ''
828        spaces = '        '#8spaces
829        # write function here
830        for line in lines:
831            # The location where to put the strings is
832            # hard-coded in the template as shown below.
833            if line.count("#self.params here"):
834                for param_line in param_str.split('\n'):
835                    p_line = param_line.lstrip().rstrip()
836                    if p_line:
837                        p0_line = self.set_param_helper(p_line)
838                        local_params += self.set_function_helper(p_line)
839                        out_f.write(p0_line)
840            elif line.count("#local params here"):
841                if local_params:
842                    out_f.write(local_params)
843            elif line.count("self.description = "):
844                des0 = self.name + "\\n"
845                desc = str(desc_str.lstrip().rstrip().replace('\"', ''))
846                out_f.write(line% (des0 + desc) + "\n")
847            elif line.count("def function(self, x=0.0%s):"):
848                if self.is_2d:
849                    y_str = ', y=0.0'
850                    out_f.write(line% y_str + "\n")
851                else:
852                    out_f.write(line% '' + "\n")
853            elif line.count("#function here"):
854                for func_line in func_str.split('\n'):
855                    f_line = func_line.rstrip()
856                    if f_line:
857                        out_f.write(spaces + f_line + "\n")
858                if not func_str:
859                    dep_var = 'y'
860                    if self.is_2d:
861                        dep_var = 'z'
862                    out_f.write(spaces + 'return %s'% dep_var + "\n")
863            elif line.count("#import scipy?"):
864                if has_scipy:
865                    out_f.write("import scipy" + "\n")
866            #elif line.count("name = "):
867            #    out_f.write(line % self.name + "\n")
868            elif line:
869                out_f.write(line + "\n")
870        # run string for 2d
871        if line_2d:
872            for line in line_2d:
873                out_f.write(line + "\n")
874        # Test strins
875        for line in line_test:
876            out_f.write(line + "\n")
877   
878        out_f.close() 
879   
880    def set_param_helper(self, line):   
881        """
882        Get string in line to define the params dictionary
883       
884        :param line: one line of string got from the param_str
885        """
886        flag = True
887        params_str = ''
888        spaces = '        '#8spaces
889        items = line.split(";")
890        for item in items:
891            name = item.split("=")[0].lstrip().rstrip()
892            try:
893                value = item.split("=")[1].lstrip().rstrip()
894                float(value)
895            except:
896                value = 1.0 # default
897            params_str += spaces + "self.params['%s'] = %s\n"% (name, value)
898           
899        return params_str
900
901    def set_function_helper(self, line):   
902        """
903        Get string in line to define the local params
904       
905        :param line: one line of string got from the param_str
906        """
907        flag = True
908        params_str = ''
909        spaces = '        '#8spaces
910        items = line.split(";")
911        for item in items:
912            name = item.split("=")[0].lstrip().rstrip()
913            params_str += spaces + "%s = self.params['%s']\n"% (name, name)
914        return params_str
915   
916    def get_warning(self):
917        """
918        Get the warning msg
919        """
920        return self.warning
921       
922    def on_close(self, event):
923        """
924        leave data as it is and close
925        """
926        self.parent.Show(False)#Close()
927        event.Skip()
928       
929class EditorWindow(wx.Frame):
930    """
931    Editor Window
932    """
933    def __init__(self, parent, base, path, title, 
934                 size=(EDITOR_WIDTH, EDITOR_HEIGTH), *args, **kwds):
935        """
936        Init
937        """
938        kwds["title"] = title
939        kwds["size"] = size
940        wx.Frame.__init__(self, parent=None, *args, **kwds)
941        self.parent = parent
942        self.panel = EditorPanel(parent=self, base=parent, 
943                                 path=path, title=title)
944        self.Show(True)
945        wx.EVT_CLOSE(self, self.OnClose)
946   
947    def OnClose(self, event): 
948        """
949        On close event
950        """
951        self.Show(False)
952        #if self.parent != None:
953        #    self.parent.new_model_frame = None
954        #self.Destroy() 
955
956## Templates for custom models
957CUSTOM_TEMPLATE = """
958from sans.models.pluginmodel import Model1DPlugin
959from math import *
960import os
961import sys
962import numpy
963#import scipy?
964class Model(Model1DPlugin):
965    name = ""                             
966    def __init__(self):
967        Model1DPlugin.__init__(self, name=self.name) 
968        #set name same as file name
969        self.name = self.get_fname()                                                   
970        #self.params here
971        self.description = "%s"
972        self.set_details()
973    def function(self, x=0.0%s):
974        #local params here
975        #function here
976"""
977CUSTOM_2D_TEMP = """
978    def run(self, x=0.0, y=0.0):
979        if x.__class__.__name__ == 'list':
980            x_val = x[0]
981            y_val = y[0]*0.0
982            return self.function(x_val, y_val)
983        elif x.__class__.__name__ == 'tuple':
984            msg = "Tuples are not allowed as input to BaseComponent models"
985            raise ValueError, msg
986        else:
987            return self.function(x, 0.0)
988    def runXY(self, x=0.0, y=0.0):
989        if x.__class__.__name__ == 'list':
990            return self.function(x, y)
991        elif x.__class__.__name__ == 'tuple':
992            msg = "Tuples are not allowed as input to BaseComponent models"
993            raise ValueError, msg
994        else:
995            return self.function(x, y)
996    def evalDistribution(self, qdist):
997        if qdist.__class__.__name__ == 'list':
998            msg = "evalDistribution expects a list of 2 ndarrays"
999            if len(qdist)!=2:
1000                raise RuntimeError, msg
1001            if qdist[0].__class__.__name__ != 'ndarray':
1002                raise RuntimeError, msg
1003            if qdist[1].__class__.__name__ != 'ndarray':
1004                raise RuntimeError, msg
1005            v_model = numpy.vectorize(self.runXY, otypes=[float])
1006            iq_array = v_model(qdist[0], qdist[1])
1007            return iq_array
1008        elif qdist.__class__.__name__ == 'ndarray':
1009            v_model = numpy.vectorize(self.runXY, otypes=[float])
1010            iq_array = v_model(qdist)
1011            return iq_array
1012"""
1013TEST_TEMPLATE = """
1014    def get_fname(self):
1015        path = sys._getframe().f_code.co_filename
1016        basename  = os.path.basename(path)
1017        name, _ = os.path.splitext(basename)
1018        return name
1019######################################################################
1020## THIS IS FOR TEST. DO NOT MODIFY THE FOLLOWING LINES!!!!!!!!!!!!!!!!       
1021if __name__ == "__main__":
1022    m= Model()
1023    out1 = m.runXY(0.0)
1024    out2 = m.runXY(0.01)
1025    isfine1 = numpy.isfinite(out1)
1026    isfine2 = numpy.isfinite(out2)
1027    print "Testing the value at Q = 0.0:"
1028    print out1, " : finite? ", isfine1
1029    print "Testing the value at Q = 0.01:"
1030    print out2, " : finite? ", isfine2
1031    if isfine1 and isfine2:
1032        print "===> Simple Test: Passed!"
1033    else:
1034        print "===> Simple Test: Failed!"
1035"""
1036SUM_TEMPLATE = """
1037# A sample of an experimental model function for Sum/Multiply(Pmodel1,Pmodel2)
1038import copy
1039from sans.models.pluginmodel import Model1DPlugin
1040# User can change the name of the model (only with single functional model)
1041#P1_model:
1042#from sans.models.%s import %s as P1
1043#from %s import Model as P1
1044
1045#P2_model:
1046#from sans.models.%s import %s as P2
1047#from %s import Model as P2
1048import os
1049import sys
1050
1051class Model(Model1DPlugin):
1052    name = ""
1053    def __init__(self):
1054        Model1DPlugin.__init__(self, name='')
1055        p_model1 = P1()
1056        p_model2 = P2()
1057        ## Setting  model name model description
1058        self.description = '%s'
1059        self.name = self.get_fname()
1060        if self.name.rstrip().lstrip() == '':
1061            self.name = self._get_name(p_model1.name, p_model2.name)
1062        if self.description.rstrip().lstrip() == '':
1063            self.description = p_model1.name
1064            self.description += p_model2.name
1065            self.fill_description(p_model1, p_model2)
1066
1067        ## Define parameters
1068        self.params = {}
1069
1070        ## Parameter details [units, min, max]
1071        self.details = {}
1072       
1073        # non-fittable parameters
1074        self.non_fittable = p_model1.non_fittable 
1075        self.non_fittable += p_model2.non_fittable 
1076           
1077        ##models
1078        self.p_model1= p_model1
1079        self.p_model2= p_model2
1080       
1081       
1082        ## dispersion
1083        self._set_dispersion()
1084        ## Define parameters
1085        self._set_params()
1086        ## New parameter:scaling_factor
1087        self.params['scale_factor'] = %s
1088       
1089        ## Parameter details [units, min, max]
1090        self._set_details()
1091        self.details['scale_factor'] = ['', None, None]
1092
1093       
1094        #list of parameter that can be fitted
1095        self._set_fixed_params() 
1096        ## parameters with orientation
1097        for item in self.p_model1.orientation_params:
1098            new_item = "p1_" + item
1099            if not new_item in self.orientation_params:
1100                self.orientation_params.append(new_item)
1101           
1102        for item in self.p_model2.orientation_params:
1103            new_item = "p2_" + item
1104            if not new_item in self.orientation_params:
1105                self.orientation_params.append(new_item)
1106        # get multiplicity if model provide it, else 1.
1107        try:
1108            multiplicity1 = p_model1.multiplicity
1109            try:
1110                multiplicity2 = p_model2.multiplicity
1111            except:
1112                multiplicity2 = 1
1113        except:
1114            multiplicity1 = 1
1115            multiplicity2 = 1
1116        ## functional multiplicity of the model
1117        self.multiplicity1 = multiplicity1 
1118        self.multiplicity2 = multiplicity2   
1119        self.multiplicity_info = []   
1120       
1121    def _clone(self, obj):
1122        obj.params     = copy.deepcopy(self.params)
1123        obj.description     = copy.deepcopy(self.description)
1124        obj.details    = copy.deepcopy(self.details)
1125        obj.dispersion = copy.deepcopy(self.dispersion)
1126        obj.p_model1  = self.p_model1.clone()
1127        obj.p_model2  = self.p_model2.clone()
1128        #obj = copy.deepcopy(self)
1129        return obj
1130   
1131    def _get_name(self, name1, name2):
1132        p1_name = self._get_upper_name(name1)
1133        if not p1_name:
1134            p1_name = name1
1135        name = p1_name
1136        name += "_and_"
1137        p2_name = self._get_upper_name(name2)
1138        if not p2_name:
1139            p2_name = name2
1140        name += p2_name
1141        return name
1142   
1143    def _get_upper_name(self, name=None):
1144        if name == None:
1145            return ""
1146        upper_name = ""
1147        str_name = str(name)
1148        for index in range(len(str_name)):
1149            if str_name[index].isupper():
1150                upper_name += str_name[index]
1151        return upper_name
1152       
1153    def _set_dispersion(self):
1154        ##set dispersion only from p_model
1155        for name , value in self.p_model1.dispersion.iteritems():
1156            #if name.lower() not in self.p_model1.orientation_params:
1157            new_name = "p1_" + name
1158            self.dispersion[new_name]= value
1159        for name , value in self.p_model2.dispersion.iteritems():
1160            #if name.lower() not in self.p_model2.orientation_params:
1161            new_name = "p2_" + name
1162            self.dispersion[new_name]= value
1163           
1164    def function(self, x=0.0):
1165        return 0
1166                               
1167    def getProfile(self):
1168        try:
1169            x,y = self.p_model1.getProfile()
1170        except:
1171            x = None
1172            y = None
1173           
1174        return x, y
1175   
1176    def _set_params(self):
1177        for name , value in self.p_model1.params.iteritems():
1178            # No 2D-supported
1179            #if name not in self.p_model1.orientation_params:
1180            new_name = "p1_" + name
1181            self.params[new_name]= value
1182           
1183        for name , value in self.p_model2.params.iteritems():
1184            # No 2D-supported
1185            #if name not in self.p_model2.orientation_params:
1186            new_name = "p2_" + name
1187            self.params[new_name]= value
1188               
1189        # Set "scale" as initializing
1190        self._set_scale_factor()
1191     
1192           
1193    def _set_details(self):
1194        for name ,detail in self.p_model1.details.iteritems():
1195            new_name = "p1_" + name
1196            #if new_name not in self.orientation_params:
1197            self.details[new_name]= detail
1198           
1199        for name ,detail in self.p_model2.details.iteritems():
1200            new_name = "p2_" + name
1201            #if new_name not in self.orientation_params:
1202            self.details[new_name]= detail
1203   
1204    def _set_scale_factor(self):
1205        pass
1206       
1207               
1208    def setParam(self, name, value):
1209        # set param to this (p1, p2) model
1210        self._setParamHelper(name, value)
1211       
1212        ## setParam to p model
1213        model_pre = name.split('_', 1)[0]
1214        new_name = name.split('_', 1)[1]
1215        if model_pre == "p1":
1216            if new_name in self.p_model1.getParamList():
1217                self.p_model1.setParam(new_name, value)
1218        elif model_pre == "p2":
1219             if new_name in self.p_model2.getParamList():
1220                self.p_model2.setParam(new_name, value)
1221        elif name.lower() == 'scale_factor':
1222            self.params['scale_factor'] = value
1223        else:
1224            raise ValueError, "Model does not contain parameter %s" % name
1225           
1226    def getParam(self, name):
1227        # Look for dispersion parameters
1228        toks = name.split('.')
1229        if len(toks)==2:
1230            for item in self.dispersion.keys():
1231                # 2D not supported
1232                if item.lower()==toks[0].lower():
1233                    for par in self.dispersion[item]:
1234                        if par.lower() == toks[1].lower():
1235                            return self.dispersion[item][par]
1236        else:
1237            # Look for standard parameter
1238            for item in self.params.keys():
1239                if item.lower()==name.lower():
1240                    return self.params[item]
1241        return 
1242        #raise ValueError, "Model does not contain parameter %s" % name
1243       
1244    def _setParamHelper(self, name, value):
1245        # Look for dispersion parameters
1246        toks = name.split('.')
1247        if len(toks)== 2:
1248            for item in self.dispersion.keys():
1249                if item.lower()== toks[0].lower():
1250                    for par in self.dispersion[item]:
1251                        if par.lower() == toks[1].lower():
1252                            self.dispersion[item][par] = value
1253                            return
1254        else:
1255            # Look for standard parameter
1256            for item in self.params.keys():
1257                if item.lower()== name.lower():
1258                    self.params[item] = value
1259                    return
1260           
1261        raise ValueError, "Model does not contain parameter %s" % name
1262             
1263   
1264    def _set_fixed_params(self):
1265        for item in self.p_model1.fixed:
1266            new_item = "p1" + item
1267            self.fixed.append(new_item)
1268        for item in self.p_model2.fixed:
1269            new_item = "p2" + item
1270            self.fixed.append(new_item)
1271
1272        self.fixed.sort()
1273               
1274                   
1275    def run(self, x = 0.0):
1276        self._set_scale_factor()
1277        return self.params['scale_factor'] %s \
1278(self.p_model1.run(x) %s self.p_model2.run(x))
1279   
1280    def runXY(self, x = 0.0):
1281        self._set_scale_factor()
1282        return self.params['scale_factor'] %s \
1283(self.p_model1.runXY(x) %s self.p_model2.runXY(x))
1284   
1285    ## Now (May27,10) directly uses the model eval function
1286    ## instead of the for-loop in Base Component.
1287    def evalDistribution(self, x = []):
1288        self._set_scale_factor()
1289        return self.params['scale_factor'] %s \
1290(self.p_model1.evalDistribution(x) %s \
1291self.p_model2.evalDistribution(x))
1292
1293    def set_dispersion(self, parameter, dispersion):
1294        value= None
1295        new_pre = parameter.split("_", 1)[0]
1296        new_parameter = parameter.split("_", 1)[1]
1297        try:
1298            if new_pre == 'p1' and \
1299new_parameter in self.p_model1.dispersion.keys():
1300                value= self.p_model1.set_dispersion(new_parameter, dispersion)
1301            if new_pre == 'p2' and \
1302new_parameter in self.p_model2.dispersion.keys():
1303                value= self.p_model2.set_dispersion(new_parameter, dispersion)
1304            self._set_dispersion()
1305            return value
1306        except:
1307            raise
1308
1309    def fill_description(self, p_model1, p_model2):
1310        description = ""
1311        description += "This model gives the summation or multiplication of"
1312        description += "%s and %s. "% ( p_model1.name, p_model2.name )
1313        self.description += description
1314         
1315    def get_fname(self):
1316        path = sys._getframe().f_code.co_filename
1317        basename  = os.path.basename(path)
1318        name, _ = os.path.splitext(basename)
1319        return name     
1320           
1321if __name__ == "__main__":
1322    m1= Model()
1323    #m1.setParam("p1_scale", 25) 
1324    #m1.setParam("p1_length", 1000)
1325    #m1.setParam("p2_scale", 100)
1326    #m1.setParam("p2_rg", 100)
1327    out1 = m1.runXY(0.01)
1328
1329    m2= Model()
1330    #m2.p_model1.setParam("scale", 25)
1331    #m2.p_model1.setParam("length", 1000)
1332    #m2.p_model2.setParam("scale", 100)
1333    #m2.p_model2.setParam("rg", 100)
1334    out2 = m2.p_model1.runXY(0.01) %s m2.p_model2.runXY(0.01)\n
1335    print "My name is %s."% m1.name
1336    print out1, " = ", out2
1337    if out1 == out2:
1338        print "===> Simple Test: Passed!"
1339    else:
1340        print "===> Simple Test: Failed!"
1341"""
1342     
1343#if __name__ == "__main__":
1344#    app = wx.PySimpleApp()
1345#    frame = TextDialog(id=1, model_list=["SphereModel", "CylinderModel"])   
1346#    frame.Show(True)
1347#    app.MainLoop()             
1348
1349if __name__ == "__main__":
1350    from sans.perspectives.fitting import models
1351    dir_path = models.find_plugins_dir()
1352    app  = wx.App()
1353    window = EditorWindow(parent=None, base=None, path=dir_path, title="Editor")
1354    app.MainLoop()         
Note: See TracBrowser for help on using the repository browser.