title: Optimizing by translation to map one x,y set of points onto another
body: <p>I have a list of x,y ideal points, and a second list of x,y measured points. The latter has some offset and some noise.</p>
  
  <p>I am trying to "fit" the latter to the former. So, extract the x,y offset of the latter relative to the former. </p>
  
  <p>I'm following some examples of <code>scipy.optimize.leastsq</code>, but having trouble getting it working. Here is my code:</p>
  
  <pre><code>import random
  import numpy as np
  from scipy import optimize
  # Generate fake data. Goal: Get back dx=0.1, dy=0.2 at the end of this exercise
  dx = 0.1
  dy = 0.2
  # "Actual" (ideal) data.
  xa = np.array([0,0,0,1,1,1])
  ya = np.array([0,1,2,0,1,2])
  # "Measured" (non-ideal) data. Add the offset and some randomness.
  xm = map(lambda x: x + dx + random.uniform(0,0.01), xa)
  ym = map(lambda y: y + dy + random.uniform(0,0.01), ya)
  # Plot each
  plt.figure()
  plt.plot(xa, ya, 'b.', xm, ym, 'r.')
  
  # The error function.
  # 
  # Args:
  #   translations: A list of xy tuples, each xy tuple holding the xy offset
  #   between 'coords' and the ideal positions.
  #   coords: A list of xy tuples, each xy tuple holding the measured (non-ideal)
  #   coordinates.
  def errfunc(translations, coords):
    sum = 0
    for t, xy in zip(translations, coords):
      dx = t[0] + xy[0]
      dy = t[1] + xy[1]
      sum += np.sqrt(dx**2 + dy**2)
    return sum
  
  translations, coords = [], []
  for xxa, yya, xxm, yym in zip(xa, ya, xm, ym):
    t = (xxm-xxa, yym-yya)
    c = (xxm, yym)
    translations.append(t)
    coords.append(c)
  
  translation_guess = [0.05, 0.1]
  out = optimize.leastsq(errfunc, translation_guess, args=(translations, coords), full_output=1)
  
  print out
  </code></pre>
  
  <p>I get the error:</p>
  
  <blockquote>
    <p>errfunc() takes exactly 2 arguments (3 given)"</p>
  </blockquote>
  
  <p>I'm not sure why it says 3 arguments as I only gave it two. Can anyone help?</p>
  
  <p>====</p>
  
  <p>ANSWER: </p>
  
  <p>I was thinking about this wrong. All I have to do is to take the average of the dx and dy's -- that gives the correct result.</p>
  
  <pre><code>n = xa.shape[0]
  dx = -np.sum(xa - xm) / n
  dy = -np.sum(ya - ym) / n
  print dx, dy
  </code></pre>