1 |
""" |
2 |
Let us solve the overdetermined nonlinear equations: |
3 |
a^2 + b^2 = 15 |
4 |
a^4 + b^4 = 100 |
5 |
a = 3.5 |
6 |
|
7 |
Let us concider the problem as |
8 |
x[0]**2 + x[1]**2 - 15 = 0 |
9 |
x[0]**4 + x[1]**4 - 100 = 0 |
10 |
x[0] - 3.5 = 0 |
11 |
|
12 |
Now we will solve the one using solver scipy_leastsq |
13 |
""" |
14 |
from openopt import NLLSP |
15 |
from numpy import * |
16 |
|
17 |
f = lambda x: ((x**2).sum() - 15, (x**4).sum() - 100, x[0]-3.5) |
18 |
# other possible f assignments: |
19 |
# f = lambda x: [(x**2).sum() - 15, (x**4).sum() - 100, x[0]-3.5] |
20 |
#f = [lambda x: (x**2).sum() - 15, lambda x: (x**4).sum() - 100, lambda x: x[0]-3.5] |
21 |
# f = (lambda x: (x**2).sum() - 15, lambda x: (x**4).sum() - 100, lambda x: x[0]-3.5) |
22 |
# f = lambda x: asfarray(((x**2).sum() - 15, (x**4).sum() - 100, x[0]-3.5)) |
23 |
#optional: gradient |
24 |
def df(x): |
25 |
r = zeros((3,2)) |
26 |
r[0,0] = 2*x[0] |
27 |
r[0,1] = 2*x[1] |
28 |
r[1,0] = 4*x[0]**3 |
29 |
r[1,1] = 4*x[1]**3 |
30 |
r[2,0] = 1 |
31 |
return r |
32 |
|
33 |
# init esimation of solution - sometimes rather pricise one is very important |
34 |
x0 = [1.5, 8] |
35 |
|
36 |
#p = NLLSP(f, x0, diffInt = 1.5e-8, xtol = 1.5e-8, ftol = 1.5e-8) |
37 |
# or |
38 |
# p = NLLSP(f, x0) |
39 |
# or |
40 |
p = NLLSP(f, x0, df = df, xtol = 1.5e-8, ftol = 1.5e-8) |
41 |
|
42 |
#optional: user-supplied gradient check: |
43 |
p.checkdf() |
44 |
#r = p.solve('scipy_leastsq', plot=1, iprint = -1) |
45 |
#or using converter lsp2nlp: |
46 |
r = p.solve('nlp:ralg', plot=1) |
47 |
#r = p.solve('nlp:ipopt',plot=1), r = p.solve('nlp:algencan'), r = p.solve('nlp:ralg'), etc |
48 |
#(some NLP solvers require additional installation) |
49 |
|
50 |
print 'x_opt:', r.xf # 2.74930862, +/-2.5597651 |
51 |
print 'funcs Values:', p.f(r.xf) # [-0.888904734668, 0.0678251418575, -0.750691380965] |
52 |
print 'f_opt:', r.ff, '; sum of squares (should be same value):', (p.f(r.xf) ** 2).sum() # 1.35828942657 |