root/trunk/openopt/scikits/openopt/examples/nlsp_constrained.py

Revision 1504, 1.9 KB (checked in by dmitrey.kroshko, 9 months ago)

add converter nlsp2nlp

Line 
1"""
2Solving system of equations:
3x[0]**3+x[1]**3-9 = 0
4x[0]-0.5*x[1] = 0
5cos(x[2])+x[0]-1.5 = 0
6with some constraints:
7150 <= x[2] <= 158
8and possible non-linear constraint:
9(x[2] - 150.8)**2 <= 1.5
10
11Note:
121. Using Ax <= b constraints is also allowed
132. You can try using equality constraints (h(x)=0, Aeq x = beq) as well.
143. Required function tolerance is p.ftol, constraints tolerance is p.contol,
15and hence using h(x)=0 constraints is not 100% same
16to some additional f coords
17"""
18
19from scikits.openopt import NLSP
20from numpy import asfarray, zeros, cos, sin
21
22# you can define f in several ways:
23f = lambda x: (x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5)
24#f = (lambda x: x[0]**3+x[1]**3-9, lambda x: x[0]-0.5*x[1], lambda x: cos(x[2])+x[0]-1.5)
25# Python list, numpy.array are allowed as well:
26#f = lambda x: [x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5]
27#or f = lambda x: asfarray((x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5))
28
29#optional: gradient
30def df(x):
31    df = zeros((3,3))
32    df[0,0] = 3*x[0]**2
33    df[0,1] = 3*x[1]**2
34    df[1,0] = 1
35    df[1,1] = -0.5
36    df[2,0] = 1
37    df[2,2] = -sin(x[2])
38    return df
39
40x0 = [8,15, 80]
41
42#w/o gradient:
43#p = NLSP(f, x0)
44
45p = NLSP(f, x0, df = df, maxFunEvals = 1e5, iprint = 10, plot=1, ftol = 1e-8, contol=1e-15)
46
47#optional: user-supplied gradient check:
48#p.checkdf()
49
50#optional: graphical output, requires matplotlib installed
51#plot doesn't work correctly for constrained NLSP yet
52#p.plot = 1
53
54
55p.lb[2] = 150
56p.ub[2] = 158
57
58# you could try also comment/uncomment nonlinear constraints:
59p.c = lambda x: (x[2] - 150.8)**2-1.5
60# optional: gradient
61p.dc = lambda x: asfarray((0, 0, 2*(x[2]-150.8)))
62# also you could set it via p=NLSP(f, x0, ..., c = c, dc = dc)
63
64#optional: user-supplied dc check:
65#p.checkdc()
66
67#r = p.solve('nssolve', debug=0, maxIter=1e9)
68# using nlsp2nlp converter, try to minimize sum(f_i(x)^2):
69r = p.solve('nlp:ralg')
70
71print 'solution:', r.xf
72print 'max residual:', r.ff
73
Note: See TracBrowser for help on using the browser.