Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
replace generator_cmp by generator_key and generator_reverse
Browse files Browse the repository at this point in the history
  • Loading branch information
a-andre committed Oct 26, 2014
1 parent 36c150e commit f7edf1e
Show file tree
Hide file tree
Showing 9 changed files with 80 additions and 44 deletions.
4 changes: 2 additions & 2 deletions src/sage/algebras/hall_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from sage.combinat.hall_polynomial import hall_polynomial
from sage.combinat.sf.sf import SymmetricFunctions
from sage.rings.all import ZZ
from functools import reduce
from functools import cmp_to_key, reduce

def transpose_cmp(x, y):
r"""
Expand Down Expand Up @@ -243,7 +243,7 @@ def __init__(self, base_ring, q, prefix='H'):
category = AlgebrasWithBasis(base_ring)
CombinatorialFreeModule.__init__(self, base_ring, Partitions(),
prefix=prefix, bracket=False,
monomial_cmp=transpose_cmp,
generator_key=cmp_to_key(transpose_cmp),
category=category)

# Coercions
Expand Down
3 changes: 2 additions & 1 deletion src/sage/algebras/iwahori_hecke_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# http://www.gnu.org/licenses/
#*****************************************************************************

from functools import cmp_to_key
from sage.misc.abstract_method import abstract_method
from sage.misc.cachefunc import cached_method
from sage.misc.bindable_class import BindableClass
Expand Down Expand Up @@ -1119,7 +1120,7 @@ def __init__(self, algebra, prefix=None):
algebra.base_ring(),
algebra._W,
category=algebra._BasesCategory(),
monomial_cmp=index_cmp,
generator_key=cmp_to_key(index_cmp),
prefix=self._prefix)

# This **must** match the name of the class in order for
Expand Down
31 changes: 25 additions & 6 deletions src/sage/categories/examples/with_realizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,15 +240,34 @@ def indices_cmp(self, x, y):
EXAMPLES::
sage: from functools import cmp_to_key
sage: A = Sets().WithRealizations().example(); A
The subset algebra of {1, 2, 3} over Rational Field
sage: sorted(A.indices(), A.indices_cmp)
sage: sorted(A.indices(), key=cmp_to_key(A.indices_cmp))
[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
"""
s = cmp(len(x), len(y))
s = (len(x) > len(y)) - (len(x) < len(y))
if s != 0:
return s
return cmp(list(x), list(y))
return (list(x) > list(y)) - (list(x) < list(y))

def indices_key(self, x):
r"""
A comparison function on sets which gives a linear extension
of the inclusion order.
INPUT:
- ``x`` -- set
EXAMPLES::
sage: A = Sets().WithRealizations().example(); A
The subset algebra of {1, 2, 3} over Rational Field
sage: sorted(A.indices(), key=A.indices_key)
[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
"""
return (len(x), list(x))

def supsets(self, set):
r"""
Expand Down Expand Up @@ -401,7 +420,7 @@ def __init__(self, A):
"""
CombinatorialFreeModule.__init__(self,
A.base_ring(), A.indices(),
category=A.Bases(), prefix='F', monomial_cmp=A.indices_cmp)
category=A.Bases(), prefix='F', generator_key=A.indices_key)

def product_on_basis(self, left, right):
r"""
Expand Down Expand Up @@ -489,7 +508,7 @@ def __init__(self, A):
"""
CombinatorialFreeModule.__init__(self,
A.base_ring(), A.indices(),
category=A.Bases(), prefix='In', monomial_cmp=A.indices_cmp)
category=A.Bases(), prefix='In', generator_key=A.indices_key)

class Out(CombinatorialFreeModule, BindableClass):
r"""
Expand Down Expand Up @@ -532,4 +551,4 @@ def __init__(self, A):
"""
CombinatorialFreeModule.__init__(self,
A.base_ring(), A.indices(),
category=A.Bases(), prefix='Out', monomial_cmp=A.indices_cmp)
category=A.Bases(), prefix='Out', generator_key=A.indices_key)
2 changes: 1 addition & 1 deletion src/sage/categories/regular_crystals.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ def demazure_operator_simple(self, i, ring = None):
sage: K = crystals.KirillovReshetikhin(['A',2,1],2,1)
sage: t = K(rows=[[3],[2]])
sage: t.demazure_operator_simple(0)
B[[[2, 3]]] + B[[[1, 2]]]
B[[[1, 2]]] + B[[[2, 3]]]
TESTS::
Expand Down
28 changes: 17 additions & 11 deletions src/sage/combinat/free_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,18 +181,19 @@ def _sorted_items_for_printing(self):
sage: f = B['a'] + 2*B['c'] + 3 * B['b']
sage: f._sorted_items_for_printing()
[('a', 1), ('b', 3), ('c', 2)]
sage: F.print_options(generator_cmp = lambda x,y: -cmp(x,y))
sage: F.print_options(generator_reverse=True)
sage: f._sorted_items_for_printing()
[('c', 2), ('b', 3), ('a', 1)]
sage: F.print_options(generator_cmp=cmp) #reset to original state
sage: F.print_options(generator_reverse=False) #reset to original state
.. seealso:: :meth:`_repr_`, :meth:`_latex_`, :meth:`print_options`
"""
print_options = self.parent().print_options()
v = self._monomial_coefficients.items()
try:
v.sort(cmp = print_options['generator_cmp'],
key = lambda monomial_coeff: monomial_coeff[0])
v.sort(key=lambda monomial_coeff:
print_options['generator_key'](monomial_coeff[0]),
reverse=print_options['generator_reverse'])
except Exception: # Sorting the output is a plus, but if we can't, no big deal
pass
return v
Expand All @@ -218,13 +219,13 @@ def _repr_(self):
function on elements of the support::
sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'],
... generator_cmp = lambda x,y: cmp(y,x))
... generator_reverse=True)
sage: e = F.basis()
sage: e['a'] + 3*e['b'] + 2*e['c']
2*B['c'] + 3*B['b'] + B['a']
sage: F = CombinatorialFreeModule(QQ, ['ac', 'ba', 'cb'],
... generator_cmp = lambda x,y: cmp(x[1],y[1]))
... generator_key=lambda x: x[1])
sage: e = F.basis()
sage: e['ac'] + 3*e['ba'] + 2*e['cb']
3*B['ba'] + 2*B['cb'] + B['ac']
Expand Down Expand Up @@ -325,13 +326,13 @@ def _latex_(self):
function on elements of the support::
sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'],
... generator_cmp = lambda x,y: cmp(y,x))
... generator_reverse=True)
sage: e = F.basis()
sage: latex(e['a'] + 3*e['b'] + 2*e['c'])
2B_{c} + 3B_{b} + B_{a}
sage: F = CombinatorialFreeModule(QQ, ['ac', 'ba', 'cb'],
... generator_cmp = lambda x,y: cmp(x[1],y[1]))
... generator_key=lambda x: x[1])
sage: e = F.basis()
sage: latex(e['ac'] + 3*e['ba'] + 2*e['cb'])
3B_{ba} + 2B_{cb} + B_{ac}
Expand Down Expand Up @@ -1105,7 +1106,9 @@ class CombinatorialFreeModule(UniqueRepresentation, Module, IndexedGenerators):
sage: F = CombinatorialFreeModule(QQ, ['a','b'], prefix='x')
sage: original_print_options = F.print_options()
sage: sorted(original_print_options.items())
[('bracket', None), ('generator_cmp', <built-in function cmp>),
[('bracket', None),
('generator_key', <function <lambda> at ...>),
('generator_reverse', False),
('latex_bracket', False), ('latex_prefix', None),
('latex_scalar_mult', None), ('prefix', 'x'),
('scalar_mult', '*'), ('tensor_symbol', None)]
Expand All @@ -1124,7 +1127,7 @@ class CombinatorialFreeModule(UniqueRepresentation, Module, IndexedGenerators):
sage: latex(e['a'] - 3 * e['b'])
y_{a} - 3 y_{b}
sage: F.print_options(generator_cmp = lambda x,y: -cmp(x,y))
sage: F.print_options(generator_reverse=True)
sage: e['a'] - 3 * e['b']
-3 x{'b'} + x{'a'}
sage: F.print_options(**original_print_options) # reset print options
Expand Down Expand Up @@ -1282,7 +1285,10 @@ def __init__(self, R, basis_keys, element_class = None, category = None, prefix=
kwds.pop('key', None)
# This needs to be first as per #10127
if 'monomial_cmp' in kwds:
kwds['generator_cmp'] = kwds['monomial_cmp']
from sage.misc.superseded import deprecation
deprecation(17229, "Option monomial_cmp is deprecated use generator_key and generator_reverse instead.")
from functools import cmp_to_key
kwds['generator_key'] = cmp_to_key(kwds['monomial_cmp'])
del kwds['monomial_cmp']
IndexedGenerators.__init__(self, basis_keys, prefix, **kwds)

Expand Down
13 changes: 3 additions & 10 deletions src/sage/combinat/ncsym/dual.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,18 +123,11 @@ def __init__(self, NCSymD):
sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()
sage: TestSuite(w).run()
"""
def lt_set_part(A, B):
A = sorted(map(sorted, A))
B = sorted(map(sorted, B))
for i in range(len(A)):
if A[i] > B[i]:
return 1
elif A[i] < B[i]:
return -1
return 0
def key_func_set_part(A):
return sorted(map(sorted, A))
CombinatorialFreeModule.__init__(self, NCSymD.base_ring(), SetPartitions(),
prefix='w', bracket=False,
monomial_cmp=lt_set_part,
generator_key=key_func_set_part,
category=NCSymDualBases(NCSymD))

@lazy_attribute
Expand Down
6 changes: 3 additions & 3 deletions src/sage/combinat/sf/sfa.py
Original file line number Diff line number Diff line change
Expand Up @@ -2025,11 +2025,11 @@ def set_print_style(self, ps):
sage: s.set_print_style('lex')
"""
if ps == 'lex':
self.print_options(generator_cmp = lambda x,y: cmp(x,y))
self.print_options(generator_key = lambda x: x)
elif ps == 'length':
self.print_options(generator_cmp = lambda x,y: cmp(len(x), len(y)))
self.print_options(generator_key = lambda x: len(x))
elif ps == 'maximal_part':
self.print_options(generator_cmp = lambda x,y: cmp(_lmax(x), _lmax(y)))
self.print_options(generator_key = lambda x: _lmax(x))
else:
raise ValueError("the print style must be one of lex, length, or maximal_part ")
self._print_style = ps
Expand Down
10 changes: 5 additions & 5 deletions src/sage/monoids/indexed_free_monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,10 +439,10 @@ def _sorted_items(self):
sage: x = a*b^2*e*d
sage: x._sorted_items()
((0, 1), (1, 2), (4, 1), (3, 1))
sage: F.print_options(generator_cmp = lambda x,y: -cmp(x,y))
sage: F.print_options(generator_reverse=True)
sage: x._sorted_items()
((0, 1), (1, 2), (4, 1), (3, 1))
sage: F.print_options(generator_cmp=cmp) # reset to original state
sage: F.print_options(generator_reverse=False) # reset to original state
.. SEEALSO::
Expand Down Expand Up @@ -525,10 +525,10 @@ def _sorted_items(self):
sage: x = a*b^2*e*d
sage: x._sorted_items()
[(0, 1), (1, 2), (3, 1), (4, 1)]
sage: F.print_options(generator_cmp = lambda x,y: -cmp(x,y))
sage: F.print_options(generator_reverse=True)
sage: x._sorted_items()
[(4, 1), (3, 1), (1, 2), (0, 1)]
sage: F.print_options(generator_cmp=cmp) # reset to original state
sage: F.print_options(generator_reverse=False) # reset to original state
.. SEEALSO::
Expand All @@ -537,7 +537,7 @@ def _sorted_items(self):
print_options = self.parent().print_options()
v = self._monomial.items()
try:
v.sort(cmp = print_options['generator_cmp'])
v.sort(key=print_options['generator_key'], reverse=print_options['generator_reverse'])
except StandardError: # Sorting the output is a plus, but if we can't, no big deal
pass
return v
Expand Down
27 changes: 22 additions & 5 deletions src/sage/structure/indexed_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,14 @@ class IndexedGenerators(object):
string to use for tensor product in the print representation. If
``None``, use ``sage.categories.tensor.symbol``.
- ``generator_cmp`` -- a comparison function (default: ``cmp``),
- ``generator_cmp`` -- deprecated
- ``generator_key`` -- a key function (default: ``lambda x: x``),
to use for sorting elements in the output of elements
- ``generator_reverse`` -- bool (default: ``False``),
if ``True`` sort elements in reverse order in the output of elements
.. NOTE::
These print options may also be accessed and modified using the
Expand Down Expand Up @@ -130,7 +135,8 @@ def __init__(self, indices, prefix="x", **kwds):
'scalar_mult': "*",
'latex_scalar_mult': None,
'tensor_symbol': None,
'generator_cmp': cmp}
'generator_key': lambda x: x,
'generator_reverse': False}
# 'bracket': its default value here is None, meaning that
# the value of self._repr_option_bracket is used; the default
# value of that attribute is True -- see immediately before
Expand Down Expand Up @@ -185,7 +191,8 @@ def print_options(self, **kwds):
- ``scalar_mult``
- ``latex_scalar_mult``
- ``tensor_symbol``
- ``generator_cmp``
- ``generator_key``
- ``generator_reverse``
See the documentation for :class:`CombinatorialFreeModule` for
descriptions of the effects of setting each of these options.
Expand All @@ -206,21 +213,31 @@ def print_options(self, **kwds):
TESTS::
sage: sorted(F.print_options().items())
[('bracket', '('), ('generator_cmp', <built-in function cmp>),
[('bracket', '('),
('generator_key', <function <lambda> at ...>), ('generator_reverse', False),
('latex_bracket', False), ('latex_prefix', None),
('latex_scalar_mult', None), ('prefix', 'x'),
('scalar_mult', '*'), ('tensor_symbol', None)]
sage: F.print_options(bracket='[') # reset
sage: F.print_options(generator_cmp=lambda x,y: (x < y) - (x > y))
doctest:...: DeprecationWarning: Option generator_cmp is deprecated use generator_key and generator_reverse instead.
See http://trac.sagemath.org/17229 for details.
"""
# don't just use kwds.get(...) because I want to distinguish
# between an argument like "option=None" and the option not
# being there altogether.
if kwds:
if 'generator_cmp' in kwds:
from sage.misc.superseded import deprecation
deprecation(17229, "Option generator_cmp is deprecated use generator_key and generator_reverse instead.")
from functools import cmp_to_key
kwds['generator_key'] = cmp_to_key(kwds['generator_cmp'])
del kwds['generator_cmp']
for option in kwds:
# TODO: make this into a set and put it in a global variable?
if option in ['prefix', 'latex_prefix', 'bracket', 'latex_bracket',
'scalar_mult', 'latex_scalar_mult', 'tensor_symbol',
'generator_cmp'
'generator_key', 'generator_reverse'
]:
self._print_options[option] = kwds[option]
else:
Expand Down

0 comments on commit f7edf1e

Please sign in to comment.