misc/assertion.py

This example looks at the printme method

View output (PDF) | source (python)

See also
Callback function functionality.
MX attachAssert(const MX &y, const std::string &fail_message="") const
returns itself, but with an assertion attached
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 from casadi import *
25 
26 
27 
28 
29 
30 
31 x = MX.sym("x")
32 y = sin(x)
33 z = sqrt(y)
34 
35 f = Function("f", [x], [z])
36 
37 z0 = f(5)
38 
39 print(z0)
40 
41 
42 
43 
44 
45 y = y.attachAssert(y>0, "bummer")
46 z = sqrt(y)
47 
48 f = Function("f", [x],[z])
49 
50 try:
51  z0 = f(5)
52 except Exception as e:
53  print("An exception was raised here:")
54  print(e)
55 
56 
57 
58 
59 class Dummy(Callback):
60  def __init__(self, name, opts={}):
61  Callback.__init__(self)
62  self.construct(name, opts)
63  def get_n_in(self): return 1
64  def get_n_out(self): return 1
65  def eval(self, arg):
66  import numpy
67  x = arg[0]
68  m = max(numpy.real(numpy.linalg.eig(blockcat([[x,-1],[-1,2]]))[0]))
69  print("m=",m)
70  return [int(m>2)]
71 
72 foo = Dummy("foo")
73 
74 y = sin(x)
75 
76 y = y.attachAssert(foo(y), "you are in trouble")
77 z = sqrt(y)
78 
79 f = Function("f", [x],[z])
80 
81 z0 = f(5)