code stringlengths 17 6.64M |
|---|
def run(argv=None):
parser = make_parser()
args = parser.parse_args((argv if (argv is not None) else sys.argv[1:]))
if (args.sage_local is None):
print('Error: An installation tree must be specified either at the command line or in the $SAGE_LOCAL environment variable', file=sys.stderr)
sys.exit(1)
try:
installcheck(args.spkg, args.sage_local, verbose=args.verbose)
except Exception as exc:
print("Error during installcheck of '{0}': {1}".format(args.spkg, exc), file=sys.stderr)
if args.debug:
raise
sys.exit(1)
|
class DistanceExceeded(Exception):
pass
|
class Levenshtein(object):
def __init__(self, limit):
"\n Levenshtein Distance with Maximum Distance Cutoff\n\n Args:\n limit (int): if the distance exceeds the limit, a\n :class:`DistanceExceeded` is raised and the\n computation is aborted.\n\n EXAMPLES::\n\n >>> from sage_bootstrap.levenshtein import Levenshtein\n >>> lev3 = Levenshtein(3)\n >>> lev3(u'saturday', u'sunday')\n 3\n >>> lev3(u'kitten', u'sitting')\n 3\n >>> lev2 = Levenshtein(2)\n >>> lev2(u'kitten', u'sitting')\n Traceback (most recent call last):\n ...\n DistanceExceeded\n "
self._limit = limit
def __call__(self, a, b):
"\n calculate the levenshtein distance\n\n args:\n a,b (str): the two strings to compare\n\n returns:\n int: the Levenshtein distance if it is less or equal to\n the distance limit.\n\n Example::\n\n >>> from app.scoring.levenshtein import Levenshtein\n >>> lev3 = Levenshtein(3)\n >>> lev3(u'Saturday', u'Sunday')\n 3\n "
(n, m) = (len(a), len(b))
if (n > m):
(a, b, n, m) = (b, a, m, n)
curr = range((n + 1))
for i in range(1, (m + 1)):
(prev, curr) = (curr, ([i] + ([0] * n)))
for j in range(1, (n + 1)):
(cost_add, cost_del) = ((prev[j] + 1), (curr[(j - 1)] + 1))
cost_change = prev[(j - 1)]
if (a[(j - 1)] != b[(i - 1)]):
cost_change += 1
curr[j] = min(cost_add, cost_del, cost_change)
if (min(curr) > self._limit):
raise DistanceExceeded
if (curr[n] > self._limit):
raise DistanceExceeded
return curr[n]
|
class ExcludeInfoFilter(logging.Filter):
def filter(self, record):
return (record.levelno != logging.INFO)
|
class OnlyInfoFilter(logging.Filter):
def filter(self, record):
return (record.levelno == logging.INFO)
|
def init_logger(config):
level = getattr(logging, config.log.upper())
logger.setLevel(level)
ch_all = logging.StreamHandler(sys.stderr)
ch_all.setLevel(logging.DEBUG)
ch_all.setFormatter(default_formatter)
ch_all.addFilter(ExcludeInfoFilter())
logger.addHandler(ch_all)
if config.interactive:
ch_info = logging.StreamHandler(sys.stdout)
else:
ch_info = logging.StreamHandler(sys.stderr)
ch_info.setLevel(logging.DEBUG)
ch_info.setFormatter(plain_formatter)
ch_info.addFilter(OnlyInfoFilter())
logger.addHandler(ch_info)
|
class Package(object):
def __init__(self, package_name):
'\n Sage Package\n\n A package is defined by a subdirectory of\n ``SAGE_ROOT/build/pkgs/``. The name of the package is the name\n of the subdirectory; The metadata of the package is contained\n in various files in the package directory. This class provides\n an abstraction to the metadata, you should never need to\n access the package directory directly.\n\n INPUT:\n\n -- ``package_name`` -- string. Name of the package. The Sage\n convention is that all package names are lower case.\n '
self.__name = package_name
self.__tarball = None
self._init_checksum()
self._init_version()
self._init_type()
self._init_install_requires()
self._init_dependencies()
def __repr__(self):
return 'Package {0}'.format(self.name)
@property
def name(self):
'\n Return the package name\n\n A package is defined by a subdirectory of\n ``SAGE_ROOT/build/pkgs/``. The name of the package is the name\n of the subdirectory.\n\n OUTPUT:\n\n String.\n '
return self.__name
@property
def md5(self):
'\n Return the MD5 checksum\n\n Do not use, this is ancient! Use :meth:`sha1` instead.\n\n OUTPUT:\n\n String.\n '
return self.__md5
@property
def sha1(self):
'\n Return the SHA1 checksum\n\n OUTPUT:\n\n String.\n '
return self.__sha1
@property
def cksum(self):
'\n Return the Ck sum checksum\n\n Do not use, this is ancient! Use :meth:`sha1` instead.\n\n OUTPUT:\n\n String.\n '
return self.__cksum
@property
def tarball(self):
'\n Return the (primary) tarball\n\n If there are multiple tarballs (currently unsupported), this\n property returns the one that is unpacked automatically.\n\n OUTPUT:\n\n Instance of :class:`sage_bootstrap.tarball.Tarball`\n '
if (self.__tarball is None):
from sage_bootstrap.tarball import Tarball
self.__tarball = Tarball(self.tarball_filename, package=self)
return self.__tarball
def _substitute_variables_once(self, pattern):
'\n Substitute (at most) one occurrence of variables in ``pattern`` by the values.\n\n These variables are ``VERSION``, ``VERSION_MAJOR``, ``VERSION_MINOR``,\n ``VERSION_MICRO``, either appearing like this or in the form ``${VERSION_MAJOR}``\n etc.\n\n Return a tuple:\n - the string with the substitution done or the original string\n - whether a substitution was done\n '
for var in ('VERSION_MAJOR', 'VERSION_MINOR', 'VERSION_MICRO', 'VERSION'):
dollar_brace_var = (('${' + var) + '}')
if (dollar_brace_var in pattern):
value = getattr(self, var.lower())
return (pattern.replace(dollar_brace_var, value, 1), True)
elif (var in pattern):
value = getattr(self, var.lower())
return (pattern.replace(var, value, 1), True)
return (pattern, False)
def _substitute_variables(self, pattern):
'\n Substitute all occurrences of ``VERSION`` in ``pattern`` by the actual version.\n\n Likewise for ``VERSION_MAJOR``, ``VERSION_MINOR``, ``VERSION_MICRO``,\n either appearing like this or in the form ``${VERSION}``, ``${VERSION_MAJOR}``,\n etc.\n '
not_done = True
while not_done:
(pattern, not_done) = self._substitute_variables_once(pattern)
return pattern
@property
def tarball_pattern(self):
'\n Return the (primary) tarball file pattern\n\n If there are multiple tarballs (currently unsupported), this\n property returns the one that is unpacked automatically.\n\n OUTPUT:\n\n String. The full-qualified tarball filename, but with\n ``VERSION`` instead of the actual tarball filename.\n '
return self.__tarball_pattern
@property
def tarball_filename(self):
'\n Return the (primary) tarball filename\n\n If there are multiple tarballs (currently unsupported), this\n property returns the one that is unpacked automatically.\n\n OUTPUT:\n\n String. The full-qualified tarball filename.\n '
pattern = self.tarball_pattern
if pattern:
return self._substitute_variables(pattern)
else:
return None
@property
def tarball_upstream_url_pattern(self):
'\n Return the tarball upstream URL pattern\n\n OUTPUT:\n\n String. The tarball upstream URL, but with the placeholder\n ``VERSION``.\n '
return self.__tarball_upstream_url_pattern
@property
def tarball_upstream_url(self):
'\n Return the tarball upstream URL or ``None`` if none is recorded\n\n OUTPUT:\n\n String. The URL.\n '
pattern = self.tarball_upstream_url_pattern
if pattern:
return self._substitute_variables(pattern)
else:
return None
@property
def tarball_package(self):
'\n Return the canonical package for the tarball\n\n This is almost always equal to ``self`` except if the package\n or the ``checksums.ini`` file is a symbolic link. In that case,\n the package of the symbolic link is returned.\n\n OUTPUT:\n\n A ``Package`` instance\n '
n = self.__tarball_package_name
if (n == self.name):
return self
else:
return type(self)(n)
@property
def version(self):
'\n Return the version\n\n OUTPUT:\n\n String. The package version. Excludes the Sage-specific\n patchlevel.\n '
return self.__version
@property
def version_major(self):
"\n Return the major version\n\n OUTPUT:\n\n String. The package's major version.\n "
return self.version.split('.')[0]
@property
def version_minor(self):
"\n Return the minor version\n\n OUTPUT:\n\n String. The package's minor version.\n "
return self.version.split('.')[1]
@property
def version_micro(self):
"\n Return the micro version\n\n OUTPUT:\n\n String. The package's micro version.\n "
return self.version.split('.')[2]
@property
def patchlevel(self):
'\n Return the patchlevel\n\n OUTPUT:\n\n Integer. The patchlevel of the package. Excludes the "p"\n prefix.\n '
return self.__patchlevel
@property
def type(self):
'\n Return the package type\n '
return self.__type
@property
def distribution_name(self):
'\n Return the Python distribution name or ``None`` for non-Python packages\n '
if (self.__install_requires is None):
return None
for line in self.__install_requires.split('\n'):
line = line.strip()
if line.startswith('#'):
continue
for part in line.split():
return part
return None
@property
def dependencies(self):
'\n Return a list of strings, the package names of the (ordinary) dependencies\n '
return self.__dependencies.partition('|')[0].strip().split()
@property
def dependencies_order_only(self):
'\n Return a list of strings, the package names of the order-only dependencies\n '
return (self.__dependencies.partition('|')[2].strip().split() + self.__dependencies_order_only.strip().split())
@property
def dependencies_check(self):
'\n Return a list of strings, the package names of the check dependencies\n '
return self.__dependencies_order_only.strip().split()
def __eq__(self, other):
return (self.tarball == other.tarball)
@classmethod
def all(cls):
'\n Return all packages\n '
base = os.path.join(SAGE_ROOT, 'build', 'pkgs')
for subdir in os.listdir(base):
path = os.path.join(base, subdir)
if (not os.path.isfile(os.path.join(path, 'type'))):
log.debug('%s has no type', subdir)
continue
try:
(yield cls(subdir))
except BaseException:
log.error('Failed to open %s', subdir)
raise
@property
def path(self):
'\n Return the package directory\n '
return os.path.join(SAGE_ROOT, 'build', 'pkgs', self.name)
def has_file(self, filename):
'\n Return whether the file exists in the package directory\n '
return os.path.exists(os.path.join(self.path, filename))
def _init_checksum(self):
'\n Load the checksums from the appropriate ``checksums.ini`` file\n '
checksums_ini = os.path.join(self.path, 'checksums.ini')
assignment = re.compile('(?P<var>[a-zA-Z0-9_]*)=(?P<value>.*)')
result = dict()
try:
with open(checksums_ini, 'rt') as f:
for line in f.readlines():
match = assignment.match(line)
if (match is None):
continue
(var, value) = match.groups()
result[var] = value
except IOError:
pass
self.__md5 = result.get('md5', None)
self.__sha1 = result.get('sha1', None)
self.__cksum = result.get('cksum', None)
self.__tarball_pattern = result.get('tarball', None)
self.__tarball_upstream_url_pattern = result.get('upstream_url', None)
self.__tarball_package_name = os.path.realpath(checksums_ini).split(os.sep)[(- 2)]
VERSION_PATCHLEVEL = re.compile('(?P<version>.*)\\.p(?P<patchlevel>[0-9]+)')
def _init_version(self):
try:
with open(os.path.join(self.path, 'package-version.txt')) as f:
package_version = f.read().strip()
except IOError:
self.__version = None
self.__patchlevel = None
else:
match = self.VERSION_PATCHLEVEL.match(package_version)
if (match is None):
self.__version = package_version
self.__patchlevel = (- 1)
else:
self.__version = match.group('version')
self.__patchlevel = int(match.group('patchlevel'))
def _init_type(self):
with open(os.path.join(self.path, 'type')) as f:
package_type = f.read().strip()
assert (package_type in ['base', 'standard', 'optional', 'experimental'])
self.__type = package_type
def _init_install_requires(self):
try:
with open(os.path.join(self.path, 'install-requires.txt')) as f:
self.__install_requires = f.read().strip()
except IOError:
self.__install_requires = None
def _init_dependencies(self):
try:
with open(os.path.join(self.path, 'dependencies')) as f:
self.__dependencies = f.readline().strip()
except IOError:
self.__dependencies = ''
try:
with open(os.path.join(self.path, 'dependencies_check')) as f:
self.__dependencies_check = f.readline().strip()
except IOError:
self.__dependencies_check = ''
try:
with open(os.path.join(self.path, 'dependencies_order_only')) as f:
self.__dependencies_order_only = f.readline()
except IOError:
self.__dependencies_order_only = ''
|
class PyPiNotFound(Exception):
pass
|
class PyPiError(Exception):
pass
|
class PyPiVersion(object):
def __init__(self, package_name, source='normal'):
self.name = package_name
self.json = self._get_json()
self.name = self.json['info']['name']
if (source == 'wheel'):
self.python_version = 'py3'
else:
self.python_version = 'source'
def _get_json(self):
response = urllib.urlopen(self.json_url)
if (response.getcode() != 200):
raise PyPiNotFound('%s not on pypi', self.name)
data = response.read()
text = data.decode('utf-8')
return json.loads(text)
@property
def json_url(self):
return 'https://pypi.python.org/pypi/{0}/json'.format(self.name)
@property
def version(self):
'\n Return the current version\n '
return self.json['info']['version']
@property
def url(self):
'\n Return the source url\n '
for download in self.json['urls']:
if (self.python_version in download['python_version']):
self.python_version = download['python_version']
return download['url']
raise PyPiError('No %s url for %s found', self.python_version, self.name)
@property
def tarball(self):
'\n Return the source tarball name\n '
for download in self.json['urls']:
if (self.python_version in download['python_version']):
self.python_version = download['python_version']
return download['filename']
raise PyPiError('No %s url for %s found', self.python_version, self.name)
@property
def package_url(self):
'\n Return the package URL\n '
return self.json['info']['package_url']
@property
def license(self):
'\n Return the package license\n '
return self.json['info']['license']
@property
def summary(self):
'\n Return the package summary\n '
return self.json['info']['summary']
def update(self, package=None):
if (package is None):
package = Package(self.name)
if (package.version == self.version):
log.info('%s is already at the latest version', self.name)
return
log.info('Updating %s: %s -> %s', package.name, package.version, self.version)
update = PackageUpdater(package.name, self.version)
update.download_upstream(self.url)
update.fix_checksum()
|
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
|
def init_streams(config):
if (not config.interactive):
sys.stdout = UnbufferedStream(REAL_STDOUT)
|
def flush():
REAL_STDOUT.flush()
REAL_STDERR.flush()
|
class ChecksumError(Exception):
'\n Exception raised when the checksum of the tarball does not match\n '
pass
|
class FileNotMirroredError(Exception):
'\n Exception raised when the tarball cannot be downloaded from the mirrors\n '
pass
|
class Tarball(object):
def __init__(self, tarball_name, package=None):
'\n A (third-party downloadable) tarball\n\n Note that the tarball might also be a different kind of\n archive format that is supported, it does not necessarily have\n to be tar.\n\n INPUT:\n\n - ``tarball_name`` - string. The full filename (``foo-1.3.tar.bz2``)\n of a tarball on the Sage mirror network.\n '
self.__filename = tarball_name
if (package is None):
self.__package = None
for pkg in Package.all():
if (pkg.tarball_filename == tarball_name):
self.__package = pkg.tarball_package
if (self.package is None):
error = 'tarball {0} is not referenced by any Sage package'.format(tarball_name)
log.error(error)
raise ValueError(error)
else:
self.__package = package
if (package.tarball_filename != tarball_name):
error = 'tarball {0} is not referenced by the {1} package'.format(tarball_name, package.name)
log.error(error)
raise ValueError(error)
def __repr__(self):
return 'Tarball {0}'.format(self.filename)
@property
def filename(self):
'\n Return the tarball filename\n\n OUTPUT:\n\n String. The full filename (``foo-1.3.tar.bz2``) of the\n tarball.\n '
return self.__filename
@property
def package(self):
'\n Return the package that the tarball belongs to\n\n OUTPUT:\n\n Instance of :class:`sage_bootstrap.package.Package`\n '
return self.__package
@property
def upstream_fqn(self):
'\n The fully-qualified (including directory) file name in the upstream directory.\n '
return os.path.join(SAGE_DISTFILES, self.filename)
def __eq__(self, other):
return (self.filename == other.filename)
def _compute_hash(self, algorithm):
with open(self.upstream_fqn, 'rb') as f:
while True:
buf = f.read(1048576)
if (not buf):
break
algorithm.update(buf)
return algorithm.hexdigest()
def _compute_sha1(self):
import hashlib
return self._compute_hash(hashlib.sha1())
def _compute_md5(self):
import hashlib
return self._compute_hash(hashlib.md5())
def _compute_cksum(self):
from sage_bootstrap.cksum import CksumAlgorithm
return self._compute_hash(CksumAlgorithm())
def checksum_verifies(self):
'\n Test whether the checksum of the downloaded file is correct.\n '
sha1 = self._compute_sha1()
return (sha1 == self.package.sha1)
def is_distributable(self):
return ('do-not-distribute' not in self.filename)
def download(self, allow_upstream=False):
'\n Download the tarball to the upstream directory.\n\n If allow_upstream is False and the package cannot be found\n on the sage mirrors, fall back to downloading it from\n the upstream URL if the package has one.\n '
if (not self.filename):
raise ValueError('non-normal package does define a tarball, so cannot download')
destination = self.upstream_fqn
if os.path.isfile(destination):
if self.checksum_verifies():
log.info('Using cached file {destination}'.format(destination=destination))
return
else:
log.warning('Invalid checksum; ignoring cached file {destination}'.format(destination=destination))
successful_download = False
log.info('Attempting to download package {0} from mirrors'.format(self.filename))
for mirror in MirrorList():
url = mirror.replace('${SPKG}', self.package.name)
if (not url.endswith('/')):
url += '/'
url += self.filename
log.info(url)
try:
Download(url, destination).run()
successful_download = True
break
except IOError:
log.debug('File not on mirror')
if (not successful_download):
url = self.package.tarball_upstream_url
if (allow_upstream and url):
log.info('Attempting to download from {}'.format(url))
try:
Download(url, destination).run()
except IOError:
raise FileNotMirroredError('tarball does not exist on mirror network and neither at the upstream URL')
else:
raise FileNotMirroredError('tarball does not exist on mirror network')
if (not self.checksum_verifies()):
raise ChecksumError('checksum does not match')
def save_as(self, destination):
'\n Save the tarball as a new file\n '
import shutil
shutil.copy(self.upstream_fqn, destination)
|
def open_archive(filename):
'\n Automatically detect archive type\n '
for cls in ARCHIVE_TYPES:
if cls.can_read(filename):
break
else:
raise ValueError
return cls(filename)
|
def unpack_archive(archive, dirname=None):
'\n Unpack archive\n '
top_level = None
if dirname:
top_levels = set()
for member in archive.names:
top_levels.add(member.split('/', 1)[0])
if (len(top_levels) == 1):
top_level = top_levels.pop()
else:
os.makedirs(dirname)
prev_cwd = os.getcwd()
if (dirname and (not top_level)):
os.chdir(dirname)
try:
archive.extractall(members=archive.names)
if (dirname and top_level):
rename = (lambda : os.rename(top_level, dirname))
retry(rename, OSError, tries=len(archive.names))
os.chmod(dirname, (os.stat(dirname).st_mode & (~ 18)))
finally:
os.chdir(prev_cwd)
|
def make_parser():
parser = argparse.ArgumentParser()
parser.add_argument('-d', dest='dir', metavar='DIR', help='directory to extract archive contents into')
parser.add_argument('pkg', nargs=1, metavar='PKG', help='the archive to extract')
parser.add_argument('file', nargs='?', metavar='FILE', help='(deprecated) print the contents of the given archive member to stdout')
return parser
|
def run():
parser = make_parser()
args = parser.parse_args(sys.argv[1:])
filename = args.pkg[0]
dirname = args.dir
try:
archive = open_archive(filename)
except ValueError:
print('Error: Unknown file type: {}'.format(filename), file=sys.stderr)
return 1
if args.file:
contents = archive.extractbytes(args.file)
if contents:
print(contents, end='')
return 0
else:
return 1
if (dirname and os.path.exists(dirname)):
print('Error: Directory {} already exists'.format(dirname), file=sys.stderr)
return 1
unpack_archive(archive, dirname)
return 0
|
def filter_os_files(filenames):
'\n Given a list of filenames, returns a filtered list with OS-specific\n special files removed.\n\n Currently removes OSX .DS_Store files and AppleDouble format ._ files.\n '
files_set = set(filenames)
def is_os_file(path):
(dirname, name) = os.path.split(path)
if (name == '.DS_Store'):
return True
if name.startswith('._'):
name = os.path.join(dirname, name[2:])
if ((name in files_set) or (os.path.normpath(name) in files_set)):
return True
return False
return [f for f in filenames if (not is_os_file(f))]
|
class SageBaseTarFile(tarfile.TarFile):
"\n Same as tarfile.TarFile, but applies a reasonable umask (0022) to the\n permissions of all extracted files and directories, and fixes\n the encoding of file names in the tarball to be 'utf-8' instead of\n depending on locale settings.\n\n Previously this applied the user's current umask per the default behavior\n of the ``tar`` utility, but this did not provide sufficiently reliable\n behavior in all cases, such as when the user's umask is not strict enough.\n\n This also sets the modified timestamps on all extracted files to the same\n time (the current time), not the timestamps stored in the tarball. This\n is meant to work around https://bugs.python.org/issue32773\n\n See https://github.com/sagemath/sage/issues/20218#comment:16 and\n https://github.com/sagemath/sage/issues/24567 for more background.\n "
umask = 18
def __init__(self, *args, **kwargs):
kwargs['encoding'] = 'utf-8'
super(SageBaseTarFile, self).__init__(*args, **kwargs)
self._extracted_mtime = time.time()
@property
def names(self):
"\n List of filenames in the archive.\n\n Filters out names of OS-related files that shouldn't be in the\n archive (.DS_Store, etc.)\n "
return filter_os_files(self.getnames())
def chmod(self, tarinfo, targetpath):
'Apply ``self.umask`` instead of the permissions in the TarInfo.'
tarinfo = copy.copy(tarinfo)
tarinfo.mode &= (~ self.umask)
tarinfo.mode |= stat.S_IWUSR
tarinfo.mode &= (~ (stat.S_ISUID | stat.S_ISGID))
return super(SageBaseTarFile, self).chmod(tarinfo, targetpath)
def utime(self, tarinfo, targetpath):
"Override to keep the extraction time as the file's timestamp."
tarinfo.mtime = self._extracted_mtime
return super(SageBaseTarFile, self).utime(tarinfo, targetpath)
def extractall(self, path='.', members=None, **kwargs):
'\n Same as tarfile.TarFile.extractall but allows filenames for\n the members argument (like zipfile.ZipFile).\n\n .. note::\n The additional ``**kwargs`` are for Python 2/3 compatibility, since\n different versions of this method accept additional arguments.\n '
if members:
name_to_member = dict(([member.name, member] for member in self.getmembers()))
members = [(m if isinstance(m, tarfile.TarInfo) else name_to_member[m]) for m in members]
return super(SageBaseTarFile, self).extractall(path=path, members=members, **kwargs)
def extractbytes(self, member):
'\n Return the contents of the specified archive member as bytes.\n\n If the member does not exist, returns None.\n '
if (member in self.getnames()):
reader = self.extractfile(member)
return reader.read()
def _extract_member(self, tarinfo, targetpath, **kwargs):
'\n Override to ensure that our custom umask is applied over the entire\n directory tree, even for directories that are not explicitly listed in\n the tarball.\n\n .. note::\n The additional ``**kwargs`` are for Python 2/3 compatibility, since\n different versions of this method accept additional arguments.\n '
old_umask = os.umask(self.umask)
try:
super(SageBaseTarFile, self)._extract_member(tarinfo, targetpath, **kwargs)
finally:
os.umask(old_umask)
|
class SageTarFile(SageBaseTarFile):
'\n A wrapper around SageBaseTarFile such that SageTarFile(filename) is\n essentially equivalent to TarFile.open(filename) which is more\n flexible than the basic TarFile.__init__\n '
def __new__(cls, filename):
return SageBaseTarFile.open(filename)
@staticmethod
def can_read(filename):
'\n Given an archive filename, returns True if this class can read and\n process the archive format of that file.\n '
return tarfile.is_tarfile(filename)
|
class SageTarXZFile(SageBaseTarFile):
'\n A ``.tar.xz`` file which is uncompressed in memory.\n '
def __new__(cls, filename):
proc = subprocess.Popen(['xz', '-d', '-c', filename], stdout=subprocess.PIPE)
(data, _) = proc.communicate()
return SageBaseTarFile(mode='r', fileobj=BytesIO(data))
@staticmethod
def can_read(filename):
'\n Given an archive filename, returns True if this class can read and\n process the archive format of that file.\n '
devnull = open(os.devnull, 'w')
try:
subprocess.check_call(['xz', '-l', filename], stdout=devnull, stderr=devnull)
except Exception:
return False
return True
|
class SageZipFile(zipfile.ZipFile):
"\n Wrapper for zipfile.ZipFile to provide better API fidelity with\n SageTarFile insofar as it's used by this script.\n "
@classmethod
def can_read(cls, filename):
'\n Given an archive filename, returns True if this class can read and\n process the archive format of that file.\n '
return zipfile.is_zipfile(filename)
@property
def names(self):
"\n List of filenames in the archive.\n\n Filters out names of OS-related files that shouldn't be in the\n archive (.DS_Store, etc.)\n "
return filter_os_files(self.namelist())
def extractbytes(self, member):
'\n Return the contents of the specified archive member as bytes.\n\n If the member does not exist, returns None.\n '
if (member in self.namelist()):
return self.read(member)
|
def uninstall(spkg_name, sage_local, keep_files=False, verbose=False):
'\n Given a package name and path to an installation tree (SAGE_LOCAL or SAGE_VENV),\n uninstall that package from that tree if it is currently installed.\n '
spkg_inst = pth.join(sage_local, 'var', 'lib', 'sage', 'installed')
pattern = pth.join(spkg_inst, '{0}-*'.format(spkg_name))
stamp_files = sorted(glob.glob(pattern), key=pth.getmtime)
if keep_files:
print('Removing stamp file but keeping package files')
remove_stamp_files(stamp_files)
return
if stamp_files:
stamp_file = stamp_files[(- 1)]
else:
stamp_file = None
spkg_meta = {}
if stamp_file:
try:
with open(stamp_file) as f:
spkg_meta = json.load(f)
except (OSError, ValueError):
pass
if ('files' not in spkg_meta):
if stamp_file:
print("Old-style or corrupt stamp file '{0}'".format(stamp_file), file=sys.stderr)
else:
print("Package '{0}' is currently not installed".format(spkg_name), file=sys.stderr)
legacy_uninstall(spkg_name, verbose=verbose)
else:
files = spkg_meta['files']
if (not files):
print("Warning: No files to uninstall for '{0}'".format(spkg_name), file=sys.stderr)
modern_uninstall(spkg_name, sage_local, files, verbose=verbose)
remove_stamp_files(stamp_files, verbose=verbose)
|
def legacy_uninstall(spkg_name, verbose=False):
"\n Run the spkg's legacy uninstall script, if one exists; otherwise do\n nothing.\n "
spkg_dir = pth.join(PKGS, spkg_name)
legacy_uninstall = pth.join(spkg_dir, 'spkg-legacy-uninstall')
if (not pth.isfile(legacy_uninstall)):
print("No legacy uninstaller found for '{0}'; nothing to do".format(spkg_name), file=sys.stderr)
return
print("Uninstalling '{0}' with legacy uninstaller".format(spkg_name))
if verbose:
with open(legacy_uninstall) as f:
print(f.read())
subprocess.check_call([legacy_uninstall])
|
def modern_uninstall(spkg_name, sage_local, files, verbose=False):
'\n Remove all listed files from the given installation tree (SAGE_LOCAL or SAGE_VENV).\n\n All file paths should be assumed relative to the installation tree.\n\n This is otherwise (currently) agnostic about what package is actually\n being uninstalled--all it cares about is removing a list of files.\n\n If the directory containing any of the listed files is empty after all\n files are removed then the directory is removed as well.\n '
spkg_scripts = pth.join(sage_local, 'var', 'lib', 'sage', 'scripts')
spkg_scripts = os.environ.get('SAGE_SPKG_SCRIPTS', spkg_scripts)
spkg_scripts = pth.join(spkg_scripts, spkg_name)
files.sort(key=(lambda f: ((- f.count(os.sep)), f)))
print("Uninstalling existing '{0}'".format(spkg_name))
try:
run_spkg_script(spkg_name, spkg_scripts, 'prerm', 'pre-uninstall')
except Exception as exc:
script_path = pth.join(spkg_scripts, 'spkg-prerm')
print("Error: The pre-uninstall script for '{0}' failed; the package will not be uninstalled, and some manual intervention may be needed to repair the package's state before uninstallation can proceed. Check further up in this log for more details, or the pre-uninstall script itself at {1}.".format(spkg_name, script_path), file=sys.stderr)
if isinstance(exc, subprocess.CalledProcessError):
sys.exit(exc.returncode)
else:
sys.exit(1)
try:
run_spkg_script(spkg_name, spkg_scripts, 'piprm', 'pip-uninstall')
except Exception:
print("Warning: Error running the pip-uninstall script for '{0}'; uninstallation may have left behind some files".format(spkg_name), file=sys.stderr)
def rmdir(dirname):
if pth.isdir(dirname):
if (not os.listdir(dirname)):
if verbose:
print('rmdir "{}"'.format(dirname))
os.rmdir(dirname)
else:
print("Warning: Directory '{0}' not found".format(dirname), file=sys.stderr)
for filename in files:
filename = pth.join(sage_local, filename.lstrip(os.sep))
dirname = pth.dirname(filename)
if pth.lexists(filename):
if verbose:
print('rm "{}"'.format(filename))
os.remove(filename)
else:
print("Warning: File '{0}' not found".format(filename), file=sys.stderr)
rmdir(dirname)
try:
run_spkg_script(spkg_name, spkg_scripts, 'postrm', 'post-uninstall')
except Exception:
print("Warning: Error running the post-uninstall script for '{0}'; the package will still be uninstalled, but may have left behind some files or settings".format(spkg_name), file=sys.stderr)
try:
shutil.rmtree(spkg_scripts)
except Exception:
pass
|
def remove_stamp_files(stamp_files, verbose=False):
for stamp_file in stamp_files:
print("Removing stamp file '{0}'".format(stamp_file))
os.remove(stamp_file)
|
def run_spkg_script(spkg_name, path, script_name, script_descr):
'\n Runs the specified ``spkg-<foo>`` script under the given ``path``,\n if it exists.\n '
script = pth.join(path, 'spkg-{0}'.format(script_name))
if pth.exists(script):
print("Running {0} script for '{1}'".format(script_descr, spkg_name))
subprocess.check_call([script])
|
def dir_type(path):
"\n A custom argument 'type' for directory paths.\n "
if (path and (not pth.isdir(path))):
raise argparse.ArgumentTypeError("'{0}' is not a directory".format(path))
return path
|
def make_parser():
'Returns the command-line argument parser for sage-spkg-uninstall.'
doc_lines = __doc__.strip().splitlines()
parser = argparse.ArgumentParser(description=doc_lines[0], epilog='\n'.join(doc_lines[1:]).strip(), formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('spkg', type=str, help='the spkg to uninstall')
parser.add_argument('sage_local', type=dir_type, nargs='?', default=os.environ.get('SAGE_LOCAL'), help='the path of the installation tree (default: the $SAGE_LOCAL environment variable if set)')
parser.add_argument('-v', '--verbose', action='store_true', help='verbose output showing all files removed')
parser.add_argument('-k', '--keep-files', action='store_true', help="only delete the package's installation record, but do not remove files installed by the package")
parser.add_argument('--debug', action='store_true', help=argparse.SUPPRESS)
return parser
|
def run(argv=None):
parser = make_parser()
args = parser.parse_args((argv if (argv is not None) else sys.argv[1:]))
if (args.sage_local is None):
print('Error: An installation tree must be specified either at the command line or in the $SAGE_LOCAL environment variable', file=sys.stderr)
sys.exit(1)
try:
uninstall(args.spkg, args.sage_local, keep_files=args.keep_files, verbose=args.verbose)
except Exception as exc:
print("Error during uninstallation of '{0}': {1}".format(args.spkg, exc), file=sys.stderr)
if args.debug:
raise
sys.exit(1)
|
class ChecksumUpdater(object):
def __init__(self, package_name):
self.__package = None
self.package_name = package_name
@property
def package(self):
if (self.__package is None):
self.__package = Package(self.package_name)
return self.__package
def fix_checksum(self):
checksums_ini = os.path.join(self.package.path, 'checksums.ini')
s = self.checksums_ini()
with open(checksums_ini, 'w') as f:
f.write(s)
def checksums_ini(self):
tarball = self.package.tarball
result = [('tarball=' + self.package.tarball_pattern), ('sha1=' + tarball._compute_sha1()), ('md5=' + tarball._compute_md5()), ('cksum=' + tarball._compute_cksum())]
if self.package.tarball_upstream_url_pattern:
result.append(('upstream_url=' + self.package.tarball_upstream_url_pattern))
result.append('')
return '\n'.join(result)
|
class PackageUpdater(ChecksumUpdater):
def __init__(self, package_name, new_version):
super(PackageUpdater, self).__init__(package_name)
self._update_version(new_version)
def _update_version(self, new_version):
old = Package(self.package_name)
package_version_txt = os.path.join(old.path, 'package-version.txt')
with open(package_version_txt, 'w') as f:
f.write((new_version.strip() + '\n'))
def download_upstream(self, download_url=None):
tarball = self.package.tarball
if (download_url is None):
pattern = self.package.tarball_upstream_url_pattern
if (pattern and ('VERSION' not in pattern)):
print('Warning: upstream_url pattern does not use the VERSION variable')
download_url = self.package.tarball_upstream_url
if (download_url is None):
raise ValueError('package has no default upstream_url pattern, download_url needed')
print('Downloading tarball from {0} to {1}'.format(download_url, tarball.upstream_fqn))
Download(download_url, tarball.upstream_fqn).run()
|
def is_url(url):
'\n Test whether argument is url\n '
url = url.rstrip()
if (len(url.splitlines()) > 1):
return False
if (url.find(' ') >= 0):
return False
return (url.startswith('http://') or url.startswith('https://') or url.startswith('ftp://'))
|
def retry(func, exc=Exception, tries=3, delay=1):
'\n Call ``func()`` up to ``tries`` times, exiting only if the function\n returns without an exception. If the function raises an exception on\n the final try that exception is raised.\n\n If given, ``exc`` can be either an `Exception` or a tuple of `Exception`s\n in which only those exceptions result in a retry, and all other exceptions\n are raised. ``delay`` is the time in seconds between each retry, and\n doubles after each retry.\n '
while True:
try:
return func()
except exc:
tries -= 1
if (tries == 0):
raise
time.sleep(delay)
delay *= 2
|
class LogCaptureHandler(logging.Handler):
def __init__(self, log_capture):
self.records = log_capture.records
logging.Handler.__init__(self)
def emit(self, record):
self.records.append(record)
|
class CapturedLog(object):
def __init__(self):
self.records = []
def __enter__(self):
self.old_level = log.level
self.old_handlers = log.handlers
log.level = logging.INFO
log.handlers = [LogCaptureHandler(self)]
return self
def __exit__(self, type, value, traceback):
log.level = self.old_level
log.handlers = self.old_handlers
def messages(self):
return tuple(((rec.levelname, rec.getMessage()) for rec in self.records))
|
@contextlib.contextmanager
def CapturedOutput():
(new_out, new_err) = (StringIO(), StringIO())
(old_out, old_err) = (sys.stdout, sys.stderr)
try:
(sys.stdout, sys.stderr) = (new_out, new_err)
(yield (sys.stdout, sys.stderr))
finally:
(sys.stdout, sys.stderr) = (old_out, old_err)
|
def print_log():
import logging
log = logging.getLogger()
log.debug('This is the debug log level')
log.info('This is the info log level')
log.warning('This is the warning log level')
log.critical('This is the critical log level')
log.error('This is the error log level')
print('This is printed')
|
def run_with(command, SAGE_BOOTSTRAP):
env = dict(os.environ)
env['SAGE_BOOTSTRAP'] = SAGE_BOOTSTRAP
proc = subprocess.Popen([sys.executable, __file__, command], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = proc.communicate()
return (out.decode('ascii'), err.decode('ascii'))
|
def run_config_with(SAGE_BOOTSTRAP):
(out, err) = run_with('print_config', SAGE_BOOTSTRAP)
assert (not err), err
return json.loads(out)
|
def print_config():
from sage_bootstrap.config import Configuration
from sage_bootstrap.stdio import REAL_STDOUT, REAL_STDERR
config = Configuration()
result = dict(log=config.log, interactive=config.interactive, stdout=('default stdout' if (sys.stdout == REAL_STDOUT) else str(type(sys.stdout))), stderr=('default stderr' if (sys.stderr == REAL_STDERR) else str(type(sys.stderr))))
print(json.dumps(result))
|
def run_log_with(SAGE_BOOTSTRAP):
return run_with('print_log', SAGE_BOOTSTRAP)
|
class CksumTestCase(unittest.TestCase):
def test_cksum_bytes(self):
cksum = CksumAlgorithm()
cksum.update(b'The quick brown fox jumps over the lazy dog\n')
self.assertEqual(cksum.hexdigest(), '2382472371')
def test_cksum_string(self):
cksum = CksumAlgorithm()
cksum.update('The quick brown fox jumps over the lazy dog\n')
self.assertEqual(cksum.hexdigest(), '2382472371')
|
class ConfigurationTestCase(unittest.TestCase):
def test_default(self):
'\n Test the default configuration\n '
config = Configuration()
self.assertEqual(config.log, 'info')
self.assertTrue(config.interactive)
def test_example(self):
'\n Test all ``SAGE_BOOTSTRAP`` settings\n '
SAGE_BOOTSTRAP = ' loG:CrItIcAl, interactive:TRUE'
result = run_config_with(SAGE_BOOTSTRAP)
self.assertEqual(len(result), 4)
self.assertEqual(result['log'], u'critical')
self.assertTrue(result['interactive'])
self.assertEqual(result['stdout'], 'default stdout')
self.assertEqual(result['stderr'], 'default stderr')
def test_logging(self):
'\n Test that the different log levels are understood\n '
for level in LOG_LEVELS:
self.assertEqual(run_config_with('LOG:{0}'.format(level.upper()))['log'], level)
def test_overriding(self):
'\n Test that overriding the isatty detection works\n '
interactive = run_config_with('interactive:true')
self.assertTrue(interactive['interactive'])
self.assertEqual(interactive['stdout'], 'default stdout')
self.assertEqual(interactive['stderr'], 'default stderr')
in_pipe = run_config_with('interactive:false')
self.assertFalse(in_pipe['interactive'])
self.assertEqual(in_pipe['stdout'], u"<class 'sage_bootstrap.stdio.UnbufferedStream'>")
self.assertEqual(in_pipe['stderr'], 'default stderr')
|
class DownloadTestCase(unittest.TestCase):
def test_download_mirror_list(self):
tmp = tempfile.NamedTemporaryFile()
tmp.close()
progress = StringIO()
Download(MirrorList.URL, tmp.name, progress=progress).run()
self.assertEqual(progress.getvalue(), '[......................................................................]\n')
with open(tmp.name, 'r') as f:
content = f.read()
self.assertTrue(content.startswith('# Sage Mirror List'))
def test_error(self):
URL = 'http://files.sagemath.org/sage_bootstrap/this_url_does_not_exist'
progress = StringIO()
download = Download(URL, progress=progress)
log = CapturedLog()
def action():
with log:
download.run()
self.assertRaises(IOError, action)
self.assertIsNotFoundError(log.messages())
self.assertEqual(progress.getvalue(), '[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx]\n')
def test_ignore_errors(self):
URL = 'http://files.sagemath.org/sage_bootstrap/this_url_does_not_exist'
with CapturedLog() as log:
Download(URL, progress=False, ignore_errors=True).run()
self.assertIsNotFoundError(log.messages())
def assertIsNotFoundError(self, messages):
self.assertEqual(len(messages), 1)
self.assertEqual(messages[0][0], 'ERROR')
self.assertTrue(messages[0][1].startswith('[Errno'))
self.assertTrue(messages[0][1].endswith("[Errno 404] Not Found: '//files.sagemath.org/sage_bootstrap/this_url_does_not_exist'"))
|
class SageDownloadFileTestCase(unittest.TestCase):
maxDiff = None
def test_print_mirror_list_no_network(self):
'\n Subsequent runs of sage-download-file\n '
try:
os.remove(MIRRORLIST_FILENAME)
except OSError:
pass
env = dict(os.environ)
env['http_proxy'] = 'http://192.0.2.0:5187/'
env['https_proxy'] = 'http://192.0.2.0:5187/'
env['ftp_proxy'] = 'http://192.0.2.0:5187/'
env['rsync_proxy'] = 'http://192.0.2.0:5187/'
proc = subprocess.Popen([EXECUTABLE, '--print-fastest-mirror', '--timeout=0.001'], stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
(stdout, stderr) = proc.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
rc = proc.returncode
self.assertEqual(rc, 0)
self.assertTrue(is_url(stdout))
self.assertTrue((stderr.find('Downloading the mirror list failed') >= 0))
def test_print_mirror_list_timing(self):
'\n The first run of sage-download-file\n '
try:
os.remove(MIRRORLIST_FILENAME)
except OSError:
pass
proc = subprocess.Popen([EXECUTABLE, '--print-fastest-mirror'], stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
rc = proc.returncode
self.assertEqual(rc, 0)
self.assertTrue(is_url(stdout))
self.assertTrue((len(stderr.strip().splitlines()) > 3))
def test_print_mirror_list_cached(self):
'\n Subsequent runs of sage-download-file\n '
proc = subprocess.Popen([EXECUTABLE, '--print-fastest-mirror'], stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
rc = proc.returncode
self.assertEqual(rc, 0)
self.assertTrue(is_url(stdout))
|
class IsUrlTestCase(unittest.TestCase):
def test_http(self):
self.assertTrue(is_url('http://foo.bar/baz'))
def test_https(self):
self.assertTrue(is_url('https://foo.bar/baz'))
def test_ftp(self):
self.assertTrue(is_url('ftp://foo.bar/baz'))
def test_nospace(self):
self.assertFalse(is_url('http://foo. bar/baz'))
def test_single_line(self):
self.assertFalse(is_url('http://foo.bar/baz\nhttp://foo.bar/baz'))
|
class LoggerTestCase(unittest.TestCase):
def test_interactive(self):
(stdout, stderr) = run_log_with('interactive:true')
self.assertEqual(stderr.strip(), dedent('\n WARNING [runnable|print_log:25]: This is the warning log level\n CRITICAL [runnable|print_log:26]: This is the critical log level\n ERROR [runnable|print_log:27]: This is the error log level\n ').strip())
self.assertEqual(stdout.strip(), dedent('\n This is the info log level\n This is printed\n ').strip())
def test_noninteractive(self):
(stdout, stderr) = run_log_with('interactive:false')
self.assertEqual(stderr.strip(), dedent('\n This is the info log level\n WARNING [runnable|print_log:25]: This is the warning log level\n CRITICAL [runnable|print_log:26]: This is the critical log level\n ERROR [runnable|print_log:27]: This is the error log level\n ').strip())
self.assertEqual(stdout.strip(), dedent('\n This is printed\n ').strip())
def test_debug(self):
'\n The lowest logging level\n '
(stdout, stderr) = run_log_with('log:debug,interactive:true')
self.assertEqual(stderr.strip(), dedent('\n DEBUG [runnable|print_log:23]: This is the debug log level\n WARNING [runnable|print_log:25]: This is the warning log level\n CRITICAL [runnable|print_log:26]: This is the critical log level\n ERROR [runnable|print_log:27]: This is the error log level\n ').strip())
self.assertEqual(stdout.strip(), dedent('\n This is the info log level\n This is printed\n ').strip())
def test_error(self):
'\n The highest logging level\n '
(stdout, stderr) = run_log_with('log:error,interactive:true')
self.assertEqual(stderr.strip(), dedent('\n CRITICAL [runnable|print_log:26]: This is the critical log level\n ERROR [runnable|print_log:27]: This is the error log level\n ').strip())
self.assertEqual(stdout.strip(), dedent('\n This is printed\n ').strip())
|
class MirrorListTestCase(unittest.TestCase):
def test_mirror_list(self):
with CapturedLog() as log:
ml = MirrorList()
msg = log.messages()
if msg:
self.assertEqual(msg[0], ('INFO', 'Downloading the Sage mirror list'))
self.assertGreaterEqual(len(ml.mirrors), 0)
self.assertTrue((ml.fastest.startswith('http://') or ml.fastest.startswith('https://') or ml.fastest.startswith('ftp://')))
|
class PackageTestCase(unittest.TestCase):
maxDiff = None
def test_package(self):
pkg = Package('pari')
self.assertTrue(pkg.name, 'pari')
self.assertTrue(pkg.path.endswith('build/pkgs/pari'))
self.assertEqual(pkg.tarball_pattern, 'pari-VERSION.tar.gz')
self.assertEqual(pkg.tarball_filename, pkg.tarball.filename)
self.assertTrue((pkg.tarball.filename.startswith('pari-') and pkg.tarball.filename.endswith('.tar.gz')))
self.assertTrue((pkg.tarball.filename.startswith('pari-') and pkg.tarball.filename.endswith('.tar.gz')))
self.assertTrue(isinstance(pkg.tarball, Tarball))
def test_all(self):
pari = Package('pari')
self.assertTrue((pari in Package.all()))
|
class SagePackageTestCase(unittest.TestCase):
def run_command(self, *args, **kwds):
env = dict(os.environ)
env.update(kwds.get('env', {}))
env['PATH'] = ((PATH + os.pathsep) + env['PATH'])
kwds.update(stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
log.debug('running {}: {}'.format(args, kwds))
proc = subprocess.Popen(args, **kwds)
(stdout, stderr) = proc.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
log.debug(u'stdout="{}", stderr="{}"'.format(stdout, stderr))
rc = proc.returncode
return (rc, stdout, stderr)
def test_config(self):
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'config')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertTrue(stdout.startswith('Configuration:\n'))
def test_list(self):
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'list')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertTrue(('configure' in stdout.splitlines()))
def test_name(self):
pkg = Package('configure')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'name', pkg.tarball_filename)
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), 'configure')
def test_tarball(self):
pkg = Package('configure')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'tarball', pkg.name)
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), pkg.tarball_filename)
def test_apropos(self):
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'apropos', 'python')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertTrue(stdout.startswith('Did you mean:'))
def test_download(self):
pkg = Package('configure')
with CapturedLog() as _:
pkg.tarball.download()
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'download', pkg.name)
self.assertTrue(stderr.startswith('Using cached file'))
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), pkg.tarball.upstream_fqn)
def test_update(self):
pkg = Package('configure')
self.assertEqual(pkg.patchlevel, (- 1))
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'update', pkg.name, pkg.version)
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout, '')
def test_fix_checksum(self):
pkg = Package('configure')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'fix-checksum', 'configure')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), 'Checksum of {0} (tarball {1}) unchanged'.format(pkg.name, pkg.tarball_filename))
def test_create(self):
tmp = tempfile.mkdtemp()
with open(os.path.join(tmp, 'configure.ac'), 'w+') as f:
f.write('test')
os.mkdir(os.path.join(tmp, 'build'))
os.mkdir(os.path.join(tmp, 'build', 'pkgs'))
os.mkdir(os.path.join(tmp, 'upstream'))
with open(os.path.join(tmp, 'upstream', 'Foo-13.5.tgz'), 'w+') as f:
f.write('tarball content')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'create', 'foo', '--version', '13.5', '--tarball', 'Foo-VERSION.tgz', '--type', 'standard', env=dict(SAGE_ROOT=tmp))
self.assertEqual(rc, 0)
with open(os.path.join(tmp, 'build', 'pkgs', 'foo', 'package-version.txt')) as f:
self.assertEqual(f.read(), '13.5\n')
with open(os.path.join(tmp, 'build', 'pkgs', 'foo', 'type')) as f:
self.assertEqual(f.read(), 'standard\n')
with open(os.path.join(tmp, 'build', 'pkgs', 'foo', 'checksums.ini')) as f:
self.assertEqual(f.read(), ((('tarball=Foo-VERSION.tgz\n' + 'sha1=15d0e36e27c69bc758231f8e9add837f40a40cd0\n') + 'md5=bc62fed5e35f31aeea2af95c00473d4d\n') + 'cksum=1436769867\n'))
shutil.rmtree(tmp)
|
class TarballTestCase(unittest.TestCase):
def test_tarball(self):
pkg = Package('configure')
tarball = Tarball(pkg.tarball_filename)
self.assertEqual(tarball, pkg.tarball)
self.assertEqual(pkg, tarball.package)
with CapturedOutput() as (stdout, stderr):
with CapturedLog() as _:
tarball.download()
self.assertEqual(stdout.getvalue(), '')
self.assertTrue(tarball.checksum_verifies())
def test_checksum(self):
pkg = Package('configure')
tarball = pkg.tarball
with CapturedOutput() as (stdout, stderr):
with CapturedLog() as log:
tarball.download()
self.assertTrue(tarball.checksum_verifies())
with open(tarball.upstream_fqn, 'w') as f:
f.write('foobar')
self.assertFalse(tarball.checksum_verifies())
with CapturedOutput() as (stdout, stderr):
with CapturedLog() as log:
tarball.download()
msg = log.messages()
self.assertTrue((('INFO', 'Attempting to download package {0} from mirrors'.format(pkg.tarball_filename)) in msg))
self.assertEqual(stdout.getvalue(), '')
self.assertEqual(stderr.getvalue(), '[......................................................................]\n')
self.assertTrue(tarball.checksum_verifies())
|
class UncompressTarFileTestCase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.filename = os.path.join(self.tmp, 'test.tar.gz')
self.make_tarfile()
def tearDown(self):
shutil.rmtree(self.tmp)
def make_tarfile(self):
src = os.path.join(self.tmp, 'src')
os.mkdir(src)
os.mkdir(os.path.join(src, 'foo'))
with open(os.path.join(src, 'content'), 'w+') as f:
f.write('root file test')
with open(os.path.join(src, 'foo', 'subcontent'), 'w+') as f:
f.write('subdirectory file test')
subprocess.check_call(['tar', 'czf', self.filename, 'content', 'foo'], cwd=src)
def test_can_read(self):
self.assertTrue(SageTarFile.can_read(self.filename))
self.assertFalse(SageZipFile.can_read(self.filename))
def test_tarball(self):
archive = open_archive(self.filename)
content = archive.extractbytes('content')
self.assertEqual(content, b'root file test')
dst = os.path.join(self.tmp, 'dst')
unpack_archive(archive, dst)
subprocess.check_call(['diff', '-r', 'src', 'dst'], cwd=self.tmp)
|
class UncompressZipFileTestCase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.filename = os.path.join(self.tmp, 'test.zip')
self.make_zipfile()
def tearDown(self):
shutil.rmtree(self.tmp)
def make_zipfile(self):
src = os.path.join(self.tmp, 'src')
os.mkdir(src)
os.mkdir(os.path.join(src, 'foo'))
with open(os.path.join(src, 'content'), 'w+') as f:
f.write('root file test')
with open(os.path.join(src, 'foo', 'subcontent'), 'w+') as f:
f.write('subdirectory file test')
subprocess.check_call(['zip', '-q', '-r', self.filename, 'content', 'foo'], cwd=src)
def test_can_read(self):
self.assertTrue(SageZipFile.can_read(self.filename))
self.assertFalse(SageTarFile.can_read(self.filename))
def test_zipfile(self):
archive = open_archive(self.filename)
content = archive.extractbytes('content')
self.assertEqual(content, b'root file test')
dst = os.path.join(self.tmp, 'dst')
unpack_archive(archive, dst)
subprocess.check_call(['diff', '-r', 'src', 'dst'], cwd=self.tmp)
|
def _main():
from argparse import ArgumentParser
from sys import exit, stdout
parser = ArgumentParser()
parser.add_argument('--version', help='show version', action='version', version=('%(prog)s ' + VERSION))
parser.add_argument('VARIABLE', nargs='?', help='output the value of VARIABLE')
args = parser.parse_args()
d = globals()
if args.VARIABLE:
stdout.write('{}\n'.format(d[args.VARIABLE]))
else:
for (k, v) in d.items():
if (not k.startswith('_')):
stdout.write('{}={}\n'.format(k, v))
|
class build_py(setuptools_build_py):
def run(self):
HERE = os.path.dirname(__file__)
if self.editable_mode:
SAGE_ROOT = os.path.join(HERE, 'sage_root')
else:
SAGE_ROOT = self._create_writable_sage_root()
if (not os.environ.get('CONDA_PREFIX', '')):
raise SetupError('No conda environment is active. See https://doc.sagemath.org/html/en/installation/conda.html on how to get started.')
cmd = f'cd {SAGE_ROOT} && ./configure --enable-build-as-root --with-system-python3=force --disable-notebook --disable-sagelib --disable-sage_conf --disable-doc'
cmd += ' --with-python=$CONDA_PREFIX/bin/python --prefix="$CONDA_PREFIX"'
cmd += ' $(for pkg in $(PATH="build/bin:$PATH" build/bin/sage-package list :standard: --exclude rpy2 --has-file spkg-configure.m4 --has-file distros/conda.txt); do echo --with-system-$pkg=force; done)'
print(f'Running {cmd}')
sys.stdout.flush()
if (os.system(cmd) != 0):
if os.path.exists(os.path.join(SAGE_ROOT, 'config.status')):
print('Warning: A configuration has been written, but the configure script has exited with an error. Carefully check any messages above before continuing.')
else:
print(f'Error: The configure script has failed; this may be caused by missing build prerequisites.')
sys.stdout.flush()
PREREQ_SPKG = '_prereq bzip2 xz libffi'
os.system(f'cd {SAGE_ROOT} && export PACKAGES="$(build/bin/sage-get-system-packages conda {PREREQ_SPKG})" && [ -n "$PACKAGES" ] && echo "You can install the required build prerequisites using the following shell command" && echo "" && build/bin/sage-print-system-package-command conda --verbose --sudo install $PACKAGES && echo ""')
raise SetupError('configure failed')
if self.editable_mode:
pass
else:
shutil.copyfile(os.path.join(SAGE_ROOT, 'pkgs', 'sage-conf', '_sage_conf', '_conf.py'), os.path.join(HERE, '_sage_conf', '_conf.py'))
shutil.copyfile(os.path.join(SAGE_ROOT, 'src', 'bin', 'sage-env-config'), os.path.join(HERE, 'bin', 'sage-env-config'))
setuptools_build_py.run(self)
def _create_writable_sage_root(self):
HERE = os.path.dirname(__file__)
DOT_SAGE = os.environ.get('DOT_SAGE', os.path.join(os.environ.get('HOME'), '.sage'))
with open(os.path.join(HERE, 'VERSION.txt')) as f:
sage_version = f.read().strip()
system = platform.system()
machine = platform.machine()
arch_tag = f'{system}-{machine}'
SAGE_ROOT = os.path.join(DOT_SAGE, f'sage-{sage_version}-{arch_tag}-conda')
def ignore(path, names):
if fnmatch.fnmatch(path, f'*/build/pkgs/*'):
return ['src']
return [name for name in names if (name in ('.tox', '.git', '__pycache__', 'prefix', 'local', 'venv', 'upstream', 'config.status', 'config.log', 'logs'))]
if (not os.path.exists(os.path.join(SAGE_ROOT, 'config.status'))):
try:
shutil.copytree('sage_root', SAGE_ROOT, ignore=ignore)
except Exception as e:
raise SetupError(f'the directory SAGE_ROOT={SAGE_ROOT} already exists but it is not configured ({e}). Please either remove it and try again, or install in editable mode (pip install -e).')
return SAGE_ROOT
|
class build_scripts(distutils_build_scripts):
def run(self):
self.distribution.scripts.append(os.path.join('bin', 'sage-env-config'))
if (not self.distribution.entry_points):
self.entry_points = self.distribution.entry_points = dict()
distutils_build_scripts.run(self)
|
class editable_wheel(setuptools_editable_wheel):
'\n Customized so that exceptions raised by our build_py\n do not lead to the "Customization incompatible with editable install" message\n '
_safely_run = setuptools_editable_wheel.run_command
|
class build_py(setuptools_build_py):
def run(self):
HERE = os.path.dirname(__file__)
if self.editable_mode:
SAGE_ROOT = os.path.join(HERE, 'sage_root')
else:
SAGE_ROOT = self._create_writable_sage_root()
if os.environ.get('CONDA_PREFIX', ''):
SETENV = ':'
else:
SETENV = '. ./.homebrew-build-env 2> /dev/null'
SAGE_LOCAL = os.path.join(SAGE_ROOT, 'local')
if os.path.exists(os.path.join(SAGE_ROOT, 'config.status')):
print(f'Reusing configured SAGE_ROOT={SAGE_ROOT}')
else:
cmd = f'cd {SAGE_ROOT} && ({SETENV}; ./configure --prefix={SAGE_LOCAL} --with-python={sys.executable} --enable-build-as-root --enable-download-from-upstream-url --with-system-python3=force --with-sage-venv --disable-notebook --disable-sagelib --disable-sage_conf --disable-doc)'
print(f'Running {cmd}')
sys.stdout.flush()
if (os.system(cmd) != 0):
print(f'configure failed; this may be caused by missing build prerequisites.')
sys.stdout.flush()
PREREQ_SPKG = '_prereq bzip2 xz libffi'
os.system(f'cd {SAGE_ROOT} && export SYSTEM=$(build/bin/sage-guess-package-system 2>/dev/null) && export PACKAGES="$(build/bin/sage-get-system-packages $SYSTEM {PREREQ_SPKG})" && [ -n "$PACKAGES" ] && echo "You can install the required build prerequisites using the following shell command" && echo "" && build/bin/sage-print-system-package-command $SYSTEM --verbose --sudo install $PACKAGES && echo ""')
raise SetupError('configure failed')
if self.editable_mode:
pass
else:
shutil.copyfile(os.path.join(SAGE_ROOT, 'pkgs', 'sage-conf', '_sage_conf', '_conf.py'), os.path.join(HERE, '_sage_conf', '_conf.py'))
shutil.copyfile(os.path.join(SAGE_ROOT, 'src', 'bin', 'sage-env-config'), os.path.join(HERE, 'bin', 'sage-env-config'))
SETMAKE = 'if [ -z "$MAKE" ]; then export MAKE="make -j$(PATH=build/bin:$PATH build/bin/sage-build-num-threads | cut -d" " -f 2)"; fi'
TARGETS = 'build'
cmd = f'cd {SAGE_ROOT} && ({SETENV}; {SETMAKE} && $MAKE V=0 ${{SAGE_CONF_TARGETS-{TARGETS}}})'
print(f'Running {cmd}', flush=True)
if (os.system(cmd) != 0):
raise SetupError(f'make ${{SAGE_CONF_TARGETS-{TARGETS}}} failed')
setuptools_build_py.run(self)
def _create_writable_sage_root(self):
HERE = os.path.dirname(__file__)
DOT_SAGE = os.environ.get('DOT_SAGE', os.path.join(os.environ.get('HOME'), '.sage'))
with open(os.path.join(HERE, 'VERSION.txt')) as f:
sage_version = f.read().strip()
system = platform.system()
machine = platform.machine()
arch_tag = f'{system}-{machine}'
SAGE_ROOT = os.path.join(DOT_SAGE, f'sage-{sage_version}-{arch_tag}')
def ignore(path, names):
if fnmatch.fnmatch(path, f'*/build/pkgs/*'):
return ['src']
return [name for name in names if (name in ('.tox', '.git', '__pycache__', 'prefix', 'local', 'venv', 'upstream', 'config.status', 'config.log', 'logs'))]
if (not os.path.exists(os.path.join(SAGE_ROOT, 'config.status'))):
try:
shutil.copytree('sage_root', SAGE_ROOT, ignore=ignore)
except Exception as e:
raise SetupError(f'the directory SAGE_ROOT={SAGE_ROOT} already exists but it is not configured ({e}). Please either remove it and try again, or install in editable mode (pip install -e).')
return SAGE_ROOT
|
class build_scripts(distutils_build_scripts):
def run(self):
self.distribution.scripts.append(os.path.join('bin', 'sage-env-config'))
if (not self.distribution.entry_points):
self.entry_points = self.distribution.entry_points = dict()
distutils_build_scripts.run(self)
|
class editable_wheel(setuptools_editable_wheel):
'\n Customized so that exceptions raised by our build_py\n do not lead to the "Customization incompatible with editable install" message\n '
_safely_run = setuptools_editable_wheel.run_command
|
def preprocess_display_latex(text):
'replace $$some display latex$$ with <display>some display latex</display>\n before the soup is built.\n\n Deals with the situation where <p></p> tags are mixed\n with $$, like $$<p>display_latex$$</p>, unless the mess is huge\n\n EXAMPLES::\n\n >>> from sage_sws2rst.comments2rst import preprocess_display_latex\n >>> s="$$a=2$$"\n >>> preprocess_display_latex(s)\n \'<display>a=2</display>\' \n >>> s="<p>$$a=2$$</p>"\n >>> preprocess_display_latex(s)\n \'<p><display>a=2</display></p>\'\n >>> s="<p>$$a=2</p>$$"\n >>> preprocess_display_latex(s)\n \'<p><display>a=2</display></p>\'\n >>> s="$$<p>a=2</p>$$"\n >>> preprocess_display_latex(s)\n \'<display>a=2</display>\'\n '
ls = []
start_tag = True
parts = double_dollar.split(text)
for c in parts[:(- 1)]:
if start_tag:
ls.append(c)
ls.append('<display>')
else:
(c0, count) = prune_tags(c)
ls.append(c0)
ls.append('</display>')
if (count == 1):
ls.append('<p>')
elif (count == (- 1)):
ls.append('</p>')
elif (abs(count) > 1):
raise Exception('display latex was messed up with html code')
start_tag = (not start_tag)
ls.append(parts[(- 1)])
return ''.join(ls)
|
def prune_tags(text):
count = (text.count('<p>') - text.count('</p>'))
return (text.replace('<br/>', '').replace('<br />', '').replace('<p>', '').replace('</p>', ''), count)
|
def escape_chars(text):
for (c, r) in escapable_chars.items():
text = text.replace(c, r)
return text
|
def replace_xml_entities(text):
for (c, r) in xml_entities.items():
text = text.replace(c, r)
return text
|
def replace_courier(soup):
"Lacking a better option, I use courier font to mark <code>\n within tinyMCE. And I want to turn that into real code tags.\n\n Most users won't be needing this(?), so this code is not called anywhere\n but kept for reference\n "
for t in soup.findAll((lambda s: (('style' in s) and ('courier' in s['style'])))):
tag = Tag(soup, 'code')
while t.contents:
tag.append(t.contents[0])
t.replaceWith(tag)
|
def replace_latex(soup):
'Replaces inline latex by :math:`code` and escapes\n some rst special chars like +, -, * and | outside of inline latex\n\n does not escape chars inside display or pre tags\n\n EXAMPLES::\n\n >>> from sage_sws2rst.comments2rst import replace_latex\n >>> from bs4 import BeautifulSoup\n >>> soup = r"<p>Some <strong>latex: $e^\\pi i=-1$</strong></p>"\n >>> s = BeautifulSoup(soup, features=\'html.parser\')\n >>> replace_latex(s)\n >>> s\n <p>Some <strong>latex: :math:`e^\\pi i=-1`</strong></p>\n\n ::\n\n >>> soup = "<p><strong>2+2 | 1+3</strong></p>"\n >>> s = BeautifulSoup(soup, features=\'html.parser\')\n >>> replace_latex(s)\n >>> s\n <p><strong>2\\+2 \\| 1\\+3</strong></p>\n '
for t in soup.findAll(text=re.compile('.+')):
if (t.fetchParents(name='display') or t.fetchParents(name='pre')):
continue
parts = single_dollar.split(t)
even = [escape_chars(parts[i]) for i in range(0, len(parts), 2)]
odd = [(' :math:`%s`' % parts[i]) for i in range(1, len(parts), 2)]
odd.append('')
t.replaceWith(''.join((''.join(p) for p in zip(even, odd))))
|
class Soup2Rst(object):
'builds the rst text from the Soup Tree\n '
tags = {'h1': 'header', 'h2': 'header', 'h3': 'header', 'h4': 'header', 'h5': 'header', 'h6': 'header', 'p': 'p', '[document]': 'document', 'address': 'em', 'br': 'br', 'b': 'strong', 'strong': 'strong', 'em': 'em', 'pre': 'pre', 'code': 'code', 'display': 'display', 'span': 'inline_no_tag', 'ul': 'ul', 'ol': 'ol', 'li': 'li', 'a': 'a', 'table': 'table', 'td': 'inline_no_tag', 'th': 'inline_no_tag', 'tt': 'inline_no_tag', 'div': 'block_no_tag', 'img': 'img'}
headers = {'h1': '=', 'h2': '-', 'h3': '^', 'h4': '"', 'h5': '~', 'h6': '*'}
def __init__(self, images_dir):
self.images_dir = images_dir
self._nested_list = (- 1)
self._inside_ol_or_ul = []
self._inside_code_tag = False
def visit(self, node):
if isinstance(node, (CData, Comment, Declaration, ProcessingInstruction)):
return ''
elif (hasattr(node, 'name') and (node.name in self.tags)):
method = ('visit_' + self.tags[node.name])
visitor = getattr(self, method)
return visitor(node)
else:
return str(node).replace('\n', '')
def visit_document(self, node):
return '\n'.join((self.visit(tag) for tag in node.contents))
def get_plain_text(self, node):
'Gets all text, removing all tags'
if hasattr(node, 'contents'):
t = ' '.join((self.get_plain_text(tag) for tag in node.contents))
else:
t = str(node)
return t.replace('\n', '')
def visit_header(self, node):
s = ''.join((self.visit(tag) for tag in node.contents))
spacer = (self.headers[node.name] * len(s))
return ((s.replace('\n', '') + '\n') + spacer)
def visit_pre(self, node):
return ('::\n\n ' + str(node)[5:(- 6)].replace('<br />', '\n').replace('<br></br>', '\n').replace('\n', '\n '))
def visit_ul(self, node):
self._nested_list += 1
self._inside_ol_or_ul.append(False)
result = (('\n\n' + ''.join((self.visit(tag) for tag in node.contents))) + '\n')
self._inside_ol_or_ul.pop()
self._nested_list -= 1
return result
def visit_ol(self, node):
self._nested_list += 1
self._inside_ol_or_ul.append(True)
result = (('\n\n' + ''.join((self.visit(tag) for tag in node.contents))) + '\n')
self._inside_ol_or_ul.pop()
self._nested_list -= 1
return result
def visit_li(self, node):
return ((((' ' * self._nested_list) + ('#. ' if self._inside_ol_or_ul[(- 1)] else '- ')) + ' '.join((self.visit(tag) for tag in node.contents))) + '\n')
def visit_display(self, node):
return (('\n\n.. MATH::\n\n ' + str(node)[9:(- 10)].replace('<br></br>', '\n').replace('\n', '\n ')) + '\n\n.. end of math\n\n')
def visit_img(self, node):
return (('.. image:: ' + os.path.join(self.images_dir, node['src'].replace(' ', '_'))) + '\n :align: center\n')
def visit_table(self, node):
rows = []
for elt in node.contents:
if (not hasattr(elt, 'name')):
pass
elif (elt.name == 'thead'):
rows.extend((self.prepare_tr(row) for row in elt if (hasattr(row, 'name') and (row.name == 'tr'))))
rows.append([])
elif ((elt.name == 'tbody') or (elt.name == 'tfoot')):
rows.extend((self.prepare_tr(row) for row in elt if (hasattr(row, 'name') and (row.name == 'tr'))))
elif (elt.name == 'tr'):
rows.append(self.prepare_tr(elt))
ncols = max((len(row) for row in rows))
for row in rows:
if (len(row) < ncols):
row.extend(([''] * (ncols - len(row))))
cols_sizes = [max((len(td) for td in tds_in_col)) for tds_in_col in zip(*rows)]
result = [' '.join((('=' * c) for c in cols_sizes))]
for row in rows:
if any((td for td in row)):
result.append(' '.join(((td + (' ' * (l - len(td)))) for (l, td) in zip(cols_sizes, row))))
else:
result.append(' '.join((('-' * c) for c in cols_sizes)))
result.append(' '.join((('=' * c) for c in cols_sizes)))
return '\n'.join(result)
def prepare_tr(self, node):
return [self.visit(tag) for tag in node.contents if (tag != '\n')]
def visit_br(self, node):
return '\n\n'
def visit_strong(self, node):
if node.contents:
content = ' '.join((self.visit(tag) for tag in node.contents)).strip()
if (not content):
return ''
elif ('``' in content):
return content
else:
return ((' **' + content) + '** ')
else:
return ''
def visit_em(self, node):
if node.contents:
content = ' '.join((self.visit(tag) for tag in node.contents)).strip()
if (not content):
return ''
elif ('``' in content):
return content
else:
return ((' *' + content) + '* ')
else:
return ''
def visit_code(self, node):
if node.contents:
content = self.get_plain_text(node).strip()
return (('``' + content) + '``')
else:
return ''
def visit_inline_no_tag(self, node):
return ' '.join((self.visit(tag) for tag in node.contents)).strip()
def visit_block_no_tag(self, node):
return ('\n'.join((self.visit(tag) for tag in node.contents)) + '\n')
def visit_p(self, node):
return (''.join((self.visit(tag) for tag in node.contents)) + '\n\n')
def visit_a(self, node):
c = ' '.join((self.visit(tag) for tag in node.contents))
try:
link = node['href']
if (link[0] == '#'):
return (':ref:`%s <%s>`' % (c, link[1:]))
else:
return ('`%s <%s>`_' % (c, link))
except KeyError:
return ('.. _%s:\n\n' % node['name'])
|
def html2rst(text, images_dir):
'\n Convert html, typically generated by tinyMCE, into rst\n compatible with Sage documentation.\n\n The main job is done by BeautifulSoup, which is much more\n robust than conventional parsers like HTMLParser, but also\n several details specific of this context are taken into\n account, so this code differs from generic approaches like\n those found on the web.\n\n INPUT:\n\n - ``text`` -- string -- a chunk of HTML text\n\n - ``images_dir`` -- string -- folder where images are stored\n\n OUTPUT:\n\n - string -- rst text\n\n EXAMPLES::\n\n >>> from sage_sws2rst.comments2rst import html2rst\n >>> text = r\'<p>Some text with <em>math</em>: $e^{\\pi i}=-1$</p>\'\n >>> html2rst(text, \'\')\n \'Some text with *math* : :math:`e^{\\\\pi i}=-1`\\n\\n\'\n\n ::\n\n >>> text = \'<p>Text with <em>incorrect</p> nesting</em>.\'\n >>> html2rst(text, \'\')\n \'Text with *incorrect* \\n\\n nesting\\n.\'\n\n ::\n\n >>> text = \'<pre>Preformatted: \\n a+2\\n</pre><p> Not preformatted: \\n a+2\\n</p>\'\n >>> html2rst(text, \'\')\n \'::\\n\\n Preformatted: \\n a+2\\n \\n Not preformatted: a\\\\+2\\n\\n\'\n\n ::\n\n >>> text = \'áñ ñá\'\n >>> html2rst(text, \'\')\n \'\\xe1\\xf1 \\xf1\\xe1\'\n\n ::\n\n >>> text = r\'<p>some text</p><p>$$</p><p>3.183098861 \\cdot 10^{-1}</p><p>$$</p>\'\n >>> html2rst(text, \'\')\n \'some text\\n\\n.. MATH::\\n\\n 3.183098861 \\\\cdot 10^{-1}\\n\\n.. end of math\\n\\n\'\n\n When the content is empty::\n\n >>> html2rst("<strong></strong> ", \'\')\n \'\\n \'\n >>> html2rst("<strong> </strong> ", \'\')\n \'\\n \'\n >>> html2rst("<em></em> ", \'\')\n \'\\n \'\n >>> html2rst("<em> </em> ", \'\')\n \'\\n \'\n\n Spaces are added around *italic* or **bold** text (otherwise, it\n may be invalid ReStructuredText syntax)::\n\n >>> text = \'<p><strong>Exercice.</strong>Let x be ...</p>\'\n >>> html2rst(text, \'\')\n \' **Exercice.** Let x be ...\\n\\n\'\n >>> text = \'<p><em>Exercice.</em>Let x be ...</p>\'\n >>> html2rst(text, \'\')\n \' *Exercice.* Let x be ...\\n\\n\'\n\n Below is an example showing the translation from html to rst is not\n always perfect.\n\n Here the strong emphasis is on more than one line and is not properly\n translated::\n\n >>> text=\'<p>You will find a <em>while loop</em> helpful here. Below is a simple example:</p><p style="padding-left: 30px;"><strong>x = 0<br />while x < 7:<br /> x = x + 2<br /> print x</strong></p>\'\n >>> html2rst(text, \'\')\n \'You will find a *while loop* helpful here. Below is a simple\n example:\\n\\n **x = 0 \\n\\n while x < 7: \\n\\n x = x \\\\+ 2 \\n\\n\n print x** \\n\\n\'\n\n '
text = preprocess_display_latex(text)
text = text.replace(' ', ' ')
soup = BeautifulSoup(text, features='html.parser')
comments = soup.findAll(text=(lambda text: isinstance(text, Comment)))
for comment in comments:
comment.extract()
replace_latex(soup)
v = Soup2Rst(images_dir)
text = v.visit(soup)
more_than_2_blank_lines = re.compile('\\n\\n+', re.MULTILINE)
text = more_than_2_blank_lines.sub('\n\n', text)
text = replace_xml_entities(text)
return text
|
class States(object):
NORMAL = 0
HTML = 1
MATH = 2
TRACEBACK = 3
|
class LineTypes(object):
PLAIN = 0
IMAGE = 1
LATEX = 2
HTML = 3
TRACE = 4
|
class ResultsParser(object):
'Auxiliary class for results2rst\n '
def __init__(self, images_dir):
self.transitions = {States.NORMAL: [(re.compile("^\\<html\\>\\<font color='black'\\>\\<img src='cell\\://(.*?)'\\>\\</font\\>\\</html\\>"), (('\n.. image:: ' + images_dir) + '\\1\n :align: center\n'), LineTypes.IMAGE, States.NORMAL), (re.compile('^\\<html\\>\\<div class=\\"math\\"\\>\\\\newcommand\\{\\\\Bold\\}\\[1\\]\\{\\\\mathbf\\{\\#1\\}\\}(.*?)\\</div\\>\\</html\\>$'), '\n.. MATH::\n\n \\1\n', LineTypes.LATEX, States.NORMAL), (re.compile('^\\<html\\>\\<div class=\\"math\\"\\>(.*?)\\</div\\>\\</html\\>$'), '\n.. MATH::\n\n \\1', LineTypes.LATEX, States.NORMAL), (re.compile('^(Traceback.*)'), ' Traceback (most recent call last):', LineTypes.TRACE, States.TRACEBACK), (re.compile('^\\<html\\>\\<div class=\\"math\\"\\>\\\\newcommand\\{\\\\Bold\\}\\[1\\]\\{\\\\mathbf\\{\\#1\\}\\}(.*?)'), '\n.. MATH::\n\n \\1', LineTypes.LATEX, States.MATH), (re.compile('^\\<html\\>.*</html\\>$'), ' <html>...</html>', LineTypes.HTML, States.NORMAL), (re.compile('^\\<html\\>.*'), ' <html>...</html>', LineTypes.HTML, States.HTML), (re.compile('(.*)'), ' \\1', LineTypes.PLAIN, States.NORMAL)], States.MATH: [(re.compile('(.*?)\\</div\\>\\</html\\>$'), ' \\1', LineTypes.LATEX, States.NORMAL), (re.compile('(.*)'), ' \\1', LineTypes.LATEX, States.MATH)], States.TRACEBACK: [(re.compile('^(\\S.*)'), ' ...\n \\1', LineTypes.TRACE, States.NORMAL)], States.HTML: [(re.compile('.*</html\\>$'), '', LineTypes.HTML, States.NORMAL)]}
def parse(self, text):
result_plain = []
result_show = []
state = States.NORMAL
for line in text.splitlines():
for (regex, replacement, line_type, new_state) in self.transitions[state]:
if regex.match(line):
result = (result_plain if (line_type in (LineTypes.PLAIN, LineTypes.HTML)) else result_show)
result.append(regex.sub(replacement, line))
state = new_state
break
result_plain.extend(result_show)
return '\n'.join(result_plain)
|
def results2rst(text, images_dir):
'Converts the result of evaluation of notebook cells\n into rst compatible with Sage documentation.\n\n Several common patterns are identified, and treated\n accordingly. Some patterns are dropped, while others\n are not recognized.\n\n Currently, latex and images are recognized and converted.\n\n INPUT:\n\n - ``text`` -- string -- a chunk of HTML text\n\n - ``images_dir`` -- string -- folder where images are stored\n\n OUTPUT:\n\n - string -- rst text\n\n EXAMPLES::\n\n >>> from sage_sws2rst.results2rst import results2rst\n >>> s="<html><font color=\'black\'><img src=\'cell://sage0.png\'></font></html>"\n >>> results2rst(s,\'\')\n \'\\n.. image:: sage0.png\\n :align: center\\n\'\n >>> results2rst("4",\'\')\n \' 4 \'\n >>> s=r\'<html><div class="math">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\frac{3}{2}</div></html>\'\n >>> results2rst(s,\'\')\n \'\\n.. MATH::\\n\\n \\\\frac{3}{2}\\n\'\n '
Parser = ResultsParser(images_dir)
return Parser.parse(text)
|
class States(object):
COMMENT = 0
CODE = 1
RESULT = 2
RESULT_TO_BE_DROPPED = 3
|
def code_parser(text):
'\n \n Arguments:\n\n INPUT:\n\n - ``s``:sage code, may or may not start with "sage:"\n\n OUTPUT:\n\n - string -- rst text\n\n EXAMPLES (not used for unit test, see \n http://groups.google.com/group/sage-devel/browse_thread/thread/d82cb049ac102f3a)\n\n : from sage_sws2rst.worksheet2rst import code_parser\n : s="a=2"\n : code_parser(s)\n \'::\n\n sage: a=2\'\n : s="def f(n):\n return n+1\n"\n : code_parser(s)\n \'::\n\n sage: def f(n):\n ....: return n+1\'\n : s="sage: def f(n):\nsage: return n+1\n"\n : code_parser(s)\n \'::\n\n sage: def f(n):\n ....: return n+1\'\n '
lines = ['::', '']
for s in text.splitlines():
l = (s[6:] if s.startswith('sage: ') else s)
if (not l):
continue
prefix = (' ....: ' if (l[0] == ' ') else ' sage: ')
lines.append((prefix + l))
return '\n'.join(lines)
|
def add_title_if_there_is_none(text):
if (not HEADER_RE.search(text)):
return ('<h1>Please write a title for this worksheet!</h1>\n' + text)
else:
return text
|
def worksheet2rst(s, images_dir=''):
'Parses a string, tipically the content of the file\n worksheet.html inside a sws file, and converts it into\n rst compatible with Sage documentation.\n\n INPUT:\n\n - ``s`` -- string -- text, tipically the content of\n worksheet.html\n\n - ``images_dir`` -- string -- folder where images are stored\n\n OUTPUT:\n\n - string -- rst text\n\n EXAMPLES (not used for unit test, see \n http://groups.google.com/group/sage-devel/browse_thread/thread/d82cb049ac102f3a)\n\n : from sage_sws2rst.worksheet2rst import worksheet2rst\n : worksheet2rst(\'<p>some text</p>\n{{{id=1|\nprint 2+2\n///\n4\n}}}\')\n u\'.. -*- coding: utf-8 -*-\n\nPlease write a title for this worksheet!\n========================================\n\nsome text\n\n\n::\n\n sage: print 2+2\n 4\n\n.. end of output\n\'\n : s = \'{{{id=2|\nshow(f)\n///\n<html><div class="math">\\sqrt{x}</div></html>\n}}}\n\'\n : worksheet2rst(s)\n u\'.. -*- coding: utf-8 -*-\n\nPlease write a title for this worksheet!\n========================================\n::\n\n sage: show(f)\n\n.. MATH::\n\n \\sqrt{x}\n\n.. end of output\n\'\n '
s = add_title_if_there_is_none(s)
state = States.COMMENT
result = ['.. -*- coding: utf-8 -*-\n']
ls = []
for line in s.splitlines():
(regex, next_state) = transitions[state]
m = regex.match(line)
if m:
if (state == States.COMMENT):
last_cell_id = m.group(1)
img_path = (images_dir + os.path.sep)
result.append(html2rst('\n'.join(ls), img_path))
elif (state == States.RESULT):
img_path = os.path.join(images_dir, ('cell_%s_' % last_cell_id))
result.append(results2rst('\n'.join(ls), img_path))
result.append('')
result.append('.. end of output')
elif (state == States.CODE):
if (ls and any(ls)):
result.append(code_parser('\n'.join(ls)))
else:
next_state = States.RESULT_TO_BE_DROPPED
ls = []
state = next_state
else:
ls.append(line)
if (state == States.COMMENT):
img_path = (images_dir + os.path.sep)
result.append(html2rst('\n'.join(ls), img_path))
elif (state == States.RESULT):
img_path = os.path.join(images_dir, ('cell_%s_' % last_cell_id))
result.append(result_parser('\n'.join(ls), img_path))
result.append('')
result.append('.. end of output')
elif (state == States.CODE):
result.append(code_parser('\n'.join(ls)))
return '\n'.join(result)
|
def number_of_cores():
'\n Try to determine the number of CPU cores in this system.\n If successful return that number. Otherwise return 1.\n '
try:
n = int(os.environ['SAGE_NUM_CORES'])
if (n > 0):
return n
except (ValueError, KeyError):
pass
try:
n = multiprocessing.cpu_count()
if (n > 0):
return n
except NotImplementedError:
pass
try:
from subprocess import Popen, PIPE
p = Popen(['sysctl', '-n', 'hw.ncpu'], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
n = int(p.stdout.read().strip())
if (n > 0):
return n
except (ValueError, OSError):
pass
return 1
|
def num_threads():
'\n Determine the number of threads from the environment variable\n :envvar:`SAGE_NUM_THREADS`. If it is 0 or not provided, use a default\n of ``min(8, number_of_cores)``.\n\n OUTPUT:\n\n a tuple (num_threads, num_threads_parallel, num_cores)\n '
num_cores = number_of_cores()
num_threads = None
num_threads_parallel = num_threads
if (num_threads_parallel is None):
num_threads_parallel = max(min(8, num_cores), 2)
try:
sage_num_threads = int(os.environ['SAGE_NUM_THREADS'])
if (sage_num_threads == 0):
if (num_threads is None):
num_threads = min(8, num_cores)
elif (sage_num_threads > 0):
num_threads = sage_num_threads
num_threads_parallel = sage_num_threads
except (ValueError, KeyError):
pass
if (num_threads is None):
num_threads = 1
try:
sage_num_threads = int(os.environ['SAGE_NUM_THREADS_PARALLEL'])
if (sage_num_threads > 0):
num_threads_parallel = sage_num_threads
except (ValueError, KeyError):
pass
return (num_threads, num_threads_parallel, num_cores)
|
def new_import(name, globals={}, locals={}, fromlist=[], level=DEFAULT_LEVEL):
'\n The new import function\n\n Note that ``name`` is not unique, it can be `sage.foo.bar` or `bar`.\n '
global all_modules, import_counter, parent, direct_children_time
old_direct_children_time = direct_children_time
direct_children_time = 0
old_parent = parent
parent = this_import_counter = import_counter
import_counter += 1
t1 = time.time()
module = old_import(name, globals, locals, fromlist, level)
t2 = time.time()
parent = old_parent
elapsed_time = (t2 - t1)
module_time = (elapsed_time - direct_children_time)
direct_children_time = (old_direct_children_time + elapsed_time)
index_to_parent[this_import_counter] = module
data = all_modules.get(module, None)
if (data is not None):
data['parents'].append(parent)
data['import_names'].add(name)
data['cumulative_time'] += elapsed_time
data['time'] += module_time
return module
data = {'cumulative_time': elapsed_time, 'time': module_time, 'import_names': set([name]), 'parents': [parent]}
all_modules[module] = data
return module
|
def print_separator():
print(('=' * 72))
|
def print_headline(line):
print('=={0:=<68}=='.format(((' ' + line) + ' ')))
|
def print_table(module_list, limit):
global fmt_header, fmt_number
print(fmt_header.format('exclude/ms', 'include/ms', '#parents', 'module name'))
for (t, module, data) in module_list[(- limit):]:
print(fmt_number.format((1000 * t), (1000 * data['cumulative_time']), len(data['parents']), module.__name__))
|
def guess_module_name(src):
module = []
(src, ext) = os.path.splitext(src)
while (src and (src != '/')):
(head, tail) = os.path.split(os.path.abspath(src))
if ((tail == 'src') or any((os.path.exists(os.path.join(head, tail, f)) for f in ('setup.py', 'pyproject.toml')))):
return '.'.join(module)
module.insert(0, tail)
src = head
return None
|
class SageDoctestModule(DoctestModule):
'\n This is essentially a copy of `DoctestModule` from\n https://github.com/pytest-dev/pytest/blob/main/src/_pytest/doctest.py.\n The only change is that we use `SageDocTestParser` to extract the doctests\n and `SageOutputChecker` to verify the output.\n '
def collect(self) -> Iterable[DoctestItem]:
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
'A hackish doctest finder that overrides stdlib internals to fix a stdlib bug.\n https://github.com/pytest-dev/pytest/issues/3456\n https://bugs.python.org/issue25532\n '
def __init__(self) -> None:
super().__init__(parser=SageDocTestParser(set(['sage'])))
def _find_lineno(self, obj, source_lines):
'Doctest code does not take into account `@property`, this\n is a hackish way to fix it. https://bugs.python.org/issue17446\n Wrapped Doctests will need to be unwrapped so the correct\n line number is returned. This will be reported upstream. #8796\n '
if isinstance(obj, property):
obj = getattr(obj, 'fget', obj)
if hasattr(obj, '__wrapped__'):
obj = inspect.unwrap(obj)
return super()._find_lineno(obj, source_lines)
def _find(self, tests, obj, name, module, source_lines, globs, seen) -> None:
if _is_mocked(obj):
return
with _patch_unwrap_mock_aware():
super()._find(tests, obj, name, module, source_lines, globs, seen)
if (self.path.name == 'conftest.py'):
module = self.config.pluginmanager._importconftest(self.path, self.config.getoption('importmode'), rootpath=self.config.rootpath)
else:
try:
module = import_path(self.path, mode=ImportMode.importlib, root=self.config.rootpath)
except ImportError:
if self.config.getvalue('doctest_ignore_import_errors'):
pytest.skip(('unable to import module %r' % self.path))
else:
raise
finder = MockAwareDocTestFinder()
optionflags = get_optionflags(self)
runner = _get_runner(verbose=False, optionflags=optionflags, checker=SageOutputChecker(), continue_on_failure=_get_continue_on_failure(self.config))
for test in finder.find(module, module.__name__):
if test.examples:
(yield DoctestItem.from_parent(self, name=test.name, runner=runner, dtest=test))
|
class IgnoreCollector(pytest.Collector):
'\n Ignore a file.\n '
def __init__(self, parent: pytest.Collector) -> None:
super().__init__('ignore', parent)
def collect(self) -> Iterable[(pytest.Item | pytest.Collector)]:
return []
|
def pytest_collect_file(file_path: Path, parent: pytest.Collector) -> (pytest.Collector | None):
'\n This hook is called when collecting test files, and can be used to\n modify the file or test selection logic by returning a list of\n ``pytest.Item`` objects which the ``pytest`` command will directly\n add to the list of test items.\n\n See `pytest documentation <https://docs.pytest.org/en/latest/reference/reference.html#std-hook-pytest_collect_file>`_.\n '
if (file_path.suffix == '.pyx'):
return IgnoreCollector.from_parent(parent)
elif (file_path.suffix == '.py'):
if parent.config.option.doctestmodules:
return SageDoctestModule.from_parent(parent, path=file_path)
|
@pytest.fixture(autouse=True, scope='session')
def add_imports(doctest_namespace: dict[(str, Any)]):
'\n Add global imports for doctests.\n\n See `pytest documentation <https://docs.pytest.org/en/stable/doctest.html#doctest-namespace-fixture>`.\n '
import sage.all
dict_all = sage.all.__dict__
dict_all.pop('__package__', None)
sage_namespace = dict(dict_all)
sage_namespace['__name__'] = '__main__'
doctest_namespace.update(**sage_namespace)
|
def something():
' a doctest in a docstring\n\n EXAMPLES::\n\n sage: something()\n 42\n sage: something() + 1\n 43\n\n TESTS::\n\n sage: something()\n 44\n '
return 42
|
class TestOldDoctestSageScript():
'Run `sage --t`.'
def test_invoke_on_inputtest_file(self):
result = subprocess.run(['sage', '-t', input_file], capture_output=True, text=True)
assert (result.returncode == 1)
assert ('Failed example:\n something()\nExpected:\n 44\nGot:\n 42\n' in result.stdout)
|
class TestPytestSageScript():
'Run `sage --pytest`.'
def test_invoke_on_inputtest_file(self):
result = subprocess.run(['sage', '--pytest', input_file], capture_output=True, text=True)
assert (result.returncode == 1)
assert ('004 EXAMPLES::\n005 \n006 sage: something()\n007 42\n008 sage: something() + 1\n009 43\n010 \n011 TESTS::\n012 \n013 sage: something()\nExpected:\n 44\nGot:\n 42\n' in result.stdout)
|
def trunc_whitespace(app, doctree, docname):
from docutils.nodes import Text, paragraph
if (not app.config.japanesesupport_trunc_whitespace):
return
for node in doctree.traverse(Text):
if isinstance(node.parent, paragraph):
newtext = node.astext()
newtext = __RGX.sub('\\1\\2', newtext)
node.parent.replace(node, Text(newtext))
|
def setup(app):
app.add_config_value('japanesesupport_trunc_whitespace', True, True)
app.connect('doctree-resolved', trunc_whitespace)
|
class AffineNilTemperleyLiebTypeA(CombinatorialFreeModule):
'\n Construct the affine nilTemperley Lieb algebra of type `A_{n-1}^{(1)}` as used in [Pos2005]_.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n The affine nilTemperley Lieb algebra is generated by `a_i` for `i=0,1,\\ldots,n-1`\n subject to the relations `a_i a_i = a_i a_{i+1} a_i = a_{i+1} a_i a_{i+1} = 0` and\n `a_i a_j = a_j a_i` for `i-j \\not \\equiv \\pm 1`, where the indices are taken modulo `n`.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(4)\n sage: a = A.algebra_generators(); a\n Finite family {0: a0, 1: a1, 2: a2, 3: a3}\n sage: a[1]*a[2]*a[0] == a[1]*a[0]*a[2]\n True\n sage: a[0]*a[3]*a[0]\n 0\n sage: A.an_element()\n 2*a0 + 1 + 3*a1 + a0*a1*a2*a3\n '
def __init__(self, n, R=ZZ, prefix='a'):
'\n Initiate the affine nilTemperley Lieb algebra over the ring `R`.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3, prefix="a"); A\n The affine nilTemperley Lieb algebra A3 over the ring Integer Ring\n sage: TestSuite(A).run()\n sage: A = AffineNilTemperleyLiebTypeA(3, QQ); A\n The affine nilTemperley Lieb algebra A3 over the ring Rational Field\n '
if (not isinstance(R, Ring)):
raise TypeError('argument R must be a ring')
self._cartan_type = CartanType(['A', (n - 1), 1])
self._n = n
W = WeylGroup(self._cartan_type)
self._prefix = prefix
self._index_set = W.index_set()
self._base_ring = R
category = AlgebrasWithBasis(R)
CombinatorialFreeModule.__init__(self, R, W, category=category)
def _element_constructor_(self, w):
'\n Constructs a basis element from an element of the Weyl group.\n\n If `w = w_1 ... w_k` is a reduced word for `w`, then `A(w)` returns\n zero if `w` contains braid relations.\n TODO: Once the functorial construction is in sage, perhaps this should be\n handled constructing the affine nilTemperley Lieb algebra as a quotient algebra.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3, prefix="a")\n sage: W = A.weyl_group()\n sage: w = W.from_reduced_word([2,1,2])\n sage: A(w)\n 0\n sage: w = W.from_reduced_word([2,1])\n sage: A(w)\n a2*a1\n '
W = self.weyl_group()
assert (w in W)
word = w.reduced_word()
if all((self.has_no_braid_relation(W.from_reduced_word(word[:i]), word[i]) for i in range(len(word)))):
return self.monomial(w)
return self.zero()
@cached_method
def one_basis(self):
'\n Return the unit of the underlying Weyl group, which index\n the one of this algebra, as per\n :meth:`AlgebrasWithBasis.ParentMethods.one_basis`.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3)\n sage: A.one_basis()\n [1 0 0]\n [0 1 0]\n [0 0 1]\n sage: A.one_basis() == A.weyl_group().one()\n True\n sage: A.one()\n 1\n '
return self.weyl_group().one()
def _repr_(self):
'\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3); A\n The affine nilTemperley Lieb algebra A3 over the ring Integer Ring\n '
return ('The affine nilTemperley Lieb algebra A%s over the ring %s' % (self._n, self._base_ring))
def weyl_group(self):
"\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3)\n sage: A.weyl_group()\n Weyl Group of type ['A', 2, 1] (as a matrix group acting on the root space)\n "
return self.basis().keys()
def index_set(self):
'\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3)\n sage: A.index_set()\n (0, 1, 2)\n '
return self._index_set
@cached_method
def algebra_generators(self):
'\n Return the generators `a_i` for `i=0,1,2,\\ldots,n-1`.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3)\n sage: a = A.algebra_generators();a\n Finite family {0: a0, 1: a1, 2: a2}\n sage: a[1]\n a1\n '
return self.weyl_group().simple_reflections().map(self.monomial)
def algebra_generator(self, i):
"\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3)\n sage: A.algebra_generator(1)\n a1\n sage: A = AffineNilTemperleyLiebTypeA(3, prefix = 't')\n sage: A.algebra_generator(1)\n t1\n "
return self.algebra_generators()[i]
def product_on_basis(self, w, w1):
'\n Return `a_w a_{w1}`, where `w` and `w1` are in the Weyl group\n assuming that `w` does not contain any braid relations.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(5)\n sage: W = A.weyl_group()\n sage: s = W.simple_reflections()\n sage: [A.product_on_basis(s[1],x) for x in s]\n [a1*a0, 0, a1*a2, a3*a1, a4*a1]\n\n sage: a = A.algebra_generators()\n sage: x = a[1] * a[2]\n sage: x\n a1*a2\n sage: x * a[1]\n 0\n sage: x * a[2]\n 0\n sage: x * a[0]\n a1*a2*a0\n\n sage: [x * a[1] for x in a]\n [a0*a1, 0, a2*a1, a3*a1, a4*a1]\n\n sage: w = s[1]*s[2]*s[1]\n sage: A.product_on_basis(w,s[1])\n Traceback (most recent call last):\n ...\n AssertionError\n '
assert (self(w) != self.zero())
for i in w1.reduced_word():
if self.has_no_braid_relation(w, i):
w = w.apply_simple_reflection(i)
else:
return self.zero()
return self.monomial(w)
@cached_method
def has_no_braid_relation(self, w, i):
'\n Assuming that `w` contains no relations of the form `s_i^2` or `s_i s_{i+1} s_i` or\n `s_i s_{i-1} s_i`, tests whether `w s_i` contains terms of this form.\n\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(5)\n sage: W = A.weyl_group()\n sage: s=W.simple_reflections()\n sage: A.has_no_braid_relation(s[2]*s[1]*s[0]*s[4]*s[3],0)\n False\n sage: A.has_no_braid_relation(s[2]*s[1]*s[0]*s[4]*s[3],2)\n True\n sage: A.has_no_braid_relation(s[4],2)\n True\n '
if (w == w.parent().one()):
return True
if (i in w.descents()):
return False
s = w.parent().simple_reflections()
wi = (w * s[i])
adjacent = [((i - 1) % w.parent().n), ((i + 1) % w.parent().n)]
for j in adjacent:
if (j in w.descents()):
if (j in wi.descents()):
return False
else:
return True
return self.has_no_braid_relation((w * s[w.first_descent()]), i)
def _repr_term(self, t, short_display=True):
"\n EXAMPLES::\n\n sage: A = AffineNilTemperleyLiebTypeA(3)\n sage: W = A.weyl_group()\n sage: A._repr_term(W.from_reduced_word([1,2,0]))\n 'a1*a2*a0'\n sage: A._repr_term(W.from_reduced_word([1,2,0]), short_display = False)\n 'a[1]*a[2]*a[0]'\n "
redword = t.reduced_word()
if (len(redword) == 0):
return '1'
elif short_display:
return '*'.join((('%s%d' % (self._prefix, i)) for i in redword))
else:
return '*'.join((('%s[%d]' % (self._prefix, i)) for i in redword))
|
def is_Algebra(x):
"\n Return True if x is an Algebra.\n\n EXAMPLES::\n\n sage: from sage.algebras.algebra import is_Algebra\n sage: R.<x,y> = FreeAlgebra(QQ,2)\n sage: is_Algebra(R)\n doctest:warning...\n DeprecationWarning: the function is_Algebra is deprecated; use '... in Algebras(base_ring)' instead\n See https://github.com/sagemath/sage/issues/35253 for details.\n True\n "
from sage.misc.superseded import deprecation
deprecation(35253, "the function is_Algebra is deprecated; use '... in Algebras(base_ring)' instead")
try:
return (isinstance(x, Algebra) or (x in Algebras(x.base_ring())))
except Exception:
return False
|
class AskeyWilsonAlgebra(CombinatorialFreeModule):
'\n The (universal) Askey-Wilson algebra.\n\n Let `R` be a commutative ring. The *universal Askey-Wilson* algebra\n is an associative unital algebra `\\Delta_q` over `R[q,q^-1]` given\n by the generators `A, B, C, \\alpha, \\beta, \\gamma` that satisfy the\n following relations:\n\n .. MATH::\n\n \\begin{aligned}\n (q-q^{-1}) \\alpha &= (q^2-q^{-2}) A + qBC - q^{-1}CB, \\\\\n (q-q^{-1}) \\beta &= (q^2-q^{-2}) B + qCA - q^{-1}AC, \\\\\n (q-q^{-1}) \\gamma &= (q^2-q^{-2}) C + qAB - q^{-1}BA.\n \\end{aligned}\n\n The universal Askey-Wilson contains a\n :meth:`Casimir element <casimir_element>` `\\Omega`, and the elements\n `\\alpha`, `\\beta`, `\\gamma`, `\\Omega` generate the center of `\\Delta_q`,\n which is isomorphic to the polynomial ring\n `(R[q,q^-1])[\\alpha,\\beta,\\gamma,\\Omega]` (assuming `q` is not a root\n of unity). Furthermore, the relations imply that `\\Delta_q` has a basis\n given by monomials `A^i B^j C^k \\alpha^r \\beta^s \\gamma^t`, where\n `i, j, k, r, s, t \\in \\ZZ_{\\geq 0}`.\n\n The universal Askey-Wilson algebra also admits a faithful action\n of `PSL_2(\\ZZ)` given by the automorphisms `\\rho`\n (:meth:`permutation_automorphism`):\n\n .. MATH::\n\n A \\mapsto B \\mapsto C \\mapsto A,\n \\qquad\n \\alpha \\mapsto \\beta \\mapsto \\gamma \\mapsto \\alpha.\n\n and `\\sigma` (:meth:`reflection_automorphism`):\n\n .. MATH::\n\n A \\mapsto B \\mapsto A,\n C \\mapsto C + \\frac{AB - BA}{q-q^{-1}},\n \\qquad\n \\alpha \\mapsto \\beta \\mapsto \\alpha,\n \\gamma \\mapsto \\gamma.\n\n Note that `\\rho^3 = \\sigma^2 = 1` and\n\n .. MATH::\n\n \\sigma(C) = C - q AB - (1+q^2) C + q \\gamma\n = C - q AB - q^2 C + q \\gamma.\n\n The Askey-Wilson `AW_q(a,b,c)` algebra is a specialization of the\n universal Askey-Wilson algebra by `\\alpha = a`, \\beta = b`,\n `\\gamma = c`, where `a,b,c \\in R`. `AW_q(a,b,c)` was first introduced\n by [Zhedanov1991]_ to describe the Askey-Wilson polynomials. The\n Askey-Wilson algebra has a central extension of `\\Delta_q`.\n\n INPUT:\n\n - ``R`` -- a commutative ring\n - ``q`` -- (optional) the parameter `q`; must be invertible in ``R``\n\n If ``q`` is not specified, then ``R`` is taken to be the base\n ring of a Laurent polynomial ring with variable `q`. Otherwise\n the element ``q`` must be an element of ``R``.\n\n .. NOTE::\n\n No check is performed to ensure ``q`` is not a root of unity,\n which may lead to violations of the results in [Terwilliger2011]_.\n\n EXAMPLES:\n\n We create the universal Askey-Wilson algebra and check\n the defining relations::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.inject_variables()\n Defining A, B, C, a, b, g\n sage: q = AW.q()\n sage: (q^2-q^-2)*A + q*B*C - q^-1*C*B == (q-q^-1)*a\n True\n sage: (q^2-q^-2)*B + q*C*A - q^-1*A*C == (q-q^-1)*b\n True\n sage: (q^2-q^-2)*C + q*A*B - q^-1*B*A == (q-q^-1)*g\n True\n\n Next, we perform some computations::\n\n sage: C * A\n (q^-2)*A*C + (q^-3-q)*B - (q^-2-1)*b\n sage: B^2 * g^2 * A\n q^4*A*B^2*g^2 - (q^-1-q^7)*B*C*g^2 + (1-q^4)*B*g^3\n + (1-2*q^4+q^8)*A*g^2 - (q-q^3-q^5+q^7)*a*g^2\n sage: (B^3 - A) * (C^2 + q*A*B)\n q^7*A*B^4 + B^3*C^2 - (q^2-q^14)*B^3*C + (q-q^7)*B^3*g - q*A^2*B\n + (3*q^3-4*q^7+q^19)*A*B^2 - A*C^2 - (1-q^6-q^8+q^14)*B^2*a\n - (q^-2-3*q^6+3*q^14-q^22)*B*C\n + (q^-1+q-3*q^3-q^5+2*q^7-q^9+q^13+q^15-q^19)*B*g\n + (2*q^-1-6*q^3+5*q^7-2*q^19+q^23)*A\n - (2-2*q^2-4*q^4+4*q^6+q^8-q^10+q^12-q^14+q^16-q^18-q^20+q^22)*a\n\n We check the elements `\\alpha`, `\\beta`, and `\\gamma`\n are in the center::\n\n sage: all(x * gen == gen * x for gen in AW.algebra_generators() for x in [a,b,g])\n True\n\n We verify that the :meth:`Casimir element <casimir_element>`\n is in the center::\n\n sage: Omega = AW.casimir_element()\n sage: all(x * Omega == Omega * x for x in [A,B,C])\n True\n\n sage: x = AW.an_element()\n sage: O2 = Omega^2\n sage: x * O2 == O2 * x\n True\n\n We prove Lemma 2.1 in [Terwilliger2011]_::\n\n sage: (q^2-q^-2) * C == (q-q^-1) * g - (q*A*B - q^-1*B*A)\n True\n sage: (q-q^-1) * (q^2-q^-2) * a == (B^2*A - (q^2+q^-2)*B*A*B + A*B^2\n ....: + (q^2-q^-2)^2*A + (q-q^-1)^2*B*g)\n True\n sage: (q-q^-1) * (q^2-q^-2) * b == (A^2*B - (q^2+q^-2)*A*B*A + B*A^2\n ....: + (q^2-q^-2)^2*B + (q-q^-1)^2*A*g)\n True\n\n We prove Theorem 2.2 in [Terwilliger2011]_::\n\n sage: q3 = q^-2 + 1 + q^2\n sage: A^3*B - q3*A^2*B*A + q3*A*B*A^2 - B*A^3 == -(q^2-q^-2)^2 * (A*B - B*A)\n True\n sage: B^3*A - q3*B^2*A*B + q3*B*A*B^2 - A*B^3 == -(q^2-q^-2)^2 * (B*A - A*B)\n True\n sage: (A^2*B^2 - B^2*A^2 + (q^2+q^-2)*(B*A*B*A-A*B*A*B)\n ....: == -(q^1-q^-1)^2 * (A*B - B*A) * g)\n True\n\n We construct an Askey-Wilson algebra over `\\GF{5}` at `q=2`::\n\n sage: AW = algebras.AskeyWilson(GF(5), q=2)\n sage: A,B,C,a,b,g = AW.algebra_generators()\n sage: q = AW.q()\n sage: Omega = AW.casimir_element()\n\n sage: B * A\n 4*A*B + 2*g\n sage: C * A\n 4*A*C + 2*b\n sage: C * B\n 4*B*C + 2*a\n sage: Omega^2\n A^2*B^2*C^2 + A^3*B*C + A*B^3*C + A*B*C^3 + A^4 + 4*A^3*a\n + 2*A^2*B^2 + A^2*B*b + 2*A^2*C^2 + 4*A^2*C*g + 4*A^2*a^2\n + 4*A*B^2*a + 4*A*C^2*a + B^4 + B^3*b + 2*B^2*C^2 + 4*B^2*C*g\n + 4*B^2*b^2 + B*C^2*b + C^4 + 4*C^3*g + 4*C^2*g^2 + 2*a*b*g\n\n sage: (q^2-q^-2)*A + q*B*C - q^-1*C*B == (q-q^-1)*a\n True\n sage: (q^2-q^-2)*B + q*C*A - q^-1*A*C == (q-q^-1)*b\n True\n sage: (q^2-q^-2)*C + q*A*B - q^-1*B*A == (q-q^-1)*g\n True\n sage: all(x * Omega == Omega * x for x in [A,B,C])\n True\n\n REFERENCES:\n\n - [Terwilliger2011]_\n '
@staticmethod
def __classcall_private__(cls, R, q=None):
'\n Normalize input to ensure a unique representation.\n\n TESTS::\n\n sage: R.<q> = LaurentPolynomialRing(QQ)\n sage: AW1 = algebras.AskeyWilson(QQ)\n sage: AW2 = algebras.AskeyWilson(R, q)\n sage: AW1 is AW2\n True\n\n sage: AW = algebras.AskeyWilson(ZZ, 0)\n Traceback (most recent call last):\n ...\n ValueError: q cannot be 0\n\n sage: AW = algebras.AskeyWilson(ZZ, 3)\n Traceback (most recent call last):\n ...\n ValueError: q=3 is not invertible in Integer Ring\n '
if (q is None):
R = LaurentPolynomialRing(R, 'q')
q = R.gen()
else:
q = R(q)
if (q == 0):
raise ValueError('q cannot be 0')
if ((1 / q) not in R):
raise ValueError('q={} is not invertible in {}'.format(q, R))
if (R not in Rings().Commutative()):
raise ValueError('{} is not a commutative ring'.format(R))
return super().__classcall__(cls, R, q)
def __init__(self, R, q):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: TestSuite(AW).run() # long time\n '
self._q = q
cat = Algebras(Rings().Commutative()).WithBasis()
indices = cartesian_product(([NonNegativeIntegers()] * 6))
CombinatorialFreeModule.__init__(self, R, indices, prefix='AW', sorting_key=_basis_key, sorting_reverse=True, category=cat)
self._assign_names('A,B,C,a,b,g')
def _repr_term(self, t):
"\n Return a string representation of the basis element indexed by ``t``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW._repr_term((0,0,0,0,0,0))\n '1'\n sage: AW._repr_term((5,1,2,3,7,2))\n 'A^5*B*C^2*a^3*b^7*g^2'\n sage: AW._repr_term((0,1,0,3,7,2))\n 'B*a^3*b^7*g^2'\n "
def exp(l, e):
if (e == 0):
return ''
if (e == 1):
return ('*' + l)
return (('*' + l) + '^{}'.format(e))
ret = ''.join((exp(l, e) for (l, e) in zip(['A', 'B', 'C', 'a', 'b', 'g'], t)))
if (not ret):
return '1'
if (ret[0] == '*'):
ret = ret[1:]
return ret
def _latex_term(self, t):
"\n Return a latex representation of the basis element indexed by ``t``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW._latex_term((0,0,0,0,0,0))\n '1'\n sage: AW._latex_term((5,1,2,3,7,2))\n 'A^{5}BC^{2}\\\\alpha^{3}\\\\beta^{7}\\\\gamma^{2}'\n sage: AW._latex_term((0,1,0,3,7,2))\n 'B\\\\alpha^{3}\\\\beta^{7}\\\\gamma^{2}'\n "
if (sum(t) == 0):
return '1'
def exp(l, e):
if (e == 0):
return ''
if (e == 1):
return l
return (l + '^{{{}}}'.format(e))
var_names = ['A', 'B', 'C', '\\alpha', '\\beta', '\\gamma']
return ''.join((exp(l, e) for (l, e) in zip(var_names, t)))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.AskeyWilson(QQ)\n Askey-Wilon algebra with q=q over\n Univariate Laurent Polynomial Ring in q over Rational Field\n '
return 'Askey-Wilon algebra with q={} over {}'.format(self._q, self.base_ring())
@cached_method
def algebra_generators(self):
"\n Return the algebra generators of ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: G = AW.algebra_generators()\n sage: G['A']\n A\n sage: G['a']\n a\n sage: list(G)\n [A, B, C, a, b, g]\n "
A = self.variable_names()
def build_monomial(g):
exp = ([0] * 6)
exp[A.index(g)] = 1
return self.monomial(self._indices(exp))
return Family(A, build_monomial)
@cached_method
def gens(self):
'\n Return the generators of ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.gens()\n (A, B, C, a, b, g)\n '
return tuple(self.algebra_generators())
@cached_method
def one_basis(self):
'\n Return the index of the basis element `1` of ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.one_basis()\n (0, 0, 0, 0, 0, 0)\n '
return self._indices(([0] * 6))
def q(self):
'\n Return the parameter `q` of ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: q = AW.q()\n sage: q\n q\n sage: q.parent()\n Univariate Laurent Polynomial Ring in q over Rational Field\n '
return self._q
@cached_method
def an_element(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.an_element()\n (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A\n '
q = self._q
I = self._indices
R = self.base_ring()
elt = {I((1, 0, 0, 0, 0, 0)): R(1), I((1, 0, 2, 0, 1, 0)): R.an_element(), I((0, 1, 0, 2, 0, 1)): ((q ** 2) * R(3)), I((0, 0, 0, 1, 1, 3)): ((((q ** (- 3)) + R(3)) + (R(2) * q)) + (q ** 2))}
return self.element_class(self, elt)
def some_elements(self):
'\n Return some elements of ``self``.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.some_elements()\n (A, B, C, a, b, g, 1,\n (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A,\n q*A*B*C + q^2*A^2 - q*A*a + (q^-2)*B^2 - (q^-1)*B*b + q^2*C^2 - q*C*g)\n '
return (self.gens() + (self.one(), self.an_element(), self.casimir_element()))
@cached_method
def casimir_element(self):
'\n Return the Casimir element of ``self``.\n\n The Casimir element of the Askey-Wilson algebra `\\Delta_q` is\n\n .. MATH::\n\n \\Omega = q ABC + q^2 A^2 + q^{-2} B^2 + q^2 C^2\n - q A\\alpha - q^{-1} B\\beta - q C\\gamma.\n\n The center `Z(\\Delta_q)` is generated by `\\alpha`, `\\beta`,\n `\\gamma`, and `\\Omega`.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.casimir_element()\n q*A*B*C + q^2*A^2 - q*A*a + (q^-2)*B^2 - (q^-1)*B*b + q^2*C^2 - q*C*g\n\n We check that the Casimir element is in the center::\n\n sage: Omega = AW.casimir_element()\n sage: all(Omega * gen == gen * Omega for gen in AW.algebra_generators())\n True\n '
q = self._q
I = self._indices
d = {I((1, 1, 1, 0, 0, 0)): q, I((2, 0, 0, 0, 0, 0)): (q ** 2), I((0, 2, 0, 0, 0, 0)): (q ** (- 2)), I((0, 0, 2, 0, 0, 0)): (q ** 2), I((1, 0, 0, 1, 0, 0)): (- q), I((0, 1, 0, 0, 1, 0)): (- (q ** (- 1))), I((0, 0, 1, 0, 0, 1)): (- q)}
return self.element_class(self, d)
@cached_method
def product_on_basis(self, x, y):
'\n Return the product of the basis elements indexed by ``x`` and ``y``.\n\n INPUT:\n\n - ``x``, ``y`` -- tuple of length 6\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: AW.product_on_basis((0,0,0,0,0,0), (3,5,2,0,12,3))\n A^3*B^5*C^2*b^12*g^3\n sage: AW.product_on_basis((0,0,0,5,3,5), (3,5,2,0,12,3))\n A^3*B^5*C^2*a^5*b^15*g^8\n sage: AW.product_on_basis((7,0,0,5,3,5), (0,5,2,0,12,3))\n A^7*B^5*C^2*a^5*b^15*g^8\n sage: AW.product_on_basis((7,3,0,5,3,5), (0,2,2,0,12,3))\n A^7*B^5*C^2*a^5*b^15*g^8\n sage: AW.product_on_basis((0,1,0,5,3,5), (2,0,0,0,5,3))\n q^4*A^2*B*a^5*b^8*g^8 - (q^-3-q^5)*A*C*a^5*b^8*g^8\n + (1-q^4)*A*a^5*b^8*g^9 - (q^-4-2+q^4)*B*a^5*b^8*g^8\n + (q^-3-q^-1-q+q^3)*a^5*b^9*g^8\n sage: AW.product_on_basis((0,2,1,0,2,0), (1,1,0,2,1,0))\n q^4*A*B^3*C*a^2*b^3 - (q^5-q^9)*A^2*B^2*a^2*b^3\n + (q^2-q^4)*A*B^2*a^3*b^3 + (q^-3-q)*B^4*a^2*b^3\n - (q^-2-1)*B^3*a^2*b^4 - (q-q^9)*B^2*C^2*a^2*b^3\n + (1-q^4)*B^2*C*a^2*b^3*g + (q^-4+2-5*q^4+2*q^12)*A*B*C*a^2*b^3\n - (q^-1+q-2*q^3-2*q^5+q^7+q^9)*A*B*a^2*b^3*g\n - (q^-3-q^3-2*q^5+q^7+q^9)*B*C*a^3*b^3\n + (q^-2-1-q^2+q^4)*B*a^3*b^3*g\n - (q^-3-2*q+2*q^9-q^13)*A^2*a^2*b^3\n + (2*q^-2-2-3*q^2+3*q^4+q^10-q^12)*A*a^3*b^3\n + (q^-7-2*q^-3+2*q^5-q^9)*B^2*a^2*b^3\n - (q^-6-q^-4-q^-2+1-q^2+q^4+q^6-q^8)*B*a^2*b^4\n - (q^-7-q^-3-2*q+2*q^5+q^9-q^13)*C^2*a^2*b^3\n + (q^-6-3-2*q^2+5*q^4-q^8+q^10-q^12)*C*a^2*b^3*g\n - (q^-1-2*q+2*q^5-q^7)*a^4*b^3\n - (q^-3-q^-1-2*q+2*q^3+q^5-q^7)*a^2*b^3*g^2\n '
I = self._indices
lhs = list(x[:3])
rhs = list(y)
for i in range(3, 6):
rhs[i] += x[i]
if (sum(rhs[:3]) == 0):
return self.monomial(I((lhs + rhs[3:])))
q = self._q
if (lhs[2] > 0):
if (rhs[0] > 0):
lhs[2] -= 1
rhs[0] -= 1
rel = {I((1, 0, 1, 0, 0, 0)): (q ** (- 2)), I((0, 1, 0, 0, 0, 0)): ((q ** (- 3)) - (q ** 1)), I((0, 0, 0, 0, 1, 0)): (1 - (q ** (- 2)))}
rel = self.element_class(self, rel)
return (self.monomial(I((lhs + ([0] * 3)))) * (rel * self.monomial(I(rhs))))
elif (rhs[1] > 0):
lhs[2] -= 1
rhs[1] -= 1
rel = {I((0, 1, 1, 0, 0, 0)): (q ** 2), I((1, 0, 0, 0, 0, 0)): ((q ** 3) - (q ** (- 1))), I((0, 0, 0, 1, 0, 0)): ((- (q ** 2)) + 1)}
rel = self.element_class(self, rel)
return (self.monomial(I((lhs + ([0] * 3)))) * (rel * self.monomial(I(rhs))))
else:
rhs[2] += lhs[2]
rhs[1] = lhs[1]
rhs[0] = lhs[0]
return self.monomial(I(rhs))
elif (lhs[1] > 0):
if (rhs[0] > 0):
lhs[1] -= 1
rhs[0] -= 1
rel = {I((1, 1, 0, 0, 0, 0)): (q ** 2), I((0, 0, 1, 0, 0, 0)): ((q ** 3) - (q ** (- 1))), I((0, 0, 0, 0, 0, 1)): ((- (q ** 2)) + 1)}
rel = self.element_class(self, rel)
return (self.monomial(I((lhs + ([0] * 3)))) * (rel * self.monomial(I(rhs))))
else:
rhs[1] += lhs[1]
rhs[0] = lhs[0]
return self.monomial(I(rhs))
elif (lhs[0] > 0):
rhs[0] += lhs[0]
return self.monomial(I(rhs))
return self.monomial(I(rhs))
def permutation_automorphism(self):
'\n Return the permutation automorphism `\\rho` of ``self``.\n\n We define the automorphism `\\rho` by\n\n .. MATH::\n\n A \\mapsto B \\mapsto C \\mapsto A,\n \\qquad\n \\alpha \\mapsto \\beta \\mapsto \\gamma \\mapsto \\alpha.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: rho = AW.permutation_automorphism()\n sage: [rho(gen) for gen in AW.algebra_generators()]\n [B, C, A, b, g, a]\n\n sage: AW.an_element()\n (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A\n sage: rho(AW.an_element())\n (q^-3+3+2*q+q^2)*a^3*b*g + q^5*A^2*B*g + 3*q^2*C*a*b^2\n - (q^-2-q^6)*A*C*g + (q-q^5)*A*g^2 - (q^-3-2*q+q^5)*B*g\n + (q^-2-1-q^2+q^4)*b*g + B\n\n sage: r3 = rho * rho * rho\n sage: [r3(gen) for gen in AW.algebra_generators()]\n [A, B, C, a, b, g]\n sage: r3(AW.an_element()) == AW.an_element()\n True\n '
(A, B, C, a, b, g) = self.gens()
return AlgebraMorphism(self, [B, C, A, b, g, a], codomain=self)
rho = permutation_automorphism
def reflection_automorphism(self):
'\n Return the reflection automorphism `\\sigma` of ``self``.\n\n We define the automorphism `\\sigma` by\n\n .. MATH::\n\n A \\mapsto B \\mapsto A,\n \\qquad\n C \\mapsto C + \\frac{AB - BA}{q-q^{-1}}\n = C - qAB - (1+q^2) C + q \\gamma,\n\n .. MATH::\n\n \\alpha \\mapsto \\beta \\mapsto \\alpha,\n \\gamma \\mapsto \\gamma.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: sigma = AW.reflection_automorphism()\n sage: [sigma(gen) for gen in AW.algebra_generators()]\n [B, A, -q*A*B - q^2*C + q*g, b, a, g]\n\n sage: AW.an_element()\n (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A\n sage: sigma(AW.an_element())\n q^9*A^2*B^3*a + (q^10+q^14)*A*B^2*C*a - (q^7+q^9)*A*B^2*a*g\n + (q^-3+3+2*q+q^2)*a*b*g^3 + (q-3*q^9+q^13+q^17)*A^2*B*a\n - (q^2-q^6-q^8+q^14)*A*B*a^2 + 3*q^2*A*b^2*g + (q^5-q^9)*B^3*a\n - (q^6-q^8)*B^2*a*b + q^13*B*C^2*a - 2*q^10*B*C*a*g + q^7*B*a*g^2\n + (q^2-2*q^10+q^18)*A*C*a - (q-q^7-2*q^9+2*q^11-q^15+q^17)*A*a*g\n - (q^3-q^7-q^9+q^13)*C*a^2 + (q^2-q^6-2*q^8+2*q^10)*a^2*g\n + (q-3*q^5+3*q^9-q^13)*B*a - (q^2-q^4-2*q^6+2*q^8+q^10-q^12)*a*b + B\n\n sage: s2 = sigma * sigma\n sage: [s2(gen) for gen in AW.algebra_generators()]\n [A, B, C, a, b, g]\n sage: s2(AW.an_element()) == AW.an_element()\n True\n '
(A, B, C, a, b, g) = self.gens()
q = self._q
Cp = (((C - ((q * A) * B)) - ((1 + (q ** 2)) * C)) + (q * g))
return AlgebraMorphism(self, [B, A, Cp, b, a, g], codomain=self)
sigma = reflection_automorphism
def loop_representation(self):
'\n Return the map `\\pi` from ``self`` to `2 \\times 2` matrices\n over `R[\\lambda,\\lambda^{-1}]`, where `F` is the fraction field\n of the base ring of ``self``.\n\n Let `AW` be the Askey-Wilson algebra over `R`, and let `F` be\n the fraction field of `R`. Let `M` be the space of `2 \\times 2`\n matrices over `F[\\lambda, \\lambda^{-1}]`. Consider the following\n elements of `M`:\n\n .. MATH::\n\n \\mathcal{A} = \\begin{pmatrix}\n \\lambda & 1 - \\lambda^{-1} \\\\ 0 & \\lambda^{-1}\n \\end{pmatrix},\n \\qquad\n \\mathcal{B} = \\begin{pmatrix}\n \\lambda^{-1} & 0 \\\\ \\lambda - 1 & \\lambda\n \\end{pmatrix},\n \\qquad\n \\mathcal{C} = \\begin{pmatrix}\n 1 & \\lambda - 1 \\\\ 1 - \\lambda^{-1} & \\lambda + \\lambda^{-1} - 1\n \\end{pmatrix}.\n\n From Lemma 3.11 of [Terwilliger2011]_, we define a\n representation `\\pi: AW \\to M` by\n\n .. MATH::\n\n A \\mapsto q \\mathcal{A} + q^{-1} \\mathcal{A}^{-1},\n \\qquad\n B \\mapsto q \\mathcal{B} + q^{-1} \\mathcal{B}^{-1},\n \\qquad\n C \\mapsto q \\mathcal{C} + q^{-1} \\mathcal{C}^{-1},\n\n .. MATH::\n\n \\alpha, \\beta, \\gamma \\mapsto \\nu I,\n\n where `\\nu = (q^2 + q^-2)(\\lambda + \\lambda^{-1})\n + (\\lambda + \\lambda^{-1})^2`.\n\n We call this representation the *loop representation* as\n it is a representation using the loop group\n `SL_2(F[\\lambda,\\lambda^{-1}])`.\n\n EXAMPLES::\n\n sage: AW = algebras.AskeyWilson(QQ)\n sage: q = AW.q()\n sage: pi = AW.loop_representation()\n sage: A,B,C,a,b,g = [pi(gen) for gen in AW.algebra_generators()]\n sage: A\n [ 1/q*lambda^-1 + q*lambda ((-q^2 + 1)/q)*lambda^-1 + ((q^2 - 1)/q)]\n [ 0 q*lambda^-1 + 1/q*lambda]\n sage: B\n [ q*lambda^-1 + 1/q*lambda 0]\n [((-q^2 + 1)/q) + ((q^2 - 1)/q)*lambda 1/q*lambda^-1 + q*lambda]\n sage: C\n [1/q*lambda^-1 + ((q^2 - 1)/q) + 1/q*lambda ((q^2 - 1)/q) + ((-q^2 + 1)/q)*lambda]\n [ ((q^2 - 1)/q)*lambda^-1 + ((-q^2 + 1)/q) q*lambda^-1 + ((-q^2 + 1)/q) + q*lambda]\n sage: a\n [lambda^-2 + ((q^4 + 1)/q^2)*lambda^-1 + 2 + ((q^4 + 1)/q^2)*lambda + lambda^2 0]\n [ 0 lambda^-2 + ((q^4 + 1)/q^2)*lambda^-1 + 2 + ((q^4 + 1)/q^2)*lambda + lambda^2]\n sage: a == b\n True\n sage: a == g\n True\n\n sage: AW.an_element()\n (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A\n sage: x = pi(AW.an_element())\n sage: y = (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A\n sage: x == y\n True\n\n We check the defining relations of the Askey-Wilson algebra::\n\n sage: A + (q*B*C - q^-1*C*B) / (q^2 - q^-2) == a / (q + q^-1)\n True\n sage: B + (q*C*A - q^-1*A*C) / (q^2 - q^-2) == b / (q + q^-1)\n True\n sage: C + (q*A*B - q^-1*B*A) / (q^2 - q^-2) == g / (q + q^-1)\n True\n\n We check Lemma 3.12 in [Terwilliger2011]_::\n\n sage: M = pi.codomain()\n sage: la = M.base_ring().gen()\n sage: p = M([[0,-1],[1,1]])\n sage: s = M([[0,1],[la,0]])\n sage: rho = AW.rho()\n sage: sigma = AW.sigma()\n sage: all(p*pi(gen)*~p == pi(rho(gen)) for gen in AW.algebra_generators())\n True\n sage: all(s*pi(gen)*~s == pi(sigma(gen)) for gen in AW.algebra_generators())\n True\n '
from sage.matrix.matrix_space import MatrixSpace
q = self._q
base = LaurentPolynomialRing(self.base_ring().fraction_field(), 'lambda')
la = base.gen()
inv = (~ la)
M = MatrixSpace(base, 2)
A = M([[la, (1 - inv)], [0, inv]])
Ai = M([[inv, (inv - 1)], [0, la]])
B = M([[inv, 0], [(la - 1), la]])
Bi = M([[la, 0], [(1 - la), inv]])
C = M([[1, (1 - la)], [(inv - 1), ((la + inv) - 1)]])
Ci = M([[((la + inv) - 1), (la - 1)], [(1 - inv), 1]])
mu = (la + inv)
nu = ((((self._q ** 2) + (self._q ** (- 2))) * mu) + (mu ** 2))
nuI = M(nu)
category = Rings()
return AlgebraMorphism(self, [((q * A) + ((q ** (- 1)) * Ai)), ((q * B) + ((q ** (- 1)) * Bi)), ((q * C) + ((q ** (- 1)) * Ci)), nuI, nuI, nuI], codomain=M, category=category)
pi = loop_representation
|
def _basis_key(t):
'\n Return a key for the basis element of the Askey-Wilson algebra\n indexed by ``t``.\n\n EXAMPLES::\n\n sage: from sage.algebras.askey_wilson import _basis_key\n sage: I = algebras.AskeyWilson(QQ).indices()\n sage: _basis_key(I((0,2,3,1,2,5)))\n (13, (0, 2, 3, 1, 2, 5))\n '
return (sum(t), t.value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.