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
@@ -244,7 +244,7 @@ def gap_command(use_workspace_cache=True, local=True):
244
244
return gap_cmd , True
245
245
246
246
247
- ############ Classes with methods for both the GAP3 and GAP4 interface
247
+ # ########### Classes with methods for both the GAP3 and GAP4 interface
248
248
249
249
class Gap_generic (ExtraTabCompletion , Expect ):
250
250
r"""
@@ -287,10 +287,10 @@ def _synchronize(self, timeout=0.5, cmd='%s;'):
287
287
E = self ._expect
288
288
from sage .misc .prandom import randrange
289
289
rnd = randrange (2147483647 )
290
- cmd = str (rnd )+ ';'
290
+ cmd = str (rnd ) + ';'
291
291
try :
292
292
E .sendline (cmd )
293
- E .expect (r'@[nf][@J\s>]*' + str (rnd ), timeout = timeout )
293
+ E .expect (r'@[nf][@J\s>]*' + str (rnd ), timeout = timeout )
294
294
E .send (' ' )
295
295
E .expect ('@i' , timeout = timeout )
296
296
except pexpect .TIMEOUT :
@@ -453,7 +453,7 @@ def load_package(self, pkg, verbose=False):
453
453
print ("Loading GAP package {}" .format (pkg ))
454
454
x = self .eval ('LoadPackage("{}")' .format (pkg ))
455
455
if x == 'fail' :
456
- raise RuntimeError ("Error loading Gap package " + str (pkg )+ ". " +
456
+ raise RuntimeError ("Error loading Gap package " + str (pkg ) + ". " +
457
457
"You may want to install gap_packages SPKG." )
458
458
459
459
def eval (self , x , newlines = False , strip = True , split_lines = True , ** kwds ):
@@ -507,10 +507,10 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
507
507
' -\n\\\\-'
508
508
"""
509
509
# '"
510
- #We remove all of the comments: On each line, we try
511
- #to find a pound sign. If we find it, we check to see if
512
- #it is occurring in a string. If it is not in a string, we
513
- #strip off the comment.
510
+ # We remove all of the comments: On each line, we try
511
+ # to find a pound sign. If we find it, we check to see if
512
+ # it is occurring in a string. If it is not in a string, we
513
+ # strip off the comment.
514
514
if not split_lines :
515
515
input_line = str (x )
516
516
else :
@@ -520,17 +520,17 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
520
520
while pound_position != - 1 :
521
521
if not is_in_string (line , pound_position ):
522
522
line = line [:pound_position ]
523
- pound_position = line .find ('#' ,pound_position + 1 )
524
- input_line += " " + line
523
+ pound_position = line .find ('#' , pound_position + 1 )
524
+ input_line += " " + line
525
525
if not input_line .endswith (';' ):
526
526
input_line += ';'
527
527
result = Expect .eval (self , input_line , ** kwds )
528
528
if not newlines :
529
- result = result .replace ("\\ \n " ,"" )
529
+ result = result .replace ("\\ \n " , "" )
530
530
return result .rstrip ()
531
531
532
532
def _execute_line (self , line , wait_for_prompt = True , expect_eof = False ):
533
- if self ._expect is None : # interface is down
533
+ if self ._expect is None : # interface is down
534
534
self ._start ()
535
535
E = self ._expect
536
536
try :
@@ -540,9 +540,9 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
540
540
except OSError :
541
541
raise RuntimeError ("Error evaluating %s in %s" % (line , self ))
542
542
if not wait_for_prompt :
543
- return (b'' ,b'' )
543
+ return (b'' , b'' )
544
544
if len (line ) == 0 :
545
- return (b'' ,b'' )
545
+ return (b'' , b'' )
546
546
try :
547
547
terminal_echo = [] # to be discarded
548
548
normal_outputs = [] # GAP stdout
@@ -556,43 +556,43 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
556
556
warnings .warn (
557
557
"possibly wrong version of GAP package "
558
558
"interface. Crossing fingers and continuing." )
559
- elif x == 1 : # @@
559
+ elif x == 1 : # @@
560
560
current_outputs .append (b'@' )
561
- elif x == 2 : # special char
561
+ elif x == 2 : # special char
562
562
c = ord (E .after [1 :2 ]) - ord (b'A' ) + 1
563
563
s = bytes ([c ])
564
564
current_outputs .append (s )
565
- elif x == 3 : # garbage collection info, ignore
565
+ elif x == 3 : # garbage collection info, ignore
566
566
pass
567
- elif x == 4 : # @e -- break loop
567
+ elif x == 4 : # @e -- break loop
568
568
E .sendline ("quit;" )
569
- elif x == 5 : # @c completion, doesn't seem to happen when -p is in use
569
+ elif x == 5 : # @c completion, doesn't seem to happen when -p is in use
570
570
warnings .warn ("I didn't think GAP could do this" )
571
- elif x == 6 : # @f GAP error message
571
+ elif x == 6 : # @f GAP error message
572
572
current_outputs = error_outputs
573
- elif x == 7 : # @h help text, but this stopped happening with new help
573
+ elif x == 7 : # @h help text, but this stopped happening with new help
574
574
warnings .warn ("I didn't think GAP could do this" )
575
- elif x == 8 : # @i awaiting normal input
575
+ elif x == 8 : # @i awaiting normal input
576
576
break
577
- elif x == 9 : # @m finished running a child
577
+ elif x == 9 : # @m finished running a child
578
578
pass # there is no need to do anything
579
- elif x == 10 : # @n normal output line
579
+ elif x == 10 : # @n normal output line
580
580
current_outputs = normal_outputs
581
- elif x == 11 : # @r echoing input
581
+ elif x == 11 : # @r echoing input
582
582
current_outputs = terminal_echo
583
- elif x == 12 : # @sN shouldn't happen
583
+ elif x == 12 : # @sN shouldn't happen
584
584
warnings .warn ("this should never happen" )
585
- elif x == 13 : # @w GAP is trying to send a Window command
585
+ elif x == 13 : # @w GAP is trying to send a Window command
586
586
warnings .warn ("this should never happen" )
587
- elif x == 14 : # @x seems to be safely ignorable
587
+ elif x == 14 : # @x seems to be safely ignorable
588
588
pass
589
- elif x == 15 :# @z GAP starting a subprocess
589
+ elif x == 15 : # @z GAP starting a subprocess
590
590
pass # there is no need to do anything
591
591
except pexpect .EOF :
592
592
if not expect_eof :
593
- raise RuntimeError ("Unexpected EOF from %s executing %s" % (self ,line ))
593
+ raise RuntimeError ("Unexpected EOF from %s executing %s" % (self , line ))
594
594
except IOError :
595
- raise RuntimeError ("IO Error from %s executing %s" % (self ,line ))
595
+ raise RuntimeError ("IO Error from %s executing %s" % (self , line ))
596
596
return (b"" .join (normal_outputs ), b"" .join (error_outputs ))
597
597
598
598
def _keyboard_interrupt (self ):
@@ -697,8 +697,8 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if
697
697
error += "\n Running gap_reset_workspace()..."
698
698
self .quit ()
699
699
gap_reset_workspace ()
700
- error = error .replace ('\r ' ,'' )
701
- raise RuntimeError ("%s produced error output\n %s\n executing %s" % (self , error ,line ))
700
+ error = error .replace ('\r ' , '' )
701
+ raise RuntimeError ("%s produced error output\n %s\n executing %s" % (self , error , line ))
702
702
if not normal :
703
703
return ''
704
704
@@ -772,7 +772,7 @@ def _contains(self, v1, v2):
772
772
sage: 2 in gap('Integers')
773
773
True
774
774
"""
775
- return self .eval ('%s in %s' % (v1 ,v2 )) == "true"
775
+ return self .eval ('%s in %s' % (v1 , v2 )) == "true"
776
776
777
777
def _true_symbol (self ):
778
778
"""
@@ -868,20 +868,21 @@ def function_call(self, function, args=None, kwds=None):
868
868
args , kwds = self ._convert_args_kwds (args , kwds )
869
869
self ._check_valid_function_name (function )
870
870
871
- #Here we have to do some magic because not all GAP
872
- #functions return a value. If you try to store their
873
- #results to a variable, then GAP will complain. Thus, before
874
- #we evaluate the function, we make it so that the marker string
875
- #is in the 'last' variable in GAP. If the function returns a
876
- #value, then that value will be in 'last', otherwise it will
877
- #be the marker.
871
+ # Here we have to do some magic because not all GAP
872
+ # functions return a value. If you try to store their
873
+ # results to a variable, then GAP will complain. Thus, before
874
+ # we evaluate the function, we make it so that the marker string
875
+ # is in the 'last' variable in GAP. If the function returns a
876
+ # value, then that value will be in 'last', otherwise it will
877
+ # be the marker.
878
878
marker = '__SAGE_LAST__:="__SAGE_LAST__";;'
879
879
cmd = "%s(%s);;" % (function , "," .join ([s .name () for s in args ] +
880
- ['%s=%s' % (key ,value .name ()) for key , value in kwds .items ()]))
880
+ [f'{ key } ={ value .name ()} '
881
+ for key , value in kwds .items ()]))
881
882
if len (marker ) + len (cmd ) <= self ._eval_using_file_cutoff :
882
883
# We combine the two commands so we only run eval() once and the
883
884
# only output would be from the second command
884
- res = self .eval (marker + cmd )
885
+ res = self .eval (marker + cmd )
885
886
else :
886
887
self .eval (marker )
887
888
res = self .eval (cmd )
@@ -1045,7 +1046,8 @@ def _matrix_(self, R):
1045
1046
1046
1047
from sage .matrix .matrix_space import MatrixSpace
1047
1048
M = MatrixSpace (R , n , m )
1048
- entries = [[R (self [r ,c ]) for c in range (1 ,m + 1 )] for r in range (1 ,n + 1 )]
1049
+ entries = [[R (self [r , c ]) for c in range (1 , m + 1 )]
1050
+ for r in range (1 , n + 1 )]
1049
1051
return M (entries )
1050
1052
1051
1053
@@ -1099,7 +1101,7 @@ def __init__(self, max_workspace_size=None,
1099
1101
self .__seq = 0
1100
1102
self ._seed = seed
1101
1103
1102
- def set_seed (self ,seed = None ):
1104
+ def set_seed (self , seed = None ):
1103
1105
"""
1104
1106
Set the seed for gap interpreter.
1105
1107
@@ -1204,8 +1206,8 @@ def _start(self):
1204
1206
self .save_workspace ()
1205
1207
# Now, as self._expect exists, we can compile some useful pattern:
1206
1208
self ._compiled_full_pattern = self ._expect .compile_pattern_list ([
1207
- r'@p\d+\.' ,'@@' ,'@[A-Z]' ,r'@[123456!"#$%&][^+]*\+' ,
1208
- '@e' ,'@c' ,'@f' ,'@h' ,'@i' ,'@m' ,'@n' ,'@r' ,r'@s\d' ,r'@w.*\+' ,'@x' ,'@z' ])
1209
+ r'@p\d+\.' , '@@' , '@[A-Z]' , r'@[123456!"#$%&][^+]*\+' ,
1210
+ '@e' , '@c' , '@f' , '@h' , '@i' , '@m' , '@n' , '@r' , r'@s\d' , r'@w.*\+' , '@x' , '@z' ])
1209
1211
# read everything up to the first "ready" prompt
1210
1212
self ._expect .expect ("@i" )
1211
1213
@@ -1246,10 +1248,9 @@ def cputime(self, t=None):
1246
1248
"""
1247
1249
if t is not None :
1248
1250
return self .cputime () - t
1249
- else :
1250
- self .eval ('_r_ := Runtimes();' )
1251
- r = sum (eval (self .eval ('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]' )))
1252
- return r / 1000.0
1251
+ self .eval ('_r_ := Runtimes();' )
1252
+ r = sum (eval (self .eval ('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]' )))
1253
+ return r / 1000.0
1253
1254
1254
1255
def save_workspace (self ):
1255
1256
r"""
@@ -1349,7 +1350,7 @@ def set(self, var, value):
1349
1350
sage: gap.get('x')
1350
1351
'2'
1351
1352
"""
1352
- cmd = ('%s:=%s;;' % (var , value )).replace ('\n ' ,'' )
1353
+ cmd = ('%s:=%s;;' % (var , value )).replace ('\n ' , '' )
1353
1354
self ._eval_line (cmd , allow_use_file = True )
1354
1355
1355
1356
def get (self , var , use_file = False ):
@@ -1366,10 +1367,10 @@ def get(self, var, use_file=False):
1366
1367
tmp = self ._local_tmpfile ()
1367
1368
if os .path .exists (tmp ):
1368
1369
os .unlink (tmp )
1369
- self .eval ('PrintTo("%s", %s);' % (tmp ,var ), strip = False )
1370
+ self .eval ('PrintTo("%s", %s);' % (tmp , var ), strip = False )
1370
1371
with open (tmp ) as f :
1371
1372
r = f .read ()
1372
- r = r .strip ().replace ("\\ \n " ,"" )
1373
+ r = r .strip ().replace ("\\ \n " , "" )
1373
1374
os .unlink (tmp )
1374
1375
return r
1375
1376
else :
@@ -1480,7 +1481,7 @@ def _tab_completion(self):
1480
1481
True
1481
1482
"""
1482
1483
names = eval (self .eval ('NamesSystemGVars()' )) + \
1483
- eval (self .eval ('NamesUserGVars()' ))
1484
+ eval (self .eval ('NamesUserGVars()' ))
1484
1485
return [n for n in names if n [0 ] in string .ascii_letters ]
1485
1486
1486
1487
@@ -1582,16 +1583,16 @@ def _latex_(self):
1582
1583
P = self ._check_valid ()
1583
1584
try :
1584
1585
s = P .eval ('LaTeXObj(%s)' % self .name ())
1585
- s = s .replace ('\\ \\ ' ,'\\ ' ).replace ('"' ,'' )
1586
- s = s .replace ('%\\ n' ,' ' )
1586
+ s = s .replace ('\\ \\ ' , '\\ ' ).replace ('"' , '' )
1587
+ s = s .replace ('%\\ n' , ' ' )
1587
1588
return s
1588
1589
except RuntimeError :
1589
1590
return str (self )
1590
1591
1591
1592
@cached_method
1592
1593
def _tab_completion (self ):
1593
1594
"""
1594
- Return additional tab completion entries
1595
+ Return additional tab completion entries.
1595
1596
1596
1597
OUTPUT:
1597
1598
@@ -1605,10 +1606,11 @@ def _tab_completion(self):
1605
1606
"""
1606
1607
P = self .parent ()
1607
1608
v = P .eval (r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self .name ())
1608
- v = v .replace ('Tester(' ,'' ).replace ('Setter(' ,'' ).replace (')' ,'' ).replace ('\n ' , '' )
1609
+ v = v .replace ('Tester(' , '' ).replace ('Setter(' , '' ).replace (')' , '' ).replace ('\n ' , '' )
1609
1610
v = v .split (',' )
1610
- v = [ oper .split ('"' )[1 ] for oper in v ]
1611
- v = [ oper for oper in v if all (ch in string .ascii_letters for ch in oper ) ]
1611
+ v = (oper .split ('"' )[1 ] for oper in v )
1612
+ v = [oper for oper in v
1613
+ if all (ch in string .ascii_letters for ch in oper )]
1612
1614
return sorted (set (v ))
1613
1615
1614
1616
@@ -1718,13 +1720,13 @@ def gfq_gap_to_sage(x, F):
1718
1720
return F (0 )
1719
1721
i1 = s .index ("(" )
1720
1722
i2 = s .index (")" )
1721
- q = eval (s [i1 + 1 :i2 ].replace ('^' ,'**' ))
1723
+ q = eval (s [i1 + 1 :i2 ].replace ('^' , '**' ))
1722
1724
if not F .cardinality ().is_power_of (q ):
1723
1725
raise ValueError ('%r has no subfield of size %r' % (F , q ))
1724
1726
if s .find (')^' ) == - 1 :
1725
1727
e = 1
1726
1728
else :
1727
- e = int (s [i2 + 2 :])
1729
+ e = int (s [i2 + 2 :])
1728
1730
if F .degree () == 1 :
1729
1731
g = F (gap .eval ('Int(Z(%s))' % q ))
1730
1732
elif F .is_conway ():
@@ -1734,6 +1736,7 @@ def gfq_gap_to_sage(x, F):
1734
1736
raise ValueError ('%r is not prime or defined by a Conway polynomial' % F )
1735
1737
return g ** e
1736
1738
1739
+
1737
1740
def intmod_gap_to_sage (x ):
1738
1741
r"""
1739
1742
INPUT:
@@ -1837,5 +1840,5 @@ def gap_console():
1837
1840
if not get_display_manager ().is_in_terminal ():
1838
1841
raise RuntimeError ('Can use the console only in the terminal. Try %%gap magics instead.' )
1839
1842
cmd , _ = gap_command (use_workspace_cache = False )
1840
- cmd += ' ' + os .path .join (SAGE_EXTCODE ,'gap' ,'console.g' )
1843
+ cmd += ' ' + os .path .join (SAGE_EXTCODE , 'gap' , 'console.g' )
1841
1844
os .system (cmd )
0 commit comments