code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
from sage.misc.misc import walltime, cputime
def count_noun(number, noun, plural=None, pad_number=False, pad_noun=False):
"""
EXAMPLES::
sage: from sage.doctest.util import count_noun
sage: count_noun(1, "apple")
'1 apple'
sage: count_noun(1, "apple", pad_noun=True)
'1 apple '
sage: count_noun(1, "apple", pad_number=3)
' 1 apple'
sage: count_noun(2, "orange")
'2 oranges'
sage: count_noun(3, "peach", "peaches")
'3 peaches'
sage: count_noun(1, "peach", plural="peaches", pad_noun=True)
'1 peach '
"""
if plural is None:
plural = noun + "s"
if pad_noun:
# We assume that the plural is never shorter than the noun....
pad_noun = " " * (len(plural) - len(noun))
else:
pad_noun = ""
if pad_number:
number_str = ("%%%sd"%pad_number)%number
else:
number_str = "%d"%number
if number == 1:
return "%s %s%s"%(number_str, noun, pad_noun)
else:
return "%s %s"%(number_str, plural)
def dict_difference(self, other):
"""
Return a dict with all key-value pairs occurring in ``self`` but not
in ``other``.
EXAMPLES::
sage: from sage.doctest.util import dict_difference
sage: d1 = {1: 'a', 2: 'b', 3: 'c'}
sage: d2 = {1: 'a', 2: 'x', 4: 'c'}
sage: dict_difference(d2, d1)
{2: 'x', 4: 'c'}
::
sage: from sage.doctest.control import DocTestDefaults
sage: D1 = DocTestDefaults()
sage: D2 = DocTestDefaults(foobar="hello", timeout=100)
sage: dict_difference(D2.__dict__, D1.__dict__)
{'foobar': 'hello', 'timeout': 100}
"""
D = dict()
for k, v in self.items():
try:
if other[k] == v:
continue
except KeyError:
pass
D[k] = v
return D
class Timer:
"""
A simple timer.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer()
{}
sage: TestSuite(Timer()).run()
"""
def start(self):
"""
Start the timer.
Can be called multiple times to reset the timer.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer().start()
{'cputime': ..., 'walltime': ...}
"""
self.cputime = cputime()
self.walltime = walltime()
return self
def stop(self):
"""
Stops the timer, recording the time that has passed since it
was started.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: import time
sage: timer = Timer().start()
sage: time.sleep(float(0.5))
sage: timer.stop()
{'cputime': ..., 'walltime': ...}
"""
self.cputime = cputime(self.cputime)
self.walltime = walltime(self.walltime)
return self
def annotate(self, object):
"""
Annotates the given object with the cputime and walltime
stored in this timer.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer().start().annotate(EllipticCurve)
sage: EllipticCurve.cputime # random
2.817255
sage: EllipticCurve.walltime # random
1332649288.410404
"""
object.cputime = self.cputime
object.walltime = self.walltime
def __repr__(self):
"""
String representation is from the dictionary.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: repr(Timer().start()) # indirect doctest
"{'cputime': ..., 'walltime': ...}"
"""
return str(self)
def __str__(self):
"""
String representation is from the dictionary.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: str(Timer().start()) # indirect doctest
"{'cputime': ..., 'walltime': ...}"
"""
return str(self.__dict__)
def __eq__(self, other):
"""
Comparison.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer() == Timer()
True
sage: t = Timer().start()
sage: loads(dumps(t)) == t
True
"""
if not isinstance(other, Timer):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Test for non-equality
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer() == Timer()
True
sage: t = Timer().start()
sage: loads(dumps(t)) != t
False
"""
return not (self == other)
# Inheritance rather then delegation as globals() must be a dict
class RecordingDict(dict):
"""
This dictionary is used for tracking the dependencies of an example.
This feature allows examples in different doctests to be grouped
for better timing data. It's obtained by recording whenever
anything is set or retrieved from this dictionary.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(test=17)
sage: D.got
set()
sage: D['test']
17
sage: D.got
{'test'}
sage: D.set
set()
sage: D['a'] = 1
sage: D['a']
1
sage: D.set
{'a'}
sage: D.got
{'test'}
TESTS::
sage: TestSuite(D).run()
"""
def __init__(self, *args, **kwds):
"""
Initialization arguments are the same as for a normal dictionary.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D.got
set()
"""
dict.__init__(self, *args, **kwds)
self.start()
def start(self):
"""
We track which variables have been set or retrieved.
This function initializes these lists to be empty.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D.set
set()
sage: D['a'] = 4
sage: D.set
{'a'}
sage: D.start(); D.set
set()
"""
self.set = set([])
self.got = set([])
def __getitem__(self, name):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4
sage: D.got
set()
sage: D['a'] # indirect doctest
4
sage: D.got
set()
sage: D['d']
42
sage: D.got
{'d'}
"""
if name not in self.set:
self.got.add(name)
return dict.__getitem__(self, name)
def __setitem__(self, name, value):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4 # indirect doctest
sage: D.set
{'a'}
"""
self.set.add(name)
dict.__setitem__(self, name, value)
def __delitem__(self, name):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: del D['d'] # indirect doctest
sage: D.set
{'d'}
"""
self.set.add(name)
dict.__delitem__(self, name)
def get(self, name, default=None):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D.get('d')
42
sage: D.got
{'d'}
sage: D.get('not_here')
sage: sorted(list(D.got))
['d', 'not_here']
"""
if name not in self.set:
self.got.add(name)
return dict.get(self, name, default)
def copy(self):
"""
Note that set and got are not copied.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4
sage: D.set
{'a'}
sage: E = D.copy()
sage: E.set
set()
sage: sorted(E.keys())
['a', 'd']
"""
return RecordingDict(dict.copy(self))
def __reduce__(self):
"""
Pickling.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4
sage: D.get('not_here')
sage: E = loads(dumps(D))
sage: E.got
{'not_here'}
"""
return make_recording_dict, (dict(self), self.set, self.got)
def make_recording_dict(D, st, gt):
"""
Auxiliary function for pickling.
EXAMPLES::
sage: from sage.doctest.util import make_recording_dict
sage: D = make_recording_dict({'a':4,'d':42},set([]),set(['not_here']))
sage: sorted(D.items())
[('a', 4), ('d', 42)]
sage: D.got
{'not_here'}
"""
ans = RecordingDict(D)
ans.set = st
ans.got = gt
return ans
class NestedName:
"""
Class used to construct fully qualified names based on indentation level.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[0] = 'Algebras'; qname
sage.categories.algebras.Algebras
sage: qname[4] = '__contains__'; qname
sage.categories.algebras.Algebras.__contains__
sage: qname[4] = 'ParentMethods'
sage: qname[8] = 'from_base_ring'; qname
sage.categories.algebras.Algebras.ParentMethods.from_base_ring
TESTS::
sage: TestSuite(qname).run()
"""
def __init__(self, base):
"""
INPUT:
- base -- a string: the name of the module.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname
sage.categories.algebras
"""
self.all = [base]
def __setitem__(self, index, value):
"""
Sets the value at a given indentation level.
INPUT:
- index -- a positive integer, the indentation level (often a multiple of 4, but not necessarily)
- value -- a string, the name of the class or function at that indentation level.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[1] = 'Algebras' # indirect doctest
sage: qname
sage.categories.algebras.Algebras
sage: qname.all
['sage.categories.algebras', None, 'Algebras']
"""
if index < 0:
raise ValueError
while len(self.all) <= index:
self.all.append(None)
self.all[index+1:] = [value]
def __str__(self):
"""
Return a .-separated string giving the full name.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[1] = 'Algebras'
sage: qname[44] = 'at_the_end_of_the_universe'
sage: str(qname) # indirect doctest
'sage.categories.algebras.Algebras.at_the_end_of_the_universe'
"""
return repr(self)
def __repr__(self):
"""
Return a .-separated string giving the full name.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[1] = 'Algebras'
sage: qname[44] = 'at_the_end_of_the_universe'
sage: print(qname) # indirect doctest
sage.categories.algebras.Algebras.at_the_end_of_the_universe
"""
return '.'.join(a for a in self.all if a is not None)
def __eq__(self, other):
"""
Comparison is just comparison of the underlying lists.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname2 = NestedName('sage.categories.algebras')
sage: qname == qname2
True
sage: qname[0] = 'Algebras'
sage: qname2[2] = 'Algebras'
sage: repr(qname) == repr(qname2)
True
sage: qname == qname2
False
"""
if not isinstance(other, NestedName):
return False
return self.all == other.all
def __ne__(self, other):
"""
Test for non-equality.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname2 = NestedName('sage.categories.algebras')
sage: qname != qname2
False
sage: qname[0] = 'Algebras'
sage: qname2[2] = 'Algebras'
sage: repr(qname) == repr(qname2)
True
sage: qname != qname2
True
"""
return not (self == other) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/doctest/util.py | 0.816809 | 0.296833 | util.py | pypi |
import os
import sys
import re
import random
import doctest
from Cython.Utils import is_package_dir
from sage.cpython.string import bytes_to_str
from sage.repl.load import load
from sage.misc.lazy_attribute import lazy_attribute
from .parsing import SageDocTestParser
from .util import NestedName
from sage.structure.dynamic_class import dynamic_class
from sage.env import SAGE_SRC, SAGE_LIB
# Python file parsing
triple_quotes = re.compile(r"\s*[rRuU]*((''')|(\"\"\"))")
name_regex = re.compile(r".*\s(\w+)([(].*)?:")
# LaTeX file parsing
begin_verb = re.compile(r"\s*\\begin{verbatim}")
end_verb = re.compile(r"\s*\\end{verbatim}\s*(%link)?")
begin_lstli = re.compile(r"\s*\\begin{lstlisting}")
end_lstli = re.compile(r"\s*\\end{lstlisting}\s*(%link)?")
skip = re.compile(r".*%skip.*")
# ReST file parsing
link_all = re.compile(r"^\s*\.\.\s+linkall\s*$")
double_colon = re.compile(r"^(\s*).*::\s*$")
code_block = re.compile(r"^(\s*)[.][.]\s*code-block\s*::.*$")
whitespace = re.compile(r"\s*")
bitness_marker = re.compile('#.*(32|64)-bit')
bitness_value = '64' if sys.maxsize > (1 << 32) else '32'
# For neutralizing doctests
find_prompt = re.compile(r"^(\s*)(>>>|sage:)(.*)")
# For testing that enough doctests are created
sagestart = re.compile(r"^\s*(>>> |sage: )\s*[^#\s]")
untested = re.compile("(not implemented|not tested)")
# For parsing a PEP 0263 encoding declaration
pep_0263 = re.compile(br'^[ \t\v]*#.*?coding[:=]\s*([-\w.]+)')
# Source line number in warning output
doctest_line_number = re.compile(r"^\s*doctest:[0-9]")
def get_basename(path):
"""
This function returns the basename of the given path, e.g. sage.doctest.sources or doc.ru.tutorial.tour_advanced
EXAMPLES::
sage: from sage.doctest.sources import get_basename
sage: from sage.env import SAGE_SRC
sage: import os
sage: get_basename(os.path.join(SAGE_SRC,'sage','doctest','sources.py'))
'sage.doctest.sources'
"""
if path is None:
return None
if not os.path.exists(path):
return path
path = os.path.abspath(path)
root = os.path.dirname(path)
# If the file is in the sage library, we can use our knowledge of
# the directory structure
dev = SAGE_SRC
sp = SAGE_LIB
if path.startswith(dev):
# there will be a branch name
i = path.find(os.path.sep, len(dev))
if i == -1:
# this source is the whole library....
return path
root = path[:i]
elif path.startswith(sp):
root = path[:len(sp)]
else:
# If this file is in some python package we can see how deep
# it goes by the presence of __init__.py files.
while os.path.exists(os.path.join(root, '__init__.py')):
root = os.path.dirname(root)
fully_qualified_path = os.path.splitext(path[len(root) + 1:])[0]
if os.path.split(path)[1] == '__init__.py':
fully_qualified_path = fully_qualified_path[:-9]
return fully_qualified_path.replace(os.path.sep, '.')
class DocTestSource(object):
"""
This class provides a common base class for different sources of doctests.
INPUT:
- ``options`` -- a :class:`sage.doctest.control.DocTestDefaults`
instance or equivalent.
"""
def __init__(self, options):
"""
Initialization.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: TestSuite(FDS).run()
"""
self.options = options
def __eq__(self, other):
"""
Comparison is just by comparison of attributes.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: DD = DocTestDefaults()
sage: FDS = FileDocTestSource(filename,DD)
sage: FDS2 = FileDocTestSource(filename,DD)
sage: FDS == FDS2
True
"""
if type(self) != type(other):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Test for non-equality.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: DD = DocTestDefaults()
sage: FDS = FileDocTestSource(filename,DD)
sage: FDS2 = FileDocTestSource(filename,DD)
sage: FDS != FDS2
False
"""
return not (self == other)
def _process_doc(self, doctests, doc, namespace, start):
"""
Appends doctests defined in ``doc`` to the list ``doctests``.
This function is called when a docstring block is completed
(either by ending a triple quoted string in a Python file,
unindenting from a comment block in a ReST file, or ending a
verbatim or lstlisting environment in a LaTeX file).
INPUT:
- ``doctests`` -- a running list of doctests to which the new
test(s) will be appended.
- ``doc`` -- a list of lines of a docstring, each including
the trailing newline.
- ``namespace`` -- a dictionary or
:class:`sage.doctest.util.RecordingDict`, used in the
creation of new :class:`doctest.DocTest`s.
- ``start`` -- an integer, giving the line number of the start
of this docstring in the larger file.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.parsing import SageDocTestParser
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','util.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: doctests, _ = FDS.create_doctests({})
sage: manual_doctests = []
sage: for dt in doctests:
....: FDS.qualified_name = dt.name
....: FDS._process_doc(manual_doctests, dt.docstring, {}, dt.lineno-1)
sage: doctests == manual_doctests
True
"""
docstring = "".join(doc)
new_doctests = self.parse_docstring(docstring, namespace, start)
sig_on_count_doc_doctest = "sig_on_count() # check sig_on/off pairings (virtual doctest)\n"
for dt in new_doctests:
if len(dt.examples) > 0 and not (hasattr(dt.examples[-1],'sage_source')
and dt.examples[-1].sage_source == sig_on_count_doc_doctest):
# Line number refers to the end of the docstring
sigon = doctest.Example(sig_on_count_doc_doctest, "0\n", lineno=docstring.count("\n"))
sigon.sage_source = sig_on_count_doc_doctest
dt.examples.append(sigon)
doctests.append(dt)
def _create_doctests(self, namespace, tab_okay=None):
"""
Creates a list of doctests defined in this source.
This function collects functionality common to file and string
sources, and is called by
:meth:`FileDocTestSource.create_doctests`.
INPUT:
- ``namespace`` -- a dictionary or
:class:`sage.doctest.util.RecordingDict`, used in the
creation of new :class:`doctest.DocTest`s.
- ``tab_okay`` -- whether tabs are allowed in this source.
OUTPUT:
- ``doctests`` -- a list of doctests defined by this source
- ``extras`` -- a dictionary with ``extras['tab']`` either
False or a list of linenumbers on which tabs appear.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.qualified_name = NestedName('sage.doctest.sources')
sage: doctests, extras = FDS._create_doctests({})
sage: len(doctests)
41
sage: extras['tab']
False
sage: extras['line_number']
False
"""
if tab_okay is None:
tab_okay = isinstance(self,TexSource)
self._init()
self.line_shift = 0
self.parser = SageDocTestParser(self.options.optional,
self.options.long)
self.linking = False
doctests = []
in_docstring = False
unparsed_doc = False
doc = []
start = None
tab_locations = []
contains_line_number = False
for lineno, line in self:
if doctest_line_number.search(line) is not None:
contains_line_number = True
if "\t" in line:
tab_locations.append(str(lineno+1))
if "SAGE_DOCTEST_ALLOW_TABS" in line:
tab_okay = True
just_finished = False
if in_docstring:
if self.ending_docstring(line):
in_docstring = False
just_finished = True
self._process_doc(doctests, doc, namespace, start)
unparsed_doc = False
else:
bitness = bitness_marker.search(line)
if bitness:
if bitness.groups()[0] != bitness_value:
self.line_shift += 1
continue
else:
line = line[:bitness.start()] + "\n"
if self.line_shift and sagestart.match(line):
# We insert blank lines to make up for the removed lines
doc.extend(["\n"]*self.line_shift)
self.line_shift = 0
doc.append(line)
unparsed_doc = True
if not in_docstring and (not just_finished or self.start_finish_can_overlap):
# to get line numbers in linked docstrings correct we
# append a blank line to the doc list.
doc.append("\n")
if not line.strip():
continue
if self.starting_docstring(line):
in_docstring = True
if self.linking:
# If there's already a doctest, we overwrite it.
if len(doctests) > 0:
doctests.pop()
if start is None:
start = lineno
doc = []
else:
self.line_shift = 0
start = lineno
doc = []
# In ReST files we can end the file without decreasing the indentation level.
if unparsed_doc:
self._process_doc(doctests, doc, namespace, start)
extras = dict(tab=not tab_okay and tab_locations,
line_number=contains_line_number,
optionals=self.parser.optionals)
if self.options.randorder is not None and self.options.randorder is not False:
# we want to randomize even when self.randorder = 0
random.seed(self.options.randorder)
randomized = []
while doctests:
i = random.randint(0, len(doctests) - 1)
randomized.append(doctests.pop(i))
return randomized, extras
else:
return doctests, extras
class StringDocTestSource(DocTestSource):
r"""
This class creates doctests from a string.
INPUT:
- ``basename`` -- string such as 'sage.doctests.sources', going
into the names of created doctests and examples.
- ``source`` -- a string, giving the source code to be parsed for
doctests.
- ``options`` -- a :class:`sage.doctest.control.DocTestDefaults`
or equivalent.
- ``printpath`` -- a string, to be used in place of a filename
when doctest failures are displayed.
- ``lineno_shift`` -- an integer (default: 0) by which to shift
the line numbers of all doctests defined in this string.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, extras = PSS.create_doctests({})
sage: len(dt)
1
sage: extras['tab']
[]
sage: extras['line_number']
False
sage: s = "'''\n\tsage: 2 + 2\n\t4\n'''"
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, extras = PSS.create_doctests({})
sage: extras['tab']
['2', '3']
sage: s = "'''\n sage: import warnings; warnings.warn('foo')\n doctest:1: UserWarning: foo \n'''"
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, extras = PSS.create_doctests({})
sage: extras['line_number']
True
"""
def __init__(self, basename, source, options, printpath, lineno_shift=0):
r"""
Initialization
TESTS::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: TestSuite(PSS).run()
"""
self.qualified_name = NestedName(basename)
self.printpath = printpath
self.source = source
self.lineno_shift = lineno_shift
DocTestSource.__init__(self, options)
def __iter__(self):
"""
Iterating over this source yields pairs ``(lineno, line)``.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: for n, line in PSS:
....: print("{} {}".format(n, line))
0 '''
1 sage: 2 + 2
2 4
3 '''
"""
for lineno, line in enumerate(self.source.split('\n')):
yield lineno + self.lineno_shift, line + '\n'
def create_doctests(self, namespace):
r"""
Creates doctests from this string.
INPUT:
- ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`.
OUTPUT:
- ``doctests`` -- a list of doctests defined by this string
- ``tab_locations`` -- either False or a list of linenumbers
on which tabs appear.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, tabs = PSS.create_doctests({})
sage: for t in dt:
....: print("{} {}".format(t.name, t.examples[0].sage_source))
<runtime> 2 + 2
"""
return self._create_doctests(namespace)
class FileDocTestSource(DocTestSource):
"""
This class creates doctests from a file.
INPUT:
- ``path`` -- string, the filename
- ``options`` -- a :class:`sage.doctest.control.DocTestDefaults`
instance or equivalent.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.basename
'sage.doctest.sources'
TESTS::
sage: TestSuite(FDS).run()
"""
def __init__(self, path, options):
"""
Initialization.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0))
sage: FDS.options.randorder
0
"""
self.path = path
DocTestSource.__init__(self, options)
base, ext = os.path.splitext(path)
if ext in ('.py', '.pyx', '.pxd', '.pxi', '.sage', '.spyx'):
self.__class__ = dynamic_class('PythonFileSource',(FileDocTestSource,PythonSource))
self.encoding = "utf-8"
elif ext == '.tex':
self.__class__ = dynamic_class('TexFileSource',(FileDocTestSource,TexSource))
self.encoding = "utf-8"
elif ext == '.rst':
self.__class__ = dynamic_class('RestFileSource',(FileDocTestSource,RestSource))
self.encoding = "utf-8"
else:
raise ValueError("unknown file extension %r"%ext)
def __iter__(self):
r"""
Iterating over this source yields pairs ``(lineno, line)``.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = tmp_filename(ext=".py")
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: with open(filename, 'w') as f:
....: _ = f.write(s)
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: for n, line in FDS:
....: print("{} {}".format(n, line))
0 '''
1 sage: 2 + 2
2 4
3 '''
The encoding is "utf-8" by default::
sage: FDS.encoding
'utf-8'
We create a file with a Latin-1 encoding without declaring it::
sage: s = b"'''\nRegardons le polyn\xF4me...\n'''\n"
sage: with open(filename, 'wb') as f:
....: _ = f.write(s)
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: L = list(FDS)
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf...8' codec can...t decode byte 0xf4 in position 18: invalid continuation byte
This works if we add a PEP 0263 encoding declaration::
sage: s = b"#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n" + s
sage: with open(filename, 'wb') as f:
....: _ = f.write(s)
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: L = list(FDS)
sage: FDS.encoding
'latin-1'
"""
with open(self.path, 'rb') as source:
for lineno, line in enumerate(source):
if lineno < 2:
match = pep_0263.search(line)
if match:
self.encoding = bytes_to_str(match.group(1), 'ascii')
yield lineno, line.decode(self.encoding)
@lazy_attribute
def printpath(self):
"""
Whether the path is printed absolutely or relatively depends on an option.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: root = os.path.realpath(os.path.join(SAGE_SRC,'sage'))
sage: filename = os.path.join(root,'doctest','sources.py')
sage: cwd = os.getcwd()
sage: os.chdir(root)
sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0,abspath=False))
sage: FDS.printpath
'doctest/sources.py'
sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0,abspath=True))
sage: FDS.printpath
'.../sage/doctest/sources.py'
sage: os.chdir(cwd)
"""
if self.options.abspath:
return os.path.abspath(self.path)
else:
relpath = os.path.relpath(self.path)
if relpath.startswith(".." + os.path.sep):
return self.path
else:
return relpath
@lazy_attribute
def basename(self):
"""
The basename of this file source, e.g. sage.doctest.sources
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','rings','integer.pyx')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.basename
'sage.rings.integer'
"""
return get_basename(self.path)
@lazy_attribute
def in_lib(self):
"""
Whether this file is part of a package (i.e. is in a directory
containing an ``__init__.py`` file).
Such files aren't loaded before running tests.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC, 'sage', 'rings', 'integer.pyx')
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: FDS.in_lib
True
sage: filename = os.path.join(SAGE_SRC, 'sage', 'doctest', 'tests', 'abort.rst')
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: FDS.in_lib
False
You can override the default::
sage: FDS = FileDocTestSource("hello_world.py",DocTestDefaults())
sage: FDS.in_lib
False
sage: FDS = FileDocTestSource("hello_world.py",DocTestDefaults(force_lib=True))
sage: FDS.in_lib
True
"""
# We need an explicit bool() because is_package_dir() returns
# 1/None instead of True/False.
return bool(self.options.force_lib or
is_package_dir(os.path.dirname(self.path)))
def create_doctests(self, namespace):
r"""
Return a list of doctests for this file.
INPUT:
- ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`.
OUTPUT:
- ``doctests`` -- a list of doctests defined in this file.
- ``extras`` -- a dictionary
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: doctests, extras = FDS.create_doctests(globals())
sage: len(doctests)
41
sage: extras['tab']
False
We give a self referential example::
sage: doctests[18].name
'sage.doctest.sources.FileDocTestSource.create_doctests'
sage: doctests[18].examples[10].source
u'doctests[Integer(18)].examples[Integer(10)].source\n'
TESTS:
We check that we correctly process results that depend on 32
vs 64 bit architecture::
sage: import sys
sage: bitness = '64' if sys.maxsize > (1 << 32) else '32'
sage: gp.get_precision() == 38
False # 32-bit
True # 64-bit
sage: ex = doctests[18].examples[13]
sage: (bitness == '64' and ex.want == 'True \n') or (bitness == '32' and ex.want == 'False \n')
True
We check that lines starting with a # aren't doctested::
#sage: raise RuntimeError
"""
if not os.path.exists(self.path):
import errno
raise IOError(errno.ENOENT, "File does not exist", self.path)
base, filename = os.path.split(self.path)
_, ext = os.path.splitext(filename)
if not self.in_lib and ext in ('.py', '.pyx', '.sage', '.spyx'):
cwd = os.getcwd()
if base:
os.chdir(base)
try:
load(filename, namespace) # errors raised here will be caught in DocTestTask
finally:
os.chdir(cwd)
self.qualified_name = NestedName(self.basename)
return self._create_doctests(namespace)
def _test_enough_doctests(self, check_extras=True, verbose=True):
"""
This function checks to see that the doctests are not getting
unexpectedly skipped. It uses a different (and simpler) code
path than the doctest creation functions, so there are a few
files in Sage that it counts incorrectly.
INPUT:
- ``check_extras`` -- bool (default True), whether to check if
doctests are created that don't correspond to either a
``sage: `` or a ``>>> `` prompt.
- ``verbose`` -- bool (default True), whether to print
offending line numbers when there are missing or extra
tests.
TESTS::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: cwd = os.getcwd()
sage: os.chdir(SAGE_SRC)
sage: import itertools
sage: for path, dirs, files in itertools.chain(os.walk('sage'), os.walk('doc')): # long time
....: path = os.path.relpath(path)
....: dirs.sort(); files.sort()
....: for F in files:
....: _, ext = os.path.splitext(F)
....: if ext in ('.py', '.pyx', '.pxd', '.pxi', '.sage', '.spyx', '.rst'):
....: filename = os.path.join(path, F)
....: FDS = FileDocTestSource(filename, DocTestDefaults(long=True, optional=True, force_lib=True))
....: FDS._test_enough_doctests(verbose=False)
There are 3 unexpected tests being run in sage/doctest/parsing.py
There are 1 unexpected tests being run in sage/doctest/reporting.py
sage: os.chdir(cwd)
"""
expected = []
rest = isinstance(self, RestSource)
if rest:
skipping = False
in_block = False
last_line = ''
for lineno, line in self:
if not line.strip():
continue
if rest:
if line.strip().startswith(".. nodoctest"):
return
# We need to track blocks in order to figure out whether we're skipping.
if in_block:
indent = whitespace.match(line).end()
if indent <= starting_indent:
in_block = False
skipping = False
if not in_block:
m1 = double_colon.match(line)
m2 = code_block.match(line.lower())
starting = (m1 and not line.strip().startswith(".. ")) or m2
if starting:
if ".. skip" in last_line:
skipping = True
in_block = True
starting_indent = whitespace.match(line).end()
last_line = line
if (not rest or in_block) and sagestart.match(line) and not ((rest and skipping) or untested.search(line.lower())):
expected.append(lineno+1)
actual = []
tests, _ = self.create_doctests({})
for dt in tests:
if dt.examples:
for ex in dt.examples[:-1]: # the last entry is a sig_on_count()
actual.append(dt.lineno + ex.lineno + 1)
shortfall = sorted(set(expected).difference(set(actual)))
extras = sorted(set(actual).difference(set(expected)))
if len(actual) == len(expected):
if not shortfall:
return
dif = extras[0] - shortfall[0]
for e, s in zip(extras[1:],shortfall[1:]):
if dif != e - s:
break
else:
print("There are %s tests in %s that are shifted by %s" % (len(shortfall), self.path, dif))
if verbose:
print(" The correct line numbers are %s" % (", ".join(str(n) for n in shortfall)))
return
elif len(actual) < len(expected):
print("There are %s tests in %s that are not being run" % (len(expected) - len(actual), self.path))
elif check_extras:
print("There are %s unexpected tests being run in %s" % (len(actual) - len(expected), self.path))
if verbose:
if shortfall:
print(" Tests on lines %s are not run" % (", ".join(str(n) for n in shortfall)))
if check_extras and extras:
print(" Tests on lines %s seem extraneous" % (", ".join(str(n) for n in extras)))
class SourceLanguage:
"""
An abstract class for functions that depend on the programming language of a doctest source.
Currently supported languages include Python, ReST and LaTeX.
"""
def parse_docstring(self, docstring, namespace, start):
"""
Return a list of doctest defined in this docstring.
This function is called by :meth:`DocTestSource._process_doc`.
The default implementation, defined here, is to use the
:class:`sage.doctest.parsing.SageDocTestParser` attached to
this source to get doctests from the docstring.
INPUT:
- ``docstring`` -- a string containing documentation and tests.
- ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`.
- ``start`` -- an integer, one less than the starting line number
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.parsing import SageDocTestParser
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','util.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: doctests, _ = FDS.create_doctests({})
sage: for dt in doctests:
....: FDS.qualified_name = dt.name
....: dt.examples = dt.examples[:-1] # strip off the sig_on() test
....: assert(FDS.parse_docstring(dt.docstring,{},dt.lineno-1)[0] == dt)
"""
return [self.parser.get_doctest(docstring, namespace, str(self.qualified_name),
self.printpath, start + 1)]
class PythonSource(SourceLanguage):
"""
This class defines the functions needed for the extraction of doctests from python sources.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: type(FDS)
<class 'sage.doctest.sources.PythonFileSource'>
"""
# The same line can't both start and end a docstring
start_finish_can_overlap = False
def _init(self):
"""
This function is called before creating doctests from a Python source.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.last_indent
-1
"""
self.last_indent = -1
self.last_line = None
self.quotetype = None
self.paren_count = 0
self.bracket_count = 0
self.curly_count = 0
self.code_wrapping = False
def _update_quotetype(self, line):
r"""
Updates the track of what kind of quoted string we're in.
We need to track whether we're inside a triple quoted
string, since a triple quoted string that starts a line
could be the end of a string and thus not the beginning of a
doctest (see sage.misc.sageinspect for an example).
To do this tracking we need to track whether we're inside a
string at all, since ''' inside a string doesn't start a
triple quote (see the top of this file for an example).
We also need to track parentheses and brackets, since we only
want to update our record of last line and indentation level
when the line is actually over.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS._update_quotetype('\"\"\"'); print(" ".join(list(FDS.quotetype)))
" " "
sage: FDS._update_quotetype("'''"); print(" ".join(list(FDS.quotetype)))
" " "
sage: FDS._update_quotetype('\"\"\"'); print(FDS.quotetype)
None
sage: FDS._update_quotetype("triple_quotes = re.compile(\"\\s*[rRuU]*((''')|(\\\"\\\"\\\"))\")")
sage: print(FDS.quotetype)
None
sage: FDS._update_quotetype("''' Single line triple quoted string \\''''")
sage: print(FDS.quotetype)
None
sage: FDS._update_quotetype("' Lots of \\\\\\\\'")
sage: print(FDS.quotetype)
None
"""
def _update_parens(start,end=None):
self.paren_count += line.count("(",start,end) - line.count(")",start,end)
self.bracket_count += line.count("[",start,end) - line.count("]",start,end)
self.curly_count += line.count("{",start,end) - line.count("}",start,end)
pos = 0
while pos < len(line):
if self.quotetype is None:
next_single = line.find("'",pos)
next_double = line.find('"',pos)
if next_single == -1 and next_double == -1:
next_comment = line.find("#",pos)
if next_comment == -1:
_update_parens(pos)
else:
_update_parens(pos,next_comment)
break
elif next_single == -1:
m = next_double
elif next_double == -1:
m = next_single
else:
m = min(next_single, next_double)
next_comment = line.find('#',pos,m)
if next_comment != -1:
_update_parens(pos,next_comment)
break
_update_parens(pos,m)
if m+2 < len(line) and line[m] == line[m+1] == line[m+2]:
self.quotetype = line[m:m+3]
pos = m+3
else:
self.quotetype = line[m]
pos = m+1
else:
next = line.find(self.quotetype,pos)
if next == -1:
break
elif next == 0 or line[next-1] != '\\':
pos = next + len(self.quotetype)
self.quotetype = None
else:
# We need to worry about the possibility that
# there are an even number of backslashes before
# the quote, in which case it is not escaped
count = 1
slashpos = next - 2
while slashpos >= pos and line[slashpos] == '\\':
count += 1
slashpos -= 1
if count % 2 == 0:
pos = next + len(self.quotetype)
self.quotetype = None
else:
# The possible ending quote was escaped.
pos = next + 1
def starting_docstring(self, line):
"""
Determines whether the input line starts a docstring.
If the input line does start a docstring (a triple quote),
then this function updates ``self.qualified_name``.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- either None or a Match object.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.starting_docstring("r'''")
<...Match object...>
sage: FDS.ending_docstring("'''")
<...Match object...>
sage: FDS.qualified_name = NestedName(FDS.basename)
sage: FDS.starting_docstring("class MyClass(object):")
sage: FDS.starting_docstring(" def hello_world(self):")
sage: FDS.starting_docstring(" '''")
<...Match object...>
sage: FDS.qualified_name
sage.doctest.sources.MyClass.hello_world
sage: FDS.ending_docstring(" '''")
<...Match object...>
sage: FDS.starting_docstring("class NewClass(object):")
sage: FDS.starting_docstring(" '''")
<...Match object...>
sage: FDS.ending_docstring(" '''")
<...Match object...>
sage: FDS.qualified_name
sage.doctest.sources.NewClass
sage: FDS.starting_docstring("print(")
sage: FDS.starting_docstring(" '''Not a docstring")
sage: FDS.starting_docstring(" ''')")
sage: FDS.starting_docstring("def foo():")
sage: FDS.starting_docstring(" '''This is a docstring'''")
<...Match object...>
"""
indent = whitespace.match(line).end()
quotematch = None
if self.quotetype is None and not self.code_wrapping:
# We're not inside a triple quote and not inside code like
# print(
# """Not a docstring
# """)
if line[indent] != '#' and (indent == 0 or indent > self.last_indent):
quotematch = triple_quotes.match(line)
# It would be nice to only run the name_regex when
# quotematch wasn't None, but then we mishandle classes
# that don't have a docstring.
if not self.code_wrapping and self.last_indent >= 0 and indent > self.last_indent:
name = name_regex.match(self.last_line)
if name:
name = name.groups()[0]
self.qualified_name[indent] = name
elif quotematch:
self.qualified_name[indent] = '?'
self._update_quotetype(line)
if line[indent] != '#' and not self.code_wrapping:
self.last_line, self.last_indent = line, indent
self.code_wrapping = not (self.paren_count == self.bracket_count == self.curly_count == 0)
return quotematch
def ending_docstring(self, line):
r"""
Determines whether the input line ends a docstring.
INPUT:
- ``line`` -- a string, one line of an input file.
OUTPUT:
- an object that, when evaluated in a boolean context, gives
True or False depending on whether the input line marks the
end of a docstring.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.quotetype = "'''"
sage: FDS.ending_docstring("'''")
<...Match object...>
sage: FDS.ending_docstring('\"\"\"')
"""
quotematch = triple_quotes.match(line)
if quotematch is not None and quotematch.groups()[0] != self.quotetype:
quotematch = None
self._update_quotetype(line)
return quotematch
def _neutralize_doctests(self, reindent):
r"""
Return a string containing the source of ``self``, but with
doctests modified so they are not tested.
This function is used in creating doctests for ReST files,
since docstrings of Python functions defined inside verbatim
blocks screw up Python's doctest parsing.
INPUT:
- ``reindent`` -- an integer, the number of spaces to indent
the result.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: print(PSS._neutralize_doctests(0))
'''
safe: 2 + 2
4
'''
"""
neutralized = []
in_docstring = False
self._init()
for lineno, line in self:
if not line.strip():
neutralized.append(line)
elif in_docstring:
if self.ending_docstring(line):
in_docstring = False
neutralized.append(" "*reindent + find_prompt.sub(r"\1safe:\3",line))
else:
if self.starting_docstring(line):
in_docstring = True
neutralized.append(" "*reindent + line)
return "".join(neutralized)
class TexSource(SourceLanguage):
"""
This class defines the functions needed for the extraction of
doctests from a LaTeX source.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: type(FDS)
<class 'sage.doctest.sources.TexFileSource'>
"""
# The same line can't both start and end a docstring
start_finish_can_overlap = False
def _init(self):
"""
This function is called before creating doctests from a Tex file.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.skipping
False
"""
self.skipping = False
def starting_docstring(self, line):
r"""
Determines whether the input line starts a docstring.
Docstring blocks in tex files are defined by verbatim or
lstlisting environments, and can be linked together by adding
%link immediately after the \end{verbatim} or \end{lstlisting}.
Within a verbatim (or lstlisting) block, you can tell Sage not to
process the rest of the block by including a %skip line.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- a boolean giving whether the input line marks the
start of a docstring (verbatim block).
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
We start docstrings with \begin{verbatim} or \begin{lstlisting}::
sage: FDS.starting_docstring(r"\begin{verbatim}")
True
sage: FDS.starting_docstring(r"\begin{lstlisting}")
True
sage: FDS.skipping
False
sage: FDS.ending_docstring("sage: 2+2")
False
sage: FDS.ending_docstring("4")
False
To start ignoring the rest of the verbatim block, use %skip::
sage: FDS.ending_docstring("%skip")
True
sage: FDS.skipping
True
sage: FDS.starting_docstring("sage: raise RuntimeError")
False
You can even pretend to start another verbatim block while skipping::
sage: FDS.starting_docstring(r"\begin{verbatim}")
False
sage: FDS.skipping
True
To stop skipping end the verbatim block::
sage: FDS.starting_docstring(r"\end{verbatim} %link")
False
sage: FDS.skipping
False
Linking works even when the block was ended while skipping::
sage: FDS.linking
True
sage: FDS.starting_docstring(r"\begin{verbatim}")
True
"""
if self.skipping:
if self.ending_docstring(line, check_skip=False):
self.skipping = False
return False
return bool(begin_verb.match(line) or begin_lstli.match(line))
def ending_docstring(self, line, check_skip=True):
r"""
Determines whether the input line ends a docstring.
Docstring blocks in tex files are defined by verbatim or
lstlisting environments, and can be linked together by adding
%link immediately after the \end{verbatim} or \end{lstlisting}.
Within a verbatim (or lstlisting) block, you can tell Sage not to
process the rest of the block by including a %skip line.
INPUT:
- ``line`` -- a string, one line of an input file
- ``check_skip`` -- boolean (default True), used internally in starting_docstring.
OUTPUT:
- a boolean giving whether the input line marks the
end of a docstring (verbatim block).
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.ending_docstring(r"\end{verbatim}")
True
sage: FDS.ending_docstring(r"\end{lstlisting}")
True
sage: FDS.linking
False
Use %link to link with the next verbatim block::
sage: FDS.ending_docstring(r"\end{verbatim}%link")
True
sage: FDS.linking
True
%skip also ends a docstring block::
sage: FDS.ending_docstring("%skip")
True
"""
m = end_verb.match(line)
if m:
if m.groups()[0]:
self.linking = True
else:
self.linking = False
return True
m = end_lstli.match(line)
if m:
if m.groups()[0]:
self.linking = True
else:
self.linking = False
return True
if check_skip and skip.match(line):
self.skipping = True
return True
return False
class RestSource(SourceLanguage):
"""
This class defines the functions needed for the extraction of
doctests from ReST sources.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: type(FDS)
<class 'sage.doctest.sources.RestFileSource'>
"""
# The same line can both start and end a docstring
start_finish_can_overlap = True
def _init(self):
"""
This function is called before creating doctests from a ReST file.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.link_all
False
"""
self.link_all = False
self.last_line = ""
self.last_indent = -1
self.first_line = False
self.skipping = False
def starting_docstring(self, line):
"""
A line ending with a double colon starts a verbatim block in a ReST file,
as does a line containing ``.. CODE-BLOCK:: language``.
This function also determines whether the docstring block
should be joined with the previous one, or should be skipped.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- either None or a Match object.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.starting_docstring("Hello world::")
True
sage: FDS.ending_docstring(" sage: 2 + 2")
False
sage: FDS.ending_docstring(" 4")
False
sage: FDS.ending_docstring("We are now done")
True
sage: FDS.starting_docstring(".. link")
sage: FDS.starting_docstring("::")
True
sage: FDS.linking
True
"""
if link_all.match(line):
self.link_all = True
if self.skipping:
end_block = self.ending_docstring(line)
if end_block:
self.skipping = False
else:
return False
m1 = double_colon.match(line)
m2 = code_block.match(line.lower())
starting = (m1 and not line.strip().startswith(".. ")) or m2
if starting:
self.linking = self.link_all or '.. link' in self.last_line
self.first_line = True
m = m1 or m2
indent = len(m.groups()[0])
if '.. skip' in self.last_line:
self.skipping = True
starting = False
else:
indent = self.last_indent
self.last_line, self.last_indent = line, indent
return starting
def ending_docstring(self, line):
"""
When the indentation level drops below the initial level the
block ends.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- a boolean, whether the verbatim block is ending.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.starting_docstring("Hello world::")
True
sage: FDS.ending_docstring(" sage: 2 + 2")
False
sage: FDS.ending_docstring(" 4")
False
sage: FDS.ending_docstring("We are now done")
True
"""
if not line.strip():
return False
indent = whitespace.match(line).end()
if self.first_line:
self.first_line = False
if indent <= self.last_indent:
# We didn't indent at all
return True
self.last_indent = indent
return indent < self.last_indent
def parse_docstring(self, docstring, namespace, start):
r"""
Return a list of doctest defined in this docstring.
Code blocks in a REST file can contain python functions with
their own docstrings in addition to in-line doctests. We want
to include the tests from these inner docstrings, but Python's
doctesting module has a problem if we just pass on the whole
block, since it expects to get just a docstring, not the
Python code as well.
Our solution is to create a new doctest source from this code
block and append the doctests created from that source. We
then replace the occurrences of "sage:" and ">>>" occurring
inside a triple quote with "safe:" so that the doctest module
doesn't treat them as tests.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.parsing import SageDocTestParser
sage: from sage.doctest.util import NestedName
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.parser = SageDocTestParser(set(['sage']))
sage: FDS.qualified_name = NestedName('sage_doc')
sage: s = "Some text::\n\n def example_python_function(a, \
....: b):\n '''\n Brief description \
....: of function.\n\n EXAMPLES::\n\n \
....: sage: test1()\n sage: test2()\n \
....: '''\n return a + b\n\n sage: test3()\n\nMore \
....: ReST documentation."
sage: tests = FDS.parse_docstring(s, {}, 100)
sage: len(tests)
2
sage: for ex in tests[0].examples:
....: print(ex.sage_source)
test3()
sage: for ex in tests[1].examples:
....: print(ex.sage_source)
test1()
test2()
sig_on_count() # check sig_on/off pairings (virtual doctest)
"""
PythonStringSource = dynamic_class("sage.doctest.sources.PythonStringSource",
(StringDocTestSource, PythonSource))
min_indent = self.parser._min_indent(docstring)
pysource = '\n'.join([l[min_indent:] for l in docstring.split('\n')])
inner_source = PythonStringSource(self.basename, pysource,
self.options,
self.printpath, lineno_shift=start+1)
inner_doctests, _ = inner_source._create_doctests(namespace, True)
safe_docstring = inner_source._neutralize_doctests(min_indent)
outer_doctest = self.parser.get_doctest(safe_docstring, namespace,
str(self.qualified_name),
self.printpath, start + 1)
return [outer_doctest] + inner_doctests
class DictAsObject(dict):
"""
A simple subclass of dict that inserts the items from the initializing dictionary into attributes.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({'a':2})
sage: D.a
2
"""
def __init__(self, attrs):
"""
Initialization.
INPUT:
- ``attrs`` -- a dictionary.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({'a':2})
sage: D.a == D['a']
True
sage: D.a
2
"""
super(DictAsObject, self).__init__(attrs)
self.__dict__.update(attrs)
def __setitem__(self, ky, val):
"""
We preserve the ability to access entries through either the
dictionary or attribute interfaces.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({})
sage: D['a'] = 2
sage: D.a
2
"""
super(DictAsObject, self).__setitem__(ky, val)
try:
super(DictAsObject, self).__setattr__(ky, val)
except TypeError:
pass
def __setattr__(self, ky, val):
"""
We preserve the ability to access entries through either the
dictionary or attribute interfaces.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({})
sage: D.a = 2
sage: D['a']
2
"""
super(DictAsObject, self).__setitem__(ky, val)
super(DictAsObject, self).__setattr__(ky, val) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/doctest/sources.py | 0.433022 | 0.197193 | sources.py | pypi |
import io
import os
import zipfile
from sage.cpython.string import bytes_to_str
from sage.structure.sage_object import SageObject
from sage.misc.cachefunc import cached_method
INNER_HTML_TEMPLATE = """
<html>
<head>
<style>
* {{
margin: 0;
padding: 0;
overflow: hidden;
}}
body, html {{
height: 100%;
width: 100%;
}}
</style>
<script type="text/javascript" src="{path_to_jsmol}/JSmol.min.js"></script>
</head>
<body>
<script type="text/javascript">
delete Jmol._tracker; // Prevent JSmol from phoning home.
var script = {script};
var Info = {{
width: '{width}',
height: '{height}',
debug: false,
disableInitialConsole: true, // very slow when used with inline mesh
color: '#3131ff',
addSelectionOptions: false,
use: 'HTML5',
j2sPath: '{path_to_jsmol}/j2s',
script: script,
}};
var jmolApplet0 = Jmol.getApplet('jmolApplet0', Info);
</script>
</body>
</html>
"""
IFRAME_TEMPLATE = """
<iframe srcdoc="{escaped_inner_html}"
width="{width}"
height="{height}"
style="border: 0;">
</iframe>
"""
OUTER_HTML_TEMPLATE = """
<html>
<head>
<title>JSmol 3D Scene</title>
</head>
</body>
{iframe}
</body>
</html>
""".format(iframe=IFRAME_TEMPLATE)
class JSMolHtml(SageObject):
def __init__(self, jmol, path_to_jsmol=None, width='100%', height='100%'):
"""
INPUT:
- ``jmol`` -- 3-d graphics or
:class:`sage.repl.rich_output.output_graphics3d.OutputSceneJmol`
instance. The 3-d scene to show.
- ``path_to_jsmol`` -- string (optional, default is
``'/nbextensions/jupyter_jsmol/jsmol'``). The path (relative or absolute)
where ``JSmol.min.js`` is served on the web server.
- ``width`` -- integer or string (optional, default:
``'100%'``). The width of the JSmol applet using CSS
dimensions.
- ``height`` -- integer or string (optional, default:
``'100%'``). The height of the JSmol applet using CSS
dimensions.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: JSMolHtml(sphere(), width=500, height=300)
JSmol Window 500x300
"""
from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
if not isinstance(jmol, OutputSceneJmol):
jmol = jmol._rich_repr_jmol()
self._jmol = jmol
self._zip = zipfile.ZipFile(io.BytesIO(self._jmol.scene_zip.get()))
if path_to_jsmol is None:
self._path = os.path.join('/', 'nbextensions', 'jupyter_jsmol', 'jsmol')
else:
self._path = path_to_jsmol
self._width = width
self._height = height
@cached_method
def script(self):
r"""
Return the JMol script file.
This method extracts the Jmol script from the Jmol spt file (a
zip archive) and inlines meshes.
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jsmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: jsmol.script()
'data "model list"\n10\nempt...aliasdisplay on;\n'
"""
script = []
with self._zip.open('SCRIPT') as SCRIPT:
for line in SCRIPT:
if line.startswith(b'pmesh'):
command, obj, meshfile = line.split(b' ', 3)
assert command == b'pmesh'
if meshfile not in [b'dots\n', b'mesh\n']:
assert (meshfile.startswith(b'"') and
meshfile.endswith(b'"\n'))
meshfile = bytes_to_str(meshfile[1:-2]) # strip quotes
script += [
'pmesh {0} inline "'.format(bytes_to_str(obj)),
bytes_to_str(self._zip.open(meshfile).read()),
'"\n'
]
continue
script += [bytes_to_str(line)]
return ''.join(script)
def js_script(self):
r"""
The :meth:`script` as Javascript string.
Since the many shortcomings of Javascript include multi-line
strings, this actually returns Javascript code to reassemble
the script from a list of strings.
OUTPUT:
String. Javascript code that evaluates to :meth:`script` as
Javascript string.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jsmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: print(jsmol.js_script())
[
'data "model list"',
...
'isosurface fullylit; pmesh o* fullylit; set antialiasdisplay on;',
].join('\n');
"""
script = [r"["]
for line in self.script().splitlines():
script += [r" '{0}',".format(line)]
script += [r"].join('\n');"]
return '\n'.join(script)
def _repr_(self):
"""
Return as string representation
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: JSMolHtml(OutputSceneJmol.example(), width=500, height=300)._repr_()
'JSmol Window 500x300'
"""
return 'JSmol Window {0}x{1}'.format(self._width, self._height)
def inner_html(self):
"""
Return a HTML document containing a JSmol applet
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: print(jmol.inner_html())
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
...
</html>
"""
return INNER_HTML_TEMPLATE.format(
script=self.js_script(),
width=self._width,
height=self._height,
path_to_jsmol=self._path,
)
def iframe(self):
"""
Return HTML iframe
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jmol = JSMolHtml(OutputSceneJmol.example())
sage: print(jmol.iframe())
<iframe srcdoc="
...
</iframe>
"""
escaped_inner_html = self.inner_html().replace('"', '"')
iframe = IFRAME_TEMPLATE.format(
script=self.js_script(),
width=self._width,
height=self._height,
escaped_inner_html=escaped_inner_html,
)
return iframe
def outer_html(self):
"""
Return a HTML document containing an iframe with a JSmol applet
OUTPUT:
String
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: print(jmol.outer_html())
<html>
<head>
<title>JSmol 3D Scene</title>
</head>
</body>
<BLANKLINE>
<iframe srcdoc="
...
</html>
"""
escaped_inner_html = self.inner_html().replace('"', '"')
outer = OUTER_HTML_TEMPLATE.format(
script=self.js_script(),
width=self._width,
height=self._height,
escaped_inner_html=escaped_inner_html,
)
return outer | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/repl/display/jsmol_iframe.py | 0.664976 | 0.19853 | jsmol_iframe.py | pypi |
import os
import errno
from sage.env import (
SAGE_DOC, SAGE_VENV, SAGE_EXTCODE,
SAGE_VERSION,
THREEJS_DIR,
)
class SageKernelSpec(object):
def __init__(self, prefix=None):
"""
Utility to manage SageMath kernels and extensions
INPUT:
- ``prefix`` -- (optional, default: ``sys.prefix``)
directory for the installation prefix
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: prefix = tmp_dir()
sage: spec = SageKernelSpec(prefix=prefix)
sage: spec._display_name # random output
'SageMath 6.9'
sage: spec.kernel_dir == SageKernelSpec(prefix=prefix).kernel_dir
True
"""
self._display_name = 'SageMath {0}'.format(SAGE_VERSION)
if prefix is None:
from sys import prefix
jupyter_dir = os.path.join(prefix, "share", "jupyter")
self.nbextensions_dir = os.path.join(jupyter_dir, "nbextensions")
self.kernel_dir = os.path.join(jupyter_dir, "kernels", self.identifier())
self._mkdirs()
def _mkdirs(self):
"""
Create necessary parent directories
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._mkdirs()
sage: os.path.isdir(spec.nbextensions_dir)
True
"""
def mkdir_p(path):
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
mkdir_p(self.nbextensions_dir)
mkdir_p(self.kernel_dir)
@classmethod
def identifier(cls):
"""
Internal identifier for the SageMath kernel
OUTPUT: the string ``"sagemath"``.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: SageKernelSpec.identifier()
'sagemath'
"""
return 'sagemath'
def symlink(self, src, dst):
"""
Symlink ``src`` to ``dst``
This is not an atomic operation.
Already-existing symlinks will be deleted, already existing
non-empty directories will be kept.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: path = tmp_dir()
sage: spec.symlink(os.path.join(path, 'a'), os.path.join(path, 'b'))
sage: os.listdir(path)
['b']
"""
try:
os.remove(dst)
except OSError as err:
if err.errno == errno.EEXIST:
return
os.symlink(src, dst)
def use_local_threejs(self):
"""
Symlink threejs to the Jupyter notebook.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec.use_local_threejs()
sage: threejs = os.path.join(spec.nbextensions_dir, 'threejs-sage')
sage: os.path.isdir(threejs)
True
"""
src = THREEJS_DIR
dst = os.path.join(self.nbextensions_dir, 'threejs-sage')
self.symlink(src, dst)
def _kernel_cmd(self):
"""
Helper to construct the SageMath kernel command.
OUTPUT:
List of strings. The command to start a new SageMath kernel.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._kernel_cmd()
['/.../sage',
'--python',
'-m',
'sage.repl.ipython_kernel',
'-f',
'{connection_file}']
"""
return [
os.path.join(SAGE_VENV, 'bin', 'sage'),
'--python',
'-m', 'sage.repl.ipython_kernel',
'-f', '{connection_file}',
]
def kernel_spec(self):
"""
Return the kernel spec as Python dictionary
OUTPUT:
A dictionary. See the Jupyter documentation for details.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec.kernel_spec()
{'argv': ..., 'display_name': 'SageMath ...', 'language': 'sage'}
"""
return dict(
argv=self._kernel_cmd(),
display_name=self._display_name,
language='sage',
)
def _install_spec(self):
"""
Install the SageMath Jupyter kernel
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._install_spec()
"""
jsonfile = os.path.join(self.kernel_dir, "kernel.json")
import json
with open(jsonfile, 'w') as f:
json.dump(self.kernel_spec(), f)
def _symlink_resources(self):
"""
Symlink miscellaneous resources
This method symlinks additional resources (like the SageMath
documentation) into the SageMath kernel directory. This is
necessary to make the help links in the notebook work.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._install_spec()
sage: spec._symlink_resources()
"""
path = os.path.join(SAGE_EXTCODE, 'notebook-ipython')
for filename in os.listdir(path):
self.symlink(
os.path.join(path, filename),
os.path.join(self.kernel_dir, filename)
)
self.symlink(
os.path.join(SAGE_DOC, 'html', 'en'),
os.path.join(self.kernel_dir, 'doc')
)
@classmethod
def update(cls, *args, **kwds):
"""
Configure the Jupyter notebook for the SageMath kernel
This method does everything necessary to use the SageMath kernel,
you should never need to call any of the other methods
directly.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: SageKernelSpec.update(prefix=tmp_dir())
"""
instance = cls(*args, **kwds)
instance.use_local_threejs()
instance._install_spec()
instance._symlink_resources()
def have_prerequisites(debug=True):
"""
Check that we have all prerequisites to run the Jupyter notebook.
In particular, the Jupyter notebook requires OpenSSL whether or
not you are using https. See :trac:`17318`.
INPUT:
``debug`` -- boolean (default: ``True``). Whether to print debug
information in case that prerequisites are missing.
OUTPUT:
Boolean.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import have_prerequisites
sage: have_prerequisites(debug=False) in [True, False]
True
"""
try:
from notebook.notebookapp import NotebookApp
return True
except ImportError:
if debug:
import traceback
traceback.print_exc()
return False | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/repl/ipython_kernel/install.py | 0.445047 | 0.173673 | install.py | pypi |
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.richcmp import richcmp_method, rich_to_bool
class UnknownError(TypeError):
"""
Raised whenever :class:`Unknown` is used in a boolean operation.
EXAMPLES::
sage: not Unknown
Traceback (most recent call last):
...
UnknownError: Unknown does not evaluate in boolean context
"""
pass
@richcmp_method
class UnknownClass(UniqueRepresentation):
"""
The Unknown truth value
The ``Unknown`` object is used in Sage in several places as return value
in addition to ``True`` and ``False``, in order to signal uncertainty
about or inability to compute the result. ``Unknown`` can be identified
using ``is``, or by catching :class:`UnknownError` from a boolean
operation.
.. WARNING::
Calling ``bool()`` with ``Unknown`` as argument will throw an
``UnknownError``. This also means that applying ``and``, ``not``,
and ``or`` to ``Unknown`` might fail.
TESTS::
sage: TestSuite(Unknown).run()
"""
def __repr__(self):
"""
TESTS::
sage: Unknown
Unknown
"""
return "Unknown"
def __bool__(self):
"""
When evaluated in a boolean context ``Unknown`` raises a ``UnknownError``.
EXAMPLES::
sage: bool(Unknown)
Traceback (most recent call last):
...
UnknownError: Unknown does not evaluate in boolean context
sage: not Unknown
Traceback (most recent call last):
...
UnknownError: Unknown does not evaluate in boolean context
"""
raise UnknownError('Unknown does not evaluate in boolean context')
__nonzero__ = __bool__
def __and__(self, other):
"""
The ``&`` logical operation.
EXAMPLES::
sage: Unknown & False
False
sage: Unknown & Unknown
Unknown
sage: Unknown & True
Unknown
sage: Unknown.__or__(3)
NotImplemented
"""
if other is False:
return False
elif other is True or other is Unknown:
return self
else:
return NotImplemented
def __or__(self, other):
"""
The ``|`` logical connector.
EXAMPLES::
sage: Unknown | False
Unknown
sage: Unknown | Unknown
Unknown
sage: Unknown | True
True
sage: Unknown.__or__(3)
NotImplemented
"""
if other is True:
return True
elif other is False or other is Unknown:
return self
else:
return NotImplemented
def __richcmp__(self, other, op):
"""
Comparison of truth value.
EXAMPLES::
sage: l = [False, Unknown, True]
sage: for a in l: print([a < b for b in l])
[False, True, True]
[False, False, True]
[False, False, False]
sage: for a in l: print([a <= b for b in l])
[True, True, True]
[False, True, True]
[False, False, True]
"""
if other is self:
return rich_to_bool(op, 0)
if not isinstance(other, bool):
return NotImplemented
if other:
return rich_to_bool(op, -1)
else:
return rich_to_bool(op, +1)
Unknown = UnknownClass() | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/unknown.py | 0.891941 | 0.522324 | unknown.py | pypi |
from functools import (partial, update_wrapper, WRAPPER_ASSIGNMENTS,
WRAPPER_UPDATES)
from copy import copy
from sage.misc.sageinspect import (sage_getsource, sage_getsourcelines,
sage_getargspec)
from inspect import ArgSpec
def sage_wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES):
r"""
Decorator factory which should be used in decorators for making sure that
meta-information on the decorated callables are retained through the
decorator, such that the introspection functions of
``sage.misc.sageinspect`` retrieves them correctly. This includes
documentation string, source, and argument specification. This is an
extension of the Python standard library decorator functools.wraps.
That the argument specification is retained from the decorated functions
implies, that if one uses ``sage_wraps`` in a decorator which intentionally
changes the argument specification, one should add this information to
the special attribute ``_sage_argspec_`` of the wrapping function (for an
example, see e.g. ``@options`` decorator in this module).
EXAMPLES:
Demonstrate that documentation string and source are retained from the
decorated function::
sage: def square(f):
....: @sage_wraps(f)
....: def new_f(x):
....: return f(x)*f(x)
....: return new_f
sage: @square
....: def g(x):
....: "My little function"
....: return x
sage: g(2)
4
sage: g(x)
x^2
sage: g.__doc__
'My little function'
sage: from sage.misc.sageinspect import sage_getsource, sage_getsourcelines, sage_getfile
sage: sage_getsource(g)
'@square...def g(x)...'
Demonstrate that the argument description are retained from the
decorated function through the special method (when left
unchanged) (see :trac:`9976`)::
sage: def diff_arg_dec(f):
....: @sage_wraps(f)
....: def new_f(y, some_def_arg=2):
....: return f(y+some_def_arg)
....: return new_f
sage: @diff_arg_dec
....: def g(x):
....: return x
sage: g(1)
3
sage: g(1, some_def_arg=4)
5
sage: from sage.misc.sageinspect import sage_getargspec
sage: sage_getargspec(g)
ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)
Demonstrate that it correctly gets the source lines and the source
file, which is essential for interactive code edition; note that we
do not test the line numbers, as they may easily change::
sage: P.<x,y> = QQ[]
sage: I = P*[x,y]
sage: sage_getfile(I.interreduced_basis) # known bug
'.../sage/rings/polynomial/multi_polynomial_ideal.py'
sage: sage_getsourcelines(I.interreduced_basis)
([' @handle_AA_and_QQbar\n',
' @singular_gb_standard_options\n',
' @libsingular_gb_standard_options\n',
' def interreduced_basis(self):\n',
...
' return self.basis.reduced()\n'], ...)
The ``f`` attribute of the decorated function refers to the
original function::
sage: foo = object()
sage: @sage_wraps(foo)
....: def func():
....: pass
sage: wrapped = sage_wraps(foo)(func)
sage: wrapped.f is foo
True
Demonstrate that sage_wraps works for non-function callables
(:trac:`9919`)::
sage: def square_for_met(f):
....: @sage_wraps(f)
....: def new_f(self, x):
....: return f(self,x)*f(self,x)
....: return new_f
sage: class T:
....: @square_for_met
....: def g(self, x):
....: "My little method"
....: return x
sage: t = T()
sage: t.g(2)
4
sage: t.g.__doc__
'My little method'
The bug described in :trac:`11734` is fixed::
sage: def square(f):
....: @sage_wraps(f)
....: def new_f(x):
....: return f(x)*f(x)
....: return new_f
sage: f = lambda x:x^2
sage: g = square(f)
sage: g(3) # this line used to fail for some people if these command were manually entered on the sage prompt
81
"""
#TRAC 9919: Workaround for bug in @update_wrapper when used with
#non-function callables.
assigned = set(assigned).intersection(set(dir(wrapped)))
#end workaround
def f(wrapper, assigned=assigned, updated=updated):
update_wrapper(wrapper, wrapped, assigned=assigned, updated=updated)
# For backwards-compatibility with old versions of sage_wraps
wrapper.f = wrapped
# For forwards-compatibility with functools.wraps on Python 3
wrapper.__wrapped__ = wrapped
wrapper._sage_src_ = lambda: sage_getsource(wrapped)
wrapper._sage_src_lines_ = lambda: sage_getsourcelines(wrapped)
#Getting the signature right in documentation by Sphinx (Trac 9976)
#The attribute _sage_argspec_() is read by Sphinx if present and used
#as the argspec of the function instead of using reflection.
wrapper._sage_argspec_ = lambda: sage_getargspec(wrapped)
return wrapper
return f
# Infix operator decorator
class infix_operator(object):
"""
A decorator for functions which allows for a hack that makes
the function behave like an infix operator.
This decorator exists as a convenience for interactive use.
EXAMPLES:
An infix dot product operator::
sage: @infix_operator('multiply')
....: def dot(a, b):
....: '''Dot product.'''
....: return a.dot_product(b)
sage: u = vector([1, 2, 3])
sage: v = vector([5, 4, 3])
sage: u *dot* v
22
An infix element-wise addition operator::
sage: @infix_operator('add')
....: def eadd(a, b):
....: return a.parent([i + j for i, j in zip(a, b)])
sage: u = vector([1, 2, 3])
sage: v = vector([5, 4, 3])
sage: u +eadd+ v
(6, 6, 6)
sage: 2*u +eadd+ v
(7, 8, 9)
A hack to simulate a postfix operator::
sage: @infix_operator('or')
....: def thendo(a, b):
....: return b(a)
sage: x |thendo| cos |thendo| (lambda x: x^2)
cos(x)^2
"""
operators = {
'add': {'left': '__add__', 'right': '__radd__'},
'multiply': {'left': '__mul__', 'right': '__rmul__'},
'or': {'left': '__or__', 'right': '__ror__'},
}
def __init__(self, precedence):
"""
INPUT:
- ``precedence`` -- one of ``'add'``, ``'multiply'``, or ``'or'``
indicating the new operator's precedence in the order of operations.
"""
self.precedence = precedence
def __call__(self, func):
"""Returns a function which acts as an inline operator."""
left_meth = self.operators[self.precedence]['left']
right_meth = self.operators[self.precedence]['right']
wrapper_name = func.__name__
wrapper_members = {
'function': staticmethod(func),
left_meth: _infix_wrapper._left,
right_meth: _infix_wrapper._right,
'_sage_src_': lambda: sage_getsource(func)
}
for attr in WRAPPER_ASSIGNMENTS:
try:
wrapper_members[attr] = getattr(func, attr)
except AttributeError:
pass
wrapper = type(wrapper_name, (_infix_wrapper,), wrapper_members)
wrapper_inst = wrapper()
wrapper_inst.__dict__.update(getattr(func, '__dict__', {}))
return wrapper_inst
class _infix_wrapper(object):
function = None
def __init__(self, left=None, right=None):
"""
Initialize the actual infix object, with possibly a specified left
and/or right operand.
"""
self.left = left
self.right = right
def __call__(self, *args, **kwds):
"""Call the passed function."""
return self.function(*args, **kwds)
def _left(self, right):
"""The function for the operation on the left (e.g., __add__)."""
if self.left is None:
if self.right is None:
new = copy(self)
new.right = right
return new
else:
raise SyntaxError("Infix operator already has its "
"right argument")
else:
return self.function(self.left, right)
def _right(self, left):
"""The function for the operation on the right (e.g., __radd__)."""
if self.right is None:
if self.left is None:
new = copy(self)
new.left = left
return new
else:
raise SyntaxError("Infix operator already has its "
"left argument")
else:
return self.function(left, self.right)
def decorator_defaults(func):
"""
This function allows a decorator to have default arguments.
Normally, a decorator can be called with or without arguments.
However, the two cases call for different types of return values.
If a decorator is called with no parentheses, it should be run
directly on the function. However, if a decorator is called with
parentheses (i.e., arguments), then it should return a function
that is then in turn called with the defined function as an
argument.
This decorator allows us to have these default arguments without
worrying about the return type.
EXAMPLES::
sage: from sage.misc.decorators import decorator_defaults
sage: @decorator_defaults
....: def my_decorator(f,*args,**kwds):
....: print(kwds)
....: print(args)
....: print(f.__name__)
sage: @my_decorator
....: def my_fun(a,b):
....: return a,b
{}
()
my_fun
sage: @my_decorator(3,4,c=1,d=2)
....: def my_fun(a,b):
....: return a,b
{'c': 1, 'd': 2}
(3, 4)
my_fun
"""
@sage_wraps(func)
def my_wrap(*args, **kwds):
if len(kwds) == 0 and len(args) == 1:
# call without parentheses
return func(*args)
else:
return lambda f: func(f, *args, **kwds)
return my_wrap
class suboptions(object):
def __init__(self, name, **options):
"""
A decorator for functions which collects all keywords
starting with ``name+'_'`` and collects them into a dictionary
which will be passed on to the wrapped function as a
dictionary called ``name_options``.
The keyword arguments passed into the constructor are taken
to be default for the ``name_options`` dictionary.
EXAMPLES::
sage: from sage.misc.decorators import suboptions
sage: s = suboptions('arrow', size=2)
sage: s.name
'arrow_'
sage: s.options
{'size': 2}
"""
self.name = name + "_"
self.options = options
def __call__(self, func):
"""
Returns a wrapper around func
EXAMPLES::
sage: from sage.misc.decorators import suboptions
sage: def f(*args, **kwds): print(sorted(kwds.items()))
sage: f = suboptions('arrow', size=2)(f)
sage: f(size=2)
[('arrow_options', {'size': 2}), ('size', 2)]
sage: f(arrow_size=3)
[('arrow_options', {'size': 3})]
sage: f(arrow_options={'size':4})
[('arrow_options', {'size': 4})]
sage: f(arrow_options={'size':4}, arrow_size=5)
[('arrow_options', {'size': 5})]
Demonstrate that the introspected argument specification of the
wrapped function is updated (see :trac:`9976`).
sage: from sage.misc.sageinspect import sage_getargspec
sage: sage_getargspec(f)
ArgSpec(args=['arrow_size'], varargs='args', keywords='kwds', defaults=(2,))
"""
@sage_wraps(func)
def wrapper(*args, **kwds):
suboptions = copy(self.options)
suboptions.update(kwds.pop(self.name+"options", {}))
# Collect all the relevant keywords in kwds
# and put them in suboptions
for key, value in list(kwds.items()):
if key.startswith(self.name):
suboptions[key[len(self.name):]] = value
del kwds[key]
kwds[self.name + "options"] = suboptions
return func(*args, **kwds)
# Add the options specified by @options to the signature of the wrapped
# function in the Sphinx-generated documentation (Trac 9976), using the
# special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect)
def argspec():
argspec = sage_getargspec(func)
def listForNone(l):
return l if l is not None else []
newArgs = [self.name + opt for opt in self.options.keys()]
args = (argspec.args if argspec.args is not None else []) + newArgs
defaults = (argspec.defaults if argspec.defaults is not None else ()) \
+ tuple(self.options.values())
# Note: argspec.defaults is not always a tuple for some reason
return ArgSpec(args, argspec.varargs, argspec.keywords, defaults)
wrapper._sage_argspec_ = argspec
return wrapper
class options(object):
def __init__(self, **options):
"""
A decorator for functions which allows for default options to be
set and reset by the end user. Additionally, if one needs to, one
can get at the original keyword arguments passed into the
decorator.
TESTS::
sage: from sage.misc.decorators import options
sage: o = options(rgbcolor=(0,0,1))
sage: o.options
{'rgbcolor': (0, 0, 1)}
sage: o = options(rgbcolor=(0,0,1), __original_opts=True)
sage: o.original_opts
True
sage: loads(dumps(o)).options
{'rgbcolor': (0, 0, 1)}
Demonstrate that the introspected argument specification of the wrapped
function is updated (see :trac:`9976`)::
sage: from sage.misc.decorators import options
sage: o = options(rgbcolor=(0,0,1))
sage: def f(*args, **kwds):
....: print("{} {}".format(args, sorted(kwds.items())))
sage: f1 = o(f)
sage: from sage.misc.sageinspect import sage_getargspec
sage: sage_getargspec(f1)
ArgSpec(args=['rgbcolor'], varargs='args', keywords='kwds', defaults=((0, 0, 1),))
"""
self.options = options
self.original_opts = options.pop('__original_opts', False)
def __call__(self, func):
"""
EXAMPLES::
sage: from sage.misc.decorators import options
sage: o = options(rgbcolor=(0,0,1))
sage: def f(*args, **kwds):
....: print("{} {}".format(args, sorted(kwds.items())))
sage: f1 = o(f)
sage: f1()
() [('rgbcolor', (0, 0, 1))]
sage: f1(rgbcolor=1)
() [('rgbcolor', 1)]
sage: o = options(rgbcolor=(0,0,1), __original_opts=True)
sage: f2 = o(f)
sage: f2(alpha=1)
() [('__original_opts', {'alpha': 1}), ('alpha', 1), ('rgbcolor', (0, 0, 1))]
"""
@sage_wraps(func)
def wrapper(*args, **kwds):
options = copy(wrapper.options)
if self.original_opts:
options['__original_opts'] = kwds
options.update(kwds)
return func(*args, **options)
#Add the options specified by @options to the signature of the wrapped
#function in the Sphinx-generated documentation (Trac 9976), using the
#special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect)
def argspec():
argspec = sage_getargspec(func)
args = ((argspec.args if argspec.args is not None else []) +
list(self.options))
defaults = (argspec.defaults or ()) + tuple(self.options.values())
# Note: argspec.defaults is not always a tuple for some reason
return ArgSpec(args, argspec.varargs, argspec.keywords, defaults)
wrapper._sage_argspec_ = argspec
def defaults():
"""
Return the default options.
EXAMPLES::
sage: from sage.misc.decorators import options
sage: o = options(rgbcolor=(0,0,1))
sage: def f(*args, **kwds):
....: print("{} {}".format(args, sorted(kwds.items())))
sage: f = o(f)
sage: f.options['rgbcolor']=(1,1,1)
sage: f.defaults()
{'rgbcolor': (0, 0, 1)}
"""
return copy(self.options)
def reset():
"""
Reset the options to the defaults.
EXAMPLES::
sage: from sage.misc.decorators import options
sage: o = options(rgbcolor=(0,0,1))
sage: def f(*args, **kwds):
....: print("{} {}".format(args, sorted(kwds.items())))
sage: f = o(f)
sage: f.options
{'rgbcolor': (0, 0, 1)}
sage: f.options['rgbcolor']=(1,1,1)
sage: f.options
{'rgbcolor': (1, 1, 1)}
sage: f()
() [('rgbcolor', (1, 1, 1))]
sage: f.reset()
sage: f.options
{'rgbcolor': (0, 0, 1)}
sage: f()
() [('rgbcolor', (0, 0, 1))]
"""
wrapper.options = copy(self.options)
wrapper.options = copy(self.options)
wrapper.reset = reset
wrapper.reset.__doc__ = """
Reset the options to the defaults.
Defaults:
%s
""" % self.options
wrapper.defaults = defaults
wrapper.defaults.__doc__ = """
Return the default options.
Defaults:
%s
""" % self.options
return wrapper
class rename_keyword(object):
def __init__(self, deprecated=None, deprecation=None, **renames):
"""
A decorator which renames keyword arguments and optionally
deprecates the new keyword.
INPUT:
- ``deprecation`` -- integer. The trac ticket number where the
deprecation was introduced.
- the rest of the arguments is a list of keyword arguments in the
form ``renamed_option='existing_option'``. This will have the
effect of renaming ``renamed_option`` so that the function only
sees ``existing_option``. If both ``renamed_option`` and
``existing_option`` are passed to the function, ``existing_option``
will override the ``renamed_option`` value.
EXAMPLES::
sage: from sage.misc.decorators import rename_keyword
sage: r = rename_keyword(color='rgbcolor')
sage: r.renames
{'color': 'rgbcolor'}
sage: loads(dumps(r)).renames
{'color': 'rgbcolor'}
To deprecate an old keyword::
sage: r = rename_keyword(deprecation=13109, color='rgbcolor')
"""
assert deprecated is None, 'Use @rename_keyword(deprecation=<trac_number>, ...)'
self.renames = renames
self.deprecation = deprecation
def __call__(self, func):
"""
Rename keywords.
EXAMPLES::
sage: from sage.misc.decorators import rename_keyword
sage: r = rename_keyword(color='rgbcolor')
sage: def f(*args, **kwds):
....: print("{} {}".format(args, kwds))
sage: f = r(f)
sage: f()
() {}
sage: f(alpha=1)
() {'alpha': 1}
sage: f(rgbcolor=1)
() {'rgbcolor': 1}
sage: f(color=1)
() {'rgbcolor': 1}
We can also deprecate the renamed keyword::
sage: r = rename_keyword(deprecation=13109, deprecated_option='new_option')
sage: def f(*args, **kwds):
....: print("{} {}".format(args, kwds))
sage: f = r(f)
sage: f()
() {}
sage: f(alpha=1)
() {'alpha': 1}
sage: f(new_option=1)
() {'new_option': 1}
sage: f(deprecated_option=1)
doctest:...: DeprecationWarning: use the option 'new_option' instead of 'deprecated_option'
See http://trac.sagemath.org/13109 for details.
() {'new_option': 1}
"""
@sage_wraps(func)
def wrapper(*args, **kwds):
for old_name, new_name in self.renames.items():
if old_name in kwds and new_name not in kwds:
if self.deprecation is not None:
from sage.misc.superseded import deprecation
deprecation(self.deprecation, "use the option "
"%r instead of %r" % (new_name, old_name))
kwds[new_name] = kwds[old_name]
del kwds[old_name]
return func(*args, **kwds)
return wrapper
class specialize:
r"""
A decorator generator that returns a decorator that in turn
returns a specialized function for function ``f``. In other words,
it returns a function that acts like ``f`` with arguments
``*args`` and ``**kwargs`` supplied.
INPUT:
- ``*args``, ``**kwargs`` -- arguments to specialize the function for.
OUTPUT:
- a decorator that accepts a function ``f`` and specializes it
with ``*args`` and ``**kwargs``
EXAMPLES::
sage: f = specialize(5)(lambda x, y: x+y)
sage: f(10)
15
sage: f(5)
10
sage: @specialize("Bon Voyage")
....: def greet(greeting, name):
....: print("{0}, {1}!".format(greeting, name))
sage: greet("Monsieur Jean Valjean")
Bon Voyage, Monsieur Jean Valjean!
sage: greet(name = 'Javert')
Bon Voyage, Javert!
"""
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, f):
return sage_wraps(f)(partial(f, *self.args, **self.kwargs))
def decorator_keywords(func):
r"""
A decorator for decorators with optional keyword arguments.
EXAMPLES::
sage: from sage.misc.decorators import decorator_keywords
sage: @decorator_keywords
....: def preprocess(f=None, processor=None):
....: def wrapper(*args, **kwargs):
....: if processor is not None:
....: args, kwargs = processor(*args, **kwargs)
....: return f(*args, **kwargs)
....: return wrapper
This decorator can be called with and without arguments::
sage: @preprocess
....: def foo(x): return x
sage: foo(None)
sage: foo(1)
1
sage: def normalize(x): return ((0,),{}) if x is None else ((x,),{})
sage: @preprocess(processor=normalize)
....: def foo(x): return x
sage: foo(None)
0
sage: foo(1)
1
"""
@sage_wraps(func)
def wrapped(f=None, **kwargs):
if f is None:
return sage_wraps(func)(lambda f:func(f, **kwargs))
else:
return func(f, **kwargs)
return wrapped | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/decorators.py | 0.788665 | 0.361277 | decorators.py | pypi |
# default variable name
var_name = 'x'
def variable_names(n, name=None):
r"""
Convert a root string into a tuple of variable names by adding
numbers in sequence.
INPUT:
- ``n`` a non-negative Integer; the number of variable names to
output
- ``names`` a string (default: ``None``); the root of the variable
name.
EXAMPLES::
sage: from sage.misc.defaults import variable_names
sage: variable_names(0)
()
sage: variable_names(1)
('x',)
sage: variable_names(1,'alpha')
('alpha',)
sage: variable_names(2,'alpha')
('alpha0', 'alpha1')
"""
if name is None:
name = var_name
n = int(n)
if n == 1:
return (name,)
return tuple(['%s%s' % (name, i) for i in range(n)])
def latex_variable_names(n, name=None):
r"""
Convert a root string into a tuple of variable names by adding
numbers in sequence.
INPUT:
- ``n`` a non-negative Integer; the number of variable names to
output
- ``names`` a string (default: ``None``); the root of the variable
name.
EXAMPLES::
sage: from sage.misc.defaults import latex_variable_names
sage: latex_variable_names(0)
()
sage: latex_variable_names(1,'a')
('a',)
sage: latex_variable_names(3,beta)
('beta_{0}', 'beta_{1}', 'beta_{2}')
sage: latex_variable_names(3,r'\beta')
('\\beta_{0}', '\\beta_{1}', '\\beta_{2}')
"""
if name is None:
name = var_name
n = int(n)
if n == 1:
return (name,)
return tuple(['%s_{%s}' % (name, i) for i in range(n)])
def set_default_variable_name(name, separator=''):
r"""
Change the default variable name and separator.
"""
global var_name, var_sep
var_name = str(name)
var_sep = str(separator)
# default series precision
series_prec = 20
def series_precision():
"""
Return the Sage-wide precision for series (symbolic,
power series, Laurent series).
EXAMPLES::
sage: series_precision()
20
"""
return series_prec
def set_series_precision(prec):
"""
Change the Sage-wide precision for series (symbolic,
power series, Laurent series).
EXAMPLES::
sage: set_series_precision(5)
sage: series_precision()
5
sage: set_series_precision(20)
"""
global series_prec
series_prec = prec | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/defaults.py | 0.785144 | 0.513425 | defaults.py | pypi |
from sage.structure.sage_object import SageObject
class MethodDecorator(SageObject):
def __init__(self, f):
"""
EXAMPLES::
sage: from sage.misc.method_decorator import MethodDecorator
sage: class Foo:
....: @MethodDecorator
....: def bar(self, x):
....: return x**2
sage: J = Foo()
sage: J.bar
<sage.misc.method_decorator.MethodDecorator object at ...>
"""
self.f = f
if hasattr(f, "__doc__"):
self.__doc__ = f.__doc__
else:
self.__doc__ = f.__doc__
if hasattr(f, "__name__"):
self.__name__ = f.__name__
self.__module__ = f.__module__
def _sage_src_(self):
"""
Return the source code for the wrapped function.
EXAMPLES:
This class is rather abstract so we showcase its features
using one of its subclasses::
sage: P.<x,y,z> = PolynomialRing(ZZ)
sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 )
sage: "primary" in I.primary_decomposition._sage_src_() # indirect doctest
True
"""
from sage.misc.sageinspect import sage_getsource
return sage_getsource(self.f)
def __call__(self, *args, **kwds):
"""
EXAMPLES:
This class is rather abstract so we showcase its features
using one of its subclasses::
sage: P.<x,y,z> = PolynomialRing(Zmod(126))
sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 )
sage: I.primary_decomposition() # indirect doctest
Traceback (most recent call last):
...
ValueError: Coefficient ring must be a field for function 'primary_decomposition'.
"""
return self.f(self._instance, *args, **kwds)
def __get__(self, inst, cls=None):
"""
EXAMPLES:
This class is rather abstract so we showcase its features
using one of its subclasses::
sage: P.<x,y,z> = PolynomialRing(Zmod(126))
sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 )
sage: I.primary_decomposition() # indirect doctest
Traceback (most recent call last):
...
ValueError: Coefficient ring must be a field for function 'primary_decomposition'.
"""
self._instance = inst
return self | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/method_decorator.py | 0.86267 | 0.332879 | method_decorator.py | pypi |
r"""
ReST index of functions
This module contains a function that generates a ReST index table of functions
for use in doc-strings.
{INDEX_OF_FUNCTIONS}
"""
import inspect
from sage.misc.sageinspect import _extract_embedded_position
from sage.misc.sageinspect import is_function_or_cython_function as _isfunction
def gen_rest_table_index(obj, names=None, sort=True, only_local_functions=True):
r"""
Return a ReST table describing a list of functions.
The list of functions can either be given explicitly, or implicitly as the
functions/methods of a module or class.
In the case of a class, only non-inherited methods are listed.
INPUT:
- ``obj`` -- a list of functions, a module or a class. If given a list of
functions, the generated table will consist of these. If given a module
or a class, all functions/methods it defines will be listed, except
deprecated or those starting with an underscore. In the case of a class,
note that inherited methods are not displayed.
- ``names`` -- a dictionary associating a name to a function. Takes
precedence over the automatically computed name for the functions. Only
used when ``list_of_entries`` is a list.
- ``sort`` (boolean; ``True``) -- whether to sort the list of methods
lexicographically.
- ``only_local_functions`` (boolean; ``True``) -- if ``list_of_entries`` is
a module, ``only_local_functions = True`` means that imported functions
will be filtered out. This can be useful to disable for making indexes of
e.g. catalog modules such as :mod:`sage.coding.codes_catalog`.
.. WARNING::
The ReST tables returned by this function use '@' as a delimiter for
cells. This can cause trouble if the first sentence in the documentation
of a function contains the '@' character.
EXAMPLES::
sage: from sage.misc.rest_index_of_methods import gen_rest_table_index
sage: print(gen_rest_table_index([graphs.PetersenGraph]))
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: @
<BLANKLINE>
:func:`~sage.graphs.generators.smallgraphs.PetersenGraph` @ Return the Petersen Graph.
The table of a module::
sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods))
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: @
<BLANKLINE>
:func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
:func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions.
:func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
:func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
<BLANKLINE>
<BLANKLINE>
The table of a class::
sage: print(gen_rest_table_index(Graph))
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: @
...
:meth:`~sage.graphs.graph.Graph.sparse6_string` @ Return the sparse6 representation of the graph as an ASCII string.
...
TESTS:
When the first sentence of the docstring spans over several lines::
sage: def a():
....: r'''
....: Here is a very very very long sentence
....: that spans on several lines.
....:
....: EXAMP...
....: '''
....: print("hey")
sage: 'Here is a very very very long sentence that spans on several lines' in gen_rest_table_index([a])
True
The inherited methods do not show up::
sage: gen_rest_table_index(sage.combinat.posets.lattices.FiniteLatticePoset).count('\n') < 75
True
sage: from sage.graphs.generic_graph import GenericGraph
sage: A = gen_rest_table_index(Graph).count('\n')
sage: B = gen_rest_table_index(GenericGraph).count('\n')
sage: A < B
True
When ``only_local_functions`` is ``False``, we do not include
``gen_rest_table_index`` itself::
sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=True))
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: @
<BLANKLINE>
:func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
:func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions.
:func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
:func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
<BLANKLINE>
<BLANKLINE>
sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=False))
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: @
<BLANKLINE>
:func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
:func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
:func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
<BLANKLINE>
<BLANKLINE>
A function that is imported into a class under a different name is listed
under its 'new' name::
sage: 'cliques_maximum' in gen_rest_table_index(Graph)
True
sage: 'all_max_cliques`' in gen_rest_table_index(Graph)
False
"""
if names is None:
names = {}
# If input is a class/module, we list all its non-private and methods/functions
if inspect.isclass(obj) or inspect.ismodule(obj):
list_of_entries, names = list_of_subfunctions(
obj, only_local_functions=only_local_functions)
else:
list_of_entries = obj
fname = lambda x: names.get(x, getattr(x, "__name__", ""))
assert isinstance(list_of_entries, list)
s = [".. csv-table::",
" :class: contentstable",
" :widths: 30, 70",
" :delim: @\n"]
if sort:
list_of_entries.sort(key=fname)
for e in list_of_entries:
if inspect.ismethod(e):
link = ":meth:`~{module}.{cls}.{func}`".format(
module=e.im_class.__module__, cls=e.im_class.__name__,
func=fname(e))
elif _isfunction(e) and inspect.isclass(obj):
link = ":meth:`~{module}.{cls}.{func}`".format(
module=obj.__module__, cls=obj.__name__, func=fname(e))
elif _isfunction(e):
link = ":func:`~{module}.{func}`".format(
module=e.__module__, func=fname(e))
else:
continue
# Extract lines injected by cython
doc = e.__doc__
doc_tmp = _extract_embedded_position(doc)
if doc_tmp:
doc = doc_tmp[0]
# Descriptions of the method/function
if doc:
desc = doc.split('\n\n')[0] # first paragraph
desc = " ".join(x.strip() for x in desc.splitlines()) # concatenate lines
desc = desc.strip() # remove leading spaces
else:
desc = "NO DOCSTRING"
s.append(" {} @ {}".format(link, desc.lstrip()))
return '\n'.join(s) + '\n'
def list_of_subfunctions(root, only_local_functions=True):
r"""
Returns the functions (resp. methods) of a given module (resp. class) with their names.
INPUT:
- ``root`` -- the module, or class, whose elements are to be listed.
- ``only_local_functions`` (boolean; ``True``) -- if ``root`` is a module,
``only_local_functions = True`` means that imported functions will be
filtered out. This can be useful to disable for making indexes of
e.g. catalog modules such as :mod:`sage.coding.codes_catalog`.
OUTPUT:
A pair ``(list,dict)`` where ``list`` is a list of function/methods and
``dict`` associates to every function/method the name under which it appears
in ``root``.
EXAMPLES::
sage: from sage.misc.rest_index_of_methods import list_of_subfunctions
sage: l = list_of_subfunctions(Graph)[0]
sage: Graph.bipartite_color in l
True
TESTS:
A ``staticmethod`` is not callable. We must handle them correctly, however::
sage: class A:
....: x = staticmethod(Graph.order)
sage: list_of_subfunctions(A)
([<function GenericGraph.order at 0x...>],
{<function GenericGraph.order at 0x...>: 'x'})
"""
if inspect.ismodule(root):
ismodule = True
elif inspect.isclass(root):
ismodule = False
superclasses = inspect.getmro(root)[1:]
else:
raise ValueError("'root' must be a module or a class.")
def local_filter(f,name):
if only_local_functions:
if ismodule:
return inspect.getmodule(root) == inspect.getmodule(f)
else:
return not any(hasattr(s,name) for s in superclasses)
else:
return inspect.isclass(root) or not (f is gen_rest_table_index)
functions = {getattr(root,name):name for name,f in root.__dict__.items() if
(not name.startswith('_') and # private functions
not hasattr(f,'trac_number') and # deprecated functions
not inspect.isclass(f) and # classes
callable(getattr(f,'__func__',f)) and # e.g. GenericGraph.graphics_array_defaults
local_filter(f,name)) # possibly filter imported functions
}
return list(functions.keys()), functions
def gen_thematic_rest_table_index(root,additional_categories=None,only_local_functions=True):
r"""
Return a ReST string of thematically sorted function (or methods) of a module (or class).
INPUT:
- ``root`` -- the module, or class, whose elements are to be listed.
- ``additional_categories`` -- a dictionary associating a category (given as
a string) to a function's name. Can be used when the decorator
:func:`doc_index` does not work on a function.
- ``only_local_functions`` (boolean; ``True``) -- if ``root`` is a module,
``only_local_functions = True`` means that imported functions will be
filtered out. This can be useful to disable for making indexes of
e.g. catalog modules such as :mod:`sage.coding.codes_catalog`.
EXAMPLES::
sage: from sage.misc.rest_index_of_methods import gen_thematic_rest_table_index, list_of_subfunctions
sage: l = list_of_subfunctions(Graph)[0]
sage: Graph.bipartite_color in l
True
"""
from collections import defaultdict
if additional_categories is None:
additional_categories = {}
functions, names = list_of_subfunctions(root,
only_local_functions=only_local_functions)
theme_to_function = defaultdict(list)
for f in functions:
if hasattr(f, 'doc_index'):
doc_ind = f.doc_index
else:
try:
doc_ind = additional_categories.get(f.__name__,
"Unsorted")
except AttributeError:
doc_ind = "Unsorted"
theme_to_function[doc_ind].append(f)
s = ["**"+theme+"**\n\n"+gen_rest_table_index(list_of_functions,names=names)
for theme, list_of_functions in sorted(theme_to_function.items())]
return "\n\n".join(s)
def doc_index(name):
r"""
Attribute an index name to a function.
This decorator can be applied to a function/method in order to specify in
which index it must appear, in the index generated by
:func:`gen_thematic_rest_table_index`.
INPUT:
- ``name`` -- a string, which will become the title of the index in which
this function/method will appear.
EXAMPLES::
sage: from sage.misc.rest_index_of_methods import doc_index
sage: @doc_index("Wouhouuuuu")
....: def a():
....: print("Hey")
sage: a.doc_index
'Wouhouuuuu'
"""
def hey(f):
setattr(f,"doc_index",name)
return f
return hey
__doc__ = __doc__.format(INDEX_OF_FUNCTIONS=gen_rest_table_index([gen_rest_table_index])) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/rest_index_of_methods.py | 0.872605 | 0.76947 | rest_index_of_methods.py | pypi |
r"""
Elements with labels.
This module implements a simple wrapper class for pairs consisting of
an "element" and a "label".
For representation purposes (``repr``, ``str``, ``latex``), this pair
behaves like its label, while the element is "silent".
However, these pairs compare like usual pairs (i.e., both element and
label have to be equal for two such pairs to be equal).
This is used for visual representations of graphs and posets
with vertex labels.
"""
from sage.misc.latex import latex
class ElementWithLabel(object):
"""
Auxiliary class for showing/viewing :class:`Poset`s with
non-injective labelings.
For hashing and equality testing the resulting object behaves
like a tuple ``(element, label)``.
For any presentation purposes it appears just as ``label`` would.
EXAMPLES::
sage: P = Poset({1: [2,3]})
sage: labs = {i: P.rank(i) for i in range(1, 4)}
sage: print(labs)
{1: 0, 2: 1, 3: 1}
sage: print(P.plot(element_labels=labs))
Graphics object consisting of 6 graphics primitives
sage: from sage.misc.element_with_label import ElementWithLabel
sage: W = WeylGroup("A1")
sage: P = W.bruhat_poset(facade=True)
sage: D = W.domain()
sage: v = D.rho() - D.fundamental_weight(1)
sage: nP = P.relabel(lambda w: ElementWithLabel(w, w.action(v)))
sage: list(nP)
[(0, 0), (0, 0)]
"""
def __init__(self, element, label):
"""
Construct an object that wraps ``element`` but presents itself
as ``label``.
TESTS::
sage: from sage.misc.element_with_label import ElementWithLabel
sage: e = ElementWithLabel(1, 'a')
sage: e
'a'
sage: e.element
1
"""
self.element = element
self.label = label
def _latex_(self):
"""
Return the latex representation of ``self``,
which is just the latex representation of the label.
TESTS::
sage: var('a_1')
a_1
sage: from sage.misc.element_with_label import ElementWithLabel
sage: e = ElementWithLabel(1, a_1)
sage: latex(e)
a_{1}
"""
return latex(self.label)
def __str__(self):
"""
Return the string representation of ``self``, which is just
the string representation of the label.
TESTS::
sage: var('a_1')
a_1
sage: from sage.misc.element_with_label import ElementWithLabel
sage: e = ElementWithLabel(1, a_1)
sage: str(e)
'a_1'
"""
return str(self.label)
def __repr__(self):
"""
Return the representation of ``self``, which is just
the representation of the label.
TESTS::
sage: var('a_1')
a_1
sage: from sage.misc.element_with_label import ElementWithLabel
sage: e = ElementWithLabel(1, a_1)
sage: repr(e)
'a_1'
"""
return repr(self.label)
def __hash__(self):
"""
Return the hash of the labeled element ``self``,
which is just the hash of ``self.element``.
TESTS::
sage: from sage.misc.element_with_label import ElementWithLabel
sage: a = ElementWithLabel(1, 'a')
sage: b = ElementWithLabel(1, 'b')
sage: d = {}
sage: d[a] = 'element 1'
sage: d[b] = 'element 2'
sage: print(d)
{'a': 'element 1', 'b': 'element 2'}
sage: a = ElementWithLabel("a", [2,3])
sage: hash(a) == hash(a.element)
True
"""
return hash(self.element)
def __eq__(self, other):
"""
Two labeled elements are equal if and only if both of their
constituents are equal.
TESTS::
sage: from sage.misc.element_with_label import ElementWithLabel
sage: a = ElementWithLabel(1, 'a')
sage: b = ElementWithLabel(1, 'b')
sage: x = ElementWithLabel(1, 'a')
sage: a == b
False
sage: a == x
True
sage: 1 == a
False
sage: b == 1
False
"""
if not (isinstance(self, ElementWithLabel) and
isinstance(other, ElementWithLabel)):
return False
return self.element == other.element and self.label == other.label
def __ne__(self, other):
"""
Two labeled elements are not equal if and only if first or second
constituents are not equal.
TESTS::
sage: from sage.misc.element_with_label import ElementWithLabel
sage: a = ElementWithLabel(1, 'a')
sage: b = ElementWithLabel(1, 'b')
sage: x = ElementWithLabel(1, 'a')
sage: a != b
True
sage: a != x
False
"""
return not(self == other) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/element_with_label.py | 0.929448 | 0.78968 | element_with_label.py | pypi |
class SageTimeitResult(object):
r"""
Represent the statistics of a timeit() command.
Prints as a string so that it can be easily returned to a user.
INPUT:
- ``stats`` -- tuple of length 5 containing the following information:
- integer, number of loops
- integer, repeat number
- Python integer, number of digits to print
- number, best timing result
- str, time unit
EXAMPLES::
sage: from sage.misc.sage_timeit import SageTimeitResult
sage: SageTimeitResult( (3, 5, int(8), pi, 'ms') )
3 loops, best of 5: 3.1415927 ms per loop
::
sage: units = [u"s", u"ms", u"μs", u"ns"]
sage: scaling = [1, 1e3, 1e6, 1e9]
sage: number = 7
sage: repeat = 13
sage: precision = int(5)
sage: best = pi / 10 ^ 9
sage: order = 3
sage: stats = (number, repeat, precision, best * scaling[order], units[order])
sage: SageTimeitResult(stats)
7 loops, best of 13: 3.1416 ns per loop
If the third argument is not a Python integer, a ``TypeError`` is raised::
sage: SageTimeitResult( (1, 2, 3, 4, 's') )
<repr(<sage.misc.sage_timeit.SageTimeitResult at 0x...>) failed: TypeError: * wants int>
"""
def __init__(self, stats, series=None):
r"""
Construction of a timing result.
See documentation of ``SageTimeitResult`` for more details and
examples.
EXAMPLES::
sage: from sage.misc.sage_timeit import SageTimeitResult
sage: SageTimeitResult( (3, 5, int(8), pi, 'ms') )
3 loops, best of 5: 3.1415927 ms per loop
sage: s = SageTimeitResult( (3, 5, int(8), pi, 'ms'), [1.0,1.1,0.5])
sage: s.series
[1.00000000000000, 1.10000000000000, 0.500000000000000]
"""
self.stats = stats
self.series = series if not None else []
def __repr__(self):
r"""
String representation.
EXAMPLES::
sage: from sage.misc.sage_timeit import SageTimeitResult
sage: stats = (1, 2, int(3), pi, 'ns')
sage: SageTimeitResult(stats) #indirect doctest
1 loop, best of 2: 3.14 ns per loop
"""
if self.stats[0] > 1:
s = u"%d loops, best of %d: %.*g %s per loop" % self.stats
else:
s = u"%d loop, best of %d: %.*g %s per loop" % self.stats
if isinstance(s, str):
return s
return s.encode("utf-8")
def sage_timeit(stmt, globals_dict=None, preparse=None, number=0, repeat=3, precision=3, seconds=False):
"""nodetex
Accurately measure the wall time required to execute ``stmt``.
INPUT:
- ``stmt`` -- a text string.
- ``globals_dict`` -- a dictionary or ``None`` (default). Evaluate
``stmt`` in the context of the globals dictionary. If not set,
the current ``globals()`` dictionary is used.
- ``preparse`` -- (default: use globals preparser default) if
``True`` preparse ``stmt`` using the Sage preparser.
- ``number`` -- integer, (optional, default: 0), number of loops.
- ``repeat`` -- integer, (optional, default: 3), number of
repetition.
- ``precision`` -- integer, (optional, default: 3), precision of
output time.
- ``seconds`` -- boolean (default: ``False``). Whether to just
return time in seconds.
OUTPUT:
An instance of ``SageTimeitResult`` unless the optional parameter
``seconds=True`` is passed. In that case, the elapsed time in
seconds is returned as a floating-point number.
EXAMPLES::
sage: from sage.misc.sage_timeit import sage_timeit
sage: sage_timeit('3^100000', globals(), preparse=True, number=50) # random output
'50 loops, best of 3: 1.97 ms per loop'
sage: sage_timeit('3^100000', globals(), preparse=False, number=50) # random output
'50 loops, best of 3: 67.1 ns per loop'
sage: a = 10
sage: sage_timeit('a^2', globals(), number=50) # random output
'50 loops, best of 3: 4.26 us per loop'
If you only want to see the timing and not have access to additional
information, just use the ``timeit`` object::
sage: timeit('10^2', number=50)
50 loops, best of 3: ... per loop
Using sage_timeit gives you more information though::
sage: s = sage_timeit('10^2', globals(), repeat=1000)
sage: len(s.series)
1000
sage: mean(s.series) # random output
3.1298141479492283e-07
sage: min(s.series) # random output
2.9258728027343752e-07
sage: t = stats.TimeSeries(s.series)
sage: t.scale(10^6).plot_histogram(bins=20,figsize=[12,6], ymax=2)
Graphics object consisting of 20 graphics primitives
The input expression can contain newlines (but doctests cannot, so
we use ``os.linesep`` here)::
sage: from sage.misc.sage_timeit import sage_timeit
sage: from os import linesep as CR
sage: # sage_timeit(r'a = 2\\nb=131\\nfactor(a^b-1)')
sage: sage_timeit('a = 2' + CR + 'b=131' + CR + 'factor(a^b-1)',
....: globals(), number=10)
10 loops, best of 3: ... per loop
Test to make sure that ``timeit`` behaves well with output::
sage: timeit("print('Hi')", number=50)
50 loops, best of 3: ... per loop
If you want a machine-readable output, use the ``seconds=True`` option::
sage: timeit("print('Hi')", seconds=True) # random output
1.42555236816e-06
sage: t = timeit("print('Hi')", seconds=True)
sage: t #r random output
3.6010742187499999e-07
TESTS:
Make sure that garbage collection is re-enabled after an exception
occurs in timeit::
sage: def f(): raise ValueError
sage: import gc
sage: gc.isenabled()
True
sage: timeit("f()")
Traceback (most recent call last):
...
ValueError
sage: gc.isenabled()
True
"""
import math
import timeit as timeit_
import sage.repl.interpreter as interpreter
import sage.repl.preparse as preparser
number = int(number)
repeat = int(repeat)
precision = int(precision)
if preparse is None:
preparse = interpreter._do_preparse
if preparse:
stmt = preparser.preparse(stmt)
if stmt == "":
return ''
units = [u"s", u"ms", u"μs", u"ns"]
scaling = [1, 1e3, 1e6, 1e9]
timer = timeit_.Timer()
# this code has tight coupling to the inner workings of timeit.Timer,
# but is there a better way to achieve that the code stmt has access
# to the shell namespace?
src = timeit_.template.format(stmt=timeit_.reindent(stmt, 8),
setup="pass", init='')
code = compile(src, "<magic-timeit>", "exec")
ns = {}
if not globals_dict:
globals_dict = globals()
exec(code, globals_dict, ns)
timer.inner = ns["inner"]
try:
import sys
f = sys.stdout
sys.stdout = open('/dev/null', 'w')
if number == 0:
# determine number so that 0.2 <= total time < 2.0
number = 1
for i in range(1, 5):
number *= 5
if timer.timeit(number) >= 0.2:
break
series = [s / number for s in timer.repeat(repeat, number)]
best = min(series)
finally:
sys.stdout.close()
sys.stdout = f
import gc
gc.enable()
if seconds:
return best
if best > 0.0:
order = min(-int(math.floor(math.log10(best)) // 3), 3)
else:
order = 3
stats = (number, repeat, precision, best * scaling[order], units[order])
return SageTimeitResult(stats, series=series) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/sage_timeit.py | 0.857843 | 0.653652 | sage_timeit.py | pypi |
import types
def abstract_method(f=None, optional=False):
r"""
Abstract methods
INPUT:
- ``f`` -- a function
- ``optional`` -- a boolean; defaults to ``False``
The decorator :obj:`abstract_method` can be used to declare
methods that should be implemented by all concrete derived
classes. This declaration should typically include documentation
for the specification for this method.
The purpose is to enforce a consistent and visual syntax for such
declarations. It is used by the Sage categories for automated
tests (see ``Sets.Parent.test_not_implemented``).
EXAMPLES:
We create a class with an abstract method::
sage: class A(object):
....:
....: @abstract_method
....: def my_method(self):
....: '''
....: The method :meth:`my_method` computes my_method
....:
....: EXAMPLES::
....:
....: '''
....: pass
sage: A.my_method
<abstract method my_method at ...>
The current policy is that a ``NotImplementedError`` is raised
when accessing the method through an instance, even before the
method is called::
sage: x = A()
sage: x.my_method
Traceback (most recent call last):
...
NotImplementedError: <abstract method my_method at ...>
It is also possible to mark abstract methods as optional::
sage: class A(object):
....:
....: @abstract_method(optional = True)
....: def my_method(self):
....: '''
....: The method :meth:`my_method` computes my_method
....:
....: EXAMPLES::
....:
....: '''
....: pass
sage: A.my_method
<optional abstract method my_method at ...>
sage: x = A()
sage: x.my_method
NotImplemented
The official mantra for testing whether an optional abstract
method is implemented is::
sage: if x.my_method is not NotImplemented:
....: x.my_method()
....: else:
....: print("x.my_method is not available.")
x.my_method is not available.
.. rubric:: Discussion
The policy details are not yet fixed. The purpose of this first
implementation is to let developers experiment with it and give
feedback on what's most practical.
The advantage of the current policy is that attempts at using a
non implemented methods are caught as early as possible. On the
other hand, one cannot use introspection directly to fetch the
documentation::
sage: x.my_method? # todo: not implemented
Instead one needs to do::
sage: A._my_method? # todo: not implemented
This could probably be fixed in :mod:`sage.misc.sageinspect`.
.. TODO:: what should be the recommended mantra for existence testing from the class?
.. TODO::
should extra information appear in the output? The name of the
class? That of the super class where the abstract method is
defined?
.. TODO:: look for similar decorators on the web, and merge
.. rubric:: Implementation details
Technically, an abstract_method is a non-data descriptor (see
Invoking Descriptors in the Python reference manual).
The syntax ``@abstract_method`` w.r.t. @abstract_method(optional = True)
is achieved by a little trick which we test here::
sage: abstract_method(optional = True)
<function abstract_method.<locals>.<lambda> at ...>
sage: abstract_method(optional = True)(banner)
<optional abstract method banner at ...>
sage: abstract_method(banner, optional = True)
<optional abstract method banner at ...>
"""
if f is None:
return lambda f: AbstractMethod(f, optional=optional)
else:
return AbstractMethod(f, optional)
class AbstractMethod(object):
def __init__(self, f, optional=False):
"""
Constructor for abstract methods
EXAMPLES::
sage: def f(x):
....: "doc of f"
....: return 1
sage: x = abstract_method(f); x
<abstract method f at ...>
sage: x.__doc__
'doc of f'
sage: x.__name__
'f'
sage: x.__module__
'__main__'
"""
assert (isinstance(f, types.FunctionType) or
getattr(type(f), '__name__', None) == 'cython_function_or_method')
assert isinstance(optional, bool)
self._f = f
self._optional = optional
self.__doc__ = f.__doc__
self.__name__ = f.__name__
try:
self.__module__ = f.__module__
except AttributeError:
pass
def __repr__(self):
"""
EXAMPLES::
sage: abstract_method(banner)
<abstract method banner at ...>
sage: abstract_method(banner, optional = True)
<optional abstract method banner at ...>
"""
return "<" + ("optional " if self._optional else "") + "abstract method %s at %s>" % (self.__name__, hex(id(self._f)))
def _sage_src_lines_(self):
"""
Returns the source code location for the wrapped function.
EXAMPLES::
sage: from sage.misc.sageinspect import sage_getsourcelines
sage: g = abstract_method(banner)
sage: (src, lines) = sage_getsourcelines(g)
sage: src[0]
'def banner():\n'
sage: lines
81
"""
from sage.misc.sageinspect import sage_getsourcelines
return sage_getsourcelines(self._f)
def __get__(self, instance, cls):
"""
Implements the attribute access protocol.
EXAMPLES::
sage: class A: pass
sage: def f(x): return 1
sage: f = abstract_method(f)
sage: f.__get__(A(), A)
Traceback (most recent call last):
...
NotImplementedError: <abstract method f at ...>
"""
if instance is None:
return self
elif self._optional:
return NotImplemented
else:
raise NotImplementedError(repr(self))
def is_optional(self):
"""
Returns whether an abstract method is optional or not.
EXAMPLES::
sage: class AbstractClass:
....: @abstract_method
....: def required(): pass
....:
....: @abstract_method(optional = True)
....: def optional(): pass
sage: AbstractClass.required.is_optional()
False
sage: AbstractClass.optional.is_optional()
True
"""
return self._optional
def abstract_methods_of_class(cls):
"""
Returns the required and optional abstract methods of the class
EXAMPLES::
sage: class AbstractClass:
....: @abstract_method
....: def required1(): pass
....:
....: @abstract_method(optional = True)
....: def optional2(): pass
....:
....: @abstract_method(optional = True)
....: def optional1(): pass
....:
....: @abstract_method
....: def required2(): pass
sage: sage.misc.abstract_method.abstract_methods_of_class(AbstractClass)
{'optional': ['optional1', 'optional2'],
'required': ['required1', 'required2']}
"""
result = {"required": [],
"optional": []}
for name in dir(cls):
entry = getattr(cls, name)
if not isinstance(entry, AbstractMethod):
continue
if entry.is_optional():
result["optional"].append(name)
else:
result["required"].append(name)
return result | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/abstract_method.py | 0.738386 | 0.496277 | abstract_method.py | pypi |
class LazyFormat(str):
"""
Lazy format strings
.. NOTE::
We recommend to use :func:`sage.misc.lazy_string.lazy_string` instead,
which is both faster and more flexible.
An instance of :class:`LazyFormat` behaves like a usual format
string, except that the evaluation of the ``__repr__`` method of
the formatted arguments it postponed until actual printing.
EXAMPLES:
Under normal circumstances, :class:`Lazyformat` strings behave as usual::
sage: from sage.misc.lazy_format import LazyFormat
sage: LazyFormat("Got `%s`; expected a list")%3
Got `3`; expected a list
sage: LazyFormat("Got `%s`; expected %s")%(3, 2/3)
Got `3`; expected 2/3
To demonstrate the lazyness, let us build an object with a broken
``__repr__`` method::
sage: class IDontLikeBeingPrinted(object):
....: def __repr__(self):
....: raise ValueError("Don't ever try to print me !")
There is no error when binding a lazy format with the broken object::
sage: lf = LazyFormat("<%s>")%IDontLikeBeingPrinted()
The error only occurs upon printing::
sage: lf
<repr(<sage.misc.lazy_format.LazyFormat at 0x...>) failed: ValueError: Don't ever try to print me !>
.. rubric:: Common use case:
Most of the time, ``__repr__`` methods are only called during user
interaction, and therefore need not be fast; and indeed there are
objects ``x`` in Sage such ``x.__repr__()`` is time consuming.
There are however some uses cases where many format strings are
constructed but not actually printed. This includes error handling
messages in :mod:`unittest` or :class:`TestSuite` executions::
sage: QQ._tester().assertTrue(0 in QQ,
....: "%s doesn't contain 0"%QQ)
In the above ``QQ.__repr__()`` has been called, and the result
immediately discarded. To demonstrate this we replace ``QQ`` in
the format string argument with our broken object::
sage: QQ._tester().assertTrue(True,
....: "%s doesn't contain 0"%IDontLikeBeingPrinted())
Traceback (most recent call last):
...
ValueError: Don't ever try to print me !
This behavior can induce major performance penalties when testing.
Note that this issue does not impact the usual assert::
sage: assert True, "%s is wrong"%IDontLikeBeingPrinted()
We now check that :class:`LazyFormat` indeed solves the assertion problem::
sage: QQ._tester().assertTrue(True,
....: LazyFormat("%s is wrong")%IDontLikeBeingPrinted())
sage: QQ._tester().assertTrue(False,
....: LazyFormat("%s is wrong")%IDontLikeBeingPrinted())
Traceback (most recent call last):
...
AssertionError: <unprintable AssertionError object>
"""
def __mod__(self, args):
"""
Binds the lazy format string with its parameters
EXAMPLES::
sage: from sage.misc.lazy_format import LazyFormat
sage: form = LazyFormat("<%s>")
sage: form
unbound LazyFormat("<%s>")
sage: form%"params"
<params>
"""
if hasattr(self, "_args"): # self is already bound...
self = LazyFormat(""+self)
self._args = args
return self
def __repr__(self):
"""
TESTS::
sage: from sage.misc.lazy_format import LazyFormat
sage: form = LazyFormat("<%s>")
sage: form
unbound LazyFormat("<%s>")
sage: print(form)
unbound LazyFormat("<%s>")
sage: form%"toto"
<toto>
sage: print(form % "toto")
<toto>
sage: print(str(form % "toto"))
<toto>
sage: print((form % "toto").__repr__())
<toto>
"""
try:
args = self._args
except AttributeError:
return "unbound LazyFormat(\""+self+"\")"
else:
return str.__mod__(self, args)
__str__ = __repr__ | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/lazy_format.py | 0.737914 | 0.685857 | lazy_format.py | pypi |
r"""
Tables
Display a rectangular array as a table, either in plain text, LaTeX,
or html. See the documentation for :class:`table` for details and
examples.
AUTHORS:
- John H. Palmieri (2012-11)
"""
from io import StringIO
from sage.structure.sage_object import SageObject
from sage.misc.cachefunc import cached_method
class table(SageObject):
r"""
Display a rectangular array as a table, either in plain text, LaTeX,
or html.
INPUT:
- ``rows`` (default ``None``) - a list of lists (or list of tuples,
etc.), containing the data to be displayed.
- ``columns`` (default ``None``) - a list of lists (etc.), containing
the data to be displayed, but stored as columns. Set either ``rows``
or ``columns``, but not both.
- ``header_row`` (default ``False``) - if ``True``, first row is
highlighted.
- ``header_column`` (default ``False``) - if ``True``, first column is
highlighted.
- ``frame`` (default ``False``) - if ``True``, put a box around each
cell.
- ``align`` (default 'left') - the alignment of each entry: either
'left', 'center', or 'right'
EXAMPLES::
sage: rows = [['a', 'b', 'c'], [100,2,3], [4,5,60]]
sage: table(rows)
a b c
100 2 3
4 5 60
sage: latex(table(rows))
\begin{tabular}{lll}
a & b & c \\
$100$ & $2$ & $3$ \\
$4$ & $5$ & $60$ \\
\end{tabular}
If ``header_row`` is ``True``, then the first row is highlighted. If
``header_column`` is ``True``, then the first column is
highlighted. If ``frame`` is ``True``, then print a box around every
"cell". ::
sage: table(rows, header_row=True)
a b c
+-----+---+----+
100 2 3
4 5 60
sage: latex(table(rows, header_row=True))
\begin{tabular}{lll}
a & b & c \\ \hline
$100$ & $2$ & $3$ \\
$4$ & $5$ & $60$ \\
\end{tabular}
sage: table(rows=rows, frame=True)
+-----+---+----+
| a | b | c |
+-----+---+----+
| 100 | 2 | 3 |
+-----+---+----+
| 4 | 5 | 60 |
+-----+---+----+
sage: latex(table(rows=rows, frame=True))
\begin{tabular}{|l|l|l|} \hline
a & b & c \\ \hline
$100$ & $2$ & $3$ \\ \hline
$4$ & $5$ & $60$ \\ \hline
\end{tabular}
sage: table(rows, header_column=True, frame=True)
+-----++---+----+
| a || b | c |
+-----++---+----+
| 100 || 2 | 3 |
+-----++---+----+
| 4 || 5 | 60 |
+-----++---+----+
sage: latex(table(rows, header_row=True, frame=True))
\begin{tabular}{|l|l|l|} \hline
a & b & c \\ \hline \hline
$100$ & $2$ & $3$ \\ \hline
$4$ & $5$ & $60$ \\ \hline
\end{tabular}
sage: table(rows, header_column=True)
a | b c
100 | 2 3
4 | 5 60
The argument ``header_row`` can, instead of being ``True`` or
``False``, be the contents of the header row, so that ``rows``
consists of the data, while ``header_row`` is the header
information. The same goes for ``header_column``. Passing lists
for both arguments simultaneously is not supported. ::
sage: table([(x,n(sin(x), digits=2)) for x in [0..3]], header_row=["$x$", r"$\sin(x)$"], frame=True)
+-----+-----------+
| $x$ | $\sin(x)$ |
+=====+===========+
| 0 | 0.00 |
+-----+-----------+
| 1 | 0.84 |
+-----+-----------+
| 2 | 0.91 |
+-----+-----------+
| 3 | 0.14 |
+-----+-----------+
You can create the transpose of this table in several ways, for
example, "by hand," that is, changing the data defining the table::
sage: table(rows=[[x for x in [0..3]], [n(sin(x), digits=2) for x in [0..3]]], header_column=['$x$', r'$\sin(x)$'], frame=True)
+-----------++------+------+------+------+
| $x$ || 0 | 1 | 2 | 3 |
+-----------++------+------+------+------+
| $\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 |
+-----------++------+------+------+------+
or by passing the original data as the ``columns`` of the table
and using ``header_column`` instead of ``header_row``::
sage: table(columns=[(x,n(sin(x), digits=2)) for x in [0..3]], header_column=['$x$', r'$\sin(x)$'], frame=True)
+-----------++------+------+------+------+
| $x$ || 0 | 1 | 2 | 3 |
+-----------++------+------+------+------+
| $\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 |
+-----------++------+------+------+------+
or by taking the :meth:`transpose` of the original table::
sage: table(rows=[(x,n(sin(x), digits=2)) for x in [0..3]], header_row=['$x$', r'$\sin(x)$'], frame=True).transpose()
+-----------++------+------+------+------+
| $x$ || 0 | 1 | 2 | 3 |
+-----------++------+------+------+------+
| $\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 |
+-----------++------+------+------+------+
In either plain text or LaTeX, entries in tables can be aligned to the
left (default), center, or right::
sage: table(rows, align='left')
a b c
100 2 3
4 5 60
sage: table(rows, align='center')
a b c
100 2 3
4 5 60
sage: table(rows, align='right', frame=True)
+-----+---+----+
| a | b | c |
+-----+---+----+
| 100 | 2 | 3 |
+-----+---+----+
| 4 | 5 | 60 |
+-----+---+----+
To generate HTML you should use ``html(table(...))``::
sage: data = [["$x$", r"$\sin(x)$"]] + [(x,n(sin(x), digits=2)) for x in [0..3]]
sage: output = html(table(data, header_row=True, frame=True))
sage: type(output)
<class 'sage.misc.html.HtmlFragment'>
sage: print(output)
<div class="notruncate">
<table border="1" class="table_form">
<tbody>
<tr>
<th style="text-align:left">\(x\)</th>
<th style="text-align:left">\(\sin(x)\)</th>
</tr>
<tr class ="row-a">
<td style="text-align:left">\(0\)</td>
<td style="text-align:left">\(0.00\)</td>
</tr>
<tr class ="row-b">
<td style="text-align:left">\(1\)</td>
<td style="text-align:left">\(0.84\)</td>
</tr>
<tr class ="row-a">
<td style="text-align:left">\(2\)</td>
<td style="text-align:left">\(0.91\)</td>
</tr>
<tr class ="row-b">
<td style="text-align:left">\(3\)</td>
<td style="text-align:left">\(0.14\)</td>
</tr>
</tbody>
</table>
</div>
It is an error to specify both ``rows`` and ``columns``::
sage: table(rows=[[1,2,3], [4,5,6]], columns=[[0,0,0], [0,0,1024]])
Traceback (most recent call last):
...
ValueError: Don't set both 'rows' and 'columns' when defining a table.
sage: table(columns=[[0,0,0], [0,0,1024]])
0 0
0 0
0 1024
Note that if ``rows`` is just a list or tuple, not nested, then
it is treated as a single row::
sage: table([1,2,3])
1 2 3
Also, if you pass a non-rectangular array, the longer rows or
columns get truncated::
sage: table([[1,2,3,7,12], [4,5]])
1 2
4 5
sage: table(columns=[[1,2,3], [4,5,6,7]])
1 4
2 5
3 6
TESTS::
sage: TestSuite(table([["$x$", r"$\sin(x)$"]] +
....: [(x,n(sin(x), digits=2)) for x in [0..3]],
....: header_row=True, frame=True)).run()
.. automethod:: _rich_repr_
"""
def __init__(self, rows=None, columns=None, header_row=False,
header_column=False, frame=False, align='left'):
r"""
EXAMPLES::
sage: table([1,2,3], frame=True)
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
"""
# If both rows and columns are set, raise an error.
if rows and columns:
raise ValueError("Don't set both 'rows' and 'columns' when defining a table.")
# If columns is set, use its transpose for rows.
if columns:
rows = list(zip(*columns))
# Set the rest of the options.
self._options = {}
if header_row is True:
self._options['header_row'] = True
elif header_row:
self._options['header_row'] = True
rows = [header_row] + rows
else:
self._options['header_row'] = False
if header_column is True:
self._options['header_column'] = True
elif header_column:
self._options['header_column'] = True
rows = [(a,) + tuple(x) for (a,x) in zip(header_column, rows)]
else:
self._options['header_column'] = False
self._options['frame'] = frame
self._options['align'] = align
# Store rows as a tuple.
if not isinstance(rows[0], (list, tuple)):
rows = (rows,)
self._rows = tuple(rows)
def __eq__(self, other):
r"""
Two tables are equal if and only if their data rowss and
their options are the same.
EXAMPLES::
sage: rows = [['a', 'b', 'c'], [1,plot(sin(x)),3], [4,5,identity_matrix(2)]]
sage: T = table(rows, header_row=True)
sage: T2 = table(rows, header_row=True)
sage: T is T2
False
sage: T == T2
True
sage: T2.options(frame=True)
sage: T == T2
False
"""
return (self._rows == other._rows and self.options() == other.options())
def options(self, **kwds):
r"""
With no arguments, return the dictionary of options for this
table. With arguments, modify options.
INPUT:
- ``header_row`` - if True, first row is highlighted.
- ``header_column`` - if True, first column is highlighted.
- ``frame`` - if True, put a box around each cell.
- ``align`` - the alignment of each entry: either 'left',
'center', or 'right'
EXAMPLES::
sage: T = table([['a', 'b', 'c'], [1,2,3]])
sage: T.options()['align'], T.options()['frame']
('left', False)
sage: T.options(align='right', frame=True)
sage: T.options()['align'], T.options()['frame']
('right', True)
Note that when first initializing a table, ``header_row`` or
``header_column`` can be a list. In this case, during the
initialization process, the header is merged with the rest of
the data, so changing the header option later using
``table.options(...)`` doesn't affect the contents of the
table, just whether the row or column is highlighted. When
using this :meth:`options` method, no merging of data occurs,
so here ``header_row`` and ``header_column`` should just be
``True`` or ``False``, not a list. ::
sage: T = table([[1,2,3], [4,5,6]], header_row=['a', 'b', 'c'], frame=True)
sage: T
+---+---+---+
| a | b | c |
+===+===+===+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
sage: T.options(header_row=False)
sage: T
+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
If you do specify a list for ``header_row``, an error is raised::
sage: T.options(header_row=['x', 'y', 'z'])
Traceback (most recent call last):
...
TypeError: header_row should be either True or False.
"""
if kwds:
for option in ['align', 'frame']:
if option in kwds:
self._options[option] = kwds[option]
for option in ['header_row', 'header_column']:
if option in kwds:
if not kwds[option]:
self._options[option] = kwds[option]
elif kwds[option] is True:
self._options[option] = kwds[option]
else:
raise TypeError("%s should be either True or False." % option)
else:
return self._options
def transpose(self):
r"""
Return a table which is the transpose of this one:
rows and columns have been interchanged. Several of the
properties of the original table are preserved: whether a
frame is present and any alignment setting. On the other hand,
header rows are converted to header columns, and vice versa.
EXAMPLES::
sage: T = table([[1,2,3], [4,5,6]])
sage: T.transpose()
1 4
2 5
3 6
sage: T = table([[1,2,3], [4,5,6]], header_row=['x', 'y', 'z'], frame=True)
sage: T.transpose()
+---++---+---+
| x || 1 | 4 |
+---++---+---+
| y || 2 | 5 |
+---++---+---+
| z || 3 | 6 |
+---++---+---+
"""
return table(list(zip(*self._rows)),
header_row=self._options['header_column'],
header_column=self._options['header_row'],
frame=self._options['frame'],
align=self._options['align'])
@cached_method
def _widths(self):
r"""
The maximum widths for (the string representation of) each
column. Used by the :meth:`_repr_` method.
EXAMPLES::
sage: table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]])._widths()
(2, 3, 5)
"""
nc = len(self._rows[0])
widths = [0] * nc
for row in self._rows:
w = []
for (idx, x) in zip(range(nc), row):
w.append(max(widths[idx], len(str(x))))
widths = w
return tuple(widths)
def _repr_(self):
r"""
String representation of a table.
The class docstring has many examples; here is one more.
EXAMPLES::
sage: table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]], align='right') # indirect doctest
a bb ccccc
10 -12 0
1 2 3
"""
rows = self._rows
nc = len(rows[0])
if len(rows) == 0 or nc == 0:
return ""
frame_line = "+" + "+".join("-" * (x+2) for x in self._widths()) + "+\n"
if self._options['header_column'] and self._options['frame']:
frame_line = "+" + frame_line[1:].replace('+', '++', 1)
if self._options['frame']:
s = frame_line
else:
s = ""
if self._options['header_row']:
s += self._str_table_row(rows[0], header_row=True)
rows = rows[1:]
for row in rows:
s += self._str_table_row(row, header_row=False)
return s.strip("\n")
def _rich_repr_(self, display_manager, **kwds):
"""
Rich Output Magic Method
See :mod:`sage.repl.rich_output` for details.
EXAMPLES::
sage: from sage.repl.rich_output import get_display_manager
sage: dm = get_display_manager()
sage: t = table([1, 2, 3])
sage: t._rich_repr_(dm) # the doctest backend does not support html
"""
OutputHtml = display_manager.types.OutputHtml
if OutputHtml in display_manager.supported_output():
return OutputHtml(self._html_())
def _str_table_row(self, row, header_row=False):
r"""
String representation of a row of a table. Used by the
:meth:`_repr_` method.
EXAMPLES::
sage: T = table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]], align='right')
sage: T._str_table_row([1,2,3])
' 1 2 3\n'
sage: T._str_table_row([1,2,3], True)
' 1 2 3\n+----+-----+-------+\n'
sage: T.options(header_column=True)
sage: T._str_table_row([1,2,3], True)
' 1 | 2 3\n+----+-----+-------+\n'
sage: T.options(frame=True)
sage: T._str_table_row([1,2,3], False)
'| 1 || 2 | 3 |\n+----++-----+-------+\n'
Check that :trac:`14601` has been fixed::
sage: table([['111111', '222222', '333333']])._str_table_row([False,True,None], False)
' False True None\n'
"""
frame = self._options['frame']
widths = self._widths()
frame_line = "+" + "+".join("-" * (x+2) for x in widths) + "+\n"
align = self._options['align']
if align == 'right':
align_char = '>'
elif align == 'center':
align_char = '^'
else:
align_char = '<'
s = ""
if frame:
s += "| "
else:
s += " "
if self._options['header_column']:
if frame:
frame_line = "+" + frame_line[1:].replace('+', '++', 1)
s += ("{!s:" + align_char + str(widths[0]) + "}").format(row[0])
if frame:
s += " || "
else:
s += " | "
row = row[1:]
widths = widths[1:]
for (entry, width) in zip(row, widths):
s += ("{!s:" + align_char + str(width) + "}").format(entry)
if frame:
s += " | "
else:
s += " "
s = s.rstrip(' ')
s += "\n"
if frame and header_row:
s += frame_line.replace('-', '=')
elif frame or header_row:
s += frame_line
return s
def _latex_(self):
r"""
LaTeX representation of a table.
If an entry is a Sage object, it is replaced by its LaTeX
representation, delimited by dollar signs (i.e., ``x`` is
replaced by ``$latex(x)$``). If an entry is a string, the
dollar signs are not automatically added, so tables can
include both plain text and mathematics.
OUTPUT:
String.
EXAMPLES::
sage: from sage.misc.table import table
sage: a = [[r'$\sin(x)$', '$x$', 'text'], [1,34342,3], [identity_matrix(2),5,6]]
sage: latex(table(a)) # indirect doctest
\begin{tabular}{lll}
$\sin(x)$ & $x$ & text \\
$1$ & $34342$ & $3$ \\
$\left(\begin{array}{rr}
1 & 0 \\
0 & 1
\end{array}\right)$ & $5$ & $6$ \\
\end{tabular}
sage: latex(table(a, frame=True, align='center'))
\begin{tabular}{|c|c|c|} \hline
$\sin(x)$ & $x$ & text \\ \hline
$1$ & $34342$ & $3$ \\ \hline
$\left(\begin{array}{rr}
1 & 0 \\
0 & 1
\end{array}\right)$ & $5$ & $6$ \\ \hline
\end{tabular}
"""
from .latex import latex, LatexExpr
rows = self._rows
nc = len(rows[0])
if len(rows) == 0 or nc == 0:
return ""
align_char = self._options['align'][0] # 'l', 'c', 'r'
if self._options['frame']:
frame_char = '|'
frame_str = ' \\hline'
else:
frame_char = ''
frame_str = ''
if self._options['header_column']:
head_col_char = '|'
else:
head_col_char = ''
if self._options['header_row']:
head_row_str = ' \\hline'
else:
head_row_str = ''
# table header
s = "\\begin{tabular}{"
s += frame_char + align_char + frame_char + head_col_char
s += frame_char.join([align_char] * (nc-1))
s += frame_char + "}" + frame_str + "\n"
# first row
s += " & ".join(LatexExpr(x) if isinstance(x, (str, LatexExpr))
else '$' + latex(x).strip() + '$' for x in rows[0])
s += " \\\\" + frame_str + head_row_str + "\n"
# other rows
for row in rows[1:]:
s += " & ".join(LatexExpr(x) if isinstance(x, (str, LatexExpr))
else '$' + latex(x).strip() + '$' for x in row)
s += " \\\\" + frame_str + "\n"
s += "\\end{tabular}"
return s
def _html_(self):
r"""
HTML representation of a table.
Strings of html will be parsed for math inside dollar and
double-dollar signs. 2D graphics will be displayed in the
cells. Expressions will be latexed.
The ``align`` option for tables is ignored in HTML
output. Specifying ``header_column=True`` may not have any
visible effect in the Sage notebook, depending on the version
of the notebook.
OUTPUT:
A :class:`~sage.misc.html.HtmlFragment` instance.
EXAMPLES::
sage: T = table([[r'$\sin(x)$', '$x$', 'text'], [1,34342,3], [identity_matrix(2),5,6]])
sage: T._html_()
'<div.../div>'
sage: print(T._html_())
<div class="notruncate">
<table class="table_form">
<tbody>
<tr class ="row-a">
<td style="text-align:left">\(\sin(x)\)</td>
<td style="text-align:left">\(x\)</td>
<td style="text-align:left">text</td>
</tr>
<tr class ="row-b">
<td style="text-align:left">\(1\)</td>
<td style="text-align:left">\(34342\)</td>
<td style="text-align:left">\(3\)</td>
</tr>
<tr class ="row-a">
<td style="text-align:left">\(\left(\begin{array}{rr}
1 & 0 \\
0 & 1
\end{array}\right)\)</td>
<td style="text-align:left">\(5\)</td>
<td style="text-align:left">\(6\)</td>
</tr>
</tbody>
</table>
</div>
Note that calling ``html(table(...))`` has the same effect as
calling ``table(...)._html_()``::
sage: T = table([["$x$", r"$\sin(x)$"]] + [(x,n(sin(x), digits=2)) for x in [0..3]], header_row=True, frame=True)
sage: T
+-----+-----------+
| $x$ | $\sin(x)$ |
+=====+===========+
| 0 | 0.00 |
+-----+-----------+
| 1 | 0.84 |
+-----+-----------+
| 2 | 0.91 |
+-----+-----------+
| 3 | 0.14 |
+-----+-----------+
sage: print(html(T))
<div class="notruncate">
<table border="1" class="table_form">
<tbody>
<tr>
<th style="text-align:left">\(x\)</th>
<th style="text-align:left">\(\sin(x)\)</th>
</tr>
<tr class ="row-a">
<td style="text-align:left">\(0\)</td>
<td style="text-align:left">\(0.00\)</td>
</tr>
<tr class ="row-b">
<td style="text-align:left">\(1\)</td>
<td style="text-align:left">\(0.84\)</td>
</tr>
<tr class ="row-a">
<td style="text-align:left">\(2\)</td>
<td style="text-align:left">\(0.91\)</td>
</tr>
<tr class ="row-b">
<td style="text-align:left">\(3\)</td>
<td style="text-align:left">\(0.14\)</td>
</tr>
</tbody>
</table>
</div>
"""
from itertools import cycle
rows = self._rows
header_row = self._options['header_row']
if self._options['frame']:
frame = 'border="1"'
else:
frame = ''
s = StringIO()
if rows:
s.writelines([
# If the table has < 100 rows, don't truncate the output in the notebook
'<div class="notruncate">\n' if len(rows) <= 100 else '<div class="truncate">' ,
'<table {} class="table_form">\n'.format(frame),
'<tbody>\n',
])
# First row:
if header_row:
s.write('<tr>\n')
self._html_table_row(s, rows[0], header=header_row)
s.write('</tr>\n')
rows = rows[1:]
# Other rows:
for row_class, row in zip(cycle(["row-a", "row-b"]), rows):
s.write('<tr class ="{}">\n'.format(row_class))
self._html_table_row(s, row, header=False)
s.write('</tr>\n')
s.write('</tbody>\n</table>\n</div>')
return s.getvalue()
def _html_table_row(self, file, row, header=False):
r"""
Write table row
Helper method used by the :meth:`_html_` method.
INPUT:
- ``file`` -- file-like object. The table row data will be
written to it.
- ``row`` -- a list with the same number of entries as each row
of the table.
- ``header`` -- bool (default False). If True, treat this as a
header row, using ``<th>`` instead of ``<td>``.
OUTPUT:
This method returns nothing. All output is written to ``file``.
Strings are written verbatim unless they seem to be LaTeX
code, in which case they are enclosed in a ``script`` tag
appropriate for MathJax. Sage objects are printed using their
LaTeX representations.
EXAMPLES::
sage: T = table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]])
sage: from io import StringIO
sage: s = StringIO()
sage: T._html_table_row(s, ['a', 2, '$x$'])
sage: print(s.getvalue())
<td style="text-align:left">a</td>
<td style="text-align:left">\(2\)</td>
<td style="text-align:left">\(x\)</td>
"""
from sage.plot.all import Graphics
from .latex import latex
from .html import math_parse
import types
if isinstance(row, types.GeneratorType):
row = list(row)
elif not isinstance(row, (list, tuple)):
row = [row]
align_char = self._options['align'][0] # 'l', 'c', 'r'
if align_char == 'l':
style = 'text-align:left'
elif align_char == 'c':
style = 'text-align:center'
elif align_char == 'r':
style = 'text-align:right'
else:
style = ''
style_attr = f' style="{style}"' if style else ''
column_tag = f'<th{style_attr}>%s</th>\n' if header else f'<td{style_attr}>%s</td>\n'
if self._options['header_column']:
first_column_tag = '<th class="ch"{style_attr}>%s</th>\n' if header else '<td class="ch"{style_attr}>%s</td>\n'
else:
first_column_tag = column_tag
# first entry of row
entry = row[0]
if isinstance(entry, Graphics):
file.write(first_column_tag % entry.show(linkmode = True))
elif isinstance(entry, str):
file.write(first_column_tag % math_parse(entry))
else:
file.write(first_column_tag % (r'\(%s\)' % latex(entry)))
# other entries
for column in range(1, len(row)):
if isinstance(row[column], Graphics):
file.write(column_tag % row[column].show(linkmode = True))
elif isinstance(row[column], str):
file.write(column_tag % math_parse(row[column]))
else:
file.write(column_tag % (r'\(%s\)' % latex(row[column]))) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/table.py | 0.920767 | 0.877004 | table.py | pypi |
class MultiplexFunction(object):
"""
A simple wrapper object for functions that are called on a list of
objects.
"""
def __init__(self, multiplexer, name):
"""
EXAMPLES::
sage: from sage.misc.object_multiplexer import Multiplex, MultiplexFunction
sage: m = Multiplex(1,1/2)
sage: f = MultiplexFunction(m,'str')
sage: f
<sage.misc.object_multiplexer.MultiplexFunction object at 0x...>
"""
self.multiplexer = multiplexer
self.name = name
def __call__(self, *args, **kwds):
"""
EXAMPLES::
sage: from sage.misc.object_multiplexer import Multiplex, MultiplexFunction
sage: m = Multiplex(1,1/2)
sage: f = MultiplexFunction(m,'str')
sage: f()
('1', '1/2')
"""
l = []
for child in self.multiplexer.children:
l.append(getattr(child, self.name)(*args, **kwds))
if all(e is None for e in l):
return None
else:
return tuple(l)
class Multiplex(object):
"""
Object for a list of children such that function calls on this
new object implies that the same function is called on all
children.
"""
def __init__(self, *args):
"""
EXAMPLES::
sage: from sage.misc.object_multiplexer import Multiplex
sage: m = Multiplex(1,1/2)
sage: m.str()
('1', '1/2')
"""
self.children = [arg for arg in args if arg is not None]
def __getattr__(self, name):
"""
EXAMPLES::
sage: from sage.misc.object_multiplexer import Multiplex
sage: m = Multiplex(1,1/2)
sage: m.str
<sage.misc.object_multiplexer.MultiplexFunction object at 0x...>
sage: m.trait_names
Traceback (most recent call last):
...
AttributeError: 'Multiplex' has no attribute 'trait_names'
"""
if name.startswith("__") or name == "trait_names":
raise AttributeError("'Multiplex' has no attribute '%s'" % name)
return MultiplexFunction(self, name) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/object_multiplexer.py | 0.735831 | 0.291 | object_multiplexer.py | pypi |
r"""
Random Numbers with Python API
AUTHORS:
-- Carl Witty (2008-03): new file
This module has the same functions as the Python standard module
\module{random}, but uses the current \sage random number state from
\module{sage.misc.randstate} (so that it can be controlled by the same
global random number seeds).
The functions here are less efficient than the functions in \module{random},
because they look up the current random number state on each call.
If you are going to be creating many random numbers in a row, it is
better to use the functions in \module{sage.misc.randstate} directly.
Here is an example:
(The imports on the next two lines are not necessary, since
\function{randrange} and \function{current_randstate} are both available
by default at the \code{sage:} prompt; but you would need them
to run these examples inside a module.) ::
sage: from sage.misc.prandom import randrange
sage: from sage.misc.randstate import current_randstate
sage: def test1():
....: return sum([randrange(100) for i in range(100)])
sage: def test2():
....: randrange = current_randstate().python_random().randrange
....: return sum([randrange(100) for i in range(100)])
Test2 will be slightly faster than test1, but they give the same answer::
sage: with seed(0): test1()
5169
sage: with seed(0): test2()
5169
sage: with seed(1): test1()
5097
sage: with seed(1): test2()
5097
sage: timeit('test1()') # random
625 loops, best of 3: 590 us per loop
sage: timeit('test2()') # random
625 loops, best of 3: 460 us per loop
The docstrings for the functions in this file are mostly copied from
Python's \file{random.py}, so those docstrings are "Copyright (c)
2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation;
All Rights Reserved" and are available under the terms of the
Python Software Foundation License Version 2.
"""
# We deliberately omit "seed" and several other seed-related functions...
# setting seeds should only be done through sage.misc.randstate .
from sage.misc.randstate import current_randstate
def _pyrand():
r"""
A tiny private helper function to return an instance of
random.Random from the current \sage random number state.
Only for use in prandom.py; other modules should use
current_randstate().python_random().
EXAMPLES::
sage: set_random_seed(0)
sage: from sage.misc.prandom import _pyrand
sage: _pyrand()
<...random.Random object at 0x...>
sage: _pyrand().getrandbits(10)
114L
"""
return current_randstate().python_random()
def getrandbits(k):
r"""
getrandbits(k) -> x. Generates a long int with k random bits.
EXAMPLES::
sage: getrandbits(10) in range(2^10)
True
sage: getrandbits(200) in range(2^200)
True
sage: getrandbits(4) in range(2^4)
True
"""
return _pyrand().getrandbits(k)
def randrange(start, stop=None, step=1):
r"""
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
EXAMPLES::
sage: s = randrange(0, 100, 11)
sage: 0 <= s < 100
True
sage: s % 11
0
sage: 5000 <= randrange(5000, 5100) < 5100
True
sage: s = [randrange(0, 2) for i in range(15)]
sage: all(t in [0, 1] for t in s)
True
sage: s = randrange(0, 1000000, 1000)
sage: 0 <= s < 1000000
True
sage: s % 1000
0
sage: -100 <= randrange(-100, 10) < 10
True
"""
return _pyrand().randrange(start, stop, step)
def randint(a, b):
r"""
Return random integer in range [a, b], including both end points.
EXAMPLES::
sage: s = [randint(0, 2) for i in range(15)]; s # random
[0, 1, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 0, 2, 2]
sage: all(t in [0, 1, 2] for t in s)
True
sage: -100 <= randint(-100, 10) <= 10
True
"""
return _pyrand().randint(a, b)
def choice(seq):
r"""
Choose a random element from a non-empty sequence.
EXAMPLES::
sage: s = [choice(list(primes(10, 100))) for i in range(5)]; s # random
[17, 47, 11, 31, 47]
sage: all(t in primes(10, 100) for t in s)
True
"""
return _pyrand().choice(seq)
def shuffle(x):
r"""
x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the sage.misc.random.random.
EXAMPLES::
sage: shuffle([1 .. 10])
"""
return _pyrand().shuffle(x)
def sample(population, k):
r"""
Choose k unique random elements from a population sequence.
Return a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use xrange as an
argument (in Python 2) or range (in Python 3). This is especially
fast and space efficient for sampling from a large population:
sample(range(10000000), 60)
EXAMPLES::
sage: from sage.misc.misc import is_sublist
sage: l = ["Here", "I", "come", "to", "save", "the", "day"]
sage: s = sample(l, 3); s # random
['Here', 'to', 'day']
sage: is_sublist(sorted(s), sorted(l))
True
sage: len(s)
3
sage: s = sample(range(2^30), 7); s # random
[357009070, 558990255, 196187132, 752551188, 85926697, 954621491, 624802848]
sage: len(s)
7
sage: all(t in range(2^30) for t in s)
True
"""
return _pyrand().sample(population, k)
def random():
r"""
Get the next random number in the range [0.0, 1.0).
EXAMPLES::
sage: sample = [random() for i in [1 .. 4]]; sample # random
[0.111439293741037, 0.5143475134191677, 0.04468968524815642, 0.332490606442413]
sage: all(0.0 <= s <= 1.0 for s in sample)
True
"""
return _pyrand().random()
def uniform(a, b):
r"""
Get a random number in the range [a, b).
Equivalent to \code{a + (b-a) * random()}.
EXAMPLES::
sage: s = uniform(0, 1); s # random
0.111439293741037
sage: 0.0 <= s <= 1.0
True
sage: s = uniform(e, pi); s # random
0.5143475134191677*pi + 0.48565248658083227*e
sage: bool(e <= s <= pi)
True
"""
return _pyrand().uniform(a, b)
def betavariate(alpha, beta):
r"""
Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
EXAMPLES::
sage: s = betavariate(0.1, 0.9); s # random
9.75087916621299e-9
sage: 0.0 <= s <= 1.0
True
sage: s = betavariate(0.9, 0.1); s # random
0.941890400939253
sage: 0.0 <= s <= 1.0
True
"""
return _pyrand().betavariate(alpha, beta)
def expovariate(lambd):
r"""
Exponential distribution.
lambd is 1.0 divided by the desired mean. (The parameter would be
called "lambda", but that is a reserved word in Python.) Returned
values range from 0 to positive infinity.
EXAMPLES::
sage: sample = [expovariate(0.001) for i in range(3)]; sample # random
[118.152309288166, 722.261959038118, 45.7190543690470]
sage: all(s >= 0.0 for s in sample)
True
sage: sample = [expovariate(1.0) for i in range(3)]; sample # random
[0.404201816061304, 0.735220464997051, 0.201765578600627]
sage: all(s >= 0.0 for s in sample)
True
sage: sample = [expovariate(1000) for i in range(3)]; sample # random
[0.0012068700332283973, 8.340929747302108e-05, 0.00219877067980605]
sage: all(s >= 0.0 for s in sample)
True
"""
return _pyrand().expovariate(lambd)
def gammavariate(alpha, beta):
r"""
Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
EXAMPLES::
sage: sample = gammavariate(1.0, 3.0); sample # random
6.58282586130638
sage: sample > 0
True
sage: sample = gammavariate(3.0, 1.0); sample # random
3.07801512341612
sage: sample > 0
True
"""
return _pyrand().gammavariate(alpha, beta)
def gauss(mu, sigma):
r"""
Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function, but is not
thread-safe.
EXAMPLES::
sage: [gauss(0, 1) for i in range(3)] # random
[0.9191011757657915, 0.7744526756246484, 0.8638996866800877]
sage: [gauss(0, 100) for i in range(3)] # random
[24.916051749154448, -62.99272061579273, -8.1993122536718...]
sage: [gauss(1000, 10) for i in range(3)] # random
[998.7590700045661, 996.1087338511692, 1010.1256817458031]
"""
return _pyrand().gauss(mu, sigma)
def lognormvariate(mu, sigma):
r"""
Log normal distribution.
If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.
EXAMPLES::
sage: [lognormvariate(100, 10) for i in range(3)] # random
[2.9410355688290246e+37, 2.2257548162070125e+38, 4.142299451717446e+43]
"""
return _pyrand().lognormvariate(mu, sigma)
def normalvariate(mu, sigma):
r"""
Normal distribution.
mu is the mean, and sigma is the standard deviation.
EXAMPLES::
sage: [normalvariate(0, 1) for i in range(3)] # random
[-1.372558980559407, -1.1701670364898928, 0.04324100555110143]
sage: [normalvariate(0, 100) for i in range(3)] # random
[37.45695875041769, 159.6347743233298, 124.1029321124009]
sage: [normalvariate(1000, 10) for i in range(3)] # random
[1008.5303090383741, 989.8624892644895, 985.7728921150242]
"""
return _pyrand().normalvariate(mu, sigma)
def vonmisesvariate(mu, kappa):
r"""
Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
EXAMPLES::
sage: sample = [vonmisesvariate(1.0r, 3.0r) for i in range(1, 5)]; sample # random
[0.898328639355427, 0.6718030007041281, 2.0308777524813393, 1.714325253725145]
sage: all(s >= 0.0 for s in sample)
True
"""
return _pyrand().vonmisesvariate(mu, kappa)
def paretovariate(alpha):
r"""
Pareto distribution. alpha is the shape parameter.
EXAMPLES::
sage: sample = [paretovariate(3) for i in range(1, 5)]; sample # random
[1.0401699394233033, 1.2722080162636495, 1.0153564009379579, 1.1442323078983077]
sage: all(s >= 1.0 for s in sample)
True
"""
return _pyrand().paretovariate(alpha)
def weibullvariate(alpha, beta):
r"""
Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.
EXAMPLES::
sage: sample = [weibullvariate(1, 3) for i in range(1, 5)]; sample # random
[0.49069775546342537, 0.8972185564611213, 0.357573846531942, 0.739377255516847]
sage: all(s >= 0.0 for s in sample)
True
"""
return _pyrand().weibullvariate(alpha, beta) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/prandom.py | 0.815196 | 0.823683 | prandom.py | pypi |
"Flatten nested lists"
import sys
def flatten(in_list, ltypes=(list, tuple), max_level=sys.maxsize):
"""
Flatten a nested list.
INPUT:
- ``in_list`` -- a list or tuple
- ``ltypes`` -- optional list of particular types to flatten
- ``max_level`` -- the maximum level to flatten
OUTPUT:
a flat list of the entries of ``in_list``
EXAMPLES::
sage: flatten([[1,1],[1],2])
[1, 1, 1, 2]
sage: flatten([[1,2,3], (4,5), [[[1],[2]]]])
[1, 2, 3, 4, 5, 1, 2]
sage: flatten([[1,2,3], (4,5), [[[1],[2]]]],max_level=1)
[1, 2, 3, 4, 5, [[1], [2]]]
sage: flatten([[[3],[]]],max_level=0)
[[[3], []]]
sage: flatten([[[3],[]]],max_level=1)
[[3], []]
sage: flatten([[[3],[]]],max_level=2)
[3]
In the following example, the vector is not flattened because
it is not given in the ``ltypes`` input. ::
sage: flatten((['Hi',2,vector(QQ,[1,2,3])],(4,5,6)))
['Hi', 2, (1, 2, 3), 4, 5, 6]
We give the vector type and then even the vector gets flattened::
sage: tV = sage.modules.vector_rational_dense.Vector_rational_dense
sage: flatten((['Hi',2,vector(QQ,[1,2,3])], (4,5,6)),
....: ltypes=(list, tuple, tV))
['Hi', 2, 1, 2, 3, 4, 5, 6]
We flatten a finite field. ::
sage: flatten(GF(5))
[0, 1, 2, 3, 4]
sage: flatten([GF(5)])
[Finite Field of size 5]
sage: tGF = type(GF(5))
sage: flatten([GF(5)], ltypes = (list, tuple, tGF))
[0, 1, 2, 3, 4]
Degenerate cases::
sage: flatten([[],[]])
[]
sage: flatten([[[]]])
[]
"""
index = 0
current_level = 0
new_list = [x for x in in_list]
level_list = [0] * len(in_list)
while index < len(new_list):
len_v = True
while isinstance(new_list[index], ltypes) and current_level < max_level:
v = list(new_list[index])
len_v = len(v)
new_list[index : index + 1] = v
old_level = level_list[index]
level_list[index : index + 1] = [0] * len_v
if len_v:
current_level += 1
level_list[index + len_v - 1] = old_level + 1
else:
current_level -= old_level
index -= 1
break
# If len_v == 0, then index points to a previous element, so we
# do not need to do anything.
if len_v:
current_level -= level_list[index]
index += 1
return new_list | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/misc/flatten.py | 0.563138 | 0.576959 | flatten.py | pypi |
import os
import importlib.util
from sage_setup.find import installed_files_by_module, get_extensions
def _remove(file_set, module_base, to_remove):
"""
Helper to remove files from a set of filenames.
INPUT:
- ``file_set`` -- a set of filenames.
- ``module_base`` -- string. Name of a Python package/module.
- ``to_remove`` -- list/tuple/iterable of strings. Either
filenames or extensions (starting with ``'.'``)
OUTPUT:
This function does not return anything. The ``file_set`` parameter
is modified in place.
EXAMPLES::
sage: files = set(['a/b/c.py', 'a/b/d.py', 'a/b/c.pyx'])
sage: from sage_setup.clean import _remove
sage: _remove(files, 'a.b', ['c.py', 'd.py'])
sage: files
{'a/b/c.pyx'}
sage: files = set(['a/b/c.py', 'a/b/d.py', 'a/b/c.pyx'])
sage: _remove(files, 'a.b.c', ['.py', '.pyx'])
sage: files
{'a/b/d.py'}
"""
path = os.path.join(*module_base.split('.'))
for filename in to_remove:
if filename.startswith('.'):
filename = path + filename
else:
filename = os.path.join(path, filename)
remove = [filename]
remove.append(importlib.util.cache_from_source(filename))
file_set.difference_update(remove)
def _find_stale_files(site_packages, python_packages, python_modules, ext_modules, data_files, nobase_data_files=()):
"""
Find stale files
This method lists all files installed and then subtracts the ones
which are intentionally being installed.
EXAMPLES:
It is crucial that only truly stale files are being found, of
course. We check that when the doctest is being run, that is,
after installation, there are no stale files::
sage: from sage.env import SAGE_SRC, SAGE_LIB, SAGE_ROOT
sage: from sage_setup.find import _cythonized_dir
sage: cythonized_dir = _cythonized_dir(SAGE_SRC)
sage: from sage_setup.find import find_python_sources, find_extra_files
sage: python_packages, python_modules, cython_modules = find_python_sources(
....: SAGE_SRC, ['sage', 'sage_setup'])
sage: extra_files = list(find_extra_files(SAGE_SRC,
....: ['sage', 'sage_setup'], cythonized_dir, []).items())
sage: from sage_setup.clean import _find_stale_files
TODO: move ``module_list.py`` into ``sage_setup`` and also check
extension modules::
sage: stale_iter = _find_stale_files(SAGE_LIB, python_packages, python_modules, [], extra_files)
sage: from sage.misc.sageinspect import loadable_module_extension
sage: skip_extensions = (loadable_module_extension(),)
sage: for f in stale_iter:
....: if f.endswith(skip_extensions): continue
....: if '/ext_data/' in f: continue
....: print('Found stale file: ' + f)
"""
PYMOD_EXTS = get_extensions('source') + get_extensions('bytecode')
CEXTMOD_EXTS = get_extensions('extension')
INIT_FILES = tuple('__init__' + x for x in PYMOD_EXTS)
module_files = installed_files_by_module(site_packages, ['sage'])
for mod in python_packages:
try:
files = module_files[mod]
except KeyError:
# the source module "mod" has not been previously installed, fine.
continue
_remove(files, mod, INIT_FILES)
for mod in python_modules:
try:
files = module_files[mod]
except KeyError:
continue
_remove(files, mod, PYMOD_EXTS)
for ext in ext_modules:
mod = ext.name
try:
files = module_files[mod]
except KeyError:
continue
_remove(files, mod, CEXTMOD_EXTS)
# Convert data_files to a set
installed_files = set()
for dir, files in data_files:
for f in files:
installed_files.add(os.path.join(dir, os.path.basename(f)))
for dir, files in nobase_data_files:
for f in files:
installed_files.add(f)
for files in module_files.values():
for f in files:
if f not in installed_files:
yield f
def clean_install_dir(site_packages, python_packages, python_modules, ext_modules, data_files, nobase_data_files):
"""
Delete all modules that are **not** being installed
If you switch branches it is common to (re)move the source for an
already installed module. Subsequent rebuilds will leave the stale
module in the install directory, which can break programs that try
to import all modules. In particular, the Sphinx autodoc builder
does this and is susceptible to hard-to-reproduce failures that
way. Hence we must make sure to delete all stale modules.
INPUT:
- ``site_packages`` -- the root Python path where the Sage library
is being installed.
- ``python_packages`` -- list of pure Python packages (directories
with ``__init__.py``).
- ``python_modules`` -- list of pure Python modules.
- ``ext_modules`` -- list of distutils ``Extension`` classes. The
output of ``cythonize``.
- ``data_files`` -- a list of (installation directory, files) pairs,
like the ``data_files`` argument to distutils' ``setup()``. Only
the basename of the files is used.
- ``nobase_data_files`` -- a list of (installation directory, files)
pairs. The files are expected to be in a subdirectory of the
installation directory; the filenames are used as is.
"""
stale_file_iter = _find_stale_files(
site_packages, python_packages, python_modules, ext_modules, data_files, nobase_data_files)
for f in stale_file_iter:
f = os.path.join(site_packages, f)
print('Cleaning up stale file: {0}'.format(f))
os.unlink(f) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/clean.py | 0.415136 | 0.251441 | clean.py | pypi |
from setuptools.extension import Extension
from sage.misc.package import list_packages
all_packages = list_packages(local=True)
class CythonizeExtension(Extension):
"""
A class for extensions which are only cythonized, but not built.
The file ``src/setup.py`` contains some logic to check the
``skip_build`` attribute of extensions.
EXAMPLES::
sage: from sage_setup.optional_extension import CythonizeExtension
sage: ext = CythonizeExtension("foo", ["foo.c"])
sage: ext.skip_build
True
"""
skip_build = True
def is_package_installed_and_updated(pkg):
from sage.misc.package import is_package_installed
try:
pkginfo = all_packages[pkg]
except KeyError:
# Might be an installed old-style package
condition = is_package_installed(pkg)
else:
condition = (pkginfo.installed_version == pkginfo.remote_version)
return condition
def OptionalExtension(*args, **kwds):
"""
If some condition (see INPUT) is satisfied, return an ``Extension``.
Otherwise, return a ``CythonizeExtension``.
Typically, the condition is some optional package or something
depending on the operating system.
INPUT:
- ``condition`` -- (boolean) the actual condition
- ``package`` -- (string) the condition is that this package is
installed and up-to-date (only used if ``condition`` is not given)
EXAMPLES::
sage: from sage_setup.optional_extension import OptionalExtension
sage: ext = OptionalExtension("foo", ["foo.c"], condition=False)
sage: print(ext.__class__.__name__)
CythonizeExtension
sage: ext = OptionalExtension("foo", ["foo.c"], condition=True)
sage: print(ext.__class__.__name__)
Extension
sage: ext = OptionalExtension("foo", ["foo.c"], package="no_such_package")
sage: print(ext.__class__.__name__)
CythonizeExtension
sage: ext = OptionalExtension("foo", ["foo.c"], package="gap")
sage: print(ext.__class__.__name__)
Extension
"""
try:
condition = kwds.pop("condition")
except KeyError:
pkg = kwds.pop("package")
condition = is_package_installed_and_updated(pkg)
if condition:
return Extension(*args, **kwds)
else:
return CythonizeExtension(*args, **kwds) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/optional_extension.py | 0.762513 | 0.18567 | optional_extension.py | pypi |
import os
import sys
import time
keep_going = False
def run_command(cmd):
"""
INPUT:
- ``cmd`` -- a string; a command to run
OUTPUT: prints ``cmd`` to the console and then runs
``os.system(cmd)``.
"""
print(cmd)
sys.stdout.flush()
return os.system(cmd)
def apply_func_progress(p):
"""
Given a triple p consisting of a function, value and a string,
output the string and apply the function to the value.
The string could for example be some progress indicator.
This exists solely because we can't pickle an anonymous function
in execute_list_of_commands_in_parallel below.
"""
sys.stdout.write(p[2])
sys.stdout.flush()
return p[0](p[1])
def execute_list_of_commands_in_parallel(command_list, nthreads):
"""
Execute the given list of commands, possibly in parallel, using
``nthreads`` threads. Terminates ``setup.py`` with an exit code
of 1 if an error occurs in any subcommand.
INPUT:
- ``command_list`` -- a list of commands, each given as a pair of
the form ``[function, argument]`` of a function to call and its
argument
- ``nthreads`` -- integer; number of threads to use
WARNING: commands are run roughly in order, but of course successive
commands may be run at the same time.
"""
# Add progress indicator strings to the command_list
N = len(command_list)
progress_fmt = "[{:%i}/{}] " % len(str(N))
for i in range(N):
progress = progress_fmt.format(i+1, N)
command_list[i] = command_list[i] + (progress,)
from multiprocessing import Pool
# map_async handles KeyboardInterrupt correctly if an argument is
# given to get(). Plain map() and apply_async() do not work
# correctly, see Trac #16113.
pool = Pool(nthreads)
result = pool.map_async(apply_func_progress, command_list, 1).get(99999)
pool.close()
pool.join()
process_command_results(result)
def process_command_results(result_values):
error = None
for r in result_values:
if r:
print("Error running command, failed with status %s."%r)
if not keep_going:
sys.exit(1)
error = r
if error:
sys.exit(1)
def execute_list_of_commands(command_list):
"""
INPUT:
- ``command_list`` -- a list of strings or pairs
OUTPUT:
For each entry in command_list, we attempt to run the command.
If it is a string, we call ``os.system()``. If it is a pair [f, v],
we call f(v).
If the environment variable :envvar:`SAGE_NUM_THREADS` is set, use
that many threads.
"""
t = time.time()
# Determine the number of threads from the environment variable
# SAGE_NUM_THREADS, which is set automatically by sage-env
try:
nthreads = int(os.environ['SAGE_NUM_THREADS'])
except KeyError:
nthreads = 1
# normalize the command_list to handle strings correctly
command_list = [ [run_command, x] if isinstance(x, str) else x for x in command_list ]
# No need for more threads than there are commands, but at least one
nthreads = min(len(command_list), nthreads)
nthreads = max(1, nthreads)
def plural(n,noun):
if n == 1:
return "1 %s"%noun
return "%i %ss"%(n,noun)
print("Executing %s (using %s)"%(plural(len(command_list),"command"), plural(nthreads,"thread")))
execute_list_of_commands_in_parallel(command_list, nthreads)
print("Time to execute %s: %.2f seconds."%(plural(len(command_list),"command"), time.time() - t)) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/run_parallel.py | 0.511473 | 0.419707 | run_parallel.py | pypi |
from __future__ import print_function, absolute_import
from .utils import je, reindent_lines as ri
def string_of_addr(a):
r"""
An address or a length from a parameter specification may be
either None, an integer, or a MemoryChunk. If the address or
length is an integer or a MemoryChunk, this function will convert
it to a string giving an expression that will evaluate to the correct
address or length. (See the docstring for params_gen for more
information on parameter specifications.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc_code = MemoryChunkConstants('code', ty_int)
sage: string_of_addr(mc_code)
'*code++'
sage: string_of_addr(42r)
'42'
"""
if isinstance(a, int):
return str(a)
assert(isinstance(a, MemoryChunk))
return '*%s++' % a.name
class MemoryChunk(object):
r"""
Memory chunks control allocation, deallocation, initialization,
etc. of the vectors and objects in the interpreter. Basically,
there is one memory chunk per argument to the C interpreter.
There are three "generic" varieties of memory chunk: "constants",
"arguments", and "scratch". These are named after their most
common use, but they could be used for other things in some
interpreters.
All three kinds of chunks are allocated in the wrapper class.
Constants are initialized when the wrapper is constructed;
arguments are initialized in the __call__ method, from the
caller's arguments. "scratch" chunks are not initialized at all;
they are used for scratch storage (often, but not necessarily, for
a stack) in the interpreter.
Interpreters which need memory chunks that don't fit into these
categories can create new subclasses of MemoryChunk.
"""
def __init__(self, name, storage_type):
r"""
Initialize an instance of MemoryChunk.
This sets the properties "name" (the name of this memory chunk;
used in generated variable names, etc.) and "storage_type",
which is a StorageType object.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: mc.name
'args'
sage: mc.storage_type is ty_mpfr
True
"""
self.name = name
self.storage_type = storage_type
def __repr__(self):
r"""
Give a string representation of this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: mc
{MC:args}
sage: mc.__repr__()
'{MC:args}'
"""
return '{MC:%s}' % self.name
def declare_class_members(self):
r"""
Return a string giving the declarations of the class members
in a wrapper class for this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: mc.declare_class_members()
u' cdef int _n_args\n cdef mpfr_t* _args\n'
"""
return self.storage_type.declare_chunk_class_members(self.name)
def init_class_members(self):
r"""
Return a string to be put in the __init__ method of a wrapper
class using this memory chunk, to initialize the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: print(mc.init_class_members())
count = args['args']
self._n_args = count
self._args = <mpfr_t*>check_allocarray(self._n_args, sizeof(mpfr_t))
for i in range(count):
mpfr_init2(self._args[i], self.domain.prec())
<BLANKLINE>
"""
return ""
def dealloc_class_members(self):
r"""
Return a string to be put in the __dealloc__ method of a wrapper
class using this memory chunk, to deallocate the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: print(mc.dealloc_class_members())
if self._args:
for i in range(self._n_args):
mpfr_clear(self._args[i])
sig_free(self._args)
<BLANKLINE>
"""
return ""
def declare_parameter(self):
r"""
Return the string to use to declare the interpreter parameter
corresponding to this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: mc.declare_parameter()
'mpfr_t* args'
"""
return '%s %s' % (self.storage_type.c_ptr_type(), self.name)
def declare_call_locals(self):
r"""
Return a string to put in the __call__ method of a wrapper
class using this memory chunk, to allocate local variables.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkRRRetval('retval', ty_mpfr)
sage: mc.declare_call_locals()
u' cdef RealNumber retval = (self.domain)()\n'
"""
return ""
def pass_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkConstants('constants', ty_mpfr)
sage: mc.pass_argument()
'self._constants'
"""
raise NotImplementedError
def pass_call_c_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter, for use in the call_c method.
Almost always the same as pass_argument.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkConstants('constants', ty_mpfr)
sage: mc.pass_call_c_argument()
'self._constants'
"""
return self.pass_argument()
def needs_cleanup_on_error(self):
r"""
In an interpreter that can terminate prematurely (due to an
exception from calling Python code, or divide by zero, or
whatever) it will just return at the end of the current instruction,
skipping the rest of the program. Thus, it may still have
values pushed on the stack, etc.
This method returns True if this memory chunk is modified by the
interpreter and needs some sort of cleanup when an error happens.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkConstants('constants', ty_mpfr)
sage: mc.needs_cleanup_on_error()
False
"""
return False
def is_stack(self):
r"""
Says whether this memory chunk is a stack. This affects code
generation for instructions using this memory chunk.
It would be nicer to make this object-oriented somehow, so
that the code generator called MemoryChunk methods instead of
using::
if ch.is_stack():
... hardcoded stack code
else:
... hardcoded non-stack code
but that hasn't been done yet.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkScratch('scratch', ty_mpfr)
sage: mc.is_stack()
False
sage: mc = MemoryChunkScratch('stack', ty_mpfr, is_stack=True)
sage: mc.is_stack()
True
"""
return False
def is_python_refcounted_stack(self):
r"""
Says whether this memory chunk refers to a stack where the entries
need to be INCREF/DECREF'ed.
It would be nice to make this object-oriented, so that the
code generator called MemoryChunk methods to do the potential
INCREF/DECREF and didn't have to explicitly test
is_python_refcounted_stack.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkScratch('args', ty_python)
sage: mc.is_python_refcounted_stack()
False
sage: mc = MemoryChunkScratch('args', ty_python, is_stack=True)
sage: mc.is_python_refcounted_stack()
True
sage: mc = MemoryChunkScratch('args', ty_mpfr, is_stack=True)
sage: mc.is_python_refcounted_stack()
False
"""
return self.is_stack() and self.storage_type.python_refcounted()
class MemoryChunkLonglivedArray(MemoryChunk):
r"""
MemoryChunkLonglivedArray is a subtype of MemoryChunk that deals
with memory chunks that are both 1) allocated as class members (rather
than being allocated in __call__) and 2) are arrays.
"""
def init_class_members(self):
r"""
Return a string to be put in the __init__ method of a wrapper
class using this memory chunk, to initialize the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_double)
sage: print(mc.init_class_members())
count = args['args']
self._n_args = count
self._args = <double*>check_allocarray(self._n_args, sizeof(double))
<BLANKLINE>
"""
return je(ri(0, """
count = args['{{ myself.name }}']
{% print(myself.storage_type.alloc_chunk_data(myself.name, 'count')) %}
"""), myself=self)
def dealloc_class_members(self):
r"""
Return a string to be put in the __dealloc__ method of a wrapper
class using this memory chunk, to deallocate the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: print(mc.dealloc_class_members())
if self._args:
for i in range(self._n_args):
mpfr_clear(self._args[i])
sig_free(self._args)
<BLANKLINE>
"""
return self.storage_type.dealloc_chunk_data(self.name)
def pass_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkConstants('constants', ty_mpfr)
sage: mc.pass_argument()
'self._constants'
"""
return 'self._%s' % self.name
class MemoryChunkConstants(MemoryChunkLonglivedArray):
r"""
MemoryChunkConstants is a subtype of MemoryChunkLonglivedArray.
MemoryChunkConstants chunks have their contents set in the
wrapper's __init__ method (and not changed afterward).
"""
def init_class_members(self):
r"""
Return a string to be put in the __init__ method of a wrapper
class using this memory chunk, to initialize the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkConstants('constants', ty_mpfr)
sage: print(mc.init_class_members())
val = args['constants']
self._n_constants = len(val)
self._constants = <mpfr_t*>check_allocarray(self._n_constants, sizeof(mpfr_t))
for i in range(len(val)):
mpfr_init2(self._constants[i], self.domain.prec())
for i in range(len(val)):
rn = self.domain(val[i])
mpfr_set(self._constants[i], rn.value, MPFR_RNDN)
<BLANKLINE>
"""
return je(ri(0, """
val = args['{{ myself.name }}']
{% print(myself.storage_type.alloc_chunk_data(myself.name, 'len(val)')) %}
for i in range(len(val)):
{{ myself.storage_type.assign_c_from_py('self._%s[i]' % myself.name, 'val[i]') | i(12) }}
"""), myself=self)
class MemoryChunkArguments(MemoryChunkLonglivedArray):
r"""
MemoryChunkArguments is a subtype of MemoryChunkLonglivedArray,
for dealing with arguments to the wrapper's ``__call__`` method.
Currently the ``__call__`` method is declared to take a varargs
`*args` argument tuple. We assume that the MemoryChunk named `args`
will deal with that tuple.
"""
def setup_args(self):
r"""
Handle the arguments of __call__ -- copy them into a pre-allocated
array, ready to pass to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: print(mc.setup_args())
cdef mpfr_t* c_args = self._args
cdef int i
for i from 0 <= i < len(args):
rn = self.domain(args[i])
mpfr_set(self._args[i], rn.value, MPFR_RNDN)
<BLANKLINE>
"""
return je(ri(0, """
cdef {{ myself.storage_type.c_ptr_type() }} c_args = self._args
cdef int i
for i from 0 <= i < len(args):
{{ myself.storage_type.assign_c_from_py('self._args[i]', 'args[i]') | i(4) }}
"""), myself=self)
def pass_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkArguments('args', ty_mpfr)
sage: mc.pass_argument()
'c_args'
"""
return 'c_args'
class MemoryChunkScratch(MemoryChunkLonglivedArray):
r"""
MemoryChunkScratch is a subtype of MemoryChunkLonglivedArray
for dealing with memory chunks that are allocated in the wrapper,
but only used in the interpreter -- stacks, scratch registers, etc.
(Currently these are only used as stacks.)
"""
def __init__(self, name, storage_type, is_stack=False):
r"""
Initialize an instance of MemoryChunkScratch.
Initializes the _is_stack property, as well as
the properties described in the documentation for
MemoryChunk.__init__.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkScratch('stack', ty_double, is_stack=True)
sage: mc.name
'stack'
sage: mc.storage_type is ty_double
True
sage: mc._is_stack
True
"""
super(MemoryChunkScratch, self).__init__(name, storage_type)
self._is_stack = is_stack
def is_stack(self):
r"""
Says whether this memory chunk is a stack. This affects code
generation for instructions using this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkScratch('stack', ty_mpfr, is_stack=True)
sage: mc.is_stack()
True
"""
return self._is_stack
def needs_cleanup_on_error(self):
r"""
In an interpreter that can terminate prematurely (due to an
exception from calling Python code, or divide by zero, or
whatever) it will just return at the end of the current instruction,
skipping the rest of the program. Thus, it may still have
values pushed on the stack, etc.
This method returns True if this memory chunk is modified by the
interpreter and needs some sort of cleanup when an error happens.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkScratch('registers', ty_python)
sage: mc.needs_cleanup_on_error()
True
"""
return self.storage_type.python_refcounted()
def handle_cleanup(self):
r"""
Handle the cleanup if the interpreter exits with an error.
For scratch/stack chunks that hold Python-refcounted values,
we assume that they are filled with NULL on every entry to the
interpreter. If the interpreter exited with an error, it may
have left values in the chunk, so we need to go through
the chunk and Py_CLEAR it.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkScratch('registers', ty_python)
sage: print(mc.handle_cleanup())
for i in range(self._n_registers):
Py_CLEAR(self._registers[i])
<BLANKLINE>
"""
# XXX This is a lot slower than it needs to be, because
# we don't have a "cdef int i" in scope here.
return je(ri(0, """
for i in range(self._n_{{ myself.name }}):
Py_CLEAR(self._{{ myself.name }}[i])
"""), myself=self) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/memory.py | 0.842766 | 0.44565 | memory.py | pypi |
from __future__ import print_function, absolute_import
import re
from .storage import ty_int
def params_gen(**chunks):
r"""
Instructions have a parameter specification that says where they get
their inputs and where their outputs go. Each parameter has
the same form: it is a triple (chunk, addr, len). The chunk says
where the parameter is read from/written to. The addr says which
value in the chunk is used. If the chunk is a stack chunk, then
addr must be null; the value will be read from/written to the top
of the stack. Otherwise, addr must be an integer, or another chunk;
if addr is another chunk, then the next value is read from that chunk
to be the address.
The len says how many values to read/write. It can be either None
(meaning to read/write only a single value), an integer, or
another chunk; if it is a chunk, then the next value is read from that
chunk to be the len. Note that specifying len changes the types
given to the instruction, so len=None is different than len=1 even
though both mean to use a single value.
These parameter specifications are cumbersome to write by hand, so
there's also a simple string format for them. This (curried)
function parses the simple string format and produces parameter
specifications. The params_gen function takes keyword arguments
mapping single-character names to memory chunks. The string format
uses these names. The params_gen function returns another function,
that takes two strings and returns a pair of lists of parameter
specifications.
Each string is the concatenation of arbitrarily many specifications.
Each specification consists of an address and a length. The
address is either a single character naming a stack chunk,
or a string of the form 'A[B]' where A names a non-stack chunk
and B names the code chunk. The length is either empty, or '@n'
for a number n (meaning to use that many arguments), or '@C', where
C is the code chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc_stack = MemoryChunkScratch('stack', ty_double, is_stack=True)
sage: mc_args = MemoryChunkArguments('args', ty_double)
sage: mc_code = MemoryChunkConstants('code', ty_int)
sage: pg = params_gen(D=mc_code, A=mc_args, S=mc_stack)
sage: pg('S', '')
([({MC:stack}, None, None)], [])
sage: pg('A[D]', '')
([({MC:args}, {MC:code}, None)], [])
sage: pg('S@5', '')
([({MC:stack}, None, 5)], [])
sage: pg('S@D', '')
([({MC:stack}, None, {MC:code})], [])
sage: pg('A[D]@D', '')
([({MC:args}, {MC:code}, {MC:code})], [])
sage: pg('SSS@D', 'A[D]S@D')
([({MC:stack}, None, None), ({MC:stack}, None, None), ({MC:stack}, None, {MC:code})], [({MC:args}, {MC:code}, None), ({MC:stack}, None, {MC:code})])
"""
def make_params(s):
p = []
s = s.strip()
while s:
chunk_code = s[0]
s = s[1:]
chunk = chunks[chunk_code]
addr = None
ch_len = None
# shouldn't hardcode 'code' here
if chunk.is_stack() or chunk.name == 'code':
pass
else:
m = re.match(r'\[(?:([0-9]+)|([a-zA-Z]))\]', s)
if m.group(1):
addr = int(m.group(1))
else:
ch = chunks[m.group(2)]
assert ch.storage_type is ty_int
addr = ch
s = s[m.end():].strip()
if len(s) and s[0] == '@':
m = re.match(r'@(?:([0-9]+)|([a-zA-Z]))', s)
if m.group(1):
ch_len = int(m.group(1))
else:
ch = chunks[m.group(2)]
assert ch.storage_type is ty_int
ch_len = ch
s = s[m.end():].strip()
p.append((chunk, addr, ch_len))
return p
def params(s_ins, s_outs):
ins = make_params(s_ins)
outs = make_params(s_outs)
return (ins, outs)
return params
class InstrSpec(object):
r"""
Each instruction in an interpreter is represented as an InstrSpec.
This contains all the information that we need to generate code
to interpret the instruction; it also is used to build the tables
that fast_callable uses, so this is the nexus point between
users of the interpreter (possibly pure Python) and the
generated C interpreter.
The underlying instructions are matched to the caller by name.
For instance, fast_callable assumes that if the interpreter has an
instruction named 'cos', then it will take a single argument,
return a single result, and implement the cos() function.
The print representation of an instruction (which will probably
only be used when doctesting this file) consists of the name,
a simplified stack effect, and the code (truncated if it's long).
The stack effect has two parts, the input and the output, separated
by '->'; the input shows what will be popped from the stack,
the output what will be placed on the stack. Each consists of
a sequence of 'S' and '*' characters, where 'S' refers to a single
argument and '*' refers to a variable number of arguments.
The code for an instruction is a small snippet of C code. It has
available variables 'i0', 'i1', ..., 'o0', 'o1', ...; one variable
for each input and output; its job is to assign values to the output
variables, based on the values of the input variables.
Normally, in an interpreter that uses doubles, each of the input
and output variables will be a double. If i0 actually represents
a variable number of arguments, then it will be a pointer to
double instead, and there will be another variable n_i0 giving
the actual number of arguments.
When instructions refer to auto-reference types, they actually
get a pointer to the data in its original location; it is
not copied into a local variable. Mostly, this makes no difference,
but there is one potential problem to be aware of. It is possible
for an output variable to point to the same object as an input
variable; in fact, this usually will happen when you're working
with the stack. If the instruction maps to a single function call,
then this is fine; the standard auto-reference implementations
(GMP, MPFR, etc.) are careful to allow having the input and output
be the same. But if the instruction maps to multiple function
calls, you may need to use a temporary variable.
Here's an example of this issue. Suppose you want to make an
instruction that does ``out = a+b*c``. You write code like this::
out = b*c
out = a+out
But out will actually share the same storage as a; so the first line
modifies a, and you actually end up computing 2*(b+c). The fix
is to only write to the output once, at the very end of your
instruction.
Instructions are also allowed to access memory chunks (other than
the stack and code) directly. They are available as C variables
with the same name as the chunk. This is useful if some type of
memory chunk doesn't fit well with the params_gen interface.
There are additional reference-counting rules that must be
followed if your interpreter operates on Python objects; these
rules are described in the docstring of the PythonInterpreter
class.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RDFInterpreter().pg
sage: InstrSpec('add', pg('SS','S'), code='o0 = i0+i1;')
add: SS->S = 'o0 = i0+i1;'
"""
def __init__(self, name, io, code=None, uses_error_handler=False,
handles_own_decref=False):
r"""
Initialize an InstrSpec.
INPUT:
- name -- the name of the instruction
- io -- a pair of lists of parameter specifications for I/O of the
instruction
- code -- a string containing a snippet of C code to read
from the input variables and write to the output variables
- uses_error_handler -- True if the instruction calls Python
and jumps to error: on a Python error
- handles_own_decref -- True if the instruction handles Python
objects and includes its own
reference-counting
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RDFInterpreter().pg
sage: InstrSpec('add', pg('SS','S'), code='o0 = i0+i1;')
add: SS->S = 'o0 = i0+i1;'
sage: instr = InstrSpec('py_call', pg('P[D]S@D', 'S'), code=('This is very complicated. ' + 'blah ' * 30)); instr
py_call: *->S = 'This is very compli... blah blah blah '
sage: instr.name
'py_call'
sage: instr.inputs
[({MC:py_constants}, {MC:code}, None), ({MC:stack}, None, {MC:code})]
sage: instr.outputs
[({MC:stack}, None, None)]
sage: instr.code
'This is very complicated. blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah '
sage: instr.parameters
['py_constants', 'n_inputs']
sage: instr.n_inputs
0
sage: instr.n_outputs
1
"""
self.name = name
self.inputs = io[0]
self.outputs = io[1]
self.uses_error_handler = uses_error_handler
self.handles_own_decref = handles_own_decref
if code is not None:
self.code = code
# XXX We assume that there is only one stack
n_inputs = 0
n_outputs = 0
in_effect = ''
out_effect = ''
p = []
for (ch, addr, len) in self.inputs:
if ch.is_stack():
if len is None:
n_inputs += 1
in_effect += 'S'
elif isinstance(len, int):
n_inputs += len
in_effect += 'S%d' % len
else:
p.append('n_inputs')
in_effect += '*'
else:
p.append(ch.name)
for (ch, addr, len) in self.outputs:
if ch.is_stack():
if len is None:
n_outputs += 1
out_effect += 'S'
elif isinstance(len, int):
n_outputs += len
out_effect += 'S%d' % len
else:
p.append('n_outputs')
out_effect += '*'
else:
p.append(ch.name)
self.parameters = p
self.n_inputs = n_inputs
self.n_outputs = n_outputs
self.in_effect = in_effect
self.out_effect = out_effect
def __repr__(self):
r"""
Produce a string representing a given instruction, consisting
of its name, a brief stack specification, and its code
(possibly abbreviated).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RDFInterpreter().pg
sage: InstrSpec('add', pg('SS','S'), code='o0 = i0+i1;')
add: SS->S = 'o0 = i0+i1;'
"""
rcode = repr(self.code)
if len(rcode) > 40:
rcode = rcode[:20] + '...' + rcode[-17:]
return '%s: %s->%s = %s' % \
(self.name, self.in_effect, self.out_effect, rcode)
# Now we have a series of helper functions that make it slightly easier
# to create instructions.
def instr_infix(name, io, op):
r"""
A helper function for creating instructions implemented by
a single infix binary operator.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RDFInterpreter().pg
sage: instr_infix('mul', pg('SS', 'S'), '*')
mul: SS->S = 'o0 = i0 * i1;'
"""
return InstrSpec(name, io, code='o0 = i0 %s i1;' % op)
def instr_funcall_2args(name, io, op):
r"""
A helper function for creating instructions implemented by
a two-argument function call.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RDFInterpreter().pg
sage: instr_funcall_2args('atan2', pg('SS', 'S'), 'atan2')
atan2: SS->S = 'o0 = atan2(i0, i1);'
"""
return InstrSpec(name, io, code='o0 = %s(i0, i1);' % op)
def instr_unary(name, io, op):
r"""
A helper function for creating instructions with one input
and one output.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RDFInterpreter().pg
sage: instr_unary('sin', pg('S','S'), 'sin(i0)')
sin: S->S = 'o0 = sin(i0);'
sage: instr_unary('neg', pg('S','S'), '-i0')
neg: S->S = 'o0 = -i0;'
"""
return InstrSpec(name, io, code='o0 = ' + op + ';')
def instr_funcall_2args_mpfr(name, io, op):
r"""
A helper function for creating MPFR instructions with two inputs
and one output.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RRInterpreter().pg
sage: instr_funcall_2args_mpfr('add', pg('SS','S'), 'mpfr_add')
add: SS->S = 'mpfr_add(o0, i0, i1, MPFR_RNDN);'
"""
return InstrSpec(name, io, code='%s(o0, i0, i1, MPFR_RNDN);' % op)
def instr_funcall_1arg_mpfr(name, io, op):
r"""
A helper function for creating MPFR instructions with one input
and one output.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = RRInterpreter().pg
sage: instr_funcall_1arg_mpfr('exp', pg('S','S'), 'mpfr_exp')
exp: S->S = 'mpfr_exp(o0, i0, MPFR_RNDN);'
"""
return InstrSpec(name, io, code='%s(o0, i0, MPFR_RNDN);' % op)
def instr_funcall_2args_mpc(name, io, op):
r"""
A helper function for creating MPC instructions with two inputs
and one output.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = CCInterpreter().pg
sage: instr_funcall_2args_mpc('add', pg('SS','S'), 'mpc_add')
add: SS->S = 'mpc_add(o0, i0, i1, MPC_RNDNN);'
"""
return InstrSpec(name, io, code='%s(o0, i0, i1, MPC_RNDNN);' % op)
def instr_funcall_1arg_mpc(name, io, op):
r"""
A helper function for creating MPC instructions with one input
and one output.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: pg = CCInterpreter().pg
sage: instr_funcall_1arg_mpc('exp', pg('S','S'), 'mpc_exp')
exp: S->S = 'mpc_exp(o0, i0, MPC_RNDNN);'
"""
return InstrSpec(name, io, code='%s(o0, i0, MPC_RNDNN);' % op) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/instructions.py | 0.723993 | 0.560583 | instructions.py | pypi |
from __future__ import print_function, absolute_import
import os
import textwrap
from jinja2 import Environment
from jinja2.runtime import StrictUndefined
# We share a single jinja2 environment among all templating in this
# file. We use trim_blocks=True (which means that we ignore white
# space after "%}" jinja2 command endings), and set undefined to
# complain if we use an undefined variable.
JINJA_ENV = Environment(trim_blocks=True, undefined=StrictUndefined)
# Allow 'i' as a shorter alias for the built-in 'indent' filter.
JINJA_ENV.filters['i'] = JINJA_ENV.filters['indent']
def je(template, **kwargs):
r"""
A convenience method for creating strings with Jinja templates.
The name je stands for "Jinja evaluate".
The first argument is the template string; remaining keyword
arguments define Jinja variables.
If the first character in the template string is a newline, it is
removed (this feature is useful when using multi-line templates defined
with triple-quoted strings -- the first line doesn't have to be on
the same line as the quotes, which would screw up the indentation).
(This is very inefficient, because it recompiles the Jinja
template on each call; don't use it in situations where
performance is important.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import je
sage: je("{{ a }} > {{ b }} * {{ c }}", a='"a suffusion of yellow"', b=3, c=7)
u'"a suffusion of yellow" > 3 * 7'
"""
if len(template) > 0 and template[0] == '\n':
template = template[1:]
# It looks like Jinja2 automatically removes one trailing newline?
if len(template) > 0 and template[-1] == '\n':
template = template + '\n'
tmpl = JINJA_ENV.from_string(template)
return tmpl.render(kwargs)
def indent_lines(n, text):
r"""
Indent each line in text by ``n`` spaces.
INPUT:
- ``n`` -- indentation amount
- ``text`` -- text to indent
EXAMPLES::
sage: from sage_setup.autogen.interpreters import indent_lines
sage: indent_lines(3, "foo")
' foo'
sage: indent_lines(3, "foo\nbar")
' foo\n bar'
sage: indent_lines(3, "foo\nbar\n")
' foo\n bar\n'
"""
lines = text.splitlines(True)
spaces = ' ' * n
return ''.join((spaces if line.strip() else '') + line
for line in lines)
def reindent_lines(n, text):
r"""
Strip any existing indentation on the given text (while keeping
relative indentation) then re-indents the text by ``n`` spaces.
INPUT:
- ``n`` -- indentation amount
- ``text`` -- text to indent
EXAMPLES::
sage: from sage_setup.autogen.interpreters import reindent_lines
sage: print(reindent_lines(3, " foo\n bar"))
foo
bar
"""
return indent_lines(n, textwrap.dedent(text))
def write_if_changed(fn, value):
r"""
Write value to the file named fn, if value is different than
the current contents.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: def last_modification(fn): return os.stat(fn).st_mtime
sage: fn = tmp_filename('gen_interp')
sage: write_if_changed(fn, 'Hello, world')
sage: t1 = last_modification(fn)
sage: open(fn).read()
'Hello, world'
sage: sleep(2) # long time
sage: write_if_changed(fn, 'Goodbye, world')
sage: t2 = last_modification(fn)
sage: open(fn).read()
'Goodbye, world'
sage: sleep(2) # long time
sage: write_if_changed(fn, 'Goodbye, world')
sage: t3 = last_modification(fn)
sage: open(fn).read()
'Goodbye, world'
sage: t1 == t2 # long time
False
sage: t2 == t3
True
"""
old_value = None
try:
with open(fn) as file:
old_value = file.read()
except IOError:
pass
if value != old_value:
# We try to remove the file, in case it exists. This is to
# automatically break hardlinks... see #5350 for motivation.
try:
os.remove(fn)
except OSError:
pass
with open(fn, 'w') as file:
file.write(value) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/utils.py | 0.55266 | 0.296826 | utils.py | pypi |
from __future__ import print_function, absolute_import
from .utils import je, reindent_lines as ri
class StorageType(object):
r"""
A StorageType specifies the C types used to deal with values of a
given type.
We currently support three categories of types.
First are the "simple" types. These are types where: the
representation is small, functions expect arguments to be passed
by value, and the C/C++ assignment operator works. This would
include built-in C types (long, float, etc.) and small structs
(like gsl_complex).
Second is 'PyObject*'. This is just like a simple type, except
that we have to incref/decref at appropriate places.
Third is "auto-reference" types. This is how
GMP/MPIR/MPFR/MPFI/FLINT types work. For these types, functions
expect arguments to be passed by reference, and the C assignment
operator does not do what we want. In addition, they take
advantage of a quirk in C (where arrays are automatically
converted to pointers) to automatically pass arguments by
reference.
Support for further categories would not be difficult to add (such
as reference-counted types other than PyObject*, or
pass-by-reference types that don't use the GMP auto-reference
trick), if we ever run across a use for them.
"""
def __init__(self):
r"""
Initialize an instance of StorageType.
This sets several properties:
class_member_declarations:
A string giving variable declarations that must be members of any
wrapper class using this type.
class_member_initializations:
A string initializing the class_member_declarations; will be
inserted into the __init__ method of any wrapper class using this
type.
local_declarations:
A string giving variable declarations that must be local variables
in Cython methods using this storage type.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.class_member_declarations
''
sage: ty_double.class_member_initializations
''
sage: ty_double.local_declarations
''
sage: ty_mpfr.class_member_declarations
'cdef RealField_class domain\n'
sage: ty_mpfr.class_member_initializations
"self.domain = args['domain']\n"
sage: ty_mpfr.local_declarations
'cdef RealNumber rn\n'
"""
self.class_member_declarations = ''
self.class_member_initializations = ''
self.local_declarations = ''
def cheap_copies(self):
r"""
Returns True or False, depending on whether this StorageType
supports cheap copies -- whether it is cheap to copy values of
this type from one location to another. This is true for
primitive types, and for types like PyObject* (where you're only
copying a pointer, and possibly changing some reference counts).
It is false for types like mpz_t and mpfr_t, where copying values
can involve arbitrarily much work (including memory allocation).
The practical effect is that if cheap_copies is True,
instructions with outputs of this type write the results into
local variables, and the results are then copied to their
final locations. If cheap_copies is False, then the addresses
of output locations are passed into the instruction and the
instruction writes outputs directly in the final location.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.cheap_copies()
True
sage: ty_python.cheap_copies()
True
sage: ty_mpfr.cheap_copies()
False
"""
return False
def python_refcounted(self):
r"""
Says whether this storage type is a Python type, so we need to
use INCREF/DECREF.
(If we needed to support any non-Python refcounted types, it
might be better to make this object-oriented and have methods
like "generate an incref" and "generate a decref". But as
long as we only support Python, this way is probably simpler.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.python_refcounted()
False
sage: ty_python.python_refcounted()
True
"""
return False
def cython_decl_type(self):
r"""
Give the Cython type for a single value of this type (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.cython_decl_type()
'double'
sage: ty_python.cython_decl_type()
'object'
sage: ty_mpfr.cython_decl_type()
'mpfr_t'
"""
return self.c_decl_type()
def cython_array_type(self):
r"""
Give the Cython type for referring to an array of values of
this type (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.cython_array_type()
'double*'
sage: ty_python.cython_array_type()
'PyObject**'
sage: ty_mpfr.cython_array_type()
'mpfr_t*'
"""
return self.c_ptr_type()
def needs_cython_init_clear(self):
r"""
Says whether values/arrays of this type need to be initialized
before use and cleared before the underlying memory is freed.
(We could remove this method, always call .cython_init() to
generate initialization code, and just let .cython_init()
generate empty code if no initialization is required; that would
generate empty loops, which are ugly and potentially might not
be optimized away.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.needs_cython_init_clear()
False
sage: ty_mpfr.needs_cython_init_clear()
True
sage: ty_python.needs_cython_init_clear()
True
"""
return False
def c_decl_type(self):
r"""
Give the C type for a single value of this type (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.c_decl_type()
'double'
sage: ty_python.c_decl_type()
'PyObject*'
sage: ty_mpfr.c_decl_type()
'mpfr_t'
"""
raise NotImplementedError
def c_ptr_type(self):
r"""
Give the C type for a pointer to this type (as a reference to
either a single value or an array) (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.c_ptr_type()
'double*'
sage: ty_python.c_ptr_type()
'PyObject**'
sage: ty_mpfr.c_ptr_type()
'mpfr_t*'
"""
return self.c_decl_type() + '*'
def c_reference_type(self):
r"""
Give the C type which should be used for passing a reference
to a single value in a call. This is used as the type for the
return value.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.c_reference_type()
'double*'
sage: ty_python.c_reference_type()
'PyObject**'
"""
return self.c_ptr_type()
def c_local_type(self):
r"""
Give the C type used for a value of this type inside an
instruction. For assignable/cheap_copy types, this is the
same as c_decl_type; for auto-reference types, this is the
pointer type.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.c_local_type()
'double'
sage: ty_python.c_local_type()
'PyObject*'
sage: ty_mpfr.c_local_type()
'mpfr_ptr'
"""
raise NotImplementedError
def assign_c_from_py(self, c, py):
r"""
Given a Cython variable/array reference/etc. of this storage type,
and a Python expression, generate code to assign to the Cython
variable from the Python expression.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.assign_c_from_py('foo', 'bar')
u'foo = bar'
sage: ty_python.assign_c_from_py('foo[i]', 'bar[j]')
u'foo[i] = <PyObject *>bar[j]; Py_INCREF(foo[i])'
sage: ty_mpfr.assign_c_from_py('foo', 'bar')
u'rn = self.domain(bar)\nmpfr_set(foo, rn.value, MPFR_RNDN)'
"""
return je("{{ c }} = {{ py }}", c=c, py=py)
def declare_chunk_class_members(self, name):
r"""
Return a string giving the declarations of the class members
in a wrapper class for a memory chunk with this storage type
and the given name.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.declare_chunk_class_members('args')
u' cdef int _n_args\n cdef mpfr_t* _args\n'
"""
return je(ri(0,
"""
{# XXX Variables here (and everywhere, really) should actually be Py_ssize_t #}
cdef int _n_{{ name }}
cdef {{ myself.cython_array_type() }} _{{ name }}
"""), myself=self, name=name)
def alloc_chunk_data(self, name, len):
r"""
Return a string allocating the memory for the class members for
a memory chunk with this storage type and the given name.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: print(ty_mpfr.alloc_chunk_data('args', 'MY_LENGTH'))
self._n_args = MY_LENGTH
self._args = <mpfr_t*>check_allocarray(self._n_args, sizeof(mpfr_t))
for i in range(MY_LENGTH):
mpfr_init2(self._args[i], self.domain.prec())
<BLANKLINE>
"""
return je(ri(0,
"""
self._n_{{ name }} = {{ len }}
self._{{ name }} = <{{ myself.c_ptr_type() }}>check_allocarray(self._n_{{ name }}, sizeof({{ myself.c_decl_type() }}))
{% if myself.needs_cython_init_clear() %}
for i in range({{ len }}):
{{ myself.cython_init('self._%s[i]' % name) }}
{% endif %}
"""), myself=self, name=name, len=len)
def dealloc_chunk_data(self, name):
r"""
Return a string to be put in the __dealloc__ method of a
wrapper class using a memory chunk with this storage type, to
deallocate the corresponding class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: print(ty_double.dealloc_chunk_data('args'))
if self._args:
sig_free(self._args)
<BLANKLINE>
sage: print(ty_mpfr.dealloc_chunk_data('constants'))
if self._constants:
for i in range(self._n_constants):
mpfr_clear(self._constants[i])
sig_free(self._constants)
<BLANKLINE>
"""
return je(ri(0, """
if self._{{ name }}:
{% if myself.needs_cython_init_clear() %}
for i in range(self._n_{{ name }}):
{{ myself.cython_clear('self._%s[i]' % name) }}
{% endif %}
sig_free(self._{{ name }})
"""), myself=self, name=name)
class StorageTypeAssignable(StorageType):
r"""
StorageTypeAssignable is a subtype of StorageType that deals with
types with cheap copies, like primitive types and PyObject*.
"""
def __init__(self, ty):
r"""
Initializes the property type (the C/Cython name for this type),
as well as the properties described in the documentation for
StorageType.__init__.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.class_member_declarations
''
sage: ty_double.class_member_initializations
''
sage: ty_double.local_declarations
''
sage: ty_double.type
'double'
sage: ty_python.type
'PyObject*'
"""
StorageType.__init__(self)
self.type = ty
def cheap_copies(self):
r"""
Returns True or False, depending on whether this StorageType
supports cheap copies -- whether it is cheap to copy values of
this type from one location to another. (See StorageType.cheap_copies
for more on this property.)
Since having cheap copies is essentially the definition of
StorageTypeAssignable, this always returns True.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.cheap_copies()
True
sage: ty_python.cheap_copies()
True
"""
return True
def c_decl_type(self):
r"""
Give the C type for a single value of this type (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.c_decl_type()
'double'
sage: ty_python.c_decl_type()
'PyObject*'
"""
return self.type
def c_local_type(self):
r"""
Give the C type used for a value of this type inside an
instruction. For assignable/cheap_copy types, this is the
same as c_decl_type; for auto-reference types, this is the
pointer type.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_double.c_local_type()
'double'
sage: ty_python.c_local_type()
'PyObject*'
"""
return self.type
class StorageTypeSimple(StorageTypeAssignable):
r"""
StorageTypeSimple is a subtype of StorageTypeAssignable that deals
with non-reference-counted types with cheap copies, like primitive
types. As of yet, it has no functionality differences from
StorageTypeAssignable.
"""
pass
ty_int = StorageTypeSimple('int')
ty_double = StorageTypeSimple('double')
class StorageTypeDoubleComplex(StorageTypeSimple):
r"""
This is specific to the complex double type. It behaves exactly
like a StorageTypeSimple in C, but needs a little help to do
conversions in Cython.
This uses functions defined in CDFInterpreter, and is for use in
that context.
"""
def assign_c_from_py(self, c, py):
"""
sage: from sage_setup.autogen.interpreters import ty_double_complex
sage: ty_double_complex.assign_c_from_py('z_c', 'z_py')
u'z_c = CDE_to_dz(z_py)'
"""
return je("{{ c }} = CDE_to_dz({{ py }})", c=c, py=py)
ty_double_complex = StorageTypeDoubleComplex('double_complex')
class StorageTypePython(StorageTypeAssignable):
r"""
StorageTypePython is a subtype of StorageTypeAssignable that deals
with Python objects.
Just allocating an array full of PyObject* leads to problems,
because the Python garbage collector must be able to get to every
Python object, and it wouldn't know how to get to these arrays.
So we allocate the array as a Python list, but then we immediately
pull the ob_item out of it and deal only with that from then on.
We often leave these lists with NULL entries. This is safe for
the garbage collector and the deallocator, which is all we care
about; but it would be unsafe to provide Python-level access to
these lists.
There is one special thing about StorageTypePython: memory that is
used by the interpreter as scratch space (for example, the stack)
must be cleared after each call (so we don't hold on to
potentially-large objects and waste memory). Since we have to do
this anyway, the interpreter gains a tiny bit of speed by assuming
that the scratch space is cleared on entry; for example, when
pushing a value onto the stack, it doesn't bother to XDECREF the
previous value because it's always NULL.
"""
def __init__(self):
r"""
Initializes the properties described in the documentation
for StorageTypeAssignable.__init__. The type is always
'PyObject*'.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.class_member_declarations
''
sage: ty_python.class_member_initializations
''
sage: ty_python.local_declarations
''
sage: ty_python.type
'PyObject*'
"""
super(StorageTypePython, self).__init__('PyObject*')
def python_refcounted(self):
r"""
Says whether this storage type is a Python type, so we need to
use INCREF/DECREF.
Returns True.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.python_refcounted()
True
"""
return True
def cython_decl_type(self):
r"""
Give the Cython type for a single value of this type (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.cython_decl_type()
'object'
"""
return 'object'
def declare_chunk_class_members(self, name):
r"""
Return a string giving the declarations of the class members
in a wrapper class for a memory chunk with this storage type
and the given name.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.declare_chunk_class_members('args')
u' cdef object _list_args\n cdef int _n_args\n cdef PyObject** _args\n'
"""
return je(ri(4,
"""
cdef object _list_{{ name }}
cdef int _n_{{ name }}
cdef {{ myself.cython_array_type() }} _{{ name }}
"""), myself=self, name=name)
def alloc_chunk_data(self, name, len):
r"""
Return a string allocating the memory for the class members for
a memory chunk with this storage type and the given name.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: print(ty_python.alloc_chunk_data('args', 'MY_LENGTH'))
self._n_args = MY_LENGTH
self._list_args = PyList_New(self._n_args)
self._args = (<PyListObject *>self._list_args).ob_item
<BLANKLINE>
"""
return je(ri(8,
"""
self._n_{{ name }} = {{ len }}
self._list_{{ name }} = PyList_New(self._n_{{ name }})
self._{{ name }} = (<PyListObject *>self._list_{{ name }}).ob_item
"""), myself=self, name=name, len=len)
def dealloc_chunk_data(self, name):
r"""
Return a string to be put in the __dealloc__ method of a
wrapper class using a memory chunk with this storage type, to
deallocate the corresponding class members.
Our array was allocated as a Python list; this means we actually
don't need to do anything to deallocate it.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.dealloc_chunk_data('args')
''
"""
return ''
def needs_cython_init_clear(self):
r"""
Says whether values/arrays of this type need to be initialized
before use and cleared before the underlying memory is freed.
Returns True.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.needs_cython_init_clear()
True
"""
return True
def assign_c_from_py(self, c, py):
r"""
Given a Cython variable/array reference/etc. of this storage type,
and a Python expression, generate code to assign to the Cython
variable from the Python expression.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.assign_c_from_py('foo[i]', 'bar[j]')
u'foo[i] = <PyObject *>bar[j]; Py_INCREF(foo[i])'
"""
return je("""{{ c }} = <PyObject *>{{ py }}; Py_INCREF({{ c }})""",
c=c, py=py)
def cython_init(self, loc):
r"""
Generates code to initialize a variable (or array reference)
holding a PyObject*. Sets it to NULL.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.cython_init('foo[i]')
u'foo[i] = NULL'
"""
return je("{{ loc }} = NULL", loc=loc)
def cython_clear(self, loc):
r"""
Generates code to clear a variable (or array reference) holding
a PyObject*.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_python.cython_clear('foo[i]')
u'Py_CLEAR(foo[i])'
"""
return je("Py_CLEAR({{ loc }})", loc=loc)
ty_python = StorageTypePython()
class StorageTypeAutoReference(StorageType):
r"""
StorageTypeAutoReference is a subtype of StorageType that deals with
types in the style of GMP/MPIR/MPFR/MPFI/FLINT, where copies are
not cheap, functions expect arguments to be passed by reference,
and the API takes advantage of the C quirk where arrays are
automatically converted to pointers to automatically pass
arguments by reference.
"""
def __init__(self, decl_ty, ref_ty):
r"""
Initializes the properties decl_type and ref_type (the C type
names used when declaring variables and function parameters,
respectively), as well as the properties described in
the documentation for StorageType.__init__.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.class_member_declarations
'cdef RealField_class domain\n'
sage: ty_mpfr.class_member_initializations
"self.domain = args['domain']\n"
sage: ty_mpfr.local_declarations
'cdef RealNumber rn\n'
sage: ty_mpfr.decl_type
'mpfr_t'
sage: ty_mpfr.ref_type
'mpfr_ptr'
"""
super(StorageTypeAutoReference, self).__init__()
self.decl_type = decl_ty
self.ref_type = ref_ty
def c_decl_type(self):
r"""
Give the C type for a single value of this type (as a string).
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.c_decl_type()
'mpfr_t'
"""
return self.decl_type
def c_local_type(self):
r"""
Give the C type used for a value of this type inside an
instruction. For assignable/cheap_copy types, this is the
same as c_decl_type; for auto-reference types, this is the
pointer type.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.c_local_type()
'mpfr_ptr'
"""
return self.ref_type
def c_reference_type(self):
r"""
Give the C type which should be used for passing a reference
to a single value in a call. This is used as the type for the
return value.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.c_reference_type()
'mpfr_t'
"""
return self.decl_type
def needs_cython_init_clear(self):
r"""
Says whether values/arrays of this type need to be initialized
before use and cleared before the underlying memory is freed.
All known examples of auto-reference types do need a special
initialization call, so this always returns True.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.needs_cython_init_clear()
True
"""
return True
class StorageTypeMPFR(StorageTypeAutoReference):
r"""
StorageTypeMPFR is a subtype of StorageTypeAutoReference that deals
the MPFR's mpfr_t type.
For any given program that we're interpreting, ty_mpfr can only
refer to a single precision. An interpreter that needs to use
two precisions of mpfr_t in the same program should instantiate two
separate instances of StorageTypeMPFR. (Interpreters that need
to handle arbitrarily many precisions in the same program are not
handled at all.)
"""
def __init__(self, id=''):
r"""
Initializes the id property, as well as the properties described
in the documentation for StorageTypeAutoReference.__init__.
The id property is used if you want to have an interpreter
that handles two instances of StorageTypeMPFR (that is,
handles mpfr_t variables at two different precisions
simultaneously). It's a string that's used to generate
variable names that don't conflict. (The id system has
never actually been used, so bugs probably remain.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.class_member_declarations
'cdef RealField_class domain\n'
sage: ty_mpfr.class_member_initializations
"self.domain = args['domain']\n"
sage: ty_mpfr.local_declarations
'cdef RealNumber rn\n'
sage: ty_mpfr.decl_type
'mpfr_t'
sage: ty_mpfr.ref_type
'mpfr_ptr'
TESTS::
sage: ty_mpfr2 = StorageTypeMPFR(id='_the_second')
sage: ty_mpfr2.class_member_declarations
'cdef RealField_class domain_the_second\n'
sage: ty_mpfr2.class_member_initializations
"self.domain_the_second = args['domain_the_second']\n"
sage: ty_mpfr2.local_declarations
'cdef RealNumber rn_the_second\n'
"""
super(StorageTypeMPFR, self).__init__('mpfr_t', 'mpfr_ptr')
self.id = id
self.class_member_declarations = "cdef RealField_class domain%s\n" % self.id
self.class_member_initializations = \
"self.domain%s = args['domain%s']\n" % (self.id, self.id)
self.local_declarations = "cdef RealNumber rn%s\n" % self.id
def cython_init(self, loc):
r"""
Generates code to initialize an mpfr_t reference (a variable, an
array reference, etc.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.cython_init('foo[i]')
u'mpfr_init2(foo[i], self.domain.prec())'
"""
return je("mpfr_init2({{ loc }}, self.domain{{ myself.id }}.prec())",
myself=self, loc=loc)
def cython_clear(self, loc):
r"""
Generates code to clear an mpfr_t reference (a variable, an
array reference, etc.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.cython_clear('foo[i]')
'mpfr_clear(foo[i])'
"""
return 'mpfr_clear(%s)' % loc
def assign_c_from_py(self, c, py):
r"""
Given a Cython variable/array reference/etc. of this storage type,
and a Python expression, generate code to assign to the Cython
variable from the Python expression.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpfr.assign_c_from_py('foo[i]', 'bar[j]')
u'rn = self.domain(bar[j])\nmpfr_set(foo[i], rn.value, MPFR_RNDN)'
"""
return je(ri(0, """
rn{{ myself.id }} = self.domain({{ py }})
mpfr_set({{ c }}, rn.value, MPFR_RNDN)"""),
myself=self, c=c, py=py)
ty_mpfr = StorageTypeMPFR()
class StorageTypeMPC(StorageTypeAutoReference):
r"""
StorageTypeMPC is a subtype of StorageTypeAutoReference that deals
the MPC's mpc_t type.
For any given program that we're interpreting, ty_mpc can only
refer to a single precision. An interpreter that needs to use
two precisions of mpc_t in the same program should instantiate two
separate instances of StorageTypeMPC. (Interpreters that need
to handle arbitrarily many precisions in the same program are not
handled at all.)
"""
def __init__(self, id=''):
r"""
Initializes the id property, as well as the properties described
in the documentation for StorageTypeAutoReference.__init__.
The id property is used if you want to have an interpreter
that handles two instances of StorageTypeMPC (that is,
handles mpC_t variables at two different precisions
simultaneously). It's a string that's used to generate
variable names that don't conflict. (The id system has
never actually been used, so bugs probably remain.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpc.class_member_declarations
'cdef object domain\ncdef ComplexNumber domain_element\n'
sage: ty_mpc.class_member_initializations
"self.domain = args['domain']\nself.domain_element = self.domain.zero()\n"
sage: ty_mpc.local_declarations
'cdef ComplexNumber cn\n'
sage: ty_mpc.decl_type
'mpc_t'
sage: ty_mpc.ref_type
'mpc_ptr'
TESTS::
sage: ty_mpfr2 = StorageTypeMPC(id='_the_second')
sage: ty_mpfr2.class_member_declarations
'cdef object domain_the_second\ncdef ComplexNumber domain_element_the_second\n'
sage: ty_mpfr2.class_member_initializations
"self.domain_the_second = args['domain_the_second']\nself.domain_element_the_second = self.domain.zero()\n"
sage: ty_mpfr2.local_declarations
'cdef ComplexNumber cn_the_second\n'
"""
StorageTypeAutoReference.__init__(self, 'mpc_t', 'mpc_ptr')
self.id = id
self.class_member_declarations = "cdef object domain%s\ncdef ComplexNumber domain_element%s\n" % (self.id, self.id)
self.class_member_initializations = \
"self.domain%s = args['domain%s']\nself.domain_element%s = self.domain.zero()\n" % (self.id, self.id, self.id)
self.local_declarations = "cdef ComplexNumber cn%s\n" % self.id
def cython_init(self, loc):
r"""
Generates code to initialize an mpc_t reference (a variable, an
array reference, etc.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpc.cython_init('foo[i]')
u'mpc_init2(foo[i], self.domain_element._prec)'
"""
return je("mpc_init2({{ loc }}, self.domain_element{{ myself.id }}._prec)",
myself=self, loc=loc)
def cython_clear(self, loc):
r"""
Generates code to clear an mpfr_t reference (a variable, an
array reference, etc.)
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpc.cython_clear('foo[i]')
'mpc_clear(foo[i])'
"""
return 'mpc_clear(%s)' % loc
def assign_c_from_py(self, c, py):
r"""
Given a Cython variable/array reference/etc. of this storage type,
and a Python expression, generate code to assign to the Cython
variable from the Python expression.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: ty_mpc.assign_c_from_py('foo[i]', 'bar[j]')
u'cn = self.domain(bar[j])\nmpc_set_fr_fr(foo[i], cn.__re, cn.__im, MPC_RNDNN)'
"""
return je("""
cn{{ myself.id }} = self.domain({{ py }})
mpc_set_fr_fr({{ c }}, cn.__re, cn.__im, MPC_RNDNN)""", myself=self, c=c, py=py)
ty_mpc = StorageTypeMPC() | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/storage.py | 0.831554 | 0.452234 | storage.py | pypi |
from __future__ import print_function, absolute_import
from .base import StackInterpreter
from ..instructions import (params_gen, instr_funcall_2args, instr_unary,
InstrSpec)
from ..memory import MemoryChunk
from ..storage import ty_python
from ..utils import je, reindent_lines as ri
class MemoryChunkPythonArguments(MemoryChunk):
r"""
A special-purpose memory chunk, for the generic Python-object based
interpreter. Rather than copy the arguments into an array allocated
in the wrapper, we use the PyTupleObject internals and pass the array
that's inside the argument tuple.
"""
def declare_class_members(self):
r"""
Return a string giving the declarations of the class members
in a wrapper class for this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPythonArguments('args', ty_python)
"""
return " cdef int _n_%s\n" % self.name
def init_class_members(self):
r"""
Return a string to be put in the __init__ method of a wrapper
class using this memory chunk, to initialize the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPythonArguments('args', ty_python)
sage: mc.init_class_members()
u" count = args['args']\n self._n_args = count\n"
"""
return je(ri(8,
"""
count = args['{{ myself.name }}']
self._n_args = count
"""), myself=self)
def setup_args(self):
r"""
Handle the arguments of __call__. Nothing to do.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPythonArguments('args', ty_python)
sage: mc.setup_args()
''
"""
return ''
def pass_argument(self):
r"""
Pass the innards of the argument tuple to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPythonArguments('args', ty_python)
sage: mc.pass_argument()
'(<PyTupleObject*>args).ob_item'
"""
return "(<PyTupleObject*>args).ob_item"
class MemoryChunkPyConstant(MemoryChunk):
r"""
A special-purpose memory chunk, for holding a single Python constant
and passing it to the interpreter as a PyObject*.
"""
def __init__(self, name):
r"""
Initialize an instance of MemoryChunkPyConstant.
Always uses the type ty_python.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPyConstant('domain')
sage: mc.name
'domain'
sage: mc.storage_type is ty_python
True
"""
super(MemoryChunkPyConstant, self).__init__(name, ty_python)
def declare_class_members(self):
r"""
Return a string giving the declarations of the class members
in a wrapper class for this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPyConstant('domain')
sage: mc.declare_class_members()
u' cdef object _domain\n'
"""
return je(ri(4,
"""
cdef object _{{ myself.name }}
"""), myself=self)
def init_class_members(self):
r"""
Return a string to be put in the __init__ method of a wrapper
class using this memory chunk, to initialize the corresponding
class members.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPyConstant('domain')
sage: mc.init_class_members()
u" self._domain = args['domain']\n"
"""
return je(ri(8,
"""
self._{{ myself.name }} = args['{{ myself.name }}']
"""), myself=self)
def declare_parameter(self):
r"""
Return the string to use to declare the interpreter parameter
corresponding to this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPyConstant('domain')
sage: mc.declare_parameter()
'PyObject* domain'
"""
return 'PyObject* %s' % self.name
def pass_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkPyConstant('domain')
sage: mc.pass_argument()
'<PyObject*>self._domain'
"""
return '<PyObject*>self._%s' % self.name
class PythonInterpreter(StackInterpreter):
r"""
A subclass of StackInterpreter, specifying an interpreter over
Python objects.
Let's discuss how the reference-counting works in Python-object
based interpreters.
There is a simple rule to remember: when executing the code
snippets, the input variables contain borrowed references;
you must fill in the output variables with references you own.
As an optimization, an instruction may set .handles_own_decref; in
that case, it must decref any input variables that came from the
stack. (Input variables that came from arguments/constants chunks
must NOT be decref'ed!) In addition, with .handles_own_decref, if
any of your input variables are arbitrary-count, then you must
NULL out these variables as you decref them. (Use Py_CLEAR to do
this, unless you understand the documentation of Py_CLEAR and why
it's different than Py_XDECREF followed by assigning NULL.)
Note that as a tiny optimization, the interpreter always assumes
(and ensures) that empty parts of the stack contain NULL, so
it doesn't bother to Py_XDECREF before it pushes onto the stack.
"""
name = 'py'
def __init__(self):
r"""
Initialize a PythonInterpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: interp = PythonInterpreter()
sage: interp.name
'py'
sage: interp.mc_args
{MC:args}
sage: interp.chunks
[{MC:args}, {MC:constants}, {MC:stack}, {MC:code}]
sage: instrs = dict([(ins.name, ins) for ins in interp.instr_descs])
sage: instrs['add']
add: SS->S = 'o0 = PyNumber_Add(i0, i1);'
sage: instrs['py_call']
py_call: *->S = '\nPyObject *py_args...CREF(py_args);\n'
"""
super(PythonInterpreter, self).__init__(ty_python)
# StackInterpreter.__init__ gave us a MemoryChunkArguments.
# Override with MemoryChunkPythonArguments.
self.mc_args = MemoryChunkPythonArguments('args', ty_python)
self.chunks = [self.mc_args, self.mc_constants, self.mc_stack,
self.mc_code]
self.c_header = ri(0,
"""
#define CHECK(x) (x != NULL)
""")
self.pyx_header = ri(0,
"""\
from cpython.number cimport PyNumber_TrueDivide
""")
pg = params_gen(A=self.mc_args, C=self.mc_constants, D=self.mc_code,
S=self.mc_stack)
self.pg = pg
instrs = [
InstrSpec('load_arg', pg('A[D]', 'S'),
code='o0 = i0; Py_INCREF(o0);'),
InstrSpec('load_const', pg('C[D]', 'S'),
code='o0 = i0; Py_INCREF(o0);'),
InstrSpec('return', pg('S', ''),
code='return i0;',
handles_own_decref=True),
InstrSpec('py_call', pg('C[D]S@D', 'S'),
handles_own_decref=True,
code=ri(0, """
PyObject *py_args = PyTuple_New(n_i1);
if (py_args == NULL) goto error;
int i;
for (i = 0; i < n_i1; i++) {
PyObject *arg = i1[i];
PyTuple_SET_ITEM(py_args, i, arg);
i1[i] = NULL;
}
o0 = PyObject_CallObject(i0, py_args);
Py_DECREF(py_args);
"""))
]
binops = [
('add', 'PyNumber_Add'),
('sub', 'PyNumber_Subtract'),
('mul', 'PyNumber_Multiply'),
('div', 'PyNumber_TrueDivide'),
('floordiv', 'PyNumber_FloorDivide')
]
for (name, op) in binops:
instrs.append(instr_funcall_2args(name, pg('SS', 'S'), op))
instrs.append(InstrSpec('pow', pg('SS', 'S'),
code='o0 = PyNumber_Power(i0, i1, Py_None);'))
instrs.append(InstrSpec('ipow', pg('SC[D]', 'S'),
code='o0 = PyNumber_Power(i0, i1, Py_None);'))
for (name, op) in [('neg', 'PyNumber_Negative'),
('invert', 'PyNumber_Invert'),
('abs', 'PyNumber_Absolute')]:
instrs.append(instr_unary(name, pg('S', 'S'), '%s(i0)'%op))
self.instr_descs = instrs
self._set_opcodes()
# Always use ipow
self.ipow_range = True
# We don't yet support call_c for Python-object interpreters
# (the default implementation doesn't work, because of
# object vs. PyObject* confusion)
self.implement_call_c = False | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/specs/python.py | 0.787686 | 0.360292 | python.py | pypi |
from __future__ import print_function, absolute_import
from .base import StackInterpreter
from .python import MemoryChunkPyConstant
from ..instructions import (params_gen, instr_funcall_1arg_mpfr,
instr_funcall_2args_mpfr, InstrSpec)
from ..memory import MemoryChunk, MemoryChunkConstants
from ..storage import ty_mpfr, ty_python
from ..utils import je, reindent_lines as ri
class MemoryChunkRRRetval(MemoryChunk):
r"""
A special-purpose memory chunk, for dealing with the return value
of the RR-based interpreter.
"""
def declare_class_members(self):
r"""
Return a string giving the declarations of the class members
in a wrapper class for this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkRRRetval('retval', ty_mpfr)
sage: mc.declare_class_members()
''
"""
return ""
def declare_call_locals(self):
r"""
Return a string to put in the __call__ method of a wrapper
class using this memory chunk, to allocate local variables.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkRRRetval('retval', ty_mpfr)
sage: mc.declare_call_locals()
u' cdef RealNumber retval = (self.domain)()\n'
"""
return je(ri(8,
"""
cdef RealNumber {{ myself.name }} = (self.domain)()
"""), myself=self)
def declare_parameter(self):
r"""
Return the string to use to declare the interpreter parameter
corresponding to this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkRRRetval('retval', ty_mpfr)
sage: mc.declare_parameter()
'mpfr_t retval'
"""
return '%s %s' % (self.storage_type.c_reference_type(), self.name)
def pass_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkRRRetval('retval', ty_mpfr)
sage: mc.pass_argument()
u'retval.value'
"""
return je("""{{ myself.name }}.value""", myself=self)
def pass_call_c_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter, for use in the call_c method.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkRRRetval('retval', ty_mpfr)
sage: mc.pass_call_c_argument()
'result'
"""
return "result"
class RRInterpreter(StackInterpreter):
r"""
A subclass of StackInterpreter, specifying an interpreter over
MPFR arbitrary-precision floating-point numbers.
"""
name = 'rr'
def __init__(self):
r"""
Initialize an RDFInterpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: interp = RRInterpreter()
sage: interp.name
'rr'
sage: interp.mc_py_constants
{MC:py_constants}
sage: interp.chunks
[{MC:args}, {MC:retval}, {MC:constants}, {MC:py_constants}, {MC:stack}, {MC:code}, {MC:domain}]
sage: interp.pg('A[D]', 'S')
([({MC:args}, {MC:code}, None)], [({MC:stack}, None, None)])
sage: instrs = dict([(ins.name, ins) for ins in interp.instr_descs])
sage: instrs['add']
add: SS->S = 'mpfr_add(o0, i0, i1, MPFR_RNDN);'
sage: instrs['py_call']
py_call: *->S = '\nif (!rr_py_call_h...goto error;\n}\n'
That py_call instruction is particularly interesting, and
demonstrates a useful technique to let you use Cython code
in an interpreter. Let's look more closely::
sage: print(instrs['py_call'].code)
if (!rr_py_call_helper(domain, i0, n_i1, i1, o0)) {
goto error;
}
This instruction makes use of the function ``rr_py_call_helper``,
which is declared in ``wrapper_rr.h``::
sage: print(interp.c_header)
<BLANKLINE>
#include <mpfr.h>
#include "sage/ext/interpreters/wrapper_rr.h"
<BLANKLINE>
The function ``rr_py_call_helper`` is implemented in Cython::
sage: print(interp.pyx_header)
cdef public bint rr_py_call_helper(object domain, object fn,
int n_args,
mpfr_t* args, mpfr_t retval) except 0:
py_args = []
cdef int i
cdef RealNumber rn
for i from 0 <= i < n_args:
rn = domain()
mpfr_set(rn.value, args[i], MPFR_RNDN)
py_args.append(rn)
cdef RealNumber result = domain(fn(*py_args))
mpfr_set(retval, result.value, MPFR_RNDN)
return 1
So instructions where you need to interact with Python can
call back into Cython code fairly easily.
"""
mc_retval = MemoryChunkRRRetval('retval', ty_mpfr)
super(RRInterpreter, self).__init__(ty_mpfr, mc_retval=mc_retval)
self.err_return = '0'
self.mc_py_constants = MemoryChunkConstants('py_constants', ty_python)
self.mc_domain = MemoryChunkPyConstant('domain')
self.chunks = [self.mc_args, self.mc_retval, self.mc_constants,
self.mc_py_constants,
self.mc_stack, self.mc_code, self.mc_domain]
pg = params_gen(A=self.mc_args, C=self.mc_constants, D=self.mc_code,
S=self.mc_stack,
P=self.mc_py_constants)
self.pg = pg
self.c_header = ri(0,
'''
#include <mpfr.h>
#include "sage/ext/interpreters/wrapper_rr.h"
''')
self.pxd_header = ri(0,
"""
from sage.rings.real_mpfr cimport RealField_class, RealNumber
from sage.libs.mpfr cimport *
""")
self.pyx_header = ri(0,
"""\
cdef public bint rr_py_call_helper(object domain, object fn,
int n_args,
mpfr_t* args, mpfr_t retval) except 0:
py_args = []
cdef int i
cdef RealNumber rn
for i from 0 <= i < n_args:
rn = domain()
mpfr_set(rn.value, args[i], MPFR_RNDN)
py_args.append(rn)
cdef RealNumber result = domain(fn(*py_args))
mpfr_set(retval, result.value, MPFR_RNDN)
return 1
""")
instrs = [
InstrSpec('load_arg', pg('A[D]', 'S'),
code='mpfr_set(o0, i0, MPFR_RNDN);'),
InstrSpec('load_const', pg('C[D]', 'S'),
code='mpfr_set(o0, i0, MPFR_RNDN);'),
InstrSpec('return', pg('S', ''),
code='mpfr_set(retval, i0, MPFR_RNDN);\nreturn 1;\n'),
InstrSpec('py_call', pg('P[D]S@D', 'S'),
uses_error_handler=True,
code=ri(0,
"""
if (!rr_py_call_helper(domain, i0, n_i1, i1, o0)) {
goto error;
}
"""))
]
for (name, op) in [('add', 'mpfr_add'), ('sub', 'mpfr_sub'),
('mul', 'mpfr_mul'), ('div', 'mpfr_div'),
('pow', 'mpfr_pow')]:
instrs.append(instr_funcall_2args_mpfr(name, pg('SS', 'S'), op))
instrs.append(instr_funcall_2args_mpfr('ipow', pg('SD', 'S'), 'mpfr_pow_si'))
for name in ['neg', 'abs',
'log', 'log2', 'log10',
'exp', 'exp2', 'exp10',
'cos', 'sin', 'tan',
'sec', 'csc', 'cot',
'acos', 'asin', 'atan',
'cosh', 'sinh', 'tanh',
'sech', 'csch', 'coth',
'acosh', 'asinh', 'atanh',
'log1p', 'expm1', 'eint',
'gamma', 'lngamma',
'zeta', 'erf', 'erfc',
'j0', 'j1', 'y0', 'y1']:
instrs.append(instr_funcall_1arg_mpfr(name, pg('S', 'S'), 'mpfr_' + name))
# mpfr_ui_div constructs a temporary mpfr_t and then calls mpfr_div;
# it would probably be (slightly) faster to use a permanent copy
# of "one" (on the other hand, the constructed temporary copy is
# on the stack, so it's very likely to be in the cache).
instrs.append(InstrSpec('invert', pg('S', 'S'),
code='mpfr_ui_div(o0, 1, i0, MPFR_RNDN);'))
self.instr_descs = instrs
self._set_opcodes()
# Supported for exponents that fit in a long, so we could use
# a much wider range on a 64-bit machine. On the other hand,
# it's easier to write the code this way, and constant integer
# exponents outside this range probably aren't very common anyway.
self.ipow_range = (int(-2**31), int(2**31-1)) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/specs/rr.py | 0.660391 | 0.269255 | rr.py | pypi |
from __future__ import print_function, absolute_import
from .base import StackInterpreter
from ..instructions import (params_gen, instr_infix, instr_funcall_2args,
instr_unary, InstrSpec)
from ..memory import MemoryChunkConstants
from ..storage import ty_double_complex, ty_python
from ..utils import reindent_lines as ri
class CDFInterpreter(StackInterpreter):
r"""
A subclass of StackInterpreter, specifying an interpreter over
complex machine-floating-point values (C doubles).
"""
name = 'cdf'
def __init__(self):
r"""
Initialize a CDFInterpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: interp = CDFInterpreter()
sage: interp.name
'cdf'
sage: interp.mc_py_constants
{MC:py_constants}
sage: interp.chunks
[{MC:args}, {MC:constants}, {MC:py_constants}, {MC:stack}, {MC:code}]
sage: interp.pg('A[D]', 'S')
([({MC:args}, {MC:code}, None)], [({MC:stack}, None, None)])
sage: instrs = dict([(ins.name, ins) for ins in interp.instr_descs])
sage: instrs['add']
add: SS->S = 'o0 = i0 + i1;'
sage: instrs['sin']
sin: S->S = 'o0 = csin(i0);'
sage: instrs['py_call']
py_call: *->S = '\nif (!cdf_py_call_...goto error;\n}\n'
A test of integer powers::
sage: f(x) = sum(x^k for k in [-20..20])
sage: f(CDF(1+2j)) # rel tol 4e-16
-10391778.999999996 + 3349659.499999962*I
sage: ff = fast_callable(f, CDF)
sage: ff(1 + 2j) # rel tol 1e-14
-10391779.000000004 + 3349659.49999997*I
sage: ff.python_calls()
[]
sage: f(x) = sum(x^k for k in [0..5])
sage: ff = fast_callable(f, CDF)
sage: ff(2)
63.0
sage: ff(2j)
13.0 + 26.0*I
"""
super(CDFInterpreter, self).__init__(ty_double_complex)
self.mc_py_constants = MemoryChunkConstants('py_constants', ty_python)
# See comment for RDFInterpreter
self.err_return = '-1094648119105371'
self.adjust_retval = "dz_to_CDE"
self.chunks = [self.mc_args, self.mc_constants, self.mc_py_constants,
self.mc_stack,
self.mc_code]
pg = params_gen(A=self.mc_args, C=self.mc_constants, D=self.mc_code,
S=self.mc_stack, P=self.mc_py_constants)
self.pg = pg
self.c_header = ri(0,"""
#include <stdlib.h>
#include <complex.h>
#include "sage/ext/interpreters/wrapper_cdf.h"
/* On Solaris, we need to define _Imaginary_I when compiling with GCC,
* otherwise the constant I doesn't work. The definition below is based
* on glibc. */
#ifdef __GNUC__
#undef _Imaginary_I
#define _Imaginary_I (__extension__ 1.0iF)
#endif
typedef double complex double_complex;
static inline double complex csquareX(double complex z) {
double complex res;
__real__(res) = __real__(z) * __real__(z) - __imag__(z) * __imag__(z);
__imag__(res) = 2 * __real__(z) * __imag__(z);
return res;
}
static inline double complex cpow_int(double complex z, int exp) {
if (exp < 0) return 1/cpow_int(z, -exp);
switch (exp) {
case 0: return 1;
case 1: return z;
case 2: return csquareX(z);
case 3: return csquareX(z) * z;
case 4:
case 5:
case 6:
case 7:
case 8:
{
double complex z2 = csquareX(z);
double complex z4 = csquareX(z2);
if (exp == 4) return z4;
if (exp == 5) return z4 * z;
if (exp == 6) return z4 * z2;
if (exp == 7) return z4 * z2 * z;
if (exp == 8) return z4 * z4;
}
}
if (cimag(z) == 0) return pow(creal(z), exp);
if (creal(z) == 0) {
double r = pow(cimag(z), exp);
switch (exp % 4) {
case 0:
return r;
case 1:
return r * I;
case 2:
return -r;
default /* case 3 */:
return -r * I;
}
}
return cpow(z, exp);
}
""")
self.pxd_header = ri(0, """
# This is to work around a header incompatibility with PARI using
# "I" as variable conflicting with the complex "I".
# If we cimport pari earlier, we avoid this problem.
cimport cypari2.types
# We need the type double_complex to work around
# http://trac.cython.org/ticket/869
# so this is a bit hackish.
cdef extern from "complex.h":
ctypedef double double_complex "double complex"
""")
self.pyx_header = ri(0, """
from sage.libs.gsl.complex cimport *
from sage.rings.complex_double cimport ComplexDoubleElement
import sage.rings.complex_double
cdef object CDF = sage.rings.complex_double.CDF
cdef extern from "complex.h":
cdef double creal(double_complex)
cdef double cimag(double_complex)
cdef double_complex _Complex_I
cdef inline double_complex CDE_to_dz(zz):
cdef ComplexDoubleElement z = <ComplexDoubleElement>(zz if isinstance(zz, ComplexDoubleElement) else CDF(zz))
return GSL_REAL(z._complex) + _Complex_I * GSL_IMAG(z._complex)
cdef inline ComplexDoubleElement dz_to_CDE(double_complex dz):
cdef ComplexDoubleElement z = <ComplexDoubleElement>ComplexDoubleElement.__new__(ComplexDoubleElement)
GSL_SET_COMPLEX(&z._complex, creal(dz), cimag(dz))
return z
cdef public bint cdf_py_call_helper(object fn,
int n_args,
double_complex* args, double_complex* retval) except 0:
py_args = []
cdef int i
for i from 0 <= i < n_args:
py_args.append(dz_to_CDE(args[i]))
py_result = fn(*py_args)
cdef ComplexDoubleElement result
if isinstance(py_result, ComplexDoubleElement):
result = <ComplexDoubleElement>py_result
else:
result = CDF(py_result)
retval[0] = CDE_to_dz(result)
return 1
"""[1:])
instrs = [
InstrSpec('load_arg', pg('A[D]', 'S'),
code='o0 = i0;'),
InstrSpec('load_const', pg('C[D]', 'S'),
code='o0 = i0;'),
InstrSpec('return', pg('S', ''),
code='return i0;'),
InstrSpec('py_call', pg('P[D]S@D', 'S'),
uses_error_handler=True,
code="""
if (!cdf_py_call_helper(i0, n_i1, i1, &o0)) {
goto error;
}
""")
]
for (name, op) in [('add', '+'), ('sub', '-'),
('mul', '*'), ('div', '/'),
('truediv', '/')]:
instrs.append(instr_infix(name, pg('SS', 'S'), op))
instrs.append(instr_funcall_2args('pow', pg('SS', 'S'), 'cpow'))
instrs.append(instr_funcall_2args('ipow', pg('SD', 'S'), 'cpow_int'))
for (name, op) in [('neg', '-i0'), ('invert', '1/i0'),
('abs', 'cabs(i0)')]:
instrs.append(instr_unary(name, pg('S', 'S'), op))
for name in ['sqrt', 'sin', 'cos', 'tan',
'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh',
'asinh', 'acosh', 'atanh', 'exp', 'log']:
instrs.append(instr_unary(name, pg('S', 'S'), "c%s(i0)" % name))
self.instr_descs = instrs
self._set_opcodes()
# supported for exponents that fit in an int
self.ipow_range = (int(-2**31), int(2**31-1)) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/specs/cdf.py | 0.576423 | 0.232757 | cdf.py | pypi |
from __future__ import print_function, absolute_import
from .base import StackInterpreter
from .python import (MemoryChunkPyConstant, MemoryChunkPythonArguments,
PythonInterpreter)
from ..storage import ty_python
from ..utils import reindent_lines as ri
class MemoryChunkElementArguments(MemoryChunkPythonArguments):
r"""
A special-purpose memory chunk, for the Python-object based
interpreters that want to process (and perhaps modify) the data.
We allocate a new list on every call to hold the modified arguments.
That's not strictly necessary -- we could pre-allocate a list and map into
it -- but this lets us use simpler code for a very-likely-negligible
efficiency cost. (The Element interpreter is going to allocate lots of
objects as it runs, anyway.)
"""
def setup_args(self):
r"""
Handle the arguments of __call__. Note: This hardcodes
"self._domain".
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkElementArguments('args', ty_python)
sage: mc.setup_args()
'mapped_args = [self._domain(a) for a in args]\n'
"""
return "mapped_args = [self._domain(a) for a in args]\n"
def pass_argument(self):
r"""
Pass the innards of the argument tuple to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkElementArguments('args', ty_python)
sage: mc.pass_argument()
'(<PyListObject*>mapped_args).ob_item'
"""
return "(<PyListObject*>mapped_args).ob_item"
class ElementInterpreter(PythonInterpreter):
r"""
A subclass of PythonInterpreter, specifying an interpreter over
Sage elements with a particular parent.
This is very similar to the PythonInterpreter, but after every
instruction, the result is checked to make sure it actually an
element with the correct parent; if not, we attempt to convert it.
Uses the same instructions (with the same implementation) as
PythonInterpreter.
"""
name = 'el'
def __init__(self):
r"""
Initialize an ElementInterpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: interp = ElementInterpreter()
sage: interp.name
'el'
sage: interp.mc_args
{MC:args}
sage: interp.chunks
[{MC:args}, {MC:constants}, {MC:stack}, {MC:domain}, {MC:code}]
sage: instrs = dict([(ins.name, ins) for ins in interp.instr_descs])
sage: instrs['add']
add: SS->S = 'o0 = PyNumber_Add(i0, i1);'
sage: instrs['py_call']
py_call: *->S = '\nPyObject *py_args...CREF(py_args);\n'
"""
super(ElementInterpreter, self).__init__()
# PythonInterpreter.__init__ gave us a MemoryChunkPythonArguments.
# Override with MemoryChunkElementArguments.
self.mc_args = MemoryChunkElementArguments('args', ty_python)
self.mc_domain_info = MemoryChunkPyConstant('domain')
self.chunks = [self.mc_args, self.mc_constants, self.mc_stack,
self.mc_domain_info, self.mc_code]
self.c_header = ri(0, """
#include "sage/ext/interpreters/wrapper_el.h"
#define CHECK(x) do_check(&(x), domain)
static inline int do_check(PyObject **x, PyObject *domain) {
if (*x == NULL) return 0;
PyObject *new_x = el_check_element(*x, domain);
Py_DECREF(*x);
*x = new_x;
if (*x == NULL) return 0;
return 1;
}
""")
self.pyx_header += ri(0, """
from sage.structure.element cimport Element
cdef public object el_check_element(object v, parent):
cdef Element v_el
if isinstance(v, Element):
v_el = <Element>v
if v_el._parent is parent:
return v_el
return parent(v)
"""[1:]) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/specs/element.py | 0.709523 | 0.381738 | element.py | pypi |
from __future__ import print_function, absolute_import
from .base import StackInterpreter
from .python import MemoryChunkPyConstant
from ..instructions import (params_gen, instr_funcall_1arg_mpc,
instr_funcall_2args_mpc, InstrSpec)
from ..memory import MemoryChunk, MemoryChunkConstants
from ..storage import ty_mpc, ty_python
from ..utils import je, reindent_lines as ri
class MemoryChunkCCRetval(MemoryChunk):
r"""
A special-purpose memory chunk, for dealing with the return value
of the CC-based interpreter.
"""
def declare_class_members(self):
r"""
Return a string giving the declarations of the class members
in a wrapper class for this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkCCRetval('retval', ty_mpc)
sage: mc.declare_class_members()
''
"""
return ""
def declare_call_locals(self):
r"""
Return a string to put in the __call__ method of a wrapper
class using this memory chunk, to allocate local variables.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkCCRetval('retval', ty_mpc)
sage: mc.declare_call_locals()
u' cdef ComplexNumber retval = (self.domain_element._new())\n'
"""
return je(ri(8,
"""
cdef ComplexNumber {{ myself.name }} = (self.domain_element._new())
"""), myself=self)
def declare_parameter(self):
r"""
Return the string to use to declare the interpreter parameter
corresponding to this memory chunk.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkCCRetval('retval', ty_mpc)
sage: mc.declare_parameter()
'mpc_t retval'
"""
return '%s %s' % (self.storage_type.c_reference_type(), self.name)
def pass_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkCCRetval('retval', ty_mpc)
sage: mc.pass_argument()
u'(<mpc_t>(retval.__re))'
"""
return je("""(<mpc_t>({{ myself.name }}.__re))""", myself=self)
def pass_call_c_argument(self):
r"""
Return the string to pass the argument corresponding to this
memory chunk to the interpreter, for use in the call_c method.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: mc = MemoryChunkCCRetval('retval', ty_mpc)
sage: mc.pass_call_c_argument()
'result'
"""
return "result"
class CCInterpreter(StackInterpreter):
r"""
A subclass of StackInterpreter, specifying an interpreter over
MPFR arbitrary-precision floating-point numbers.
"""
name = 'cc'
def __init__(self):
r"""
Initialize a CCInterpreter.
EXAMPLES::
sage: from sage_setup.autogen.interpreters import *
sage: interp = CCInterpreter()
sage: interp.name
'cc'
sage: interp.mc_py_constants
{MC:py_constants}
sage: interp.chunks
[{MC:args}, {MC:retval}, {MC:constants}, {MC:py_constants}, {MC:stack}, {MC:code}, {MC:domain}]
sage: interp.pg('A[D]', 'S')
([({MC:args}, {MC:code}, None)], [({MC:stack}, None, None)])
sage: instrs = dict([(ins.name, ins) for ins in interp.instr_descs])
sage: instrs['add']
add: SS->S = 'mpc_add(o0, i0, i1, MPC_RNDNN);'
sage: instrs['py_call']
py_call: *->S = '\n if (!cc_py_call...goto error;\n}\n'
That py_call instruction is particularly interesting, and
demonstrates a useful technique to let you use Cython code
in an interpreter. Let's look more closely::
sage: print(instrs['py_call'].code)
<BLANKLINE>
if (!cc_py_call_helper(domain, i0, n_i1, i1, o0)) {
goto error;
}
<BLANKLINE>
This instruction makes use of the function cc_py_call_helper,
which is declared::
sage: print(interp.c_header)
<BLANKLINE>
#include <mpc.h>
#include "sage/ext/interpreters/wrapper_cc.h"
<BLANKLINE>
So instructions where you need to interact with Python can
call back into Cython code fairly easily.
"""
mc_retval = MemoryChunkCCRetval('retval', ty_mpc)
super(CCInterpreter, self).__init__(ty_mpc, mc_retval=mc_retval)
self.err_return = '0'
self.mc_py_constants = MemoryChunkConstants('py_constants', ty_python)
self.mc_domain = MemoryChunkPyConstant('domain')
self.chunks = [self.mc_args, self.mc_retval, self.mc_constants,
self.mc_py_constants,
self.mc_stack, self.mc_code, self.mc_domain]
pg = params_gen(A=self.mc_args, C=self.mc_constants, D=self.mc_code,
S=self.mc_stack,
P=self.mc_py_constants)
self.pg = pg
self.c_header = ri(0,
'''
#include <mpc.h>
#include "sage/ext/interpreters/wrapper_cc.h"
''')
self.pxd_header = ri(0,
"""
from sage.rings.real_mpfr cimport RealNumber
from sage.libs.mpfr cimport *
from sage.rings.complex_mpfr cimport ComplexNumber
from sage.libs.mpc cimport *
""")
self.pyx_header = ri(0,
"""\
# distutils: libraries = mpfr mpc gmp
cdef public bint cc_py_call_helper(object domain, object fn,
int n_args,
mpc_t* args, mpc_t retval) except 0:
py_args = []
cdef int i
cdef ComplexNumber ZERO=domain.zero()
cdef ComplexNumber cn
for i from 0 <= i < n_args:
cn = ZERO._new()
mpfr_set(cn.__re, mpc_realref(args[i]), MPFR_RNDN)
mpfr_set(cn.__im, mpc_imagref(args[i]), MPFR_RNDN)
py_args.append(cn)
cdef ComplexNumber result = domain(fn(*py_args))
mpc_set_fr_fr(retval, result.__re,result.__im, MPC_RNDNN)
return 1
""")
instrs = [
InstrSpec('load_arg', pg('A[D]', 'S'),
code='mpc_set(o0, i0, MPC_RNDNN);'),
InstrSpec('load_const', pg('C[D]', 'S'),
code='mpc_set(o0, i0, MPC_RNDNN);'),
InstrSpec('return', pg('S', ''),
code='mpc_set(retval, i0, MPC_RNDNN);\nreturn 1;\n'),
InstrSpec('py_call', pg('P[D]S@D', 'S'),
uses_error_handler=True,
code="""
if (!cc_py_call_helper(domain, i0, n_i1, i1, o0)) {
goto error;
}
""")
]
for (name, op) in [('add', 'mpc_add'), ('sub', 'mpc_sub'),
('mul', 'mpc_mul'), ('div', 'mpc_div'),
('pow', 'mpc_pow')]:
instrs.append(instr_funcall_2args_mpc(name, pg('SS', 'S'), op))
instrs.append(instr_funcall_2args_mpc('ipow', pg('SD', 'S'), 'mpc_pow_si'))
for name in ['neg',
'log', 'log10',
'exp',
'cos', 'sin', 'tan',
'acos', 'asin', 'atan',
'cosh', 'sinh', 'tanh',
'acosh', 'asinh', 'atanh']:
instrs.append(instr_funcall_1arg_mpc(name, pg('S', 'S'), 'mpc_' + name))
# mpc_ui_div constructs a temporary mpc_t and then calls mpc_div;
# it would probably be (slightly) faster to use a permanent copy
# of "one" (on the other hand, the constructed temporary copy is
# on the stack, so it's very likely to be in the cache).
instrs.append(InstrSpec('invert', pg('S', 'S'),
code='mpc_ui_div(o0, 1, i0, MPC_RNDNN);'))
self.instr_descs = instrs
self._set_opcodes()
# Supported for exponents that fit in a long, so we could use
# a much wider range on a 64-bit machine. On the other hand,
# it's easier to write the code this way, and constant integer
# exponents outside this range probably aren't very common anyway.
self.ipow_range = (int(-2**31), int(2**31-1)) | /sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage_setup/autogen/interpreters/specs/cc.py | 0.709925 | 0.21213 | cc.py | pypi |
from sage.misc.misc import walltime, cputime
def count_noun(number, noun, plural=None, pad_number=False, pad_noun=False):
"""
EXAMPLES::
sage: from sage.doctest.util import count_noun
sage: count_noun(1, "apple")
'1 apple'
sage: count_noun(1, "apple", pad_noun=True)
'1 apple '
sage: count_noun(1, "apple", pad_number=3)
' 1 apple'
sage: count_noun(2, "orange")
'2 oranges'
sage: count_noun(3, "peach", "peaches")
'3 peaches'
sage: count_noun(1, "peach", plural="peaches", pad_noun=True)
'1 peach '
"""
if plural is None:
plural = noun + "s"
if pad_noun:
# We assume that the plural is never shorter than the noun....
pad_noun = " " * (len(plural) - len(noun))
else:
pad_noun = ""
if pad_number:
number_str = ("%%%sd"%pad_number)%number
else:
number_str = "%d"%number
if number == 1:
return "%s %s%s"%(number_str, noun, pad_noun)
else:
return "%s %s"%(number_str, plural)
def dict_difference(self, other):
"""
Return a dict with all key-value pairs occurring in ``self`` but not
in ``other``.
EXAMPLES::
sage: from sage.doctest.util import dict_difference
sage: d1 = {1: 'a', 2: 'b', 3: 'c'}
sage: d2 = {1: 'a', 2: 'x', 4: 'c'}
sage: dict_difference(d2, d1)
{2: 'x', 4: 'c'}
::
sage: from sage.doctest.control import DocTestDefaults
sage: D1 = DocTestDefaults()
sage: D2 = DocTestDefaults(foobar="hello", timeout=100)
sage: dict_difference(D2.__dict__, D1.__dict__)
{'foobar': 'hello', 'timeout': 100}
"""
D = dict()
for k, v in self.items():
try:
if other[k] == v:
continue
except KeyError:
pass
D[k] = v
return D
class Timer:
"""
A simple timer.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer()
{}
sage: TestSuite(Timer()).run()
"""
def start(self):
"""
Start the timer.
Can be called multiple times to reset the timer.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer().start()
{'cputime': ..., 'walltime': ...}
"""
self.cputime = cputime()
self.walltime = walltime()
return self
def stop(self):
"""
Stops the timer, recording the time that has passed since it
was started.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: import time
sage: timer = Timer().start()
sage: time.sleep(float(0.5))
sage: timer.stop()
{'cputime': ..., 'walltime': ...}
"""
self.cputime = cputime(self.cputime)
self.walltime = walltime(self.walltime)
return self
def annotate(self, object):
"""
Annotates the given object with the cputime and walltime
stored in this timer.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer().start().annotate(EllipticCurve)
sage: EllipticCurve.cputime # random
2.817255
sage: EllipticCurve.walltime # random
1332649288.410404
"""
object.cputime = self.cputime
object.walltime = self.walltime
def __repr__(self):
"""
String representation is from the dictionary.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: repr(Timer().start()) # indirect doctest
"{'cputime': ..., 'walltime': ...}"
"""
return str(self)
def __str__(self):
"""
String representation is from the dictionary.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: str(Timer().start()) # indirect doctest
"{'cputime': ..., 'walltime': ...}"
"""
return str(self.__dict__)
def __eq__(self, other):
"""
Comparison.
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer() == Timer()
True
sage: t = Timer().start()
sage: loads(dumps(t)) == t
True
"""
if not isinstance(other, Timer):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Test for non-equality
EXAMPLES::
sage: from sage.doctest.util import Timer
sage: Timer() == Timer()
True
sage: t = Timer().start()
sage: loads(dumps(t)) != t
False
"""
return not (self == other)
# Inheritance rather then delegation as globals() must be a dict
class RecordingDict(dict):
"""
This dictionary is used for tracking the dependencies of an example.
This feature allows examples in different doctests to be grouped
for better timing data. It's obtained by recording whenever
anything is set or retrieved from this dictionary.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(test=17)
sage: D.got
set()
sage: D['test']
17
sage: D.got
{'test'}
sage: D.set
set()
sage: D['a'] = 1
sage: D['a']
1
sage: D.set
{'a'}
sage: D.got
{'test'}
TESTS::
sage: TestSuite(D).run()
"""
def __init__(self, *args, **kwds):
"""
Initialization arguments are the same as for a normal dictionary.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D.got
set()
"""
dict.__init__(self, *args, **kwds)
self.start()
def start(self):
"""
We track which variables have been set or retrieved.
This function initializes these lists to be empty.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D.set
set()
sage: D['a'] = 4
sage: D.set
{'a'}
sage: D.start(); D.set
set()
"""
self.set = set([])
self.got = set([])
def __getitem__(self, name):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4
sage: D.got
set()
sage: D['a'] # indirect doctest
4
sage: D.got
set()
sage: D['d']
42
sage: D.got
{'d'}
"""
if name not in self.set:
self.got.add(name)
return dict.__getitem__(self, name)
def __setitem__(self, name, value):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4 # indirect doctest
sage: D.set
{'a'}
"""
self.set.add(name)
dict.__setitem__(self, name, value)
def __delitem__(self, name):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: del D['d'] # indirect doctest
sage: D.set
{'d'}
"""
self.set.add(name)
dict.__delitem__(self, name)
def get(self, name, default=None):
"""
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D.get('d')
42
sage: D.got
{'d'}
sage: D.get('not_here')
sage: sorted(list(D.got))
['d', 'not_here']
"""
if name not in self.set:
self.got.add(name)
return dict.get(self, name, default)
def copy(self):
"""
Note that set and got are not copied.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4
sage: D.set
{'a'}
sage: E = D.copy()
sage: E.set
set()
sage: sorted(E.keys())
['a', 'd']
"""
return RecordingDict(dict.copy(self))
def __reduce__(self):
"""
Pickling.
EXAMPLES::
sage: from sage.doctest.util import RecordingDict
sage: D = RecordingDict(d = 42)
sage: D['a'] = 4
sage: D.get('not_here')
sage: E = loads(dumps(D))
sage: E.got
{'not_here'}
"""
return make_recording_dict, (dict(self), self.set, self.got)
def make_recording_dict(D, st, gt):
"""
Auxiliary function for pickling.
EXAMPLES::
sage: from sage.doctest.util import make_recording_dict
sage: D = make_recording_dict({'a':4,'d':42},set([]),set(['not_here']))
sage: sorted(D.items())
[('a', 4), ('d', 42)]
sage: D.got
{'not_here'}
"""
ans = RecordingDict(D)
ans.set = st
ans.got = gt
return ans
class NestedName:
"""
Class used to construct fully qualified names based on indentation level.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[0] = 'Algebras'; qname
sage.categories.algebras.Algebras
sage: qname[4] = '__contains__'; qname
sage.categories.algebras.Algebras.__contains__
sage: qname[4] = 'ParentMethods'
sage: qname[8] = 'from_base_ring'; qname
sage.categories.algebras.Algebras.ParentMethods.from_base_ring
TESTS::
sage: TestSuite(qname).run()
"""
def __init__(self, base):
"""
INPUT:
- base -- a string: the name of the module.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname
sage.categories.algebras
"""
self.all = [base]
def __setitem__(self, index, value):
"""
Sets the value at a given indentation level.
INPUT:
- index -- a positive integer, the indentation level (often a multiple of 4, but not necessarily)
- value -- a string, the name of the class or function at that indentation level.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[1] = 'Algebras' # indirect doctest
sage: qname
sage.categories.algebras.Algebras
sage: qname.all
['sage.categories.algebras', None, 'Algebras']
"""
if index < 0:
raise ValueError
while len(self.all) <= index:
self.all.append(None)
self.all[index+1:] = [value]
def __str__(self):
"""
Return a .-separated string giving the full name.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[1] = 'Algebras'
sage: qname[44] = 'at_the_end_of_the_universe'
sage: str(qname) # indirect doctest
'sage.categories.algebras.Algebras.at_the_end_of_the_universe'
"""
return repr(self)
def __repr__(self):
"""
Return a .-separated string giving the full name.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname[1] = 'Algebras'
sage: qname[44] = 'at_the_end_of_the_universe'
sage: print(qname) # indirect doctest
sage.categories.algebras.Algebras.at_the_end_of_the_universe
"""
return '.'.join(a for a in self.all if a is not None)
def __eq__(self, other):
"""
Comparison is just comparison of the underlying lists.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname2 = NestedName('sage.categories.algebras')
sage: qname == qname2
True
sage: qname[0] = 'Algebras'
sage: qname2[2] = 'Algebras'
sage: repr(qname) == repr(qname2)
True
sage: qname == qname2
False
"""
if not isinstance(other, NestedName):
return False
return self.all == other.all
def __ne__(self, other):
"""
Test for non-equality.
EXAMPLES::
sage: from sage.doctest.util import NestedName
sage: qname = NestedName('sage.categories.algebras')
sage: qname2 = NestedName('sage.categories.algebras')
sage: qname != qname2
False
sage: qname[0] = 'Algebras'
sage: qname2[2] = 'Algebras'
sage: repr(qname) == repr(qname2)
True
sage: qname != qname2
True
"""
return not (self == other) | /sagemath-repl-10.0b0.tar.gz/sagemath-repl-10.0b0/sage/doctest/util.py | 0.816809 | 0.296833 | util.py | pypi |
import os
import sys
import re
import random
import doctest
from sage.cpython.string import bytes_to_str
from sage.repl.load import load
from sage.misc.lazy_attribute import lazy_attribute
from sage.misc.package_dir import is_package_or_sage_namespace_package_dir
from .parsing import SageDocTestParser
from .util import NestedName
from sage.structure.dynamic_class import dynamic_class
from sage.env import SAGE_SRC, SAGE_LIB
# Python file parsing
triple_quotes = re.compile(r"\s*[rRuU]*((''')|(\"\"\"))")
name_regex = re.compile(r".*\s(\w+)([(].*)?:")
# LaTeX file parsing
begin_verb = re.compile(r"\s*\\begin{verbatim}")
end_verb = re.compile(r"\s*\\end{verbatim}\s*(%link)?")
begin_lstli = re.compile(r"\s*\\begin{lstlisting}")
end_lstli = re.compile(r"\s*\\end{lstlisting}\s*(%link)?")
skip = re.compile(r".*%skip.*")
# ReST file parsing
link_all = re.compile(r"^\s*\.\.\s+linkall\s*$")
double_colon = re.compile(r"^(\s*).*::\s*$")
code_block = re.compile(r"^(\s*)[.][.]\s*code-block\s*::.*$")
whitespace = re.compile(r"\s*")
bitness_marker = re.compile('#.*(32|64)-bit')
bitness_value = '64' if sys.maxsize > (1 << 32) else '32'
# For neutralizing doctests
find_prompt = re.compile(r"^(\s*)(>>>|sage:)(.*)")
# For testing that enough doctests are created
sagestart = re.compile(r"^\s*(>>> |sage: )\s*[^#\s]")
untested = re.compile("(not implemented|not tested)")
# For parsing a PEP 0263 encoding declaration
pep_0263 = re.compile(br'^[ \t\v]*#.*?coding[:=]\s*([-\w.]+)')
# Source line number in warning output
doctest_line_number = re.compile(r"^\s*doctest:[0-9]")
def get_basename(path):
"""
This function returns the basename of the given path, e.g. sage.doctest.sources or doc.ru.tutorial.tour_advanced
EXAMPLES::
sage: from sage.doctest.sources import get_basename
sage: from sage.env import SAGE_SRC
sage: import os
sage: get_basename(os.path.join(SAGE_SRC,'sage','doctest','sources.py'))
'sage.doctest.sources'
"""
if path is None:
return None
if not os.path.exists(path):
return path
path = os.path.abspath(path)
root = os.path.dirname(path)
# If the file is in the sage library, we can use our knowledge of
# the directory structure
dev = SAGE_SRC
sp = SAGE_LIB
if path.startswith(dev):
# there will be a branch name
i = path.find(os.path.sep, len(dev))
if i == -1:
# this source is the whole library....
return path
root = path[:i]
elif path.startswith(sp):
root = path[:len(sp)]
else:
# If this file is in some python package we can see how deep
# it goes.
while is_package_or_sage_namespace_package_dir(root):
root = os.path.dirname(root)
fully_qualified_path = os.path.splitext(path[len(root) + 1:])[0]
if os.path.split(path)[1] == '__init__.py':
fully_qualified_path = fully_qualified_path[:-9]
return fully_qualified_path.replace(os.path.sep, '.')
class DocTestSource():
"""
This class provides a common base class for different sources of doctests.
INPUT:
- ``options`` -- a :class:`sage.doctest.control.DocTestDefaults`
instance or equivalent.
"""
def __init__(self, options):
"""
Initialization.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: TestSuite(FDS).run()
"""
self.options = options
def __eq__(self, other):
"""
Comparison is just by comparison of attributes.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: DD = DocTestDefaults()
sage: FDS = FileDocTestSource(filename,DD)
sage: FDS2 = FileDocTestSource(filename,DD)
sage: FDS == FDS2
True
"""
if type(self) != type(other):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Test for non-equality.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: DD = DocTestDefaults()
sage: FDS = FileDocTestSource(filename,DD)
sage: FDS2 = FileDocTestSource(filename,DD)
sage: FDS != FDS2
False
"""
return not (self == other)
def _process_doc(self, doctests, doc, namespace, start):
"""
Appends doctests defined in ``doc`` to the list ``doctests``.
This function is called when a docstring block is completed
(either by ending a triple quoted string in a Python file,
unindenting from a comment block in a ReST file, or ending a
verbatim or lstlisting environment in a LaTeX file).
INPUT:
- ``doctests`` -- a running list of doctests to which the new
test(s) will be appended.
- ``doc`` -- a list of lines of a docstring, each including
the trailing newline.
- ``namespace`` -- a dictionary or
:class:`sage.doctest.util.RecordingDict`, used in the
creation of new :class:`doctest.DocTest` s.
- ``start`` -- an integer, giving the line number of the start
of this docstring in the larger file.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.parsing import SageDocTestParser
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','util.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: doctests, _ = FDS.create_doctests({})
sage: manual_doctests = []
sage: for dt in doctests:
....: FDS.qualified_name = dt.name
....: FDS._process_doc(manual_doctests, dt.docstring, {}, dt.lineno-1)
sage: doctests == manual_doctests
True
"""
docstring = "".join(doc)
new_doctests = self.parse_docstring(docstring, namespace, start)
sig_on_count_doc_doctest = "sig_on_count() # check sig_on/off pairings (virtual doctest)\n"
for dt in new_doctests:
if len(dt.examples) > 0 and not (hasattr(dt.examples[-1],'sage_source')
and dt.examples[-1].sage_source == sig_on_count_doc_doctest):
# Line number refers to the end of the docstring
sigon = doctest.Example(sig_on_count_doc_doctest, "0\n", lineno=docstring.count("\n"))
sigon.sage_source = sig_on_count_doc_doctest
dt.examples.append(sigon)
doctests.append(dt)
def _create_doctests(self, namespace, tab_okay=None):
"""
Creates a list of doctests defined in this source.
This function collects functionality common to file and string
sources, and is called by
:meth:`FileDocTestSource.create_doctests`.
INPUT:
- ``namespace`` -- a dictionary or
:class:`sage.doctest.util.RecordingDict`, used in the
creation of new :class:`doctest.DocTest` s.
- ``tab_okay`` -- whether tabs are allowed in this source.
OUTPUT:
- ``doctests`` -- a list of doctests defined by this source
- ``extras`` -- a dictionary with ``extras['tab']`` either
False or a list of linenumbers on which tabs appear.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.qualified_name = NestedName('sage.doctest.sources')
sage: doctests, extras = FDS._create_doctests({})
sage: len(doctests)
41
sage: extras['tab']
False
sage: extras['line_number']
False
"""
if tab_okay is None:
tab_okay = isinstance(self,TexSource)
self._init()
self.line_shift = 0
self.parser = SageDocTestParser(self.options.optional,
self.options.long)
self.linking = False
doctests = []
in_docstring = False
unparsed_doc = False
doc = []
start = None
tab_locations = []
contains_line_number = False
for lineno, line in self:
if doctest_line_number.search(line) is not None:
contains_line_number = True
if "\t" in line:
tab_locations.append(str(lineno+1))
if "SAGE_DOCTEST_ALLOW_TABS" in line:
tab_okay = True
just_finished = False
if in_docstring:
if self.ending_docstring(line):
in_docstring = False
just_finished = True
self._process_doc(doctests, doc, namespace, start)
unparsed_doc = False
else:
bitness = bitness_marker.search(line)
if bitness:
if bitness.groups()[0] != bitness_value:
self.line_shift += 1
continue
else:
line = line[:bitness.start()] + "\n"
if self.line_shift and sagestart.match(line):
# We insert blank lines to make up for the removed lines
doc.extend(["\n"]*self.line_shift)
self.line_shift = 0
doc.append(line)
unparsed_doc = True
if not in_docstring and (not just_finished or self.start_finish_can_overlap):
# to get line numbers in linked docstrings correct we
# append a blank line to the doc list.
doc.append("\n")
if not line.strip():
continue
if self.starting_docstring(line):
in_docstring = True
if self.linking:
# If there's already a doctest, we overwrite it.
if len(doctests) > 0:
doctests.pop()
if start is None:
start = lineno
doc = []
else:
self.line_shift = 0
start = lineno
doc = []
# In ReST files we can end the file without decreasing the indentation level.
if unparsed_doc:
self._process_doc(doctests, doc, namespace, start)
extras = dict(tab=not tab_okay and tab_locations,
line_number=contains_line_number,
optionals=self.parser.optionals)
if self.options.randorder is not None and self.options.randorder is not False:
# we want to randomize even when self.randorder = 0
random.seed(self.options.randorder)
randomized = []
while doctests:
i = random.randint(0, len(doctests) - 1)
randomized.append(doctests.pop(i))
return randomized, extras
else:
return doctests, extras
class StringDocTestSource(DocTestSource):
r"""
This class creates doctests from a string.
INPUT:
- ``basename`` -- string such as 'sage.doctests.sources', going
into the names of created doctests and examples.
- ``source`` -- a string, giving the source code to be parsed for
doctests.
- ``options`` -- a :class:`sage.doctest.control.DocTestDefaults`
or equivalent.
- ``printpath`` -- a string, to be used in place of a filename
when doctest failures are displayed.
- ``lineno_shift`` -- an integer (default: 0) by which to shift
the line numbers of all doctests defined in this string.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, extras = PSS.create_doctests({})
sage: len(dt)
1
sage: extras['tab']
[]
sage: extras['line_number']
False
sage: s = "'''\n\tsage: 2 + 2\n\t4\n'''"
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, extras = PSS.create_doctests({})
sage: extras['tab']
['2', '3']
sage: s = "'''\n sage: import warnings; warnings.warn('foo')\n doctest:1: UserWarning: foo \n'''"
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, extras = PSS.create_doctests({})
sage: extras['line_number']
True
"""
def __init__(self, basename, source, options, printpath, lineno_shift=0):
r"""
Initialization
TESTS::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: TestSuite(PSS).run()
"""
self.qualified_name = NestedName(basename)
self.printpath = printpath
self.source = source
self.lineno_shift = lineno_shift
DocTestSource.__init__(self, options)
def __iter__(self):
r"""
Iterating over this source yields pairs ``(lineno, line)``.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: for n, line in PSS:
....: print("{} {}".format(n, line))
0 '''
1 sage: 2 + 2
2 4
3 '''
"""
for lineno, line in enumerate(self.source.split('\n')):
yield lineno + self.lineno_shift, line + '\n'
def create_doctests(self, namespace):
r"""
Creates doctests from this string.
INPUT:
- ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`.
OUTPUT:
- ``doctests`` -- a list of doctests defined by this string
- ``tab_locations`` -- either False or a list of linenumbers
on which tabs appear.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: dt, tabs = PSS.create_doctests({})
sage: for t in dt:
....: print("{} {}".format(t.name, t.examples[0].sage_source))
<runtime> 2 + 2
"""
return self._create_doctests(namespace)
class FileDocTestSource(DocTestSource):
"""
This class creates doctests from a file.
INPUT:
- ``path`` -- string, the filename
- ``options`` -- a :class:`sage.doctest.control.DocTestDefaults`
instance or equivalent.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.basename
'sage.doctest.sources'
TESTS::
sage: TestSuite(FDS).run()
::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = tmp_filename(ext=".txtt")
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
Traceback (most recent call last):
...
ValueError: unknown extension for the file to test (=...txtt),
valid extensions are: .py, .pyx, .pxd, .pxi, .sage, .spyx, .tex, .rst, .rst.txt
"""
def __init__(self, path, options):
"""
Initialization.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0))
sage: FDS.options.randorder
0
"""
self.path = path
DocTestSource.__init__(self, options)
if path.endswith('.rst.txt'):
ext = '.rst.txt'
else:
base, ext = os.path.splitext(path)
valid_code_ext = ('.py', '.pyx', '.pxd', '.pxi', '.sage', '.spyx')
if ext in valid_code_ext:
self.__class__ = dynamic_class('PythonFileSource',(FileDocTestSource,PythonSource))
self.encoding = "utf-8"
elif ext == '.tex':
self.__class__ = dynamic_class('TexFileSource',(FileDocTestSource,TexSource))
self.encoding = "utf-8"
elif ext == '.rst' or ext == '.rst.txt':
self.__class__ = dynamic_class('RestFileSource',(FileDocTestSource,RestSource))
self.encoding = "utf-8"
else:
valid_ext = ", ".join(valid_code_ext + ('.tex', '.rst', '.rst.txt'))
raise ValueError("unknown extension for the file to test (={}),"
" valid extensions are: {}".format(path, valid_ext))
def __iter__(self):
r"""
Iterating over this source yields pairs ``(lineno, line)``.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = tmp_filename(ext=".py")
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: with open(filename, 'w') as f:
....: _ = f.write(s)
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: for n, line in FDS:
....: print("{} {}".format(n, line))
0 '''
1 sage: 2 + 2
2 4
3 '''
The encoding is "utf-8" by default::
sage: FDS.encoding
'utf-8'
We create a file with a Latin-1 encoding without declaring it::
sage: s = b"'''\nRegardons le polyn\xF4me...\n'''\n"
sage: with open(filename, 'wb') as f:
....: _ = f.write(s)
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: L = list(FDS)
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf...8' codec can...t decode byte 0xf4 in position 18: invalid continuation byte
This works if we add a PEP 0263 encoding declaration::
sage: s = b"#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n" + s
sage: with open(filename, 'wb') as f:
....: _ = f.write(s)
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: L = list(FDS)
sage: FDS.encoding
'latin-1'
"""
with open(self.path, 'rb') as source:
for lineno, line in enumerate(source):
if lineno < 2:
match = pep_0263.search(line)
if match:
self.encoding = bytes_to_str(match.group(1), 'ascii')
yield lineno, line.decode(self.encoding)
@lazy_attribute
def printpath(self):
"""
Whether the path is printed absolutely or relatively depends on an option.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: root = os.path.realpath(os.path.join(SAGE_SRC,'sage'))
sage: filename = os.path.join(root,'doctest','sources.py')
sage: cwd = os.getcwd()
sage: os.chdir(root)
sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0,abspath=False))
sage: FDS.printpath
'doctest/sources.py'
sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0,abspath=True))
sage: FDS.printpath
'.../sage/doctest/sources.py'
sage: os.chdir(cwd)
"""
if self.options.abspath:
return os.path.abspath(self.path)
else:
relpath = os.path.relpath(self.path)
if relpath.startswith(".." + os.path.sep):
return self.path
else:
return relpath
@lazy_attribute
def basename(self):
"""
The basename of this file source, e.g. sage.doctest.sources
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','rings','integer.pyx')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.basename
'sage.rings.integer'
"""
return get_basename(self.path)
@lazy_attribute
def in_lib(self):
"""
Whether this file is to be treated as a module in a Python package.
Such files aren't loaded before running tests.
This uses :func:`~sage.misc.package_dir.is_package_or_sage_namespace_package_dir`
but can be overridden via :class:`~sage.doctest.control.DocTestDefaults`.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC, 'sage', 'rings', 'integer.pyx')
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: FDS.in_lib
True
sage: filename = os.path.join(SAGE_SRC, 'sage', 'doctest', 'tests', 'abort.rst')
sage: FDS = FileDocTestSource(filename, DocTestDefaults())
sage: FDS.in_lib
False
You can override the default::
sage: FDS = FileDocTestSource("hello_world.py",DocTestDefaults())
sage: FDS.in_lib
False
sage: FDS = FileDocTestSource("hello_world.py",DocTestDefaults(force_lib=True))
sage: FDS.in_lib
True
"""
return (self.options.force_lib
or is_package_or_sage_namespace_package_dir(os.path.dirname(self.path)))
def create_doctests(self, namespace):
r"""
Return a list of doctests for this file.
INPUT:
- ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`.
OUTPUT:
- ``doctests`` -- a list of doctests defined in this file.
- ``extras`` -- a dictionary
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: doctests, extras = FDS.create_doctests(globals())
sage: len(doctests)
41
sage: extras['tab']
False
We give a self referential example::
sage: doctests[18].name
'sage.doctest.sources.FileDocTestSource.create_doctests'
sage: doctests[18].examples[10].source
'doctests[Integer(18)].examples[Integer(10)].source\n'
TESTS:
We check that we correctly process results that depend on 32
vs 64 bit architecture::
sage: import sys
sage: bitness = '64' if sys.maxsize > (1 << 32) else '32'
sage: gp.get_precision() == 38
False # 32-bit
True # 64-bit
sage: ex = doctests[18].examples[13]
sage: (bitness == '64' and ex.want == 'True \n') or (bitness == '32' and ex.want == 'False \n')
True
We check that lines starting with a # aren't doctested::
#sage: raise RuntimeError
"""
if not os.path.exists(self.path):
import errno
raise IOError(errno.ENOENT, "File does not exist", self.path)
base, filename = os.path.split(self.path)
_, ext = os.path.splitext(filename)
if not self.in_lib and ext in ('.py', '.pyx', '.sage', '.spyx'):
cwd = os.getcwd()
if base:
os.chdir(base)
try:
load(filename, namespace) # errors raised here will be caught in DocTestTask
finally:
os.chdir(cwd)
self.qualified_name = NestedName(self.basename)
return self._create_doctests(namespace)
def _test_enough_doctests(self, check_extras=True, verbose=True):
r"""
This function checks to see that the doctests are not getting
unexpectedly skipped. It uses a different (and simpler) code
path than the doctest creation functions, so there are a few
files in Sage that it counts incorrectly.
INPUT:
- ``check_extras`` -- bool (default ``True``), whether to check if
doctests are created that do not correspond to either a ``sage:``
or a ``>>>`` prompt
- ``verbose`` -- bool (default ``True``), whether to print
offending line numbers when there are missing or extra tests
TESTS::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: cwd = os.getcwd()
sage: os.chdir(SAGE_SRC)
sage: import itertools
sage: for path, dirs, files in itertools.chain(os.walk('sage'), os.walk('doc')): # long time
....: path = os.path.relpath(path)
....: dirs.sort(); files.sort()
....: for F in files:
....: _, ext = os.path.splitext(F)
....: if ext in ('.py', '.pyx', '.pxd', '.pxi', '.sage', '.spyx', '.rst'):
....: filename = os.path.join(path, F)
....: FDS = FileDocTestSource(filename, DocTestDefaults(long=True, optional=True, force_lib=True))
....: FDS._test_enough_doctests(verbose=False)
There are 3 unexpected tests being run in sage/doctest/parsing.py
There are 1 unexpected tests being run in sage/doctest/reporting.py
sage: os.chdir(cwd)
"""
expected = []
rest = isinstance(self, RestSource)
if rest:
skipping = False
in_block = False
last_line = ''
for lineno, line in self:
if not line.strip():
continue
if rest:
if line.strip().startswith(".. nodoctest"):
return
# We need to track blocks in order to figure out whether we're skipping.
if in_block:
indent = whitespace.match(line).end()
if indent <= starting_indent:
in_block = False
skipping = False
if not in_block:
m1 = double_colon.match(line)
m2 = code_block.match(line.lower())
starting = (m1 and not line.strip().startswith(".. ")) or m2
if starting:
if ".. skip" in last_line:
skipping = True
in_block = True
starting_indent = whitespace.match(line).end()
last_line = line
if (not rest or in_block) and sagestart.match(line) and not ((rest and skipping) or untested.search(line.lower())):
expected.append(lineno+1)
actual = []
tests, _ = self.create_doctests({})
for dt in tests:
if dt.examples:
for ex in dt.examples[:-1]: # the last entry is a sig_on_count()
actual.append(dt.lineno + ex.lineno + 1)
shortfall = sorted(set(expected).difference(set(actual)))
extras = sorted(set(actual).difference(set(expected)))
if len(actual) == len(expected):
if not shortfall:
return
dif = extras[0] - shortfall[0]
for e, s in zip(extras[1:],shortfall[1:]):
if dif != e - s:
break
else:
print("There are %s tests in %s that are shifted by %s" % (len(shortfall), self.path, dif))
if verbose:
print(" The correct line numbers are %s" % (", ".join(str(n) for n in shortfall)))
return
elif len(actual) < len(expected):
print("There are %s tests in %s that are not being run" % (len(expected) - len(actual), self.path))
elif check_extras:
print("There are %s unexpected tests being run in %s" % (len(actual) - len(expected), self.path))
if verbose:
if shortfall:
print(" Tests on lines %s are not run" % (", ".join(str(n) for n in shortfall)))
if check_extras and extras:
print(" Tests on lines %s seem extraneous" % (", ".join(str(n) for n in extras)))
class SourceLanguage:
"""
An abstract class for functions that depend on the programming language of a doctest source.
Currently supported languages include Python, ReST and LaTeX.
"""
def parse_docstring(self, docstring, namespace, start):
"""
Return a list of doctest defined in this docstring.
This function is called by :meth:`DocTestSource._process_doc`.
The default implementation, defined here, is to use the
:class:`sage.doctest.parsing.SageDocTestParser` attached to
this source to get doctests from the docstring.
INPUT:
- ``docstring`` -- a string containing documentation and tests.
- ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`.
- ``start`` -- an integer, one less than the starting line number
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.parsing import SageDocTestParser
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','util.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: doctests, _ = FDS.create_doctests({})
sage: for dt in doctests:
....: FDS.qualified_name = dt.name
....: dt.examples = dt.examples[:-1] # strip off the sig_on() test
....: assert(FDS.parse_docstring(dt.docstring,{},dt.lineno-1)[0] == dt)
"""
return [self.parser.get_doctest(docstring, namespace, str(self.qualified_name),
self.printpath, start + 1)]
class PythonSource(SourceLanguage):
"""
This class defines the functions needed for the extraction of doctests from python sources.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: type(FDS)
<class 'sage.doctest.sources.PythonFileSource'>
"""
# The same line can't both start and end a docstring
start_finish_can_overlap = False
def _init(self):
"""
This function is called before creating doctests from a Python source.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.last_indent
-1
"""
self.last_indent = -1
self.last_line = None
self.quotetype = None
self.paren_count = 0
self.bracket_count = 0
self.curly_count = 0
self.code_wrapping = False
def _update_quotetype(self, line):
r"""
Updates the track of what kind of quoted string we're in.
We need to track whether we're inside a triple quoted
string, since a triple quoted string that starts a line
could be the end of a string and thus not the beginning of a
doctest (see sage.misc.sageinspect for an example).
To do this tracking we need to track whether we're inside a
string at all, since ''' inside a string doesn't start a
triple quote (see the top of this file for an example).
We also need to track parentheses and brackets, since we only
want to update our record of last line and indentation level
when the line is actually over.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS._update_quotetype('\"\"\"'); print(" ".join(list(FDS.quotetype)))
" " "
sage: FDS._update_quotetype("'''"); print(" ".join(list(FDS.quotetype)))
" " "
sage: FDS._update_quotetype('\"\"\"'); print(FDS.quotetype)
None
sage: FDS._update_quotetype("triple_quotes = re.compile(\"\\s*[rRuU]*((''')|(\\\"\\\"\\\"))\")")
sage: print(FDS.quotetype)
None
sage: FDS._update_quotetype("''' Single line triple quoted string \\''''")
sage: print(FDS.quotetype)
None
sage: FDS._update_quotetype("' Lots of \\\\\\\\'")
sage: print(FDS.quotetype)
None
"""
def _update_parens(start,end=None):
self.paren_count += line.count("(",start,end) - line.count(")",start,end)
self.bracket_count += line.count("[",start,end) - line.count("]",start,end)
self.curly_count += line.count("{",start,end) - line.count("}",start,end)
pos = 0
while pos < len(line):
if self.quotetype is None:
next_single = line.find("'",pos)
next_double = line.find('"',pos)
if next_single == -1 and next_double == -1:
next_comment = line.find("#",pos)
if next_comment == -1:
_update_parens(pos)
else:
_update_parens(pos,next_comment)
break
elif next_single == -1:
m = next_double
elif next_double == -1:
m = next_single
else:
m = min(next_single, next_double)
next_comment = line.find('#',pos,m)
if next_comment != -1:
_update_parens(pos,next_comment)
break
_update_parens(pos,m)
if m+2 < len(line) and line[m] == line[m+1] == line[m+2]:
self.quotetype = line[m:m+3]
pos = m+3
else:
self.quotetype = line[m]
pos = m+1
else:
next = line.find(self.quotetype,pos)
if next == -1:
break
elif next == 0 or line[next-1] != '\\':
pos = next + len(self.quotetype)
self.quotetype = None
else:
# We need to worry about the possibility that
# there are an even number of backslashes before
# the quote, in which case it is not escaped
count = 1
slashpos = next - 2
while slashpos >= pos and line[slashpos] == '\\':
count += 1
slashpos -= 1
if count % 2 == 0:
pos = next + len(self.quotetype)
self.quotetype = None
else:
# The possible ending quote was escaped.
pos = next + 1
def starting_docstring(self, line):
"""
Determines whether the input line starts a docstring.
If the input line does start a docstring (a triple quote),
then this function updates ``self.qualified_name``.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- either None or a Match object.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.starting_docstring("r'''")
<...Match object...>
sage: FDS.ending_docstring("'''")
<...Match object...>
sage: FDS.qualified_name = NestedName(FDS.basename)
sage: FDS.starting_docstring("class MyClass():")
sage: FDS.starting_docstring(" def hello_world(self):")
sage: FDS.starting_docstring(" '''")
<...Match object...>
sage: FDS.qualified_name
sage.doctest.sources.MyClass.hello_world
sage: FDS.ending_docstring(" '''")
<...Match object...>
sage: FDS.starting_docstring("class NewClass():")
sage: FDS.starting_docstring(" '''")
<...Match object...>
sage: FDS.ending_docstring(" '''")
<...Match object...>
sage: FDS.qualified_name
sage.doctest.sources.NewClass
sage: FDS.starting_docstring("print(")
sage: FDS.starting_docstring(" '''Not a docstring")
sage: FDS.starting_docstring(" ''')")
sage: FDS.starting_docstring("def foo():")
sage: FDS.starting_docstring(" '''This is a docstring'''")
<...Match object...>
"""
indent = whitespace.match(line).end()
quotematch = None
if self.quotetype is None and not self.code_wrapping:
# We're not inside a triple quote and not inside code like
# print(
# """Not a docstring
# """)
if line[indent] != '#' and (indent == 0 or indent > self.last_indent):
quotematch = triple_quotes.match(line)
# It would be nice to only run the name_regex when
# quotematch wasn't None, but then we mishandle classes
# that don't have a docstring.
if not self.code_wrapping and self.last_indent >= 0 and indent > self.last_indent:
name = name_regex.match(self.last_line)
if name:
name = name.groups()[0]
self.qualified_name[indent] = name
elif quotematch:
self.qualified_name[indent] = '?'
self._update_quotetype(line)
if line[indent] != '#' and not self.code_wrapping:
self.last_line, self.last_indent = line, indent
self.code_wrapping = not (self.paren_count == self.bracket_count == self.curly_count == 0)
return quotematch
def ending_docstring(self, line):
r"""
Determines whether the input line ends a docstring.
INPUT:
- ``line`` -- a string, one line of an input file.
OUTPUT:
- an object that, when evaluated in a boolean context, gives
True or False depending on whether the input line marks the
end of a docstring.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.util import NestedName
sage: from sage.env import SAGE_SRC
sage: import os
sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py')
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.quotetype = "'''"
sage: FDS.ending_docstring("'''")
<...Match object...>
sage: FDS.ending_docstring('\"\"\"')
"""
quotematch = triple_quotes.match(line)
if quotematch is not None and quotematch.groups()[0] != self.quotetype:
quotematch = None
self._update_quotetype(line)
return quotematch
def _neutralize_doctests(self, reindent):
r"""
Return a string containing the source of ``self``, but with
doctests modified so they are not tested.
This function is used in creating doctests for ReST files,
since docstrings of Python functions defined inside verbatim
blocks screw up Python's doctest parsing.
INPUT:
- ``reindent`` -- an integer, the number of spaces to indent
the result.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import StringDocTestSource, PythonSource
sage: from sage.structure.dynamic_class import dynamic_class
sage: s = "'''\n sage: 2 + 2\n 4\n'''"
sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource))
sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime')
sage: print(PSS._neutralize_doctests(0))
'''
safe: 2 + 2
4
'''
"""
neutralized = []
in_docstring = False
self._init()
for lineno, line in self:
if not line.strip():
neutralized.append(line)
elif in_docstring:
if self.ending_docstring(line):
in_docstring = False
neutralized.append(" "*reindent + find_prompt.sub(r"\1safe:\3",line))
else:
if self.starting_docstring(line):
in_docstring = True
neutralized.append(" "*reindent + line)
return "".join(neutralized)
class TexSource(SourceLanguage):
"""
This class defines the functions needed for the extraction of
doctests from a LaTeX source.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: type(FDS)
<class 'sage.doctest.sources.TexFileSource'>
"""
# The same line can't both start and end a docstring
start_finish_can_overlap = False
def _init(self):
"""
This function is called before creating doctests from a Tex file.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.skipping
False
"""
self.skipping = False
def starting_docstring(self, line):
r"""
Determines whether the input line starts a docstring.
Docstring blocks in tex files are defined by verbatim or
lstlisting environments, and can be linked together by adding
%link immediately after the \end{verbatim} or \end{lstlisting}.
Within a verbatim (or lstlisting) block, you can tell Sage not to
process the rest of the block by including a %skip line.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- a boolean giving whether the input line marks the
start of a docstring (verbatim block).
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
We start docstrings with \begin{verbatim} or \begin{lstlisting}::
sage: FDS.starting_docstring(r"\begin{verbatim}")
True
sage: FDS.starting_docstring(r"\begin{lstlisting}")
True
sage: FDS.skipping
False
sage: FDS.ending_docstring("sage: 2+2")
False
sage: FDS.ending_docstring("4")
False
To start ignoring the rest of the verbatim block, use %skip::
sage: FDS.ending_docstring("%skip")
True
sage: FDS.skipping
True
sage: FDS.starting_docstring("sage: raise RuntimeError")
False
You can even pretend to start another verbatim block while skipping::
sage: FDS.starting_docstring(r"\begin{verbatim}")
False
sage: FDS.skipping
True
To stop skipping end the verbatim block::
sage: FDS.starting_docstring(r"\end{verbatim} %link")
False
sage: FDS.skipping
False
Linking works even when the block was ended while skipping::
sage: FDS.linking
True
sage: FDS.starting_docstring(r"\begin{verbatim}")
True
"""
if self.skipping:
if self.ending_docstring(line, check_skip=False):
self.skipping = False
return False
return bool(begin_verb.match(line) or begin_lstli.match(line))
def ending_docstring(self, line, check_skip=True):
r"""
Determines whether the input line ends a docstring.
Docstring blocks in tex files are defined by verbatim or
lstlisting environments, and can be linked together by adding
%link immediately after the \end{verbatim} or \end{lstlisting}.
Within a verbatim (or lstlisting) block, you can tell Sage not to
process the rest of the block by including a %skip line.
INPUT:
- ``line`` -- a string, one line of an input file
- ``check_skip`` -- boolean (default True), used internally in starting_docstring.
OUTPUT:
- a boolean giving whether the input line marks the
end of a docstring (verbatim block).
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_paper.tex"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.ending_docstring(r"\end{verbatim}")
True
sage: FDS.ending_docstring(r"\end{lstlisting}")
True
sage: FDS.linking
False
Use %link to link with the next verbatim block::
sage: FDS.ending_docstring(r"\end{verbatim}%link")
True
sage: FDS.linking
True
%skip also ends a docstring block::
sage: FDS.ending_docstring("%skip")
True
"""
m = end_verb.match(line)
if m:
if m.groups()[0]:
self.linking = True
else:
self.linking = False
return True
m = end_lstli.match(line)
if m:
if m.groups()[0]:
self.linking = True
else:
self.linking = False
return True
if check_skip and skip.match(line):
self.skipping = True
return True
return False
class RestSource(SourceLanguage):
"""
This class defines the functions needed for the extraction of
doctests from ReST sources.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: type(FDS)
<class 'sage.doctest.sources.RestFileSource'>
"""
# The same line can both start and end a docstring
start_finish_can_overlap = True
def _init(self):
"""
This function is called before creating doctests from a ReST file.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.link_all
False
"""
self.link_all = False
self.last_line = ""
self.last_indent = -1
self.first_line = False
self.skipping = False
def starting_docstring(self, line):
"""
A line ending with a double colon starts a verbatim block in a ReST file,
as does a line containing ``.. CODE-BLOCK:: language``.
This function also determines whether the docstring block
should be joined with the previous one, or should be skipped.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- either None or a Match object.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.starting_docstring("Hello world::")
True
sage: FDS.ending_docstring(" sage: 2 + 2")
False
sage: FDS.ending_docstring(" 4")
False
sage: FDS.ending_docstring("We are now done")
True
sage: FDS.starting_docstring(".. link")
sage: FDS.starting_docstring("::")
True
sage: FDS.linking
True
"""
if link_all.match(line):
self.link_all = True
if self.skipping:
end_block = self.ending_docstring(line)
if end_block:
self.skipping = False
else:
return False
m1 = double_colon.match(line)
m2 = code_block.match(line.lower())
starting = (m1 and not line.strip().startswith(".. ")) or m2
if starting:
self.linking = self.link_all or '.. link' in self.last_line
self.first_line = True
m = m1 or m2
indent = len(m.groups()[0])
if '.. skip' in self.last_line:
self.skipping = True
starting = False
else:
indent = self.last_indent
self.last_line, self.last_indent = line, indent
return starting
def ending_docstring(self, line):
"""
When the indentation level drops below the initial level the
block ends.
INPUT:
- ``line`` -- a string, one line of an input file
OUTPUT:
- a boolean, whether the verbatim block is ending.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS._init()
sage: FDS.starting_docstring("Hello world::")
True
sage: FDS.ending_docstring(" sage: 2 + 2")
False
sage: FDS.ending_docstring(" 4")
False
sage: FDS.ending_docstring("We are now done")
True
"""
if not line.strip():
return False
indent = whitespace.match(line).end()
if self.first_line:
self.first_line = False
if indent <= self.last_indent:
# We didn't indent at all
return True
self.last_indent = indent
return indent < self.last_indent
def parse_docstring(self, docstring, namespace, start):
r"""
Return a list of doctest defined in this docstring.
Code blocks in a REST file can contain python functions with
their own docstrings in addition to in-line doctests. We want
to include the tests from these inner docstrings, but Python's
doctesting module has a problem if we just pass on the whole
block, since it expects to get just a docstring, not the
Python code as well.
Our solution is to create a new doctest source from this code
block and append the doctests created from that source. We
then replace the occurrences of "sage:" and ">>>" occurring
inside a triple quote with "safe:" so that the doctest module
doesn't treat them as tests.
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults
sage: from sage.doctest.sources import FileDocTestSource
sage: from sage.doctest.parsing import SageDocTestParser
sage: from sage.doctest.util import NestedName
sage: filename = "sage_doc.rst"
sage: FDS = FileDocTestSource(filename,DocTestDefaults())
sage: FDS.parser = SageDocTestParser(set(['sage']))
sage: FDS.qualified_name = NestedName('sage_doc')
sage: s = "Some text::\n\n def example_python_function(a, \
....: b):\n '''\n Brief description \
....: of function.\n\n EXAMPLES::\n\n \
....: sage: test1()\n sage: test2()\n \
....: '''\n return a + b\n\n sage: test3()\n\nMore \
....: ReST documentation."
sage: tests = FDS.parse_docstring(s, {}, 100)
sage: len(tests)
2
sage: for ex in tests[0].examples:
....: print(ex.sage_source)
test3()
sage: for ex in tests[1].examples:
....: print(ex.sage_source)
test1()
test2()
sig_on_count() # check sig_on/off pairings (virtual doctest)
"""
PythonStringSource = dynamic_class("sage.doctest.sources.PythonStringSource",
(StringDocTestSource, PythonSource))
min_indent = self.parser._min_indent(docstring)
pysource = '\n'.join(l[min_indent:] for l in docstring.split('\n'))
inner_source = PythonStringSource(self.basename, pysource,
self.options,
self.printpath,
lineno_shift=start + 1)
inner_doctests, _ = inner_source._create_doctests(namespace, True)
safe_docstring = inner_source._neutralize_doctests(min_indent)
outer_doctest = self.parser.get_doctest(safe_docstring, namespace,
str(self.qualified_name),
self.printpath, start + 1)
return [outer_doctest] + inner_doctests
class DictAsObject(dict):
"""
A simple subclass of dict that inserts the items from the initializing dictionary into attributes.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({'a':2})
sage: D.a
2
"""
def __init__(self, attrs):
"""
Initialization.
INPUT:
- ``attrs`` -- a dictionary.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({'a':2})
sage: D.a == D['a']
True
sage: D.a
2
"""
super().__init__(attrs)
self.__dict__.update(attrs)
def __setitem__(self, ky, val):
"""
We preserve the ability to access entries through either the
dictionary or attribute interfaces.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({})
sage: D['a'] = 2
sage: D.a
2
"""
super().__setitem__(ky, val)
try:
super().__setattr__(ky, val)
except TypeError:
pass
def __setattr__(self, ky, val):
"""
We preserve the ability to access entries through either the
dictionary or attribute interfaces.
EXAMPLES::
sage: from sage.doctest.sources import DictAsObject
sage: D = DictAsObject({})
sage: D.a = 2
sage: D['a']
2
"""
super().__setitem__(ky, val)
super().__setattr__(ky, val) | /sagemath-repl-10.0b0.tar.gz/sagemath-repl-10.0b0/sage/doctest/sources.py | 0.438785 | 0.192027 | sources.py | pypi |
import io
import os
import zipfile
from sage.cpython.string import bytes_to_str
from sage.structure.sage_object import SageObject
from sage.misc.cachefunc import cached_method
INNER_HTML_TEMPLATE = """
<html>
<head>
<style>
* {{
margin: 0;
padding: 0;
overflow: hidden;
}}
body, html {{
height: 100%;
width: 100%;
}}
</style>
<script type="text/javascript" src="{path_to_jsmol}/JSmol.min.js"></script>
</head>
<body>
<script type="text/javascript">
delete Jmol._tracker; // Prevent JSmol from phoning home.
var script = {script};
var Info = {{
width: '{width}',
height: '{height}',
debug: false,
disableInitialConsole: true, // very slow when used with inline mesh
color: '#3131ff',
addSelectionOptions: false,
use: 'HTML5',
j2sPath: '{path_to_jsmol}/j2s',
script: script,
}};
var jmolApplet0 = Jmol.getApplet('jmolApplet0', Info);
</script>
</body>
</html>
"""
IFRAME_TEMPLATE = """
<iframe srcdoc="{escaped_inner_html}"
width="{width}"
height="{height}"
style="border: 0;">
</iframe>
"""
OUTER_HTML_TEMPLATE = """
<html>
<head>
<title>JSmol 3D Scene</title>
</head>
</body>
{iframe}
</body>
</html>
""".format(iframe=IFRAME_TEMPLATE)
class JSMolHtml(SageObject):
def __init__(self, jmol, path_to_jsmol=None, width='100%', height='100%'):
"""
INPUT:
- ``jmol`` -- 3-d graphics or
:class:`sage.repl.rich_output.output_graphics3d.OutputSceneJmol`
instance. The 3-d scene to show.
- ``path_to_jsmol`` -- string (optional, default is
``'/nbextensions/jupyter-jsmol/jsmol'``). The path (relative or absolute)
where ``JSmol.min.js`` is served on the web server.
- ``width`` -- integer or string (optional, default:
``'100%'``). The width of the JSmol applet using CSS
dimensions.
- ``height`` -- integer or string (optional, default:
``'100%'``). The height of the JSmol applet using CSS
dimensions.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: JSMolHtml(sphere(), width=500, height=300)
JSmol Window 500x300
"""
from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
if not isinstance(jmol, OutputSceneJmol):
jmol = jmol._rich_repr_jmol()
self._jmol = jmol
self._zip = zipfile.ZipFile(io.BytesIO(self._jmol.scene_zip.get()))
if path_to_jsmol is None:
self._path = os.path.join('/', 'nbextensions', 'jupyter-jsmol', 'jsmol')
else:
self._path = path_to_jsmol
self._width = width
self._height = height
@cached_method
def script(self):
r"""
Return the JMol script file.
This method extracts the Jmol script from the Jmol spt file (a
zip archive) and inlines meshes.
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jsmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: jsmol.script()
'data "model list"\n10\nempt...aliasdisplay on;\n'
"""
script = []
with self._zip.open('SCRIPT') as SCRIPT:
for line in SCRIPT:
if line.startswith(b'pmesh'):
command, obj, meshfile = line.split(b' ', 3)
assert command == b'pmesh'
if meshfile not in [b'dots\n', b'mesh\n']:
assert (meshfile.startswith(b'"') and
meshfile.endswith(b'"\n'))
meshfile = bytes_to_str(meshfile[1:-2]) # strip quotes
script += [
'pmesh {0} inline "'.format(bytes_to_str(obj)),
bytes_to_str(self._zip.open(meshfile).read()),
'"\n'
]
continue
script += [bytes_to_str(line)]
return ''.join(script)
def js_script(self):
r"""
The :meth:`script` as Javascript string.
Since the many shortcomings of Javascript include multi-line
strings, this actually returns Javascript code to reassemble
the script from a list of strings.
OUTPUT:
String. Javascript code that evaluates to :meth:`script` as
Javascript string.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jsmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: print(jsmol.js_script())
[
'data "model list"',
...
'isosurface fullylit; pmesh o* fullylit; set antialiasdisplay on;',
].join('\n');
"""
script = [r"["]
for line in self.script().splitlines():
script += [r" '{0}',".format(line)]
script += [r"].join('\n');"]
return '\n'.join(script)
def _repr_(self):
"""
Return as string representation
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: JSMolHtml(OutputSceneJmol.example(), width=500, height=300)._repr_()
'JSmol Window 500x300'
"""
return 'JSmol Window {0}x{1}'.format(self._width, self._height)
def inner_html(self):
"""
Return a HTML document containing a JSmol applet
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: print(jmol.inner_html())
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
...
</html>
"""
return INNER_HTML_TEMPLATE.format(
script=self.js_script(),
width=self._width,
height=self._height,
path_to_jsmol=self._path,
)
def iframe(self):
"""
Return HTML iframe
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jmol = JSMolHtml(OutputSceneJmol.example())
sage: print(jmol.iframe())
<iframe srcdoc="
...
</iframe>
"""
escaped_inner_html = self.inner_html().replace('"', '"')
return IFRAME_TEMPLATE.format(width=self._width,
height=self._height,
escaped_inner_html=escaped_inner_html)
def outer_html(self):
"""
Return a HTML document containing an iframe with a JSmol applet
OUTPUT:
String
EXAMPLES::
sage: from sage.repl.display.jsmol_iframe import JSMolHtml
sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
sage: jmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300)
sage: print(jmol.outer_html())
<html>
<head>
<title>JSmol 3D Scene</title>
</head>
</body>
<BLANKLINE>
<iframe srcdoc="
...
</html>
"""
escaped_inner_html = self.inner_html().replace('"', '"')
outer = OUTER_HTML_TEMPLATE.format(
script=self.js_script(),
width=self._width,
height=self._height,
escaped_inner_html=escaped_inner_html,
)
return outer | /sagemath-repl-10.0b0.tar.gz/sagemath-repl-10.0b0/sage/repl/display/jsmol_iframe.py | 0.664867 | 0.198219 | jsmol_iframe.py | pypi |
import os
import errno
import warnings
from sage.env import (
SAGE_DOC, SAGE_VENV, SAGE_EXTCODE,
SAGE_VERSION,
THREEJS_DIR,
)
class SageKernelSpec():
def __init__(self, prefix=None):
"""
Utility to manage SageMath kernels and extensions
INPUT:
- ``prefix`` -- (optional, default: ``sys.prefix``)
directory for the installation prefix
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: prefix = tmp_dir()
sage: spec = SageKernelSpec(prefix=prefix)
sage: spec._display_name # random output
'SageMath 6.9'
sage: spec.kernel_dir == SageKernelSpec(prefix=prefix).kernel_dir
True
"""
self._display_name = 'SageMath {0}'.format(SAGE_VERSION)
if prefix is None:
from sys import prefix
jupyter_dir = os.path.join(prefix, "share", "jupyter")
self.nbextensions_dir = os.path.join(jupyter_dir, "nbextensions")
self.kernel_dir = os.path.join(jupyter_dir, "kernels", self.identifier())
self._mkdirs()
def _mkdirs(self):
"""
Create necessary parent directories
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._mkdirs()
sage: os.path.isdir(spec.nbextensions_dir)
True
"""
def mkdir_p(path):
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
mkdir_p(self.nbextensions_dir)
mkdir_p(self.kernel_dir)
@classmethod
def identifier(cls):
"""
Internal identifier for the SageMath kernel
OUTPUT: the string ``"sagemath"``.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: SageKernelSpec.identifier()
'sagemath'
"""
return 'sagemath'
def symlink(self, src, dst):
"""
Symlink ``src`` to ``dst``
This is not an atomic operation.
Already-existing symlinks will be deleted, already existing
non-empty directories will be kept.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: path = tmp_dir()
sage: spec.symlink(os.path.join(path, 'a'), os.path.join(path, 'b'))
sage: os.listdir(path)
['b']
"""
try:
os.remove(dst)
except OSError as err:
if err.errno == errno.EEXIST:
return
os.symlink(src, dst)
def use_local_threejs(self):
"""
Symlink threejs to the Jupyter notebook.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec.use_local_threejs()
sage: threejs = os.path.join(spec.nbextensions_dir, 'threejs-sage')
sage: os.path.isdir(threejs)
True
"""
src = THREEJS_DIR
dst = os.path.join(self.nbextensions_dir, 'threejs-sage')
self.symlink(src, dst)
def _kernel_cmd(self):
"""
Helper to construct the SageMath kernel command.
OUTPUT:
List of strings. The command to start a new SageMath kernel.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._kernel_cmd()
['/.../sage',
'--python',
'-m',
'sage.repl.ipython_kernel',
'-f',
'{connection_file}']
"""
return [
os.path.join(SAGE_VENV, 'bin', 'sage'),
'--python',
'-m', 'sage.repl.ipython_kernel',
'-f', '{connection_file}',
]
def kernel_spec(self):
"""
Return the kernel spec as Python dictionary
OUTPUT:
A dictionary. See the Jupyter documentation for details.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec.kernel_spec()
{'argv': ..., 'display_name': 'SageMath ...', 'language': 'sage'}
"""
return dict(
argv=self._kernel_cmd(),
display_name=self._display_name,
language='sage',
)
def _install_spec(self):
"""
Install the SageMath Jupyter kernel
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._install_spec()
"""
jsonfile = os.path.join(self.kernel_dir, "kernel.json")
import json
with open(jsonfile, 'w') as f:
json.dump(self.kernel_spec(), f)
def _symlink_resources(self):
"""
Symlink miscellaneous resources
This method symlinks additional resources (like the SageMath
documentation) into the SageMath kernel directory. This is
necessary to make the help links in the notebook work.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec._install_spec()
sage: spec._symlink_resources()
"""
path = os.path.join(SAGE_EXTCODE, 'notebook-ipython')
for filename in os.listdir(path):
self.symlink(
os.path.join(path, filename),
os.path.join(self.kernel_dir, filename)
)
self.symlink(
SAGE_DOC,
os.path.join(self.kernel_dir, 'doc')
)
@classmethod
def update(cls, *args, **kwds):
"""
Configure the Jupyter notebook for the SageMath kernel
This method does everything necessary to use the SageMath kernel,
you should never need to call any of the other methods
directly.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: SageKernelSpec.update(prefix=tmp_dir())
"""
instance = cls(*args, **kwds)
instance.use_local_threejs()
instance._install_spec()
instance._symlink_resources()
@classmethod
def check(cls):
"""
Check that the SageMath kernel can be discovered by its name (sagemath).
This method issues a warning if it cannot -- either because it is not installed,
or it is shadowed by a different kernel of this name, or Jupyter is
misconfigured in a different way.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: SageKernelSpec.check() # random
"""
from jupyter_client.kernelspec import get_kernel_spec, NoSuchKernel
ident = cls.identifier()
try:
spec = get_kernel_spec(ident)
except NoSuchKernel:
warnings.warn(f'no kernel named {ident} is accessible; '
'check your Jupyter configuration '
'(see https://docs.jupyter.org/en/latest/use/jupyter-directories.html)')
else:
from pathlib import Path
if Path(spec.argv[0]).resolve() != Path(os.path.join(SAGE_VENV, 'bin', 'sage')).resolve():
warnings.warn(f'the kernel named {ident} does not seem to correspond to this '
'installation of SageMath; check your Jupyter configuration '
'(see https://docs.jupyter.org/en/latest/use/jupyter-directories.html)')
def have_prerequisites(debug=True):
"""
Check that we have all prerequisites to run the Jupyter notebook.
In particular, the Jupyter notebook requires OpenSSL whether or
not you are using https. See :trac:`17318`.
INPUT:
``debug`` -- boolean (default: ``True``). Whether to print debug
information in case that prerequisites are missing.
OUTPUT:
Boolean.
EXAMPLES::
sage: from sage.repl.ipython_kernel.install import have_prerequisites
sage: have_prerequisites(debug=False) in [True, False]
True
"""
try:
from notebook.notebookapp import NotebookApp
return True
except ImportError:
if debug:
import traceback
traceback.print_exc()
return False | /sagemath-repl-10.0b0.tar.gz/sagemath-repl-10.0b0/sage/repl/ipython_kernel/install.py | 0.451327 | 0.153835 | install.py | pypi |
r"""
Parallel Interface to the Sage interpreter
This is an expect interface to \emph{multiple} copy of the \sage
interpreter, which can all run simultaneous calculations. A PSage
object does not work as well as the usual Sage object, but does have
the great property that when you construct an object in a PSage you
get back a prompt immediately. All objects constructed for that
PSage print <<currently executing code>> until code execution
completes, when they print as normal.
\note{BUG -- currently non-idle PSage subprocesses do not stop when
\sage exits. I would very much like to fix this but don't know how.}
EXAMPLES:
We illustrate how to factor 3 integers in parallel.
First start up 3 parallel Sage interfaces::
sage: v = [PSage() for _ in range(3)]
Next, request factorization of one random integer in each copy. ::
sage: w = [x('factor(2^%s-1)'% randint(250,310)) for x in v] # long time (5s on sage.math, 2011)
Print the status::
sage: w # long time, random output (depends on timing)
[3 * 11 * 31^2 * 311 * 11161 * 11471 * 73471 * 715827883 * 2147483647 * 4649919401 * 18158209813151 * 5947603221397891 * 29126056043168521,
<<currently executing code>>,
9623 * 68492481833 * 23579543011798993222850893929565870383844167873851502677311057483194673]
Note that at the point when we printed two of the factorizations had
finished but a third one hadn't. A few seconds later all three have
finished::
sage: w # long time, random output
[3 * 11 * 31^2 * 311 * 11161 * 11471 * 73471 * 715827883 * 2147483647 * 4649919401 * 18158209813151 * 5947603221397891 * 29126056043168521,
23^2 * 47 * 89 * 178481 * 4103188409 * 199957736328435366769577 * 44667711762797798403039426178361,
9623 * 68492481833 * 23579543011798993222850893929565870383844167873851502677311057483194673]
"""
import os
import time
from .sage0 import Sage, SageElement
from pexpect import ExceptionPexpect
number = 0
class PSage(Sage):
def __init__(self, **kwds):
if 'server' in kwds:
raise NotImplementedError("PSage doesn't work on remote server yet.")
Sage.__init__(self, **kwds)
import sage.misc.misc
T = sage.misc.temporary_file.tmp_dir('sage_smp')
self.__tmp_dir = T
self.__tmp = '%s/lock' % T
self._unlock()
self._unlock_code = "with open('%s', 'w') as f: f.write('__unlocked__')" % self.__tmp
global number
self._number = number
number += 1
def _repr_(self):
"""
TESTS::
sage: from sage.interfaces.psage import PSage
sage: PSage() # indirect doctest
A running non-blocking (parallel) instance of Sage (number ...)
"""
return 'A running non-blocking (parallel) instance of Sage (number %s)'%(self._number)
def _unlock(self):
self._locked = False
with open(self.__tmp, 'w') as fobj:
fobj.write('__unlocked__')
def _lock(self):
self._locked = True
with open(self.__tmp, 'w') as fobj:
fobj.write('__locked__')
def _start(self):
Sage._start(self)
self.expect().timeout = 0.25
self.expect().delaybeforesend = 0.01
def is_locked(self) -> bool:
try:
with open(self.__tmp) as fobj:
if fobj.read() != '__locked__':
return False
except FileNotFoundError:
# Directory may have already been deleted :trac:`30730`
return False
# looks like we are locked, but check health first
try:
self.expect().expect(self._prompt)
self.expect().expect(self._prompt)
except ExceptionPexpect:
return False
return True
def __del__(self):
"""
TESTS:
Check that :trac:`29989` is fixed::
sage: PSage().__del__()
"""
try:
files = os.listdir(self.__tmp_dir)
for x in files:
os.remove(os.path.join(self.__tmp_dir, x))
os.removedirs(self.__tmp_dir)
except OSError:
pass
if not (self._expect is None):
cmd = 'kill -9 %s'%self._expect.pid
os.system(cmd)
def eval(self, x, strip=True, **kwds):
"""
x -- code
strip --ignored
"""
if self.is_locked():
return "<<currently executing code>>"
if self._locked:
self._locked = False
#self._expect.expect('__unlocked__')
self.expect().send('\n')
self.expect().expect(self._prompt)
self.expect().expect(self._prompt)
try:
return Sage.eval(self, x, **kwds)
except ExceptionPexpect:
return "<<currently executing code>>"
def get(self, var):
"""
Get the value of the variable var.
"""
try:
return self.eval('print(%s)' % var)
except ExceptionPexpect:
return "<<currently executing code>>"
def set(self, var, value):
"""
Set the variable var to the given value.
"""
cmd = '%s=%s'%(var,value)
self._send_nowait(cmd)
time.sleep(0.02)
def _send_nowait(self, x):
if x.find('\n') != -1:
raise ValueError("x must not have any newlines")
# Now we want the client Python process to execute two things.
# The first is x and the second is c. The effect of c
# will be to unlock the lock.
if self.is_locked():
return "<<currently executing code>>"
E = self.expect()
self._lock()
E.write(self.preparse(x) + '\n')
try:
E.expect(self._prompt)
except ExceptionPexpect:
pass
E.write(self._unlock_code + '\n\n')
def _object_class(self):
return PSageElement
class PSageElement(SageElement):
def is_locked(self):
return self.parent().is_locked() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/interfaces/psage.py | 0.631935 | 0.472318 | psage.py | pypi |
r"""
Abstract base classes for interface elements
"""
class AxiomElement:
r"""
Abstract base class for :class:`~sage.interfaces.axiom.AxiomElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.AxiomElement.__subclasses__()) <= 1
True
"""
pass
class ExpectElement:
r"""
Abstract base class for :class:`~sage.interfaces.expect.ExpectElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.ExpectElement.__subclasses__()) <= 1
True
"""
pass
class FriCASElement:
r"""
Abstract base class for :class:`~sage.interfaces.fricas.FriCASElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.FriCASElement.__subclasses__()) <= 1
True
"""
pass
class GapElement:
r"""
Abstract base class for :class:`~sage.interfaces.gap.GapElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.GapElement.__subclasses__()) <= 1
True
"""
pass
class GpElement:
r"""
Abstract base class for :class:`~sage.interfaces.gp.GpElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.GpElement.__subclasses__()) <= 1
True
"""
pass
class Macaulay2Element:
r"""
Abstract base class for :class:`~sage.interfaces.macaulay2.Macaulay2Element`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.Macaulay2Element.__subclasses__()) <= 1
True
"""
pass
class MagmaElement:
r"""
Abstract base class for :class:`~sage.interfaces.magma.MagmaElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.MagmaElement.__subclasses__()) <= 1
True
"""
pass
class SingularElement:
r"""
Abstract base class for :class:`~sage.interfaces.singular.SingularElement`.
This class is defined for the purpose of ``isinstance`` tests. It should not be
instantiated.
EXAMPLES:
By design, there is a unique direct subclass::
sage: len(sage.interfaces.abc.SingularElement.__subclasses__()) <= 1
True
"""
pass | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/interfaces/abc.py | 0.849035 | 0.57093 | abc.py | pypi |
import os
from sage.misc.cachefunc import cached_function
@cached_function
def sage_spawned_process_file():
"""
EXAMPLES::
sage: from sage.interfaces.quit import sage_spawned_process_file
sage: len(sage_spawned_process_file()) > 1
True
"""
# This is the old value of SAGE_TMP. Until sage-cleaner is
# completely removed, we need to leave these spawned_processes
# files where sage-cleaner will look for them.
from sage.env import DOT_SAGE, HOSTNAME
d = os.path.join(DOT_SAGE, "temp", HOSTNAME, str(os.getpid()))
os.makedirs(d, exist_ok=True)
return os.path.join(d, "spawned_processes")
def register_spawned_process(pid, cmd=''):
"""
Write a line to the ``spawned_processes`` file with the given
``pid`` and ``cmd``.
"""
if cmd != '':
cmd = cmd.strip().split()[0]
# This is safe, since only this process writes to this file.
try:
with open(sage_spawned_process_file(), 'a') as o:
o.write('%s %s\n'%(pid, cmd))
except IOError:
pass
else:
# If sage is being used as a python library, we need to launch
# the cleaner ourselves upon being told that there will be
# something to clean.
from sage.interfaces.cleaner import start_cleaner
start_cleaner()
expect_objects = []
def expect_quitall(verbose=False):
"""
EXAMPLES::
sage: sage.interfaces.quit.expect_quitall()
sage: gp.eval('a=10')
'10'
sage: gp('a')
10
sage: sage.interfaces.quit.expect_quitall()
sage: gp('a')
a
sage: sage.interfaces.quit.expect_quitall(verbose=True)
Exiting PARI/GP interpreter with PID ... running .../gp --fast --emacs --quiet --stacksize 10000000
"""
for P in expect_objects:
R = P()
if R is not None:
try:
R.quit(verbose=verbose)
except RuntimeError:
pass
kill_spawned_jobs()
def kill_spawned_jobs(verbose=False):
"""
INPUT:
- ``verbose`` -- bool (default: False); if True, display a
message each time a process is sent a kill signal
EXAMPLES::
sage: gp.eval('a=10')
'10'
sage: sage.interfaces.quit.kill_spawned_jobs(verbose=False)
sage: sage.interfaces.quit.expect_quitall()
sage: gp.eval('a=10')
'10'
sage: sage.interfaces.quit.kill_spawned_jobs(verbose=True)
Killing spawned job ...
After doing the above, we do the following to avoid confusion in other doctests::
sage: sage.interfaces.quit.expect_quitall()
"""
fname = sage_spawned_process_file()
if not os.path.exists(fname):
return
with open(fname) as f:
for L in f:
i = L.find(' ')
pid = L[:i].strip()
try:
if verbose:
print("Killing spawned job %s" % pid)
os.killpg(int(pid), 9)
except OSError:
pass
def is_running(pid):
"""
Return True if and only if there is a process with id pid running.
"""
try:
os.kill(int(pid), 0)
return True
except (OSError, ValueError):
return False
def invalidate_all():
"""
Invalidate all of the expect interfaces.
This is used, e.g., by the fork-based @parallel decorator.
EXAMPLES::
sage: a = maxima(2); b = gp(3)
sage: a, b
(2, 3)
sage: sage.interfaces.quit.invalidate_all()
sage: a
(invalid Maxima object -- The maxima session in which this object was defined is no longer running.)
sage: b
(invalid PARI/GP interpreter object -- The pari session in which this object was defined is no longer running.)
However the maxima and gp sessions should still work out, though with their state reset:
sage: a = maxima(2); b = gp(3)
sage: a, b
(2, 3)
"""
for I in expect_objects:
I1 = I()
if I1:
I1.detach() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/interfaces/quit.py | 0.558809 | 0.323327 | quit.py | pypi |
from sympy.core.basic import Basic
from sympy.core.decorators import sympify_method_args
from sympy.core.sympify import sympify
from sympy.sets.sets import Set
@sympify_method_args
class SageSet(Set):
r"""
Wrapper for a Sage set providing the SymPy Set API.
Parents in the category :class:`sage.categories.sets_cat.Sets`, unless
a more specific method is implemented, convert to SymPy by creating
an instance of this class.
EXAMPLES::
sage: F = Family([2, 3, 5, 7]); F
Family (2, 3, 5, 7)
sage: sF = F._sympy_(); sF # indirect doctest
SageSet(Family (2, 3, 5, 7))
sage: sF._sage_() is F
True
sage: bool(sF)
True
sage: len(sF)
4
sage: list(sF)
[2, 3, 5, 7]
sage: sF.is_finite_set
True
"""
def __new__(cls, sage_set):
r"""
Construct a wrapper for a Sage set.
TESTS::
sage: from sage.interfaces.sympy_wrapper import SageSet
sage: F = Set([1, 2]); F
{1, 2}
sage: sF = SageSet(F); sF
SageSet({1, 2})
"""
return Basic.__new__(cls, sage_set)
def _sage_(self):
r"""
Return the underlying Sage set of the wrapper ``self``.
EXAMPLES::
sage: F = Family([1, 2])
sage: F is Family([1, 2])
False
sage: sF = F._sympy_(); sF
SageSet(Family (1, 2))
sage: sF._sage_() is F
True
"""
return self._args[0]
@property
def is_empty(self):
r"""
Return whether the set ``self`` is empty.
EXAMPLES::
sage: Empty = Family([])
sage: sEmpty = Empty._sympy_()
sage: sEmpty.is_empty
True
"""
return self._sage_().is_empty()
@property
def is_finite_set(self):
r"""
Return whether the set ``self`` is finite.
EXAMPLES::
sage: W = WeylGroup(["A",1,1])
sage: sW = W._sympy_(); sW
SageSet(Weyl Group of type ['A', 1, 1] (as a matrix group acting on the root space))
sage: sW.is_finite_set
False
"""
return self._sage_().is_finite()
@property
def is_iterable(self):
r"""
Return whether the set ``self`` is iterable.
EXAMPLES::
sage: W = WeylGroup(["A",1,1])
sage: sW = W._sympy_(); sW
SageSet(Weyl Group of type ['A', 1, 1] (as a matrix group acting on the root space))
sage: sW.is_iterable
True
"""
from sage.categories.enumerated_sets import EnumeratedSets
return self._sage_() in EnumeratedSets()
def __iter__(self):
r"""
Iterator for the set ``self``.
EXAMPLES::
sage: sPrimes = Primes()._sympy_(); sPrimes
SageSet(Set of all prime numbers: 2, 3, 5, 7, ...)
sage: iter_sPrimes = iter(sPrimes)
sage: next(iter_sPrimes), next(iter_sPrimes), next(iter_sPrimes)
(2, 3, 5)
"""
for element in self._sage_():
yield sympify(element)
def _contains(self, element):
"""
Return whether ``element`` is an element of the set ``self``.
EXAMPLES::
sage: sPrimes = Primes()._sympy_(); sPrimes
SageSet(Set of all prime numbers: 2, 3, 5, 7, ...)
sage: 91 in sPrimes
False
sage: from sympy.abc import p
sage: sPrimes.contains(p)
Contains(p, SageSet(Set of all prime numbers: 2, 3, 5, 7, ...))
sage: p in sPrimes
Traceback (most recent call last):
...
TypeError: did not evaluate to a bool: None
"""
if element.is_symbol:
# keep symbolic
return None
return element in self._sage_()
def __len__(self):
"""
Return the cardinality of the finite set ``self``.
EXAMPLES::
sage: sB3 = WeylGroup(["B", 3])._sympy_(); sB3
SageSet(Weyl Group of type ['B', 3] (as a matrix group acting on the ambient space))
sage: len(sB3)
48
"""
return len(self._sage_())
def __str__(self):
"""
Return the print representation of ``self``.
EXAMPLES::
sage: sPrimes = Primes()._sympy_()
sage: str(sPrimes) # indirect doctest
'SageSet(Set of all prime numbers: 2, 3, 5, 7, ...)'
sage: repr(sPrimes)
'SageSet(Set of all prime numbers: 2, 3, 5, 7, ...)'
"""
# Provide this method so that sympy's printing code does not try to inspect
# the Sage object.
return f"SageSet({self._sage_()})"
__repr__ = __str__ | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/interfaces/sympy_wrapper.py | 0.904021 | 0.541833 | sympy_wrapper.py | pypi |
import builtins
class ExtraTabCompletion():
def __dir__(self):
"""
Add to the dir() output
This is used by IPython to read off the tab completions.
EXAMPLES::
sage: from sage.interfaces.tab_completion import ExtraTabCompletion
sage: obj = ExtraTabCompletion()
sage: dir(obj)
Traceback (most recent call last):
...
NotImplementedError: <class 'sage.interfaces.tab_completion.ExtraTabCompletion'> must implement _tab_completion() method
"""
try:
tab_fn = self._tab_completion
except AttributeError:
raise NotImplementedError(
'{0} must implement _tab_completion() method'.format(self.__class__))
return dir(self.__class__) + list(self.__dict__) + tab_fn()
def completions(s, globs):
"""
Return a list of completions in the given context.
INPUT:
- ``s`` -- a string
- ``globs`` -- a string: object dictionary; context in which to
search for completions, e.g., :func:`globals()`
OUTPUT:
a list of strings
EXAMPLES::
sage: X.<x> = PolynomialRing(QQ)
sage: import sage.interfaces.tab_completion as s
sage: p = x**2 + 1
sage: s.completions('p.co',globals()) # indirect doctest
['p.coefficients',...]
sage: s.completions('dic',globals()) # indirect doctest
['dickman_rho', 'dict']
"""
if not s:
raise ValueError('empty string')
if '.' not in s:
n = len(s)
v = [x for x in globs if x[:n] == s]
v += [x for x in builtins.__dict__ if x[:n] == s]
else:
i = s.rfind('.')
method = s[i + 1:]
obj = s[:i]
n = len(method)
try:
O = eval(obj, globs)
D = dir(O)
if not method:
v = [obj + '.' + x for x in D if x and x[0] != '_']
else:
v = [obj + '.' + x for x in D if x[:n] == method]
except Exception:
v = []
return sorted(set(v)) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/interfaces/tab_completion.py | 0.601945 | 0.334943 | tab_completion.py | pypi |
from sage.structure.sage_object import SageObject
from sage.combinat.rigged_configurations.tensor_product_kr_tableaux import TensorProductOfKirillovReshetikhinTableaux
from sage.combinat.rigged_configurations.kr_tableaux import KirillovReshetikhinTableaux
from sage.combinat.rigged_configurations.rigged_configurations import RiggedConfigurations
from sage.combinat.root_system.cartan_type import CartanType
from sage.typeset.ascii_art import ascii_art
from sage.rings.integer_ring import ZZ
class SolitonCellularAutomata(SageObject):
r"""
Soliton cellular automata.
Fix an affine Lie algebra `\mathfrak{g}` with index `I` and
classical index set `I_0`. Fix some `r \in I_0`. A *soliton
cellular automaton* (SCA) is a discrete (non-linear) dynamical
system given as follows. The *states* are given by elements of
a semi-infinite tensor product of Kirillov-Reshetihkin crystals
`B^{r,1}`, where only a finite number of factors are not the
maximal element `u`, which we will call the *vacuum*. The *time
evolution* `T_s` is defined by
.. MATH::
R(p \otimes u_s) = u_s \otimes T_s(p),
where `p = \cdots \otimes p_3 \otimes p_2 \otimes p_1 \otimes p_0`
is a state and `u_s` is the maximal element of `B^{r,s}`.
In more detail, we have `R(p_i \otimes u^{(i)}) =
u^{(i+1)} \otimes \widetilde{p}_i` with `u^{(0)} = u_s` and
`T_s(p) = \cdots \otimes \widetilde{p}_1 \otimes \widetilde{p}_0`.
This is well-defined since `R(u \otimes u_s) = u_s \otimes u`
and `u^{(k)} = u_s` for all `k \gg 1`.
INPUT:
- ``initial_state`` -- the list of elements, can also be a string
when ``vacuum`` is 1 and ``n`` is `\mathfrak{sl}_n`
- ``cartan_type`` -- (default: 2) the value ``n``, for `\mathfrak{sl}_n`,
or a Cartan type
- ``r`` -- (default: 1) the node index `r`; typically this
corresponds to the height of the vacuum element
EXAMPLES:
We first create an example in `\mathfrak{sl}_4` (type `A_3`)::
sage: B = SolitonCellularAutomata('3411111122411112223', 4)
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: []
current state:
34......224....2223
We then apply an standard evolution::
sage: B.evolve()
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19)]
current state:
.................34.....224...2223....
Next, we apply a smaller carrier evolution. Note that the soliton
of size 4 moves only 3 steps::
sage: B.evolve(3)
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19), (1, 3)]
current state:
...............34....224...2223.......
We can also use carriers corresponding to non-vacuum indices.
In these cases, the carrier might not return to its initial
state, which results in a message being displayed about
the resulting state of the carrier::
sage: B.evolve(carrier_capacity=7, carrier_index=3)
Last carrier:
1 1 1 1 1 1 1
2 2 2 2 2 3 3
3 3 3 3 3 4 4
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19), (1, 3), (3, 7)]
current state:
.....................23....222....2223.......
sage: B.evolve(carrier_capacity=3, carrier_index=2)
Last carrier:
1 1 1
2 2 3
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19), (1, 3), (3, 7), (2, 3)]
current state:
.......................22.....223...2222........
To summarize our current evolutions, we can use :meth:`print_states`::
sage: B.print_states(5)
t: 0
.............................34......224....2223
t: 1
...........................34.....224...2223....
t: 2
.........................34....224...2223.......
t: 3
........................23....222....2223.......
t: 4
.......................22.....223...2222........
To run the SCA further under the standard evolutions, one can use
:meth:`print_states` or :meth:`latex_states`::
sage: B.print_states(15)
t: 0
................................................34......224....2223
t: 1
..............................................34.....224...2223....
t: 2
............................................34....224...2223.......
t: 3
...........................................23....222....2223.......
t: 4
..........................................22.....223...2222........
t: 5
........................................22....223..2222............
t: 6
......................................22..2223..222................
t: 7
..................................2222..23...222...................
t: 8
..............................2222....23..222......................
t: 9
..........................2222......23.222.........................
t: 10
......................2222.......223.22............................
t: 11
..................2222........223..22..............................
t: 12
..............2222.........223...22................................
t: 13
..........2222..........223....22..................................
t: 14
......2222...........223.....22....................................
Next, we use `r = 2` in type `A_3`. Here, we give the data as lists of
values corresponding to the entries of the column of height 2 from
the largest entry to smallest. Our columns are drawn in French
convention::
sage: B = SolitonCellularAutomata([[4,1],[4,1],[2,1],[2,1],[2,1],[2,1],[3,1],[3,1],[3,2]], 4, 2)
We perform 3 evolutions and obtain the following::
sage: B.evolve(number=3)
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 2
initial state:
44 333
11....112
evoltuions: [(2, 9), (2, 9), (2, 9)]
current state:
44 333
...11.112.........
We construct Example 2.9 from [LS2017]_::
sage: B = SolitonCellularAutomata([[2],[-3],[1],[1],[1],[4],[0],[-2],
....: [1],[1],[1],[1],[3],[-4],[-3],[-3],[1]], ['D',5,2])
sage: B.print_states(10)
t: 0 _ _ ___
..................................23...402....3433.
t: 1 _ _ ___
................................23..402...3433.....
t: 2 _ _ ___
..............................23.402..3433.........
t: 3 _ _ ___
...........................243.02.3433.............
t: 4 _ __ __
.......................2403..42333.................
t: 5 _ ___ _
...................2403...44243....................
t: 6 _ ___ _
...............2403....442.43......................
t: 7 _ ___ _
...........2403.....442..43........................
t: 8 _ ___ _
.......2403......442...43..........................
t: 9 _ ___ _
...2403.......442....43............................
Example 3.4 from [LS2017]_::
sage: B = SolitonCellularAutomata([['E'],[1],[1],[1],[3],[0],
....: [1],[1],[1],[1],[2],[-3],[-1],[1]], ['D',4,2])
sage: B.print_states(10)
t: 0 __
..........................................E...30....231.
t: 1 __
.........................................E..30..231.....
t: 2 _ _
........................................E303.21.........
t: 3 _ _
....................................303E2.22............
t: 4 _ _
................................303E...222..............
t: 5 _ _
............................303E......12................
t: 6 _ _
........................303E........1.2.................
t: 7 _ _
....................303E..........1..2..................
t: 8 _ _
................303E............1...2...................
t: 9 _ _
............303E..............1....2....................
Example 3.12 from [LS2017]_::
sage: B = SolitonCellularAutomata([[-1,3,2],[3,2,1],[3,2,1],[-3,2,1],
....: [-2,-3,1]], ['B',3,1], 3)
sage: B.print_states(6)
-1 -3-2
t: 0 3 2-3
. . . . . . . . . . . . . . . 2 . . 1 1
-1-3-2
t: 1 3 2-3
. . . . . . . . . . . . . . 2 1 1 . . .
-3-1
t: 2 2-2
. . . . . . . . . . . . 1-3 . . . . . .
-3-1 -3
t: 3 2-2 2
. . . . . . . . . 1 3 . 1 . . . . . . .
-3-1 -3
t: 4 2-2 2
. . . . . . 1 3 . . . 1 . . . . . . . .
-3-1 -3
t: 5 2-2 2
. . . 1 3 . . . . . 1 . . . . . . . . .
Example 4.12 from [LS2017]_::
sage: K = crystals.KirillovReshetikhin(['E',6,1], 1,1, 'KR')
sage: u = K.module_generators[0]
sage: x = u.f_string([1,3,4,5])
sage: y = u.f_string([1,3,4,2,5,6])
sage: a = u.f_string([1,3,4,2])
sage: B = SolitonCellularAutomata([a, u,u,u, x,y], ['E',6,1], 1)
sage: B
Soliton cellular automata of type ['E', 6, 1] and vacuum = 1
initial state:
(-2, 5) . . . (-5, 2, 6)(-2, -6, 4)
evoltuions: []
current state:
(-2, 5) . . . (-5, 2, 6)(-2, -6, 4)
sage: B.print_states(8)
t: 0 ...
t: 7
. (-2, 5)(-2, -5, 4, 6) ... (-6, 2) ...
"""
def __init__(self, initial_state, cartan_type=2, vacuum=1):
"""
Initialize ``self``.
EXAMPLES::
sage: B = SolitonCellularAutomata('3411111122411112223', 4)
sage: TestSuite(B).run()
"""
if cartan_type in ZZ:
cartan_type = CartanType(['A',cartan_type-1,1])
else:
cartan_type = CartanType(cartan_type)
self._cartan_type = cartan_type
self._vacuum = vacuum
K = KirillovReshetikhinTableaux(self._cartan_type, self._vacuum, 1)
try:
# FIXME: the maximal_vector() does not work in type E and F
self._vacuum_elt = K.maximal_vector()
except (ValueError, TypeError, AttributeError):
self._vacuum_elt = K.module_generators[0]
if isinstance(initial_state, str):
# We consider things 1-9
initial_state = [[ZZ(x) if x != '.' else ZZ.one()] for x in initial_state]
try:
KRT = TensorProductOfKirillovReshetikhinTableaux(self._cartan_type,
[[vacuum, len(st)//vacuum]
for st in initial_state])
self._states = [KRT(pathlist=initial_state)]
except TypeError:
KRT = TensorProductOfKirillovReshetikhinTableaux(self._cartan_type,
[[vacuum, 1]
for st in initial_state])
self._states = [KRT(*initial_state)]
self._evolutions = []
self._initial_carrier = []
self._nballs = len(self._states[0])
def __eq__(self, other):
"""
Check equality.
Two SCAs are equal when they have the same initial state
and evolutions.
TESTS::
sage: B1 = SolitonCellularAutomata('34112223', 4)
sage: B2 = SolitonCellularAutomata('34112223', 4)
sage: B1 == B2
True
sage: B1.evolve()
sage: B1 == B2
False
sage: B2.evolve()
sage: B1 == B2
True
sage: B1.evolve(5)
sage: B2.evolve(6)
sage: B1 == B2
False
"""
return (isinstance(other, SolitonCellularAutomata)
and self._states[0] == other._states[0]
and self._evolutions == other._evolutions)
def __ne__(self, other):
"""
Check non equality.
TESTS::
sage: B1 = SolitonCellularAutomata('34112223', 4)
sage: B2 = SolitonCellularAutomata('34112223', 4)
sage: B1 != B2
False
sage: B1.evolve()
sage: B1 != B2
True
sage: B2.evolve()
sage: B1 != B2
False
sage: B1.evolve(5)
sage: B2.evolve(6)
sage: B1 != B2
True
"""
return not (self == other)
# Evolution functions
# -------------------
def evolve(self, carrier_capacity=None, carrier_index=None, number=None):
r"""
Evolve ``self``.
Time evolution `T_s` of a SCA state `p` is determined by
.. MATH::
u_{r,s} \otimes T_s(p) = R(p \otimes u_{r,s}),
where `u_{r,s}` is the maximal element of `B^{r,s}`.
INPUT:
- ``carrier_capacity`` -- (default: the number of balls in
the system) the size `s` of carrier
- ``carrier_index`` -- (default: the vacuum index) the index `r`
of the carrier
- ``number`` -- (optional) the number of times to perform
the evolutions
To perform multiple evolutions of the SCA, ``carrier_capacity``
and ``carrier_index`` may be lists of the same length.
EXAMPLES::
sage: B = SolitonCellularAutomata('3411111122411112223', 4)
sage: for k in range(10):
....: B.evolve()
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19), (1, 19), (1, 19), (1, 19), (1, 19),
(1, 19), (1, 19), (1, 19), (1, 19), (1, 19)]
current state:
......2344.......222....23...............................
sage: B.reset()
sage: B.evolve(number=10); B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19), (1, 19), (1, 19), (1, 19), (1, 19),
(1, 19), (1, 19), (1, 19), (1, 19), (1, 19)]
current state:
......2344.......222....23...............................
sage: B.reset()
sage: B.evolve(carrier_capacity=[1,2,3,4,5,6,7,8,9,10]); B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
(1, 6), (1, 7), (1, 8), (1, 9), (1, 10)]
current state:
........2344....222..23..............................
sage: B.reset()
sage: B.evolve(carrier_index=[1,2,3])
Last carrier:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 4 4
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 19), (2, 19), (3, 19)]
current state:
..................................22......223...2222.....
sage: B.reset()
sage: B.evolve(carrier_capacity=[1,2,3], carrier_index=[1,2,3])
Last carrier:
1 1
3 4
Last carrier:
1 1 1
2 2 3
3 3 4
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(1, 1), (2, 2), (3, 3)]
current state:
.....22.......223....2222..
sage: B.reset()
sage: B.evolve(1, 2, number=3)
Last carrier:
1
3
Last carrier:
1
4
Last carrier:
1
3
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: [(2, 1), (2, 1), (2, 1)]
current state:
.24......222.....2222.
"""
if isinstance(carrier_capacity, (list, tuple)):
if not isinstance(carrier_index, (list, tuple)):
carrier_index = [carrier_index] * len(carrier_capacity)
if len(carrier_index) != len(carrier_capacity):
raise ValueError("carrier_index and carrier_capacity"
" must have the same length")
for i, r in zip(carrier_capacity, carrier_index):
self.evolve(i, r)
return
if isinstance(carrier_index, (list, tuple)):
# carrier_capacity must be not be a list/tuple if given
for r in carrier_index:
self.evolve(carrier_capacity, r)
return
if carrier_capacity is None:
carrier_capacity = self._nballs
if carrier_index is None:
carrier_index = self._vacuum
if number is not None:
for _ in range(number):
self.evolve(carrier_capacity, carrier_index)
return
passed = False
K = KirillovReshetikhinTableaux(self._cartan_type, carrier_index, carrier_capacity)
try:
# FIXME: the maximal_vector() does not work in type E and F
empty_carrier = K.maximal_vector()
except (ValueError, TypeError, AttributeError):
empty_carrier = K.module_generators[0]
self._initial_carrier.append(empty_carrier)
carrier_factor = (carrier_index, carrier_capacity)
last_final_carrier = empty_carrier
state = self._states[-1]
dims = state.parent().dims
while not passed:
KRT = TensorProductOfKirillovReshetikhinTableaux(self._cartan_type,
dims + (carrier_factor,))
elt = KRT(*(list(state) + [empty_carrier]))
RC = RiggedConfigurations(self._cartan_type, (carrier_factor,) + dims)
elt2 = RC(*elt.to_rigged_configuration()).to_tensor_product_of_kirillov_reshetikhin_tableaux()
# Back to an empty carrier or we are not getting any better
if elt2[0] == empty_carrier or elt2[0] == last_final_carrier:
passed = True
KRT = TensorProductOfKirillovReshetikhinTableaux(self._cartan_type, dims)
self._states.append(KRT(*elt2[1:]))
self._evolutions.append(carrier_factor)
if elt2[0] != empty_carrier:
print("Last carrier:")
print(ascii_art(last_final_carrier))
else:
# We need to add more vacuum states
last_final_carrier = elt2[0]
dims = tuple([(self._vacuum, 1)]*carrier_capacity) + dims
def state_evolution(self, num):
"""
Return a list of the carrier values at state ``num`` evolving to
the next state.
If ``num`` is greater than the number of states, this performs
the standard evolution `T_k`, where `k` is the number of balls
in the system.
.. SEEALSO::
:meth:`print_state_evolution`, :meth:`latex_state_evolution`
EXAMPLES::
sage: B = SolitonCellularAutomata('1113123', 3)
sage: B.evolve(3)
sage: B.state_evolution(0)
[[[1, 1, 1]],
[[1, 1, 1]],
[[1, 1, 1]],
[[1, 1, 3]],
[[1, 1, 2]],
[[1, 2, 3]],
[[1, 1, 3]],
[[1, 1, 1]]]
sage: B.state_evolution(2)
[[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 3]],
[[1, 1, 1, 1, 1, 3, 3]],
[[1, 1, 1, 1, 1, 1, 3]],
[[1, 1, 1, 1, 1, 1, 2]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1, 1]]]
"""
if num + 2 > len(self._states):
for _ in range(num + 2 - len(self._states)):
self.evolve()
carrier = KirillovReshetikhinTableaux(self._cartan_type, *self._evolutions[num])
num_factors = len(self._states[num+1])
vacuum = self._vacuum_elt
state = [vacuum]*(num_factors - len(self._states[num])) + list(self._states[num])
final = []
u = [self._initial_carrier[num]]
# Assume every element has the same parent
R = state[0].parent().R_matrix(carrier)
for elt in reversed(state):
up, eltp = R(R.domain()(elt, u[0]))
u.insert(0, up)
final.insert(0, eltp)
return u
def reset(self):
r"""
Reset ``self`` back to the initial state.
EXAMPLES::
sage: B = SolitonCellularAutomata('34111111224', 4)
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224
evoltuions: []
current state:
34......224
sage: B.evolve()
sage: B.evolve()
sage: B.evolve()
sage: B.evolve()
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224
evoltuions: [(1, 11), (1, 11), (1, 11), (1, 11)]
current state:
...34..224............
sage: B.reset()
sage: B
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224
evoltuions: []
current state:
34......224
"""
self._states = [self._states[0]]
self._evolutions = []
self._initial_carrier = []
# Output functions
# ----------------
def _column_repr(self, b, vacuum_letter=None):
"""
Return a string representation of the column ``b``.
EXAMPLES::
sage: B = SolitonCellularAutomata([[-2,1],[2,1],[-3,1],[-3,2]], ['D',4,2], 2)
sage: K = crystals.KirillovReshetikhin(['D',4,2], 2,1, 'KR')
sage: B._column_repr(K(-2,1))
-2
1
sage: B._column_repr(K.module_generator())
2
1
sage: B._column_repr(K.module_generator(), 'x')
x
"""
if vacuum_letter is not None and b == self._vacuum_elt:
return ascii_art(vacuum_letter)
if self._vacuum_elt.parent()._tableau_height == 1:
s = str(b[0])
return ascii_art(s if s[0] != '-' else '_\n' + s[1:])
letter_str = [str(letter) for letter in b]
max_width = max(len(s) for s in letter_str)
return ascii_art('\n'.join(' '*(max_width-len(s)) + s for s in letter_str))
def _repr_state(self, state, vacuum_letter='.'):
"""
Return a string representation of ``state``.
EXAMPLES::
sage: B = SolitonCellularAutomata('3411111122411112223', 4)
sage: B.evolve(number=10)
sage: print(B._repr_state(B._states[0]))
34......224....2223
sage: print(B._repr_state(B._states[-1], '_'))
______2344_______222____23_______________________________
"""
output = [self._column_repr(b, vacuum_letter) for b in state]
max_width = max(cell.width() for cell in output)
return sum((ascii_art(' '*(max_width-b.width())) + b for b in output),
ascii_art(''))
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: SolitonCellularAutomata('3411111122411112223', 4)
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
34......224....2223
evoltuions: []
current state:
34......224....2223
sage: SolitonCellularAutomata([[4,1],[2,1],[2,1],[3,1],[3,2]], 4, 2)
Soliton cellular automata of type ['A', 3, 1] and vacuum = 2
initial state:
4 33
1..12
evoltuions: []
current state:
4 33
1..12
sage: SolitonCellularAutomata([[4,1],[2,1],[2,1],[3,1],[3,2]], ['C',4,1], 2)
Soliton cellular automata of type ['C', 4, 1] and vacuum = 2
initial state:
4 33
1..12
evoltuions: []
current state:
4 33
1..12
sage: SolitonCellularAutomata([[4,3],[2,1],[-3,1],[-3,2]], ['B',4,1], 2)
Soliton cellular automata of type ['B', 4, 1] and vacuum = 2
initial state:
4 -3-3
3 . 1 2
evoltuions: []
current state:
4 -3-3
3 . 1 2
"""
ret = "Soliton cellular automata of type {} and vacuum = {}\n".format(self._cartan_type, self._vacuum)
ret += " initial state:\n{}\n evoltuions: {}\n current state:\n{}".format(
ascii_art(' ') + self._repr_state(self._states[0]),
self._evolutions,
ascii_art(' ') + self._repr_state(self._states[-1])
)
return ret
def print_state(self, num=None, vacuum_letter='.', remove_trailing_vacuums=False):
"""
Print the state ``num``.
INPUT:
- ``num`` -- (default: the current state) the state to print
- ``vacuum_letter`` -- (default: ``'.'``) the letter to print
for the vacuum
- ``remove_trailing_vacuums`` -- (default: ``False``) if ``True``
then this does not print the vacuum letters at the right end
of the state
EXAMPLES::
sage: B = SolitonCellularAutomata('3411111122411112223', 4)
sage: B.print_state()
34......224....2223
sage: B.evolve(number=2)
sage: B.print_state(vacuum_letter=',')
,,,,,,,,,,,,,,,34,,,,224,,2223,,,,,,,,
sage: B.print_state(10, '_')
______2344_______222____23_______________________________
sage: B.print_state(10, '_', True)
______2344_______222____23
"""
if num is None:
num = len(self._states) - 1
if num + 1 > len(self._states):
for _ in range(num + 1 - len(self._states)):
self.evolve()
state = self._states[num]
if remove_trailing_vacuums:
pos = len(state) - 1
# The pos goes negative if and only if the state consists
# entirely of vacuum elements.
while pos >= 0 and state[pos] == self._vacuum_elt:
pos -= 1
state = state[:pos+1]
print(self._repr_state(state, vacuum_letter))
def print_states(self, num=None, vacuum_letter='.'):
r"""
Print the first ``num`` states of ``self``.
.. NOTE::
If the number of states computed for ``self`` is less than
``num``, then this evolves the system using the default
time evolution.
INPUT:
- ``num`` -- the number of states to print
EXAMPLES::
sage: B = SolitonCellularAutomata([[2],[-1],[1],[1],[1],[1],[2],[2],[3],
....: [-2],[1],[1],[2],[-1],[1],[1],[1],[1],[1],[1],[2],[3],[3],[-3],[-2]],
....: ['C',3,1])
sage: B.print_states(7)
t: 0 _ _ _ __
.........................21....2232..21......23332
t: 1 _ _ _ __
......................21...2232...21....23332.....
t: 2 _ _ _ __
...................21..2232....21..23332..........
t: 3 _ _ _ __
...............221..232...2231..332...............
t: 4 _ _ _ __
...........221...232.2231....332..................
t: 5 _ __ __
.......221...2321223......332.....................
t: 6 _ __ __
..2221...321..223......332........................
sage: B = SolitonCellularAutomata([[2],[1],[1],[1],[3],[-2],[1],[1],
....: [1],[2],[2],[-3],[1],[1],[1],[1],[1],[1],[2],[3],[3],[-3]],
....: ['B',3,1])
sage: B.print_states(9, ' ')
t: 0 _ _ _
2 32 223 2333
t: 1 _ _ _
2 32 223 2333
t: 2 _ _ _
2 32 223 2333
t: 3 _ _ _
23 2223 2333
t: 4 __ _
23 213 2333
t: 5 _ _ _
2233 222 333
t: 6 _ _ _
2233 23223 3
t: 7 _ _ _
2233 232 23 3
t: 8 _ _ _
2233 232 23 3
sage: B = SolitonCellularAutomata([[2],[-2],[1],[1],[1],[1],[2],[0],[-3],
....: [1],[1],[1],[1],[1],[2],[2],[3],[-3],], ['D',4,2])
sage: B.print_states(10)
t: 0 _ _ _
....................................22....203.....2233
t: 1 _ _ _
..................................22...203....2233....
t: 2 _ _ _
................................22..203...2233........
t: 3 _ _ _
..............................22.203..2233............
t: 4 _ _ _
............................22203.2233................
t: 5 _ _ _
........................220223.233....................
t: 6 _ _ _
....................2202.223.33.......................
t: 7 _ _ _
................2202..223..33.........................
t: 8 _ _ _
............2202...223...33...........................
t: 9 _ _ _
........2202....223....33.............................
Example 4.13 from [Yamada2007]_::
sage: B = SolitonCellularAutomata([[3],[3],[1],[1],[1],[1],[2],[2],[2]], ['D',4,3])
sage: B.print_states(15)
t: 0
....................................33....222
t: 1
..................................33...222...
t: 2
................................33..222......
t: 3
..............................33.222.........
t: 4
............................33222............
t: 5
..........................3022...............
t: 6 _
........................332..................
t: 7 _
......................03.....................
t: 8 _
....................3E.......................
t: 9 _
.................21..........................
t: 10
..............20E............................
t: 11 _
...........233...............................
t: 12
........2302.................................
t: 13
.....23322...................................
t: 14
..233.22.....................................
Example 4.14 from [Yamada2007]_::
sage: B = SolitonCellularAutomata([[3],[1],[1],[1],[2],[3],[1],[1],[1],[2],[3],[3]], ['D',4,3])
sage: B.print_states(15)
t: 0
....................................3...23...233
t: 1
...................................3..23..233...
t: 2
..................................3.23.233......
t: 3
.................................323233.........
t: 4
................................0033............
t: 5 _
..............................313...............
t: 6
...........................30E.3................
t: 7 _
........................333...3.................
t: 8
.....................3302....3..................
t: 9
..................33322.....3...................
t: 10
...............333.22......3....................
t: 11
............333..22.......3.....................
t: 12
.........333...22........3......................
t: 13
......333....22.........3.......................
t: 14
...333.....22..........3........................
"""
if num is None:
num = len(self._states)
if num > len(self._states):
for _ in range(num - len(self._states)):
self.evolve()
vacuum = self._vacuum_elt
num_factors = len(self._states[num-1])
for i,state in enumerate(self._states[:num]):
state = [vacuum]*(num_factors - len(state)) + list(state)
output = [self._column_repr(b, vacuum_letter) for b in state]
max_width = max(b.width() for b in output)
start = ascii_art("t: %s \n"%i)
start._baseline = -1
print(start
+ sum((ascii_art(' '*(max_width-b.width())) + b for b in output),
ascii_art('')))
def latex_states(self, num=None, as_array=True, box_width='5pt'):
r"""
Return a latex version of the states.
INPUT:
- ``num`` -- the number of states
- ``as_array`` (default: ``True``) if ``True``, then the states are
placed inside of an array; if ``False``, then the states are
given as a word
- ``box_width`` -- (default: ``'5pt'``) the width of the ``.`` used
to represent the vacuum state when ``as_array`` is ``True``
If ``as_array`` is ``False``, then the vacuum element is printed
in a gray color. If ``as_array`` is ``True``, then the vacuum
is given as ``.``
Use the ``box_width`` to help create more even spacing when
a column in the output contains only vacuum elements.
EXAMPLES::
sage: B = SolitonCellularAutomata('411122', 4)
sage: B.latex_states(8)
{\arraycolsep=0.5pt \begin{array}{c|ccccccccccccccccccc}
t = 0 & \cdots & ... & \makebox[5pt]{.} & 4 & \makebox[5pt]{.}
& \makebox[5pt]{.} & \makebox[5pt]{.} & 2 & 2 \\
t = 1 & \cdots & ... & 4 & \makebox[5pt]{.} & \makebox[5pt]{.} & 2 & 2 & ... \\
t = 2 & \cdots & ... & 4 & \makebox[5pt]{.} & 2 & 2 & ... \\
t = 3 & \cdots & ... & 4 & 2 & 2 & ... \\
t = 4 & \cdots & ... & 2 & 4 & 2 & ... \\
t = 5 & \cdots & ... & 2 & 4 & \makebox[5pt]{.} & 2 & ... \\
t = 6 & \cdots & ... & 2 & 4 & \makebox[5pt]{.} & \makebox[5pt]{.}
& 2 & ... \\
t = 7 & \cdots & \makebox[5pt]{.} & 2 & 4 & \makebox[5pt]{.}
& \makebox[5pt]{.} & \makebox[5pt]{.} & 2 & ... \\
\end{array}}
sage: B = SolitonCellularAutomata('511122', 5)
sage: B.latex_states(8, as_array=False)
{\begin{array}{c|c}
t = 0 & \cdots ... {\color{gray} 1} 5 {\color{gray} 1}
{\color{gray} 1} {\color{gray} 1} 2 2 \\
t = 1 & \cdots ... 5 {\color{gray} 1} {\color{gray} 1} 2 2 ... \\
t = 2 & \cdots ... 5 {\color{gray} 1} 2 2 ... \\
t = 3 & \cdots ... 5 2 2 ... \\
t = 4 & \cdots ... 2 5 2 ... \\
t = 5 & \cdots ... 2 5 {\color{gray} 1} 2 ... \\
t = 6 & \cdots ... 2 5 {\color{gray} 1} {\color{gray} 1} 2 ... \\
t = 7 & \cdots {\color{gray} 1} 2 5 {\color{gray} 1}
{\color{gray} 1} {\color{gray} 1} 2 ... \\
\end{array}}
"""
from sage.misc.latex import latex, LatexExpr
if not as_array:
latex.add_package_to_preamble_if_available('xcolor')
if num is None:
num = len(self._states)
if num > len(self._states):
for _ in range(num - len(self._states)):
self.evolve()
vacuum = self._vacuum_elt
def compact_repr(b):
if as_array and b == vacuum:
return "\\makebox[%s]{.}"%box_width
if b.parent()._tableau_height == 1:
temp = latex(b[0])
else:
temp = "\\begin{array}{@{}c@{}}" # No padding around columns
temp += r"\\".join(latex(letter) for letter in reversed(b))
temp += "\\end{array}"
if b == vacuum:
return "{\\color{gray} %s}"%temp
return temp # "\\makebox[%s]{$%s$}"%(box_width, temp)
num_factors = len(self._states[num-1])
if as_array:
ret = "{\\arraycolsep=0.5pt \\begin{array}"
ret += "{c|c%s}\n"%('c'*num_factors)
else:
ret = "{\\begin{array}"
ret += "{c|c}\n"
for i,state in enumerate(self._states[:num]):
state = [vacuum]*(num_factors-len(state)) + list(state)
if as_array:
ret += "t = %s & \\cdots & %s \\\\\n"%(i, r" & ".join(compact_repr(b) for b in state))
else:
ret += "t = %s & \\cdots %s \\\\\n"%(i, r" ".join(compact_repr(b) for b in state))
ret += "\\end{array}}\n"
return LatexExpr(ret)
def print_state_evolution(self, num):
r"""
Print the evolution process of the state ``num``.
.. SEEALSO::
:meth:`state_evolution`, :meth:`latex_state_evolution`
EXAMPLES::
sage: B = SolitonCellularAutomata('1113123', 3)
sage: B.evolve(3)
sage: B.evolve(3)
sage: B.print_state_evolution(0)
1 1 1 3 1 2 3
| | | | | | |
111 --+-- 111 --+-- 111 --+-- 113 --+-- 112 --+-- 123 --+-- 113 --+-- 111
| | | | | | |
1 1 3 2 3 1 1
sage: B.print_state_evolution(1)
1 1 3 2 3 1 1
| | | | | | |
111 --+-- 113 --+-- 133 --+-- 123 --+-- 113 --+-- 111 --+-- 111 --+-- 111
| | | | | | |
3 3 2 1 1 1 1
"""
u = self.state_evolution(num) # Also evolves as necessary
final = self._states[num+1]
vacuum = self._vacuum_elt
state = [vacuum]*(len(final) - len(self._states[num])) + list(self._states[num])
carrier = KirillovReshetikhinTableaux(self._cartan_type, *self._evolutions[num])
def simple_repr(x):
return ''.join(repr(x).strip('[]').split(', '))
def carrier_repr(x):
if carrier._tableau_height == 1:
return sum((ascii_art(repr(b)) if repr(b)[0] != '-'
else ascii_art("_" + '\n' + repr(b)[1:])
for b in x),
ascii_art(''))
return ascii_art(''.join(repr(x).strip('[]').split(', ')))
def cross_repr(i):
ret = ascii_art(
"""
{!s:^7}
|
--+--
|
{!s:^7}
""".format(simple_repr(state[i]), simple_repr(final[i])))
ret._baseline = 2
return ret
art = sum((cross_repr(i)
+ carrier_repr(u[i+1])
for i in range(len(state))), ascii_art(''))
print(ascii_art(carrier_repr(u[0])) + art)
def latex_state_evolution(self, num, scale=1):
r"""
Return a latex version of the evolution process of
the state ``num``.
.. SEEALSO::
:meth:`state_evolution`, :meth:`print_state_evolution`
EXAMPLES::
sage: B = SolitonCellularAutomata('113123', 3)
sage: B.evolve(3)
sage: B.latex_state_evolution(0)
\begin{tikzpicture}[scale=1]
\node (i0) at (0.0,0.9) {$1$};
\node (i1) at (2.48,0.9) {$1$};
\node (i2) at (4.96,0.9) {$3$};
...
\draw[->] (i5) -- (t5);
\draw[->] (u6) -- (u5);
\end{tikzpicture}
sage: B.latex_state_evolution(1)
\begin{tikzpicture}[scale=1]
...
\end{tikzpicture}
"""
from sage.graphs.graph_latex import setup_latex_preamble
from sage.misc.latex import LatexExpr
setup_latex_preamble()
u = self.state_evolution(num) # Also evolves as necessary
final = self._states[num+1]
vacuum = self._vacuum_elt
initial = [vacuum]*(len(final) - len(self._states[num])) + list(self._states[num])
cs = len(u[0]) * 0.08 + 1 # carrier scaling
def simple_repr(x):
return ''.join(repr(x).strip('[]').split(', '))
ret = '\\begin{{tikzpicture}}[scale={}]\n'.format(scale)
for i,val in enumerate(initial):
ret += '\\node (i{}) at ({},0.9) {{${}$}};\n'.format(i, 2*i*cs, simple_repr(val))
for i,val in enumerate(final):
ret += '\\node (t{}) at ({},-1) {{${}$}};\n'.format(i, 2*i*cs, simple_repr(val))
for i,val in enumerate(u):
ret += '\\node (u{}) at ({},0) {{${}$}};\n'.format(i, (2*i-1)*cs, simple_repr(val))
for i in range(len(initial)):
ret += '\\draw[->] (i{}) -- (t{});\n'.format(i, i)
ret += '\\draw[->] (u{}) -- (u{});\n'.format(i+1, i)
ret += '\\end{tikzpicture}'
return LatexExpr(ret)
class PeriodicSolitonCellularAutomata(SolitonCellularAutomata):
r"""
A periodic soliton cellular automata.
Fix some `r \in I_0`. A *periodic soliton cellular automata* is a
:class:`SolitonCellularAutomata` with a state being a fixed number of
tensor factors `p = p_{\ell} \otimes \cdots \otimes p_1 \otimes p_0`
and the *time evolution* `T_s` is defined by
.. MATH::
R(p \otimes u) = u \otimes T_s(p),
for some element `u \in B^{r,s}`.
INPUT:
- ``initial_state`` -- the list of elements, can also be a string
when ``vacuum`` is 1 and ``n`` is `\mathfrak{sl}_n`
- ``cartan_type`` -- (default: 2) the value ``n``, for `\mathfrak{sl}_n`,
or a Cartan type
- ``r`` -- (default: 1) the node index `r`; typically this
corresponds to the height of the vacuum element
EXAMPLES:
The construction and usage is the same as for
:class:`SolitonCellularAutomata`::
sage: P = PeriodicSolitonCellularAutomata('1123334111241111423111411123112', 4)
sage: P.evolve()
sage: P
Soliton cellular automata of type ['A', 3, 1] and vacuum = 1
initial state:
..23334...24....423...4...23..2
evoltuions: [(1, 31)]
current state:
34......24....243....4.223.233.
sage: P.evolve(carrier_capacity=2)
sage: P.evolve(carrier_index=2)
sage: P.evolve(carrier_index=2, carrier_capacity=3)
sage: P.print_states(10)
t: 0
..23334...24....423...4...23..2
t: 1
34......24....243....4.223.233.
t: 2
......24....24.3....4223.2333.4
t: 3
.....34....34.2..223234.24...3.
t: 4
....34...23..242223.4..33....4.
t: 5
..34.2223.224.3....4.33.....4..
t: 6
34223...24...3....433......4.22
t: 7
23....24....3...343....222434..
t: 8
....24.....3..34.322244...3..23
t: 9
..24.....332442342.......3.23..
Using `r = 2` in type `A_3^{(1)}`::
sage: initial = [[2,1],[2,1],[4,1],[2,1],[2,1],[2,1],[3,1],[3,1],[3,2]]
sage: P = PeriodicSolitonCellularAutomata(initial, 4, 2)
sage: P.print_states(10)
t: 0 4 333
..1...112
t: 1 4 333
.1.112...
t: 2 433 3
112.....1
t: 3 3 334
2....111.
t: 4 334 3
..111...2
t: 5 34 33
11.....21
t: 6 3334
....1121.
t: 7 333 4
.112..1..
t: 8 3 4 33
2....1.11
t: 9 3433
...1112..
We do some examples in other types::
sage: initial = [[1],[2],[2],[1],[1],[1],[3],[1],['E'],[1],[1]]
sage: P = PeriodicSolitonCellularAutomata(initial, ['D',4,3])
sage: P.print_states(10)
t: 0
.22...3.E..
t: 1
2....3.E..2
t: 2
....3.E.22.
t: 3
...3.E22...
t: 4
..32E2.....
t: 5
.00.2......
t: 6 _
22.2.......
t: 7
2.2......3E
t: 8
.2.....30.2
t: 9
2....332.2.
sage: P = PeriodicSolitonCellularAutomata([[3],[2],[1],[1],[-2]], ['C',2,1])
sage: P.print_state_evolution(0)
3 2 1 1 -2
_ | | | _ | __ | _
11112 --+-- 11112 --+-- 11111 --+-- 11112 --+-- 11122 --+-- 11112
| | | | |
2 1 -2 -2 1
REFERENCES:
- [KTT2006]_
- [KS2006]_
- [YT2002]_
- [YYT2003]_
"""
def evolve(self, carrier_capacity=None, carrier_index=None, number=None):
r"""
Evolve ``self``.
Time evolution `T_s` of a SCA state `p` is determined by
.. MATH::
u \otimes T_s(p) = R(p \otimes u),
where `u` is some element in `B^{r,s}`.
INPUT:
- ``carrier_capacity`` -- (default: the number of balls in
the system) the size `s` of carrier
- ``carrier_index`` -- (default: the vacuum index) the index `r`
of the carrier
- ``number`` -- (optional) the number of times to perform
the evolutions
To perform multiple evolutions of the SCA, ``carrier_capacity``
and ``carrier_index`` may be lists of the same length.
.. WARNING::
Time evolution is only guaranteed to result in a solution
when the ``carrier_index`` is the defining `r` of the SCA.
If no solution is found, then this will raise an error.
EXAMPLES::
sage: P = PeriodicSolitonCellularAutomata('12411133214131221122', 4)
sage: P.evolve()
sage: P.print_state(0)
.24...332.4.3.22..22
sage: P.print_state(1)
4...33.2.42322..22..
sage: P.evolve(carrier_capacity=2)
sage: P.print_state(2)
..33.22.4232..22...4
sage: P.evolve(carrier_capacity=[1,3,1,2])
sage: P.evolve(1, number=3)
sage: P.print_states(10)
t: 0
.24...332.4.3.22..22
t: 1
4...33.2.42322..22..
t: 2
..33.22.4232..22...4
t: 3
.33.22.4232..22...4.
t: 4
3222..43.2.22....4.3
t: 5
222..43.2.22....4.33
t: 6
2...4322.2.....43322
t: 7
...4322.2.....433222
t: 8
..4322.2.....433222.
t: 9
.4322.2.....433222..
sage: P = PeriodicSolitonCellularAutomata('12411132121', 4)
sage: P.evolve(carrier_index=2, carrier_capacity=3)
sage: P.state_evolution(0)
[[[1, 1, 1], [2, 2, 4]],
[[1, 1, 2], [2, 2, 4]],
[[1, 1, 3], [2, 2, 4]],
[[1, 1, 1], [2, 2, 3]],
[[1, 1, 1], [2, 2, 3]],
[[1, 1, 1], [2, 2, 3]],
[[1, 1, 2], [2, 2, 3]],
[[1, 1, 1], [2, 2, 2]],
[[1, 1, 1], [2, 2, 2]],
[[1, 1, 1], [2, 2, 2]],
[[1, 1, 1], [2, 2, 4]],
[[1, 1, 1], [2, 2, 4]]]
"""
if isinstance(carrier_capacity, (list, tuple)):
if not isinstance(carrier_index, (list, tuple)):
carrier_index = [carrier_index] * len(carrier_capacity)
if len(carrier_index) != len(carrier_capacity):
raise ValueError("carrier_index and carrier_capacity"
" must have the same length")
for i, r in zip(carrier_capacity, carrier_index):
self.evolve(i, r)
return
if isinstance(carrier_index, (list, tuple)):
# carrier_capacity must be not be a list/tuple if given
for r in carrier_index:
self.evolve(carrier_capacity, r)
return
if carrier_capacity is None:
carrier_capacity = self._nballs
if carrier_index is None:
carrier_index = self._vacuum
if number is not None:
for _ in range(number):
self.evolve(carrier_capacity, carrier_index)
return
if carrier_capacity is None:
carrier_capacity = self._nballs
if carrier_index is None:
carrier_index = self._vacuum
K = KirillovReshetikhinTableaux(self._cartan_type, carrier_index, carrier_capacity)
carrier_factor = (carrier_index, carrier_capacity)
state = self._states[-1]
dims = state.parent().dims
for carrier in K:
KRT = TensorProductOfKirillovReshetikhinTableaux(self._cartan_type,
dims + (carrier_factor,))
elt = KRT(*(list(state) + [carrier]))
RC = RiggedConfigurations(self._cartan_type, (carrier_factor,) + dims)
elt2 = RC(*elt.to_rigged_configuration()).to_tensor_product_of_kirillov_reshetikhin_tableaux()
# Back to an empty carrier or we are not getting any better
if elt2[0] == carrier:
KRT = TensorProductOfKirillovReshetikhinTableaux(self._cartan_type, dims)
self._states.append(KRT(*elt2[1:]))
self._evolutions.append(carrier_factor)
self._initial_carrier.append(carrier)
break
else:
raise ValueError("cannot find solution to time evolution")
def __eq__(self, other):
"""
Check equality.
Two periodic SCAs are equal when they have the same initial
state and evolutions.
TESTS::
sage: P1 = PeriodicSolitonCellularAutomata('34112223', 4)
sage: P2 = PeriodicSolitonCellularAutomata('34112223', 4)
sage: P1 == P2
True
sage: P1.evolve()
sage: P1 == P2
False
sage: P2.evolve()
sage: P1 == P2
True
sage: P1.evolve(5)
sage: P2.evolve(6)
sage: P1 == P2
False
sage: P = PeriodicSolitonCellularAutomata('34112223', 4)
sage: B = SolitonCellularAutomata('34112223', 4)
sage: P == B
False
sage: B == P
False
"""
return (isinstance(other, PeriodicSolitonCellularAutomata)
and SolitonCellularAutomata.__eq__(self, other)) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/dynamics/cellular_automata/solitons.py | 0.87006 | 0.616301 | solitons.py | pypi |
from sage.matrix.constructor import matrix
from sage.rings.integer_ring import ZZ
# Function below could be replicated into
# sage.matrix.matrix_integer_dense.Matrix_integer_dense.is_LLL_reduced
# which is its only current use (2011-02-26). Then this could
# be deprecated and this file removed.
def gram_schmidt(B):
r"""
Return the Gram-Schmidt orthogonalization of the entries in the list
B of vectors, along with the matrix mu of Gram-Schmidt coefficients.
Note that the output vectors need not have unit length. We do this
to avoid having to extract square roots.
.. NOTE::
Use of this function is discouraged. It fails on linearly
dependent input and its output format is not as natural as it
could be. Instead, see :meth:`sage.matrix.matrix2.Matrix2.gram_schmidt`
which is safer and more general-purpose.
EXAMPLES::
sage: B = [vector([1,2,1/5]), vector([1,2,3]), vector([-1,0,0])]
sage: from sage.modules.misc import gram_schmidt
sage: G, mu = gram_schmidt(B)
sage: G
[(1, 2, 1/5), (-1/9, -2/9, 25/9), (-4/5, 2/5, 0)]
sage: G[0] * G[1]
0
sage: G[0] * G[2]
0
sage: G[1] * G[2]
0
sage: mu
[ 0 0 0]
[ 10/9 0 0]
[-25/126 1/70 0]
sage: a = matrix([])
sage: a.gram_schmidt()
([], [])
sage: a = matrix([[],[],[],[]])
sage: a.gram_schmidt()
([], [])
Linearly dependent input leads to a zero dot product in a denominator.
This shows that :trac:`10791` is fixed. ::
sage: from sage.modules.misc import gram_schmidt
sage: V = [vector(ZZ,[1,1]), vector(ZZ,[2,2]), vector(ZZ,[1,2])]
sage: gram_schmidt(V)
Traceback (most recent call last):
...
ValueError: linearly dependent input for module version of Gram-Schmidt
TESTS::
sage: from sage.modules.misc import gram_schmidt
sage: V = []
sage: gram_schmidt(V)
([], [])
sage: V = [vector(ZZ,[0])]
sage: gram_schmidt(V)
Traceback (most recent call last):
...
ValueError: linearly dependent input for module version of Gram-Schmidt
"""
from sage.modules.free_module_element import vector
if len(B) == 0 or len(B[0]) == 0:
return B, matrix(ZZ, 0, 0, [])
n = len(B)
Bstar = [B[0]]
K = B[0].base_ring().fraction_field()
zero = vector(K, len(B[0]))
if Bstar[0] == zero:
raise ValueError("linearly dependent input for module version of Gram-Schmidt")
mu = matrix(K, n, n)
for i in range(1, n):
for j in range(i):
mu[i, j] = B[i].dot_product(Bstar[j]) / (Bstar[j].dot_product(Bstar[j]))
Bstar.append(B[i] - sum(mu[i, j] * Bstar[j] for j in range(i)))
if Bstar[i] == zero:
raise ValueError("linearly dependent input for module version of Gram-Schmidt")
return Bstar, mu | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modules/misc.py | 0.844313 | 0.739963 | misc.py | pypi |
from . import free_module_element
from sage.symbolic.all import Expression
def apply_map(phi):
"""
Returns a function that applies phi to its argument.
EXAMPLES::
sage: from sage.modules.vector_symbolic_dense import apply_map
sage: v = vector([1,2,3])
sage: f = apply_map(lambda x: x+1)
sage: f(v)
(2, 3, 4)
"""
def apply(self, *args, **kwds):
"""
Generic function used to implement common symbolic operations
elementwise as methods of a vector.
EXAMPLES::
sage: var('x,y')
(x, y)
sage: v = vector([sin(x)^2 + cos(x)^2, log(x*y), sin(x/(x^2 + x)), factorial(x+1)/factorial(x)])
sage: v.simplify_trig()
(1, log(x*y), sin(1/(x + 1)), factorial(x + 1)/factorial(x))
sage: v.canonicalize_radical()
(cos(x)^2 + sin(x)^2, log(x) + log(y), sin(1/(x + 1)), factorial(x + 1)/factorial(x))
sage: v.simplify_rational()
(cos(x)^2 + sin(x)^2, log(x*y), sin(1/(x + 1)), factorial(x + 1)/factorial(x))
sage: v.simplify_factorial()
(cos(x)^2 + sin(x)^2, log(x*y), sin(x/(x^2 + x)), x + 1)
sage: v.simplify_full()
(1, log(x*y), sin(1/(x + 1)), x + 1)
sage: v = vector([sin(2*x), sin(3*x)])
sage: v.simplify_trig()
(2*cos(x)*sin(x), (4*cos(x)^2 - 1)*sin(x))
sage: v.simplify_trig(False)
(sin(2*x), sin(3*x))
sage: v.simplify_trig(expand=False)
(sin(2*x), sin(3*x))
"""
return self.apply_map(lambda x: phi(x, *args, **kwds))
apply.__doc__ += "\nSee Expression." + phi.__name__ + "() for optional arguments."
return apply
class Vector_symbolic_dense(free_module_element.FreeModuleElement_generic_dense):
pass
# Add elementwise methods.
for method in ['simplify', 'simplify_factorial',
'simplify_log', 'simplify_rational',
'simplify_trig', 'simplify_full', 'trig_expand',
'canonicalize_radical', 'trig_reduce']:
setattr(Vector_symbolic_dense, method, apply_map(getattr(Expression, method))) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modules/vector_symbolic_dense.py | 0.832305 | 0.688823 | vector_symbolic_dense.py | pypi |
r"""
Morphisms defined by a matrix
A matrix morphism is a morphism that is defined by multiplication
by a matrix. Elements of domain must either have a method
``vector()`` that returns a vector that the defining
matrix can hit from the left, or be coercible into vector space of
appropriate dimension.
EXAMPLES::
sage: from sage.modules.matrix_morphism import MatrixMorphism, is_MatrixMorphism
sage: V = QQ^3
sage: T = End(V)
sage: M = MatrixSpace(QQ,3)
sage: I = M.identity_matrix()
sage: m = MatrixMorphism(T, I); m
Morphism defined by the matrix
[1 0 0]
[0 1 0]
[0 0 1]
sage: is_MatrixMorphism(m)
True
sage: m.charpoly('x')
x^3 - 3*x^2 + 3*x - 1
sage: m.base_ring()
Rational Field
sage: m.det()
1
sage: m.fcp('x')
(x - 1)^3
sage: m.matrix()
[1 0 0]
[0 1 0]
[0 0 1]
sage: m.rank()
3
sage: m.trace()
3
AUTHOR:
- William Stein: initial versions
- David Joyner (2005-12-17): added examples
- William Stein (2005-01-07): added __reduce__
- Craig Citro (2008-03-18): refactored MatrixMorphism class
- Rob Beezer (2011-07-15): additional methods, bug fixes, documentation
"""
import sage.categories.morphism
import sage.categories.homset
from sage.structure.all import Sequence, parent
from sage.structure.richcmp import richcmp, op_NE, op_EQ
def is_MatrixMorphism(x):
"""
Return True if x is a Matrix morphism of free modules.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1])
sage: sage.modules.matrix_morphism.is_MatrixMorphism(phi)
True
sage: sage.modules.matrix_morphism.is_MatrixMorphism(3)
False
"""
return isinstance(x, MatrixMorphism_abstract)
class MatrixMorphism_abstract(sage.categories.morphism.Morphism):
def __init__(self, parent, side='left'):
"""
INPUT:
- ``parent`` - a homspace
- ``A`` - matrix
EXAMPLES::
sage: from sage.modules.matrix_morphism import MatrixMorphism
sage: T = End(ZZ^3)
sage: M = MatrixSpace(ZZ,3)
sage: I = M.identity_matrix()
sage: A = MatrixMorphism(T, I)
sage: loads(A.dumps()) == A
True
"""
if not sage.categories.homset.is_Homset(parent):
raise TypeError("parent must be a Hom space")
if side not in ["left", "right"]:
raise ValueError("the argument side must be either 'left' or 'right'")
self._side = side
sage.categories.morphism.Morphism.__init__(self, parent)
def _richcmp_(self, other, op):
"""
Rich comparison of morphisms.
EXAMPLES::
sage: V = ZZ^2
sage: phi = V.hom([3*V.0, 2*V.1])
sage: psi = V.hom([5*V.0, 5*V.1])
sage: id = V.hom([V.0, V.1])
sage: phi == phi
True
sage: phi == psi
False
sage: psi == End(V)(5)
True
sage: psi == 5 * id
True
sage: psi == 5 # no coercion
False
sage: id == End(V).identity()
True
"""
if not isinstance(other, MatrixMorphism) or op not in (op_EQ, op_NE):
# Generic comparison
return sage.categories.morphism.Morphism._richcmp_(self, other, op)
return richcmp(self.matrix(), other.matrix(), op)
def _call_(self, x):
"""
Evaluate this matrix morphism at an element of the domain.
.. NOTE::
Coercion is done in the generic :meth:`__call__` method,
which calls this method.
EXAMPLES::
sage: V = QQ^3; W = QQ^2
sage: H = Hom(V, W); H
Set of Morphisms (Linear Transformations) from
Vector space of dimension 3 over Rational Field to
Vector space of dimension 2 over Rational Field
sage: phi = H(matrix(QQ, 3, 2, range(6))); phi
Vector space morphism represented by the matrix:
[0 1]
[2 3]
[4 5]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 2 over Rational Field
sage: phi(V.0)
(0, 1)
sage: phi(V([1, 2, 3]))
(16, 22)
Last, we have a situation where coercion occurs::
sage: U = V.span([[3,2,1]])
sage: U.0
(1, 2/3, 1/3)
sage: phi(2*U.0)
(16/3, 28/3)
TESTS::
sage: V = QQ^3; W = span([[1,2,3],[-1,2,5/3]], QQ)
sage: phi = V.hom(matrix(QQ,3,[1..9]))
We compute the image of some elements::
sage: phi(V.0) #indirect doctest
(1, 2, 3)
sage: phi(V.1)
(4, 5, 6)
sage: phi(V.0 - 1/4*V.1)
(0, 3/4, 3/2)
We restrict ``phi`` to ``W`` and compute the image of an element::
sage: psi = phi.restrict_domain(W)
sage: psi(W.0) == phi(W.0)
True
sage: psi(W.1) == phi(W.1)
True
"""
try:
if parent(x) is not self.domain():
x = self.domain()(x)
except TypeError:
raise TypeError("%s must be coercible into %s"%(x,self.domain()))
if self.domain().is_ambient():
x = x.element()
else:
x = self.domain().coordinate_vector(x)
C = self.codomain()
if self.side() == "left":
v = x.change_ring(C.base_ring()) * self.matrix()
else:
v = self.matrix() * x.change_ring(C.base_ring())
if not C.is_ambient():
v = C.linear_combination_of_basis(v)
# The call method of parents uses (coercion) morphisms.
# Hence, in order to avoid recursion, we call the element
# constructor directly; after all, we already know the
# coordinates.
return C._element_constructor_(v)
def _call_with_args(self, x, args=(), kwds={}):
"""
Like :meth:`_call_`, but takes optional and keyword arguments.
EXAMPLES::
sage: V = RR^2
sage: f = V.hom(V.gens())
sage: f._matrix *= I # f is now invalid
sage: f((1, 0))
Traceback (most recent call last):
...
TypeError: Unable to coerce entries (=[1.00000000000000*I, 0.000000000000000]) to coefficients in Real Field with 53 bits of precision
sage: f((1, 0), coerce=False)
(1.00000000000000*I, 0.000000000000000)
"""
if self.domain().is_ambient():
x = x.element()
else:
x = self.domain().coordinate_vector(x)
C = self.codomain()
v = x.change_ring(C.base_ring()) * self.matrix()
if not C.is_ambient():
v = C.linear_combination_of_basis(v)
# The call method of parents uses (coercion) morphisms.
# Hence, in order to avoid recursion, we call the element
# constructor directly; after all, we already know the
# coordinates.
return C._element_constructor_(v, *args, **kwds)
def __invert__(self):
"""
Invert this matrix morphism.
EXAMPLES::
sage: V = QQ^2; phi = V.hom([3*V.0, 2*V.1])
sage: phi^(-1)
Vector space morphism represented by the matrix:
[1/3 0]
[ 0 1/2]
Domain: Vector space of dimension 2 over Rational Field
Codomain: Vector space of dimension 2 over Rational Field
Check that a certain non-invertible morphism isn't invertible::
sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1])
sage: phi^(-1)
Traceback (most recent call last):
...
ZeroDivisionError: matrix morphism not invertible
"""
try:
B = ~(self.matrix())
except ZeroDivisionError:
raise ZeroDivisionError("matrix morphism not invertible")
try:
return self.parent().reversed()(B, side=self.side())
except TypeError:
raise ZeroDivisionError("matrix morphism not invertible")
def side(self):
"""
Return the side of vectors acted on, relative to the matrix.
EXAMPLES::
sage: m = matrix(2, [1, 1, 0, 1])
sage: V = ZZ^2
sage: h1 = V.hom(m); h2 = V.hom(m, side="right")
sage: h1.side()
'left'
sage: h1([1, 0])
(1, 1)
sage: h2.side()
'right'
sage: h2([1, 0])
(1, 0)
"""
return self._side
def side_switch(self):
"""
Return the same morphism, acting on vectors on the opposite side
EXAMPLES::
sage: m = matrix(2, [1,1,0,1]); m
[1 1]
[0 1]
sage: V = ZZ^2
sage: h = V.hom(m); h.side()
'left'
sage: h2 = h.side_switch(); h2
Free module morphism defined as left-multiplication by the matrix
[1 0]
[1 1]
Domain: Ambient free module of rank 2 over the principal ideal domain Integer Ring
Codomain: Ambient free module of rank 2 over the principal ideal domain Integer Ring
sage: h2.side()
'right'
sage: h2.side_switch().matrix()
[1 1]
[0 1]
"""
side = "left" if self.side() == "right" else "right"
return self.parent()(self.matrix().transpose(), side=side)
def inverse(self):
r"""
Return the inverse of this matrix morphism, if the inverse exists.
Raises a ``ZeroDivisionError`` if the inverse does not exist.
EXAMPLES:
An invertible morphism created as a restriction of
a non-invertible morphism, and which has an unequal
domain and codomain. ::
sage: V = QQ^4
sage: W = QQ^3
sage: m = matrix(QQ, [[2, 0, 3], [-6, 1, 4], [1, 2, -4], [1, 0, 1]])
sage: phi = V.hom(m, W)
sage: rho = phi.restrict_domain(V.span([V.0, V.3]))
sage: zeta = rho.restrict_codomain(W.span([W.0, W.2]))
sage: x = vector(QQ, [2, 0, 0, -7])
sage: y = zeta(x); y
(-3, 0, -1)
sage: inv = zeta.inverse(); inv
Vector space morphism represented by the matrix:
[-1 3]
[ 1 -2]
Domain: Vector space of degree 3 and dimension 2 over Rational Field
Basis matrix:
[1 0 0]
[0 0 1]
Codomain: Vector space of degree 4 and dimension 2 over Rational Field
Basis matrix:
[1 0 0 0]
[0 0 0 1]
sage: inv(y) == x
True
An example of an invertible morphism between modules,
(rather than between vector spaces). ::
sage: M = ZZ^4
sage: p = matrix(ZZ, [[ 0, -1, 1, -2],
....: [ 1, -3, 2, -3],
....: [ 0, 4, -3, 4],
....: [-2, 8, -4, 3]])
sage: phi = M.hom(p, M)
sage: x = vector(ZZ, [1, -3, 5, -2])
sage: y = phi(x); y
(1, 12, -12, 21)
sage: rho = phi.inverse(); rho
Free module morphism defined by the matrix
[ -5 3 -1 1]
[ -9 4 -3 2]
[-20 8 -7 4]
[ -6 2 -2 1]
Domain: Ambient free module of rank 4 over the principal ideal domain ...
Codomain: Ambient free module of rank 4 over the principal ideal domain ...
sage: rho(y) == x
True
A non-invertible morphism, despite having an appropriate
domain and codomain. ::
sage: V = QQ^2
sage: m = matrix(QQ, [[1, 2], [20, 40]])
sage: phi = V.hom(m, V)
sage: phi.is_bijective()
False
sage: phi.inverse()
Traceback (most recent call last):
...
ZeroDivisionError: matrix morphism not invertible
The matrix representation of this morphism is invertible
over the rationals, but not over the integers, thus the
morphism is not invertible as a map between modules.
It is easy to notice from the definition that every
vector of the image will have a second entry that
is an even integer. ::
sage: V = ZZ^2
sage: q = matrix(ZZ, [[1, 2], [3, 4]])
sage: phi = V.hom(q, V)
sage: phi.matrix().change_ring(QQ).inverse()
[ -2 1]
[ 3/2 -1/2]
sage: phi.is_bijective()
False
sage: phi.image()
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1 0]
[0 2]
sage: phi.lift(vector(ZZ, [1, 1]))
Traceback (most recent call last):
...
ValueError: element is not in the image
sage: phi.inverse()
Traceback (most recent call last):
...
ZeroDivisionError: matrix morphism not invertible
The unary invert operator (~, tilde, "wiggle") is synonymous
with the ``inverse()`` method (and a lot easier to type). ::
sage: V = QQ^2
sage: r = matrix(QQ, [[4, 3], [-2, 5]])
sage: phi = V.hom(r, V)
sage: rho = phi.inverse()
sage: zeta = ~phi
sage: rho.is_equal_function(zeta)
True
TESTS::
sage: V = QQ^2
sage: W = QQ^3
sage: U = W.span([W.0, W.1])
sage: m = matrix(QQ, [[2, 1], [3, 4]])
sage: phi = V.hom(m, U)
sage: inv = phi.inverse()
sage: (inv*phi).is_identity()
True
sage: (phi*inv).is_identity()
True
"""
return ~self
def __rmul__(self, left):
"""
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: 2*phi
Free module morphism defined by the matrix
[2 2]
[0 4]...
sage: phi*2
Free module morphism defined by the matrix
[2 2]
[0 4]...
"""
R = self.base_ring()
return self.parent()(R(left) * self.matrix(), side=self.side())
def __mul__(self, right):
r"""
Composition of morphisms, denoted by \*.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi*phi
Free module morphism defined by the matrix
[1 3]
[0 4]
Domain: Ambient free module of rank 2 over the principal ideal domain ...
Codomain: Ambient free module of rank 2 over the principal ideal domain ...
sage: V = QQ^3
sage: E = V.endomorphism_ring()
sage: phi = E(Matrix(QQ,3,range(9))) ; phi
Vector space morphism represented by the matrix:
[0 1 2]
[3 4 5]
[6 7 8]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 3 over Rational Field
sage: phi*phi
Vector space morphism represented by the matrix:
[ 15 18 21]
[ 42 54 66]
[ 69 90 111]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 3 over Rational Field
sage: phi.matrix()**2
[ 15 18 21]
[ 42 54 66]
[ 69 90 111]
::
sage: W = QQ**4
sage: E_VW = V.Hom(W)
sage: psi = E_VW(Matrix(QQ,3,4,range(12))) ; psi
Vector space morphism represented by the matrix:
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 4 over Rational Field
sage: psi*phi
Vector space morphism represented by the matrix:
[ 20 23 26 29]
[ 56 68 80 92]
[ 92 113 134 155]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 4 over Rational Field
sage: phi*psi
Traceback (most recent call last):
...
TypeError: Incompatible composition of morphisms: domain of left morphism must be codomain of right.
sage: phi.matrix()*psi.matrix()
[ 20 23 26 29]
[ 56 68 80 92]
[ 92 113 134 155]
Composite maps can be formed with matrix morphisms::
sage: K.<a> = NumberField(x^2 + 23)
sage: V, VtoK, KtoV = K.vector_space()
sage: f = V.hom([V.0 - V.1, V.0 + V.1])*KtoV; f
Composite map:
From: Number Field in a with defining polynomial x^2 + 23
To: Vector space of dimension 2 over Rational Field
Defn: Isomorphism map:
From: Number Field in a with defining polynomial x^2 + 23
To: Vector space of dimension 2 over Rational Field
then
Vector space morphism represented by the matrix:
[ 1 -1]
[ 1 1]
Domain: Vector space of dimension 2 over Rational Field
Codomain: Vector space of dimension 2 over Rational Field
sage: f(a)
(1, 1)
sage: V.hom([V.0 - V.1, V.0 + V.1], side="right")*KtoV
Composite map:
From: Number Field in a with defining polynomial x^2 + 23
To: Vector space of dimension 2 over Rational Field
Defn: Isomorphism map:
From: Number Field in a with defining polynomial x^2 + 23
To: Vector space of dimension 2 over Rational Field
then
Vector space morphism represented as left-multiplication by the matrix:
[ 1 1]
[-1 1]
Domain: Vector space of dimension 2 over Rational Field
Codomain: Vector space of dimension 2 over Rational Field
We can test interraction between morphisms with different ``side``::
sage: V = ZZ^2
sage: m = matrix(2, [1,1,0,1])
sage: hl = V.hom(m)
sage: hr = V.hom(m, side="right")
sage: hl * hl
Free module morphism defined by the matrix
[1 2]
[0 1]...
sage: hl * hr
Free module morphism defined by the matrix
[1 1]
[1 2]...
sage: hl * hl.side_switch()
Free module morphism defined by the matrix
[1 2]
[0 1]...
sage: hr * hl
Free module morphism defined by the matrix
[2 1]
[1 1]...
sage: hl * hl
Free module morphism defined by the matrix
[1 2]
[0 1]...
sage: hr / hl
Free module morphism defined by the matrix
[ 0 -1]
[ 1 1]...
sage: hr / hr.side_switch()
Free module morphism defined by the matrix
[1 0]
[0 1]...
sage: hl / hl
Free module morphism defined by the matrix
[1 0]
[0 1]...
sage: hr / hr
Free module morphism defined as left-multiplication by the matrix
[1 0]
[0 1]...
.. WARNING::
Matrix morphisms can be defined by either left or right-multiplication.
The composite morphism always applies the morphism on the right of \* first.
The matrix of the composite morphism of two morphisms given by
right-multiplication is not the morphism given by the product of their
respective matrices.
If the two morphisms act on different sides, then the side of the resulting
morphism is the default one.
"""
if not isinstance(right, MatrixMorphism):
if isinstance(right, (sage.categories.morphism.Morphism, sage.categories.map.Map)):
return sage.categories.map.Map.__mul__(self, right)
R = self.base_ring()
return self.parent()(self.matrix() * R(right))
H = right.domain().Hom(self.codomain())
if self.domain() != right.codomain():
raise TypeError("Incompatible composition of morphisms: domain of left morphism must be codomain of right.")
if self.side() == "left":
if right.side() == "left":
return H(right.matrix() * self.matrix(), side=self.side())
else:
return H(right.matrix().transpose() * self.matrix(), side=self.side())
else:
if right.side() == "right":
return H(self.matrix() * right.matrix(), side=self.side())
else:
return H(right.matrix() * self.matrix().transpose(), side="left")
def __add__(self, right):
"""
Sum of morphisms, denoted by +.
EXAMPLES::
sage: phi = (ZZ**2).endomorphism_ring()(Matrix(ZZ,2,[2..5])) ; phi
Free module morphism defined by the matrix
[2 3]
[4 5]
Domain: Ambient free module of rank 2 over the principal ideal domain ...
Codomain: Ambient free module of rank 2 over the principal ideal domain ...
sage: phi + 3
Free module morphism defined by the matrix
[5 3]
[4 8]
Domain: Ambient free module of rank 2 over the principal ideal domain ...
Codomain: Ambient free module of rank 2 over the principal ideal domain ...
sage: phi + phi
Free module morphism defined by the matrix
[ 4 6]
[ 8 10]
Domain: Ambient free module of rank 2 over the principal ideal domain ...
Codomain: Ambient free module of rank 2 over the principal ideal domain ...
sage: psi = (ZZ**3).endomorphism_ring()(Matrix(ZZ,3,[22..30])) ; psi
Free module morphism defined by the matrix
[22 23 24]
[25 26 27]
[28 29 30]
Domain: Ambient free module of rank 3 over the principal ideal domain ...
Codomain: Ambient free module of rank 3 over the principal ideal domain ...
sage: phi + psi
Traceback (most recent call last):
...
ValueError: inconsistent number of rows: should be 2 but got 3
::
sage: V = ZZ^2
sage: m = matrix(2, [1,1,0,1])
sage: hl = V.hom(m)
sage: hr = V.hom(m, side="right")
sage: hl + hl
Free module morphism defined by the matrix
[2 2]
[0 2]...
sage: hr + hr
Free module morphism defined as left-multiplication by the matrix
[2 2]
[0 2]...
sage: hr + hl
Free module morphism defined by the matrix
[2 1]
[1 2]...
sage: hl + hr
Free module morphism defined by the matrix
[2 1]
[1 2]...
.. WARNING::
If the two morphisms do not share the same ``side`` attribute, then
the resulting morphism will be defined with the default value.
"""
# TODO: move over to any coercion model!
if not isinstance(right, MatrixMorphism):
R = self.base_ring()
return self.parent()(self.matrix() + R(right))
if not right.parent() == self.parent():
right = self.parent()(right, side=right.side())
if self.side() == "left":
if right.side() == "left":
return self.parent()(self.matrix() + right.matrix(), side=self.side())
elif right.side() == "right":
return self.parent()(self.matrix() + right.matrix().transpose(), side="left")
if self.side() == "right":
if right.side() == "right":
return self.parent()(self.matrix() + right.matrix(), side=self.side())
elif right.side() == "left":
return self.parent()(self.matrix().transpose() + right.matrix(), side="left")
def __neg__(self):
"""
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: -phi
Free module morphism defined by the matrix
[-1 -1]
[ 0 -2]...
sage: phi2 = phi.side_switch(); -phi2
Free module morphism defined as left-multiplication by the matrix
[-1 0]
[-1 -2]...
"""
return self.parent()(-self.matrix(), side=self.side())
def __sub__(self, other):
"""
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi - phi
Free module morphism defined by the matrix
[0 0]
[0 0]...
::
sage: V = ZZ^2
sage: m = matrix(2, [1,1,0,1])
sage: hl = V.hom(m)
sage: hr = V.hom(m, side="right")
sage: hl - hr
Free module morphism defined by the matrix
[ 0 1]
[-1 0]...
sage: hl - hl
Free module morphism defined by the matrix
[0 0]
[0 0]...
sage: hr - hr
Free module morphism defined as left-multiplication by the matrix
[0 0]
[0 0]...
sage: hr-hl
Free module morphism defined by the matrix
[ 0 -1]
[ 1 0]...
.. WARNING::
If the two morphisms do not share the same ``side`` attribute, then
the resulting morphism will be defined with the default value.
"""
# TODO: move over to any coercion model!
if not isinstance(other, MatrixMorphism):
R = self.base_ring()
return self.parent()(self.matrix() - R(other), side=self.side())
if not other.parent() == self.parent():
other = self.parent()(other, side=other.side())
if self.side() == "left":
if other.side() == "left":
return self.parent()(self.matrix() - other.matrix(), side=self.side())
elif other.side() == "right":
return self.parent()(self.matrix() - other.matrix().transpose(), side="left")
if self.side() == "right":
if other.side() == "right":
return self.parent()(self.matrix() - other.matrix(), side=self.side())
elif other.side() == "left":
return self.parent()(self.matrix().transpose() - other.matrix(), side="left")
def base_ring(self):
"""
Return the base ring of self, that is, the ring over which self is
given by a matrix.
EXAMPLES::
sage: sage.modules.matrix_morphism.MatrixMorphism((ZZ**2).endomorphism_ring(), Matrix(ZZ,2,[3..6])).base_ring()
Integer Ring
"""
return self.domain().base_ring()
def characteristic_polynomial(self, var='x'):
r"""
Return the characteristic polynomial of this endomorphism.
``characteristic_polynomial`` and ``char_poly`` are the same method.
INPUT:
- var -- variable
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi.characteristic_polynomial()
x^2 - 3*x + 2
sage: phi.charpoly()
x^2 - 3*x + 2
sage: phi.matrix().charpoly()
x^2 - 3*x + 2
sage: phi.charpoly('T')
T^2 - 3*T + 2
"""
if not self.is_endomorphism():
raise ArithmeticError("charpoly only defined for endomorphisms "
"(i.e., domain = range)")
return self.matrix().charpoly(var)
charpoly = characteristic_polynomial
def decomposition(self, *args, **kwds):
"""
Return decomposition of this endomorphism, i.e., sequence of
subspaces obtained by finding invariant subspaces of self.
See the documentation for self.matrix().decomposition for more
details. All inputs to this function are passed onto the
matrix one.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi.decomposition()
[
Free module of degree 2 and rank 1 over Integer Ring
Echelon basis matrix:
[0 1],
Free module of degree 2 and rank 1 over Integer Ring
Echelon basis matrix:
[ 1 -1]
]
sage: phi2 = V.hom(phi.matrix(), side="right")
sage: phi2.decomposition()
[
Free module of degree 2 and rank 1 over Integer Ring
Echelon basis matrix:
[1 1],
Free module of degree 2 and rank 1 over Integer Ring
Echelon basis matrix:
[1 0]
]
"""
if not self.is_endomorphism():
raise ArithmeticError("Matrix morphism must be an endomorphism.")
D = self.domain()
if self.side() == "left":
E = self.matrix().decomposition(*args,**kwds)
else:
E = self.matrix().transpose().decomposition(*args,**kwds)
if D.is_ambient():
return Sequence([D.submodule(V, check=False) for V, _ in E],
cr=True, check=False)
else:
B = D.basis_matrix()
R = D.base_ring()
return Sequence([D.submodule((V.basis_matrix() * B).row_module(R),
check=False) for V, _ in E],
cr=True, check=False)
def trace(self):
r"""
Return the trace of this endomorphism.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi.trace()
3
"""
return self._matrix.trace()
def det(self):
"""
Return the determinant of this endomorphism.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi.det()
2
"""
if not self.is_endomorphism():
raise ArithmeticError("Matrix morphism must be an endomorphism.")
return self.matrix().determinant()
def fcp(self, var='x'):
"""
Return the factorization of the characteristic polynomial.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi.fcp()
(x - 2) * (x - 1)
sage: phi.fcp('T')
(T - 2) * (T - 1)
"""
return self.charpoly(var).factor()
def kernel(self):
"""
Compute the kernel of this morphism.
EXAMPLES::
sage: V = VectorSpace(QQ,3)
sage: id = V.Hom(V)(identity_matrix(QQ,3))
sage: null = V.Hom(V)(0*identity_matrix(QQ,3))
sage: id.kernel()
Vector space of degree 3 and dimension 0 over Rational Field
Basis matrix:
[]
sage: phi = V.Hom(V)(matrix(QQ,3,range(9)))
sage: phi.kernel()
Vector space of degree 3 and dimension 1 over Rational Field
Basis matrix:
[ 1 -2 1]
sage: hom(CC^2, CC^2, matrix(CC, [[1,0], [0,1]])).kernel()
Vector space of degree 2 and dimension 0 over Complex Field with 53 bits of precision
Basis matrix:
[]
sage: m = matrix(3, [1, 0, 0, 1, 0, 0, 0, 0, 1]); m
[1 0 0]
[1 0 0]
[0 0 1]
sage: f1 = V.hom(m)
sage: f2 = V.hom(m, side="right")
sage: f1.kernel()
Vector space of degree 3 and dimension 1 over Rational Field
Basis matrix:
[ 1 -1 0]
sage: f2.kernel()
Vector space of degree 3 and dimension 1 over Rational Field
Basis matrix:
[0 1 0]
"""
if self.side() == "left":
V = self.matrix().left_kernel()
else:
V = self.matrix().right_kernel()
D = self.domain()
if not D.is_ambient():
# Transform V to ambient space
# This is a matrix multiply: we take the linear combinations of the basis for
# D given by the elements of the basis for V.
B = V.basis_matrix() * D.basis_matrix()
V = B.row_module(D.base_ring())
return self.domain().submodule(V, check=False)
def image(self):
"""
Compute the image of this morphism.
EXAMPLES::
sage: V = VectorSpace(QQ,3)
sage: phi = V.Hom(V)(matrix(QQ, 3, range(9)))
sage: phi.image()
Vector space of degree 3 and dimension 2 over Rational Field
Basis matrix:
[ 1 0 -1]
[ 0 1 2]
sage: hom(GF(7)^3, GF(7)^2, zero_matrix(GF(7), 3, 2)).image()
Vector space of degree 2 and dimension 0 over Finite Field of size 7
Basis matrix:
[]
sage: m = matrix(3, [1, 0, 0, 1, 0, 0, 0, 0, 1]); m
[1 0 0]
[1 0 0]
[0 0 1]
sage: f1 = V.hom(m)
sage: f2 = V.hom(m, side="right")
sage: f1.image()
Vector space of degree 3 and dimension 2 over Rational Field
Basis matrix:
[1 0 0]
[0 0 1]
sage: f2.image()
Vector space of degree 3 and dimension 2 over Rational Field
Basis matrix:
[1 1 0]
[0 0 1]
Compute the image of the identity map on a ZZ-submodule::
sage: V = (ZZ^2).span([[1,2],[3,4]])
sage: phi = V.Hom(V)(identity_matrix(ZZ,2))
sage: phi(V.0) == V.0
True
sage: phi(V.1) == V.1
True
sage: phi.image()
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1 0]
[0 2]
sage: phi.image() == V
True
"""
if self.side() == 'left':
V = self.matrix().row_space()
else:
V = self.matrix().column_space()
C = self.codomain()
if not C.is_ambient():
# Transform V to ambient space
# This is a matrix multiply: we take the linear combinations of the basis for
# D given by the elements of the basis for V.
B = V.basis_matrix() * C.basis_matrix()
V = B.row_module(self.domain().base_ring())
return self.codomain().submodule(V, check=False)
def matrix(self):
"""
EXAMPLES::
sage: V = ZZ^2; phi = V.hom(V.basis())
sage: phi.matrix()
[1 0]
[0 1]
sage: sage.modules.matrix_morphism.MatrixMorphism_abstract.matrix(phi)
Traceback (most recent call last):
...
NotImplementedError: this method must be overridden in the extension class
"""
raise NotImplementedError("this method must be overridden in the extension class")
def _matrix_(self):
"""
EXAMPLES:
Check that this works with the :func:`matrix` function
(:trac:`16844`)::
sage: H = Hom(ZZ^2, ZZ^3)
sage: x = H.an_element()
sage: matrix(x)
[0 0 0]
[0 0 0]
TESTS:
``matrix(x)`` is immutable::
sage: H = Hom(QQ^3, QQ^2)
sage: phi = H(matrix(QQ, 3, 2, list(reversed(range(6))))); phi
Vector space morphism represented by the matrix:
[5 4]
[3 2]
[1 0]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 2 over Rational Field
sage: A = phi.matrix()
sage: A[1, 1] = 19
Traceback (most recent call last):
...
ValueError: matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).
"""
return self.matrix()
def rank(self):
r"""
Returns the rank of the matrix representing this morphism.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom(V.basis())
sage: phi.rank()
2
sage: V = ZZ^2; phi = V.hom([V.0, V.0])
sage: phi.rank()
1
"""
return self.matrix().rank()
def nullity(self):
r"""
Returns the nullity of the matrix representing this morphism, which is the
dimension of its kernel.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom(V.basis())
sage: phi.nullity()
0
sage: V = ZZ^2; phi = V.hom([V.0, V.0])
sage: phi.nullity()
1
::
sage: m = matrix(2, [1, 2])
sage: V = ZZ^2
sage: h1 = V.hom(m)
sage: h1.nullity()
1
sage: W = ZZ^1
sage: h2 = W.hom(m, side="right")
sage: h2.nullity()
0
"""
if self.side() == "left":
return self._matrix.left_nullity()
else:
return self._matrix.right_nullity()
def is_bijective(self):
r"""
Tell whether ``self`` is bijective.
EXAMPLES:
Two morphisms that are obviously not bijective, simply on
considerations of the dimensions. However, each fullfills
half of the requirements to be a bijection. ::
sage: V1 = QQ^2
sage: V2 = QQ^3
sage: m = matrix(QQ, [[1, 2, 3], [4, 5, 6]])
sage: phi = V1.hom(m, V2)
sage: phi.is_injective()
True
sage: phi.is_bijective()
False
sage: rho = V2.hom(m.transpose(), V1)
sage: rho.is_surjective()
True
sage: rho.is_bijective()
False
We construct a simple bijection between two one-dimensional
vector spaces. ::
sage: V1 = QQ^3
sage: V2 = QQ^2
sage: phi = V1.hom(matrix(QQ, [[1, 2], [3, 4], [5, 6]]), V2)
sage: x = vector(QQ, [1, -1, 4])
sage: y = phi(x); y
(18, 22)
sage: rho = phi.restrict_domain(V1.span([x]))
sage: zeta = rho.restrict_codomain(V2.span([y]))
sage: zeta.is_bijective()
True
AUTHOR:
- Rob Beezer (2011-06-28)
"""
return self.is_injective() and self.is_surjective()
def is_identity(self):
r"""
Determines if this morphism is an identity function or not.
EXAMPLES:
A homomorphism that cannot possibly be the identity
due to an unequal domain and codomain. ::
sage: V = QQ^3
sage: W = QQ^2
sage: m = matrix(QQ, [[1, 2], [3, 4], [5, 6]])
sage: phi = V.hom(m, W)
sage: phi.is_identity()
False
A bijection, but not the identity. ::
sage: V = QQ^3
sage: n = matrix(QQ, [[3, 1, -8], [5, -4, 6], [1, 1, -5]])
sage: phi = V.hom(n, V)
sage: phi.is_bijective()
True
sage: phi.is_identity()
False
A restriction that is the identity. ::
sage: V = QQ^3
sage: p = matrix(QQ, [[1, 0, 0], [5, 8, 3], [0, 0, 1]])
sage: phi = V.hom(p, V)
sage: rho = phi.restrict(V.span([V.0, V.2]))
sage: rho.is_identity()
True
An identity linear transformation that is defined with a
domain and codomain with wildly different bases, so that the
matrix representation is not simply the identity matrix. ::
sage: A = matrix(QQ, [[1, 1, 0], [2, 3, -4], [2, 4, -7]])
sage: B = matrix(QQ, [[2, 7, -2], [-1, -3, 1], [-1, -6, 2]])
sage: U = (QQ^3).subspace_with_basis(A.rows())
sage: V = (QQ^3).subspace_with_basis(B.rows())
sage: H = Hom(U, V)
sage: id = lambda x: x
sage: phi = H(id)
sage: phi([203, -179, 34])
(203, -179, 34)
sage: phi.matrix()
[ 1 0 1]
[ -9 -18 -2]
[-17 -31 -5]
sage: phi.is_identity()
True
TESTS::
sage: V = QQ^10
sage: H = Hom(V, V)
sage: id = H.identity()
sage: id.is_identity()
True
AUTHOR:
- Rob Beezer (2011-06-28)
"""
if self.domain() != self.codomain():
return False
# testing for the identity matrix will only work for
# endomorphisms which have the same basis for domain and codomain
# so we test equality on a basis, which is sufficient
return all(self(u) == u for u in self.domain().basis())
def is_zero(self):
r"""
Determines if this morphism is a zero function or not.
EXAMPLES:
A zero morphism created from a function. ::
sage: V = ZZ^5
sage: W = ZZ^3
sage: z = lambda x: zero_vector(ZZ, 3)
sage: phi = V.hom(z, W)
sage: phi.is_zero()
True
An image list that just barely makes a non-zero morphism. ::
sage: V = ZZ^4
sage: W = ZZ^6
sage: z = zero_vector(ZZ, 6)
sage: images = [z, z, W.5, z]
sage: phi = V.hom(images, W)
sage: phi.is_zero()
False
TESTS::
sage: V = QQ^10
sage: W = QQ^3
sage: H = Hom(V, W)
sage: rho = H.zero()
sage: rho.is_zero()
True
AUTHOR:
- Rob Beezer (2011-07-15)
"""
# any nonzero entry in any matrix representation
# disqualifies the morphism as having totally zero outputs
return self._matrix.is_zero()
def is_equal_function(self, other):
r"""
Determines if two morphisms are equal functions.
INPUT:
- ``other`` - a morphism to compare with ``self``
OUTPUT:
Returns ``True`` precisely when the two morphisms have
equal domains and codomains (as sets) and produce identical
output when given the same input. Otherwise returns ``False``.
This is useful when ``self`` and ``other`` may have different
representations.
Sage's default comparison of matrix morphisms requires the
domains to have the same bases and the codomains to have the
same bases, and then compares the matrix representations.
This notion of equality is more permissive (it will
return ``True`` "more often"), but is more correct
mathematically.
EXAMPLES:
Three morphisms defined by combinations of different
bases for the domain and codomain and different functions.
Two are equal, the third is different from both of the others. ::
sage: B = matrix(QQ, [[-3, 5, -4, 2],
....: [-1, 2, -1, 4],
....: [ 4, -6, 5, -1],
....: [-5, 7, -6, 1]])
sage: U = (QQ^4).subspace_with_basis(B.rows())
sage: C = matrix(QQ, [[-1, -6, -4],
....: [ 3, -5, 6],
....: [ 1, 2, 3]])
sage: V = (QQ^3).subspace_with_basis(C.rows())
sage: H = Hom(U, V)
sage: D = matrix(QQ, [[-7, -2, -5, 2],
....: [-5, 1, -4, -8],
....: [ 1, -1, 1, 4],
....: [-4, -1, -3, 1]])
sage: X = (QQ^4).subspace_with_basis(D.rows())
sage: E = matrix(QQ, [[ 4, -1, 4],
....: [ 5, -4, -5],
....: [-1, 0, -2]])
sage: Y = (QQ^3).subspace_with_basis(E.rows())
sage: K = Hom(X, Y)
sage: f = lambda x: vector(QQ, [x[0]+x[1], 2*x[1]-4*x[2], 5*x[3]])
sage: g = lambda x: vector(QQ, [x[0]-x[2], 2*x[1]-4*x[2], 5*x[3]])
sage: rho = H(f)
sage: phi = K(f)
sage: zeta = H(g)
sage: rho.is_equal_function(phi)
True
sage: phi.is_equal_function(rho)
True
sage: zeta.is_equal_function(rho)
False
sage: phi.is_equal_function(zeta)
False
TESTS::
sage: H = Hom(ZZ^2, ZZ^2)
sage: phi = H(matrix(ZZ, 2, range(4)))
sage: phi.is_equal_function('junk')
Traceback (most recent call last):
...
TypeError: can only compare to a matrix morphism, not junk
AUTHOR:
- Rob Beezer (2011-07-15)
"""
if not is_MatrixMorphism(other):
msg = 'can only compare to a matrix morphism, not {0}'
raise TypeError(msg.format(other))
if self.domain() != other.domain():
return False
if self.codomain() != other.codomain():
return False
# check agreement on any basis of the domain
return all(self(u) == other(u) for u in self.domain().basis())
def restrict_domain(self, sub):
"""
Restrict this matrix morphism to a subspace sub of the domain. The
subspace sub should have a basis() method and elements of the basis
should be coercible into domain.
The resulting morphism has the same codomain as before, but a new
domain.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1])
sage: phi.restrict_domain(V.span([V.0]))
Free module morphism defined by the matrix
[3 0]
Domain: Free module of degree 2 and rank 1 over Integer Ring
Echelon ...
Codomain: Ambient free module of rank 2 over the principal ideal domain ...
sage: phi.restrict_domain(V.span([V.1]))
Free module morphism defined by the matrix
[0 2]...
sage: m = matrix(2, range(1,5))
sage: f1 = V.hom(m); f2 = V.hom(m, side="right")
sage: SV = V.span([V.0])
sage: f1.restrict_domain(SV)
Free module morphism defined by the matrix
[1 2]...
sage: f2.restrict_domain(SV)
Free module morphism defined as left-multiplication by the matrix
[1]
[3]...
"""
D = self.domain()
if hasattr(D, 'coordinate_module'):
# We only have to do this in case the module supports
# alternative basis. Some modules do, some modules don't.
V = D.coordinate_module(sub)
else:
V = sub.free_module()
if self.side() == "right":
A = self.matrix().transpose().restrict_domain(V).transpose()
else:
A = self.matrix().restrict_domain(V)
H = sub.Hom(self.codomain())
try:
return H(A, side=self.side())
except Exception:
return H(A)
def restrict_codomain(self, sub):
"""
Restrict this matrix morphism to a subspace sub of the codomain.
The resulting morphism has the same domain as before, but a new
codomain.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([4*(V.0+V.1),0])
sage: W = V.span([2*(V.0+V.1)])
sage: phi
Free module morphism defined by the matrix
[4 4]
[0 0]
Domain: Ambient free module of rank 2 over the principal ideal domain ...
Codomain: Ambient free module of rank 2 over the principal ideal domain ...
sage: psi = phi.restrict_codomain(W); psi
Free module morphism defined by the matrix
[2]
[0]
Domain: Ambient free module of rank 2 over the principal ideal domain ...
Codomain: Free module of degree 2 and rank 1 over Integer Ring
Echelon ...
sage: phi2 = phi.side_switch(); phi2.restrict_codomain(W)
Free module morphism defined as left-multiplication by the matrix
[2 0]
Domain: Ambient free module of rank 2 over the principal ideal domain Integer Ring
Codomain: Free module of degree 2 and rank 1 over Integer Ring
Echelon ...
An example in which the codomain equals the full ambient space, but
with a different basis::
sage: V = QQ^2
sage: W = V.span_of_basis([[1,2],[3,4]])
sage: phi = V.hom(matrix(QQ,2,[1,0,2,0]),W)
sage: phi.matrix()
[1 0]
[2 0]
sage: phi(V.0)
(1, 2)
sage: phi(V.1)
(2, 4)
sage: X = V.span([[1,2]]); X
Vector space of degree 2 and dimension 1 over Rational Field
Basis matrix:
[1 2]
sage: phi(V.0) in X
True
sage: phi(V.1) in X
True
sage: psi = phi.restrict_codomain(X); psi
Vector space morphism represented by the matrix:
[1]
[2]
Domain: Vector space of dimension 2 over Rational Field
Codomain: Vector space of degree 2 and dimension 1 over Rational Field
Basis matrix:
[1 2]
sage: psi(V.0)
(1, 2)
sage: psi(V.1)
(2, 4)
sage: psi(V.0).parent() is X
True
"""
H = self.domain().Hom(sub)
C = self.codomain()
if hasattr(C, 'coordinate_module'):
# We only have to do this in case the module supports
# alternative basis. Some modules do, some modules don't.
V = C.coordinate_module(sub)
else:
V = sub.free_module()
try:
if self.side() == "right":
return H(self.matrix().transpose().restrict_codomain(V).transpose(), side="right")
else:
return H(self.matrix().restrict_codomain(V))
except Exception:
return H(self.matrix().restrict_codomain(V))
def restrict(self, sub):
"""
Restrict this matrix morphism to a subspace sub of the domain.
The codomain and domain of the resulting matrix are both sub.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1])
sage: phi.restrict(V.span([V.0]))
Free module morphism defined by the matrix
[3]
Domain: Free module of degree 2 and rank 1 over Integer Ring
Echelon ...
Codomain: Free module of degree 2 and rank 1 over Integer Ring
Echelon ...
sage: V = (QQ^2).span_of_basis([[1,2],[3,4]])
sage: phi = V.hom([V.0+V.1, 2*V.1])
sage: phi(V.1) == 2*V.1
True
sage: W = span([V.1])
sage: phi(W)
Vector space of degree 2 and dimension 1 over Rational Field
Basis matrix:
[ 1 4/3]
sage: psi = phi.restrict(W); psi
Vector space morphism represented by the matrix:
[2]
Domain: Vector space of degree 2 and dimension 1 over Rational Field
Basis matrix:
[ 1 4/3]
Codomain: Vector space of degree 2 and dimension 1 over Rational Field
Basis matrix:
[ 1 4/3]
sage: psi.domain() == W
True
sage: psi(W.0) == 2*W.0
True
::
sage: V = ZZ^3
sage: h1 = V.hom([V.0, V.1+V.2, -V.1+V.2])
sage: h2 = h1.side_switch()
sage: SV = V.span([2*V.1,2*V.2])
sage: h1.restrict(SV)
Free module morphism defined by the matrix
[ 1 1]
[-1 1]
Domain: Free module of degree 3 and rank 2 over Integer Ring
Echelon basis matrix:
[0 2 0]
[0 0 2]
Codomain: Free module of degree 3 and rank 2 over Integer Ring
Echelon basis matrix:
[0 2 0]
[0 0 2]
sage: h2.restrict(SV)
Free module morphism defined as left-multiplication by the matrix
[ 1 -1]
[ 1 1]
Domain: Free module of degree 3 and rank 2 over Integer Ring
Echelon basis matrix:
[0 2 0]
[0 0 2]
Codomain: Free module of degree 3 and rank 2 over Integer Ring
Echelon basis matrix:
[0 2 0]
[0 0 2]
"""
if not self.is_endomorphism():
raise ArithmeticError("matrix morphism must be an endomorphism")
D = self.domain()
C = self.codomain()
if D is not C and (D.basis() != C.basis()):
# Tricky case when two bases for same space
return self.restrict_domain(sub).restrict_codomain(sub)
if hasattr(D, 'coordinate_module'):
# We only have to do this in case the module supports
# alternative basis. Some modules do, some modules don't.
V = D.coordinate_module(sub)
else:
V = sub.free_module()
if self.side() == "right":
A = self.matrix().transpose().restrict(V).transpose()
else:
A = self.matrix().restrict(V)
H = sage.categories.homset.End(sub, self.domain().category())
return H(A, side=self.side())
class MatrixMorphism(MatrixMorphism_abstract):
"""
A morphism defined by a matrix.
INPUT:
- ``parent`` -- a homspace
- ``A`` -- matrix or a :class:`MatrixMorphism_abstract` instance
- ``copy_matrix`` -- (default: ``True``) make an immutable copy of
the matrix ``A`` if it is mutable; if ``False``, then this makes
``A`` immutable
"""
def __init__(self, parent, A, copy_matrix=True, side='left'):
"""
Initialize ``self``.
EXAMPLES::
sage: from sage.modules.matrix_morphism import MatrixMorphism
sage: T = End(ZZ^3)
sage: M = MatrixSpace(ZZ,3)
sage: I = M.identity_matrix()
sage: A = MatrixMorphism(T, I)
sage: loads(A.dumps()) == A
True
"""
if parent is None:
raise ValueError("no parent given when creating this matrix morphism")
if isinstance(A, MatrixMorphism_abstract):
A = A.matrix()
if side == "left":
if A.nrows() != parent.domain().rank():
raise ArithmeticError("number of rows of matrix (={}) must equal rank of domain (={})".format(A.nrows(), parent.domain().rank()))
if A.ncols() != parent.codomain().rank():
raise ArithmeticError("number of columns of matrix (={}) must equal rank of codomain (={})".format(A.ncols(), parent.codomain().rank()))
if side == "right":
if A.nrows() != parent.codomain().rank():
raise ArithmeticError("number of rows of matrix (={}) must equal rank of codomain (={})".format(A.nrows(), parent.domain().rank()))
if A.ncols() != parent.domain().rank():
raise ArithmeticError("number of columns of matrix (={}) must equal rank of domain (={})".format(A.ncols(), parent.codomain().rank()))
if A.is_mutable():
if copy_matrix:
from copy import copy
A = copy(A)
A.set_immutable()
self._matrix = A
MatrixMorphism_abstract.__init__(self, parent, side)
def matrix(self, side=None):
r"""
Return a matrix that defines this morphism.
INPUT:
- ``side`` -- (default: ``'None'``) the side of the matrix
where a vector is placed to effect the morphism (function)
OUTPUT:
A matrix which represents the morphism, relative to bases
for the domain and codomain. If the modules are provided
with user bases, then the representation is relative to
these bases.
Internally, Sage represents a matrix morphism with the
matrix multiplying a row vector placed to the left of the
matrix. If the option ``side='right'`` is used, then a
matrix is returned that acts on a vector to the right of
the matrix. These two matrices are just transposes of
each other and the difference is just a preference for
the style of representation.
EXAMPLES::
sage: V = ZZ^2; W = ZZ^3
sage: m = column_matrix([3*V.0 - 5*V.1, 4*V.0 + 2*V.1, V.0 + V.1])
sage: phi = V.hom(m, W)
sage: phi.matrix()
[ 3 4 1]
[-5 2 1]
sage: phi.matrix(side='right')
[ 3 -5]
[ 4 2]
[ 1 1]
TESTS::
sage: V = ZZ^2
sage: phi = V.hom([3*V.0, 2*V.1])
sage: phi.matrix(side='junk')
Traceback (most recent call last):
...
ValueError: side must be 'left' or 'right', not junk
"""
if side not in ['left', 'right', None]:
raise ValueError("side must be 'left' or 'right', not {0}".format(side))
if side == self.side() or side is None:
return self._matrix
return self._matrix.transpose()
def is_injective(self):
"""
Tell whether ``self`` is injective.
EXAMPLES::
sage: V1 = QQ^2
sage: V2 = QQ^3
sage: phi = V1.hom(Matrix([[1,2,3],[4,5,6]]),V2)
sage: phi.is_injective()
True
sage: psi = V2.hom(Matrix([[1,2],[3,4],[5,6]]),V1)
sage: psi.is_injective()
False
AUTHOR:
-- Simon King (2010-05)
"""
if self.side() == 'left':
ker = self._matrix.left_kernel()
else:
ker = self._matrix.right_kernel()
return ker.dimension() == 0
def is_surjective(self):
r"""
Tell whether ``self`` is surjective.
EXAMPLES::
sage: V1 = QQ^2
sage: V2 = QQ^3
sage: phi = V1.hom(Matrix([[1,2,3],[4,5,6]]), V2)
sage: phi.is_surjective()
False
sage: psi = V2.hom(Matrix([[1,2],[3,4],[5,6]]), V1)
sage: psi.is_surjective()
True
An example over a PID that is not `\ZZ`. ::
sage: R = PolynomialRing(QQ, 'x')
sage: A = R^2
sage: B = R^2
sage: H = A.hom([B([x^2-1, 1]), B([x^2, 1])])
sage: H.image()
Free module of degree 2 and rank 2 over Univariate Polynomial Ring in x over Rational Field
Echelon basis matrix:
[ 1 0]
[ 0 -1]
sage: H.is_surjective()
True
This tests if :trac:`11552` is fixed. ::
sage: V = ZZ^2
sage: m = matrix(ZZ, [[1,2],[0,2]])
sage: phi = V.hom(m, V)
sage: phi.lift(vector(ZZ, [0, 1]))
Traceback (most recent call last):
...
ValueError: element is not in the image
sage: phi.is_surjective()
False
AUTHORS:
- Simon King (2010-05)
- Rob Beezer (2011-06-28)
"""
# Testing equality of free modules over PIDs is unreliable
# see Trac #11579 for explanation and status
# We test if image equals codomain with two inclusions
# reverse inclusion of below is trivially true
return self.codomain().is_submodule(self.image())
def _repr_(self):
r"""
Return string representation of this matrix morphism.
This will typically be overloaded in a derived class.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1])
sage: sage.modules.matrix_morphism.MatrixMorphism._repr_(phi)
'Morphism defined by the matrix\n[3 0]\n[0 2]'
sage: phi._repr_()
'Free module morphism defined by the matrix\n[3 0]\n[0 2]\nDomain: Ambient free module of rank 2 over the principal ideal domain Integer Ring\nCodomain: Ambient free module of rank 2 over the principal ideal domain Integer Ring'
"""
rep = "Morphism defined by the matrix\n{0}".format(self.matrix())
if self._side == 'right':
rep += " acting by multiplication on the left"
return rep | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modules/matrix_morphism.py | 0.839273 | 0.742492 | matrix_morphism.py | pypi |
from sage.geometry.polyhedron.constructor import Polyhedron
from sage.matrix.constructor import matrix, identity_matrix
from sage.modules.free_module_element import vector
from math import sqrt, floor, ceil
def plane_inequality(v):
"""
Return the inequality for points on the same side as the origin
with respect to the plane through ``v`` normal to ``v``.
EXAMPLES::
sage: from sage.modules.diamond_cutting import plane_inequality
sage: ieq = plane_inequality([1, -1]); ieq
[2, -1, 1]
sage: ieq[0] + vector(ieq[1:]) * vector([1, -1])
0
"""
v = vector(v)
c = -v * v
if c < 0:
c, v = -c, -v
return [c] + list(v)
def jacobi(M):
r"""
Compute the upper-triangular part of the Cholesky/Jacobi
decomposition of the symmetric matrix ``M``.
Let `M` be a symmetric `n \times n`-matrix over a field `F`.
Let `m_{i,j}` denote the `(i,j)`-th entry of `M` for any
`1 \leq i \leq n` and `1 \leq j \leq n`. Then, the
upper-triangular part computed by this method is the
upper-triangular `n \times n`-matrix `Q` whose
`(i,j)`-th entry `q_{i,j}` satisfies
.. MATH::
q_{i,j} =
\begin{cases}
\frac{1}{q_{i,i}} \left( m_{i,j} - \sum_{r<i} q_{r,r} q_{r,i} q_{r,j} \right) & i < j, \\
a_{i,j} - \sum_{r<i} q_{r,r} q_{r,i}^2 & i = j, \\
0 & i > j,
\end{cases}
for all `1 \leq i \leq n` and `1 \leq j \leq n`. (These
equalities determine the entries of `Q` uniquely by
recursion.) This matrix `Q` is defined for all `M` in a
certain Zariski-dense open subset of the set of all
`n \times n`-matrices.
.. NOTE::
This should be a method of matrices.
EXAMPLES::
sage: from sage.modules.diamond_cutting import jacobi
sage: jacobi(identity_matrix(3) * 4)
[4 0 0]
[0 4 0]
[0 0 4]
sage: def testall(M):
....: Q = jacobi(M)
....: for j in range(3):
....: for i in range(j):
....: if Q[i,j] * Q[i,i] != M[i,j] - sum(Q[r,i] * Q[r,j] * Q[r,r] for r in range(i)):
....: return False
....: for i in range(3):
....: if Q[i,i] != M[i,i] - sum(Q[r,i] ** 2 * Q[r,r] for r in range(i)):
....: return False
....: for j in range(i):
....: if Q[i,j] != 0:
....: return False
....: return True
sage: M = Matrix(QQ, [[8,1,5], [1,6,0], [5,0,3]])
sage: Q = jacobi(M); Q
[ 8 1/8 5/8]
[ 0 47/8 -5/47]
[ 0 0 -9/47]
sage: testall(M)
True
sage: M = Matrix(QQ, [[3,6,-1,7],[6,9,8,5],[-1,8,2,4],[7,5,4,0]])
sage: testall(M)
True
"""
if not M.is_square():
raise ValueError("the matrix must be square")
dim = M.nrows()
q = [list(row) for row in M]
for i in range(dim - 1):
for j in range(i + 1, dim):
q[j][i] = q[i][j]
q[i][j] = q[i][j] / q[i][i]
for k in range(i + 1, dim):
for l in range(k, dim):
q[k][l] -= q[k][i] * q[i][l]
for i in range(1, dim):
for j in range(i):
q[i][j] = 0
return matrix(q)
def diamond_cut(V, GM, C, verbose=False):
r"""
Perform diamond cutting on polyhedron ``V`` with basis matrix ``GM``
and radius ``C``.
INPUT:
- ``V`` -- polyhedron to cut from
- ``GM`` -- half of the basis matrix of the lattice
- ``C`` -- radius to use in cutting algorithm
- ``verbose`` -- (default: ``False``) whether to print debug information
OUTPUT:
A :class:`Polyhedron` instance.
EXAMPLES::
sage: from sage.modules.diamond_cutting import diamond_cut
sage: V = Polyhedron([[0], [2]])
sage: GM = matrix([2])
sage: V = diamond_cut(V, GM, 4)
sage: V.vertices()
(A vertex at (2), A vertex at (0))
"""
if verbose:
print("Cut\n{}\nwith radius {}".format(GM, C))
dim = GM.dimensions()
if dim[0] != dim[1]:
raise ValueError("the matrix must be square")
dim = dim[0]
T = [0] * dim
U = [0] * dim
x = [0] * dim
L = [0] * dim
# calculate the Gram matrix
q = matrix([[sum(GM[i][k] * GM[j][k] for k in range(dim))
for j in range(dim)] for i in range(dim)])
if verbose:
print("q:\n{}".format(q.n()))
# apply Cholesky/Jacobi decomposition
q = jacobi(q)
if verbose:
print("q:\n{}".format(q.n()))
i = dim - 1
T[i] = C
U[i] = 0
new_dimension = True
cut_count = 0
inequalities = []
while True:
if verbose:
print("Dimension: {}".format(i))
if new_dimension:
Z = sqrt(T[i] / q[i][i])
if verbose:
print("Z: {}".format(Z))
L[i] = int(floor(Z - U[i]))
if verbose:
print("L: {}".format(L))
x[i] = int(ceil(-Z - U[i]) - 1)
new_dimension = False
x[i] += 1
if verbose:
print("x: {}".format(x))
if x[i] > L[i]:
i += 1
elif i > 0:
T[i - 1] = T[i] - q[i][i] * (x[i] + U[i]) ** 2
i -= 1
U[i] = 0
for j in range(i + 1, dim):
U[i] += q[i][j] * x[j]
new_dimension = True
else:
if all(elmt == 0 for elmt in x):
break
hv = [0] * dim
for k in range(dim):
for j in range(dim):
hv[k] += x[j] * GM[j][k]
hv = vector(hv)
for hv in [hv, -hv]:
cut_count += 1
if verbose:
print("\n%d) Cut using normal vector %s" % (cut_count, hv))
inequalities.append(plane_inequality(hv))
if verbose:
print("Final cut")
cut = Polyhedron(ieqs=inequalities)
V = V.intersection(cut)
if verbose:
print("End")
return V
def calculate_voronoi_cell(basis, radius=None, verbose=False):
"""
Calculate the Voronoi cell of the lattice defined by basis
INPUT:
- ``basis`` -- embedded basis matrix of the lattice
- ``radius`` -- radius of basis vectors to consider
- ``verbose`` -- whether to print debug information
OUTPUT:
A :class:`Polyhedron` instance.
EXAMPLES::
sage: from sage.modules.diamond_cutting import calculate_voronoi_cell
sage: V = calculate_voronoi_cell(matrix([[1, 0], [0, 1]]))
sage: V.volume()
1
"""
dim = basis.dimensions()
artificial_length = None
if dim[0] < dim[1]:
# introduce "artificial" basis points (representing infinity)
def approx_norm(v):
r,r1 = (v.inner_product(v)).sqrtrem()
return r + (r1 > 0)
artificial_length = max(approx_norm(v) for v in basis) * 2
additional_vectors = identity_matrix(dim[1]) * artificial_length
basis = basis.stack(additional_vectors)
# LLL-reduce to get quadratic matrix
basis = basis.LLL()
basis = matrix([v for v in basis if v])
dim = basis.dimensions()
if dim[0] != dim[1]:
raise ValueError("invalid matrix")
basis = basis / 2
ieqs = []
for v in basis:
ieqs.append(plane_inequality(v))
ieqs.append(plane_inequality(-v))
Q = Polyhedron(ieqs=ieqs)
# twice the length of longest vertex in Q is a safe choice
if radius is None:
radius = 2 * max(v.inner_product(v) for v in basis)
V = diamond_cut(Q, basis, radius, verbose=verbose)
if artificial_length is not None:
# remove inequalities introduced by artificial basis points
H = V.Hrepresentation()
H = [v for v in H if all(not V._is_zero(v.A() * w / 2 - v.b()) and
not V._is_zero(v.A() * (-w) / 2 - v.b())
for w in additional_vectors)]
V = Polyhedron(ieqs=H)
return V | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modules/diamond_cutting.py | 0.880277 | 0.769643 | diamond_cutting.py | pypi |
from sage.misc.abstract_method import abstract_method
from sage.structure.element import Element
from sage.combinat.free_module import CombinatorialFreeModule
from sage.categories.modules import Modules
class Representation_abstract(CombinatorialFreeModule):
"""
Abstract base class for representations of semigroups.
INPUT:
- ``semigroup`` -- a semigroup
- ``base_ring`` -- a commutative ring
"""
def __init__(self, semigroup, base_ring, *args, **opts):
"""
Initialize ``self``.
EXAMPLES::
sage: G = FreeGroup(3)
sage: T = G.trivial_representation()
sage: TestSuite(T).run()
"""
self._semigroup = semigroup
self._semigroup_algebra = semigroup.algebra(base_ring)
CombinatorialFreeModule.__init__(self, base_ring, *args, **opts)
def semigroup(self):
"""
Return the semigroup whose representation ``self`` is.
EXAMPLES::
sage: G = SymmetricGroup(4)
sage: M = CombinatorialFreeModule(QQ, ['v'])
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.term(m, g.sign())
sage: R = Representation(G, M, on_basis)
sage: R.semigroup()
Symmetric group of order 4! as a permutation group
"""
return self._semigroup
def semigroup_algebra(self):
"""
Return the semigroup algebra whose representation ``self`` is.
EXAMPLES::
sage: G = SymmetricGroup(4)
sage: M = CombinatorialFreeModule(QQ, ['v'])
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.term(m, g.sign())
sage: R = Representation(G, M, on_basis)
sage: R.semigroup_algebra()
Symmetric group algebra of order 4 over Rational Field
"""
return self._semigroup_algebra
@abstract_method
def side(self):
"""
Return whether ``self`` is a left, right, or two-sided representation.
OUTPUT:
- the string ``"left"``, ``"right"``, or ``"twosided"``
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.regular_representation()
sage: R.side()
'left'
"""
def invariant_module(self, S=None, **kwargs):
r"""
Return the submodule of ``self`` invariant under the action of ``S``.
For a semigroup `S` acting on a module `M`, the invariant
submodule is given by
.. MATH::
M^S = \{m \in M : s \cdot m = m \forall s \in S\}.
INPUT:
- ``S`` -- a finitely-generated semigroup (default: the semigroup
this is a representation of)
- ``action`` -- a function (default: :obj:`operator.mul`)
- ``side`` -- ``'left'`` or ``'right'`` (default: :meth:`side()`);
which side of ``self`` the elements of ``S`` acts
.. NOTE::
Two sided actions are considered as left actions for the
invariant module.
OUTPUT:
- :class:`~sage.modules.with_basis.invariant.FiniteDimensionalInvariantModule`
EXAMPLES::
sage: S3 = SymmetricGroup(3)
sage: M = S3.regular_representation()
sage: I = M.invariant_module()
sage: [I.lift(b) for b in I.basis()]
[() + (2,3) + (1,2) + (1,2,3) + (1,3,2) + (1,3)]
We build the `D_4`-invariant representation inside of the regular
representation of `S_4`::
sage: D4 = groups.permutation.Dihedral(4)
sage: S4 = SymmetricGroup(4)
sage: R = S4.regular_representation()
sage: I = R.invariant_module(D4)
sage: [I.lift(b) for b in I.basis()]
[() + (2,4) + (1,2)(3,4) + (1,2,3,4) + (1,3) + (1,3)(2,4) + (1,4,3,2) + (1,4)(2,3),
(3,4) + (2,3,4) + (1,2) + (1,2,4) + (1,3,2) + (1,3,2,4) + (1,4,3) + (1,4,2,3),
(2,3) + (2,4,3) + (1,2,3) + (1,2,4,3) + (1,3,4,2) + (1,3,4) + (1,4,2) + (1,4)]
"""
if S is None:
S = self.semigroup()
side = kwargs.pop('side', self.side())
if side == "twosided":
side = "left"
return super().invariant_module(S, side=side, **kwargs)
def twisted_invariant_module(self, chi, G=None, **kwargs):
r"""
Create the isotypic component of the action of ``G`` on
``self`` with irreducible character given by ``chi``.
.. SEEALSO::
- :class:`~sage.modules.with_basis.invariant.FiniteDimensionalTwistedInvariantModule`
INPUT:
- ``chi`` -- a list/tuple of character values or an instance
of :class:`~sage.groups.class_function.ClassFunction_gap`
- ``G`` -- a finitely-generated semigroup (default: the semigroup
this is a representation of)
This also accepts the group to be the first argument to be the group.
OUTPUT:
- :class:`~sage.modules.with_basis.invariant.FiniteDimensionalTwistedInvariantModule`
EXAMPLES::
sage: G = SymmetricGroup(3)
sage: R = G.regular_representation(QQ)
sage: T = R.twisted_invariant_module([2,0,-1])
sage: T.basis()
Finite family {0: B[0], 1: B[1], 2: B[2], 3: B[3]}
sage: [T.lift(b) for b in T.basis()]
[() - (1,2,3), -(1,2,3) + (1,3,2), (2,3) - (1,2), -(1,2) + (1,3)]
We check the different inputs work
sage: R.twisted_invariant_module([2,0,-1], G) is T
True
sage: R.twisted_invariant_module(G, [2,0,-1]) is T
True
"""
from sage.categories.groups import Groups
if G is None:
G = self.semigroup()
elif chi in Groups():
G, chi = chi, G
side = kwargs.pop('side', self.side())
if side == "twosided":
side = "left"
return super().twisted_invariant_module(G, chi, side=side, **kwargs)
class Representation(Representation_abstract):
"""
Representation of a semigroup.
INPUT:
- ``semigroup`` -- a semigroup
- ``module`` -- a module with a basis
- ``on_basis`` -- function which takes as input ``g``, ``m``, where
``g`` is an element of the semigroup and ``m`` is an element of the
indexing set for the basis, and returns the result of ``g`` acting
on ``m``
- ``side`` -- (default: ``"left"``) whether this is a
``"left"`` or ``"right"`` representation
EXAMPLES:
We construct the sign representation of a symmetric group::
sage: G = SymmetricGroup(4)
sage: M = CombinatorialFreeModule(QQ, ['v'])
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.term(m, g.sign())
sage: R = Representation(G, M, on_basis)
sage: x = R.an_element(); x
2*B['v']
sage: c,s = G.gens()
sage: c,s
((1,2,3,4), (1,2))
sage: c * x
-2*B['v']
sage: s * x
-2*B['v']
sage: c * s * x
2*B['v']
sage: (c * s) * x
2*B['v']
This extends naturally to the corresponding group algebra::
sage: A = G.algebra(QQ)
sage: s,c = A.algebra_generators()
sage: c,s
((1,2,3,4), (1,2))
sage: c * x
-2*B['v']
sage: s * x
-2*B['v']
sage: c * s * x
2*B['v']
sage: (c * s) * x
2*B['v']
sage: (c + s) * x
-4*B['v']
REFERENCES:
- :wikipedia:`Group_representation`
"""
def __init__(self, semigroup, module, on_basis, side="left", **kwargs):
"""
Initialize ``self``.
EXAMPLES::
sage: G = SymmetricGroup(4)
sage: M = CombinatorialFreeModule(QQ, ['v'])
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.term(m, g.sign())
sage: R = Representation(G, M, on_basis)
sage: R._test_representation()
sage: G = CyclicPermutationGroup(3)
sage: M = algebras.Exterior(QQ, 'x', 3)
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.prod([M.monomial(FrozenBitset([g(j+1)-1])) for j in m]) #cyclically permute generators
sage: from sage.categories.algebras import Algebras
sage: R = Representation(G, M, on_basis, category=Algebras(QQ).WithBasis().FiniteDimensional())
sage: r = R.an_element(); r
1 + 2*x0 + x0*x1 + 3*x1
sage: r*r
1 + 4*x0 + 2*x0*x1 + 6*x1
sage: x0, x1, x2 = M.gens()
sage: s = R(x0*x1)
sage: g = G.an_element()
sage: g*s
x1*x2
sage: g*R(x1*x2)
-x0*x2
sage: g*r
1 + 2*x1 + x1*x2 + 3*x2
sage: g^2*r
1 + 3*x0 - x0*x2 + 2*x2
sage: G = SymmetricGroup(4)
sage: A = SymmetricGroup(4).algebra(QQ)
sage: from sage.categories.algebras import Algebras
sage: from sage.modules.with_basis.representation import Representation
sage: action = lambda g,x: A.monomial(g*x)
sage: category = Algebras(QQ).WithBasis().FiniteDimensional()
sage: R = Representation(G, A, action, 'left', category=category)
sage: r = R.an_element(); r
() + (2,3,4) + 2*(1,3)(2,4) + 3*(1,4)(2,3)
sage: r^2
14*() + 2*(2,3,4) + (2,4,3) + 12*(1,2)(3,4) + 3*(1,2,4) + 2*(1,3,2) + 4*(1,3)(2,4) + 5*(1,4,3) + 6*(1,4)(2,3)
sage: g = G.an_element(); g
(2,3,4)
sage: g*r
(2,3,4) + (2,4,3) + 2*(1,3,2) + 3*(1,4,3)
"""
try:
self.product_on_basis = module.product_on_basis
except AttributeError:
pass
category = kwargs.pop('category', Modules(module.base_ring()).WithBasis())
if side not in ["left", "right"]:
raise ValueError('side must be "left" or "right"')
self._left_repr = (side == "left")
self._on_basis = on_basis
self._module = module
indices = module.basis().keys()
if 'FiniteDimensional' in module.category().axioms():
category = category.FiniteDimensional()
Representation_abstract.__init__(self, semigroup, module.base_ring(), indices,
category=category, **module.print_options())
def _test_representation(self, **options):
"""
Check (on some elements) that ``self`` is a representation of the
given semigroup.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.regular_representation()
sage: R._test_representation()
sage: G = CoxeterGroup(['A',4,1], base_ring=ZZ)
sage: M = CombinatorialFreeModule(QQ, ['v'])
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.term(m, (-1)**g.length())
sage: R = Representation(G, M, on_basis, side="right")
sage: R._test_representation(max_runs=500)
"""
from sage.misc.functional import sqrt
tester = self._tester(**options)
S = tester.some_elements()
L = []
max_len = int(sqrt(tester._max_runs)) + 1
for i,x in enumerate(self._semigroup):
L.append(x)
if i >= max_len:
break
for x in L:
for y in L:
for elt in S:
if self._left_repr:
tester.assertEqual(x*(y*elt), (x*y)*elt)
else:
tester.assertEqual((elt*y)*x, elt*(y*x))
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: P = Permutations(4)
sage: M = CombinatorialFreeModule(QQ, ['v'])
sage: from sage.modules.with_basis.representation import Representation
sage: on_basis = lambda g,m: M.term(m, g.sign())
sage: Representation(P, M, on_basis)
Representation of Standard permutations of 4 indexed by {'v'}
over Rational Field
"""
return "Representation of {} indexed by {} over {}".format(
self._semigroup, self.basis().keys(), self.base_ring())
def _repr_term(self, b):
"""
Return a string representation of a basis index ``b`` of ``self``.
EXAMPLES::
sage: SGA = SymmetricGroupAlgebra(QQ, 3)
sage: R = SGA.regular_representation()
sage: all(R._repr_term(b) == SGA._repr_term(b) for b in SGA.basis().keys())
True
"""
return self._module._repr_term(b)
def _latex_term(self, b):
"""
Return a LaTeX representation of a basis index ``b`` of ``self``.
EXAMPLES::
sage: SGA = SymmetricGroupAlgebra(QQ, 3)
sage: R = SGA.regular_representation()
sage: all(R._latex_term(b) == SGA._latex_term(b) for b in SGA.basis().keys())
True
"""
return self._module._latex_term(b)
def _element_constructor_(self, x):
"""
Construct an element of ``self`` from ``x``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: A = G.algebra(ZZ)
sage: R = A.regular_representation()
sage: x = A.an_element(); x
() + (1,3) + 2*(1,3)(2,4) + 3*(1,4,3,2)
sage: R(x)
() + (1,3) + 2*(1,3)(2,4) + 3*(1,4,3,2)
"""
if isinstance(x, Element) and x.parent() is self._module:
return self._from_dict(x.monomial_coefficients(copy=False), remove_zeros=False)
return super()._element_constructor_(x)
def product_by_coercion(self, left, right):
"""
Return the product of ``left`` and ``right`` by passing to ``self._module``
and then building a new element of ``self``.
EXAMPLES::
sage: G = groups.permutation.KleinFour()
sage: E = algebras.Exterior(QQ,'e',4)
sage: on_basis = lambda g,m: E.monomial(m) # the trivial representation
sage: from sage.modules.with_basis.representation import Representation
sage: R = Representation(G, E, on_basis)
sage: r = R.an_element(); r
1 + 2*e0 + 3*e1 + e1*e2
sage: g = G.an_element();
sage: g*r == r
True
sage: r*r
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for *:
'Representation of The Klein 4 group of order 4, as a permutation
group indexed by Subsets of {0,1,...,3} over Rational Field' and
'Representation of The Klein 4 group of order 4, as a permutation
group indexed by Subsets of {0,1,...,3} over Rational Field'
sage: from sage.categories.algebras import Algebras
sage: category = Algebras(QQ).FiniteDimensional().WithBasis()
sage: T = Representation(G, E, on_basis, category=category)
sage: t = T.an_element(); t
1 + 2*e0 + 3*e1 + e1*e2
sage: g*t == t
True
sage: t*t
1 + 4*e0 + 4*e0*e1*e2 + 6*e1 + 2*e1*e2
"""
M = self._module
# Multiply in self._module
p = M._from_dict(left._monomial_coefficients, False, False) * M._from_dict(right._monomial_coefficients, False, False)
# Convert from a term in self._module to a term in self
return self._from_dict(p.monomial_coefficients(copy=False), False, False)
def side(self):
"""
Return whether ``self`` is a left or a right representation.
OUTPUT:
- the string ``"left"`` or ``"right"``
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.regular_representation()
sage: R.side()
'left'
sage: S = G.regular_representation(side="right")
sage: S.side()
'right'
"""
return "left" if self._left_repr else "right"
class Element(CombinatorialFreeModule.Element):
def _acted_upon_(self, scalar, self_on_left=False):
"""
Return the action of ``scalar`` on ``self``.
EXAMPLES::
sage: G = groups.misc.WeylGroup(['B',2], prefix='s')
sage: R = G.regular_representation()
sage: s1,s2 = G.gens()
sage: x = R.an_element(); x
2*s2*s1*s2 + s1*s2 + 3*s2 + 1
sage: 2 * x
4*s2*s1*s2 + 2*s1*s2 + 6*s2 + 2
sage: s1 * x
2*s2*s1*s2*s1 + 3*s1*s2 + s1 + s2
sage: s2 * x
s2*s1*s2 + 2*s1*s2 + s2 + 3
sage: G = groups.misc.WeylGroup(['B',2], prefix='s')
sage: R = G.regular_representation(side="right")
sage: s1,s2 = G.gens()
sage: x = R.an_element(); x
2*s2*s1*s2 + s1*s2 + 3*s2 + 1
sage: x * s1
2*s2*s1*s2*s1 + s1*s2*s1 + 3*s2*s1 + s1
sage: x * s2
2*s2*s1 + s1 + s2 + 3
sage: G = groups.misc.WeylGroup(['B',2], prefix='s')
sage: R = G.regular_representation()
sage: R.base_ring()
Integer Ring
sage: A = G.algebra(ZZ)
sage: s1,s2 = A.algebra_generators()
sage: x = R.an_element(); x
2*s2*s1*s2 + s1*s2 + 3*s2 + 1
sage: s1 * x
2*s2*s1*s2*s1 + 3*s1*s2 + s1 + s2
sage: s2 * x
s2*s1*s2 + 2*s1*s2 + s2 + 3
sage: (2*s1 - s2) * x
4*s2*s1*s2*s1 - s2*s1*s2 + 4*s1*s2 + 2*s1 + s2 - 3
sage: (3*s1 + s2) * R.zero()
0
sage: A = G.algebra(QQ)
sage: s1,s2 = A.algebra_generators()
sage: a = 1/2 * s1
sage: a * x
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for *:
'Algebra of Weyl Group of type ['B', 2] ... over Rational Field'
and 'Left Regular Representation of Weyl Group of type ['B', 2] ... over Integer Ring'
Check that things that coerce into the group (algebra) also have
an action::
sage: D4 = groups.permutation.Dihedral(4)
sage: S4 = SymmetricGroup(4)
sage: S4.has_coerce_map_from(D4)
True
sage: R = S4.regular_representation()
sage: D4.an_element() * R.an_element()
2*(2,4) + 3*(1,2,3,4) + (1,3) + (1,4,2,3)
"""
if isinstance(scalar, Element):
P = self.parent()
sP = scalar.parent()
if sP is P._semigroup:
if not self:
return self
if self_on_left == P._left_repr:
scalar = ~scalar
return P.linear_combination(((P._on_basis(scalar, m), c)
for m,c in self), not self_on_left)
if sP is P._semigroup_algebra:
if not self:
return self
ret = P.zero()
for ms,cs in scalar:
if self_on_left == P._left_repr:
ms = ~ms
ret += P.linear_combination(((P._on_basis(ms, m), cs*c)
for m,c in self), not self_on_left)
return ret
if P._semigroup.has_coerce_map_from(sP):
scalar = P._semigroup(scalar)
return self._acted_upon_(scalar, self_on_left)
# Check for scalars first before general coercion to the semigroup algebra.
# This will result in a faster action for the scalars.
ret = CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left)
if ret is not None:
return ret
if P._semigroup_algebra.has_coerce_map_from(sP):
scalar = P._semigroup_algebra(scalar)
return self._acted_upon_(scalar, self_on_left)
return None
return CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left)
class RegularRepresentation(Representation):
r"""
The regular representation of a semigroup.
The left regular representation of a semigroup `S` over a commutative
ring `R` is the semigroup ring `R[S]` equipped with the left
`S`-action `x b_y = b_{xy}`, where `(b_z)_{z \in S}` is the natural
basis of `R[S]` and `x,y \in S`.
INPUT:
- ``semigroup`` -- a semigroup
- ``base_ring`` -- the base ring for the representation
- ``side`` -- (default: ``"left"``) whether this is a
``"left"`` or ``"right"`` representation
REFERENCES:
- :wikipedia:`Regular_representation`
"""
def __init__(self, semigroup, base_ring, side="left"):
"""
Initialize ``self``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.regular_representation()
sage: TestSuite(R).run()
"""
if side == "left":
on_basis = self._left_on_basis
else:
on_basis = self._right_on_basis
module = semigroup.algebra(base_ring)
Representation.__init__(self, semigroup, module, on_basis, side)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: G.regular_representation()
Left Regular Representation of Dihedral group of order 8
as a permutation group over Integer Ring
sage: G.regular_representation(side="right")
Right Regular Representation of Dihedral group of order 8
as a permutation group over Integer Ring
"""
if self._left_repr:
base = "Left Regular Representation"
else:
base = "Right Regular Representation"
return base + " of {} over {}".format(self._semigroup, self.base_ring())
def _left_on_basis(self, g, m):
"""
Return the left action of ``g`` on ``m``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.regular_representation()
sage: R._test_representation() # indirect doctest
"""
return self.monomial(g*m)
def _right_on_basis(self, g, m):
"""
Return the right action of ``g`` on ``m``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.regular_representation(side="right")
sage: R._test_representation() # indirect doctest
"""
return self.monomial(m*g)
class TrivialRepresentation(Representation_abstract):
"""
The trivial representation of a semigroup.
The trivial representation of a semigroup `S` over a commutative ring
`R` is the `1`-dimensional `R`-module on which every element of `S`
acts by the identity.
This is simultaneously a left and right representation.
INPUT:
- ``semigroup`` -- a semigroup
- ``base_ring`` -- the base ring for the representation
REFERENCES:
- :wikipedia:`Trivial_representation`
"""
def __init__(self, semigroup, base_ring):
"""
Initialize ``self``.
EXAMPLES::
sage: G = groups.permutation.PGL(2, 3)
sage: V = G.trivial_representation()
sage: TestSuite(V).run()
"""
cat = Modules(base_ring).WithBasis().FiniteDimensional()
Representation_abstract.__init__(self, semigroup, base_ring, ['v'], category=cat)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: G.trivial_representation()
Trivial representation of Dihedral group of order 8
as a permutation group over Integer Ring
"""
return "Trivial representation of {} over {}".format(self._semigroup,
self.base_ring())
def side(self):
"""
Return that ``self`` is a two-sided representation.
OUTPUT:
- the string ``"twosided"``
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.trivial_representation()
sage: R.side()
'twosided'
"""
return "twosided"
class Element(CombinatorialFreeModule.Element):
def _acted_upon_(self, scalar, self_on_left=False):
"""
Return the action of ``scalar`` on ``self``.
EXAMPLES::
sage: SGA = SymmetricGroupAlgebra(QQ, 3)
sage: V = SGA.trivial_representation()
sage: x = V.an_element()
sage: 2 * x
4*B['v']
sage: all(x * b == x for b in SGA.basis())
True
sage: all(b * x == x for b in SGA.basis())
True
sage: z = V.zero()
sage: all(b * z == z for b in SGA.basis())
True
sage: H = groups.permutation.Dihedral(5)
sage: G = SymmetricGroup(5)
sage: G.has_coerce_map_from(H)
True
sage: R = G.trivial_representation(QQ)
sage: H.an_element() * R.an_element()
2*B['v']
sage: AG = G.algebra(QQ)
sage: AG.an_element() * R.an_element()
14*B['v']
sage: AH = H.algebra(ZZ)
sage: AG.has_coerce_map_from(AH)
True
sage: AH.an_element() * R.an_element()
14*B['v']
"""
if isinstance(scalar, Element):
P = self.parent()
if P._semigroup.has_coerce_map_from(scalar.parent()):
return self
if P._semigroup_algebra.has_coerce_map_from(scalar.parent()):
if not self:
return self
scalar = P._semigroup_algebra(scalar)
d = self.monomial_coefficients(copy=True)
d['v'] *= sum(scalar.coefficients())
return P._from_dict(d)
return CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left)
class SignRepresentation_abstract(Representation_abstract):
"""
Generic implementation of a sign representation.
The sign representation of a semigroup `S` over a commutative ring
`R` is the `1`-dimensional `R`-module on which every element of `S`
acts by 1 if order of element is even (including 0) or -1 if order of element if odd.
This is simultaneously a left and right representation.
INPUT:
- ``permgroup`` -- a permgroup
- ``base_ring`` -- the base ring for the representation
- ``sign_function`` -- a function which returns 1 or -1 depending on the elements sign
REFERENCES:
- :wikipedia:`Representation_theory_of_the_symmetric_group`
"""
def __init__(self, group, base_ring, sign_function=None):
"""
Initialize ``self``.
EXAMPLES::
sage: G = groups.permutation.PGL(2, 3)
sage: V = G.sign_representation()
sage: TestSuite(V).run()
"""
self.sign_function = sign_function
if sign_function is None:
try:
self.sign_function = self._default_sign
except AttributeError:
raise TypeError("a sign function must be given")
cat = Modules(base_ring).WithBasis().FiniteDimensional()
Representation_abstract.__init__(self, group, base_ring, ["v"], category=cat)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: G.sign_representation()
Sign representation of Dihedral group of order 8
as a permutation group over Integer Ring
"""
return "Sign representation of {} over {}".format(
self._semigroup, self.base_ring()
)
def side(self):
"""
Return that ``self`` is a two-sided representation.
OUTPUT:
- the string ``"twosided"``
EXAMPLES::
sage: G = groups.permutation.Dihedral(4)
sage: R = G.sign_representation()
sage: R.side()
'twosided'
"""
return "twosided"
class Element(CombinatorialFreeModule.Element):
def _acted_upon_(self, scalar, self_on_left=False):
"""
Return the action of ``scalar`` on ``self``.
EXAMPLES::
sage: G = PermutationGroup(gens=[(1,2,3), (1,2)])
sage: S = G.sign_representation()
sage: x = S.an_element(); x
2*B['v']
sage: s,c = G.gens(); c
(1,2,3)
sage: s*x
-2*B['v']
sage: s*x*s
2*B['v']
sage: s*x*s*s*c
-2*B['v']
sage: A = G.algebra(ZZ)
sage: s,c = A.algebra_generators()
sage: c
(1,2,3)
sage: s
(1,2)
sage: c*x
2*B['v']
sage: c*c*x
2*B['v']
sage: c*x*s
-2*B['v']
sage: c*x*s*s
2*B['v']
sage: (c+s)*x
0
sage: (c-s)*x
4*B['v']
sage: H = groups.permutation.Dihedral(4)
sage: G = SymmetricGroup(4)
sage: G.has_coerce_map_from(H)
True
sage: R = G.sign_representation()
sage: H.an_element() * R.an_element()
-2*B['v']
sage: AG = G.algebra(ZZ)
sage: AH = H.algebra(ZZ)
sage: AG.has_coerce_map_from(AH)
True
sage: AH.an_element() * R.an_element()
-2*B['v']
"""
if isinstance(scalar, Element):
P = self.parent()
if P._semigroup.has_coerce_map_from(scalar.parent()):
scalar = P._semigroup(scalar)
return self if P.sign_function(scalar) > 0 else -self
# We need to check for scalars first
ret = CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left)
if ret is not None:
return ret
if P._semigroup_algebra.has_coerce_map_from(scalar.parent()):
if not self:
return self
sum_scalar_coeff = 0
scalar = P._semigroup_algebra(scalar)
for ms, cs in scalar:
sum_scalar_coeff += P.sign_function(ms) * cs
return sum_scalar_coeff * self
return None
return CombinatorialFreeModule.Element._acted_upon_(
self, scalar, self_on_left
)
class SignRepresentationPermgroup(SignRepresentation_abstract):
"""
The sign representation for a permutation group.
EXAMPLES::
sage: G = groups.permutation.PGL(2, 3)
sage: V = G.sign_representation()
sage: TestSuite(V).run()
"""
def _default_sign(self, elem):
"""
Return the sign of the element
INPUT:
- ``elem`` -- the element of the group
EXAMPLES::
sage: G = groups.permutation.PGL(2, 3)
sage: V = G.sign_representation()
sage: elem = G.an_element()
sage: elem
(1,2,4,3)
sage: V._default_sign(elem)
-1
"""
return elem.sign()
class SignRepresentationMatrixGroup(SignRepresentation_abstract):
"""
The sign representation for a matrix group.
EXAMPLES::
sage: G = groups.permutation.PGL(2, 3)
sage: V = G.sign_representation()
sage: TestSuite(V).run()
"""
def _default_sign(self, elem):
"""
Return the sign of the element
INPUT:
- ``elem`` -- the element of the group
EXAMPLES::
sage: G = GL(2, QQ)
sage: V = G.sign_representation()
sage: m = G.an_element()
sage: m
[1 0]
[0 1]
sage: V._default_sign(m)
1
"""
return 1 if elem.matrix().det() > 0 else -1
class SignRepresentationCoxeterGroup(SignRepresentation_abstract):
"""
The sign representation for a Coxeter group.
EXAMPLES::
sage: G = WeylGroup(["A", 1, 1])
sage: V = G.sign_representation()
sage: TestSuite(V).run()
"""
def _default_sign(self, elem):
"""
Return the sign of the element
INPUT:
- ``elem`` -- the element of the group
EXAMPLES::
sage: G = WeylGroup(["A", 1, 1])
sage: elem = G.an_element()
sage: V = G.sign_representation()
sage: V._default_sign(elem)
1
"""
return -1 if elem.length() % 2 else 1 | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modules/with_basis/representation.py | 0.902492 | 0.437884 | representation.py | pypi |
r"""
Monoids
"""
from sage.structure.parent import Parent
from sage.misc.cachefunc import cached_method
def is_Monoid(x):
r"""
Returns True if ``x`` is of type ``Monoid_class``.
EXAMPLES::
sage: from sage.monoids.monoid import is_Monoid
sage: is_Monoid(0)
False
sage: is_Monoid(ZZ) # The technical math meaning of monoid has
....: # no bearing whatsoever on the result: it's
....: # a typecheck which is not satisfied by ZZ
....: # since it does not inherit from Monoid_class.
False
sage: is_Monoid(sage.monoids.monoid.Monoid_class(('a','b')))
True
sage: F.<a,b,c,d,e> = FreeMonoid(5)
sage: is_Monoid(F)
True
"""
return isinstance(x, Monoid_class)
class Monoid_class(Parent):
def __init__(self, names):
r"""
EXAMPLES::
sage: from sage.monoids.monoid import Monoid_class
sage: Monoid_class(('a','b'))
<sage.monoids.monoid.Monoid_class_with_category object at ...>
TESTS::
sage: F.<a,b,c,d,e> = FreeMonoid(5)
sage: TestSuite(F).run()
"""
from sage.categories.monoids import Monoids
category = Monoids().FinitelyGeneratedAsMagma()
Parent.__init__(self, base=self, names=names, category=category)
@cached_method
def gens(self):
r"""
Returns the generators for ``self``.
EXAMPLES::
sage: F.<a,b,c,d,e> = FreeMonoid(5)
sage: F.gens()
(a, b, c, d, e)
"""
return tuple(self.gen(i) for i in range(self.ngens()))
def monoid_generators(self):
r"""
Returns the generators for ``self``.
EXAMPLES::
sage: F.<a,b,c,d,e> = FreeMonoid(5)
sage: F.monoid_generators()
Family (a, b, c, d, e)
"""
from sage.sets.family import Family
return Family(self.gens()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/monoids/monoid.py | 0.808521 | 0.498779 | monoid.py | pypi |
from copy import copy
from sage.misc.abstract_method import abstract_method
from sage.misc.cachefunc import cached_method
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element import MonoidElement
from sage.structure.indexed_generators import IndexedGenerators, parse_indices_names
from sage.structure.richcmp import op_EQ, op_NE, richcmp, rich_to_bool
import sage.data_structures.blas_dict as blas
from sage.categories.monoids import Monoids
from sage.categories.poor_man_map import PoorManMap
from sage.categories.sets_cat import Sets
from sage.rings.integer import Integer
from sage.rings.infinity import infinity
from sage.rings.integer_ring import ZZ
from sage.sets.family import Family
class IndexedMonoidElement(MonoidElement):
"""
An element of an indexed monoid.
This is an abstract class which uses the (abstract) method
:meth:`_sorted_items` for all of its functions. So to implement an
element of an indexed monoid, one just needs to implement
:meth:`_sorted_items`, which returns a list of pairs ``(i, p)`` where
``i`` is the index and ``p`` is the corresponding power, sorted in some
order. For example, in the free monoid there is no such choice, but for
the free abelian monoid, one could want lex order or have the highest
powers first.
Indexed monoid elements are ordered lexicographically with respect to
the result of :meth:`_sorted_items` (which for abelian free monoids is
influenced by the order on the indexing set).
"""
def __init__(self, F, x):
"""
Create the element ``x`` of an indexed free abelian monoid ``F``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F.gen(1)
F[1]
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: x = a^2 * b^3 * a^2 * b^4; x
F[0]^4*F[1]^7
sage: TestSuite(x).run()
sage: F = FreeMonoid(index_set=tuple('abcde'))
sage: a,b,c,d,e = F.gens()
sage: a in F
True
sage: a*b in F
True
sage: TestSuite(a*d^2*e*c*a).run()
"""
MonoidElement.__init__(self, F)
self._monomial = x
@abstract_method
def _sorted_items(self):
"""
Return the sorted items (i.e factors) of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: x = a*b^2*e*d
sage: x._sorted_items()
((0, 1), (1, 2), (4, 1), (3, 1))
.. SEEALSO::
:meth:`_repr_`, :meth:`_latex_`, :meth:`print_options`
"""
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: a*b^2*e*d
F[0]*F[1]^2*F[3]*F[4]
"""
if not self._monomial:
return '1'
monomial = self._sorted_items()
P = self.parent()
scalar_mult = P._print_options['scalar_mult']
exp = lambda v: '^{}'.format(v) if v != 1 else ''
return scalar_mult.join(P._repr_generator(g) + exp(v) for g,v in monomial)
def _ascii_art_(self):
r"""
Return an ASCII art representation of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: ascii_art(a*e*d)
F *F *F
0 3 4
sage: ascii_art(a*b^2*e*d)
2
F *F *F *F
0 1 3 4
"""
from sage.typeset.ascii_art import AsciiArt, ascii_art, empty_ascii_art
if not self._monomial:
return AsciiArt(["1"])
monomial = self._sorted_items()
P = self.parent()
scalar_mult = P._print_options['scalar_mult']
if all(x[1] == 1 for x in monomial):
ascii_art_gen = lambda m: P._ascii_art_generator(m[0])
else:
pref = AsciiArt([P.prefix()])
def ascii_art_gen(m):
if m[1] != 1:
r = (AsciiArt([" " * len(pref)]) + ascii_art(m[1]))
else:
r = empty_ascii_art
r = r * P._ascii_art_generator(m[0])
r._baseline = r._h - 2
return r
b = ascii_art_gen(monomial[0])
for x in monomial[1:]:
b = b + AsciiArt([scalar_mult]) + ascii_art_gen(x)
return b
def _latex_(self):
r"""
Return a `\LaTeX` representation of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: latex(a*b^2*e*d)
F_{0} F_{1}^{2} F_{3} F_{4}
"""
if not self._monomial:
return '1'
monomial = self._sorted_items()
P = self.parent()
scalar_mult = P._print_options['latex_scalar_mult']
if scalar_mult is None:
scalar_mult = P._print_options['scalar_mult']
if scalar_mult == "*":
scalar_mult = " "
exp = lambda v: '^{{{}}}'.format(v) if v != 1 else ''
return scalar_mult.join(P._latex_generator(g) + exp(v) for g,v in monomial)
def __iter__(self):
"""
Iterate over ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: list(b*a*c^3*b)
[(F[1], 1), (F[0], 1), (F[2], 3), (F[1], 1)]
::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: list(b*c^3*a)
[(F[0], 1), (F[1], 1), (F[2], 3)]
"""
return ((self.parent().gen(index), exp) for (index,exp) in self._sorted_items())
def _richcmp_(self, other, op):
r"""
Comparisons
TESTS::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: a == a
True
sage: a*e == a*e
True
sage: a*b*c^3*b*d == (a*b*c)*(c^2*b*d)
True
sage: a != b
True
sage: a*b != b*a
True
sage: a*b*c^3*b*d != (a*b*c)*(c^2*b*d)
False
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: a < b
True
sage: a*b < b*a
True
sage: a*b < a*a
False
sage: a^2*b < a*b*b
True
sage: b > a
True
sage: a*b > b*a
False
sage: a*b > a*a
True
sage: a*b <= b*a
True
sage: a*b <= b*a
True
sage: FA = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [FA.gen(i) for i in range(5)]
sage: a == a
True
sage: a*e == e*a
True
sage: a*b*c^3*b*d == a*d*(b^2*c^2)*c
True
sage: a != b
True
sage: a*b != a*a
True
sage: a*b*c^3*b*d != a*d*(b^2*c^2)*c
False
"""
if self._monomial == other._monomial:
# Equal
return rich_to_bool(op, 0)
if op == op_EQ or op == op_NE:
# Not equal
return rich_to_bool(op, 1)
return richcmp(self.to_word_list(), other.to_word_list(), op)
def support(self):
"""
Return a list of the objects indexing ``self`` with
non-zero exponents.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*a*c^3*b).support()
[0, 1, 2]
::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (a*c^3).support()
[0, 2]
"""
supp = set(key for key, exp in self._sorted_items() if exp != 0)
return sorted(supp)
def leading_support(self):
"""
Return the support of the leading generator of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*a*c^3*a).leading_support()
1
::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*c^3*a).leading_support()
0
"""
if not self:
return None
return self._sorted_items()[0][0]
def trailing_support(self):
"""
Return the support of the trailing generator of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*a*c^3*a).trailing_support()
0
::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*c^3*a).trailing_support()
2
"""
if not self:
return None
return self._sorted_items()[-1][0]
def to_word_list(self):
"""
Return ``self`` as a word represented as a list whose entries
are indices of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*a*c^3*a).to_word_list()
[1, 0, 2, 2, 2, 0]
::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (b*c^3*a).to_word_list()
[0, 1, 2, 2, 2]
"""
return [k for k,e in self._sorted_items() for dummy in range(e)]
class IndexedFreeMonoidElement(IndexedMonoidElement):
"""
An element of an indexed free abelian monoid.
"""
def __init__(self, F, x):
"""
Create the element ``x`` of an indexed free abelian monoid ``F``.
EXAMPLES::
sage: F = FreeMonoid(index_set=tuple('abcde'))
sage: x = F( [(1, 2), (0, 1), (3, 2), (0, 1)] )
sage: y = F( ((1, 2), (0, 1), [3, 2], [0, 1]) )
sage: z = F( reversed([(0, 1), (3, 2), (0, 1), (1, 2)]) )
sage: x == y and y == z
True
sage: TestSuite(x).run()
"""
IndexedMonoidElement.__init__(self, F, tuple(map(tuple, x)))
def __hash__(self):
r"""
TESTS::
sage: F = FreeMonoid(index_set=tuple('abcde'))
sage: hash(F ([(1,2),(0,1)]) ) == hash(((1, 2), (0, 1)))
True
sage: hash(F ([(0,2),(1,1)]) ) == hash(((0, 2), (1, 1)))
True
"""
return hash(self._monomial)
def _sorted_items(self):
"""
Return the sorted items (i.e factors) of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: x = a*b^2*e*d
sage: x._sorted_items()
((0, 1), (1, 2), (4, 1), (3, 1))
sage: F.print_options(sorting_reverse=True)
sage: x._sorted_items()
((0, 1), (1, 2), (4, 1), (3, 1))
sage: F.print_options(sorting_reverse=False) # reset to original state
.. SEEALSO::
:meth:`_repr_`, :meth:`_latex_`, :meth:`print_options`
"""
return self._monomial
def _mul_(self, other):
"""
Multiply ``self`` by ``other``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: a*b^2*e*d
F[0]*F[1]^2*F[4]*F[3]
sage: (a*b^2*d^2) * (d^4*b*e)
F[0]*F[1]^2*F[3]^6*F[1]*F[4]
"""
if not self._monomial:
return other
if not other._monomial:
return self
ret = list(self._monomial)
rhs = list(other._monomial)
if ret[-1][0] == rhs[0][0]:
rhs[0] = (rhs[0][0], rhs[0][1] + ret.pop()[1])
ret += rhs
return self.__class__(self.parent(), tuple(ret))
def __len__(self):
"""
Return the length of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: elt = a*c^3*b^2*a
sage: elt.length()
7
sage: len(elt)
7
"""
return sum(exp for gen,exp in self._monomial)
length = __len__
class IndexedFreeAbelianMonoidElement(IndexedMonoidElement):
"""
An element of an indexed free abelian monoid.
"""
def __init__(self, F, x):
"""
Create the element ``x`` of an indexed free abelian monoid ``F``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: x = F([(0, 1), (2, 2), (-1, 2)])
sage: y = F({0:1, 2:2, -1:2})
sage: z = F(reversed([(0, 1), (2, 2), (-1, 2)]))
sage: x == y and y == z
True
sage: TestSuite(x).run()
"""
IndexedMonoidElement.__init__(self, F, dict(x))
def _sorted_items(self):
"""
Return the sorted items (i.e factors) of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: x = a*b^2*e*d
sage: x._sorted_items()
[(0, 1), (1, 2), (3, 1), (4, 1)]
sage: F.print_options(sorting_reverse=True)
sage: x._sorted_items()
[(4, 1), (3, 1), (1, 2), (0, 1)]
sage: F.print_options(sorting_reverse=False) # reset to original state
.. SEEALSO::
:meth:`_repr_`, :meth:`_latex_`, :meth:`print_options`
"""
print_options = self.parent().print_options()
v = list(self._monomial.items())
try:
v.sort(key=print_options['sorting_key'],
reverse=print_options['sorting_reverse'])
except Exception: # Sorting the output is a plus, but if we can't, no big deal
pass
return v
def __hash__(self):
r"""
TESTS::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: H1 = hash( F([(0,1), (2,2)]) )
sage: H2 = hash( F([(2,1)]) )
sage: H1 == H2
False
"""
return hash(frozenset(self._monomial.items()))
def _mul_(self, other):
"""
Multiply ``self`` by ``other``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: a*b^2*e*d
F[0]*F[1]^2*F[3]*F[4]
"""
return self.__class__(self.parent(),
blas.add(self._monomial, other._monomial))
def __pow__(self, n):
"""
Raise ``self`` to the power of ``n``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: x = a*b^2*e*d; x
F[0]*F[1]^2*F[3]*F[4]
sage: x^3
F[0]^3*F[1]^6*F[3]^3*F[4]^3
sage: x^0
1
"""
if not isinstance(n, (int, Integer)):
raise TypeError("Argument n (= {}) must be an integer".format(n))
if n < 0:
raise ValueError("Argument n (= {}) must be positive".format(n))
if n == 1:
return self
if n == 0:
return self.parent().one()
return self.__class__(self.parent(), {k:v*n for k,v in self._monomial.items()})
def __floordiv__(self, elt):
"""
Cancel the element ``elt`` out of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: elt = a*b*c^3*d^2; elt
F[0]*F[1]*F[2]^3*F[3]^2
sage: elt // a
F[1]*F[2]^3*F[3]^2
sage: elt // c
F[0]*F[1]*F[2]^2*F[3]^2
sage: elt // (a*b*d^2)
F[2]^3
sage: elt // a^4
Traceback (most recent call last):
...
ValueError: invalid cancellation
sage: elt // e^4
Traceback (most recent call last):
...
ValueError: invalid cancellation
"""
d = copy(self._monomial)
for k, v in elt._monomial.items():
if k not in d:
raise ValueError("invalid cancellation")
diff = d[k] - v
if diff < 0:
raise ValueError("invalid cancellation")
elif diff == 0:
del d[k]
else:
d[k] = diff
return self.__class__(self.parent(), d)
def __len__(self):
"""
Return the length of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: elt = a*c^3*b^2*a
sage: elt.length()
7
sage: len(elt)
7
"""
m = self._monomial
return sum(m[gen] for gen in m)
length = __len__
def dict(self):
"""
Return ``self`` as a dictionary.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: a,b,c,d,e = [F.gen(i) for i in range(5)]
sage: (a*c^3).dict()
{0: 1, 2: 3}
"""
return copy(self._monomial)
class IndexedMonoid(Parent, IndexedGenerators, UniqueRepresentation):
"""
Base class for monoids with an indexed set of generators.
INPUT:
- ``indices`` -- the indices for the generators
For the optional arguments that control the printing, see
:class:`~sage.structure.indexed_generators.IndexedGenerators`.
"""
@staticmethod
def __classcall__(cls, indices, prefix=None, names=None, **kwds):
"""
TESTS::
sage: F = FreeAbelianMonoid(index_set=['a','b','c'])
sage: G = FreeAbelianMonoid(index_set=('a','b','c'))
sage: H = FreeAbelianMonoid(index_set=tuple('abc'))
sage: F is G and F is H
True
sage: F = FreeAbelianMonoid(index_set=['a','b','c'], latex_bracket=['LEFT', 'RIGHT'])
sage: F.print_options()['latex_bracket']
('LEFT', 'RIGHT')
sage: F is G
False
sage: Groups.Commutative.free()
Traceback (most recent call last):
...
ValueError: either the indices or names must be given
"""
names, indices, prefix = parse_indices_names(names, indices, prefix, kwds)
if prefix is None:
prefix = "F"
# bracket or latex_bracket might be lists, so convert
# them to tuples so that they're hashable.
bracket = kwds.get('bracket', None)
if isinstance(bracket, list):
kwds['bracket'] = tuple(bracket)
latex_bracket = kwds.get('latex_bracket', None)
if isinstance(latex_bracket, list):
kwds['latex_bracket'] = tuple(latex_bracket)
return super().__classcall__(cls, indices, prefix,
names=names, **kwds)
def __init__(self, indices, prefix, category=None, names=None, **kwds):
"""
Initialize ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: TestSuite(F).run()
sage: F = FreeMonoid(index_set=tuple('abcde'))
sage: TestSuite(F).run()
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: TestSuite(F).run()
sage: F = FreeAbelianMonoid(index_set=tuple('abcde'))
sage: TestSuite(F).run()
"""
self._indices = indices
category = Monoids().or_subcategory(category)
if indices.cardinality() == 0:
category = category.Finite()
else:
category = category.Infinite()
if indices in Sets().Finite():
category = category.FinitelyGeneratedAsMagma()
Parent.__init__(self, names=names, category=category)
# ignore the optional 'key' since it only affects CachedRepresentation
kwds.pop('key', None)
IndexedGenerators.__init__(self, indices, prefix, **kwds)
def _first_ngens(self, n):
"""
Used by the preparser for ``F.<x> = ...``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: F._first_ngens(3)
(F[0], F[1], F[-1])
"""
it = iter(self._indices)
return tuple(self.gen(next(it)) for i in range(n))
def _element_constructor_(self, x=None):
"""
Create an element of this abelian monoid from ``x``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F(F.gen(2))
F[2]
sage: F([[1, 3], [-2, 12]])
F[-2]^12*F[1]^3
sage: F(-5)
Traceback (most recent call last):
...
TypeError: unable to convert -5, use gen() instead
"""
if x is None:
return self.one()
if x in self._indices:
raise TypeError("unable to convert {!r}, use gen() instead".format(x))
return self.element_class(self, x)
def _an_element_(self):
"""
Return an element of ``self``.
EXAMPLES::
sage: G = FreeAbelianMonoid(index_set=ZZ)
sage: G.an_element()
F[-1]^3*F[0]*F[1]^3
sage: G = FreeMonoid(index_set=tuple('ab'))
sage: G.an_element()
F['a']^2*F['b']^2
"""
x = self.one()
I = self._indices
try:
x *= self.gen(I.an_element())
except Exception:
pass
try:
g = iter(self._indices)
for c in range(1,4):
x *= self.gen(next(g)) ** c
except Exception:
pass
return x
def cardinality(self):
r"""
Return the cardinality of ``self``, which is `\infty` unless this is
the trivial monoid.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: F.cardinality()
+Infinity
sage: F = FreeMonoid(index_set=())
sage: F.cardinality()
1
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F.cardinality()
+Infinity
sage: F = FreeAbelianMonoid(index_set=())
sage: F.cardinality()
1
"""
if self._indices.cardinality() == 0:
return ZZ.one()
return infinity
@cached_method
def monoid_generators(self):
"""
Return the monoid generators of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F.monoid_generators()
Lazy family (Generator map from Integer Ring to
Free abelian monoid indexed by Integer Ring(i))_{i in Integer Ring}
sage: F = FreeAbelianMonoid(index_set=tuple('abcde'))
sage: sorted(F.monoid_generators())
[F['a'], F['b'], F['c'], F['d'], F['e']]
"""
if self._indices.cardinality() == infinity:
gen = PoorManMap(self.gen, domain=self._indices, codomain=self, name="Generator map")
return Family(self._indices, gen)
return Family(self._indices, self.gen)
gens = monoid_generators
class IndexedFreeMonoid(IndexedMonoid):
"""
Free monoid with an indexed set of generators.
INPUT:
- ``indices`` -- the indices for the generators
For the optional arguments that control the printing, see
:class:`~sage.structure.indexed_generators.IndexedGenerators`.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: F.gen(15)^3 * F.gen(2) * F.gen(15)
F[15]^3*F[2]*F[15]
sage: F.gen(1)
F[1]
Now we examine some of the printing options::
sage: F = FreeMonoid(index_set=ZZ, prefix='X', bracket=['|','>'])
sage: F.gen(2) * F.gen(12)
X|2>*X|12>
"""
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: FreeMonoid(index_set=ZZ)
Free monoid indexed by Integer Ring
"""
return "Free monoid indexed by {}".format(self._indices)
Element = IndexedFreeMonoidElement
@cached_method
def one(self):
"""
Return the identity element of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: F.one()
1
"""
return self.element_class(self, ())
def gen(self, x):
"""
The generator indexed by ``x`` of ``self``.
EXAMPLES::
sage: F = FreeMonoid(index_set=ZZ)
sage: F.gen(0)
F[0]
sage: F.gen(2)
F[2]
TESTS::
sage: F = FreeMonoid(index_set=[1,2])
sage: F.gen(2)
F[2]
sage: F.gen(0)
Traceback (most recent call last):
...
IndexError: 0 is not in the index set
"""
if x not in self._indices:
raise IndexError("{} is not in the index set".format(x))
try:
return self.element_class(self, ((self._indices(x),1),))
except (TypeError, NotImplementedError): # Backup (e.g., if it is a string)
return self.element_class(self, ((x,1),))
class IndexedFreeAbelianMonoid(IndexedMonoid):
"""
Free abelian monoid with an indexed set of generators.
INPUT:
- ``indices`` -- the indices for the generators
For the optional arguments that control the printing, see
:class:`~sage.structure.indexed_generators.IndexedGenerators`.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F.gen(15)^3 * F.gen(2) * F.gen(15)
F[2]*F[15]^4
sage: F.gen(1)
F[1]
Now we examine some of the printing options::
sage: F = FreeAbelianMonoid(index_set=Partitions(), prefix='A', bracket=False, scalar_mult='%')
sage: F.gen([3,1,1]) * F.gen([2,2])
A[2, 2]%A[3, 1, 1]
"""
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: FreeAbelianMonoid(index_set=ZZ)
Free abelian monoid indexed by Integer Ring
"""
return "Free abelian monoid indexed by {}".format(self._indices)
def _element_constructor_(self, x=None):
"""
Create an element of ``self`` from ``x``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F(F.gen(2))
F[2]
sage: F([[1, 3], [-2, 12]])
F[-2]^12*F[1]^3
sage: F({1:3, -2: 12})
F[-2]^12*F[1]^3
TESTS::
sage: F([(1, 3), (1, 2)])
F[1]^5
sage: F([(42, 0)])
1
sage: F({42: 0})
1
"""
if isinstance(x, (list, tuple)):
d = dict()
for k, v in x:
if k in d:
d[k] += v
else:
d[k] = v
x = d
if isinstance(x, dict):
x = {k: v for k, v in x.items() if v != 0}
return IndexedMonoid._element_constructor_(self, x)
Element = IndexedFreeAbelianMonoidElement
@cached_method
def one(self):
"""
Return the identity element of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F.one()
1
"""
return self.element_class(self, {})
def gen(self, x):
"""
The generator indexed by ``x`` of ``self``.
EXAMPLES::
sage: F = FreeAbelianMonoid(index_set=ZZ)
sage: F.gen(0)
F[0]
sage: F.gen(2)
F[2]
TESTS::
sage: F = FreeAbelianMonoid(index_set=[1,2])
sage: F.gen(2)
F[2]
sage: F.gen(0)
Traceback (most recent call last):
...
IndexError: 0 is not in the index set
"""
if x not in self._indices:
raise IndexError("{} is not in the index set".format(x))
try:
return self.element_class(self, {self._indices(x): 1})
except (TypeError, NotImplementedError): # Backup (e.g., if it is a string)
return self.element_class(self, {x: 1}) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/monoids/indexed_free_monoid.py | 0.874573 | 0.476701 | indexed_free_monoid.py | pypi |
from sage.rings.integer import Integer
from sage.structure.element import MonoidElement
from sage.structure.richcmp import richcmp, richcmp_not_equal
def is_FreeMonoidElement(x):
return isinstance(x, FreeMonoidElement)
class FreeMonoidElement(MonoidElement):
"""
Element of a free monoid.
EXAMPLES::
sage: a = FreeMonoid(5, 'a').gens()
sage: x = a[0]*a[1]*a[4]**3
sage: x**3
a0*a1*a4^3*a0*a1*a4^3*a0*a1*a4^3
sage: x**0
1
sage: x**(-1)
Traceback (most recent call last):
...
NotImplementedError
"""
def __init__(self, F, x, check=True):
"""
Create the element `x` of the FreeMonoid `F`.
This should typically be called by a FreeMonoid.
"""
MonoidElement.__init__(self, F)
if isinstance(x, (int, Integer)):
if x == 1:
self._element_list = []
else:
raise TypeError("argument x (= %s) is of the wrong type" % x)
elif isinstance(x, list):
if check:
x2 = []
for v in x:
if not (isinstance(v, tuple) and len(v) == 2):
raise TypeError("x (= %s) must be a list of 2-tuples or 1" % x)
if not (isinstance(v[0], (int, Integer)) and
isinstance(v[1], (int, Integer))):
raise TypeError("x (= %s) must be a list of 2-tuples of integers or 1" % x)
if len(x2) > 0 and v[0] == x2[len(x2)-1][0]:
x2[len(x2)-1] = (v[0], v[1]+x2[len(x2)-1][1])
else:
x2.append(v)
self._element_list = x2
else:
self._element_list = list(x) # make copy, so user can't accidentally change monoid.
else:
# TODO: should have some other checks here...
raise TypeError("argument x (= %s) is of the wrong type" % x)
def __hash__(self):
r"""
TESTS::
sage: R.<x,y> = FreeMonoid(2)
sage: hash(x) == hash(((0, 1),))
True
sage: hash(y) == hash(((1, 1),))
True
sage: hash(x*y) == hash(((0, 1), (1, 1)))
True
"""
return hash(tuple(self._element_list))
def __iter__(self):
"""
Return an iterator which yields tuples of variable and exponent.
EXAMPLES::
sage: a = FreeMonoid(5, 'a').gens()
sage: list(a[0]*a[1]*a[4]**3*a[0])
[(a0, 1), (a1, 1), (a4, 3), (a0, 1)]
"""
gens = self.parent().gens()
return ((gens[index], exponent)
for (index, exponent) in self._element_list)
def _repr_(self):
s = ""
v = self._element_list
x = self.parent().variable_names()
for i in range(len(v)):
if len(s) > 0:
s += "*"
g = x[int(v[i][0])]
e = v[i][1]
if e == 1:
s += "%s"%g
else:
s += "%s^%s"%(g,e)
if len(s) == 0:
s = "1"
return s
def _latex_(self):
r"""
Return latex representation of self.
EXAMPLES::
sage: F = FreeMonoid(3, 'a')
sage: z = F([(0,5),(1,2),(0,10),(0,2),(1,2)])
sage: z._latex_()
'a_{0}^{5}a_{1}^{2}a_{0}^{12}a_{1}^{2}'
sage: F.<alpha,beta,gamma> = FreeMonoid(3)
sage: latex(alpha*beta*gamma)
\alpha \beta \gamma
Check that :trac:`14509` is fixed::
sage: K.< alpha,b > = FreeAlgebra(SR)
sage: latex(alpha*b)
\alpha b
sage: latex(b*alpha)
b \alpha
sage: "%s" % latex(alpha*b)
'\\alpha b'
"""
s = ""
v = self._element_list
x = self.parent().latex_variable_names()
for i in range(len(v)):
g = x[int(v[i][0])]
e = v[i][1]
if e == 1:
s += "%s " % (g,)
else:
s += "%s^{%s}" % (g, e)
s = s.rstrip(" ") # strip the trailing whitespace caused by adding a space after each element name
if len(s) == 0:
s = "1"
return s
def __call__(self, *x, **kwds):
"""
EXAMPLES::
sage: M.<x,y,z>=FreeMonoid(3)
sage: (x*y).subs(x=1,y=2,z=14)
2
sage: (x*y).subs({x:z,y:z})
z^2
sage: M1=MatrixSpace(ZZ,1,2)
sage: M2=MatrixSpace(ZZ,2,1)
sage: (x*y).subs({x:M1([1,2]),y:M2([3,4])})
[11]
sage: M.<x,y> = FreeMonoid(2)
sage: (x*y).substitute(x=1)
y
sage: M.<a> = FreeMonoid(1)
sage: a.substitute(a=5)
5
AUTHORS:
- Joel B. Mohler (2007-10-27)
"""
if kwds and x:
raise ValueError("must not specify both a keyword and positional argument")
P = self.parent()
if kwds:
x = self.gens()
gens_dict = {name: i for i, name in enumerate(P.variable_names())}
for key, value in kwds.items():
if key in gens_dict:
x[gens_dict[key]] = value
if isinstance(x[0], tuple):
x = x[0]
if len(x) != self.parent().ngens():
raise ValueError("must specify as many values as generators in parent")
# I don't start with 0, because I don't want to preclude evaluation with
#arbitrary objects (e.g. matrices) because of funny coercion.
one = P.one()
result = None
for var_index, exponent in self._element_list:
# Take further pains to ensure that non-square matrices are not exponentiated.
replacement = x[var_index]
if exponent > 1:
c = replacement ** exponent
elif exponent == 1:
c = replacement
else:
c = one
if result is None:
result = c
else:
result *= c
if result is None:
return one
return result
def _mul_(self, y):
"""
Multiply two elements ``self`` and ``y`` of the
free monoid.
EXAMPLES::
sage: a = FreeMonoid(5, 'a').gens()
sage: x = a[0] * a[1] * a[4]**3
sage: y = a[4] * a[0] * a[1]
sage: x*y
a0*a1*a4^4*a0*a1
"""
M = self.parent()
z = M(1)
x_elt = self._element_list
y_elt = y._element_list
if not x_elt:
z._element_list = y_elt
elif not y_elt:
z._element_list = x_elt
else:
k = len(x_elt)-1
if x_elt[k][0] != y_elt[0][0]:
z._element_list = x_elt + y_elt
else:
m = (y_elt[0][0], x_elt[k][1]+y_elt[0][1])
z._element_list = x_elt[:k] + [ m ] + y_elt[1:]
return z
def __invert__(self):
"""
EXAMPLES::
sage: a = FreeMonoid(5, 'a').gens()
sage: x = a[0]*a[1]*a[4]**3
sage: x**(-1)
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def __len__(self):
"""
Return the degree of the monoid element ``self``, where each
generator of the free monoid is given degree `1`.
For example, the length of the identity is `0`, and the
length of `x_0^2x_1` is `3`.
EXAMPLES::
sage: F = FreeMonoid(3, 'a')
sage: z = F(1)
sage: len(z)
0
sage: a = F.gens()
sage: len(a[0]**2 * a[1])
3
"""
s = 0
for x in self._element_list:
s += x[1]
return s
def _richcmp_(self, other, op):
"""
Compare two free monoid elements with the same parents.
The ordering is first by increasing length, then lexicographically
on the underlying word.
EXAMPLES::
sage: S = FreeMonoid(3, 'a')
sage: (x,y,z) = S.gens()
sage: x * y < y * x
True
sage: a = FreeMonoid(5, 'a').gens()
sage: x = a[0]*a[1]*a[4]**3
sage: x < x
False
sage: x == x
True
sage: x >= x*x
False
"""
m = sum(i for x, i in self._element_list)
n = sum(i for x, i in other._element_list)
if m != n:
return richcmp_not_equal(m, n, op)
v = tuple([x for x, i in self._element_list for j in range(i)])
w = tuple([x for x, i in other._element_list for j in range(i)])
return richcmp(v, w, op)
def _acted_upon_(self, x, self_on_left):
"""
Currently, returns the action of the integer 1 on this
element.
EXAMPLES::
sage: M.<x,y,z>=FreeMonoid(3)
sage: 1*x
x
"""
if x == 1:
return self
return None
def to_word(self, alph=None):
"""
Return ``self`` as a word.
INPUT:
- ``alph`` -- (optional) the alphabet which the result should
be specified in
EXAMPLES::
sage: M.<x,y,z> = FreeMonoid(3)
sage: a = x * x * y * x
sage: w = a.to_word(); w
word: xxyx
sage: w.to_monoid_element() == a
True
.. SEEALSO::
:meth:`to_list`
"""
from sage.combinat.words.finite_word import Words
gens = self.parent().gens()
if alph is None:
alph = gens
alph = [str(_) for _ in alph]
W = Words(alph)
return W(sum([ [alph[gens.index(i[0])]] * i[1] for i in list(self) ], []))
def to_list(self, indices=False):
r"""
Return ``self`` as a list of generators.
If ``self`` equals `x_{i_1} x_{i_2} \cdots x_{i_n}`, with
`x_{i_1}, x_{i_2}, \ldots, x_{i_n}` being some of the
generators of the free monoid, then this method returns
the list `[x_{i_1}, x_{i_2}, \ldots, x_{i_n}]`.
If the optional argument ``indices`` is set to ``True``,
then the list `[i_1, i_2, \ldots, i_n]` is returned instead.
EXAMPLES::
sage: M.<x,y,z> = FreeMonoid(3)
sage: a = x * x * y * x
sage: w = a.to_list(); w
[x, x, y, x]
sage: M.prod(w) == a
True
sage: w = a.to_list(indices=True); w
[0, 0, 1, 0]
sage: a = M.one()
sage: a.to_list()
[]
.. SEEALSO::
:meth:`to_word`
"""
if not indices:
return sum(([i[0]] * i[1] for i in list(self)), [])
gens = self.parent().gens()
return sum(([gens.index(i[0])] * i[1] for i in list(self)), []) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/monoids/free_monoid_element.py | 0.649245 | 0.460228 | free_monoid_element.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.categories.category_singleton import Category_singleton
from sage.categories.category_with_axiom import CategoryWithAxiom
from sage.categories.sets_cat import Sets
from sage.categories.homsets import HomsetsCategory
from sage.rings.infinity import Infinity
from sage.rings.integer import Integer
class SimplicialSets(Category_singleton):
r"""
The category of simplicial sets.
A simplicial set `X` is a collection of sets `X_i`, indexed by
the non-negative integers, together with maps
.. math::
d_i: X_n \to X_{n-1}, \quad 0 \leq i \leq n \quad \text{(face maps)} \\
s_j: X_n \to X_{n+1}, \quad 0 \leq j \leq n \quad \text{(degeneracy maps)}
satisfying the *simplicial identities*:
.. math::
d_i d_j &= d_{j-1} d_i \quad \text{if } i<j \\
d_i s_j &= s_{j-1} d_i \quad \text{if } i<j \\
d_j s_j &= 1 = d_{j+1} s_j \\
d_i s_j &= s_{j} d_{i-1} \quad \text{if } i>j+1 \\
s_i s_j &= s_{j+1} s_{i} \quad \text{if } i \leq j
Morphisms are sequences of maps `f_i : X_i \to Y_i` which commute
with the face and degeneracy maps.
EXAMPLES::
sage: from sage.categories.simplicial_sets import SimplicialSets
sage: C = SimplicialSets(); C
Category of simplicial sets
TESTS::
sage: TestSuite(C).run()
"""
@cached_method
def super_categories(self):
"""
EXAMPLES::
sage: from sage.categories.simplicial_sets import SimplicialSets
sage: SimplicialSets().super_categories()
[Category of sets]
"""
return [Sets()]
class ParentMethods:
def is_finite(self):
"""
Return ``True`` if this simplicial set is finite, i.e., has a
finite number of nondegenerate simplices.
EXAMPLES::
sage: simplicial_sets.Torus().is_finite()
True
sage: C5 = groups.misc.MultiplicativeAbelian([5])
sage: simplicial_sets.ClassifyingSpace(C5).is_finite()
False
"""
return SimplicialSets.Finite() in self.categories()
def is_pointed(self):
"""
Return ``True`` if this simplicial set is pointed, i.e., has a
base point.
EXAMPLES::
sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet
sage: v = AbstractSimplex(0)
sage: w = AbstractSimplex(0)
sage: e = AbstractSimplex(1)
sage: X = SimplicialSet({e: (v, w)})
sage: Y = SimplicialSet({e: (v, w)}, base_point=w)
sage: X.is_pointed()
False
sage: Y.is_pointed()
True
"""
return SimplicialSets.Pointed() in self.categories()
def set_base_point(self, point):
"""
Return a copy of this simplicial set in which the base point is
set to ``point``.
INPUT:
- ``point`` -- a 0-simplex in this simplicial set
EXAMPLES::
sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet
sage: v = AbstractSimplex(0, name='v_0')
sage: w = AbstractSimplex(0, name='w_0')
sage: e = AbstractSimplex(1)
sage: X = SimplicialSet({e: (v, w)})
sage: Y = SimplicialSet({e: (v, w)}, base_point=w)
sage: Y.base_point()
w_0
sage: X_star = X.set_base_point(w)
sage: X_star.base_point()
w_0
sage: Y_star = Y.set_base_point(v)
sage: Y_star.base_point()
v_0
TESTS::
sage: X.set_base_point(e)
Traceback (most recent call last):
...
ValueError: the "point" is not a zero-simplex
sage: pt = AbstractSimplex(0)
sage: X.set_base_point(pt)
Traceback (most recent call last):
...
ValueError: the point is not a simplex in this simplicial set
"""
from sage.topology.simplicial_set import SimplicialSet
if point.dimension() != 0:
raise ValueError('the "point" is not a zero-simplex')
if point not in self._simplices:
raise ValueError('the point is not a simplex in this '
'simplicial set')
return SimplicialSet(self.face_data(), base_point=point)
class Homsets(HomsetsCategory):
class Endset(CategoryWithAxiom):
class ParentMethods:
def one(self):
r"""
Return the identity morphism in `\operatorname{Hom}(S, S)`.
EXAMPLES::
sage: T = simplicial_sets.Torus()
sage: Hom(T, T).identity()
Simplicial set endomorphism of Torus
Defn: Identity map
"""
from sage.topology.simplicial_set_morphism import SimplicialSetMorphism
return SimplicialSetMorphism(domain=self.domain(),
codomain=self.codomain(),
identity=True)
class Finite(CategoryWithAxiom):
"""
Category of finite simplicial sets.
The objects are simplicial sets with finitely many
non-degenerate simplices.
"""
pass
class SubcategoryMethods:
def Pointed(self):
"""
A simplicial set is *pointed* if it has a distinguished base
point.
EXAMPLES::
sage: from sage.categories.simplicial_sets import SimplicialSets
sage: SimplicialSets().Pointed().Finite()
Category of finite pointed simplicial sets
sage: SimplicialSets().Finite().Pointed()
Category of finite pointed simplicial sets
"""
return self._with_axiom("Pointed")
class Pointed(CategoryWithAxiom):
class ParentMethods:
def base_point(self):
"""
Return this simplicial set's base point
EXAMPLES::
sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet
sage: v = AbstractSimplex(0, name='*')
sage: e = AbstractSimplex(1)
sage: S1 = SimplicialSet({e: (v, v)}, base_point=v)
sage: S1.is_pointed()
True
sage: S1.base_point()
*
"""
return self._basepoint
def base_point_map(self, domain=None):
"""
Return a map from a one-point space to this one, with image the
base point.
This raises an error if this simplicial set does not have a
base point.
INPUT:
- ``domain`` -- optional, default ``None``. Use
this to specify a particular one-point space as
the domain. The default behavior is to use the
:func:`sage.topology.simplicial_set.Point`
function to use a standard one-point space.
EXAMPLES::
sage: T = simplicial_sets.Torus()
sage: f = T.base_point_map(); f
Simplicial set morphism:
From: Point
To: Torus
Defn: Constant map at (v_0, v_0)
sage: S3 = simplicial_sets.Sphere(3)
sage: g = S3.base_point_map()
sage: f.domain() == g.domain()
True
sage: RP3 = simplicial_sets.RealProjectiveSpace(3)
sage: temp = simplicial_sets.Simplex(0)
sage: pt = temp.set_base_point(temp.n_cells(0)[0])
sage: h = RP3.base_point_map(domain=pt)
sage: f.domain() == h.domain()
False
sage: C5 = groups.misc.MultiplicativeAbelian([5])
sage: BC5 = simplicial_sets.ClassifyingSpace(C5)
sage: BC5.base_point_map()
Simplicial set morphism:
From: Point
To: Classifying space of Multiplicative Abelian group isomorphic to C5
Defn: Constant map at 1
"""
from sage.topology.simplicial_set_examples import Point
if domain is None:
domain = Point()
else:
if len(domain._simplices) > 1:
raise ValueError('domain has more than one nondegenerate simplex')
target = self.base_point()
return domain.Hom(self).constant_map(point=target)
def fundamental_group(self, simplify=True):
r"""
Return the fundamental group of this pointed simplicial set.
INPUT:
- ``simplify`` (bool, optional ``True``) -- if
``False``, then return a presentation of the group
in terms of generators and relations. If ``True``,
the default, simplify as much as GAP is able to.
Algorithm: we compute the edge-path group -- see
Section 19 of [Kan1958]_ and
:wikipedia:`Fundamental_group`. Choose a spanning tree
for the connected component of the 1-skeleton
containing the base point, and then the group's
generators are given by the non-degenerate
edges. There are two types of relations: `e=1` if `e`
is in the spanning tree, and for every 2-simplex, if
its faces are `e_0`, `e_1`, and `e_2`, then we impose
the relation `e_0 e_1^{-1} e_2 = 1`, where we first
set `e_i=1` if `e_i` is degenerate.
EXAMPLES::
sage: S1 = simplicial_sets.Sphere(1)
sage: eight = S1.wedge(S1)
sage: eight.fundamental_group() # free group on 2 generators
Finitely presented group < e0, e1 | >
The fundamental group of a disjoint union of course depends on
the choice of base point::
sage: T = simplicial_sets.Torus()
sage: K = simplicial_sets.KleinBottle()
sage: X = T.disjoint_union(K)
sage: X_0 = X.set_base_point(X.n_cells(0)[0])
sage: X_0.fundamental_group().is_abelian()
True
sage: X_1 = X.set_base_point(X.n_cells(0)[1])
sage: X_1.fundamental_group().is_abelian()
False
sage: RP3 = simplicial_sets.RealProjectiveSpace(3)
sage: RP3.fundamental_group()
Finitely presented group < e | e^2 >
Compute the fundamental group of some classifying spaces::
sage: C5 = groups.misc.MultiplicativeAbelian([5])
sage: BC5 = C5.nerve()
sage: BC5.fundamental_group()
Finitely presented group < e0 | e0^5 >
sage: Sigma3 = groups.permutation.Symmetric(3)
sage: BSigma3 = Sigma3.nerve()
sage: pi = BSigma3.fundamental_group(); pi
Finitely presented group < e0, e1 | e0^2, e1^3, (e0*e1^-1)^2 >
sage: pi.order()
6
sage: pi.is_abelian()
False
The sphere has a trivial fundamental group::
sage: S2 = simplicial_sets.Sphere(2)
sage: S2.fundamental_group()
Finitely presented group < | >
"""
# Import this here to prevent importing libgap upon startup.
from sage.groups.free_group import FreeGroup
skel = self.n_skeleton(2)
graph = skel.graph()
if not skel.is_connected():
graph = graph.subgraph(skel.base_point())
edges = [e[2] for e in graph.edges(sort=True)]
spanning_tree = [e[2] for e in graph.min_spanning_tree()]
gens = [e for e in edges if e not in spanning_tree]
if not gens:
return FreeGroup([]).quotient([])
gens_dict = dict(zip(gens, range(len(gens))))
FG = FreeGroup(len(gens), 'e')
rels = []
for f in skel.n_cells(2):
z = dict()
for i, sigma in enumerate(skel.faces(f)):
if sigma in spanning_tree:
z[i] = FG.one()
elif sigma.is_degenerate():
z[i] = FG.one()
elif sigma in edges:
z[i] = FG.gen(gens_dict[sigma])
else:
# sigma is not in the correct connected component.
z[i] = FG.one()
rels.append(z[0]*z[1].inverse()*z[2])
if simplify:
return FG.quotient(rels).simplified()
else:
return FG.quotient(rels)
def is_simply_connected(self):
"""
Return ``True`` if this pointed simplicial set is simply connected.
.. WARNING::
Determining simple connectivity is not always
possible, because it requires determining when a
group, as given by generators and relations, is
trivial. So this conceivably may give a false
negative in some cases.
EXAMPLES::
sage: T = simplicial_sets.Torus()
sage: T.is_simply_connected()
False
sage: T.suspension().is_simply_connected()
True
sage: simplicial_sets.KleinBottle().is_simply_connected()
False
sage: S2 = simplicial_sets.Sphere(2)
sage: S3 = simplicial_sets.Sphere(3)
sage: (S2.wedge(S3)).is_simply_connected()
True
sage: X = S2.disjoint_union(S3)
sage: X = X.set_base_point(X.n_cells(0)[0])
sage: X.is_simply_connected()
False
sage: C3 = groups.misc.MultiplicativeAbelian([3])
sage: BC3 = simplicial_sets.ClassifyingSpace(C3)
sage: BC3.is_simply_connected()
False
"""
if not self.is_connected():
return False
try:
if not self.is_pointed():
space = self.set_base_point(self.n_cells(0)[0])
else:
space = self
return bool(space.fundamental_group().IsTrivial())
except AttributeError:
try:
return space.fundamental_group().order() == 1
except (NotImplementedError, RuntimeError):
# I don't know of any simplicial sets for which the
# code reaches this point, but there are certainly
# groups for which these errors are raised. 'IsTrivial'
# works for all of the examples I've seen, though.
raise ValueError('unable to determine if the fundamental '
'group is trivial')
def connectivity(self, max_dim=None):
"""
Return the connectivity of this pointed simplicial set.
INPUT:
- ``max_dim`` -- specify a maximum dimension through
which to check. This is required if this simplicial
set is simply connected and not finite.
The dimension of the first nonzero homotopy group. If
simply connected, this is the same as the dimension of
the first nonzero homology group.
.. WARNING::
See the warning for the :meth:`is_simply_connected` method.
The connectivity of a contractible space is ``+Infinity``.
EXAMPLES::
sage: simplicial_sets.Sphere(3).connectivity()
2
sage: simplicial_sets.Sphere(0).connectivity()
-1
sage: K = simplicial_sets.Simplex(4)
sage: K = K.set_base_point(K.n_cells(0)[0])
sage: K.connectivity()
+Infinity
sage: X = simplicial_sets.Torus().suspension(2)
sage: X.connectivity()
2
sage: C2 = groups.misc.MultiplicativeAbelian([2])
sage: BC2 = simplicial_sets.ClassifyingSpace(C2)
sage: BC2.connectivity()
0
"""
if not self.is_connected():
return Integer(-1)
if not self.is_simply_connected():
return Integer(0)
if max_dim is None:
if self.is_finite():
max_dim = self.dimension()
else:
# Note: at the moment, this will never be reached,
# because our only examples (so far) of infinite
# simplicial sets are not simply connected.
raise ValueError('this simplicial set may be infinite, '
'so specify a maximum dimension through '
'which to check')
H = self.homology(range(2, max_dim + 1))
for i in range(2, max_dim + 1):
if i in H and H[i].order() != 1:
return i-1
return Infinity
class Finite(CategoryWithAxiom):
class ParentMethods():
def unset_base_point(self):
"""
Return a copy of this simplicial set in which the base point has
been forgotten.
EXAMPLES::
sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet
sage: v = AbstractSimplex(0, name='v_0')
sage: w = AbstractSimplex(0, name='w_0')
sage: e = AbstractSimplex(1)
sage: Y = SimplicialSet({e: (v, w)}, base_point=w)
sage: Y.is_pointed()
True
sage: Y.base_point()
w_0
sage: Z = Y.unset_base_point()
sage: Z.is_pointed()
False
"""
from sage.topology.simplicial_set import SimplicialSet
return SimplicialSet(self.face_data())
def fat_wedge(self, n):
"""
Return the `n`-th fat wedge of this pointed simplicial set.
This is the subcomplex of the `n`-fold product `X^n`
consisting of those points in which at least one
factor is the base point. Thus when `n=2`, this is the
wedge of the simplicial set with itself, but when `n`
is larger, the fat wedge is larger than the `n`-fold
wedge.
EXAMPLES::
sage: S1 = simplicial_sets.Sphere(1)
sage: S1.fat_wedge(0)
Point
sage: S1.fat_wedge(1)
S^1
sage: S1.fat_wedge(2).fundamental_group()
Finitely presented group < e0, e1 | >
sage: S1.fat_wedge(4).homology()
{0: 0, 1: Z x Z x Z x Z, 2: Z^6, 3: Z x Z x Z x Z}
"""
from sage.topology.simplicial_set_examples import Point
if n == 0:
return Point()
if n == 1:
return self
return self.product(*[self]*(n-1)).fat_wedge_as_subset()
def smash_product(self, *others):
"""
Return the smash product of this simplicial set with ``others``.
INPUT:
- ``others`` -- one or several simplicial sets
EXAMPLES::
sage: S1 = simplicial_sets.Sphere(1)
sage: RP2 = simplicial_sets.RealProjectiveSpace(2)
sage: X = S1.smash_product(RP2)
sage: X.homology(base_ring=GF(2))
{0: Vector space of dimension 0 over Finite Field of size 2,
1: Vector space of dimension 0 over Finite Field of size 2,
2: Vector space of dimension 1 over Finite Field of size 2,
3: Vector space of dimension 1 over Finite Field of size 2}
sage: T = S1.product(S1)
sage: X = T.smash_product(S1)
sage: X.homology(reduced=False)
{0: Z, 1: 0, 2: Z x Z, 3: Z}
"""
from sage.topology.simplicial_set_constructions import SmashProductOfSimplicialSets_finite
return SmashProductOfSimplicialSets_finite((self,) + others) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/simplicial_sets.py | 0.90287 | 0.627666 | simplicial_sets.py | pypi |
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring
from sage.categories.graded_modules import GradedModulesCategory
class LambdaBracketAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
"""
The category of Lambda bracket algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).WithBasis()
Category of Lie conformal algebras with basis over Algebraic Field
"""
class ElementMethods:
def index(self):
"""
The index of this basis element.
EXAMPLES::
sage: V = lie_conformal_algebras.NeveuSchwarz(QQ)
sage: V.inject_variables()
Defining L, G, C
sage: G.T(3).index()
('G', 3)
sage: v = V.an_element(); v
L + G + C
sage: v.index()
Traceback (most recent call last):
...
ValueError: index can only be computed for monomials, got L + G + C
"""
if self.is_zero():
return None
if not self.is_monomial():
raise ValueError("index can only be computed for "
"monomials, got {}".format(self))
return next(iter(self.monomial_coefficients()))
class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring):
"""
The category of finitely generated lambda bracket algebras with
basis.
EXAMPLES::
sage: C = LieConformalAlgebras(QQbar)
sage: C.WithBasis().FinitelyGenerated()
Category of finitely generated Lie conformal algebras with basis over Algebraic Field
sage: C.WithBasis().FinitelyGenerated() is C.FinitelyGenerated().WithBasis()
True
"""
class Graded(GradedModulesCategory):
"""
The category of H-graded finitely generated lambda bracket
algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded()
Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field
"""
class ParentMethods:
def degree_on_basis(self, m):
r"""
Return the degree of the basis element indexed by ``m``
in ``self``.
EXAMPLES::
sage: V = lie_conformal_algebras.Virasoro(QQ)
sage: V.degree_on_basis(('L',2))
4
"""
if m[0] in self._central_elements:
return 0
return self._weights[self._index_to_pos[m[0]]] + m[1] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/lambda_bracket_algebras_with_basis.py | 0.807043 | 0.406067 | lambda_bracket_algebras_with_basis.py | pypi |
r"""
Sage categories quickref
- ``sage.categories.primer?`` a primer on Elements, Parents, and Categories
- ``sage.categories.tutorial?`` a tutorial on Elements, Parents, and Categories
- ``Category?`` technical background on categories
- ``Sets()``, ``Semigroups()``, ``Algebras(QQ)`` some categories
- ``SemiGroups().example()??`` sample implementation of a semigroup
- ``Hom(A, B)``, ``End(A, Algebras())`` homomorphisms sets
- ``tensor``, ``cartesian_product`` functorial constructions
Module layout:
- :mod:`sage.categories.basic` the basic categories
- :mod:`sage.categories.all` all categories
- :mod:`sage.categories.semigroups` the ``Semigroups()`` category
- :mod:`sage.categories.examples.semigroups` the example of ``Semigroups()``
- :mod:`sage.categories.homset` morphisms, ...
- :mod:`sage.categories.map`
- :mod:`sage.categories.morphism`
- :mod:`sage.categories.functors`
- :mod:`sage.categories.cartesian_product` functorial constructions
- :mod:`sage.categories.tensor`
- :mod:`sage.categories.dual`
"""
# install the docstring of this module to the containing package
from sage.misc.namespace_package import install_doc
install_doc(__package__, __doc__)
from . import primer
from sage.misc.lazy_import import lazy_import
from .all__sagemath_objects import *
from .basic import *
from .chain_complexes import ChainComplexes, HomologyFunctor
from .simplicial_complexes import SimplicialComplexes
from .tensor import tensor
from .signed_tensor import tensor_signed
from .g_sets import GSets
from .pointed_sets import PointedSets
from .sets_with_grading import SetsWithGrading
from .groupoid import Groupoid
from .permutation_groups import PermutationGroups
# enumerated sets
from .finite_sets import FiniteSets
from .enumerated_sets import EnumeratedSets
from .finite_enumerated_sets import FiniteEnumeratedSets
from .infinite_enumerated_sets import InfiniteEnumeratedSets
# posets
from .posets import Posets
from .finite_posets import FinitePosets
from .lattice_posets import LatticePosets
from .finite_lattice_posets import FiniteLatticePosets
# finite groups/...
from .finite_semigroups import FiniteSemigroups
from .finite_monoids import FiniteMonoids
from .finite_groups import FiniteGroups
from .finite_permutation_groups import FinitePermutationGroups
# fields
from .number_fields import NumberFields
from .function_fields import FunctionFields
# modules
from .left_modules import LeftModules
from .right_modules import RightModules
from .bimodules import Bimodules
from .modules import Modules
RingModules = Modules
from .vector_spaces import VectorSpaces
# (hopf) algebra structures
from .algebras import Algebras
from .commutative_algebras import CommutativeAlgebras
from .coalgebras import Coalgebras
from .bialgebras import Bialgebras
from .hopf_algebras import HopfAlgebras
from .lie_algebras import LieAlgebras
# specific algebras
from .monoid_algebras import MonoidAlgebras
from .group_algebras import GroupAlgebras
from .matrix_algebras import MatrixAlgebras
# ideals
from .ring_ideals import RingIdeals
Ideals = RingIdeals
from .commutative_ring_ideals import CommutativeRingIdeals
from .algebra_modules import AlgebraModules
from .algebra_ideals import AlgebraIdeals
from .commutative_algebra_ideals import CommutativeAlgebraIdeals
# schemes and varieties
from .modular_abelian_varieties import ModularAbelianVarieties
from .schemes import Schemes
# * with basis
from .modules_with_basis import ModulesWithBasis
FreeModules = ModulesWithBasis
from .hecke_modules import HeckeModules
from .algebras_with_basis import AlgebrasWithBasis
from .coalgebras_with_basis import CoalgebrasWithBasis
from .bialgebras_with_basis import BialgebrasWithBasis
from .hopf_algebras_with_basis import HopfAlgebrasWithBasis
# finite dimensional * with basis
from .finite_dimensional_modules_with_basis import FiniteDimensionalModulesWithBasis
from .finite_dimensional_algebras_with_basis import FiniteDimensionalAlgebrasWithBasis
from .finite_dimensional_coalgebras_with_basis import FiniteDimensionalCoalgebrasWithBasis
from .finite_dimensional_bialgebras_with_basis import FiniteDimensionalBialgebrasWithBasis
from .finite_dimensional_hopf_algebras_with_basis import FiniteDimensionalHopfAlgebrasWithBasis
# graded *
from .graded_modules import GradedModules
from .graded_algebras import GradedAlgebras
from .graded_coalgebras import GradedCoalgebras
from .graded_bialgebras import GradedBialgebras
from .graded_hopf_algebras import GradedHopfAlgebras
# graded * with basis
from .graded_modules_with_basis import GradedModulesWithBasis
from .graded_algebras_with_basis import GradedAlgebrasWithBasis
from .graded_coalgebras_with_basis import GradedCoalgebrasWithBasis
from .graded_bialgebras_with_basis import GradedBialgebrasWithBasis
from .graded_hopf_algebras_with_basis import GradedHopfAlgebrasWithBasis
# Coxeter groups
from .coxeter_groups import CoxeterGroups
lazy_import('sage.categories.finite_coxeter_groups', 'FiniteCoxeterGroups')
from .weyl_groups import WeylGroups
from .finite_weyl_groups import FiniteWeylGroups
from .affine_weyl_groups import AffineWeylGroups
# crystal bases
from .crystals import Crystals
from .highest_weight_crystals import HighestWeightCrystals
from .regular_crystals import RegularCrystals
from .finite_crystals import FiniteCrystals
from .classical_crystals import ClassicalCrystals
# polyhedra
lazy_import('sage.categories.polyhedra', 'PolyhedralSets')
# lie conformal algebras
lazy_import('sage.categories.lie_conformal_algebras', 'LieConformalAlgebras') | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/all.py | 0.839701 | 0.540318 | all.py | pypi |
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring
from sage.categories.graded_lie_conformal_algebras import GradedLieConformalAlgebrasCategory
from sage.categories.graded_modules import GradedModulesCategory
from sage.categories.super_modules import SuperModulesCategory
class LieConformalAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
"""
The category of Lie conformal algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).WithBasis()
Category of Lie conformal algebras with basis over Algebraic Field
"""
class Super(SuperModulesCategory):
"""
The category of super Lie conformal algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(AA).WithBasis().Super()
Category of super Lie conformal algebras with basis over Algebraic Real Field
"""
class ParentMethods:
def _even_odd_on_basis(self, m):
"""
Return the parity of the basis element indexed by ``m``.
OUTPUT:
``0`` if ``m`` is for an even element or ``1`` if ``m``
is for an odd element.
EXAMPLES::
sage: V = lie_conformal_algebras.NeveuSchwarz(QQ)
sage: B = V._indices
sage: V._even_odd_on_basis(B(('G',1)))
1
"""
return self._parity[self.monomial((m[0],0))]
class Graded(GradedLieConformalAlgebrasCategory):
"""
The category of H-graded super Lie conformal algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).WithBasis().Super().Graded()
Category of H-graded super Lie conformal algebras with basis over Algebraic Field
"""
class Graded(GradedLieConformalAlgebrasCategory):
"""
The category of H-graded Lie conformal algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).WithBasis().Graded()
Category of H-graded Lie conformal algebras with basis over Algebraic Field
"""
class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring):
"""
The category of finitely generated Lie conformal
algebras with basis.
EXAMPLES::
sage: C = LieConformalAlgebras(QQbar)
sage: C.WithBasis().FinitelyGenerated()
Category of finitely generated Lie conformal algebras with basis over Algebraic Field
sage: C.WithBasis().FinitelyGenerated() is C.FinitelyGenerated().WithBasis()
True
"""
class Super(SuperModulesCategory):
"""
The category of super finitely generated Lie conformal
algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(AA).WithBasis().FinitelyGenerated().Super()
Category of super finitely generated Lie conformal algebras with basis over Algebraic Real Field
"""
class Graded(GradedModulesCategory):
"""
The category of H-graded super finitely generated Lie
conformal algebras with basis.
EXAMPLES::
sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated()
sage: C.Graded().Super()
Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field
sage: C.Graded().Super() is C.Super().Graded()
True
"""
def _repr_object_names(self):
"""
The names of the objects of ``self``.
EXAMPLES::
sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated()
sage: C.Super().Graded()
Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field
"""
return "H-graded {}".format(self.base_category()._repr_object_names())
class Graded(GradedLieConformalAlgebrasCategory):
"""
The category of H-graded finitely generated Lie conformal
algebras with basis.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded()
Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field
""" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/lie_conformal_algebras_with_basis.py | 0.845942 | 0.462594 | lie_conformal_algebras_with_basis.py | pypi |
from sage.misc.abstract_method import abstract_method
from sage.misc.cachefunc import cached_method
from sage.categories.category_singleton import Category_singleton
from sage.categories.category_with_axiom import CategoryWithAxiom
from sage.categories.simplicial_complexes import SimplicialComplexes
from sage.categories.sets_cat import Sets
class Graphs(Category_singleton):
r"""
The category of graphs.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs(); C
Category of graphs
TESTS::
sage: TestSuite(C).run()
"""
@cached_method
def super_categories(self):
"""
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: Graphs().super_categories()
[Category of simplicial complexes]
"""
return [SimplicialComplexes()]
class ParentMethods:
@abstract_method
def vertices(self):
"""
Return the vertices of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.vertices()
[0, 1, 2, 3, 4]
"""
@abstract_method
def edges(self):
"""
Return the edges of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.edges()
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
"""
def dimension(self):
"""
Return the dimension of ``self`` as a CW complex.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.dimension()
1
"""
if self.edges():
return 1
return 0
def facets(self):
"""
Return the facets of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.facets()
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
"""
return self.edges()
def faces(self):
"""
Return the faces of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: sorted(C.faces(), key=lambda x: (x.dimension(), x.value))
[0, 1, 2, 3, 4, (0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
"""
return set(self.edges()).union(self.vertices())
class Connected(CategoryWithAxiom):
"""
The category of connected graphs.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().Connected()
sage: TestSuite(C).run()
"""
def extra_super_categories(self):
"""
Return the extra super categories of ``self``.
A connected graph is also a metric space.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: Graphs().Connected().super_categories() # indirect doctest
[Category of connected topological spaces,
Category of connected simplicial complexes,
Category of graphs,
Category of metric spaces]
"""
return [Sets().Metric()] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/graphs.py | 0.920683 | 0.562026 | graphs.py | pypi |
from sage.categories.category import Category
from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory
class SubobjectsCategory(RegressiveCovariantConstructionCategory):
_functor_category = "Subobjects"
@classmethod
def default_super_categories(cls, category):
"""
Returns the default super categories of ``category.Subobjects()``
Mathematical meaning: if `A` is a subobject of `B` in the
category `C`, then `A` is also a subquotient of `B` in the
category `C`.
INPUT:
- ``cls`` -- the class ``SubobjectsCategory``
- ``category`` -- a category `Cat`
OUTPUT: a (join) category
In practice, this returns ``category.Subquotients()``, joined
together with the result of the method
:meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>`
(that is the join of ``category`` and ``cat.Subobjects()`` for
each ``cat`` in the super categories of ``category``).
EXAMPLES:
Consider ``category=Groups()``, which has ``cat=Monoids()`` as
super category. Then, a subgroup of a group `G` is
simultaneously a subquotient of `G`, a group by itself, and a
submonoid of `G`::
sage: Groups().Subobjects().super_categories()
[Category of groups, Category of subquotients of monoids, Category of subobjects of sets]
Mind the last item above: there is indeed currently nothing
implemented about submonoids.
This resulted from the following call::
sage: sage.categories.subobjects.SubobjectsCategory.default_super_categories(Groups())
Join of Category of groups and Category of subquotients of monoids and Category of subobjects of sets
"""
return Category.join([category.Subquotients(), super().default_super_categories(category)]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/subobjects.py | 0.909975 | 0.476519 | subobjects.py | pypi |
from sage.misc.lazy_import import lazy_import
from sage.categories.covariant_functorial_construction import CovariantFunctorialConstruction, CovariantConstructionCategory
from sage.categories.pushout import MultivariateConstructionFunctor
native_python_containers = set([tuple, list, set, frozenset, range])
class CartesianProductFunctor(CovariantFunctorialConstruction, MultivariateConstructionFunctor):
"""
The Cartesian product functor.
EXAMPLES::
sage: cartesian_product
The cartesian_product functorial construction
``cartesian_product`` takes a finite collection of sets, and
constructs the Cartesian product of those sets::
sage: A = FiniteEnumeratedSet(['a','b','c'])
sage: B = FiniteEnumeratedSet([1,2])
sage: C = cartesian_product([A, B]); C
The Cartesian product of ({'a', 'b', 'c'}, {1, 2})
sage: C.an_element()
('a', 1)
sage: C.list() # todo: not implemented
[['a', 1], ['a', 2], ['b', 1], ['b', 2], ['c', 1], ['c', 2]]
If those sets are endowed with more structure, say they are
monoids (hence in the category ``Monoids()``), then the result is
automatically endowed with its natural monoid structure::
sage: M = Monoids().example()
sage: M
An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd')
sage: M.rename('M')
sage: C = cartesian_product([M, ZZ, QQ])
sage: C
The Cartesian product of (M, Integer Ring, Rational Field)
sage: C.an_element()
('abcd', 1, 1/2)
sage: C.an_element()^2
('abcdabcd', 1, 1/4)
sage: C.category()
Category of Cartesian products of monoids
sage: Monoids().CartesianProducts()
Category of Cartesian products of monoids
The Cartesian product functor is covariant: if ``A`` is a
subcategory of ``B``, then ``A.CartesianProducts()`` is a
subcategory of ``B.CartesianProducts()`` (see also
:class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`)::
sage: C.categories()
[Category of Cartesian products of monoids,
Category of monoids,
Category of Cartesian products of semigroups,
Category of semigroups,
Category of Cartesian products of unital magmas,
Category of Cartesian products of magmas,
Category of unital magmas,
Category of magmas,
Category of Cartesian products of sets,
Category of sets, ...]
[Category of Cartesian products of monoids,
Category of monoids,
Category of Cartesian products of semigroups,
Category of semigroups,
Category of Cartesian products of magmas,
Category of unital magmas,
Category of magmas,
Category of Cartesian products of sets,
Category of sets,
Category of sets with partial maps,
Category of objects]
Hence, the role of ``Monoids().CartesianProducts()`` is solely to
provide mathematical information and algorithms which are relevant
to Cartesian product of monoids. For example, it specifies that
the result is again a monoid, and that its multiplicative unit is
the Cartesian product of the units of the underlying sets::
sage: C.one()
('', 1, 1)
Those are implemented in the nested class
:class:`Monoids.CartesianProducts
<sage.categories.monoids.Monoids.CartesianProducts>` of
``Monoids(QQ)``. This nested class is itself a subclass of
:class:`CartesianProductsCategory`.
"""
_functor_name = "cartesian_product"
_functor_category = "CartesianProducts"
symbol = " (+) "
def __init__(self, category=None):
r"""
Constructor. See :class:`CartesianProductFunctor` for details.
TESTS::
sage: from sage.categories.cartesian_product import CartesianProductFunctor
sage: CartesianProductFunctor()
The cartesian_product functorial construction
"""
CovariantFunctorialConstruction.__init__(self)
self._forced_category = category
from sage.categories.sets_cat import Sets
if self._forced_category is not None:
codomain = self._forced_category
else:
codomain = Sets()
MultivariateConstructionFunctor.__init__(self, Sets(), codomain)
def __call__(self, args, **kwds):
r"""
Functorial construction application.
This specializes the generic ``__call__`` from
:class:`CovariantFunctorialConstruction` to:
- handle the following plain Python containers as input:
:class:`frozenset`, :class:`list`, :class:`set`,
:class:`tuple`, and :class:`xrange` (Python3 ``range``).
- handle the empty list of factors.
See the examples below.
EXAMPLES::
sage: cartesian_product([[0,1], ('a','b','c')])
The Cartesian product of ({0, 1}, {'a', 'b', 'c'})
sage: _.category()
Category of Cartesian products of finite enumerated sets
sage: cartesian_product([set([0,1,2]), [0,1]])
The Cartesian product of ({0, 1, 2}, {0, 1})
sage: _.category()
Category of Cartesian products of finite enumerated sets
Check that the empty product is handled correctly:
sage: C = cartesian_product([])
sage: C
The Cartesian product of ()
sage: C.cardinality()
1
sage: C.an_element()
()
sage: C.category()
Category of Cartesian products of sets
Check that Python3 ``range`` is handled correctly::
sage: C = cartesian_product([range(2), range(2)])
sage: list(C)
[(0, 0), (0, 1), (1, 0), (1, 1)]
sage: C.category()
Category of Cartesian products of finite enumerated sets
"""
if any(type(arg) in native_python_containers for arg in args):
from sage.categories.sets_cat import Sets
S = Sets()
args = [S(a, enumerated_set=True) for a in args]
elif not args:
if self._forced_category is None:
from sage.categories.sets_cat import Sets
cat = Sets().CartesianProducts()
else:
cat = self._forced_category
from sage.sets.cartesian_product import CartesianProduct
return CartesianProduct((), cat)
elif self._forced_category is not None:
return super().__call__(args, category=self._forced_category, **kwds)
return super().__call__(args, **kwds)
def __eq__(self, other):
r"""
Comparison ignores the ``category`` parameter.
TESTS::
sage: from sage.categories.cartesian_product import CartesianProductFunctor
sage: cartesian_product([ZZ, ZZ]).construction()[0] == CartesianProductFunctor()
True
"""
return isinstance(other, CartesianProductFunctor)
def __ne__(self, other):
r"""
Comparison ignores the ``category`` parameter.
TESTS::
sage: from sage.categories.cartesian_product import CartesianProductFunctor
sage: cartesian_product([ZZ, ZZ]).construction()[0] != CartesianProductFunctor()
False
"""
return not (self == other)
class CartesianProductsCategory(CovariantConstructionCategory):
r"""
An abstract base class for all ``CartesianProducts`` categories.
TESTS::
sage: C = Sets().CartesianProducts()
sage: C
Category of Cartesian products of sets
sage: C.base_category()
Category of sets
sage: latex(C)
\mathbf{CartesianProducts}(\mathbf{Sets})
"""
_functor_category = "CartesianProducts"
def _repr_object_names(self):
"""
EXAMPLES::
sage: ModulesWithBasis(QQ).CartesianProducts() # indirect doctest
Category of Cartesian products of vector spaces with basis over Rational Field
"""
# This method is only required for the capital `C`
return "Cartesian products of %s"%(self.base_category()._repr_object_names())
def CartesianProducts(self):
"""
Return the category of (finite) Cartesian products of objects
of ``self``.
By associativity of Cartesian products, this is ``self`` (a Cartesian
product of Cartesian products of `A`'s is a Cartesian product of
`A`'s).
EXAMPLES::
sage: ModulesWithBasis(QQ).CartesianProducts().CartesianProducts()
Category of Cartesian products of vector spaces with basis over Rational Field
"""
return self
def base_ring(self):
"""
The base ring of a Cartesian product is the base ring of the underlying category.
EXAMPLES::
sage: Algebras(ZZ).CartesianProducts().base_ring()
Integer Ring
"""
return self.base_category().base_ring()
# Moved to avoid circular imports
lazy_import('sage.categories.sets_cat', 'cartesian_product')
"""
The Cartesian product functorial construction
See :class:`CartesianProductFunctor` for more information
EXAMPLES::
sage: cartesian_product
The cartesian_product functorial construction
""" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/cartesian_product.py | 0.711331 | 0.521106 | cartesian_product.py | pypi |
from sage.misc.bindable_class import BindableClass
from sage.categories.category import Category
from sage.categories.category_types import Category_over_base
from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory
class RealizationsCategory(RegressiveCovariantConstructionCategory):
"""
An abstract base class for all categories of realizations category
Relization are implemented as
:class:`~sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory`.
See there for the documentation of how the various bindings such
as ``Sets().Realizations()`` and ``P.Realizations()``, where ``P``
is a parent, work.
.. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`
TESTS::
sage: Sets().Realizations
<bound method Realizations of Category of sets>
sage: Sets().Realizations()
Category of realizations of sets
sage: Sets().Realizations().super_categories()
[Category of sets]
sage: Groups().Realizations().super_categories()
[Category of groups, Category of realizations of unital magmas]
"""
_functor_category = "Realizations"
def Realizations(self):
"""
Return the category of realizations of the parent ``self`` or of objects
of the category ``self``
INPUT:
- ``self`` -- a parent or a concrete category
.. NOTE:: this *function* is actually inserted as a *method* in the class
:class:`~sage.categories.category.Category` (see
:meth:`~sage.categories.category.Category.Realizations`). It is defined
here for code locality reasons.
EXAMPLES:
The category of realizations of some algebra::
sage: Algebras(QQ).Realizations()
Join of Category of algebras over Rational Field and Category of realizations of unital magmas
The category of realizations of a given algebra::
sage: A = Sets().WithRealizations().example(); A
The subset algebra of {1, 2, 3} over Rational Field
sage: A.Realizations()
Category of realizations of The subset algebra of {1, 2, 3} over Rational Field
sage: C = GradedHopfAlgebrasWithBasis(QQ).Realizations(); C
Join of Category of graded hopf algebras with basis over Rational Field and Category of realizations of hopf algebras over Rational Field
sage: C.super_categories()
[Category of graded hopf algebras with basis over Rational Field, Category of realizations of hopf algebras over Rational Field]
sage: TestSuite(C).run()
.. SEEALSO::
- :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`
- :class:`ClasscallMetaclass`
.. TODO::
Add an optional argument to allow for::
sage: Realizations(A, category = Blahs()) # todo: not implemented
"""
if isinstance(self, Category):
return RealizationsCategory.category_of(self)
else:
return getattr(self.__class__, "Realizations")(self)
Category.Realizations = Realizations
class Category_realization_of_parent(Category_over_base, BindableClass):
"""
An abstract base class for categories of all realizations of a given parent
INPUT:
- ``parent_with_realization`` -- a parent
.. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`
EXAMPLES::
sage: A = Sets().WithRealizations().example(); A
The subset algebra of {1, 2, 3} over Rational Field
The role of this base class is to implement some technical goodies, like
the binding ``A.Realizations()`` when a subclass ``Realizations`` is
implemented as a nested class in ``A``
(see the :mod:`code of the example <sage.categories.examples.with_realizations.SubsetAlgebra>`)::
sage: C = A.Realizations(); C
Category of realizations of The subset algebra of {1, 2, 3} over Rational Field
as well as the name for that category.
"""
def __init__(self, parent_with_realization):
"""
TESTS::
sage: from sage.categories.realizations import Category_realization_of_parent
sage: A = Sets().WithRealizations().example(); A
The subset algebra of {1, 2, 3} over Rational Field
sage: C = A.Realizations(); C
Category of realizations of The subset algebra of {1, 2, 3} over Rational Field
sage: isinstance(C, Category_realization_of_parent)
True
sage: C.parent_with_realization
The subset algebra of {1, 2, 3} over Rational Field
sage: TestSuite(C).run(skip=["_test_category_over_bases"])
.. TODO::
Fix the failing test by making ``C`` a singleton
category. This will require some fiddling with the
assertion in :meth:`Category_singleton.__classcall__`
"""
Category_over_base.__init__(self, parent_with_realization)
self.parent_with_realization = parent_with_realization
def _get_name(self):
"""
Return a human readable string specifying which kind of bases this category is for
It is obtained by splitting and lower casing the last part of
the class name.
EXAMPLES::
sage: from sage.categories.realizations import Category_realization_of_parent
sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent):
....: def super_categories(self): return [Objects()]
sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym")
sage: MultiplicativeBasesOnPrimitiveElements(Sym)._get_name()
'multiplicative bases on primitive elements'
"""
import re
return re.sub(".[A-Z]", lambda s: s.group()[0]+" "+s.group()[1], self.__class__.__base__.__name__.split(".")[-1]).lower()
def _repr_object_names(self):
"""
Return the name of the objects of this category.
.. SEEALSO:: :meth:`Category._repr_object_names`
EXAMPLES::
sage: from sage.categories.realizations import Category_realization_of_parent
sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent):
....: def super_categories(self): return [Objects()]
sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym")
sage: C = MultiplicativeBasesOnPrimitiveElements(Sym); C
Category of multiplicative bases on primitive elements of Sym
sage: C._repr_object_names()
'multiplicative bases on primitive elements of Sym'
"""
return "{} of {}".format(self._get_name(), self.base()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/realizations.py | 0.836187 | 0.606571 | realizations.py | pypi |
r"""
Coxeter Group Algebras
"""
import functools
from sage.misc.cachefunc import cached_method
from sage.categories.algebra_functor import AlgebrasCategory
class CoxeterGroupAlgebras(AlgebrasCategory):
class ParentMethods:
def demazure_lusztig_operator_on_basis(self, w, i, q1, q2,
side="right"):
r"""
Return the result of applying the `i`-th Demazure Lusztig
operator on ``w``.
INPUT:
- ``w`` -- an element of the Coxeter group
- ``i`` -- an element of the index set
- ``q1,q2`` -- two elements of the ground ring
- ``bar`` -- a boolean (default ``False``)
See :meth:`demazure_lusztig_operators` for details.
EXAMPLES::
sage: W = WeylGroup(["B",3])
sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word())
sage: K = QQ['q1,q2']
sage: q1, q2 = K.gens()
sage: KW = W.algebra(K)
sage: w = W.an_element()
sage: KW.demazure_lusztig_operator_on_basis(w, 0, q1, q2)
(-q2)*323123 + (q1+q2)*123
sage: KW.demazure_lusztig_operator_on_basis(w, 1, q1, q2)
q1*1231
sage: KW.demazure_lusztig_operator_on_basis(w, 2, q1, q2)
q1*1232
sage: KW.demazure_lusztig_operator_on_basis(w, 3, q1, q2)
(q1+q2)*123 + (-q2)*12
At `q_1=1` and `q_2=0` we recover the action of the
isobaric divided differences `\pi_i`::
sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, 0)
123
sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, 0)
1231
sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, 0)
1232
sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, 0)
123
At `q_1=1` and `q_2=-1` we recover the action of the
simple reflection `s_i`::
sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, -1)
323123
sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, -1)
1231
sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, -1)
1232
sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, -1)
12
"""
return (q1+q2) * self.monomial(w.apply_simple_projection(i,side=side)) - self.term(w.apply_simple_reflection(i, side=side), q2)
def demazure_lusztig_operators(self, q1, q2, side="right", affine=True):
r"""
Return the Demazure Lusztig operators acting on ``self``.
INPUT:
- ``q1,q2`` -- two elements of the ground ring `K`
- ``side`` -- ``"left"`` or ``"right"`` (default: ``"right"``);
which side to act upon
- ``affine`` -- a boolean (default: ``True``)
The Demazure-Lusztig operator `T_i` is the linear map
`R \to R` obtained by interpolating between the
simple projection `\pi_i` (see
:meth:`CoxeterGroups.ElementMethods.simple_projection`)
and the simple reflection `s_i` so that `T_i` has
eigenvalues `q_1` and `q_2`:
.. MATH::
(q_1 + q_2) \pi_i - q_2 s_i.
The Demazure-Lusztig operators give the usual
representation of the operators `T_i` of the `q_1,q_2`
Hecke algebra associated to the Coxeter group.
For a finite Coxeter group, and if ``affine=True``, the
Demazure-Lusztig operators `T_1,\dots,T_n` are completed
by `T_0` to implement the level `0` action of the affine
Hecke algebra.
EXAMPLES::
sage: W = WeylGroup(["B",3])
sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word())
sage: K = QQ['q1,q2']
sage: q1, q2 = K.gens()
sage: KW = W.algebra(K)
sage: T = KW.demazure_lusztig_operators(q1, q2, affine=True)
sage: x = KW.monomial(W.an_element()); x
123
sage: T[0](x)
(-q2)*323123 + (q1+q2)*123
sage: T[1](x)
q1*1231
sage: T[2](x)
q1*1232
sage: T[3](x)
(q1+q2)*123 + (-q2)*12
sage: T._test_relations()
.. NOTE::
For a finite Weyl group `W`, the level 0 action of the
affine Weyl group `\tilde W` only depends on the
Coxeter diagram of the affinization, not its Dynkin
diagram. Hence it is possible to explore all cases
using only untwisted affinizations.
"""
from sage.combinat.root_system.hecke_algebra_representation import HeckeAlgebraRepresentation
W = self.basis().keys()
cartan_type = W.cartan_type()
if affine and cartan_type.is_finite():
cartan_type = cartan_type.affine()
T_on_basis = functools.partial(self.demazure_lusztig_operator_on_basis, q1=q1, q2=q2, side=side)
return HeckeAlgebraRepresentation(self, T_on_basis, cartan_type, q1, q2)
@cached_method
def demazure_lusztig_eigenvectors(self, q1, q2):
r"""
Return the family of eigenvectors for the Cherednik operators.
INPUT:
- ``self`` -- a finite Coxeter group `W`
- ``q1,q2`` -- two elements of the ground ring `K`
The affine Hecke algebra `H_{q_1,q_2}(\tilde W)` acts on
the group algebra of `W` through the Demazure-Lusztig
operators `T_i`. Its Cherednik operators `Y^\lambda` can
be simultaneously diagonalized as long as `q_1/q_2` is not
a small root of unity [HST2008]_.
This method returns the family of joint eigenvectors,
indexed by `W`.
.. SEEALSO::
- :meth:`demazure_lusztig_operators`
- :class:`sage.combinat.root_system.hecke_algebra_representation.CherednikOperatorsEigenvectors`
EXAMPLES::
sage: W = WeylGroup(["B",2])
sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word())
sage: K = QQ['q1,q2'].fraction_field()
sage: q1, q2 = K.gens()
sage: KW = W.algebra(K)
sage: E = KW.demazure_lusztig_eigenvectors(q1,q2)
sage: E.keys()
Weyl Group of type ['B', 2] (as a matrix group acting on the ambient space)
sage: w = W.an_element()
sage: E[w]
(q2/(-q1+q2))*2121 + ((-q2)/(-q1+q2))*121 - 212 + 12
"""
W = self.basis().keys()
if not W.cartan_type().is_finite():
raise ValueError("the Demazure-Lusztig eigenvectors are only defined for finite Coxeter groups")
result = self.demazure_lusztig_operators(q1, q2, affine=True).Y_eigenvectors()
w0 = W.long_element()
result.affine_lift = w0._mul_
result.affine_retract = w0._mul_
return result | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/coxeter_group_algebras.py | 0.910212 | 0.508605 | coxeter_group_algebras.py | pypi |
from sage.categories.category import Category
from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory
class QuotientsCategory(RegressiveCovariantConstructionCategory):
_functor_category = "Quotients"
@classmethod
def default_super_categories(cls, category):
"""
Returns the default super categories of ``category.Quotients()``
Mathematical meaning: if `A` is a quotient of `B` in the
category `C`, then `A` is also a subquotient of `B` in the
category `C`.
INPUT:
- ``cls`` -- the class ``QuotientsCategory``
- ``category`` -- a category `Cat`
OUTPUT: a (join) category
In practice, this returns ``category.Subquotients()``, joined
together with the result of the method
:meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>`
(that is the join of ``category`` and ``cat.Quotients()`` for
each ``cat`` in the super categories of ``category``).
EXAMPLES:
Consider ``category=Groups()``, which has ``cat=Monoids()`` as
super category. Then, a subgroup of a group `G` is
simultaneously a subquotient of `G`, a group by itself, and a
quotient monoid of ``G``::
sage: Groups().Quotients().super_categories()
[Category of groups, Category of subquotients of monoids, Category of quotients of semigroups]
Mind the last item above: there is indeed currently nothing
implemented about quotient monoids.
This resulted from the following call::
sage: sage.categories.quotients.QuotientsCategory.default_super_categories(Groups())
Join of Category of groups and Category of subquotients of monoids and Category of quotients of semigroups
"""
return Category.join([category.Subquotients(), super().default_super_categories(category)]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/quotients.py | 0.915207 | 0.565359 | quotients.py | pypi |
from sage.categories.category import Category
from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory
def WithRealizations(self):
r"""
Return the category of parents in ``self`` endowed with multiple realizations.
INPUT:
- ``self`` -- a category
.. SEEALSO::
- The documentation and code
(:mod:`sage.categories.examples.with_realizations`) of
``Sets().WithRealizations().example()`` for more on how to use and
implement a parent with several realizations.
- Various use cases:
- :class:`SymmetricFunctions`
- :class:`QuasiSymmetricFunctions`
- :class:`NonCommutativeSymmetricFunctions`
- :class:`SymmetricFunctionsNonCommutingVariables`
- :class:`DescentAlgebra`
- :class:`algebras.Moebius`
- :class:`IwahoriHeckeAlgebra`
- :class:`ExtendedAffineWeylGroup`
- The `Implementing Algebraic Structures
<../../../../../thematic_tutorials/tutorial-implementing-algebraic-structures>`_
thematic tutorial.
- :mod:`sage.categories.realizations`
.. NOTE:: this *function* is actually inserted as a *method* in the class
:class:`~sage.categories.category.Category` (see
:meth:`~sage.categories.category.Category.WithRealizations`). It is defined
here for code locality reasons.
EXAMPLES::
sage: Sets().WithRealizations()
Category of sets with realizations
.. RUBRIC:: Parent with realizations
Let us now explain the concept of realizations. A *parent with
realizations* is a facade parent (see :class:`Sets.Facade`)
admitting multiple concrete realizations where its elements are
represented. Consider for example an algebra `A` which admits
several natural bases::
sage: A = Sets().WithRealizations().example(); A
The subset algebra of {1, 2, 3} over Rational Field
For each such basis `B` one implements a parent `P_B` which
realizes `A` with its elements represented by expanding them on
the basis `B`::
sage: A.F()
The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis
sage: A.Out()
The subset algebra of {1, 2, 3} over Rational Field in the Out basis
sage: A.In()
The subset algebra of {1, 2, 3} over Rational Field in the In basis
sage: A.an_element()
F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}]
If `B` and `B'` are two bases, then the change of basis from `B`
to `B'` is implemented by a canonical coercion between `P_B` and
`P_{B'}`::
sage: F = A.F(); In = A.In(); Out = A.Out()
sage: i = In.an_element(); i
In[{}] + 2*In[{1}] + 3*In[{2}] + In[{1, 2}]
sage: F(i)
7*F[{}] + 3*F[{1}] + 4*F[{2}] + F[{1, 2}]
sage: F.coerce_map_from(Out)
Generic morphism:
From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis
To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis
allowing for mixed arithmetic::
sage: (1 + Out.from_set(1)) * In.from_set(2,3)
Out[{}] + 2*Out[{1}] + 2*Out[{2}] + 2*Out[{3}] + 2*Out[{1, 2}] + 2*Out[{1, 3}] + 4*Out[{2, 3}] + 4*Out[{1, 2, 3}]
In our example, there are three realizations::
sage: A.realizations()
[The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis,
The subset algebra of {1, 2, 3} over Rational Field in the In basis,
The subset algebra of {1, 2, 3} over Rational Field in the Out basis]
Instead of manually defining the shorthands ``F``, ``In``, and
``Out``, as above one can just do::
sage: A.inject_shorthands()
Defining F as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis
Defining In as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the In basis
Defining Out as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Out basis
.. RUBRIC:: Rationale
Besides some goodies described below, the role of `A` is threefold:
- To provide, as illustrated above, a single entry point for the
algebra as a whole: documentation, access to its properties and
different realizations, etc.
- To provide a natural location for the initialization of the
bases and the coercions between, and other methods that are
common to all bases.
- To let other objects refer to `A` while allowing elements to be
represented in any of the realizations.
We now illustrate this second point by defining the polynomial
ring with coefficients in `A`::
sage: P = A['x']; P
Univariate Polynomial Ring in x over The subset algebra of {1, 2, 3} over Rational Field
sage: x = P.gen()
In the following examples, the coefficients turn out to be all
represented in the `F` basis::
sage: P.one()
F[{}]
sage: (P.an_element() + 1)^2
F[{}]*x^2 + 2*F[{}]*x + F[{}]
However we can create a polynomial with mixed coefficients, and
compute with it::
sage: p = P([1, In[{1}], Out[{2}] ]); p
Out[{2}]*x^2 + In[{1}]*x + F[{}]
sage: p^2
Out[{2}]*x^4
+ (-8*In[{}] + 4*In[{1}] + 8*In[{2}] + 4*In[{3}] - 4*In[{1, 2}] - 2*In[{1, 3}] - 4*In[{2, 3}] + 2*In[{1, 2, 3}])*x^3
+ (F[{}] + 3*F[{1}] + 2*F[{2}] - 2*F[{1, 2}] - 2*F[{2, 3}] + 2*F[{1, 2, 3}])*x^2
+ (2*F[{}] + 2*F[{1}])*x
+ F[{}]
Note how each coefficient involves a single basis which need not
be that of the other coefficients. Which basis is used depends on
how coercion happened during mixed arithmetic and needs not be
deterministic.
One can easily coerce all coefficient to a given basis with::
sage: p.map_coefficients(In)
(-4*In[{}] + 2*In[{1}] + 4*In[{2}] + 2*In[{3}] - 2*In[{1, 2}] - In[{1, 3}] - 2*In[{2, 3}] + In[{1, 2, 3}])*x^2 + In[{1}]*x + In[{}]
Alas, the natural notation for constructing such polynomials does
not yet work::
sage: In[{1}] * x
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for *: 'The subset algebra of {1, 2, 3} over Rational Field in the In basis' and 'Univariate Polynomial Ring in x over The subset algebra of {1, 2, 3} over Rational Field'
.. RUBRIC:: The category of realizations of `A`
The set of all realizations of `A`, together with the coercion morphisms
is a category (whose class inherits from
:class:`~sage.categories.realizations.Category_realization_of_parent`)::
sage: A.Realizations()
Category of realizations of The subset algebra of {1, 2, 3} over Rational Field
The various parent realizing `A` belong to this category::
sage: A.F() in A.Realizations()
True
`A` itself is in the category of algebras with realizations::
sage: A in Algebras(QQ).WithRealizations()
True
The (mostly technical) ``WithRealizations`` categories are the
analogs of the ``*WithSeveralBases`` categories in
MuPAD-Combinat. They provide support tools for handling the
different realizations and the morphisms between them.
Typically, ``VectorSpaces(QQ).FiniteDimensional().WithRealizations()``
will eventually be in charge, whenever a coercion `\phi: A\mapsto B` is
registered, to register `\phi^{-1}` as coercion `B \mapsto A`
if there is none defined yet. To achieve this,
``FiniteDimensionalVectorSpaces`` would provide a nested class
``WithRealizations`` implementing the appropriate logic.
``WithRealizations`` is a :mod:`regressive covariant functorial
construction <sage.categories.covariant_functorial_construction>`.
On our example, this simply means that `A` is automatically in the
category of rings with realizations (covariance)::
sage: A in Rings().WithRealizations()
True
and in the category of algebras (regressiveness)::
sage: A in Algebras(QQ)
True
.. NOTE::
For ``C`` a category, ``C.WithRealizations()`` in fact calls
``sage.categories.with_realizations.WithRealizations(C)``. The
later is responsible for building the hierarchy of the
categories with realizations in parallel to that of their base
categories, optimizing away those categories that do not
provide a ``WithRealizations`` nested class. See
:mod:`sage.categories.covariant_functorial_construction` for
the technical details.
.. NOTE::
Design question: currently ``WithRealizations`` is a
regressive construction. That is ``self.WithRealizations()``
is a subcategory of ``self`` by default::
sage: Algebras(QQ).WithRealizations().super_categories()
[Category of algebras over Rational Field,
Category of monoids with realizations,
Category of additive unital additive magmas with realizations]
Is this always desirable? For example,
``AlgebrasWithBasis(QQ).WithRealizations()`` should certainly
be a subcategory of ``Algebras(QQ)``, but not of
``AlgebrasWithBasis(QQ)``. This is because
``AlgebrasWithBasis(QQ)`` is specifying something about the
concrete realization.
TESTS::
sage: Semigroups().WithRealizations()
Join of Category of semigroups and Category of sets with realizations
sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C
Category of graded hopf algebras with basis over Rational Field with realizations
sage: C.super_categories()
[Join of Category of hopf algebras over Rational Field
and Category of graded algebras over Rational Field
and Category of graded coalgebras over Rational Field]
sage: TestSuite(Semigroups().WithRealizations()).run()
"""
return WithRealizationsCategory.category_of(self)
Category.WithRealizations = WithRealizations
class WithRealizationsCategory(RegressiveCovariantConstructionCategory):
"""
An abstract base class for all categories of parents with multiple
realizations.
.. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`
The role of this base class is to implement some technical goodies, such
as the name for that category.
"""
_functor_category = "WithRealizations"
def _repr_(self):
"""
String representation.
EXAMPLES::
sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C #indirect doctest
Category of graded hopf algebras with basis over Rational Field with realizations
"""
s = repr(self.base_category())
return s+" with realizations" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/with_realizations.py | 0.946621 | 0.796372 | with_realizations.py | pypi |
from sage.categories.graded_modules import GradedModulesCategory
from sage.categories.super_modules import SuperModulesCategory
from sage.misc.abstract_method import abstract_method
from sage.categories.lambda_bracket_algebras import LambdaBracketAlgebras
class SuperLieConformalAlgebras(SuperModulesCategory):
r"""
The category of super Lie conformal algebras.
EXAMPLES::
sage: LieConformalAlgebras(AA).Super()
Category of super Lie conformal algebras over Algebraic Real Field
Notice that we can force to have a *purely even* super Lie
conformal algebra::
sage: bosondict = {('a','a'):{1:{('K',0):1}}}
sage: R = LieConformalAlgebra(QQ,bosondict,names=('a',),
....: central_elements=('K',), super=True)
sage: [g.is_even_odd() for g in R.gens()]
[0, 0]
"""
def extra_super_categories(self):
"""
The extra super categories of ``self``.
EXAMPLES::
sage: LieConformalAlgebras(QQ).Super().super_categories()
[Category of super modules over Rational Field,
Category of Lambda bracket algebras over Rational Field]
"""
return [LambdaBracketAlgebras(self.base_ring())]
def example(self):
"""
An example parent in this category.
EXAMPLES::
sage: LieConformalAlgebras(QQ).Super().example()
The Neveu-Schwarz super Lie conformal algebra over Rational Field
"""
from sage.algebras.lie_conformal_algebras.neveu_schwarz_lie_conformal_algebra\
import NeveuSchwarzLieConformalAlgebra
return NeveuSchwarzLieConformalAlgebra(self.base_ring())
class ParentMethods:
def _test_jacobi(self, **options):
"""
Test the Jacobi axiom of this super Lie conformal algebra.
INPUT:
- ``options`` -- any keyword arguments acceptde by :meth:`_tester`
EXAMPLES:
By default, this method tests only the elements returned by
``self.some_elements()``::
sage: V = lie_conformal_algebras.Affine(QQ, 'B2')
sage: V._test_jacobi() # long time (6 seconds)
It works for super Lie conformal algebras too::
sage: V = lie_conformal_algebras.NeveuSchwarz(QQ)
sage: V._test_jacobi()
We can use specific elements by passing the ``elements``
keyword argument::
sage: V = lie_conformal_algebras.Affine(QQ, 'A1', names=('e', 'h', 'f'))
sage: V.inject_variables()
Defining e, h, f, K
sage: V._test_jacobi(elements=(e, 2*f+h, 3*h))
TESTS::
sage: wrongdict = {('a', 'a'): {0: {('b', 0): 1}}, ('b', 'a'): {0: {('a', 0): 1}}}
sage: V = LieConformalAlgebra(QQ, wrongdict, names=('a', 'b'), parity=(1, 0))
sage: V._test_jacobi()
Traceback (most recent call last):
...
AssertionError: {(0, 0): -3*a} != {}
- {(0, 0): -3*a}
+ {}
"""
tester = self._tester(**options)
S = tester.some_elements()
# Try our best to avoid non-homogeneous elements
elements = []
for s in S:
try:
s.is_even_odd()
except ValueError:
try:
elements.extend([s.even_component(), s.odd_component()])
except (AttributeError, ValueError):
pass
continue
elements.append(s)
S = elements
from sage.misc.misc import some_tuples
from sage.arith.misc import binomial
pz = tester._instance.zero()
for x,y,z in some_tuples(S, 3, tester._max_runs):
if x.is_zero() or y.is_zero():
sgn = 1
elif x.is_even_odd() * y.is_even_odd():
sgn = -1
else:
sgn = 1
brxy = x.bracket(y)
brxz = x.bracket(z)
bryz = y.bracket(z)
br1 = {k: x.bracket(v) for k,v in bryz.items()}
br2 = {k: v.bracket(z) for k,v in brxy.items()}
br3 = {k: y.bracket(v) for k,v in brxz.items()}
jac1 = {(j,k): v for k in br1 for j,v in br1[k].items()}
jac3 = {(k,j): v for k in br3 for j,v in br3[k].items()}
jac2 = {}
for k,br in br2.items():
for j,v in br.items():
for r in range(j+1):
jac2[(k+r, j-r)] = (jac2.get((k+r, j-r), pz)
+ binomial(k+r, r)*v)
for k,v in jac2.items():
jac1[k] = jac1.get(k, pz) - v
for k,v in jac3.items():
jac1[k] = jac1.get(k, pz) - sgn*v
jacobiator = {k: v for k,v in jac1.items() if v}
tester.assertDictEqual(jacobiator, {})
class ElementMethods:
@abstract_method
def is_even_odd(self):
"""
Return ``0`` if this element is *even* and ``1`` if it is
*odd*.
EXAMPLES::
sage: R = lie_conformal_algebras.NeveuSchwarz(QQ);
sage: R.inject_variables()
Defining L, G, C
sage: G.is_even_odd()
1
"""
class Graded(GradedModulesCategory):
"""
The category of H-graded super Lie conformal algebras.
EXAMPLES::
sage: LieConformalAlgebras(AA).Super().Graded()
Category of H-graded super Lie conformal algebras over Algebraic Real Field
"""
def _repr_object_names(self):
"""
The names of the objects of this category.
EXAMPLES::
sage: LieConformalAlgebras(QQbar).Graded()
Category of H-graded Lie conformal algebras over Algebraic Field
"""
return "H-graded {}".format(self.base_category()._repr_object_names()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/super_lie_conformal_algebras.py | 0.777553 | 0.36625 | super_lie_conformal_algebras.py | pypi |
from sage.categories.category import Category
from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory
class IsomorphicObjectsCategory(RegressiveCovariantConstructionCategory):
_functor_category = "IsomorphicObjects"
@classmethod
def default_super_categories(cls, category):
"""
Returns the default super categories of ``category.IsomorphicObjects()``
Mathematical meaning: if `A` is the image of `B` by an
isomorphism in the category `C`, then `A` is both a subobject
of `B` and a quotient of `B` in the category `C`.
INPUT:
- ``cls`` -- the class ``IsomorphicObjectsCategory``
- ``category`` -- a category `Cat`
OUTPUT: a (join) category
In practice, this returns ``category.Subobjects()`` and
``category.Quotients()``, joined together with the result of the method
:meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>`
(that is the join of ``category`` and
``cat.IsomorphicObjects()`` for each ``cat`` in the super
categories of ``category``).
EXAMPLES:
Consider ``category=Groups()``, which has ``cat=Monoids()`` as
super category. Then, the image of a group `G'` by a group
isomorphism is simultaneously a subgroup of `G`, a subquotient
of `G`, a group by itself, and the image of `G` by a monoid
isomorphism::
sage: Groups().IsomorphicObjects().super_categories()
[Category of groups,
Category of subquotients of monoids,
Category of quotients of semigroups,
Category of isomorphic objects of sets]
Mind the last item above: there is indeed currently nothing
implemented about isomorphic objects of monoids.
This resulted from the following call::
sage: sage.categories.isomorphic_objects.IsomorphicObjectsCategory.default_super_categories(Groups())
Join of Category of groups and
Category of subquotients of monoids and
Category of quotients of semigroups and
Category of isomorphic objects of sets
"""
return Category.join([category.Subobjects(), category.Quotients(),
super().default_super_categories(category)]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/isomorphic_objects.py | 0.90881 | 0.620995 | isomorphic_objects.py | pypi |
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element_wrapper import ElementWrapper
from sage.categories.graphs import Graphs
class Cycle(UniqueRepresentation, Parent):
r"""
An example of a graph: the cycle of length `n`.
This class illustrates a minimal implementation of a graph.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example(); C
An example of a graph: the 5-cycle
sage: C.category()
Category of graphs
We conclude by running systematic tests on this graph::
sage: TestSuite(C).run()
"""
def __init__(self, n=5):
r"""
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example(6); C
An example of a graph: the 6-cycle
TESTS::
sage: TestSuite(C).run()
"""
self._n = n
Parent.__init__(self, category=Graphs())
def _repr_(self):
r"""
TESTS::
sage: from sage.categories.graphs import Graphs
sage: Graphs().example()
An example of a graph: the 5-cycle
"""
return "An example of a graph: the {}-cycle".format(self._n)
def an_element(self):
r"""
Return an element of the graph, as per
:meth:`Sets.ParentMethods.an_element`.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.an_element()
0
"""
return self(0)
def vertices(self):
"""
Return the vertices of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.vertices()
[0, 1, 2, 3, 4]
"""
return [self(i) for i in range(self._n)]
def edges(self):
"""
Return the edges of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: C.edges()
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
"""
return [self( (i, (i+1) % self._n) ) for i in range(self._n)]
class Element(ElementWrapper):
def dimension(self):
"""
Return the dimension of ``self``.
EXAMPLES::
sage: from sage.categories.graphs import Graphs
sage: C = Graphs().example()
sage: e = C.edges()[0]
sage: e.dimension()
2
sage: v = C.vertices()[0]
sage: v.dimension()
1
"""
if isinstance(self.value, tuple):
return 2
return 1
Example = Cycle | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/graphs.py | 0.935328 | 0.674771 | graphs.py | pypi |
r"""
Example of a set with grading
"""
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.categories.sets_with_grading import SetsWithGrading
from sage.rings.integer_ring import IntegerRing
from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
class NonNegativeIntegers(UniqueRepresentation, Parent):
r"""
Non negative integers graded by themselves.
EXAMPLES::
sage: E = SetsWithGrading().example(); E
Non negative integers
sage: E in Sets().Infinite()
True
sage: E.graded_component(0)
{0}
sage: E.graded_component(100)
{100}
"""
def __init__(self):
r"""
TESTS::
sage: TestSuite(SetsWithGrading().example()).run()
"""
Parent.__init__(self, category=SetsWithGrading().Infinite(),
facade=IntegerRing())
def an_element(self):
r"""
Return 0.
EXAMPLES::
sage: SetsWithGrading().example().an_element()
0
"""
return 0
def _repr_(self):
r"""
TESTS::
sage: SetsWithGrading().example() # indirect example
Non negative integers
"""
return "Non negative integers"
def graded_component(self, grade):
r"""
Return the component with grade ``grade``.
EXAMPLES::
sage: N = SetsWithGrading().example()
sage: N.graded_component(65)
{65}
"""
return FiniteEnumeratedSet([grade])
def grading(self, elt):
r"""
Return the grade of ``elt``.
EXAMPLES::
sage: N = SetsWithGrading().example()
sage: N.grading(10)
10
"""
return elt
def generating_series(self, var='z'):
r"""
Return `1 / (1-z)`.
EXAMPLES::
sage: N = SetsWithGrading().example(); N
Non negative integers
sage: f = N.generating_series(); f
1/(-z + 1)
sage: LaurentSeriesRing(ZZ,'z')(f)
1 + z + z^2 + z^3 + z^4 + z^5 + z^6 + z^7 + z^8 + z^9 + z^10 + z^11 + z^12 + z^13 + z^14 + z^15 + z^16 + z^17 + z^18 + z^19 + O(z^20)
"""
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.integer import Integer
R = PolynomialRing(IntegerRing(), var)
z = R.gen()
return Integer(1) / (Integer(1) - z)
Example = NonNegativeIntegers | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/sets_with_grading.py | 0.938131 | 0.656383 | sets_with_grading.py | pypi |
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.categories.all import Posets
from sage.structure.element_wrapper import ElementWrapper
from sage.sets.set import Set, Set_object_enumerated
from sage.sets.positive_integers import PositiveIntegers
class FiniteSetsOrderedByInclusion(UniqueRepresentation, Parent):
r"""
An example of a poset: finite sets ordered by inclusion
This class provides a minimal implementation of a poset
EXAMPLES::
sage: P = Posets().example(); P
An example of a poset: sets ordered by inclusion
We conclude by running systematic tests on this poset::
sage: TestSuite(P).run(verbose = True)
running ._test_an_element() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_construction() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
running ._test_some_elements() . . . pass
"""
def __init__(self):
r"""
EXAMPLES::
sage: P = Posets().example(); P
An example of a poset: sets ordered by inclusion
sage: P.category()
Category of posets
sage: type(P)
<class 'sage.categories.examples.posets.FiniteSetsOrderedByInclusion_with_category'>
sage: TestSuite(P).run()
"""
Parent.__init__(self, category=Posets())
def _repr_(self):
r"""
TESTS::
sage: S = Posets().example()
sage: S._repr_()
'An example of a poset: sets ordered by inclusion'
"""
return "An example of a poset: sets ordered by inclusion"
def le(self, x, y):
r"""
Returns whether `x` is a subset of `y`
EXAMPLES::
sage: P = Posets().example()
sage: P.le( P(Set([1,3])), P(Set([1,2,3])) )
True
sage: P.le( P(Set([1,3])), P(Set([1,3])) )
True
sage: P.le( P(Set([1,2])), P(Set([1,3])) )
False
"""
return x.value.issubset(y.value)
def an_element(self):
r"""
Returns an element of this poset
EXAMPLES::
sage: B = Posets().example()
sage: B.an_element()
{1, 4, 6}
"""
return self(Set([1,4,6]))
class Element(ElementWrapper):
wrapped_class = Set_object_enumerated
class PositiveIntegersOrderedByDivisibilityFacade(UniqueRepresentation, Parent):
r"""
An example of a facade poset: the positive integers ordered by divisibility
This class provides a minimal implementation of a facade poset
EXAMPLES::
sage: P = Posets().example("facade"); P
An example of a facade poset: the positive integers ordered by divisibility
sage: P(5)
5
sage: P(0)
Traceback (most recent call last):
...
ValueError: Can't coerce `0` in any parent `An example of a facade poset: the positive integers ordered by divisibility` is a facade for
sage: 3 in P
True
sage: 0 in P
False
"""
element_class = type(Set([]))
def __init__(self):
r"""
EXAMPLES::
sage: P = Posets().example("facade"); P
An example of a facade poset: the positive integers ordered by divisibility
sage: P.category()
Category of facade posets
sage: type(P)
<class 'sage.categories.examples.posets.PositiveIntegersOrderedByDivisibilityFacade_with_category'>
sage: TestSuite(P).run()
"""
Parent.__init__(self, facade=(PositiveIntegers(),), category=Posets())
def _repr_(self):
r"""
TESTS::
sage: S = Posets().example("facade")
sage: S._repr_()
'An example of a facade poset: the positive integers ordered by divisibility'
"""
return "An example of a facade poset: the positive integers ordered by divisibility"
def le(self, x, y):
r"""
Returns whether `x` is divisible by `y`
EXAMPLES::
sage: P = Posets().example("facade")
sage: P.le(3, 6)
True
sage: P.le(3, 3)
True
sage: P.le(3, 7)
False
"""
return x.divides(y) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/posets.py | 0.934739 | 0.481271 | posets.py | pypi |
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element_wrapper import ElementWrapper
from sage.categories.manifolds import Manifolds
class Plane(UniqueRepresentation, Parent):
r"""
An example of a manifold: the `n`-dimensional plane.
This class illustrates a minimal implementation of a manifold.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: M = Manifolds(QQ).example(); M
An example of a Rational Field manifold: the 3-dimensional plane
sage: M.category()
Category of manifolds over Rational Field
We conclude by running systematic tests on this manifold::
sage: TestSuite(M).run()
"""
def __init__(self, n=3, base_ring=None):
r"""
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: M = Manifolds(QQ).example(6); M
An example of a Rational Field manifold: the 6-dimensional plane
TESTS::
sage: TestSuite(M).run()
"""
self._n = n
Parent.__init__(self, base=base_ring, category=Manifolds(base_ring))
def _repr_(self):
r"""
TESTS::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(QQ).example()
An example of a Rational Field manifold: the 3-dimensional plane
"""
return "An example of a {} manifold: the {}-dimensional plane".format(
self.base_ring(), self._n)
def dimension(self):
"""
Return the dimension of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: M = Manifolds(QQ).example()
sage: M.dimension()
3
"""
return self._n
def an_element(self):
r"""
Return an element of the manifold, as per
:meth:`Sets.ParentMethods.an_element`.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: M = Manifolds(QQ).example()
sage: M.an_element()
(0, 0, 0)
"""
zero = self.base_ring().zero()
return self(tuple([zero]*self._n))
Element = ElementWrapper
Example = Plane | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/manifolds.py | 0.926748 | 0.512937 | manifolds.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.structure.parent import Parent
from sage.categories.all import CommutativeAdditiveMonoids
from .commutative_additive_semigroups import FreeCommutativeAdditiveSemigroup
class FreeCommutativeAdditiveMonoid(FreeCommutativeAdditiveSemigroup):
r"""
An example of a commutative additive monoid: the free commutative monoid
This class illustrates a minimal implementation of a commutative monoid.
EXAMPLES::
sage: S = CommutativeAdditiveMonoids().example(); S
An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd')
sage: S.category()
Category of commutative additive monoids
This is the free semigroup generated by::
sage: S.additive_semigroup_generators()
Family (a, b, c, d)
with product rule given by `a \times b = a` for all `a, b`::
sage: (a,b,c,d) = S.additive_semigroup_generators()
We conclude by running systematic tests on this commutative monoid::
sage: TestSuite(S).run(verbose = True)
running ._test_additive_associativity() . . . pass
running ._test_an_element() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_construction() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_nonzero_equal() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
running ._test_some_elements() . . . pass
running ._test_zero() . . . pass
"""
def __init__(self, alphabet=('a','b','c','d')):
r"""
The free commutative monoid
INPUT:
- ``alphabet`` -- a tuple of strings: the generators of the monoid
EXAMPLES::
sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c')); M
An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c')
TESTS::
sage: TestSuite(M).run()
"""
self.alphabet = alphabet
Parent.__init__(self, category=CommutativeAdditiveMonoids())
def _repr_(self):
r"""
TESTS::
sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c'))
sage: M._repr_()
"An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c')"
"""
return "An example of a commutative monoid: the free commutative monoid generated by %s"%(self.alphabet,)
@cached_method
def zero(self):
r"""
Returns the zero of this additive monoid, as per :meth:`CommutativeAdditiveMonoids.ParentMethods.zero`.
EXAMPLES::
sage: M = CommutativeAdditiveMonoids().example(); M
An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd')
sage: M.zero()
0
"""
return self(())
class Element(FreeCommutativeAdditiveSemigroup.Element):
def __bool__(self) -> bool:
"""
Check if ``self`` is not the zero of the monoid
EXAMPLES::
sage: M = CommutativeAdditiveMonoids().example()
sage: bool(M.zero())
False
sage: [bool(m) for m in M.additive_semigroup_generators()]
[True, True, True, True]
"""
return any(x for x in self.value.values())
Example = FreeCommutativeAdditiveMonoid | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/commutative_additive_monoids.py | 0.923756 | 0.439928 | commutative_additive_monoids.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.sets.family import Family
from sage.categories.semigroups import Semigroups
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element_wrapper import ElementWrapper
class LeftRegularBand(UniqueRepresentation, Parent):
r"""
An example of a finite semigroup
This class provides a minimal implementation of a finite semigroup.
EXAMPLES::
sage: S = FiniteSemigroups().example(); S
An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd')
This is the semigroup generated by::
sage: S.semigroup_generators()
Family ('a', 'b', 'c', 'd')
such that `x^2 = x` and `x y x = xy` for any `x` and `y` in `S`::
sage: S('dab')
'dab'
sage: S('dab') * S('acb')
'dabc'
It follows that the elements of `S` are strings without
repetitions over the alphabet `a`, `b`, `c`, `d`::
sage: sorted(S.list())
['a', 'ab', 'abc', 'abcd', 'abd', 'abdc', 'ac', 'acb', 'acbd', 'acd',
'acdb', 'ad', 'adb', 'adbc', 'adc', 'adcb', 'b', 'ba', 'bac',
'bacd', 'bad', 'badc', 'bc', 'bca', 'bcad', 'bcd', 'bcda', 'bd',
'bda', 'bdac', 'bdc', 'bdca', 'c', 'ca', 'cab', 'cabd', 'cad',
'cadb', 'cb', 'cba', 'cbad', 'cbd', 'cbda', 'cd', 'cda', 'cdab',
'cdb', 'cdba', 'd', 'da', 'dab', 'dabc', 'dac', 'dacb', 'db',
'dba', 'dbac', 'dbc', 'dbca', 'dc', 'dca', 'dcab', 'dcb', 'dcba']
It also follows that there are finitely many of them::
sage: S.cardinality()
64
Indeed::
sage: 4 * ( 1 + 3 * (1 + 2 * (1 + 1)))
64
As expected, all the elements of `S` are idempotents::
sage: all( x.is_idempotent() for x in S )
True
Now, let us look at the structure of the semigroup::
sage: S = FiniteSemigroups().example(alphabet = ('a','b','c'))
sage: S.cayley_graph(side="left", simple=True).plot()
Graphics object consisting of 60 graphics primitives
sage: S.j_transversal_of_idempotents() # random (arbitrary choice)
['acb', 'ac', 'ab', 'bc', 'a', 'c', 'b']
We conclude by running systematic tests on this semigroup::
sage: TestSuite(S).run(verbose = True)
running ._test_an_element() . . . pass
running ._test_associativity() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_construction() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_enumerated_set_contains() . . . pass
running ._test_enumerated_set_iter_cardinality() . . . pass
running ._test_enumerated_set_iter_list() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
running ._test_some_elements() . . . pass
"""
def __init__(self, alphabet=('a','b','c','d')):
r"""
A left regular band.
EXAMPLES::
sage: S = FiniteSemigroups().example(); S
An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd')
sage: S = FiniteSemigroups().example(alphabet=('x','y')); S
An example of a finite semigroup: the left regular band generated by ('x', 'y')
sage: TestSuite(S).run()
"""
self.alphabet = alphabet
Parent.__init__(self,
category=Semigroups().Finite().FinitelyGenerated())
def _repr_(self):
r"""
TESTS::
sage: S = FiniteSemigroups().example()
sage: S._repr_()
"An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd')"
"""
return "An example of a finite semigroup: the left regular band generated by %s"%(self.alphabet,)
def product(self, x, y):
r"""
Returns the product of two elements of the semigroup.
EXAMPLES::
sage: S = FiniteSemigroups().example()
sage: S('a') * S('b')
'ab'
sage: S('a') * S('b') * S('a')
'ab'
sage: S('a') * S('a')
'a'
"""
assert x in self
assert y in self
x = x.value
y = y.value
return self(x + ''.join(c for c in y if c not in x))
@cached_method
def semigroup_generators(self):
r"""
Returns the generators of the semigroup.
EXAMPLES::
sage: S = FiniteSemigroups().example(alphabet=('x','y'))
sage: S.semigroup_generators()
Family ('x', 'y')
"""
return Family([self(i) for i in self.alphabet])
def an_element(self):
r"""
Returns an element of the semigroup.
EXAMPLES::
sage: S = FiniteSemigroups().example()
sage: S.an_element()
'cdab'
sage: S = FiniteSemigroups().example(("b"))
sage: S.an_element()
'b'
"""
return self(''.join(self.alphabet[2:]+self.alphabet[0:2]))
class Element (ElementWrapper):
wrapped_class = str
__lt__ = ElementWrapper._lt_by_value
Example = LeftRegularBand | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/finite_semigroups.py | 0.895306 | 0.496643 | finite_semigroups.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.sets.family import Family
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element_wrapper import ElementWrapper
from sage.categories.all import Monoids
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
class IntegerModMonoid(UniqueRepresentation, Parent):
r"""
An example of a finite monoid: the integers mod `n`
This class illustrates a minimal implementation of a finite monoid.
EXAMPLES::
sage: S = FiniteMonoids().example(); S
An example of a finite multiplicative monoid: the integers modulo 12
sage: S.category()
Category of finitely generated finite enumerated monoids
We conclude by running systematic tests on this monoid::
sage: TestSuite(S).run(verbose = True)
running ._test_an_element() . . . pass
running ._test_associativity() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_construction() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_enumerated_set_contains() . . . pass
running ._test_enumerated_set_iter_cardinality() . . . pass
running ._test_enumerated_set_iter_list() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_one() . . . pass
running ._test_pickling() . . . pass
running ._test_prod() . . . pass
running ._test_some_elements() . . . pass
"""
def __init__(self, n=12):
r"""
EXAMPLES::
sage: M = FiniteMonoids().example(6); M
An example of a finite multiplicative monoid: the integers modulo 6
TESTS::
sage: TestSuite(M).run()
"""
self.n = n
Parent.__init__(self, category=Monoids().Finite().FinitelyGenerated())
def _repr_(self):
r"""
TESTS::
sage: M = FiniteMonoids().example()
sage: M._repr_()
'An example of a finite multiplicative monoid: the integers modulo 12'
"""
return "An example of a finite multiplicative monoid: the integers modulo %s"%self.n
def semigroup_generators(self):
r"""
Returns a set of generators for ``self``, as per
:meth:`Semigroups.ParentMethods.semigroup_generators`.
Currently this returns all integers mod `n`, which is of
course far from optimal!
EXAMPLES::
sage: M = FiniteMonoids().example()
sage: M.semigroup_generators()
Family (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
"""
return Family(tuple(self(ZZ(i)) for i in range(self.n)))
@cached_method
def one(self):
r"""
Return the one of the monoid, as per :meth:`Monoids.ParentMethods.one`.
EXAMPLES::
sage: M = FiniteMonoids().example()
sage: M.one()
1
"""
return self(ZZ.one())
def product(self, x, y):
r"""
Return the product of two elements `x` and `y` of the monoid, as
per :meth:`Semigroups.ParentMethods.product`.
EXAMPLES::
sage: M = FiniteMonoids().example()
sage: M.product(M(3), M(5))
3
"""
return self((x.value * y.value) % self.n)
def an_element(self):
r"""
Returns an element of the monoid, as per :meth:`Sets.ParentMethods.an_element`.
EXAMPLES::
sage: M = FiniteMonoids().example()
sage: M.an_element()
6
"""
return self(ZZ(42) % self.n)
class Element (ElementWrapper):
wrapped_class = Integer
Example = IntegerModMonoid | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/finite_monoids.py | 0.937676 | 0.447762 | finite_monoids.py | pypi |
from sage.structure.parent import Parent
from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
from sage.structure.unique_representation import UniqueRepresentation
from sage.rings.integer import Integer
class NonNegativeIntegers(UniqueRepresentation, Parent):
r"""
An example of infinite enumerated set: the non negative integers
This class provides a minimal implementation of an infinite enumerated set.
EXAMPLES::
sage: NN = InfiniteEnumeratedSets().example()
sage: NN
An example of an infinite enumerated set: the non negative integers
sage: NN.cardinality()
+Infinity
sage: NN.list()
Traceback (most recent call last):
...
NotImplementedError: cannot list an infinite set
sage: NN.element_class
<class 'sage.rings.integer.Integer'>
sage: it = iter(NN)
sage: [next(it), next(it), next(it), next(it), next(it)]
[0, 1, 2, 3, 4]
sage: x = next(it); type(x)
<class 'sage.rings.integer.Integer'>
sage: x.parent()
Integer Ring
sage: x+3
8
sage: NN(15)
15
sage: NN.first()
0
This checks that the different methods of `NN` return consistent
results::
sage: TestSuite(NN).run(verbose = True)
running ._test_an_element() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_construction() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_nonzero_equal() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_enumerated_set_contains() . . . pass
running ._test_enumerated_set_iter_cardinality() . . . pass
running ._test_enumerated_set_iter_list() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
running ._test_some_elements() . . . pass
"""
def __init__(self):
"""
TESTS::
sage: NN = InfiniteEnumeratedSets().example()
sage: NN
An example of an infinite enumerated set: the non negative integers
sage: NN.category()
Category of infinite enumerated sets
sage: TestSuite(NN).run()
"""
Parent.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self):
"""
TESTS::
sage: InfiniteEnumeratedSets().example() # indirect doctest
An example of an infinite enumerated set: the non negative integers
"""
return "An example of an infinite enumerated set: the non negative integers"
def __contains__(self, elt):
"""
EXAMPLES::
sage: NN = InfiniteEnumeratedSets().example()
sage: 1 in NN
True
sage: -1 in NN
False
"""
return Integer(elt) >= Integer(0)
def __iter__(self):
"""
EXAMPLES::
sage: NN = InfiniteEnumeratedSets().example()
sage: g = iter(NN)
sage: next(g), next(g), next(g), next(g)
(0, 1, 2, 3)
"""
i = Integer(0)
while True:
yield self._element_constructor_(i)
i += 1
def __call__(self, elt):
"""
EXAMPLES::
sage: NN = InfiniteEnumeratedSets().example()
sage: NN(3) # indirect doctest
3
sage: NN(3).parent()
Integer Ring
sage: NN(-1)
Traceback (most recent call last):
...
ValueError: Value -1 is not a non negative integer.
"""
if elt in self:
return self._element_constructor_(elt)
raise ValueError("Value %s is not a non negative integer." % (elt))
def an_element(self):
"""
EXAMPLES::
sage: InfiniteEnumeratedSets().example().an_element()
42
"""
return self._element_constructor_(Integer(42))
def next(self, o):
"""
EXAMPLES::
sage: NN = InfiniteEnumeratedSets().example()
sage: NN.next(3)
4
"""
return self._element_constructor_(o+1)
def _element_constructor_(self, i):
"""
The default implementation of _element_constructor_ assumes
that the constructor of the element class takes the parent as
parameter. This is not the case for ``Integer``, so we need to
provide an implementation.
TESTS::
sage: NN = InfiniteEnumeratedSets().example()
sage: x = NN(42); x
42
sage: type(x)
<class 'sage.rings.integer.Integer'>
sage: x.parent()
Integer Ring
"""
return self.element_class(i)
Element = Integer
Example = NonNegativeIntegers | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/infinite_enumerated_sets.py | 0.912062 | 0.535706 | infinite_enumerated_sets.py | pypi |
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element import Element
from sage.categories.cw_complexes import CWComplexes
from sage.sets.family import Family
class Surface(UniqueRepresentation, Parent):
r"""
An example of a CW complex: a (2-dimensional) surface.
This class illustrates a minimal implementation of a CW complex.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example(); X
An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2)
sage: X.category()
Category of finite finite dimensional CW complexes
We conclude by running systematic tests on this manifold::
sage: TestSuite(X).run()
"""
def __init__(self, bdy=(1, 2, 1, 2)):
r"""
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example((1, 2)); X
An example of a CW complex: the surface given by the boundary map (1, 2)
TESTS::
sage: TestSuite(X).run()
"""
self._bdy = bdy
self._edges = frozenset(bdy)
Parent.__init__(self, category=CWComplexes().Finite())
def _repr_(self):
r"""
TESTS::
sage: from sage.categories.cw_complexes import CWComplexes
sage: CWComplexes().example()
An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2)
"""
return "An example of a CW complex: the surface given by the boundary map {}".format(self._bdy)
def cells(self):
"""
Return the cells of ``self``.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example()
sage: C = X.cells()
sage: sorted((d, C[d]) for d in C.keys())
[(0, (0-cell v,)),
(1, (0-cell e1, 0-cell e2)),
(2, (2-cell f,))]
"""
d = {0: (self.element_class(self, 0, 'v'),)}
d[1] = tuple([self.element_class(self, 0, 'e'+str(e)) for e in self._edges])
d[2] = (self.an_element(),)
return Family(d)
def an_element(self):
r"""
Return an element of the CW complex, as per
:meth:`Sets.ParentMethods.an_element`.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example()
sage: X.an_element()
2-cell f
"""
return self.element_class(self, 2, 'f')
class Element(Element):
"""
A cell in a CW complex.
"""
def __init__(self, parent, dim, name):
"""
Initialize ``self``.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example()
sage: f = X.an_element()
sage: TestSuite(f).run()
"""
Element.__init__(self, parent)
self._dim = dim
self._name = name
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example()
sage: X.an_element()
2-cell f
"""
return "{}-cell {}".format(self._dim, self._name)
def __eq__(self, other):
"""
Check equality.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example()
sage: f = X.an_element()
sage: f == X(2, 'f')
True
sage: e1 = X(1, 'e1')
sage: e1 == f
False
"""
return (isinstance(other, Surface.Element)
and self.parent() is other.parent()
and self._dim == other._dim
and self._name == other._name)
def dimension(self):
"""
Return the dimension of ``self``.
EXAMPLES::
sage: from sage.categories.cw_complexes import CWComplexes
sage: X = CWComplexes().example()
sage: f = X.an_element()
sage: f.dimension()
2
"""
return self._dim
Example = Surface | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/categories/examples/cw_complexes.py | 0.955992 | 0.673975 | cw_complexes.py | pypi |
from sage.categories.groups import Groups
from sage.categories.poor_man_map import PoorManMap
from sage.groups.group import Group, AbelianGroup
from sage.monoids.indexed_free_monoid import (IndexedMonoid,
IndexedFreeMonoidElement, IndexedFreeAbelianMonoidElement)
from sage.misc.cachefunc import cached_method
import sage.data_structures.blas_dict as blas
from sage.rings.integer import Integer
from sage.rings.infinity import infinity
from sage.sets.family import Family
class IndexedGroup(IndexedMonoid):
"""
Base class for free (abelian) groups whose generators are indexed
by a set.
TESTS:
We check finite properties::
sage: G = Groups().free(index_set=ZZ)
sage: G.is_finite()
False
sage: G = Groups().free(index_set='abc')
sage: G.is_finite()
False
sage: G = Groups().free(index_set=[])
sage: G.is_finite()
True
::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: G.is_finite()
False
sage: G = Groups().Commutative().free(index_set='abc')
sage: G.is_finite()
False
sage: G = Groups().Commutative().free(index_set=[])
sage: G.is_finite()
True
"""
def order(self):
r"""
Return the number of elements of ``self``, which is `\infty` unless
this is the trivial group.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: G.order()
+Infinity
sage: G = Groups().Commutative().free(index_set='abc')
sage: G.order()
+Infinity
sage: G = Groups().Commutative().free(index_set=[])
sage: G.order()
1
"""
return self.cardinality()
def rank(self):
"""
Return the rank of ``self``.
This is the number of generators of ``self``.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: G.rank()
+Infinity
sage: G = Groups().free(index_set='abc')
sage: G.rank()
3
sage: G = Groups().free(index_set=[])
sage: G.rank()
0
::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: G.rank()
+Infinity
sage: G = Groups().Commutative().free(index_set='abc')
sage: G.rank()
3
sage: G = Groups().Commutative().free(index_set=[])
sage: G.rank()
0
"""
return self.group_generators().cardinality()
@cached_method
def group_generators(self):
"""
Return the group generators of ``self``.
EXAMPLES::
sage: G = Groups.free(index_set=ZZ)
sage: G.group_generators()
Lazy family (Generator map from Integer Ring to
Free group indexed by Integer Ring(i))_{i in Integer Ring}
sage: G = Groups().free(index_set='abcde')
sage: sorted(G.group_generators())
[F['a'], F['b'], F['c'], F['d'], F['e']]
"""
if self._indices.cardinality() == infinity:
gen = PoorManMap(self.gen, domain=self._indices, codomain=self, name="Generator map")
return Family(self._indices, gen)
return Family(self._indices, self.gen)
gens = group_generators
class IndexedFreeGroup(IndexedGroup, Group):
"""
An indexed free group.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: G
Free group indexed by Integer Ring
sage: G = Groups().free(index_set='abcde')
sage: G
Free group indexed by {'a', 'b', 'c', 'd', 'e'}
"""
def __init__(self, indices, prefix, category=None, **kwds):
"""
Initialize ``self``.
TESTS::
sage: G = Groups().free(index_set=ZZ)
sage: TestSuite(G).run()
sage: G = Groups().free(index_set='abc')
sage: TestSuite(G).run()
"""
category = Groups().or_subcategory(category)
IndexedGroup.__init__(self, indices, prefix, category, **kwds)
def _repr_(self):
"""
Return a string representation of ``self``
TESTS::
sage: Groups().free(index_set=ZZ) # indirect doctest
Free group indexed by Integer Ring
"""
return 'Free group indexed by {}'.format(self._indices)
@cached_method
def one(self):
"""
Return the identity element of ``self``.
EXAMPLES::
sage: G = Groups().free(ZZ)
sage: G.one()
1
"""
return self.element_class(self, ())
def gen(self, x):
"""
The generator indexed by ``x`` of ``self``.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: G.gen(0)
F[0]
sage: G.gen(2)
F[2]
"""
if x not in self._indices:
raise IndexError("{} is not in the index set".format(x))
try:
return self.element_class(self, ((self._indices(x),1),))
except TypeError: # Backup (if it is a string)
return self.element_class(self, ((x,1),))
class Element(IndexedFreeMonoidElement):
def __len__(self):
"""
Return the length of ``self``.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: elt = a*c^-3*b^-2*a
sage: elt.length()
7
sage: len(elt)
7
sage: G = Groups().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: elt = a*c^-3*b^-2*a
sage: elt.length()
7
sage: len(elt)
7
"""
return sum(abs(exp) for gen,exp in self._monomial)
length = __len__
def _mul_(self, other):
"""
Multiply ``self`` by ``other``.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: a*b^2*e*d
F[0]*F[1]^2*F[4]*F[3]
sage: (a*b^2*d^2) * (d^-4*b*e)
F[0]*F[1]^2*F[3]^-2*F[1]*F[4]
sage: (a*b^-2*d^2) * (d^-2*b^2*a^-1)
1
"""
if not self._monomial:
return other
if not other._monomial:
return self
ret = list(self._monomial)
rhs = list(other._monomial)
while ret and rhs and ret[-1][0] == rhs[0][0]:
rhs[0] = (rhs[0][0], rhs[0][1] + ret.pop()[1])
if rhs[0][1] == 0:
rhs.pop(0)
ret += rhs
return self.__class__(self.parent(), tuple(ret))
def __invert__(self):
"""
Return the inverse of ``self``.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: x = a*b^2*e^-1*d; ~x
F[3]^-1*F[4]*F[1]^-2*F[0]^-1
sage: x * ~x
1
"""
return self.__class__(self.parent(),
tuple((x[0], -x[1]) for x in reversed(self._monomial)))
def to_word_list(self):
"""
Return ``self`` as a word represented as a list whose entries
are the pairs ``(i, s)`` where ``i`` is the index and ``s`` is
the sign.
EXAMPLES::
sage: G = Groups().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: x = a*b^2*e*a^-1
sage: x.to_word_list()
[(0, 1), (1, 1), (1, 1), (4, 1), (0, -1)]
"""
sign = lambda x: 1 if x > 0 else -1 # It is never 0
return [ (k, sign(e)) for k,e in self._sorted_items()
for dummy in range(abs(e))]
class IndexedFreeAbelianGroup(IndexedGroup, AbelianGroup):
"""
An indexed free abelian group.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: G
Free abelian group indexed by Integer Ring
sage: G = Groups().Commutative().free(index_set='abcde')
sage: G
Free abelian group indexed by {'a', 'b', 'c', 'd', 'e'}
"""
def __init__(self, indices, prefix, category=None, **kwds):
"""
Initialize ``self``.
TESTS::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: TestSuite(G).run()
sage: G = Groups().Commutative().free(index_set='abc')
sage: TestSuite(G).run()
"""
category = Groups().or_subcategory(category)
IndexedGroup.__init__(self, indices, prefix, category, **kwds)
def _repr_(self):
"""
TESTS::
sage: Groups.Commutative().free(index_set=ZZ)
Free abelian group indexed by Integer Ring
"""
return 'Free abelian group indexed by {}'.format(self._indices)
def _element_constructor_(self, x=None):
"""
Create an element of ``self`` from ``x``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: G(G.gen(2))
F[2]
sage: G([[1, 3], [-2, 12]])
F[-2]^12*F[1]^3
sage: G({1: 3, -2: 12})
F[-2]^12*F[1]^3
sage: G(-5)
Traceback (most recent call last):
...
TypeError: unable to convert -5, use gen() instead
TESTS::
sage: G([(1, 3), (1, -5)])
F[1]^-2
sage: G([(42, 0)])
1
sage: G([(42, 3), (42, -3)])
1
sage: G({42: 0})
1
"""
if isinstance(x, (list, tuple)):
d = dict()
for k, v in x:
if k in d:
d[k] += v
else:
d[k] = v
x = d
if isinstance(x, dict):
x = {k: v for k, v in x.items() if v != 0}
return IndexedGroup._element_constructor_(self, x)
@cached_method
def one(self):
"""
Return the identity element of ``self``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: G.one()
1
"""
return self.element_class(self, {})
def gen(self, x):
"""
The generator indexed by ``x`` of ``self``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: G.gen(0)
F[0]
sage: G.gen(2)
F[2]
"""
if x not in self._indices:
raise IndexError("{} is not in the index set".format(x))
try:
return self.element_class(self, {self._indices(x):1})
except TypeError: # Backup (if it is a string)
return self.element_class(self, {x:1})
class Element(IndexedFreeAbelianMonoidElement, IndexedFreeGroup.Element):
def _mul_(self, other):
"""
Multiply ``self`` by ``other``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: a*b^2*e^-1*d
F[0]*F[1]^2*F[3]*F[4]^-1
sage: (a*b^2*d^2) * (d^-4*b^-2*e)
F[0]*F[3]^-2*F[4]
sage: (a*b^-2*d^2) * (d^-2*b^2*a^-1)
1
"""
return self.__class__(self.parent(),
blas.add(self._monomial, other._monomial))
def __invert__(self):
"""
Return the inverse of ``self``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: x = a*b^2*e^-1*d; ~x
F[0]^-1*F[1]^-2*F[3]^-1*F[4]
sage: x * ~x
1
"""
return self ** -1
def __floordiv__(self, a):
"""
Return the division of ``self`` by ``a``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: elt = a*b*c^3*d^2; elt
F[0]*F[1]*F[2]^3*F[3]^2
sage: elt // a
F[1]*F[2]^3*F[3]^2
sage: elt // c
F[0]*F[1]*F[2]^2*F[3]^2
sage: elt // (a*b*d^2)
F[2]^3
sage: elt // a^4
F[0]^-3*F[1]*F[2]^3*F[3]^2
"""
return self * ~a
def __pow__(self, n):
"""
Raise ``self`` to the power of ``n``.
EXAMPLES::
sage: G = Groups().Commutative().free(index_set=ZZ)
sage: a,b,c,d,e = [G.gen(i) for i in range(5)]
sage: x = a*b^2*e^-1*d; x
F[0]*F[1]^2*F[3]*F[4]^-1
sage: x^3
F[0]^3*F[1]^6*F[3]^3*F[4]^-3
sage: x^0
1
sage: x^-3
F[0]^-3*F[1]^-6*F[3]^-3*F[4]^3
"""
if not isinstance(n, (int, Integer)):
raise TypeError("Argument n (= {}) must be an integer".format(n))
if n == 1:
return self
if n == 0:
return self.parent().one()
return self.__class__(self.parent(), {k:v*n for k,v in self._monomial.items()}) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/indexed_free_group.py | 0.845433 | 0.498352 | indexed_free_group.py | pypi |
r"""
Galois groups of field extensions.
We don't necessarily require extensions to be normal, but we do require them to be separable.
When an extension is not normal, the Galois group refers to
the automorphism group of the normal closure.
AUTHORS:
- David Roe (2019): initial version
"""
from sage.groups.perm_gps.permgroup import PermutationGroup, PermutationGroup_generic, PermutationGroup_subgroup
from sage.groups.abelian_gps.abelian_group import AbelianGroup_class, AbelianGroup_subgroup
from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
from sage.misc.lazy_attribute import lazy_attribute
from sage.misc.abstract_method import abstract_method
from sage.misc.cachefunc import cached_method
from sage.structure.category_object import normalize_names
from sage.rings.integer_ring import ZZ
def _alg_key(self, algorithm=None, recompute=False):
r"""
Return a key for use in cached_method calls.
If recompute is false, will cache using ``None`` as the key, so no recomputation will be done.
If recompute is true, will cache by algorithm, yielding a recomputation for each different algorithm.
EXAMPLES::
sage: from sage.groups.galois_group import _alg_key
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: _alg_key(G, algorithm="pari", recompute=True)
'pari'
"""
if recompute:
algorithm = self._get_algorithm(algorithm)
return algorithm
class _GMixin:
r"""
This class provides some methods for Galois groups to be used for both permutation groups
and abelian groups, subgroups and full Galois groups.
It is just intended to provide common functionality between various different Galois group classes.
"""
@lazy_attribute
def _default_algorithm(self):
"""
A string, the default algorithm used for computing the Galois group
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: G._default_algorithm
'pari'
"""
return NotImplemented
@lazy_attribute
def _gcdata(self):
"""
A pair:
- the Galois closure of the top field in the ambient Galois group;
- an embedding of the top field into the Galois closure.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 - 2)
sage: G = K.galois_group()
sage: G._gcdata
(Number Field in ac with defining polynomial x^6 + 108,
Ring morphism:
From: Number Field in a with defining polynomial x^3 - 2
To: Number Field in ac with defining polynomial x^6 + 108
Defn: a |--> -1/36*ac^4 - 1/2*ac)
"""
return NotImplemented
def _get_algorithm(self, algorithm):
r"""
Allows overriding the default algorithm specified at object creation.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: G._get_algorithm(None)
'pari'
sage: G._get_algorithm('magma')
'magma'
"""
return self._default_algorithm if algorithm is None else algorithm
@lazy_attribute
def _galois_closure(self):
r"""
The Galois closure of the top field.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group(names='b')
sage: G._galois_closure
Number Field in b with defining polynomial x^6 + 12*x^4 + 36*x^2 + 140
"""
return self._gcdata[0]
def splitting_field(self):
r"""
The Galois closure of the top field.
EXAMPLES::
sage: K = NumberField(x^3 - x + 1, 'a')
sage: K.galois_group(names='b').splitting_field()
Number Field in b with defining polynomial x^6 - 6*x^4 + 9*x^2 + 23
sage: L = QuadraticField(-23, 'c'); L.galois_group().splitting_field() is L
True
"""
return self._galois_closure
@lazy_attribute
def _gc_map(self):
r"""
The inclusion of the top field into the Galois closure.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group(names='b')
sage: G._gc_map
Ring morphism:
From: Number Field in a with defining polynomial x^3 + 2*x + 2
To: Number Field in b with defining polynomial x^6 + 12*x^4 + 36*x^2 + 140
Defn: a |--> 1/36*b^4 + 5/18*b^2 - 1/2*b + 4/9
"""
return self._gcdata[1]
class _GaloisMixin(_GMixin):
"""
This class provides methods for Galois groups, allowing concrete instances
to inherit from both permutation group and abelian group classes.
"""
@lazy_attribute
def _field(self):
"""
The top field, ie the field whose Galois closure elements of this group act upon.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: G._field
Number Field in a with defining polynomial x^3 + 2*x + 2
"""
return NotImplemented
def _repr_(self):
"""
String representation of this Galois group
EXAMPLES::
sage: from sage.groups.galois_group import GaloisGroup_perm
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: GaloisGroup_perm._repr_(G)
'Galois group of x^3 + 2*x + 2'
"""
f = self._field.defining_polynomial()
return "Galois group of %s" % f
def top_field(self):
r"""
Return the larger of the two fields in the extension defining this Galois group.
Note that this field may not be Galois.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: L = K.galois_closure('b')
sage: GK = K.galois_group()
sage: GK.top_field() is K
True
sage: GL = L.galois_group()
sage: GL.top_field() is L
True
"""
return self._field
@lazy_attribute
def _field_degree(self):
"""
Degree of the top field over its base.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: L.<b> = K.extension(x^2 + 3*a^2 + 8)
sage: GK = K.galois_group()
sage: GL = L.galois_group()
doctest:warning
...
DeprecationWarning: Use .absolute_field().galois_group() if you want the Galois group of the absolute field
See https://trac.sagemath.org/28782 for details.
sage: GK._field_degree
3
Despite the fact that `L` is a relative number field, the Galois group
is computed for the corresponding absolute extension of the rationals.
This behavior may change in the future::
sage: GL._field_degree
6
sage: GL.transitive_label()
'6T2'
sage: GL
Galois group 6T2 ([3]2) with order 6 of x^2 + 3*a^2 + 8
"""
try:
return self._field.degree()
except NotImplementedError: # relative number fields don't support degree
return self._field.absolute_degree()
def transitive_label(self):
r"""
Return the transitive label for the action of this Galois group on the roots of
the defining polynomial of the field extension.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^8 - x^5 + x^4 - x^3 + 1)
sage: G = K.galois_group()
sage: G.transitive_label()
'8T44'
"""
return "%sT%s" % (self._field_degree, self.transitive_number())
def is_galois(self):
r"""
Return whether the top field is Galois over its base.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^8 - x^5 + x^4 - x^3 + 1)
sage: G = K.galois_group()
sage: from sage.groups.galois_group import GaloisGroup_perm
sage: GaloisGroup_perm.is_galois(G)
False
"""
return self.order() == self._field_degree
class _SubGaloisMixin(_GMixin):
"""
This class provides methods for subgroups of Galois groups, allowing concrete instances
to inherit from both permutation group and abelian group classes.
"""
@lazy_attribute
def _ambient_group(self):
"""
The ambient Galois group of which this is a subgroup.
EXAMPLES::
sage: L.<a> = NumberField(x^4 + 1)
sage: G = L.galois_group()
sage: H = G.decomposition_group(L.primes_above(3)[0])
sage: H._ambient_group is G
True
"""
return NotImplemented
@abstract_method(optional=True)
def fixed_field(self, name=None, polred=None, threshold=None):
"""
Return the fixed field of this subgroup (as a subfield of the Galois closure).
INPUT:
- ``name`` -- a variable name for the new field.
- ``polred`` -- whether to optimize the generator of the newly created field
for a simpler polynomial, using pari's polredbest.
Defaults to ``True`` when the degree of the fixed field is at most 8.
- ``threshold`` -- positive number; polred only performed if the cost is at most this threshold
EXAMPLES::
sage: k.<a> = GF(3^12)
sage: g = k.galois_group()([8])
sage: k0, embed = g.fixed_field()
sage: k0.cardinality()
81
"""
@lazy_attribute
def _gcdata(self):
"""
The Galois closure data is just that of the ambient group.
EXAMPLES::
sage: L.<a> = NumberField(x^4 + 1)
sage: G = L.galois_group()
sage: H = G.decomposition_group(L.primes_above(3)[0])
sage: H.splitting_field() # indirect doctest
Number Field in a with defining polynomial x^4 + 1
"""
return self._ambient_group._gcdata
class GaloisGroup_perm(_GaloisMixin, PermutationGroup_generic):
r"""
The group of automorphisms of a Galois closure of a given field.
INPUT:
- ``field`` -- a field, separable over its base
- ``names`` -- a string or tuple of length 1, giving a variable name for the splitting field
- ``gc_numbering`` -- boolean, whether to express permutations in terms of the
roots of the defining polynomial of the splitting field (versus the defining polynomial
of the original extension). The default value may vary based on the type of field.
"""
@abstract_method
def transitive_number(self, algorithm=None, recompute=False):
"""
The transitive number (as in the GAP and Magma databases of transitive groups)
for the action on the roots of the defining polynomial of the top field.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: G.transitive_number()
2
"""
@lazy_attribute
def _gens(self):
"""
The generators of this Galois group as permutations of the roots. It's important that this
be computed lazily, since it's often possible to compute other attributes (such as the order
or transitive number) more cheaply.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^5-2)
sage: G = K.galois_group(gc_numbering=False)
sage: G._gens
[(1,2,3,5), (1,4,3,2,5)]
"""
return NotImplemented
def __init__(self, field, algorithm=None, names=None, gc_numbering=False):
r"""
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^3 + 2*x + 2)
sage: G = K.galois_group()
sage: TestSuite(G).run()
"""
self._field = field
self._default_algorithm = algorithm
self._base = field.base_field()
self._gc_numbering = gc_numbering
if names is None:
# add a c for Galois closure
names = field.variable_name() + 'c'
self._gc_names = normalize_names(1, names)
# We do only the parts of the initialization of PermutationGroup_generic
# that don't depend on _gens
from sage.categories.permutation_groups import PermutationGroups
category = PermutationGroups().FinitelyGenerated().Finite()
# Note that we DON'T call the __init__ method for PermutationGroup_generic
# Instead, the relevant attributes are computed lazily
super(PermutationGroup_generic, self).__init__(category=category)
@lazy_attribute
def _deg(self):
r"""
The number of moved points in the permutation representation.
This will be the degree of the original number field if `_gc_numbering``
is ``False``, or the degree of the Galois closure otherwise.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^5-2)
sage: G = K.galois_group(gc_numbering=False); G
Galois group 5T3 (5:4) with order 20 of x^5 - 2
sage: G._deg
5
sage: G = K.galois_group(gc_numbering=True); G._deg
20
"""
if self._gc_numbering:
return self.order()
else:
try:
return self._field.degree()
except NotImplementedError: # relative number fields don't support degree
return self._field.relative_degree()
@lazy_attribute
def _domain(self):
r"""
The integers labeling the roots on which this Galois group acts.
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^5-2)
sage: G = K.galois_group(gc_numbering=False); G
Galois group 5T3 (5:4) with order 20 of x^5 - 2
sage: G._domain
{1, 2, 3, 4, 5}
sage: G = K.galois_group(gc_numbering=True); G._domain
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
"""
return FiniteEnumeratedSet(range(1, self._deg+1))
@lazy_attribute
def _domain_to_gap(self):
r"""
Dictionary implementing the identity (used by PermutationGroup_generic).
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^5-2)
sage: G = K.galois_group(gc_numbering=False)
sage: G._domain_to_gap[5]
5
"""
return dict((key, i+1) for i, key in enumerate(self._domain))
@lazy_attribute
def _domain_from_gap(self):
r"""
Dictionary implementing the identity (used by PermutationGroup_generic).
EXAMPLES::
sage: R.<x> = ZZ[]
sage: K.<a> = NumberField(x^5-2)
sage: G = K.galois_group(gc_numbering=True)
sage: G._domain_from_gap[20]
20
"""
return dict((i+1, key) for i, key in enumerate(self._domain))
def ngens(self):
r"""
Number of generators of this Galois group
EXAMPLES::
sage: QuadraticField(-23, 'a').galois_group().ngens()
1
"""
return len(self._gens)
class GaloisGroup_ab(_GaloisMixin, AbelianGroup_class):
r"""
Abelian Galois groups
"""
def __init__(self, field, generator_orders, algorithm=None, gen_names='sigma'):
r"""
Initialize this Galois group.
TESTS::
sage: TestSuite(GF(9).galois_group()).run()
"""
self._field = field
self._default_algorithm = algorithm
AbelianGroup_class.__init__(self, generator_orders, gen_names)
def is_galois(self):
r"""
Abelian extensions are Galois.
For compatibility with Galois groups of number fields.
EXAMPLES::
sage: GF(9).galois_group().is_galois()
True
"""
return True
@lazy_attribute
def _gcdata(self):
r"""
Return the Galois closure (ie, the finite field itself) together with the identity
EXAMPLES::
sage: GF(3^2).galois_group()._gcdata
(Finite Field in z2 of size 3^2,
Identity endomorphism of Finite Field in z2 of size 3^2)
"""
k = self._field
return k, k.Hom(k).identity()
@cached_method
def permutation_group(self):
r"""
Return a permutation group giving the action on the roots of a defining polynomial.
This is the regular representation for the abelian group, which is not necessarily the smallest degree permutation representation.
EXAMPLES::
sage: GF(3^10).galois_group().permutation_group()
Permutation Group with generators [(1,2,3,4,5,6,7,8,9,10)]
"""
return PermutationGroup(gap_group=self._gap_().RegularActionHomomorphism().Image())
@cached_method(key=_alg_key)
def transitive_number(self, algorithm=None, recompute=False):
r"""
Return the transitive number for the action on the roots of the defining polynomial.
For abelian groups, there is only one transitive action up to isomorphism
(left multiplication of the group on itself), so we identify that action.
EXAMPLES::
sage: from sage.groups.galois_group import GaloisGroup_ab
sage: Gtest = GaloisGroup_ab(field=None, generator_orders=(2,2,4))
sage: Gtest.transitive_number()
2
"""
return ZZ(self.permutation_group()._gap_().TransitiveIdentification())
class GaloisGroup_cyc(GaloisGroup_ab):
r"""
Cyclic Galois groups
"""
def transitive_number(self, algorithm=None, recompute=False):
r"""
Return the transitive number for the action on the roots of the defining polynomial.
EXAMPLES::
sage: GF(2^8).galois_group().transitive_number()
1
sage: GF(3^32).galois_group().transitive_number()
33
sage: GF(2^60).galois_group().transitive_number()
Traceback (most recent call last):
...
NotImplementedError: transitive database only computed up to degree 47
"""
d = self.order()
if d > 47:
raise NotImplementedError("transitive database only computed up to degree 47")
elif d == 32:
# I don't know why this case is special, but you can check this in Magma (GAP only goes up to 22)
return ZZ(33)
else:
return ZZ(1)
def signature(self):
r"""
Return 1 if contained in the alternating group, -1 otherwise.
EXAMPLES::
sage: GF(3^2).galois_group().signature()
-1
sage: GF(3^3).galois_group().signature()
1
"""
return ZZ(1) if (self._field.degree() % 2) else ZZ(-1)
class GaloisSubgroup_perm(PermutationGroup_subgroup, _SubGaloisMixin):
"""
Subgroups of Galois groups (implemented as permutation groups), specified
by giving a list of generators.
Unlike ambient Galois groups, where we use a lazy ``_gens`` attribute in order
to enable creation without determining a list of generators,
we require that generators for a subgroup be specified during initialization,
as specified in the ``__init__`` method of permutation subgroups.
"""
pass
class GaloisSubgroup_ab(AbelianGroup_subgroup, _SubGaloisMixin):
"""
Subgroups of abelian Galois groups.
"""
pass
GaloisGroup_perm.Subgroup = GaloisSubgroup_perm
GaloisGroup_ab.Subgroup = GaloisSubgroup_ab | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/galois_group.py | 0.870625 | 0.580411 | galois_group.py | pypi |
r"""
PARI Groups
See :pari:`polgalois` for the PARI documentation of these objects.
"""
from sage.libs.pari import pari
from sage.rings.integer import Integer
from sage.groups.perm_gps.permgroup_named import TransitiveGroup
class PariGroup():
def __init__(self, x, degree):
"""
EXAMPLES::
sage: PariGroup([6, -1, 2, "S3"], 3)
PARI group [6, -1, 2, S3] of degree 3
sage: R.<x> = PolynomialRing(QQ)
sage: f = x^4 - 17*x^3 - 2*x + 1
sage: G = f.galois_group(pari_group=True); G
PARI group [24, -1, 5, "S4"] of degree 4
"""
self.__x = pari(x)
self.__degree = Integer(degree)
def __repr__(self):
"""
String representation of this group
EXAMPLES::
sage: PariGroup([6, -1, 2, "S3"], 3)
PARI group [6, -1, 2, S3] of degree 3
"""
return "PARI group %s of degree %s" % (self.__x, self.__degree)
def __eq__(self, other):
"""
Test equality.
EXAMPLES::
sage: R.<x> = PolynomialRing(QQ)
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: f2 = x^3 - x - 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G2 = f2.galois_group(pari_group=True)
sage: G1 == G1
True
sage: G1 == G2
False
"""
return (isinstance(other, PariGroup) and
(self.__x, self.__degree) == (other.__x, other.__degree))
def __ne__(self, other):
"""
Test inequality.
EXAMPLES::
sage: R.<x> = PolynomialRing(QQ)
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: f2 = x^3 - x - 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G2 = f2.galois_group(pari_group=True)
sage: G1 != G1
False
sage: G1 != G2
True
"""
return not (self == other)
def __pari__(self):
"""
TESTS::
sage: G = PariGroup([6, -1, 2, "S3"], 3)
sage: pari(G)
[6, -1, 2, S3]
"""
return self.__x
def degree(self):
"""
Return the degree of this group.
EXAMPLES::
sage: R.<x> = PolynomialRing(QQ)
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G1.degree()
4
"""
return self.__degree
def signature(self):
"""
Return 1 if contained in the alternating group, -1 otherwise.
EXAMPLES::
sage: R.<x> = QQ[]
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G1.signature()
-1
"""
return Integer(self.__x[1])
def transitive_number(self):
"""
If the transitive label is nTk, return `k`.
EXAMPLES::
sage: R.<x> = QQ[]
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G1.transitive_number()
5
"""
return Integer(self.__x[2])
def label(self):
"""
Return the human readable description for this group generated by Pari.
EXAMPLES::
sage: R.<x> = QQ[]
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G1.label()
'S4'
"""
return str(self.__x[3])
def order(self):
"""
Return the order of ``self``.
EXAMPLES::
sage: R.<x> = PolynomialRing(QQ)
sage: f1 = x^4 - 17*x^3 - 2*x + 1
sage: G1 = f1.galois_group(pari_group=True)
sage: G1.order()
24
"""
return Integer(self.__x[0])
cardinality = order
def permutation_group(self):
"""
Return the corresponding GAP transitive group
EXAMPLES::
sage: R.<x> = QQ[]
sage: f = x^8 - x^5 + x^4 - x^3 + 1
sage: G = f.galois_group(pari_group=True)
sage: G.permutation_group()
Transitive group number 44 of degree 8
"""
return TransitiveGroup(self.__degree, self.__x[2])
_permgroup_ = permutation_group | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/pari_group.py | 0.894182 | 0.617051 | pari_group.py | pypi |
from sage.groups.group import Group
from sage.groups.libgap_wrapper import ParentLibGAP, ElementLibGAP
from sage.groups.libgap_mixin import GroupMixinLibGAP
from sage.structure.unique_representation import UniqueRepresentation
from sage.libs.gap.libgap import libgap
from sage.libs.gap.element import GapElement
from sage.misc.cachefunc import cached_method
from sage.groups.free_group import FreeGroupElement
from sage.functions.generalized import sign
from sage.matrix.constructor import matrix
from sage.categories.morphism import SetMorphism
class GroupMorphismWithGensImages(SetMorphism):
r"""
Class used for morphisms from finitely presented groups to
other groups. It just adds the images of the generators at the
end of the representation.
EXAMPLES::
sage: F = FreeGroup(3)
sage: G = F / [F([1, 2, 3, 1, 2, 3]), F([1, 1, 1])]
sage: H = AlternatingGroup(3)
sage: HS = G.Hom(H)
sage: from sage.groups.finitely_presented import GroupMorphismWithGensImages
sage: GroupMorphismWithGensImages(HS, lambda a: H.one())
Generic morphism:
From: Finitely presented group < x0, x1, x2 | (x0*x1*x2)^2, x0^3 >
To: Alternating group of order 3!/2 as a permutation group
Defn: x0 |--> ()
x1 |--> ()
x2 |--> ()
"""
def _repr_defn(self):
r"""
Return the part of the representation that includes the images of the generators.
EXAMPLES::
sage: F = FreeGroup(3)
sage: G = F / [F([1,2,3,1,2,3]),F([1,1,1])]
sage: H = AlternatingGroup(3)
sage: HS = G.Hom(H)
sage: from sage.groups.finitely_presented import GroupMorphismWithGensImages
sage: f = GroupMorphismWithGensImages(HS, lambda a: H.one())
sage: f._repr_defn()
'x0 |--> ()\nx1 |--> ()\nx2 |--> ()'
"""
D = self.domain()
return '\n'.join(['%s |--> %s'%(i, self(i)) for\
i in D.gens()])
class FinitelyPresentedGroupElement(FreeGroupElement):
"""
A wrapper of GAP's Finitely Presented Group elements.
The elements are created by passing the Tietze list that determines them.
EXAMPLES::
sage: G = FreeGroup('a, b')
sage: H = G / [G([1]), G([2, 2, 2])]
sage: H([1, 2, 1, -1])
a*b
sage: H([1, 2, 1, -2])
a*b*a*b^-1
sage: x = H([1, 2, -1, -2])
sage: x
a*b*a^-1*b^-1
sage: y = H([2, 2, 2, 1, -2, -2, -2])
sage: y
b^3*a*b^-3
sage: x*y
a*b*a^-1*b^2*a*b^-3
sage: x^(-1)
b*a*b^-1*a^-1
"""
def __init__(self, parent, x, check=True):
"""
The Python constructor.
See :class:`FinitelyPresentedGroupElement` for details.
TESTS::
sage: G = FreeGroup('a, b')
sage: H = G / [G([1]), G([2, 2, 2])]
sage: H([1, 2, 1, -1])
a*b
sage: TestSuite(G).run()
sage: TestSuite(H).run()
sage: G.<a,b> = FreeGroup()
sage: H = G / (G([1]), G([2, 2, 2]))
sage: x = H([1, 2, -1, -2])
sage: TestSuite(x).run()
sage: TestSuite(G.one()).run()
"""
if not isinstance(x, GapElement):
F = parent.free_group()
free_element = F(x)
fp_family = parent.gap().Identity().FamilyObj()
x = libgap.ElementOfFpGroup(fp_family, free_element.gap())
ElementLibGAP.__init__(self, parent, x)
def __reduce__(self):
"""
Used in pickling.
TESTS::
sage: F.<a,b> = FreeGroup()
sage: G = F / [a*b, a^2]
sage: G.inject_variables()
Defining a, b
sage: a.__reduce__()
(Finitely presented group < a, b | a*b, a^2 >, ((1,),))
sage: (a*b*a^-1).__reduce__()
(Finitely presented group < a, b | a*b, a^2 >, ((1, 2, -1),))
sage: F.<a,b,c> = FreeGroup('a, b, c')
sage: G = F.quotient([a*b*c/(b*c*a), a*b*c/(c*a*b)])
sage: G.inject_variables()
Defining a, b, c
sage: x = a*b*c
sage: x.__reduce__()
(Finitely presented group < a, b, c | a*b*c*a^-1*c^-1*b^-1, a*b*c*b^-1*a^-1*c^-1 >,
((1, 2, 3),))
"""
return (self.parent(), tuple([self.Tietze()]))
def _repr_(self):
"""
Return a string representation.
OUTPUT:
String.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: H = G / [a^2, b^3]
sage: H.gen(0)
a
sage: H.gen(0)._repr_()
'a'
sage: H.one()
1
"""
# computing that an element is actually one can be very expensive
if self.Tietze() == ():
return '1'
else:
return self.gap()._repr_()
@cached_method
def Tietze(self):
"""
Return the Tietze list of the element.
The Tietze list of a word is a list of integers that represent
the letters in the word. A positive integer `i` represents
the letter corresponding to the `i`-th generator of the group.
Negative integers represent the inverses of generators.
OUTPUT:
A tuple of integers.
EXAMPLES::
sage: G = FreeGroup('a, b')
sage: H = G / (G([1]), G([2, 2, 2]))
sage: H.inject_variables()
Defining a, b
sage: a.Tietze()
(1,)
sage: x = a^2*b^(-3)*a^(-2)
sage: x.Tietze()
(1, 1, -2, -2, -2, -1, -1)
"""
tl = self.gap().UnderlyingElement().TietzeWordAbstractWord()
return tuple(tl.sage())
def __call__(self, *values, **kwds):
"""
Replace the generators of the free group with ``values``.
INPUT:
- ``*values`` -- a list/tuple/iterable of the same length as
the number of generators.
- ``check=True`` -- boolean keyword (default:
``True``). Whether to verify that ``values`` satisfy the
relations in the finitely presented group.
OUTPUT:
The product of ``values`` in the order and with exponents
specified by ``self``.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: H = G / [a/b]; H
Finitely presented group < a, b | a*b^-1 >
sage: H.simplified()
Finitely presented group < a | >
The generator `b` can be eliminated using the relation `a=b`. Any
values that you plug into a word must satisfy this relation::
sage: A, B = H.gens()
sage: w = A^2 * B
sage: w(2,2)
8
sage: w(3,3)
27
sage: w(1,2)
Traceback (most recent call last):
...
ValueError: the values do not satisfy all relations of the group
sage: w(1, 2, check=False) # result depends on presentation of the group element
2
"""
values = list(values)
if kwds.get('check', True):
for rel in self.parent().relations():
rel = rel(values)
if rel != 1:
raise ValueError('the values do not satisfy all relations of the group')
return super().__call__(values)
def wrap_FpGroup(libgap_fpgroup):
"""
Wrap a GAP finitely presented group.
This function changes the comparison method of
``libgap_free_group`` to comparison by Python ``id``. If you want
to put the LibGAP free group into a container ``(set, dict)`` then you
should understand the implications of
:meth:`~sage.libs.gap.element.GapElement._set_compare_by_id`. To
be safe, it is recommended that you just work with the resulting
Sage :class:`FinitelyPresentedGroup`.
INPUT:
- ``libgap_fpgroup`` -- a LibGAP finitely presented group
OUTPUT:
A Sage :class:`FinitelyPresentedGroup`.
EXAMPLES:
First construct a LibGAP finitely presented group::
sage: F = libgap.FreeGroup(['a', 'b'])
sage: a_cubed = F.GeneratorsOfGroup()[0] ^ 3
sage: P = F / libgap([ a_cubed ]); P
<fp group of size infinity on the generators [ a, b ]>
sage: type(P)
<class 'sage.libs.gap.element.GapElement'>
Now wrap it::
sage: from sage.groups.finitely_presented import wrap_FpGroup
sage: wrap_FpGroup(P)
Finitely presented group < a, b | a^3 >
"""
assert libgap_fpgroup.IsFpGroup()
libgap_fpgroup._set_compare_by_id()
from sage.groups.free_group import wrap_FreeGroup
free_group = wrap_FreeGroup(libgap_fpgroup.FreeGroupOfFpGroup())
relations = tuple( free_group(rel.UnderlyingElement())
for rel in libgap_fpgroup.RelatorsOfFpGroup() )
return FinitelyPresentedGroup(free_group, relations)
class RewritingSystem():
"""
A class that wraps GAP's rewriting systems.
A rewriting system is a set of rules that allow to transform
one word in the group to an equivalent one.
If the rewriting system is confluent, then the transformed
word is a unique reduced form of the element of the group.
.. WARNING::
Note that the process of making a rewriting system confluent
might not end.
INPUT:
- ``G`` -- a group
REFERENCES:
- :wikipedia:`Knuth-Bendix_completion_algorithm`
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: G = F / [a*b/a/b]
sage: k = G.rewriting_system()
sage: k
Rewriting system of Finitely presented group < a, b | a*b*a^-1*b^-1 >
with rules:
a*b*a^-1*b^-1 ---> 1
sage: k.reduce(a*b*a*b)
(a*b)^2
sage: k.make_confluent()
sage: k
Rewriting system of Finitely presented group < a, b | a*b*a^-1*b^-1 >
with rules:
b^-1*a^-1 ---> a^-1*b^-1
b^-1*a ---> a*b^-1
b*a^-1 ---> a^-1*b
b*a ---> a*b
sage: k.reduce(a*b*a*b)
a^2*b^2
.. TODO::
- Include support for different orderings (currently only shortlex
is used).
- Include the GAP package kbmag for more functionalities, including
automatic structures and faster compiled functions.
AUTHORS:
- Miguel Angel Marco Buzunariz (2013-12-16)
"""
def __init__(self, G):
"""
Initialize ``self``.
EXAMPLES::
sage: F.<a,b,c> = FreeGroup()
sage: G = F / [a^2, b^3, c^5]
sage: k = G.rewriting_system()
sage: k
Rewriting system of Finitely presented group < a, b, c | a^2, b^3, c^5 >
with rules:
a^2 ---> 1
b^3 ---> 1
c^5 ---> 1
"""
self._free_group = G.free_group()
self._fp_group = G
self._fp_group_gap = G.gap()
self._monoid_isomorphism = self._fp_group_gap.IsomorphismFpMonoid()
self._monoid = self._monoid_isomorphism.Image()
self._gap = self._monoid.KnuthBendixRewritingSystem()
def __repr__(self):
"""
Return a string representation.
EXAMPLES::
sage: F.<a> = FreeGroup()
sage: G = F / [a^2]
sage: k = G.rewriting_system()
sage: k
Rewriting system of Finitely presented group < a | a^2 >
with rules:
a^2 ---> 1
"""
ret = "Rewriting system of {}\nwith rules:".format(self._fp_group)
for i in sorted(self.rules().items()): # Make sure they are sorted to the repr is unique
ret += "\n {} ---> {}".format(i[0], i[1])
return ret
def free_group(self):
"""
The free group after which the rewriting system is defined
EXAMPLES::
sage: F = FreeGroup(3)
sage: G = F / [ [1,2,3], [-1,-2,-3] ]
sage: k = G.rewriting_system()
sage: k.free_group()
Free Group on generators {x0, x1, x2}
"""
return self._free_group
def finitely_presented_group(self):
"""
The finitely presented group where the rewriting system is defined.
EXAMPLES::
sage: F = FreeGroup(3)
sage: G = F / [ [1,2,3], [-1,-2,-3], [1,1], [2,2] ]
sage: k = G.rewriting_system()
sage: k.make_confluent()
sage: k
Rewriting system of Finitely presented group < x0, x1, x2 | x0*x1*x2, x0^-1*x1^-1*x2^-1, x0^2, x1^2 >
with rules:
x0^-1 ---> x0
x1^-1 ---> x1
x2^-1 ---> x2
x0^2 ---> 1
x0*x1 ---> x2
x0*x2 ---> x1
x1*x0 ---> x2
x1^2 ---> 1
x1*x2 ---> x0
x2*x0 ---> x1
x2*x1 ---> x0
x2^2 ---> 1
sage: k.finitely_presented_group()
Finitely presented group < x0, x1, x2 | x0*x1*x2, x0^-1*x1^-1*x2^-1, x0^2, x1^2 >
"""
return self._fp_group
def reduce(self, element):
"""
Applies the rules in the rewriting system to the element, to obtain
a reduced form.
If the rewriting system is confluent, this reduced form is unique
for all words representing the same element.
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: G = F/[a^2, b^3, (a*b/a)^3, b*a*b*a]
sage: k = G.rewriting_system()
sage: k.reduce(b^4)
b
sage: k.reduce(a*b*a)
a*b*a
"""
eg = self._fp_group(element).gap()
egim = self._monoid_isomorphism.Image(eg)
red = self.gap().ReducedForm(egim.UnderlyingElement())
redfpmon = self._monoid.One().FamilyObj().ElementOfFpMonoid(red)
reducfpgr = self._monoid_isomorphism.PreImagesRepresentative(redfpmon)
tz = reducfpgr.UnderlyingElement().TietzeWordAbstractWord(self._free_group.gap().GeneratorsOfGroup())
return self._fp_group(tz.sage())
def gap(self):
"""
The gap representation of the rewriting system.
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: G = F/[a*a,b*b]
sage: k = G.rewriting_system()
sage: k.gap()
Knuth Bendix Rewriting System for Monoid( [ a, A, b, B ] ) with rules
[ [ a^2, <identity ...> ], [ a*A, <identity ...> ],
[ A*a, <identity ...> ], [ b^2, <identity ...> ],
[ b*B, <identity ...> ], [ B*b, <identity ...> ] ]
"""
return self._gap
def rules(self):
"""
Return the rules that form the rewriting system.
OUTPUT:
A dictionary containing the rules of the rewriting system.
Each key is a word in the free group, and its corresponding
value is the word to which it is reduced.
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: G = F / [a*a*a,b*b*a*a]
sage: k = G.rewriting_system()
sage: k
Rewriting system of Finitely presented group < a, b | a^3, b^2*a^2 >
with rules:
a^3 ---> 1
b^2*a^2 ---> 1
sage: k.rules()
{a^3: 1, b^2*a^2: 1}
sage: k.make_confluent()
sage: sorted(k.rules().items())
[(a^-2, a), (a^-1*b^-1, a*b), (a^-1*b, b^-1), (a^2, a^-1),
(a*b^-1, b), (b^-1*a^-1, a*b), (b^-1*a, b), (b^-2, a^-1),
(b*a^-1, b^-1), (b*a, a*b), (b^2, a)]
"""
dic = {}
grules = self.gap().Rules()
for i in grules:
a, b = i
afpmon = self._monoid.One().FamilyObj().ElementOfFpMonoid(a)
afg = self._monoid_isomorphism.PreImagesRepresentative(afpmon)
atz = afg.UnderlyingElement().TietzeWordAbstractWord(self._free_group.gap().GeneratorsOfGroup())
af = self._free_group(atz.sage())
if len(af.Tietze()) != 0:
bfpmon = self._monoid.One().FamilyObj().ElementOfFpMonoid(b)
bfg = self._monoid_isomorphism.PreImagesRepresentative(bfpmon)
btz = bfg.UnderlyingElement().TietzeWordAbstractWord(self._free_group.gap().GeneratorsOfGroup())
bf = self._free_group(btz.sage())
dic[af]=bf
return dic
def is_confluent(self):
"""
Return ``True`` if the system is confluent and ``False`` otherwise.
EXAMPLES::
sage: F = FreeGroup(3)
sage: G = F / [F([1,2,1,2,1,3,-1]),F([2,2,2,1,1,2]),F([1,2,3])]
sage: k = G.rewriting_system()
sage: k.is_confluent()
False
sage: k
Rewriting system of Finitely presented group < x0, x1, x2 | (x0*x1)^2*x0*x2*x0^-1, x1^3*x0^2*x1, x0*x1*x2 >
with rules:
x0*x1*x2 ---> 1
x1^3*x0^2*x1 ---> 1
(x0*x1)^2*x0*x2*x0^-1 ---> 1
sage: k.make_confluent()
sage: k.is_confluent()
True
sage: k
Rewriting system of Finitely presented group < x0, x1, x2 | (x0*x1)^2*x0*x2*x0^-1, x1^3*x0^2*x1, x0*x1*x2 >
with rules:
x0^-1 ---> x0
x1^-1 ---> x1
x0^2 ---> 1
x0*x1 ---> x2^-1
x0*x2^-1 ---> x1
x1*x0 ---> x2
x1^2 ---> 1
x1*x2^-1 ---> x0*x2
x1*x2 ---> x0
x2^-1*x0 ---> x0*x2
x2^-1*x1 ---> x0
x2^-2 ---> x2
x2*x0 ---> x1
x2*x1 ---> x0*x2
x2^2 ---> x2^-1
"""
return self._gap.IsConfluent().sage()
def make_confluent(self):
"""
Applies Knuth-Bendix algorithm to try to transform the rewriting
system into a confluent one.
Note that this method does not return any object, just changes the
rewriting system internally.
.. WARNING::
This algorithm is not granted to finish. Although it may be useful
in some occasions to run it, interrupt it manually after some time
and use then the transformed rewriting system. Even if it is not
confluent, it could be used to reduce some words.
ALGORITHM:
Uses GAP's ``MakeConfluent``.
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: G = F / [a^2,b^3,(a*b/a)^3,b*a*b*a]
sage: k = G.rewriting_system()
sage: k
Rewriting system of Finitely presented group < a, b | a^2, b^3, a*b^3*a^-1, (b*a)^2 >
with rules:
a^2 ---> 1
b^3 ---> 1
(b*a)^2 ---> 1
a*b^3*a^-1 ---> 1
sage: k.make_confluent()
sage: k
Rewriting system of Finitely presented group < a, b | a^2, b^3, a*b^3*a^-1, (b*a)^2 >
with rules:
a^-1 ---> a
a^2 ---> 1
b^-1*a ---> a*b
b^-2 ---> b
b*a ---> a*b^-1
b^2 ---> b^-1
"""
try:
self._gap.MakeConfluent()
except ValueError:
raise ValueError('could not make the system confluent')
class FinitelyPresentedGroup(GroupMixinLibGAP, UniqueRepresentation,
Group, ParentLibGAP):
"""
A class that wraps GAP's Finitely Presented Groups.
.. WARNING::
You should use
:meth:`~sage.groups.free_group.FreeGroup_class.quotient` to
construct finitely presented groups as quotients of free
groups.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: H = G / [a, b^3]
sage: H
Finitely presented group < a, b | a, b^3 >
sage: H.gens()
(a, b)
sage: F.<a,b> = FreeGroup('a, b')
sage: J = F / (F([1]), F([2, 2, 2]))
sage: J is H
True
sage: G = FreeGroup(2)
sage: H = G / (G([1, 1]), G([2, 2, 2]))
sage: H.gens()
(x0, x1)
sage: H.gen(0)
x0
sage: H.ngens()
2
sage: H.gap()
<fp group on the generators [ x0, x1 ]>
sage: type(_)
<class 'sage.libs.gap.element.GapElement'>
"""
Element = FinitelyPresentedGroupElement
def __init__(self, free_group, relations, category=None):
"""
The Python constructor.
TESTS::
sage: G = FreeGroup('a, b')
sage: H = G / (G([1]), G([2])^3)
sage: H
Finitely presented group < a, b | a, b^3 >
sage: F = FreeGroup('a, b')
sage: J = F / (F([1]), F([2, 2, 2]))
sage: J is H
True
sage: TestSuite(H).run()
sage: TestSuite(J).run()
"""
from sage.groups.free_group import is_FreeGroup
assert is_FreeGroup(free_group)
assert isinstance(relations, tuple)
self._free_group = free_group
self._relations = relations
self._assign_names(free_group.variable_names())
parent_gap = free_group.gap() / libgap([rel.gap() for rel in relations])
ParentLibGAP.__init__(self, parent_gap)
Group.__init__(self, category=category)
def _repr_(self):
"""
Return a string representation.
OUTPUT:
String.
TESTS::
sage: G.<a,b> = FreeGroup()
sage: H = G / (G([1]), G([2])^3)
sage: H # indirect doctest
Finitely presented group < a, b | a, b^3 >
sage: H._repr_()
'Finitely presented group < a, b | a, b^3 >'
"""
gens = ', '.join(self.variable_names())
rels = ', '.join([ str(r) for r in self.relations() ])
return 'Finitely presented group ' + '< '+ gens + ' | ' + rels + ' >'
def _latex_(self):
"""
Return a LaTeX representation
OUTPUT:
String. A valid LaTeX math command sequence.
TESTS::
sage: F = FreeGroup(4)
sage: F.inject_variables()
Defining x0, x1, x2, x3
sage: G = F.quotient([x0*x2, x3*x1*x3, x2*x1*x2])
sage: G._latex_()
'\\langle x_{0}, x_{1}, x_{2}, x_{3} \\mid x_{0}\\cdot x_{2} , x_{3}\\cdot x_{1}\\cdot x_{3} , x_{2}\\cdot x_{1}\\cdot x_{2}\\rangle'
"""
r = '\\langle '
for i in range(self.ngens()):
r = r+self.gen(i)._latex_()
if i < self.ngens()-1:
r = r+', '
r = r+' \\mid '
for i in range(len(self._relations)):
r = r+(self._relations)[i]._latex_()
if i < len(self.relations())-1:
r = r+' , '
r = r+'\\rangle'
return r
def free_group(self):
"""
Return the free group (without relations).
OUTPUT:
A :func:`~sage.groups.free_group.FreeGroup`.
EXAMPLES::
sage: G.<a,b,c> = FreeGroup()
sage: H = G / (a^2, b^3, a*b*~a*~b)
sage: H.free_group()
Free Group on generators {a, b, c}
sage: H.free_group() is G
True
"""
return self._free_group
def relations(self):
"""
Return the relations of the group.
OUTPUT:
The relations as a tuple of elements of :meth:`free_group`.
EXAMPLES::
sage: F = FreeGroup(5, 'x')
sage: F.inject_variables()
Defining x0, x1, x2, x3, x4
sage: G = F.quotient([x0*x2, x3*x1*x3, x2*x1*x2])
sage: G.relations()
(x0*x2, x3*x1*x3, x2*x1*x2)
sage: all(rel in F for rel in G.relations())
True
"""
return self._relations
@cached_method
def cardinality(self, limit=4096000):
"""
Compute the cardinality of ``self``.
INPUT:
- ``limit`` -- integer (default: 4096000). The maximal number
of cosets before the computation is aborted.
OUTPUT:
Integer or ``Infinity``. The number of elements in the group.
EXAMPLES::
sage: G.<a,b> = FreeGroup('a, b')
sage: H = G / (a^2, b^3, a*b*~a*~b)
sage: H.cardinality()
6
sage: F.<a,b,c> = FreeGroup()
sage: J = F / (F([1]), F([2, 2, 2]))
sage: J.cardinality()
+Infinity
ALGORITHM:
Uses GAP.
.. WARNING::
This is in general not a decidable problem, so it is not
guaranteed to give an answer. If the group is infinite, or
too big, you should be prepared for a long computation
that consumes all the memory without finishing if you do
not set a sensible ``limit``.
"""
with libgap.global_context('CosetTableDefaultMaxLimit', limit):
if not libgap.IsFinite(self.gap()):
from sage.rings.infinity import Infinity
return Infinity
try:
size = self.gap().Size()
except ValueError:
raise ValueError('Coset enumeration ran out of memory, is the group finite?')
return size.sage()
order = cardinality
def as_permutation_group(self, limit=4096000):
"""
Return an isomorphic permutation group.
The generators of the resulting group correspond to the images
by the isomorphism of the generators of the given group.
INPUT:
- ``limit`` -- integer (default: 4096000). The maximal number
of cosets before the computation is aborted.
OUTPUT:
A Sage
:func:`~sage.groups.perm_gps.permgroup.PermutationGroup`. If
the number of cosets exceeds the given ``limit``, a
``ValueError`` is returned.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: H = G / (a^2, b^3, a*b*~a*~b)
sage: H.as_permutation_group()
Permutation Group with generators [(1,2)(3,5)(4,6), (1,3,4)(2,5,6)]
sage: G.<a,b> = FreeGroup()
sage: H = G / [a^3*b]
sage: H.as_permutation_group(limit=1000)
Traceback (most recent call last):
...
ValueError: Coset enumeration exceeded limit, is the group finite?
ALGORITHM:
Uses GAP's coset enumeration on the trivial subgroup.
.. WARNING::
This is in general not a decidable problem (in fact, it is
not even possible to check if the group is finite or
not). If the group is infinite, or too big, you should be
prepared for a long computation that consumes all the
memory without finishing if you do not set a sensible
``limit``.
"""
with libgap.global_context('CosetTableDefaultMaxLimit', limit):
try:
trivial_subgroup = self.gap().TrivialSubgroup()
coset_table = self.gap().CosetTable(trivial_subgroup).sage()
except ValueError:
raise ValueError('Coset enumeration exceeded limit, is the group finite?')
from sage.combinat.permutation import Permutation
from sage.groups.perm_gps.permgroup import PermutationGroup
return PermutationGroup([
Permutation(coset_table[2*i]) for i in range(len(coset_table)//2)])
def direct_product(self, H, reduced=False, new_names=True):
r"""
Return the direct product of ``self`` with finitely presented
group ``H``.
Calls GAP function ``DirectProduct``, which returns the direct
product of a list of groups of any representation.
From [Joh1990]_ (p. 45, proposition 4): If `G`, `H` are groups
presented by `\langle X \mid R \rangle` and `\langle Y \mid S \rangle`
respectively, then their direct product has the presentation
`\langle X, Y \mid R, S, [X, Y] \rangle` where `[X, Y]` denotes the
set of commutators `\{ x^{-1} y^{-1} x y \mid x \in X, y \in Y \}`.
INPUT:
- ``H`` -- a finitely presented group
- ``reduced`` -- (default: ``False``) boolean; if ``True``, then
attempt to reduce the presentation of the product group
- ``new_names`` -- (default: ``True``) boolean; If ``True``, then
lexicographical variable names are assigned to the generators of
the group to be returned. If ``False``, the group to be returned
keeps the generator names of the two groups forming the direct
product. Note that one cannot ask to reduce the output and ask
to keep the old variable names, as they may change meaning
in the output group if its presentation is reduced.
OUTPUT:
The direct product of ``self`` with ``H`` as a finitely
presented group.
EXAMPLES::
sage: G = FreeGroup()
sage: C12 = ( G / [G([1,1,1,1])] ).direct_product( G / [G([1,1,1])]); C12
Finitely presented group < a, b | a^4, b^3, a^-1*b^-1*a*b >
sage: C12.order(), C12.as_permutation_group().is_cyclic()
(12, True)
sage: klein = ( G / [G([1,1])] ).direct_product( G / [G([1,1])]); klein
Finitely presented group < a, b | a^2, b^2, a^-1*b^-1*a*b >
sage: klein.order(), klein.as_permutation_group().is_cyclic()
(4, False)
We can keep the variable names from ``self`` and ``H`` to examine how
new relations are formed::
sage: F = FreeGroup("a"); G = FreeGroup("g")
sage: X = G / [G.0^12]; A = F / [F.0^6]
sage: X.direct_product(A, new_names=False)
Finitely presented group < g, a | g^12, a^6, g^-1*a^-1*g*a >
sage: A.direct_product(X, new_names=False)
Finitely presented group < a, g | a^6, g^12, a^-1*g^-1*a*g >
Or we can attempt to reduce the output group presentation::
sage: F = FreeGroup("a"); G = FreeGroup("g")
sage: X = G / [G.0]; A = F / [F.0]
sage: X.direct_product(A, new_names=True)
Finitely presented group < a, b | a, b, a^-1*b^-1*a*b >
sage: X.direct_product(A, reduced=True, new_names=True)
Finitely presented group < | >
But we cannot do both::
sage: K = FreeGroup(['a','b'])
sage: D = K / [K.0^5, K.1^8]
sage: D.direct_product(D, reduced=True, new_names=False)
Traceback (most recent call last):
...
ValueError: cannot reduce output and keep old variable names
TESTS::
sage: G = FreeGroup()
sage: Dp = (G / [G([1,1])]).direct_product( G / [G([1,1,1,1,1,1])] )
sage: Dp.as_permutation_group().is_isomorphic(PermutationGroup(['(1,2)','(3,4,5,6,7,8)']))
True
sage: C7 = G / [G.0**7]; C6 = G / [G.0**6]
sage: C14 = G / [G.0**14]; C3 = G / [G.0**3]
sage: C7.direct_product(C6).is_isomorphic(C14.direct_product(C3))
#I Forcing finiteness test
True
sage: F = FreeGroup(2); D = F / [F([1,1,1,1,1]),F([2,2]),F([1,2])**2]
sage: D.direct_product(D).as_permutation_group().is_isomorphic(
....: direct_product_permgroups([DihedralGroup(5),DihedralGroup(5)]))
True
AUTHORS:
- Davis Shurbert (2013-07-20): initial version
"""
from sage.groups.free_group import FreeGroup, _lexi_gen
if not isinstance(H, FinitelyPresentedGroup):
raise TypeError("input must be a finitely presented group")
if reduced and not new_names:
raise ValueError("cannot reduce output and keep old variable names")
fp_product = libgap.DirectProduct([self.gap(), H.gap()])
GAP_gens = fp_product.FreeGeneratorsOfFpGroup()
if new_names:
name_itr = _lexi_gen() # Python generator for lexicographical variable names
gen_names = [next(name_itr) for i in GAP_gens]
else:
gen_names= [str(g) for g in self.gens()] + [str(g) for g in H.gens()]
# Build the direct product in Sage for better variable names
ret_F = FreeGroup(gen_names)
ret_rls = tuple([ret_F(rel_word.TietzeWordAbstractWord(GAP_gens).sage())
for rel_word in fp_product.RelatorsOfFpGroup()])
ret_fpg = FinitelyPresentedGroup(ret_F, ret_rls)
if reduced:
ret_fpg = ret_fpg.simplified()
return ret_fpg
def semidirect_product(self, H, hom, check=True, reduced=False):
r"""
The semidirect product of ``self`` with ``H`` via ``hom``.
If there exists a homomorphism `\phi` from a group `G` to the
automorphism group of a group `H`, then we can define the semidirect
product of `G` with `H` via `\phi` as the Cartesian product of `G`
and `H` with the operation
.. MATH::
(g_1, h_1)(g_2, h_2) = (g_1 g_2, \phi(g_2)(h_1) h_2).
INPUT:
- ``H`` -- Finitely presented group which is implicitly acted on
by ``self`` and can be naturally embedded as a normal subgroup
of the semidirect product.
- ``hom`` -- Homomorphism from ``self`` to the automorphism group
of ``H``. Given as a pair, with generators of ``self`` in the
first slot and the images of the corresponding generators in the
second. These images must be automorphisms of ``H``, given again
as a pair of generators and images.
- ``check`` -- Boolean (default ``True``). If ``False`` the defining
homomorphism and automorphism images are not tested for validity.
This test can be costly with large groups, so it can be bypassed
if the user is confident that his morphisms are valid.
- ``reduced`` -- Boolean (default ``False``). If ``True`` then the
method attempts to reduce the presentation of the output group.
OUTPUT:
The semidirect product of ``self`` with ``H`` via ``hom`` as a
finitely presented group. See
:meth:`PermutationGroup_generic.semidirect_product
<sage.groups.perm_gps.permgroup.PermutationGroup_generic.semidirect_product>`
for a more in depth explanation of a semidirect product.
AUTHORS:
- Davis Shurbert (8-1-2013)
EXAMPLES:
Group of order 12 as two isomorphic semidirect products::
sage: D4 = groups.presentation.Dihedral(4)
sage: C3 = groups.presentation.Cyclic(3)
sage: alpha1 = ([C3.gen(0)],[C3.gen(0)])
sage: alpha2 = ([C3.gen(0)],[C3([1,1])])
sage: S1 = D4.semidirect_product(C3, ([D4.gen(1), D4.gen(0)],[alpha1,alpha2]))
sage: C2 = groups.presentation.Cyclic(2)
sage: Q = groups.presentation.DiCyclic(3)
sage: a = Q([1]); b = Q([-2])
sage: alpha = (Q.gens(), [a,b])
sage: S2 = C2.semidirect_product(Q, ([C2.0],[alpha]))
sage: S1.is_isomorphic(S2)
#I Forcing finiteness test
True
Dihedral groups can be constructed as semidirect products
of cyclic groups::
sage: C2 = groups.presentation.Cyclic(2)
sage: C8 = groups.presentation.Cyclic(8)
sage: hom = (C2.gens(), [ ([C8([1])], [C8([-1])]) ])
sage: D = C2.semidirect_product(C8, hom)
sage: D.as_permutation_group().is_isomorphic(DihedralGroup(8))
True
You can attempt to reduce the presentation of the output group::
sage: D = C2.semidirect_product(C8, hom); D
Finitely presented group < a, b | a^2, b^8, a^-1*b*a*b >
sage: D = C2.semidirect_product(C8, hom, reduced=True); D
Finitely presented group < a, b | a^2, a*b*a*b, b^8 >
sage: C3 = groups.presentation.Cyclic(3)
sage: C4 = groups.presentation.Cyclic(4)
sage: hom = (C3.gens(), [(C4.gens(), C4.gens())])
sage: C3.semidirect_product(C4, hom)
Finitely presented group < a, b | a^3, b^4, a^-1*b*a*b^-1 >
sage: D = C3.semidirect_product(C4, hom, reduced=True); D
Finitely presented group < a, b | a^3, b^4, a^-1*b*a*b^-1 >
sage: D.as_permutation_group().is_cyclic()
True
You can turn off the checks for the validity of the input morphisms.
This check is expensive but behavior is unpredictable if inputs are
invalid and are not caught by these tests::
sage: C5 = groups.presentation.Cyclic(5)
sage: C12 = groups.presentation.Cyclic(12)
sage: hom = (C5.gens(), [(C12.gens(), C12.gens())])
sage: sp = C5.semidirect_product(C12, hom, check=False); sp
Finitely presented group < a, b | a^5, b^12, a^-1*b*a*b^-1 >
sage: sp.as_permutation_group().is_cyclic(), sp.order()
(True, 60)
TESTS:
The following was fixed in Gap-4.7.2::
sage: C5.semidirect_product(C12, hom) == sp
True
A more complicated semidirect product::
sage: C = groups.presentation.Cyclic(7)
sage: D = groups.presentation.Dihedral(5)
sage: id1 = ([C.0], [(D.gens(),D.gens())])
sage: Se1 = C.semidirect_product(D, id1)
sage: id2 = (D.gens(), [(C.gens(),C.gens()),(C.gens(),C.gens())])
sage: Se2 = D.semidirect_product(C ,id2)
sage: Dp1 = C.direct_product(D)
sage: Dp1.is_isomorphic(Se1), Dp1.is_isomorphic(Se2)
#I Forcing finiteness test
#I Forcing finiteness test
(True, True)
Most checks for validity of input are left to GAP to handle::
sage: bad_aut = ([C.0], [(D.gens(),[D.0, D.0])])
sage: C.semidirect_product(D, bad_aut)
Traceback (most recent call last):
...
ValueError: images of input homomorphism must be automorphisms
sage: bad_hom = ([D.0, D.1], [(C.gens(),C.gens())])
sage: D.semidirect_product(C, bad_hom)
Traceback (most recent call last):
...
GAPError: Error, <gens> and <imgs> must be lists of same length
"""
from sage.groups.free_group import FreeGroup, _lexi_gen
if not isinstance(H, FinitelyPresentedGroup):
raise TypeError("input must be a finitely presented group")
GAP_self = self.gap()
GAP_H = H.gap()
auto_grp = libgap.AutomorphismGroup(H.gap())
self_gens = [h.gap() for h in hom[0]]
# construct image automorphisms in GAP
GAP_aut_imgs = [ libgap.GroupHomomorphismByImages(GAP_H, GAP_H, [g.gap() for g in gns],
[i.gap() for i in img]) for (gns, img) in hom[1] ]
# check for automorphism validity in images of operation defining homomorphism,
# and construct the defining homomorphism.
if check:
if not all(a in libgap.List(libgap.AutomorphismGroup(GAP_H))
for a in GAP_aut_imgs):
raise ValueError("images of input homomorphism must be automorphisms")
GAP_def_hom = libgap.GroupHomomorphismByImages(GAP_self, auto_grp, self_gens, GAP_aut_imgs)
else:
GAP_def_hom = GAP_self.GroupHomomorphismByImagesNC( auto_grp, self_gens, GAP_aut_imgs)
prod = libgap.SemidirectProduct(GAP_self, GAP_def_hom, GAP_H)
# Convert pc group to fp group
if prod.IsPcGroup():
prod = libgap.Image(libgap.IsomorphismFpGroupByPcgs(prod.FamilyPcgs() , 'x'))
if not prod.IsFpGroup():
raise NotImplementedError("unable to convert GAP output to equivalent Sage fp group")
# Convert GAP group object to Sage via Tietze
# lists for readability of variable names
GAP_gens = prod.FreeGeneratorsOfFpGroup()
name_itr = _lexi_gen() # Python generator for lexicographical variable names
ret_F = FreeGroup([next(name_itr) for i in GAP_gens])
ret_rls = tuple([ret_F(rel_word.TietzeWordAbstractWord(GAP_gens).sage())
for rel_word in prod.RelatorsOfFpGroup()])
ret_fpg = FinitelyPresentedGroup(ret_F, ret_rls)
if reduced:
ret_fpg = ret_fpg.simplified()
return ret_fpg
def _element_constructor_(self, *args, **kwds):
"""
Construct an element of ``self``.
TESTS::
sage: G.<a,b> = FreeGroup()
sage: H = G / (G([1]), G([2, 2, 2]))
sage: H([1, 2, 1, -1]) # indirect doctest
a*b
sage: H([1, 2, 1, -2]) # indirect doctest
a*b*a*b^-1
"""
if len(args)!=1:
return self.element_class(self, *args, **kwds)
x = args[0]
if x==1:
return self.one()
try:
P = x.parent()
except AttributeError:
return self.element_class(self, x, **kwds)
if P is self._free_group:
return self.element_class(self, x.Tietze(), **kwds)
return self.element_class(self, x, **kwds)
@cached_method
def abelian_invariants(self):
r"""
Return the abelian invariants of ``self``.
The abelian invariants are given by a list of integers
`(i_1, \ldots, i_j)`, such that the abelianization of the group is
isomorphic to `\ZZ / (i_1) \times \cdots \times \ZZ / (i_j)`.
EXAMPLES::
sage: G = FreeGroup(4, 'g')
sage: G.inject_variables()
Defining g0, g1, g2, g3
sage: H = G.quotient([g1^2, g2*g1*g2^(-1)*g1^(-1), g1*g3^(-2), g0^4])
sage: H.abelian_invariants()
(0, 4, 4)
ALGORITHM:
Uses GAP.
"""
invariants = self.gap().AbelianInvariants()
return tuple( i.sage() for i in invariants )
def simplification_isomorphism(self):
"""
Return an isomorphism from ``self`` to a finitely presented group with
a (hopefully) simpler presentation.
EXAMPLES::
sage: G.<a,b,c> = FreeGroup()
sage: H = G / [a*b*c, a*b^2, c*b/c^2]
sage: I = H.simplification_isomorphism()
sage: I
Generic morphism:
From: Finitely presented group < a, b, c | a*b*c, a*b^2, c*b*c^-2 >
To: Finitely presented group < b | >
Defn: a |--> b^-2
b |--> b
c |--> b
sage: I(a)
b^-2
sage: I(b)
b
sage: I(c)
b
TESTS::
sage: F = FreeGroup(1)
sage: G = F.quotient([F.0])
sage: G.simplification_isomorphism()
Generic morphism:
From: Finitely presented group < x | x >
To: Finitely presented group < | >
Defn: x |--> 1
ALGORITHM:
Uses GAP.
"""
I = self.gap().IsomorphismSimplifiedFpGroup()
codomain = wrap_FpGroup(I.Range())
phi = lambda x: codomain(I.ImageElm(x.gap()))
HS = self.Hom(codomain)
return GroupMorphismWithGensImages(HS, phi)
def simplified(self):
"""
Return an isomorphic group with a (hopefully) simpler presentation.
OUTPUT:
A new finitely presented group. Use
:meth:`simplification_isomorphism` if you want to know the
isomorphism.
EXAMPLES::
sage: G.<x,y> = FreeGroup()
sage: H = G / [x ^5, y ^4, y*x*y^3*x ^3]
sage: H
Finitely presented group < x, y | x^5, y^4, y*x*y^3*x^3 >
sage: H.simplified()
Finitely presented group < x, y | y^4, y*x*y^-1*x^-2, x^5 >
A more complicate example::
sage: G.<e0, e1, e2, e3, e4, e5, e6, e7, e8, e9> = FreeGroup()
sage: rels = [e6, e5, e3, e9, e4*e7^-1*e6, e9*e7^-1*e0,
....: e0*e1^-1*e2, e5*e1^-1*e8, e4*e3^-1*e8, e2]
sage: H = G.quotient(rels); H
Finitely presented group < e0, e1, e2, e3, e4, e5, e6, e7, e8, e9 |
e6, e5, e3, e9, e4*e7^-1*e6, e9*e7^-1*e0, e0*e1^-1*e2, e5*e1^-1*e8, e4*e3^-1*e8, e2 >
sage: H.simplified()
Finitely presented group < e0 | e0^2 >
"""
return self.simplification_isomorphism().codomain()
def epimorphisms(self, H):
r"""
Return the epimorphisms from `self` to `H`, up to automorphism of `H`.
INPUT:
- `H` -- Another group
EXAMPLES::
sage: F = FreeGroup(3)
sage: G = F / [F([1, 2, 3, 1, 2, 3]), F([1, 1, 1])]
sage: H = AlternatingGroup(3)
sage: G.epimorphisms(H)
[Generic morphism:
From: Finitely presented group < x0, x1, x2 | x0*x1*x2*x0*x1*x2, x0^3 >
To: Alternating group of order 3!/2 as a permutation group
Defn: x0 |--> ()
x1 |--> (1,3,2)
x2 |--> (1,2,3),
Generic morphism:
From: Finitely presented group < x0, x1, x2 | x0*x1*x2*x0*x1*x2, x0^3 >
To: Alternating group of order 3!/2 as a permutation group
Defn: x0 |--> (1,3,2)
x1 |--> ()
x2 |--> (1,2,3),
Generic morphism:
From: Finitely presented group < x0, x1, x2 | x0*x1*x2*x0*x1*x2, x0^3 >
To: Alternating group of order 3!/2 as a permutation group
Defn: x0 |--> (1,3,2)
x1 |--> (1,2,3)
x2 |--> (),
Generic morphism:
From: Finitely presented group < x0, x1, x2 | x0*x1*x2*x0*x1*x2, x0^3 >
To: Alternating group of order 3!/2 as a permutation group
Defn: x0 |--> (1,2,3)
x1 |--> (1,2,3)
x2 |--> (1,2,3)]
ALGORITHM:
Uses libgap's GQuotients function.
"""
from sage.misc.misc_c import prod
HomSpace = self.Hom(H)
Gg = libgap(self)
Hg = libgap(H)
gquotients = Gg.GQuotients(Hg)
res = []
# the following closure is needed to attach a specific value of quo to
# each function in the different morphisms
fmap = lambda tup: (lambda a: H(prod(tup[abs(i)-1]**sign(i) for i in a.Tietze())))
for quo in gquotients:
tup = tuple(H(quo.ImageElm(i.gap()).sage()) for i in self.gens())
fhom = GroupMorphismWithGensImages(HomSpace, fmap(tup))
res.append(fhom)
return res
def alexander_matrix(self, im_gens=None):
"""
Return the Alexander matrix of the group.
This matrix is given by the fox derivatives of the relations
with respect to the generators.
- ``im_gens`` -- (optional) the images of the generators
OUTPUT:
A matrix with coefficients in the group algebra. If ``im_gens`` is
given, the coefficients will live in the same algebra as the given
values. The result depends on the (fixed) choice of presentation.
EXAMPLES::
sage: G.<a,b,c> = FreeGroup()
sage: H = G.quotient([a*b/a/b, a*c/a/c, c*b/c/b])
sage: H.alexander_matrix()
[ 1 - a*b*a^-1 a - a*b*a^-1*b^-1 0]
[ 1 - a*c*a^-1 0 a - a*c*a^-1*c^-1]
[ 0 c - c*b*c^-1*b^-1 1 - c*b*c^-1]
If we introduce the images of the generators, we obtain the
result in the corresponding algebra.
::
sage: G.<a,b,c,d,e> = FreeGroup()
sage: H = G.quotient([a*b/a/b, a*c/a/c, a*d/a/d, b*c*d/(c*d*b), b*c*d/(d*b*c)])
sage: H.alexander_matrix()
[ 1 - a*b*a^-1 a - a*b*a^-1*b^-1 0 0 0]
[ 1 - a*c*a^-1 0 a - a*c*a^-1*c^-1 0 0]
[ 1 - a*d*a^-1 0 0 a - a*d*a^-1*d^-1 0]
[ 0 1 - b*c*d*b^-1 b - b*c*d*b^-1*d^-1*c^-1 b*c - b*c*d*b^-1*d^-1 0]
[ 0 1 - b*c*d*c^-1*b^-1 b - b*c*d*c^-1 b*c - b*c*d*c^-1*b^-1*d^-1 0]
sage: R.<t1,t2,t3,t4> = LaurentPolynomialRing(ZZ)
sage: H.alexander_matrix([t1,t2,t3,t4])
[ -t2 + 1 t1 - 1 0 0 0]
[ -t3 + 1 0 t1 - 1 0 0]
[ -t4 + 1 0 0 t1 - 1 0]
[ 0 -t3*t4 + 1 t2 - 1 t2*t3 - t3 0]
[ 0 -t4 + 1 -t2*t4 + t2 t2*t3 - 1 0]
"""
rel = self.relations()
gen = self._free_group.gens()
return matrix(len(rel), len(gen),
lambda i,j: rel[i].fox_derivative(gen[j], im_gens))
def rewriting_system(self):
"""
Return the rewriting system corresponding to the finitely presented
group. This rewriting system can be used to reduce words with respect
to the relations.
If the rewriting system is transformed into a confluent one, the
reduction process will give as a result the (unique) reduced form
of an element.
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: G = F / [a^2,b^3,(a*b/a)^3,b*a*b*a]
sage: k = G.rewriting_system()
sage: k
Rewriting system of Finitely presented group < a, b | a^2, b^3, a*b^3*a^-1, b*a*b*a >
with rules:
a^2 ---> 1
b^3 ---> 1
b*a*b*a ---> 1
a*b^3*a^-1 ---> 1
sage: G([1,1,2,2,2])
a^2*b^3
sage: k.reduce(G([1,1,2,2,2]))
1
sage: k.reduce(G([2,2,1]))
b^2*a
sage: k.make_confluent()
sage: k.reduce(G([2,2,1]))
a*b
"""
return RewritingSystem(self)
from sage.groups.generic import structure_description | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/finitely_presented.py | 0.833528 | 0.562237 | finitely_presented.py | pypi |
from sage.categories.groups import Groups
from sage.groups.group import Group
from sage.groups.libgap_wrapper import ParentLibGAP, ElementLibGAP
from sage.structure.unique_representation import UniqueRepresentation
from sage.libs.gap.libgap import libgap
from sage.libs.gap.element import GapElement
from sage.rings.integer import Integer
from sage.rings.integer_ring import IntegerRing
from sage.misc.cachefunc import cached_method
from sage.misc.misc_c import prod
from sage.structure.sequence import Sequence
from sage.structure.element import coercion_model, parent
def is_FreeGroup(x):
"""
Test whether ``x`` is a :class:`FreeGroup_class`.
INPUT:
- ``x`` -- anything.
OUTPUT:
Boolean.
EXAMPLES::
sage: from sage.groups.free_group import is_FreeGroup
sage: is_FreeGroup('a string')
False
sage: is_FreeGroup(FreeGroup(0))
True
sage: is_FreeGroup(FreeGroup(index_set=ZZ))
True
"""
if isinstance(x, FreeGroup_class):
return True
from sage.groups.indexed_free_group import IndexedFreeGroup
return isinstance(x, IndexedFreeGroup)
def _lexi_gen(zeroes=False):
"""
Return a generator object that produces variable names suitable for the
generators of a free group.
INPUT:
- ``zeroes`` -- Boolean defaulting as ``False``. If ``True``, the
integers appended to the output string begin at zero at the
first iteration through the alphabet.
OUTPUT:
Python generator object which outputs a character from the alphabet on each
``next()`` call in lexicographical order. The integer `i` is appended
to the output string on the `i^{th}` iteration through the alphabet.
EXAMPLES::
sage: from sage.groups.free_group import _lexi_gen
sage: itr = _lexi_gen()
sage: F = FreeGroup([next(itr) for i in [1..10]]); F
Free Group on generators {a, b, c, d, e, f, g, h, i, j}
sage: it = _lexi_gen()
sage: [next(it) for i in range(10)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
sage: itt = _lexi_gen(True)
sage: [next(itt) for i in range(10)]
['a0', 'b0', 'c0', 'd0', 'e0', 'f0', 'g0', 'h0', 'i0', 'j0']
sage: test = _lexi_gen()
sage: ls = [next(test) for i in range(3*26)]
sage: ls[2*26:3*26]
['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2', 'j2', 'k2', 'l2', 'm2',
'n2', 'o2', 'p2', 'q2', 'r2', 's2', 't2', 'u2', 'v2', 'w2', 'x2', 'y2', 'z2']
TESTS::
sage: from sage.groups.free_group import _lexi_gen
sage: test = _lexi_gen()
sage: ls = [next(test) for i in range(500)]
sage: ls[234], ls[260]
('a9', 'a10')
"""
count = Integer(0)
while True:
mwrap, ind = count.quo_rem(26)
if mwrap == 0 and not zeroes:
name = ''
else:
name = str(mwrap)
name = chr(ord('a') + ind) + name
yield name
count += 1
class FreeGroupElement(ElementLibGAP):
"""
A wrapper of GAP's Free Group elements.
INPUT:
- ``x`` -- something that determines the group element. Either a
:class:`~sage.libs.gap.element.GapElement` or the Tietze list
(see :meth:`Tietze`) of the group element.
- ``parent`` -- the parent :class:`FreeGroup`.
EXAMPLES::
sage: G = FreeGroup('a, b')
sage: x = G([1, 2, -1, -2])
sage: x
a*b*a^-1*b^-1
sage: y = G([2, 2, 2, 1, -2, -2, -2])
sage: y
b^3*a*b^-3
sage: x*y
a*b*a^-1*b^2*a*b^-3
sage: y*x
b^3*a*b^-3*a*b*a^-1*b^-1
sage: x^(-1)
b*a*b^-1*a^-1
sage: x == x*y*y^(-1)
True
"""
def __init__(self, parent, x):
"""
The Python constructor.
See :class:`FreeGroupElement` for details.
TESTS::
sage: G.<a,b> = FreeGroup()
sage: x = G([1, 2, -1, -1])
sage: x # indirect doctest
a*b*a^-2
sage: y = G([2, 2, 2, 1, -2, -2, -1])
sage: y # indirect doctest
b^3*a*b^-2*a^-1
sage: TestSuite(G).run()
sage: TestSuite(x).run()
"""
if not isinstance(x, GapElement):
try:
l = x.Tietze()
except AttributeError:
l = list(x)
if len(l)>0:
if min(l) < -parent.ngens() or parent.ngens() < max(l):
raise ValueError('generators not in the group')
if 0 in l:
raise ValueError('zero does not denote a generator')
i=0
while i<len(l)-1:
if l[i]==-l[i+1]:
l.pop(i)
l.pop(i)
if i>0:
i=i-1
else:
i=i+1
AbstractWordTietzeWord = libgap.eval('AbstractWordTietzeWord')
x = AbstractWordTietzeWord(l, parent.gap().GeneratorsOfGroup())
ElementLibGAP.__init__(self, parent, x)
def __hash__(self):
r"""
TESTS::
sage: G.<a,b> = FreeGroup()
sage: hash(a*b*b*~a) == hash((1, 2, 2, -1))
True
"""
return hash(self.Tietze())
def _latex_(self):
r"""
Return a LaTeX representation
OUTPUT:
String. A valid LaTeX math command sequence.
EXAMPLES::
sage: F.<a,b,c> = FreeGroup()
sage: f = F([1, 2, 2, -3, -1]) * c^15 * a^(-23)
sage: f._latex_()
'a\\cdot b^{2}\\cdot c^{-1}\\cdot a^{-1}\\cdot c^{15}\\cdot a^{-23}'
sage: F = FreeGroup(3)
sage: f = F([1, 2, 2, -3, -1]) * F.gen(2)^11 * F.gen(0)^(-12)
sage: f._latex_()
'x_{0}\\cdot x_{1}^{2}\\cdot x_{2}^{-1}\\cdot x_{0}^{-1}\\cdot x_{2}^{11}\\cdot x_{0}^{-12}'
sage: F.<a,b,c> = FreeGroup()
sage: G = F / (F([1, 2, 1, -3, 2, -1]), F([2, -1]))
sage: f = G([1, 2, 2, -3, -1]) * G.gen(2)^15 * G.gen(0)^(-23)
sage: f._latex_()
'a\\cdot b^{2}\\cdot c^{-1}\\cdot a^{-1}\\cdot c^{15}\\cdot a^{-23}'
sage: F = FreeGroup(4)
sage: G = F.quotient((F([1, 2, 4, -3, 2, -1]), F([2, -1])))
sage: f = G([1, 2, 2, -3, -1]) * G.gen(3)^11 * G.gen(0)^(-12)
sage: f._latex_()
'x_{0}\\cdot x_{1}^{2}\\cdot x_{2}^{-1}\\cdot x_{0}^{-1}\\cdot x_{3}^{11}\\cdot x_{0}^{-12}'
"""
import re
s = self._repr_()
s = re.sub('([a-z]|[A-Z])([0-9]+)', r'\g<1>_{\g<2>}', s)
s = re.sub(r'(\^)(-)([0-9]+)', r'\g<1>{\g<2>\g<3>}', s)
s = re.sub(r'(\^)([0-9]+)', r'\g<1>{\g<2>}', s)
s = s.replace('*', r'\cdot ')
return s
def __reduce__(self):
"""
Implement pickling.
TESTS::
sage: F.<a,b> = FreeGroup()
sage: a.__reduce__()
(Free Group on generators {a, b}, ((1,),))
sage: (a*b*a^-1).__reduce__()
(Free Group on generators {a, b}, ((1, 2, -1),))
"""
return (self.parent(), (self.Tietze(),))
@cached_method
def Tietze(self):
"""
Return the Tietze list of the element.
The Tietze list of a word is a list of integers that represent
the letters in the word. A positive integer `i` represents
the letter corresponding to the `i`-th generator of the group.
Negative integers represent the inverses of generators.
OUTPUT:
A tuple of integers.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: a.Tietze()
(1,)
sage: x = a^2 * b^(-3) * a^(-2)
sage: x.Tietze()
(1, 1, -2, -2, -2, -1, -1)
TESTS::
sage: type(a.Tietze())
<... 'tuple'>
sage: type(a.Tietze()[0])
<class 'sage.rings.integer.Integer'>
"""
tl = self.gap().TietzeWordAbstractWord()
return tuple(tl.sage())
def fox_derivative(self, gen, im_gens=None, ring=None):
r"""
Return the Fox derivative of ``self`` with respect to a given
generator ``gen`` of the free group.
Let `F` be a free group with free generators
`x_1, x_2, \ldots, x_n`. Let `j \in \left\{ 1, 2, \ldots ,
n \right\}`. Let `a_1, a_2, \ldots, a_n` be `n`
invertible elements of a ring `A`. Let `a : F \to A^\times`
be the (unique) homomorphism from `F` to the multiplicative
group of invertible elements of `A` which sends each `x_i`
to `a_i`. Then, we can define a map `\partial_j : F \to A`
by the requirements that
.. MATH::
\partial_j (x_i) = \delta_{i, j}
\qquad \qquad \text{ for all indices } i \text{ and } j
and
.. MATH::
\partial_j (uv) = \partial_j(u) + a(u) \partial_j(v)
\qquad \qquad \text{ for all } u, v \in F .
This map `\partial_j` is called the `j`-th Fox derivative
on `F` induced by `(a_1, a_2, \ldots, a_n)`.
The most well-known case is when `A` is the group ring
`\ZZ [F]` of `F` over `\ZZ`, and when `a_i = x_i \in A`.
In this case, `\partial_j` is simply called the `j`-th
Fox derivative on `F`.
INPUT:
- ``gen`` -- the generator with respect to which the
derivative will be computed. If this is `x_j`, then the
method will return `\partial_j`.
- ``im_gens`` (optional) -- the images of the generators
(given as a list or iterable). This is the list
`(a_1, a_2, \ldots, a_n)`.
If not provided, it defaults to
`(x_1, x_2, \ldots, x_n)` in the group ring
`\ZZ [F]`.
- ``ring`` (optional) -- the ring in which the elements
of the list `(a_1, a_2, \ldots, a_n)` lie. If not
provided, this ring is inferred from these elements.
OUTPUT:
The fox derivative of ``self`` with respect to ``gen``
(induced by ``im_gens``).
By default, it is an element of the group algebra with
integer coefficients.
If ``im_gens`` are provided, the result lives in the
algebra where ``im_gens`` live.
EXAMPLES::
sage: G = FreeGroup(5)
sage: G.inject_variables()
Defining x0, x1, x2, x3, x4
sage: (~x0*x1*x0*x2*~x0).fox_derivative(x0)
-x0^-1 + x0^-1*x1 - x0^-1*x1*x0*x2*x0^-1
sage: (~x0*x1*x0*x2*~x0).fox_derivative(x1)
x0^-1
sage: (~x0*x1*x0*x2*~x0).fox_derivative(x2)
x0^-1*x1*x0
sage: (~x0*x1*x0*x2*~x0).fox_derivative(x3)
0
If ``im_gens`` is given, the images of the generators are
mapped to them::
sage: F = FreeGroup(3)
sage: a = F([2,1,3,-1,2])
sage: a.fox_derivative(F([1]))
x1 - x1*x0*x2*x0^-1
sage: R.<t> = LaurentPolynomialRing(ZZ)
sage: a.fox_derivative(F([1]),[t,t,t])
t - t^2
sage: S.<t1,t2,t3> = LaurentPolynomialRing(ZZ)
sage: a.fox_derivative(F([1]),[t1,t2,t3])
-t2*t3 + t2
sage: R.<x,y,z> = QQ[]
sage: a.fox_derivative(F([1]),[x,y,z])
-y*z + y
sage: a.inverse().fox_derivative(F([1]),[x,y,z])
(z - 1)/(y*z)
The optional parameter ``ring`` determines the ring `A`::
sage: u = a.fox_derivative(F([1]), [1,2,3], ring=QQ)
sage: u
-4
sage: parent(u)
Rational Field
sage: u = a.fox_derivative(F([1]), [1,2,3], ring=R)
sage: u
-4
sage: parent(u)
Multivariate Polynomial Ring in x, y, z over Rational Field
TESTS::
sage: F = FreeGroup(3)
sage: a = F([])
sage: a.fox_derivative(F([1]))
0
sage: R.<t> = LaurentPolynomialRing(ZZ)
sage: a.fox_derivative(F([1]),[t,t,t])
0
"""
if gen not in self.parent().generators():
raise ValueError("Fox derivative can only be computed with respect to generators of the group")
l = list(self.Tietze())
if im_gens is None:
F = self.parent()
R = F.algebra(IntegerRing())
R_basis = R.basis()
symb = [R_basis[a] for a in F.gens()]
symb += reversed([R_basis[a.inverse()] for a in F.gens()])
if ring is not None:
R = ring
symb = [R(i) for i in symb]
else:
if ring is None:
R = Sequence(im_gens).universe()
else:
R = ring
symb = list(im_gens)
symb += reversed([a**(-1) for a in im_gens])
i = gen.Tietze()[0] # So ``gen`` is the `i`-th
# generator of the free group.
a = R.zero()
coef = R.one()
while l:
b = l.pop(0)
if b == i:
a += coef * R.one()
coef *= symb[b-1]
elif b == -i:
a -= coef * symb[b]
coef *= symb[b]
elif b > 0:
coef *= symb[b-1]
else:
coef *= symb[b]
return a
@cached_method
def syllables(self):
r"""
Return the syllables of the word.
Consider a free group element `g = x_1^{n_1} x_2^{n_2} \cdots
x_k^{n_k}`. The uniquely-determined subwords `x_i^{e_i}`
consisting only of powers of a single generator are called the
syllables of `g`.
OUTPUT:
The tuple of syllables. Each syllable is given as a pair
`(x_i, e_i)` consisting of a generator and a non-zero integer.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: w = a^2 * b^-1 * a^3
sage: w.syllables()
((a, 2), (b, -1), (a, 3))
"""
g = self.gap().UnderlyingElement()
k = g.NumberSyllables().sage()
exponent_syllable = libgap.eval('ExponentSyllable')
generator_syllable = libgap.eval('GeneratorSyllable')
result = []
gen = self.parent().gen
for i in range(k):
exponent = exponent_syllable(g, i+1).sage()
generator = gen(generator_syllable(g, i+1).sage() - 1)
result.append( (generator, exponent) )
return tuple(result)
def __call__(self, *values):
"""
Replace the generators of the free group by corresponding
elements of the iterable ``values`` in the group element
``self``.
INPUT:
- ``*values`` -- a sequence of values, or a
list/tuple/iterable of the same length as the number of
generators of the free group.
OUTPUT:
The product of ``values`` in the order and with exponents
specified by ``self``.
EXAMPLES::
sage: G.<a,b> = FreeGroup()
sage: w = a^2 * b^-1 * a^3
sage: w(1, 2)
1/2
sage: w(2, 1)
32
sage: w.subs(b=1, a=2) # indirect doctest
32
TESTS::
sage: w([1, 2])
1/2
sage: w((1, 2))
1/2
sage: w(i+1 for i in range(2))
1/2
Check that :trac:`25017` is fixed::
sage: F = FreeGroup(2)
sage: x0, x1 = F.gens()
sage: u = F(1)
sage: parent(u.subs({x1:x0})) is F
True
sage: F = FreeGroup(2)
sage: x0, x1 = F.gens()
sage: u = x0*x1
sage: u.subs({x0:3, x1:2})
6
sage: u.subs({x0:1r, x1:2r})
2
sage: M0 = matrix(ZZ,2,[1,1,0,1])
sage: M1 = matrix(ZZ,2,[1,0,1,1])
sage: u.subs({x0: M0, x1: M1})
[2 1]
[1 1]
TESTS::
sage: F.<x,y> = FreeGroup()
sage: F.one().subs(x=x, y=1)
Traceback (most recent call last):
...
TypeError: no common canonical parent for objects with parents: 'Free Group on generators {x, y}' and 'Integer Ring'
"""
if len(values) == 1:
try:
values = list(values[0])
except TypeError:
pass
G = self.parent()
if len(values) != G.ngens():
raise ValueError('number of values has to match the number of generators')
replace = dict(zip(G.gens(), values))
new_parent = coercion_model.common_parent(*[parent(v) for v in values])
try:
return new_parent.prod(replace[gen] ** power
for gen, power in self.syllables())
except AttributeError:
return prod(new_parent(replace[gen]) ** power
for gen, power in self.syllables())
def FreeGroup(n=None, names='x', index_set=None, abelian=False, **kwds):
"""
Construct a Free Group.
INPUT:
- ``n`` -- integer or ``None`` (default). The number of
generators. If not specified the ``names`` are counted.
- ``names`` -- string or list/tuple/iterable of strings (default:
``'x'``). The generator names or name prefix.
- ``index_set`` -- (optional) an index set for the generators; if
specified then the optional keyword ``abelian`` can be used
- ``abelian`` -- (default: ``False``) whether to construct a free
abelian group or a free group
.. NOTE::
If you want to create a free group, it is currently preferential to
use ``Groups().free(...)`` as that does not load GAP.
EXAMPLES::
sage: G.<a,b> = FreeGroup(); G
Free Group on generators {a, b}
sage: H = FreeGroup('a, b')
sage: G is H
True
sage: FreeGroup(0)
Free Group on generators {}
The entry can be either a string with the names of the generators,
or the number of generators and the prefix of the names to be
given. The default prefix is ``'x'`` ::
sage: FreeGroup(3)
Free Group on generators {x0, x1, x2}
sage: FreeGroup(3, 'g')
Free Group on generators {g0, g1, g2}
sage: FreeGroup()
Free Group on generators {x}
We give two examples using the ``index_set`` option::
sage: FreeGroup(index_set=ZZ)
Free group indexed by Integer Ring
sage: FreeGroup(index_set=ZZ, abelian=True)
Free abelian group indexed by Integer Ring
TESTS::
sage: G1 = FreeGroup(2, 'a,b')
sage: G2 = FreeGroup('a,b')
sage: G3.<a,b> = FreeGroup()
sage: G1 is G2, G2 is G3
(True, True)
"""
# Support Freegroup('a,b') syntax
if n is not None:
try:
n = Integer(n)
except TypeError:
names = n
n = None
# derive n from counting names
if n is None:
if isinstance(names, str):
n = len(names.split(','))
else:
names = list(names)
n = len(names)
from sage.structure.category_object import normalize_names
names = normalize_names(n, names)
if index_set is not None or abelian:
if abelian:
from sage.groups.indexed_free_group import IndexedFreeAbelianGroup
return IndexedFreeAbelianGroup(index_set, names=names, **kwds)
from sage.groups.indexed_free_group import IndexedFreeGroup
return IndexedFreeGroup(index_set, names=names, **kwds)
return FreeGroup_class(names)
def wrap_FreeGroup(libgap_free_group):
"""
Wrap a LibGAP free group.
This function changes the comparison method of
``libgap_free_group`` to comparison by Python ``id``. If you want
to put the LibGAP free group into a container (set, dict) then you
should understand the implications of
:meth:`~sage.libs.gap.element.GapElement._set_compare_by_id`. To
be safe, it is recommended that you just work with the resulting
Sage :class:`FreeGroup_class`.
INPUT:
- ``libgap_free_group`` -- a LibGAP free group.
OUTPUT:
A Sage :class:`FreeGroup_class`.
EXAMPLES:
First construct a LibGAP free group::
sage: F = libgap.FreeGroup(['a', 'b'])
sage: type(F)
<class 'sage.libs.gap.element.GapElement'>
Now wrap it::
sage: from sage.groups.free_group import wrap_FreeGroup
sage: wrap_FreeGroup(F)
Free Group on generators {a, b}
TESTS:
Check that we can do it twice (see :trac:`12339`) ::
sage: G = libgap.FreeGroup(['a', 'b'])
sage: wrap_FreeGroup(G)
Free Group on generators {a, b}
"""
assert libgap_free_group.IsFreeGroup()
libgap_free_group._set_compare_by_id()
names = tuple( str(g) for g in libgap_free_group.GeneratorsOfGroup() )
return FreeGroup_class(names, libgap_free_group)
class FreeGroup_class(UniqueRepresentation, Group, ParentLibGAP):
"""
A class that wraps GAP's FreeGroup
See :func:`FreeGroup` for details.
TESTS::
sage: G = FreeGroup('a, b')
sage: TestSuite(G).run()
sage: G.category()
Category of infinite groups
"""
Element = FreeGroupElement
def __init__(self, generator_names, libgap_free_group=None):
"""
Python constructor.
INPUT:
- ``generator_names`` -- a tuple of strings. The names of the
generators.
- ``libgap_free_group`` -- a LibGAP free group or ``None``
(default). The LibGAP free group to wrap. If ``None``, a
suitable group will be constructed.
TESTS::
sage: G.<a,b> = FreeGroup() # indirect doctest
sage: G
Free Group on generators {a, b}
sage: G.variable_names()
('a', 'b')
"""
self._assign_names(generator_names)
if libgap_free_group is None:
libgap_free_group = libgap.FreeGroup(generator_names)
ParentLibGAP.__init__(self, libgap_free_group)
if not generator_names:
cat = Groups().Finite()
else:
cat = Groups().Infinite()
Group.__init__(self, category=cat)
def _repr_(self):
"""
TESTS::
sage: G = FreeGroup('a, b')
sage: G # indirect doctest
Free Group on generators {a, b}
sage: G._repr_()
'Free Group on generators {a, b}'
"""
return 'Free Group on generators {'+ ', '.join(self.variable_names()) + '}'
def rank(self):
"""
Return the number of generators of self.
Alias for :meth:`ngens`.
OUTPUT:
Integer.
EXAMPLES::
sage: G = FreeGroup('a, b'); G
Free Group on generators {a, b}
sage: G.rank()
2
sage: H = FreeGroup(3, 'x')
sage: H
Free Group on generators {x0, x1, x2}
sage: H.rank()
3
"""
return self.ngens()
def _gap_init_(self):
"""
Return the string used to construct the object in gap.
EXAMPLES::
sage: G = FreeGroup(3)
sage: G._gap_init_()
'FreeGroup(["x0", "x1", "x2"])'
"""
gap_names = [ '"' + s + '"' for s in self.variable_names() ]
gen_str = ', '.join(gap_names)
return 'FreeGroup(['+gen_str+'])'
def _element_constructor_(self, *args, **kwds):
"""
TESTS::
sage: G.<a,b> = FreeGroup()
sage: G([1, 2, 1]) # indirect doctest
a*b*a
sage: G([1, 2, -2, 1, 1, -2]) # indirect doctest
a^3*b^-1
sage: G( a.gap() )
a
sage: type(_)
<class 'sage.groups.free_group.FreeGroup_class_with_category.element_class'>
Check that conversion between free groups follow the convention that
names are preserved::
sage: F = FreeGroup('a,b')
sage: G = FreeGroup('b,a')
sage: G(F.gen(0))
a
sage: F(G.gen(0))
b
sage: a,b = F.gens()
sage: G(a^2*b^-3*a^-1)
a^2*b^-3*a^-1
Check that :trac:`17246` is fixed::
sage: F = FreeGroup(0)
sage: F([])
1
Check that 0 isn't considered the identity::
sage: F = FreeGroup('x')
sage: F(0)
Traceback (most recent call last):
...
TypeError: 'sage.rings.integer.Integer' object is not iterable
"""
if len(args)!=1:
return self.element_class(self, *args, **kwds)
x = args[0]
if x==1 or x == [] or x == ():
return self.one()
try:
P = x.parent()
except AttributeError:
return self.element_class(self, x, **kwds)
if isinstance(P, FreeGroup_class):
names = set(P._names[abs(i)-1] for i in x.Tietze())
if names.issubset(self._names):
return self([i.sign()*(self._names.index(P._names[abs(i)-1])+1)
for i in x.Tietze()])
else:
raise ValueError('generators of %s not in the group'%x)
return self.element_class(self, x, **kwds)
def abelian_invariants(self):
r"""
Return the Abelian invariants of ``self``.
The Abelian invariants are given by a list of integers
`i_1 \dots i_j`, such that the abelianization of the
group is isomorphic to
.. MATH::
\ZZ / (i_1) \times \dots \times \ZZ / (i_j)
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: F.abelian_invariants()
(0, 0)
"""
return (0,) * self.ngens()
def quotient(self, relations, **kwds):
"""
Return the quotient of ``self`` by the normal subgroup generated
by the given elements.
This quotient is a finitely presented groups with the same
generators as ``self``, and relations given by the elements of
``relations``.
INPUT:
- ``relations`` -- A list/tuple/iterable with the elements of
the free group.
- further named arguments, that are passed to the constructor
of a finitely presented group.
OUTPUT:
A finitely presented group, with generators corresponding to
the generators of the free group, and relations corresponding
to the elements in ``relations``.
EXAMPLES::
sage: F.<a,b> = FreeGroup()
sage: F.quotient([a*b^2*a, b^3])
Finitely presented group < a, b | a*b^2*a, b^3 >
Division is shorthand for :meth:`quotient` ::
sage: F / [a*b^2*a, b^3]
Finitely presented group < a, b | a*b^2*a, b^3 >
Relations are converted to the free group, even if they are not
elements of it (if possible) ::
sage: F1.<a,b,c,d> = FreeGroup()
sage: F2.<a,b> = FreeGroup()
sage: r = a*b/a
sage: r.parent()
Free Group on generators {a, b}
sage: F1/[r]
Finitely presented group < a, b, c, d | a*b*a^-1 >
"""
from sage.groups.finitely_presented import FinitelyPresentedGroup
return FinitelyPresentedGroup(self, tuple(map(self, relations) ), **kwds)
__truediv__ = quotient | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/free_group.py | 0.834002 | 0.406185 | free_group.py | pypi |
from sage.libs.gap.libgap import libgap
from sage.libs.gap.element import GapElement
from sage.structure.element import parent
from sage.misc.cachefunc import cached_method
from sage.groups.class_function import ClassFunction_libgap
from sage.groups.libgap_wrapper import ElementLibGAP
class GroupMixinLibGAP():
def __contains__(self, elt):
r"""
TESTS::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: G = GroupLibGAP(libgap.SL(2,3))
sage: libgap([[1,0],[0,1]]) in G
False
sage: o = Mod(1, 3)
sage: z = Mod(0, 3)
sage: libgap([[o,z],[z,o]]) in G
True
sage: G.an_element() in GroupLibGAP(libgap.GL(2,3))
True
sage: G.an_element() in GroupLibGAP(libgap.GL(2,5))
False
"""
if parent(elt) is self:
return True
elif isinstance(elt, GapElement):
return elt in self.gap()
elif isinstance(elt, ElementLibGAP):
return elt.gap() in self.gap()
else:
try:
elt2 = self(elt)
except Exception:
return False
return elt == elt2
def is_abelian(self):
r"""
Return whether the group is Abelian.
OUTPUT:
Boolean. ``True`` if this group is an Abelian group and ``False``
otherwise.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.CyclicGroup(12)).is_abelian()
True
sage: GroupLibGAP(libgap.SymmetricGroup(12)).is_abelian()
False
sage: SL(1, 17).is_abelian()
True
sage: SL(2, 17).is_abelian()
False
"""
return self.gap().IsAbelian().sage()
def is_nilpotent(self):
r"""
Return whether this group is nilpotent.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.AlternatingGroup(3)).is_nilpotent()
True
sage: GroupLibGAP(libgap.SymmetricGroup(3)).is_nilpotent()
False
"""
return self.gap().IsNilpotentGroup().sage()
def is_solvable(self):
r"""
Return whether this group is solvable.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.SymmetricGroup(4)).is_solvable()
True
sage: GroupLibGAP(libgap.SymmetricGroup(5)).is_solvable()
False
"""
return self.gap().IsSolvableGroup().sage()
def is_supersolvable(self):
r"""
Return whether this group is supersolvable.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.SymmetricGroup(3)).is_supersolvable()
True
sage: GroupLibGAP(libgap.SymmetricGroup(4)).is_supersolvable()
False
"""
return self.gap().IsSupersolvableGroup().sage()
def is_polycyclic(self):
r"""
Return whether this group is polycyclic.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.AlternatingGroup(4)).is_polycyclic()
True
sage: GroupLibGAP(libgap.AlternatingGroup(5)).is_solvable()
False
"""
return self.gap().IsPolycyclicGroup().sage()
def is_perfect(self):
r"""
Return whether this group is perfect.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.SymmetricGroup(5)).is_perfect()
False
sage: GroupLibGAP(libgap.AlternatingGroup(5)).is_perfect()
True
sage: SL(3,3).is_perfect()
True
"""
return self.gap().IsPerfectGroup().sage()
def is_p_group(self):
r"""
Return whether this group is a p-group.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.CyclicGroup(9)).is_p_group()
True
sage: GroupLibGAP(libgap.CyclicGroup(10)).is_p_group()
False
"""
return self.gap().IsPGroup().sage()
def is_simple(self):
r"""
Return whether this group is simple.
EXAMPLES::
sage: from sage.groups.libgap_group import GroupLibGAP
sage: GroupLibGAP(libgap.SL(2,3)).is_simple()
False
sage: GroupLibGAP(libgap.SL(3,3)).is_simple()
True
sage: SL(3,3).is_simple()
True
"""
return self.gap().IsSimpleGroup().sage()
def is_finite(self):
"""
Test whether the matrix group is finite.
OUTPUT:
Boolean.
EXAMPLES::
sage: G = GL(2,GF(3))
sage: G.is_finite()
True
sage: SL(2,ZZ).is_finite()
False
"""
return self.gap().IsFinite().sage()
def cardinality(self):
"""
Implements :meth:`EnumeratedSets.ParentMethods.cardinality`.
EXAMPLES::
sage: G = Sp(4,GF(3))
sage: G.cardinality()
51840
sage: G = SL(4,GF(3))
sage: G.cardinality()
12130560
sage: F = GF(5); MS = MatrixSpace(F,2,2)
sage: gens = [MS([[1,2],[-1,1]]),MS([[1,1],[0,1]])]
sage: G = MatrixGroup(gens)
sage: G.cardinality()
480
sage: G = MatrixGroup([matrix(ZZ,2,[1,1,0,1])])
sage: G.cardinality()
+Infinity
sage: G = Sp(4,GF(3))
sage: G.cardinality()
51840
sage: G = SL(4,GF(3))
sage: G.cardinality()
12130560
sage: F = GF(5); MS = MatrixSpace(F,2,2)
sage: gens = [MS([[1,2],[-1,1]]),MS([[1,1],[0,1]])]
sage: G = MatrixGroup(gens)
sage: G.cardinality()
480
sage: G = MatrixGroup([matrix(ZZ,2,[1,1,0,1])])
sage: G.cardinality()
+Infinity
"""
return self.gap().Size().sage()
order = cardinality
@cached_method
def conjugacy_classes_representatives(self):
"""
Return a set of representatives for each of the conjugacy classes
of the group.
EXAMPLES::
sage: G = SU(3,GF(2))
sage: len(G.conjugacy_classes_representatives())
16
sage: G = GL(2,GF(3))
sage: G.conjugacy_classes_representatives()
(
[1 0] [0 2] [2 0] [0 2] [0 2] [0 1] [0 1] [2 0]
[0 1], [1 1], [0 2], [1 2], [1 0], [1 2], [1 1], [0 1]
)
sage: len(GU(2,GF(5)).conjugacy_classes_representatives())
36
::
sage: GL(2,ZZ).conjugacy_classes_representatives()
Traceback (most recent call last):
...
NotImplementedError: only implemented for finite groups
"""
if not self.is_finite():
raise NotImplementedError("only implemented for finite groups")
G = self.gap()
reps = [ cc.Representative() for cc in G.ConjugacyClasses() ]
return tuple(self(g) for g in reps)
def conjugacy_classes(self):
r"""
Return a list with all the conjugacy classes of ``self``.
EXAMPLES::
sage: G = SL(2, GF(2))
sage: G.conjugacy_classes()
(Conjugacy class of [1 0]
[0 1] in Special Linear Group of degree 2 over Finite Field of size 2,
Conjugacy class of [0 1]
[1 0] in Special Linear Group of degree 2 over Finite Field of size 2,
Conjugacy class of [0 1]
[1 1] in Special Linear Group of degree 2 over Finite Field of size 2)
::
sage: GL(2,ZZ).conjugacy_classes()
Traceback (most recent call last):
...
NotImplementedError: only implemented for finite groups
"""
if not self.is_finite():
raise NotImplementedError("only implemented for finite groups")
from sage.groups.conjugacy_classes import ConjugacyClassGAP
return tuple(ConjugacyClassGAP(self, self(g)) for g in self.conjugacy_classes_representatives())
def conjugacy_class(self, g):
r"""
Return the conjugacy class of ``g``.
OUTPUT:
The conjugacy class of ``g`` in the group ``self``. If ``self`` is the
group denoted by `G`, this method computes the set
`\{x^{-1}gx\ \vert\ x\in G\}`.
EXAMPLES::
sage: G = SL(2, QQ)
sage: g = G([[1,1],[0,1]])
sage: G.conjugacy_class(g)
Conjugacy class of [1 1]
[0 1] in Special Linear Group of degree 2 over Rational Field
"""
from sage.groups.conjugacy_classes import ConjugacyClassGAP
return ConjugacyClassGAP(self, self(g))
def class_function(self, values):
"""
Return the class function with given values.
INPUT:
- ``values`` -- list/tuple/iterable of numbers. The values of the
class function on the conjugacy classes, in that order.
EXAMPLES::
sage: G = GL(2,GF(3))
sage: chi = G.class_function(range(8))
sage: list(chi)
[0, 1, 2, 3, 4, 5, 6, 7]
"""
from sage.groups.class_function import ClassFunction_libgap
return ClassFunction_libgap(self, values)
@cached_method
def center(self):
"""
Return the center of this linear group as a subgroup.
OUTPUT:
The center as a subgroup.
EXAMPLES::
sage: G = SU(3,GF(2))
sage: G.center()
Subgroup with 1 generators (
[a 0 0]
[0 a 0]
[0 0 a]
) of Special Unitary Group of degree 3 over Finite Field in a of size 2^2
sage: GL(2,GF(3)).center()
Subgroup with 1 generators (
[2 0]
[0 2]
) of General Linear Group of degree 2 over Finite Field of size 3
sage: GL(3,GF(3)).center()
Subgroup with 1 generators (
[2 0 0]
[0 2 0]
[0 0 2]
) of General Linear Group of degree 3 over Finite Field of size 3
sage: GU(3,GF(2)).center()
Subgroup with 1 generators (
[a + 1 0 0]
[ 0 a + 1 0]
[ 0 0 a + 1]
) of General Unitary Group of degree 3 over Finite Field in a of size 2^2
sage: A = Matrix(FiniteField(5), [[2,0,0], [0,3,0], [0,0,1]])
sage: B = Matrix(FiniteField(5), [[1,0,0], [0,1,0], [0,1,1]])
sage: MatrixGroup([A,B]).center()
Subgroup with 1 generators (
[1 0 0]
[0 1 0]
[0 0 1]
) of Matrix group over Finite Field of size 5 with 2 generators (
[2 0 0] [1 0 0]
[0 3 0] [0 1 0]
[0 0 1], [0 1 1]
)
"""
G = self.gap()
center = list(G.Center().GeneratorsOfGroup())
if len(center) == 0:
center = [G.One()]
return self.subgroup(center)
def intersection(self, other):
"""
Return the intersection of two groups (if it makes sense) as a
subgroup of the first group.
EXAMPLES::
sage: A = Matrix([(0, 1/2, 0), (2, 0, 0), (0, 0, 1)])
sage: B = Matrix([(0, 1/2, 0), (-2, -1, 2), (0, 0, 1)])
sage: G = MatrixGroup([A,B])
sage: len(G) # isomorphic to S_3
6
sage: G.intersection(GL(3,ZZ))
Subgroup with 1 generators (
[ 1 0 0]
[-2 -1 2]
[ 0 0 1]
) of Matrix group over Rational Field with 2 generators (
[ 0 1/2 0] [ 0 1/2 0]
[ 2 0 0] [ -2 -1 2]
[ 0 0 1], [ 0 0 1]
)
sage: GL(3,ZZ).intersection(G)
Subgroup with 1 generators (
[ 1 0 0]
[-2 -1 2]
[ 0 0 1]
) of General Linear Group of degree 3 over Integer Ring
sage: G.intersection(SL(3,ZZ))
Subgroup with 0 generators () of Matrix group over Rational Field with 2 generators (
[ 0 1/2 0] [ 0 1/2 0]
[ 2 0 0] [ -2 -1 2]
[ 0 0 1], [ 0 0 1]
)
"""
G = self.gap()
H = other.gap()
C = G.Intersection(H)
return self.subgroup(C.GeneratorsOfGroup())
@cached_method
def irreducible_characters(self):
"""
Return the irreducible characters of the group.
OUTPUT:
A tuple containing all irreducible characters.
EXAMPLES::
sage: G = GL(2,2)
sage: G.irreducible_characters()
(Character of General Linear Group of degree 2 over Finite Field of size 2,
Character of General Linear Group of degree 2 over Finite Field of size 2,
Character of General Linear Group of degree 2 over Finite Field of size 2)
::
sage: GL(2,ZZ).irreducible_characters()
Traceback (most recent call last):
...
NotImplementedError: only implemented for finite groups
"""
if not self.is_finite():
raise NotImplementedError("only implemented for finite groups")
Irr = self.gap().Irr()
L = []
for irr in Irr:
L.append(ClassFunction_libgap(self, irr))
return tuple(L)
def character(self, values):
r"""
Return a group character from ``values``, where ``values`` is
a list of the values of the character evaluated on the conjugacy
classes.
INPUT:
- ``values`` -- a list of values of the character
OUTPUT: a group character
EXAMPLES::
sage: G = MatrixGroup(AlternatingGroup(4))
sage: G.character([1]*len(G.conjugacy_classes_representatives()))
Character of Matrix group over Integer Ring with 12 generators
::
sage: G = GL(2,ZZ)
sage: G.character([1,1,1,1])
Traceback (most recent call last):
...
NotImplementedError: only implemented for finite groups
"""
if not self.is_finite():
raise NotImplementedError("only implemented for finite groups")
return ClassFunction_libgap(self, values)
def trivial_character(self):
r"""
Return the trivial character of this group.
OUTPUT: a group character
EXAMPLES::
sage: MatrixGroup(SymmetricGroup(3)).trivial_character()
Character of Matrix group over Integer Ring with 6 generators
::
sage: GL(2,ZZ).trivial_character()
Traceback (most recent call last):
...
NotImplementedError: only implemented for finite groups
"""
if not self.is_finite():
raise NotImplementedError("only implemented for finite groups")
values = [1]*self._gap_().NrConjugacyClasses().sage()
return self.character(values)
def character_table(self):
r"""
Return the matrix of values of the irreducible characters of this
group `G` at its conjugacy classes.
The columns represent the conjugacy classes of
`G` and the rows represent the different irreducible
characters in the ordering given by GAP.
OUTPUT: a matrix defined over a cyclotomic field
EXAMPLES::
sage: MatrixGroup(SymmetricGroup(2)).character_table()
[ 1 -1]
[ 1 1]
sage: MatrixGroup(SymmetricGroup(3)).character_table()
[ 1 1 -1]
[ 2 -1 0]
[ 1 1 1]
sage: MatrixGroup(SymmetricGroup(5)).character_table()
[ 1 -1 -1 1 -1 1 1]
[ 4 0 1 -1 -2 1 0]
[ 5 1 -1 0 -1 -1 1]
[ 6 0 0 1 0 0 -2]
[ 5 -1 1 0 1 -1 1]
[ 4 0 -1 -1 2 1 0]
[ 1 1 1 1 1 1 1]
"""
#code from function in permgroup.py, but modified for
#how gap handles these groups.
G = self._gap_()
cl = self.conjugacy_classes()
from sage.rings.integer import Integer
n = Integer(len(cl))
irrG = G.Irr()
ct = [[irrG[i][j] for j in range(n)] for i in range(n)]
from sage.rings.all import CyclotomicField
e = irrG.Flat().Conductor()
K = CyclotomicField(e)
ct = [[K(x) for x in v] for v in ct]
# Finally return the result as a matrix.
from sage.matrix.all import MatrixSpace
MS = MatrixSpace(K, n)
return MS(ct)
def random_element(self):
"""
Return a random element of this group.
OUTPUT:
A group element.
EXAMPLES::
sage: G = Sp(4,GF(3))
sage: G.random_element() # random
[2 1 1 1]
[1 0 2 1]
[0 1 1 0]
[1 0 0 1]
sage: G.random_element() in G
True
sage: F = GF(5); MS = MatrixSpace(F,2,2)
sage: gens = [MS([[1,2],[-1,1]]),MS([[1,1],[0,1]])]
sage: G = MatrixGroup(gens)
sage: G.random_element() # random
[1 3]
[0 3]
sage: G.random_element() in G
True
"""
return self(self.gap().Random())
def __iter__(self):
"""
Iterate over the elements of the group.
EXAMPLES::
sage: F = GF(3)
sage: gens = [matrix(F,2, [1,0, -1,1]), matrix(F, 2, [1,1,0,1])]
sage: G = MatrixGroup(gens)
sage: next(iter(G))
[1 0]
[0 1]
sage: from sage.groups.libgap_group import GroupLibGAP
sage: G = GroupLibGAP(libgap.AlternatingGroup(5))
sage: sum(1 for g in G)
60
"""
if self.list.cache is not None:
for g in self.list():
yield g
return
iterator = self.gap().Iterator()
while not iterator.IsDoneIterator().sage():
yield self.element_class(self, iterator.NextIterator())
def __len__(self):
"""
Return the number of elements in ``self``.
EXAMPLES::
sage: F = GF(3)
sage: gens = [matrix(F,2, [1,-1,0,1]), matrix(F, 2, [1,1,-1,1])]
sage: G = MatrixGroup(gens)
sage: len(G)
48
An error is raised if the group is not finite::
sage: len(GL(2,ZZ))
Traceback (most recent call last):
...
NotImplementedError: group must be finite
"""
size = self.gap().Size()
if size.IsInfinity():
raise NotImplementedError("group must be finite")
return int(size)
@cached_method
def list(self):
"""
List all elements of this group.
OUTPUT:
A tuple containing all group elements in a random but fixed
order.
EXAMPLES::
sage: F = GF(3)
sage: gens = [matrix(F,2, [1,0,-1,1]), matrix(F, 2, [1,1,0,1])]
sage: G = MatrixGroup(gens)
sage: G.cardinality()
24
sage: v = G.list()
sage: len(v)
24
sage: v[:5]
(
[1 0] [2 0] [0 1] [0 2] [1 2]
[0 1], [0 2], [2 0], [1 0], [2 2]
)
sage: all(g in G for g in G.list())
True
An example over a ring (see :trac:`5241`)::
sage: M1 = matrix(ZZ,2,[[-1,0],[0,1]])
sage: M2 = matrix(ZZ,2,[[1,0],[0,-1]])
sage: M3 = matrix(ZZ,2,[[-1,0],[0,-1]])
sage: MG = MatrixGroup([M1, M2, M3])
sage: MG.list()
(
[1 0] [ 1 0] [-1 0] [-1 0]
[0 1], [ 0 -1], [ 0 1], [ 0 -1]
)
sage: MG.list()[1]
[ 1 0]
[ 0 -1]
sage: MG.list()[1].parent()
Matrix group over Integer Ring with 3 generators (
[-1 0] [ 1 0] [-1 0]
[ 0 1], [ 0 -1], [ 0 -1]
)
An example over a field (see :trac:`10515`)::
sage: gens = [matrix(QQ,2,[1,0,0,1])]
sage: MatrixGroup(gens).list()
(
[1 0]
[0 1]
)
Another example over a ring (see :trac:`9437`)::
sage: len(SL(2, Zmod(4)).list())
48
An error is raised if the group is not finite::
sage: GL(2,ZZ).list()
Traceback (most recent call last):
...
NotImplementedError: group must be finite
"""
if not self.is_finite():
raise NotImplementedError('group must be finite')
return tuple(self.element_class(self, g) for g in self.gap().AsList())
def is_isomorphic(self, H):
"""
Test whether ``self`` and ``H`` are isomorphic groups.
INPUT:
- ``H`` -- a group.
OUTPUT:
Boolean.
EXAMPLES::
sage: m1 = matrix(GF(3), [[1,1],[0,1]])
sage: m2 = matrix(GF(3), [[1,2],[0,1]])
sage: F = MatrixGroup(m1)
sage: G = MatrixGroup(m1, m2)
sage: H = MatrixGroup(m2)
sage: F.is_isomorphic(G)
True
sage: G.is_isomorphic(H)
True
sage: F.is_isomorphic(H)
True
sage: F == G, G == H, F == H
(False, False, False)
"""
return self.gap().IsomorphismGroups(H.gap()) != libgap.fail | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/libgap_mixin.py | 0.843057 | 0.364382 | libgap_mixin.py | pypi |
from sage.structure.element import MultiplicativeGroupElement
from sage.misc.cachefunc import cached_method
from sage.arith.all import GCD, LCM
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.infinity import infinity
from sage.structure.richcmp import richcmp
class AbelianGroupElementBase(MultiplicativeGroupElement):
"""
Base class for abelian group elements
The group element is defined by a tuple whose ``i``-th entry is an
integer in the range from 0 (inclusively) to ``G.gen(i).order()``
(exclusively) if the `i`-th generator is of finite order, and an
arbitrary integer if the `i`-th generator is of infinite order.
INPUT:
- ``exponents`` -- ``1`` or a list/tuple/iterable of integers. The
exponent vector (with respect to the parent generators) defining
the group element.
- ``parent`` -- Abelian group. The parent of the group element.
EXAMPLES::
sage: F = AbelianGroup(3,[7,8,9])
sage: Fd = F.dual_group(names="ABC")
sage: A,B,C = Fd.gens()
sage: A*B^-1 in Fd
True
"""
def __init__(self, parent, exponents):
"""
Create an element.
EXAMPLES::
sage: F = AbelianGroup(3,[7,8,9])
sage: Fd = F.dual_group(names="ABC")
sage: A,B,C = Fd.gens()
sage: A*B^-1 in Fd
True
"""
MultiplicativeGroupElement.__init__(self, parent)
n = parent.ngens()
if exponents == 1:
self._exponents = tuple( ZZ.zero() for i in range(n) )
else:
self._exponents = tuple( ZZ(e) for e in exponents )
if len(self._exponents) != n:
raise IndexError('argument length (= %s) must be %s.'%(len(exponents), n))
def __hash__(self):
r"""
TESTS::
sage: F = AbelianGroup(3,[7,8,9])
sage: hash(F.an_element()) # random
1024
"""
return hash(self.parent()) ^ hash(self._exponents)
def exponents(self):
"""
The exponents of the generators defining the group element.
OUTPUT:
A tuple of integers for an abelian group element. The integer
can be arbitrary if the corresponding generator has infinite
order. If the generator is of finite order, the integer is in
the range from 0 (inclusive) to the order (exclusive).
EXAMPLES::
sage: F.<a,b,c,f> = AbelianGroup([7,8,9,0])
sage: (a^3*b^2*c).exponents()
(3, 2, 1, 0)
sage: F([3, 2, 1, 0])
a^3*b^2*c
sage: (c^42).exponents()
(0, 0, 6, 0)
sage: (f^42).exponents()
(0, 0, 0, 42)
"""
return self._exponents
def _libgap_(self):
r"""
TESTS::
sage: F.<a,b,c> = AbelianGroup([7,8,9])
sage: libgap(a**2 * c) * libgap(b * c**2)
f1^2*f2*f6
"""
from sage.misc.misc_c import prod
from sage.libs.gap.libgap import libgap
G = libgap(self.parent())
return prod(g**i for g,i in zip(G.GeneratorsOfGroup(), self._exponents))
def list(self):
"""
Return a copy of the exponent vector.
Use :meth:`exponents` instead.
OUTPUT:
The underlying coordinates used to represent this element. If
this is a word in an abelian group on `n` generators, then
this is a list of nonnegative integers of length `n`.
EXAMPLES::
sage: F = AbelianGroup(5,[2, 3, 5, 7, 8], names="abcde")
sage: a,b,c,d,e = F.gens()
sage: Ad = F.dual_group(names="ABCDE")
sage: A,B,C,D,E = Ad.gens()
sage: (A*B*C^2*D^20*E^65).exponents()
(1, 1, 2, 6, 1)
sage: X = A*B*C^2*D^2*E^-6
sage: X.exponents()
(1, 1, 2, 2, 2)
"""
# to be deprecated (really, return a list??). Use exponents() instead.
return list(self._exponents)
def _repr_(self):
"""
Return a string representation of ``self``.
OUTPUT:
String.
EXAMPLES::
sage: G = AbelianGroup([2])
sage: G.gen(0)._repr_()
'f'
sage: G.one()._repr_()
'1'
"""
s = ""
G = self.parent()
for v_i, x_i in zip(self.exponents(), G.variable_names()):
if v_i == 0:
continue
if len(s) > 0:
s += '*'
if v_i == 1:
s += str(x_i)
else:
s += str(x_i) + '^' + str(v_i)
if s:
return s
else:
return '1'
def _richcmp_(self, other, op):
"""
Compare ``self`` and ``other``.
The comparison is based on the exponents.
OUTPUT:
boolean
EXAMPLES::
sage: G.<a,b> = AbelianGroup([2,3])
sage: a > b
True
sage: Gd.<A,B> = G.dual_group()
sage: A > B
True
"""
return richcmp(self._exponents, other._exponents, op)
@cached_method
def order(self):
"""
Return the order of this element.
OUTPUT:
An integer or ``infinity``.
EXAMPLES::
sage: F = AbelianGroup(3,[7,8,9])
sage: Fd = F.dual_group()
sage: A,B,C = Fd.gens()
sage: (B*C).order()
72
sage: F = AbelianGroup(3,[7,8,9]); F
Multiplicative Abelian group isomorphic to C7 x C8 x C9
sage: F.gens()[2].order()
9
sage: a,b,c = F.gens()
sage: (b*c).order()
72
sage: G = AbelianGroup(3,[7,8,9])
sage: type((G.0 * G.1).order())==Integer
True
"""
M = self.parent()
order = M.gens_orders()
L = self.exponents()
N = LCM([order[i]/GCD(order[i],L[i]) for i in range(len(order)) if L[i]!=0])
if N == 0:
return infinity
else:
return ZZ(N)
multiplicative_order = order
def _div_(left, right):
"""
Divide ``left`` and ``right``
TESTS::
sage: G.<a,b> = AbelianGroup(2)
sage: a/b
a*b^-1
sage: a._div_(b)
a*b^-1
"""
G = left.parent()
assert G is right.parent()
exponents = [ (x-y)%order if order!=0 else x-y
for x, y, order in
zip(left._exponents, right._exponents, G.gens_orders()) ]
return G.element_class(G, exponents)
def _mul_(left, right):
"""
Multiply ``left`` and ``right``
TESTS::
sage: G.<a,b> = AbelianGroup(2)
sage: a*b
a*b
sage: a._mul_(b)
a*b
"""
G = left.parent()
assert G is right.parent()
exponents = [ (x+y)%order if order!=0 else x+y
for x, y, order in
zip(left._exponents, right._exponents, G.gens_orders()) ]
return G.element_class(G, exponents)
def __pow__(self, n):
"""
Exponentiate ``self``
TESTS::
sage: G.<a,b> = AbelianGroup(2)
sage: a^3
a^3
"""
m = Integer(n)
if n != m:
raise TypeError('argument n (= '+str(n)+') must be an integer.')
G = self.parent()
exponents = [ (m*e) % order if order!=0 else m*e
for e,order in zip(self._exponents, G.gens_orders()) ]
return G.element_class(G, exponents)
def __invert__(self):
"""
Return the inverse element.
EXAMPLES::
sage: G.<a,b> = AbelianGroup([0,5])
sage: a.inverse() # indirect doctest
a^-1
sage: a.__invert__()
a^-1
sage: a^-1
a^-1
sage: ~a
a^-1
sage: (a*b).exponents()
(1, 1)
sage: (a*b).inverse().exponents()
(-1, 4)
"""
G = self.parent()
exponents = [(-e) % order if order != 0 else -e
for e, order in zip(self._exponents, G.gens_orders())]
return G.element_class(G, exponents)
def is_trivial(self):
"""
Test whether ``self`` is the trivial group element ``1``.
OUTPUT:
Boolean.
EXAMPLES::
sage: G.<a,b> = AbelianGroup([0,5])
sage: (a^5).is_trivial()
False
sage: (b^5).is_trivial()
True
"""
return all(e==0 for e in self._exponents) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/abelian_gps/element_base.py | 0.856737 | 0.467575 | element_base.py | pypi |
from sage.arith.all import LCM
from sage.groups.abelian_gps.element_base import AbelianGroupElementBase
def is_DualAbelianGroupElement(x) -> bool:
"""
Test whether ``x`` is a dual Abelian group element.
INPUT:
- ``x`` -- anything
OUTPUT:
Boolean
EXAMPLES::
sage: from sage.groups.abelian_gps.dual_abelian_group import is_DualAbelianGroupElement
sage: F = AbelianGroup(5,[5,5,7,8,9],names = list("abcde")).dual_group()
sage: is_DualAbelianGroupElement(F)
False
sage: is_DualAbelianGroupElement(F.an_element())
True
"""
return isinstance(x, DualAbelianGroupElement)
class DualAbelianGroupElement(AbelianGroupElementBase):
"""
Base class for abelian group elements
"""
def __call__(self, g):
"""
Evaluate ``self`` on a group element ``g``.
OUTPUT:
An element in
:meth:`~sage.groups.abelian_gps.dual_abelian_group.DualAbelianGroup_class.base_ring`.
EXAMPLES::
sage: F = AbelianGroup(5, [2,3,5,7,8], names="abcde")
sage: a,b,c,d,e = F.gens()
sage: Fd = F.dual_group(names="ABCDE")
sage: A,B,C,D,E = Fd.gens()
sage: A*B^2*D^7
A*B^2
sage: A(a)
-1
sage: B(b)
zeta840^140 - 1
sage: CC(B(b)) # abs tol 1e-8
-0.499999999999995 + 0.866025403784447*I
sage: A(a*b)
-1
TESTS::
sage: F = AbelianGroup(1, [7], names="a")
sage: a, = F.gens()
sage: Fd = F.dual_group(names="A", base_ring=GF(29))
sage: A, = Fd.gens()
sage: A(a)
16
"""
F = self.parent().base_ring()
expsX = self.exponents()
expsg = g.exponents()
order = self.parent().gens_orders()
N = LCM(order)
order_not = [N / o for o in order]
zeta = F.zeta(N)
return F.prod(zeta**(expsX[i] * expsg[i] * order_not[i])
for i in range(len(expsX)))
def word_problem(self, words):
"""
This is a rather hackish method and is included for completeness.
The word problem for an instance of DualAbelianGroup as it can
for an AbelianGroup. The reason why is that word problem
for an instance of AbelianGroup simply calls GAP (which
has abelian groups implemented) and invokes "EpimorphismFromFreeGroup"
and "PreImagesRepresentative". GAP does not have duals of
abelian groups implemented. So, by using the same name
for the generators, the method below converts the problem for
the dual group to the corresponding problem on the group
itself and uses GAP to solve that.
EXAMPLES::
sage: G = AbelianGroup(5,[3, 5, 5, 7, 8],names="abcde")
sage: Gd = G.dual_group(names="abcde")
sage: a,b,c,d,e = Gd.gens()
sage: u = a^3*b*c*d^2*e^5
sage: v = a^2*b*c^2*d^3*e^3
sage: w = a^7*b^3*c^5*d^4*e^4
sage: x = a^3*b^2*c^2*d^3*e^5
sage: y = a^2*b^4*c^2*d^4*e^5
sage: e.word_problem([u,v,w,x,y])
[[b^2*c^2*d^3*e^5, 245]]
"""
from sage.libs.gap.libgap import libgap
A = libgap.AbelianGroup(self.parent().gens_orders())
gens = A.GeneratorsOfGroup()
gap_g = libgap.Product([gi**Li for gi, Li in zip(gens, self.list())])
gensH = [libgap.Product([gi**Li for gi, Li in zip(gens, w.list())])
for w in words]
H = libgap.Group(gensH)
hom = H.EpimorphismFromFreeGroup()
ans = hom.PreImagesRepresentative(gap_g)
resu = ans.ExtRepOfObj().sage() # (indice, power, indice, power, etc)
indices = resu[0::2]
powers = resu[1::2]
return [[words[indi - 1], powi] for indi, powi in zip(indices, powers)] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/abelian_gps/dual_abelian_group_element.py | 0.811377 | 0.598957 | dual_abelian_group_element.py | pypi |
from sage.groups.abelian_gps.element_base import AbelianGroupElementBase
def is_AbelianGroupElement(x):
"""
Return true if x is an abelian group element, i.e., an element of
type AbelianGroupElement.
EXAMPLES: Though the integer 3 is in the integers, and the integers
have an abelian group structure, 3 is not an AbelianGroupElement::
sage: from sage.groups.abelian_gps.abelian_group_element import is_AbelianGroupElement
sage: is_AbelianGroupElement(3)
False
sage: F = AbelianGroup(5, [3,4,5,8,7], 'abcde')
sage: is_AbelianGroupElement(F.0)
True
"""
return isinstance(x, AbelianGroupElement)
class AbelianGroupElement(AbelianGroupElementBase):
"""
Elements of an
:class:`~sage.groups.abelian_gps.abelian_group.AbelianGroup`
INPUT:
- ``x`` -- list/tuple/iterable of integers (the element vector)
- ``parent`` -- the parent
:class:`~sage.groups.abelian_gps.abelian_group.AbelianGroup`
EXAMPLES::
sage: F = AbelianGroup(5, [3,4,5,8,7], 'abcde')
sage: a, b, c, d, e = F.gens()
sage: a^2 * b^3 * a^2 * b^-4
a*b^3
sage: b^-11
b
sage: a^-11
a
sage: a*b in F
True
"""
def as_permutation(self):
r"""
Return the element of the permutation group G (isomorphic to the
abelian group A) associated to a in A.
EXAMPLES::
sage: G = AbelianGroup(3,[2,3,4],names="abc"); G
Multiplicative Abelian group isomorphic to C2 x C3 x C4
sage: a,b,c = G.gens()
sage: Gp = G.permutation_group(); Gp
Permutation Group with generators [(6,7,8,9), (3,4,5), (1,2)]
sage: a.as_permutation()
(1,2)
sage: ap = a.as_permutation(); ap
(1,2)
sage: ap in Gp
True
"""
from sage.libs.gap.libgap import libgap
G = self.parent()
A = libgap.AbelianGroup(G.gens_orders())
phi = libgap.IsomorphismPermGroup(A)
gens = libgap.GeneratorsOfGroup(A)
L2 = libgap.Product([geni**Li for geni, Li in zip(gens, self.list())])
pg = libgap.Image(phi, L2)
return G.permutation_group()(pg)
def word_problem(self, words):
"""
TODO - this needs a rewrite - see stuff in the matrix_grp
directory.
G and H are abelian groups, g in G, H is a subgroup of G generated
by a list (words) of elements of G. If self is in H, return the
expression for self as a word in the elements of (words).
This function does not solve the word problem in Sage. Rather
it pushes it over to GAP, which has optimized (non-deterministic)
algorithms for the word problem.
.. warning::
Don't use E (or other GAP-reserved letters) as a generator
name.
EXAMPLES::
sage: G = AbelianGroup(2,[2,3], names="xy")
sage: x,y = G.gens()
sage: x.word_problem([x,y])
[[x, 1]]
sage: y.word_problem([x,y])
[[y, 1]]
sage: v = (y*x).word_problem([x,y]); v #random
[[x, 1], [y, 1]]
sage: prod([x^i for x,i in v]) == y*x
True
"""
from sage.groups.abelian_gps.abelian_group import word_problem
return word_problem(words, self) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/abelian_gps/abelian_group_element.py | 0.823399 | 0.557424 | abelian_group_element.py | pypi |
from . import permgroup_element
from sage.misc.sage_eval import sage_eval
from sage.misc.lazy_import import lazy_import
from sage.interfaces.gap import GapElement
from sage.libs.pari.all import pari_gen
from sage.libs.gap.element import GapElement_Permutation
lazy_import('sage.combinat.permutation', ['Permutation', 'from_cycles'])
def PermutationGroupElement(g, parent=None, check=True):
r"""
Builds a permutation from ``g``.
INPUT:
- ``g`` -- either
- a list of images
- a tuple describing a single cycle
- a list of tuples describing the cycle decomposition
- a string describing the cycle decomposition
- ``parent`` -- (optional) an ambient permutation group for the result;
it is mandatory if you want a permutation on a domain different
from `\{1, \ldots, n\}`
- ``check`` -- (default: ``True``) whether additional check are performed;
setting it to ``False`` is likely to result in faster code
EXAMPLES:
Initialization as a list of images::
sage: p = PermutationGroupElement([1,4,2,3])
sage: p
(2,4,3)
sage: p.parent()
Symmetric group of order 4! as a permutation group
Initialization as a list of cycles::
sage: p = PermutationGroupElement([(3,5),(4,6,9)])
sage: p
(3,5)(4,6,9)
sage: p.parent()
Symmetric group of order 9! as a permutation group
Initialization as a string representing a cycle decomposition::
sage: p = PermutationGroupElement('(2,4)(3,5)')
sage: p
(2,4)(3,5)
sage: p.parent()
Symmetric group of order 5! as a permutation group
By default the constructor assumes that the domain is `\{1, \dots, n\}`
but it can be set to anything via its second ``parent`` argument::
sage: S = SymmetricGroup(['a', 'b', 'c', 'd', 'e'])
sage: PermutationGroupElement(['e', 'c', 'b', 'a', 'd'], S)
('a','e','d')('b','c')
sage: PermutationGroupElement(('a', 'b', 'c'), S)
('a','b','c')
sage: PermutationGroupElement([('a', 'c'), ('b', 'e')], S)
('a','c')('b','e')
sage: PermutationGroupElement("('a','b','e')('c','d')", S)
('a','b','e')('c','d')
But in this situation, you might want to use the more direct::
sage: S(['e', 'c', 'b', 'a', 'd'])
('a','e','d')('b','c')
sage: S(('a', 'b', 'c'))
('a','b','c')
sage: S([('a', 'c'), ('b', 'e')])
('a','c')('b','e')
sage: S("('a','b','e')('c','d')")
('a','b','e')('c','d')
"""
if isinstance(g, permgroup_element.PermutationGroupElement):
if parent is None or g.parent() is parent:
return g
if parent is None:
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
try:
v = standardize_generator(g, None)
except KeyError:
raise ValueError("invalid permutation vector: %s" % g)
parent = SymmetricGroup(len(v))
# We have constructed the parent from the element and already checked
# that it is a valid permutation
check = False
return parent.element_class(g, parent, check)
def string_to_tuples(g):
"""
EXAMPLES::
sage: from sage.groups.perm_gps.constructor import string_to_tuples
sage: string_to_tuples('(1,2,3)')
[(1, 2, 3)]
sage: string_to_tuples('(1,2,3)(4,5)')
[(1, 2, 3), (4, 5)]
sage: string_to_tuples(' (1,2, 3) (4,5)')
[(1, 2, 3), (4, 5)]
sage: string_to_tuples('(1,2)(3)')
[(1, 2), (3,)]
"""
if not isinstance(g, str):
raise ValueError("g (= %s) must be a string" % g)
elif g == '()':
return []
g = g.replace('\n', '').replace(' ', '').replace(')(', '),(').replace(')', ',)')
g = '[' + g + ']'
return sage_eval(g, preparse=False)
def standardize_generator(g, convert_dict=None, as_cycles=False):
r"""
Standardize the input for permutation group elements to a list
or a list of tuples.
This was factored out of the
``PermutationGroupElement.__init__`` since
``PermutationGroup_generic.__init__`` needs to do the same computation
in order to compute the domain of a group when it's not explicitly
specified.
INPUT:
- ``g`` -- a list, tuple, string, GapElement,
PermutationGroupElement, Permutation
- ``convert_dict`` -- (optional) a dictionary used to convert the
points to a number compatible with GAP
- ``as_cycles`` -- (default: ``False``) whether the output should be
as cycles or in one-line notation
OUTPUT:
The permutation in as a list in one-line notation or a list of cycles
as tuples.
EXAMPLES::
sage: from sage.groups.perm_gps.constructor import standardize_generator
sage: standardize_generator('(1,2)')
[2, 1]
sage: p = PermutationGroupElement([(1,2)])
sage: standardize_generator(p)
[2, 1]
sage: standardize_generator(p._gap_())
[2, 1]
sage: standardize_generator((1,2))
[2, 1]
sage: standardize_generator([(1,2)])
[2, 1]
sage: standardize_generator(p, as_cycles=True)
[(1, 2)]
sage: standardize_generator(p._gap_(), as_cycles=True)
[(1, 2)]
sage: standardize_generator((1,2), as_cycles=True)
[(1, 2)]
sage: standardize_generator([(1,2)], as_cycles=True)
[(1, 2)]
sage: standardize_generator(Permutation([2,1,3]))
[2, 1, 3]
sage: standardize_generator(Permutation([2,1,3]), as_cycles=True)
[(1, 2), (3,)]
::
sage: d = {'a': 1, 'b': 2}
sage: p = SymmetricGroup(['a', 'b']).gen(0); p
('a','b')
sage: standardize_generator(p, convert_dict=d)
[2, 1]
sage: standardize_generator(p._gap_(), convert_dict=d)
[2, 1]
sage: standardize_generator(('a','b'), convert_dict=d)
[2, 1]
sage: standardize_generator([('a','b')], convert_dict=d)
[2, 1]
sage: standardize_generator(p, convert_dict=d, as_cycles=True)
[(1, 2)]
sage: standardize_generator(p._gap_(), convert_dict=d, as_cycles=True)
[(1, 2)]
sage: standardize_generator(('a','b'), convert_dict=d, as_cycles=True)
[(1, 2)]
sage: standardize_generator([('a','b')], convert_dict=d, as_cycles=True)
[(1, 2)]
"""
if isinstance(g, pari_gen):
g = list(g)
needs_conversion = True
if isinstance(g, GapElement_Permutation):
g = g.sage()
needs_conversion = False
if isinstance(g, GapElement):
g = str(g)
needs_conversion = False
if isinstance(g, Permutation):
if as_cycles:
return g.cycle_tuples()
return g._list
elif isinstance(g, permgroup_element.PermutationGroupElement):
if not as_cycles:
l = list(range(1, g.parent().degree() + 1))
return g._act_on_list_on_position(l)
g = g.cycle_tuples()
elif isinstance(g, str):
g = string_to_tuples(g)
elif isinstance(g, tuple) and (len(g) == 0 or not isinstance(g[0], tuple)):
g = [g]
# Get the permutation in list notation
if isinstance(g, list) and not (g and isinstance(g[0], tuple)):
if convert_dict is not None and needs_conversion:
for i, x in enumerate(g):
g[i] = convert_dict[x]
if as_cycles:
return Permutation(g).cycle_tuples()
return g
# Otherwise it is in cycle notation
if convert_dict is not None and needs_conversion:
g = [tuple([convert_dict[x] for x in cycle]) for cycle in g]
if not as_cycles:
degree = max([1] + [max(cycle + (1,)) for cycle in g])
g = from_cycles(degree, g)
return g | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/perm_gps/constructor.py | 0.758466 | 0.502502 | constructor.py | pypi |
r"""
Semimonomial transformation group
The semimonomial transformation group of degree `n` over a ring `R` is
the semidirect product of the monomial transformation group of degree `n`
(also known as the complete monomial group over the group of units
`R^{\times}` of `R`) and the group of ring automorphisms.
The multiplication of two elements `(\phi, \pi, \alpha)(\psi, \sigma, \beta)`
with
- `\phi, \psi \in {R^{\times}}^n`
- `\pi, \sigma \in S_n` (with the multiplication `\pi\sigma`
done from left to right (like in GAP) --
that is, `(\pi\sigma)(i) = \sigma(\pi(i))` for all `i`.)
- `\alpha, \beta \in Aut(R)`
is defined by
.. MATH::
(\phi, \pi, \alpha)(\psi, \sigma, \beta) =
(\phi \cdot \psi^{\pi, \alpha}, \pi\sigma, \alpha \circ \beta)
where
`\psi^{\pi, \alpha} = (\alpha(\psi_{\pi(1)-1}), \ldots, \alpha(\psi_{\pi(n)-1}))`
and the multiplication of vectors is defined elementwisely. (The indexing
of vectors is `0`-based here, so `\psi = (\psi_0, \psi_1, \ldots, \psi_{n-1})`.)
.. TODO::
Up to now, this group is only implemented for finite fields because of
the limited support of automorphisms for arbitrary rings.
AUTHORS:
- Thomas Feulner (2012-11-15): initial version
EXAMPLES::
sage: S = SemimonomialTransformationGroup(GF(4, 'a'), 4)
sage: G = S.gens()
sage: G[0]*G[1]
((a, 1, 1, 1); (1,2,3,4), Ring endomorphism of Finite Field in a of size 2^2
Defn: a |--> a)
TESTS::
sage: TestSuite(S).run()
sage: TestSuite(S.an_element()).run()
"""
from __future__ import annotations
from sage.rings.integer import Integer
from sage.groups.group import FiniteGroup
from sage.structure.unique_representation import UniqueRepresentation
from sage.categories.action import Action
from sage.combinat.permutation import Permutation
from sage.groups.semimonomial_transformations.semimonomial_transformation import SemimonomialTransformation
class SemimonomialTransformationGroup(FiniteGroup, UniqueRepresentation):
r"""
A semimonomial transformation group over a ring.
The semimonomial transformation group of degree `n` over a ring `R` is
the semidirect product of the monomial transformation group of degree `n`
(also known as the complete monomial group over the group of units
`R^{\times}` of `R`) and the group of ring automorphisms.
The multiplication of two elements `(\phi, \pi, \alpha)(\psi, \sigma, \beta)`
with
- `\phi, \psi \in {R^{\times}}^n`
- `\pi, \sigma \in S_n` (with the multiplication `\pi\sigma`
done from left to right (like in GAP) --
that is, `(\pi\sigma)(i) = \sigma(\pi(i))` for all `i`.)
- `\alpha, \beta \in Aut(R)`
is defined by
.. MATH::
(\phi, \pi, \alpha)(\psi, \sigma, \beta) =
(\phi \cdot \psi^{\pi, \alpha}, \pi\sigma, \alpha \circ \beta)
where
`\psi^{\pi, \alpha} = (\alpha(\psi_{\pi(1)-1}), \ldots, \alpha(\psi_{\pi(n)-1}))`
and the multiplication of vectors is defined elementwisely. (The indexing
of vectors is `0`-based here, so `\psi = (\psi_0, \psi_1, \ldots, \psi_{n-1})`.)
.. TODO::
Up to now, this group is only implemented for finite fields because of
the limited support of automorphisms for arbitrary rings.
EXAMPLES::
sage: F.<a> = GF(9)
sage: S = SemimonomialTransformationGroup(F, 4)
sage: g = S(v = [2, a, 1, 2])
sage: h = S(perm = Permutation('(1,2,3,4)'), autom=F.hom([a**3]))
sage: g*h
((2, a, 1, 2); (1,2,3,4), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> 2*a + 1)
sage: h*g
((2*a + 1, 1, 2, 2); (1,2,3,4), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> 2*a + 1)
sage: S(g)
((2, a, 1, 2); (), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> a)
sage: S(1)
((1, 1, 1, 1); (), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> a)
"""
Element = SemimonomialTransformation
def __init__(self, R, len):
r"""
Initialization.
INPUT:
- ``R`` -- a ring
- ``len`` -- the degree of the monomial group
OUTPUT:
- the complete semimonomial group
EXAMPLES::
sage: F.<a> = GF(9)
sage: S = SemimonomialTransformationGroup(F, 4)
"""
if not R.is_field():
raise NotImplementedError('the ring must be a field')
self._R = R
self._len = len
from sage.categories.finite_groups import FiniteGroups
super().__init__(category=FiniteGroups())
def _element_constructor_(self, arg1, v=None, perm=None, autom=None, check=True):
r"""
Coerce ``arg1`` into this permutation group, if ``arg1`` is 0,
then we will try to coerce ``(v, perm, autom)``.
INPUT:
- ``arg1`` (optional) -- either the integers 0, 1 or an element of ``self``
- ``v`` (optional) -- a vector of length ``self.degree()``
- ``perm`` (optional) -- a permutation of degree ``self.degree()``
- ``autom`` (optional) -- an automorphism of the ring
EXAMPLES::
sage: F.<a> = GF(9)
sage: S = SemimonomialTransformationGroup(F, 4)
sage: S(1)
((1, 1, 1, 1); (), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> a)
sage: g = S(v=[1,1,1,a])
sage: S(g)
((1, 1, 1, a); (), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> a)
sage: S(perm=Permutation('(1,2)(3,4)'))
((1, 1, 1, 1); (1,2)(3,4), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> a)
sage: S(autom=F.hom([a**3]))
((1, 1, 1, 1); (), Ring endomorphism of Finite Field in a of size 3^2 Defn: a |--> 2*a + 1)
"""
from sage.categories.homset import End
R = self.base_ring()
if arg1 == 0:
if v is None:
v = [R.one()] * self.degree()
if perm is None:
perm = Permutation(range(1, self.degree() + 1))
if autom is None:
autom = R.hom(R.gens())
if check:
try:
v = [R(x) for x in v]
except TypeError:
raise TypeError('the vector attribute %s ' % v +
'should be iterable')
if len(v) != self.degree():
raise ValueError('the length of the vector is %s,' % len(v) +
' should be %s' % self.degree())
if not all(x.parent() is R and x.is_unit() for x in v):
raise ValueError('there is at least one element in the ' +
'list %s not lying in %s ' % (v, R) +
'or which is not invertible')
try:
perm = Permutation(perm)
except TypeError:
raise TypeError('the permutation attribute %s ' % perm +
'could not be converted to a permutation')
if len(perm) != self.degree():
txt = 'the permutation length is {}, should be {}'
raise ValueError(txt.format(len(perm), self.degree()))
try:
if autom.parent() != End(R):
autom = End(R)(autom)
except TypeError:
raise TypeError('%s of type %s' % (autom, type(autom)) +
' is not coerceable to an automorphism')
return self.Element(self, v, perm, autom)
else:
try:
if arg1.parent() is self:
return arg1
except AttributeError:
pass
try:
from sage.rings.integer import Integer
if Integer(arg1) == 1:
return self()
except TypeError:
pass
raise TypeError('the first argument must be an integer' +
' or an element of this group')
def base_ring(self):
r"""
Return the underlying ring of ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 3).base_ring() is F
True
"""
return self._R
def degree(self) -> Integer:
r"""
Return the degree of ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 3).degree()
3
"""
return self._len
def _an_element_(self):
r"""
Return an element of ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 3).an_element() # indirect doctest
((a, 1, 1); (1,3,2), Ring endomorphism of Finite Field in a of size 2^2 Defn: a |--> a + 1)
"""
R = self.base_ring()
v = [R.primitive_element()] + [R.one()] * (self.degree() - 1)
p = Permutation([self.degree()] + [i for i in range(1, self.degree())])
if not R.is_prime_field():
f = R.hom([R.gen()**R.characteristic()])
else:
f = R.Hom(R).identity()
return self(0, v, p, f)
def __contains__(self, item) -> bool:
r"""
EXAMPLES::
sage: F.<a> = GF(4)
sage: S = SemimonomialTransformationGroup(F, 3)
sage: 1 in S # indirect doctest
True
sage: a in S # indirect doctest
False
"""
try:
self(item, check=True)
except TypeError:
return False
return True
def gens(self) -> tuple:
r"""
Return a tuple of generators of ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 3).gens()
(((a, 1, 1); (), Ring endomorphism of Finite Field in a of size 2^2
Defn: a |--> a), ((1, 1, 1); (1,2,3), Ring endomorphism of Finite Field in a of size 2^2
Defn: a |--> a), ((1, 1, 1); (1,2), Ring endomorphism of Finite Field in a of size 2^2
Defn: a |--> a), ((1, 1, 1); (), Ring endomorphism of Finite Field in a of size 2^2
Defn: a |--> a + 1))
"""
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
R = self.base_ring()
l = [self(v=([R.primitive_element()] + [R.one()] * (self.degree() - 1)))]
for g in SymmetricGroup(self.degree()).gens():
l.append(self(perm=Permutation(g)))
if R.is_field() and not R.is_prime_field():
l.append(self(autom=R.hom([R.primitive_element()**R.characteristic()])))
return tuple(l)
def order(self) -> Integer:
r"""
Return the number of elements of ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 5).order() == (4-1)**5 * factorial(5) * 2
True
"""
from sage.arith.misc import factorial
from sage.categories.homset import End
n = self.degree()
R = self.base_ring()
if R.is_field():
multgroup_size = len(R) - 1
autgroup_size = R.degree()
else:
multgroup_size = R.unit_group_order()
autgroup_size = len([x for x in End(R) if x.is_injective()])
return multgroup_size**n * factorial(n) * autgroup_size
def _get_action_(self, X, op, self_on_left):
r"""
If ``self`` is the semimonomial group of degree `n` over `R`, then
there is the natural action on `R^n` and on matrices `R^{m \times n}`
for arbitrary integers `m` from the left.
See also:
:class:`~sage.groups.semimonomial_transformations.semimonomial_transformation_group.SemimonomialActionVec` and
:class:`~sage.groups.semimonomial_transformations.semimonomial_transformation_group.SemimonomialActionMat`
EXAMPLES::
sage: F.<a> = GF(4)
sage: s = SemimonomialTransformationGroup(F, 3).an_element()
sage: v = (F**3).0
sage: s*v # indirect doctest
(0, 1, 0)
sage: M = MatrixSpace(F, 3).one()
sage: s*M # indirect doctest
[ 0 1 0]
[ 0 0 1]
[a + 1 0 0]
"""
if self_on_left:
try:
A = SemimonomialActionVec(self, X)
return A
except ValueError:
pass
try:
A = SemimonomialActionMat(self, X)
return A
except ValueError:
pass
return None
def _repr_(self) -> str:
r"""
Return a string describing ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 3) # indirect doctest
Semimonomial transformation group over Finite Field in a of size 2^2 of degree 3
"""
return ('Semimonomial transformation group over %s' % self.base_ring() +
' of degree %s' % self.degree())
def _latex_(self) -> str:
r"""
Method for describing ``self`` in LaTeX.
EXAMPLES::
sage: F.<a> = GF(4)
sage: latex(SemimonomialTransformationGroup(F, 3)) # indirect doctest
\left(\Bold{F}_{2^{2}}^3\wr\langle (1,2,3), (1,2) \rangle \right) \rtimes \operatorname{Aut}(\Bold{F}_{2^{2}})
"""
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
ring_latex = self.base_ring()._latex_()
return ('\\left(' + ring_latex + '^' + str(self.degree()) + '\\wr' +
SymmetricGroup(self.degree())._latex_() +
' \\right) \\rtimes \\operatorname{Aut}(' + ring_latex + ')')
class SemimonomialActionVec(Action):
r"""
The natural left action of the semimonomial group on vectors.
The action is defined by:
`(\phi, \pi, \alpha)*(v_0, \ldots, v_{n-1}) :=
(\alpha(v_{\pi(1)-1}) \cdot \phi_0^{-1}, \ldots, \alpha(v_{\pi(n)-1}) \cdot \phi_{n-1}^{-1})`.
(The indexing of vectors is `0`-based here, so
`\psi = (\psi_0, \psi_1, \ldots, \psi_{n-1})`.)
"""
def __init__(self, G, V, check=True):
r"""
Initialization.
EXAMPLES::
sage: F.<a> = GF(4)
sage: s = SemimonomialTransformationGroup(F, 3).an_element()
sage: v = (F**3).1
sage: s*v # indirect doctest
(0, 0, 1)
"""
if check:
from sage.modules.free_module import FreeModule_generic
if not isinstance(G, SemimonomialTransformationGroup):
raise ValueError('%s is not a semimonomial group' % G)
if not isinstance(V, FreeModule_generic):
raise ValueError('%s is not a free module' % V)
if V.ambient_module() != V:
raise ValueError('%s is not equal to its ambient module' % V)
if V.dimension() != G.degree():
raise ValueError('%s has a dimension different to the degree of %s' % (V, G))
if V.base_ring() != G.base_ring():
raise ValueError('%s and %s have different base rings' % (V, G))
Action.__init__(self, G, V.dense_module())
def _act_(self, a, b):
r"""
Apply the semimonomial group element `a` to the vector `b`.
EXAMPLES::
sage: F.<a> = GF(4)
sage: s = SemimonomialTransformationGroup(F, 3).an_element()
sage: v = (F**3).1
sage: s*v # indirect doctest
(0, 0, 1)
"""
b = b.apply_map(a.get_autom())
b = self.codomain()(a.get_perm().action(b))
return b.pairwise_product(self.codomain()(a.get_v_inverse()))
class SemimonomialActionMat(Action):
r"""
The left action of
:class:`~sage.groups.semimonomial_transformations.semimonomial_transformation_group.SemimonomialTransformationGroup`
on matrices over the same ring whose number of columns is equal to the degree.
See :class:`~sage.groups.semimonomial_transformations.semimonomial_transformation_group.SemimonomialActionVec`
for the definition of the action on the row vectors of such a matrix.
"""
def __init__(self, G, M, check=True):
r"""
Initialization.
EXAMPLES::
sage: F.<a> = GF(4)
sage: s = SemimonomialTransformationGroup(F, 3).an_element()
sage: M = MatrixSpace(F, 3).one()
sage: s*M # indirect doctest
[ 0 1 0]
[ 0 0 1]
[a + 1 0 0]
"""
if check:
from sage.matrix.matrix_space import MatrixSpace
if not isinstance(G, SemimonomialTransformationGroup):
raise ValueError('%s is not a semimonomial group' % G)
if not isinstance(M, MatrixSpace):
raise ValueError('%s is not a matrix space' % M)
if M.ncols() != G.degree():
raise ValueError('the number of columns of %s' % M +
' and the degree of %s are different' % G)
if M.base_ring() != G.base_ring():
raise ValueError('%s and %s have different base rings' % (M, G))
Action.__init__(self, G, M)
def _act_(self, a, b):
r"""
Apply the semimonomial group element `a` to the matrix `b`.
EXAMPLES::
sage: F.<a> = GF(4)
sage: s = SemimonomialTransformationGroup(F, 3).an_element()
sage: M = MatrixSpace(F, 3).one()
sage: s*M # indirect doctest
[ 0 1 0]
[ 0 0 1]
[a + 1 0 0]
"""
return self.codomain()([a * x for x in b.rows()]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/semimonomial_transformations/semimonomial_transformation_group.py | 0.801276 | 0.984411 | semimonomial_transformation_group.py | pypi |
from sage.structure.unique_representation import CachedRepresentation
from sage.groups.matrix_gps.matrix_group import (
MatrixGroup_generic, MatrixGroup_gap )
def normalize_args_vectorspace(*args, **kwds):
"""
Normalize the arguments that relate to a vector space.
INPUT:
Something that defines an affine space. For example
* An affine space itself:
- ``A`` -- affine space
* A vector space:
- ``V`` -- a vector space
* Degree and base ring:
- ``degree`` -- integer. The degree of the affine group, that
is, the dimension of the affine space the group is acting on.
- ``ring`` -- a ring or an integer. The base ring of the affine
space. If an integer is given, it must be a prime power and
the corresponding finite field is constructed.
- ``var='a'`` -- optional keyword argument to specify the finite
field generator name in the case where ``ring`` is a prime
power.
OUTPUT:
A pair ``(degree, ring)``.
TESTS::
sage: from sage.groups.matrix_gps.named_group import normalize_args_vectorspace
sage: A = AffineSpace(2, GF(4,'a')); A
Affine Space of dimension 2 over Finite Field in a of size 2^2
sage: normalize_args_vectorspace(A)
(2, Finite Field in a of size 2^2)
sage: normalize_args_vectorspace(2,4) # shorthand
(2, Finite Field in a of size 2^2)
sage: V = ZZ^3; V
Ambient free module of rank 3 over the principal ideal domain Integer Ring
sage: normalize_args_vectorspace(V)
(3, Integer Ring)
sage: normalize_args_vectorspace(2, QQ)
(2, Rational Field)
"""
from sage.rings.integer_ring import ZZ
if len(args) == 1:
V = args[0]
try:
degree = V.dimension_relative()
except AttributeError:
degree = V.dimension()
ring = V.base_ring()
if len(args) == 2:
degree, ring = args
try:
ring = ZZ(ring)
from sage.rings.finite_rings.finite_field_constructor import FiniteField
var = kwds.get('var', 'a')
ring = FiniteField(ring, var)
except (ValueError, TypeError):
pass
return (ZZ(degree), ring)
def normalize_args_invariant_form(R, d, invariant_form):
r"""
Normalize the input of a user defined invariant bilinear form
for orthogonal, unitary and symplectic groups.
Further informations and examples can be found in the defining
functions (:func:`GU`, :func:`SU`, :func:`Sp`, etc.) for unitary,
symplectic groups, etc.
INPUT:
- ``R`` -- instance of the integral domain which should become
the ``base_ring`` of the classical group
- ``d`` -- integer giving the dimension of the module the classical
group is operating on
- ``invariant_form`` -- (optional) instances being accepted by
the matrix-constructor that define a `d \times d` square matrix
over R describing the bilinear form to be kept invariant
by the classical group
OUTPUT:
``None`` if ``invariant_form`` was not specified (or ``None``).
A matrix if the normalization was possible; otherwise an error
is raised.
TESTS::
sage: from sage.groups.matrix_gps.named_group import normalize_args_invariant_form
sage: CF3 = CyclotomicField(3)
sage: m = normalize_args_invariant_form(CF3, 3, (1,2,3,0,2,0,0,2,1)); m
[1 2 3]
[0 2 0]
[0 2 1]
sage: m.base_ring() == CF3
True
sage: normalize_args_invariant_form(ZZ, 3, (1,2,3,0,2,0,0,2))
Traceback (most recent call last):
...
ValueError: sequence too short (expected length 9, got 8)
sage: normalize_args_invariant_form(QQ, 3, (1,2,3,0,2,0,0,2,0))
Traceback (most recent call last):
...
ValueError: invariant_form must be non-degenerate
AUTHORS:
- Sebastian Oehms (2018-8) (see :trac:`26028`)
"""
if invariant_form is None:
return invariant_form
from sage.matrix.constructor import matrix
m = matrix(R, d, d, invariant_form)
if m.is_singular():
raise ValueError("invariant_form must be non-degenerate")
return m
class NamedMatrixGroup_generic(CachedRepresentation, MatrixGroup_generic):
def __init__(self, degree, base_ring, special, sage_name, latex_string,
category=None, invariant_form=None):
"""
Base class for "named" matrix groups
INPUT:
- ``degree`` -- integer; the degree (number of rows/columns of
matrices)
- ``base_ring`` -- ring; the base ring of the matrices
- ``special`` -- boolean; whether the matrix group is special,
that is, elements have determinant one
- ``sage_name`` -- string; the name of the group
- ``latex_string`` -- string; the latex representation
- ``category`` -- (optional) a subcategory of
:class:`sage.categories.groups.Groups` passed to
the constructor of
:class:`sage.groups.matrix_gps.matrix_group.MatrixGroup_generic`
- ``invariant_form`` -- (optional) square-matrix of the given
degree over the given base_ring describing a bilinear form
to be kept invariant by the group
EXAMPLES::
sage: G = GL(2, QQ)
sage: from sage.groups.matrix_gps.named_group import NamedMatrixGroup_generic
sage: isinstance(G, NamedMatrixGroup_generic)
True
.. SEEALSO::
See the examples for :func:`GU`, :func:`SU`, :func:`Sp`, etc.
as well.
"""
MatrixGroup_generic.__init__(self, degree, base_ring, category=category)
self._special = special
self._name_string = sage_name
self._latex_string = latex_string
self._invariant_form = invariant_form
def _an_element_(self):
"""
Return an element.
OUTPUT:
A group element.
EXAMPLES::
sage: GL(2, QQ)._an_element_()
[1 0]
[0 1]
"""
return self(1)
def _repr_(self):
"""
Return a string representation.
OUTPUT:
String.
EXAMPLES::
sage: GL(2, QQ)._repr_()
'General Linear Group of degree 2 over Rational Field'
"""
return self._name_string
def _latex_(self):
"""
Return a LaTeX representation
OUTPUT:
String.
EXAMPLES::
sage: GL(2, QQ)._latex_()
'GL(2, \\Bold{Q})'
"""
return self._latex_string
def __richcmp__(self, other, op):
"""
Override comparison.
We need to override the comparison since the named groups
derive from
:class:`~sage.structure.unique_representation.UniqueRepresentation`,
which compare by identity.
EXAMPLES::
sage: G = GL(2,3)
sage: G == MatrixGroup(G.gens())
True
sage: G = groups.matrix.GL(4,2)
sage: H = MatrixGroup(G.gens())
sage: G == H
True
sage: G != H
False
"""
return MatrixGroup_generic.__richcmp__(self, other, op)
class NamedMatrixGroup_gap(NamedMatrixGroup_generic, MatrixGroup_gap):
def __init__(self, degree, base_ring, special, sage_name, latex_string,
gap_command_string, category=None):
"""
Base class for "named" matrix groups using LibGAP
INPUT:
- ``degree`` -- integer. The degree (number of rows/columns of
matrices).
- ``base_ring`` -- ring. The base ring of the matrices.
- ``special`` -- boolean. Whether the matrix group is special,
that is, elements have determinant one.
- ``latex_string`` -- string. The latex representation.
- ``gap_command_string`` -- string. The GAP command to construct
the matrix group.
EXAMPLES::
sage: G = GL(2, GF(3))
sage: from sage.groups.matrix_gps.named_group import NamedMatrixGroup_gap
sage: isinstance(G, NamedMatrixGroup_gap)
True
"""
from sage.libs.gap.libgap import libgap
group = libgap.eval(gap_command_string)
MatrixGroup_gap.__init__(self, degree, base_ring, group,
category=category)
self._special = special
self._gap_string = gap_command_string
self._name_string = sage_name
self._latex_string = latex_string | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/groups/matrix_gps/named_group.py | 0.952761 | 0.687879 | named_group.py | pypi |
from sage.sat.solvers import SatSolver
from sage.sat.converters import ANF2CNFConverter
from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence
def solve(F, converter=None, solver=None, n=1, target_variables=None, **kwds):
"""
Solve system of Boolean polynomials ``F`` by solving the
SAT-problem -- produced by ``converter`` -- using ``solver``.
INPUT:
- ``F`` - a sequence of Boolean polynomials
- ``n`` - number of solutions to return. If ``n`` is +infinity
then all solutions are returned. If ``n <infinity`` then ``n``
solutions are returned if ``F`` has at least ``n``
solutions. Otherwise, all solutions of ``F`` are
returned. (default: ``1``)
- ``converter`` - an ANF to CNF converter class or object. If
``converter`` is ``None`` then
:class:`sage.sat.converters.polybori.CNFEncoder` is used to
construct a new converter. (default: ``None``)
- ``solver`` - a SAT-solver class or object. If ``solver`` is
``None`` then :class:`sage.sat.solvers.cryptominisat.CryptoMiniSat`
is used to construct a new converter. (default: ``None``)
- ``target_variables`` - a list of variables. The elements of the list are
used to exclude a particular combination of variable assignments of a
solution from any further solution. Furthermore ``target_variables``
denotes which variable-value pairs appear in the solutions. If
``target_variables`` is ``None`` all variables appearing in the
polynomials of ``F`` are used to construct exclusion clauses.
(default: ``None``)
- ``**kwds`` - parameters can be passed to the converter and the
solver by prefixing them with ``c_`` and ``s_`` respectively. For
example, to increase CryptoMiniSat's verbosity level, pass
``s_verbosity=1``.
OUTPUT:
A list of dictionaries, each of which contains a variable
assignment solving ``F``.
EXAMPLES:
We construct a very small-scale AES system of equations::
sage: sr = mq.SR(1,1,1,4,gf2=True,polybori=True)
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
and pass it to a SAT solver::
sage: from sage.sat.boolean_polynomials import solve as solve_sat # optional - pycryptosat
sage: s = solve_sat(F) # optional - pycryptosat
sage: F.subs(s[0]) # optional - pycryptosat
Polynomial Sequence with 36 Polynomials in 0 Variables
This time we pass a few options through to the converter and the solver::
sage: s = solve_sat(F, c_max_vars_sparse=4, c_cutting_number=8) # optional - pycryptosat
sage: F.subs(s[0]) # optional - pycryptosat
Polynomial Sequence with 36 Polynomials in 0 Variables
We construct a very simple system with three solutions and ask for a specific number of solutions::
sage: B.<a,b> = BooleanPolynomialRing() # optional - pycryptosat
sage: f = a*b # optional - pycryptosat
sage: l = solve_sat([f],n=1) # optional - pycryptosat
sage: len(l) == 1, f.subs(l[0]) # optional - pycryptosat
(True, 0)
sage: l = solve_sat([a*b],n=2) # optional - pycryptosat
sage: len(l) == 2, f.subs(l[0]), f.subs(l[1]) # optional - pycryptosat
(True, 0, 0)
sage: sorted((d[a], d[b]) for d in solve_sat([a*b],n=3)) # optional - pycryptosat
[(0, 0), (0, 1), (1, 0)]
sage: sorted((d[a], d[b]) for d in solve_sat([a*b],n=4)) # optional - pycryptosat
[(0, 0), (0, 1), (1, 0)]
sage: sorted((d[a], d[b]) for d in solve_sat([a*b],n=infinity)) # optional - pycryptosat
[(0, 0), (0, 1), (1, 0)]
In the next example we see how the ``target_variables`` parameter works::
sage: from sage.sat.boolean_polynomials import solve as solve_sat # optional - pycryptosat
sage: R.<a,b,c,d> = BooleanPolynomialRing() # optional - pycryptosat
sage: F = [a+b,a+c+d] # optional - pycryptosat
First the normal use case::
sage: sorted((D[a], D[b], D[c], D[d]) for D in solve_sat(F,n=infinity)) # optional - pycryptosat
[(0, 0, 0, 0), (0, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0)]
Now we are only interested in the solutions of the variables a and b::
sage: solve_sat(F,n=infinity,target_variables=[a,b]) # optional - pycryptosat
[{b: 0, a: 0}, {b: 1, a: 1}]
Here, we generate and solve the cubic equations of the AES SBox (see :trac:`26676`)::
sage: from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence # optional - pycryptosat, long time
sage: from sage.sat.boolean_polynomials import solve as solve_sat # optional - pycryptosat, long time
sage: sr = sage.crypto.mq.SR(1, 4, 4, 8, allow_zero_inversions = True) # optional - pycryptosat, long time
sage: sb = sr.sbox() # optional - pycryptosat, long time
sage: eqs = sb.polynomials(degree = 3) # optional - pycryptosat, long time
sage: eqs = PolynomialSequence(eqs) # optional - pycryptosat, long time
sage: variables = map(str, eqs.variables()) # optional - pycryptosat, long time
sage: variables = ",".join(variables) # optional - pycryptosat, long time
sage: R = BooleanPolynomialRing(16, variables) # optional - pycryptosat, long time
sage: eqs = [R(eq) for eq in eqs] # optional - pycryptosat, long time
sage: sls_aes = solve_sat(eqs, n = infinity) # optional - pycryptosat, long time
sage: len(sls_aes) # optional - pycryptosat, long time
256
TESTS:
Test that :trac:`26676` is fixed::
sage: varl = ['k{0}'.format(p) for p in range(29)]
sage: B = BooleanPolynomialRing(names = varl)
sage: B.inject_variables(verbose=False)
sage: keqs = [
....: k0 + k6 + 1,
....: k3 + k9 + 1,
....: k5*k18 + k6*k18 + k7*k16 + k7*k10,
....: k9*k17 + k8*k24 + k11*k17,
....: k1*k13 + k1*k15 + k2*k12 + k3*k15 + k4*k14,
....: k5*k18 + k6*k16 + k7*k18,
....: k3 + k26,
....: k0 + k19,
....: k9 + k28,
....: k11 + k20]
sage: from sage.sat.boolean_polynomials import solve as solve_sat
sage: solve_sat(keqs, n=1, solver=SAT('cryptominisat')) # optional - pycryptosat
[{k28: 0,
k26: 1,
k24: 0,
k20: 0,
k19: 0,
k18: 0,
k17: 0,
k16: 0,
k15: 0,
k14: 0,
k13: 0,
k12: 0,
k11: 0,
k10: 0,
k9: 0,
k8: 0,
k7: 0,
k6: 1,
k5: 0,
k4: 0,
k3: 1,
k2: 0,
k1: 0,
k0: 0}]
sage: solve_sat(keqs, n=1, solver=SAT('picosat')) # optional - pycosat
[{k28: 0,
k26: 1,
k24: 0,
k20: 0,
k19: 0,
k18: 0,
k17: 0,
k16: 0,
k15: 0,
k14: 0,
k13: 1,
k12: 1,
k11: 0,
k10: 0,
k9: 0,
k8: 0,
k7: 0,
k6: 1,
k5: 0,
k4: 1,
k3: 1,
k2: 1,
k1: 1,
k0: 0}]
.. NOTE::
Although supported, passing converter and solver objects
instead of classes is discouraged because these objects are
stateful.
"""
assert(n>0)
try:
len(F)
except AttributeError:
F = F.gens()
len(F)
P = next(iter(F)).parent()
K = P.base_ring()
if target_variables is None:
target_variables = PolynomialSequence(F).variables()
else:
target_variables = PolynomialSequence(target_variables).variables()
assert(set(target_variables).issubset(set(P.gens())))
# instantiate the SAT solver
if solver is None:
from sage.sat.solvers import CryptoMiniSat as solver
if not isinstance(solver, SatSolver):
solver_kwds = {}
for k, v in kwds.items():
if k.startswith("s_"):
solver_kwds[k[2:]] = v
solver = solver(**solver_kwds)
# instantiate the ANF to CNF converter
if converter is None:
from sage.sat.converters.polybori import CNFEncoder as converter
if not isinstance(converter, ANF2CNFConverter):
converter_kwds = {}
for k, v in kwds.items():
if k.startswith("c_"):
converter_kwds[k[2:]] = v
converter = converter(solver, P, **converter_kwds)
phi = converter(F)
rho = dict((phi[i], i) for i in range(len(phi)))
S = []
while True:
s = solver()
if s:
S.append(dict((x, K(s[rho[x]])) for x in target_variables))
if n is not None and len(S) == n:
break
exclude_solution = tuple(-rho[x] if s[rho[x]] else rho[x] for x in target_variables)
solver.add_clause(exclude_solution)
else:
try:
learnt = solver.learnt_clauses(unitary_only=True)
if learnt:
S.append(dict((phi[abs(i)-1], K(i<0)) for i in learnt))
else:
S.append(s)
break
except (AttributeError, NotImplementedError):
# solver does not support recovering learnt clauses
S.append(s)
break
if len(S) == 1:
if S[0] is False:
return False
if S[0] is None:
return None
elif S[-1] is False:
return S[0:-1]
return S
def learn(F, converter=None, solver=None, max_learnt_length=3, interreduction=False, **kwds):
"""
Learn new polynomials by running SAT-solver ``solver`` on
SAT-instance produced by ``converter`` from ``F``.
INPUT:
- ``F`` - a sequence of Boolean polynomials
- ``converter`` - an ANF to CNF converter class or object. If ``converter`` is ``None`` then
:class:`sage.sat.converters.polybori.CNFEncoder` is used to construct a new
converter. (default: ``None``)
- ``solver`` - a SAT-solver class or object. If ``solver`` is ``None`` then
:class:`sage.sat.solvers.cryptominisat.CryptoMiniSat` is used to construct a new converter.
(default: ``None``)
- ``max_learnt_length`` - only clauses of length <= ``max_length_learnt`` are considered and
converted to polynomials. (default: ``3``)
- ``interreduction`` - inter-reduce the resulting polynomials (default: ``False``)
.. NOTE::
More parameters can be passed to the converter and the solver by prefixing them with ``c_`` and
``s_`` respectively. For example, to increase CryptoMiniSat's verbosity level, pass
``s_verbosity=1``.
OUTPUT:
A sequence of Boolean polynomials.
EXAMPLES::
sage: from sage.sat.boolean_polynomials import learn as learn_sat # optional - pycryptosat
We construct a simple system and solve it::
sage: set_random_seed(2300) # optional - pycryptosat
sage: sr = mq.SR(1,2,2,4,gf2=True,polybori=True) # optional - pycryptosat
sage: F,s = sr.polynomial_system() # optional - pycryptosat
sage: H = learn_sat(F) # optional - pycryptosat
sage: H[-1] # optional - pycryptosat
k033 + 1
"""
try:
len(F)
except AttributeError:
F = F.gens()
len(F)
P = next(iter(F)).parent()
K = P.base_ring()
# instantiate the SAT solver
if solver is None:
from sage.sat.solvers.cryptominisat import CryptoMiniSat as solver
solver_kwds = {}
for k, v in kwds.items():
if k.startswith("s_"):
solver_kwds[k[2:]] = v
solver = solver(**solver_kwds)
# instantiate the ANF to CNF converter
if converter is None:
from sage.sat.converters.polybori import CNFEncoder as converter
converter_kwds = {}
for k, v in kwds.items():
if k.startswith("c_"):
converter_kwds[k[2:]] = v
converter = converter(solver, P, **converter_kwds)
phi = converter(F)
rho = dict((phi[i], i) for i in range(len(phi)))
s = solver()
if s:
learnt = [x + K(s[rho[x]]) for x in P.gens()]
else:
learnt = []
try:
lc = solver.learnt_clauses()
except (AttributeError, NotImplementedError):
# solver does not support recovering learnt clauses
lc = []
for c in lc:
if len(c) <= max_learnt_length:
try:
learnt.append(converter.to_polynomial(c))
except (ValueError, NotImplementedError, AttributeError):
# the solver might have learnt clauses that contain CNF
# variables which have no correspondence to variables in our
# polynomial ring (XOR chaining variables for example)
pass
learnt = PolynomialSequence(P, learnt)
if interreduction:
learnt = learnt.ideal().interreduced_basis()
return learnt | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sat/boolean_polynomials.py | 0.935472 | 0.659302 | boolean_polynomials.py | pypi |
import os
import sys
import subprocess
import shlex
from sage.sat.solvers.satsolver import SatSolver
from sage.misc.temporary_file import tmp_filename
from time import sleep
class DIMACS(SatSolver):
"""
Generic DIMACS Solver.
.. note::
Usually, users won't have to use this class directly but some
class which inherits from this class.
.. automethod:: __init__
.. automethod:: __call__
"""
command = ""
def __init__(self, command=None, filename=None, verbosity=0, **kwds):
"""
Construct a new generic DIMACS solver.
INPUT:
- ``command`` - a named format string with the command to
run. The string must contain {input} and may contain
{output} if the solvers writes the solution to an output
file. For example "sat-solver {input}" is a valid
command. If ``None`` then the class variable ``command`` is
used. (default: ``None``)
- ``filename`` - a filename to write clauses to in DIMACS
format, must be writable. If ``None`` a temporary filename
is chosen automatically. (default: ``None``)
- ``verbosity`` - a verbosity level, where zero means silent
and anything else means verbose output. (default: ``0``)
- ``**kwds`` - accepted for compatibility with other solves,
ignored.
TESTS::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: DIMACS()
DIMACS Solver: ''
"""
if filename is None:
filename = tmp_filename()
self._headname = filename
self._verbosity = verbosity
if command is not None:
self._command = command
else:
self._command = self.__class__.command
self._tail = open(tmp_filename(),'w')
self._var = 0
self._lit = 0
def __repr__(self):
"""
TESTS::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: DIMACS(command="iliketurtles {input}")
DIMACS Solver: 'iliketurtles {input}'
"""
return "DIMACS Solver: '%s'"%(self._command)
def __del__(self):
"""
TESTS::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: d = DIMACS(command="iliketurtles {input}")
sage: del d
"""
if not self._tail.closed:
self._tail.close()
if os.path.exists(self._tail.name):
os.unlink(self._tail.name)
def var(self, decision=None):
"""
Return a *new* variable.
INPUT:
- ``decision`` - accepted for compatibility with other solvers, ignored.
EXAMPLES::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: solver = DIMACS()
sage: solver.var()
1
"""
self._var+= 1
return self._var
def nvars(self):
"""
Return the number of variables.
EXAMPLES::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: solver = DIMACS()
sage: solver.var()
1
sage: solver.var(decision=True)
2
sage: solver.nvars()
2
"""
return self._var
def add_clause(self, lits):
"""
Add a new clause to set of clauses.
INPUT:
- ``lits`` - a tuple of integers != 0
.. note::
If any element ``e`` in ``lits`` has ``abs(e)`` greater
than the number of variables generated so far, then new
variables are created automatically.
EXAMPLES::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: solver = DIMACS()
sage: solver.var()
1
sage: solver.var(decision=True)
2
sage: solver.add_clause( (1, -2 , 3) )
sage: solver
DIMACS Solver: ''
"""
l = []
for lit in lits:
lit = int(lit)
while abs(lit) > self.nvars():
self.var()
l.append(str(lit))
l.append("0\n")
self._tail.write(" ".join(l) )
self._lit += 1
def write(self, filename=None):
"""
Write DIMACS file.
INPUT:
- ``filename`` - if ``None`` default filename specified at initialization is used for
writing to (default: ``None``)
EXAMPLES::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: fn = tmp_filename()
sage: solver = DIMACS(filename=fn)
sage: solver.add_clause( (1, -2 , 3) )
sage: _ = solver.write()
sage: for line in open(fn).readlines():
....: print(line)
p cnf 3 1
1 -2 3 0
sage: from sage.sat.solvers.dimacs import DIMACS
sage: fn = tmp_filename()
sage: solver = DIMACS()
sage: solver.add_clause( (1, -2 , 3) )
sage: _ = solver.write(fn)
sage: for line in open(fn).readlines():
....: print(line)
p cnf 3 1
1 -2 3 0
"""
headname = self._headname if filename is None else filename
head = open(headname, "w")
head.truncate(0)
head.write("p cnf %d %d\n"%(self._var,self._lit))
head.close()
tail = self._tail
tail.close()
head = open(headname,"a")
tail = open(self._tail.name,"r")
head.write(tail.read())
tail.close()
head.close()
self._tail = open(self._tail.name,"a")
return headname
def clauses(self, filename=None):
"""
Return original clauses.
INPUT:
- ``filename`` - if not ``None`` clauses are written to ``filename`` in
DIMACS format (default: ``None``)
OUTPUT:
If ``filename`` is ``None`` then a list of ``lits, is_xor, rhs``
tuples is returned, where ``lits`` is a tuple of literals,
``is_xor`` is always ``False`` and ``rhs`` is always ``None``.
If ``filename`` points to a writable file, then the list of original
clauses is written to that file in DIMACS format.
EXAMPLES::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: fn = tmp_filename()
sage: solver = DIMACS()
sage: solver.add_clause( (1, 2, 3) )
sage: solver.clauses()
[((1, 2, 3), False, None)]
sage: solver.add_clause( (1, 2, -3) )
sage: solver.clauses(fn)
sage: print(open(fn).read())
p cnf 3 2
1 2 3 0
1 2 -3 0
<BLANKLINE>
"""
if filename is not None:
self.write(filename)
else:
tail = self._tail
tail.close()
tail = open(self._tail.name,"r")
clauses = []
for line in tail.readlines():
if line.startswith("p") or line.startswith("c"):
continue
clause = []
for lit in line.split(" "):
lit = int(lit)
if lit == 0:
break
clause.append(lit)
clauses.append( ( tuple(clause), False, None ) )
tail.close()
self._tail = open(self._tail.name, "a")
return clauses
@staticmethod
def render_dimacs(clauses, filename, nlits):
"""
Produce DIMACS file ``filename`` from ``clauses``.
INPUT:
- ``clauses`` - a list of clauses, either in simple format as a list of
literals or in extended format for CryptoMiniSat: a tuple of literals,
``is_xor`` and ``rhs``.
- ``filename`` - the file to write to
- ``nlits -- the number of literals appearing in ``clauses``
EXAMPLES::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: fn = tmp_filename()
sage: solver = DIMACS()
sage: solver.add_clause( (1, 2, -3) )
sage: DIMACS.render_dimacs(solver.clauses(), fn, solver.nvars())
sage: print(open(fn).read())
p cnf 3 1
1 2 -3 0
<BLANKLINE>
This is equivalent to::
sage: solver.clauses(fn)
sage: print(open(fn).read())
p cnf 3 1
1 2 -3 0
<BLANKLINE>
This function also accepts a "simple" format::
sage: DIMACS.render_dimacs([ (1,2), (1,2,-3) ], fn, 3)
sage: print(open(fn).read())
p cnf 3 2
1 2 0
1 2 -3 0
<BLANKLINE>
"""
fh = open(filename, "w")
fh.write("p cnf %d %d\n"%(nlits,len(clauses)))
for clause in clauses:
if len(clause) == 3 and clause[1] in (True, False) and clause[2] in (True,False,None):
lits, is_xor, rhs = clause
else:
lits, is_xor, rhs = clause, False, None
if is_xor:
closing = lits[-1] if rhs else -lits[-1]
fh.write("x" + " ".join(map(str, lits[:-1])) + " %d 0\n"%closing)
else:
fh.write(" ".join(map(str, lits)) + " 0\n")
fh.close()
def _run(self):
r"""
Run 'command' and collect output.
TESTS:
This class is not meant to be called directly::
sage: from sage.sat.solvers.dimacs import DIMACS
sage: fn = tmp_filename()
sage: solver = DIMACS(filename=fn)
sage: solver.add_clause( (1, -2 , 3) )
sage: solver._run()
Traceback (most recent call last):
...
ValueError: no SAT solver command selected
It is used by subclasses::
sage: from sage.sat.solvers import Glucose
sage: solver = Glucose()
sage: solver.add_clause( (1, 2, 3) )
sage: solver.add_clause( (-1,) )
sage: solver.add_clause( (-2,) )
sage: solver._run() # optional - glucose
sage: solver._output # optional - glucose
[...
's SATISFIABLE\n',
'v -1 -2 3 0\n']
"""
from sage.misc.verbose import get_verbose
self.write()
output_filename = None
self._output = []
command = self._command.strip()
if not command:
raise ValueError("no SAT solver command selected")
if "{output}" in command:
output_filename = tmp_filename()
command = command.format(input=self._headname, output=output_filename)
args = shlex.split(command)
try:
process = subprocess.Popen(args, stdout=subprocess.PIPE)
except OSError:
raise OSError("Could run '%s', perhaps you need to add your SAT solver to $PATH?" % (" ".join(args)))
try:
while process.poll() is None:
for line in iter(process.stdout.readline, b''):
if get_verbose() or self._verbosity:
print(line)
sys.stdout.flush()
self._output.append(line.decode('utf-8'))
sleep(0.1)
if output_filename:
self._output.extend(open(output_filename).readlines())
except BaseException:
process.kill()
raise
def __call__(self, assumptions=None):
"""
Solve this instance and return the parsed output.
INPUT:
- ``assumptions`` - ignored, accepted for compatibility with
other solvers (default: ``None``)
OUTPUT:
- If this instance is SAT: A tuple of length ``nvars()+1``
where the ``i``-th entry holds an assignment for the
``i``-th variables (the ``0``-th entry is always ``None``).
- If this instance is UNSAT: ``False``
EXAMPLES:
When the problem is SAT::
sage: from sage.sat.solvers import RSat
sage: solver = RSat()
sage: solver.add_clause( (1, 2, 3) )
sage: solver.add_clause( (-1,) )
sage: solver.add_clause( (-2,) )
sage: solver() # optional - rsat
(None, False, False, True)
When the problem is UNSAT::
sage: solver = RSat()
sage: solver.add_clause((1,2))
sage: solver.add_clause((-1,2))
sage: solver.add_clause((1,-2))
sage: solver.add_clause((-1,-2))
sage: solver() # optional - rsat
False
With Glucose::
sage: from sage.sat.solvers.dimacs import Glucose
sage: solver = Glucose()
sage: solver.add_clause((1,2))
sage: solver.add_clause((-1,2))
sage: solver.add_clause((1,-2))
sage: solver() # optional - glucose
(None, True, True)
sage: solver.add_clause((-1,-2))
sage: solver() # optional - glucose
False
With GlucoseSyrup::
sage: from sage.sat.solvers.dimacs import GlucoseSyrup
sage: solver = GlucoseSyrup()
sage: solver.add_clause((1,2))
sage: solver.add_clause((-1,2))
sage: solver.add_clause((1,-2))
sage: solver() # optional - glucose
(None, True, True)
sage: solver.add_clause((-1,-2))
sage: solver() # optional - glucose
False
TESTS::
sage: from sage.sat.boolean_polynomials import solve as solve_sat
sage: sr = mq.SR(1,1,1,4,gf2=True,polybori=True)
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
sage: solve_sat(F, solver=sage.sat.solvers.RSat) # optional - RSat
"""
if assumptions is not None:
raise NotImplementedError("Assumptions are not supported for DIMACS based solvers.")
self._run()
v_lines = []
for line in self._output:
if line.startswith("c"):
continue
if line.startswith("s"):
if "UNSAT" in line:
return False
if line.startswith("v"):
v_lines.append(line[1:].strip())
if v_lines:
L = " ".join(v_lines).split(" ")
assert L[-1] == "0", "last digit of solution line must be zero (not {})".format(L[-1])
return (None,) + tuple(int(e)>0 for e in L[:-1])
else:
raise ValueError("When parsing the output, no line starts with letter v or s")
class RSat(DIMACS):
"""
An instance of the RSat solver.
For information on RSat see: http://reasoning.cs.ucla.edu/rsat/
EXAMPLES::
sage: from sage.sat.solvers import RSat
sage: solver = RSat()
sage: solver
DIMACS Solver: 'rsat {input} -v -s'
When the problem is SAT::
sage: from sage.sat.solvers import RSat
sage: solver = RSat()
sage: solver.add_clause( (1, 2, 3) )
sage: solver.add_clause( (-1,) )
sage: solver.add_clause( (-2,) )
sage: solver() # optional - rsat
(None, False, False, True)
When the problem is UNSAT::
sage: solver = RSat()
sage: solver.add_clause((1,2))
sage: solver.add_clause((-1,2))
sage: solver.add_clause((1,-2))
sage: solver.add_clause((-1,-2))
sage: solver() # optional - rsat
False
"""
command = "rsat {input} -v -s"
class Glucose(DIMACS):
"""
An instance of the Glucose solver.
For information on Glucose see: http://www.labri.fr/perso/lsimon/glucose/
EXAMPLES::
sage: from sage.sat.solvers import Glucose
sage: solver = Glucose()
sage: solver
DIMACS Solver: 'glucose -verb=0 -model {input}'
When the problem is SAT::
sage: from sage.sat.solvers import Glucose
sage: solver1 = Glucose()
sage: solver1.add_clause( (1, 2, 3) )
sage: solver1.add_clause( (-1,) )
sage: solver1.add_clause( (-2,) )
sage: solver1() # optional - glucose
(None, False, False, True)
When the problem is UNSAT::
sage: solver2 = Glucose()
sage: solver2.add_clause((1,2))
sage: solver2.add_clause((-1,2))
sage: solver2.add_clause((1,-2))
sage: solver2.add_clause((-1,-2))
sage: solver2() # optional - glucose
False
With one hundred variables::
sage: solver3 = Glucose()
sage: solver3.add_clause( (1, 2, 100) )
sage: solver3.add_clause( (-1,) )
sage: solver3.add_clause( (-2,) )
sage: solver3() # optional - glucose
(None, False, False, ..., True)
TESTS::
sage: print(''.join(solver1._output)) # optional - glucose
c...
s SATISFIABLE
v -1 -2 3 0
::
sage: print(''.join(solver2._output)) # optional - glucose
c...
s UNSATISFIABLE
Glucose gives large solution on one single line::
sage: print(''.join(solver3._output)) # optional - glucose
c...
s SATISFIABLE
v -1 -2 ... 100 0
"""
command = "glucose -verb=0 -model {input}"
class GlucoseSyrup(DIMACS):
"""
An instance of the Glucose-syrup parallel solver.
For information on Glucose see: http://www.labri.fr/perso/lsimon/glucose/
EXAMPLES::
sage: from sage.sat.solvers import GlucoseSyrup
sage: solver = GlucoseSyrup()
sage: solver
DIMACS Solver: 'glucose-syrup -model -verb=0 {input}'
When the problem is SAT::
sage: solver1 = GlucoseSyrup()
sage: solver1.add_clause( (1, 2, 3) )
sage: solver1.add_clause( (-1,) )
sage: solver1.add_clause( (-2,) )
sage: solver1() # optional - glucose
(None, False, False, True)
When the problem is UNSAT::
sage: solver2 = GlucoseSyrup()
sage: solver2.add_clause((1,2))
sage: solver2.add_clause((-1,2))
sage: solver2.add_clause((1,-2))
sage: solver2.add_clause((-1,-2))
sage: solver2() # optional - glucose
False
With one hundred variables::
sage: solver3 = GlucoseSyrup()
sage: solver3.add_clause( (1, 2, 100) )
sage: solver3.add_clause( (-1,) )
sage: solver3.add_clause( (-2,) )
sage: solver3() # optional - glucose
(None, False, False, ..., True)
TESTS::
sage: print(''.join(solver1._output)) # optional - glucose
c...
s SATISFIABLE
v -1 -2 3 0
::
sage: print(''.join(solver2._output)) # optional - glucose
c...
s UNSATISFIABLE
GlucoseSyrup gives large solution on one single line::
sage: print(''.join(solver3._output)) # optional - glucose
c...
s SATISFIABLE
v -1 -2 ... 100 0
"""
command = "glucose-syrup -model -verb=0 {input}"
class Kissat(DIMACS):
"""
An instance of the Kissat SAT solver
For information on Kissat see: http://fmv.jku.at/kissat/
EXAMPLES::
sage: from sage.sat.solvers import Kissat
sage: solver = Kissat()
sage: solver
DIMACS Solver: 'kissat -q {input}'
When the problem is SAT::
sage: solver1 = Kissat()
sage: solver1.add_clause( (1, 2, 3) )
sage: solver1.add_clause( (-1,) )
sage: solver1.add_clause( (-2,) )
sage: solver1() # optional - kissat
(None, False, False, True)
When the problem is UNSAT::
sage: solver2 = Kissat()
sage: solver2.add_clause((1,2))
sage: solver2.add_clause((-1,2))
sage: solver2.add_clause((1,-2))
sage: solver2.add_clause((-1,-2))
sage: solver2() # optional - kissat
False
With one hundred variables::
sage: solver3 = Kissat()
sage: solver3.add_clause( (1, 2, 100) )
sage: solver3.add_clause( (-1,) )
sage: solver3.add_clause( (-2,) )
sage: solver3() # optional - kissat
(None, False, False, ..., True)
TESTS::
sage: print(''.join(solver1._output)) # optional - kissat
s SATISFIABLE
v -1 -2 3 0
::
sage: print(''.join(solver2._output)) # optional - kissat
s UNSATISFIABLE
Here the output contains many lines starting with letter "v"::
sage: print(''.join(solver3._output)) # optional - kissat
s SATISFIABLE
v -1 -2 ...
v ...
v ...
v ... 100 0
"""
command = "kissat -q {input}" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sat/solvers/dimacs.py | 0.629091 | 0.254694 | dimacs.py | pypi |
r"""
Solve SAT problems Integer Linear Programming
The class defined here is a :class:`~sage.sat.solvers.satsolver.SatSolver` that
solves its instance using :class:`MixedIntegerLinearProgram`. Its performance
can be expected to be slower than when using
:class:`~sage.sat.solvers.cryptominisat.cryptominisat.CryptoMiniSat`.
"""
from .satsolver import SatSolver
from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException
class SatLP(SatSolver):
def __init__(self, solver=None, verbose=0, *, integrality_tolerance=1e-3):
r"""
Initializes the instance
INPUT:
- ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear Programming
(MILP) solver to be used. If set to ``None``, the default one is used. For
more information on MILP solvers and which default solver is used, see
the method
:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`
of the class
:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.
- ``verbose`` -- integer (default: ``0``). Sets the level of verbosity
of the LP solver. Set to 0 by default, which means quiet.
- ``integrality_tolerance`` -- parameter for use with MILP solvers over an
inexact base ring; see :meth:`MixedIntegerLinearProgram.get_values`.
EXAMPLES::
sage: S=SAT(solver="LP"); S
an ILP-based SAT Solver
"""
SatSolver.__init__(self)
self._LP = MixedIntegerLinearProgram(solver=solver)
self._LP_verbose = verbose
self._vars = self._LP.new_variable(binary=True)
self._integrality_tolerance = integrality_tolerance
def var(self):
"""
Return a *new* variable.
EXAMPLES::
sage: S=SAT(solver="LP"); S
an ILP-based SAT Solver
sage: S.var()
1
"""
nvars = n = self._LP.number_of_variables()
while nvars==self._LP.number_of_variables():
n += 1
self._vars[n] # creates the variable if needed
return n
def nvars(self):
"""
Return the number of variables.
EXAMPLES::
sage: S=SAT(solver="LP"); S
an ILP-based SAT Solver
sage: S.var()
1
sage: S.var()
2
sage: S.nvars()
2
"""
return self._LP.number_of_variables()
def add_clause(self, lits):
"""
Add a new clause to set of clauses.
INPUT:
- ``lits`` - a tuple of integers != 0
.. note::
If any element ``e`` in ``lits`` has ``abs(e)`` greater
than the number of variables generated so far, then new
variables are created automatically.
EXAMPLES::
sage: S=SAT(solver="LP"); S
an ILP-based SAT Solver
sage: for u,v in graphs.CycleGraph(6).edges(sort=False, labels=False):
....: u,v = u+1,v+1
....: S.add_clause((u,v))
....: S.add_clause((-u,-v))
"""
if 0 in lits:
raise ValueError("0 should not appear in the clause: {}".format(lits))
p = self._LP
p.add_constraint(p.sum(self._vars[x] if x>0 else 1-self._vars[-x] for x in lits)
>=1)
def __call__(self):
"""
Solve this instance.
OUTPUT:
- If this instance is SAT: A tuple of length ``nvars()+1``
where the ``i``-th entry holds an assignment for the
``i``-th variables (the ``0``-th entry is always ``None``).
- If this instance is UNSAT: ``False``
EXAMPLES::
sage: def is_bipartite_SAT(G):
....: S=SAT(solver="LP"); S
....: for u,v in G.edges(sort=False, labels=False):
....: u,v = u+1,v+1
....: S.add_clause((u,v))
....: S.add_clause((-u,-v))
....: return S
sage: S = is_bipartite_SAT(graphs.CycleGraph(6))
sage: S() # random
[None, True, False, True, False, True, False]
sage: True in S()
True
sage: S = is_bipartite_SAT(graphs.CycleGraph(7))
sage: S()
False
"""
try:
self._LP.solve(log=self._LP_verbose)
except MIPSolverException:
return False
b = self._LP.get_values(self._vars, convert=bool, tolerance=self._integrality_tolerance)
n = max(b)
return [None]+[b.get(i, False) for i in range(1,n+1)]
def __repr__(self):
"""
TESTS::
sage: S=SAT(solver="LP"); S
an ILP-based SAT Solver
"""
return "an ILP-based SAT Solver" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sat/solvers/sat_lp.py | 0.935788 | 0.712176 | sat_lp.py | pypi |
from sage.matrix.constructor import matrix
from sage.structure.element import is_Matrix
from sage.arith.all import legendre_symbol
from sage.rings.integer_ring import ZZ
def is_triangular_number(n, return_value=False):
"""
Return whether ``n`` is a triangular number.
A *triangular number* is a number of the form `k(k+1)/2` for some
non-negative integer `n`. See :wikipedia:`Triangular_number`. The sequence
of triangular number is references as A000217 in the Online encyclopedia of
integer sequences (OEIS).
If you want to get the value of `k` for which `n=k(k+1)/2` set the
argument ``return_value`` to ``True`` (see the examples below).
INPUT:
- ``n`` - an integer
- ``return_value`` - a boolean set to ``False`` by default. If set to
``True`` the function returns a pair made of a boolean and the value ``v``
such that `v(v+1)/2 = n`.
EXAMPLES::
sage: is_triangular_number(3)
True
sage: is_triangular_number(3, return_value=True)
(True, 2)
sage: is_triangular_number(2)
False
sage: is_triangular_number(2, return_value=True)
(False, None)
sage: is_triangular_number(25*(25+1)/2)
True
sage: is_triangular_number(10^6 * (10^6 +1)/2, return_value=True)
(True, 1000000)
TESTS::
sage: F1 = [n for n in range(1,100*(100+1)/2)
....: if is_triangular_number(n)]
sage: F2 = [n*(n+1)/2 for n in range(1,100)]
sage: F1 == F2
True
sage: for n in range(1000):
....: res,v = is_triangular_number(n,return_value=True)
....: assert res == is_triangular_number(n)
....: if res: assert v*(v+1)/2 == n
"""
n = ZZ(n)
if return_value:
if n < 0:
return (False, None)
if n == 0:
return (True, ZZ.zero())
s, r = (8 * n + 1).sqrtrem()
if r:
return (False, None)
return (True, (s - 1) // 2)
return (8 * n + 1).is_square()
def extend_to_primitive(A_input):
"""
Given a matrix (resp. list of vectors), extend it to a square
matrix (resp. list of vectors), such that its determinant is the
gcd of its minors (i.e. extend the basis of a lattice to a
"maximal" one in Z^n).
Author(s): Gonzalo Tornaria and Jonathan Hanke.
INPUT:
a matrix, or a list of length n vectors (in the same space)
OUTPUT:
a square matrix, or a list of n vectors (resp.)
EXAMPLES::
sage: A = Matrix(ZZ, 3, 2, range(6))
sage: extend_to_primitive(A)
[ 0 1 -1]
[ 2 3 0]
[ 4 5 0]
sage: extend_to_primitive([vector([1,2,3])])
[(1, 2, 3), (0, 1, 1), (-1, 0, 0)]
"""
# Deal with a list of vectors
if not is_Matrix(A_input):
A = matrix(A_input) # Make a matrix A with the given rows.
vec_output_flag = True
else:
A = A_input
vec_output_flag = False
# Arrange for A to have more columns than rows.
if A.is_square():
return A
if A.nrows() > A.ncols():
return extend_to_primitive(A.transpose()).transpose()
# Setup
k = A.nrows()
n = A.ncols()
R = A.base_ring()
# Smith normal form transformation, assuming more columns than rows
V = A.smith_form()[2]
# Extend the matrix in new coordinates, then switch back.
B = A * V
B_new = matrix(R, n - k, n)
for i in range(n - k):
B_new[i, n - i - 1] = 1
C = B.stack(B_new)
D = C * V**(-1)
# Normalize for a positive determinant
if D.det() < 0:
D.rescale_row(n - 1, -1)
# Return the current information
if vec_output_flag:
return D.rows()
else:
return D
def least_quadratic_nonresidue(p):
"""
Return the smallest positive integer quadratic non-residue in Z/pZ for primes p>2.
EXAMPLES::
sage: least_quadratic_nonresidue(5)
2
sage: [least_quadratic_nonresidue(p) for p in prime_range(3,100)]
[2, 2, 3, 2, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 2, 2, 2, 7, 5, 3, 2, 3, 5]
TESTS:
This raises an error if input is a positive composite integer. ::
sage: least_quadratic_nonresidue(20)
Traceback (most recent call last):
...
ValueError: p must be a prime number > 2
This raises an error if input is 2. This is because every integer is a
quadratic residue modulo 2. ::
sage: least_quadratic_nonresidue(2)
Traceback (most recent call last):
...
ValueError: there are no quadratic non-residues in Z/2Z
"""
p1 = abs(p)
# Deal with the prime p = 2 and |p| <= 1.
if p1 == 2:
raise ValueError("there are no quadratic non-residues in Z/2Z")
if p1 < 2:
raise ValueError("p must be a prime number > 2")
# Find the smallest non-residue mod p
# For 7/8 of primes the answer is 2, 3 or 5:
if p % 8 in (3, 5):
return ZZ(2)
if p % 12 in (5, 7):
return ZZ(3)
if p % 5 in (2, 3):
return ZZ(5)
# default case (first needed for p=71):
if not p.is_prime():
raise ValueError("p must be a prime number > 2")
from sage.arith.srange import xsrange
for r in xsrange(7, p):
if legendre_symbol(r, p) == -1:
return ZZ(r) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/extras.py | 0.92183 | 0.666741 | extras.py | pypi |
from sage.quadratic_forms.genera.genus import Genus, LocalGenusSymbol
from sage.rings.integer_ring import ZZ
from sage.arith.all import is_prime, prime_divisors
def global_genus_symbol(self):
r"""
Return the genus of two times a quadratic form over `\ZZ`.
These are defined by a collection of local genus symbols (a la
Chapter 15 of Conway-Sloane [CS1999]_), and a signature.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3,4])
sage: Q.global_genus_symbol()
Genus of
[2 0 0 0]
[0 4 0 0]
[0 0 6 0]
[0 0 0 8]
Signature: (4, 0)
Genus symbol at 2: [2^-2 4^1 8^1]_6
Genus symbol at 3: 1^3 3^-1
::
sage: Q = QuadraticForm(ZZ, 4, range(10))
sage: Q.global_genus_symbol()
Genus of
[ 0 1 2 3]
[ 1 8 5 6]
[ 2 5 14 8]
[ 3 6 8 18]
Signature: (3, 1)
Genus symbol at 2: 1^-4
Genus symbol at 563: 1^3 563^-1
"""
if self.base_ring() is not ZZ:
raise TypeError("the quadratic form is not defined over the integers")
return Genus(self.Hessian_matrix())
def local_genus_symbol(self, p):
r"""
Return the Conway-Sloane genus symbol of 2 times a quadratic form
defined over `\ZZ` at a prime number `p`.
This is defined (in the
Genus_Symbol_p_adic_ring() class in the quadratic_forms/genera
subfolder) to be a list of tuples (one for each Jordan component
p^m*A at p, where A is a unimodular symmetric matrix with
coefficients the p-adic integers) of the following form:
1. If p>2 then return triples of the form [`m`, `n`, `d`] where
`m` = valuation of the component
`n` = rank of A
`d` = det(A) in {1,u} for normalized quadratic non-residue u.
2. If p=2 then return quintuples of the form [`m`,`n`,`s`, `d`, `o`] where
`m` = valuation of the component
`n` = rank of A
`d` = det(A) in {1,3,5,7}
`s` = 0 (or 1) if A is even (or odd)
`o` = oddity of A (= 0 if s = 0) in Z/8Z
= the trace of the diagonalization of A
.. NOTE::
The Conway-Sloane convention for describing the prime 'p = -1'
is not supported here, and neither is the convention for
including the 'prime' Infinity. See note on p370 of Conway-Sloane
(3rd ed) [CS1999]_ for a discussion of this convention.
INPUT:
- `p` -- a prime number > 0
OUTPUT:
a Conway-Sloane genus symbol at `p`, which is an
instance of the Genus_Symbol_p_adic_ring class.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3,4])
sage: Q.local_genus_symbol(2)
Genus symbol at 2: [2^-2 4^1 8^1]_6
sage: Q.local_genus_symbol(3)
Genus symbol at 3: 1^3 3^-1
sage: Q.local_genus_symbol(5)
Genus symbol at 5: 1^4
"""
if not is_prime(p):
raise TypeError("the number " + str(p) + " is not prime")
if self.base_ring() is not ZZ:
raise TypeError("the quadratic form is not defined over the integers")
return LocalGenusSymbol(self.Hessian_matrix(), p)
def CS_genus_symbol_list(self, force_recomputation=False):
"""
Return the list of Conway-Sloane genus symbols in increasing order of primes dividing 2*det.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3,4])
sage: Q.CS_genus_symbol_list()
[Genus symbol at 2: [2^-2 4^1 8^1]_6, Genus symbol at 3: 1^3 3^-1]
"""
# Try to use the cached list
if not force_recomputation:
try:
return self.__CS_genus_symbol_list
except AttributeError:
pass
# Otherwise recompute and cache the list
list_of_CS_genus_symbols = []
for p in prime_divisors(2 * self.det()):
list_of_CS_genus_symbols.append(self.local_genus_symbol(p))
self.__CS_genus_symbol_list = list_of_CS_genus_symbols
return list_of_CS_genus_symbols | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/quadratic_form__genus.py | 0.894513 | 0.736637 | quadratic_form__genus.py | pypi |
from sage.rings.all import ZZ, QQ, Integer
from sage.modules.free_module_element import vector
from sage.matrix.constructor import Matrix
def qfsolve(G):
r"""
Find a solution `x = (x_0,...,x_n)` to `x G x^t = 0` for an
`n \times n`-matrix ``G`` over `\QQ`.
OUTPUT:
If a solution exists, return a vector of rational numbers `x`.
Otherwise, returns `-1` if no solution exists over the reals or a
prime `p` if no solution exists over the `p`-adic field `\QQ_p`.
ALGORITHM:
Uses PARI/GP function ``qfsolve``.
EXAMPLES::
sage: from sage.quadratic_forms.qfsolve import qfsolve
sage: M = Matrix(QQ, [[0, 0, -12], [0, -12, 0], [-12, 0, -1]]); M
[ 0 0 -12]
[ 0 -12 0]
[-12 0 -1]
sage: sol = qfsolve(M); sol
(1, 0, 0)
sage: sol.parent()
Vector space of dimension 3 over Rational Field
sage: M = Matrix(QQ, [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
sage: ret = qfsolve(M); ret
-1
sage: ret.parent()
Integer Ring
sage: M = Matrix(QQ, [[1, 0, 0], [0, 1, 0], [0, 0, -7]])
sage: qfsolve(M)
7
sage: M = Matrix(QQ, [[3, 0, 0, 0], [0, 5, 0, 0], [0, 0, -7, 0], [0, 0, 0, -11]])
sage: qfsolve(M)
(3, 4, -3, -2)
"""
ret = G.__pari__().qfsolve()
if ret.type() == 't_COL':
return vector(QQ, ret)
return ZZ(ret)
def qfparam(G, sol):
r"""
Parametrizes the conic defined by the matrix ``G``.
INPUT:
- ``G`` -- a `3 \times 3`-matrix over `\QQ`.
- ``sol`` -- a triple of rational numbers providing a solution
to sol*G*sol^t = 0.
OUTPUT:
A triple of polynomials that parametrizes all solutions of
x*G*x^t = 0 up to scaling.
ALGORITHM:
Uses PARI/GP function ``qfparam``.
EXAMPLES::
sage: from sage.quadratic_forms.qfsolve import qfsolve, qfparam
sage: M = Matrix(QQ, [[0, 0, -12], [0, -12, 0], [-12, 0, -1]]); M
[ 0 0 -12]
[ 0 -12 0]
[-12 0 -1]
sage: sol = qfsolve(M)
sage: ret = qfparam(M, sol); ret
(-12*t^2 - 1, 24*t, 24)
sage: ret.parent()
Ambient free module of rank 3 over the principal ideal domain Univariate Polynomial Ring in t over Rational Field
"""
R = QQ['t']
mat = G.__pari__().qfparam(sol)
# Interpret the rows of mat as coefficients of polynomials
return vector(R, mat.Col())
def solve(self, c=0):
r"""
Return a vector `x` such that ``self(x) == c``.
INPUT:
- ``c`` -- (default: 0) a rational number.
OUTPUT:
- A non-zero vector `x` satisfying ``self(x) == c``.
ALGORITHM:
Uses PARI's qfsolve(). Algorithm described by Jeroen Demeyer; see comments on :trac:`19112`
EXAMPLES::
sage: F = DiagonalQuadraticForm(QQ, [1, -1]); F
Quadratic form in 2 variables over Rational Field with coefficients:
[ 1 0 ]
[ * -1 ]
sage: F.solve()
(1, 1)
sage: F.solve(1)
(1, 0)
sage: F.solve(2)
(3/2, -1/2)
sage: F.solve(3)
(2, -1)
::
sage: F = DiagonalQuadraticForm(QQ, [1, 1, 1, 1])
sage: F.solve(7)
(1, 2, -1, -1)
sage: F.solve()
Traceback (most recent call last):
...
ArithmeticError: no solution found (local obstruction at -1)
::
sage: Q = QuadraticForm(QQ, 2, [17, 94, 130])
sage: x = Q.solve(5); x
(17, -6)
sage: Q(x)
5
sage: Q.solve(6)
Traceback (most recent call last):
...
ArithmeticError: no solution found (local obstruction at 3)
sage: G = DiagonalQuadraticForm(QQ, [5, -3, -2])
sage: x = G.solve(10); x
(3/2, -1/2, 1/2)
sage: G(x)
10
sage: F = DiagonalQuadraticForm(QQ, [1, -4])
sage: x = F.solve(); x
(2, 1)
sage: F(x)
0
::
sage: F = QuadraticForm(QQ, 4, [0, 0, 1, 0, 0, 0, 1, 0, 0, 0]); F
Quadratic form in 4 variables over Rational Field with coefficients:
[ 0 0 1 0 ]
[ * 0 0 1 ]
[ * * 0 0 ]
[ * * * 0 ]
sage: F.solve(23)
(23, 0, 1, 0)
Other fields besides the rationals are currently not supported::
sage: F = DiagonalQuadraticForm(GF(11), [1, 1])
sage: F.solve()
Traceback (most recent call last):
...
TypeError: solving quadratic forms is only implemented over QQ
"""
if self.base_ring() is not QQ:
raise TypeError("solving quadratic forms is only implemented over QQ")
M = self.Gram_matrix()
# If no argument passed for c, we just pass self into qfsolve().
if not c:
x = qfsolve(M)
if isinstance(x, Integer):
raise ArithmeticError("no solution found (local obstruction at {})".format(x))
return x
# If c != 0, define a new quadratic form Q = self - c*z^2
d = self.dim()
N = Matrix(self.base_ring(), d+1, d+1)
for i in range(d):
for j in range(d):
N[i,j] = M[i,j]
N[d,d] = -c
# Find a solution x to Q(x) = 0, using qfsolve()
x = qfsolve(N)
# Raise an error if qfsolve() doesn't find a solution
if isinstance(x, Integer):
raise ArithmeticError("no solution found (local obstruction at {})".format(x))
# Let z be the last term of x, and remove z from x
z = x[-1]
x = x[:-1]
# If z != 0, then Q(x/z) = c
if z:
return x * (1/z)
# Case 2: We found a solution self(x) = 0. Let e be any vector such
# that B(x,e) != 0, where B is the bilinear form corresponding to self.
# To find e, just try all unit vectors (0,..0,1,0...0).
# Let a = (c - self(e))/(2B(x,e)) and let y = e + a*x.
# Then self(y) = B(e + a*x, e + a*x) = self(e) + 2B(e, a*x)
# = self(e) + 2([c - self(e)]/[2B(x,e)]) * B(x,e) = c.
e = vector([1] + [0] * (d-1))
i = 0
while self.bilinear_map(x, e) == 0:
e[i] = 0
i += 1
e[i] = 1
a = (c - self(e)) / (2 * self.bilinear_map(x, e))
return e + a*x | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/qfsolve.py | 0.913782 | 0.778186 | qfsolve.py | pypi |
from sage.arith.all import valuation
from sage.rings.rational_field import QQ
def local_density(self, p, m):
"""
Return the local density.
.. NOTE::
This screens for imprimitive forms, and puts the quadratic
form in local normal form, which is a *requirement* of the
routines performing the computations!
INPUT:
- `p` -- a prime number > 0
- `m` -- an integer
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1]) # NOTE: This is already in local normal form for *all* primes p!
sage: Q.local_density(p=2, m=1)
1
sage: Q.local_density(p=3, m=1)
8/9
sage: Q.local_density(p=5, m=1)
24/25
sage: Q.local_density(p=7, m=1)
48/49
sage: Q.local_density(p=11, m=1)
120/121
"""
n = self.dim()
if n == 0:
raise TypeError("we do not currently handle 0-dim'l forms")
# Find the local normal form and p-scale of Q -- Note: This uses the valuation ordering of local_normal_form.
# TO DO: Write a separate p-scale and p-norm routines!
Q_local = self.local_normal_form(p)
if n == 1:
p_valuation = valuation(Q_local[0,0], p)
else:
p_valuation = min(valuation(Q_local[0,0], p), valuation(Q_local[0,1], p))
# If m is less p-divisible than the matrix, return zero
if ((m != 0) and (valuation(m,p) < p_valuation)): # Note: The (m != 0) condition protects taking the valuation of zero.
return QQ(0)
# If the form is imprimitive, rescale it and call the local density routine
p_adjustment = QQ(1) / p**p_valuation
m_prim = QQ(m) / p**p_valuation
Q_prim = Q_local.scale_by_factor(p_adjustment)
# Return the densities for the reduced problem
return Q_prim.local_density_congruence(p, m_prim)
def local_primitive_density(self, p, m):
"""
Gives the local primitive density -- should be called by the user. =)
NOTE: This screens for imprimitive forms, and puts the
quadratic form in local normal form, which is a *requirement* of
the routines performing the computations!
INPUT:
`p` -- a prime number > 0
`m` -- an integer
OUTPUT:
a rational number
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 4, range(10))
sage: Q[0,0] = 5
sage: Q[1,1] = 10
sage: Q[2,2] = 15
sage: Q[3,3] = 20
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 5 1 2 3 ]
[ * 10 5 6 ]
[ * * 15 8 ]
[ * * * 20 ]
sage: Q.theta_series(20)
1 + 2*q^5 + 2*q^10 + 2*q^14 + 2*q^15 + 2*q^16 + 2*q^18 + O(q^20)
sage: Q.local_normal_form(2)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 0 1 0 0 ]
[ * 0 0 0 ]
[ * * 0 1 ]
[ * * * 0 ]
sage: Q.local_primitive_density(2, 1)
3/4
sage: Q.local_primitive_density(5, 1)
24/25
sage: Q.local_primitive_density(2, 5)
3/4
sage: Q.local_density(2, 5)
3/4
"""
n = self.dim()
if n == 0:
raise TypeError("we do not currently handle 0-dim'l forms")
# Find the local normal form and p-scale of Q -- Note: This uses the valuation ordering of local_normal_form.
# TO DO: Write a separate p-scale and p-norm routines!
Q_local = self.local_normal_form(p)
if n == 1:
p_valuation = valuation(Q_local[0,0], p)
else:
p_valuation = min(valuation(Q_local[0,0], p), valuation(Q_local[0,1], p))
# If m is less p-divisible than the matrix, return zero
if ((m != 0) and (valuation(m,p) < p_valuation)): # Note: The (m != 0) condition protects taking the valuation of zero.
return QQ(0)
# If the form is imprimitive, rescale it and call the local density routine
p_adjustment = QQ(1) / p**p_valuation
m_prim = QQ(m) / p**p_valuation
Q_prim = Q_local.scale_by_factor(p_adjustment)
# Return the densities for the reduced problem
return Q_prim.local_primitive_density_congruence(p, m_prim) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/quadratic_form__local_density_interfaces.py | 0.828349 | 0.612484 | quadratic_form__local_density_interfaces.py | pypi |
r"""
Routines for computing special values of `L`-functions
- :func:`gamma__exact` -- Exact values of the `\Gamma` function at integers and half-integers
- :func:`zeta__exact` -- Exact values of the Riemann `\zeta` function at critical values
- :func:`quadratic_L_function__exact` -- Exact values of the Dirichlet L-functions of quadratic characters at critical values
- :func:`quadratic_L_function__numerical` -- Numerical values of the Dirichlet L-functions of quadratic characters in the domain of convergence
"""
from sage.combinat.combinat import bernoulli_polynomial
from sage.misc.functional import denominator
from sage.arith.all import kronecker_symbol, bernoulli, factorial, fundamental_discriminant
from sage.rings.infinity import infinity
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ
import sage.rings.abc
from sage.symbolic.constants import pi, I
# ---------------- The Gamma Function ------------------
def gamma__exact(n):
r"""
Evaluates the exact value of the `\Gamma` function at an integer or
half-integer argument.
EXAMPLES::
sage: gamma__exact(4)
6
sage: gamma__exact(3)
2
sage: gamma__exact(2)
1
sage: gamma__exact(1)
1
sage: gamma__exact(1/2)
sqrt(pi)
sage: gamma__exact(3/2)
1/2*sqrt(pi)
sage: gamma__exact(5/2)
3/4*sqrt(pi)
sage: gamma__exact(7/2)
15/8*sqrt(pi)
sage: gamma__exact(-1/2)
-2*sqrt(pi)
sage: gamma__exact(-3/2)
4/3*sqrt(pi)
sage: gamma__exact(-5/2)
-8/15*sqrt(pi)
sage: gamma__exact(-7/2)
16/105*sqrt(pi)
TESTS::
sage: gamma__exact(1/3)
Traceback (most recent call last):
...
TypeError: you must give an integer or half-integer argument
"""
from sage.all import sqrt
n = QQ(n)
if denominator(n) == 1:
if n <= 0:
return infinity
return factorial(n - 1)
elif denominator(n) == 2:
# now n = 1/2 + an integer
ans = QQ.one()
while n != QQ((1, 2)):
if n < 0:
ans /= n
n += 1
else:
n += -1
ans *= n
ans *= sqrt(pi)
return ans
else:
raise TypeError("you must give an integer or half-integer argument")
# ------------- The Riemann Zeta Function --------------
def zeta__exact(n):
r"""
Returns the exact value of the Riemann Zeta function
The argument must be a critical value, namely either positive even
or negative odd.
See for example [Iwa1972]_, p13, Special value of `\zeta(2k)`
EXAMPLES:
Let us test the accuracy for negative special values::
sage: RR = RealField(100)
sage: for i in range(1,10):
....: print("zeta({}): {}".format(1-2*i, RR(zeta__exact(1-2*i)) - zeta(RR(1-2*i))))
zeta(-1): 0.00000000000000000000000000000
zeta(-3): 0.00000000000000000000000000000
zeta(-5): 0.00000000000000000000000000000
zeta(-7): 0.00000000000000000000000000000
zeta(-9): 0.00000000000000000000000000000
zeta(-11): 0.00000000000000000000000000000
zeta(-13): 0.00000000000000000000000000000
zeta(-15): 0.00000000000000000000000000000
zeta(-17): 0.00000000000000000000000000000
Let us test the accuracy for positive special values::
sage: all(abs(RR(zeta__exact(2*i))-zeta(RR(2*i))) < 10**(-28) for i in range(1,10))
True
TESTS::
sage: zeta__exact(4)
1/90*pi^4
sage: zeta__exact(-3)
1/120
sage: zeta__exact(0)
-1/2
sage: zeta__exact(5)
Traceback (most recent call last):
...
TypeError: n must be a critical value (i.e. even > 0 or odd < 0)
REFERENCES:
- [Iwa1972]_
- [IR1990]_
- [Was1997]_
"""
if n < 0:
return bernoulli(1-n)/(n-1)
elif n > 1:
if (n % 2 == 0):
return ZZ(-1)**(n//2 + 1) * ZZ(2)**(n-1) * pi**n * bernoulli(n) / factorial(n)
else:
raise TypeError("n must be a critical value (i.e. even > 0 or odd < 0)")
elif n == 1:
return infinity
elif n == 0:
return QQ((-1, 2))
# ---------- Dirichlet L-functions with quadratic characters ----------
def QuadraticBernoulliNumber(k, d):
r"""
Compute `k`-th Bernoulli number for the primitive
quadratic character associated to `\chi(x) = \left(\frac{d}{x}\right)`.
EXAMPLES:
Let us create a list of some odd negative fundamental discriminants::
sage: test_set = [d for d in range(-163, -3, 4) if is_fundamental_discriminant(d)]
In general, we have `B_{1, \chi_d} = -2 h/w` for odd negative fundamental
discriminants::
sage: all(QuadraticBernoulliNumber(1, d) == -len(BinaryQF_reduced_representatives(d)) for d in test_set)
True
REFERENCES:
- [Iwa1972]_, pp 7-16.
"""
# Ensure the character is primitive
d1 = fundamental_discriminant(d)
f = abs(d1)
# Make the (usual) k-th Bernoulli polynomial
x = PolynomialRing(QQ, 'x').gen()
bp = bernoulli_polynomial(x, k)
# Make the k-th quadratic Bernoulli number
total = sum([kronecker_symbol(d1, i) * bp(i/f) for i in range(f)])
total *= (f ** (k-1))
return total
def quadratic_L_function__exact(n, d):
r"""
Returns the exact value of a quadratic twist of the Riemann Zeta function
by `\chi_d(x) = \left(\frac{d}{x}\right)`.
The input `n` must be a critical value.
EXAMPLES::
sage: quadratic_L_function__exact(1, -4)
1/4*pi
sage: quadratic_L_function__exact(-4, -4)
5/2
sage: quadratic_L_function__exact(2, 1)
1/6*pi^2
TESTS::
sage: quadratic_L_function__exact(2, -4)
Traceback (most recent call last):
...
TypeError: n must be a critical value (i.e. odd > 0 or even <= 0)
REFERENCES:
- [Iwa1972]_, pp 16-17, Special values of `L(1-n, \chi)` and `L(n, \chi)`
- [IR1990]_
- [Was1997]_
"""
from sage.all import SR, sqrt
if n <= 0:
return QuadraticBernoulliNumber(1-n,d)/(n-1)
elif n >= 1:
# Compute the kind of critical values (p10)
if kronecker_symbol(fundamental_discriminant(d), -1) == 1:
delta = 0
else:
delta = 1
# Compute the positive special values (p17)
if ((n - delta) % 2 == 0):
f = abs(fundamental_discriminant(d))
if delta == 0:
GS = sqrt(f)
else:
GS = I * sqrt(f)
ans = SR(ZZ(-1)**(1+(n-delta)/2))
ans *= (2*pi/f)**n
ans *= GS # Evaluate the Gauss sum here! =0
ans *= QQ.one()/(2 * I**delta)
ans *= QuadraticBernoulliNumber(n,d)/factorial(n)
return ans
else:
if delta == 0:
raise TypeError("n must be a critical value (i.e. even > 0 or odd < 0)")
if delta == 1:
raise TypeError("n must be a critical value (i.e. odd > 0 or even <= 0)")
def quadratic_L_function__numerical(n, d, num_terms=1000):
"""
Evaluate the Dirichlet L-function (for quadratic character) numerically
(in a very naive way).
EXAMPLES:
First, let us test several values for a given character::
sage: RR = RealField(100)
sage: for i in range(5):
....: print("L({}, (-4/.)): {}".format(1+2*i, RR(quadratic_L_function__exact(1+2*i, -4)) - quadratic_L_function__numerical(RR(1+2*i),-4, 10000)))
L(1, (-4/.)): 0.000049999999500000024999996962707
L(3, (-4/.)): 4.99999970000003...e-13
L(5, (-4/.)): 4.99999922759382...e-21
L(7, (-4/.)): ...e-29
L(9, (-4/.)): ...e-29
This procedure fails for negative special values, as the Dirichlet
series does not converge here::
sage: quadratic_L_function__numerical(-3,-4, 10000)
Traceback (most recent call last):
...
ValueError: the Dirichlet series does not converge here
Test for several characters that the result agrees with the exact
value, to a given accuracy ::
sage: for d in range(-20,0): # long time (2s on sage.math 2014)
....: if abs(RR(quadratic_L_function__numerical(1, d, 10000) - quadratic_L_function__exact(1, d))) > 0.001:
....: print("We have a problem at d = {}: exact = {}, numerical = {}".format(d, RR(quadratic_L_function__exact(1, d)), RR(quadratic_L_function__numerical(1, d))))
"""
# Set the correct precision if it is given (for n).
if isinstance(n.parent(), sage.rings.abc.RealField):
R = n.parent()
else:
from sage.rings.real_mpfr import RealField
R = RealField()
if n < 0:
raise ValueError('the Dirichlet series does not converge here')
d1 = fundamental_discriminant(d)
ans = R.zero()
for i in range(1,num_terms):
ans += R(kronecker_symbol(d1,i) / R(i)**n)
return ans | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/special_values.py | 0.927256 | 0.782164 | special_values.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.libs.pari.all import pari
from sage.matrix.constructor import Matrix
from sage.rings.integer_ring import ZZ
from sage.modules.all import FreeModule
from sage.modules.free_module_element import vector
from sage.arith.all import GCD
@cached_method
def basis_of_short_vectors(self, show_lengths=False):
r"""
Return a basis for `\ZZ^n` made of vectors with minimal lengths Q(`v`).
OUTPUT:
a tuple of vectors, and optionally a tuple of values for each vector.
This uses :pari:`qfminim`.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,5,7])
sage: Q.basis_of_short_vectors()
((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))
sage: Q.basis_of_short_vectors(True)
(((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)), (1, 3, 5, 7))
The returned vectors are immutable::
sage: v = Q.basis_of_short_vectors()[0]
sage: v
(1, 0, 0, 0)
sage: v[0] = 0
Traceback (most recent call last):
...
ValueError: vector is immutable; please change a copy instead (use copy())
"""
# Set an upper bound for the number of vectors to consider
Max_number_of_vectors = 10000
# Generate a PARI matrix for the associated Hessian matrix
M_pari = self.__pari__()
# Run through all possible minimal lengths to find a spanning set of vectors
n = self.dim()
M1 = Matrix([[0]])
vec_len = 0
while M1.rank() < n:
vec_len += 1
pari_mat = M_pari.qfminim(vec_len, Max_number_of_vectors)[2]
number_of_vecs = ZZ(pari_mat.matsize()[1])
vector_list = []
for i in range(number_of_vecs):
new_vec = vector([ZZ(x) for x in list(pari_mat[i])])
vector_list.append(new_vec)
# Make a matrix from the short vectors
if vector_list:
M1 = Matrix(vector_list)
# Organize these vectors by length (and also introduce their negatives)
max_len = vec_len // 2
vector_list_by_length = [[] for _ in range(max_len + 1)]
for v in vector_list:
l = self(v)
vector_list_by_length[l].append(v)
vector_list_by_length[l].append(vector([-x for x in v]))
# Make a matrix from the column vectors (in order of ascending length).
sorted_list = []
for i in range(len(vector_list_by_length)):
for v in vector_list_by_length[i]:
sorted_list.append(v)
sorted_matrix = Matrix(sorted_list).transpose()
# Determine a basis of vectors of minimal length
pivots = sorted_matrix.pivots()
basis = tuple(sorted_matrix.column(i) for i in pivots)
for v in basis:
v.set_immutable()
# Return the appropriate result
if show_lengths:
pivot_lengths = tuple(self(v) for v in basis)
return basis, pivot_lengths
else:
return basis
def short_vector_list_up_to_length(self, len_bound, up_to_sign_flag=False):
"""
Return a list of lists of short vectors `v`, sorted by length, with
Q(`v`) < len_bound.
INPUT:
- ``len_bound`` -- bound for the length of the vectors.
- ``up_to_sign_flag`` -- (default: ``False``) if set to True, then
only one of the vectors of the pair `[v, -v]` is listed.
OUTPUT:
A list of lists of vectors such that entry `[i]` contains all
vectors of length `i`.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,5,7])
sage: Q.short_vector_list_up_to_length(3)
[[(0, 0, 0, 0)], [(1, 0, 0, 0), (-1, 0, 0, 0)], []]
sage: Q.short_vector_list_up_to_length(4)
[[(0, 0, 0, 0)],
[(1, 0, 0, 0), (-1, 0, 0, 0)],
[],
[(0, 1, 0, 0), (0, -1, 0, 0)]]
sage: Q.short_vector_list_up_to_length(5)
[[(0, 0, 0, 0)],
[(1, 0, 0, 0), (-1, 0, 0, 0)],
[],
[(0, 1, 0, 0), (0, -1, 0, 0)],
[(1, 1, 0, 0),
(-1, -1, 0, 0),
(1, -1, 0, 0),
(-1, 1, 0, 0),
(2, 0, 0, 0),
(-2, 0, 0, 0)]]
sage: Q.short_vector_list_up_to_length(5, True)
[[(0, 0, 0, 0)],
[(1, 0, 0, 0)],
[],
[(0, 1, 0, 0)],
[(1, 1, 0, 0), (1, -1, 0, 0), (2, 0, 0, 0)]]
sage: Q = QuadraticForm(matrix(6, [2, 1, 1, 1, -1, -1, 1, 2, 1, 1, -1, -1, 1, 1, 2, 0, -1, -1, 1, 1, 0, 2, 0, -1, -1, -1, -1, 0, 2, 1, -1, -1, -1, -1, 1, 2]))
sage: vs = Q.short_vector_list_up_to_length(8)
sage: [len(vs[i]) for i in range(len(vs))]
[1, 72, 270, 720, 936, 2160, 2214, 3600]
sage: vs = Q.short_vector_list_up_to_length(30) # long time (28s on sage.math, 2014)
sage: [len(vs[i]) for i in range(len(vs))] # long time
[1, 72, 270, 720, 936, 2160, 2214, 3600, 4590, 6552, 5184, 10800, 9360, 12240, 13500, 17712, 14760, 25920, 19710, 26064, 28080, 36000, 25920, 47520, 37638, 43272, 45900, 59040, 46800, 75600]
The cases of ``len_bound < 2`` led to exception or infinite runtime before.
::
sage: Q.short_vector_list_up_to_length(-1)
[]
sage: Q.short_vector_list_up_to_length(0)
[]
sage: Q.short_vector_list_up_to_length(1)
[[(0, 0, 0, 0, 0, 0)]]
In the case of quadratic forms that are not positive definite an error is raised.
::
sage: QuadraticForm(matrix(2, [2, 0, 0, -2])).short_vector_list_up_to_length(3)
Traceback (most recent call last):
...
ValueError: Quadratic form must be positive definite in order to enumerate short vectors
Check that PARI does not return vectors which are too long::
sage: Q = QuadraticForm(matrix(2, [72, 12, 12, 120]))
sage: len_bound_pari = 2*22953421 - 2; len_bound_pari
45906840
sage: vs = list(Q.__pari__().qfminim(len_bound_pari)[2]) # long time (18s on sage.math, 2014)
sage: v = vs[0]; v # long time
[66, -623]~
sage: v.Vec() * Q.__pari__() * v # long time
45902280
"""
if not self.is_positive_definite():
raise ValueError("Quadratic form must be positive definite "
"in order to enumerate short vectors")
if len_bound <= 0:
return []
# Free module in which the vectors live
V = FreeModule(ZZ, self.dim())
# Adjust length for PARI. We need to subtract 1 because PARI returns
# returns vectors of length less than or equal to b, but we want
# strictly less. We need to double because the matrix is doubled.
len_bound_pari = 2 * (len_bound - 1)
# Call PARI's qfminim()
parilist = self.__pari__().qfminim(len_bound_pari)[2].Vec()
# List of lengths
parilens = pari(r"(M,v) -> vector(#v, i, (v[i]~ * M * v[i])\2)")(self, parilist)
# Sort the vectors into lists by their length
vec_sorted_list = [list() for i in range(len_bound)]
for i in range(len(parilist)):
length = int(parilens[i])
# In certain trivial cases, PARI can sometimes return longer
# vectors than requested.
if length < len_bound:
sagevec = V(list(parilist[i]))
vec_sorted_list[length].append(sagevec)
if not up_to_sign_flag:
vec_sorted_list[length].append(-sagevec)
# Add the zero vector by hand
vec_sorted_list[0].append(V.zero_vector())
return vec_sorted_list
def short_primitive_vector_list_up_to_length(self, len_bound, up_to_sign_flag=False):
r"""
Return a list of lists of short primitive vectors `v`, sorted by length, with
Q(`v`) < len_bound. The list in output `[i]` indexes all vectors of
length `i`. If the up_to_sign_flag is set to ``True``, then only one of
the vectors of the pair `[v, -v]` is listed.
.. NOTE::
This processes the PARI/GP output to always give elements of type `\ZZ`.
OUTPUT: a list of lists of vectors.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,5,7])
sage: Q.short_vector_list_up_to_length(5, True)
[[(0, 0, 0, 0)],
[(1, 0, 0, 0)],
[],
[(0, 1, 0, 0)],
[(1, 1, 0, 0), (1, -1, 0, 0), (2, 0, 0, 0)]]
sage: Q.short_primitive_vector_list_up_to_length(5, True)
[[], [(1, 0, 0, 0)], [], [(0, 1, 0, 0)], [(1, 1, 0, 0), (1, -1, 0, 0)]]
"""
# Get a list of short vectors
full_vec_list = self.short_vector_list_up_to_length(len_bound, up_to_sign_flag)
# Make a new list of the primitive vectors
prim_vec_list = [[v for v in L if GCD(v) == 1]
for L in full_vec_list]
# Return the list of primitive vectors
return prim_vec_list
def _compute_automorphisms(self):
"""
Call PARI to compute the automorphism group of the quadratic form.
This uses :pari:`qfauto`.
OUTPUT: None, this just caches the result.
TESTS::
sage: DiagonalQuadraticForm(ZZ, [-1,1,1])._compute_automorphisms()
Traceback (most recent call last):
...
ValueError: not a definite form in QuadraticForm.automorphisms()
sage: DiagonalQuadraticForm(GF(5), [1,1,1])._compute_automorphisms()
Traceback (most recent call last):
...
NotImplementedError: computing the automorphism group of a quadratic form is only supported over ZZ
"""
if self.base_ring() is not ZZ:
raise NotImplementedError("computing the automorphism group of a quadratic form is only supported over ZZ")
if not self.is_definite():
raise ValueError("not a definite form in QuadraticForm.automorphisms()")
if hasattr(self, "__automorphisms_pari"):
return
A = self.__pari__().qfauto()
self.__number_of_automorphisms = A[0]
self.__automorphisms_pari = A[1]
def automorphism_group(self):
"""
Return the group of automorphisms of the quadratic form.
OUTPUT: a :class:`MatrixGroup`
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1])
sage: Q.automorphism_group()
Matrix group over Rational Field with 3 generators (
[ 0 0 1] [1 0 0] [ 1 0 0]
[-1 0 0] [0 0 1] [ 0 -1 0]
[ 0 1 0], [0 1 0], [ 0 0 1]
)
::
sage: DiagonalQuadraticForm(ZZ, [1,3,5,7]).automorphism_group()
Matrix group over Rational Field with 4 generators (
[-1 0 0 0] [ 1 0 0 0] [ 1 0 0 0] [ 1 0 0 0]
[ 0 -1 0 0] [ 0 -1 0 0] [ 0 1 0 0] [ 0 1 0 0]
[ 0 0 -1 0] [ 0 0 1 0] [ 0 0 -1 0] [ 0 0 1 0]
[ 0 0 0 -1], [ 0 0 0 1], [ 0 0 0 1], [ 0 0 0 -1]
)
The smallest possible automorphism group has order two, since we
can always change all signs::
sage: Q = QuadraticForm(ZZ, 3, [2, 1, 2, 2, 1, 3])
sage: Q.automorphism_group()
Matrix group over Rational Field with 1 generators (
[-1 0 0]
[ 0 -1 0]
[ 0 0 -1]
)
"""
self._compute_automorphisms()
from sage.matrix.matrix_space import MatrixSpace
from sage.groups.matrix_gps.finitely_generated import MatrixGroup
MS = MatrixSpace(self.base_ring().fraction_field(), self.dim(), self.dim())
gens = [MS(x.sage()) for x in self.__automorphisms_pari]
return MatrixGroup(gens)
def automorphisms(self):
"""
Return the list of the automorphisms of the quadratic form.
OUTPUT: a list of matrices
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1])
sage: Q.number_of_automorphisms()
48
sage: 2^3 * factorial(3)
48
sage: len(Q.automorphisms())
48
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,5,7])
sage: Q.number_of_automorphisms()
16
sage: aut = Q.automorphisms()
sage: len(aut)
16
sage: all(Q(M) == Q for M in aut)
True
sage: Q = QuadraticForm(ZZ, 3, [2, 1, 2, 2, 1, 3])
sage: sorted(Q.automorphisms())
[
[-1 0 0] [1 0 0]
[ 0 -1 0] [0 1 0]
[ 0 0 -1], [0 0 1]
]
"""
return [x.matrix() for x in self.automorphism_group()]
def number_of_automorphisms(self):
"""
Return the number of automorphisms (of det 1 and -1) of
the quadratic form.
OUTPUT:
an integer >= 2.
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 3, [1, 0, 0, 1, 0, 1], unsafe_initialization=True)
sage: Q.number_of_automorphisms()
48
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.number_of_automorphisms()
384
sage: 2^4 * factorial(4)
384
"""
try:
return self.__number_of_automorphisms
except AttributeError:
self._compute_automorphisms()
return self.__number_of_automorphisms
def set_number_of_automorphisms(self, num_autos):
"""
Set the number of automorphisms to be the value given. No error
checking is performed, to this may lead to erroneous results.
The fact that this result was set externally is recorded in the
internal list of external initializations, accessible by the
method list_external_initializations().
OUTPUT: None
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1, 1, 1])
sage: Q.list_external_initializations()
[]
sage: Q.set_number_of_automorphisms(-3)
sage: Q.number_of_automorphisms()
-3
sage: Q.list_external_initializations()
['number_of_automorphisms']
"""
self.__number_of_automorphisms = num_autos
text = 'number_of_automorphisms'
if text not in self._external_initialization_list:
self._external_initialization_list.append(text) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/quadratic_form__automorphisms.py | 0.790328 | 0.514095 | quadratic_form__automorphisms.py | pypi |
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.quadratic_forms.quadratic_form import QuadraticForm
def BezoutianQuadraticForm(f, g):
r"""
Compute the Bezoutian of two polynomials defined over a common base ring. This is defined by
.. MATH::
{\rm Bez}(f, g) := \frac{f(x) g(y) - f(y) g(x)}{y - x}
and has size defined by the maximum of the degrees of `f` and `g`.
INPUT:
- `f`, `g` -- polynomials in `R[x]`, for some ring `R`
OUTPUT:
a quadratic form over `R`
EXAMPLES::
sage: R = PolynomialRing(ZZ, 'x')
sage: f = R([1,2,3])
sage: g = R([2,5])
sage: Q = BezoutianQuadraticForm(f, g) ; Q
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 1 -12 ]
[ * -15 ]
AUTHORS:
- Fernando Rodriguez-Villegas, Jonathan Hanke -- added on 11/9/2008
"""
# Check that f and g are polynomials with a common base ring
if not is_Polynomial(f) or not is_Polynomial(g):
raise TypeError("one of your inputs is not a polynomial")
if f.base_ring() != g.base_ring(): # TO DO: Change this to allow coercion!
raise TypeError("these polynomials are not defined over the same coefficient ring")
# Initialize the quadratic form
R = f.base_ring()
P = PolynomialRing(R, ['x','y'])
a, b = P.gens()
n = max(f.degree(), g.degree())
Q = QuadraticForm(R, n)
# Set the coefficients of Bezoutian
bez_poly = (f(a) * g(b) - f(b) * g(a)) // (b - a) # Truncated (exact) division here
for i in range(n):
for j in range(i, n):
if i == j:
Q[i,j] = bez_poly.coefficient({a:i,b:j})
else:
Q[i,j] = bez_poly.coefficient({a:i,b:j}) * 2
return Q
def HyperbolicPlane_quadratic_form(R, r=1):
"""
Constructs the direct sum of `r` copies of the quadratic form `xy`
representing a hyperbolic plane defined over the base ring `R`.
INPUT:
- `R`: a ring
- `n` (integer, default 1) number of copies
EXAMPLES::
sage: HyperbolicPlane_quadratic_form(ZZ)
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 0 1 ]
[ * 0 ]
"""
r = ZZ(r)
# Check that the multiplicity is a natural number
if r < 1:
raise TypeError("the multiplicity r must be a natural number")
H = QuadraticForm(R, 2, [0, 1, 0])
return sum([H for i in range(r - 1)], H) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/constructions.py | 0.916168 | 0.677132 | constructions.py | pypi |
from copy import deepcopy
from sage.matrix.constructor import matrix
from sage.functions.all import floor
from sage.misc.mrange import mrange
from sage.modules.free_module_element import vector
from sage.rings.integer_ring import ZZ
def reduced_binary_form1(self):
r"""
Reduce the form `ax^2 + bxy+cy^2` to satisfy the reduced condition `|b| \le
a \le c`, with `b \ge 0` if `a = c`. This reduction occurs within the
proper class, so all transformations are taken to have determinant 1.
EXAMPLES::
sage: QuadraticForm(ZZ,2,[5,5,2]).reduced_binary_form1()
(
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 2 -1 ]
[ * 2 ] ,
<BLANKLINE>
[ 0 -1]
[ 1 1]
)
"""
if self.dim() != 2:
raise TypeError("This must be a binary form for now...")
R = self.base_ring()
interior_reduced_flag = False
Q = deepcopy(self)
M = matrix(R, 2, 2, [1,0,0,1])
while not interior_reduced_flag:
interior_reduced_flag = True
# Arrange for a <= c
if Q[0,0] > Q[1,1]:
M_new = matrix(R,2,2,[0, -1, 1, 0])
Q = Q(M_new)
M = M * M_new
interior_reduced_flag = False
# Arrange for |b| <= a
if abs(Q[0,1]) > Q[0,0]:
r = R(floor(round(Q[0,1]/(2*Q[0,0]))))
M_new = matrix(R,2,2,[1, -r, 0, 1])
Q = Q(M_new)
M = M * M_new
interior_reduced_flag = False
return Q, M
def reduced_ternary_form__Dickson(self):
"""
Find the unique reduced ternary form according to the conditions
of Dickson's "Studies in the Theory of Numbers", pp164-171.
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1, 1, 1])
sage: Q.reduced_ternary_form__Dickson()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def reduced_binary_form(self):
"""
Find a form which is reduced in the sense that no further binary
form reductions can be done to reduce the original form.
EXAMPLES::
sage: QuadraticForm(ZZ,2,[5,5,2]).reduced_binary_form()
(
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 2 -1 ]
[ * 2 ] ,
<BLANKLINE>
[ 0 -1]
[ 1 1]
)
"""
R = self.base_ring()
n = self.dim()
interior_reduced_flag = False
Q = deepcopy(self)
M = matrix(R, n, n)
for i in range(n):
M[i,i] = 1
while not interior_reduced_flag:
interior_reduced_flag = True
# Arrange for (weakly) increasing diagonal entries
for i in range(n):
for j in range(i+1,n):
if Q[i,i] > Q[j,j]:
M_new = matrix(R,n,n)
for k in range(n):
M_new[k,k] = 1
M_new[i,j] = -1
M_new[j,i] = 1
M_new[i,i] = 0
M_new[j,j] = 1
Q = Q(M_new)
M = M * M_new
interior_reduced_flag = False
# Arrange for |b| <= a
if abs(Q[i,j]) > Q[i,i]:
r = R(floor(round(Q[i,j]/(2*Q[i,i]))))
M_new = matrix(R,n,n)
for k in range(n):
M_new[k,k] = 1
M_new[i,j] = -r
Q = Q(M_new)
M = M * M_new
interior_reduced_flag = False
return Q, M
def minkowski_reduction(self):
"""
Find a Minkowski-reduced form equivalent to the given one.
This means that
.. MATH::
Q(v_k) <= Q(s_1 * v_1 + ... + s_n * v_n)
for all `s_i` where GCD`(s_k, ... s_n) = 1`.
Note: When Q has dim <= 4 we can take all `s_i` in {1, 0, -1}.
References:
Schulze-Pillot's paper on "An algorithm for computing genera
of ternary and quaternary quadratic forms", p138.
Donaldson's 1979 paper "Minkowski Reduction of Integral
Matrices", p203.
EXAMPLES::
sage: Q = QuadraticForm(ZZ,4,[30, 17, 11, 12, 29, 25, 62, 64, 25, 110])
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 30 17 11 12 ]
[ * 29 25 62 ]
[ * * 64 25 ]
[ * * * 110 ]
sage: Q.minkowski_reduction()
(
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 30 17 11 -5 ]
[ * 29 25 4 ]
[ * * 64 0 ]
[ * * * 77 ] ,
<BLANKLINE>
[ 1 0 0 0]
[ 0 1 0 -1]
[ 0 0 1 0]
[ 0 0 0 1]
)
::
sage: Q = QuadraticForm(ZZ,4,[1, -2, 0, 0, 2, 0, 0, 2, 0, 2])
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 -2 0 0 ]
[ * 2 0 0 ]
[ * * 2 0 ]
[ * * * 2 ]
sage: Q.minkowski_reduction()
(
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 0 0 0 ]
[ * 1 0 0 ]
[ * * 2 0 ]
[ * * * 2 ] ,
<BLANKLINE>
[1 1 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
)
sage: Q = QuadraticForm(ZZ,5,[2,2,0,0,0,2,2,0,0,2,2,0,2,2,2])
sage: Q.Gram_matrix()
[2 1 0 0 0]
[1 2 1 0 0]
[0 1 2 1 0]
[0 0 1 2 1]
[0 0 0 1 2]
sage: Q.minkowski_reduction()
Traceback (most recent call last):
...
NotImplementedError: this algorithm is only for dimensions less than 5
"""
from sage.quadratic_forms.quadratic_form import QuadraticForm
from sage.quadratic_forms.quadratic_form import matrix
if not self.is_positive_definite():
raise TypeError("Minkowski reduction only works for positive definite forms")
if self.dim() > 4:
raise NotImplementedError("this algorithm is only for dimensions less than 5")
R = self.base_ring()
n = self.dim()
Q = deepcopy(self)
M = matrix(R, n, n)
for i in range(n):
M[i, i] = 1
# Begin the reduction
done_flag = False
while not done_flag:
# Loop through possible shorted vectors until
done_flag = True
for j in range(n-1, -1, -1):
for a_first in mrange([3 for i in range(j)]):
y = [x-1 for x in a_first] + [1] + [0 for k in range(n-1-j)]
e_j = [0 for k in range(n)]
e_j[j] = 1
# Reduce if a shorter vector is found
if Q(y) < Q(e_j):
# Create the transformation matrix
M_new = matrix(R, n, n)
for k in range(n):
M_new[k,k] = 1
for k in range(n):
M_new[k,j] = y[k]
# Perform the reduction and restart the loop
Q = QuadraticForm(M_new.transpose()*Q.matrix()*M_new)
M = M * M_new
done_flag = False
if not done_flag:
break
if not done_flag:
break
# Return the results
return Q, M
def minkowski_reduction_for_4vars__SP(self):
"""
Find a Minkowski-reduced form equivalent to the given one.
This means that
Q(`v_k`) <= Q(`s_1 * v_1 + ... + s_n * v_n`)
for all `s_i` where GCD(`s_k, ... s_n`) = 1.
Note: When Q has dim <= 4 we can take all `s_i` in {1, 0, -1}.
References:
Schulze-Pillot's paper on "An algorithm for computing genera
of ternary and quaternary quadratic forms", p138.
Donaldson's 1979 paper "Minkowski Reduction of Integral
Matrices", p203.
EXAMPLES::
sage: Q = QuadraticForm(ZZ,4,[30,17,11,12,29,25,62,64,25,110])
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 30 17 11 12 ]
[ * 29 25 62 ]
[ * * 64 25 ]
[ * * * 110 ]
sage: Q.minkowski_reduction_for_4vars__SP()
(
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 29 -17 25 4 ]
[ * 30 -11 5 ]
[ * * 64 0 ]
[ * * * 77 ] ,
<BLANKLINE>
[ 0 1 0 0]
[ 1 0 0 -1]
[ 0 0 1 0]
[ 0 0 0 1]
)
"""
R = self.base_ring()
n = self.dim()
Q = deepcopy(self)
M = matrix(R, n, n)
for i in range(n):
M[i, i] = 1
# Only allow 4-variable forms
if n != 4:
raise TypeError(f"the given quadratic form has {n} != 4 variables")
# Step 1: Begin the reduction
done_flag = False
while not done_flag:
# Loop through possible shorter vectors
done_flag = True
for j in range(n-1, -1, -1):
for a_first in mrange([2 for i in range(j)]):
y = [x-1 for x in a_first] + [1] + [0 for k in range(n-1-j)]
e_j = [0 for k in range(n)]
e_j[j] = 1
# Reduce if a shorter vector is found
if Q(y) < Q(e_j):
# Further n=4 computations
B_y_vec = Q.matrix() * vector(ZZ, y)
# SP's B = our self.matrix()/2
# SP's A = coeff matrix of his B
# Here we compute the double of both and compare.
B_sum = sum([abs(B_y_vec[i]) for i in range(4) if i != j])
A_sum = sum([abs(Q[i,j]) for i in range(4) if i != j])
B_max = max([abs(B_y_vec[i]) for i in range(4) if i != j])
A_max = max([abs(Q[i,j]) for i in range(4) if i != j])
if (B_sum < A_sum) or ((B_sum == A_sum) and (B_max < A_max)):
# Create the transformation matrix
M_new = matrix(R, n, n)
for k in range(n):
M_new[k,k] = 1
for k in range(n):
M_new[k,j] = y[k]
# Perform the reduction and restart the loop
Q = Q(M_new)
M = M * M_new
done_flag = False
if not done_flag:
break
if not done_flag:
break
# Step 2: Order A by certain criteria
for i in range(4):
for j in range(i+1,4):
# Condition (a)
if (Q[i,i] > Q[j,j]):
Q.swap_variables(i,j,in_place=True)
M_new = matrix(R,n,n)
M_new[i,j] = -1
M_new[j,i] = 1
for r in range(4):
if (r == i) or (r == j):
M_new[r,r] = 0
else:
M_new[r,r] = 1
M = M * M_new
elif (Q[i,i] == Q[j,j]):
i_sum = sum([abs(Q[i,k]) for k in range(4) if k != i])
j_sum = sum([abs(Q[j,k]) for k in range(4) if k != j])
# Condition (b)
if (i_sum > j_sum):
Q.swap_variables(i,j,in_place=True)
M_new = matrix(R,n,n)
M_new[i,j] = -1
M_new[j,i] = 1
for r in range(4):
if (r == i) or (r == j):
M_new[r,r] = 0
else:
M_new[r,r] = 1
M = M * M_new
elif (i_sum == j_sum):
for k in [2,1,0]: # TO DO: These steps are a little redundant...
Q1 = Q.matrix()
c_flag = True
for l in range(k+1,4):
c_flag = c_flag and (abs(Q1[i,l]) == abs(Q1[j,l]))
# Condition (c)
if c_flag and (abs(Q1[i,k]) > abs(Q1[j,k])):
Q.swap_variables(i,j,in_place=True)
M_new = matrix(R,n,n)
M_new[i,j] = -1
M_new[j,i] = 1
for r in range(4):
if (r == i) or (r == j):
M_new[r,r] = 0
else:
M_new[r,r] = 1
M = M * M_new
# Step 3: Order the signs
for i in range(4):
if Q[i,3] < 0:
Q.multiply_variable(-1, i, in_place=True)
M_new = matrix(R,n,n)
for r in range(4):
if r == i:
M_new[r,r] = -1
else:
M_new[r,r] = 1
M = M * M_new
for i in range(4):
j = 3
while (Q[i,j] == 0):
j += -1
if (Q[i,j] < 0):
Q.multiply_variable(-1, i, in_place=True)
M_new = matrix(R,n,n)
for r in range(4):
if r == i:
M_new[r,r] = -1
else:
M_new[r,r] = 1
M = M * M_new
if Q[1,2] < 0:
# Test a row 1 sign change
if (Q[1,3] <= 0 and \
((Q[1,3] < 0) or (Q[1,3] == 0 and Q[1,2] < 0) \
or (Q[1,3] == 0 and Q[1,2] == 0 and Q[1,1] < 0))):
Q.multiply_variable(-1, i, in_place=True)
M_new = matrix(R,n,n)
for r in range(4):
if r == i:
M_new[r,r] = -1
else:
M_new[r,r] = 1
M = M * M_new
elif (Q[2,3] <= 0 and \
((Q[2,3] < 0) or (Q[2,3] == 0 and Q[2,2] < 0) \
or (Q[2,3] == 0 and Q[2,2] == 0 and Q[2,1] < 0))):
Q.multiply_variable(-1, i, in_place=True)
M_new = matrix(R,n,n)
for r in range(4):
if r == i:
M_new[r,r] = -1
else:
M_new[r,r] = 1
M = M * M_new
# Return the results
return Q, M | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/quadratic_form__reduction_theory.py | 0.819316 | 0.557845 | quadratic_form__reduction_theory.py | pypi |
def swap_variables(self, r, s, in_place=False):
"""
Switch the variables `x_r` and `x_s` in the quadratic form
(replacing the original form if the in_place flag is True).
INPUT:
- `r`, `s` -- integers >= 0
OUTPUT:
a QuadraticForm (by default, otherwise none)
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 4, range(1,11))
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 2 3 4 ]
[ * 5 6 7 ]
[ * * 8 9 ]
[ * * * 10 ]
sage: Q.swap_variables(0,2)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 8 6 3 9 ]
[ * 5 2 7 ]
[ * * 1 4 ]
[ * * * 10 ]
sage: Q.swap_variables(0,2).swap_variables(0,2)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 2 3 4 ]
[ * 5 6 7 ]
[ * * 8 9 ]
[ * * * 10 ]
"""
if not in_place:
Q = self.parent()(self.base_ring(), self.dim(), self.coefficients())
Q.swap_variables(r, s, in_place=True)
return Q
# Switch diagonal elements
tmp = self[r, r]
self[r, r] = self[s, s]
self[s, s] = tmp
# Switch off-diagonal elements
for i in range(self.dim()):
if (i != r) and (i != s):
tmp = self[r, i]
self[r, i] = self[s, i]
self[s, i] = tmp
def multiply_variable(self, c, i, in_place=False):
"""
Replace the variables `x_i` by `c*x_i` in the quadratic form
(replacing the original form if the in_place flag is True).
Here `c` must be an element of the base_ring defining the
quadratic form.
INPUT:
- `c` -- an element of Q.base_ring()
- `i` -- an integer >= 0
OUTPUT:
a QuadraticForm (by default, otherwise none)
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,9,5,7])
sage: Q.multiply_variable(5,0)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 25 0 0 0 ]
[ * 9 0 0 ]
[ * * 5 0 ]
[ * * * 7 ]
"""
if not in_place:
Q = self.parent()(self.base_ring(), self.dim(), self.coefficients())
Q.multiply_variable(c, i, in_place=True)
return Q
# Stretch the diagonal element
tmp = c * c * self[i, i]
self[i, i] = tmp
# Switch off-diagonal elements
for k in range(self.dim()):
if (k != i):
tmp = c * self[k, i]
self[k, i] = tmp
def divide_variable(self, c, i, in_place=False):
"""
Replace the variables `x_i` by `(x_i)/c` in the quadratic form
(replacing the original form if the in_place flag is True).
Here `c` must be an element of the base_ring defining the
quadratic form, and the division must be defined in the base
ring.
INPUT:
- `c` -- an element of Q.base_ring()
- `i` -- an integer >= 0
OUTPUT:
a QuadraticForm (by default, otherwise none)
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,9,5,7])
sage: Q.divide_variable(3,1)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 0 0 0 ]
[ * 1 0 0 ]
[ * * 5 0 ]
[ * * * 7 ]
"""
if not in_place:
Q = self.parent()(self.base_ring(), self.dim(), self.coefficients())
Q.divide_variable(c, i, in_place=True)
return Q
# Stretch the diagonal element
tmp = self[i, i] / (c * c)
self[i, i] = tmp
# Switch off-diagonal elements
for k in range(self.dim()):
if (k != i):
tmp = self[k, i] / c
self[k, i] = tmp
def scale_by_factor(self, c, change_value_ring_flag=False):
"""
Scale the values of the quadratic form by the number `c`, if
this is possible while still being defined over its base ring.
If the flag is set to true, then this will alter the value ring
to be the field of fractions of the original ring (if necessary).
INPUT:
`c` -- a scalar in the fraction field of the value ring of the form.
OUTPUT:
A quadratic form of the same dimension
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [3,9,18,27])
sage: Q.scale_by_factor(3)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 9 0 0 0 ]
[ * 27 0 0 ]
[ * * 54 0 ]
[ * * * 81 ]
sage: Q.scale_by_factor(1/3)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 0 0 0 ]
[ * 3 0 0 ]
[ * * 6 0 ]
[ * * * 9 ]
"""
# Try to scale the coefficients while staying in the ring of values.
new_coeff_list = [x * c for x in self.coefficients()]
# Check if we can preserve the value ring and return result. -- USE THE BASE_RING FOR NOW...
R = self.base_ring()
try:
list2 = [R(x) for x in new_coeff_list]
Q = self.parent()(R, self.dim(), list2)
return Q
except ValueError:
if not change_value_ring_flag:
raise TypeError("we could not rescale the lattice in this way and preserve its defining ring")
else:
raise RuntimeError("this code is not tested by current doctests")
F = R.fraction_field()
list2 = [F(x) for x in new_coeff_list]
Q = self.parent()(self.dim(), F, list2, R) # DEFINE THIS! IT WANTS TO SET THE EQUIVALENCE RING TO R, BUT WITH COEFFS IN F.
# Q.set_equivalence_ring(R)
return Q
def extract_variables(QF, var_indices):
"""
Extract the variables (in order) whose indices are listed in
``var_indices``, to give a new quadratic form.
INPUT:
``var_indices`` -- a list of integers >= 0
OUTPUT:
a QuadraticForm
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 4, range(10)); Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 0 1 2 3 ]
[ * 4 5 6 ]
[ * * 7 8 ]
[ * * * 9 ]
sage: Q.extract_variables([1,3])
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 4 6 ]
[ * 9 ]
"""
m = len(var_indices)
return QF.parent()(QF.base_ring(), m,
[QF[var_indices[i], var_indices[j]]
for i in range(m)
for j in range(i, m)])
def elementary_substitution(self, c, i, j, in_place=False): # CHECK THIS!!!
"""
Perform the substitution `x_i --> x_i + c*x_j` (replacing the
original form if the in_place flag is True).
INPUT:
- `c` -- an element of Q.base_ring()
- `i`, `j` -- integers >= 0
OUTPUT:
a QuadraticForm (by default, otherwise none)
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 4, range(1,11))
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 2 3 4 ]
[ * 5 6 7 ]
[ * * 8 9 ]
[ * * * 10 ]
sage: Q.elementary_substitution(c=1, i=0, j=3)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 2 3 6 ]
[ * 5 6 9 ]
[ * * 8 12 ]
[ * * * 15 ]
::
sage: R = QuadraticForm(ZZ, 4, range(1,11))
sage: R
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 2 3 4 ]
[ * 5 6 7 ]
[ * * 8 9 ]
[ * * * 10 ]
::
sage: M = Matrix(ZZ, 4, 4, [1,0,0,1,0,1,0,0,0,0,1,0,0,0,0,1])
sage: M
[1 0 0 1]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
sage: R(M)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 1 2 3 6 ]
[ * 5 6 9 ]
[ * * 8 12 ]
[ * * * 15 ]
"""
if not in_place:
Q = self.parent()(self.base_ring(), self.dim(), self.coefficients())
Q.elementary_substitution(c, i, j, True)
return Q
# Adjust the a_{k,j} coefficients
ij_old = self[i, j] # Store this since it's overwritten, but used in the a_{j,j} computation!
for k in range(self.dim()):
if (k != i) and (k != j):
ans = self[j, k] + c * self[i, k]
self[j, k] = ans
elif (k == j):
ans = self[j, k] + c * ij_old + c * c * self[i, i]
self[j, k] = ans
else:
ans = self[j, k] + 2 * c * self[i, k]
self[j, k] = ans
def add_symmetric(self, c, i, j, in_place=False):
"""
Performs the substitution `x_j --> x_j + c*x_i`, which has the
effect (on associated matrices) of symmetrically adding
`c * j`-th row/column to the `i`-th row/column.
NOTE: This is meant for compatibility with previous code,
which implemented a matrix model for this class. It is used
in the local_normal_form() method.
INPUT:
- `c` -- an element of Q.base_ring()
- `i`, `j` -- integers >= 0
OUTPUT:
a QuadraticForm (by default, otherwise none)
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 3, range(1,7)); Q
Quadratic form in 3 variables over Integer Ring with coefficients:
[ 1 2 3 ]
[ * 4 5 ]
[ * * 6 ]
sage: Q.add_symmetric(-1, 1, 0)
Quadratic form in 3 variables over Integer Ring with coefficients:
[ 1 0 3 ]
[ * 3 2 ]
[ * * 6 ]
sage: Q.add_symmetric(-3/2, 2, 0) # ERROR: -3/2 isn't in the base ring ZZ
Traceback (most recent call last):
...
RuntimeError: this coefficient cannot be coerced to an element of the base ring for the quadratic form
::
sage: Q = QuadraticForm(QQ, 3, range(1,7)); Q
Quadratic form in 3 variables over Rational Field with coefficients:
[ 1 2 3 ]
[ * 4 5 ]
[ * * 6 ]
sage: Q.add_symmetric(-3/2, 2, 0)
Quadratic form in 3 variables over Rational Field with coefficients:
[ 1 2 0 ]
[ * 4 2 ]
[ * * 15/4 ]
"""
return self.elementary_substitution(c, j, i, in_place) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/quadratic_form__variable_substitutions.py | 0.719581 | 0.722992 | quadratic_form__variable_substitutions.py | pypi |
import copy
from sage.rings.infinity import Infinity
from sage.rings.integer_ring import IntegerRing, ZZ
from sage.rings.rational_field import QQ
from sage.arith.all import GCD, valuation, is_prime
def find_entry_with_minimal_scale_at_prime(self, p):
"""
Finds the entry of the quadratic form with minimal scale at the
prime p, preferring diagonal entries in case of a tie. (I.e. If
we write the quadratic form as a symmetric matrix M, then this
entry M[i,j] has the minimal valuation at the prime p.)
Note: This answer is independent of the kind of matrix (Gram or
Hessian) associated to the form.
INPUT:
`p` -- a prime number > 0
OUTPUT:
a pair of integers >= 0
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 2, [6, 2, 20]); Q
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 6 2 ]
[ * 20 ]
sage: Q.find_entry_with_minimal_scale_at_prime(2)
(0, 1)
sage: Q.find_entry_with_minimal_scale_at_prime(3)
(1, 1)
sage: Q.find_entry_with_minimal_scale_at_prime(5)
(0, 0)
"""
n = self.dim()
min_val = Infinity
ij_index = None
val_2 = valuation(2, p)
for d in range(n): # d = difference j-i
for e in range(n - d): # e is the length of the diagonal with value d.
# Compute the valuation of the entry
if d == 0:
tmp_val = valuation(self[e, e + d], p)
else:
tmp_val = valuation(self[e, e + d], p) - val_2
# Check if it's any smaller than what we have
if tmp_val < min_val:
ij_index = (e, e + d)
min_val = tmp_val
# Return the result
return ij_index
def local_normal_form(self, p):
r"""
Return a locally integrally equivalent quadratic form over
the `p`-adic integers `\ZZ_p` which gives the Jordan decomposition.
The Jordan components are written as sums of blocks of size <= 2
and are arranged by increasing scale, and then by increasing norm.
This is equivalent to saying that we put the 1x1 blocks before
the 2x2 blocks in each Jordan component.
INPUT:
- `p` -- a positive prime number.
OUTPUT:
a quadratic form over `\ZZ`
.. WARNING::
Currently this only works for quadratic forms defined over `\ZZ`.
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 2, [10,4,1])
sage: Q.local_normal_form(5)
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 1 0 ]
[ * 6 ]
::
sage: Q.local_normal_form(3)
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 10 0 ]
[ * 15 ]
sage: Q.local_normal_form(2)
Quadratic form in 2 variables over Integer Ring with coefficients:
[ 1 0 ]
[ * 6 ]
"""
# Sanity Checks
if (self.base_ring() != IntegerRing()):
raise NotImplementedError("this currently only works for quadratic forms defined over ZZ")
if not ((p>=2) and is_prime(p)):
raise TypeError("p is not a positive prime number")
# Some useful local variables
Q = self.parent()(self.base_ring(), self.dim(), self.coefficients())
# Prepare the final form to return
Q_Jordan = copy.deepcopy(self)
Q_Jordan.__init__(self.base_ring(), 0)
while Q.dim() > 0:
n = Q.dim()
# Step 1: Find the minimally p-divisible matrix entry, preferring diagonals
# -------------------------------------------------------------------------
(min_i, min_j) = Q.find_entry_with_minimal_scale_at_prime(p)
if min_i == min_j:
min_val = valuation(2 * Q[min_i, min_j], p)
else:
min_val = valuation(Q[min_i, min_j], p)
# Error if we still haven't seen non-zero coefficients!
if (min_val == Infinity):
raise RuntimeError("the original matrix is degenerate")
# Step 2: Arrange for the upper leftmost entry to have minimal valuation
# ----------------------------------------------------------------------
if (min_i == min_j):
block_size = 1
Q.swap_variables(0, min_i, in_place = True)
else:
# Work in the upper-left 2x2 block, and replace it by its 2-adic equivalent form
Q.swap_variables(0, min_i, in_place = True)
Q.swap_variables(1, min_j, in_place = True)
# 1x1 => make upper left the smallest
if (p != 2):
block_size = 1
Q.add_symmetric(1, 0, 1, in_place=True)
# 2x2 => replace it with the appropriate 2x2 matrix
else:
block_size = 2
# Step 3: Clear out the remaining entries
# ---------------------------------------
min_scale = p ** min_val # This is the minimal valuation of the Hessian matrix entries.
# Perform cancellation over Z by ensuring divisibility
if (block_size == 1):
a = 2 * Q[0,0]
for j in range(block_size, n):
b = Q[0, j]
g = GCD(a, b)
# Sanity Check: a/g is a p-unit
if valuation(g, p) != valuation(a, p):
raise RuntimeError("we have a problem with our rescaling not preserving p-integrality")
Q.multiply_variable(ZZ(a/g), j, in_place = True) # Ensures that the new b entry is divisible by a
Q.add_symmetric(ZZ(-b/g), j, 0, in_place = True) # Performs the cancellation
elif (block_size == 2):
a1 = 2 * Q[0,0]
a2 = Q[0, 1]
b1 = Q[1, 0] # This is the same as a2
b2 = 2 * Q[1, 1]
big_det = (a1*b2 - a2*b1)
small_det = big_det / (min_scale * min_scale)
# Cancels out the rows/columns of the 2x2 block
for j in range(block_size, n):
a = Q[0, j]
b = Q[1, j]
# Ensures an integral result (scale jth row/column by big_det)
Q.multiply_variable(big_det, j, in_place = True)
# Performs the cancellation (by producing -big_det * jth row/column)
Q.add_symmetric(ZZ(-(a*b2 - b*a2)), j, 0, in_place = True)
Q.add_symmetric(ZZ(-(-a*b1 + b*a1)), j, 1, in_place = True)
# Now remove the extra factor (non p-unit factor) in big_det we introduced above
Q.divide_variable(ZZ(min_scale * min_scale), j, in_place = True)
# Uses Cassels's proof to replace the remaining 2 x 2 block
if (((1 + small_det) % 8) == 0):
Q[0, 0] = 0
Q[1, 1] = 0
Q[0, 1] = min_scale
elif (((5 + small_det) % 8) == 0):
Q[0, 0] = min_scale
Q[1, 1] = min_scale
Q[0, 1] = min_scale
else:
raise RuntimeError("Error in LocalNormal: Impossible behavior for a 2x2 block! \n")
# Check that the cancellation worked, extract the upper-left block, and trim Q to handle the next block.
for i in range(block_size):
for j in range(block_size, n):
if Q[i,j] != 0:
raise RuntimeError(f"the cancellation did not work properly at entry ({i},{j})")
Q_Jordan = Q_Jordan + Q.extract_variables(range(block_size))
Q = Q.extract_variables(range(block_size, n))
return Q_Jordan
def jordan_blocks_by_scale_and_unimodular(self, p, safe_flag=True):
r"""
Return a list of pairs `(s_i, L_i)` where `L_i` is a maximal
`p^{s_i}`-unimodular Jordan component which is further decomposed into
block diagonals of block size `\le 2`.
For each `L_i` the 2x2 blocks are listed after the 1x1 blocks
(which follows from the convention of the
:meth:`local_normal_form` method).
.. NOTE::
The decomposition of each `L_i` into smaller blocks is not unique!
The ``safe_flag`` argument allows us to select whether we want a copy of
the output, or the original output. By default ``safe_flag = True``, so we
return a copy of the cached information. If this is set to ``False``, then
the routine is much faster but the return values are vulnerable to being
corrupted by the user.
INPUT:
- `p` -- a prime number > 0.
OUTPUT:
A list of pairs `(s_i, L_i)` where:
- `s_i` is an integer,
- `L_i` is a block-diagonal unimodular quadratic form over `\ZZ_p`.
.. note::
These forms `L_i` are defined over the `p`-adic integers, but by a
matrix over `\ZZ` (or `\QQ`?).
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,9,5,7])
sage: Q.jordan_blocks_by_scale_and_unimodular(3)
[(0, Quadratic form in 3 variables over Integer Ring with coefficients:
[ 1 0 0 ]
[ * 5 0 ]
[ * * 7 ]), (2, Quadratic form in 1 variables over Integer Ring with coefficients:
[ 1 ])]
::
sage: Q2 = QuadraticForm(ZZ, 2, [1,1,1])
sage: Q2.jordan_blocks_by_scale_and_unimodular(2)
[(-1, Quadratic form in 2 variables over Integer Ring with coefficients:
[ 2 2 ]
[ * 2 ])]
sage: Q = Q2 + Q2.scale_by_factor(2)
sage: Q.jordan_blocks_by_scale_and_unimodular(2)
[(-1, Quadratic form in 2 variables over Integer Ring with coefficients:
[ 2 2 ]
[ * 2 ]), (0, Quadratic form in 2 variables over Integer Ring with coefficients:
[ 2 2 ]
[ * 2 ])]
"""
# Try to use the cached result
try:
if safe_flag:
return copy.deepcopy(self.__jordan_blocks_by_scale_and_unimodular_dict[p])
else:
return self.__jordan_blocks_by_scale_and_unimodular_dict[p]
except Exception:
# Initialize the global dictionary if it doesn't exist
if not hasattr(self, '__jordan_blocks_by_scale_and_unimodular_dict'):
self.__jordan_blocks_by_scale_and_unimodular_dict = {}
# Deal with zero dim'l forms
if self.dim() == 0:
return []
# Find the Local Normal form of Q at p
Q1 = self.local_normal_form(p)
# Parse this into Jordan Blocks
n = Q1.dim()
tmp_Jordan_list = []
i = 0
start_ind = 0
if (n >= 2) and (Q1[0,1] != 0):
start_scale = valuation(Q1[0,1], p) - 1
else:
start_scale = valuation(Q1[0,0], p)
while (i < n):
# Determine the size of the current block
if (i == n-1) or (Q1[i,i+1] == 0):
block_size = 1
else:
block_size = 2
# Determine the valuation of the current block
if block_size == 1:
block_scale = valuation(Q1[i,i], p)
else:
block_scale = valuation(Q1[i,i+1], p) - 1
# Process the previous block if the valuation increased
if block_scale > start_scale:
tmp_Jordan_list += [(start_scale, Q1.extract_variables(range(start_ind, i)).scale_by_factor(ZZ(1) / (QQ(p)**(start_scale))))]
start_ind = i
start_scale = block_scale
# Increment the index
i += block_size
# Add the last block
tmp_Jordan_list += [(start_scale, Q1.extract_variables(range(start_ind, n)).scale_by_factor(ZZ(1) / QQ(p)**(start_scale)))]
# Cache the result
self.__jordan_blocks_by_scale_and_unimodular_dict[p] = tmp_Jordan_list
# Return the result
return tmp_Jordan_list
def jordan_blocks_in_unimodular_list_by_scale_power(self, p):
"""
Returns a list of Jordan components, whose component at index i
should be scaled by the factor p^i.
This is only defined for integer-valued quadratic forms
(i.e. forms with base_ring ZZ), and the indexing only works
correctly for p=2 when the form has an integer Gram matrix.
INPUT:
self -- a quadratic form over ZZ, which has integer Gram matrix if p == 2
`p` -- a prime number > 0
OUTPUT:
a list of p-unimodular quadratic forms
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 3, [2, -2, 0, 3, -5, 4])
sage: Q.jordan_blocks_in_unimodular_list_by_scale_power(2)
Traceback (most recent call last):
...
TypeError: the given quadratic form has a Jordan component with a negative scale exponent
sage: Q.scale_by_factor(2).jordan_blocks_in_unimodular_list_by_scale_power(2)
[Quadratic form in 2 variables over Integer Ring with coefficients:
[ 0 2 ]
[ * 0 ], Quadratic form in 0 variables over Integer Ring with coefficients:
, Quadratic form in 1 variables over Integer Ring with coefficients:
[ 345 ]]
sage: Q.jordan_blocks_in_unimodular_list_by_scale_power(3)
[Quadratic form in 2 variables over Integer Ring with coefficients:
[ 2 0 ]
[ * 10 ], Quadratic form in 1 variables over Integer Ring with coefficients:
[ 2 ]]
"""
# Sanity Check
if self.base_ring() != ZZ:
raise TypeError("this method only makes sense for integer-valued quadratic forms (i.e. defined over ZZ)")
# Deal with zero dim'l forms
if self.dim() == 0:
return []
# Find the Jordan Decomposition
list_of_jordan_pairs = self.jordan_blocks_by_scale_and_unimodular(p)
scale_list = [P[0] for P in list_of_jordan_pairs]
s_max = max(scale_list)
if min(scale_list) < 0:
raise TypeError("the given quadratic form has a Jordan component with a negative scale exponent")
# Make the new list of unimodular Jordan components
zero_form = self.parent()(ZZ, 0)
list_by_scale = [zero_form for _ in range(s_max + 1)]
for P in list_of_jordan_pairs:
list_by_scale[P[0]] = P[1]
# Return the new list
return list_by_scale | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/quadratic_forms/quadratic_form__local_normal_form.py | 0.761893 | 0.58673 | quadratic_form__local_normal_form.py | pypi |
from sage.misc.lazy_import import lazy_import
lazy_import('sage.functions.piecewise', 'piecewise')
lazy_import('sage.functions.error', ['erf', 'erfc', 'erfi', 'erfinv',
'fresnel_sin', 'fresnel_cos'])
from .trig import ( sin, cos, sec, csc, cot, tan,
asin, acos, atan,
acot, acsc, asec,
arcsin, arccos, arctan,
arccot, arccsc, arcsec,
arctan2, atan2)
from .hyperbolic import ( tanh, sinh, cosh, coth, sech, csch,
asinh, acosh, atanh, acoth, asech, acsch,
arcsinh, arccosh, arctanh, arccoth, arcsech, arccsch )
reciprocal_trig_functions = {'sec': cos, 'csc': sin, 'cot': tan, 'sech': cosh, 'csch': sinh, 'coth': tanh}
from .other import ( ceil, floor, abs_symbolic, sqrt, real_nth_root,
arg, real_part, real, frac,
factorial, binomial,
imag_part, imag, imaginary, conjugate, cases,
complex_root_of)
from .log import (exp, exp_polar, log, ln, polylog, dilog, lambert_w, harmonic_number)
from .transcendental import (zeta, zetaderiv, zeta_symmetric, hurwitz_zeta,
dickman_rho, stieltjes)
from .bessel import (bessel_I, bessel_J, bessel_K, bessel_Y,
Bessel, struve_H, struve_L, hankel1, hankel2,
spherical_bessel_J, spherical_bessel_Y,
spherical_hankel1, spherical_hankel2)
from .special import (spherical_harmonic, elliptic_e,
elliptic_f, elliptic_ec, elliptic_eu,
elliptic_kc, elliptic_pi, elliptic_j)
from .jacobi import (jacobi, inverse_jacobi, jacobi_nd, jacobi_ns, jacobi_nc,
jacobi_dn, jacobi_ds, jacobi_dc, jacobi_sn, jacobi_sd,
jacobi_sc, jacobi_cn, jacobi_cd, jacobi_cs, jacobi_am,
inverse_jacobi_nd, inverse_jacobi_ns, inverse_jacobi_nc,
inverse_jacobi_dn, inverse_jacobi_ds, inverse_jacobi_dc,
inverse_jacobi_sn, inverse_jacobi_sd, inverse_jacobi_sc,
inverse_jacobi_cn, inverse_jacobi_cd, inverse_jacobi_cs)
from .orthogonal_polys import (chebyshev_T,
chebyshev_U,
gen_laguerre,
gen_legendre_P,
gen_legendre_Q,
hermite,
jacobi_P,
laguerre,
legendre_P,
legendre_Q,
ultraspherical,
gegenbauer,
krawtchouk,
meixner,
hahn)
from .spike_function import spike_function
from .prime_pi import legendre_phi, partial_sieve_function, prime_pi
from .wigner import (wigner_3j, clebsch_gordan, racah, wigner_6j,
wigner_9j, gaunt)
from .generalized import (dirac_delta, heaviside, unit_step, sgn, sign,
kronecker_delta)
from .min_max import max_symbolic, min_symbolic
from .airy import airy_ai, airy_ai_prime, airy_bi, airy_bi_prime
from .exp_integral import (exp_integral_e, exp_integral_e1, log_integral, li, Li,
log_integral_offset,
sin_integral, cos_integral, Si, Ci,
sinh_integral, cosh_integral, Shi, Chi,
exponential_integral_1, Ei, exp_integral_ei)
from .hypergeometric import hypergeometric, hypergeometric_M, hypergeometric_U
from .gamma import (gamma, psi, beta, log_gamma,
gamma_inc, gamma_inc_lower)
Γ = gamma
ψ = psi
ζ = zeta | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/functions/all.py | 0.665954 | 0.183265 | all.py | pypi |
import sys
from sage.rings.integer_ring import ZZ
from sage.rings.real_mpfr import RR
from sage.rings.real_double import RDF
from sage.rings.complex_mpfr import ComplexField, is_ComplexNumber
from sage.rings.cc import CC
from sage.rings.real_mpfr import (RealField, is_RealNumber)
from sage.symbolic.function import GinacFunction, BuiltinFunction
import sage.libs.mpmath.utils as mpmath_utils
from sage.combinat.combinat import bernoulli_polynomial
from .gamma import psi
from .other import factorial
I = CC.gen(0)
class Function_zeta(GinacFunction):
def __init__(self):
r"""
Riemann zeta function at s with s a real or complex number.
INPUT:
- ``s`` - real or complex number
If s is a real number the computation is done using the MPFR
library. When the input is not real, the computation is done using
the PARI C library.
EXAMPLES::
sage: zeta(x)
zeta(x)
sage: zeta(2)
1/6*pi^2
sage: zeta(2.)
1.64493406684823
sage: RR = RealField(200)
sage: zeta(RR(2))
1.6449340668482264364724151666460251892189499012067984377356
sage: zeta(I)
zeta(I)
sage: zeta(I).n()
0.00330022368532410 - 0.418155449141322*I
sage: zeta(sqrt(2))
zeta(sqrt(2))
sage: zeta(sqrt(2)).n() # rel tol 1e-10
3.02073767948603
It is possible to use the ``hold`` argument to prevent
automatic evaluation::
sage: zeta(2,hold=True)
zeta(2)
To then evaluate again, we currently must use Maxima via
:meth:`sage.symbolic.expression.Expression.simplify`::
sage: a = zeta(2,hold=True); a.simplify()
1/6*pi^2
The Laurent expansion of `\zeta(s)` at `s=1` is
implemented by means of the
:wikipedia:`Stieltjes constants <Stieltjes_constants>`::
sage: s = SR('s')
sage: zeta(s).series(s==1, 2)
1*(s - 1)^(-1) + euler_gamma + (-stieltjes(1))*(s - 1) + Order((s - 1)^2)
Generally, the Stieltjes constants occur in the Laurent
expansion of `\zeta`-type singularities::
sage: zeta(2*s/(s+1)).series(s==1, 2)
2*(s - 1)^(-1) + (euler_gamma + 1) + (-1/2*stieltjes(1))*(s - 1) + Order((s - 1)^2)
TESTS::
sage: latex(zeta(x))
\zeta(x)
sage: a = loads(dumps(zeta(x)))
sage: a.operator() == zeta
True
sage: zeta(x)._sympy_()
zeta(x)
sage: zeta(1)
Infinity
sage: zeta(x).subs(x=1)
Infinity
Check that :trac:`19799` is resolved::
sage: zeta(pi)
zeta(pi)
sage: zeta(pi).n() # rel tol 1e-10
1.17624173838258
Check that :trac:`20082` is fixed::
sage: zeta(x).series(x==pi, 2)
(zeta(pi)) + (zetaderiv(1, pi))*(-pi + x) + Order((pi - x)^2)
sage: (zeta(x) * 1/(1 - exp(-x))).residue(x==2*pi*I)
zeta(2*I*pi)
Check that :trac:`20102` is fixed::
sage: (zeta(x)^2).series(x==1, 1)
1*(x - 1)^(-2) + (2*euler_gamma)*(x - 1)^(-1)
+ (euler_gamma^2 - 2*stieltjes(1)) + Order(x - 1)
sage: (zeta(x)^4).residue(x==1)
4/3*euler_gamma*(3*euler_gamma^2 - 2*stieltjes(1))
- 28/3*euler_gamma*stieltjes(1) + 2*stieltjes(2)
Check that the right infinities are returned (:trac:`19439`)::
sage: zeta(1.0)
+infinity
sage: zeta(SR(1.0))
Infinity
Fixed conversion::
sage: zeta(3)._maple_init_()
'Zeta(3)'
sage: zeta(3)._maple_().sage() # optional - maple
zeta(3)
"""
GinacFunction.__init__(self, 'zeta',
conversions={'giac': 'Zeta',
'maple': 'Zeta',
'sympy': 'zeta',
'mathematica': 'Zeta'})
zeta = Function_zeta()
class Function_stieltjes(GinacFunction):
def __init__(self):
r"""
Stieltjes constant of index ``n``.
``stieltjes(0)`` is identical to the Euler-Mascheroni constant
(:class:`sage.symbolic.constants.EulerGamma`). The Stieltjes
constants are used in the series expansions of `\zeta(s)`.
INPUT:
- ``n`` - non-negative integer
EXAMPLES::
sage: _ = var('n')
sage: stieltjes(n)
stieltjes(n)
sage: stieltjes(0)
euler_gamma
sage: stieltjes(2)
stieltjes(2)
sage: stieltjes(int(2))
stieltjes(2)
sage: stieltjes(2).n(100)
-0.0096903631928723184845303860352
sage: RR = RealField(200)
sage: stieltjes(RR(2))
-0.0096903631928723184845303860352125293590658061013407498807014
It is possible to use the ``hold`` argument to prevent
automatic evaluation::
sage: stieltjes(0,hold=True)
stieltjes(0)
sage: latex(stieltjes(n))
\gamma_{n}
sage: a = loads(dumps(stieltjes(n)))
sage: a.operator() == stieltjes
True
sage: stieltjes(x)._sympy_()
stieltjes(x)
sage: stieltjes(x).subs(x==0)
euler_gamma
"""
GinacFunction.__init__(self, "stieltjes", nargs=1,
conversions=dict(mathematica='StieltjesGamma',
sympy='stieltjes'),
latex_name=r'\gamma')
stieltjes = Function_stieltjes()
class Function_HurwitzZeta(BuiltinFunction):
def __init__(self):
r"""
TESTS::
sage: latex(hurwitz_zeta(x, 2))
\zeta\left(x, 2\right)
sage: hurwitz_zeta(x, 2)._sympy_()
zeta(x, 2)
"""
BuiltinFunction.__init__(self, 'hurwitz_zeta', nargs=2,
conversions=dict(mathematica='HurwitzZeta',
sympy='zeta'),
latex_name=r'\zeta')
def _eval_(self, s, x):
r"""
TESTS::
sage: hurwitz_zeta(x, 1)
zeta(x)
sage: hurwitz_zeta(4, 3)
1/90*pi^4 - 17/16
sage: hurwitz_zeta(-4, x)
-1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x
sage: hurwitz_zeta(3, 0.5)
8.41439832211716
sage: hurwitz_zeta(0, x)
-x + 1/2
"""
if x == 1:
return zeta(s)
if s in ZZ and s > 1:
return ((-1) ** s) * psi(s - 1, x) / factorial(s - 1)
elif s in ZZ and s <= 0:
return -bernoulli_polynomial(x, -s + 1) / (-s + 1)
else:
return
def _evalf_(self, s, x, parent=None, algorithm=None):
r"""
TESTS::
sage: hurwitz_zeta(11/10, 1/2).n()
12.1038134956837
sage: hurwitz_zeta(11/10, 1/2).n(100)
12.103813495683755105709077413
sage: hurwitz_zeta(11/10, 1 + 1j).n()
9.85014164287853 - 1.06139499403981*I
"""
from mpmath import zeta
return mpmath_utils.call(zeta, s, x, parent=parent)
def _derivative_(self, s, x, diff_param):
r"""
TESTS::
sage: y = var('y')
sage: diff(hurwitz_zeta(x, y), y)
-x*hurwitz_zeta(x + 1, y)
"""
if diff_param == 1:
return -s * hurwitz_zeta(s + 1, x)
else:
raise NotImplementedError('derivative with respect to first '
'argument')
hurwitz_zeta_func = Function_HurwitzZeta()
def hurwitz_zeta(s, x, **kwargs):
r"""
The Hurwitz zeta function `\zeta(s, x)`, where `s` and `x` are complex.
The Hurwitz zeta function is one of the many zeta functions. It
is defined as
.. MATH::
\zeta(s, x) = \sum_{k=0}^{\infty} (k + x)^{-s}.
When `x = 1`, this coincides with Riemann's zeta function.
The Dirichlet L-functions may be expressed as linear combinations
of Hurwitz zeta functions.
EXAMPLES:
Symbolic evaluations::
sage: hurwitz_zeta(x, 1)
zeta(x)
sage: hurwitz_zeta(4, 3)
1/90*pi^4 - 17/16
sage: hurwitz_zeta(-4, x)
-1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x
sage: hurwitz_zeta(7, -1/2)
127*zeta(7) - 128
sage: hurwitz_zeta(-3, 1)
1/120
Numerical evaluations::
sage: hurwitz_zeta(3, 1/2).n()
8.41439832211716
sage: hurwitz_zeta(11/10, 1/2).n()
12.1038134956837
sage: hurwitz_zeta(3, x).series(x, 60).subs(x=0.5).n()
8.41439832211716
sage: hurwitz_zeta(3, 0.5)
8.41439832211716
REFERENCES:
- :wikipedia:`Hurwitz_zeta_function`
"""
return hurwitz_zeta_func(s, x, **kwargs)
class Function_zetaderiv(GinacFunction):
def __init__(self):
r"""
Derivatives of the Riemann zeta function.
EXAMPLES::
sage: zetaderiv(1, x)
zetaderiv(1, x)
sage: zetaderiv(1, x).diff(x)
zetaderiv(2, x)
sage: var('n')
n
sage: zetaderiv(n,x)
zetaderiv(n, x)
sage: zetaderiv(1, 4).n()
-0.0689112658961254
sage: import mpmath; mpmath.diff(lambda x: mpmath.zeta(x), 4)
mpf('-0.068911265896125382')
TESTS::
sage: latex(zetaderiv(2,x))
\zeta^\prime\left(2, x\right)
sage: a = loads(dumps(zetaderiv(2,x)))
sage: a.operator() == zetaderiv
True
sage: b = RBF(3/2, 1e-10)
sage: zetaderiv(1, b, hold=True)
zetaderiv(1, [1.500000000 +/- 1.01e-10])
sage: zetaderiv(b, 1)
zetaderiv([1.500000000 +/- 1.01e-10], 1)
"""
GinacFunction.__init__(self, "zetaderiv", nargs=2,
conversions=dict(maple="Zeta"))
def _evalf_(self, n, x, parent=None, algorithm=None):
r"""
TESTS::
sage: zetaderiv(0, 3, hold=True).n() == zeta(3).n()
True
sage: zetaderiv(2, 3 + I).n()
0.0213814086193841 - 0.174938812330834*I
"""
from mpmath import zeta
return mpmath_utils.call(zeta, x, 1, n, parent=parent)
def _method_arguments(self, k, x, **args):
r"""
TESTS::
sage: zetaderiv(1, RBF(3/2, 0.0001))
[-3.93 +/- ...e-3]
"""
return [x, k]
zetaderiv = Function_zetaderiv()
def zeta_symmetric(s):
r"""
Completed function `\xi(s)` that satisfies
`\xi(s) = \xi(1-s)` and has zeros at the same points as the
Riemann zeta function.
INPUT:
- ``s`` - real or complex number
If s is a real number the computation is done using the MPFR
library. When the input is not real, the computation is done using
the PARI C library.
More precisely,
.. MATH::
xi(s) = \gamma(s/2 + 1) * (s-1) * \pi^{-s/2} * \zeta(s).
EXAMPLES::
sage: zeta_symmetric(0.7)
0.497580414651127
sage: zeta_symmetric(1-0.7)
0.497580414651127
sage: RR = RealField(200)
sage: zeta_symmetric(RR(0.7))
0.49758041465112690357779107525638385212657443284080589766062
sage: C.<i> = ComplexField()
sage: zeta_symmetric(0.5 + i*14.0)
0.000201294444235258 + 1.49077798716757e-19*I
sage: zeta_symmetric(0.5 + i*14.1)
0.0000489893483255687 + 4.40457132572236e-20*I
sage: zeta_symmetric(0.5 + i*14.2)
-0.0000868931282620101 + 7.11507675693612e-20*I
REFERENCE:
- I copied the definition of xi from
http://web.viu.ca/pughg/RiemannZeta/RiemannZetaLong.html
"""
if not (is_ComplexNumber(s) or is_RealNumber(s)):
s = ComplexField()(s)
R = s.parent()
if s == 1: # deal with poles, hopefully
return R(0.5)
return (s/2 + 1).gamma() * (s-1) * (R.pi()**(-s/2)) * s.zeta()
import math
from sage.rings.polynomial.polynomial_real_mpfr_dense import PolynomialRealDense
class DickmanRho(BuiltinFunction):
r"""
Dickman's function is the continuous function satisfying the
differential equation
.. MATH::
x \rho'(x) + \rho(x-1) = 0
with initial conditions `\rho(x)=1` for
`0 \le x \le 1`. It is useful in estimating the frequency
of smooth numbers as asymptotically
.. MATH::
\Psi(a, a^{1/s}) \sim a \rho(s)
where `\Psi(a,b)` is the number of `b`-smooth
numbers less than `a`.
ALGORITHM:
Dickmans's function is analytic on the interval
`[n,n+1]` for each integer `n`. To evaluate at
`n+t, 0 \le t < 1`, a power series is recursively computed
about `n+1/2` using the differential equation stated above.
As high precision arithmetic may be needed for intermediate results
the computed series are cached for later use.
Simple explicit formulas are used for the intervals [0,1] and
[1,2].
EXAMPLES::
sage: dickman_rho(2)
0.306852819440055
sage: dickman_rho(10)
2.77017183772596e-11
sage: dickman_rho(10.00000000000000000000000000000000000000)
2.77017183772595898875812120063434232634e-11
sage: plot(log(dickman_rho(x)), (x, 0, 15))
Graphics object consisting of 1 graphics primitive
AUTHORS:
- Robert Bradshaw (2008-09)
REFERENCES:
- G. Marsaglia, A. Zaman, J. Marsaglia. "Numerical
Solutions to some Classical Differential-Difference Equations."
Mathematics of Computation, Vol. 53, No. 187 (1989).
"""
def __init__(self):
"""
Constructs an object to represent Dickman's rho function.
TESTS::
sage: dickman_rho(x)
dickman_rho(x)
sage: dickman_rho(3)
0.0486083882911316
sage: dickman_rho(pi)
0.0359690758968463
"""
self._cur_prec = 0
BuiltinFunction.__init__(self, "dickman_rho", 1)
def _eval_(self, x):
"""
EXAMPLES::
sage: [dickman_rho(n) for n in [1..10]]
[1.00000000000000, 0.306852819440055, 0.0486083882911316, 0.00491092564776083, 0.000354724700456040, 0.0000196496963539553, 8.74566995329392e-7, 3.23206930422610e-8, 1.01624828273784e-9, 2.77017183772596e-11]
sage: dickman_rho(0)
1.00000000000000
"""
if not is_RealNumber(x):
try:
x = RR(x)
except (TypeError, ValueError):
return None
if x < 0:
return x.parent()(0)
elif x <= 1:
return x.parent()(1)
elif x <= 2:
return 1 - x.log()
n = x.floor()
if self._cur_prec < x.parent().prec() or n not in self._f:
self._cur_prec = rel_prec = x.parent().prec()
# Go a bit beyond so we're not constantly re-computing.
max = x.parent()(1.1)*x + 10
abs_prec = (-self.approximate(max).log2() + rel_prec + 2*max.log2()).ceil()
self._f = {}
if sys.getrecursionlimit() < max + 10:
sys.setrecursionlimit(int(max) + 10)
self._compute_power_series(max.floor(), abs_prec, cache_ring=x.parent())
return self._f[n](2*(x-n-x.parent()(0.5)))
def power_series(self, n, abs_prec):
"""
This function returns the power series about `n+1/2` used
to evaluate Dickman's function. It is scaled such that the interval
`[n,n+1]` corresponds to x in `[-1,1]`.
INPUT:
- ``n`` - the lower endpoint of the interval for which
this power series holds
- ``abs_prec`` - the absolute precision of the
resulting power series
EXAMPLES::
sage: f = dickman_rho.power_series(2, 20); f
-9.9376e-8*x^11 + 3.7722e-7*x^10 - 1.4684e-6*x^9 + 5.8783e-6*x^8 - 0.000024259*x^7 + 0.00010341*x^6 - 0.00045583*x^5 + 0.0020773*x^4 - 0.0097336*x^3 + 0.045224*x^2 - 0.11891*x + 0.13032
sage: f(-1), f(0), f(1)
(0.30685, 0.13032, 0.048608)
sage: dickman_rho(2), dickman_rho(2.5), dickman_rho(3)
(0.306852819440055, 0.130319561832251, 0.0486083882911316)
"""
return self._compute_power_series(n, abs_prec, cache_ring=None)
def _compute_power_series(self, n, abs_prec, cache_ring=None):
"""
Compute the power series giving Dickman's function on [n, n+1], by
recursion in n. For internal use; self.power_series() is a wrapper
around this intended for the user.
INPUT:
- ``n`` - the lower endpoint of the interval for which
this power series holds
- ``abs_prec`` - the absolute precision of the
resulting power series
- ``cache_ring`` - for internal use, caches the power
series at this precision.
EXAMPLES::
sage: f = dickman_rho.power_series(2, 20); f
-9.9376e-8*x^11 + 3.7722e-7*x^10 - 1.4684e-6*x^9 + 5.8783e-6*x^8 - 0.000024259*x^7 + 0.00010341*x^6 - 0.00045583*x^5 + 0.0020773*x^4 - 0.0097336*x^3 + 0.045224*x^2 - 0.11891*x + 0.13032
"""
if n <= 1:
if n <= -1:
return PolynomialRealDense(RealField(abs_prec)['x'])
if n == 0:
return PolynomialRealDense(RealField(abs_prec)['x'], [1])
elif n == 1:
nterms = (RDF(abs_prec) * RDF(2).log()/RDF(3).log()).ceil()
R = RealField(abs_prec)
neg_three = ZZ(-3)
coeffs = [1 - R(1.5).log()] + [neg_three**-k/k for k in range(1, nterms)]
f = PolynomialRealDense(R['x'], coeffs)
if cache_ring is not None:
self._f[n] = f.truncate_abs(f[0] >> (cache_ring.prec()+1)).change_ring(cache_ring)
return f
else:
f = self._compute_power_series(n-1, abs_prec, cache_ring)
# integrand = f / (2n+1 + x)
# We calculate this way because the most significant term is the constant term,
# and so we want to push the error accumulation and remainder out to the least
# significant terms.
integrand = f.reverse().quo_rem(PolynomialRealDense(f.parent(), [1, 2*n+1]))[0].reverse()
integrand = integrand.truncate_abs(RR(2)**-abs_prec)
iintegrand = integrand.integral()
ff = PolynomialRealDense(f.parent(), [f(1) + iintegrand(-1)]) - iintegrand
i = 0
while abs(f[i]) < abs(f[i+1]):
i += 1
rel_prec = int(abs_prec + abs(RR(f[i])).log2())
if cache_ring is not None:
self._f[n] = ff.truncate_abs(ff[0] >> (cache_ring.prec()+1)).change_ring(cache_ring)
return ff.change_ring(RealField(rel_prec))
def approximate(self, x, parent=None):
r"""
Approximate using de Bruijn's formula
.. MATH::
\rho(x) \sim \frac{exp(-x \xi + Ei(\xi))}{\sqrt{2\pi x}\xi}
which is asymptotically equal to Dickman's function, and is much
faster to compute.
REFERENCES:
- N. De Bruijn, "The Asymptotic behavior of a function
occurring in the theory of primes." J. Indian Math Soc. v 15.
(1951)
EXAMPLES::
sage: dickman_rho.approximate(10)
2.41739196365564e-11
sage: dickman_rho(10)
2.77017183772596e-11
sage: dickman_rho.approximate(1000)
4.32938809066403e-3464
"""
log, exp, sqrt, pi = math.log, math.exp, math.sqrt, math.pi
x = float(x)
xi = log(x)
y = (exp(xi)-1.0)/xi - x
while abs(y) > 1e-12:
dydxi = (exp(xi)*(xi-1.0) + 1.0)/(xi*xi)
xi -= y/dydxi
y = (exp(xi)-1.0)/xi - x
return (-x*xi + RR(xi).eint()).exp() / (sqrt(2*pi*x)*xi)
dickman_rho = DickmanRho() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/functions/transcendental.py | 0.610686 | 0.476092 | transcendental.py | pypi |
from sage.symbolic.function import GinacFunction, BuiltinFunction
from sage.symbolic.constants import e as const_e
from sage.symbolic.constants import pi as const_pi
from sage.libs.mpmath import utils as mpmath_utils
from sage.structure.all import parent as s_parent
from sage.symbolic.expression import Expression, register_symbol
from sage.rings.real_double import RDF
from sage.rings.complex_double import CDF
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.misc.functional import log as log
class Function_exp(GinacFunction):
r"""
The exponential function, `\exp(x) = e^x`.
EXAMPLES::
sage: exp(-1)
e^(-1)
sage: exp(2)
e^2
sage: exp(2).n(100)
7.3890560989306502272304274606
sage: exp(x^2 + log(x))
e^(x^2 + log(x))
sage: exp(x^2 + log(x)).simplify()
x*e^(x^2)
sage: exp(2.5)
12.1824939607035
sage: exp(float(2.5))
12.182493960703473
sage: exp(RDF('2.5'))
12.182493960703473
sage: exp(I*pi/12)
(1/4*I + 1/4)*sqrt(6) - (1/4*I - 1/4)*sqrt(2)
To prevent automatic evaluation, use the ``hold`` parameter::
sage: exp(I*pi,hold=True)
e^(I*pi)
sage: exp(0,hold=True)
e^0
To then evaluate again, we currently must use Maxima via
:meth:`sage.symbolic.expression.Expression.simplify`::
sage: exp(0,hold=True).simplify()
1
::
sage: exp(pi*I/2)
I
sage: exp(pi*I)
-1
sage: exp(8*pi*I)
1
sage: exp(7*pi*I/2)
-I
For the sake of simplification, the argument is reduced modulo the
period of the complex exponential function, `2\pi i`::
sage: k = var('k', domain='integer')
sage: exp(2*k*pi*I)
1
sage: exp(log(2) + 2*k*pi*I)
2
The precision for the result is deduced from the precision of
the input. Convert the input to a higher precision explicitly
if a result with higher precision is desired::
sage: t = exp(RealField(100)(2)); t
7.3890560989306502272304274606
sage: t.prec()
100
sage: exp(2).n(100)
7.3890560989306502272304274606
TESTS::
sage: latex(exp(x))
e^{x}
sage: latex(exp(sqrt(x)))
e^{\sqrt{x}}
sage: latex(exp)
\exp
sage: latex(exp(sqrt(x))^x)
\left(e^{\sqrt{x}}\right)^{x}
sage: latex(exp(sqrt(x)^x))
e^{\left(\sqrt{x}^{x}\right)}
sage: exp(x)._sympy_()
exp(x)
Test conjugates::
sage: conjugate(exp(x))
e^conjugate(x)
Test simplifications when taking powers of exp (:trac:`7264`)::
sage: var('a,b,c,II')
(a, b, c, II)
sage: model_exp = exp(II)**a*(b)
sage: sol1_l={b: 5.0, a: 1.1}
sage: model_exp.subs(sol1_l)
5.00000000000000*e^(1.10000000000000*II)
::
sage: exp(3)^II*exp(x)
e^(3*II + x)
sage: exp(x)*exp(x)
e^(2*x)
sage: exp(x)*exp(a)
e^(a + x)
sage: exp(x)*exp(a)^2
e^(2*a + x)
Another instance of the same problem (:trac:`7394`)::
sage: 2*sqrt(e)
2*e^(1/2)
Check that :trac:`19918` is fixed::
sage: exp(-x^2).subs(x=oo)
0
sage: exp(-x).subs(x=-oo)
+Infinity
"""
def __init__(self):
"""
TESTS::
sage: loads(dumps(exp))
exp
sage: maxima(exp(x))._sage_()
e^x
"""
GinacFunction.__init__(self, "exp", latex_name=r"\exp",
conversions=dict(maxima='exp', fricas='exp'))
exp = Function_exp()
class Function_log1(GinacFunction):
r"""
The natural logarithm of ``x``.
See :meth:`log()` for extensive documentation.
EXAMPLES::
sage: ln(e^2)
2
sage: ln(2)
log(2)
sage: ln(10)
log(10)
TESTS::
sage: latex(x.log())
\log\left(x\right)
sage: latex(log(1/4))
\log\left(\frac{1}{4}\right)
sage: log(x)._sympy_()
log(x)
sage: loads(dumps(ln(x)+1))
log(x) + 1
``conjugate(log(x))==log(conjugate(x))`` unless on the branch cut which
runs along the negative real axis.::
sage: conjugate(log(x))
conjugate(log(x))
sage: var('y', domain='positive')
y
sage: conjugate(log(y))
log(y)
sage: conjugate(log(y+I))
conjugate(log(y + I))
sage: conjugate(log(-1))
-I*pi
sage: log(conjugate(-1))
I*pi
Check if float arguments are handled properly.::
sage: from sage.functions.log import function_log as log
sage: log(float(5))
1.6094379124341003
sage: log(float(0))
-inf
sage: log(float(-1))
3.141592653589793j
sage: log(x).subs(x=float(-1))
3.141592653589793j
:trac:`22142`::
sage: log(QQbar(sqrt(2)))
log(1.414213562373095?)
sage: log(QQbar(sqrt(2))*1.)
0.346573590279973
sage: polylog(QQbar(sqrt(2)),3)
polylog(1.414213562373095?, 3)
"""
def __init__(self):
"""
TESTS::
sage: loads(dumps(ln))
log
sage: maxima(ln(x))._sage_()
log(x)
"""
GinacFunction.__init__(self, 'log', latex_name=r'\log',
conversions=dict(maxima='log', fricas='log',
mathematica='Log', giac='ln'))
ln = function_log = Function_log1()
class Function_log2(GinacFunction):
"""
Return the logarithm of x to the given base.
See :meth:`log() <sage.functions.log.log>` for extensive documentation.
EXAMPLES::
sage: from sage.functions.log import logb
sage: logb(1000,10)
3
TESTS::
sage: logb(7, 2)
log(7)/log(2)
sage: logb(int(7), 2)
log(7)/log(2)
"""
def __init__(self):
"""
TESTS::
sage: from sage.functions.log import logb
sage: loads(dumps(logb))
log
"""
GinacFunction.__init__(self, 'log', ginac_name='logb', nargs=2,
latex_name=r'\log',
conversions=dict(maxima='log'))
logb = Function_log2()
class Function_polylog(GinacFunction):
def __init__(self):
r"""
The polylog function
`\text{Li}_s(z) = \sum_{k=1}^{\infty} z^k / k^s`.
The first argument is `s` (usually an integer called the weight)
and the second argument is `z` : ``polylog(s, z)``.
This definition is valid for arbitrary complex numbers `s` and `z`
with `|z| < 1`. It can be extended to `|z| \ge 1` by the process of
analytic continuation, with a branch cut along the positive real axis
from `1` to `+\infty`. A `NaN` value may be returned for floating
point arguments that are on the branch cut.
EXAMPLES::
sage: polylog(2.7, 0)
0.000000000000000
sage: polylog(2, 1)
1/6*pi^2
sage: polylog(2, -1)
-1/12*pi^2
sage: polylog(3, -1)
-3/4*zeta(3)
sage: polylog(2, I)
I*catalan - 1/48*pi^2
sage: polylog(4, 1/2)
polylog(4, 1/2)
sage: polylog(4, 0.5)
0.517479061673899
sage: polylog(1, x)
-log(-x + 1)
sage: polylog(2,x^2+1)
dilog(x^2 + 1)
sage: f = polylog(4, 1); f
1/90*pi^4
sage: f.n()
1.08232323371114
sage: polylog(4, 2).n()
2.42786280675470 - 0.174371300025453*I
sage: complex(polylog(4,2))
(2.4278628067547032-0.17437130002545306j)
sage: float(polylog(4,0.5))
0.5174790616738993
sage: z = var('z')
sage: polylog(2,z).series(z==0, 5)
1*z + 1/4*z^2 + 1/9*z^3 + 1/16*z^4 + Order(z^5)
sage: loads(dumps(polylog))
polylog
sage: latex(polylog(5, x))
{\rm Li}_{5}(x)
sage: polylog(x, x)._sympy_()
polylog(x, x)
TESTS:
Check if :trac:`8459` is fixed::
sage: t = maxima(polylog(5,x)).sage(); t
polylog(5, x)
sage: t.operator() == polylog
True
sage: t.subs(x=.5).n()
0.50840057924226...
Check if :trac:`18386` is fixed::
sage: polylog(2.0, 1)
1.64493406684823
sage: polylog(2, 1.0)
1.64493406684823
sage: polylog(2.0, 1.0)
1.64493406684823
sage: polylog(2, RealBallField(100)(1/3))
[0.36621322997706348761674629766... +/- ...]
sage: polylog(2, ComplexBallField(100)(4/3))
[2.27001825336107090380391448586 +/- ...] + [-0.90377988538400159956755721265 +/- ...]*I
sage: polylog(2, CBF(1/3))
[0.366213229977063 +/- ...]
sage: parent(_)
Complex ball field with 53 bits of precision
sage: polylog(2, CBF(1))
[1.644934066848226 +/- ...]
sage: parent(_)
Complex ball field with 53 bits of precision
sage: polylog(1,-1) # known bug
-log(2)
Check for :trac:`21907`::
sage: bool(x*polylog(x,x)==0)
False
"""
GinacFunction.__init__(self, "polylog", nargs=2,
conversions=dict(mathematica='PolyLog',
magma='Polylog',
matlab='polylog',
sympy='polylog'))
def _maxima_init_evaled_(self, *args):
"""
EXAMPLES:
These are indirect doctests for this function::
sage: polylog(2, x)._maxima_()
li[2](_SAGE_VAR_x)
sage: polylog(4, x)._maxima_()
polylog(4,_SAGE_VAR_x)
"""
args_maxima = []
for a in args:
if isinstance(a, str):
args_maxima.append(a)
elif hasattr(a, '_maxima_init_'):
args_maxima.append(a._maxima_init_())
else:
args_maxima.append(str(a))
n, x = args_maxima
if int(n) in [1, 2, 3]:
return 'li[%s](%s)' % (n, x)
else:
return 'polylog(%s, %s)' % (n, x)
def _method_arguments(self, k, z):
r"""
TESTS::
sage: b = RBF(1/2, .0001)
sage: polylog(2, b)
[0.582 +/- ...]
"""
return [z, k]
polylog = Function_polylog()
class Function_dilog(GinacFunction):
def __init__(self):
r"""
The dilogarithm function
`\text{Li}_2(z) = \sum_{k=1}^{\infty} z^k / k^2`.
This is simply an alias for polylog(2, z).
EXAMPLES::
sage: dilog(1)
1/6*pi^2
sage: dilog(1/2)
1/12*pi^2 - 1/2*log(2)^2
sage: dilog(x^2+1)
dilog(x^2 + 1)
sage: dilog(-1)
-1/12*pi^2
sage: dilog(-1.0)
-0.822467033424113
sage: dilog(-1.1)
-0.890838090262283
sage: dilog(1/2)
1/12*pi^2 - 1/2*log(2)^2
sage: dilog(.5)
0.582240526465012
sage: dilog(1/2).n()
0.582240526465012
sage: var('z')
z
sage: dilog(z).diff(z, 2)
log(-z + 1)/z^2 - 1/((z - 1)*z)
sage: dilog(z).series(z==1/2, 3)
(1/12*pi^2 - 1/2*log(2)^2) + (-2*log(1/2))*(z - 1/2) + (2*log(1/2) + 2)*(z - 1/2)^2 + Order(1/8*(2*z - 1)^3)
sage: latex(dilog(z))
{\rm Li}_2\left(z\right)
Dilog has a branch point at `1`. Sage's floating point libraries
may handle this differently from the symbolic package::
sage: dilog(1)
1/6*pi^2
sage: dilog(1.)
1.64493406684823
sage: dilog(1).n()
1.64493406684823
sage: float(dilog(1))
1.6449340668482262
TESTS:
``conjugate(dilog(x))==dilog(conjugate(x))`` unless on the branch cuts
which run along the positive real axis beginning at 1.::
sage: conjugate(dilog(x))
conjugate(dilog(x))
sage: var('y',domain='positive')
y
sage: conjugate(dilog(y))
conjugate(dilog(y))
sage: conjugate(dilog(1/19))
dilog(1/19)
sage: conjugate(dilog(1/2*I))
dilog(-1/2*I)
sage: dilog(conjugate(1/2*I))
dilog(-1/2*I)
sage: conjugate(dilog(2))
conjugate(dilog(2))
Check that return type matches argument type where possible
(:trac:`18386`)::
sage: dilog(0.5)
0.582240526465012
sage: dilog(-1.0)
-0.822467033424113
sage: y = dilog(RealField(13)(0.5))
sage: parent(y)
Real Field with 13 bits of precision
sage: dilog(RealField(13)(1.1))
1.96 - 0.300*I
sage: parent(_)
Complex Field with 13 bits of precision
"""
GinacFunction.__init__(self, 'dilog',
conversions=dict(maxima='li[2]',
magma='Dilog',
fricas='(x+->dilog(1-x))'))
def _sympy_(self, z):
r"""
Special case for sympy, where there is no dilog function.
EXAMPLES::
sage: w = dilog(x)._sympy_(); w
polylog(2, x)
sage: w.diff()
polylog(1, x)/x
sage: w._sage_()
dilog(x)
"""
import sympy
from sympy import polylog as sympy_polylog
return sympy_polylog(2, sympy.sympify(z, evaluate=False))
dilog = Function_dilog()
class Function_lambert_w(BuiltinFunction):
r"""
The integral branches of the Lambert W function `W_n(z)`.
This function satisfies the equation
.. MATH::
z = W_n(z) e^{W_n(z)}
INPUT:
- ``n`` -- an integer. `n=0` corresponds to the principal branch.
- ``z`` -- a complex number
If called with a single argument, that argument is ``z`` and the branch ``n`` is
assumed to be 0 (the principal branch).
ALGORITHM:
Numerical evaluation is handled using the mpmath and SciPy libraries.
REFERENCES:
- :wikipedia:`Lambert_W_function`
EXAMPLES:
Evaluation of the principal branch::
sage: lambert_w(1.0)
0.567143290409784
sage: lambert_w(-1).n()
-0.318131505204764 + 1.33723570143069*I
sage: lambert_w(-1.5 + 5*I)
1.17418016254171 + 1.10651494102011*I
Evaluation of other branches::
sage: lambert_w(2, 1.0)
-2.40158510486800 + 10.7762995161151*I
Solutions to certain exponential equations are returned in terms of lambert_w::
sage: S = solve(e^(5*x)+x==0, x, to_poly_solve=True)
sage: z = S[0].rhs(); z
-1/5*lambert_w(5)
sage: N(z)
-0.265344933048440
Check the defining equation numerically at `z=5`::
sage: N(lambert_w(5)*exp(lambert_w(5)) - 5)
0.000000000000000
There are several special values of the principal branch which
are automatically simplified::
sage: lambert_w(0)
0
sage: lambert_w(e)
1
sage: lambert_w(-1/e)
-1
Integration (of the principal branch) is evaluated using Maxima::
sage: integrate(lambert_w(x), x)
(lambert_w(x)^2 - lambert_w(x) + 1)*x/lambert_w(x)
sage: integrate(lambert_w(x), x, 0, 1)
(lambert_w(1)^2 - lambert_w(1) + 1)/lambert_w(1) - 1
sage: integrate(lambert_w(x), x, 0, 1.0)
0.3303661247616807
Warning: The integral of a non-principal branch is not implemented,
neither is numerical integration using GSL. The :meth:`numerical_integral`
function does work if you pass a lambda function::
sage: numerical_integral(lambda x: lambert_w(x), 0, 1)
(0.33036612476168054, 3.667800782666048e-15)
"""
def __init__(self):
r"""
See the docstring for :meth:`Function_lambert_w`.
EXAMPLES::
sage: lambert_w(0, 1.0)
0.567143290409784
sage: lambert_w(x, x)._sympy_()
LambertW(x, x)
TESTS:
Check that :trac:`25987` is fixed::
sage: lambert_w(x)._fricas_() # optional - fricas
lambertW(x)
sage: fricas(lambert_w(x)).eval(x = -1/e) # optional - fricas
- 1
The two-argument form of Lambert's function is not supported
by FriCAS, so we return a generic operator::
sage: var("n")
n
sage: lambert_w(n, x)._fricas_() # optional - fricas
generalizedLambertW(n,x)
"""
BuiltinFunction.__init__(self, "lambert_w", nargs=2,
conversions={'mathematica': 'ProductLog',
'maple': 'LambertW',
'matlab': 'lambertw',
'maxima': 'generalized_lambert_w',
'fricas': "((n,z)+->(if n=0 then lambertW(z) else operator('generalizedLambertW)(n,z)))",
'sympy': 'LambertW'})
def __call__(self, *args, **kwds):
r"""
Custom call method allows the user to pass one argument or two. If
one argument is passed, we assume it is ``z`` and that ``n=0``.
EXAMPLES::
sage: lambert_w(1)
lambert_w(1)
sage: lambert_w(1, 2)
lambert_w(1, 2)
"""
if len(args) == 2:
return BuiltinFunction.__call__(self, *args, **kwds)
elif len(args) == 1:
return BuiltinFunction.__call__(self, 0, args[0], **kwds)
else:
raise TypeError("lambert_w takes either one or two arguments.")
def _method_arguments(self, n, z):
r"""
TESTS::
sage: b = RBF(1, 0.001)
sage: lambert_w(b)
[0.567 +/- 6.44e-4]
sage: lambert_w(CBF(b))
[0.567 +/- 6.44e-4]
sage: lambert_w(2r, CBF(b))
[-2.40 +/- 2.79e-3] + [10.78 +/- 4.91e-3]*I
sage: lambert_w(2, CBF(b))
[-2.40 +/- 2.79e-3] + [10.78 +/- 4.91e-3]*I
"""
if n == 0:
return [z]
else:
return [z, n]
def _eval_(self, n, z):
"""
EXAMPLES::
sage: lambert_w(6.0)
1.43240477589830
sage: lambert_w(1)
lambert_w(1)
sage: lambert_w(x+1)
lambert_w(x + 1)
There are three special values which are automatically simplified::
sage: lambert_w(0)
0
sage: lambert_w(e)
1
sage: lambert_w(-1/e)
-1
sage: lambert_w(SR(0))
0
The special values only hold on the principal branch::
sage: lambert_w(1,e)
lambert_w(1, e)
sage: lambert_w(1, e.n())
-0.532092121986380 + 4.59715801330257*I
TESTS:
When automatic simplification occurs, the parent of the output
value should be either the same as the parent of the input, or
a Sage type::
sage: parent(lambert_w(int(0)))
<... 'int'>
sage: parent(lambert_w(Integer(0)))
Integer Ring
sage: parent(lambert_w(e))
Symbolic Ring
"""
if not isinstance(z, Expression):
if n == 0 and z == 0:
return s_parent(z)(0)
elif n == 0:
if z.is_trivial_zero():
return s_parent(z)(Integer(0))
elif (z - const_e).is_trivial_zero():
return s_parent(z)(Integer(1))
elif (z + 1 / const_e).is_trivial_zero():
return s_parent(z)(Integer(-1))
def _evalf_(self, n, z, parent=None, algorithm=None):
"""
EXAMPLES::
sage: N(lambert_w(1))
0.567143290409784
sage: lambert_w(RealField(100)(1))
0.56714329040978387299996866221
SciPy is used to evaluate for float, RDF, and CDF inputs::
sage: lambert_w(RDF(1))
0.5671432904097838
sage: lambert_w(float(1))
0.5671432904097838
sage: lambert_w(CDF(1))
0.5671432904097838
sage: lambert_w(complex(1))
(0.5671432904097838+0j)
sage: lambert_w(RDF(-1)) # abs tol 2e-16
-0.31813150520476413 + 1.3372357014306895*I
sage: lambert_w(float(-1)) # abs tol 2e-16
(-0.31813150520476413+1.3372357014306895j)
"""
R = parent or s_parent(z)
if R is float or R is RDF:
from scipy.special import lambertw
res = lambertw(z, n)
# SciPy always returns a complex value, make it real if possible
if not res.imag:
return R(res.real)
elif R is float:
return complex(res)
else:
return CDF(res)
elif R is complex or R is CDF:
from scipy.special import lambertw
return R(lambertw(z, n))
else:
import mpmath
return mpmath_utils.call(mpmath.lambertw, z, n, parent=R)
def _derivative_(self, n, z, diff_param=None):
r"""
The derivative of `W_n(x)` is `W_n(x)/(x \cdot W_n(x) + x)`.
EXAMPLES::
sage: x = var('x')
sage: derivative(lambert_w(x), x)
lambert_w(x)/(x*lambert_w(x) + x)
sage: derivative(lambert_w(2, exp(x)), x)
e^x*lambert_w(2, e^x)/(e^x*lambert_w(2, e^x) + e^x)
TESTS:
Differentiation in the first parameter raises an error :trac:`14788`::
sage: n = var('n')
sage: lambert_w(n, x).diff(n)
Traceback (most recent call last):
...
ValueError: cannot differentiate lambert_w in the first parameter
"""
if diff_param == 0:
raise ValueError("cannot differentiate lambert_w in the first parameter")
return lambert_w(n, z) / (z * lambert_w(n, z) + z)
def _maxima_init_evaled_(self, n, z):
"""
EXAMPLES:
These are indirect doctests for this function.::
sage: lambert_w(0, x)._maxima_()
lambert_w(_SAGE_VAR_x)
sage: lambert_w(1, x)._maxima_()
generalized_lambert_w(1,_SAGE_VAR_x)
TESTS::
sage: lambert_w(x)._maxima_()._sage_()
lambert_w(x)
sage: lambert_w(2, x)._maxima_()._sage_()
lambert_w(2, x)
"""
if isinstance(z, str):
maxima_z = z
elif hasattr(z, '_maxima_init_'):
maxima_z = z._maxima_init_()
else:
maxima_z = str(z)
if n == 0:
return "lambert_w(%s)" % maxima_z
else:
return "generalized_lambert_w(%s,%s)" % (n, maxima_z)
def _print_(self, n, z):
"""
Custom _print_ method to avoid printing the branch number if
it is zero.
EXAMPLES::
sage: lambert_w(1)
lambert_w(1)
sage: lambert_w(0,x)
lambert_w(x)
"""
if n == 0:
return "lambert_w(%s)" % z
else:
return "lambert_w(%s, %s)" % (n, z)
def _print_latex_(self, n, z):
r"""
Custom _print_latex_ method to avoid printing the branch
number if it is zero.
EXAMPLES::
sage: latex(lambert_w(1))
\operatorname{W}({1})
sage: latex(lambert_w(0,x))
\operatorname{W}({x})
sage: latex(lambert_w(1,x))
\operatorname{W_{1}}({x})
sage: latex(lambert_w(1,x+exp(x)))
\operatorname{W_{1}}({x + e^{x}})
"""
if n == 0:
return r"\operatorname{W}({%s})" % z._latex_()
else:
return r"\operatorname{W_{%s}}({%s})" % (n, z._latex_())
lambert_w = Function_lambert_w()
class Function_exp_polar(BuiltinFunction):
def __init__(self):
r"""
Representation of a complex number in a polar form.
INPUT:
- ``z`` -- a complex number `z = a + ib`.
OUTPUT:
A complex number with modulus `\exp(a)` and argument `b`.
If `-\pi < b \leq \pi` then `\operatorname{exp\_polar}(z)=\exp(z)`.
For other values of `b` the function is left unevaluated.
EXAMPLES:
The following expressions are evaluated using the exponential
function::
sage: exp_polar(pi*I/2)
I
sage: x = var('x', domain='real')
sage: exp_polar(-1/2*I*pi + x)
e^(-1/2*I*pi + x)
The function is left unevaluated when the imaginary part of the
input `z` does not satisfy `-\pi < \Im(z) \leq \pi`::
sage: exp_polar(2*pi*I)
exp_polar(2*I*pi)
sage: exp_polar(-4*pi*I)
exp_polar(-4*I*pi)
This fixes :trac:`18085`::
sage: integrate(1/sqrt(1+x^3),x,algorithm='sympy')
1/3*x*gamma(1/3)*hypergeometric((1/3, 1/2), (4/3,), -x^3)/gamma(4/3)
.. SEEALSO::
`Examples in Sympy documentation <http://docs.sympy.org/latest/modules/functions/special.html?highlight=exp_polar>`_,
`Sympy source code of exp_polar <http://docs.sympy.org/0.7.4/_modules/sympy/functions/elementary/exponential.html>`_
REFERENCES:
:wikipedia:`Complex_number#Polar_form`
"""
BuiltinFunction.__init__(self, "exp_polar",
latex_name=r"\operatorname{exp\_polar}",
conversions=dict(sympy='exp_polar'))
def _evalf_(self, z, parent=None, algorithm=None):
r"""
EXAMPLES:
If the imaginary part of `z` obeys `-\pi < z \leq \pi`, then
`\operatorname{exp\_polar}(z)` is evaluated as `\exp(z)`::
sage: exp_polar(1.0 + 2.0*I)
-1.13120438375681 + 2.47172667200482*I
If the imaginary part of `z` is outside of that interval the
expression is left unevaluated::
sage: exp_polar(-5.0 + 8.0*I)
exp_polar(-5.00000000000000 + 8.00000000000000*I)
An attempt to numerically evaluate such an expression raises an error::
sage: exp_polar(-5.0 + 8.0*I).n()
Traceback (most recent call last):
...
ValueError: invalid attempt to numerically evaluate exp_polar()
"""
from sage.functions.other import imag
if (not isinstance(z, Expression) and
bool(-const_pi < imag(z) <= const_pi)):
return exp(z)
else:
raise ValueError("invalid attempt to numerically evaluate exp_polar()")
def _eval_(self, z):
"""
EXAMPLES::
sage: exp_polar(3*I*pi)
exp_polar(3*I*pi)
sage: x = var('x', domain='real')
sage: exp_polar(4*I*pi + x)
exp_polar(4*I*pi + x)
TESTS:
Check that :trac:`24441` is fixed::
sage: exp_polar(arcsec(jacobi_sn(1.1*I*x, x))) # should be fast
exp_polar(arcsec(jacobi_sn(1.10000000000000*I*x, x)))
"""
try:
im = z.imag_part()
if not im.variables() and (-const_pi < im <= const_pi):
return exp(z)
except AttributeError:
pass
exp_polar = Function_exp_polar()
class Function_harmonic_number_generalized(BuiltinFunction):
r"""
Harmonic and generalized harmonic number functions,
defined by:
.. MATH::
H_{n}=H_{n,1}=\sum_{k=1}^n\frac{1}{k}
H_{n,m}=\sum_{k=1}^n\frac{1}{k^m}
They are also well-defined for complex argument, through:
.. MATH::
H_{s}=\int_0^1\frac{1-x^s}{1-x}
H_{s,m}=\zeta(m)-\zeta(m,s-1)
If called with a single argument, that argument is ``s`` and ``m`` is
assumed to be 1 (the normal harmonic numbers ``H_s``).
ALGORITHM:
Numerical evaluation is handled using the mpmath and FLINT libraries.
REFERENCES:
- :wikipedia:`Harmonic_number`
EXAMPLES:
Evaluation of integer, rational, or complex argument::
sage: harmonic_number(5)
137/60
sage: harmonic_number(3,3)
251/216
sage: harmonic_number(5/2)
-2*log(2) + 46/15
sage: harmonic_number(3.,3)
zeta(3) - 0.0400198661225573
sage: harmonic_number(3.,3.)
1.16203703703704
sage: harmonic_number(3,3).n(200)
1.16203703703703703703703...
sage: harmonic_number(1+I,5)
harmonic_number(I + 1, 5)
sage: harmonic_number(5,1.+I)
1.57436810798989 - 1.06194728851357*I
Solutions to certain sums are returned in terms of harmonic numbers::
sage: k=var('k')
sage: sum(1/k^7,k,1,x)
harmonic_number(x, 7)
Check the defining integral at a random integer::
sage: n=randint(10,100)
sage: bool(SR(integrate((1-x^n)/(1-x),x,0,1)) == harmonic_number(n))
True
There are several special values which are automatically simplified::
sage: harmonic_number(0)
0
sage: harmonic_number(1)
1
sage: harmonic_number(x,1)
harmonic_number(x)
"""
def __init__(self):
r"""
EXAMPLES::
sage: loads(dumps(harmonic_number(x,5)))
harmonic_number(x, 5)
sage: harmonic_number(x, x)._sympy_()
harmonic(x, x)
"""
BuiltinFunction.__init__(self, "harmonic_number", nargs=2,
conversions={'sympy': 'harmonic'})
def __call__(self, z, m=1, **kwds):
r"""
Custom call method allows the user to pass one argument or two. If
one argument is passed, we assume it is ``z`` and that ``m=1``.
EXAMPLES::
sage: harmonic_number(x)
harmonic_number(x)
sage: harmonic_number(x,1)
harmonic_number(x)
sage: harmonic_number(x,2)
harmonic_number(x, 2)
"""
return BuiltinFunction.__call__(self, z, m, **kwds)
def _eval_(self, z, m):
"""
EXAMPLES::
sage: harmonic_number(x,0)
x
sage: harmonic_number(x,1)
harmonic_number(x)
sage: harmonic_number(5)
137/60
sage: harmonic_number(3,3)
251/216
sage: harmonic_number(3,3).n() # this goes from rational to float
1.16203703703704
sage: harmonic_number(3,3.) # the following uses zeta functions
1.16203703703704
sage: harmonic_number(3.,3)
zeta(3) - 0.0400198661225573
sage: harmonic_number(0.1,5)
zeta(5) - 0.650300133161038
sage: harmonic_number(0.1,5).n()
0.386627621982332
sage: harmonic_number(3,5/2)
1/27*sqrt(3) + 1/8*sqrt(2) + 1
TESTS::
sage: harmonic_number(int(3), int(3))
1.162037037037037
"""
if m == 0:
return z
elif m == 1:
return harmonic_m1._eval_(z)
if z in ZZ and z >= 0:
return sum(ZZ(k) ** (-m) for k in range(1, z + 1))
def _evalf_(self, z, m, parent=None, algorithm=None):
"""
EXAMPLES::
sage: harmonic_number(3.,3)
zeta(3) - 0.0400198661225573
sage: harmonic_number(3.,3.)
1.16203703703704
sage: harmonic_number(3,3).n(200)
1.16203703703703703703703...
sage: harmonic_number(5,I).n()
2.36889632899995 - 3.51181956521611*I
"""
if m == 0:
if parent is None:
return z
return parent(z)
elif m == 1:
return harmonic_m1._evalf_(z, parent, algorithm)
from sage.functions.transcendental import zeta, hurwitz_zeta
return zeta(m) - hurwitz_zeta(m, z + 1)
def _maxima_init_evaled_(self, n, z):
"""
EXAMPLES::
sage: maxima_calculus(harmonic_number(x,2))
gen_harmonic_number(2,_SAGE_VAR_x)
sage: maxima_calculus(harmonic_number(3,harmonic_number(x,3),hold=True))
1/3^gen_harmonic_number(3,_SAGE_VAR_x)+1/2^gen_harmonic_number(3,_SAGE_VAR_x)+1
"""
if isinstance(n, str):
maxima_n = n
elif hasattr(n, '_maxima_init_'):
maxima_n = n._maxima_init_()
else:
maxima_n = str(n)
if isinstance(z, str):
maxima_z = z
elif hasattr(z, '_maxima_init_'):
maxima_z = z._maxima_init_()
else:
maxima_z = str(z)
return "gen_harmonic_number(%s,%s)" % (maxima_z, maxima_n) # swap arguments
def _derivative_(self, n, m, diff_param=None):
"""
The derivative of `H_{n,m}`.
EXAMPLES::
sage: k,m,n = var('k,m,n')
sage: sum(1/k, k, 1, x).diff(x)
1/6*pi^2 - harmonic_number(x, 2)
sage: harmonic_number(x, 1).diff(x)
1/6*pi^2 - harmonic_number(x, 2)
sage: harmonic_number(n, m).diff(n)
-m*(harmonic_number(n, m + 1) - zeta(m + 1))
sage: harmonic_number(n, m).diff(m)
Traceback (most recent call last):
...
ValueError: cannot differentiate harmonic_number in the second parameter
"""
from sage.functions.transcendental import zeta
if diff_param == 1:
raise ValueError("cannot differentiate harmonic_number in the second parameter")
if m == 1:
return harmonic_m1(n).diff()
else:
return m * (zeta(m + 1) - harmonic_number(n, m + 1))
def _print_(self, z, m):
"""
EXAMPLES::
sage: harmonic_number(x)
harmonic_number(x)
sage: harmonic_number(x,2)
harmonic_number(x, 2)
"""
if m == 1:
return "harmonic_number(%s)" % z
else:
return "harmonic_number(%s, %s)" % (z, m)
def _print_latex_(self, z, m):
"""
EXAMPLES::
sage: latex(harmonic_number(x))
H_{x}
sage: latex(harmonic_number(x,2))
H_{{x},{2}}
"""
if m == 1:
return r"H_{%s}" % z
else:
return r"H_{{%s},{%s}}" % (z, m)
harmonic_number = Function_harmonic_number_generalized()
class _Function_swap_harmonic(BuiltinFunction):
r"""
Harmonic number function with swapped arguments. For internal use only.
EXAMPLES::
sage: maxima(harmonic_number(x,2)) # maxima expect interface
gen_harmonic_number(2,_SAGE_VAR_x)
sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms
sage: sefms('gen_harmonic_number(3,x)')
harmonic_number(x, 3)
sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_sr
sage: c=maxima_lib(harmonic_number(x,2)); c
gen_harmonic_number(2,_SAGE_VAR_x)
sage: max_to_sr(c.ecl())
harmonic_number(x, 2)
"""
def __init__(self):
BuiltinFunction.__init__(self, "_swap_harmonic", nargs=2)
def _eval_(self, a, b, **kwds):
return harmonic_number(b, a, **kwds)
_swap_harmonic = _Function_swap_harmonic()
register_symbol(_swap_harmonic, {'maxima': 'gen_harmonic_number'})
register_symbol(_swap_harmonic, {'maple': 'harmonic'})
class Function_harmonic_number(BuiltinFunction):
r"""
Harmonic number function, defined by:
.. MATH::
H_{n}=H_{n,1}=\sum_{k=1}^n\frac1k
H_{s}=\int_0^1\frac{1-x^s}{1-x}
See the docstring for :meth:`Function_harmonic_number_generalized`.
This class exists as callback for ``harmonic_number`` returned by Maxima.
"""
def __init__(self):
r"""
EXAMPLES::
sage: k=var('k')
sage: loads(dumps(sum(1/k,k,1,x)))
harmonic_number(x)
sage: harmonic_number(x)._sympy_()
harmonic(x)
"""
BuiltinFunction.__init__(self, "harmonic_number", nargs=1,
conversions={'mathematica': 'HarmonicNumber',
'maple': 'harmonic',
'maxima': 'harmonic_number',
'sympy': 'harmonic'})
def _eval_(self, z, **kwds):
"""
EXAMPLES::
sage: harmonic_number(0)
0
sage: harmonic_number(1)
1
sage: harmonic_number(20)
55835135/15519504
sage: harmonic_number(5/2)
-2*log(2) + 46/15
sage: harmonic_number(2*x)
harmonic_number(2*x)
"""
if z in ZZ:
if z == 0:
return Integer(0)
elif z == 1:
return Integer(1)
elif z > 1:
import sage.libs.flint.arith as flint_arith
return flint_arith.harmonic_number(z)
elif z in QQ:
from .gamma import psi1
return psi1(z + 1) - psi1(1)
def _evalf_(self, z, parent=None, algorithm='mpmath'):
"""
EXAMPLES::
sage: harmonic_number(20).n() # this goes from rational to float
3.59773965714368
sage: harmonic_number(20).n(200)
3.59773965714368191148376906...
sage: harmonic_number(20.) # this computes the integral with mpmath
3.59773965714368
sage: harmonic_number(1.0*I)
0.671865985524010 + 1.07667404746858*I
"""
from sage.libs.mpmath import utils as mpmath_utils
import mpmath
return mpmath_utils.call(mpmath.harmonic, z, parent=parent)
def _derivative_(self, z, diff_param=None):
"""
The derivative of `H_x`.
EXAMPLES::
sage: k=var('k')
sage: sum(1/k,k,1,x).diff(x)
1/6*pi^2 - harmonic_number(x, 2)
"""
from sage.functions.transcendental import zeta
return zeta(2) - harmonic_number(z, 2)
def _print_latex_(self, z):
"""
EXAMPLES::
sage: k=var('k')
sage: latex(sum(1/k,k,1,x))
H_{x}
"""
return r"H_{%s}" % z
harmonic_m1 = Function_harmonic_number() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/functions/log.py | 0.905719 | 0.703131 | log.py | pypi |
from sage.symbolic.function import GinacFunction, BuiltinFunction
from sage.symbolic.expression import register_symbol, symbol_table
from sage.structure.all import parent as s_parent
from sage.rings.complex_mpfr import ComplexField
from sage.rings.rational import Rational
from sage.functions.exp_integral import Ei
from sage.libs.mpmath import utils as mpmath_utils
from .log import exp
from .other import sqrt
from sage.symbolic.constants import pi
class Function_gamma(GinacFunction):
def __init__(self):
r"""
The Gamma function. This is defined by
.. MATH::
\Gamma(z) = \int_0^\infty t^{z-1}e^{-t} dt
for complex input `z` with real part greater than zero, and by
analytic continuation on the rest of the complex plane (except
for negative integers, which are poles).
It is computed by various libraries within Sage, depending on
the input type.
EXAMPLES::
sage: from sage.functions.gamma import gamma1
sage: gamma1(CDF(0.5,14))
-4.0537030780372815e-10 - 5.773299834553605e-10*I
sage: gamma1(CDF(I))
-0.15494982830181067 - 0.49801566811835607*I
Recall that `\Gamma(n)` is `n-1` factorial::
sage: gamma1(11) == factorial(10)
True
sage: gamma1(6)
120
sage: gamma1(1/2)
sqrt(pi)
sage: gamma1(-1)
Infinity
sage: gamma1(I)
gamma(I)
sage: gamma1(x/2)(x=5)
3/4*sqrt(pi)
sage: gamma1(float(6)) # For ARM: rel tol 3e-16
120.0
sage: gamma(6.)
120.000000000000
sage: gamma1(x)
gamma(x)
::
sage: gamma1(pi)
gamma(pi)
sage: gamma1(i)
gamma(I)
sage: gamma1(i).n()
-0.154949828301811 - 0.498015668118356*I
sage: gamma1(int(5))
24
::
sage: conjugate(gamma(x))
gamma(conjugate(x))
::
sage: plot(gamma1(x),(x,1,5))
Graphics object consisting of 1 graphics primitive
We are also able to compute the Laurent expansion of the
Gamma function (as well as of functions containing
the Gamma function)::
sage: gamma(x).series(x==0, 2)
1*x^(-1) + (-euler_gamma)
+ (1/2*euler_gamma^2 + 1/12*pi^2)*x + Order(x^2)
sage: (gamma(x)^2).series(x==0, 1)
1*x^(-2) + (-2*euler_gamma)*x^(-1)
+ (2*euler_gamma^2 + 1/6*pi^2) + Order(x)
To prevent automatic evaluation use the ``hold`` argument::
sage: gamma1(1/2,hold=True)
gamma(1/2)
To then evaluate again, we currently must use Maxima via
:meth:`sage.symbolic.expression.Expression.simplify`::
sage: gamma1(1/2,hold=True).simplify()
sqrt(pi)
TESTS:
sage: gamma(x)._sympy_()
gamma(x)
We verify that we can convert this function to Maxima and
convert back to Sage::
sage: z = var('z')
sage: maxima(gamma1(z)).sage()
gamma(z)
sage: latex(gamma1(z))
\Gamma\left(z\right)
Test that :trac:`5556` is fixed::
sage: gamma1(3/4)
gamma(3/4)
sage: gamma1(3/4).n(100)
1.2254167024651776451290983034
Check that negative integer input works::
sage: (-1).gamma()
Infinity
sage: (-1.).gamma()
NaN
sage: CC(-1).gamma()
Infinity
sage: RDF(-1).gamma()
NaN
sage: CDF(-1).gamma()
Infinity
Check if :trac:`8297` is fixed::
sage: latex(gamma(1/4))
\Gamma\left(\frac{1}{4}\right)
Test pickling::
sage: loads(dumps(gamma(x)))
gamma(x)
Check that the implementations roughly agrees (note there might be
difference of several ulp on more complicated entries)::
sage: import mpmath
sage: float(gamma(10.)) == gamma(10.r) == float(gamma(mpmath.mpf(10)))
True
sage: float(gamma(8.5)) == gamma(8.5r) == float(gamma(mpmath.mpf(8.5)))
True
Check that ``QQbar`` half integers work with the ``pi`` formula::
sage: gamma(QQbar(1/2))
sqrt(pi)
sage: gamma(QQbar(-9/2))
-32/945*sqrt(pi)
.. SEEALSO::
:meth:`gamma`
"""
GinacFunction.__init__(self, 'gamma', latex_name=r"\Gamma",
ginac_name='gamma',
conversions={'mathematica':'Gamma',
'maple':'GAMMA',
'sympy':'gamma',
'fricas':'Gamma',
'giac':'Gamma'})
gamma1 = Function_gamma()
class Function_log_gamma(GinacFunction):
def __init__(self):
r"""
The principal branch of the log gamma function. Note that for
`x < 0`, ``log(gamma(x))`` is not, in general, equal to
``log_gamma(x)``.
It is computed by the ``log_gamma`` function for the number type,
or by ``lgamma`` in Ginac, failing that.
Gamma is defined for complex input `z` with real part greater
than zero, and by analytic continuation on the rest of the
complex plane (except for negative integers, which are poles).
EXAMPLES:
Numerical evaluation happens when appropriate, to the
appropriate accuracy (see :trac:`10072`)::
sage: log_gamma(6)
log(120)
sage: log_gamma(6.)
4.78749174278205
sage: log_gamma(6).n()
4.78749174278205
sage: log_gamma(RealField(100)(6))
4.7874917427820459942477009345
sage: log_gamma(2.4 + I)
-0.0308566579348816 + 0.693427705955790*I
sage: log_gamma(-3.1)
0.400311696703985 - 12.5663706143592*I
sage: log_gamma(-1.1) == log(gamma(-1.1))
False
Symbolic input works (see :trac:`10075`)::
sage: log_gamma(3*x)
log_gamma(3*x)
sage: log_gamma(3 + I)
log_gamma(I + 3)
sage: log_gamma(3 + I + x)
log_gamma(x + I + 3)
Check that :trac:`12521` is fixed::
sage: log_gamma(-2.1)
1.53171380819509 - 9.42477796076938*I
sage: log_gamma(CC(-2.1))
1.53171380819509 - 9.42477796076938*I
sage: log_gamma(-21/10).n()
1.53171380819509 - 9.42477796076938*I
sage: exp(log_gamma(-1.3) + log_gamma(-0.4) -
....: log_gamma(-1.3 - 0.4)).real_part() # beta(-1.3, -0.4)
-4.92909641669610
In order to prevent evaluation, use the ``hold`` argument;
to evaluate a held expression, use the ``n()`` numerical
evaluation method::
sage: log_gamma(SR(5), hold=True)
log_gamma(5)
sage: log_gamma(SR(5), hold=True).n()
3.17805383034795
TESTS::
sage: log_gamma(-2.1 + I)
-1.90373724496982 - 7.18482377077183*I
sage: log_gamma(pari(6))
4.78749174278205
sage: log_gamma(x)._sympy_()
loggamma(x)
sage: log_gamma(CC(6))
4.78749174278205
sage: log_gamma(CC(-2.5))
-0.0562437164976741 - 9.42477796076938*I
sage: log_gamma(RDF(-2.5))
-0.056243716497674054 - 9.42477796076938*I
sage: log_gamma(CDF(-2.5))
-0.056243716497674054 - 9.42477796076938*I
sage: log_gamma(float(-2.5))
(-0.056243716497674054-9.42477796076938j)
sage: log_gamma(complex(-2.5))
(-0.056243716497674054-9.42477796076938j)
``conjugate(log_gamma(x)) == log_gamma(conjugate(x))`` unless on the
branch cut, which runs along the negative real axis.::
sage: conjugate(log_gamma(x))
conjugate(log_gamma(x))
sage: var('y', domain='positive')
y
sage: conjugate(log_gamma(y))
log_gamma(y)
sage: conjugate(log_gamma(y + I))
conjugate(log_gamma(y + I))
sage: log_gamma(-2)
+Infinity
sage: conjugate(log_gamma(-2))
+Infinity
"""
GinacFunction.__init__(self, "log_gamma", latex_name=r'\log\Gamma',
conversions=dict(mathematica='LogGamma',
maxima='log_gamma',
sympy='loggamma',
fricas='logGamma'))
log_gamma = Function_log_gamma()
class Function_gamma_inc(BuiltinFunction):
def __init__(self):
r"""
The upper incomplete gamma function.
It is defined by the integral
.. MATH::
\Gamma(a,z)=\int_z^\infty t^{a-1}e^{-t}\,\mathrm{d}t
EXAMPLES::
sage: gamma_inc(CDF(0,1), 3)
0.0032085749933691158 + 0.012406185811871568*I
sage: gamma_inc(RDF(1), 3)
0.049787068367863944
sage: gamma_inc(3,2)
gamma(3, 2)
sage: gamma_inc(x,0)
gamma(x)
sage: latex(gamma_inc(3,2))
\Gamma\left(3, 2\right)
sage: loads(dumps((gamma_inc(3,2))))
gamma(3, 2)
sage: i = ComplexField(30).0; gamma_inc(2, 1 + i)
0.70709210 - 0.42035364*I
sage: gamma_inc(2., 5)
0.0404276819945128
sage: x,y=var('x,y')
sage: gamma_inc(x,y).diff(x)
diff(gamma(x, y), x)
sage: (gamma_inc(x,x+1).diff(x)).simplify()
-(x + 1)^(x - 1)*e^(-x - 1) + D[0](gamma)(x, x + 1)
TESTS:
Check that :trac:`21407` is fixed::
sage: gamma(-1,5)._sympy_()
expint(2, 5)/5
sage: gamma(-3/2,5)._sympy_()
-6*sqrt(5)*exp(-5)/25 + 4*sqrt(pi)*erfc(sqrt(5))/3
Check that :trac:`25597` is fixed::
sage: gamma(-1,5)._fricas_() # optional - fricas
Gamma(- 1,5)
sage: var('t') # optional - fricas
t
sage: integrate(-exp(-x)*x^(t-1), x, algorithm="fricas") # optional - fricas
gamma(t, x)
.. SEEALSO::
:meth:`gamma`
"""
BuiltinFunction.__init__(self, "gamma", nargs=2, latex_name=r"\Gamma",
conversions={'maxima':'gamma_incomplete', 'mathematica':'Gamma',
'maple':'GAMMA', 'sympy':'uppergamma', 'fricas':'Gamma',
'giac':'ugamma'})
def _method_arguments(self, x, y):
r"""
TESTS::
sage: b = RBF(1, 1e-10)
sage: gamma(b) # abs tol 1e-9
[1.0000000000 +/- 5.78e-11]
sage: gamma(CBF(b)) # abs tol 1e-9
[1.0000000000 +/- 5.78e-11]
sage: gamma(CBF(b), 4) # abs tol 2e-9
[0.018315639 +/- 9.00e-10]
sage: gamma(CBF(1), b)
[0.3678794412 +/- 6.54e-11]
"""
return [x, y]
def _eval_(self, x, y):
"""
EXAMPLES::
sage: gamma_inc(2.,0)
1.00000000000000
sage: gamma_inc(2,0)
1
sage: gamma_inc(1/2,2)
-sqrt(pi)*(erf(sqrt(2)) - 1)
sage: gamma_inc(1/2,1)
-sqrt(pi)*(erf(1) - 1)
sage: gamma_inc(1/2,0)
sqrt(pi)
sage: gamma_inc(x,0)
gamma(x)
sage: gamma_inc(1,2)
e^(-2)
sage: gamma_inc(0,2)
-Ei(-2)
"""
if y == 0:
return gamma(x)
if x == 1:
return exp(-y)
if x == 0:
return -Ei(-y)
if x == Rational((1, 2)): # only for x>0
from sage.functions.error import erf
return sqrt(pi) * (1 - erf(sqrt(y)))
return None
def _evalf_(self, x, y, parent=None, algorithm='pari'):
"""
EXAMPLES::
sage: gamma_inc(0,2)
-Ei(-2)
sage: gamma_inc(0,2.)
0.0489005107080611
sage: gamma_inc(0,2).n(algorithm='pari')
0.0489005107080611
sage: gamma_inc(0,2).n(200)
0.048900510708061119567239835228...
sage: gamma_inc(3,2).n()
1.35335283236613
TESTS:
Check that :trac:`7099` is fixed::
sage: R = RealField(1024)
sage: gamma(R(9), R(10^-3)) # rel tol 1e-308
40319.99999999999999999999999999988898884344822911869926361916294165058203634104838326009191542490601781777105678829520585311300510347676330951251563007679436243294653538925717144381702105700908686088851362675381239820118402497959018315224423868693918493033078310647199219674433536605771315869983788442389633
sage: numerical_approx(gamma(9, 10^(-3)) - gamma(9), digits=40) # abs tol 1e-36
-1.110111598370794007949063502542063148294e-28
Check that :trac:`17328` is fixed::
sage: gamma_inc(float(-1), float(-1))
(-0.8231640121031085+3.141592653589793j)
sage: gamma_inc(RR(-1), RR(-1))
-0.823164012103109 + 3.14159265358979*I
sage: gamma_inc(-1, float(-log(3))) - gamma_inc(-1, float(-log(2))) # abs tol 1e-15
(1.2730972164471142+0j)
Check that :trac:`17130` is fixed::
sage: r = gamma_inc(float(0), float(1)); r
0.21938393439552029
sage: type(r)
<... 'float'>
"""
R = parent or s_parent(x)
# C is the complex version of R
# prec is the precision of R
if R is float:
prec = 53
C = complex
else:
try:
prec = R.precision()
except AttributeError:
prec = 53
try:
C = R.complex_field()
except AttributeError:
C = R
if algorithm == 'pari':
v = ComplexField(prec)(x).gamma_inc(y)
else:
import mpmath
v = ComplexField(prec)(mpmath_utils.call(mpmath.gammainc, x, y, parent=R))
if v.is_real():
return R(v)
else:
return C(v)
# synonym.
gamma_inc = Function_gamma_inc()
class Function_gamma_inc_lower(BuiltinFunction):
def __init__(self):
r"""
The lower incomplete gamma function.
It is defined by the integral
.. MATH::
\Gamma(a,z)=\int_0^z t^{a-1}e^{-t}\,\mathrm{d}t
EXAMPLES::
sage: gamma_inc_lower(CDF(0,1), 3)
-0.1581584032951798 - 0.5104218539302277*I
sage: gamma_inc_lower(RDF(1), 3)
0.950212931632136
sage: gamma_inc_lower(3, 2, hold=True)
gamma_inc_lower(3, 2)
sage: gamma_inc_lower(3, 2)
-10*e^(-2) + 2
sage: gamma_inc_lower(x, 0)
0
sage: latex(gamma_inc_lower(x, x))
\gamma\left(x, x\right)
sage: loads(dumps((gamma_inc_lower(x, x))))
gamma_inc_lower(x, x)
sage: i = ComplexField(30).0; gamma_inc_lower(2, 1 + i)
0.29290790 + 0.42035364*I
sage: gamma_inc_lower(2., 5)
0.959572318005487
Interfaces to other software::
sage: gamma_inc_lower(x,x)._sympy_()
lowergamma(x, x)
sage: maxima(gamma_inc_lower(x,x))
gamma_incomplete_lower(_SAGE_VAR_x,_SAGE_VAR_x)
.. SEEALSO::
:class:`Function_gamma_inc`
"""
BuiltinFunction.__init__(self, "gamma_inc_lower", nargs=2, latex_name=r"\gamma",
conversions={'maxima':'gamma_incomplete_lower',
'maple':'GAMMA', 'sympy':'lowergamma', 'giac':'igamma'})
def _eval_(self, x, y):
"""
EXAMPLES::
sage: gamma_inc_lower(2.,0)
0.000000000000000
sage: gamma_inc_lower(2,0)
0
sage: gamma_inc_lower(1/2,2)
sqrt(pi)*erf(sqrt(2))
sage: gamma_inc_lower(1/2,1)
sqrt(pi)*erf(1)
sage: gamma_inc_lower(1/2,0)
0
sage: gamma_inc_lower(x,0)
0
sage: gamma_inc_lower(1,2)
-e^(-2) + 1
sage: gamma_inc_lower(0,2)
+Infinity
sage: gamma_inc_lower(2,377/79)
-456/79*e^(-377/79) + 1
sage: gamma_inc_lower(3,x)
-(x^2 + 2*x + 2)*e^(-x) + 2
sage: gamma_inc_lower(9/2,37/7)
-1/38416*sqrt(pi)*(1672946*sqrt(259)*e^(-37/7)/sqrt(pi) - 252105*erf(1/7*sqrt(259)))
"""
if y == 0:
return 0
if x == 0:
from sage.rings.infinity import Infinity
return Infinity
elif x == 1:
return 1 - exp(-y)
elif (2 * x).is_integer():
return self(x, y, hold=True)._sympy_()
else:
return None
def _evalf_(self, x, y, parent=None, algorithm='mpmath'):
"""
EXAMPLES::
sage: gamma_inc_lower(3,2.)
0.646647167633873
sage: gamma_inc_lower(3,2).n(200)
0.646647167633873081060005050275155...
sage: gamma_inc_lower(0,2.)
+infinity
"""
R = parent or s_parent(x)
# C is the complex version of R
# prec is the precision of R
if R is float:
prec = 53
C = complex
else:
try:
prec = R.precision()
except AttributeError:
prec = 53
try:
C = R.complex_field()
except AttributeError:
C = R
if algorithm == 'pari':
Cx = ComplexField(prec)(x)
v = Cx.gamma() - Cx.gamma_inc(y)
else:
import mpmath
v = ComplexField(prec)(mpmath_utils.call(mpmath.gammainc, x, 0, y, parent=R))
return R(v) if v.is_real() else C(v)
def _derivative_(self, x, y, diff_param=None):
"""
EXAMPLES::
sage: x,y = var('x,y')
sage: gamma_inc_lower(x,y).diff(y)
y^(x - 1)*e^(-y)
sage: gamma_inc_lower(x,y).diff(x)
Traceback (most recent call last):
...
NotImplementedError: cannot differentiate gamma_inc_lower in the first parameter
"""
if diff_param == 0:
raise NotImplementedError("cannot differentiate gamma_inc_lower in the"
" first parameter")
else:
return exp(-y) * y**(x - 1)
def _mathematica_init_evaled_(self, *args):
r"""
EXAMPLES::
sage: gamma_inc_lower(4/3, 1)._mathematica_() # indirect doctest, optional - mathematica
Gamma[4/3, 0, 1]
"""
args_mathematica = []
for a in args:
if isinstance(a, str):
args_mathematica.append(a)
elif hasattr(a, '_mathematica_init_'):
args_mathematica.append(a._mathematica_init_())
else:
args_mathematica.append(str(a))
x, z = args_mathematica
return "Gamma[%s,0,%s]" % (x, z)
# synonym.
gamma_inc_lower = Function_gamma_inc_lower()
def gamma(a, *args, **kwds):
r"""
Gamma and upper incomplete gamma functions in one symbol.
Recall that `\Gamma(n)` is `n-1` factorial::
sage: gamma(11) == factorial(10)
True
sage: gamma(6)
120
sage: gamma(1/2)
sqrt(pi)
sage: gamma(-4/3)
gamma(-4/3)
sage: gamma(-1)
Infinity
sage: gamma(0)
Infinity
::
sage: gamma_inc(3,2)
gamma(3, 2)
sage: gamma_inc(x,0)
gamma(x)
::
sage: gamma(5, hold=True)
gamma(5)
sage: gamma(x, 0, hold=True)
gamma(x, 0)
::
sage: gamma(CDF(I))
-0.15494982830181067 - 0.49801566811835607*I
sage: gamma(CDF(0.5,14))
-4.0537030780372815e-10 - 5.773299834553605e-10*I
Use ``numerical_approx`` to get higher precision from
symbolic expressions::
sage: gamma(pi).n(100)
2.2880377953400324179595889091
sage: gamma(3/4).n(100)
1.2254167024651776451290983034
The precision for the result is also deduced from the precision of the
input. Convert the input to a higher precision explicitly if a result
with higher precision is desired.::
sage: t = gamma(RealField(100)(2.5)); t
1.3293403881791370204736256125
sage: t.prec()
100
The gamma function only works with input that can be coerced to the
Symbolic Ring::
sage: Q.<i> = NumberField(x^2+1)
sage: gamma(i)
Traceback (most recent call last):
...
TypeError: cannot coerce arguments: no canonical coercion from Number Field in i with defining polynomial x^2 + 1 to Symbolic Ring
.. SEEALSO::
:class:`Function_gamma`
"""
if not args:
return gamma1(a, **kwds)
if len(args) > 1:
raise TypeError("Symbolic function gamma takes at most 2 arguments (%s given)" % (len(args) + 1))
return gamma_inc(a, args[0], **kwds)
# We have to add the wrapper function manually to the symbol_table when we have
# two functions with different number of arguments and the same name
symbol_table['functions']['gamma'] = gamma
def _mathematica_gamma3(*args):
r"""
EXAMPLES::
sage: gamma(4/3)._mathematica_().sage() # indirect doctest, optional - mathematica
gamma(4/3)
sage: gamma(4/3, 1)._mathematica_().sage() # indirect doctest, optional - mathematica
gamma(4/3, 1)
sage: mathematica('Gamma[4/3, 0, 1]').sage() # indirect doctest, optional - mathematica
gamma(4/3) - gamma(4/3, 1)
"""
assert len(args) == 3
return gamma_inc(args[0], args[1]) - gamma_inc(args[0], args[2])
register_symbol(_mathematica_gamma3, dict(mathematica='Gamma'), 3)
class Function_psi1(GinacFunction):
def __init__(self):
r"""
The digamma function, `\psi(x)`, is the logarithmic derivative of the
gamma function.
.. MATH::
\psi(x) = \frac{d}{dx} \log(\Gamma(x)) = \frac{\Gamma'(x)}{\Gamma(x)}
EXAMPLES::
sage: from sage.functions.gamma import psi1
sage: psi1(x)
psi(x)
sage: psi1(x).derivative(x)
psi(1, x)
::
sage: psi1(3)
-euler_gamma + 3/2
::
sage: psi(.5)
-1.96351002602142
sage: psi(RealField(100)(.5))
-1.9635100260214234794409763330
TESTS::
sage: latex(psi1(x))
\psi\left(x\right)
sage: loads(dumps(psi1(x)+1))
psi(x) + 1
sage: t = psi1(x); t
psi(x)
sage: t.subs(x=.2)
-5.28903989659219
sage: psi(x)._sympy_()
polygamma(0, x)
sage: psi(x)._fricas_() # optional - fricas
digamma(x)
"""
GinacFunction.__init__(self, "psi", nargs=1, latex_name=r'\psi',
conversions=dict(mathematica='PolyGamma',
maxima='psi[0]',
maple='Psi',
sympy='digamma',
fricas='digamma'))
class Function_psi2(GinacFunction):
def __init__(self):
r"""
Derivatives of the digamma function `\psi(x)`. T
EXAMPLES::
sage: from sage.functions.gamma import psi2
sage: psi2(2, x)
psi(2, x)
sage: psi2(2, x).derivative(x)
psi(3, x)
sage: n = var('n')
sage: psi2(n, x).derivative(x)
psi(n + 1, x)
::
sage: psi2(0, x)
psi(x)
sage: psi2(-1, x)
log(gamma(x))
sage: psi2(3, 1)
1/15*pi^4
::
sage: psi2(2, .5).n()
-16.8287966442343
sage: psi2(2, .5).n(100)
-16.828796644234319995596334261
TESTS::
sage: psi2(n, x).derivative(n)
Traceback (most recent call last):
...
RuntimeError: cannot diff psi(n,x) with respect to n
sage: latex(psi2(2,x))
\psi\left(2, x\right)
sage: loads(dumps(psi2(2,x)+1))
psi(2, x) + 1
sage: psi(2, x)._sympy_()
polygamma(2, x)
sage: psi(2, x)._fricas_() # optional - fricas
polygamma(2,x)
Fixed conversion::
sage: psi(2,x)._maple_init_()
'Psi(2,x)'
"""
GinacFunction.__init__(self, "psi", nargs=2, latex_name=r'\psi',
conversions=dict(mathematica='PolyGamma',
sympy='polygamma',
maple='Psi',
giac='Psi',
fricas='polygamma'))
def _maxima_init_evaled_(self, *args):
"""
EXAMPLES:
These are indirect doctests for this function.::
sage: from sage.functions.gamma import psi2
sage: psi2(2, x)._maxima_()
psi[2](_SAGE_VAR_x)
sage: psi2(4, x)._maxima_()
psi[4](_SAGE_VAR_x)
"""
args_maxima = []
for a in args:
if isinstance(a, str):
args_maxima.append(a)
elif hasattr(a, '_maxima_init_'):
args_maxima.append(a._maxima_init_())
else:
args_maxima.append(str(a))
n, x = args_maxima
return "psi[%s](%s)" % (n, x)
psi1 = Function_psi1()
psi2 = Function_psi2()
def psi(x, *args, **kwds):
r"""
The digamma function, `\psi(x)`, is the logarithmic derivative of the
gamma function.
.. MATH::
\psi(x) = \frac{d}{dx} \log(\Gamma(x)) = \frac{\Gamma'(x)}{\Gamma(x)}
We represent the `n`-th derivative of the digamma function with
`\psi(n, x)` or `psi(n, x)`.
EXAMPLES::
sage: psi(x)
psi(x)
sage: psi(.5)
-1.96351002602142
sage: psi(3)
-euler_gamma + 3/2
sage: psi(1, 5)
1/6*pi^2 - 205/144
sage: psi(1, x)
psi(1, x)
sage: psi(1, x).derivative(x)
psi(2, x)
::
sage: psi(3, hold=True)
psi(3)
sage: psi(1, 5, hold=True)
psi(1, 5)
TESTS::
sage: psi(2, x, 3)
Traceback (most recent call last):
...
TypeError: Symbolic function psi takes at most 2 arguments (3 given)
"""
if not args:
return psi1(x, **kwds)
if len(args) > 1:
raise TypeError("Symbolic function psi takes at most 2 arguments (%s given)" % (len(args) + 1))
return psi2(x, args[0], **kwds)
# We have to add the wrapper function manually to the symbol_table when we have
# two functions with different number of arguments and the same name
symbol_table['functions']['psi'] = psi
def _swap_psi(a, b):
return psi(b, a)
register_symbol(_swap_psi, {'giac': 'Psi'}, 2)
class Function_beta(GinacFunction):
def __init__(self):
r"""
Return the beta function. This is defined by
.. MATH::
\operatorname{B}(p,q) = \int_0^1 t^{p-1}(1-t)^{q-1} dt
for complex or symbolic input `p` and `q`.
Note that the order of inputs does not matter:
`\operatorname{B}(p,q)=\operatorname{B}(q,p)`.
GiNaC is used to compute `\operatorname{B}(p,q)`. However, complex inputs
are not yet handled in general. When GiNaC raises an error on
such inputs, we raise a NotImplementedError.
If either input is 1, GiNaC returns the reciprocal of the
other. In other cases, GiNaC uses one of the following
formulas:
.. MATH::
\operatorname{B}(p,q) = \frac{\Gamma(p)\Gamma(q)}{\Gamma(p+q)}
or
.. MATH::
\operatorname{B}(p,q) = (-1)^q \operatorname{B}(1-p-q, q).
For numerical inputs, GiNaC uses the formula
.. MATH::
\operatorname{B}(p,q) = \exp[\log\Gamma(p)+\log\Gamma(q)-\log\Gamma(p+q)]
INPUT:
- ``p`` - number or symbolic expression
- ``q`` - number or symbolic expression
OUTPUT: number or symbolic expression (if input is symbolic)
EXAMPLES::
sage: beta(3,2)
1/12
sage: beta(3,1)
1/3
sage: beta(1/2,1/2)
beta(1/2, 1/2)
sage: beta(-1,1)
-1
sage: beta(-1/2,-1/2)
0
sage: ex = beta(x/2,3)
sage: set(ex.operands()) == set([1/2*x, 3])
True
sage: beta(.5,.5)
3.14159265358979
sage: beta(1,2.0+I)
0.400000000000000 - 0.200000000000000*I
sage: ex = beta(3,x+I)
sage: set(ex.operands()) == set([x+I, 3])
True
The result is symbolic if exact input is given::
sage: ex = beta(2,1+5*I); ex
beta(...
sage: set(ex.operands()) == set([1+5*I, 2])
True
sage: beta(2, 2.)
0.166666666666667
sage: beta(I, 2.)
-0.500000000000000 - 0.500000000000000*I
sage: beta(2., 2)
0.166666666666667
sage: beta(2., I)
-0.500000000000000 - 0.500000000000000*I
sage: beta(x, x)._sympy_()
beta(x, x)
Test pickling::
sage: loads(dumps(beta))
beta
Check that :trac:`15196` is fixed::
sage: beta(-1.3,-0.4)
-4.92909641669610
"""
GinacFunction.__init__(self, 'beta', nargs=2,
latex_name=r"\operatorname{B}",
conversions=dict(maxima='beta',
mathematica='Beta',
maple='Beta',
sympy='beta',
fricas='Beta',
giac='Beta'))
def _method_arguments(self, x, y):
r"""
TESTS::
sage: RBF(beta(sin(3),sqrt(RBF(2).add_error(1e-8)/3))) # abs tol 6e-7
[7.407662 +/- 6.17e-7]
"""
return [x, y]
beta = Function_beta() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/functions/gamma.py | 0.887951 | 0.717964 | gamma.py | pypi |
r"""
Congruence subgroup `\Gamma(N)`
"""
#*****************************************************************************
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.arith.misc import gcd
from sage.groups.matrix_gps.finitely_generated import MatrixGroup
from sage.matrix.constructor import matrix
from sage.misc.misc_c import prod
from sage.modular.cusps import Cusp
from sage.rings.finite_rings.integer_mod_ring import Zmod
from sage.rings.integer import GCD_list
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.structure.richcmp import richcmp_method, richcmp
from .congroup_generic import CongruenceSubgroup
from .congroup_sl2z import SL2Z
_gamma_cache = {}
def Gamma_constructor(N):
r"""
Return the congruence subgroup `\Gamma(N)`.
EXAMPLES::
sage: Gamma(5) # indirect doctest
Congruence Subgroup Gamma(5)
sage: G = Gamma(23)
sage: G is Gamma(23)
True
sage: TestSuite(G).run()
Test global uniqueness::
sage: G = Gamma(17)
sage: G is loads(dumps(G))
True
sage: G2 = sage.modular.arithgroup.congroup_gamma.Gamma_class(17)
sage: G == G2
True
sage: G is G2
False
"""
if N == 1:
return SL2Z
try:
return _gamma_cache[N]
except KeyError:
_gamma_cache[N] = Gamma_class(N)
return _gamma_cache[N]
@richcmp_method
class Gamma_class(CongruenceSubgroup):
r"""
The principal congruence subgroup `\Gamma(N)`.
"""
def _repr_(self):
"""
Return the string representation of self.
EXAMPLES::
sage: Gamma(133)._repr_()
'Congruence Subgroup Gamma(133)'
"""
return "Congruence Subgroup Gamma(%s)"%self.level()
def _latex_(self):
r"""
Return the \LaTeX representation of self.
EXAMPLES::
sage: Gamma(20)._latex_()
'\\Gamma(20)'
sage: latex(Gamma(20))
\Gamma(20)
"""
return "\\Gamma(%s)"%self.level()
def __reduce__(self):
"""
Used for pickling self.
EXAMPLES::
sage: Gamma(5).__reduce__()
(<function Gamma_constructor at ...>, (5,))
"""
return Gamma_constructor, (self.level(),)
def __richcmp__(self, other, op):
r"""
Compare self to other.
EXAMPLES::
sage: Gamma(3) == SymmetricGroup(8)
False
sage: Gamma(3) == Gamma1(3)
False
sage: Gamma(5) < Gamma(6)
True
sage: Gamma(5) == Gamma(5)
True
sage: Gamma(3) == Gamma(3).as_permutation_group()
True
"""
if is_Gamma(other):
return richcmp(self.level(), other.level(), op)
else:
return NotImplemented
def index(self):
r"""
Return the index of self in the full modular group. This is given by
.. MATH::
\prod_{\substack{p \mid N \\ \text{$p$ prime}}}\left(p^{3e}-p^{3e-2}\right).
EXAMPLES::
sage: [Gamma(n).index() for n in [1..19]]
[1, 6, 24, 48, 120, 144, 336, 384, 648, 720, 1320, 1152, 2184, 2016, 2880, 3072, 4896, 3888, 6840]
sage: Gamma(32041).index()
32893086819240
"""
return prod([p**(3*e-2)*(p*p-1) for (p,e) in self.level().factor()])
def _contains_sl2(self, a,b,c,d):
r"""
EXAMPLES::
sage: G = Gamma(5)
sage: [1, 0, -10, 1] in G
True
sage: 1 in G
True
sage: SL2Z([26, 5, 5, 1]) in G
True
sage: SL2Z([1, 1, 6, 7]) in G
False
"""
N = self.level()
# don't need to check d == 1 as this is automatic from det
return ((a%N == 1) and (b%N == 0) and (c%N == 0))
def ncusps(self):
r"""
Return the number of cusps of this subgroup `\Gamma(N)`.
EXAMPLES::
sage: [Gamma(n).ncusps() for n in [1..19]]
[1, 3, 4, 6, 12, 12, 24, 24, 36, 36, 60, 48, 84, 72, 96, 96, 144, 108, 180]
sage: Gamma(30030).ncusps()
278691840
sage: Gamma(2^30).ncusps()
432345564227567616
"""
n = self.level()
if n==1:
return ZZ(1)
if n==2:
return ZZ(3)
return prod([p**(2*e) - p**(2*e-2) for (p,e) in n.factor()])//2
def nirregcusps(self):
r"""
Return the number of irregular cusps of self. For principal congruence subgroups this is always 0.
EXAMPLES::
sage: Gamma(17).nirregcusps()
0
"""
return 0
def _find_cusps(self):
r"""
Calculate the reduced representatives of the equivalence classes of
cusps for this group. Adapted from code by Ron Evans.
EXAMPLES::
sage: Gamma(8).cusps() # indirect doctest
[0, 1/4, 1/3, 3/8, 1/2, 2/3, 3/4, 1, 4/3, 3/2, 5/3, 2, 7/3, 5/2, 8/3, 3, 7/2, 11/3, 4, 14/3, 5, 6, 7, Infinity]
"""
n = self.level()
C = [QQ(x) for x in range(n)]
n0=n//2
n1=(n+1)//2
for r in range(1, n1):
if r > 1 and gcd(r,n)==1:
C.append(ZZ(r)/ZZ(n))
if n0==n/2 and gcd(r,n0)==1:
C.append(ZZ(r)/ZZ(n0))
for s in range(2,n1):
for r in range(1, 1+n):
if GCD_list([s,r,n])==1:
# GCD_list is ~40x faster than gcd, since gcd wastes loads
# of time initialising a Sequence type.
u,v = _lift_pair(r,s,n)
C.append(ZZ(u)/ZZ(v))
return [Cusp(x) for x in sorted(C)] + [Cusp(1,0)]
def reduce_cusp(self, c):
r"""
Calculate the unique reduced representative of the equivalence of the
cusp `c` modulo this group. The reduced representative of an
equivalence class is the unique cusp in the class of the form `u/v`
with `u, v \ge 0` coprime, `v` minimal, and `u` minimal for that `v`.
EXAMPLES::
sage: Gamma(5).reduce_cusp(1/5)
Infinity
sage: Gamma(5).reduce_cusp(7/8)
3/2
sage: Gamma(6).reduce_cusp(4/3)
2/3
TESTS::
sage: G = Gamma(50)
sage: all(c == G.reduce_cusp(c) for c in G.cusps())
True
"""
N = self.level()
c = Cusp(c)
u,v = c.numerator() % N, c.denominator() % N
if (v > N//2) or (2*v == N and u > N//2):
u,v = -u,-v
u,v = _lift_pair(u,v,N)
return Cusp(u,v)
def are_equivalent(self, x, y, trans=False):
r"""
Check if the cusps `x` and `y` are equivalent under the action of this group.
ALGORITHM: The cusps `u_1 / v_1` and `u_2 / v_2` are equivalent modulo
`\Gamma(N)` if and only if `(u_1, v_1) = \pm (u_2, v_2) \bmod N`.
EXAMPLES::
sage: Gamma(7).are_equivalent(Cusp(2/3), Cusp(5/4))
True
"""
if trans:
return CongruenceSubgroup.are_equivalent(self, x,y,trans=trans)
N = self.level()
u1,v1 = (x.numerator() % N, x.denominator() % N)
u2,v2 = (y.numerator(), y.denominator())
return ((u1,v1) == (u2 % N, v2 % N)) or ((u1,v1) == (-u2 % N, -v2 % N))
def nu3(self):
r"""
Return the number of elliptic points of order 3 for this arithmetic
subgroup. Since this subgroup is `\Gamma(N)` for `N \ge 2`, there are
no such points, so we return 0.
EXAMPLES::
sage: Gamma(89).nu3()
0
"""
return 0
# We don't need to override nu2, since the default nu2 implementation knows
# that nu2 = 0 for odd subgroups.
def image_mod_n(self):
r"""
Return the image of this group modulo `N`, as a subgroup of `SL(2, \ZZ
/ N\ZZ)`. This is just the trivial subgroup.
EXAMPLES::
sage: Gamma(3).image_mod_n()
Matrix group over Ring of integers modulo 3 with 1 generators (
[1 0]
[0 1]
)
"""
return MatrixGroup([matrix(Zmod(self.level()), 2, 2, 1)])
def is_Gamma(x):
r"""
Return True if x is a congruence subgroup of type Gamma.
EXAMPLES::
sage: from sage.modular.arithgroup.all import is_Gamma
sage: is_Gamma(Gamma0(13))
False
sage: is_Gamma(Gamma(4))
True
"""
return isinstance(x, Gamma_class)
def _lift_pair(U,V,N):
r"""
Utility function. Given integers ``U, V, N``, with `N \ge 1` and `{\rm
gcd}(U, V, N) = 1`, return a pair `(u, v)` congruent to `(U, V) \bmod N`,
such that `{\rm gcd}(u,v) = 1`, `u, v \ge 0`, `v` is as small as possible,
and `u` is as small as possible for that `v`.
*Warning*: As this function is for internal use, it does not do a
preliminary sanity check on its input, for efficiency. It will recover
reasonably gracefully if ``(U, V, N)`` are not coprime, but only after
wasting quite a lot of cycles!
EXAMPLES::
sage: from sage.modular.arithgroup.congroup_gamma import _lift_pair
sage: _lift_pair(2,4,7)
(9, 4)
sage: _lift_pair(2,4,8) # don't do this
Traceback (most recent call last):
...
ValueError: (U, V, N) must be coprime
"""
u = U % N
v = V % N
if v == 0:
if u == 1:
return (1,0)
else:
v = N
while gcd(u, v) > 1:
u = u+N
if u > N*v:
raise ValueError("(U, V, N) must be coprime")
return (u, v) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/arithgroup/congroup_gamma.py | 0.781497 | 0.495178 | congroup_gamma.py | pypi |
r"""
The matrix monoid `\Sigma_0(N)`.
This stands for a monoid of matrices over `\ZZ`, `\QQ`, `\ZZ_p`, or `\QQ_p`,
depending on an integer `N \ge 1`. This class exists in order to act on p-adic
distribution spaces.
Over `\QQ` or `\ZZ`, it is the monoid of matrices `2\times2` matrices
`\begin{pmatrix} a & b \\ c & d \end{pmatrix}`
such that
- `ad - bc \ne 0`,
- `a` is integral and invertible at the primes dividing `N`,
- `c` has valuation at least `v_p(N)` for each `p` dividing `N` (but may be
non-integral at other places).
The value `N=1` is allowed, in which case the second and third conditions are vacuous.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S1 = Sigma0(1); S3 = Sigma0(3)
sage: S1([3, 0, 0, 1])
[3 0]
[0 1]
sage: S3([3, 0, 0, 1]) # boom
Traceback (most recent call last):
...
TypeError: 3 is not a unit at 3
sage: S3([5,0,0,1])
[5 0]
[0 1]
sage: S3([1, 0, 0, 3])
[1 0]
[0 3]
sage: matrix(ZZ, 2, [1,0,0,1]) in S1
True
AUTHORS:
- David Pollack (2012): initial version
"""
# Warning to developers: when working with Sigma0 elements it is generally a
# good idea to avoid using the entries of x.matrix() directly; rather, use the
# "adjuster" mechanism. The purpose of this is to allow us to seamlessly change
# conventions for matrix actions (since there are several in use in the
# literature and no natural "best" choice).
from sage.matrix.matrix_space import MatrixSpace
from sage.misc.abstract_method import abstract_method
from sage.structure.factory import UniqueFactory
from sage.structure.element import MonoidElement
from sage.structure.richcmp import richcmp
from sage.categories.monoids import Monoids
from sage.categories.morphism import Morphism
from sage.structure.parent import Parent
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.structure.unique_representation import UniqueRepresentation
class Sigma0ActionAdjuster(UniqueRepresentation):
@abstract_method
def __call__(self, x):
r"""
Given a :class:`Sigma0element` ``x``, return four integers.
This is used to allow for other conventions for the action of Sigma0
on the space of distributions.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import _default_adjuster
sage: A = _default_adjuster()
sage: A(matrix(ZZ, 2, [3,4,5,6])) # indirect doctest
(3, 4, 5, 6)
"""
pass
class _default_adjuster(Sigma0ActionAdjuster):
"""
A callable object that does nothing to a matrix, returning its entries
in the natural, by-row, order.
INPUT:
- ``g`` -- a `2 \times 2` matrix
OUTPUT:
- a 4-tuple consisting of the entries of the matrix
EXAMPLES::
sage: A = sage.modular.pollack_stevens.sigma0._default_adjuster(); A
<sage.modular.pollack_stevens.sigma0._default_adjuster object at 0x...>
sage: TestSuite(A).run()
"""
def __call__(self, g):
"""
EXAMPLES::
sage: T = sage.modular.pollack_stevens.sigma0._default_adjuster()
sage: T(matrix(ZZ,2,[1..4])) # indirect doctest
(1, 2, 3, 4)
"""
return tuple(g.list())
class Sigma0_factory(UniqueFactory):
r"""
Create the monoid of non-singular matrices, upper triangular mod `N`.
INPUT:
- ``N`` (integer) -- the level (should be strictly positive)
- ``base_ring`` (commutative ring, default `\ZZ`) -- the base
ring (normally `\ZZ` or a `p`-adic ring)
- ``adjuster`` -- None, or a callable which takes a `2 \times 2` matrix and returns
a 4-tuple of integers. This is supplied in order to support differing
conventions for the action of `2 \times 2` matrices on distributions.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: Sigma0(3)
Monoid Sigma0(3) with coefficients in Integer Ring
"""
def create_key(self, N, base_ring=ZZ, adjuster=None):
r"""
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: Sigma0.create_key(3)
(3, Integer Ring, <sage.modular.pollack_stevens.sigma0._default_adjuster object at 0x...>)
sage: TestSuite(Sigma0).run()
"""
N = ZZ(N)
if N <= 0:
raise ValueError("Modulus should be > 0")
if adjuster is None:
adjuster = _default_adjuster()
if base_ring not in (QQ, ZZ):
try:
if not N.is_power_of(base_ring.prime()):
raise ValueError("Modulus must equal base ring prime")
except AttributeError:
raise ValueError("Base ring must be QQ, ZZ or a p-adic field")
return (N, base_ring, adjuster)
def create_object(self, version, key):
r"""
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: Sigma0(3) # indirect doctest
Monoid Sigma0(3) with coefficients in Integer Ring
"""
return Sigma0_class(*key)
Sigma0 = Sigma0_factory('sage.modular.pollack_stevens.sigma0.Sigma0')
class Sigma0Element(MonoidElement):
r"""
An element of the monoid Sigma0. This is a wrapper around a `2 \times 2` matrix.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(7)
sage: g = S([2,3,7,1])
sage: g.det()
-19
sage: h = S([1,2,0,1])
sage: g * h
[ 2 7]
[ 7 15]
sage: g.inverse()
Traceback (most recent call last):
...
TypeError: no conversion of this rational to integer
sage: h.inverse()
[ 1 -2]
[ 0 1]
"""
def __init__(self, parent, mat):
r"""
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3]) # indirect doctest
sage: TestSuite(s).run()
"""
self._mat = mat
MonoidElement.__init__(self, parent)
def __hash__(self):
r"""
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3])
sage: hash(s) # indirect doctest
8095169151987216923 # 64-bit
619049499 # 32-bit
"""
return hash(self.matrix())
def det(self):
r"""
Return the determinant of this matrix, which is (by assumption) non-zero.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3])
sage: s.det()
-9
"""
return self.matrix().det()
def _mul_(self, other):
r"""
Return the product of two Sigma0 elements.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3])
sage: t = Sigma0(15)([4,0,0,1])
sage: u = s*t; u # indirect doctest
[ 4 4]
[12 3]
sage: type(u)
<class 'sage.modular.pollack_stevens.sigma0.Sigma0_class_with_category.element_class'>
sage: u.parent()
Monoid Sigma0(3) with coefficients in Integer Ring
"""
return self.parent()(self._mat * other._mat, check=False)
def _richcmp_(self, other, op):
r"""
Compare two elements (of a common Sigma0 object).
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3])
sage: t = Sigma0(3)([4,0,0,1])
sage: s == t
False
sage: s == Sigma0(1)([1,4,3,3])
True
This uses the coercion model to find a common parent, with occasionally surprising results::
sage: t == Sigma0(5)([4, 0, 0, 1])
False
"""
return richcmp(self._mat, other._mat, op)
def _repr_(self):
r"""
String representation of self.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3])
sage: s._repr_()
'[1 4]\n[3 3]'
"""
return self.matrix().__repr__()
def matrix(self):
r"""
Return self as a matrix (forgetting the additional data that it is in Sigma0(N)).
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,3])
sage: sm = s.matrix()
sage: type(s)
<class 'sage.modular.pollack_stevens.sigma0.Sigma0_class_with_category.element_class'>
sage: type(sm)
<class 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'>
sage: s == sm
True
"""
return self._mat
def __invert__(self):
r"""
Return the inverse of ``self``.
This will raise an error if the result is not in the monoid.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: s = Sigma0(3)([1,4,3,13])
sage: s.inverse() # indirect doctest
[13 -4]
[-3 1]
sage: Sigma0(3)([1, 0, 0, 3]).inverse()
Traceback (most recent call last):
...
TypeError: no conversion of this rational to integer
.. TODO::
In an ideal world this would silently extend scalars to `\QQ` if
the inverse has non-integer entries but is still in `\Sigma_0(N)`
locally at `N`. But we do not use such functionality, anyway.
"""
return self.parent()(~self._mat)
class _Sigma0Embedding(Morphism):
r"""
A Morphism object giving the natural inclusion of `\Sigma_0` into the
appropriate matrix space. This snippet of code is fed to the coercion
framework so that "x * y" will work if ``x`` is a matrix and ``y`` is a `\Sigma_0`
element (returning a matrix, *not* a Sigma0 element).
"""
def __init__(self, domain):
r"""
TESTS::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0, _Sigma0Embedding
sage: x = _Sigma0Embedding(Sigma0(3))
sage: TestSuite(x).run(skip=['_test_category'])
# TODO: The category test breaks because _Sigma0Embedding is not an instance of
# the element class of its parent (a homset in the category of
# monoids). I have no idea how to fix this.
"""
Morphism.__init__(self, domain.Hom(domain._matrix_space, category=Monoids()))
def _call_(self, x):
r"""
Return a matrix.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0, _Sigma0Embedding
sage: S = Sigma0(3)
sage: x = _Sigma0Embedding(S)
sage: x(S([1,0,0,3])).parent() # indirect doctest
Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
"""
return x.matrix()
def _richcmp_(self, other, op):
r"""
Required for pickling.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0, _Sigma0Embedding
sage: S = Sigma0(3)
sage: x = _Sigma0Embedding(S)
sage: x == loads(dumps(x))
True
"""
return richcmp(self.domain(), other.domain(), op)
class Sigma0_class(Parent):
r"""
The class representing the monoid `\Sigma_0(N)`.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(5); S
Monoid Sigma0(5) with coefficients in Integer Ring
sage: S([1,2,1,1])
Traceback (most recent call last):
...
TypeError: level 5^1 does not divide 1
sage: S([1,2,5,1])
[1 2]
[5 1]
"""
Element = Sigma0Element
def __init__(self, N, base_ring, adjuster):
r"""
Standard init function. For args documentation see the factory
function.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(3) # indirect doctest
sage: TestSuite(S).run()
"""
self._N = N
self._primes = list(N.factor())
self._base_ring = base_ring
self._adjuster = adjuster
self._matrix_space = MatrixSpace(base_ring, 2)
Parent.__init__(self, category=Monoids())
self.register_embedding(_Sigma0Embedding(self))
def _an_element_(self):
r"""
Return an element of self. This is implemented in a rather dumb way.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(3)
sage: S.an_element() # indirect doctest
[1 0]
[0 1]
"""
return self([1, 0, 0, 1])
def level(self):
r"""
If this monoid is `\Sigma_0(N)`, return `N`.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(3)
sage: S.level()
3
"""
return self._N
def base_ring(self):
r"""
Return the base ring.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(3)
sage: S.base_ring()
Integer Ring
"""
return self._base_ring
def _coerce_map_from_(self, other):
r"""
Find out whether ``other`` coerces into ``self``.
The *only* thing that coerces canonically into `\Sigma_0` is another
`\Sigma_0`. It is *very bad* if integers are allowed to coerce in, as
this leads to a noncommutative coercion diagram whenever we let
`\Sigma_0` act on anything..
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: Sigma0(1, QQ).has_coerce_map_from(Sigma0(3, ZZ)) # indirect doctest
True
sage: Sigma0(1, ZZ).has_coerce_map_from(ZZ)
False
(If something changes that causes the last doctest above to return
True, then the entire purpose of this class is violated, and all sorts
of nasty things will go wrong with scalar multiplication of
distributions. Do not let this happen!)
"""
return (isinstance(other, Sigma0_class)
and self.level().divides(other.level())
and self.base_ring().has_coerce_map_from(other.base_ring()))
def _element_constructor_(self, x, check=True):
r"""
Construct an element of self from x.
INPUT:
- ``x`` -- something that one can make into a matrix over the
appropriate base ring
- ``check`` (boolean, default True) -- if True, then check that this
matrix actually satisfies the conditions.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(3)
sage: S([1,0,0,3]) # indirect doctest
[1 0]
[0 3]
sage: S([3,0,0,1]) # boom
Traceback (most recent call last):
...
TypeError: 3 is not a unit at 3
sage: S(Sigma0(1)([3,0,0,1]), check=False) # don't do this
[3 0]
[0 1]
"""
if isinstance(x, Sigma0Element):
x = x.matrix()
if check:
x = self._matrix_space(x)
a, b, c, d = self._adjuster(x)
for (p, e) in self._primes:
if c.valuation(p) < e:
raise TypeError("level %s^%s does not divide %s" % (p, e, c))
if a.valuation(p) != 0:
raise TypeError("%s is not a unit at %s" % (a, p))
if x.det() == 0:
raise TypeError("matrix must be nonsingular")
x.set_immutable()
return self.element_class(self, x)
def _repr_(self):
r"""
String representation of ``self``.
EXAMPLES::
sage: from sage.modular.pollack_stevens.sigma0 import Sigma0
sage: S = Sigma0(3)
sage: S._repr_()
'Monoid Sigma0(3) with coefficients in Integer Ring'
"""
return 'Monoid Sigma0(%s) with coefficients in %s' % (self.level(),
self.base_ring()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/pollack_stevens/sigma0.py | 0.88993 | 0.80456 | sigma0.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.