[simplex] Add __str__ method for simplex dictionary.
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Mikaël Capelle 2019-12-03 15:00:58 +00:00
parent 9cdaeccb38
commit 16453c424d

View File

@ -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)