|
Revision 1504, 1.3 KB
(checked in by dmitrey.kroshko, 9 months ago)
|
|
add converter nlsp2nlp
|
| Line | |
|---|
| 1 | """ |
|---|
| 2 | Solving system of equations: |
|---|
| 3 | x[0]**3+x[1]**3-9 = 0 |
|---|
| 4 | x[0]-0.5*x[1] = 0 |
|---|
| 5 | cos(x[2])+x[0]-1.5 = 0 |
|---|
| 6 | """ |
|---|
| 7 | |
|---|
| 8 | from scikits.openopt import NLSP |
|---|
| 9 | from numpy import asfarray, zeros, cos, sin |
|---|
| 10 | |
|---|
| 11 | f = lambda x: (x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5) |
|---|
| 12 | # or: |
|---|
| 13 | #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) |
|---|
| 14 | # Python list, numpy.array are allowed as well: |
|---|
| 15 | #f = lambda x: [x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5] |
|---|
| 16 | #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)) |
|---|
| 17 | |
|---|
| 18 | #optional: gradient |
|---|
| 19 | def DF(x): |
|---|
| 20 | df = zeros((3,3)) |
|---|
| 21 | df[0,0] = 3*x[0]**2 |
|---|
| 22 | df[0,1] = 3*x[1]**2 |
|---|
| 23 | df[1,0] = 1 |
|---|
| 24 | df[1,1] = -0.5 |
|---|
| 25 | df[2,0] = 1 |
|---|
| 26 | df[2,2] = -sin(x[2]) |
|---|
| 27 | return df |
|---|
| 28 | |
|---|
| 29 | x0 = [8,15, 80] |
|---|
| 30 | |
|---|
| 31 | #w/o gradient: |
|---|
| 32 | #p = NLSP(f, x0) |
|---|
| 33 | p = NLSP(f, x0, df = DF) |
|---|
| 34 | |
|---|
| 35 | #optional: user-supplied gradient check: |
|---|
| 36 | #p.checkdf() |
|---|
| 37 | |
|---|
| 38 | #optional: graphical output, requires matplotlib installed |
|---|
| 39 | p.plot = 1 |
|---|
| 40 | |
|---|
| 41 | #r = p.solve('scipy_fsolve') |
|---|
| 42 | p.maxFunEvals = 1e5 |
|---|
| 43 | p.iprint = 10 |
|---|
| 44 | |
|---|
| 45 | #r = p.solve('scipy_fsolve') |
|---|
| 46 | #r = p.solve('nssolve') |
|---|
| 47 | #or using converter nlsp2nlp, try to minimize sum(f_i(x)^2): |
|---|
| 48 | r = p.solve('nlp:ralg') |
|---|
| 49 | |
|---|
| 50 | print 'solution:', r.xf |
|---|
| 51 | print 'max residual:', r.ff |
|---|
| 52 | ############################### |
|---|
| 53 | #should print: |
|---|
| 54 | #solution: [ 1. 2. 55.50147021] |
|---|
| 55 | #max residual: 2.72366951215e-09 |
|---|