Skip to content

Commit

Permalink
gh-36890: pep8 cleanup for gap interface
Browse files Browse the repository at this point in the history
    
full pep8 cleanup for the gap interface

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: #36890
Reported by: Frédéric Chapoton
Reviewer(s): David Coudert
  • Loading branch information
Release Manager committed Dec 17, 2023
2 parents 7ef39dd + e026eaf commit 74f82be
Showing 1 changed file with 70 additions and 67 deletions.
137 changes: 70 additions & 67 deletions src/sage/interfaces/gap.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@
gap(...), x.[tab], and docs, e.g., gap.function? and x.function?
"""

#*****************************************************************************
# ****************************************************************************
# Copyright (C) 2005 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
Expand All @@ -189,8 +189,8 @@
#
# The full text of the GPL is available at:
#
# http://www.gnu.org/licenses/
#*****************************************************************************
# https://www.gnu.org/licenses/
# ****************************************************************************

from .expect import Expect, ExpectElement, FunctionElement, ExpectFunction
from .gap_workspace import gap_workspace_file, prepare_workspace_dir
Expand Down Expand Up @@ -244,7 +244,7 @@ def gap_command(use_workspace_cache=True, local=True):
return gap_cmd, True


############ Classes with methods for both the GAP3 and GAP4 interface
# ########### Classes with methods for both the GAP3 and GAP4 interface

class Gap_generic(ExtraTabCompletion, Expect):
r"""
Expand Down Expand Up @@ -287,10 +287,10 @@ def _synchronize(self, timeout=0.5, cmd='%s;'):
E = self._expect
from sage.misc.prandom import randrange
rnd = randrange(2147483647)
cmd = str(rnd)+';'
cmd = str(rnd) + ';'
try:
E.sendline(cmd)
E.expect(r'@[nf][@J\s>]*'+str(rnd), timeout=timeout)
E.expect(r'@[nf][@J\s>]*' + str(rnd), timeout=timeout)
E.send(' ')
E.expect('@i', timeout=timeout)
except pexpect.TIMEOUT:
Expand Down Expand Up @@ -453,7 +453,7 @@ def load_package(self, pkg, verbose=False):
print("Loading GAP package {}".format(pkg))
x = self.eval('LoadPackage("{}")'.format(pkg))
if x == 'fail':
raise RuntimeError("Error loading Gap package "+str(pkg)+". " +
raise RuntimeError("Error loading Gap package " + str(pkg) + ". " +
"You may want to install gap_packages SPKG.")

def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
Expand Down Expand Up @@ -507,10 +507,10 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
' -\n\\\\-'
"""
# '"
#We remove all of the comments: On each line, we try
#to find a pound sign. If we find it, we check to see if
#it is occurring in a string. If it is not in a string, we
#strip off the comment.
# We remove all of the comments: On each line, we try
# to find a pound sign. If we find it, we check to see if
# it is occurring in a string. If it is not in a string, we
# strip off the comment.
if not split_lines:
input_line = str(x)
else:
Expand All @@ -520,17 +520,17 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
while pound_position != -1:
if not is_in_string(line, pound_position):
line = line[:pound_position]
pound_position = line.find('#',pound_position+1)
input_line += " "+line
pound_position = line.find('#', pound_position + 1)
input_line += " " + line
if not input_line.endswith(';'):
input_line += ';'
result = Expect.eval(self, input_line, **kwds)
if not newlines:
result = result.replace("\\\n","")
result = result.replace("\\\n", "")
return result.rstrip()

def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
if self._expect is None: # interface is down
if self._expect is None: # interface is down
self._start()
E = self._expect
try:
Expand All @@ -540,9 +540,9 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
except OSError:
raise RuntimeError("Error evaluating %s in %s" % (line, self))
if not wait_for_prompt:
return (b'',b'')
return (b'', b'')
if len(line) == 0:
return (b'',b'')
return (b'', b'')
try:
terminal_echo = [] # to be discarded
normal_outputs = [] # GAP stdout
Expand All @@ -556,43 +556,43 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
warnings.warn(
"possibly wrong version of GAP package "
"interface. Crossing fingers and continuing.")
elif x == 1: #@@
elif x == 1: # @@
current_outputs.append(b'@')
elif x == 2: #special char
elif x == 2: # special char
c = ord(E.after[1:2]) - ord(b'A') + 1
s = bytes([c])
current_outputs.append(s)
elif x == 3: # garbage collection info, ignore
elif x == 3: # garbage collection info, ignore
pass
elif x == 4: # @e -- break loop
elif x == 4: # @e -- break loop
E.sendline("quit;")
elif x == 5: # @c completion, doesn't seem to happen when -p is in use
elif x == 5: # @c completion, doesn't seem to happen when -p is in use
warnings.warn("I didn't think GAP could do this")
elif x == 6: # @f GAP error message
elif x == 6: # @f GAP error message
current_outputs = error_outputs
elif x == 7: # @h help text, but this stopped happening with new help
elif x == 7: # @h help text, but this stopped happening with new help
warnings.warn("I didn't think GAP could do this")
elif x == 8: # @i awaiting normal input
elif x == 8: # @i awaiting normal input
break
elif x == 9: # @m finished running a child
elif x == 9: # @m finished running a child
pass # there is no need to do anything
elif x == 10: #@n normal output line
elif x == 10: # @n normal output line
current_outputs = normal_outputs
elif x == 11: #@r echoing input
elif x == 11: # @r echoing input
current_outputs = terminal_echo
elif x == 12: #@sN shouldn't happen
elif x == 12: # @sN shouldn't happen
warnings.warn("this should never happen")
elif x == 13: #@w GAP is trying to send a Window command
elif x == 13: # @w GAP is trying to send a Window command
warnings.warn("this should never happen")
elif x == 14: #@x seems to be safely ignorable
elif x == 14: # @x seems to be safely ignorable
pass
elif x == 15:#@z GAP starting a subprocess
elif x == 15: # @z GAP starting a subprocess
pass # there is no need to do anything
except pexpect.EOF:
if not expect_eof:
raise RuntimeError("Unexpected EOF from %s executing %s" % (self,line))
raise RuntimeError("Unexpected EOF from %s executing %s" % (self, line))
except IOError:
raise RuntimeError("IO Error from %s executing %s" % (self,line))
raise RuntimeError("IO Error from %s executing %s" % (self, line))
return (b"".join(normal_outputs), b"".join(error_outputs))

def _keyboard_interrupt(self):
Expand Down Expand Up @@ -697,8 +697,8 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if
error += "\nRunning gap_reset_workspace()..."
self.quit()
gap_reset_workspace()
error = error.replace('\r','')
raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error,line))
error = error.replace('\r', '')
raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error, line))
if not normal:
return ''

Expand Down Expand Up @@ -772,7 +772,7 @@ def _contains(self, v1, v2):
sage: 2 in gap('Integers')
True
"""
return self.eval('%s in %s' % (v1,v2)) == "true"
return self.eval('%s in %s' % (v1, v2)) == "true"

def _true_symbol(self):
"""
Expand Down Expand Up @@ -868,20 +868,21 @@ def function_call(self, function, args=None, kwds=None):
args, kwds = self._convert_args_kwds(args, kwds)
self._check_valid_function_name(function)

#Here we have to do some magic because not all GAP
#functions return a value. If you try to store their
#results to a variable, then GAP will complain. Thus, before
#we evaluate the function, we make it so that the marker string
#is in the 'last' variable in GAP. If the function returns a
#value, then that value will be in 'last', otherwise it will
#be the marker.
# Here we have to do some magic because not all GAP
# functions return a value. If you try to store their
# results to a variable, then GAP will complain. Thus, before
# we evaluate the function, we make it so that the marker string
# is in the 'last' variable in GAP. If the function returns a
# value, then that value will be in 'last', otherwise it will
# be the marker.
marker = '__SAGE_LAST__:="__SAGE_LAST__";;'
cmd = "%s(%s);;" % (function, ",".join([s.name() for s in args] +
['%s=%s' % (key,value.name()) for key, value in kwds.items()]))
[f'{key}={value.name()}'
for key, value in kwds.items()]))
if len(marker) + len(cmd) <= self._eval_using_file_cutoff:
# We combine the two commands so we only run eval() once and the
# only output would be from the second command
res = self.eval(marker+cmd)
res = self.eval(marker + cmd)
else:
self.eval(marker)
res = self.eval(cmd)
Expand Down Expand Up @@ -1045,7 +1046,8 @@ def _matrix_(self, R):

from sage.matrix.matrix_space import MatrixSpace
M = MatrixSpace(R, n, m)
entries = [[R(self[r,c]) for c in range(1,m+1)] for r in range(1,n+1)]
entries = [[R(self[r, c]) for c in range(1, m + 1)]
for r in range(1, n + 1)]
return M(entries)


Expand Down Expand Up @@ -1099,7 +1101,7 @@ def __init__(self, max_workspace_size=None,
self.__seq = 0
self._seed = seed

def set_seed(self,seed=None):
def set_seed(self, seed=None):
"""
Set the seed for gap interpreter.
Expand Down Expand Up @@ -1204,8 +1206,8 @@ def _start(self):
self.save_workspace()
# Now, as self._expect exists, we can compile some useful pattern:
self._compiled_full_pattern = self._expect.compile_pattern_list([
r'@p\d+\.','@@','@[A-Z]',r'@[123456!"#$%&][^+]*\+',
'@e','@c','@f','@h','@i','@m','@n','@r',r'@s\d',r'@w.*\+','@x','@z'])
r'@p\d+\.', '@@', '@[A-Z]', r'@[123456!"#$%&][^+]*\+',
'@e', '@c', '@f', '@h', '@i', '@m', '@n', '@r', r'@s\d', r'@w.*\+', '@x', '@z'])
# read everything up to the first "ready" prompt
self._expect.expect("@i")

Expand Down Expand Up @@ -1246,10 +1248,9 @@ def cputime(self, t=None):
"""
if t is not None:
return self.cputime() - t
else:
self.eval('_r_ := Runtimes();')
r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]')))
return r/1000.0
self.eval('_r_ := Runtimes();')
r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]')))
return r / 1000.0

def save_workspace(self):
r"""
Expand Down Expand Up @@ -1349,7 +1350,7 @@ def set(self, var, value):
sage: gap.get('x')
'2'
"""
cmd = ('%s:=%s;;' % (var, value)).replace('\n','')
cmd = ('%s:=%s;;' % (var, value)).replace('\n', '')
self._eval_line(cmd, allow_use_file=True)

def get(self, var, use_file=False):
Expand All @@ -1366,10 +1367,10 @@ def get(self, var, use_file=False):
tmp = self._local_tmpfile()
if os.path.exists(tmp):
os.unlink(tmp)
self.eval('PrintTo("%s", %s);' % (tmp,var), strip=False)
self.eval('PrintTo("%s", %s);' % (tmp, var), strip=False)
with open(tmp) as f:
r = f.read()
r = r.strip().replace("\\\n","")
r = r.strip().replace("\\\n", "")
os.unlink(tmp)
return r
else:
Expand Down Expand Up @@ -1480,7 +1481,7 @@ def _tab_completion(self):
True
"""
names = eval(self.eval('NamesSystemGVars()')) + \
eval(self.eval('NamesUserGVars()'))
eval(self.eval('NamesUserGVars()'))
return [n for n in names if n[0] in string.ascii_letters]


Expand Down Expand Up @@ -1582,16 +1583,16 @@ def _latex_(self):
P = self._check_valid()
try:
s = P.eval('LaTeXObj(%s)' % self.name())
s = s.replace('\\\\','\\').replace('"','')
s = s.replace('%\\n',' ')
s = s.replace('\\\\', '\\').replace('"', '')
s = s.replace('%\\n', ' ')
return s
except RuntimeError:
return str(self)

@cached_method
def _tab_completion(self):
"""
Return additional tab completion entries
Return additional tab completion entries.
OUTPUT:
Expand All @@ -1605,10 +1606,11 @@ def _tab_completion(self):
"""
P = self.parent()
v = P.eval(r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self.name())
v = v.replace('Tester(','').replace('Setter(','').replace(')','').replace('\n', '')
v = v.replace('Tester(', '').replace('Setter(', '').replace(')', '').replace('\n', '')
v = v.split(',')
v = [ oper.split('"')[1] for oper in v ]
v = [ oper for oper in v if all(ch in string.ascii_letters for ch in oper) ]
v = (oper.split('"')[1] for oper in v)
v = [oper for oper in v
if all(ch in string.ascii_letters for ch in oper)]
return sorted(set(v))


Expand Down Expand Up @@ -1718,13 +1720,13 @@ def gfq_gap_to_sage(x, F):
return F(0)
i1 = s.index("(")
i2 = s.index(")")
q = eval(s[i1+1:i2].replace('^','**'))
q = eval(s[i1 + 1:i2].replace('^', '**'))
if not F.cardinality().is_power_of(q):
raise ValueError('%r has no subfield of size %r' % (F, q))
if s.find(')^') == -1:
e = 1
else:
e = int(s[i2+2:])
e = int(s[i2 + 2:])
if F.degree() == 1:
g = F(gap.eval('Int(Z(%s))' % q))
elif F.is_conway():
Expand All @@ -1734,6 +1736,7 @@ def gfq_gap_to_sage(x, F):
raise ValueError('%r is not prime or defined by a Conway polynomial' % F)
return g**e


def intmod_gap_to_sage(x):
r"""
INPUT:
Expand Down Expand Up @@ -1837,5 +1840,5 @@ def gap_console():
if not get_display_manager().is_in_terminal():
raise RuntimeError('Can use the console only in the terminal. Try %%gap magics instead.')
cmd, _ = gap_command(use_workspace_cache=False)
cmd += ' ' + os.path.join(SAGE_EXTCODE,'gap','console.g')
cmd += ' ' + os.path.join(SAGE_EXTCODE, 'gap', 'console.g')
os.system(cmd)

0 comments on commit 74f82be

Please sign in to comment.