title: Python-scipy: Error while recasting code into a function
body: <p>I have the following code (from the scipy cookbook) to fit a circle to a trajectory: </p>
  
  <pre><code>def calc_R(xc, yc):
      """ calculate the distance of each data points from the center (xc, yc) """
      return np.sqrt((x-xc)**2 + (y-yc)**2)
  
  def f_2b(c):
      """ calculate the algebraic distance between the 2D points and the mean circle centered at c=(xc, yc) """
      Ri = calc_R(*c)
      return Ri - Ri.mean()
  
  def Df_2b(c):
      """ Jacobian of f_2b
      The axis corresponding to derivatives must be coherent with the col_deriv option of leastsq"""
      xc, yc     = c
      df2b_dc    = np.empty((len(c), x.size))
  
      Ri = calc_R(xc, yc)
      df2b_dc[0] = (xc - x)/Ri                   # dR/dxc
      df2b_dc[1] = (yc - y)/Ri                   # dR/dyc
      df2b_dc    = df2b_dc - df2b_dc.mean(axis=1)[:, np.newaxis]
  
      return df2b_dc
  
  x = x_dat[list(np.array(track))] #the x-coordinates of the trajectory: obtained from another np array defined elsewhere in the code 
  y = y_dat[list(np.array(track))]
  x_m = np.mean(x)
  y_m = np.mean(y)
  
  center_estimate = x_m, y_m
  center_2b, ier = optimize.leastsq(f_2b, center_estimate, Dfun=Df_2b, col_deriv=True)
  
  xc_2b, yc_2b = center_2b
  Ri_2b        = calc_R(*center_2b)
  R_2b         = Ri_2b.mean() #this is the value i need
  </code></pre>
  
  <p>Now, I want to recast the last few lines of code as a function, so I did this:</p>
  
  <pre><code>def funct(track, x_dat, y_dat):
       x = x_dat[list(np.array(track))] #the x-coordinates of the trajectory: obtained from another np array defined elsewhere in the code 
       y = y_dat[list(np.array(track))]
       x_m = np.mean(x)
       y_m = np.mean(y)
  
       center_estimate = x_m, y_m
       center_2b, ier = optimize.leastsq(f_2b, center_estimate, Dfun=Df_2b, col_deriv=True)
  
       xc_2b, yc_2b = center_2b
       Ri_2b        = calc_R(*center_2b)
       R_2b         = Ri_2b.mean() #this is the value i need
  
       return R_2b
  </code></pre>
  
  <p>Now, when I run </p>
  
  <pre><code>R = funct(track, x_dat, y_dat) # the arguments are calculated in a different part of the code and supplied here
  </code></pre>
  
  <p>I get the error:</p>
  
  <blockquote>
    <p>name 'x' is not defined</p>
  </blockquote>
  
  <p>and it traces back to the function <code>calc_R</code>. </p>
  
  <p>Where am I making a mistake? Sorry about the extremely long post. </p>