How to set up minification with scipy lesssq
I'm trying to figure out how to set up python scipy minification problem. This is the example that I used in the Excel Solver solution. The easiest way to explain the problem is to try to solve a very simple electrical network:
R1: 100
R2: 1000
R3: 50
U: 10
Three resistors, two in parallel (R2, R3) and then in series with R1. 10 volt power supply
Control equations
i1 - i2 - i3 = 0
U - i1*R1 - i2*R2 = 0
U - i1*R1 - i3*R3 = 0
The solution for i1, i2, i3 is found by minimizing the objective function defined as
(i1-i2-i3)**2 + (U-i1R1-i2R2)**2 + (U-i1*R1-i3R3)**2
How do I implement this problem in scipy lesssq?
The reason I want to use lesssq is because my actual network is much more complex and contains non-linear elements (it is not actually an electrical network, but hydraulics).
Many thanks! Willem
source to share
First, you define an actual target function that should take your unknown variables as an argument
def objective(x):
i1, i2, i3 = x
R1 = 100
R2 = 1000
R3 = 50
U = 10
return (i1-i2-i3)**2 + (U-i1*R1-i2*R2)**2 + (U-i1*R1-i3*R3)**2
Then you give some initial guess for your currents
x0 = [1.0, 1.0, 1.0] # or whatever you want to start with
Then call minimize
from scipy.optimize import minimize
res = minimize(objective, x0)
You can also pass an argument method
if you want to specify a specific minimization algorithm .
Also, if you can define your yakobianskie (and possibly your gessianskie) of the matrix, you can also use the method on the basis of the gradient, respectively, passing arguments jac
and hess
that should converge faster.
source to share