]> gitweb.michael.orlitzky.com - dunshire.git/blob - src/dunshire/errors.py
Add a few docs/examples to errors.py.
[dunshire.git] / src / dunshire / errors.py
1 """
2 Errors that can occur when solving a linear game.
3 """
4
5 from cvxopt import matrix
6
7
8 def _pretty_format_dict(dictionary):
9 """
10 Return a pretty-formatted string representation of a dictionary
11 containing CVXOPT matrices.
12
13 EXAMPLES:
14
15 >>> d = {'foo': 1.234, 'bar': matrix([1,2,3])}
16 >>> print(_pretty_format_dict(d))
17 bar:
18 [ 1]
19 [ 2]
20 [ 3]
21 foo: 1.234
22
23 """
24 result = ''
25 for (key, value) in dictionary.items():
26 if isinstance(value, matrix):
27 # Display matrices on their own lines, indented.
28 result += '{:s}:'.format(key)
29 colvec = '\n{!s}'.format(value)
30 result += '\n '.join(colvec.splitlines())
31 result += '\n'
32 else:
33 result += '{:s}: {!s}\n'.format(key, value)
34
35 return result.rstrip('\n') # Kills trailing newlines on matrices.
36
37
38 class GameUnsolvableException(Exception):
39 """
40 Every linear game has a solution (this follows from a general
41 min-max theorem). If we can't solve the conic program associated
42 with a linear game, then something is wrong with either the model of
43 the input.
44 """
45 def __init__(self, solution_dict):
46 """
47 Create a new GameUnsolvableException object.
48
49 INPUT:
50
51 - ``solution_dict`` -- the solution dictionary returned from the
52 cone program.
53
54 """
55 super().__init__()
56 self._solution_dict = solution_dict
57
58
59 def __str__(self):
60 """
61 Return a string representation of this exception.
62
63 The returned representation highlights the "status" field of the
64 CVXOPT dictionary, since that should explain what went
65 wrong. The full CVXOPT solution dictionary is included after the
66 status.
67 """
68 tpl = 'Solution failed with result "{:s}."\n' \
69 'CVXOPT returned:\n {!s}'
70 cvx_lines = _pretty_format_dict(self._solution_dict).splitlines()
71 cvx_str = '\n '.join(cvx_lines) # Indent the whole dict by two spaces.
72 return tpl.format(self._solution_dict['status'], cvx_str)