[SciPy-user] Using SciPy/NumPy optimization THANKS!

Alok Singhal as8ca at virginia.edu
Wed Feb 28 16:16:26 EST 2007


On 28/02/07: 15:51, Brandon Nuttall wrote:
> import numpy as np
> from scipy import rand
> from scipy.optimize import leastsq
> import pylab
> 
> class HypObj:
>      """Object for best fit to hyperbolic function"""
>      def __init__(self,x,y,guess=None,plot=None):
>          self.x = x
>          self.y = y
>          self.plot=plot
>          if guess==None:
>              self.guess = [y.max(),1.0,0.5]
>          else:
>              self.guess = guess
>          self.parameters, self.success = leastsq(self._errf,
>                                                  self.guess[:],
>                                                  args = (self.x, self.y))
>          self.r2 = self._r2(self.x,self.y,self.parameters)
>          if self.plot<>None:

Maybe 

if self.plot is not None:

is better?  See http://www.python.org/dev/peps/pep-0008/, section
'Programming Recommendations'.

> def list_toarray(data):
>      """Convert input list of data pairs to two arrays"""
>      x = []
>      y = []
>      for i in data:
>          x.append(float(i[0]))
>          y.append(float(i[1]))
>      x = np.array(x)
>      y = np.array(y)
>      return x,y

For your data, you can do:

x = [data[i][0] for i in range(60)]
y = [data[i][1] for i in range(60)]

If you want to use numpy, then you could do:

data = np.asarray(data)
x = data[:, 0]
y = data[:, 1]

> def test():
> 
>      def f(p, x): # for testing, make the objective function available
>          return p[0]*(1.0+p[1]*p[2]*x)**(-1.0/p[1])
> 
>      # fake data for testing, should get perfect correlation
>      print "\nTest 1: should find an exact solution = [1.25,0.75,0.25]"
>      print "(No plot)"
>      qi, b, di = [1.25,0.75,0.25]
>      sample = []
>      for i in range(1,61):
>          sample.append([float(i),qi*(1.0+b*di*float(i))**(-1.0/b)])

You don't need the loop:

sample = np.zeros((60, 2), dtype=float)
sample[:, 0] = np.arange(60) + 1
sample[:, 1] = qi*(1. + b*di*sample[:, 0])**(-1.0/b)

Given that you 'unpack' sample at a later stage anyway, you could as
well use two different variables instead of sample.

Cheers,
Alok

-- 
Alok Singhal                               *   *          
Graduate Student, dept. of Astronomy   *           *     *
University of Virginia                                    
http://www.astro.virginia.edu/~as8ca/              *    * 



More information about the SciPy-User mailing list