Ticket #9370: trac_9370-module-elt-repr-suggestions-cs.patch

File trac_9370-module-elt-repr-suggestions-cs.patch, 16.9 KB (added by stumpc5, 10 years ago)
  • sage/combinat/combinatorial_algebra.py

    # HG changeset patch
    # Parent 1a36ffb5657439c56d7330e8676151105c5d56e1
    
    diff --git a/sage/combinat/combinatorial_algebra.py b/sage/combinat/combinatorial_algebra.py
    a b symmetric functions. 
    1919    ...         self._one = Partition([])
    2020    ...         self._name = 'Power-sum symmetric functions'
    2121    ...         CombinatorialAlgebra.__init__(self, R, Partitions())
    22     ...
    23     ...     _prefix = 'p'
     22    ...         self.print_options(prefix='p')
    2423    ...
    2524    ...     def _multiply_basis(self, a, b):
    2625    ...         l = list(a)+list(b)
    symmetric functions. 
    4241The important things to define are ._basis_keys which
    4342specifies the combinatorial class that indexes the basis elements,
    4443._one which specifies the identity element in the algebra, ._name
    45 which specifies the name of the algebra, ._prefix which is the
    46 string put in front of each basis element, and finally a _multiply
     44which specifies the name of the algebra, ps.print_options is used to set
     45the print options for the elements, and finally a _multiply
    4746or _multiply basis method that defines the multiplication in the
    4847algebra.
    4948"""
  • sage/combinat/free_module.py

    diff --git a/sage/combinat/free_module.py b/sage/combinat/free_module.py
    a b class CombinatorialFreeModuleElement(Ele 
    143143        """
    144144        v = self._monomial_coefficients.items()
    145145        try:
    146             v = sorted(v)
     146            v.sort()
    147147        except StandardError: # Sorting the output is a plus, but if we can't, no big deal
    148148            pass
    149149        repr_term = self.parent()._repr_term
    150         mons = [ repr_term(m) for (m, _) in v ]
    151         cffs = [ x for (_, x) in v ]
    152         x = repr_lincomb(mons, cffs).replace("*1 "," ")
    153         if x[len(x)-2:] == "*1":
     150        v = [ (repr_term(m),x) for (m, x) in v ]
     151        if v:
     152            mons, cffs = zip(*v)
     153        else:
     154            mons = cffs = []
     155        ast = self.parent()._print_options.get('scalar_mult', "*")
     156        x = repr_lincomb(mons, cffs,scalar_mult=ast).replace("%s1 "%ast," ")
     157        if x[len(x)-2:] == "%s1"%ast:
    154158            x = x[:len(x)-2]
    155         ast = self.parent()._print_options.get('scalar_mult', "*")
    156         x = x.replace("*", ast)
    157159        return x
    158160
    159161    def _latex_(self):
    class CombinatorialFreeModuleElement(Ele 
    172174            sage: a = 2 + QS3([2,1,3])
    173175            sage: latex(a) #indirect doctest
    174176            2[1, 2, 3] + [2, 1, 3]
     177
     178       ::
     179
     180            sage: F = CombinatorialFreeModule(QQ, ['a','b'], prefix='beta', latex_prefix='\\beta')
     181            sage: x = F.an_element()
     182            sage: x
     183            2*beta['a'] + 2*beta['b']
     184            sage: latex(x)
     185            2\beta_{a} + 2\beta_{b}
    175186        """
    176187        v = self._monomial_coefficients.items()
    177         v.sort()
    178         prefix = self.parent().prefix()
     188        try:
     189            v.sort()
     190        except StandardError: # Sorting the output is a plus, but if we can't, no big deal
     191            pass
     192        latex_prefix = self.parent()._print_options.get('latex_prefix')
    179193        latex_term = self.parent()._latex_term
    180         mons = [ latex_term(m) for (m, _) in v ]
    181         cffs = [ x for (_, x) in v ]
    182         x = repr_lincomb(mons, cffs, is_latex=True).replace("*1 "," ")
    183         if x[len(x)-2:] == "*1":
    184             return x[:len(x)-2]
     194        v = [ (latex_term(m), x) for (m, x) in v ]
     195        if v:
     196            mons, cffs = zip(*v)
     197        else:
     198            mons = cffs = []
     199        ast = self.parent()._print_options.get('latex_scalar_mult')
     200        if ast is None:
     201            ast = self.parent()._print_options.get('scalar_mult')
     202            if ast == '*':
     203                ast = ''
     204        ast_replace = ast if ast else ''
     205        l = len(ast_replace)
     206        x = repr_lincomb(mons, cffs, is_latex=True, latex_scalar_mult=ast)
     207        if x[len(x)-l-1:] == ast_replace+"1":
     208            return x[:len(x)-l-1]
    185209        else:
    186210            return x
    187211
    class CombinatorialFreeModule(UniqueRepr 
    872896        sage: e['a'] - 3 * e['b']
    873897        x{'a'} - 3 x{'b'}
    874898        sage: latex(e['a'] - 3 * e['b'])
    875         x_{a} + \left(-3\right)x_{b}
     899        x_{a} + \left(-3\right) x_{b}
    876900
    877901        sage: F.print_options(latex_prefix='y')
    878902        sage: latex(e['a'] - 3 * e['b'])
    879         y_{a} + \left(-3\right)y_{b}
     903        y_{a} + \left(-3\right) y_{b}
    880904       
    881905        sage: F = CombinatorialFreeModule(QQ, [(1,2), (3,4)])
    882906        sage: e = F.basis()
    class CombinatorialFreeModule(UniqueRepr 
    9951019
    9961020        self._order = None
    9971021
    998         if not hasattr(self, "_prefix"):
    999             self._prefix = prefix
    1000 
    1001         # printing options for elements.  These include self._prefix
     1022        # printing options for elements.
    10021023        # (set when initializing self) and self._repr_option_bracket
    10031024        # (declared to be True by default, needs to be overridden
    10041025        # explicitly).
    10051026        self._print_options = {}
    1006         self._print_options['prefix'] = self._prefix
     1027        self._print_options['prefix'] = prefix
    10071028        # 'bracket': its default value here is None, meaning that
    10081029        # the value of self._repr_option_bracket is used; the default
    10091030        # value of that attribute is True -- see immediately before
    class CombinatorialFreeModule(UniqueRepr 
    10131034        # using 'bracket' instead of _repr_option_bracket.
    10141035        self._print_options['bracket'] = kwds.get('bracket', None)
    10151036        self._print_options['latex_bracket'] = kwds.get('latex_bracket', False)
    1016         self._print_options['latex_prefix'] = kwds.get('latex_prefix', self._prefix)
     1037        self._print_options['latex_prefix'] = kwds.get('latex_prefix', prefix)
    10171038        self._print_options['scalar_mult'] = kwds.get('scalar_mult', "*")
     1039        self._print_options['latex_scalar_mult'] = kwds.get('latex_scalar_mult', None)
    10181040
    10191041    # mostly for backward compatibility
    10201042    @lazy_attribute
    class CombinatorialFreeModule(UniqueRepr 
    13551377        cc = self.get_order()
    13561378        return self._from_dict(dict( (cc[index], coeff) for (index,coeff) in vector.iteritems()))
    13571379
    1358 
    13591380    def prefix(self):
    13601381        """
    13611382        Returns the prefix used when displaying elements of self.
    class CombinatorialFreeModule(UniqueRepr 
    13721393            sage: X.prefix()
    13731394            'X'
    13741395        """
    1375         return self._prefix
     1396        return self._print_options['prefix']
    13761397
    13771398    def print_options(self, **kwds):
    13781399        """
    class CombinatorialFreeModule(UniqueRepr 
    14001421
    14011422            sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix='x')
    14021423            sage: F.print_options()
    1403             {'latex_bracket': False, 'prefix': 'x', 'bracket': None, 'scalar_mult': '*', 'latex_prefix': 'x'}
     1424            {'latex_prefix': 'x', 'scalar_mult': '*', 'prefix': 'x', 'bracket': None, 'latex_bracket': False, 'latex_scalar_mult': None}
    14041425            sage: F.print_options(bracket='(')
    14051426            sage: F.print_options()
    1406             {'latex_bracket': False, 'prefix': 'x', 'bracket': '(', 'scalar_mult': '*', 'latex_prefix': 'x'}
     1427            {'latex_prefix': 'x', 'scalar_mult': '*', 'prefix': 'x', 'bracket': '(', 'latex_bracket': False, 'latex_scalar_mult': None}
    14071428        """
    14081429        # don't just use kwds.get(...) because I want to distinguish
    14091430        # between an argument like "option=None" and the option not
    14101431        # being there altogether.
    14111432        args = False
    1412         if 'prefix' in kwds:
    1413             args = True
    1414             prefix = kwds['prefix']
    1415             self._prefix = prefix
    1416             self._print_options['prefix'] = prefix
    1417             if 'latex_prefix' not in kwds:
    1418                 self._print_options['latex_prefix'] = prefix
    1419 
    1420         for option in ['latex_prefix', 'bracket', 'latex_bracket',
    1421                        'scalar_mult', 'tensor_symbol']:
    1422             if option in kwds:
     1433
     1434        for option in kwds:
     1435            if option in ['prefix','latex_prefix', 'bracket', 'latex_bracket',
     1436                       'scalar_mult', 'latex_scalar_mult', 'tensor_symbol']:
    14231437                args = True
    14241438                self._print_options[option] = kwds[option]
     1439            else:
     1440                raise ValueError, 'The input option is not a valid print option.'
    14251441
    14261442        if not args:
    14271443            return self._print_options
    class CombinatorialFreeModule(UniqueRepr 
    15371553            sage: latex(e['a'] + 2*e['b'])    # indirect doctest
    15381554            C_{a} + 2C_{b}
    15391555
    1540             sage: QS3 = CombinatorialFreeModule(QQ, Permutations(3), prefix="")
     1556            sage: QS3 = CombinatorialFreeModule(QQ, Permutations(3), prefix="", scalar_mult="*")
    15411557            sage: a = 2*QS3([1,2,3])+4*QS3([3,2,1])
    15421558            sage: latex(a)                     # indirect doctest
    15431559            2[1, 2, 3] + 4[3, 2, 1]
  • sage/combinat/root_system/root_space.py

    diff --git a/sage/combinat/root_system/root_space.py b/sage/combinat/root_system/root_space.py
    a b class RootSpace(ClearCacheOnPickle, Comb 
    3939        sage: r = RootSystem(['A',4]).root_lattice()
    4040        sage: r.simple_root(1)
    4141        alpha[1]
     42        sage: latex(r.simple_root(1))
     43        \alpha_{1}
    4244
    4345    """
    4446
    class RootSpace(ClearCacheOnPickle, Comb 
    5254        """
    5355        self.root_system = root_system
    5456        basis_name = "alphacheck" if root_system.dual_side else "alpha"
     57        basis_name_latex  = "\\alpha^\\vee" if root_system.dual_side else "\\alpha"
    5558        CombinatorialFreeModule.__init__(self, base_ring,
    5659                                         root_system.index_set(),
    5760                                         element_class = RootSpaceElement,
    58                                          prefix=basis_name)
     61                                         prefix=basis_name,
     62                                         latex_prefix=basis_name_latex)
    5963
    6064    def _repr_(self):
    6165        """
  • sage/combinat/schubert_polynomial.py

    diff --git a/sage/combinat/schubert_polynomial.py b/sage/combinat/schubert_polynomial.py
    a b class SchubertPolynomialRing_xbasis(Comb 
    184184            True
    185185        """
    186186        self._name = "Schubert polynomial ring with X basis"
    187         self._prefix = "X"
    188187        self._repr_option_bracket = False
    189188        self._one = permutation.Permutation([1])
    190189        CombinatorialAlgebra.__init__(self, R, cc = permutation.Permutations(), category = GradedAlgebrasWithBasis(R))
     190        self.print_options(prefix='X')
    191191
    192192    def _element_constructor_(self, x):
    193193        """
  • sage/combinat/symmetric_group_algebra.py

    diff --git a/sage/combinat/symmetric_group_algebra.py b/sage/combinat/symmetric_group_algebra.py
    a b class SymmetricGroupAlgebra_n(Combinator 
    101101        """
    102102        self.n = n
    103103        self._name = "Symmetric group algebra of order %s"%self.n
    104         CombinatorialFreeModule.__init__(self, R, permutation.Permutations(n), category = FiniteDimensionalAlgebrasWithBasis(R))
     104        CombinatorialFreeModule.__init__(self, R, permutation.Permutations(n), prefix='', latex_prefix='', category = FiniteDimensionalAlgebrasWithBasis(R))
    105105        # This is questionable, and won't be inherited properly
    106106        if n > 0:
    107107            S = SymmetricGroupAlgebra(R, n-1)
    108108            self.register_coercion(S.canonical_embedding(self))
    109109       
    110110    # _repr_ customization: output the basis element indexed by [1,2,3] as [1,2,3]
    111     _prefix = ""
    112111    _repr_option_bracket = False
    113112
    114113    @cached_method
    class HeckeAlgebraSymmetricGroup_generic 
    735734        self._q = q
    736735       
    737736        CombinatorialAlgebra.__init__(self, R)
     737        # _repr_ customization: output the basis element indexed by [1,2,3] as [1,2,3]
     738        self.print_options(prefix="")
    738739
    739     # _repr_ customization: output the basis element indexed by [1,2,3] as [1,2,3]
    740     _prefix = ""
    741740    _repr_option_bracket = False
    742741
    743742    def q(self):
    class HeckeAlgebraSymmetricGroup_t(Hecke 
    779778            sage: H3 == loads(dumps(H3))
    780779            True
    781780        """
    782         self._prefix = "T"
    783781        HeckeAlgebraSymmetricGroup_generic.__init__(self, R, n, q)
    784782        self._name += " on the T basis"
     783        self.print_options(prefix="T")
    785784       
    786785    def t_action_on_basis(self, perm, i):
    787786        """
  • sage/misc/misc.py

    diff --git a/sage/misc/misc.py b/sage/misc/misc.py
    a b def coeff_repr(c, is_latex=False): 
    668668        else:
    669669            return "(%s)"%s
    670670    return s
    671        
    672 def repr_lincomb(symbols, coeffs, is_latex=False):
     671
     672def repr_lincomb(symbols, coeffs, is_latex=False, scalar_mult='*', latex_scalar_mult=None):
    673673    """
    674674    Compute a string representation of a linear combination of some
    675675    formal symbols.
    676676   
    677677    INPUT:
    678    
    679    
    680     -  ``symbols`` - list of symbols
    681    
    682     -  ``coeffs`` - list of coefficients of the symbols
    683    
    684    
     678
     679    - ``symbols`` -- list of symbols
     680    - ``coeffs`` -- list of coefficients of the symbols
     681    - ``scalar_mult`` -- (default:'*') string representing the multiplication
     682    - `` latex_scalar_mult`` -- (default:None) None or string representing the multiplication in latex
     683                                if None and the scalar_mult is '*': empty string '' is used
     684                                if None and the scaler_mult is not '*': scalar_mult string is used
     685                                otherwise: latex_scalar_mult is used
     686
    685687    OUTPUT:
    686    
    687    
     688
    688689    -  ``str`` - a string
    689    
    690    
    691     EXAMPLES::
    692    
     690
     691    EXAMPLES:
     692
     693    - examples without scalar_mult or latex_scaler_mult::
     694
    693695        sage: repr_lincomb(['a','b','c'], [1,2,3])
    694696        'a + 2*b + 3*c'
    695697        sage: repr_lincomb(['a','b','c'], [1,'2+3*x',3])
    def repr_lincomb(symbols, coeffs, is_lat 
    703705        sage: t = PolynomialRing(RationalField(),'t').gen()
    704706        sage: repr_lincomb(['a', 's', ''], [-t,t-2,t**2+2])
    705707        '-t*a + (t-2)*s + (t^2+2)'
     708
     709    - example for scalar_mult::
     710
     711        sage: repr_lincomb(['a','b','c'], [1,2,3], scalar_mult='**')
     712        'a + 2**b + 3**c'
     713
     714        sage: repr_lincomb(['a','b','c'], [1,2,3], scalar_mult='**')
     715        'a + 2**b + 3**c'
     716
     717    - examples for latex_scalar_mult::
     718
     719        sage: repr_lincomb(['a','b','c'], [1,2,3], is_latex=True)
     720        'a + 2b + 3c'
     721
     722        sage: repr_lincomb(['a','b','c'], [1,2,3], is_latex=True, scalar_mult='**')
     723        'a + 2**b + 3**c'
     724
     725        sage: repr_lincomb(['a','b','c'], [1,2,3], is_latex=True, latex_scalar_mult='*')
     726        'a + 2*b + 3*c'
     727
     728    - examples for scalar_mult and latex_scalar_mult::
     729
     730        sage: repr_lincomb(['a','b','c'], [1,2,3], latex_scalar_mult='*')
     731        'a + 2*b + 3*c'
     732        sage: repr_lincomb(['a','b','c'], [1,2,3], is_latex=True, latex_scalar_mult='*')
     733        'a + 2*b + 3*c'
     734
     735        sage: repr_lincomb(['a','b','c'], [1,2,3], scalar_mult='**', latex_scalar_mult='*')
     736        'a + 2**b + 3**c'
     737        sage: repr_lincomb(['a','b','c'], [1,2,3], is_latex=True, scalar_mult='**', latex_scalar_mult='*')
     738        'a + 2*b + 3*c'
    706739    """
    707740    s = ""
    708741    first = True
    709742    i = 0
    710743
     744    if is_latex:
     745        if latex_scalar_mult is None:
     746            if scalar_mult == '*':
     747                scalar_mult = ''
     748        else:
     749            scalar_mult = latex_scalar_mult
     750    l = len(scalar_mult)
     751
    711752    all_atomic = True
    712753    for c in coeffs:
    713754        if is_latex and hasattr(symbols[i], '_latex_'):
    def repr_lincomb(symbols, coeffs, is_lat 
    716757            b = str(symbols[i])
    717758        if c != 0:
    718759            coeff = coeff_repr(c, is_latex)
    719             if coeff == "1":
    720                 coeff = ""
    721             elif coeff == "-1":
    722                 coeff = "-"
    723             elif not is_latex and len(b) > 0:
    724                 b = "*" + b
    725             elif len(coeff) > 0 and b == "1":
    726                 b = ""
    727             if not first:
    728                 coeff = " + %s"%coeff
    729             else:
    730                 coeff = "%s"%coeff
     760            if coeff != "0":
     761                if coeff == "1":
     762                    coeff = ""
     763                elif coeff == "-1":
     764                    coeff = "-"
     765                elif len(b) > 0:
     766                    b = scalar_mult + b
     767                elif len(coeff) > 0 and b == "1":
     768                    b = ""
     769                if not first:
     770                    if len(coeff) > 0 and coeff[0] == "-":
     771                        coeff = " - %s"%coeff[1:]
     772                    else:
     773                        coeff = " + %s"%coeff
     774                else:
     775                    coeff = "%s"%coeff
    731776            s += "%s%s"%(coeff, b)
    732777            first = False
    733778        i += 1
    734779    if first:
    735         s = "0"
    736     s = s.replace("+ -","- ")
    737     if s[:2] == "1*":
    738         s = s[2:]
    739     elif s[:3] == "-1*":
    740         s = "-" + s[3:]
    741     s = s.replace(" 1*", " ")
    742     if s == "":
     780        return "0"
     781    elif s == "":
    743782        return "1"
    744     return s
     783    else:
     784        return s
     785
     786
    745787
    746788def strunc(s, n = 60):
    747789    """