# Contents of /trunk/models/johnpye/leastsq.a4c

Fri May 11 19:52:18 2012 UTC (8 years, 8 months ago) by jpye
File MIME type: text/x-ascend
File size: 1522 byte(s)
```Least squares model currently solves with SOLVE command, but not via GUI...
```
 1 (* 2 Testing implementation of a least-squares curve fit using IPOPT as the 3 solver... 4 5 Solution should be close to a = 1, b = -12, c = 37 6 *) 7 IMPORT "ipopt"; 8 IMPORT "johnpye/extpy/extpy"; 9 IMPORT "johnpye/leastsq_fit"; 10 REQUIRE "atoms.a4l"; 11 12 (* 13 Model containing just the parameters we wish to identify. 14 *) 15 MODEL params; 16 a,b,c IS_A solver_var; 17 END params; 18 19 (* 20 Parametric model containing the fitting curve. The parameters are passed 21 in along with a single 'x' value; the 'y' value is calculated and stored 22 as part of this sub-model. 23 *) 24 MODEL fn( 25 p WILL_BE params; 26 x WILL_BE solver_var; 27 ); 28 y IS_A solver_var; 29 y = (p.a * x + p.b)*x + p.c; 30 END fn; 31 32 (* 33 Least-squares curve fit model (fitting simple x-y data). No provision yet 34 for reading x-y data from an external file. 35 *) 36 MODEL leastsq; 37 p IS_A params; 38 n IS_A integer_constant; 39 n :== 10; 40 x[1..n], y[1..n] IS_A solver_var; 41 FOR i IN [1..n] CREATE 42 f[i] IS_A fn(p, x[i]); 43 END FOR; 44 sse IS_A solver_var; 45 sse = SUM[(y[i] - f[i].y)^2 | i IN [1..n]]; 46 MINIMIZE sse; 47 METHODS 48 METHOD on_load; 49 FIX x[1..n], y[1..n]; 50 FOR i IN [1..n] DO 51 x[i] := i; 52 END FOR; 53 y[1] := 27.5638512764; 54 y[2] := 17.0591647169; 55 y[3] := 10.2458879212; 56 y[4] := 5.5211061304; 57 y[5] := 3.8450975241; 58 y[6] := 2.7473614207; 59 y[7] := 4.279372646; 60 y[8] := 6.2993978336; 61 y[9] := 11.9244818208; 62 y[10] := 19.6601520996; 63 64 SOLVER IPOPT; 65 OPTION hessian_approximation 'limited-memory'; 66 SOLVE; 67 RUN plot_fit; 68 END on_load; 69 METHOD plot_fit; 70 EXTERNAL leastsq_plot(SELF); 71 END plot_fit; 72 END leastsq;