integrators/tolerance.py

This example looks at the effect of the 'reltol' setting of casadi::Integrator.

View output (PDF) | source (python)

See also
CASADI_EXPORT Function integrator(const std::string &name, const std::string &solver, const SXDict &dae, const Dict &opts=Dict())
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 from casadi import *
28 from numpy import *
29 from pylab import *
30 
31 x=SX.sym('x')
32 dx=SX.sym('dx')
33 states = vertcat(x,dx)
34 
35 dae={'x':states, 'ode':vertcat(dx,-x)}
36 
37 tend = 2*pi*3
38 ts = linspace(0,tend,1000)
39 
40 tolerances = [-10,-5,-4,-3,-2,-1]
41 
42 figure()
43 
44 for tol in tolerances:
45  opts = {'reltol':10.0**tol, 'abstol':10.0**tol, 'grid':ts, 'output_t0':True}
46  F = integrator('F', 'cvodes', dae, opts)
47  res = F(x0=[1,0])
48  plot(ts,array(res['xf'])[0,:].T,label='tol = 1e%d' % tol)
49 legend( loc='upper left')
50 xlabel('Time [s]')
51 ylabel('State x [-]')
52 show()
53 
54 
55 tolerances = logspace(-15,1,500)
56 endresult=[]
57 
58 for tol in tolerances:
59  opts = {}
60  opts['reltol'] = tol
61  opts['abstol'] = tol
62  opts['tf'] = tend
63  F = integrator('F', 'cvodes', dae, opts)
64  res = F(x0=[1,0])
65  endresult.append(res['xf'][0])
66 
67 endresult = vcat(endresult)
68 
69 figure()
70 loglog(tolerances,(array(endresult)-1),'b',label='Positive error')
71 loglog(tolerances,-(array(endresult)-1),'r',label='Negative error')
72 xlabel('Integrator relative tolerance')
73 ylabel('Error at the end of integration time')
74 legend(loc='upper left')
75 show()