Home > OS >  Solution of an overdetermined nonlinear system of equations with boundary conditions in python
Solution of an overdetermined nonlinear system of equations with boundary conditions in python

Time:10-08

I try to solve an overdetermined linear equation system with boundary conditions. To describe my problem, I try to give an example:

### Input values
LED1_10 = np.array([1.5, 1, 0.5, 0.5])
LED1_20 = np.array([2.5, 1.75, 1.2, 1.2])
LED1_30 = np.array([3, 2.3, 1.7, 1.7])

LED2_10 = np.array([0.2, 0.8, 0.4, 0.4])
LED2_20 = np.array([0.6, 1.6, 0.5, 0.5])
LED2_30 = np.array([1.0, 2.0, 0.55, 0.55])

LED3_10 = np.array([1, 0.1, 0.4, 0.4])
LED3_20 = np.array([2.5, 0.8, 0.9, 0.9])
LED3_30 = np.array([3.25, 1, 1.3, 1.3])

### Rearrange the values
LED1 = np.stack((LED1_10, LED1_20, LED1_30)).T
LED2 = np.stack((LED2_10, LED2_20, LED2_30)).T
LED3 = np.stack((LED3_10, LED3_20, LED3_30)).T

### Fit polynomals
LEDs = np.array([LED1, LED2, LED3])
fits = [
    [np.polyfit(np.array([10, 20, 30]), LEDs[i,j], 2) for j in range(LEDs.shape[1])]
    for i in range(LEDs.shape[0])
]
fits = np.array(fits)

def g(x):
    X = np.array([x**2, x, np.ones_like(x)]).T
    return np.sum(fits * X[:,None], axis=(0, 2))

### Solve
def system(x,b):
    return (g(x)-b)

b = [5, 8, 4, 12]
x = least_squares(system, np.asarray((1,1,1)), bounds=(0, 20), args = b).x

In my first approach I solved the system without boundaries using the solver leastsq like this x = scipy.optimize.leastsq(system, np.asarray((1,1,1)), args=b)[0] This worked out fine and brought me a solution for x1, x2 and x3. But now I've realized that my real-world application requires limits.

If i run my code as presented above i get the error: "system() takes 2 positional arguments but 5 were given"

Can anyone help me solving this problem? Or maybe suggest another solver for this task if least_squares is not the right choice.

Thank you for all of your help.

CodePudding user response:

You are passing a list of 4 elements as args, so least_squares thinks your function system takes 5 arguments. Instead, either pass a tuple of your optional arguments, i.e.

x = least_squares(system, np.asarray((1,1,1)), bounds=(0, 20), args = (b,)).x

or use a lambda:

x = least_squares(lambda x: g(x) - b, np.asarray((1,1,1)), bounds=(0, 20)).x
  • Related