3

I am trying to understand how to set up a python scipy minimizing problem. It is an example I took from an Excel Solver problem. The simplest way to explain the problem is by trying to solve a very simple electrical network:

R1: 100
R2: 1000
R3: 50
U: 10

Three resistors, two parallel (R2,R3) and then in series with R1. Power supply of 10 Volts

The governing equations are

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 given as

(i1-i2-i3)**2 + (U-i1R1-i2R2)**2 + (U-i1*R1-i3R3)**2

How to implement this problem in scipy leastsq?

The reason I want to use leastsq is because my actual network is far more complex and contains non-linear elements (it is actually not a electrical network, but a hydraulics network).

Thanks very much! Willem

Willem
  • 61
  • 4

1 Answers1

0

First you define the actual objective function, which must 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 provide 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 in the method argument if you'd like to specify a specific minimization algorithm.

Also, if you can define your Jacobian (and possibly your Hessian) matrices, you can also use a gradient-based method by passing in the jac and hess arguments respectively, which should converge faster.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218