Ticket #5848: untabify.patch

File untabify.patch, 222.1 KB (added by jhpalmieri, 12 years ago)
  • sage/algebras/algebra_order.py

    # HG changeset patch
    # User John H. Palmieri <palmieri@math.washington.edu>
    # Date 1240353484 25200
    # Node ID 203bbc5a8a5f0e862e4459b7f6f241db61bc2e8e
    # Parent  84d47cdd70031673e4000de43c4582938656f12e
    untabify
    
    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/algebras/algebra_order.py
    a b  
    6363
    6464    def __contains__(self, x):
    6565        if isinstance(x, AlgebraOrderElement) and x.parent() is self:
    66             return True
     66            return True
    6767        elif isinstance(x, AlgebraElement) \
    6868               and x.parent() is self.ambient_algebra():
    6969            M = self.inverse_embedding_matrix()
     
    151151            M = MatrixSpace(K,n)
    152152            self.__embedding_matrix = M([ x.ambient_algebra_element().vector() for x in self.basis() ])
    153153        return self.__embedding_matrix
    154        
     154
    155155    def inverse_embedding_matrix(self):
    156156        r"""
    157157        Return the inverse of the $n\times n$ matrix whose rows are
     
    168168            return self.__inverse_embedding_matrix
    169169        except ZeroDivisionError:
    170170            raise AttributeError, "Basis for quaternion order is not of full rank."
    171        
     171
    172172    def module(self):
    173173        r"""
    174174        Convert this algebra order into a module over the base ring.
  • sage/algebras/algebra_order_element.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/algebras/algebra_order_element.py
    a b  
    8282        """
    8383        The trace of the element with respect to its action
    8484        by left or right multiplication on the order.
    85         """
     85        """
    8686        R = self.parent().base_ring()
    8787        return R(self.__ambient_algebra_element.trace())
    88                
     88
    8989    def norm(self):
    9090        """
    9191        The determinant (= norm) of the element with respect to
    9292        its action by left or right multiplication on the order.
    93         """
     93        """
    9494        R = self.parent().base_ring()
    9595        return R(self.__ambient_algebra_element.norm())
    9696
     
    9898        """
    9999        The characteristic polynomial of the element with respect
    100100        to its action by left or right multiplication on the order.
    101         """
     101        """
    102102        R = self.parent().base_ring()
    103103        P = PolynomialRing(R, var)
    104104        return P(self.__ambient_algebra_element.charpoly('x'))
     
    109109        """
    110110        The minimal polynomial of the element with respect to its
    111111        action by left or right multiplication on the order.
    112         """
     112        """
    113113        R = self.parent().base_ring()
    114114        P = PolynomialRing(R, var)
    115115        return P(self.__element.minpoly())
  • sage/algebras/algebra_order_ideal.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/algebras/algebra_order_ideal.py
    a b  
    4848        return AlgebraOrderIdealElement(self, x, check=check)
    4949                               
    5050    def __contains__(self, x):
    51         if isinstance(x, AlgebraOrderIdealElement) and x.parent() is self: 
    52             return True
     51        if isinstance(x, AlgebraOrderIdealElement) and x.parent() is self:
     52            return True
    5353        elif isinstance(x, AlgebraElement) \
    5454               and x.parent() is self.ambient_algebra():
    5555            return NotImplementedError
  • sage/algebras/group_algebra.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/algebras/group_algebra.py
    a b  
    200200            self.group(), an element of self.base_ring(), or an element
    201201            of self.group().
    202202            -- check (boolean): whether or not to check that the given elements
    203             really do lie in self.group(). Chiefly provided to speed up
    204             arithmetic operations with elements that have already been checked
    205             to lie in the group.
     203            really do lie in self.group(). Chiefly provided to speed up
     204            arithmetic operations with elements that have already been checked
     205            to lie in the group.
    206206
    207207        OUTPUT:
    208208            -- a GroupAlgebraElement instance whose parent is self.
  • sage/algebras/quatalg/quaternion_algebra_element.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/algebras/quatalg/quaternion_algebra_element.pyx
    a b  
    12341234        """
    12351235        #return 2*self[0]
    12361236       
    1237         mpz_mul_si(U1, self.x, 2)       
     1237        mpz_mul_si(U1, self.x, 2)
    12381238        cdef Rational result = PY_NEW(Rational)
    12391239        mpq_set_num(result.value, U1)
    12401240        mpq_set_den(result.value, self.d)
  • sage/calculus/calculus.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/calculus/calculus.py
    a b  
    65456545            return z
    65466546   
    65476547    def is_field(self):
    6548             """
     6548        """
    65496549        Returns True, since the callable symbolic expression ring is (for
    65506550        the most part) a field.
    65516551       
     
    65556555            sage: g.parent().is_field()
    65566556            True
    65576557        """
    6558             return True
     6558        return True
    65596559
    65606560    def _an_element_impl(self):
    65616561        """
  • sage/coding/guava.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/coding/guava.py
    a b  
    6161        sage: C.minimum_distance()
    6262        4
    6363        sage: C.gen_mat()
    64         [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
    65         [0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1]
    66         [0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1]
    67         [0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1]
    68         [0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
    69         [0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1]
    70         [0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1]
    71         [0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1]
    72         [0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1]
    73         [0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1]
    74         [0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1]
     64        [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
     65        [0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1]
     66        [0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1]
     67        [0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1]
     68        [0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
     69        [0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1]
     70        [0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1]
     71        [0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1]
     72        [0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1]
     73        [0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1]
     74        [0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1]
    7575
    7676    AUTHOR: David Joyner (11-2005)
    7777    """
  • sage/coding/linear_code.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/coding/linear_code.py
    a b  
    11401140            sage: v = vector(GF(5),[1,0,0,2,1,0])
    11411141            sage: C.decode(v)
    11421142            (2, 0, 0, 2, 1, 0)
    1143             sage: F = GF(4,"a")
    1144             sage: C = HammingCode(2,F)
    1145             sage: v = vector(F, [1,0,0,a,1])
    1146             sage: C.decode(v)
    1147             (1, 0, 0, 1, 1)
    1148             sage: C.decode(v, method="nearest neighbor")
    1149             (1, 0, 0, 1, 1)
    1150             sage: C.decode(v, method="guava")
    1151             (1, 0, 0, 1, 1)
     1143            sage: F = GF(4,"a")
     1144            sage: C = HammingCode(2,F)
     1145            sage: v = vector(F, [1,0,0,a,1])
     1146            sage: C.decode(v)
     1147            (1, 0, 0, 1, 1)
     1148            sage: C.decode(v, method="nearest neighbor")
     1149            (1, 0, 0, 1, 1)
     1150            sage: C.decode(v, method="guava")
     1151            (1, 0, 0, 1, 1)
    11521152       
    11531153        Does not work for very long codes since the syndrome table grows
    11541154        too large.
     
    20032003            else:
    20042004                c0 = QQ((n-d)*C.spectrum()[d])/rising_factorial(n-d0-1,d0+2)
    20052005        if i==3 or i==4:
    2006             if d>d0:
     2006            if d>d0:
    20072007                c0 = rising_factorial(d-d0,d0+1)*C.spectrum()[d]/((q-1)*rising_factorial(n-d0,d0+1))
    20082008            else:
    20092009                c0 = C.spectrum()[d]/((q-1)*rising_factorial(n-d0,d0+1))
  • sage/combinat/crystals/crystals.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/crystals/crystals.py
    a b  
    182182        return self.cartan_type().root_system().ambient_space()
    183183
    184184    def cartan_type(self):
    185         """
    186         Returns the Cartan type of the associated crystal
     185        """
     186        Returns the Cartan type of the associated crystal
    187187
    188         EXAMPLES::
     188        EXAMPLES::
    189189            sage: C = CrystalOfLetters(['A',2])
    190             sage: C.cartan_type()
    191             ['A', 2]
     190            sage: C.cartan_type()
     191            ['A', 2]
    192192        """
    193         return self._cartan_type
     193        return self._cartan_type
    194194 
    195195    def index_set(self):
    196         """
    197         Returns the index set of the Dynkin diagram underlying the given crystal
     196        """
     197        Returns the index set of the Dynkin diagram underlying the given crystal
    198198
    199         EXAMPLES:
    200             sage: C = CrystalOfLetters(['A', 5])
    201             sage: C.index_set()
    202             [1, 2, 3, 4, 5]
     199        EXAMPLES:
     200            sage: C = CrystalOfLetters(['A', 5])
     201            sage: C.index_set()
     202            [1, 2, 3, 4, 5]
    203203        """
    204         return self.cartan_type().index_set()
     204        return self.cartan_type().index_set()
    205205
    206206    def Lambda(self):
    207207        """
     
    318318        hlist = {}
    319319        mlist = {}
    320320
    321         for x in self.highest_weight_vectors():
     321        for x in self.highest_weight_vectors():
    322322            k = x.weight()
    323323            if k in hlist:
    324324                hlist[k] += 1
     
    645645        return self.parent().index_set()
    646646
    647647    def cartan_type(self):
    648         """
    649         Returns the cartan type associated to self
     648        """
     649        Returns the cartan type associated to self
    650650
    651         EXAMPLES::
    652             sage: C = CrystalOfLetters(['A', 5])
    653             sage: C(1).cartan_type()
    654             ['A', 5]
     651        EXAMPLES::
     652            sage: C = CrystalOfLetters(['A', 5])
     653            sage: C(1).cartan_type()
     654            ['A', 5]
    655655        """
    656         return self.parent().cartan_type()
     656        return self.parent().cartan_type()
    657657
    658658    def weight(self):
    659659        """
     
    663663            sage: C(1).weight()
    664664            (1, 0, 0, 0, 0, 0)
    665665        """
    666         return self.Phi() - self.Epsilon()
     666        return self.Phi() - self.Epsilon()
    667667
    668668    def e(self, i):
    669669        r"""
     
    750750            (1, 0, 0, 0, 0, 0)
    751751        """
    752752        Lambda = self.parent().Lambda()
    753         return sum(self.epsilon(i) * Lambda[i] for i in self.index_set())
     753        return sum(self.epsilon(i) * Lambda[i] for i in self.index_set())
    754754
    755755    def Phi(self):
    756756        """
     
    765765            (1, 1, 0, 0, 0, 0)
    766766        """
    767767        Lambda = self.parent().Lambda()
    768         return sum(self.phi(i) * Lambda[i] for i in self.index_set())
     768        return sum(self.phi(i) * Lambda[i] for i in self.index_set())
    769769
    770770    def s(self, i):
    771         r"""
    772         Returns the reflection of self along its `i`-string
    773        
    774         EXAMPLES::
    775        
    776             sage: C = CrystalOfTableaux(['A',2], shape=[2,1])
    777             sage: b=C(rows=[[1,1],[3]])
    778             sage: b.s(1)
    779             [[2, 2], [3]]
    780             sage: b=C(rows=[[1,2],[3]])
    781             sage: b.s(2)
    782             [[1, 2], [3]]
    783             sage: T=CrystalOfTableaux(['A',2],shape=[4])
    784             sage: t=T(rows=[[1,2,2,2]])
    785             sage: t.s(1)
    786             [[1, 1, 1, 2]]
    787         """
     771        r"""
     772        Returns the reflection of self along its `i`-string
     773       
     774        EXAMPLES::
     775       
     776            sage: C = CrystalOfTableaux(['A',2], shape=[2,1])
     777            sage: b=C(rows=[[1,1],[3]])
     778            sage: b.s(1)
     779            [[2, 2], [3]]
     780            sage: b=C(rows=[[1,2],[3]])
     781            sage: b.s(2)
     782            [[1, 2], [3]]
     783            sage: T=CrystalOfTableaux(['A',2],shape=[4])
     784            sage: t=T(rows=[[1,2,2,2]])
     785            sage: t.s(1)
     786            [[1, 1, 1, 2]]
     787        """
    788788        d = self.phi(i)-self.epsilon(i)
    789         b = self
    790         if d > 0:
    791             for j in range(d):
    792                 b = b.f(i)
    793         else:
    794             for j in range(-d):
    795                 b = b.e(i)
    796         return b
     789        b = self
     790        if d > 0:
     791            for j in range(d):
     792                b = b.f(i)
     793        else:
     794            for j in range(-d):
     795                b = b.e(i)
     796        return b
    797797
    798798    def is_highest_weight(self):
    799         r"""
    800         Returns True if self is a highest weight.
    801        
    802         EXAMPLES::
    803        
    804             sage: C = CrystalOfLetters(['A',5])
    805             sage: C(1).is_highest_weight()
    806             True
    807             sage: C(2).is_highest_weight()
    808             False
    809         """
    810         return all(self.e(i) == None for i in self.index_set())
     799        r"""
     800        Returns True if self is a highest weight.
     801       
     802        EXAMPLES::
     803       
     804            sage: C = CrystalOfLetters(['A',5])
     805            sage: C(1).is_highest_weight()
     806            True
     807            sage: C(2).is_highest_weight()
     808            False
     809        """
     810        return all(self.e(i) == None for i in self.index_set())
    811811
    812812class CrystalBacktracker(GenericBacktracker):
    813813    def __init__(self, crystal):
  • sage/combinat/crystals/tensor_product.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/crystals/tensor_product.py
    a b  
    209209    It has `8` elements::
    210210
    211211        sage: T.list()
    212         [[2, 1, 1], [2, 1, 2], [2, 1, 3], [3, 1, 3], [3, 2, 3], [3, 1, 1], [3, 1, 2], [3, 2, 2]]
     212        [[2, 1, 1], [2, 1, 2], [2, 1, 3], [3, 1, 3], [3, 2, 3], [3, 1, 1], [3, 1, 2], [3, 2, 2]]
    213213
    214214    One can also check the Cartan type of the crystal::
    215215
    216216        sage: T.cartan_type()
    217         ['A', 2]
     217        ['A', 2]
    218218   
    219219    Other examples include crystals of tableaux (which internally are represented as tensor products
    220220    obtained by reading the tableaux columnwise)::
    221221
    222222        sage: C = CrystalOfTableaux(['A',3], shape=[1,1,0])
    223         sage: D = CrystalOfTableaux(['A',3], shape=[1,0,0])
    224         sage: T = TensorProductOfCrystals(C,D, generators=[[C(rows=[[1], [2]]), D(rows=[[1]])], [C(rows=[[2], [3]]), D(rows=[[1]])]])
    225         sage: T.cardinality()
    226         24
    227         sage: T.check()
    228         True
    229         sage: T.module_generators
    230         [[[[1], [2]], [[1]]], [[[2], [3]], [[1]]]]
    231         sage: [x.weight() for x in T.module_generators]
    232         [(2, 1, 0, 0), (1, 1, 1, 0)]
     223        sage: D = CrystalOfTableaux(['A',3], shape=[1,0,0])
     224        sage: T = TensorProductOfCrystals(C,D, generators=[[C(rows=[[1], [2]]), D(rows=[[1]])], [C(rows=[[2], [3]]), D(rows=[[1]])]])
     225        sage: T.cardinality()
     226        24
     227        sage: T.check()
     228        True
     229        sage: T.module_generators
     230        [[[[1], [2]], [[1]]], [[[2], [3]], [[1]]]]
     231        sage: [x.weight() for x in T.module_generators]
     232        [(2, 1, 0, 0), (1, 1, 1, 0)]
    233233
    234234    If no module generators are specified, we obtain the full tensor
    235235    product::
    236236
    237237        sage: C=CrystalOfLetters(['A',2])
    238         sage: T=TensorProductOfCrystals(C,C)
    239         sage: T.list()
    240         [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
    241         sage: T.cardinality()
    242         9
     238        sage: T=TensorProductOfCrystals(C,C)
     239        sage: T.list()
     240        [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
     241        sage: T.cardinality()
     242        9
    243243
    244244    For a tensor product of crystals without module generators, the
    245245    default implementation of module_generators contains all elements
     
    248248    this needs to be implemented for the specific crystal separately::
    249249
    250250        sage: T.module_generators.list()
    251         [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
     251        [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
    252252
    253253    For classical highest weight crystals, it is also possible to list
    254254    all highest weight elements::
    255255
    256256        sage: C = CrystalOfLetters(['A',2])
    257         sage: T = TensorProductOfCrystals(C,C,C,generators=[[C(2),C(1),C(1)],[C(1),C(2),C(1)]])
    258         sage: T.highest_weight_vectors()
    259         [[2, 1, 1], [1, 2, 1]]
     257        sage: T = TensorProductOfCrystals(C,C,C,generators=[[C(2),C(1),C(1)],[C(1),C(2),C(1)]])
     258        sage: T.highest_weight_vectors()
     259        [[2, 1, 1], [1, 2, 1]]
    260260    """
    261261    if options.has_key('generators'):
    262262        if all(isinstance(crystal,ClassicalCrystal) for crystal in crystals):
     
    304304            sage: T == loads(dumps(T))
    305305            True
    306306        """
    307         crystals = [ crystal for crystal in crystals]
     307        crystals = [ crystal for crystal in crystals]
    308308        self._name = "The tensor product of the crystals %s"%crystals
    309309        self.crystals = crystals
    310310        if options.has_key('cartan_type'):
     
    460460                height = minus
    461461            else:
    462462                height = height - plus + minus
    463         return height   
     463        return height
    464464   
    465465    def epsilon(self, i):
    466466        """
     
    534534        l = self.positions_of_unmatched_minus(i, dual=True, reverse=True)
    535535        l.reverse()
    536536        return [len(self)-1-l[j] for j in range(len(l))]
    537        
     537
    538538class CrystalOfTableaux(CrystalOfWords, ClassicalCrystal):
    539539    r"""
    540540    Crystals of tableaux. Input: a Cartan Type type and "shape", a
     
    624624        True
    625625        sage: T.list()
    626626        [[[1]], [[2]], [[-2]], [[-1]]]
    627         sage: T = CrystalOfTableaux(['A',2], shapes = [[],[1],[2]])
    628         sage: T.list()
    629         [[], [[1]], [[2]], [[3]], [[1, 1]], [[1, 2]], [[2, 2]], [[1, 3]], [[2, 3]], [[3, 3]]]
    630         sage: T.module_generators
    631         ([], [[1]], [[1, 1]])
    632         sage: T = CrystalOfTableaux(['B',2],shape=[3])
    633         sage: T(rows=[[1,1,0]])
    634         [[1, 1, 0]]
     627        sage: T = CrystalOfTableaux(['A',2], shapes = [[],[1],[2]])
     628        sage: T.list()
     629        [[], [[1]], [[2]], [[3]], [[1, 1]], [[1, 2]], [[2, 2]], [[1, 3]], [[2, 3]], [[3, 3]]]
     630        sage: T.module_generators
     631        ([], [[1]], [[1, 1]])
     632        sage: T = CrystalOfTableaux(['B',2],shape=[3])
     633        sage: T(rows=[[1,1,0]])
     634        [[1, 1, 0]]
    635635
    636636   
    637637    Input tests::
     
    663663    The next example checks whether a given tableau is in fact a valid type C tableau or not:
    664664
    665665        sage: T = CrystalOfTableaux(['C',3], shape = [2,2,2])
    666         sage: t = T(rows=[[1,3],[2,-3],[3,-1]])
    667         sage: t in T.list()
    668         True
    669         sage: t = T(rows=[[2,3],[3,-3],[-3,-2]])
    670         sage: t in T.list()
    671         False
     666        sage: t = T(rows=[[1,3],[2,-3],[3,-1]])
     667        sage: t in T.list()
     668        True
     669        sage: t = T(rows=[[2,3],[3,-3],[-3,-2]])
     670        sage: t in T.list()
     671        False
    672672    """
    673673    def __init__(self, type, shape = None, shapes = None):
    674674        """
     
    679679            True
    680680        """
    681681        self.letters = CrystalOfLetters(type)
    682         if shape is not None:
    683             assert shapes is None
    684             shapes = (shape,)
    685         assert shapes is not None
    686         CrystalOfWords.__init__(self)
    687         module_generators = tuple(self.module_generator(la) for la in shapes)
     682        if shape is not None:
     683            assert shapes is None
     684            shapes = (shape,)
     685        assert shapes is not None
     686        CrystalOfWords.__init__(self)
     687        module_generators = tuple(self.module_generator(la) for la in shapes)
    688688        self.module_generators = module_generators
    689689        self._name = "The crystal of tableaux of type %s and shape(s) %s"%(type, str(shapes))
    690690
    691691    def cartan_type(self):
    692         """
    693         Returns the Cartan type of the associated crystal
     692        """
     693        Returns the Cartan type of the associated crystal
    694694
    695         EXAMPLES::
    696             sage: T = CrystalOfTableaux(['A',3], shape = [2,2])
    697             sage: T.cartan_type()
    698             ['A', 3]
     695        EXAMPLES::
     696            sage: T = CrystalOfTableaux(['A',3], shape = [2,2])
     697            sage: T.cartan_type()
     698            ['A', 3]
    699699        """
    700         return self.letters.cartan_type()
     700        return self.letters.cartan_type()
    701701
    702702    def module_generator(self, shape):
    703         """
    704         This yields the module generator (or highest weight element) of a classical
    705         crystal of given shape. The module generator is the unique tableau with equal
    706         shape and content.
    707        
    708         EXAMPLE:
    709             sage: T = CrystalOfTableaux(['D',3], shape = [1,1])
    710             sage: T.module_generator([1,1])
    711             [[1], [2]]
    712         """
    713         type = self.cartan_type()
    714         if type[0] == 'D' and len(shape) == type[1] and shape[type[1]-1] < 0:
    715             invert = True
    716             shape[type[1]-1]=-shape[type[1]-1]
    717         else:
    718             invert = False
    719         p = Partition(shape).conjugate()
    720         # The column canonical tableau, read by columns
    721         module_generator = flatten([[p[j]-i for i in range(p[j])] for j in range(len(p))])
    722         if invert:
    723             for i in range(type[1]):
    724                 if module_generator[i] == type[1]:
    725                     module_generator[i] = -type[1]
    726         return self(*[self.letters(x) for x in module_generator])
     703        """
     704        This yields the module generator (or highest weight element) of a classical
     705        crystal of given shape. The module generator is the unique tableau with equal
     706        shape and content.
     707       
     708        EXAMPLE:
     709            sage: T = CrystalOfTableaux(['D',3], shape = [1,1])
     710            sage: T.module_generator([1,1])
     711            [[1], [2]]
     712        """
     713        type = self.cartan_type()
     714        if type[0] == 'D' and len(shape) == type[1] and shape[type[1]-1] < 0:
     715            invert = True
     716            shape[type[1]-1]=-shape[type[1]-1]
     717        else:
     718            invert = False
     719        p = Partition(shape).conjugate()
     720        # The column canonical tableau, read by columns
     721        module_generator = flatten([[p[j]-i for i in range(p[j])] for j in range(len(p))])
     722        if invert:
     723            for i in range(type[1]):
     724                if module_generator[i] == type[1]:
     725                    module_generator[i] = -type[1]
     726        return self(*[self.letters(x) for x in module_generator])
    727727
    728728    def __call__(self, *args, **options):
    729729        """
     
    750750            True
    751751        """
    752752        if len(args) == 1:
    753             if isinstance(args[0], CrystalOfTableauxElement):
    754                 if args[0].parent() == parent:
    755                     return args[0]
    756                 else:
    757                     raise ValueError, "Inconsistent parent"
    758             elif isinstance(args[0], Tableau_class):
    759                 options['rows'] = args[0]
    760         if options.has_key('list'):
    761             list = options['list']
     753            if isinstance(args[0], CrystalOfTableauxElement):
     754                if args[0].parent() == parent:
     755                    return args[0]
     756                else:
     757                    raise ValueError, "Inconsistent parent"
     758            elif isinstance(args[0], Tableau_class):
     759                options['rows'] = args[0]
     760        if options.has_key('list'):
     761            list = options['list']
    762762        elif options.has_key('rows'):
    763763            rows=options['rows']
    764764#            list=Tableau(rows).to_word_by_column()
    765             rows=Tableau(rows).conjugate()
    766             list=[]
    767             for col in rows:
    768                 col.reverse()
    769                 list+=col
     765            rows=Tableau(rows).conjugate()
     766            list=[]
     767            for col in rows:
     768                col.reverse()
     769                list+=col
    770770        elif options.has_key('columns'):
    771771            columns=options['columns']
    772772            list=[]
     
    822822            <class 'sage.combinat.tableau.Tableau_class'>
    823823            sage: type(t[0][0])
    824824            <type 'sage.rings.integer.Integer'>
    825             sage: T = CrystalOfTableaux(['D',3], shape = [1,1])
    826             sage: t=T(rows=[[-3],[3]]).to_tableau(); t
    827             [[-3], [3]]
    828             sage: t=T(rows=[[3],[-3]]).to_tableau(); t
    829             [[3], [-3]]
     825            sage: T = CrystalOfTableaux(['D',3], shape = [1,1])
     826            sage: t=T(rows=[[-3],[3]]).to_tableau(); t
     827            [[-3], [3]]
     828            sage: t=T(rows=[[3],[-3]]).to_tableau(); t
     829            [[3], [-3]]
    830830        """
    831         if self._list == []:
    832             return Tableau([])
    833         tab = [ [self[0].value] ]
    834         for i in range(1,len(self)):
    835             if self[i-1] <= self[i]:
    836                 tab.append([self[i].value])
    837             else:
    838                 l = len(tab)-1
    839                 tab[l].append(self[i].value)
    840         for x in tab:
    841             x.reverse()
    842         return Tableau(tab).conjugate()
     831        if self._list == []:
     832            return Tableau([])
     833        tab = [ [self[0].value] ]
     834        for i in range(1,len(self)):
     835            if self[i-1] <= self[i]:
     836                tab.append([self[i].value])
     837            else:
     838                l = len(tab)-1
     839                tab[l].append(self[i].value)
     840        for x in tab:
     841            x.reverse()
     842        return Tableau(tab).conjugate()
  • sage/combinat/matrices/dancing_links.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/matrices/dancing_links.pyx
    a b  
    121121        initialised using the same row list.
    122122
    123123        TESTS:
    124             sage: from sage.combinat.matrices.dancing_links import dlx_solver
     124            sage: from sage.combinat.matrices.dancing_links import dlx_solver
    125125            sage: rows = [[0,1,2]]
    126126            sage: X = dlx_solver(rows)
    127127            sage: Z = dlx_solver(rows)
  • sage/combinat/partition.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/partition.py
    a b  
    14001400            [[0, 2], [2, 0]]
    14011401            sage: Partition([6,3,3,1,1,1]).outside_corners()
    14021402            [[0, 6], [1, 3], [3, 1], [6, 0]]
    1403             sage: Partition([]).outside_corners()
    1404             [[0, 0]]
    1405         """
    1406         p = self
    1407         if p == Partition([]):
    1408             return [[0,0]]
     1403            sage: Partition([]).outside_corners()
     1404            [[0, 0]]
     1405        """
     1406        p = self
     1407        if p == Partition([]):
     1408            return [[0,0]]
    14091409        res = [ [0, p[0]] ]       
    14101410        for i in range(1, len(p)):
    14111411            if p[i-1] != p[i]:
  • sage/combinat/posets/poset_examples.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/posets/poset_examples.py
    a b  
    286286        element_labels = dict([[s,"".join(map(str,s.reduced_word_lexmin()))] for s in Permutations(n)])
    287287    def weak_covers(s):
    288288        return [v for v in s.bruhat_succ() if
    289                 s.length() + (s.inverse()*v).length() == v.length()]
     289                s.length() + (s.inverse()*v).length() == v.length()]
    290290    return Poset(dict([[s,weak_covers(s)] for s in Permutations(n)]),element_labels)
    291291
    292292#def PosetExamples(n,uc=None):
  • sage/combinat/posets/posets.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/posets/posets.py
    a b  
    478478        """
    479479        if label_elements and element_labels is None:
    480480            element_labels = self._elements
    481         return self.hasse_diagram().plot(label_elements=label_elements,
    482                         element_labels=element_labels,
    483                         label_font_size=label_font_size,
    484                         label_font_color=label_font_color,
    485                         vertex_size=vertex_size,vertex_colors=vertex_colors,**kwds)
     481        return self.hasse_diagram().plot(label_elements=label_elements,
     482                        element_labels=element_labels,
     483                        label_font_size=label_font_size,
     484                        label_font_color=label_font_color,
     485                        vertex_size=vertex_size,vertex_colors=vertex_colors,**kwds)
    486486
    487487    def show(self, label_elements=True, element_labels=None,
    488488            label_font_size=12,label_font_color='black',
  • sage/combinat/ribbon_tableau.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/ribbon_tableau.py
    a b  
    579579##     // Generic function for driving into the graph of partitions coding all ribbons
    580580##     // tableaux of a given shape and weight
    581581##     //////////////////////////////////////////////////////////////////////////////////////////
    582                                                  
     582
    583583##     //This function construct the graph of the set of k-ribbon tableaux
    584584##     //of a given skew shape and a given weight.
    585585##     //The first argument is always a skew partition.
  • sage/combinat/root_system/type_G.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/root_system/type_G.py
    a b  
    2828        """
    2929        EXAMPLES:
    3030            sage: CartanType(['G',2]).root_system().ambient_space().simple_roots()
    31             Finite family {1: (0, 1, -1), 2: (1, -2, 1)}
     31            Finite family {1: (0, 1, -1), 2: (1, -2, 1)}
    3232         """
    3333        return self._term(1)-self._term(2) if i == 1 else self._term(0)-2*self._term(1)+self._term(2)
    3434
  • sage/combinat/sloane_functions.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/sloane_functions.py
    a b  
    10181018
    10191019    def s2(self, n, k):
    10201020        """
    1021         Returns the Stirling number S2(n,k) of the 2nd kind.
    1022        
    1023         EXAMPLES::
    1024        
    1025             sage: sloane.A008277.s2(4,2)
    1026             7
    1027         """
     1021        Returns the Stirling number S2(n,k) of the 2nd kind.
     1022       
     1023        EXAMPLES::
     1024       
     1025            sage: sloane.A008277.s2(4,2)
     1026            7
     1027        """
    10281028        return combinat.stirling_number2(n,k)
    10291029
    10301030    def _eval(self, n):
     
    17721772    def _repr_(self):
    17731773        """
    17741774        EXAMPLES::
    1775        
     1775
    17761776            sage: sloane.A002378._repr_()
    17771777            'Oblong (or pronic, or heteromecic) numbers: n(n+1).'
    17781778        """
     
    20232023
    20242024            sage: [sloane.A000120._eval(n) for n in range(10)]
    20252025            [0, 1, 1, 2, 1, 2, 2, 3, 1, 2]
    2026         """   
     2026        """   
    20272027        return self.f(n)
    20282028
    20292029class A010060(SloaneSequence):
     
    53785378        """
    53795379        SloaneSequence.__init__(self, offset=0)
    53805380        self._b = []
    5381         self._a0a1d = (0,1,2)
     5381        self._a0a1d = (0,1,2)
    53825382        self._precompute(2)  # force precomputation, e.g. a(0) will fail when asked first
    53835383       
    53845384    def _repr_(self):
     
    54365436        """
    54375437        SloaneSequence.__init__(self, offset=0)
    54385438        self._b = []
    5439         self._a0a1d = (1,1,1)
     5439        self._a0a1d = (1,1,1)
    54405440        self._precompute(2)  # force precomputation, e.g. a(0) will fail when asked first
    54415441       
    54425442    def _repr_(self):
     
    55015501        - Jaap Spies (2007-01-23)
    55025502        """
    55035503        SloaneSequence.__init__(self, offset=1)
    5504         self._a0a1d = (0,1,3)
     5504        self._a0a1d = (0,1,3)
    55055505        self._b = []
    55065506        self._k = self.offset + 1
    55075507       
     
    55645564        - Jaap Spies (2007-01-13)
    55655565        """
    55665566        SloaneSequence.__init__(self, offset=2)
    5567         self._a0a1d = (0,1,4)
    5568         self._b = []
    5569         self._k = self.offset + 1       
     5567        self._a0a1d = (0,1,4)
     5568        self._b = []
     5569        self._k = self.offset + 1
    55705570       
    55715571    def _repr_(self):
    55725572        """
     
    56285628        - Jaap Spies (2007-01-13)
    56295629        """
    56305630        SloaneSequence.__init__(self, offset=3)
    5631         self._a0a1d = (0,1,5)
     5631        self._a0a1d = (0,1,5)
    56325632        self._b = []
    56335633        self._k = self.offset + 1
    56345634       
     
    57185718        - Jaap Spies (2007-01-23)
    57195719        """
    57205720        SloaneSequence.__init__(self, offset=1)
    5721         self._a0a1d = (6,43,6)
     5721        self._a0a1d = (6,43,6)
    57225722        self._k = self.offset + 1
    57235723        self._b = []
    57245724       
     
    57845784        - Jaap Spies (2007-01-23)
    57855785        """
    57865786        SloaneSequence.__init__(self, offset=0)
    5787         self._a0a1d = (0,2,1)
     5787        self._a0a1d = (0,2,1)
    57885788        self._b = []
    57895789        self._precompute(2)
    57905790        self._k1 = 2
     
    88428842
    88438843    def _repr_(self):
    88448844        """
    8845         EXAMPLES::
    8846        
    8847             sage: sloane.A079922._repr_()
    8848             'Solutions to the Dancing School problem with n girls and n+3 boys'
    8849         """
     8845        EXAMPLES::
     8846       
     8847            sage: sloane.A079922._repr_()
     8848            'Solutions to the Dancing School problem with n girls and n+3 boys'
     8849        """
    88508850        return "Solutions to the Dancing School problem with n girls and n+3 boys"
    88518851   
    88528852   
     
    89188918
    89198919    def _repr_(self):
    89208920        """
    8921         EXAMPLES::
    8922        
    8923             sage: sloane.A079923._repr_()
    8924             'Solutions to the Dancing School problem with n girls and n+4 boys'
    8925         """
     8921        EXAMPLES::
     8922       
     8923            sage: sloane.A079923._repr_()
     8924            'Solutions to the Dancing School problem with n girls and n+4 boys'
     8925        """
    89268926        return "Solutions to the Dancing School problem with n girls and n+4 boys"
    89278927   
    89288928    def _eval(self, n):
     
    94989498            'Sequence of Uppuluri-Carpenter numbers'
    94999499        """
    95009500        return "Sequence of Uppuluri-Carpenter numbers"
    9501        
    95029501
    95039502
    95049503# A000100  a(n) = number of compositions of n in which the maximum part size is 3. Milestone!
  • sage/combinat/symmetric_group_algebra.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/symmetric_group_algebra.py
    a b  
    314314    if star:
    315315        it = it.restrict(it.size() - star)
    316316        kt = kt.restrict(kt.size() - star)
    317                
     317
    318318    if it.shape() != kt.shape():
    319319        raise ValueError, "the two tableaux must be of the same shape"
    320320
     
    525525            if value != 0:
    526526                print value
    527527                raise ValueError, "3.2.12.2 - %s"%tab
    528                        
     528
    529529            for tab2 in StandardTableaux(part):
    530530                #3.2.8 1
    531531                if e_ik(tab, tab2) - e(tab)*pi_ik(tab, tab2)*e(tab2)*(1/kappa(part)) != 0:
  • sage/combinat/tableau.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/tableau.py
    a b  
    919919        return sage.combinat.skew_tableau.SkewTableau(st).rectify()
    920920
    921921    def promotion_inverse(self, n):
    922         """
    923         Inverse promotion operator defined on rectangular tableaux using
    924         jeu de taquin
    925        
    926         EXAMPLES::
    927        
    928             sage: t = Tableau([[1,2],[3,3]])
    929             sage: t.promotion_inverse(2)
    930             [[1, 2], [2, 3]]
    931             sage: t = Tableau([[1,2],[2,3]])
    932             sage: t.promotion_inverse(2)
    933             [[1, 1], [2, 3]]
    934         """
    935         if not self.is_rectangular():
    936             raise ValueError, "Tableau is not rectangular"
    937         s = self.shape()[0]
    938         l = self.weight()[0]
    939         word = [i for i in self.to_word() if i>1]
    940         word = [i-1 for i in word]
    941         t = Tableau([])
    942         t = t.insert_word(word)
    943         t = t.to_list()
    944         if l<s:
    945             for i in range(l):
    946                 t[len(t)-1].append(n+1)
    947         else:
    948             t.append([n+1 for i in range(s)])
    949         return Tableau(t)
     922        """
     923        Inverse promotion operator defined on rectangular tableaux using
     924        jeu de taquin
     925       
     926        EXAMPLES::
     927       
     928            sage: t = Tableau([[1,2],[3,3]])
     929            sage: t.promotion_inverse(2)
     930            [[1, 2], [2, 3]]
     931            sage: t = Tableau([[1,2],[2,3]])
     932            sage: t.promotion_inverse(2)
     933            [[1, 1], [2, 3]]
     934        """
     935        if not self.is_rectangular():
     936            raise ValueError, "Tableau is not rectangular"
     937        s = self.shape()[0]
     938        l = self.weight()[0]
     939        word = [i for i in self.to_word() if i>1]
     940        word = [i-1 for i in word]
     941        t = Tableau([])
     942        t = t.insert_word(word)
     943        t = t.to_list()
     944        if l<s:
     945            for i in range(l):
     946                t[len(t)-1].append(n+1)
     947        else:
     948            t.append([n+1 for i in range(s)])
     949        return Tableau(t)
    950950   
    951951    def promotion(self, n):
    952         """
    953         Promotion operator defined on rectangular tableaux using jeu de
    954         taquin
    955        
    956         EXAMPLES::
    957        
    958             sage: t = Tableau([[1,2],[3,3]])
    959             sage: t.promotion(2)
    960             [[1, 1], [2, 3]]
    961             sage: t = Tableau([[1,1,1],[2,2,3],[3,4,4]])
    962             sage: t.promotion(3)
    963             [[1, 1, 2], [2, 2, 3], [3, 4, 4]]
    964             sage: t = Tableau([[1,2],[2]])
    965             sage: t.promotion(3)
    966             Traceback (most recent call last):
    967             ...
    968             ValueError: Tableau is not rectangular
    969         """
    970         if not self.is_rectangular():
    971             raise ValueError, "Tableau is not rectangular"
    972         t = self.rotate_180()
    973         t = [[n+2-i for i in row] for row in t.to_list()]
    974         t = Tableau(t).promotion_inverse(n)
    975         t = [[n+2-i for i in row] for row in t.to_list()]
    976         return Tableau(t).rotate_180()
     952        """
     953        Promotion operator defined on rectangular tableaux using jeu de
     954        taquin
     955       
     956        EXAMPLES::
     957       
     958            sage: t = Tableau([[1,2],[3,3]])
     959            sage: t.promotion(2)
     960            [[1, 1], [2, 3]]
     961            sage: t = Tableau([[1,1,1],[2,2,3],[3,4,4]])
     962            sage: t.promotion(3)
     963            [[1, 1, 2], [2, 2, 3], [3, 4, 4]]
     964            sage: t = Tableau([[1,2],[2]])
     965            sage: t.promotion(3)
     966            Traceback (most recent call last):
     967            ...
     968            ValueError: Tableau is not rectangular
     969        """
     970        if not self.is_rectangular():
     971            raise ValueError, "Tableau is not rectangular"
     972        t = self.rotate_180()
     973        t = [[n+2-i for i in row] for row in t.to_list()]
     974        t = Tableau(t).promotion_inverse(n)
     975        t = [[n+2-i for i in row] for row in t.to_list()]
     976        return Tableau(t).rotate_180()
    977977
    978978
    979979    def row_stabilizer(self):
  • sage/combinat/words/morphism.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/combinat/words/morphism.py
    a b  
    737737       
    738738    def _check_primitive(self):
    739739        r"""
    740         Returns True if all the letters of the domain appear in all the
    741         images of letters of the domain.
    742        
    743         INPUT:
    744        
    745        
    746         -  ``self`` - the codomain must be an instance of
    747            Words
    748        
    749        
    750         EXAMPLES::
    751        
    752             sage: m = WordMorphism('a->ab,b->ba')
    753             sage: m._check_primitive()
    754             True
    755             sage: fibo = WordMorphism('a->ab,b->a')
    756             sage: fibo._check_primitive()
    757             False
    758             sage: print WordMorphism({2:[4,5,6],3:[4,1,8]})     
    759             WordMorphism: 2->456, 3->418
    760             sage: WordMorphism({2:[4,5,6],3:[4,1,8]})._check_primitive()
    761             False
    762         """
     740        Returns True if all the letters of the domain appear in all the
     741        images of letters of the domain.
     742       
     743        INPUT:
     744       
     745       
     746        -  ``self`` - the codomain must be an instance of
     747           Words
     748       
     749       
     750        EXAMPLES::
     751       
     752            sage: m = WordMorphism('a->ab,b->ba')
     753            sage: m._check_primitive()
     754            True
     755            sage: fibo = WordMorphism('a->ab,b->a')
     756            sage: fibo._check_primitive()
     757            False
     758            sage: print WordMorphism({2:[4,5,6],3:[4,1,8]})     
     759            WordMorphism: 2->456, 3->418
     760            sage: WordMorphism({2:[4,5,6],3:[4,1,8]})._check_primitive()
     761            False
     762        """
    763763        if not is_Words(self.codomain()):
    764764            raise TypeError, "codomain of self(=%s) must be an instance of Words"%self
    765765
  • sage/crypto/cipher.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/cipher.py
    a b  
    2727       
    2828        EXAMPLES: None yet
    2929        """
    30         self._parent = parent
    31         self._key = key
    32        
     30        self._parent = parent
     31        self._key = key
     32       
    3333    def __eq__(self, right):
    3434        return type(self) == type(right) and self._parent == right._parent and self._key == right._key
    3535
    3636    def __repr__(self):
    37         return str(self._key)
     37        return str(self._key)
    3838
    3939    def key(self):
    4040        return self._key # was str(self._key)
     
    6060       
    6161        EXAMPLES: None yet
    6262        """
    63         Cipher.__init__(self, parent, key)
     63        Cipher.__init__(self, parent, key)
    6464
    6565class PublicKeyCipher(Cipher):
    6666    """
     
    7474       
    7575        EXAMPLES: None yet
    7676        """
    77         Cipher.__init__(self, parent, key)
    78         self._public = public
     77        Cipher.__init__(self, parent, key)
     78        self._public = public
  • sage/crypto/classical.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/classical.py
    a b  
    103103        """
    104104        if not isinstance(S, StringMonoid_class):
    105105            raise TypeError, "S (= %s) must be a string monoid."%S
    106         R = IntegerModRing(S.ngens())
    107         M = MatrixSpace(R,m,m)
     106        R = IntegerModRing(S.ngens())
     107        M = MatrixSpace(R,m,m)
    108108        SymmetricKeyCryptosystem.__init__(self, S, S, M, block_length = m)
    109109
    110110    def __call__(self, A):
     
    214214            True
    215215        """
    216216        M = self.key_space()
    217         R = M.base_ring()
     217        R = M.base_ring()
    218218        m = M.nrows()
    219219        N = Integer(self.cipher_domain().ngens())
    220         while True:
    221             A = M([ randint(0,N-1) for i in range(m**2) ])
    222             if N.gcd(A.det()) == 1:
    223                 break
     220        while True:
     221            A = M([ randint(0,N-1) for i in range(m**2) ])
     222            if N.gcd(A.det()) == 1:
     223                break
    224224        return A
    225225
    226226    def inverse_key(self, A):
     
    247247            sage: c(e(M))
    248248            LAMAISONBLANCHE
    249249        """
    250         S = self.plaintext_space()
    251         M = self.key_space()
    252         if not A in M:
    253             raise TypeError, "A (= %s) must be a matrix in the key space of %s." % (A, self)
    254         m = self.block_length()
    255         MatZZ = MatrixSpace(ZZ,m)
    256         AZ = MatZZ([ [ A[i,j].lift() for j in range(m) ] for i in range(m) ])
    257         AZ_adj = AZ.adjoint()
    258         u, r, s = xgcd(A.det().lift(),S.ngens())
    259         if u != 1:
    260             raise ValueError, "Argument:\n\n%s\n\nis not invertible."%(A)
     250        S = self.plaintext_space()
     251        M = self.key_space()
     252        if not A in M:
     253            raise TypeError, "A (= %s) must be a matrix in the key space of %s." % (A, self)
     254        m = self.block_length()
     255        MatZZ = MatrixSpace(ZZ,m)
     256        AZ = MatZZ([ [ A[i,j].lift() for j in range(m) ] for i in range(m) ])
     257        AZ_adj = AZ.adjoint()
     258        u, r, s = xgcd(A.det().lift(),S.ngens())
     259        if u != 1:
     260            raise ValueError, "Argument:\n\n%s\n\nis not invertible."%(A)
    261261        return r * A.parent()(AZ_adj)
    262262
    263263    def encoding(self, M):
  • sage/crypto/classical_cipher.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/classical_cipher.py
    a b  
    5151            sage: E == loads(dumps(E))
    5252            True
    5353        """
    54         # TODO: some type checking that the key is an invertible matrix?
    55         SymmetricKeyCipher.__init__(self, parent, key)
     54        # TODO: some type checking that the key is an invertible matrix?
     55        SymmetricKeyCipher.__init__(self, parent, key)
    5656
    5757    def __eq__(self, right):
    5858        return type(self) == type(right) and self.parent() == right.parent() and self.key() == right.key()
    5959
    6060    def __call__(self, M):
    61         S = self.domain() # = plaintext_space = ciphertext_space
    62         if not isinstance(M, StringMonoidElement) and M.parent() == S:
    63             raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
    64         m = self.parent().block_length()
    65         if len(M) % m != 0:
    66             raise TypeError, "The length of M (= %s) must be a multiple of %s." % (M, m )
    67         Alph = list(S.alphabet())
    68         A = self.key() # A is an m x m matrix
     61        S = self.domain() # = plaintext_space = ciphertext_space
     62        if not isinstance(M, StringMonoidElement) and M.parent() == S:
     63            raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
     64        m = self.parent().block_length()
     65        if len(M) % m != 0:
     66            raise TypeError, "The length of M (= %s) must be a multiple of %s." % (M, m )
     67        Alph = list(S.alphabet())
     68        A = self.key() # A is an m x m matrix
    6969        R = A.parent().base_ring()
    7070        V = FreeModule(R,m)
    71         Mstr = str(M)
    72         C = []
    73         for i in range(len(M)//m):
    74             v = V([ Alph.index(Mstr[m*i+j]) for j in range(m) ])
    75             C += (v * A).list()
    76         return S([ k.lift() for k in C ])
    77        
     71        Mstr = str(M)
     72        C = []
     73        for i in range(len(M)//m):
     74            v = V([ Alph.index(Mstr[m*i+j]) for j in range(m) ])
     75            C += (v * A).list()
     76        return S([ k.lift() for k in C ])
     77       
    7878    def inverse(self):
    7979        E = self.parent()
    80         try:
    81             B = E.inverse_key(self.key())
    82         except:
    83             raise ValueError, "Argument\n\n%s\n\nmust be an invertible cipher." % self
    84         return E(B)
     80        try:
     81            B = E.inverse_key(self.key())
     82        except:
     83            raise ValueError, "Argument\n\n%s\n\nmust be an invertible cipher." % self
     84        return E(B)
    8585
    8686class SubstitutionCipher(SymmetricKeyCipher):
    8787    """
     
    114114            sage: E == loads(dumps(E))
    115115            True
    116116        """
    117         SymmetricKeyCipher.__init__(self, parent, key)
     117        SymmetricKeyCipher.__init__(self, parent, key)
    118118
    119119    def __eq__(self, right):
    120120        return type(self) == type(right) and self.parent() == right.parent() and self.key() == right.key()
    121121
    122122    def __call__(self, M):
    123         S = self.domain() # = plaintext_space = ciphertext_space
    124         if not isinstance(M, StringMonoidElement) and M.parent() == S:
    125             raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
    126         A = list(S.alphabet())
    127         K = str(self.key()) # K is a string, while we want the indices:
    128         I = [ A.index(K[i]) for i in range(len(K)) ]
    129         Mstr = str(M)
    130         return S([ I[A.index(Mstr[i])] for i in range(len(Mstr)) ])
    131        
     123        S = self.domain() # = plaintext_space = ciphertext_space
     124        if not isinstance(M, StringMonoidElement) and M.parent() == S:
     125            raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
     126        A = list(S.alphabet())
     127        K = str(self.key()) # K is a string, while we want the indices:
     128        I = [ A.index(K[i]) for i in range(len(K)) ]
     129        Mstr = str(M)
     130        return S([ I[A.index(Mstr[i])] for i in range(len(Mstr)) ])
     131       
    132132    def inverse(self):
    133133        E = self.parent()
    134         K = E.inverse_key(self.key())
    135         return E(K)
     134        K = E.inverse_key(self.key())
     135        return E(K)
    136136
    137137class TranspositionCipher(SymmetricKeyCipher):
    138138    """
     
    178178            sage: E == loads(dumps(E))
    179179            True
    180180        """
    181         n = parent.block_length()
    182         if isinstance(key, list) and not len(key) == n:
    183             raise ValueError, "key (= %s) must have block length %s" % (key, n)
    184         SymmetricKeyCipher.__init__(self, parent, key)
     181        n = parent.block_length()
     182        if isinstance(key, list) and not len(key) == n:
     183            raise ValueError, "key (= %s) must have block length %s" % (key, n)
     184        SymmetricKeyCipher.__init__(self, parent, key)
    185185
    186186    def __call__(self, M, mode = "ECB"):
    187         S = self.domain() # = plaintext_space = ciphertext_space
    188         if not isinstance(M, StringMonoidElement) and M.parent() == S:
    189             raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
    190         if not mode == "ECB":
    191             raise NotImplementedError, "Enciphering not implemented for mode (= %s) other than 'ECB'." % mode
    192         g = self.key()
    193         N = len(M)
    194         m = self.parent().block_length()
    195         if not N%m == 0:
    196             raise TypeError, "Argument M (= %s) must be a string of length k*%s." % (M, m)
    197         Melt = M._element_list # this uses the internal structure of string monoids
    198         # Caution: this is parsed as an outer loop in k and an inner loop in i:
    199         #     for k in range(N//m):
    200         #         for i in range(m):
    201         #             S([ Melt[g(i+1)-1+k*m]
    202         return S([ Melt[g(i+1)-1+k*m] for k in range(N//m) for i in range(m) ])
     187        S = self.domain() # = plaintext_space = ciphertext_space
     188        if not isinstance(M, StringMonoidElement) and M.parent() == S:
     189            raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
     190        if not mode == "ECB":
     191            raise NotImplementedError, "Enciphering not implemented for mode (= %s) other than 'ECB'." % mode
     192        g = self.key()
     193        N = len(M)
     194        m = self.parent().block_length()
     195        if not N%m == 0:
     196            raise TypeError, "Argument M (= %s) must be a string of length k*%s." % (M, m)
     197        Melt = M._element_list # this uses the internal structure of string monoids
     198        # Caution: this is parsed as an outer loop in k and an inner loop in i:
     199        #     for k in range(N//m):
     200        #         for i in range(m):
     201        #             S([ Melt[g(i+1)-1+k*m]
     202        return S([ Melt[g(i+1)-1+k*m] for k in range(N//m) for i in range(m) ])
    203203
    204204    def inverse(self):
    205205        E = self.parent()
    206         K = E.inverse_key(self.key())
    207         return E(K)
     206        K = E.inverse_key(self.key())
     207        return E(K)
    208208
    209209class VigenereCipher(SymmetricKeyCipher):
    210210    """
     
    233233            sage: E == loads(dumps(E))
    234234            True
    235235        """
    236         SymmetricKeyCipher.__init__(self, parent, key)
     236        SymmetricKeyCipher.__init__(self, parent, key)
    237237
    238238    def __call__(self, M, mode = "ECB"):
    239         S = self.domain() # = plaintext_space = ciphertext_space
    240         if not isinstance(M, StringMonoidElement) and M.parent() == S:
    241             raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
    242         if not mode == "ECB":
    243             raise NotImplementedError, "Enciphering not implemented for mode (= %s) other than 'ECB'." % mode
    244         K = self.key()
    245         m = self.parent().period()
    246         n = S.ngens()
    247         # This uses the internal structure of string monoids
    248         Melt = M._element_list
    249         Kelt = K._element_list
    250         return S([ (Melt[i]+Kelt[i%m])%n for i in range(len(M)) ])
     239        S = self.domain() # = plaintext_space = ciphertext_space
     240        if not isinstance(M, StringMonoidElement) and M.parent() == S:
     241            raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M
     242        if not mode == "ECB":
     243            raise NotImplementedError, "Enciphering not implemented for mode (= %s) other than 'ECB'." % mode
     244        K = self.key()
     245        m = self.parent().period()
     246        n = S.ngens()
     247        # This uses the internal structure of string monoids
     248        Melt = M._element_list
     249        Kelt = K._element_list
     250        return S([ (Melt[i]+Kelt[i%m])%n for i in range(len(M)) ])
    251251
    252252    def inverse(self):
    253253        E = self.parent()
    254         K = E.inverse_key(self.key())
    255         return E(K)
     254        K = E.inverse_key(self.key())
     255        return E(K)
    256256
    257257
    258258
  • sage/crypto/cryptosystem.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/cryptosystem.py
    a b  
    5151      key.
    5252      """
    5353      def __init__(self, plaintext_space, ciphertext_space, key_space, block_length = 1, period = None):
    54           self._cipher_domain = plaintext_space  
    55           self._cipher_codomain = ciphertext_space
    56           self._key_space = key_space
    57           self._block_length = block_length
    58           self._period = period
     54          self._cipher_domain = plaintext_space  
     55          self._cipher_codomain = ciphertext_space
     56          self._key_space = key_space
     57          self._block_length = block_length
     58          self._period = period
    5959
    6060      def __eq__(self,right):
    6161            return type(self) == type(right) and  \
     
    6767
    6868     
    6969      def plaintext_space(self):
    70           return self._cipher_domain
     70          return self._cipher_domain
    7171
    7272      def cipher_domain(self):
    73           return self._cipher_domain
     73          return self._cipher_domain
    7474
    7575      def ciphertext_space(self):
    76           return self._cipher_codomain
     76          return self._cipher_codomain
    7777
    7878      def cipher_codomain(self):
    79           return self._cipher_codomain
     79          return self._cipher_codomain
    8080
    8181      def key_space(self):
    82           return self._key_space
     82          return self._key_space
    8383
    8484      def block_length(self):
    8585          return self._block_length
    8686
    8787      def period(self):
    88           if self._period is None:
    89               raise TypeError, "Argument has no associated period."
    90           return self._period
     88          if self._period is None:
     89              raise TypeError, "Argument has no associated period."
     90          return self._period
    9191
    9292class SymmetricKeyCryptosystem(Cryptosystem):
    9393      """
  • sage/crypto/lfsr.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/lfsr.py
    a b  
    307307      IEEE Trans. Inform. Theory, vol. IT-15, pp. 122-127, Jan. 19 69.
    308308    """
    309309    # Initialization:
    310     FF = s[0].base_ring()       
     310    FF = s[0].base_ring()
    311311    R = PolynomialRing(FF, "x")
    312312    x = R.gen()
    313313    C = R(1); B = R(1); m = 1; b = FF(1); L = 0; N = 0
  • sage/crypto/mq/mpolynomialsystem.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/mq/mpolynomialsystem.py
    a b  
    150150        R = arg1.ring()
    151151        rounds = arg1.gens()
    152152    elif isinstance(arg1, (list,tuple)):
    153         rounds = arg1
    154         R = iter(rounds).next().parent()
    155         for f in rounds:
    156             if f.parent() is not R:
    157                 raise TypeError("Generators must have same parent.")
     153        rounds = arg1
     154        R = iter(rounds).next().parent()
     155        for f in rounds:
     156            if f.parent() is not R:
     157                raise TypeError("Generators must have same parent.")
    158158    else:
    159159        raise TypeError, "first parameter must be a MPolynomialRing"           
    160160
     
    198198            self._gens = list(gens)
    199199
    200200    def __copy__(self):
    201         """
    202         Return a copy of this round system.
    203        
    204         EXAMPLE::
    205        
     201        """
     202        Return a copy of this round system.
     203       
     204        EXAMPLE::
     205       
    206206            sage: sr = mq.SR(allow_zero_inversions=True)
    207207            sage: F,s = sr.polynomial_system()
    208             sage: r = F.round(0)
     208            sage: r = F.round(0)
    209209            sage: copy(r)
    210             [w100 + k000 + (a^3 + a + 1), w101 + k001 + (a^3 + 1),
    211             w102 + k002 + (a^3 + a^2 + 1), w103 + k003 + (a^3 + a^2 +
    212             a)]
    213         """
    214         return MPolynomialRoundSystem_generic(self._ring, list(self._gens))
     210            [w100 + k000 + (a^3 + a + 1), w101 + k001 + (a^3 + 1),
     211            w102 + k002 + (a^3 + a^2 + 1), w103 + k003 + (a^3 + a^2 +
     212            a)]
     213        """
     214        return MPolynomialRoundSystem_generic(self._ring, list(self._gens))
    215215
    216216    def __cmp__(self, other):
    217217        """
     
    546546                raise TypeError, "parameter not supported"
    547547
    548548    def __copy__(self):
    549         """
    550         Return a copy of self. While this is not a deep copy, only mutable
    551         members of this system are copied.
    552        
    553         EXAMPLE::
    554        
     549        """
     550        Return a copy of self. While this is not a deep copy, only mutable
     551        members of this system are copied.
     552       
     553        EXAMPLE::
     554       
    555555            sage: sr = mq.SR(allow_zero_inversions=True)
    556556            sage: F,s = sr.polynomial_system()
    557557            sage: copy(F) # indirect doctest
    558             Polynomial System with 40 Polynomials in 20 Variables
    559         """
    560         return MPolynomialSystem_generic(self._ring, [r.__copy__() for r in self._rounds])
     558            Polynomial System with 40 Polynomials in 20 Variables
     559        """
     560        return MPolynomialSystem_generic(self._ring, [r.__copy__() for r in self._rounds])
    561561
    562562    def __cmp__(self, other):
    563563        """
  • sage/crypto/stream.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/crypto/stream.py
    a b  
    4646        implementation is limited to the finite field of 2 elements only
    4747        because of the dependence on binary strings.
    4848        """
    49         if field is None:
    50            field = FiniteField(2)
    51         if field.cardinality() != 2:
    52             raise NotImplementedError, "Not yet implemented."
    53         S = BinaryStrings()
    54         P = PolynomialRing(FiniteField(2),'x')
     49        if field is None:
     50           field = FiniteField(2)
     51        if field.cardinality() != 2:
     52            raise NotImplementedError, "Not yet implemented."
     53        S = BinaryStrings()
     54        P = PolynomialRing(FiniteField(2),'x')
    5555        SymmetricKeyCryptosystem.__init__(self, S, S, None)
    56         self._field = field
     56        self._field = field
    5757
    5858    def __eq__(self,right):
    5959        return type(self) == type(right) and self._field == right._field
     
    6464       
    6565        INPUT: A polynomial and inital state of the LFSR.
    6666        """       
    67         if not isinstance(key, (list,tuple)) and len(key) == 2:
    68             raise TypeError, "Argument key (= %s) must be a list of tuple of length 2" % key
    69         poly = key[0]; IS = key[1]
     67        if not isinstance(key, (list,tuple)) and len(key) == 2:
     68            raise TypeError, "Argument key (= %s) must be a list of tuple of length 2" % key
     69        poly = key[0]; IS = key[1]
    7070        if not is_Polynomial(poly):
    7171            raise TypeError, "poly (= %s) must be a polynomial." % poly
    7272        if not isinstance(IS, (list,tuple)):
    7373            raise TypeError, "IS (= %s) must be an initial in the key space."%K
    7474        if len(IS) != poly.degree():
    7575            raise TypeError, \
    76                 "The length of IS (= %s) must equal the degree of poly (= %s)" % (IS, poly)
     76                "The length of IS (= %s) must equal the degree of poly (= %s)" % (IS, poly)
    7777        return LFSRCipher(self, poly, IS)
    7878
    7979    def __repr__(self):
    8080        return "LFSR cryptosystem over %s" % self._field
    8181
    8282    def encoding(self,M):
    83         S = self.cipher_domain()
    84         try:
    85             return S.encoding(M)
    86         except:
    87             raise TypeError, "Argument M = %s does not encode in the cipher domain" % M
     83        S = self.cipher_domain()
     84        try:
     85            return S.encoding(M)
     86        except:
     87            raise TypeError, "Argument M = %s does not encode in the cipher domain" % M
    8888
    8989class ShrinkingGeneratorCryptosystem(SymmetricKeyCryptosystem):
    9090    """
     
    104104            sage: E
    105105                   Shrinking generator cryptosystem over Finite Field of size 2
    106106        """
    107         if field is None:
    108            field = FiniteField(2)
    109         if field.cardinality() != 2:
    110             raise NotImplementedError, "Not yet implemented."
    111         S = BinaryStrings()
    112         P = PolynomialRing(field, 'x')
     107        if field is None:
     108           field = FiniteField(2)
     109        if field.cardinality() != 2:
     110            raise NotImplementedError, "Not yet implemented."
     111        S = BinaryStrings()
     112        P = PolynomialRing(field, 'x')
    113113        SymmetricKeyCryptosystem.__init__(self, S, S, None)
    114         self._field = field
     114        self._field = field
    115115
    116116    def __call__(self, key):
    117117        """
     
    122122        OUTPUT: The shrinking generator cipher with key stream generator e1
    123123        and decimating cipher e2.
    124124        """       
    125         if not isinstance(key, (list,tuple)) and len(key) == 2:
    126             raise TypeError, "Argument key (= %s) must be a list of tuple of length 2" % key
    127         e1 = key[0]; e2 = key[1]
     125        if not isinstance(key, (list,tuple)) and len(key) == 2:
     126            raise TypeError, "Argument key (= %s) must be a list of tuple of length 2" % key
     127        e1 = key[0]; e2 = key[1]
    128128        if not isinstance(e1, LFSRCipher) or not isinstance(e2, LFSRCipher):
    129129            raise TypeError, "The key (= (%s,%s)) must be a tuple of two LFSR ciphers." % key
    130130        return ShrinkingGeneratorCipher(self, e1, e2)
     
    133133        return "Shrinking generator cryptosystem over %s" % self._field
    134134
    135135    def encoding(self,M):
    136         S = self.cipher_domain()
    137         try:
    138             return S.encoding(M)
    139         except:
    140             raise TypeError, "Argument M = %s does not encode in the cipher domain" % M
     136        S = self.cipher_domain()
     137        try:
     138            return S.encoding(M)
     139        except:
     140            raise TypeError, "Argument M = %s does not encode in the cipher domain" % M
    141141
    142142
  • sage/databases/compressed_storage.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/databases/compressed_storage.py
    a b  
    3030
    3131# This is the original copyright notice:
    3232#
    33 #       $Id$
     33#       $Id$
    3434#
    3535# Copyright (c) 1999 Tyler C. Sarna (tsarna@endicor.com)
    3636# All rights reserved.
  • sage/dsage/interface/dsage_interface.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/dsage/interface/dsage_interface.py
    a b  
    992992        """
    993993        Resubmits the current job.
    994994        """
    995         from twisted.internet import reactor
     995        from twisted.internet import reactor
    996996        self.job_id = blockingCallFromThread(reactor,
    997997                                             self._remoteobj.callRemote,
    998998                                             'submit_job', self._jdict)
  • sage/ext/interactive_constructors_c.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/ext/interactive_constructors_c.pyx
    a b  
    4141        sage: GF(9,'c')
    4242        Finite Field in c of size 3^2
    4343        sage: c^3
    44                 2*c + 1
     44        2*c + 1
    4545
    4646    ROLL YOUR OWN: If a constructor you would like to auto inject
    4747    variables isn't made to do so by running this command your options
  • sage/functions/constants.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/functions/constants.py
    a b  
    11441144            NaN
    11451145        """
    11461146        Constant.__init__(self,
    1147             {'matlab':'NaN'})
     1147            {'matlab':'NaN'})
    11481148   
    11491149    def _repr_(self, simplify=True):
    11501150        """
     
    12201220            golden_ratio
    12211221        """
    12221222        Constant.__init__(self,{'mathematica':'N[(1+Sqrt[5])/2]','gp':'(1+sqrt(5))/2',
    1223                                 'maple':'(1+sqrt(5))/2','maxima':'(1+sqrt(5))/2',
    1224                                 'pari':'(1+sqrt(5))/2','octave':'(1+sqrt(5))/2',
    1225                                 'kash':'(1+Sqrt(5))/2'})
     1223                                'maple':'(1+sqrt(5))/2','maxima':'(1+sqrt(5))/2',
     1224                                'pari':'(1+sqrt(5))/2','octave':'(1+sqrt(5))/2',
     1225                                'kash':'(1+Sqrt(5))/2'})
    12261226    def _repr_(self, simplify=True):
    12271227        """
    12281228        EXAMPLES::
     
    12851285            sage: RealField(100)(golden_ratio)
    12861286            1.6180339887498948482045868344
    12871287        """
    1288         return (R(1)+R(5).sqrt())/R(2)
     1288        return (R(1)+R(5).sqrt())/R(2)
    12891289
    12901290    def _algebraic_(self, field):
    12911291        """
     
    13501350            log2
    13511351        """
    13521352        Constant.__init__(self,{'mathematica':'N[Log[2]]','kash':'Log(2)',
    1353                                 'maple':'log(2)','maxima':'log(2)','gp':'log(2)',
    1354                                 'pari':'log(2)','octave':'log(2)'})
     1353                                'maple':'log(2)','maxima':'log(2)','gp':'log(2)',
     1354                                'pari':'log(2)','octave':'log(2)'})
    13551355
    13561356    def _repr_(self, simplify=True):
    13571357        """
     
    14471447            euler_gamma
    14481448        """
    14491449        Constant.__init__(self,
    1450             {'kash':'EulerGamma(R)','maple':'gamma',
     1450            {'kash':'EulerGamma(R)','maple':'gamma',
    14511451             'mathematica':'EulerGamma','pari':'Euler',
    14521452             'maxima':'%gamma', 'maxima':'euler_gamma'})   
    14531453
     
    16721672            sage: RDF(khinchin)
    16731673            2.68545200107
    16741674        """
    1675         return R('2.685452001065306445309714835481795693820')
     1675        return R('2.685452001065306445309714835481795693820')
    16761676
    16771677       
    16781678    def __float__(self):
     
    17201720            twinprime
    17211721        """
    17221722        Constant.__init__(self,{'maxima':'twinprime'}) #Twin prime is not implemented in any other algebra systems.
    1723        
     1723       
    17241724        #digits come from http://www.gn-50uma.de/alula/essays/Moree/Moree-details.en.shtml
    1725        
     1725       
    17261726        self.__value = "0.660161815846869573927812110014555778432623360284733413319448423335405642304495277143760031413839867911779005226693304002965847755123366227747165713213986968741097620630214153735434853131596097803669932135255299767199302474590593101082978291553834469297505205916657133653611991532464281301172462306379341060056466676584434063501649322723528968010934966475600478812357962789459842433655749375581854814173628678098705969498703841243363386589311969079150040573717814371081810615401233104810577794415613125444598860988997585328984038108718035525261719887112136382808782349722374224097142697441764455225265548994829771790977784043757891956590649994567062907828608828395990394287082529070521554595671723599449769037800675978761690802426600295711092099633708272559284672129858001148697941855401824639887493941711828528382365997050328725708087980662201068630474305201992394282014311102297265141514194258422242375342296879836738796224286600285358098482833679152235700192585875285961205994728621007171131607980572"
    17271727
    17281728        self.__bits = len(self.__value)*3-1   # underestimate
     
    17711771            sage: RDF(twinprime)
    17721772            0.660161815847
    17731773        """
    1774         return R('0.660161815846869573927812110014555778432')
     1774        return R('0.660161815846869573927812110014555778432')
    17751775
    17761776       
    17771777    def __float__(self):
     
    17811781            sage: float(twinprime)
    17821782            0.66016181584686962
    17831783        """
    1784         return 0.660161815846869573927812110014555778432
     1784        return 0.660161815846869573927812110014555778432
    17851785
    17861786twinprime = TwinPrime()
    17871787
     
    18691869            sage: float(merten)
    18701870            0.26149721284764277
    18711871        """
    1872         return 0.261497212847642783755426838608695859051
     1872        return 0.261497212847642783755426838608695859051
    18731873
    18741874
    18751875merten = Merten()
     
    19601960            sage: float(brun)
    19611961            1.902160583104
    19621962        """
    1963         return 1.9021605831040
     1963        return 1.9021605831040
    19641964
    19651965brun=Brun()
    19661966
  • sage/functions/functions.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/functions/functions.py
    a b  
    298298            raise TypeError, "these objects are not comparable"
    299299        if c: return c
    300300        try:
    301             return cmp(maxima(self),maxima(right))
    302         except TypeError:
    303             pass
     301            return cmp(maxima(self),maxima(right))
     302        except TypeError:
     303            pass
    304304        raise NotImplementedError, "equality testing for general mathematical functions not yet implemented (can't prove equality)."
    305305
    306306
  • sage/functions/piecewise.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/functions/piecewise.py
    a b  
    190190            self.length(),self.list())
    191191 
    192192    def _latex_(self):
    193         r"""
    194         EXAMPLES::
    195        
    196             sage: f1(x) = 1
    197             sage: f2(x) = 1 - x
    198             sage: f = Piecewise([[(0,1),f1],[(1,2),f2]])
    199             sage: latex(f)
    200             \begin{cases}
    201             x \ {\mapsto}\ 1 &\text{on $(0, 1)$}\cr
    202             x \ {\mapsto}\ 1 - x &\text{on $(1, 2)$}\cr
    203             \end{cases}
    204        
    205         ::
    206        
    207             sage: f(x) = sin(x*pi/2)
    208             sage: g(x) = 1-(x-1)^2
    209             sage: h(x) = -x
    210             sage: P = Piecewise([[(0,1), f], [(1,3),g], [(3,5), h]])
    211             sage: latex(P)
    212             \begin{cases}
    213             x \ {\mapsto}\ \sin \left( \frac{{\pi x}}{2} \right) &\text{on $(0, 1)$}\cr
    214             x \ {\mapsto}\ 1 - {\left( x - 1 \right)}^{2}  &\text{on $(1, 3)$}\cr
    215             x \ {\mapsto}\ -x &\text{on  $(3, 5)$}\cr
    216             \end{cases}
    217         """
     193        r"""
     194        EXAMPLES::
     195       
     196            sage: f1(x) = 1
     197            sage: f2(x) = 1 - x
     198            sage: f = Piecewise([[(0,1),f1],[(1,2),f2]])
     199            sage: latex(f)
     200            \begin{cases}
     201            x \ {\mapsto}\ 1 &\text{on $(0, 1)$}\cr
     202            x \ {\mapsto}\ 1 - x &\text{on $(1, 2)$}\cr
     203            \end{cases}
     204       
     205        ::
     206       
     207            sage: f(x) = sin(x*pi/2)
     208            sage: g(x) = 1-(x-1)^2
     209            sage: h(x) = -x
     210            sage: P = Piecewise([[(0,1), f], [(1,3),g], [(3,5), h]])
     211            sage: latex(P)
     212            \begin{cases}
     213            x \ {\mapsto}\ \sin \left( \frac{{\pi x}}{2} \right) &\text{on $(0, 1)$}\cr
     214            x \ {\mapsto}\ 1 - {\left( x - 1 \right)}^{2}  &\text{on $(1, 3)$}\cr
     215            x \ {\mapsto}\ -x &\text{on  $(3, 5)$}\cr
     216            \end{cases}
     217        """
    218218        from sage.misc.latex import latex
    219219        tex = ['\\begin{cases}\n']
    220220        for (left, right), f in self.list():
     
    11361136            -3*sin(2*x)/pi + 3*sin(x)/pi - 3*cos(x)/pi - 1/4
    11371137        """
    11381138        return self._fourier_series_helper(N, L, lambda n: F[n])
    1139        
     1139       
    11401140    def plot_fourier_series_partial_sum(self,N,L,xmin,xmax, **kwds):
    11411141        r"""
    11421142        Plots the partial sum
     
    12281228        """     
    12291229        from sage.plot.all import plot
    12301230        return plot(self.fourier_series_partial_sum_hann(N,L), xmin, xmax, **kwds)
    1231        
     1231       
    12321232    def plot_fourier_series_partial_sum_filtered(self,N,L,F,xmin,xmax, **kwds):
    12331233        r"""
    12341234        Plots the partial sum
     
    12601260        """
    12611261        from sage.plot.all import plot
    12621262        return plot(self.fourier_series_partial_sum_filtered(N,L,F), xmin, xmax, **kwds)
    1263                
     1263               
    12641264    def fourier_series_value(self,x,L):
    12651265        r"""
    12661266        Returns the value of the Fourier series coefficient of self at
     
    14981498   
    14991499    def __add__(self,other):
    15001500        """
    1501         Returns the piecewise defined function which is the sum of self and
    1502         other. Does not require both domains be the same.
    1503        
    1504         EXAMPLES::
    1505        
    1506             sage: x = PolynomialRing(QQ,'x').gen()
    1507             sage: f1 = x^0
     1501        Returns the piecewise defined function which is the sum of self and
     1502        other. Does not require both domains be the same.
     1503       
     1504        EXAMPLES::
     1505       
     1506            sage: x = PolynomialRing(QQ,'x').gen()
     1507            sage: f1 = x^0
    15081508            sage: f2 = 1-x
    15091509            sage: f3 = 2*x
    15101510            sage: f4 = 10-x
    15111511            sage: f = Piecewise([[(0,1),f1],[(1,2),f2],[(2,3),f3],[(3,10),f4]])
    1512             sage: g1 = x-2
     1512            sage: g1 = x-2
    15131513            sage: g2 = x-5
    15141514            sage: g = Piecewise([[(0,5),g1],[(5,10),g2]])
    1515             sage: h = f+g
    1516             sage: h
     1515            sage: h = f+g
     1516            sage: h
    15171517            Piecewise defined function with 5 parts, [[(0, 1), x - 1], [(1, 2), -1], [(2, 3), 3*x - 2], [(3, 5), 8], [(5, 10), 5]]
    1518        
    1519         Note that in this case the functions must be defined using
    1520         polynomial expressions *not* using the lambda notation.
    1521         """
     1518       
     1519        Note that in this case the functions must be defined using
     1520        polynomial expressions *not* using the lambda notation.
     1521        """
    15221522        F, G, intervals = self._make_compatible(other)
    15231523        fcn = []
    15241524        for a,b in intervals:
    1525             fcn.append([(a,b), F.which_function(b)+G.which_function(b)])       
     1525            fcn.append([(a,b), F.which_function(b)+G.which_function(b)])       
    15261526        return Piecewise(fcn)
    1527        
     1527       
    15281528    def __mul__(self,other):
    15291529        r"""
    1530         Returns the piecewise defined function which is the product of one
    1531         piecewise function (self) with another one (other).
    1532        
    1533         EXAMPLES::
    1534        
    1535             sage: x = PolynomialRing(QQ,'x').gen()
    1536             sage: f1 = x^0
     1530        Returns the piecewise defined function which is the product of one
     1531        piecewise function (self) with another one (other).
     1532       
     1533        EXAMPLES::
     1534       
     1535            sage: x = PolynomialRing(QQ,'x').gen()
     1536            sage: f1 = x^0
    15371537            sage: f2 = 1-x
    15381538            sage: f3 = 2*x
    15391539            sage: f4 = 10-x
    15401540            sage: f = Piecewise([[(0,1),f1],[(1,2),f2],[(2,3),f3],[(3,10),f4]])
    1541             sage: g1 = x-2
     1541            sage: g1 = x-2
    15421542            sage: g2 = x-5
    15431543            sage: g = Piecewise([[(0,5),g1],[(5,10),g2]])
    1544             sage: h = f*g
    1545             sage: h
    1546             Piecewise defined function with 5 parts, [[(0, 1), x - 2], [(1, 2), -x^2 + 3*x - 2], [(2, 3), 2*x^2 - 4*x], [(3, 5), -x^2 + 12*x - 20], [(5, 10), -x^2 + 15*x - 50]]
     1544            sage: h = f*g
     1545            sage: h
     1546            Piecewise defined function with 5 parts, [[(0, 1), x - 2], [(1, 2), -x^2 + 3*x - 2], [(2, 3), 2*x^2 - 4*x], [(3, 5), -x^2 + 12*x - 20], [(5, 10), -x^2 + 15*x - 50]]
    15471547            sage: g*(11/2)
    15481548            Piecewise defined function with 2 parts, [[(0, 5), 11/2*x - 11], [(5, 10), 11/2*x - 55/2]]
    15491549           
    1550         Note that in this method the functions must be defined using
    1551         polynomial expressions *not* using the lambda notation.
    1552         """
     1550        Note that in this method the functions must be defined using
     1551        polynomial expressions *not* using the lambda notation.
     1552        """
    15531553        ## needed for scalar multiplication
    15541554        if isinstance(other,Rational) or isinstance(other,Integer):
    15551555            return Piecewise([[(a,b), other*f] for (a,b),f in self.list()])
     
    15571557            F, G, intervals = self._make_compatible(other)
    15581558            fcn = []
    15591559            for a,b in intervals:
    1560                 fcn.append([(a,b),F.which_function(b)*G.which_function(b)])     
     1560                fcn.append([(a,b),F.which_function(b)*G.which_function(b)])     
    15611561            return Piecewise(fcn)
    15621562
    15631563    __rmul__ = __mul__
  • sage/geometry/polyhedra.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/geometry/polyhedra.py
    a b  
    7575    answer._vertices = temp_vertex_list
    7676    answer._remove_redundant_vertices()
    7777    if verbose:
    78         print 'Another pair of polytopes computed, sum has ' + str(len(answer._vertices)) + ' vertices'
     78        print 'Another pair of polytopes computed, sum has ' + str(len(answer._vertices)) + ' vertices'
    7979    if len(polyhedra_list) == 2:
    8080        return answer
    8181    else:
     
    9696            [[1, -1], [1, 1], [-1, 1], [-1, -1]]
    9797            sage: square_from_vertices.ieqs()
    9898            [[1, 0, 1], [1, 1, 0], [1, 0, -1], [1, -1, 0]]
    99             sage: p = Polyhedron(vertices = [[1.1, 2.2], [3.3, 4.4]], cdd_type = 'real')
    100             sage: len(p.ieqs())
    101             2
     99            sage: p = Polyhedron(vertices = [[1.1, 2.2], [3.3, 4.4]], cdd_type = 'real')
     100            sage: len(p.ieqs())
     101            2
    102102
    103103        NOTE:
    104104             Although the option cdd_type = 'real' allows numerical data to be used, its use is
    105105        discouraged - the results can depend upon the tolerance setting of cddlib, whose
    106106        default is rather large since cddlib was designed with rational and integer data in mind.
    107107        """
    108         self._cdd_type = cdd_type
     108        self._cdd_type = cdd_type
    109109        self._vertices = vertices
    110110        self._ieqs = ieqs
    111111        self._linearities = linearities
    112112        self._rays = rays
    113113        self._verbose = verbose
    114         if self._vertices != []:
    115             self._remove_redundant_vertices(cdd_type = self._cdd_type)
     114        if self._vertices != []:
     115            self._remove_redundant_vertices(cdd_type = self._cdd_type)
    116116        else:
    117117            if self._ieqs != []:
    118118                vertices = [x for x in self.vertices()]
     
    343343            sage: oct = polytopes.cross_polytope(3)
    344344            sage: cube_oct = cube.intersection(oct*2)
    345345            sage: cube_oct
    346             A Polyhedron with 12 vertices with 14 supporting hyperplanes.
     346            A Polyhedron with 12 vertices with 14 supporting hyperplanes.
    347347            sage: len(cube_oct.vertices())
    348348            12
    349349            sage: cube_oct
     
    363363            A Polyhedron object, truncated as described above.
    364364
    365365        EXAMPLES:
    366         Truncating a cube:
    367             sage: cube = polytopes.n_cube(3)
    368             sage: trunc_cube = cube.edge_truncation()
    369             sage: trunc_cube.n_vertices()
    370             24
    371             sage: trunc_cube.n_facets()
    372             14
     366        Truncating a cube:
     367            sage: cube = polytopes.n_cube(3)
     368            sage: trunc_cube = cube.edge_truncation()
     369            sage: trunc_cube.n_vertices()
     370            24
     371            sage: trunc_cube.n_facets()
     372            14
    373373        """
    374374        new_verts = []
    375375        old_verts = [vector(x) for x in self.vertices()]
     
    742742            If the figure is already composed of triangles, then all is well
    743743            sage: Polyhedron(vertices = [[5,0,0],[0,5,0],[5,5,0],[2,2,5]]).triangulated_facial_incidences()
    744744            [[0, [0, 2, 3]], [1, [0, 1, 2]], [2, [1, 2, 3]], [3, [0, 1, 3]]]
    745                              
    746             Otherwise some faces get split up to triangles
    747             sage: Polyhedron(vertices = [[2,0,0],[4,1,0],[0,5,0],[5,5,0],[1,1,0],[0,0,1]]).triangulated_facial_incidences()
     745                             
     746            Otherwise some faces get split up to triangles
     747            sage: Polyhedron(vertices = [[2,0,0],[4,1,0],[0,5,0],[5,5,0],[1,1,0],[0,0,1]]).triangulated_facial_incidences()
    748748            [[0, [0, 1, 5]], [1, [0, 4, 5]], [2, [2, 4, 5]], [3, [2, 3, 5]], [4, [1, 3, 5]], [5, [0, 4, 1]], [5, [4, 1, 2]], [5, [1, 2, 3]]]
    749749
    750750        """
     
    774774                            t_fac_incs.append([a_face[0], [self.vertices().index(q) for q in proj_verts]])
    775775                else:
    776776                    vs = a_face[1]
    777                     adj = dict([a[0], filter(lambda p: p in a_face[1], a[1])] for a in filter(lambda va: va[0] in a_face[1], self.vertex_adjacencies()))
    778                     t = vs[0]
     777                    adj = dict([a[0], filter(lambda p: p in a_face[1], a[1])] for a in filter(lambda va: va[0] in a_face[1], self.vertex_adjacencies()))
     778                    t = vs[0]
    779779                    vs.remove(t)
    780780                    ts = adj[t]
    781781                    for v in ts:
     
    12221222    in_length = len(in_list[0])
    12231223    in_str = 'H-representation\n'
    12241224    if linearities != []:
    1225         in_str += 'linearity ' + str(len(linearities)) + ' '
     1225        in_str += 'linearity ' + str(len(linearities)) + ' '
    12261226        for index in range(len(linearities)):
    1227             in_str += str(index+1) + ' '
     1227            in_str += str(index+1) + ' '
    12281228    in_str += '\n'
    12291229    in_str += 'begin\n'
    12301230    in_str += str(len(in_list)+len(linearities)) + ' ' + str(in_length) + ' ' + cdd_type + '\n'
    12311231    if linearities != []:
    12321232        for lin in linearities:
    1233             for numb in lin:
    1234                 in_str += str(numb) + ' '
     1233            for numb in lin:
     1234                in_str += str(numb) + ' '
    12351235            in_str += '\n'
    12361236    for ieq in in_list:
    12371237        for numb in ieq:
     
    14421442        Returns a dodecahedron. The vertices are
    14431443        rational, so a rational approximation of the golden ratio
    14441444        is used.
    1445        
    1446         EXAMPLES:
    1447             sage: d12 = polytopes.dodecahedron()
    1448             sage: d12.n_facets()
    1449             12
     1445       
     1446        EXAMPLES:
     1447            sage: d12 = polytopes.dodecahedron()
     1448            sage: d12.n_facets()
     1449            12
    14501450        """
    14511451        return self.icosahedron().polar()
    14521452
     
    14541454        """
    14551455        An Archimedean solid with 24 vertices and 26 faces.
    14561456
    1457         EXAMPLES:
    1458             sage: sr = polytopes.small_rhombicuboctahedron()
    1459             sage: sr.n_vertices()
    1460             24
    1461             sage: sr.n_facets()
    1462             26
     1457        EXAMPLES:
     1458            sage: sr = polytopes.small_rhombicuboctahedron()
     1459            sage: sr.n_vertices()
     1460            24
     1461            sage: sr.n_facets()
     1462            26
    14631463        """
    14641464        verts = [[-3/2, -1/2, -1/2], [-3/2, -1/2, 1/2], [-3/2, 1/2, -1/2], [-3/2, 1/2,
    146514651/2], [-1/2, -3/2, -1/2], [-1/2, -3/2, 1/2], [-1/2, -1/2, -3/2], [-1/2,
     
    14741474        """
    14751475        An Archimedean solid with 48 vertices and 26 faces.
    14761476
    1477         EXAMPLES:
    1478             sage: gr = polytopes.great_rhombicuboctahedron()
    1479             sage: gr.n_vertices()
    1480             48
    1481             sage: gr.n_facets()
    1482             26
     1477        EXAMPLES:
     1478            sage: gr = polytopes.great_rhombicuboctahedron()
     1479            sage: gr.n_vertices()
     1480            48
     1481            sage: gr.n_facets()
     1482            26
    14831483        """
    14841484        sqr2 = 77171371357/54568400000 #sqrt(2) approximation
    14851485        verts = [[1, 131739771357/54568400000, 104455571357/27284200000], [1, 104455571357/27284200000, 131739771357/54568400000], [131739771357/54568400000, 1, 104455571357/27284200000], [131739771357/54568400000, 104455571357/27284200000, 1], [104455571357/27284200000, 1, 131739771357/54568400000], [104455571357/27284200000, 131739771357/54568400000, 1]]
     
    14931493        This face-regular, vertex-uniform polytope is dual to the
    14941494        cuboctahedron. It has 14 vertices and 12 faces.
    14951495
    1496         EXAMPLES:
    1497             sage: rd = polytopes.rhombic_dodecahedron()
    1498             sage: rd.n_vertices()
    1499             14
    1500             sage: rd.n_facets()
    1501             12
     1496        EXAMPLES:
     1497            sage: rd = polytopes.rhombic_dodecahedron()
     1498            sage: rd.n_vertices()
     1499            14
     1500            sage: rd.n_facets()
     1501            12
    15021502        """
    1503         return Polyhedron(vertices = [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1], [0, 0, 2], [0, 2, 0], [2, 0, 0], [0, 0, -2], [0, -2, 0], [-2, 0, 0]])
     1503        return Polyhedron(vertices = [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1], [0, 0, 2], [0, 2, 0], [2, 0, 0], [0, 0, -2], [0, -2, 0], [-2, 0, 0]])
    15041504        #return self.n_cube(3).union(2*self.cross_polytope(3))
    15051505
    15061506    def cuboctahedron(self):
     
    15081508        An Archimedean solid with 12 vertices and 14 faces.  Dual to
    15091509        the rhombic dodecahedron.
    15101510
    1511         EXAMPLES:
    1512             sage: co = polytopes.cuboctahedron()
    1513             sage: co.n_vertices()
    1514             12
    1515             sage: len(co.facial_incidences())
    1516             14
     1511        EXAMPLES:
     1512            sage: co = polytopes.cuboctahedron()
     1513            sage: co.n_vertices()
     1514            12
     1515            sage: len(co.facial_incidences())
     1516            14
    15171517        """
    15181518        one = Integer(1)
    15191519        verts = [[0, -one/2, -one/2], [0, one/2, -one/2], [one/2, -one/2, 0], [one/2, one/2, 0], [one/2, 0, one/2], [one/2, 0, -one/2], [0, one/2, one/2], [0, -one/2, one/2], [-one/2, 0, one/2], [-one/2, one/2, 0], [-one/2, 0, -one/2], [-one/2, -one/2, 0]]
     
    15241524        Also known as the truncated icosahedron, an Archimedean solid.
    15251525        It has 32 faces and 60 vertices.
    15261526
    1527         EXAMPLES:
    1528             sage: bb = polytopes.buckyball()
    1529             sage: bb.n_vertices()
    1530             60
    1531             sage: bb.n_facets()
    1532             32
     1527        EXAMPLES:
     1528            sage: bb = polytopes.buckyball()
     1529            sage: bb.n_vertices()
     1530            60
     1531            sage: bb.n_facets()
     1532            32
    15331533        """
    15341534        approx =  self.icosahedron().edge_truncation()
    15351535        # the approximate version has some facets broken, which we can fix:
    1536         approx_ieqs = approx.ieqs()
     1536        approx_ieqs = approx.ieqs()
    15371537        buck_ieqs = [x for x in approx_ieqs if QQ(912022)/618033 != x[0]]
    15381538        return Polyhedron(ieqs = buck_ieqs)
    15391539
     
    15421542        This face-regular, vertex-uniform polytope is dual to the
    15431543        truncated icosahedron.  It has 60 faces and 32 vertices.
    15441544
    1545         EXAMPLES:
    1546             sage: pd = polytopes.pentakis_dodecahedron() 
    1547             sage: pd.n_vertices()
    1548             32
    1549             sage: pd.n_facets()
    1550             60
     1545        EXAMPLES:
     1546            sage: pd = polytopes.pentakis_dodecahedron() 
     1547            sage: pd.n_vertices()
     1548            32
     1549            sage: pd.n_facets()
     1550            60
    15511551        """
    15521552        return self.buckyball().polar()
    15531553
  • sage/geometry/polytope.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/geometry/polytope.py
    a b  
    137137        F = tmp_file
    138138        open(F,'w').write(self.__data)
    139139        c = '%s %s %s'%(polymake_command, F, cmd)
    140         polymake_processes = Popen([polymake_command, F, cmd],stdout=PIPE,stderr=PIPE)
     140        polymake_processes = Popen([polymake_command, F, cmd],stdout=PIPE,stderr=PIPE)
    141141        ans, err = polymake_processes.communicate()
    142142        if len(err) > 0:
    143143            raise RuntimeError, err
  • sage/graphs/graph.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/graphs/graph.py
    a b  
    10061006        Note that any additional keywords will be pased on to either
    10071007        the adjacency_matrix or weighted_adjacency_matrix method.
    10081008
    1009         AUTHORS:
    1010              
     1009        AUTHORS:
     1010             
    10111011        - Tom Boothby
    10121012       
    10131013        EXAMPLES::
  • sage/graphs/graph_database.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/graphs/graph_database.py
    a b  
    411411               
    412412                # set expression
    413413                if not isinstance(kwds[key],list):
    414                                         if key == 'induced_subgraphs':
    415                                                 qdict['expression'] = [key, 'regexp', '.*%s.*'%(graph.Graph(kwds[key]).canonical_label()).graph6_string()]
    416                                         else:
    417                                                 qdict['expression'] = [key, '=', kwds[key]]
     414                                        if key == 'induced_subgraphs':
     415                                                qdict['expression'] = [key, 'regexp', '.*%s.*'%(graph.Graph(kwds[key]).canonical_label()).graph6_string()]
     416                                        else:
     417                                                qdict['expression'] = [key, '=', kwds[key]]
    418418                elif key == 'degree_sequence':
    419419                    qdict['expression'] = [key, '=', degseq_to_data(kwds[key])]
    420420                elif key != 'induced_subgraphs':
     
    445445           
    446446            # organize display
    447447            if display_cols is not None:
    448                                 for col in display_cols:
    449                                         if col in graph_data: graph_data_disp.append(col)
    450                                         elif col in aut_grp: aut_grp_disp.append(col)
    451                                         elif col in degrees: degrees_disp.append(col)
    452                                         elif col in misc: misc_disp.append(col)
    453                                         elif col in spectrum: spectrum_disp.append(col)
     448                                for col in display_cols:
     449                                        if col in graph_data: graph_data_disp.append(col)
     450                                        elif col in aut_grp: aut_grp_disp.append(col)
     451                                        elif col in degrees: degrees_disp.append(col)
     452                                        elif col in misc: misc_disp.append(col)
     453                                        elif col in spectrum: spectrum_disp.append(col)
    454454           
    455                                 # finish filling master join with display tables
    456                                 for tab in disp_tables:
    457                                         if len(tab) > 1:
    458                                                 master_join[tab[0]] = ('graph_id', 'graph_id')
    459                                
    460                                 # join clause for display tables
    461                                 join_str = 'FROM graph_data '
    462                                 for tab in master_join:
    463                                         join_str += 'INNER JOIN %s ON graph_data.graph_id=%s.graph_id '%(tab, tab)
    464                                
    465                                 # construct sql syntax substring for display cols
    466                                 disp_str = 'SELECT graph_data.graph6, '
    467                                 for col in graph_data_disp[1:]:
    468                                         if col != 'graph6': disp_str += 'graph_data.%s, '%col
    469                                 for col in aut_grp_disp[1:]: disp_str += 'aut_grp.%s, '%col
    470                                 for col in degrees_disp[1:]: disp_str += 'degrees.%s, '%col
    471                                 for col in misc_disp[1:]: disp_str += 'misc.%s, '%col
    472                                 for col in spectrum_disp[1:]: disp_str += 'spectrum.%s, '%col               
    473                                 disp_str = disp_str.rstrip(', ') + ' '
     455                                # finish filling master join with display tables
     456                                for tab in disp_tables:
     457                                        if len(tab) > 1:
     458                                                master_join[tab[0]] = ('graph_id', 'graph_id')
     459                               
     460                                # join clause for display tables
     461                                join_str = 'FROM graph_data '
     462                                for tab in master_join:
     463                                        join_str += 'INNER JOIN %s ON graph_data.graph_id=%s.graph_id '%(tab, tab)
     464                               
     465                                # construct sql syntax substring for display cols
     466                                disp_str = 'SELECT graph_data.graph6, '
     467                                for col in graph_data_disp[1:]:
     468                                        if col != 'graph6': disp_str += 'graph_data.%s, '%col
     469                                for col in aut_grp_disp[1:]: disp_str += 'aut_grp.%s, '%col
     470                                for col in degrees_disp[1:]: disp_str += 'degrees.%s, '%col
     471                                for col in misc_disp[1:]: disp_str += 'misc.%s, '%col
     472                                for col in spectrum_disp[1:]: disp_str += 'spectrum.%s, '%col               
     473                                disp_str = disp_str.rstrip(', ') + ' '
    474474
    475                                 # substitue disp_str and join_str back into self's query string
    476                                 self.__query_string__ = re.sub('SELECT.*WHERE ', disp_str + join_str + \
    477                                                                                                 'WHERE ', self.__query_string__)
     475                                # substitue disp_str and join_str back into self's query string
     476                                self.__query_string__ = re.sub('SELECT.*WHERE ', disp_str + join_str + \
     477                                                                                                'WHERE ', self.__query_string__)
    478478                   
    479479    def show(self, max_field_size=20, with_picture=False):
    480480        """
  • sage/groups/abelian_gps/abelian_group_morphism.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/abelian_gps/abelian_group_morphism.py
    a b  
    3636    A set-theoretic map between AbelianGroups.
    3737    """
    3838    def __init__(self, parent):
    39         Morphism.__init__(self, parent)
     39        Morphism.__init__(self, parent)
    4040
    4141    def _repr_type(self):
    4242        return "AbelianGroup"
     
    104104        self._codomain = H
    105105        if not(G.is_abelian()):
    106106            raise TypeError, "Sorry, the groups must be abelian groups."
    107         if not(H.is_abelian()):
     107        if not(H.is_abelian()):
    108108            raise TypeError, "Sorry, the groups must be abelian groups."
    109109        G_domain = G.subgroup(genss)
    110110        if G_domain.order() != G.order():
     
    134134            sage: phi._gap_init_()
    135135            'phi := GroupHomomorphismByImages(G,H,[x, y],[a, b])'
    136136        """
    137         G  = (self.domain())._gap_init_()
    138         H  = (self.range())._gap_init_()
     137        G  = (self.domain())._gap_init_()
     138        H  = (self.range())._gap_init_()
    139139        # print G,H
    140140        s3 = 'G:=%s; H:=%s'%(G,H)
    141141        #print s3,"\n"
     
    155155           cmd = ("%s := gensH["+str(i+1)+"]")%gensH[i]
    156156           #print i,"  \n",cmd
    157157           gap.eval(cmd)
    158         args = str(self.domaingens)+","+ str(self.codomaingens)
     158        args = str(self.domaingens)+","+ str(self.codomaingens)
    159159        #print args,"\n"
    160         gap.eval("phi := GroupHomomorphismByImages(G,H,"+args+")")
     160        gap.eval("phi := GroupHomomorphismByImages(G,H,"+args+")")
    161161        self.gap_hom_string = "phi := GroupHomomorphismByImages(G,H,"+args+")"
    162162        return self.gap_hom_string
    163163 
     
    221221
    222222    def __call__( self, g ):
    223223        """
    224         Some python code for wrapping GAP's Images function but only for
    225         permutation groups. Returns an error if g is not in G.
    226        
    227         EXAMPLES::
    228        
    229             sage: H = AbelianGroup(3, [2,3,4], names="abc")
    230             sage: a,b,c = H.gens()
    231             sage: G = AbelianGroup(2, [2,3], names="xy")
    232             sage: x,y = G.gens()
    233             sage: phi = AbelianGroupMorphism(G,H,[x,y],[a,b])
    234             sage: phi(y*x)
    235             a*b
    236             sage: phi(y^2)
    237             b^2
    238         """
     224        Some python code for wrapping GAP's Images function but only for
     225        permutation groups. Returns an error if g is not in G.
     226       
     227        EXAMPLES::
     228       
     229            sage: H = AbelianGroup(3, [2,3,4], names="abc")
     230            sage: a,b,c = H.gens()
     231            sage: G = AbelianGroup(2, [2,3], names="xy")
     232            sage: x,y = G.gens()
     233            sage: phi = AbelianGroupMorphism(G,H,[x,y],[a,b])
     234            sage: phi(y*x)
     235            a*b
     236            sage: phi(y^2)
     237            b^2
     238        """
    239239        G = g.parent()
    240240        w = g.word_problem(self.domaingens)
    241241        n = len(w)
     
    243243        # g.word_problem is faster in general than word_problem(g)
    244244        gens = self.codomaingens
    245245        h = prod([gens[(self.domaingens).index(w[i][0])]**(w[i][1]) for i in range(n)])
    246         return h
     246        return h
    247247
    248248
    249249
  • sage/groups/class_function.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/class_function.py
    a b  
    346346            Character of Symmetric group of order 5! as a permutation group
    347347            sage: H = G.subgroup([(1,2,3), (1,2), (4,5)])
    348348            sage: chi.restrict(H)
    349             Character of Subgroup of SymmetricGroup(5) generated by [(4,5), (1,2), (1,2,3)]
     349            Character of Subgroup of SymmetricGroup(5) generated by [(4,5), (1,2), (1,2,3)]
    350350            sage: chi.restrict(H).values()
    351351            [3, -3, -3, -1, 0, 0]
    352352        """
     
    359359            sage: G = SymmetricGroup(5)
    360360            sage: H = G.subgroup([(1,2,3), (1,2), (4,5)])
    361361            sage: xi = H.trivial_character(); xi
    362             Character of Subgroup of SymmetricGroup(5) generated by [(4,5), (1,2), (1,2,3)]
     362            Character of Subgroup of SymmetricGroup(5) generated by [(4,5), (1,2), (1,2,3)]
    363363            sage: xi.induct(G)
    364364            Character of Symmetric group of order 5! as a permutation group
    365365            sage: xi.induct(G).values()
  • sage/groups/matrix_gps/matrix_group.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/matrix_gps/matrix_group.py
    a b  
    10301030##             sage: gens = [MS([[1,0],[-1,1]]),MS([[1,1],[0,1]])]
    10311031##             sage: G = MatrixGroup(gens)
    10321032##             sage: G.conjugacy_class_representatives_gap()
    1033 ##          ['[ [ Z(3)^0, 0*Z(3) ], [ 0*Z(3), Z(3)^0 ] ]',
    1034 ##          '[ [ 0*Z(3), Z(3)^0 ], [ Z(3), Z(3)^0 ] ]',
     1033##          ['[ [ Z(3)^0, 0*Z(3) ], [ 0*Z(3), Z(3)^0 ] ]',
     1034##          '[ [ 0*Z(3), Z(3)^0 ], [ Z(3), Z(3)^0 ] ]',
    10351035##             '[ [ 0*Z(3), Z(3)^0 ], [ Z(3), Z(3) ] ]',
    10361036##             '[ [ 0*Z(3), Z(3) ], [ Z(3)^0, Z(3)^0 ] ]',
    1037 ##                  '[ [ 0*Z(3), Z(3) ], [ Z(3)^0, Z(3) ] ]',
    1038 ##                  '[ [ 0*Z(3), Z(3)^0 ], [ Z(3), 0*Z(3) ] ]',
    1039 ##          '[ [ Z(3), 0*Z(3) ], [ 0*Z(3), Z(3) ] ]']
     1037##                  '[ [ 0*Z(3), Z(3) ], [ Z(3)^0, Z(3) ] ]',
     1038##                  '[ [ 0*Z(3), Z(3)^0 ], [ Z(3), 0*Z(3) ] ]',
     1039##          '[ [ Z(3), 0*Z(3) ], [ 0*Z(3), Z(3) ] ]']
    10401040         
    10411041##         AUTHOR: David Joyner (1-2006)
    10421042##         """
  • sage/groups/matrix_gps/matrix_group_morphism.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/matrix_gps/matrix_group_morphism.py
    a b  
    2727    A set-theoretic map between matrix groups.
    2828    """
    2929    def __init__(self, parent):
    30         Morphism.__init__(self, parent)
     30        Morphism.__init__(self, parent)
    3131
    3232    def _repr_type(self):
    3333        return "MatrixGroup"
     
    6969        MatrixGroupMorphism.__init__(self, homset)   # sets the parent
    7070        G = homset.domain()
    7171        H = homset.codomain()
    72         gaplist_gens = [gap(x) for x in G.gens()]
    73         gaplist_imgs = [gap(x) for x in imgsH]
     72        gaplist_gens = [gap(x) for x in G.gens()]
     73        gaplist_imgs = [gap(x) for x in imgsH]
    7474        genss = '[%s]'%(','.join(str(v) for v in gaplist_gens))
    7575        imgss = '[%s]'%(','.join(str(v) for v in gaplist_imgs))
    7676        args = '%s, %s, %s, %s'%(G._gap_init_(), H._gap_init_(), genss, imgss)
    7777        self._gap_str = 'GroupHomomorphismByImages(%s)'%args
    7878        self._gap_hom_string = 'phi := %s'%self._gap_str
    79         phi0 = gap.eval(self._gap_hom_string)
    80         if phi0=="fail":
     79        phi0 = gap.eval(self._gap_hom_string)
     80        if phi0=="fail":
    8181            raise ValueError,"The map "+str(gensG)+"-->"+str(imgsH)+" isn't a homomorphism."
    82         self.hom = gap.eval("phi")
     82        self.hom = gap.eval("phi")
    8383
    8484    def _gap_init_(self):
    8585        return self._gap_str
     
    168168
    169169    def __call__( self, g ):
    170170        """
    171         Some python code for wrapping GAP's Images function for a matrix
    172         group G. Returns an error if g is not in G.
    173        
    174         EXAMPLES::
    175        
    176             sage: F = GF(5); MS = MatrixSpace(F,2,2)
    177             sage: g = MS([1,1,0,1])
    178             sage: G = MatrixGroup([g])
    179             sage: phi = G.hom(G.gens())
    180             sage: phi(G.0)
    181             [1 1]
    182             [0 1]
    183             sage: phi(G(g^2))
    184             [1 2]
    185             [0 1]
    186        
    187         ::
    188        
    189             sage: F = GF(5); MS = MatrixSpace(F,2,2)
    190             sage: gens = [MS([1,2,  -1,1]),MS([1,1,  0,1])]
    191             sage: G = MatrixGroup(gens)
    192             sage: phi = G.hom(G.gens())
    193             sage: phi(G.0)
    194             [1 2]
    195             [4 1]
    196             sage: phi(G.1)
    197             [1 1]
    198             [0 1]
    199         """
     171        Some python code for wrapping GAP's Images function for a matrix
     172        group G. Returns an error if g is not in G.
     173       
     174        EXAMPLES::
     175       
     176            sage: F = GF(5); MS = MatrixSpace(F,2,2)
     177            sage: g = MS([1,1,0,1])
     178            sage: G = MatrixGroup([g])
     179            sage: phi = G.hom(G.gens())
     180            sage: phi(G.0)
     181            [1 1]
     182            [0 1]
     183            sage: phi(G(g^2))
     184            [1 2]
     185            [0 1]
     186       
     187        ::
     188       
     189            sage: F = GF(5); MS = MatrixSpace(F,2,2)
     190            sage: gens = [MS([1,2,  -1,1]),MS([1,1,  0,1])]
     191            sage: G = MatrixGroup(gens)
     192            sage: phi = G.hom(G.gens())
     193            sage: phi(G.0)
     194            [1 2]
     195            [4 1]
     196            sage: phi(G.1)
     197            [1 1]
     198            [0 1]
     199        """
    200200        cmd = self._gap_hom_string
    201201        gap.eval(cmd)
    202202        G = self.domain()
    203203        F = G.base_ring()
    204204        h = gap(g)
    205         return gap('Image(phi, %s)'%h.name())._matrix_(F)
     205        return gap('Image(phi, %s)'%h.name())._matrix_(F)
    206206
    207207
    208208
  • sage/groups/perm_gps/permgroup.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/perm_gps/permgroup.py
    a b  
    11341134        if p == 0:
    11351135            L = eval(gap.eval("GroupCohomology(%s,%s)"%(GG,n)))
    11361136        else:
    1137             L = eval(gap.eval("GroupCohomology(%s,%s,%s)"%(GG,n,p)))
     1137            L = eval(gap.eval("GroupCohomology(%s,%s,%s)"%(GG,n,p)))
    11381138        return AbelianGroup(len(L),L)
    11391139
    11401140    def cohomology_part(self, n, p = 0):
     
    11721172            gap.eval("S := SylowSubgroup(%s,%s)"%(GG,p))
    11731173            gap.eval("R:=ResolutionFiniteGroup(S,%s)"%(n+1))
    11741174            gap.eval("HR:=HomToIntegers(R)")
    1175             L = eval(gap.eval("Cohomology(HR,%s)"%n))
     1175            L = eval(gap.eval("Cohomology(HR,%s)"%n))
    11761176        return AbelianGroup(len(L),L)
    11771177
    11781178    def homology(self, n, p = 0):
     
    12251225        if p == 0:
    12261226            L = eval(gap.eval("GroupHomology(%s,%s)"%(GG,n)))
    12271227        else:
    1228             L = eval(gap.eval("GroupHomology(%s,%s,%s)"%(GG,n,p)))
     1228            L = eval(gap.eval("GroupHomology(%s,%s,%s)"%(GG,n,p)))
    12291229        return AbelianGroup(len(L),L)
    12301230
    12311231    def homology_part(self, n, p = 0):
     
    12601260            gap.eval("S := SylowSubgroup(%s,%s)"%(GG,p))
    12611261            gap.eval("R:=ResolutionFiniteGroup(S,%s)"%(n+1))
    12621262            gap.eval("TR:=TensorWithIntegers(R);")
    1263             L = eval(gap.eval("Homology(TR,%s)"%n))
     1263            L = eval(gap.eval("Homology(TR,%s)"%n))
    12641264        return AbelianGroup(len(L),L)
    12651265
    12661266    def character_table(self):
     
    14701470        L = gap("List([1..Length(%s)], i->Representative(%s[i]))"%(
    14711471            cl.name(),  cl.name()))
    14721472        return [PermutationGroup(gap_group=L[i])for i in range(1,n+1)]
    1473        
     1473       
    14741474    def normalizer(self, g):
    14751475        """
    14761476        Returns the normalizer of ``g`` in ``self``.
     
    18101810            if not (G.has_element(x)):
    18111811                return False
    18121812        return True
    1813        
     1813       
    18141814    def is_supersolvable(self):
    18151815        """
    18161816        Returns ``True`` if the group is supersolvable. A finite group is
     
    19941994        gap.eval("cc := ConstituentsOfCharacter( pi )")
    19951995        M = gap.eval("M := MolienSeries(Sum(cc))")
    19961996        R = PolynomialRing(RationalField(),"x")
    1997         x = R.gen()
     1997        x = R.gen()
    19981998        nn = gap.eval("NumeratorOfRationalFunction(M)")
    19991999        dd = gap.eval("DenominatorOfRationalFunction(M)")
    20002000        FF = FractionField(R)
     
    20622062        GG = G._gap_init_()
    20632063        ff = gap.eval("ff := PoincareSeriesPrimePart(%s,%s,%s)"%(GG,p,n))
    20642064        R = PolynomialRing(RationalField(),"x")
    2065         x = R.gen()
     2065        x = R.gen()
    20662066        nn = gap.eval("NumeratorOfRationalFunction(ff)").replace("x_1","x")
    20672067        dd = gap.eval("DenominatorOfRationalFunction(ff)").replace("x_1","x")
    20682068        FF = FractionField(R)
  • sage/groups/perm_gps/permgroup_morphism.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/perm_gps/permgroup_morphism.py
    a b  
    6666    A set-theoretic map between PermutationGroups.
    6767    """
    6868    def __init__(self, parent):
    69         Morphism.__init__(self, parent)
     69        Morphism.__init__(self, parent)
    7070
    7171    def _repr_type(self):
    7272        return "PermutationGroup"
     
    111111        self._codomain = H
    112112        if not(isinstance(G, PermutationGroup_generic)):
    113113            raise TypeError, "Sorry, the groups must be permutation groups."
    114         if not(isinstance(H, PermutationGroup_generic)):
     114        if not(isinstance(H, PermutationGroup_generic)):
    115115            raise TypeError, "Sorry, the groups must be permutation groups."
    116         G0  = G._gap_init_()
    117         H0  = H._gap_init_()
     116        G0  = G._gap_init_()
     117        H0  = H._gap_init_()
    118118        self.gap_hom_string = gap_hom_str
    119119        self._name = name
    120120        self.hom = gap.eval(gap_hom_str)
     
    185185
    186186    def __call__( self, g ):
    187187        """
    188         Some python code for wrapping GAP's Images function but only for
    189         permutation groups. Returns an error if g is not in G.
    190         """
     188        Some python code for wrapping GAP's Images function but only for
     189        permutation groups. Returns an error if g is not in G.
     190        """
    191191        cmd = self.gap_hom_string
    192192        gap.eval(cmd)
    193         return PermutationGroupElement(gap.eval("Image( "+self._name+", "+str(g)+")"),self.range(), check = True)
     193        return PermutationGroupElement(gap.eval("Image( "+self._name+", "+str(g)+")"),self.range(), check = True)
    194194
    195195class PermutationGroupMorphism_im_gens:
    196196    """
     
    228228        self._codomain = H
    229229        if not(isinstance(G, PermutationGroup_generic)):
    230230            raise TypeError, "Sorry, the groups must be permutation groups."
    231         if not(isinstance(H, PermutationGroup_generic)):
     231        if not(isinstance(H, PermutationGroup_generic)):
    232232            raise TypeError, "Sorry, the groups must be permutation groups."
    233         G0  = G._gap_init_()
    234         H0  = H._gap_init_()
    235         gaplist_gens = [gap_format(x) for x in gensG]
    236         gaplist_imgs = [gap_format(x) for x in imgsH]
    237         L = gaplist_gens
    238         if len(L) == 1:
     233        G0  = G._gap_init_()
     234        H0  = H._gap_init_()
     235        gaplist_gens = [gap_format(x) for x in gensG]
     236        gaplist_imgs = [gap_format(x) for x in imgsH]
     237        L = gaplist_gens
     238        if len(L) == 1:
    239239            genss = "["+L[0]+"]"
    240         if len(L)>1:
     240        if len(L)>1:
    241241            genss = "["+L[0]+''.join([","+L[i+1] for i in range(len(L)-1)])+"]"
    242         L = gaplist_imgs
    243         if len(L) == 1:
     242        L = gaplist_imgs
     243        if len(L) == 1:
    244244            imgss = "["+L[0]+"]"
    245         if len(L)>1:
     245        if len(L)>1:
    246246            imgss = "["+L[0]+''.join([","+L[i+1] for i in range(len(L)-1)])+"]"
    247         args = str(G0)+","+str(H0)+","+genss+","+ imgss
    248         phi0 = gap.eval("phi := GroupHomomorphismByImages("+args+")")
     247        args = str(G0)+","+str(H0)+","+genss+","+ imgss
     248        phi0 = gap.eval("phi := GroupHomomorphismByImages("+args+")")
    249249        self.gap_hom_string = "phi := GroupHomomorphismByImages("+args+")"
    250         if phi0=="fail":
     250        if phi0=="fail":
    251251            raise ValueError,"The map "+str(gensG)+"-->"+str(imgsH)+" isn't a homomorphism."
    252         self.hom = gap.eval("phi")
     252        self.hom = gap.eval("phi")
    253253
    254254    def __repr__(self):
    255255        return "Homomorphism : %s --> %s"%(self.domain(),self.range())
     
    308308
    309309    def __call__( self, g ):
    310310        """
    311         Some python code for wrapping GAP's Images function but only for
    312         permutation groups. Returns an error if g is not in G.
    313        
    314         EXAMPLES::
    315        
    316             sage: G = CyclicPermutationGroup(4)
     311        Some python code for wrapping GAP's Images function but only for
     312        permutation groups. Returns an error if g is not in G.
     313       
     314        EXAMPLES::
     315       
     316            sage: G = CyclicPermutationGroup(4)
    317317            sage: gens = G.gens()
    318318            sage: H = DihedralGroup(4)
    319319            sage: phi = PermutationGroupMorphism_im_gens( G, H, gens, gens)
    320320            sage: g = G([(1,3),(2,4)]); g
    321             (1,3)(2,4)
     321            (1,3)(2,4)
    322322            sage: phi(g)
    323             (1,3)(2,4)
    324         """
     323            (1,3)(2,4)
     324        """
    325325        return self.image(g)
    326326
    327327PermutationGroupMorphism = PermutationGroupMorphism_im_gens
  • sage/groups/perm_gps/permgroup_named.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/groups/perm_gps/permgroup_named.py
    a b  
    317317        """
    318318        Return True if this group is commutative.
    319319
    320         EXAMPLES:
     320        EXAMPLES:
    321321            sage: C = CyclicPermutationGroup(8)
    322322            sage: C.is_commutative()
    323323            True
     
    328328        """
    329329        Return True if this group is abelian.
    330330
    331         EXAMPLES:
     331        EXAMPLES:
    332332            sage: C = CyclicPermutationGroup(8)
    333333            sage: C.is_abelian()
    334334            True
     
    336336        return True
    337337   
    338338    def as_AbelianGroup(self):
    339         """
    340         Returns the corresponding Abelian Group instance.
    341        
    342         EXAMPLES:
     339        """
     340        Returns the corresponding Abelian Group instance.
     341       
     342        EXAMPLES:
    343343            sage: C = CyclicPermutationGroup(8)
    344344            sage: C.as_AbelianGroup()
    345345            Multiplicative Abelian Group isomorphic to C8
    346346
    347         """
    348         n = self.order()
     347        """
     348        n = self.order()
    349349        a = list(factor(n))
    350350        invs = [x[0]**x[1] for x in a]
    351351        G = AbelianGroup(len(a),invs)
    352         return G
    353                
     352        return G
     353               
    354354class KleinFourGroup(PermutationGroup_generic):
    355355    def __init__(self):
    356356        r"""
     
    403403            sage: DihedralGroup(2)
    404404            Dihedral group of order 4 as a permutation group
    405405            sage: DihedralGroup(2).gens()
    406             [(3,4), (1,2)]
     406            [(3,4), (1,2)]
    407407
    408408            sage: DihedralGroup(5).gens()
    409409            [(1,2,3,4,5), (1,5)(2,4)]
     
    921921        from sage.rings.arith import valuation
    922922        t = valuation(q, 2)
    923923        if 2**t != q or is_even(t):
    924             raise ValueError,"The ground field size %s must be an odd power of 2."%q
     924            raise ValueError,"The ground field size %s must be an odd power of 2."%q
    925925        id = 'SuzukiGroup(IsPermGroup,%s)'%q
    926926        PermutationGroup_generic.__init__(self, gap_group=id)
    927927        self._q = q
  • sage/gsl/dwt.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/gsl/dwt.pyx
    a b  
    123123        if self.wavelet != NULL:
    124124            gsl_wavelet_free(self.wavelet)
    125125            gsl_wavelet_workspace_free(self.workspace)
    126        
     126
    127127    def forward_transform(self):
    128128        gsl_wavelet_transform_forward(self.wavelet,self.data,self.stride,self.n,self.workspace)
    129129
  • sage/interfaces/ecm.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/interfaces/ecm.py
    a b  
    193193        child = pexpect.spawn(self.__cmd)       
    194194        cleaner.cleaner(child.pid, self.__cmd)
    195195        child.timeout = None
    196         child.__del__ = nothing   # work around stupid exception ignored error
     196        child.__del__ = nothing   # work around stupid exception ignored error
    197197        child.expect('[ECM]')
    198198        child.sendline(str(n))
    199199        child.sendline("bad") # child.sendeof()
     
    261261        child = pexpect.spawn(self.__cmd)       
    262262        cleaner.cleaner(child.pid, self.__cmd)
    263263        child.timeout = None
    264         child.__del__ = nothing   # program around stupid exception ignored error
     264        child.__del__ = nothing   # program around stupid exception ignored error
    265265        child.expect('[ECM]')
    266266        child.sendline(str(n))
    267267        child.sendline("bad") # child.sendeof()
  • sage/interfaces/macaulay2.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/interfaces/macaulay2.py
    a b  
    737737        return P.eval('%s == 0'%self.name()) == 'false'       
    738738
    739739    def sage_polystring(self):
    740         """
    741         If this Macaulay2 element is a polynomial, return a string
    742         representation of this polynomial that is suitable for
    743         evaluation in Python.  Thus * is used for multiplication
    744         and ** for exponentiation.   This function is primarily
    745         used internally.
    746        
    747         EXAMPLES:
     740        """
     741        If this Macaulay2 element is a polynomial, return a string
     742        representation of this polynomial that is suitable for
     743        evaluation in Python.  Thus * is used for multiplication
     744        and ** for exponentiation.   This function is primarily
     745        used internally.
     746       
     747        EXAMPLES:
    748748            sage: R = macaulay2.ring('QQ','(x,y)')               # optional
    749749            sage: f = macaulay2('x^3 + 3*y^11 + 5')              # optional
    750750            sage: print f                                        # optional
     
    752752            x  + 3y   + 5           
    753753            sage: f.sage_polystring()                            # optional
    754754            'x**3+3*y**11+5'
    755         """
     755        """
    756756        return self.external_string().replace('^','**')
    757757
    758758    def structure_sheaf(self):
  • sage/interfaces/maxima.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/interfaces/maxima.py
    a b  
    697697        self._synchronize()
    698698
    699699        if len(line) > self.__eval_using_file_cutoff:
    700             # This implicitly uses the set method, then displays the result of the thing that was set.
     700            # This implicitly uses the set method, then displays the result of the thing that was set.
    701701            # This only works when the input line is an expression.   But this is our only choice, since
    702702            # batchmode doesn't display expressions to screen.   
    703703            a = self(line)
  • sage/interfaces/phc.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/interfaces/phc.py
    a b  
    114114    solution_dicts = {}
    115115    solution_types = ['complex', 'real','failure']
    116116    for sol_type in solution_types:
    117         solution_dicts[sol_type] = []
     117        solution_dicts[sol_type] = []
    118118    for solution_line in range(len(output_list)-1,-1,-1):
    119119        if output_list[solution_line].find('THE SOLUTIONS') == 0:
    120120            break
     
    122122    sol_number = int(output_list[solution_line+2].split(' ')[0])
    123123    for i in range(solution_line + 1,len(output_list)):
    124124        if output_list[i].count('the solution for t') == 1:
    125             phc_type = output_list[i+var_number+1].split(' = ')[-1]
     125            phc_type = output_list[i+var_number+1].split(' = ')[-1]
    126126            if phc_type.find('complex') != -1:
    127127                phc_type = 'complex'
    128128            elif phc_type.find('real') != -1:
     
    168168class PHC_Object:
    169169
    170170    def __init__(self, output_file_contents, input_ring):
    171         """
     171        """
    172172        A container for data from the PHCpack program - lists of float
    173173        solutions, etc.  Currently the file contents are kept as a string;
    174174        for really large outputs this would be bad.
    175175   
    176         INPUT:
    177             output_file_contents: the string output of PHCpack
    178             input_ring: for coercion of the variables into the desired ring.
     176        INPUT:
     177            output_file_contents: the string output of PHCpack
     178            input_ring: for coercion of the variables into the desired ring.
    179179
    180180        EXAMPLES:
    181181            sage: from sage.interfaces.phc import phc #optional
     
    184184            sage: sol = phc.blackbox(start_sys, R2)  #optional
    185185            sage: str(sum([x[0] for x in sol.solutions()]).real())[0:3] #optional
    186186            '2.0'
    187         """
     187        """
    188188        self.output_file_contents = output_file_contents
    189         self.input_ring = input_ring
     189        self.input_ring = input_ring
    190190
    191191
    192192    def save_as_start(self, start_filename = None, sol_filter = ''):
     
    206206            sage: len(sol.solutions())               #optional
    207207            15
    208208        """
    209         start_data = ''
    210         output_list = self.output_file_contents.splitlines()
    211         for a_line in output_list:
    212             if a_line.find('ROOT COUNTS') != -1 or a_line.find('START SOLUTIONS') != -1:
    213                 break
    214             else:
    215                 start_data += a_line + '\n'
    216         for index in range(len(output_list)-1,0,-1):
    217             a_line = output_list[index]
    218             if a_line.find('THE SOLUTIONS') != -1:
    219                 found_solutions = index
    220                 break
    221         start_data += output_list[found_solutions] + '\n\n'
    222         try:
     209        start_data = ''
     210        output_list = self.output_file_contents.splitlines()
     211        for a_line in output_list:
     212            if a_line.find('ROOT COUNTS') != -1 or a_line.find('START SOLUTIONS') != -1:
     213                break
     214            else:
     215                start_data += a_line + '\n'
     216        for index in range(len(output_list)-1,0,-1):
     217            a_line = output_list[index]
     218            if a_line.find('THE SOLUTIONS') != -1:
     219                found_solutions = index
     220                break
     221        start_data += output_list[found_solutions] + '\n\n'
     222        try:
    223223            var_number = int(output_list[found_solutions+1].split(' ')[1])
    224224        except:
    225225            # bad error handling
    226226            var_number = int(output_list[found_solutions+2].split(' ')[1])
    227         sol_count = 0
    228         sol_data = ''
    229         for i in range(found_solutions + 2, len(output_list)):
    230             if output_list[i].count('the solution for t') == 1 and output_list[i+1+var_number].find(sol_filter) != -1:
    231                 phc_type = output_list[i+var_number+1].split(' = ')[-1]
    232                 if phc_type.find('no solution') == -1:
    233                     sol_count += 1
    234                     for ind2 in range(i-3,i+var_number+2):
    235                         sol_data += output_list[ind2] + '\n'
    236         jan_bar = '===========================================================================\n'
    237         sol_data += jan_bar
    238         start_data += str(sol_count) + ' ' + str(var_number) + '\n'
    239         start_data += jan_bar + sol_data
    240         if start_filename != None:
    241             start_file = file(start_filename,'w')
    242             start_file.write(start_data)
    243             start_file.close()
    244         return start_data
     227        sol_count = 0
     228        sol_data = ''
     229        for i in range(found_solutions + 2, len(output_list)):
     230            if output_list[i].count('the solution for t') == 1 and output_list[i+1+var_number].find(sol_filter) != -1:
     231                phc_type = output_list[i+var_number+1].split(' = ')[-1]
     232                if phc_type.find('no solution') == -1:
     233                    sol_count += 1
     234                    for ind2 in range(i-3,i+var_number+2):
     235                        sol_data += output_list[ind2] + '\n'
     236        jan_bar = '===========================================================================\n'
     237        sol_data += jan_bar
     238        start_data += str(sol_count) + ' ' + str(var_number) + '\n'
     239        start_data += jan_bar + sol_data
     240        if start_filename != None:
     241            start_file = file(start_filename,'w')
     242            start_file.write(start_data)
     243            start_file.close()
     244        return start_data
    245245
    246246    def classified_solution_dicts(self):
    247         """
    248         Returns a dictionary of lists of dictionaries of solutions.
    249         Its not as crazy as it sounds; the keys are the types of solutions as
    250         classified by phcpack: regular vs. singular, complex vs. real
     247        """
     248        Returns a dictionary of lists of dictionaries of solutions.
     249        Its not as crazy as it sounds; the keys are the types of solutions as
     250        classified by phcpack: regular vs. singular, complex vs. real
    251251
    252         INPUT:
    253             None
     252        INPUT:
     253            None
    254254
    255255        OUTPUT:
    256             A dictionary of lists of dictionaries of solutions 
     256            A dictionary of lists of dictionaries of solutions 
    257257
    258258        EXAMPLES:
    259259            sage: from sage.interfaces.phc import phc #optional
     
    263263            sage: classifieds = sol.classified_solution_dicts()          #optional
    264264            sage: str(sum([q[y] for q in classifieds['real']]))[0:3]          #optional
    265265            '2.0'
    266         """
    267         try:
    268             return self.__classified_sols
    269         except AttributeError:
    270             pass
    271         classified_sols = get_classified_solution_dicts(self.output_file_contents, self.input_ring)
     266        """
     267        try:
     268            return self.__classified_sols
     269        except AttributeError:
     270            pass
     271        classified_sols = get_classified_solution_dicts(self.output_file_contents, self.input_ring)
    272272        self.__classified_sols = classified_sols
    273273        return classified_sols
    274274
     
    276276        """
    277277        Returns a list of solutions in dictionary form: variable:value.
    278278
    279         INPUT:
     279        INPUT:
    280280            self -- for access to self_out_file_contents, the string
    281             of raw PHCpack output.
     281            of raw PHCpack output.
    282282
    283283            get_failures (optional) -- a boolean.  The default (False)
    284             is to not process failed homotopies.  These either lie on
    285             positive-dimensional components or at infinity.
     284            is to not process failed homotopies.  These either lie on
     285            positive-dimensional components or at infinity.
    286286
    287287        OUTPUT:
    288             solution_dicts: a list of dictionaries.  Each dictionary
    289             element is of the form variable:value, where the variable
    290             is an element of the input_ring, and the value is in
    291             ComplexField.
     288            solution_dicts: a list of dictionaries.  Each dictionary
     289            element is of the form variable:value, where the variable
     290            is an element of the input_ring, and the value is in
     291            ComplexField.
    292292       
    293293        EXAMPLES:
    294294            sage: from sage.interfaces.phc import * #optional
     
    309309        return solution_dicts
    310310
    311311    def solutions(self, get_failures = False):
    312         """
    313         Returns a list of solutions in the ComplexField.  Use the variable_list function to get the order of variables used by PHCpack, which is usually different than the term order of the input_ring.
     312        """
     313        Returns a list of solutions in the ComplexField.  Use the variable_list function to get the order of variables used by PHCpack, which is usually different than the term order of the input_ring.
    314314
    315         INPUT:
    316             self -- for access to self_out_file_contents, the string
    317             of raw PHCpack output.
    318             get_failures (optional) -- a boolean.  The default (False)
    319             is to not process failed homotopies.  These either lie on
    320             positive-dimensional components or at infinity.
     315        INPUT:
     316            self -- for access to self_out_file_contents, the string
     317            of raw PHCpack output.
     318            get_failures (optional) -- a boolean.  The default (False)
     319            is to not process failed homotopies.  These either lie on
     320            positive-dimensional components or at infinity.
    321321
    322322        OUTPUT:
    323             solutions: a list of lists of ComplexField-valued solutions.
     323            solutions: a list of lists of ComplexField-valued solutions.
    324324
    325325        EXAMPLES:
    326326            sage: from sage.interfaces.phc import *         #optional
     
    329329            sage: sol = phc.blackbox(test_sys, R2)          #optional
    330330            sage: len(sol.solutions())                      #optional
    331331            25
    332         """
    333         try:
    334             return self.__solutions
    335         except AttributeError:
     332        """
     333        try:
     334            return self.__solutions
     335        except AttributeError:
    336336            pass
    337337        solution_dicts = get_solution_dicts(self.output_file_contents, self.input_ring, get_failures = get_failures)
    338338        self.__solution_dicts = solution_dicts
    339         solutions = [sol_dict.values() for sol_dict in solution_dicts]
    340         self.__solutions = solutions
     339        solutions = [sol_dict.values() for sol_dict in solution_dicts]
     340        self.__solutions = solutions
    341341        return solutions
    342342
    343343    def variable_list(self):
    344344        """
    345         Returns the variables, as strings, in the order in which
    346         PHCpack has processed them.
     345        Returns the variables, as strings, in the order in which
     346        PHCpack has processed them.
    347347
    348348        EXAMPLES:
    349349            sage: from sage.interfaces.phc import *         #optional
     
    369369    EXAMPLES:
    370370        sage: from sage.interfaces.phc import phc #optional
    371371        sage: R.<x,y> = PolynomialRing(CDF,2)     #optional
    372         sage: testsys = [x^2 + 1, x*y - 1]        #optional
     372        sage: testsys = [x^2 + 1, x*y - 1]        #optional
    373373        sage: phc.mixed_volume(testsys)        # optional -- you must have phc install
    374374        2
    375375        sage: v = phc.blackbox(testsys, R)     # optional
    376376        sage: sols = v.solutions()             # optional
    377377        sage: sols.sort()                      # optional
    378         sage: sols                             # optional
     378        sage: sols                             # optional
    379379        [[-1.00000000000000*I, 1.00000000000000*I], [1.00000000000000*I, -1.00000000000000*I]]
    380         sage: sol_dict = v.solution_dicts()    # optional
     380        sage: sol_dict = v.solution_dicts()    # optional
    381381        sage: x_sols_from_dict = [d[x] for d in sol_dict]    # optional
    382382        sage: x_sols_from_dict.sort(); x_sols_from_dict      # optional
    383383        [-1.00000000000000*I, 1.00000000000000*I]
    384         sage: residuals = [[test_equation.change_ring(CDF).subs(sol) for test_equation in testsys] for sol in v.solution_dicts()]      # optional
    385         sage: residuals                             # optional
    386         [[0, 0], [0, 0]]
     384        sage: residuals = [[test_equation.change_ring(CDF).subs(sol) for test_equation in testsys] for sol in v.solution_dicts()]      # optional
     385        sage: residuals                             # optional
     386        [[0, 0], [0, 0]]
    387387    """
    388388
    389389    def _output_from_command_list(self, command_list, polys, verbose = False):
     
    586586        """
    587587        # Probably unnecessarily redundant from the start_from function
    588588        if start_filename_or_string.find('THE SOLUTIONS') != -1:
    589             start_filename = sage.misc.misc.tmp_filename()
    590             start_file = file(start_filename,'w')
    591             start_file.write(start_filename_or_string)
    592             start_file.close()
    593         elif os.path.exists(start_filename_or_string):
    594             start_filename = start_filename_or_string
    595         else:
    596             raise RuntimeError, "There is something wrong with your start string or filename"
     589            start_filename = sage.misc.misc.tmp_filename()
     590            start_file = file(start_filename,'w')
     591            start_file.write(start_filename_or_string)
     592            start_file.close()
     593        elif os.path.exists(start_filename_or_string):
     594            start_filename = start_filename_or_string
     595        else:
     596            raise RuntimeError, "There is something wrong with your start string or filename"
    597597       
    598598        return self._output_from_command_list(['phc','0','0','A',start_filename, 'y','1','0','n','k','2','a','1',str(c_skew),'0','0','2'], polys, verbose = verbose)
    599599
     
    726726            return mixed_vol
    727727        except NameError:
    728728            raise RuntimeError, "Mixed volume not found in output; something went wrong running phc."
    729        
     729       
    730730
    731731    def start_from(self, start_filename_or_string, polys, input_ring, path_track_file = None, verbose = False):
    732         """
    733         This computes solutions starting from a phcpack solution file.
     732        """
     733        This computes solutions starting from a phcpack solution file.
    734734       
    735735        INPUT:
    736             start_filename_or_string -- the filename for a phcpack start system, or the contents of such a file as a string.  Variable names must match the inputring variables.  The value of the homotopy variable t should be 1, not 0.
     736            start_filename_or_string -- the filename for a phcpack start system, or the contents of such a file as a string.  Variable names must match the inputring variables.  The value of the homotopy variable t should be 1, not 0.
    737737            polys -- a list of multivariate polynomials (elements of a multivariate
    738738                     polynomial ring).
    739739            input_ring: for coercion of the variables into the desired ring.
     
    753753            sage: sol = phc.start_from(start_save, end_sys, R2) #optional
    754754            sage: len(sol.solutions())                     #optional
    755755            30
    756         """
    757         input_filename = sage.misc.misc.tmp_filename()
    758         output_filename = sage.misc.misc.tmp_filename()
     756        """
     757        input_filename = sage.misc.misc.tmp_filename()
     758        output_filename = sage.misc.misc.tmp_filename()
    759759
    760         if start_filename_or_string.find('THE SOLUTIONS') != -1:
    761             start_filename = sage.misc.misc.tmp_filename()
    762             start_file = file(start_filename,'w')
    763             start_file.write(start_filename_or_string)
    764             start_file.close()
    765         elif os.path.exists(start_filename_or_string):
    766             start_filename = start_filename_or_string
    767         else:
    768             raise RuntimeError, "There is something wrong with your start string or filename"
     760        if start_filename_or_string.find('THE SOLUTIONS') != -1:
     761            start_filename = sage.misc.misc.tmp_filename()
     762            start_file = file(start_filename,'w')
     763            start_file.write(start_filename_or_string)
     764            start_file.close()
     765        elif os.path.exists(start_filename_or_string):
     766            start_filename = start_filename_or_string
     767        else:
     768            raise RuntimeError, "There is something wrong with your start string or filename"
    769769
    770         # Get the input polynomial text
     770        # Get the input polynomial text
    771771        input = self._input_file(polys)
    772772        if verbose:
    773773            print "Writing the input file to %s"%input_filename
     
    776776        if verbose:
    777777            print "The following file will be the input polynomial file to phc."
    778778            print input
    779        
    780         # Create a phc process
     779       
     780        # Create a phc process
    781781        child_phc = pexpect.spawn('phc')
    782782        child_phc.sendline('y')
    783783        child_phc.sendline(input_filename)
     
    787787        child_phc.expect('Nonlinear Reduction')
    788788        child_phc.sendline('A')
    789789        child_phc.sendline(start_filename)
    790         child_phc.sendline('y')
    791         child_phc.sendline('1')
    792         child_phc.sendline('0')
     790        child_phc.sendline('y')
     791        child_phc.sendline('1')
     792        child_phc.sendline('0')
    793793        if verbose:
    794794            phc_dialog = child_phc.read(size = 40)
    795795            print phc_dialog
    796         child_phc.sendline('n')
    797         child_phc.sendline('0')
     796        child_phc.sendline('n')
     797        child_phc.sendline('0')
    798798        if verbose:
    799799            child_phc.expect('CURRENT CONTINUATION')
    800800            phc_dialog = child_phc.read(size = 40)
    801801            print phc_dialog
    802         child_phc.sendline('0')
    803         if path_track_file == None:
    804             child_phc.sendline('0')
    805         else:
    806             child_phc.sendline('2')
     802        child_phc.sendline('0')
     803        if path_track_file == None:
     804            child_phc.sendline('0')
     805        else:
     806            child_phc.sendline('2')
    807807        child_phc.expect('results')
    808         dots = child_phc.read()
     808        dots = child_phc.read()
    809809        if verbose:
    810810            print "should be . : " + dots
    811811       
    812         #close down the process:
    813         child_phc.close()
     812        #close down the process:
     813        child_phc.close()
    814814        if not os.path.exists(output_filename):
    815815            raise RuntimeError, "The output file does not exist; something went wrong running phc."
    816        
    817         # Read the output produced by PHC
     816       
     817        # Read the output produced by PHC
    818818        out = open(output_filename).read()
    819819
    820820        # Delete the temporary files
  • sage/interfaces/singular.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/interfaces/singular.py
    a b  
    12861286        return P.eval('%s == 0'%self.name()) == '0'
    12871287           
    12881288    def sage_polystring(self):
    1289         r"""
    1290         If this Singular element is a polynomial, return a string
    1291         representation of this polynomial that is suitable for evaluation
    1292         in Python. Thus \* is used for multiplication and \*\* for
    1293         exponentiation. This function is primarily used internally.
    1294        
    1295         The short=0 option *must* be set for the parent ring or this
    1296         function will not work as expected. This option is set by default
    1297         for rings created using ``singular.ring`` or set using
    1298         ``ring_name.set_ring()``.
    1299        
    1300         EXAMPLES::
    1301        
    1302             sage: R = singular.ring(0,'(x,y)')
    1303             sage: f = singular('x^3 + 3*y^11 + 5')
    1304             sage: f
    1305             x^3+3*y^11+5
    1306             sage: f.sage_polystring()
    1307             'x**3+3*y**11+5'
    1308         """
     1289        r"""
     1290        If this Singular element is a polynomial, return a string
     1291        representation of this polynomial that is suitable for evaluation
     1292        in Python. Thus \* is used for multiplication and \*\* for
     1293        exponentiation. This function is primarily used internally.
     1294       
     1295        The short=0 option *must* be set for the parent ring or this
     1296        function will not work as expected. This option is set by default
     1297        for rings created using ``singular.ring`` or set using
     1298        ``ring_name.set_ring()``.
     1299       
     1300        EXAMPLES::
     1301       
     1302            sage: R = singular.ring(0,'(x,y)')
     1303            sage: f = singular('x^3 + 3*y^11 + 5')
     1304            sage: f
     1305            x^3+3*y^11+5
     1306            sage: f.sage_polystring()
     1307            'x**3+3*y**11+5'
     1308        """
    13091309        return str(self).replace('^','**')
    13101310
    13111311
  • sage/libs/ntl/ntl_mat_GF2.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/libs/ntl/ntl_mat_GF2.pyx
    a b  
    569569
    570570    def __invert__(self):
    571571        """
    572         Return $X = A^{-1}$; an error is raised if A is singular.
     572        Return $X = A^{-1}$; an error is raised if A is singular.
    573573
    574574        EXAMPLES:
    575575            sage: l = [0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, \
  • sage/libs/ntl/ntl_mat_GF2E.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/libs/ntl/ntl_mat_GF2E.pyx
    a b  
    535535
    536536    def __invert__(self):
    537537        """
    538         Return $X = A^{-1}$; an error is raised if A is singular.
     538        Return $X = A^{-1}$; an error is raised if A is singular.
    539539
    540540        EXAMPLES:
    541541            sage: ctx = ntl.GF2EContext([1,1,0,1,1,0,0,0,1])
  • sage/libs/pari/gen.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/libs/pari/gen.pyx
    a b  
    75577557            't_POL'
    75587558        """
    75597559        # The following original code leaks memory:
    7560         #        return str(type_name(typ(self.g)))
    7561         #
    7562         # This code is the usual workaround:
    7563         #        cdef char* s= <char*>type_name(typ(self.g))
    7564         #        t=str(s)
    7565         #        free(s)
    7566         #        return(t)
     7560        #        return str(type_name(typ(self.g)))
     7561        #
     7562        # This code is the usual workaround:
     7563        #        cdef char* s= <char*>type_name(typ(self.g))
     7564        #        t=str(s)
     7565        #        free(s)
     7566        #        return(t)
    75677567        # However, it causes segfaults with t_INTs on some
    75687568        # machines, and errors about freeing non-aligned
    75697569        # pointers on others. So we settle for the following
  • sage/matrix/constructor.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/matrix/constructor.py
    a b  
    505505                entries = 0
    506506                entry_ring = rings.ZZ
    507507            elif isinstance(args[0][0], (list, tuple)) or is_Vector(args[0][0]):
    508                 # Ensure we have a list of lists, each inner list having the same number of elements
    509                 first_len = len(args[0][0])
    510                 if not all( (isinstance(v, (list, tuple)) or is_Vector(v)) and len(v) == first_len for v in args[0]):
    511                     raise ValueError, "List of rows is not valid (rows are wrong types or lengths)"
     508                # Ensure we have a list of lists, each inner list having the same number of elements
     509                first_len = len(args[0][0])
     510                if not all( (isinstance(v, (list, tuple)) or is_Vector(v)) and len(v) == first_len for v in args[0]):
     511                    raise ValueError, "List of rows is not valid (rows are wrong types or lengths)"
    512512                # We have a list of rows or vectors
    513513                if nrows is None:
    514514                    nrows = len(args[0])
    515515                elif nrows != len(args[0]):
    516516                    raise ValueError, "Number of rows does not match up with specified number."
    517517                if ncols is None:
    518                     ncols = len(args[0][0])
     518                    ncols = len(args[0][0])
    519519                elif ncols != len(args[0][0]):
    520520                    raise ValueError, "Number of columns does not match up with specified number."
    521521
  • sage/matrix/matrix_double_dense.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/matrix/matrix_double_dense.pyx
    a b  
    10201020            [               2.0                3.0]
    10211021            [               4.0                5.0]
    10221022
    1023         Due to numerical noise issues on Intel Macs, the following fails if 1e-14
    1024         is changed to 1e-15:
     1023        Due to numerical noise issues on Intel Macs, the following fails if 1e-14
     1024        is changed to 1e-15:
    10251025            sage: max((U*S*V.transpose()-m).list())<1e-14 # check
    10261026            True
    10271027
  • sage/matrix/matrix_mod2_dense.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/matrix/matrix_mod2_dense.pyx
    a b  
    549549        INPUT:
    550550            right -- Matrix
    551551            k -- parameter $k$ for the Gray Code table size. If $k=0$ a
    552                  suitable value is chosen by the function. 
    553                 ($0<= k <= 16$, default: 0)
     552                 suitable value is chosen by the function.
     553                ($0<= k <= 16$, default: 0)
    554554
    555555        EXAMPLE:
    556556              sage: A = Matrix(GF(2), 4, 3, [0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1] )
     
    590590        multiplication as implemented in the M4RI library.
    591591
    592592        REFERENCES:
    593             [AHU] A. Aho, J. Hopcroft, and J. Ullman. 'Chapter 6:
     593            [AHU] A. Aho, J. Hopcroft, and J. Ullman. 'Chapter 6:
    594594                     Matrix Multiplication and Related Operations.'
    595595                     The Design and Analysis of Computer
    596596                     Algorithms. Addison-Wesley, 1974.
     
    847847       
    848848        if self._nrows and self._ncols:
    849849            mzd_copy(A._entries, self._entries)
    850        
     850
    851851        if self.subdivisions is not None:
    852852            A.subdivide(*self.get_subdivisions())
    853853
     
    13811381
    13821382    def submatrix(self, lowr, lowc, nrows , ncols):
    13831383        """
    1384         Return submatrix from the index lowr,lowc (inclusive) with
    1385         dimension nrows x ncols.
     1384        Return submatrix from the index lowr,lowc (inclusive) with
     1385        dimension nrows x ncols.
    13861386
    13871387        INPUT:
    13881388            lowr -- index of start row
     
    14051405             True
    14061406             sage: A[1:200,1:200] == A.submatrix(1,1,199,199)
    14071407             True
    1408         """
     1408        """
    14091409        cdef Matrix_mod2_dense A
    14101410
    14111411        cdef int highr, highc
  • sage/matrix/matrix_modn_dense.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/matrix/matrix_modn_dense.pyx
    a b  
    15761576            self.cache('det', d2)
    15771577            return d2
    15781578        else:
    1579             return matrix_dense.Matrix_dense.determinant(self) 
     1579            return matrix_dense.Matrix_dense.determinant(self)
    15801580
    15811581    def randomize(self, density=1):
    15821582        """
  • sage/misc/darcs.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/misc/darcs.py
    a b  
    102102        Run 'darcs cmd' where cmd is an arbitrary string
    103103        in the darcs repository.
    104104        """
    105         darcs_ensure_installed()
     105        darcs_ensure_installed()
    106106        if check_initialized and not self.__initialized:
    107107            self.initialize()
    108108        darcs_ensure_installed()
  • sage/misc/edit_module.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/misc/edit_module.py
    a b  
    9595       infile.readline()
    9696       if infile.readline().find("*autogenerated*") >= 0:
    9797         filename=filename[:-3]+'.sage'
    98         lineno = lineno-3
     98        lineno = lineno-3
    9999
    100100   sageroot = sage.misc.sageinspect.SAGE_ROOT+'/'
    101101   runbranches = ['local/lib/python/site-packages',
  • sage/misc/hg.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/misc/hg.py
    a b  
    168168        if self.__name == "SAGE Library Source Code":
    169169            b = branch_current_hg()
    170170            if b == '': b='main'
    171             elif b[-1] == '/':
    172                 b = b[:-1]
     171            elif b[-1] == '/':
     172                b = b[:-1]
    173173            print("Branch: %s"%b)
    174174
    175175
     
    12071207SAGE_INCOMING_SERVER = os.getenv("SAGE_INCOMING_SERVER")
    12081208if SAGE_INCOMING_SERVER is None:
    12091209    try:
    1210         SAGE_INCOMING_SERVER = os.environ['SAGE_HG_SERVER'].strip('/')
     1210        SAGE_INCOMING_SERVER = os.environ['SAGE_HG_SERVER'].strip('/')
    12111211    except KeyError:
    12121212        #print "Falling back to a hard coded sage server in misc/hg.py"
    12131213        SAGE_INCOMING_SERVER = DEFAULT_SERVER
  • sage/modular/dirichlet.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modular/dirichlet.py
    a b  
    986986        r"""
    987987        Return the "twisted" Kloosterman sum associated to this Dirichlet character.
    988988        This includes Gauss sums, classical Kloosterman sums, Salie sums, etc. 
    989         
     989        
    990990        The Kloosterman sum associated to $\chi$ and the integers a,b is
    991991        $$
    992992        K(a,b,\chi) = \sum_{r \in (\Z/m\Z)^\times} \chi(r)\,\zeta^{ar+br^{-1}},
     
    10011001        EXAMPLES::
    10021002 
    10031003            sage: G = DirichletGroup(3)
    1004             sage: e = G([-1])
    1005             sage: e.kloosterman_sum(3,5)
    1006             -2*zeta6 + 1
    1007             sage: G = DirichletGroup(20)
    1008             sage: e = G([1 for  u in G.unit_gens()])
    1009             sage: e.kloosterman_sum(7,17)
    1010             -2*zeta20^6 + 2*zeta20^4 + 4
    1011         
     1004            sage: e = G([-1])
     1005            sage: e.kloosterman_sum(3,5)
     1006            -2*zeta6 + 1
     1007            sage: G = DirichletGroup(20)
     1008            sage: e = G([1 for  u in G.unit_gens()])
     1009            sage: e.kloosterman_sum(7,17)
     1010            -2*zeta20^6 + 2*zeta20^4 + 4
     1011        
    10121012        """
    10131013        G = self.parent()
    10141014        K = G.base_ring()
     
    10291029           
    10301030    def kloosterman_sum_numerical(self, prec=53, a=1,b=0):
    10311031        r"""
    1032         Return the Kloosterman sum associated to this Dirichlet character as
    1033         an approximate complex number with prec bits of precision.
    1034         
    1035         INPUT:
    1036         -  prec -- integer (deafault: 53), *bits* of precision
    1037         -  a -- integer, as for kloosterman_sum
    1038         -  b -- integer, as for kloosterman_sum.
    1039                      
    1040         EXAMPLES::
     1032        Return the Kloosterman sum associated to this Dirichlet character as
     1033        an approximate complex number with prec bits of precision.
     1034        
     1035        INPUT:
     1036        -  prec -- integer (deafault: 53), *bits* of precision
     1037        -  a -- integer, as for kloosterman_sum
     1038        -  b -- integer, as for kloosterman_sum.
     1039                     
     1040        EXAMPLES::
    10411041
    1042             sage: G = DirichletGroup(3)
    1043             sage: e = G.0
     1042            sage: G = DirichletGroup(3)
     1043            sage: e = G.0
    10441044
    10451045        The real component of the numerical value of e is near zero::
    10461046
     
    10491049            True
    10501050            sage: v.imag()
    10511051            1.73205080757
    1052             sage: G = DirichletGroup(20)
    1053             sage: e = G.1 
    1054             sage: e.kloosterman_sum_numerical(53,3,11)
    1055             3.80422606518 - 3.80422606518*I           
    1056                              
    1057         """
    1058         G = self.parent()
    1059         K = G.base_ring()
    1060         if not (rings.is_CyclotomicField(K) or rings.is_RationalField(K)):
     1052            sage: G = DirichletGroup(20)
     1053            sage: e = G.1 
     1054            sage: e.kloosterman_sum_numerical(53,3,11)
     1055            3.80422606518 - 3.80422606518*I           
     1056                             
     1057        """
     1058        G = self.parent()
     1059        K = G.base_ring()
     1060        if not (rings.is_CyclotomicField(K) or rings.is_RationalField(K)):
    10611061            raise NotImplementedError, "Kloosterman sums only currently implemented when the base ring is a cyclotomic field or QQ."
    10621062        phi = K.complex_embedding(prec)
    1063         CC = phi.codomain()     
     1063        CC = phi.codomain()     
    10641064        g = 0
    10651065        m = G.modulus()
    10661066        zeta = CC.zeta(m)
    10671067 
    1068         for c in range(1,m):
     1068        for c in range(1,m):
    10691069            if arith.gcd(c,m)==1:
    10701070                e = rings.Mod(c,m)
    10711071                z = zeta ** (a*e + b*(e**(-1)))
  • sage/modular/modform/eisenstein_submodule.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modular/modform/eisenstein_submodule.py
    a b  
    250250            ]
    251251
    252252            sage: M = ModularForms(19,3).eisenstein_subspace()
    253             sage: M.eisenstein_series()     
     253            sage: M.eisenstein_series()
    254254            [
    255255            ]
    256256        """
     
    394394    """
    395395    # TODO
    396396    #def _compute_q_expansion_basis(self, prec):
    397         #B = EisensteinSubmodule_params._compute_q_expansion_basis(self, prec)
     397        #B = EisensteinSubmodule_params._compute_q_expansion_basis(self, prec)
    398398        #raise NotImplementedError, "must restrict scalars down correctly."
    399399
    400400
  • sage/modular/overconvergent/weightspace.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modular/overconvergent/weightspace.py
    a b  
    270270    """
    271271   
    272272    # This should probably derive from Morphism or even from
    273         # AbelianGroupMorphism; but SAGE doesn't know about the abelian group
    274         # Z_p^*, so Hom(Z_p^*, C_p^*) is a bit beyond it!
     273        # AbelianGroupMorphism; but SAGE doesn't know about the abelian group
     274        # Z_p^*, so Hom(Z_p^*, C_p^*) is a bit beyond it!
    275275
    276276    def __init__(self, parent):
    277277        r"""
     
    646646        WeightCharacter.__init__(self, parent)
    647647
    648648        self.t = ZZ(t) % (self._p > 2 and (self._p - 1) or 2)
    649                 # do we store w precisely?
     649                # do we store w precisely?
    650650        if (w - 1).valuation() <= 0:
    651651            raise ValueError, "Must send generator to something nearer 1"
    652652        self.w = w
  • sage/modular/quatalg/brandt.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modular/quatalg/brandt.py
    a b  
    7474
    7575.. math:
    7676
    77         T_n[I]=\sum_{\phi} [J]
    78        
     77        T_n[I]=\sum_{\phi} [J]
     78       
    7979where '(n,pM)=1' and the sum is over cyclic '\mathcal{O}'-module
    8080homomorphisms '\phi :I\rightarrow J ' of degree 'n' up to isomorphism
    8181of 'J'. Equivalently one can sum over the inclusions of the submodules
     
    103103
    104104.. math:
    105105
    106         \theta_L(q)=\sum_{x \in L} q^{\frac{N(x)}{N(L)}}
     106        \theta_L(q)=\sum_{x \in L} q^{\frac{N(x)}{N(L)}}
    107107
    108108L.theta_series(T,q) returns a power series representing '\theta_L(q)'
    109109up to a precision of '\mathcal{O}(q^{T+1})'.
  • sage/modules/free_module.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modules/free_module.py
    a b  
    14831483        if self.is_ambient():
    14841484            return sage.matrix.matrix_space.MatrixSpace(self.base_ring(), self.degree(), sparse=True)(1)
    14851485        else:
    1486             if self._gram_matrix is None:
     1486            if self._gram_matrix is None:
    14871487                B = self.basis_matrix()
    1488                 self._gram_matrix = B*B.transpose()
     1488                self._gram_matrix = B*B.transpose()
    14891489            return self._gram_matrix
    14901490
    14911491    def has_user_basis(self):
     
    35393539        quo = quomap.codomain()
    35403540        liftmap = quo.Hom(self)(L)
    35413541
    3542         return quomap.codomain(), quomap, liftmap
     3542        return quomap.codomain(), quomap, liftmap
    35433543   
    35443544###############################################################################
    35453545#
  • sage/modules/free_module_element.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modules/free_module_element.pyx
    a b  
    450450            sage: vector(v, ZZ['x', 'y'])
    451451            (2, 12, 22)
    452452
    453             sage: vector(vector((1, 6.8)))
    454             (1.00000000000000, 6.80000000000000)
    455             sage: vector(vector(SR, (1, sqrt(2)) ) )
    456             (1, sqrt(2))
     453            sage: vector(vector((1, 6.8)))
     454            (1.00000000000000, 6.80000000000000)
     455            sage: vector(vector(SR, (1, sqrt(2)) ) )
     456            (1, sqrt(2))
    457457        """
    458458        if R is None:
    459459            R = self.base_ring()
  • sage/modules/free_quadratic_module.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modules/free_quadratic_module.py
    a b  
    379379        the ambient space), and B the basis matrix.
    380380       
    381381        EXAMPLES:
    382             sage: V = VectorSpace(QQ,4)
    383             sage: u = V([1/2,1/2,1/2,1/2])
    384             sage: v = V([0,1,1,0])
    385             sage: w = V([0,0,1,1])
    386             sage: M = span([u,v,w], ZZ)
    387             sage: M.inner_product_matrix() == V.inner_product_matrix()
    388             True
    389             sage: L = M.submodule_with_basis([u,v,w])
    390             sage: L.inner_product_matrix() == M.inner_product_matrix()
    391             True
    392             sage: L.gram_matrix()
    393             [1 1 1]
    394             [1 2 1]
    395             [1 1 2]
     382            sage: V = VectorSpace(QQ,4)
     383            sage: u = V([1/2,1/2,1/2,1/2])
     384            sage: v = V([0,1,1,0])
     385            sage: w = V([0,0,1,1])
     386            sage: M = span([u,v,w], ZZ)
     387            sage: M.inner_product_matrix() == V.inner_product_matrix()
     388            True
     389            sage: L = M.submodule_with_basis([u,v,w])
     390            sage: L.inner_product_matrix() == M.inner_product_matrix()
     391            True
     392            sage: L.gram_matrix()
     393            [1 1 1]
     394            [1 2 1]
     395            [1 1 2]
    396396
    397397        """
    398398        if self.is_ambient():
    399             return self.inner_product_matrix()
     399            return self.inner_product_matrix()
    400400        else:
    401             if self._gram_matrix is None:
    402                 A = self.inner_product_matrix()
     401            if self._gram_matrix is None:
     402                A = self.inner_product_matrix()
    403403                B = self.basis_matrix()
    404                 self._gram_matrix = B*A*B.transpose()
     404                self._gram_matrix = B*A*B.transpose()
    405405            return self._gram_matrix
    406406
    407407    def inner_product_matrix(self):
     
    423423            [0 1 0]
    424424            [0 0 1]
    425425
    426         The inner product does not have to be symmetric or definite.
     426        The inner product does not have to be symmetric or definite.
    427427
    428428            sage: N = FreeModule(ZZ,2,inner_product_matrix=[[1,-1],[2,5]])
    429429            sage: N.inner_product_matrix()
    430430            [ 1 -1]
    431431            [ 2  5]
    432             sage: u, v = N.basis()
    433             sage: u.inner_product(v)
    434             -1
    435             sage: v.inner_product(u)
    436             2
     432            sage: u, v = N.basis()
     433            sage: u.inner_product(v)
     434            -1
     435            sage: v.inner_product(u)
     436            2
    437437
    438         The inner product matrix is defined with respect to the ambient space.
     438        The inner product matrix is defined with respect to the ambient space.
    439439
    440             sage: V = QQ^3
    441             sage: u = V([1/2,1,1])
    442             sage: v = V([1,1,1/2])
    443             sage: M = span([u,v], ZZ)
    444             sage: M.inner_product_matrix()
     440            sage: V = QQ^3
     441            sage: u = V([1/2,1,1])
     442            sage: v = V([1,1,1/2])
     443            sage: M = span([u,v], ZZ)
     444            sage: M.inner_product_matrix()
    445445            [1 0 0]
    446446            [0 1 0]
    447447            [0 0 1]
    448             sage: M.inner_product_matrix() == V.inner_product_matrix()
    449             True
    450             sage: M.gram_matrix()
    451             [ 1/2 -3/4]
    452             [-3/4 13/4]
     448            sage: M.inner_product_matrix() == V.inner_product_matrix()
     449            True
     450            sage: M.gram_matrix()
     451            [ 1/2 -3/4]
     452            [-3/4 13/4]
    453453
    454454        """
    455455        return self._inner_product_matrix
  • sage/modules/matrix_morphism.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/modules/matrix_morphism.py
    a b  
    389389        return H(MS(ims))       
    390390       
    391391        #D  = self.domain()
    392         #C  = self.codomain()
    393         #M  = self.matrix()
    394         #Mr = M.restrict_domain(sub)
    395         #return sub.Hom(C)(Mr)
     392        #C  = self.codomain()
     393        #M  = self.matrix()
     394        #Mr = M.restrict_domain(sub)
     395        #return sub.Hom(C)(Mr)
    396396
    397397    def restrict_codomain(self, sub):
    398398        """
    399         Restrict this matrix morphism to a subspace sub of the codomain.
    400        
    401         The resulting morphism has the same domain as before, but a new
    402         codomain.
    403         """
    404         A = self.matrix().restrict_codomain(sub.free_module())
     399        Restrict this matrix morphism to a subspace sub of the codomain.
     400       
     401        The resulting morphism has the same domain as before, but a new
     402        codomain.
     403        """
     404        A = self.matrix().restrict_codomain(sub.free_module())
    405405        H = sage.categories.homset.Hom(self.domain(), sub, self.domain().category())
    406406        return H(A)
    407407
  • sage/monoids/string_monoid.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/monoids/string_monoid.py
    a b  
    3535    EXAMPLES:
    3636        sage: S = BinaryStrings(); S
    3737        Free binary string monoid
    38         sage: u = S('')
    39         sage: u
    40        
     38        sage: u = S('')
     39        sage: u
     40       
    4141        sage: x = S('0')
    42         sage: x
    43         0
     42        sage: x
     43        0
    4444        sage: y = S('1')
    45         sage: y
    46         1
     45        sage: y
     46        1
    4747        sage: z = S('01110')
    48         sage: z
     48        sage: z
    4949        01110
    5050        sage: x*y^3*x == z
    51         True
    52         sage: u*x == x*u
    53         True
     51        True
     52        sage: u*x == x*u
     53        True
    5454    """
    5555    # Here we cache the binary strings to make them unique
    5656    if _cache.has_key(2):
     
    7878        0
    7979        sage: x[7]
    8080        7
    81         sage: x[0] * x[3]^3 * x[5]^4 * x[6]
     81        sage: x[0] * x[3]^3 * x[5]^4 * x[6]
    8282        033355556
    8383    """
    8484    # Here we cache the octal strings to make them unique
     
    106106        sage: x = S.gen(0)
    107107        sage: y = S.gen(10)
    108108        sage: z = S.gen(15)
    109         sage: z
     109        sage: z
    110110        f
    111111        sage: x*y^3*z
    112         0aaaf
     112        0aaaf
    113113    """
    114114    # Here we cache the hexadecimal strings to make them unique
    115115    if _cache.has_key(16):
     
    140140        sage: S = Radix64Strings(); S
    141141        Free radix 64 string monoid
    142142        sage: x = S.gens()
    143         sage: x[0]
    144         A
     143        sage: x[0]
     144        A
    145145        sage: x[62]
    146         +
     146        +
    147147        sage: x[63]
    148         /
     148        /
    149149    """
    150150    # Here we cache the radix-64 strings to make them unique
    151151    if _cache.has_key(64):
     
    172172        sage: S = AlphabeticStrings(); S
    173173        Free alphabetic string monoid on A-Z
    174174        sage: x = S.gens()
    175         sage: x[0]
    176         A
     175        sage: x[0]
     176        A
    177177        sage: x[25]
    178         Z
     178        Z
    179179    """
    180180    # Here we cache the alphabetic strings to make them unique
    181181    if _cache.has_key(26):
     
    197197        Create free binary string monoid on $n$ generators$.
    198198
    199199        INPUT:
    200             n: Integer
    201             alphabet: String or tuple whose characters or elements denote the generators.
     200            n: Integer
     201            alphabet: String or tuple whose characters or elements denote the generators.
    202202       
    203203        EXAMPLES:
    204204            sage: S = BinaryStrings(); S
     
    208208            01111101
    209209        """
    210210        # Names must be alphabetical -- omitted since printing is defined locally
    211         # FreeMonoid_class.__init__(self, n, names = alphabet)
    212         FreeMonoid_class.__init__(self, n)
    213         self._alphabet = alphabet
     211        # FreeMonoid_class.__init__(self, n, names = alphabet)
     212        FreeMonoid_class.__init__(self, n)
     213        self._alphabet = alphabet
    214214
    215215    def __contains__(self, x):
    216216        return isinstance(x, StringMonoidElement) and x.parent() == self
     
    239239            sage: S.gen(0)
    240240            0
    241241            sage: S.gen(12)
    242             c
     242            c
    243243            sage: S.gen(16)
    244244            Traceback (most recent call last):
    245245            ...
    246246            IndexError: Argument i (= 16) must be between 0 and 15.
    247247        """
    248         n = self.ngens()
     248        n = self.ngens()
    249249        if i < 0 or not i < n:
    250250            raise IndexError, "Argument i (= %s) must be between 0 and %s."%(i,n-1)
    251251        return StringMonoidElement(self,[int(i)])
     
    271271            sage: x[0]*x[1]**5 * (x[0]*x[1])
    272272            01111101
    273273        """
    274         StringMonoid_class.__init__(self, 2, ['0','1'])
     274        StringMonoid_class.__init__(self, 2, ['0','1'])
    275275
    276276    def __cmp__(self, other):
    277277        if not isinstance(other, BinaryStringMonoid):
     
    286286        Return $x$ coerced into this free monoid.
    287287
    288288        One can create a free binary string monoid element from a
    289         Python string of 0's and 1's or list integers
     289        Python string of 0's and 1's or list integers
    290290
    291         NOTE: Due to the ambiguity of the second generator '1' with the that the
    292         identity element '' of the monoid, the syntax S(1) is not permissible.
     291        NOTE: Due to the ambiguity of the second generator '1' with the that the
     292        identity element '' of the monoid, the syntax S(1) is not permissible.
    293293
    294294        EXAMPLES:
    295295            sage: S = BinaryStrings()
     
    298298            sage: S.gen(0)
    299299            0
    300300            sage: S.gen(1)
    301             1
     301            1
    302302        """
    303303        ## There should really some careful type checking here...
    304304        if isinstance(x, StringMonoidElement) and x.parent() == self:
     
    327327
    328328        Set padic = True to reverse the bit string.
    329329
    330         EXAMPLES:       
    331             sage: S = BinaryStrings()
    332             sage: S.encoding('A')
    333             01000001
    334             sage: S.encoding('A',padic=True)
    335             10000010
    336             sage: S.encoding(' ',padic=True)
    337             00000100
     330        EXAMPLES:       
     331            sage: S = BinaryStrings()
     332            sage: S.encoding('A')
     333            01000001
     334            sage: S.encoding('A',padic=True)
     335            10000010
     336            sage: S.encoding(' ',padic=True)
     337            00000100
    338338        """
    339         from Crypto.Util.number import bytes_to_long
     339        from Crypto.Util.number import bytes_to_long
    340340        bit_string = [ ]
    341341        for i in range(len(S)):
    342342            n = int(bytes_to_long(S[i]))
     
    365365            sage: x = S.gens()
    366366            sage: (x[0]*x[7])**3 * (x[0]*x[1]*x[6]*x[5])**2
    367367            07070701650165
    368             sage: S([ i for i in range(8) ])
    369             01234567
     368            sage: S([ i for i in range(8) ])
     369            01234567
    370370        """
    371         StringMonoid_class.__init__(self, 8, [ str(i) for i in range(8) ])
     371        StringMonoid_class.__init__(self, 8, [ str(i) for i in range(8) ])
    372372
    373373    def __cmp__(self, other):
    374374        if not isinstance(other, OctalStringMonoid):
     
    383383        Return $x$ coerced into this free monoid.
    384384
    385385        One can create a free octal string monoid element from a
    386         Python string of 0's to 7's or list of integers.
     386        Python string of 0's to 7's or list of integers.
    387387
    388388        EXAMPLES:
    389389            sage: S = OctalStrings()
     
    392392            sage: S.gen(0)
    393393            0
    394394            sage: S.gen(1)
    395             1
    396             sage: S([ i for i in range(8) ])
    397             01234567
     395            1
     396            sage: S([ i for i in range(8) ])
     397            01234567
    398398        """
    399399        ## There should really some careful type checking here...
    400400        if isinstance(x, StringMonoidElement) and x.parent() == self:
     
    422422            sage: x = S.gens()
    423423            sage: (x[0]*x[10])**3 * (x[0]*x[1]*x[9]*x[15])**2
    424424            0a0a0a019f019f
    425             sage: S([ i for i in range(16) ])
    426             0123456789abcdef
     425            sage: S([ i for i in range(16) ])
     426            0123456789abcdef
    427427        """
    428         alph = '0123456789abcdef'
    429         StringMonoid_class.__init__(self, 16, [ alph[i] for i in range(16) ])
     428        alph = '0123456789abcdef'
     429        StringMonoid_class.__init__(self, 16, [ alph[i] for i in range(16) ])
    430430
    431431    def __cmp__(self, other):
    432432        if not isinstance(other, HexadecimalStringMonoid):
     
    441441        Return $x$ coerced into this free monoid.
    442442
    443443        One can create a free hexadecimal string monoid element from a
    444         Python string of a list of integers in $\{0,..,15\}$.
     444        Python string of a list of integers in $\{0,..,15\}$.
    445445
    446446        EXAMPLES:
    447447            sage: S = HexadecimalStrings()
     
    450450            sage: S.gen(0)
    451451            0
    452452            sage: S.gen(1)
    453             1
    454             sage: S([ i for i in range(16) ])
    455             0123456789abcdef
     453            1
     454            sage: S([ i for i in range(16) ])
     455            0123456789abcdef
    456456        """
    457457        ## There should really some careful type checking here...
    458458        if isinstance(x, StringMonoidElement) and x.parent() == self:
     
    478478            Z = '\x5a' -> 5a
    479479       
    480480        rather than a left-to-right representation A = 65 -> 14.
    481         Although standard (e.g., in the Python constructor '\xhh'),
     481        Although standard (e.g., in the Python constructor '\xhh'),
    482482        this can be confusing when the string reads left-to-right.
    483483
    484484        Set padic = True to reverse the character encoding.
    485485
    486         EXAMPLES:       
    487             sage: S = HexadecimalStrings()
    488             sage: S.encoding('A')
    489             41
    490             sage: S.encoding('A',padic=True)
    491             14
    492             sage: S.encoding(' ',padic=False)
    493             20
    494             sage: S.encoding(' ',padic=True)
    495             02
     486        EXAMPLES:       
     487            sage: S = HexadecimalStrings()
     488            sage: S.encoding('A')
     489            41
     490            sage: S.encoding('A',padic=True)
     491            14
     492            sage: S.encoding(' ',padic=False)
     493            20
     494            sage: S.encoding(' ',padic=True)
     495            02
    496496        """
    497         from Crypto.Util.number import bytes_to_long
     497        from Crypto.Util.number import bytes_to_long
    498498        hex_string = [ ]
    499499        for i in range(len(S)):
    500500            n = int(bytes_to_long(S[i]))
    501             n0 = n % 16; n1 = n // 16
    502             if not padic:
    503                 hex_chars = [n1,n0]
    504             else:
    505                 hex_chars = [n0,n1]
     501            n0 = n % 16; n1 = n // 16
     502            if not padic:
     503                hex_chars = [n1,n0]
     504            else:
     505                hex_chars = [n0,n1]
    506506            hex_string.extend(hex_chars)
    507507        return self(hex_string)
    508508
     
    521521            Free radix 64 string monoid
    522522            sage: x = S.gens()
    523523            sage: (x[50]*x[10])**3 * (x[60]*x[1]*x[19]*x[35])**2
    524             yKyKyK8BTj8BTj
    525             sage: S([ i for i in range(64) ])
    526             ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
     524            yKyKyK8BTj8BTj
     525            sage: S([ i for i in range(64) ])
     526            ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
    527527        """
    528         alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    529         StringMonoid_class.__init__(self, 64, [ alph[i] for i in range(64) ])
     528        alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
     529        StringMonoid_class.__init__(self, 64, [ alph[i] for i in range(64) ])
    530530
    531531
    532532    def __cmp__(self, other):
     
    543543
    544544        One can create a free radix 64 string monoid element from a
    545545        Python string or a list of integers in $0,..,63$, as for
    546         generic FreeMonoids. 
     546        generic FreeMonoids. 
    547547
    548548        EXAMPLES:
    549549            sage: S = Radix64Strings()
    550550            sage: S.gen(0)
    551551            A
    552552            sage: S.gen(1)
    553             B
     553            B
    554554            sage: S.gen(62)
    555             +
     555            +
    556556            sage: S.gen(63)
    557             /
    558             sage: S([ i for i in range(64) ])
    559             ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
     557            /
     558            sage: S([ i for i in range(64) ])
     559            ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
    560560        """
    561561        ## There should really some careful type checking here...
    562562        if isinstance(x, StringMonoidElement) and x.parent() == self:
     
    582582            sage: S = AlphabeticStrings(); S
    583583            Free alphabetic string monoid on A-Z
    584584            sage: S.gen(0)
    585             A
     585            A
    586586            sage: S.gen(25)
    587             Z
    588             sage: S([ i for i in range(26) ])
    589             ABCDEFGHIJKLMNOPQRSTUVWXYZ
     587            Z
     588            sage: S([ i for i in range(26) ])
     589            ABCDEFGHIJKLMNOPQRSTUVWXYZ
    590590        """
    591         alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    592         StringMonoid_class.__init__(self, 26, [ alph[i] for i in range(26) ])
     591        alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     592        StringMonoid_class.__init__(self, 26, [ alph[i] for i in range(26) ])
    593593
    594594    def __cmp__(self, other):
    595595        if not isinstance(other, AlphabeticStringMonoid):
     
    611611            sage: S.gen(0)
    612612            A
    613613            sage: S.gen(1)
    614             B
     614            B
    615615            sage: S.gen(25)
    616             Z
    617             sage: S([ i for i in range(26) ])
    618             ABCDEFGHIJKLMNOPQRSTUVWXYZ
     616            Z
     617            sage: S([ i for i in range(26) ])
     618            ABCDEFGHIJKLMNOPQRSTUVWXYZ
    619619        """
    620620        ## There should really some careful type checking here...
    621621        if isinstance(x, StringMonoidElement) and x.parent() == self:
     
    638638
    639639        It should be noted that this is a non-injective monoid homomorphism.
    640640
    641         EXAMPLES:
    642             sage: S = AlphabeticStrings()
    643             sage: s = S.encoding("The cat in the hat."); s
    644             THECATINTHEHAT
    645             sage: s.decoding()
    646             'THECATINTHEHAT'
    647         """
     641        EXAMPLES:
     642            sage: S = AlphabeticStrings()
     643            sage: s = S.encoding("The cat in the hat."); s
     644            THECATINTHEHAT
     645            sage: s.decoding()
     646            'THECATINTHEHAT'
     647        """
    648648        return self(strip_encoding(S))
    649649
    650650
  • sage/monoids/string_monoid_element.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/monoids/string_monoid_element.py
    a b  
    230230            'A..Za..z'
    231231        """
    232232        S = self.parent()
    233         from Crypto.Util.number import long_to_bytes
     233        from Crypto.Util.number import long_to_bytes
    234234        if isinstance(S,string_monoid.AlphabeticStringMonoid):
    235235            return ''.join([ long_to_bytes(65+i) for i in self._element_list ])
    236236        n = self.__len__()
     
    292292        """
    293293        if not length in (1,2):
    294294            raise NotImplementedError, "Not implemented"
    295         if prec == 0:
     295        if prec == 0:
    296296            RR = RealField()
    297297        else:       
    298298            RR = RealField(prec)
    299         S = self.parent()
     299        S = self.parent()
    300300        n = S.ngens()
    301         if length == 1:
    302             Alph = S.gens()
    303         else:
    304             Alph = tuple([ x*y for x in S.gens() for y in S.gens() ])
     301        if length == 1:
     302            Alph = S.gens()
     303        else:
     304            Alph = tuple([ x*y for x in S.gens() for y in S.gens() ])
    305305        X = {}
    306306        N = len(self)-length+1
    307307        eps = RR(Integer(1)/N)
    308308        for i in range(N):
    309309            c = self[i:i+length]
    310             if X.has_key(c):
     310            if X.has_key(c):
    311311                X[c] += eps
    312             else:
     312            else:
    313313                X[c] = eps
    314314        return DiscreteProbabilitySpace(Alph,X,RR)
    315315
  • sage/monoids/string_ops.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/monoids/string_ops.py
    a b  
    1919    EXAMPLES:
    2020        sage: S = "The cat in the hat."
    2121        sage: strip_encoding(S)
    22         'THECATINTHEHAT'
     22        'THECATINTHEHAT'
    2323    """
    2424    if not isinstance(S,str):
    2525        raise TypeError, "Argument S (= %s) must be a string."
    2626    X = ''
    2727    for i in range(len(S)):
    28         C = S[i]
    29         if C.isalpha():
    30             X += S[i].upper()
     28        C = S[i]
     29        if C.isalpha():
     30            X += S[i].upper()
    3131    return X
    3232
    3333def frequency_distribution(S, n=1, field=None):
     
    4747        for i in range(N):
    4848            c = S[i]
    4949            if P.has_key(c):
    50                 P[c] += eps
     50                P[c] += eps
    5151            else:
    52                 P[c] = eps
     52                P[c] = eps
    5353        return DiscreteProbabilitySpace(S,P,field)
    5454    raise TypeError, "Argument S (= %s) must be a string, list, or tuple."
    5555
     
    5757    """
    5858    The coincidence index of the string S.
    5959    EXAMPLES:
    60         sage: S = strip_encoding("The cat in the hat.")
    61         sage: coincidence_index(S)
    62         0.120879120879121
     60        sage: S = strip_encoding("The cat in the hat.")
     61        sage: coincidence_index(S)
     62        0.120879120879121
    6363    """
    6464    if not isinstance(S,str):
    6565        try:
    66             S.coincidence_index(n)
    67         except AttributeError:
     66            S.coincidence_index(n)
     67        except AttributeError:
    6868            raise TypeError, "Argument S (= %s) must be a string."
    6969    S = strip_encoding(S)
    7070    N = len(S)-n+1
     
    7373        c = S[i:i+n]
    7474        if X.has_key(c):
    7575            X[c] += 1
    76         else:              
     76        else:              
    7777            X[c] = 1
    7878    RR = RealField()
    7979    return RR(sum([ m*(m-1) for m in X.values() ]))/RR(N*(N-1))
     
    8686    character pairs, relative to their independent one-character probabilities.
    8787
    8888    EXAMPLES:
    89         sage: S = strip_encoding("The cat in the hat.")
    90         sage: coincidence_discriminant([ S[i:i+2] for i in range(len(S)-1) ])
     89        sage: S = strip_encoding("The cat in the hat.")
     90        sage: coincidence_discriminant([ S[i:i+2] for i in range(len(S)-1) ])
    9191        0.0827001855677322
    9292    """         
    9393    if not isinstance(S,(list,tuple)):
     
    9696        raise ValueError, "Argument n (= %s) is only implemented for n = 2" % n
    9797    truth = True
    9898    for bool in ( isinstance(c,(str,StringMonoidElement)) for c in S ):
    99         truth = truth and bool
     99        truth = truth and bool
    100100    if not truth:
    101101        raise TypeError, "Argument S (= %s) must be a list of strings."
    102102    for bool in ( len(c) == n for c in S ):
    103         truth = truth and bool
     103        truth = truth and bool
    104104    if not truth:
    105105        raise ValueError, "Argument S (= %s) must be a list of strings of length 2" % S
    106106    X1 = [ frequency_distribution([ s[i] for s in S]) for i in range(2) ]
    107107    XX = frequency_distribution(S)
    108108    if isinstance(S[0],StringMonoidElement):
    109         M = S[0].parent()
    110         n = M.ngens()
     109        M = S[0].parent()
     110        n = M.ngens()
    111111        return sum([ (XX(M([i,j]))-X1[0](M([i]))*X1[1](M([j])))**2 for i in range(n) for j in range(n) ])
    112112    AZ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    113113    return sum([ (XX(AZ[i]+AZ[j])-X1[0](AZ[i])*X1[1](AZ[j]))**2 for i in range(26) for j in range(26) ])
  • sage/plot/bezier_path.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/plot/bezier_path.py
    a b  
    6262                'thickness':'How thick the border of the polygon is.',
    6363                'rgbcolor':'The color as an rgb tuple.',
    6464                'zorder':'The layer level in which to draw',
    65                                 'linestyle':"The style of the line, which is one of 'dashed', 'dotted', 'solid', 'dashdot'."}
     65                                'linestyle':"The style of the line, which is one of 'dashed', 'dotted', 'solid', 'dashdot'."}
    6666               
    6767    def _repr_(self):
    6868        return "Bezier path from %s to %s"%(self.path[0][0],self.path[-1][-1])
  • sage/plot/disk.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/plot/disk.py
    a b  
    6969        deg1 = self.rad1*(360.0/(2.0*pi)) #convert radians to degrees
    7070        deg2 = self.rad2*(360.0/(2.0*pi))
    7171        p = patches.Wedge((float(self.x), float(self.y)), float(self.r), float(deg1),
    72                             float(deg2))       
     72                            float(deg2))
    7373        p.set_linewidth(float(options['thickness']))
    7474        p.set_fill(options['fill'])
    7575        p.set_alpha(options['alpha'])
  • sage/plot/plot.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/plot/plot.py
    a b  
    23712371        self._rows = len(array)
    23722372        if self._rows > 0:
    23732373            if not isinstance(array[0], (list, tuple)):
    2374                 array = [array] 
     2374                array = [array]
    23752375                self._rows = 1
    23762376            self._cols = len(array[0])
    23772377        else:
  • sage/plot/tachyon.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/plot/tachyon.py
    a b  
    435435        self._objects.append(FCylinder(base, apex, radius, texture))
    436436
    437437    def triangle(self, vertex_1, vertex_2, vertex_3, texture):
    438         self._objects.append(TachyonTriangle(vertex_1,vertex_2,vertex_3,texture))
     438        self._objects.append(TachyonTriangle(vertex_1,vertex_2,vertex_3,texture))
    439439
    440440    def smooth_triangle(self, vertex_1, vertex_2, vertex_3, normal_1, normal_2, normal_3, texture):
    441441         self._objects.append(TachyonSmoothTriangle(vertex_1, vertex_2, vertex_3, normal_1, normal_2, normal_3, texture))
  • sage/probability/random_variable.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/probability/random_variable.py
    a b  
    5353        self._codomain = RR
    5454
    5555    def probability_space(self):
    56         return self.base()
     56        return self.base()
    5757
    5858    def domain(self):
    59         return self.base()
     59        return self.base()
    6060
    6161    def codomain(self):
    62         return self._codomain
     62        return self._codomain
    6363
    6464    def field(self):
    65         return self._codomain
     65        return self._codomain
    6666
    6767class DiscreteRandomVariable(RandomVariable_generic):
    6868    """
     
    7777        """
    7878        if not is_DiscreteProbabilitySpace(X):
    7979            raise TypeError, "Argument X (= %s) must be a discrete probability space" % X
    80         if check:
    81             raise NotImplementedError, "Not implemented"
     80        if check:
     81            raise NotImplementedError, "Not implemented"
    8282        if codomain is None:
    83             RR = RealField()
    84         else:
    85             RR = codomain
     83            RR = RealField()
     84        else:
     85            RR = codomain
    8686        RandomVariable_generic.__init__(self, X, RR)
    8787        self._function = f
    8888
     
    9090        """
    9191        Return the value of the random variable at x.
    9292        """
    93         RR = self.field()
     93        RR = self.field()
    9494        try:
    9595            return RR(self._function[x])
    9696        except KeyError:
    97             # Need some condition for x being a valid domain element:
    98             #    raise IndexError, "Argument x (= %s) is not a valid domain element." % x
     97            # Need some condition for x being a valid domain element:
     98            #    raise IndexError, "Argument x (= %s) is not a valid domain element." % x
    9999            return RR(0)
    100100       
    101101    def __repr__(self):
    102         return "Discrete random variable defined by %s" % self._function
     102        return "Discrete random variable defined by %s" % self._function
    103103       
    104104    def function(self):
    105         """
    106         The function defining the random variable.
    107         """
    108         return self._function
     105        """
     106        The function defining the random variable.
     107        """
     108        return self._function
    109109
    110110    def expectation(self):
    111111        r"""
     
    146146        """
    147147        Omega = self.probability_space()
    148148        mu = self.expectation()
    149         var = 0   
     149        var = 0   
    150150        for x in self._function.keys():
    151151            var += Omega(x) * (self(x) - mu)**2
    152152        return var
     
    166166        """
    167167        Omega = self.probability_space()
    168168        mu = self.translation_expectation(map)
    169         var = 0   
    170         for x in Omega._function.keys():
     169        var = 0   
     170        for x in Omega._function.keys():
    171171            var += Omega(x) * (self(map(x)) - mu)**2
    172172        return var
    173173
     
    185185                     \text{cov}(X,Y) = E((X-E(X)*(Y-E(Y)) = \sum_{x \in S} p(x) (X(x) - E(X))(Y(x) - E(Y))
    186186        """
    187187        Omega = self.probability_space()
    188         if Omega != other.probability_space():
    189             raise ValueError, \
    190                 "Argument other (= %s) must be defined on the same probability space." % other
     188        if Omega != other.probability_space():
     189            raise ValueError, \
     190                "Argument other (= %s) must be defined on the same probability space." % other
    191191        muX = self.expectation()
    192192        muY = other.expectation()
    193         cov = 0
    194         for x in self._function.keys():
     193        cov = 0
     194        for x in self._function.keys():
    195195            cov += Omega(x)*(self(x) - muX)*(other(x) - muY)
    196196        return cov
    197197
     
    209209                     \text{cov}(X,Y) = E((X-E(X)*(Y-E(Y)) = \sum_{x \in S} p(x) (X(x) - E(X))(Y(x) - E(Y))
    210210        """
    211211        Omega = self.probability_space()
    212         if Omega != other.probability_space():
    213             raise ValueError, \
    214                 "Argument other (= %s) must be defined on the same probability space." % other
     212        if Omega != other.probability_space():
     213            raise ValueError, \
     214                "Argument other (= %s) must be defined on the same probability space." % other
    215215        muX = self.expectation()
    216216        muY = other.translation_expectation(map)
    217         cov = 0
    218         for x in Omega._function.keys():
     217        cov = 0
     218        for x in Omega._function.keys():
    219219            cov += Omega(x)*(self(x) - muX)*(other(map(x)) - muY)
    220220        return cov
    221221
     
    255255        """
    256256        The correlation of the probability space X = self with Y = other.
    257257        """
    258         cov = self.covariance(other)
    259         sigX = self.standard_deviation()
    260         sigY = other.standard_deviation()
    261         if sigX == 0 or sigY == 0:
    262             raise ValueError, \
    263                 "Correlation not defined if standard deviations are not both nonzero."
    264         return cov/(sigX*sigY)
     258        cov = self.covariance(other)
     259        sigX = self.standard_deviation()
     260        sigY = other.standard_deviation()
     261        if sigX == 0 or sigY == 0:
     262            raise ValueError, \
     263                "Correlation not defined if standard deviations are not both nonzero."
     264        return cov/(sigX*sigY)
    265265
    266266    def translation_correlation(self, other, map):
    267267        """
    268268        The correlation of the probability space X = self with image of Y =
    269269        other under map.
    270270        """
    271         cov = self.translation_covariance(other, map)
    272         sigX = self.standard_deviation()
    273         sigY = other.translation_standard_deviation(map)
    274         if sigX == 0 or sigY == 0:
    275             raise ValueError, \
    276                 "Correlation not defined if standard deviations are not both nonzero."
    277         return cov/(sigX*sigY)
     271        cov = self.translation_covariance(other, map)
     272        sigX = self.standard_deviation()
     273        sigY = other.translation_standard_deviation(map)
     274        if sigX == 0 or sigY == 0:
     275            raise ValueError, \
     276                "Correlation not defined if standard deviations are not both nonzero."
     277        return cov/(sigX*sigY)
    278278
    279279################################################################################
    280280################################################################################
     
    284284    A probability space.
    285285    """
    286286    def __init__(self, domain, RR):
    287         """
    288         A generic probability space on given domain space and codomain
    289         ring.
    290         """
    291         if isinstance(domain, list):
    292             domain = tuple(domain)
    293         if not isinstance(domain, tuple):
    294             raise TypeError, \
     287        """
     288        A generic probability space on given domain space and codomain
     289        ring.
     290        """
     291        if isinstance(domain, list):
     292            domain = tuple(domain)
     293        if not isinstance(domain, tuple):
     294            raise TypeError, \
    295295                "Argument domain (= %s) must be a list, tuple, or set containing." % domain
    296         self._domain = domain
     296        self._domain = domain
    297297        RandomVariable_generic.__init__(self, self, RR)
    298298
    299299    def domain(self):
     
    305305    """
    306306    def __init__(self, X, P, codomain = None, check = False):
    307307        r"""
    308         Create the discrete probability space with probabilities on the
    309         space X given by the dictionary P with values in the field
    310         real_field.
    311        
    312         EXAMPLES::
    313        
    314             sage: S = [ i for i in range(16) ]
    315             sage: P = {}
    316                    sage: for i in range(15): P[i] = 2^(-i-1)
    317             sage: P[15] = 2^-16
    318             sage: X = DiscreteProbabilitySpace(S,P)
    319             sage: X.domain()
    320             (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
    321             sage: X.set()
    322             {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
    323             sage: X.entropy()
    324                    1.9997253418
    325        
    326         A probability space can be defined on any list of elements.
    327        
    328         EXAMPLES::
    329        
    330             sage: AZ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    331             sage: S = [ AZ[i] for i in range(26) ]
    332             sage: P = { 'A':1/2, 'B':1/4, 'C':1/4 }
    333             sage: X = DiscreteProbabilitySpace(S,P)
    334             sage: X
    335             Discrete probability space defined by {'A': 1/2, 'C': 1/4, 'B': 1/4}
    336             sage: X.entropy()
    337                    1.5
    338         """
     308        Create the discrete probability space with probabilities on the
     309        space X given by the dictionary P with values in the field
     310        real_field.
     311       
     312        EXAMPLES::
     313       
     314            sage: S = [ i for i in range(16) ]
     315            sage: P = {}
     316                   sage: for i in range(15): P[i] = 2^(-i-1)
     317            sage: P[15] = 2^-16
     318            sage: X = DiscreteProbabilitySpace(S,P)
     319            sage: X.domain()
     320            (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
     321            sage: X.set()
     322            {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
     323            sage: X.entropy()
     324                   1.9997253418
     325       
     326        A probability space can be defined on any list of elements.
     327       
     328        EXAMPLES::
     329       
     330            sage: AZ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     331            sage: S = [ AZ[i] for i in range(26) ]
     332            sage: P = { 'A':1/2, 'B':1/4, 'C':1/4 }
     333            sage: X = DiscreteProbabilitySpace(S,P)
     334            sage: X
     335            Discrete probability space defined by {'A': 1/2, 'C': 1/4, 'B': 1/4}
     336            sage: X.entropy()
     337                   1.5
     338        """
    339339        if codomain is None:
    340             codomain = RealField()
    341         if not is_RealField(codomain) and not is_RationalField(codomain):
    342             raise TypeError, "Argument codomain (= %s) must be the reals or rationals" % codomain
    343         if check:
    344             one = sum([ P[x] for x in P.keys() ])
    345             if is_RationalField(codomain):   
    346                 if not one == 1:
    347                     raise TypeError, "Argument P (= %s) does not define a probability function"
    348             else:
    349                 if not Abs(one-1) < 2^(-codomain.precision()+1):
    350                     raise TypeError, "Argument P (= %s) does not define a probability function"
     340            codomain = RealField()
     341        if not is_RealField(codomain) and not is_RationalField(codomain):
     342            raise TypeError, "Argument codomain (= %s) must be the reals or rationals" % codomain
     343        if check:
     344            one = sum([ P[x] for x in P.keys() ])
     345            if is_RationalField(codomain):   
     346                if not one == 1:
     347                    raise TypeError, "Argument P (= %s) does not define a probability function"
     348            else:
     349                if not Abs(one-1) < 2^(-codomain.precision()+1):
     350                    raise TypeError, "Argument P (= %s) does not define a probability function"
    351351        ProbabilitySpace_generic.__init__(self, X, codomain)
    352352        DiscreteRandomVariable.__init__(self, self, P, codomain, check)
    353353
    354354    def __repr__(self):
    355         return "Discrete probability space defined by %s" % self.function()
     355        return "Discrete probability space defined by %s" % self.function()
    356356       
    357357    def set(self):
    358358        r"""
    359359        The set of values of the probability space taking possibly nonzero
    360360        probability (a subset of the domain).
    361361        """
    362         return Set(self.function().keys())
     362        return Set(self.function().keys())
    363363
    364364    def entropy(self):
    365365        """
    366366        The entropy of the probability space.
    367367        """
    368         def neg_xlog2x(p):
    369             if p == 0:
    370                 return 0
    371             else: 
    372                 return -p*log(p,2)
    373         p = self.function()
    374         return sum([ neg_xlog2x(p[x]) for x in p.keys() ])
    375                
     368        def neg_xlog2x(p):
     369            if p == 0:
     370                return 0
     371            else: 
     372                return -p*log(p,2)
     373        p = self.function()
     374        return sum([ neg_xlog2x(p[x]) for x in p.keys() ])
     375               
  • sage/rings/arith.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/arith.py
    a b  
    25182518    """
    25192519    s, c = 0, 1
    25202520    for k in ks:
    2521         s += k
    2522         c *= binomial(s, k)
     2521        s += k
     2522        c *= binomial(s, k)
    25232523    return c
    25242524
    25252525def binomial_coefficients(n):
  • sage/rings/finite_field_givaro.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/finite_field_givaro.pyx
    a b  
    437437            sage: k, a = FiniteField_givaro(5^2, 'a').objgen()
    438438            sage: k(R(2/3))
    439439            4
    440             sage: k(x^2)
    441             a + 3
     440            sage: k(x^2)
     441            a + 3
    442442            sage: R.<x> = GF(5)[]
    443443            sage: k(x^3-2*x+1)
    444444            2*a + 4
     
    463463            sage: k(R(1/5))
    464464            Traceback (most recent call last):
    465465            ...
    466             ZeroDivisionError: division by zero in finite field.
     466            ZeroDivisionError: division by zero in finite field.
    467467
    468468       
    469469            PARI elements are interpreted as finite field elements; this PARI flexibility
     
    933933        """
    934934        Return integer representation of e.
    935935       
    936         Elements of this field are represented as ints in as follows:
     936        Elements of this field are represented as ints in as follows:
    937937        for $e \in \FF_p[x]$ with $e = a_0 + a_1x + a_2x^2 + \cdots $, $e$ is
    938938        represented as: $n= a_0 + a_1  p + a_2  p^2 + \cdots$.
    939939
  • sage/rings/finite_field_ntl_gf2e.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/finite_field_ntl_gf2e.pyx
    a b  
    359359            ...
    360360            NameError: name 'b' is not defined
    361361
    362             sage: R.<x>=GF(2)[]
    363             sage: k(1+x+x^10+x^55)
    364             a^19 + a^17 + a^16 + a^15 + a^12 + a^11 + a^8 + a^6 + a^4 + a^2 + 1
     362            sage: R.<x>=GF(2)[]
     363            sage: k(1+x+x^10+x^55)
     364            a^19 + a^17 + a^16 + a^15 + a^12 + a^11 + a^8 + a^6 + a^4 + a^2 + 1
    365365
    366366            sage: V = k.vector_space()
    367367            sage: v = V.random_element(); v
  • sage/rings/integer_mod.pyx

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/integer_mod.pyx
    a b  
    10001000        ``other`` must be coprime to the modulus of
    10011001        ``self``.
    10021002
    1003         EXAMPLES::
     1003        EXAMPLES::
    10041004       
    10051005            sage: a = mod(3,5)
    10061006            sage: b = mod(2,7)
     
    17041704        to other. The modulus of other must be coprime to the modulus of
    17051705        self.
    17061706
    1707         EXAMPLES::
     1707        EXAMPLES::
    17081708       
    17091709            sage: a = mod(3,5)
    17101710            sage: b = mod(2,7)
     
    24562456        to other. The modulus of other must be coprime to the modulus of
    24572457        self.
    24582458
    2459         EXAMPLES::
     2459        EXAMPLES::
    24602460       
    24612461            sage: a = mod(3,5^10)
    24622462            sage: b = mod(2,7)
  • sage/rings/number_field/number_field.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/number_field/number_field.py
    a b  
    69806980        return self.extension(f, names)
    69816981
    69826982    def hilbert_class_polynomial(self, name='x'):
    6983         r"""
    6984         Compute the Hilbert class polynomial of this quadratic field.
     6983        r"""
     6984        Compute the Hilbert class polynomial of this quadratic field.
    69856985
    69866986        Right now, this is only implemented for imaginary quadratic
    69876987        fields.
    6988        
    6989         EXAMPLES::
     6988       
     6989        EXAMPLES::
    69906990
    69916991            sage: K.<a> = QuadraticField(-3)
    69926992            sage: K.hilbert_class_polynomial()
     
    69956995            sage: K.<a> = QuadraticField(-31)
    69966996            sage: K.hilbert_class_polynomial(name='z')
    69976997            z^3 + 39491307*z^2 - 58682638134*z + 1566028350940383
    6998         """
    6999         D = self.discriminant()
     6998        """
     6999        D = self.discriminant()
    70007000
    70017001        if D > 0:
    70027002            raise NotImplementedError, "Hilbert class polynomial is not implemented for real quadratic fields."
    70037003
    7004         # get all reduced quadratic forms
     7004        # get all reduced quadratic forms
    70057005        from sage.quadratic_forms.binary_qf import BinaryQF_reduced_representatives
    7006         rqf = BinaryQF_reduced_representatives(D)
    7007 
    7008         # compute needed  precision     
    7009         # (according to [http://arxiv.org/abs/0802.0979v1])
    7010         N = (D.abs()//3).isqrt()+1
    7011         h = len(rqf)
    7012         a_s = [1/qf.a for qf in rqf]
     7006        rqf = BinaryQF_reduced_representatives(D)
     7007
     7008        # compute needed  precision     
     7009        # (according to [http://arxiv.org/abs/0802.0979v1])
     7010        N = (D.abs()//3).isqrt()+1
     7011        h = len(rqf)
     7012        a_s = [1/qf.a for qf in rqf]
    70137013        from sage.rings.all import RR
    7014         prec = RR(sum(a_s, 0)*5.1416*D.abs().isqrt()+h*2.48).floor()+1
    7015         prec = max(prec, 71)
    7016                                                                                                                        
    7017         # set appropriate precision for further computing
     7014        prec = RR(sum(a_s, 0)*5.1416*D.abs().isqrt()+h*2.48).floor()+1
     7015        prec = max(prec, 71)
     7016                                                                                                                       
     7017        # set appropriate precision for further computing
    70187018        from sage.rings.all import ComplexField
    7019         __CC = ComplexField(prec)
     7019        __CC = ComplexField(prec)
    70207020
    70217021        Dsqrt = D.sqrt(prec=prec)
    7022         R = __CC['t']
     7022        R = __CC['t']
    70237023        t = R.gen()
    7024         pol = R(1)
     7024        pol = R(1)
    70257025        for qf in rqf:
    70267026            tau = (qf.b+Dsqrt)/(qf.a<<1)
    70277027            jinv = pari(tau).ellj()
    70287028            pol = pol * (t - __CC(jinv))
    7029        
    7030         coeffs = [cof.real().round() for cof in pol.coeffs()]
     7029       
     7030        coeffs = [cof.real().round() for cof in pol.coeffs()]
    70317031        R = ZZ[name]
    7032         return R(coeffs)
     7032        return R(coeffs)
    70337033
    70347034
    70357035
  • sage/rings/number_field/totallyreal_phc.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/number_field/totallyreal_phc.py
    a b  
    8989        sage: __lagrange_bounds_phc(3,5,[8,1,2,0,1]) # optional
    9090        []
    9191        sage: x, y = __lagrange_bounds_phc(3,2,[8,1,2,0,1]) # optional
    92         sage: x # optional
     92        sage: x # optional
    9393        -1.3333333333333299
    94         sage: y < 0.00000001 # optional
    95         True
     94        sage: y < 0.00000001 # optional
     95        True
    9696        sage: __lagrange_bounds_phc(3,1,[8,1,2,0,1]) # optional
    9797        []   
    9898    """
  • sage/rings/padics/local_generic.py

    diff -r 84d47cdd7003 -r 203bbc5a8a5f sage/rings/padics/local_generic.py
    a b  
    6969        EXAMPLES:
    7070            sage: R = Zp(3, 10,'fixed-mod'); R.precision_cap()
    7171            10
    72             sage: R = Zp(3, 10,'capped-rel'); R.precision_cap()
    73             10     
    74             sage: R = Zp(3, 10,'capped-abs'); R.precision_cap()
    75             10
     72            sage: R = Zp(3, 10,'capped-rel'); R.precision_cap()
     73            10     
     74            sage: R = Zp(3, 10,'capped-abs'); R.precision_cap()
     75            10
    7676
    77             #sage: R = Zp(3, 10, 'lazy'); R.precision_cap()
    78             #10
     77            #sage: R = Zp(3, 10, 'lazy'); R.precision_cap()
     78            #10
    7979
    8080        NOTES:
    8181            This will have different meanings depending on the type of local ring.
     
    104104        OUTPUT:
    105105            boolean -- whether self's representation is atomic, i.e., False
    106106
    107         EXAMPLES:
    108             sage: R = Zp(5, 5, 'fixed-mod'); R.is_atomic_repr()
     107        EXAMPLES:
     108            sage: R = Zp(5, 5, 'fixed-mod'); R.is_atomic_repr()
    109109            False
    110110
    111111        """
     
    121121        OUTPUT:
    122122            boolean -- whether self is exact, i.e. False.
    123123
    124         EXAMPLES:
    125             #sage: R = Zp(5, 3, 'lazy'); R.is_exact()
    126             #False
     124        EXAMPLES:
     125            #sage: R = Zp(5, 3, 'lazy'); R.is_exact()
     126            #False
    127127            sage: R = Zp(5, 3, 'fixed-mod'); R.is_exact()
    128128            False
    129129        """
    130130        return False
    131131
    132132    def residue_characteristic(self):
    133         r"""
    134         Returns the characteristic of self's residue field.
     133        r"""
     134        Returns the characteristic of self's residue field.
    135135
    136         INPUT:
    137             self -- a p-adic ring.
     136        INPUT:
     137            self -- a p-adic ring.
    138138
    139         OUTPUT:
    140             integer -- the characteristic of the residue field.
     139        OUTPUT:
     140            integer -- the characteristic of the residue field.
    141141
    142         EXAMPLES:
    143             sage: R = Zp(3, 5, 'capped-rel'); R.residue_characteristic()
    144             3
    145         """
     142        EXAMPLES:
     143            sage: R = Zp(3, 5, 'capped-rel'); R.residue_characteristic()
     144            3
     145        """
    146146        return self.residue_class_field().characteristic()
    147147
    148148    def residue_class_field(self):
    149         #ASK: Is this function implemented by subclasses? It seems to work for any specific p-adic ring.
     149        #ASK: Is this function implemented by subclasses? It seems to work for any specific p-adic ring.