Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Using `scipy.optimize.leaset_squares` to fit two curves with undetermined argument shapes [closed]

$
0
0

I'm writing code to fit parameters of related pairs of functions from a family using the scipy.optimize.least_squares() function and it seems that the test parameters are not being passed to the function correctly. Here's a simplified illustration of the problem.

import numpy as npimport numpy.linalg as laimport scipy.optimizeimport mathHa = {'H': lambda x, a, b : a + b*x, 'nParams': 2}Hb = {'H': lambda x, a, b, c : a + b*x + c*x*x, 'nParams': 3}Hc = {'H': lambda x, a, b, c, d : a*math.cos(b*(x-c)) + d, 'nParams': 4}points1 = [(1,0), (2,4), (3,5), (7,8)]points2 = [(1,1), (2,6), (4,1), (6,6)]def coupled_1 (x, g, *params, **kwargs):    H1, H2 = kwargs.values() # H1 and H2 are dictionaries containing the two curves                             # to be fit, 'H', and their respective numbers of                             # parameters, 'nParams'    matrix = np.diag([H1['H'](x, *params[:H1['nParams']]), H2['H'](x, *params[H1['nParams']:])]) \+ np.diag([g],k=1) + np.diag([g],k=-1)    return la.eigh(matrix)['eigenvalues'][0]def coupled_2 (x, g, *params, **kwargs):    H1, H2 = kwargs.values()    matrix = np.diag([H1['H'](x, *params[:H1['nParams']]), H2['H'](x, *params[H1['nParams']:])]) \+ np.diag([g],k=1) + np.diag([g],k=-1)    return la.eigh(matrix)['eigenvalues'][1]def getParameters(H1, H2, pts1, pts2):    nParams = H1['nParams'] + H2['nParams']    # These points sometimes come in pairs and sometimes don't so I've found no better way to zip them    pts     = [(p1, p2) for p1 in pts1 for p2 in pts2 if p1[0] == p2[0]]    res     = lambda *params, **kwargs: \                     np.sqrt(sum( [( p[0][1]-coupled_1(p[0][0], *params, **kwargs) )**2 \+ (p[1][1]-coupled_2(p[0][0], *params, **kwargs) )**2 for p in pts] ))    result  = scipy.optimize.least_squares(res,[1] + [0]*nParams, kwargs={'H1':H1,'H2':H2})    return result['x']params = getParameters(Ha, Hc, points1, points2)

I'm receiving an error from Ha() that it is missing all but its first positional argument, but I'm unsure why the test parameters from least_squares() aren't making it to Ha().


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>