Skip to content

Commit 94a3410

Browse files
BrunoStintdimpase
authored andcommitted
added graphical tables + pep8 formatting
1 parent 2114066 commit 94a3410

File tree

1 file changed

+73
-31
lines changed

1 file changed

+73
-31
lines changed

src/sage/matrix/operation_table.py

Lines changed: 73 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,7 @@ class OperationTable(SageObject):
383383
384384
- Rob Beezer (2010-03-15)
385385
"""
386+
386387
def __init__(self, S, operation, names='letters', elements=None):
387388
r"""
388389
TESTS::
@@ -432,7 +433,7 @@ def __init__(self, S, operation, names='letters', elements=None):
432433
supported = {
433434
add: (add, '+', '+'),
434435
mul: (mul, '*', '\\ast')
435-
}
436+
}
436437
# default symbols for upper-left-hand-corner of table
437438
self._ascii_symbol = '.'
438439
self._latex_symbol = '\\cdot'
@@ -451,7 +452,7 @@ def __init__(self, S, operation, names='letters', elements=None):
451452
# the elements might not be hashable. But if they are it is much
452453
# faster to lookup in a hash table rather than in a list!
453454
try:
454-
get_row = {e: i for i,e in enumerate(self._elts)}.__getitem__
455+
get_row = {e: i for i, e in enumerate(self._elts)}.__getitem__
455456
except TypeError:
456457
get_row = self._elts.index
457458

@@ -461,7 +462,8 @@ def __init__(self, S, operation, names='letters', elements=None):
461462
try:
462463
result = self._operation(g, h)
463464
except Exception:
464-
raise TypeError('elements %s and %s of %s are incompatible with operation: %s' % (g,h,S,self._operation))
465+
raise TypeError('elements %s and %s of %s are incompatible with operation: %s' % (
466+
g, h, S, self._operation))
465467

466468
try:
467469
r = get_row(result)
@@ -477,7 +479,8 @@ def __init__(self, S, operation, names='letters', elements=None):
477479
except (KeyError, ValueError):
478480
failed = True
479481
if failed:
480-
raise ValueError('%s%s%s=%s, and so the set is not closed' % (g, self._ascii_symbol, h, result))
482+
raise ValueError('%s%s%s=%s, and so the set is not closed' % (
483+
g, self._ascii_symbol, h, result))
481484

482485
row.append(r)
483486
self._table.append(row)
@@ -558,7 +561,8 @@ def _name_maker(self, names):
558561
else:
559562
width = int(log(self._n - 1, base)) + 1
560563
for i in range(self._n):
561-
places = Integer(i).digits(base=base, digits=letters, padto=width)
564+
places = Integer(i).digits(
565+
base=base, digits=letters, padto=width)
562566
places.reverse()
563567
name_list.append(''.join(places))
564568
elif names == 'elements':
@@ -570,19 +574,22 @@ def _name_maker(self, names):
570574
name_list.append(estr)
571575
elif isinstance(names, list):
572576
if len(names) != self._n:
573-
raise ValueError('list of element names must be the same size as the set, %s != %s'%(len(names), self._n))
577+
raise ValueError('list of element names must be the same size as the set, %s != %s' % (
578+
len(names), self._n))
574579
width = 0
575580
for name in names:
576581
if not isinstance(name, str):
577-
raise ValueError('list of element names must only contain strings, not %s' % name)
582+
raise ValueError(
583+
'list of element names must only contain strings, not %s' % name)
578584
if len(name) > width:
579585
width = len(name)
580586
name_list.append(name)
581587
else:
582-
raise ValueError("element names must be a list, or one of the keywords: 'letters', 'digits', 'elements'")
588+
raise ValueError(
589+
"element names must be a list, or one of the keywords: 'letters', 'digits', 'elements'")
583590
name_dict = {}
584591
for i in range(self._n):
585-
name_dict[name_list[i]]=self._elts[i]
592+
name_dict[name_list[i]] = self._elts[i]
586593
return width, name_list, name_dict
587594

588595
def __getitem__(self, pair):
@@ -632,13 +639,15 @@ def __getitem__(self, pair):
632639
IndexError: invalid indices of operation table: ((1,512), (1,3,2,4)(5,7))
633640
"""
634641
if not (isinstance(pair, tuple) and len(pair) == 2):
635-
raise TypeError('indexing into an operation table requires exactly two elements')
642+
raise TypeError(
643+
'indexing into an operation table requires exactly two elements')
636644
g, h = pair
637645
try:
638646
row = self._elts.index(g)
639647
col = self._elts.index(h)
640648
except ValueError:
641-
raise IndexError('invalid indices of operation table: (%s, %s)' % (g, h))
649+
raise IndexError(
650+
'invalid indices of operation table: (%s, %s)' % (g, h))
642651
return self._elts[self._table[row][col]]
643652

644653
def __eq__(self, other):
@@ -747,8 +756,9 @@ def set_print_symbols(self, ascii, latex):
747756
...
748757
ValueError: ASCII symbol should be a single character, not 5
749758
"""
750-
if not isinstance(ascii, str) or not len(ascii)==1:
751-
raise ValueError('ASCII symbol should be a single character, not %s' % ascii)
759+
if not isinstance(ascii, str) or not len(ascii) == 1:
760+
raise ValueError(
761+
'ASCII symbol should be a single character, not %s' % ascii)
752762
if not isinstance(latex, str):
753763
raise ValueError('LaTeX symbol must be a string, not %s' % latex)
754764
self._ascii_symbol = ascii
@@ -935,22 +945,53 @@ def matrix_of_variables(self):
935945
from sage.rings.rational_field import QQ
936946
R = PolynomialRing(QQ, 'x', self._n)
937947
MS = MatrixSpace(R, self._n, self._n)
938-
entries = [R('x'+str(self._table[i][j])) for i in range(self._n) for j in range(self._n)]
939-
return MS( entries )
940-
941-
#def color_table():
942-
#r"""
943-
#Returns a graphic image as a square grid where entries are color coded.
944-
#"""
945-
#pass
946-
#return None
947-
948-
#def gray_table():
949-
#r"""
950-
#Returns a graphic image as a square grid where entries are coded as grayscale values.
951-
#"""
952-
#pass
953-
#return None
948+
entries = [R('x'+str(self._table[i][j]))
949+
for i in range(self._n) for j in range(self._n)]
950+
return MS(entries)
951+
952+
def color_table(self, element_names=True, cmap=gist_rainbow, **options):
953+
r"""
954+
Returns a graphic image as a square grid where entries are color coded.
955+
956+
INPUT:
957+
958+
- ``element_names`` - (default : ``True``) Whether to display text with element names on the image
959+
960+
- ``cmap`` - (default : ``gist_rainbow``) colour map for plot, see matplotlib.cm
961+
962+
- ``**options`` - passed on to matrix_plot call
963+
964+
"""
965+
966+
# Base matrix plot object, without text
967+
plot = matrix_plot(Matrix(self._table), cmap=cmap,
968+
frame=False, **options)
969+
970+
if element_names:
971+
972+
# adapted from ._ascii_table()
973+
# prepare widenames[] list for labelling on image
974+
n = self._n
975+
width = self._width
976+
977+
widenames = []
978+
for name in self._names:
979+
widenames.append("{0: >{1}s}".format(name, width))
980+
981+
# iterate through each element
982+
for g in range(n):
983+
for h in range(n):
984+
985+
# add text to the plot
986+
tPos = (g, h)
987+
tText = widenames[self._table[g][h]]
988+
t = text(tText, tPos, rgbcolor=(0, 0, 0))
989+
plot = plot + t
990+
991+
return plot
992+
993+
def gray_table(self, **options):
994+
return self.color_table(cmap=Greys, **options)
954995

955996
def _ascii_table(self):
956997
r"""
@@ -1031,7 +1072,7 @@ def _ascii_table(self):
10311072
widenames.append('{0: >{1}s}'.format(name, width))
10321073

10331074
# Headers
1034-
table = ['{0: >{1}s} '.format(self._ascii_symbol,width)]
1075+
table = ['{0: >{1}s} '.format(self._ascii_symbol, width)]
10351076
table += [' '+widenames[i] for i in range(n)]+['\n']
10361077
table += [' ']*width + ['+'] + ['-']*(n*(width+1))+['\n']
10371078

@@ -1068,7 +1109,8 @@ def _latex_(self):
10681109

10691110
# Row label and body of table
10701111
for g in range(n):
1071-
table.append('{}') # Interrupts newline and [], so not line spacing
1112+
# Interrupts newline and [], so not line spacing
1113+
table.append('{}')
10721114
table.append(names[g])
10731115
for h in range(n):
10741116
table.append('&'+names[self._table[g][h]])

0 commit comments

Comments
 (0)