Index: sansview/perspectives/fitting/fitting.py
===================================================================
--- sansview/perspectives/fitting/fitting.py	(revision 54905deac983bd6ed343a09aae47d96d64b380b4)
+++ sansview/perspectives/fitting/fitting.py	(revision f93dfcbee4f77b948d7a155ac0b955274f52fc50)
@@ -86,9 +86,8 @@
         #menu for model
         menu2 = wx.Menu()
-    
         self.menu_mng.populate_menu(menu2, owner)
         id2 = wx.NewId()
         owner.Bind(models.EVT_MODEL,self._on_model_menu)
-      
+        ## Allow fitpanel to access list of models
         self.fit_panel.set_owner(owner)
         self.fit_panel.set_model_list(self.menu_mng.get_model_list())
@@ -98,6 +97,8 @@
         return [(id, self.menu1, "Fitting"),(id2, menu2, "Model")]
     
+    
     def on_add_sim_page(self, event):
         """
+            Create a page to access simultaneous fit option
         """
         self.sim_page= self.fit_panel.add_sim_page()
@@ -110,9 +111,4 @@
             TODO: replace the text with a nice image
         """
-        #from helpDialog import  HelpWindow
-        #dialog = HelpWindow(None, -1, 'HelpWindow')
-        #if dialog.ShowModal() == wx.ID_OK:
-        #    pass
-        #dialog.Destroy()
         from helpPanel import  HelpWindow
         frame = HelpWindow(None, -1, 'HelpWindow')    
@@ -132,6 +128,5 @@
                           "Dialog with fitting parameters ", self._onSelect]] 
             else:
-                #if item.name==graph.selected_plottable and\
-                # item.__class__.__name__ is  "Data1D":
+               
                 if item.name==graph.selected_plottable :
                     return [["Select data  for Fitting", \
@@ -147,5 +142,5 @@
         # Creation of the fit panel
         self.fit_panel = FitPanel(self.parent, -1)
-        #Set the manager forthe main panel
+        #Set the manager for the main panel
         self.fit_panel.set_manager(self)
         # List of windows used for the perspective
@@ -160,7 +155,5 @@
         self.parent.Bind( ERR_DATA, self._on_data_error)
         
-        #create the fitting panel
-        #return [self.fit_panel]
-        
+        #Send the fitting panel to guiframe
         self.mypanels.append(self.fit_panel)
         return self.mypanels
@@ -169,6 +162,7 @@
     def _on_slicer_event(self, event):
         """
-        """
-        #print "fitting:slicer event ", event.panel
+            Receive a panel as event and send it to guiframe 
+            @param event: event containing a panel
+        """
         if event.panel!=None:
             new_panel = event.panel
@@ -214,4 +208,7 @@
     def copy_data(self, item, dy):
         """
+            receive a data 1D and the list of errors on dy
+            and create a new data1D data
+            @param return 
         """
         detector=None
@@ -243,4 +240,5 @@
         for item in self.panel.graph.plottables:
             if item.name == self.panel.graph.selected_plottable:
+                ## reset the error back to data
                 if len(self.err_dy)>0:
                     if item.name in  self.err_dy.iterkeys():
@@ -258,30 +256,22 @@
             else:
                 data= item
-                        
-                        
+            ## create anew page                   
             if item.name == self.panel.graph.selected_plottable or\
                  item.__class__.__name__ is "Data2D":
-                #find a name for the page created for notebook
-                #print "fitting", self.panel
                 try:
-                   
-                    #page = self.fit_panel.add_fit_page(item)
                     page = self.fit_panel.add_fit_page(data)
-                    #page, model_name = self.fit_panel.add_fit_page(item)
                     # add data associated to the page created
-                   
                     if page !=None:   
                         #create a fitproblem storing all link to data,model,page creation
                         self.page_finder[page]= FitProblem()
-                        #self.page_finder[page].save_model_name(model_name)  
+                        ## item is almost the same as data but contains
+                        ## axis info for plotting 
                         self.page_finder[page].add_plotted_data(item)
                         self.page_finder[page].add_fit_data(data)
-                       
-                            
+                        
                         wx.PostEvent(self.parent, StatusEvent(status="Page Created"))
                     else:
                         wx.PostEvent(self.parent, StatusEvent(status="Page was already Created"))
                 except:
-                    #raise
                     wx.PostEvent(self.parent, StatusEvent(status="Creating Fit page: %s"\
                     %sys.exc_value))
@@ -291,5 +281,9 @@
     def schedule_for_fit(self,value=0,fitproblem =None):  
         """
-        
+            Set the fit problem field to 0 or 1 to schedule that problem to fit.
+            Schedule the specified fitproblem or get the fit problem related to 
+            the current page and set value.
+            @param value : integer 0 or 1 
+            @param fitproblem: fitproblem to schedule or not to fit
         """   
         if fitproblem !=None:
@@ -316,11 +310,9 @@
              @note: expecting park used for fit.
         """  
-        #sim_page=self.fit_panel.GetPage(1) 
         sim_page= self.sim_page
         for page, value in self.page_finder.iteritems():
             if page != sim_page:
                 list=value.get_model()
-                model=list[0]
-                #print "fitting",model.name,modelname, values
+                model = list[0]
                 if model.name== modelname:
                     value.set_model_param(names,values)
@@ -354,37 +346,29 @@
           
         """
-        
-        #print "single fit ", pars,result.pvec,result.stderr,result.fitness
         wx.PostEvent(self.parent, StatusEvent(status="Single fit \
-        complete " , type="stop"))
+        complete! " , type="stop"))
         try:
             for page, value in self.page_finder.iteritems():
                 if page==cpage :
-                    #fitdata = value.get_data()
                     list = value.get_model()
                     model= list[0]
                     break
+            ## reset the current model with new fitted parameters    
             i = 0
-          
             for name in pars:
                 if result.pvec.__class__==numpy.float64:
                     model.setParam(name,result.pvec)
                 else:
-                    #print "fitting result : chisqr",result.fitness
-                    #print "fitting result : pvec",result.pvec
-                    #print "fitting result : stderr",result.stderr
                     model.setParam(name,result.pvec[i])
-                    #print "fitting: single fit", name, result.pvec[i]
                     i += 1
-           
-           
+            ## Reset values of the current page to fit result
             cpage.onsetValues(result.fitness, result.pvec,result.stderr)
-            #title="Fitted model 2D "
+            ## plot the current model with new param
             self.plot_helper(currpage=cpage,qmin=qmin,qmax=qmax,
                              ymin=ymin, ymax=ymax,
                              xmin=xmin, xmax=xmax,title=None)
         except:
-            #raise
-            wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
+            msg= "Single Fit completed but Following error occurred:"
+            wx.PostEvent(self.parent, StatusEvent(status="%s %s" % (msg, sys.exc_value)))
             return
        
@@ -399,4 +383,6 @@
         """
         if cpage!=None:
+            ## the fit perform was a single fit but selected  from the 
+            ## simultaneous fit page
             self._single_fit_completed(result=result,pars=pars,cpage=cpage,
                                        qmin=qmin,qmax=qmax,
@@ -406,10 +392,8 @@
             wx.PostEvent(self.parent, StatusEvent(status="Simultaneous fit \
             complete ", type="stop"))
-            #print "result",cpage,str(result),result.parameters,result.fitness,result.stderr
-            
+            ## fit more than 1 model at the same time 
             try:
                 for page, value in self.page_finder.iteritems():
                     if value.get_scheduled()==1:
-                        #fitdata = value.get_data()
                         list = value.get_model()
                         model= list[0]
@@ -427,22 +411,24 @@
                                 small_cov.append(p.stderr)
                                 model.setParam(param_name,p.value)  
+                                
                         # Display result on each page 
-                        #print "mmmm",p.value,p.stderr
                         page.onsetValues(result.fitness, small_out,small_cov)
-                        #print "out,err",small_out,small_cov
-                        #Replot model
+                        #Replot models
+                        msg= "Single Fit completed plotting %s:"%model.name
+                        wx.PostEvent(self.parent, StatusEvent(status="%s " % msg))
                         self.plot_helper(currpage= page,qmin= qmin,qmax= qmax,
                                          xmin=xmin, xmax=xmax,
                                          ymin=ymin, ymax=ymax) 
             except:
-                wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fitting error: %s" % sys.exc_value))
-                return
-            
-            
+                 msg= "Simultaneous Fit completed but Following error occurred: "
+                 wx.PostEvent(self.parent, StatusEvent(status="%s%s" %(msg,sys.exc_value)))
+                 return 
+             
+             
     def stop_fit(self):
         """
+            Stop the fit engine
         """
         if self.calc_thread != None and self.calc_thread.isrunning():
-            #self.calc_thread.interrupt()
             self.calc_thread.stop()
             wx.PostEvent(self.parent, StatusEvent(status="Fitting  \
@@ -458,49 +444,42 @@
             
         """
-        #print "in single fitting"
         #set an engine to perform fit
         from sans.fit.Fitting import Fit
-        self.fitter= Fit(self._fit_engine)
+        self.fitter = Fit(self._fit_engine)
         #Setting an id to store model and data in fit engine
-        self.fit_id= 0
+        self.fit_id = 0
         if id!=None:
-            self.fit_id= id
-        
-        page_fitted=None
-        fit_problem=None
+            self.fit_id = id
+        
+        page_fitted = None
+        fit_problem = None
         #Get information (model , data) related to the page on 
         #with the fit will be perform
-        current_pg=self.fit_panel.get_current_page() 
-        #simul_pg=self.fit_panel.GetPage(1 )
-        simul_pg=self.sim_page
+        current_pg= self.fit_panel.get_current_page() 
+        simul_pg= self.sim_page
         pars=[]   
-        #for page, value in self.page_finder.iteritems():
-        if current_pg!= simul_pg:
-        #    if  value.get_scheduled() ==1 :
+        ## Check that the current page is different from self.sim_page
+        if current_pg != simul_pg:
             value = self.page_finder[current_pg]
             metadata =  value.get_fit_data()
             list = value.get_model()
             model = list[0]
-            smearer= value.get_smearer()
+            smearer = value.get_smearer()
            
-    
             #Create list of parameters for fitting used
-            
             templist=[]
             try:
-                #templist=current_pg.get_param_list()
-                templist=current_pg.get_param_list()
+                ## get the list of parameter names to fit
+                templist = current_pg.get_param_list()
                 for element in templist:
                     pars.append(str(element[0].GetLabelText()))
                 pars.sort()
+                 
                 #Do the single fit
-                self.fitter.set_model(Model(model), self.fit_id, pars) 
-                if self._fit_engine=="scipy":
-                    wx.PostEvent(self.parent, StatusEvent(status="Parameters range will\
-                     be ignored for %s fitting engine"%str(self._fit_engine)))
-                #print "args...:",metadata,self.fit_id,smearer,qmin,qmax,ymin,ymax
+                self.fitter.set_model(Model(model), self.fit_id, pars)
                 dy=[]
                 x=[]
                 y=[]
+                ## checking the validity of error
                 if metadata.__class__ in  ["Data1D","Theory1D"]:
                     for i in range(len(metadata.dy)):
@@ -516,18 +495,21 @@
                         metadata.x=numpy.zeros(len(x))
                         metadata.x=x
+                        
                 self.fitter.set_data(data=metadata,Uid=self.fit_id,
                                      smearer=smearer,qmin= qmin,qmax=qmax,
                                      ymin=ymin,ymax=ymax)
-                self.fitter.select_problem_for_fit(Uid=self.fit_id,value=value.get_scheduled())
+                
+                self.fitter.select_problem_for_fit(Uid= self.fit_id,
+                                                   value= value.get_scheduled())
                 page_fitted=current_pg
-                #self.fit_id+=1
-                #self.schedule_for_fit( 0,value) 
+               
             except:
-                wx.PostEvent(self.parent, StatusEvent(status="Single Fit error: %s" % sys.exc_value))
+                msg= "Single Fit error: %s" % sys.exc_value
+                wx.PostEvent(self.parent, StatusEvent(status= msg ))
                 return
             # make sure to keep an alphabetic order 
             #of parameter names in the list      
             try:
-                # If a thread is already started, stop it
+                ## If a thread is already started, stop it
                 if self.calc_thread != None and self.calc_thread.isrunning():
                     self.calc_thread.stop()
@@ -566,5 +548,4 @@
              self.fit_id= id
        
-        
         for page, value in self.page_finder.iteritems():
             try:
@@ -573,7 +554,7 @@
                     list = value.get_model()
                     model= list[0]
-                    #Create dictionary of parameters for fitting used
+                    ## store page
                     cpage= page
-                    print ""
+                    #Get list of parameters name to fit
                     pars = []
                     templist = []
@@ -586,6 +567,6 @@
                             wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fit error: %s" % sys.exc_value))
                             return
-                    # need to check this print "new model "
-                    
+                    ## create a park model and reset parameter value if constraint
+                    ## is given
                     new_model=Model(model)
                     param=value.get_model_param()
@@ -595,9 +576,8 @@
                             param_value = item[1]
                             param_name = item[0]
-    
                             new_model.parameterset[ param_name].set( param_value )
                         
                     self.fitter.set_model(new_model, self.fit_id, pars) 
-                    #print "sim-->model",metadata,model,self.fit_id, pars
+                    ## check that non -zero value are send as dy in the fit engine
                     dy=[]
                     x=[]
@@ -616,18 +596,22 @@
                                 metadata.x=numpy.zeros(len(x))
                                 metadata.x=x
+                                
                     self.fitter.set_data(metadata,self.fit_id,qmin,qmax,ymin,ymax)
-                    #print "sim---->value of problem",value.get_scheduled()
-                    self.fitter.select_problem_for_fit(Uid=self.fit_id,value=value.get_scheduled())
+                    self.fitter.select_problem_for_fit(Uid= self.fit_id,
+                                                       value= value.get_scheduled())
                     self.fit_id += 1 
                     value.clear_model_param()
-                    #self.schedule_for_fit( 0,value) 
+                   
             except:
-                wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fit error: %s" % sys.exc_value))
+                msg= "Simultaneous Fit error: %s" % sys.exc_value
+                wx.PostEvent(self.parent, StatusEvent(status= msg ))
                 return 
+            
         #Do the simultaneous fit
         try:
-            # If a thread is already started, stop it
+            ## If a thread is already started, stop it
             if self.calc_thread != None and self.calc_thread.isrunning():
                 self.calc_thread.stop()
+            ## Perform a single fit , then need to page 
             if  self.fit_id==1:
                 self.calc_thread =FitThread(parent =self.parent,
@@ -643,4 +627,5 @@
                       
             else:
+                ## Perform more than 1 fit at the time
                 self.calc_thread =FitThread(parent =self.parent,
                                         fn= self.fitter,
@@ -655,5 +640,6 @@
             
         except:
-            wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fit error: %s" % sys.exc_value))
+            msg= "Simultaneous Fit error: %s" % sys.exc_value
+            wx.PostEvent(self.parent, StatusEvent(status= msg ))
             return
         
@@ -661,5 +647,6 @@
     def _onset_engine(self,event):
         """ 
-            set engine to scipy
+            Toggle engine name from "park" to "scipy" or reverse if event received
+            @param event: wx.menu item checked
         """
         if self._fit_engine== 'park':
@@ -667,5 +654,7 @@
         else:
             self._on_change_engine('park')
-        wx.PostEvent(self.parent, StatusEvent(status="Engine set to: %s" % self._fit_engine))
+            
+        msg= "Engine set to: %s" % self._fit_engine
+        wx.PostEvent(self.parent, StatusEvent(status= msg ))
   
     
@@ -681,17 +670,17 @@
         """
             react to model selection on any combo box or model menu.plot the model  
+            @param evt: wx.combobox event
         """
        
         model = evt.model
         name = evt.name
-        
-        #print "name fitting", name
-        #sim_page=self.fit_panel.GetPage(1)
+       
         sim_page=self.sim_page
         current_pg = self.fit_panel.get_current_page() 
+        ## make sure nothing is done on self.sim_page
+        ## example trying to call set_panel on self.sim_page
         if current_pg != sim_page:
             current_pg.set_panel(model)
-            #model.name = self.page_finder[current_pg].get_name()
-            #print "model name", model.name
+           
             model.name="M"+str(self.index_model)
             try:
@@ -702,19 +691,22 @@
             self.index_model += 1  
             
-            
             # save model name
-            
             # save the name containing the data name with the appropriate model
             self.page_finder[current_pg].set_model(model,M_name)
             self.plot_helper(currpage= current_pg,qmin= None,qmax= None)
+            ## draw  self.sim_page and store information on the selected model
             if self.sim_page!=None:
                 self.sim_page.add_model(self.page_finder)
         
+        
+        
     def  set_smearer(self,smearer):
         """
-        
+            Get a smear object and store it to a fit problem
+            @param smearer: smear object to allow smearing data
         """   
         current_pg=self.fit_panel.get_current_page()
         self.page_finder[current_pg].set_smearer(smearer)
+         
          
     def redraw_model(self,qmin= None,qmax= None):
@@ -730,5 +722,7 @@
         self.plot_helper(currpage=page,qmin= qmin,qmax= qmax)
         
-    def plot_helper(self,currpage, fitModel=None, qmin=None,qmax=None,
+        
+        
+    def plot_helper(self,currpage, qmin=None,qmax=None,
                     ymin=None,ymax=None, xmin=None, xmax=None,title=None ):
         """
@@ -740,15 +734,21 @@
             for page in self.page_finder.iterkeys():
                 if  page==currpage :  
-                    data=self.page_finder[page].get_plotted_data()
-                    list=self.page_finder[page].get_model()
+                    data= self.page_finder[page].get_plotted_data()
+                    list= self.page_finder[page].get_model()
+                    smearer= self.page_finder[page].get_smearer()
                     model=list[0]
                     break 
-            #print "model in fitting",model
+            ## create Model 1D
             if data!=None and data.__class__.__name__ != 'Data2D':
-                theory = Theory1D(x=[], y=[])
+                x= numpy.zeros(len(data.x))  
+                y= numpy.zeros(len(data.x)) 
+                
+                theory = Theory1D(x=x, y=y)
                 theory.name = model.name
                 theory.group_id = data.group_id
                 theory.id = "Model"
-                   
+                
+                 
+                
                 x_name, x_units = data.get_xaxis() 
                 y_name, y_units = data.get_yaxis() 
@@ -759,9 +759,11 @@
                 if qmax == None :
                    qmax = max(data.x)
+                j=0
                 try:
                     tempx = qmin
                     tempy = model.run(qmin)
-                    theory.x.append(tempx)
-                    theory.y.append(tempy)
+                    theory.x[j]=tempx
+                    theory.y[j]=tempy
+                    j+=1
                 except :
                         wx.PostEvent(self.parent, StatusEvent(status="fitting \
@@ -773,6 +775,9 @@
                             tempx = data.x[i]
                             tempy = model.run(tempx)
-                            theory.x.append(tempx) 
-                            theory.y.append(tempy)
+                            
+                            if j< i:
+                                theory.x[j]=tempx 
+                                theory.y[j]=tempy
+                                j+=1
                            
                     except:
@@ -782,14 +787,18 @@
                     tempx = qmax
                     tempy = model.run(qmax)
-                    theory.x.append(tempx)
-                    theory.y.append(tempy)
+                
+                    theory.x[j]=tempx 
+                    theory.y[j]=tempy
+                    j+=1
                 except:
                     wx.PostEvent(self.parent, StatusEvent(status="fitting \
                         skipping point x %g %s" %(qmin, sys.exc_value)) )
-                    
+                
+                if smearer!=None:
+                    theory.y= smearer(theory.y)   
                 wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
                                                 title=str(data.name)))
             else:
-               
+                ## create Model 2D
                 theory=Data2D(data.data, data.err_data)
                 theory.name= model.name
@@ -805,10 +814,12 @@
                 theory.y_bins= data.y_bins
                 tempy=[]
-                #print "max x,y",max(data.xmax,data.xmin),max(data.ymax,data.ymin)
+                
                 if qmin==None:
-                    qmin=0#min(math.fabs(data.xmax),math.fabs(data.ymin))
+                    qmin=0
                 if qmax==None:
-                    qmax=math.sqrt(math.pow(max(math.fabs(data.xmax),math.fabs(data.xmin)),2)/
-                                   +math.pow(max(math.fabs(data.ymax),math.fabs(data.ymin)),2))
+                    x= math.pow(max(math.fabs(data.xmax),math.fabs(data.xmin)),2)
+                    y= math.pow(max(math.fabs(data.ymax),math.fabs(data.ymin)),2)
+                    qmax=math.sqrt( x+y )
+                    
                 if ymin==None:
                     ymin=data.ymin
@@ -823,17 +834,20 @@
                 for j in range(len(data.y_bins)):
                     for i in range(len(data.x_bins)):
-                        tempqij=math.sqrt((math.pow(data.y_bins[j],2)+math.pow(data.x_bins[i],2)))
+                        tempqij=math.sqrt(( math.pow(data.y_bins[j],2)\
+                                           +math.pow(data.x_bins[i],2) ))
+                        
                         if tempqij>= qmin and tempqij<= qmax: 
-                            theory.data[j][i]=model.runXY([data.y_bins[j],data.x_bins[i]])
+                            theory.data[j][i] = model.runXY([data.y_bins[j],
+                                                             data.x_bins[i]] )
                         else:
-                            theory.data[j][i]=0 #None # Later, We need to decide which of  0 and None is better.
-                #print "len(data.x_bins),len(data.y_bins);",len(data.x_bins),len(data.y_bins),qmax
-                #print "fitting : plot_helper:", theory.image
-                #print "fitting : plot_helper:",theory.image
+                            ## Later, We need to decide which of  0 and None is better.
+                            theory.data[j][i]=0 
+             
                 theory.detector= data.detector
                 theory.source= data.source
-                
+                ## qmin, qmax will used later to define q range.
                 theory.qmin= qmin
                 theory.qmax= qmax
+                ## plot boundaries
                 theory.ymin= ymin
                 theory.ymax= ymax
@@ -848,9 +862,9 @@
         """
             Plot a theory from a model selected from the menu
+            @param evt: wx.menu event
         """
         name = evt.model.__name__
         if hasattr(evt.model, "name"):
             name = evt.model.name
-        #print "on model menu", name
         model=evt.model()
         description=model.description
@@ -861,13 +875,28 @@
         self.fit_panel.add_model_page(model,description,name,topmenu=True)
         
-    def draw_model(self,model,name ,data=None,description=None,enable1D=True, enable2D=False,
-                   qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
-        """
-             draw model with default data value
-        """
+        
+    def draw_model(self, model, name, data= None, description= None,
+                   enable1D= True, enable2D= False,
+                   qmin= DEFAULT_QMIN, qmax= DEFAULT_QMAX, qstep= DEFAULT_NPTS):
+        """
+             Draw model.
+             @param model: the model to draw
+             @param name: the name of the model to draw
+             @param data: the data on which the model is based to be drawn
+             @param description: model's description
+             @param enable1D: if true enable drawing model 1D
+             @param enable2D: if true enable drawing model 2D
+             @param qmin:  Range's minimum value to draw model
+             @param qmax:  Range's maximum value to draw model
+             @param qstep: number of step to divide the x and y-axis
+             
+        """
+        ## draw model based on loaded data
         if data !=None:
             self.redraw_model(qmin,qmax)
             return 
+        ## draw model 1D with no loaded data
         self._draw_model1D(model,name,model.description, enable1D,qmin,qmax, qstep)
+        ## draw model 2D with no initial data
         self._draw_model2D(model=model,
                            description=model.description,
@@ -878,61 +907,50 @@
         
               
-    def _draw_model1D(self,model,name,description=None, enable1D=True,
-                      qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
-        """
-        
-        """
-        
-        if enable1D:
-            x=  numpy.linspace(start= qmin,
-                               stop= qmax,
-                               num= qstep,
-                               endpoint=True
-                               )      
-            xlen= len(x)
-            y = numpy.zeros(xlen)
-            if not enable1D:
-                for i in range(xlen):
-                    y[i] = model.run(x[i])
+    def _draw_model1D(self, model, name, description= None, enable1D= True,
+                      qmin= DEFAULT_QMIN, qmax= DEFAULT_QMAX, qstep= DEFAULT_NPTS):
+        """
+            Draw model 1D between qmin and qmax value
+            @param model: the model to draw
+            @param name: the name of the model
+            @param description: descripion of the model as string
+            @param enable1D:  allow to draw model 1D if True  else False
+            @param qmin: the minimum value of the range to draw the model
+            @param qmax: the maximum value of the range to draw the model
+            @param qstep: the number of points to draw  
+        """
+        x=  numpy.linspace(start= qmin,
+                           stop= qmax,
+                           num= qstep,
+                           endpoint=True
+                           )      
+        xlen= len(x)
+        y = numpy.zeros(xlen)
+        
+        if  enable1D:
+            for i in range(xlen):
+                y[i] = model.run(x[i]) 
+            try:
+                new_plot = Theory1D(x, y)
+                new_plot.name = name
+                new_plot.xaxis("\\rm{Q}", 'A^{-1}')
+                new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
+                new_plot.id ="Model"
+                new_plot.group_id ="Model"
+                # Pass the reset flag to let the plotting event handler
+                # know that we are replacing the whole plot
+                wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot,
+                                 title="Analytical model 1D ", reset=True ))
                 
-                try:
-                    new_plot = Theory1D(x, y)
-                    
-                    new_plot.name = name
-                    new_plot.xaxis("\\rm{Q}", 'A^{-1}')
-                    new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
-                    new_plot.id = "Model"
-                    new_plot.group_id ="Model"
-                    wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title="Analytical model 1D"))
-                except:
-                    wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
-                    #raise
-                    return
-            else:
-                for i in range(xlen):
-                    y[i] = model.run(x[i]) 
-                try:
-                    new_plot = Theory1D(x, y)
-                    #print "draw model 1D", name
-                    new_plot.name = name
-                    new_plot.xaxis("\\rm{Q}", 'A^{-1}')
-                    new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
-                    new_plot.id ="Model"
-                    new_plot.group_id ="Model"
-                    
-                    # Pass the reset flag to let the plotting event handler
-                    # know that we are replacing the whole plot
-                    wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot,
-                                     title="Analytical model 1D ", reset=True ))
-                    
-                except:
-                    #raise
-                    wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
-                    return
-    
-    
+            except:
+                msg= " Error occurred when drawing %s Model 1D: "%new_plot.name
+                msg+= " %s"%sys.exc_value
+                wx.PostEvent( self.parent, StatusEvent(status= msg ))
+                return
+
+
     
     def update(self, output,time):
         """
+            Update the output of plotting model
         """
         pass
@@ -940,8 +958,10 @@
     def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS):
         """
-        """
-        wx.PostEvent(self.parent, StatusEvent(status="Calc \
-        complete !" , type="stop"))
-        #print "complete",output, model,qmin, qmax
+            Complete get the result of modelthread and create model 2D
+            that can be plot.
+        """
+        msg = "Calc complete !"
+        wx.PostEvent( self.parent, StatusEvent( status= msg , type="stop" ))
+    
         data = output
         temp= numpy.zeros(numpy.shape(data))
@@ -950,24 +970,22 @@
     
         from DataLoader.data_info import Detector, Source
-        
         detector = Detector()
         theory.detector=[]
         theory.detector.append(detector) 
             
-        theory.detector[0].distance=1e+32#13705.0
+        theory.detector[0].distance=1e+32
         theory.source= Source()
-        theory.source.wavelength=2*math.pi/1e+32#8.4
+        theory.source.wavelength=2*math.pi/1e+32
         theory.x_bins =[]
         theory.y_bins =[]
-        #Now qmax is xmax.
-        xmax=2*theory.detector[0].distance*math.atan(qmax/(4*math.pi/theory.source.wavelength))
-        theory.detector[0].pixel_size.x= xmax/(qstep/2-0.5)#5.0
-        theory.detector[0].pixel_size.y= xmax/(qstep/2-0.5)#5.0
+        ## Create detector for Model 2D
+        xmax=2*theory.detector[0].distance*math.atan(\
+                            qmax/(4*math.pi/theory.source.wavelength))
+        
+        theory.detector[0].pixel_size.x= xmax/(qstep/2-0.5)
+        theory.detector[0].pixel_size.y= xmax/(qstep/2-0.5)
         theory.detector[0].beam_center.x= qmax
         theory.detector[0].beam_center.y= qmax
-        #print "xmax,qmax",xmax,qmax
-        # compute x_bins and y_bins
-        # Qx and Qy vectors
-    
+        ## create x_bins and y_bins of the model 2D
         distance   = theory.detector[0].distance
         pixel      = qstep/2-1
@@ -981,28 +999,22 @@
         
         size_x, size_y= numpy.shape(theory.data)
-        #print "size_x,size_y",size_x, size_y
-        #This case, q and x are equivalent to each other.
         for i_x in range(size_x):
-            theta = (i_x-center_x)*pixel_width_x / distance #/ size_x#100.0
+            theta = (i_x-center_x)*pixel_width_x / distance 
             qx = 4.0*math.pi/wavelength * math.tan(theta/2.0)
             theory.x_bins.append(qx)    
         for i_y in range(size_y):
-            theta = (i_y-center_y)*pixel_width_y / distance #/ size_y#100.0
+            theta = (i_y-center_y)*pixel_width_y / distance 
             qy =4.0*math.pi/wavelength * math.tan(theta/2.0)
             theory.y_bins.append(qy)
            
-        #theory.err_data= numpy.    
         theory.name= model.name
         theory.group_id ="Model"
         theory.id ="Model"
-        
-       
-        
-        theory.xmin= -qmax#/math.sqrt(2)#You can not do sqrt(2), that changes axis scale not data itself
-        theory.xmax= qmax#/math.sqrt(2)
-        theory.ymin= -qmax#/math.sqrt(2)
-        theory.ymax= qmax#/math.sqrt(2)
-        
-        #print "model draw comptele xmax",theory.xmax,model.name
+        ## determine plot boundaries
+        theory.xmin= -qmax
+        theory.xmax= qmax
+        theory.ymin= -qmax
+        theory.ymax= qmax
+        ## plot
         wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
                          title="Analytical model 2D ", reset=True ))
@@ -1012,5 +1024,14 @@
     def _draw_model2D(self,model,description=None, enable2D=False,
                       qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
-        
+        """
+            draw model in 2D
+            @param model: instance of the model to draw
+            @param description: the description of the model
+            @param enable2D: when True allows to draw model 2D
+            @param qmin: the minimum value to  draw model 2D
+            @param qmax: the maximum value to draw model 2D
+            @param qstep: the number of division of Qx and Qy of the model to draw
+            
+        """
         x=  numpy.linspace(start= -1*qmax,
                                stop= qmax,
@@ -1022,12 +1043,8 @@
                                endpoint=True )
        
-        lx = len(x)
-        #print x
-        #data=numpy.zeros([len(x),len(y)])
         self.model= model
         if enable2D:
             try:
                 from sans.guiframe.model_thread import Calc2D
-               # print "in draw model 2d ",self.model
                 self.calc_thread = Calc2D(parent =self.parent,x=x,
                                            y=y,model= self.model, 
@@ -1040,8 +1057,9 @@
                 self.calc_thread.ready(2.5)
             except:
-                raise
+                msg= "Draw model 2D error: "
+                wx.PostEvent(self.parent, StatusEvent(status="%s %s" % sys.exc_value))
+                return
             
-    def show_panel2D(self, id=None ):
-        self.parent.show_panel(self.model2D_id)
+  
            
    
