コード例 #1
0
    def load_mangled(cls, name, dir=None):
        r"""
        Load an object based on its standardized name.

        INPUT:

        - ``cls`` -- the class object.
        - ``name`` -- string: the file name suffix (without ".obj")
          part of the standardized name.
        - ``dir`` -- string, optional. The directory where the object
          was saved. Default is None, meaning the current directory.

        OUTPUT:

        The object that was saved in the file referred to by the
        standardized name and the directory.

        EXAMPLES:

        ::

            sage: import os
            sage: from boolean_cayley_graphs.boolean_function_improved import BooleanFunctionImproved as BFI
            sage: a = BFI([0,1,0,0])
            sage: d = tmp_dir()
            sage: a.save_mangled("a", dir=d)
            sage: b = BFI.load_mangled("a", dir=d)
            sage: a == b
            True
            sage: BFI.remove_mangled("a", dir=d)
            sage: os.rmdir(d)
        """
        return cls(load(cls.mangled_name(name, dir=dir)))
コード例 #2
0
ファイル: odlyzko.py プロジェクト: swewers/mein_sage
def zeta_zeros():
    r"""
    List of the imaginary parts of the first 2,001,052 zeros of the
    Riemann zeta function, accurate to within 4e-9.

    In order to use ``zeta_zeros()``, you will need to
    install the optional Odlyzko database package::

        sage -i database_odlyzko_zeta

    You can see a list of all available optional packages with
    ``sage --optional``.

    REFERENCES:

    - http://www.dtc.umn.edu/~odlyzko/zeta_tables/index.html

    EXAMPLES:

    The following example prints the imaginary part of the 13th
    nontrivial zero of the Riemann zeta function::

        sage: zz = zeta_zeros()  # optional - database_odlyzko_zeta
        sage: zz[12]             # optional - database_odlyzko_zeta
        59.347044003
        sage: len(zz)            # optional - database_odlyzko_zeta
        2001052
    """
    from sage.misc.verbose import verbose
    sobj = os.path.join(SAGE_SHARE, 'odlyzko', 'zeros.sobj')
    verbose("Loading Odlyzko database from " + sobj)
    return load(sobj)
コード例 #3
0
    def demo_version(self):
        r"""
        Return whether the KnotInfo databases are installed completely or
        just the demo version is used.

        EXAMPLES::

            sage: from sage.databases.knotinfo_db import KnotInfoDataBase
            sage: ki_db = KnotInfoDataBase()
            sage: ki_db.demo_version()       # optional - database_knotinfo
            False
        """
        if self._demo is None:
            if self._feature.is_present():
                num_knots_file = os.path.join(
                    self._sobj_path,
                    self.filename.knots.num_knots(self.version()))
                from builtins import FileNotFoundError
                try:
                    self._num_knots = load(num_knots_file)
                except FileNotFoundError:
                    self.create_filecache()
                self._demo = False
            else:
                self._demo = True
                self._num_knots = len(
                    [v for v in row_demo_sample.values() if v[1] == 1])
        return self._demo
コード例 #4
0
 def dict(self):
     """
     Return the already computed values
     """
     import glob
     return dict(
         persist.load(name)
         for name in glob.glob("%s*.sobj" % self._prefix))
コード例 #5
0
    def _sage_(self):
        """
        Return local copy of self.

        EXAMPLES::

            sage: sr = mq.SR(allow_zero_inversions=True)
            sage: F,s = sr.polynomial_system()
            sage: F == sage0(F)._sage_()
            True
        """
        P = self.parent()
        if P.is_remote():
            P.eval('save({}, {!r})'.format(self.name(), P._remote_tmpfile()))
            P._get_tmpfile_from_server(self)
            return load(P._local_tmp_file())
        else:
            P.eval('save({}, {!r})'.format(self.name(), P._local_tmpfile()))
            return load(P._local_tmpfile())
コード例 #6
0
ファイル: cunningham_tables.py プロジェクト: sagemath/sage
def cunningham_prime_factors():
    r"""
    List of all the prime numbers occuring in the so called Cunningham table.

    They occur in the factorization of numbers of type $b^n+1$ or $b^n-1$ with $b \in \{2,3,5,6,7,10,11,12\}$.

    Data from http://cage.ugent.be/~jdemeyer/cunningham/
    """
    file = os.path.join(SAGE_SHARE,'cunningham_tables','cunningham_prime_factors.sobj')
    if os.path.exists(file):
        return [Integer(_) for _ in load(file)]
    else:
        from warnings import warn
        warn("You might consider installing the optional package for factoring Cunningham numbers with the following command: ``sage -i cunningham_tables``")
        return []
コード例 #7
0
    def __call__(self, *args, **kwds):
        key = self.key(*args, **kwds)
        h = self._hash(key)
        name = '%s_%s.sobj' % (self._prefix, h)

        if os.path.exists(name):
            key2, val = persist.load(name)
            if key == key2:
                # We save and test equality of keys to avoid
                # the (extremely remote) possibility of a hash
                # collision.  Correctness is crucial in mathematics.
                return val

        val = self._func(*args, **kwds)
        persist.save((key, val), name)
        return val
コード例 #8
0
ファイル: cunningham_tables.py プロジェクト: timgates42/sage
def cunningham_prime_factors():
    r"""
    List of all the prime numbers occurring in the so called Cunningham table.

    They occur in the factorization of numbers of type $b^n+1$ or $b^n-1$ with $b \in \{2,3,5,6,7,10,11,12\}$.

    Data from http://cage.ugent.be/~jdemeyer/cunningham/
    """
    file = os.path.join(SAGE_SHARE, 'cunningham_tables',
                        'cunningham_prime_factors.sobj')
    if os.path.exists(file):
        return [Integer(_) for _ in load(file)]
    else:
        from warnings import warn
        warn(
            "You might consider installing the optional package for factoring Cunningham numbers with the following command: ``sage -i cunningham_tables``"
        )
        return []
コード例 #9
0
    def read_column_dict(self):
        r"""
        Read the dictionary for the column names from the according sobj-file

        OUTPUT:

        A python dictionary containing the column names and types

        EXAMPLES::

            sage: from sage.databases.knotinfo_db import KnotInfoDataBase
            sage: ki_db = KnotInfoDataBase()
            sage: len(ki_db.read_column_dict()) > 120       # optional - database_knotinfo
            True
        """
        if self.demo_version():
            return column_demo_sample
        sobj_path = self._sobj_path
        filename = self.filename.knots.sobj_column()
        return load('%s/%s' % (sobj_path, filename))
コード例 #10
0
ファイル: jones.py プロジェクト: sagemath/sage
    def get(self, S, var='a'):
        """
        Return all fields in the database ramified exactly at
        the primes in S.

        INPUT:

        -  ``S`` - list or set of primes, or a single prime

        -  ``var`` - the name used for the generator of the number fields (default 'a').

        EXAMPLES::

            sage: J = JonesDatabase()              # optional - database_jones_numfield
            sage: J.get(163, var='z')              # optional - database_jones_numfield
            [Number Field in z with defining polynomial x^2 + 163,
             Number Field in z with defining polynomial x^3 - x^2 - 54*x + 169,
             Number Field in z with defining polynomial x^4 - x^3 - 7*x^2 + 2*x + 9]
            sage: J.get([3, 4])                    # optional - database_jones_numfield
            Traceback (most recent call last):
            ...
            ValueError: S must be a list of primes
        """
        if self.root is None:
            if os.path.exists(JONESDATA + "/jones.sobj"):
                self.root = load(JONESDATA + "/jones.sobj")
            else:
                raise PackageNotFoundError("database_jones_numfield")
        try:
            S = list(S)
        except TypeError:
            S = [S]
        if not all(p.is_prime() for p in S):
            raise ValueError("S must be a list of primes")
        S.sort()
        s = tuple(S)
        if s not in self.root:
            return []
        return [NumberField(f, var, check=False) for f in self.root[s]]
コード例 #11
0
    def get(self, S, var='a'):
        """
        Return all fields in the database ramified exactly at
        the primes in S.

        INPUT:

        -  ``S`` - list or set of primes, or a single prime

        -  ``var`` - the name used for the generator of the number fields (default 'a').

        EXAMPLES::

            sage: J = JonesDatabase()              # optional - database_jones_numfield
            sage: J.get(163, var='z')              # optional - database_jones_numfield
            [Number Field in z with defining polynomial x^2 + 163,
             Number Field in z with defining polynomial x^3 - x^2 - 54*x + 169,
             Number Field in z with defining polynomial x^4 - x^3 - 7*x^2 + 2*x + 9]
            sage: J.get([3, 4])                    # optional - database_jones_numfield
            Traceback (most recent call last):
            ...
            ValueError: S must be a list of primes
        """
        if self.root is None:
            if os.path.exists(JONESDATA + "/jones.sobj"):
                self.root = load(JONESDATA + "/jones.sobj")
            else:
                raise PackageNotFoundError("database_jones_numfield")
        try:
            S = list(S)
        except TypeError:
            S = [S]
        if not all([p.is_prime() for p in S]):
            raise ValueError("S must be a list of primes")
        S.sort()
        s = tuple(S)
        if s not in self.root:
            return []
        return [NumberField(f, var, check=False) for f in self.root[s]]
コード例 #12
0
    def read_row_dict(self):
        r"""
        Read the dictionary for the row names that is the knot and link names
        from the according sobj-file

        OUTPUT:

        A python dictionary containing the names of the knots and links
        together with their table index and the corresponding number of
        components

        EXAMPLES::

            sage: from sage.databases.knotinfo_db import KnotInfoDataBase
            sage: ki_db = KnotInfoDataBase()
            sage: ki_db.read_row_dict()['K7_1']
            [8, 1]
        """
        if self.demo_version():
            return row_demo_sample
        sobj_path = self._sobj_path
        filename = self.filename.knots.sobj_row()
        return load('%s/%s' % (sobj_path, filename))
コード例 #13
0
    def read(self, column):
        r"""
        Access a column of KnotInfo / LinkInfo

        INPUT:

        ``column`` -- instance of enum :class:`KnotInfoColumns`
          to select the data to be read in

        OUTPUT:

        A python list containing the data corresponding to the column.

        EXAMPLES::

            sage: from sage.databases.knotinfo_db import KnotInfoDataBase
            sage: ki_db = KnotInfoDataBase()
        """
        if not isinstance(column, KnotInfoColumns):
            raise TypeError('column must be an instance of enum %s' %
                            (KnotInfoColumns))

        if self.demo_version():
            return data_demo_sample[column]

        sobj_path = self._sobj_path
        if column.column_type() == column.types.OnlyLinks:
            filename = self.filename.links.sobj_data(column)
        else:
            filename = self.filename.knots.sobj_data(column)

        verbose('loading data library %s ...' % (filename))
        res = load('%s/%s' % (sobj_path, filename))
        verbose('... finished!')

        return res
コード例 #14
0
ファイル: hgm.py プロジェクト: edgarcosta/amortizedHGM
from sage.misc.misc_c import prod
from sage.misc.persist import load
from sage.modular.hypergeometric_motive import enumerate_hypergeometric_data, HypergeometricData
from sage.modules.free_module_element import vector
from sage.rings.fast_arith import prime_range
from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ


# for pyflakes
def mbound_dict_c(indices, start, end):
    pass


load(path.join(path.dirname(path.abspath(__file__)), "hgm_misc.pyx"))


# for pyflakes
def remainder_forest(M,
                     m,
                     k,
                     kbase=0,
                     indices=None,
                     V=None,
                     ans=None,
                     kappa=None):
    pass


load(path.join(path.dirname(path.abspath(__file__)), "average_poly.pyx"))
コード例 #15
0
    def _create_data_sobj(self, sobj_path=None):
        r"""
        Create ``sobj`` files containing the contents of the whole table.
        To each column there is created one file containing a list of
        strings giving the entries of the database table.

        The length of these lists depends on the type of the corresponding
        column. If a column is used in both tables
        (``KnotInfoColumnTypes.KnotsAndLinks``) the list of proper links
        is appended to the list of knots.  In both other cases the lenght
        of the list corresponds to the number of listed knots and proper
        links respectively.

        EXAMPLES::

            sage: from sage.databases.knotinfo_db import KnotInfoDataBase
            sage: ki_db = KnotInfoDataBase()
            sage: ki_db._create_data_sobj() # not tested (just used on installation)
        """
        knot_list = self.knot_list()
        link_list = self.link_list()
        len_knots = len(knot_list)
        len_links = len(link_list)

        row_dict = {}

        if not sobj_path:
            sobj_path = self._sobj_path

        # ----------------------------------------------------------------
        # Columns that exist for knots and links
        # ----------------------------------------------------------------
        column_dict = load('%s/%s' %
                           (sobj_path, self.filename.knots.sobj_column()))
        cols = KnotInfoColumns('ColsTemp', column_dict)
        for col in cols:
            val_list = []

            if col.column_type() != col.types.OnlyLinks:
                for i in range(1, len_knots):
                    if col.name == self._names_column:
                        row_dict[self._knot_prefix +
                                 knot_list[i][col.name]] = [i - 1, 1]

                    val_list.append(knot_list[i][col.name])

            if col.column_type() != col.types.OnlyKnots:
                for i in range(1, len_links):
                    if col.name == self._names_column:
                        link_name = link_list[i][col.name]
                        link_name = link_name.replace('{', '_')
                        link_name = link_name.replace(',', '_')
                        link_name = link_name.replace('}', '')

                        num_comp = int(link_list[i][self._components_column])
                        row_dict[link_name] = [i + len_knots - 2, num_comp]

                    val_list.append(link_list[i][col.name])

            if val_list:
                save(val_list,
                     '%s/%s' % (sobj_path, self.filename.knots.sobj_data(col)))

        save(row_dict, '%s/%s' % (sobj_path, self.filename.knots.sobj_row()))