test_examples.py
Go to the documentation of this file.
1 """
2 This file is part of qpOASES.
3 
4 qpOASES -- An Implementation of the Online Active Set Strategy.
5 Copyright (C) 2007-2015 by Hans Joachim Ferreau et al. All rights reserved.
6 
7 qpOASES is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
11 
12 qpOASES is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU Lesser General Public License for more details.
16 
17 You should have received a copy of the GNU Lesser General Public
18 License along with qpOASES; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 
21 author Manuel Kudruss
22 version 3.2
23 date 2013-2015
24 """
25 
26 import os
27 import re
28 import numpy as np
29 from numpy.testing import *
30 from subprocess import Popen, PIPE, STDOUT
31 
32 from qpoases import PyQProblem as QProblem
33 from qpoases import PyQProblemB as QProblemB
34 from qpoases import PySQProblem as SQProblem
35 from qpoases import PySolutionAnalysis as SolutionAnalysis
36 from qpoases import PyBooleanType as BooleanType
37 from qpoases import PySubjectToStatus as SubjectToStatus
38 from qpoases import PyOptions as Options
39 from qpoases import PyPrintLevel as PrintLevel
40 
41 # get qpOASES path
42 qpoases_path = os.path.dirname(os.path.abspath(__file__))
43 qpoases_path = os.path.dirname(qpoases_path)
44 qpoases_path = os.path.dirname(qpoases_path)
45 qpoases_path = os.path.dirname(qpoases_path)
46 
47 # set qpOASES binary path
48 bin_path = os.path.join(qpoases_path, "bin")
49 
50 class TestExamples(TestCase):
51 
52  def test_example1(self):
53  return 0
54  # Example for qpOASES main function using the QProblem class.
55  #Setup data of first QP.
56 
57  H = np.array([1.0, 0.0, 0.0, 0.5 ]).reshape((2,2))
58  A = np.array([1.0, 1.0 ]).reshape((2,1))
59  g = np.array([1.5, 1.0 ])
60  lb = np.array([0.5, -2.0])
61  ub = np.array([5.0, 2.0 ])
62  lbA = np.array([-1.0 ])
63  ubA = np.array([2.0])
64 
65  # Setup data of second QP.
66 
67  g_new = np.array([1.0, 1.5])
68  lb_new = np.array([0.0, -1.0])
69  ub_new = np.array([5.0, -0.5])
70  lbA_new = np.array([-2.0])
71  ubA_new = np.array([1.0])
72 
73  # Setting up QProblemB object.
74  qp = QProblem(2, 1)
75  options = Options()
76  options.printLevel = PrintLevel.NONE
77  qp.setOptions(options)
78 
79  # Solve first QP.
80  nWSR = 10
81  qp.init(H, g, A, lb, ub, lbA, ubA, nWSR)
82 
83  # Solve second QP.
84  nWSR = 10
85  qp.hotstart(g_new, lb_new, ub_new, lbA_new, ubA_new, nWSR)
86 
87  # Get and print solution of second QP.
88  xOpt_actual = np.zeros(2)
89  qp.getPrimalSolution(xOpt_actual)
90  xOpt_actual = np.asarray(xOpt_actual, dtype=float)
91  objVal_actual = qp.getObjVal()
92  objVal_actual = np.asarray(objVal_actual, dtype=float)
93 
94  cmd = os.path.join(bin_path, "example1")
95  p = Popen(cmd, shell=True, stdout=PIPE)
96  stdout, stderr = p.communicate()
97  stdout = str(stdout).replace('\\n', '\n')
98  stdout = stdout.replace("'", '')
99  print(stdout)
100 
101  # get c++ solution from std
102  pattern = re.compile(r'xOpt\s*=\s*\[\s+(?P<xOpt>([0-9., e+-])*)\];')
103  match = pattern.search(stdout)
104  xOpt_expected = match.group('xOpt')
105  xOpt_expected = xOpt_expected.split(",")
106  xOpt_expected = np.asarray(xOpt_expected, dtype=float)
107 
108  pattern = re.compile(r'objVal = (?P<objVal>[0-9-+e.]*)')
109  match = pattern.search(stdout)
110  objVal_expected = match.group('objVal')
111  objVal_expected = np.asarray(objVal_expected, dtype=float)
112 
113  print("xOpt_actual =", xOpt_actual)
114  print("xOpt_expected =", xOpt_expected)
115  print("objVal_actual = ", objVal_actual)
116  print("objVal_expected = ", objVal_expected)
117 
118  assert_almost_equal(xOpt_actual, xOpt_expected, decimal=7)
119  assert_almost_equal(objVal_actual, objVal_expected, decimal=7)
120 
121  def test_example1b(self):
122  """Example for qpOASES main function using the QProblemB class."""
123  # Setup data of first QP.
124  H = np.array([1.0, 0.0, 0.0, 0.5]).reshape((2, 2))
125  g = np.array([1.5, 1.0])
126  lb = np.array([0.5, -2.0])
127  ub = np.array([5.0, 2.0])
128 
129  # Setup data of second QP.
130 
131  g_new = np.array([1.0, 1.5])
132  lb_new = np.array([0.0, -1.0])
133  ub_new = np.array([5.0, -0.5])
134 
135  # Setting up QProblemB object.
136  qp = QProblemB(2)
137 
138  options = Options()
139  # options.enableFlippingBounds = BooleanType.FALSE
140  options.initialStatusBounds = SubjectToStatus.INACTIVE
141  options.numRefinementSteps = 1
142  options.enableCholeskyRefactorisation = 1
143  options.printLevel = PrintLevel.NONE
144  qp.setOptions(options)
145 
146  # Solve first QP.
147  nWSR = 10
148  qp.init(H, g, lb, ub, nWSR)
149 
150  xOpt_actual = np.zeros(2)
151  qp.getPrimalSolution(xOpt_actual)
152  xOpt_actual = np.asarray(xOpt_actual, dtype=float)
153  objVal_actual = qp.getObjVal()
154  objVal_actual = np.asarray(objVal_actual, dtype=float)
155  print 'xOpt_actual:', xOpt_actual
156  print 'objVal_actual:', objVal_actual
157 
158  # Solve second QP.
159  nWSR = 10
160  qp.hotstart(g_new, lb_new, ub_new, nWSR)
161 
162  xOpt_actual = np.zeros(2)
163  qp.getPrimalSolution(xOpt_actual)
164  xOpt_actual = np.asarray(xOpt_actual, dtype=float)
165  objVal_actual = qp.getObjVal()
166  objVal_actual = np.asarray(objVal_actual, dtype=float)
167  print 'xOpt_actual:', xOpt_actual
168  print 'objVal_actual:', objVal_actual
169 
170  # Get and print solution of second QP.
171  xOpt_actual = np.zeros(2)
172  qp.getPrimalSolution(xOpt_actual)
173  xOpt_actual = np.asarray(xOpt_actual, dtype=float)
174  objVal_actual = qp.getObjVal()
175  objVal_actual = np.asarray(objVal_actual, dtype=float)
176 
177  cmd = os.path.join(bin_path, "example1b")
178  p = Popen(cmd, shell=True, stdout=PIPE)
179  stdout, stderr = p.communicate()
180  stdout = str(stdout).replace('\\n', '\n')
181  stdout = stdout.replace("'", '')
182 
183  # get c++ solution from std
184  pattern = re.compile(r'xOpt\s*=\s*\[\s+(?P<xOpt>([0-9., e+-])*)\];')
185  match = pattern.findall(stdout)
186  xOpt_expected = match[-1][0]
187  xOpt_expected = xOpt_expected.split(",")
188  xOpt_expected = np.asarray(xOpt_expected, dtype=float)
189 
190  pattern = re.compile(r'objVal = (?P<objVal>[0-9-+e.]*)')
191  match = pattern.findall(stdout)
192  print match
193  objVal_expected = match[-1]
194  objVal_expected = np.asarray(objVal_expected, dtype=float)
195 
196  print("xOpt_actual =", xOpt_actual)
197  print("xOpt_expected =", xOpt_expected)
198  print("objVal_actual = ", objVal_actual)
199  print("objVal_expected = ", objVal_expected)
200 
201  assert_almost_equal(xOpt_actual, xOpt_expected, decimal=7)
202  assert_almost_equal(objVal_actual, objVal_expected, decimal=7)
203 
204 
205  def test_example2(self):
206  # Example for qpOASES main function using the SQProblem class.
207  # Setup data of first QP.
208  H = np.array([ 1.0, 0.0, 0.0, 0.5 ]).reshape((2,2))
209  A = np.array([ 1.0, 1.0 ]).reshape((2,1))
210  g = np.array([ 1.5, 1.0 ])
211  lb = np.array([ 0.5, -2.0 ])
212  ub = np.array([ 5.0, 2.0 ])
213  lbA = np.array([ -1.0 ])
214  ubA = np.array([ 2.0 ])
215 
216  # Setup data of second QP.
217  H_new = np.array([ 1.0, 0.5, 0.5, 0.5 ]).reshape((2,2))
218  A_new = np.array([ 1.0, 5.0 ]).reshape((2,1))
219  g_new = np.array([ 1.0, 1.5 ])
220  lb_new = np.array([ 0.0, -1.0 ])
221  ub_new = np.array([ 5.0, -0.5 ])
222  lbA_new = np.array([ -2.0 ])
223  ubA_new = np.array([ 1.0 ])
224 
225  # Setting up SQProblem object and solution analyser.
226  qp = SQProblem(2, 1)
227  options = Options()
228  options.printLevel = PrintLevel.NONE
229  qp.setOptions(options)
230 
231  analyser = SolutionAnalysis()
232 
233  # get c++ solution from std
234  cmd = os.path.join(bin_path, "example2")
235  p = Popen(cmd, shell=True, stdout=PIPE)
236  stdout, stderr = p.communicate()
237  stdout = str(stdout).replace('\\n', '\n')
238  stdout = stdout.replace("'", '')
239  print(stdout)
240 
241  # Solve first QP ...
242  nWSR = 10
243  qp.init(H, g, A, lb, ub, lbA, ubA, nWSR)
244 
245  # ... and analyse it.
246  maxViol = np.zeros(1)
247  maxStat = np.zeros(1)
248  maxFeas = np.zeros(1)
249  maxCmpl = np.zeros(1)
250  maxViol[0] = analyser.getKktViolation(
251  qp, maxStat, maxFeas, maxCmpl
252  )
253  print("maxViol: %e\n" % maxViol)
254  actual = np.asarray(maxViol)
255 
256  pattern = re.compile(
257  r'maxKktViolation: (?P<KktViolation>[0-9+-e.]*)'
258  )
259 
260  match = pattern.findall(stdout)
261  expected = np.asarray(match[0], dtype=float)
262 
263  assert_almost_equal(actual, expected, decimal=7)
264 
265  # Solve second QP ...
266  nWSR = 10
267  qp.hotstart(
268  H_new, g_new, A_new,
269  lb_new, ub_new,
270  lbA_new, ubA_new,
271  nWSR
272  )
273 
274  # ... and analyse it.
275  maxViol = np.zeros(1)
276  maxStat = np.zeros(1)
277  maxFeas = np.zeros(1)
278  maxCmpl = np.zeros(1)
279  maxViol[0] = analyser.getKktViolation(
280  qp, maxStat, maxFeas, maxCmpl
281  )
282  print("maxViol: %e\n" % maxViol)
283  actual = np.asarray(maxViol)
284 
285  expected = np.asarray(match[1], dtype=float)
286 
287  assert_almost_equal(actual, expected, decimal=7)
288 
289  # ------------ VARIANCE-COVARIANCE EVALUATION --------------------
290 
291  Var = np.zeros(5*5)
292  Primal_Dual_Var = np.zeros(5*5)
293 
294  Var.reshape((5, 5))[0, 0] = 1.
295  Var.reshape((5, 5))[1, 1] = 1.
296 
297  # ( 1 0 0 0 0 )
298  # ( 0 1 0 0 0 )
299  # Var = ( 0 0 0 0 0 )
300  # ( 0 0 0 0 0 )
301  # ( 0 0 0 0 0 )
302 
303  analyser.getVarianceCovariance(qp, Var, Primal_Dual_Var)
304  print('Primal_Dual_Var=\n', Primal_Dual_Var.reshape((5, 5)))
305  actual = Primal_Dual_Var.reshape((5, 5))
306 
307  pattern = re.compile(
308  r'Primal_Dual_VAR = (?P<VAR>.*)',
309  re.DOTALL
310  )
311 
312  print(stdout)
313  match = pattern.search(stdout)
314  expected = match.group('VAR').strip().split("\n")
315  expected = [x.strip().split() for x in expected]
316  print(expected)
317  expected = np.asarray(expected, dtype=float)
318 
319  assert_almost_equal(actual, expected, decimal=7)
320 
321  def test_example7(self):
322  H = np.array([
323  0.8514828085899353, -0.15739890933036804, -0.081726007163524628, -0.530426025390625, 0.16773293912410736,
324  -0.15739890933036804, 1.1552412509918213, 0.57780224084854126, -0.0072606131434440613, 0.010559185408055782,
325  -0.081726007163524628, 0.57780224084854126, 0.28925251960754395, 5.324830453901086e-006, -3.0256599075073609e-006,
326  -0.530426025390625, -0.0072606131434440613, 5.324830453901086e-006, 0.35609596967697144, -0.15124998986721039,
327  0.16773293912410736, 0.010559185408055782, -3.0256599075073609e-006, -0.15124998986721039, 0.15129712224006653
328  ], dtype=float
329  ).reshape((5, 5))
330  g = np.array([0.30908384919166565, 0.99325823783874512, 0.49822014570236206, -0.26309865713119507, 0.024296050891280174], dtype=float).reshape((5,))
331  A = np.array([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1], dtype=float).reshape((5, 5))
332  lb = np.array([-0.052359879016876221, -0.052359879016876221, -0.052359879016876221, -0.052359879016876221, -0.052359938621520996], dtype=float).reshape((5,))
333  ub = np.array([ 0.052359879016876221, 0.052359879016876221, 0.052359879016876221, 0, 0], dtype=float).reshape((5,))
334  lbA = np.array([-0.052359879016876221, -0.052359879016876221, -0.052359879016876221, -0.052359879016876221, -0.052359938621520996], dtype=float).reshape((5,))
335  ubA = np.array([0.052359879016876221, 0.052359879016876221, 0.052359879016876221, 0, 0], dtype=float).reshape((5,))
336 
337  # Setting up QProblem object.
338  qp = QProblem(5, 5)
339  options = Options()
340  options.printLevel = PrintLevel.NONE
341  qp.setOptions(options)
342 
343  # Solve first QP.
344  nWSR = 100
345  qp.init(H, g, A, lb, ub, lbA, ubA, nWSR)
346 
347  result = np.zeros((5,))
348  qp.getPrimalSolution(result)
349 
350  # TODO check against what?
351  # Where can I find solution?
352 
353 if __name__=="__main__":
354  try:
355  import nose
356  nose.runmodule()
357 
358  except ImportError:
359  sys.stderr.write("Please install nosestests for python unittesting.\n")
360 
Implements the online active set strategy for box-constrained QPs.
Implements the online active set strategy for QPs with varying matrices.
Provides a generic way to set and pass user-specified options.
Definition: options.hpp:65
BEGIN_NAMESPACE_QPOASES returnValue print(const real_t *const v, int n)
Implements the online active set strategy for QPs with general constraints.


acado
Author(s): Milan Vukov, Rien Quirynen
autogenerated on Mon Jun 10 2019 12:35:12