Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Least squares in a set of equations with optimize.leastsq() (Python)

I have two functions and a set of data. Both functions have the same x data and the same parameters. I want to obtain the parameters by least squares method that makes the best fit of my data.

The parameters are: ex,ey,ez.

The X data are: RA,DE (like 3000 points).

The Y data are: dRA,dDE.

I tried this but I obtained a wrong solution:

def residuals(p, dRA, dDE, RA, DEC):
    ex,ey,ez = p
    f1 = dRA-(ex*sin(DEC)*cos(RA)+ey*sin(DEC)*sin(RA)-ez*cos(DEC))
    f2 = dDE-(-ex*sin(RA)+ey*cos(RA))
    err = np.concatenate((f1,f2))
    return err

from scipy.optimize import leastsq
p0 = [0, 0., 0.]
plsq_coord = leastsq(residuals, p0, args=(dRA, dDE, RA, DE))
print plsq_coord[0] 

Any kind of help would be very wellcome

like image 841
user1404919 Avatar asked Dec 11 '25 02:12

user1404919


1 Answers

As shown by this test code code

import numpy as np, numpy.random,scipy.optimize
def residuals(p, dRA, dDE, RA, DEC):
    ex,ey,ez = p
    f1 = dRA-(ex*np.sin(DEC)*np.cos(RA)+ey*np.sin(DEC)*np.sin(RA)-ez*np.cos(DEC))
    f2 = dDE-(-ex*np.sin(RA)+ey*np.cos(RA))
    err = np.concatenate((f1,f2))
    return err    
ex, ey, ez = 0.2, 0.3, 0.4
N = 100
err = 1e-3
ra, dec = np.random.uniform(0,1,N), np.random.uniform(0,.5,N)
dra = (ex*np.sin(dec)*np.cos(ra)+ey*np.sin(dec)*np.sin(ra)-ez*np.cos(dec))+np.random.normal(size=N)*err
ddec = (-ex*np.sin(ra)+ey*np.cos(ra))+np.random.normal(size=N)*err
print scipy.optimize.leastsq(residuals, p0, args=(dra, ddec, ra, dec))

your code should work fine, unless your function is written incorrectly (e.g. your ra,dec are in degrees, not radians) or you have some bad datapoints in the dataset which screw the chisq fit.

like image 115
sega_sai Avatar answered Dec 12 '25 17:12

sega_sai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!