-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
element.pyx
3289 lines (2562 loc) · 90.9 KB
/
element.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
GAP element wrapper
This document describes the individual wrappers for various GAP
elements. For general information about GAP, you should read the
:mod:`~sage.libs.gap.libgap` module documentation.
"""
# ****************************************************************************
# Copyright (C) 2012 Volker Braun <vbraun.name@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from cpython.object cimport Py_EQ, Py_NE, Py_LE, Py_GE, Py_LT, Py_GT
from cysignals.signals cimport sig_on, sig_off
from sage.libs.gap.gap_includes cimport *
from sage.libs.gap.libgap import libgap
from sage.libs.gap.util cimport *
from sage.libs.gap.util import GAPError
from sage.cpython.string cimport str_to_bytes, char_to_str
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_double import RDF
from sage.groups.perm_gps.permgroup_element cimport PermutationGroupElement
from sage.combinat.permutation import Permutation
from sage.structure.coerce cimport coercion_model as cm
############################################################################
### helper functions to construct lists and records ########################
############################################################################
cdef Obj make_gap_list(sage_list) except NULL:
"""
Convert Sage lists into Gap lists
INPUT:
- ``a`` -- list of :class:`GapElement`.
OUTPUT:
The list of the elements in ``a`` as a Gap ``Obj``.
"""
cdef Obj l
cdef GapElement elem
cdef int i
try:
GAP_Enter()
l = GAP_NewPlist(0)
for i, x in enumerate(sage_list):
if not isinstance(x, GapElement):
elem = <GapElement>libgap(x)
else:
elem = <GapElement>x
GAP_AssList(l, i + 1, elem.value)
return l
finally:
GAP_Leave()
cdef Obj make_gap_matrix(sage_list, gap_ring) except NULL:
"""
Convert Sage lists into Gap matrices
INPUT:
- ``sage_list`` -- list of :class:`GapElement`.
- ``gap_ring`` -- the base ring
If ``gap_ring`` is ``None``, nothing is made to make sure
that all coefficients live in the same Gap ring. The resulting Gap list
may not be recognized as a matrix by Gap.
OUTPUT:
The list of the elements in ``sage_list`` as a Gap ``Obj``.
"""
cdef Obj l
cdef GapElement elem
cdef GapElement one
cdef int i
if gap_ring is not None:
one = <GapElement>gap_ring.One()
else:
one = <GapElement>libgap(1)
try:
GAP_Enter()
l = GAP_NewPlist(0)
for i, x in enumerate(sage_list):
if not isinstance(x, GapElement):
elem = <GapElement>libgap(x)
elem = elem * one
else:
elem = <GapElement>x
GAP_AssList(l, i + 1, elem.value)
return l
finally:
GAP_Leave()
cdef char *capture_stdout(Obj func, Obj obj) noexcept:
"""
Call a single-argument GAP function ``func`` with the argument ``obj``
and return the stdout from that function call.
This can be used to capture the output of GAP functions that are used to
print objects such as ``Print()`` and ``ViewObj()``.
"""
cdef Obj s, stream, output_text_string
cdef Obj l
# The only way to get a string representation of an object that is truly
# consistent with how it would be represented at the GAP REPL is to call
# ViewObj on it. Unfortunately, ViewObj *prints* to the output stream,
# and there is no equivalent that simply returns the string that would be
# printed. The closest approximation would be DisplayString, but this
# bypasses any type-specific overrides for ViewObj so for many objects
# that does not give consistent results.
# TODO: This is probably needlessly slow, but we might need better
# support from GAP to improve this...
try:
GAP_Enter()
s = NEW_STRING(0)
output_text_string = GAP_ValueGlobalVariable("OutputTextString")
stream = GAP_CallFunc2Args(output_text_string, s, GAP_True)
l = GAP_NewPlist(1)
GAP_AssList(l, 1, obj)
CALL_WITH_STREAM = GAP_ValueGlobalVariable("CALL_WITH_STREAM")
GAP_CallFunc3Args(CALL_WITH_STREAM, stream, func, l)
return GAP_CSTR_STRING(s)
finally:
GAP_Leave()
cdef char *gap_element_repr(Obj obj) noexcept:
"""
Implement ``repr()`` of ``GapElement``s using the ``ViewObj()`` function,
which is by default closest to what you get when displaying an object in
GAP on the command-line (i.e. when evaluating an expression that returns
that object.
"""
cdef Obj func
try:
GAP_Enter()
func = GAP_ValueGlobalVariable("ViewObj")
return capture_stdout(func, obj)
finally:
GAP_Leave()
cdef char *gap_element_str(Obj obj) noexcept:
"""
Implement ``str()`` of ``GapElement``s using the ``Print()`` function.
This mirrors somewhat how Python uses ``str()`` on an object when passing
it to the ``print()`` function. This is also how the GAP pexpect interface
has traditionally repr'd objects; for the libgap interface we take a
slightly different approach more closely mirroring Python's str/repr
difference (though this does not map perfectly onto GAP).
"""
cdef Obj func
try:
GAP_Enter()
func = GAP_ValueGlobalVariable("Print")
return capture_stdout(func, obj)
finally:
GAP_Leave()
cdef Obj make_gap_record(sage_dict) except NULL:
"""
Convert Sage dictionary into Gap record
INPUT:
- ``a`` -- list of :class:`GapElement`.
OUTPUT:
The list of the elements in ``a`` as a Gap ``Obj``.
TESTS::
sage: libgap({'a': 1, 'b':123}) # indirect doctest
rec( a := 1, b := 123 )
"""
data = [ (str(key), libgap(value)) for key, value in sage_dict.iteritems() ]
cdef Obj rec
cdef GapElement val
cdef UInt rnam
try:
GAP_Enter()
rec = GAP_NewPrecord(len(data))
for d in data:
key, val = d
rnam = RNamName(str_to_bytes(key))
AssPRec(rec, rnam, val.value)
return rec
finally:
GAP_Leave()
cdef Obj make_gap_integer(sage_int) except NULL:
"""
Convert Sage integer into Gap integer
INPUT:
- ``sage_int`` -- a Sage integer.
OUTPUT:
The integer as a GAP ``Obj``.
TESTS::
sage: libgap(1) # indirect doctest
1
"""
return GAP_NewObjIntFromInt(<int>sage_int)
cdef Obj make_gap_string(sage_string) except NULL:
"""
Convert a Python string to a Gap string
INPUT:
- ``sage_string`` -- a Python str.
OUTPUT:
The string as a GAP ``Obj``.
TESTS::
sage: libgap('string') # indirect doctest
"string"
"""
cdef Obj result
try:
GAP_Enter()
b = str_to_bytes(sage_string)
result = GAP_MakeStringWithLen(b, len(b))
return result
finally:
GAP_Leave()
############################################################################
### generic construction of GapElements ####################################
############################################################################
cdef GapElement make_any_gap_element(parent, Obj obj):
"""
Return the GAP element wrapper of ``obj``
The most suitable subclass of GapElement is determined
automatically. Use this function to wrap GAP objects unless you
know exactly which type it is (then you can use the specialized
``make_GapElement_...``)
TESTS::
sage: x = libgap.eval("'c'"); x
"c"
sage: type(x)
<class 'sage.libs.gap.element.GapElement_String'>
sage: libgap.eval("['a', 'b', 'c']") # gap strings are also lists of chars
"abc"
sage: t = libgap.UnorderedTuples('abc', 2); t
[ "aa", "ab", "ac", "bb", "bc", "cc" ]
sage: t[1]
"ab"
sage: t[1].sage()
'ab'
sage: t.sage()
['aa', 'ab', 'ac', 'bb', 'bc', 'cc']
Check that :issue:`18158` is fixed::
sage: S = SymmetricGroup(5)
sage: irr = libgap.Irr(S)[3]
sage: irr[0]
6
sage: irr[1]
0
"""
cdef int num
try:
GAP_Enter()
if obj is NULL:
return make_GapElement(parent, obj)
num = TNUM_OBJ(obj)
if GAP_IsInt(obj):
return make_GapElement_Integer(parent, obj)
elif GAP_IsMacFloat(obj):
return make_GapElement_Float(parent, obj)
elif num == T_CYC:
return make_GapElement_Cyclotomic(parent, obj)
elif num == T_FFE:
return make_GapElement_FiniteField(parent, obj)
elif num == T_RAT:
return make_GapElement_Rational(parent, obj)
elif num == T_BOOL:
return make_GapElement_Boolean(parent, obj)
elif num == T_FUNCTION:
return make_GapElement_Function(parent, obj)
elif num == T_PERM2 or num == T_PERM4:
return make_GapElement_Permutation(parent, obj)
elif GAP_IsRecord(obj):
return make_GapElement_Record(parent, obj)
elif GAP_IsList(obj) and GAP_LenList(obj) == 0:
# Empty lists are lists and not strings in Python
return make_GapElement_List(parent, obj)
elif IsStringConv(obj):
# GAP strings are lists, too. Make sure this comes before non-empty make_GapElement_List
return make_GapElement_String(parent, obj)
elif GAP_IsList(obj):
return make_GapElement_List(parent, obj)
elif GAP_ValueOfChar(obj) != -1:
ch = make_GapElement(parent, obj).IntChar().sage()
return make_GapElement_String(parent, make_gap_string(chr(ch)))
result = make_GapElement(parent, obj)
if num == T_POSOBJ:
if result.IsZmodnZObj():
return make_GapElement_IntegerMod(parent, obj)
if num == T_COMOBJ:
if result.IsRing():
return make_GapElement_Ring(parent, obj)
return result
finally:
GAP_Leave()
############################################################################
### GapElement #############################################################
############################################################################
cdef GapElement make_GapElement(parent, Obj obj):
r"""
Turn a Gap C object (of type ``Obj``) into a Cython ``GapElement``.
INPUT:
- ``parent`` -- the parent of the new :class:`GapElement`
- ``obj`` -- a GAP object.
OUTPUT:
A :class:`GapElement_Function` instance, or one of its derived
classes if it is a better fit for the GAP object.
EXAMPLES::
sage: libgap(0)
0
sage: type(_)
<class 'sage.libs.gap.element.GapElement_Integer'>
sage: libgap.eval('')
sage: libgap(None)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute '_gap_init_'...
"""
cdef GapElement r = GapElement.__new__(GapElement)
r._initialize(parent, obj)
return r
cpdef _from_sage(elem):
"""
Currently just used for unpickling; equivalent to calling ``libgap(elem)``
to convert a Sage object to a `GapElement` where possible.
"""
if isinstance(elem, str):
return libgap.eval(elem)
return libgap(elem)
cdef class GapElement(RingElement):
r"""
Wrapper for all Gap objects.
.. NOTE::
In order to create ``GapElements`` you should use the
``libgap`` instance (the parent of all Gap elements) to
convert things into ``GapElement``. You must not create
``GapElement`` instances manually.
EXAMPLES::
sage: libgap(0)
0
If Gap finds an error while evaluating, a :class:`GAPError`
exception is raised::
sage: libgap.eval('1/0')
Traceback (most recent call last):
...
GAPError: Error, Rational operations: <divisor> must not be zero
Also, a ``GAPError`` is raised if the input is not a simple expression::
sage: libgap.eval('1; 2; 3')
Traceback (most recent call last):
...
GAPError: can only evaluate a single statement
"""
def __cinit__(self):
"""
The Cython constructor.
EXAMPLES::
sage: libgap.eval('1')
1
"""
self.value = NULL
self._compare_by_id = False
def __init__(self):
"""
The ``GapElement`` constructor
Users must use the ``libgap`` instance to construct instances
of :class:`GapElement`. Cython programmers must use
:func:`make_GapElement` factory function.
TESTS::
sage: from sage.libs.gap.element import GapElement
sage: GapElement()
Traceback (most recent call last):
...
TypeError: this class cannot be instantiated from Python
"""
raise TypeError('this class cannot be instantiated from Python')
cdef _initialize(self, parent, Obj obj):
r"""
Initialize the GapElement.
This Cython method is called from :func:`make_GapElement` to
initialize the newly-constructed object. You must never call
it manually.
TESTS::
sage: n_before = libgap.count_GAP_objects()
sage: a = libgap.eval('123')
sage: b = libgap.eval('456')
sage: c = libgap.eval('CyclicGroup(3)')
sage: d = libgap.eval('"a string"')
sage: libgap.collect()
sage: del c
sage: libgap.collect()
sage: n_after = libgap.count_GAP_objects()
sage: n_after - n_before
3
"""
assert self.value is NULL
self._parent = parent
self.value = obj
if obj is NULL:
return
reference_obj(obj)
def __dealloc__(self):
r"""
The Cython destructor
TESTS::
sage: pre_refcount = libgap.count_GAP_objects()
sage: def f():
....: local_variable = libgap.eval('"This is a new string"')
sage: f()
sage: f()
sage: f()
sage: post_refcount = libgap.count_GAP_objects()
sage: post_refcount - pre_refcount
0
"""
if self.value is NULL:
return
dereference_obj(self.value)
def __copy__(self):
r"""
TESTS::
sage: a = libgap(1)
sage: a.__copy__() is a
True
sage: a = libgap(1/3)
sage: a.__copy__() is a
True
sage: a = libgap([1,2])
sage: b = a.__copy__()
sage: a is b
False
sage: a[0] = 3
sage: a
[ 3, 2 ]
sage: b
[ 1, 2 ]
sage: a = libgap([[0,1],[2,3,4]])
sage: b = a.__copy__()
sage: b[0][1] = -2
sage: b
[ [ 0, -2 ], [ 2, 3, 4 ] ]
sage: a
[ [ 0, -2 ], [ 2, 3, 4 ] ]
"""
if IS_MUTABLE_OBJ(self.value):
return make_any_gap_element(self.parent(), SHALLOW_COPY_OBJ(self.value))
else:
return self
cpdef GapElement deepcopy(self, bint mut):
r"""
Return a deepcopy of this Gap object
Note that this is the same thing as calling ``StructuralCopy`` but much
faster.
INPUT:
- ``mut`` - (boolean) whether to return a mutable copy
EXAMPLES::
sage: a = libgap([[0,1],[2,3]])
sage: b = a.deepcopy(1)
sage: b[0,0] = 5
sage: a
[ [ 0, 1 ], [ 2, 3 ] ]
sage: b
[ [ 5, 1 ], [ 2, 3 ] ]
sage: l = libgap([0,1])
sage: l.deepcopy(0).IsMutable()
false
sage: l.deepcopy(1).IsMutable()
true
"""
if IS_MUTABLE_OBJ(self.value):
return make_any_gap_element(self.parent(), CopyObj(self.value, mut))
else:
return self
def __deepcopy__(self, memo):
r"""
TESTS::
sage: a = libgap([[0,1],[2]])
sage: b = deepcopy(a)
sage: a[0,0] = -1
sage: a
[ [ -1, 1 ], [ 2 ] ]
sage: b
[ [ 0, 1 ], [ 2 ] ]
"""
return self.deepcopy(0)
def __reduce__(self):
"""
Attempt to pickle GAP elements from libgap.
This is inspired in part by
``sage.interfaces.interface.Interface._reduce``, though for a fallback
we use ``str(self)`` instead of ``repr(self)``, since the former is
equivalent in the libgap interface to the latter in the pexpect
interface.
TESTS:
This workaround was motivated in particular by this example from the
permutation groups implementation::
sage: CC = libgap.eval('ConjugacyClass(SymmetricGroup([ 1 .. 5 ]), (1,2)(3,4))')
sage: CC.sage()
Traceback (most recent call last):
...
NotImplementedError: cannot construct equivalent Sage object
sage: libgap.eval(str(CC))
(1,2)(3,4)^G
sage: loads(dumps(CC))
(1,2)(3,4)^G
"""
if self.is_string():
elem = repr(self.sage())
try:
elem = self.sage()
except NotImplementedError:
elem = str(self)
return (_from_sage, (elem,))
def __contains__(self, other):
r"""
TESTS::
sage: libgap(1) in libgap.eval('Integers')
True
sage: 1 in libgap.eval('Integers')
True
sage: 3 in libgap([1,5,3,2])
True
sage: -5 in libgap([1,5,3,2])
False
sage: libgap.eval('Integers') in libgap(1)
Traceback (most recent call last):
...
GAPError: Error, no method found! Error, no 1st choice method found for `in' on 2 arguments
"""
GAP_IN = libgap.eval(r'\in')
return GAP_IN(other, self).sage()
cpdef _type_number(self):
"""
Return the GAP internal type number.
This is only useful for libgap development purposes.
OUTPUT:
Integer.
EXAMPLES::
sage: x = libgap(1)
sage: x._type_number()
(0, b'integer')
"""
n = TNUM_OBJ(self.value)
name = TNAM_OBJ(self.value)
return (n, name)
def __dir__(self):
"""
Customize tab completion
EXAMPLES::
sage: G = libgap.DihedralGroup(4)
sage: 'GeneratorsOfMagmaWithInverses' in dir(G)
True
sage: 'GeneratorsOfGroup' in dir(G) # known bug
False
sage: x = libgap(1)
sage: len(dir(x)) > 100
True
"""
from sage.libs.gap.operations import OperationInspector
ops = OperationInspector(self).op_names()
return dir(self.__class__) + ops
def __getattr__(self, name):
r"""
Return functionoid implementing the function ``name``.
EXAMPLES::
sage: lst = libgap([])
sage: 'Add' in dir(lst) # This is why tab-completion works
True
sage: lst.Add(1) # this is the syntactic sugar
sage: lst
[ 1 ]
The above is equivalent to the following calls::
sage: lst = libgap.eval('[]')
sage: libgap.eval('Add') (lst, 1)
sage: lst
[ 1 ]
TESTS::
sage: lst.Adddddd(1)
Traceback (most recent call last):
...
AttributeError: 'Adddddd' is not defined in GAP
sage: libgap.eval('some_name := 1')
1
sage: lst.some_name
Traceback (most recent call last):
...
AttributeError: 'some_name' does not define a GAP function
"""
if name in ('__dict__', '_getAttributeNames', '_SageObject__custom_name', 'keys'):
raise AttributeError('Python special name, not a GAP function.')
try:
proxy = make_GapElement_MethodProxy\
(self.parent(), gap_eval(name), self)
except GAPError:
raise AttributeError(f"'{name}' is not defined in GAP")
if not proxy.is_function():
raise AttributeError(f"'{name}' does not define a GAP function")
return proxy
def __str__(self):
r"""
Return a string representation of ``self`` for printing.
EXAMPLES::
sage: libgap(0)
0
sage: print(libgap.eval(''))
None
sage: print(libgap('a'))
a
sage: print(libgap.eval('SymmetricGroup(3)'))
SymmetricGroup( [ 1 .. 3 ] )
sage: libgap(0).__str__()
'0'
"""
if self.value == NULL:
return 'NULL'
s = char_to_str(gap_element_str(self.value))
return s.strip()
def _repr_(self):
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: libgap(0)
0
sage: libgap.eval('')
sage: libgap('a')
"a"
sage: libgap.eval('SymmetricGroup(3)')
Sym( [ 1 .. 3 ] )
sage: libgap(0)._repr_()
'0'
"""
if self.value == NULL:
return 'NULL'
s = char_to_str(gap_element_repr(self.value))
return s.strip()
cpdef _set_compare_by_id(self):
"""
Set comparison to compare by ``id``
By default, GAP is used to compare GAP objects. However,
this is not defined for all GAP objects. To have GAP play
nice with ``UniqueRepresentation``, comparison must always
work. This method allows one to override the comparison to
sort by the (unique) Python ``id``.
Obviously it is a bad idea to change the comparison of objects
after you have inserted them into a set/dict. You also must
not mix GAP objects with different sort methods in the same
container.
EXAMPLES::
sage: F1 = libgap.FreeGroup(['a'])
sage: F2 = libgap.FreeGroup(['a'])
sage: F1 < F2
Traceback (most recent call last):
...
GAPError: Error, no method found!
Error, no 1st choice method found for `<' on 2 arguments
sage: F1._set_compare_by_id()
sage: F1 != F2
Traceback (most recent call last):
...
ValueError: comparison style must be the same for both operands
sage: F1._set_compare_by_id()
sage: F2._set_compare_by_id()
sage: F1 != F2
True
"""
self._compare_by_id = True
cpdef _assert_compare_by_id(self):
"""
Ensure that comparison is by ``id``
See :meth:`_set_compare_by_id`.
OUTPUT:
This method returns nothing. A ``ValueError`` is raised if
:meth:`_set_compare_by_id` has not been called on this libgap
object.
EXAMPLES::
sage: x = libgap.FreeGroup(1)
sage: x._assert_compare_by_id()
Traceback (most recent call last):
...
ValueError: this requires a GAP object whose comparison is by "id"
sage: x._set_compare_by_id()
sage: x._assert_compare_by_id()
"""
if not self._compare_by_id:
raise ValueError('this requires a GAP object whose comparison is by "id"')
def __hash__(self):
"""
Make hashable.
EXAMPLES::
sage: hash(libgap(123)) # random output
163512108404620371
"""
return hash(str(self))
cpdef _richcmp_(self, other, int op):
"""
Compare ``self`` with ``other``.
Uses the GAP comparison by default, or the Python ``id`` if
:meth:`_set_compare_by_id` was called.
OUTPUT:
Boolean, depending on the comparison of ``self`` and
``other``. Raises a ``ValueError`` if GAP does not support
comparison of ``self`` and ``other``, unless
:meth:`_set_compare_by_id` was called on both ``self`` and
``other``.
EXAMPLES::
sage: a = libgap(123)
sage: a == a
True
sage: b = libgap('string')
sage: a._richcmp_(b, 0)
1
sage: (a < b) or (a > b)
True
sage: a._richcmp_(libgap(123), 2)
True
GAP does not have a comparison function for two ``FreeGroup``
objects. LibGAP signals this by raising a ``ValueError`` ::
sage: F1 = libgap.FreeGroup(['a'])
sage: F2 = libgap.FreeGroup(['a'])
sage: F1 < F2
Traceback (most recent call last):
...
GAPError: Error, no method found!
Error, no 1st choice method found for `<' on 2 arguments
sage: F1._set_compare_by_id()
sage: F1 < F2
Traceback (most recent call last):
...
ValueError: comparison style must be the same for both operands
sage: F1._set_compare_by_id()
sage: F2._set_compare_by_id()
sage: F1 < F2 or F1 > F2
True
Check that :issue:`26388` is fixed::
sage: 1 > libgap(1)
False
sage: libgap(1) > 1
False
sage: 1 >= libgap(1)
True
sage: libgap(1) >= 1
True
"""
if self._compare_by_id != (<GapElement>other)._compare_by_id:
raise ValueError("comparison style must be the same for both operands")
if op==Py_LT:
return self._compare_less(other)
elif op==Py_LE:
return self._compare_equal(other) or self._compare_less(other)
elif op == Py_EQ:
return self._compare_equal(other)
elif op == Py_GT:
return not self._compare_less(other) and not self._compare_equal(other)
elif op == Py_GE:
return not self._compare_less(other)
elif op == Py_NE:
return not self._compare_equal(other)
else:
assert False # unreachable
cdef bint _compare_equal(self, Element other) except -2:
"""
Compare ``self`` with ``other``.
Helper for :meth:`_richcmp_`
EXAMPLES::
sage: libgap(1) == libgap(1) # indirect doctest
True
"""
if self._compare_by_id:
return id(self) == id(other)
cdef GapElement c_other = <GapElement>other
sig_on()
try:
GAP_Enter()
return GAP_EQ(self.value, c_other.value)
finally:
GAP_Leave()
sig_off()
cdef bint _compare_less(self, Element other) except -2:
"""
Compare ``self`` with ``other``.
Helper for :meth:`_richcmp_`
EXAMPLES::
sage: libgap(1) < libgap(2) # indirect doctest
True
"""
if self._compare_by_id:
return id(self) < id(other)
cdef GapElement c_other = <GapElement>other
sig_on()
try:
GAP_Enter()
return GAP_LT(self.value, c_other.value)
finally:
GAP_Leave()
sig_off()
cpdef _add_(self, right):
r"""
Add two GapElement objects.
EXAMPLES::
sage: g1 = libgap(1)
sage: g2 = libgap(2)
sage: g1._add_(g2)
3
sage: g1 + g2 # indirect doctest
3
sage: libgap(1) + libgap.CyclicGroup(2)
Traceback (most recent call last):
...
GAPError: Error, no method found!
Error, no 1st choice method found for `+' on 2 arguments
"""
cdef Obj result
try:
sig_GAP_Enter()
sig_on()
result = GAP_SUM(self.value, (<GapElement>right).value)
sig_off()