File: fittingEquations.wxm

package info (click to toggle)
wxmaxima 26.01.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 32,436 kB
  • sloc: cpp: 77,544; xml: 10,497; ansic: 3,651; lisp: 1,900; sh: 28; makefile: 27
file content (465 lines) | stat: -rw-r--r-- 13,460 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/* [wxMaxima batch file version 1] [ DO NOT EDIT BY HAND! ]*/
/* [ Created with wxMaxima version 20.04.0-DevelopmentSnapshot ] */
/* [wxMaxima: title   start ]
Fitting equations to real measurement data
   [wxMaxima: title   end   ] */


/* [wxMaxima: comment start ]
One place Maxima can show its full power at is where symbolical mathematics that describes a phenomenon is used for understanding real measurement data.
   [wxMaxima: comment end   ] */


/* [wxMaxima: comment start ]
As a first step normally the real measurement data is loaded from a .csv file using read_matrix:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
? read_matrix;
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
For the sake of generating a self-contained example we generate this data synthetically. For the first example a parabola with a bit of measurement noise might be a good start:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
fun1(x):=3*x^2-2*x+7;
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
time1:makelist(i,i,-10,10,.02)$
data1:transpose(
    matrix(
        time1,
        makelist(fun1(i)+random(32.0)-16,i,time1)
    )
)$
wxdraw2d(grid=true,xlabel="x",ylabel="y",
    points(data1)
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: section start ]
The general approach
   [wxMaxima: section end   ] */


/* [wxMaxima: comment start ]
Let's assume we have guessed that the curve might be something parabola-like:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
approach1:y=a*x^2+b*x+c;
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Maxima now offers a simple, but powerful curve fitter that guesses the parameters a,b and c for us:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
load("lsquares")$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
lsquares_estimates_approximate(
    lsquares_mse(
        data1,[x,y],approach1
    ),
    [a,b,c],
    initial=[0,0,0]
);
params1:%[1];
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
In this example the "initial=" wasn't really necessary. But sometimes using the wrong starting point means that lsquares heads for the wrong local optimum of the problem.
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
rec1:subst(params1,approach1);
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
wxdraw2d(
    grid=true,xlabel="x",ylabel="y",
    color=red,key="Reconstructed",
    explicit(rhs(rec1),x,-10,10),
    color=blue,key="Original",
    explicit(fun1,x,-10,10)
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Besides lsquares_estimates_approximate the lsquares package also provides a command named lsquares_estimates that tries to find the exact optimum by running the problem through solve() before finding the answer numerically. But as it is always the case with computers if the problem that is to be solved is complex one does not know in advance how long it will take and if it ever will finish. lsquares_estimates_approximate doesn't have this drawback.
   [wxMaxima: comment end   ] */


/* [wxMaxima: section start ]
Dealing with non-evenly-spaced data
   [wxMaxima: section end   ] */


/* [wxMaxima: comment start ]
Sometimes the input data isn't evenly spaced.
   [wxMaxima: comment end   ] */


/* [wxMaxima: comment start ]
The places with a higher density of samples have more weight when fitting data to the curves. So let's add an error to the place with the highest data density and see if we can cope with it.
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
time2:makelist(i^4*i/abs(i),i,-2,2,.02)$
data2:transpose(
    matrix(
        time2,
        makelist(fun1(i)+random(4.0)-2+50*sin(i)/i,i,time2)
    )
)$
wxdraw2d(grid=true,xlabel="x",ylabel="y",
    points(data2),
    yrange=[0,800]
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Since the biggest error occurs where we have the highest density of data the result of fitting the curve to this data directly will be suboptimal:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
lsquares_estimates_approximate(
    lsquares_mse(
        data2,[x,y],approach1
    ),
    [a,b,c]
);
params2_1:%[1];
wxdraw2d(
    grid=true,xlabel="x",ylabel="y",
    color=red,key="Reconstructed",
    explicit(rhs(subst(params2_1,approach1)),x,-10,10),
    color=blue,key="Original",
    explicit(fun1,x,-10,10)
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: subsect start ]
Converting the data to a continuous curve
   [wxMaxima: subsect end   ] */


/* [wxMaxima: comment start ]
The interpol package allows to generate continuous and half-way smooth curves from any input data.
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
load("interpol")$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
data2_cont:cspline(data2,'varname=x)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
wxdraw2d(
    explicit(data2_cont,x,-10,10),
    grid=true,xlabel="x",ylabel="y"
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: subsect start ]
Generating evenly-spaced samples from this curve
   [wxMaxima: subsect end   ] */


/* [wxMaxima: comment start ]
First, we generate the new data and time vector. As always, the fact that a subst() is necessary in this step is caused by a bug in makelist.
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
time_i:makelist(i,i,-10,10,.05)$
values2_i:makelist(subst(x=i,data2_cont),i,time_i)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Now we generate a matrix of values lsquares can deal with:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
data2_i:float(transpose(matrix(time_i,values2_i)))$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
The result is a still noisy and distorted, but more evenly-spaced curve:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
wxdraw2d(
    points(data2_i),
    grid=true,xlabel="x",ylabel="y"
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Fitting this curve will yield a better result as the first attempt:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
lsquares_estimates_approximate(
    lsquares_mse(
        data2_i,[x,y],approach1
    ),
    [a,b,c]
);
params2_2:%[1];
wxdraw2d(
    grid=true,xlabel="x",ylabel="y",
    color=red,key="Reconstructed",
    explicit(rhs(subst(params2_2,approach1)),x,-10,10),
    color=blue,key="Original",
    explicit(fun1,x,-10,10)
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: section start ]
Fitting data to a·exp(k·t)
   [wxMaxima: section end   ] */


/* [wxMaxima: comment start ]
The natural approach to fitting data to exponential curves would be:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
approach2:y=a*exp(k*t);
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Unfortunately it is hard to fit to experimental data to this approach in many ways, for example:
 * One part of this curve results in low values. Even small measurement noise on this part will yield widely incorrect results for the curve parameters as the fitter is trying to model the noise, too, and as noise in nonlinear systems tends not to be averaged out completely.
 * Another part of this curve contains very high values and is sensitive to even small changes in k. As the fitter wants to keep the overall error low it will therefore respect this part much more than the lower, more good-natured part of the curve.
 * Starting from the wrong point and optimizing a and k in the direction that reduces the error most in each step might lead to a point that is far from being the solution
 * and trying to use lsquares_estimates to find the ideal solution often leads to numbers that exceed the floating-point range (or exact numbers longer than the computer's memory).
   [wxMaxima: comment end   ] */


/* [wxMaxima: comment start ]
A better approach is therefore to use Caruana's approach for fitting:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
approach2/a;
caruana:log(%);
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
This approach is much more good-natured for finding the parameters (that can then be substituted into approach2).
   [wxMaxima: comment end   ] */


/* [wxMaxima: comment start ]
The problem with noise causing finding erroneous parameters is still valid, though, in this case.  It can be partially eliminated by introducing a c_noise, as proposed by Guo.
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
lhs(approach2)=rhs(approach2+c_noise);
%-c_noise;
%/a;
approach_guo:log(%),logexpand=super;
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Additionally https://ieeexplore.ieee.org/document/5999593 offers an iterative method that allows to reduce the influence of noise in each step:
   [wxMaxima: comment end   ] */


/* [wxMaxima: section start ]
Using a different fitting algorithm
   [wxMaxima: section end   ] */


/* [wxMaxima: comment start ]
Maxima provides a second algorithm that often produces even better results, but is a bit more complicated to use. For example it requires us to manually compile a list of the errors we want to minimize. Let's do that for data2_i and approach1:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
approach1;
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
errval:lhs(approach1)-rhs(approach1);
my_mse:makelist(
    subst(
        [x=i[1],y=i[2]],
        errval
    ),
    i,args(data2_i)
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Hints for understanding this construct:
 * args() converts a matrix to a list of lists, 
 * The makelist() command steps through this list and for each  data point assigns the list of the x and y value to i
 * rhs() and lhs() extract the right hand side and the left hand side of an equation (the part right and left of the "=") 
 * and since we know which element in i means which variable we can use subst() in order to substitute the elements in i into errval, the equation that tells us how big the error in this point is.
   [wxMaxima: comment end   ] */


/* [wxMaxima: comment start ]
The result is a list of error values, each in the following format:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
my_mse[1];
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Now let's load the package that contains the other fitter:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
load("minpack")$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Fitting the data is simple:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
param_list:[a,b,c];
result:minpack_lsquares(my_mse,param_list,[1,1,1]);
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Converting the result into a list of equations is a bit more complicated:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
params_3:map(lambda([x],x[1]=x[2]),args(transpose(matrix(param_list,result[1]))));
/* [wxMaxima: input   end   ] */


/* [wxMaxima: comment start ]
Hints for understanding this line:
 * Map runs a command on each element of a list
 * We want to  provide map with a command that converts something of the type "[a,3]" to an "a=3".  But we won't re-use this command so there is no need to actually give this command a name. Therefore we use lambda() in order to create a name-less command with one parameter, x.
 * args again converts a matrix to a list of lists and
 * we need to convert our input data into a list in order to transpose it (which means: exchange the columns by rows and vice versa)
   [wxMaxima: comment end   ] */


/* [wxMaxima: comment start ]
The result isn't too bad, this time, neither:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
wxdraw2d(
    grid=true,xlabel="x",ylabel="y",
    color=red,key="Reconstructed",
    explicit(rhs(subst(params_3,approach1)),x,-10,10),
    color=blue,key="Original",
    explicit(fun1,x,-10,10)
)$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: section start ]
A third fitting algorithm
   [wxMaxima: section end   ] */


/* [wxMaxima: comment start ]
Maxima even offers a third fitting algorithm that is even able to understand constraints:
   [wxMaxima: comment end   ] */


/* [wxMaxima: input   start ] */
? fmin_cobyla;
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
load("fmin_cobyla")$
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
fmin_cobyla(
    lsquares_mse(
        data1,[x,y],approach1
    ),
    [a,b,c],
    [0,0,0]
);
params5:%[1];
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
rec5:subst(params5,approach1);
/* [wxMaxima: input   end   ] */


/* [wxMaxima: input   start ] */
wxdraw2d(
    grid=true,xlabel="x",ylabel="y",
    key="Measured data",color=gray,points_joined=true,line_type='dashes,point_type='none,
    points(data1),
    color=red,key="Reconstructed",
    explicit(rhs(rec5),x,-10,10),
    color=blue,key="Original",
    explicit(fun1,x,-10,10)
)$
/* [wxMaxima: input   end   ] */



/* Old versions of Maxima abort on loading files that end in a comment. */
"Created with wxMaxima 20.04.0-DevelopmentSnapshot"$