From 16453c424dc1fe09fc807a7301ff0c59e3499907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=C3=ABl=20Capelle?= Date: Tue, 3 Dec 2019 15:00:58 +0000 Subject: [PATCH] [simplex] Add __str__ method for simplex dictionary. --- simplex/simplex_dictionary.py | 53 ++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/simplex/simplex_dictionary.py b/simplex/simplex_dictionary.py index 4204f59..9e870dc 100644 --- a/simplex/simplex_dictionary.py +++ b/simplex/simplex_dictionary.py @@ -31,7 +31,7 @@ class simplex_dictionary(typing.Generic[V]): - N The list of non-basic variables (immutable). - b The current value of the basic variables. - a The current coefficients of the non-basic variables in the expression - of the basic variables. + of the basic variables. - c The current coefficients of the non-basic variables in the objective. - z The current value of the objective. @@ -91,18 +91,22 @@ class simplex_dictionary(typing.Generic[V]): @property def variables(self) -> typing.List[V]: + """ Returns: The list of variables in this dictionary. """ return sorted(self.B + self.N) @property def B(self) -> typing.List[V]: + """ Returns: The list of basic variables for this dictionary. """ return self.__B @property def N(self) -> typing.List[V]: + """ Returns: The list of non-basic variables for this dictionary. """ return self.__N @property def a(self) -> magic_dictionary[V, magic_dictionary[V, Fraction]]: + """ Returns: The a matrix of this dictionary. """ return self._a @a.setter @@ -232,3 +236,50 @@ class simplex_dictionary(typing.Generic[V]): d = r"{} = \left.{}\right.".format(name, d) display(Math(d)) + + def __str__(self) -> str: + # Length for the variables: + vnames = [str(x) for x in self.variables] + vlength = max(len(n) for n in vnames) + + # Length for the b column: + z = str(self.z) + b = [str(self.b[x]) for x in self.B] + blength = max(len(z), max(len(n) for n in b)) + + # Length for the other columns: + a = [[str(self.a[xb][xn]) for xn in self.N] for xb in self.B] + c = [str(self.c[xn]) for xn in self.N] + alength = max( + vlength, max(len(n) for r in a for n in r), max(len(n) for n in c) + ) + + # Create the string: + row_format_s = " {:>{vwidth}} | {:>{bwidth}} | " + row_format_s += " | ".join("{:>{awidth}}" for _ in self.N) + row_format_s += " |" + + def format(*args): + return row_format_s.format( + *map(str, args), vwidth=vlength, bwidth=blength, awidth=alength + ) + + s = [] + + # First row: + s.append(format("", "b", *self.N)) + + # Length of a row: + lr = len(s[0]) + + # Separator: + s.append("-" * lr) + + for xb in self.B: + s.append(format(xb, self.b[xb], *[self.a[xb][xn] for xn in self.N])) + + s.append("-" * lr) + s.append(format("z", self.z, *[self.c[xn] for xn in self.N])) + s.append("-" * lr) + + return "\n".join(s)