Skip to content

Commit bb8b646

Browse files
committed
use the faster binomial in combinat
1 parent dc99dc8 commit bb8b646

File tree

9 files changed

+74
-86
lines changed

9 files changed

+74
-86
lines changed

src/sage/combinat/affine_permutation.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# ****************************************************************************
1414
from itertools import repeat
1515

16-
from sage.arith.misc import binomial
1716
from sage.categories.affine_weyl_groups import AffineWeylGroups
1817
from sage.combinat.composition import Composition
1918
from sage.combinat.partition import Partition
@@ -77,13 +76,13 @@ def __init__(self, parent, lst, check=True):
7776
"""
7877
if check:
7978
lst = [ZZ(val) for val in lst]
80-
self.k = parent.k
79+
self.k = ZZ(parent.k)
8180
self.n = self.k + 1
82-
#This N doesn't matter for type A, but comes up in all other types.
81+
# This N doesn't matter for type A, but comes up in all other types.
8382
if parent.cartan_type()[0] == 'A':
8483
self.N = self.n
8584
elif parent.cartan_type()[0] in ['B', 'C', 'D']:
86-
self.N = 2*self.k + 1
85+
self.N = 2 * self.k + 1
8786
elif parent.cartan_type()[0] == 'G':
8887
self.N = 6
8988
else:
@@ -245,7 +244,7 @@ def is_i_grassmannian(self, i=0, side='right') -> bool:
245244
"""
246245
return self == self.parent().one() or self.descents(side) == [i]
247246

248-
def index_set(self):
247+
def index_set(self) -> tuple:
249248
r"""
250249
Index set of the affine permutation group.
251250
@@ -255,7 +254,7 @@ def index_set(self):
255254
sage: A.index_set()
256255
(0, 1, 2, 3, 4, 5, 6, 7)
257256
"""
258-
return tuple(range(self.k+1))
257+
return tuple(range(self.k + 1))
259258

260259
def lower_covers(self, side='right'):
261260
r"""
@@ -440,13 +439,14 @@ def check(self):
440439
if not self:
441440
return
442441
k = self.parent().k
443-
#Type A.
442+
# Type A
444443
if len(self) != k + 1:
445-
raise ValueError("length of list must be k+1="+str(k+1))
446-
if binomial(k+2,2) != sum(self):
447-
raise ValueError("window does not sum to " + str(binomial((k+2),2)))
448-
l = sorted([i % (k+1) for i in self])
449-
if l != list(range(k+1)):
444+
raise ValueError(f"length of list must be k+1={k + 1}")
445+
sigma = (k + 2).binomial(2)
446+
if sigma != sum(self):
447+
raise ValueError(f"window does not sum to {sigma}")
448+
l = sorted(i % (k + 1) for i in self)
449+
if any(i != j for i, j in enumerate(l)):
450450
raise ValueError("entries must have distinct residues")
451451

452452
def value(self, i, base_window=False):
@@ -2001,9 +2001,9 @@ class AffinePermutationGroupGeneric(UniqueRepresentation, Parent):
20012001
methods for the specific affine permutation groups.
20022002
"""
20032003

2004-
#----------------------
2005-
#Type-free methods.
2006-
#----------------------
2004+
# ----------------------
2005+
# Type-free methods.
2006+
# ----------------------
20072007

20082008
def __init__(self, cartan_type):
20092009
r"""
@@ -2014,13 +2014,13 @@ def __init__(self, cartan_type):
20142014
"""
20152015
Parent.__init__(self, category=AffineWeylGroups())
20162016
ct = CartanType(cartan_type)
2017-
self.k = ct.n
2017+
self.k = ZZ(ct.n)
20182018
self.n = ct.rank()
2019-
#This N doesn't matter for type A, but comes up in all other types.
2019+
# This N doesn't matter for type A, but comes up in all other types.
20202020
if ct.letter == 'A':
20212021
self.N = self.k + 1
20222022
elif ct.letter == 'B' or ct.letter == 'C' or ct.letter == 'D':
2023-
self.N = 2*self.k + 1
2023+
self.N = 2 * self.k + 1
20242024
elif ct.letter == 'G':
20252025
self.N = 6
20262026
self._cartan_type = ct
@@ -2034,14 +2034,14 @@ def _element_constructor_(self, *args, **keywords):
20342034
"""
20352035
return self.element_class(self, *args, **keywords)
20362036

2037-
def _repr_(self):
2037+
def _repr_(self) -> str:
20382038
r"""
20392039
TESTS::
20402040
20412041
sage: AffinePermutationGroup(['A',7,1])
20422042
The group of affine permutations of type ['A', 7, 1]
20432043
"""
2044-
return "The group of affine permutations of type "+str(self.cartan_type())
2044+
return "The group of affine permutations of type " + str(self.cartan_type())
20452045

20462046
def _test_enumeration(self, n=4, **options):
20472047
r"""

src/sage/combinat/baxter_permutations.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
"""
22
Baxter permutations
33
"""
4-
5-
from sage.structure.unique_representation import UniqueRepresentation
6-
from sage.structure.parent import Parent
7-
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
84
from sage.combinat.permutation import Permutations
9-
105
from sage.rings.integer_ring import ZZ
6+
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
7+
from sage.structure.parent import Parent
8+
from sage.structure.unique_representation import UniqueRepresentation
119

1210

1311
class BaxterPermutations(UniqueRepresentation, Parent):
@@ -228,12 +226,11 @@ def cardinality(self):
228226
Integer Ring
229227
"""
230228
if self._n == 0:
231-
return 1
232-
from sage.arith.misc import binomial
233-
return sum((binomial(self._n + 1, k) *
234-
binomial(self._n + 1, k + 1) *
235-
binomial(self._n + 1, k + 2)) //
236-
((self._n + 1) * binomial(self._n + 1, 2))
229+
return ZZ.one()
230+
n = self._n + 1
231+
return sum((n.binomial(k) *
232+
n.binomial(k + 1) *
233+
n.binomial(k + 2)) // (n * n.binomial(2))
237234
for k in range(self._n))
238235

239236

src/sage/combinat/blob_algebra.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,19 @@
1717
# https://www.gnu.org/licenses/
1818
# ****************************************************************************
1919

20-
from sage.structure.parent import Parent
21-
from sage.structure.unique_representation import UniqueRepresentation
22-
from sage.structure.element import Element, get_coercion_model
23-
from sage.structure.richcmp import richcmp
24-
#from sage.misc.inherit_comparison import InheritComparisonClasscallMetaclass
25-
from sage.misc.cachefunc import cached_method
26-
from sage.combinat.subset import powerset
27-
from sage.arith.misc import binomial
28-
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
2920
from sage.categories.algebras import Algebras
21+
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
3022
from sage.combinat.diagram_algebras import (TemperleyLiebDiagrams, diagram_latex,
3123
TL_diagram_ascii_art)
32-
from sage.combinat.free_module import CombinatorialFreeModule
3324
from sage.combinat.dyck_word import DyckWords
34-
35-
#@add_metaclass(InheritComparisonClasscallMetaclass)
25+
from sage.combinat.free_module import CombinatorialFreeModule
26+
from sage.combinat.subset import powerset
27+
from sage.misc.cachefunc import cached_method
28+
from sage.rings.integer_ring import ZZ
29+
from sage.structure.element import Element, get_coercion_model
30+
from sage.structure.parent import Parent
31+
from sage.structure.richcmp import richcmp
32+
from sage.structure.unique_representation import UniqueRepresentation
3633

3734

3835
class BlobDiagram(Element):
@@ -167,7 +164,7 @@ def __init__(self, n):
167164
sage: BD4 = BlobDiagrams(4)
168165
sage: TestSuite(BD4).run()
169166
"""
170-
self._n = n
167+
self._n = ZZ(n)
171168
self._TL_diagrams = TemperleyLiebDiagrams(n)
172169
Parent.__init__(self, category=FiniteEnumeratedSets())
173170

@@ -181,7 +178,7 @@ def _repr_(self):
181178
sage: BlobDiagrams(4)
182179
Blob diagrams of order 4
183180
"""
184-
return "Blob diagrams of order {}".format(self._n)
181+
return f"Blob diagrams of order {self._n}"
185182

186183
def cardinality(self):
187184
r"""
@@ -194,7 +191,7 @@ def cardinality(self):
194191
sage: BD4.cardinality()
195192
70
196193
"""
197-
return binomial(2*self._n, self._n)
194+
return (2 * self._n).binomial(self._n)
198195

199196
def order(self):
200197
r"""
@@ -221,7 +218,7 @@ def base_set(self):
221218
sage: sorted(BD4.base_set())
222219
[-4, -3, -2, -1, 1, 2, 3, 4]
223220
"""
224-
return frozenset(range(1,self._n+1)).union(range(-self._n,0))
221+
return frozenset(range(1, self._n + 1)).union(range(-self._n, 0))
225222

226223
def _element_constructor_(self, marked, unmarked=None):
227224
r"""

src/sage/combinat/cluster_algebra_quiver/cluster_seed.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ def __init__(self, data, frozen=None, is_principal=False, user_labels=None, user
332332
else:
333333
labelset = set(user_labels)
334334
# Sanitizes our ``user_labels`` to use Integers instead of ints
335-
user_labels = [ZZ(x) if x in ZZ else x for x in user_labels]
335+
user_labels = [Integer(x) if x in ZZ else x for x in user_labels]
336336
if labelset != set(self._nlist + self._mlist) and labelset != set(range(self._n + self._m)):
337337
raise ValueError('user_labels conflict with both the given'
338338
' vertex labels and the default labels')
@@ -3593,7 +3593,7 @@ def mutation_class_iter(self, depth=infinity, show_depth=False,
35933593
else:
35943594
orbits = [index for index in range(n) if index > i or sd2._M[index, i] != 0]
35953595

3596-
clusters[cl2] = [sd2, orbits, clusters[key][2]+[i]]
3596+
clusters[cl2] = [sd2, orbits, clusters[key][2] + [i]]
35973597
if return_paths:
35983598
yield (sd2, clusters[cl2][2])
35993599
else:
@@ -3602,10 +3602,10 @@ def mutation_class_iter(self, depth=infinity, show_depth=False,
36023602
if show_depth and gets_bigger:
36033603
timer2 = time.time()
36043604
dc = str(depth_counter)
3605-
dc += ' ' * (5-len(dc))
3605+
dc += ' ' * (5 - len(dc))
36063606
nr = str(len(clusters))
3607-
nr += ' ' * (10-len(nr))
3608-
print(f"Depth: {dc} found: {nr} Time: {timer2-timer:.2f} s")
3607+
nr += ' ' * (10 - len(nr))
3608+
print(f"Depth: {dc} found: {nr} Time: {timer2 - timer:.2f} s")
36093609

36103610
def mutation_class(self, depth=infinity, show_depth=False, return_paths=False,
36113611
up_to_equivalence=True, only_sink_source=False):
@@ -4718,7 +4718,7 @@ def _produce_upper_cluster_algebra_element(self, vd, cList):
47184718
for l in range(num_cols):
47194719
denominator = denominator * (R.gen(l))**vd[i][0][l]
47204720
# Each copy of a vector in vd contributes a factor of the Laurent polynomial calculated from it.
4721-
final = (numerator/denominator)**vd[i][1]
4721+
final = (numerator / denominator)**vd[i][1]
47224722
finalP.append(final)
47234723
laurentP = 1
47244724
# The UCA element for the vector a is the product of the elements produced from the vectors in its decomposition.
@@ -4740,10 +4740,8 @@ def _bino(n, k):
47404740
0
47414741
"""
47424742
if n >= 0:
4743-
from sage.arith.misc import binomial
4744-
return binomial(n, k)
4745-
else:
4746-
return 0
4743+
return Integer(n).binomial(k)
4744+
return 0
47474745

47484746

47494747
def coeff_recurs(p, q, a1, a2, b, c):
@@ -5192,7 +5190,7 @@ def almost_positive_root(self):
51925190
mt = self._mutation_type._repr_()
51935191
# mt is a string of the shape "['A', 15]"
51945192
# where A is a single letter and 15 is an integer
5195-
Phi = RootSystem([mt[2: 3], ZZ(mt[6: -1])])
5193+
Phi = RootSystem([mt[2: 3], Integer(mt[6: -1])])
51965194
Phiplus = Phi.root_lattice().simple_roots()
51975195

51985196
if self.denominator() == 1:

src/sage/combinat/dyck_word.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -544,13 +544,13 @@ def _repr_lattice(self, type=None, labelling=None, underpath=True) -> str:
544544
row = " " * (n - alst[-1] - 1) + final_fall + "\n"
545545
for i in range(n - 1):
546546
c = 0
547-
row = row + " "*(n-i-2-alst[-i-2])
547+
row = row + " " * (n-i-2-alst[-i-2])
548548
c += n-i-2-alst[-i-2]
549549
if alst[-i-2]+1 != alst[-i-1]:
550550
row += " _"
551551
c += alst[-i-2] - alst[-i-1]
552552
if underpath:
553-
row += "__"*(alst[-i-2]-alst[-i-1])+"|" + labels[-1] + "x "*(n-c-2-i) + " ."*i + "\n"
553+
row += "__" * (alst[-i-2]-alst[-i-1]) + "|" + labels[-1] + "x "*(n-c-2-i) + " ." * i + "\n"
554554
else:
555555
row += "__"*(alst[-i-2]-alst[-i-1])+"| " + "x "*(n-c-2-i) + " ."*i + labels[-1] + "\n"
556556
labels.pop()
@@ -3780,8 +3780,7 @@ def cardinality(self) -> int:
37803780
....: for p in range(7))
37813781
True
37823782
"""
3783-
from sage.arith.misc import binomial
3784-
return (self.k1 - self.k2 + 1) * binomial(self.k1 + self.k2, self.k2) // (self.k1 + 1)
3783+
return (self.k1 - self.k2 + 1) * (self.k1 + self.k2).binomial(self.k2) // (self.k1 + 1)
37853784

37863785
################################################################
37873786
# Complete Dyck words

src/sage/combinat/interval_posets.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
from sage.misc.lazy_attribute import lazy_attribute
4848
from sage.misc.lazy_import import lazy_import
4949
from sage.rings.integer import Integer
50+
from sage.rings.integer_ring import ZZ
5051
from sage.rings.semirings.non_negative_integer_semiring import NN
5152
from sage.sets.non_negative_integers import NonNegativeIntegers
5253
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
@@ -3757,11 +3758,10 @@ def cardinality(self) -> Integer:
37573758
sage: [TamariIntervalPosets(i).cardinality() for i in range(6)]
37583759
[1, 1, 3, 13, 68, 399]
37593760
"""
3760-
from sage.arith.misc import binomial
37613761
n = self._size
37623762
if n == 0:
3763-
return Integer(1)
3764-
return (2 * binomial(4 * n + 1, n - 1)) // (n * (n + 1))
3763+
return ZZ.one()
3764+
return (2 * Integer(4 * n + 1).binomial(n - 1)) // (n * (n + 1))
37653765
# return Integer(2 * factorial(4*n+1)/(factorial(n+1)*factorial(3*n+2)))
37663766

37673767
def __iter__(self) -> Iterator[TIP]:

src/sage/combinat/posets/posets.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,6 @@
292292
from sage.misc.cachefunc import cached_method
293293
from sage.misc.lazy_attribute import lazy_attribute
294294
from sage.misc.misc_c import prod
295-
from sage.arith.misc import binomial
296295
from sage.categories.category import Category
297296
from sage.categories.sets_cat import Sets
298297
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
@@ -1815,7 +1814,7 @@ def atkinson(self, a):
18151814
for r in range(1, n + 1):
18161815
new_a_spec.append(0)
18171816
for i in range(max(1, r - n + k), min(r, k) + 1):
1818-
k_val = binomial(r - 1, i - 1) * binomial(n - r, k - i)
1817+
k_val = Integer(r - 1).binomial(i - 1) * Integer(n - r).binomial(k - i)
18191818
new_a_spec[-1] += k_val * a_spec[i - 1] * n_lin_exts
18201819
return new_a_spec
18211820

@@ -5295,7 +5294,7 @@ def factor(self):
52955294
dg = self._hasse_diagram
52965295
if not dg.is_connected():
52975296
raise NotImplementedError('the poset is not connected')
5298-
if ZZ(dg.num_verts()).is_prime():
5297+
if Integer(dg.num_verts()).is_prime():
52995298
return [self]
53005299
G = dg.to_undirected()
53015300
is_product, dic = G.is_cartesian_product(relabeling=True)
@@ -6492,7 +6491,7 @@ def random_order_ideal(self, direction='down'):
64926491
with seed(currseed):
64936492
for _ in range(count):
64946493
for element in range(n):
6495-
if random() % 2 == 1:
6494+
if random() % 2: # should use one random bit
64966495
s = [state[i] for i in lower_covers[element]]
64976496
if 1 not in s:
64986497
if 2 not in s:
@@ -8141,7 +8140,7 @@ def is_eulerian(self, k=None, certificate=False):
81418140
n = self.cardinality()
81428141
if n == 1:
81438142
return True
8144-
if k is None and not certificate and n % 2 == 1:
8143+
if k is None and not certificate and n % 2:
81458144
return False
81468145

81478146
H = self._hasse_diagram

0 commit comments

Comments
 (0)