177
177
gap(...), x.[tab], and docs, e.g., gap.function? and x.function?
178
178
"""
179
179
180
- #* ****************************************************************************
180
+ # ****************************************************************************
181
181
# Copyright (C) 2005 William Stein <[email protected] >
182
182
#
183
183
# Distributed under the terms of the GNU General Public License (GPL)
189
189
#
190
190
# The full text of the GPL is available at:
191
191
#
192
- # http ://www.gnu.org/licenses/
193
- #* ****************************************************************************
192
+ # https ://www.gnu.org/licenses/
193
+ # ****************************************************************************
194
194
195
195
from .expect import Expect , ExpectElement , FunctionElement , ExpectFunction
196
196
from .gap_workspace import gap_workspace_file , prepare_workspace_dir
@@ -234,7 +234,7 @@ def gap_command(use_workspace_cache=True, local=True):
234
234
return gap_cmd , True
235
235
236
236
237
- ############ Classes with methods for both the GAP3 and GAP4 interface
237
+ # ########### Classes with methods for both the GAP3 and GAP4 interface
238
238
239
239
class Gap_generic (ExtraTabCompletion , Expect ):
240
240
r"""
@@ -277,10 +277,10 @@ def _synchronize(self, timeout=0.5, cmd='%s;'):
277
277
E = self ._expect
278
278
from sage .misc .prandom import randrange
279
279
rnd = randrange (2147483647 )
280
- cmd = str (rnd )+ ';'
280
+ cmd = str (rnd ) + ';'
281
281
try :
282
282
E .sendline (cmd )
283
- E .expect (r'@[nf][@J\s>]*' + str (rnd ), timeout = timeout )
283
+ E .expect (r'@[nf][@J\s>]*' + str (rnd ), timeout = timeout )
284
284
E .send (' ' )
285
285
E .expect ('@i' , timeout = timeout )
286
286
except pexpect .TIMEOUT :
@@ -443,7 +443,7 @@ def load_package(self, pkg, verbose=False):
443
443
print ("Loading GAP package {}" .format (pkg ))
444
444
x = self .eval ('LoadPackage("{}")' .format (pkg ))
445
445
if x == 'fail' :
446
- raise RuntimeError ("Error loading Gap package " + str (pkg )+ ". " +
446
+ raise RuntimeError ("Error loading Gap package " + str (pkg ) + ". " +
447
447
"You may want to install gap_packages SPKG." )
448
448
449
449
def eval (self , x , newlines = False , strip = True , split_lines = True , ** kwds ):
@@ -497,10 +497,10 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
497
497
' -\n\\\\-'
498
498
"""
499
499
# '"
500
- #We remove all of the comments: On each line, we try
501
- #to find a pound sign. If we find it, we check to see if
502
- #it is occurring in a string. If it is not in a string, we
503
- #strip off the comment.
500
+ # We remove all of the comments: On each line, we try
501
+ # to find a pound sign. If we find it, we check to see if
502
+ # it is occurring in a string. If it is not in a string, we
503
+ # strip off the comment.
504
504
if not split_lines :
505
505
input_line = str (x )
506
506
else :
@@ -510,17 +510,17 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
510
510
while pound_position != - 1 :
511
511
if not is_in_string (line , pound_position ):
512
512
line = line [:pound_position ]
513
- pound_position = line .find ('#' ,pound_position + 1 )
514
- input_line += " " + line
513
+ pound_position = line .find ('#' , pound_position + 1 )
514
+ input_line += " " + line
515
515
if not input_line .endswith (';' ):
516
516
input_line += ';'
517
517
result = Expect .eval (self , input_line , ** kwds )
518
518
if not newlines :
519
- result = result .replace ("\\ \n " ,"" )
519
+ result = result .replace ("\\ \n " , "" )
520
520
return result .rstrip ()
521
521
522
522
def _execute_line (self , line , wait_for_prompt = True , expect_eof = False ):
523
- if self ._expect is None : # interface is down
523
+ if self ._expect is None : # interface is down
524
524
self ._start ()
525
525
E = self ._expect
526
526
try :
@@ -530,9 +530,9 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
530
530
except OSError :
531
531
raise RuntimeError ("Error evaluating %s in %s" % (line , self ))
532
532
if not wait_for_prompt :
533
- return (b'' ,b'' )
533
+ return (b'' , b'' )
534
534
if len (line ) == 0 :
535
- return (b'' ,b'' )
535
+ return (b'' , b'' )
536
536
try :
537
537
terminal_echo = [] # to be discarded
538
538
normal_outputs = [] # GAP stdout
@@ -546,43 +546,43 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
546
546
warnings .warn (
547
547
"possibly wrong version of GAP package "
548
548
"interface. Crossing fingers and continuing." )
549
- elif x == 1 : # @@
549
+ elif x == 1 : # @@
550
550
current_outputs .append (b'@' )
551
- elif x == 2 : # special char
551
+ elif x == 2 : # special char
552
552
c = ord (E .after [1 :2 ]) - ord (b'A' ) + 1
553
553
s = bytes ([c ])
554
554
current_outputs .append (s )
555
- elif x == 3 : # garbage collection info, ignore
555
+ elif x == 3 : # garbage collection info, ignore
556
556
pass
557
- elif x == 4 : # @e -- break loop
557
+ elif x == 4 : # @e -- break loop
558
558
E .sendline ("quit;" )
559
- elif x == 5 : # @c completion, doesn't seem to happen when -p is in use
559
+ elif x == 5 : # @c completion, doesn't seem to happen when -p is in use
560
560
warnings .warn ("I didn't think GAP could do this" )
561
- elif x == 6 : # @f GAP error message
561
+ elif x == 6 : # @f GAP error message
562
562
current_outputs = error_outputs
563
- elif x == 7 : # @h help text, but this stopped happening with new help
563
+ elif x == 7 : # @h help text, but this stopped happening with new help
564
564
warnings .warn ("I didn't think GAP could do this" )
565
- elif x == 8 : # @i awaiting normal input
565
+ elif x == 8 : # @i awaiting normal input
566
566
break
567
- elif x == 9 : # @m finished running a child
567
+ elif x == 9 : # @m finished running a child
568
568
pass # there is no need to do anything
569
- elif x == 10 : # @n normal output line
569
+ elif x == 10 : # @n normal output line
570
570
current_outputs = normal_outputs
571
- elif x == 11 : # @r echoing input
571
+ elif x == 11 : # @r echoing input
572
572
current_outputs = terminal_echo
573
- elif x == 12 : # @sN shouldn't happen
573
+ elif x == 12 : # @sN shouldn't happen
574
574
warnings .warn ("this should never happen" )
575
- elif x == 13 : # @w GAP is trying to send a Window command
575
+ elif x == 13 : # @w GAP is trying to send a Window command
576
576
warnings .warn ("this should never happen" )
577
- elif x == 14 : # @x seems to be safely ignorable
577
+ elif x == 14 : # @x seems to be safely ignorable
578
578
pass
579
- elif x == 15 :# @z GAP starting a subprocess
579
+ elif x == 15 : # @z GAP starting a subprocess
580
580
pass # there is no need to do anything
581
581
except pexpect .EOF :
582
582
if not expect_eof :
583
- raise RuntimeError ("Unexpected EOF from %s executing %s" % (self ,line ))
583
+ raise RuntimeError ("Unexpected EOF from %s executing %s" % (self , line ))
584
584
except IOError :
585
- raise RuntimeError ("IO Error from %s executing %s" % (self ,line ))
585
+ raise RuntimeError ("IO Error from %s executing %s" % (self , line ))
586
586
return (b"" .join (normal_outputs ), b"" .join (error_outputs ))
587
587
588
588
def _keyboard_interrupt (self ):
@@ -687,8 +687,8 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if
687
687
error += "\n Running gap_reset_workspace()..."
688
688
self .quit ()
689
689
gap_reset_workspace ()
690
- error = error .replace ('\r ' ,'' )
691
- raise RuntimeError ("%s produced error output\n %s\n executing %s" % (self , error ,line ))
690
+ error = error .replace ('\r ' , '' )
691
+ raise RuntimeError ("%s produced error output\n %s\n executing %s" % (self , error , line ))
692
692
if not normal :
693
693
return ''
694
694
@@ -762,7 +762,7 @@ def _contains(self, v1, v2):
762
762
sage: 2 in gap('Integers')
763
763
True
764
764
"""
765
- return self .eval ('%s in %s' % (v1 ,v2 )) == "true"
765
+ return self .eval ('%s in %s' % (v1 , v2 )) == "true"
766
766
767
767
def _true_symbol (self ):
768
768
"""
@@ -858,20 +858,21 @@ def function_call(self, function, args=None, kwds=None):
858
858
args , kwds = self ._convert_args_kwds (args , kwds )
859
859
self ._check_valid_function_name (function )
860
860
861
- #Here we have to do some magic because not all GAP
862
- #functions return a value. If you try to store their
863
- #results to a variable, then GAP will complain. Thus, before
864
- #we evaluate the function, we make it so that the marker string
865
- #is in the 'last' variable in GAP. If the function returns a
866
- #value, then that value will be in 'last', otherwise it will
867
- #be the marker.
861
+ # Here we have to do some magic because not all GAP
862
+ # functions return a value. If you try to store their
863
+ # results to a variable, then GAP will complain. Thus, before
864
+ # we evaluate the function, we make it so that the marker string
865
+ # is in the 'last' variable in GAP. If the function returns a
866
+ # value, then that value will be in 'last', otherwise it will
867
+ # be the marker.
868
868
marker = '__SAGE_LAST__:="__SAGE_LAST__";;'
869
869
cmd = "%s(%s);;" % (function , "," .join ([s .name () for s in args ] +
870
- ['%s=%s' % (key ,value .name ()) for key , value in kwds .items ()]))
870
+ [f'{ key } ={ value .name ()} '
871
+ for key , value in kwds .items ()]))
871
872
if len (marker ) + len (cmd ) <= self ._eval_using_file_cutoff :
872
873
# We combine the two commands so we only run eval() once and the
873
874
# only output would be from the second command
874
- res = self .eval (marker + cmd )
875
+ res = self .eval (marker + cmd )
875
876
else :
876
877
self .eval (marker )
877
878
res = self .eval (cmd )
@@ -1035,7 +1036,8 @@ def _matrix_(self, R):
1035
1036
1036
1037
from sage .matrix .matrix_space import MatrixSpace
1037
1038
M = MatrixSpace (R , n , m )
1038
- entries = [[R (self [r ,c ]) for c in range (1 ,m + 1 )] for r in range (1 ,n + 1 )]
1039
+ entries = [[R (self [r , c ]) for c in range (1 , m + 1 )]
1040
+ for r in range (1 , n + 1 )]
1039
1041
return M (entries )
1040
1042
1041
1043
@@ -1089,7 +1091,7 @@ def __init__(self, max_workspace_size=None,
1089
1091
self .__seq = 0
1090
1092
self ._seed = seed
1091
1093
1092
- def set_seed (self ,seed = None ):
1094
+ def set_seed (self , seed = None ):
1093
1095
"""
1094
1096
Set the seed for gap interpreter.
1095
1097
@@ -1194,8 +1196,8 @@ def _start(self):
1194
1196
self .save_workspace ()
1195
1197
# Now, as self._expect exists, we can compile some useful pattern:
1196
1198
self ._compiled_full_pattern = self ._expect .compile_pattern_list ([
1197
- r'@p\d+\.' ,'@@' ,'@[A-Z]' ,r'@[123456!"#$%&][^+]*\+' ,
1198
- '@e' ,'@c' ,'@f' ,'@h' ,'@i' ,'@m' ,'@n' ,'@r' ,r'@s\d' ,r'@w.*\+' ,'@x' ,'@z' ])
1199
+ r'@p\d+\.' , '@@' , '@[A-Z]' , r'@[123456!"#$%&][^+]*\+' ,
1200
+ '@e' , '@c' , '@f' , '@h' , '@i' , '@m' , '@n' , '@r' , r'@s\d' , r'@w.*\+' , '@x' , '@z' ])
1199
1201
# read everything up to the first "ready" prompt
1200
1202
self ._expect .expect ("@i" )
1201
1203
@@ -1236,10 +1238,9 @@ def cputime(self, t=None):
1236
1238
"""
1237
1239
if t is not None :
1238
1240
return self .cputime () - t
1239
- else :
1240
- self .eval ('_r_ := Runtimes();' )
1241
- r = sum (eval (self .eval ('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]' )))
1242
- return r / 1000.0
1241
+ self .eval ('_r_ := Runtimes();' )
1242
+ r = sum (eval (self .eval ('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]' )))
1243
+ return r / 1000.0
1243
1244
1244
1245
def save_workspace (self ):
1245
1246
r"""
@@ -1339,7 +1340,7 @@ def set(self, var, value):
1339
1340
sage: gap.get('x')
1340
1341
'2'
1341
1342
"""
1342
- cmd = ('%s:=%s;;' % (var , value )).replace ('\n ' ,'' )
1343
+ cmd = ('%s:=%s;;' % (var , value )).replace ('\n ' , '' )
1343
1344
self ._eval_line (cmd , allow_use_file = True )
1344
1345
1345
1346
def get (self , var , use_file = False ):
@@ -1356,10 +1357,10 @@ def get(self, var, use_file=False):
1356
1357
tmp = self ._local_tmpfile ()
1357
1358
if os .path .exists (tmp ):
1358
1359
os .unlink (tmp )
1359
- self .eval ('PrintTo("%s", %s);' % (tmp ,var ), strip = False )
1360
+ self .eval ('PrintTo("%s", %s);' % (tmp , var ), strip = False )
1360
1361
with open (tmp ) as f :
1361
1362
r = f .read ()
1362
- r = r .strip ().replace ("\\ \n " ,"" )
1363
+ r = r .strip ().replace ("\\ \n " , "" )
1363
1364
os .unlink (tmp )
1364
1365
return r
1365
1366
else :
@@ -1470,7 +1471,7 @@ def _tab_completion(self):
1470
1471
True
1471
1472
"""
1472
1473
names = eval (self .eval ('NamesSystemGVars()' )) + \
1473
- eval (self .eval ('NamesUserGVars()' ))
1474
+ eval (self .eval ('NamesUserGVars()' ))
1474
1475
return [n for n in names if n [0 ] in string .ascii_letters ]
1475
1476
1476
1477
@@ -1572,16 +1573,16 @@ def _latex_(self):
1572
1573
P = self ._check_valid ()
1573
1574
try :
1574
1575
s = P .eval ('LaTeXObj(%s)' % self .name ())
1575
- s = s .replace ('\\ \\ ' ,'\\ ' ).replace ('"' ,'' )
1576
- s = s .replace ('%\\ n' ,' ' )
1576
+ s = s .replace ('\\ \\ ' , '\\ ' ).replace ('"' , '' )
1577
+ s = s .replace ('%\\ n' , ' ' )
1577
1578
return s
1578
1579
except RuntimeError :
1579
1580
return str (self )
1580
1581
1581
1582
@cached_method
1582
1583
def _tab_completion (self ):
1583
1584
"""
1584
- Return additional tab completion entries
1585
+ Return additional tab completion entries.
1585
1586
1586
1587
OUTPUT:
1587
1588
@@ -1595,10 +1596,11 @@ def _tab_completion(self):
1595
1596
"""
1596
1597
P = self .parent ()
1597
1598
v = P .eval (r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self .name ())
1598
- v = v .replace ('Tester(' ,'' ).replace ('Setter(' ,'' ).replace (')' ,'' ).replace ('\n ' , '' )
1599
+ v = v .replace ('Tester(' , '' ).replace ('Setter(' , '' ).replace (')' , '' ).replace ('\n ' , '' )
1599
1600
v = v .split (',' )
1600
- v = [ oper .split ('"' )[1 ] for oper in v ]
1601
- v = [ oper for oper in v if all (ch in string .ascii_letters for ch in oper ) ]
1601
+ v = (oper .split ('"' )[1 ] for oper in v )
1602
+ v = [oper for oper in v
1603
+ if all (ch in string .ascii_letters for ch in oper )]
1602
1604
return sorted (set (v ))
1603
1605
1604
1606
@@ -1708,13 +1710,13 @@ def gfq_gap_to_sage(x, F):
1708
1710
return F (0 )
1709
1711
i1 = s .index ("(" )
1710
1712
i2 = s .index (")" )
1711
- q = eval (s [i1 + 1 :i2 ].replace ('^' ,'**' ))
1713
+ q = eval (s [i1 + 1 :i2 ].replace ('^' , '**' ))
1712
1714
if not F .cardinality ().is_power_of (q ):
1713
1715
raise ValueError ('%r has no subfield of size %r' % (F , q ))
1714
1716
if s .find (')^' ) == - 1 :
1715
1717
e = 1
1716
1718
else :
1717
- e = int (s [i2 + 2 :])
1719
+ e = int (s [i2 + 2 :])
1718
1720
if F .degree () == 1 :
1719
1721
g = F (gap .eval ('Int(Z(%s))' % q ))
1720
1722
elif F .is_conway ():
@@ -1724,6 +1726,7 @@ def gfq_gap_to_sage(x, F):
1724
1726
raise ValueError ('%r is not prime or defined by a Conway polynomial' % F )
1725
1727
return g ** e
1726
1728
1729
+
1727
1730
def intmod_gap_to_sage (x ):
1728
1731
r"""
1729
1732
INPUT:
@@ -1827,5 +1830,5 @@ def gap_console():
1827
1830
if not get_display_manager ().is_in_terminal ():
1828
1831
raise RuntimeError ('Can use the console only in the terminal. Try %%gap magics instead.' )
1829
1832
cmd , _ = gap_command (use_workspace_cache = False )
1830
- cmd += ' ' + os .path .join (SAGE_EXTCODE ,'gap' ,'console.g' )
1833
+ cmd += ' ' + os .path .join (SAGE_EXTCODE , 'gap' , 'console.g' )
1831
1834
os .system (cmd )
0 commit comments