def translation_length(self):  #UHP
        r"""
        For hyperbolic elements, return the translation length;
        otherwise, raise a ``ValueError``.

        EXAMPLES::

            sage: UHP = HyperbolicPlane().UHP()
            sage: UHP.get_isometry(matrix(2,[2,0,0,1/2])).translation_length()
            2*arccosh(5/4)

        ::

            sage: H = UHP.isometry_from_fixed_points(-1,1)
            sage: p = UHP.get_point(exp(i*7*pi/8))
            sage: Hp = H(p)
            sage: bool((UHP.dist(p, Hp) - H.translation_length()) < 10**-9)
            True
        """
        d = sqrt(self._matrix.det()**2)
        tau = sqrt((self._matrix / sqrt(d)).trace()**2)
        if self.classification() in [
                'hyperbolic', 'orientation-reversing hyperbolic'
        ]:
            return 2 * arccosh(tau / 2)
        raise TypeError(
            "translation length is only defined for hyperbolic transformations"
        )
Пример #2
0
    def _derivative_(self, n, z, m, diff_param):
        """
        EXAMPLES::

            sage: n,z,m = var('n,z,m')
            sage: elliptic_pi(n,z,m).diff(n)
            1/4*(sqrt(-m*sin(z)^2 + 1)*n*sin(2*z)/(n*sin(z)^2 - 1)
            + 2*(m - n)*elliptic_f(z, m)/n
            + 2*(n^2 - m)*elliptic_pi(n, z, m)/n
            + 2*elliptic_e(z, m))/((m - n)*(n - 1))
            sage: elliptic_pi(n,z,m).diff(z)
            -1/(sqrt(-m*sin(z)^2 + 1)*(n*sin(z)^2 - 1))
            sage: elliptic_pi(n,z,m).diff(m)
            1/4*(m*sin(2*z)/(sqrt(-m*sin(z)^2 + 1)*(m - 1))
            - 2*elliptic_e(z, m)/(m - 1)
            - 2*elliptic_pi(n, z, m))/(m - n)
        """
        if diff_param == 0:
            return ((Integer(1) / (Integer(2) * (m - n) * (n - Integer(1)))) *
                    (elliptic_e(z, m) + ((m - n) / n) * elliptic_f(z, m) +
                     ((n**Integer(2) - m) / n) * elliptic_pi(n, z, m) -
                     (n * sqrt(Integer(1) - m * sin(z)**Integer(2)) *
                      sin(Integer(2) * z)) /
                     (Integer(2) * (Integer(1) - n * sin(z)**Integer(2)))))
        elif diff_param == 1:
            return (Integer(1) /
                    (sqrt(Integer(1) - m * sin(z)**Integer(Integer(2))) *
                     (Integer(1) - n * sin(z)**Integer(2))))
        elif diff_param == 2:
            return ((Integer(1) / (Integer(2) * (n - m))) * (
                elliptic_e(z, m) / (m - Integer(1)) + elliptic_pi(n, z, m) -
                (m * sin(Integer(2) * z)) /
                (Integer(2) *
                 (m - Integer(1)) * sqrt(Integer(1) - m * sin(z)**Integer(2))))
                    )
Пример #3
0
    def _derivative_(self, u, m, diff_param):
        """
        EXAMPLES::

            sage: x,m = var('x,m')
            sage: elliptic_eu(x,m).diff(x)
            sqrt(-m*jacobi_sn(x, m)^2 + 1)*jacobi_dn(x, m)
            sage: elliptic_eu(x,m).diff(m)
            1/2*(elliptic_eu(x, m)
             - elliptic_f(jacobi_am(x, m), m))/m
             - 1/2*(m*jacobi_cn(x, m)*jacobi_sn(x, m)
             - (m - 1)*x
             - elliptic_eu(x, m)*jacobi_dn(x, m))*sqrt(-m*jacobi_sn(x, m)^2 + 1)/((m - 1)*m)
        """
        from sage.functions.jacobi import jacobi, jacobi_am
        if diff_param == 0:
            return (sqrt(-m * jacobi('sn', u, m)**Integer(2) + Integer(1)) *
                    jacobi('dn', u, m))
        elif diff_param == 1:
            return (Integer(1) / Integer(2) *
                    (elliptic_eu(u, m) - elliptic_f(jacobi_am(u, m), m)) / m -
                    Integer(1) / Integer(2) *
                    sqrt(-m * jacobi('sn', u, m)**Integer(2) + Integer(1)) *
                    (m * jacobi('sn', u, m) * jacobi('cn', u, m) -
                     (m - Integer(1)) * u -
                     elliptic_eu(u, m) * jacobi('dn', u, m)) /
                    ((m - Integer(1)) * m))
    def __eq__(self, other):
        r"""
        Return ``True`` if the isometries are the same and ``False`` otherwise.

        EXAMPLES::

            sage: UHP = HyperbolicPlane().UHP()
            sage: A = UHP.get_isometry(identity_matrix(2))
            sage: B = UHP.get_isometry(-identity_matrix(2))
            sage: A == B
            True

            sage: HM = HyperbolicPlane().HM()
            sage: A = HM.random_isometry()
            sage: A == A
            True
        """
        if not isinstance(other, HyperbolicIsometry):
            return False
        test_matrix = bool((self.matrix() - other.matrix()).norm() < EPSILON)
        if self.domain().is_isometry_group_projective():
            A, B = self.matrix(), other.matrix()  # Rename for simplicity
            m = self.matrix().ncols()
            A = A / sqrt(A.det(), m)  # Normalized to have determinant 1
            B = B / sqrt(B.det(), m)
            test_matrix = ((A - B).norm() < EPSILON
                           or (A + B).norm() < EPSILON)
        return self.domain() is other.domain() and test_matrix
Пример #5
0
def SO21_to_SL2R(M):
    r"""
    A homomorphism from `SO(2, 1)` to `SL(2, \RR)`.

    Note that this is not the only homomorphism, but it is the only one
    that works in the context of the implemented 2D hyperbolic geometry
    models.

    EXAMPLES::

        sage: from sage.geometry.hyperbolic_space.hyperbolic_coercion import SO21_to_SL2R
        sage: (SO21_to_SL2R(identity_matrix(3)) - identity_matrix(2)).norm() < 10**-4
        True
    """
    ####################################################################
    # SL(2,R) is the double cover of SO (2,1)^+, so we need to choose  #
    # a lift.  I have formulas for the absolute values of each entry   #
    # a,b ,c,d of the lift matrix(2,[a,b,c,d]), but we need to choose  #
    # one entry to be positive.  I choose d for no particular reason,  #
    # unless d = 0, then we choose c > 0.  The basic strategy for this #
    # function is to find the linear map induced by the SO(2,1)        #
    # element on the Lie algebra sl(2, R).  This corresponds to the    #
    # Adjoint action by a matrix A or -A in SL(2,R).  To find which    #
    # matrix let X,Y,Z be a basis for sl(2,R) and look at the images   #
    # of X,Y,Z as well as the second and third standard basis vectors  #
    # for 2x2 matrices (these are traceless, so are in the Lie         #
    # algebra).  These corresponds to AXA^-1 etc and give formulas     #
    # for the entries of A.                                            #
    ####################################################################
    (m_1, m_2, m_3, m_4, m_5, m_6, m_7, m_8, m_9) = M.list()
    d = sqrt(
        Integer(1) / Integer(2) * m_5 - Integer(1) / Integer(2) * m_6 -
        Integer(1) / Integer(2) * m_8 + Integer(1) / Integer(2) * m_9)
    if M.det() > 0:  # EPSILON?
        det_sign = 1
    elif M.det() < 0:  # EPSILON?
        det_sign = -1
    if d > 0:  # EPSILON?
        c = (-Integer(1) / Integer(2) * m_4 +
             Integer(1) / Integer(2) * m_7) / d
        b = (-Integer(1) / Integer(2) * m_2 +
             Integer(1) / Integer(2) * m_3) / d
        ad = det_sign * 1 + b * c  # ad - bc = pm 1
        a = ad / d
    else:  # d is 0, so we make c > 0
        c = sqrt(-Integer(1) / Integer(2) * m_5 -
                 Integer(1) / Integer(2) * m_6 +
                 Integer(1) / Integer(2) * m_8 + Integer(1) / Integer(2) * m_9)
        d = (-Integer(1) / Integer(2) * m_4 +
             Integer(1) / Integer(2) * m_7) / c
        # d = 0, so ad - bc = -bc = pm 1.
        b = -(det_sign * 1) / c
        a = (Integer(1) / Integer(2) * m_4 + Integer(1) / Integer(2) * m_7) / b
    A = matrix(2, [a, b, c, d])
    return A
Пример #6
0
    def _eval_(self, n, m, theta, phi, **kwargs):
        r"""
        TESTS::

            sage: x, y = var('x y')
            sage: spherical_harmonic(1, 2, x, y)
            0
            sage: spherical_harmonic(1, -2, x, y)
            0
            sage: spherical_harmonic(1/2, 2, x, y)
            spherical_harmonic(1/2, 2, x, y)
            sage: spherical_harmonic(3, 2, x, y)
            1/8*sqrt(30)*sqrt(7)*cos(x)*e^(2*I*y)*sin(x)^2/sqrt(pi)
            sage: spherical_harmonic(3, 2, 1, 2)
            1/8*sqrt(30)*sqrt(7)*cos(1)*e^(4*I)*sin(1)^2/sqrt(pi)
            sage: spherical_harmonic(3 + I, 2., 1, 2)
            -0.351154337307488 - 0.415562233975369*I

        Check that :trac:`20939` is fixed::

            sage: ex = spherical_harmonic(3,2,1,2*pi/3)
            sage: QQbar(ex * sqrt(pi)/cos(1)/sin(1)^2).minpoly()
            x^4 + 105/32*x^2 + 11025/1024

        Check whether :trac:`25034` yields correct results compared to Maxima::

            sage: spherical_harmonic(1,1,pi/3,pi/6).n() # abs tol 1e-14
            0.259120612103502 + 0.149603355150537*I
            sage: maxima.spherical_harmonic(1,1,pi/3,pi/6).n() # abs tol 1e-14
            0.259120612103502 + 0.149603355150537*I
            sage: spherical_harmonic(1,-1,pi/3,pi/6).n() # abs tol 1e-14
            -0.259120612103502 + 0.149603355150537*I
            sage: maxima.spherical_harmonic(1,-1,pi/3,pi/6).n() # abs tol 1e-14
            -0.259120612103502 + 0.149603355150537*I

        """
        if n in ZZ and m in ZZ and n > -1:
            if abs(m) > n:
                return ZZ(0)
            if m == 0 and theta.is_zero():
                return sqrt((2 * n + 1) / 4 / pi)
            from sage.arith.misc import factorial
            from sage.functions.trig import cos
            from sage.functions.orthogonal_polys import gen_legendre_P
            return (sqrt(
                factorial(n - m) * (2 * n + 1) / (4 * pi * factorial(n + m))) *
                    exp(I * m * phi) * gen_legendre_P(n, m, cos(theta)) *
                    (-1)**m).simplify_trig()
Пример #7
0
def solve_degree2_to_integer_range(a, b, c):
    r"""
    Returns the greatest integer range `[i_1, i_2]` such that
    `i_1 > x_1` and `i_2 < x_2` where `x_1, x_2` are the two zeroes of the equation in `x`:
    `ax^2+bx+c=0`.

    If there is no real solution to the equation, it returns an empty range with negative coefficients.

    INPUT:

    - ``a``, ``b`` and ``c`` -- coefficients of a second degree equation, ``a`` being the coefficient of
      the higher degree term.

    EXAMPLES::

        sage: from sage.coding.guruswami_sudan.utils import solve_degree2_to_integer_range
        sage: solve_degree2_to_integer_range(1, -5, 1)
        (1, 4)

    If there is no real solution::

        sage: solve_degree2_to_integer_range(50, 5, 42)
        (-2, -1)
    """
    D = b**2 - 4 * a * c
    if D < 0:
        return (-2, -1)
    sD = float(sqrt(D))
    minx, maxx = (-b - sD) / 2.0 / a, (-b + sD) / 2.0 / a
    mini, maxi = (ligt(minx), gilt(maxx))
    if mini > maxi:
        return (-2, -1)
    else:
        return (mini, maxi)
        def _base(j, k, c):

            assert k - j == 1
            aajk = subbasis(j, k)
            assert all(a.order() in (1, p) for a in aajk)
            idxs = [i for i, a in enumerate(aajk) if a.order() == p]

            rs = [([0], [0]) for i in range(len(aajk))]
            for i in range(len(idxs)):
                rs[idxs[i]] = (range(p), [0]) if i % 2 else ([0], range(p))
            if len(idxs) % 2:
                m = ceil(sqrt(p))
                rs[idxs[-1]] = range(0, p, m), range(m)

            tab = {}
            for x in iproduct(*(r for r, _ in rs)):
                key = dotprod(x, aajk)
                if hasattr(key, 'set_immutable'):
                    key.set_immutable()
                tab[key] = vector(x)
            for y in iproduct(*(r for _, r in rs)):
                key = c - dotprod(y, aajk)
                if hasattr(key, 'set_immutable'):
                    key.set_immutable()
                if key in tab:
                    return tab[key] + vector(y)

            raise TypeError('Not in group')
Пример #9
0
    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))
Пример #10
0
    def __init__(self, n, instance='key', m=None):
        """
        Construct LWE instance parameterised by security parameter ``n`` where
        all other parameters are chosen as in [CGW2013]_.

        INPUT:

        - ``n`` - security parameter (integer >= 89)
        - ``instance`` - one of

          - "key" - the LWE-instance that hides the secret key is generated
          - "encrypt" - the LWE-instance that hides the message is generated
            (default: ``key``)

        - ``m`` - number of allowed samples or ``None`` in which case ``m`` is
          chosen as in [CGW2013]_.  (default: ``None``)

        EXAMPLES::

            sage: from sage.crypto.lwe import UniformNoiseLWE
            sage: UniformNoiseLWE(89)
            LWE(89, 64311834871, UniformSampler(0, 6577), 'noise', 131)

            sage: UniformNoiseLWE(89, instance='encrypt')
            LWE(131, 64311834871, UniformSampler(0, 11109), 'noise', 181)
        """

        if n < 89:
            raise TypeError("Parameter too small")

        n2 = n
        C = 4 / sqrt(2 * pi)
        kk = floor((n2 - 2 * log(n2, 2)**2) / 5)
        n1 = (3 * n2 - 5 * kk) // 2
        ke = floor((n1 - 2 * log(n1, 2)**2) / 5)
        l = (3 * n1 - 5 * ke) // 2 - n2
        sk = ceil((C * (n1 + n2))**(ZZ(3) / 2))
        se = ceil((C * (n1 + n2 + l))**(ZZ(3) / 2))
        q = next_prime(
            max(ceil((4 * sk)**(ZZ(n1 + n2) / n1)),
                ceil((4 * se)**(ZZ(n1 + n2 + l) / (n2 + l))),
                ceil(4 * (n1 + n2) * se * sk + 4 * se + 1)))

        if kk <= 0:
            raise TypeError("Parameter too small")

        if instance == 'key':
            D = UniformSampler(0, sk - 1)
            if m is None:
                m = n1
            LWE.__init__(self, n=n2, q=q, D=D, secret_dist='noise', m=m)
        elif instance == 'encrypt':
            D = UniformSampler(0, se - 1)
            if m is None:
                m = n2 + l
            LWE.__init__(self, n=n1, q=q, D=D, secret_dist='noise', m=m)
        else:
            raise TypeError("Parameter instance=%s not understood." %
                            (instance))
    def _2x2_matrix_entries(self, beta):
        r"""
        Young's representations are constructed by combining
        `2 \times 2`-matrices that depend on ``beta``.

        For the orthogonal representation, this is the following matrix::

            [     -beta       sqrt(1-beta^2) ]
            [ sqrt(1-beta^2)       beta      ]

        EXAMPLES::

            sage: orth = SymmetricGroupRepresentation([2,1], "orthogonal")
            sage: orth._2x2_matrix_entries(1/2)
            (-1/2, 1/2*sqrt(3), 1/2*sqrt(3), 1/2)
        """
        return (-beta, sqrt(1 - beta**2), sqrt(1 - beta**2), beta)
    def __lalg__(self, D):
        r"""
        For positive `D`, this function evaluates the quotient
        `L(E_D,1)\cdot \sqrt(D)/\Omega_E` where `E_D` is the twist of
        `E` by `D`, `\Omega_E` is the least positive period of `E`.

        For negative `E`, it is the quotient
        `L(E_D,1)\cdot \sqrt(-D)/\Omega^{-}_E`
        where `\Omega^{-}_E` is the least positive imaginary part of a
        non-real period of `E`.

        EXAMPLES::

            sage: E = EllipticCurve('11a1')
            sage: m = E.modular_symbol(sign=+1, implementation='sage')
            sage: m.__lalg__(1)
            1/5
            sage: m.__lalg__(3)
            5/2
        """
        from sage.misc.functional import sqrt
        # the computation of the L-value could take a lot of time,
        # but then the conductor is so large
        # that the computation of modular symbols for E took even longer

        E = self._E
        ED = E.quadratic_twist(D)
        lv = ED.lseries().L_ratio(
        )  # this is L(ED,1) divided by the Néron period omD of ED
        lv *= ED.real_components()  # now it is by the least positive period
        omD = ED.period_lattice().basis()[0]
        if D > 0:
            om = E.period_lattice().basis()[0]
            q = sqrt(D) * omD / om * 8
        else:
            om = E.period_lattice().basis()[1].imag()
            if E.real_components() == 1:
                om *= 2
            q = sqrt(-D) * omD / om * 8

        # see padic_lseries.pAdicLeries._quotient_of_periods_to_twist
        # for the explanation of the second factor
        verbose('real approximation is %s' % q)
        return lv / 8 * QQ(q.round())
Пример #13
0
    def _derivative_(self, x, diff_param=None):
        """
        Derivative of erfc function.

        EXAMPLES::

            sage: erfc(x).diff(x)
            -2*e^(-x^2)/sqrt(pi)
        """
        return -2*exp(-x**2)/sqrt(pi)
Пример #14
0
    def __init__(self, N, delta=0.01, m=None):
        """
        Construct a Ring-LWE oracle in dimension ``n=phi(N)`` where
        the modulus ``q`` and the ``stddev`` of the noise is chosen as in
        [LP2011]_.

        INPUT:

        - ``N`` - index of cyclotomic polynomial (integer > 0, must be power of 2)
        - ``delta`` - error probability per symbol (default: 0.01)
        - ``m`` - number of allowed samples or ``None`` in which case ``3*n`` is
          used (default: ``None``)

        EXAMPLES::

            sage: from sage.crypto.lwe import RingLindnerPeikert
            sage: RingLindnerPeikert(N=16)
            RingLWE(16, 1031, Discrete Gaussian sampler for polynomials of degree < 8 with σ=2.803372 in each component, x^8 + 1, 'noise', 24)
        """
        n = euler_phi(N)
        if m is None:
            m = 3 * n
        # Find c>=1 such that c*exp((1-c**2)/2))**(2*n) == 2**-40
        #  i.e c>=1 such that 2*n*log(c)+n*(1-c**2) + 40*log(2) == 0
        c = SR.var('c')
        c = find_root(2 * n * log(c) + n * (1 - c**2) + 40 * log(2) == 0, 1,
                      10)
        # Upper bound on s**2/t
        s_t_bound = (sqrt(2) * pi / c / sqrt(2 * n * log(2 / delta))).n()
        # Interpretation of "choose q just large enough to allow for a Gaussian parameter s>=8" in [LP2011]_
        q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
        # Gaussian parameter as defined in [LP2011]_
        s = sqrt(s_t_bound * floor(q / 4))
        # Transform s into stddev
        stddev = s / sqrt(2 * pi.n())
        D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], n, stddev)
        RingLWE.__init__(self,
                         N=N,
                         q=q,
                         D=D,
                         poly=None,
                         secret_dist='noise',
                         m=m)
Пример #15
0
    def _derivative_(self, x, diff_param=None):
        """
        Derivative of inverse erf function.

        EXAMPLES::

            sage: erfinv(x).diff(x)
            1/2*sqrt(pi)*e^(erfinv(x)^2)
        """
        return sqrt(pi)*exp(erfinv(x)**2)/2
Пример #16
0
    def __init__(self, n, delta=0.01, m=None):
        """
        Construct LWE instance parameterised by security parameter ``n`` where
        the modulus ``q`` and the ``stddev`` of the noise is chosen as in
        [LP2011]_.

        INPUT:

        - ``n`` - security parameter (integer > 0)
        - ``delta`` - error probability per symbol (default: 0.01)
        - ``m`` - number of allowed samples or ``None`` in which case ``m=2*n +
          128`` as in [LP2011]_ (default: ``None``)

        EXAMPLES::

            sage: from sage.crypto.lwe import LindnerPeikert
            sage: LindnerPeikert(n=20)
            LWE(20, 2053, Discrete Gaussian sampler over the Integers with sigma = 3.600954 and c = 0, 'noise', 168)
        """
        if m is None:
            m = 2 * n + 128
        # Find c>=1 such that c*exp((1-c**2)/2))**(2*n) == 2**-40
        #         (c*exp((1-c**2)/2))**(2*n) == 2**-40
        #    log((c*exp((1-c**2)/2))**(2*n)) == -40*log(2)
        #       (2*n)*log(c*exp((1-c**2)/2)) == -40*log(2)
        #  2*n*(log(c)+log(exp((1-c**2)/2))) == -40*log(2)
        #            2*n*(log(c)+(1-c**2)/2) == -40*log(2)
        #              2*n*log(c)+n*(1-c**2) == -40*log(2)
        #  2*n*log(c)+n*(1-c**2) + 40*log(2) == 0
        c = SR.var('c')
        c = find_root(2 * n * log(c) + n * (1 - c**2) + 40 * log(2) == 0, 1,
                      10)
        # Upper bound on s**2/t
        s_t_bound = (sqrt(2) * pi / c / sqrt(2 * n * log(2 / delta))).n()
        # Interpretation of "choose q just large enough to allow for a Gaussian parameter s>=8" in [LP2011]_
        q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
        # Gaussian parameter as defined in [LP2011]_
        s = sqrt(s_t_bound * floor(q / 4))
        # Transform s into stddev
        stddev = s / sqrt(2 * pi.n())
        D = DiscreteGaussianDistributionIntegerSampler(stddev)
        LWE.__init__(self, n=n, q=q, D=D, secret_dist='noise', m=m)
Пример #17
0
    def _derivative_(self, z, m, diff_param):
        """
        EXAMPLES::

            sage: x,m = var('x,m')
            sage: elliptic_f(x,m).diff(x)
            1/sqrt(-m*sin(x)^2 + 1)
            sage: elliptic_f(x,m).diff(m)
            -1/2*elliptic_f(x, m)/m
            + 1/4*sin(2*x)/(sqrt(-m*sin(x)^2 + 1)*(m - 1))
            - 1/2*elliptic_e(x, m)/((m - 1)*m)
        """
        if diff_param == 0:
            return Integer(1) / sqrt(Integer(1) - m * sin(z)**Integer(2))
        elif diff_param == 1:
            return (elliptic_e(z, m) / (Integer(2) * (Integer(1) - m) * m) -
                    elliptic_f(z, m) / (Integer(2) * m) -
                    (sin(Integer(2) * z) /
                     (Integer(4) * (Integer(1) - m) *
                      sqrt(Integer(1) - m * sin(z)**Integer(2)))))
Пример #18
0
    def _derivative_(self, x, diff_param=None):
        """
        Derivative of erfi function.

        EXAMPLES::

            sage: erfi(x).diff(x)
            2*e^(x^2)/sqrt(pi)

        """
        return 2*exp(x**2)/sqrt(pi)
Пример #19
0
    def image_coordinates(self, x):
        """
        Return the image of the coordinates of the hyperbolic point ``x``
        under ``self``.

        EXAMPLES::

            sage: KM = HyperbolicPlane().KM()
            sage: UHP = HyperbolicPlane().UHP()
            sage: phi = UHP.coerce_map_from(KM)
            sage: phi.image_coordinates((0, 0))
            I
            sage: phi.image_coordinates((0, 1))
            +Infinity
        """
        if tuple(x) == (0, 1):
            return infinity
        return (-x[0] / (x[1] - 1) + I *
                (-(sqrt(-x[0]**2 - x[1]**2 + 1) - x[0]**2 - x[1]**2 + 1) /
                 ((x[1] - 1) * sqrt(-x[0]**2 - x[1]**2 + 1) + x[1] - 1)))
Пример #20
0
def elias_bound_asymp(delta, q):
    r"""
    The asymptotic Elias bound for the information rate.

    This only makes sense when `0 < \delta < 1-1/q`.

    EXAMPLES::

        sage: codes.bounds.elias_bound_asymp(1/4,2)
        0.39912396330...
    """
    r = 1 - 1 / q
    return RDF((1 - entropy(r - sqrt(r * (r - delta)), q)))
Пример #21
0
    def standard_deviation(self):
        r"""
        The standard deviation of the discrete random variable.

        Let `S` be the probability space of `X` = self,
        with probability function `p`, and `E(X)` be the
        expectation of `X`. Then the standard deviation of
        `X` is defined to be

        .. math::

                     \sigma(X) = \sqrt{ \sum_{x \in S} p(x) (X(x) - E(x))**2}
        """
        return sqrt(self.variance())
Пример #22
0
def mrrw1_bound_asymp(delta, q):
    r"""
    The first asymptotic McEliese-Rumsey-Rodemich-Welsh bound.

    This only makes sense when `0 < \delta < 1-1/q`.

    EXAMPLES::

        sage: codes.bounds.mrrw1_bound_asymp(1/4,2)   # abs tol 4e-16
        0.3545789026652697
    """
    return RDF(
        entropy((q - 1 - delta * (q - 2) - 2 * sqrt(
            (q - 1) * delta * (1 - delta))) / q, q))
Пример #23
0
    def _derivative_(self, z, m, diff_param):
        """
        EXAMPLES::

            sage: x,z = var('x,z')
            sage: elliptic_e(z, x).diff(z, 1)
            sqrt(-x*sin(z)^2 + 1)
            sage: elliptic_e(z, x).diff(x, 1)
            1/2*(elliptic_e(z, x) - elliptic_f(z, x))/x
        """
        if diff_param == 0:
            return sqrt(Integer(1) - m * sin(z)**Integer(2))
        elif diff_param == 1:
            return (elliptic_e(z, m) - elliptic_f(z, m)) / (Integer(2) * m)
Пример #24
0
 def standard_deviation(self):
     r"""
     The standard deviation of the discrete random variable.
     
     Let `S` be the probability space of `X` = self,
     with probability function `p`, and `E(X)` be the
     expectation of `X`. Then the standard deviation of
     `X` is defined to be
     
     .. math::
     
                  \sigma(X) = \sqrt{ \sum_{x \in S} p(x) (X(x) - E(x))**2}
     """
     return sqrt(self.variance())
Пример #25
0
 def translation_standard_deviation(self, map):
     r"""
     The standard deviation of the translated discrete random variable
     `X \circ e`, where `X` = self and `e` =
     map.
     
     Let `S` be the probability space of `X` = self,
     with probability function `p`, and `E(X)` be the
     expectation of `X`. Then the standard deviation of
     `X` is defined to be
     
     .. math::
     
                  \sigma(X) = \sqrt{ \sum_{x \in S} p(x) (X(x) - E(x))**2}
     """
     return sqrt(self.translation_variance(map))
Пример #26
0
    def translation_standard_deviation(self, map):
        r"""
        The standard deviation of the translated discrete random variable
        `X \circ e`, where `X` = self and `e` =
        map.

        Let `S` be the probability space of `X` = self,
        with probability function `p`, and `E(X)` be the
        expectation of `X`. Then the standard deviation of
        `X` is defined to be

        .. math::

                     \sigma(X) = \sqrt{ \sum_{x \in S} p(x) (X(x) - E(x))**2}
        """
        return sqrt(self.translation_variance(map))
Пример #27
0
def johnson_radius(n, d):
    r"""
    Returns the Johnson-radius for the code length `n` and the minimum distance `d`.

    The Johnson radius is defined as `n - \sqrt(n(n-d))`.

    INPUT:

    - ``n`` -- an integer, the length of the code
    - ``d`` -- an integer, the minimum distance of the code

    EXAMPLES::

        sage: sage.coding.guruswami_sudan.utils.johnson_radius(250, 181)
        -5*sqrt(690) + 250
    """
    return n - sqrt(n * (n - d))
Пример #28
0
    def is_quasigeometric(self):
        """
        Decide whether the binary recurrence sequence is degenerate and similar to a geometric sequence,
        i.e. the union of multiple geometric sequences, or geometric after term ``u0``.

        If `\\alpha/\\beta` is a `k` th root of unity, where `k>1`, then necessarily `k = 2, 3, 4, 6`.
        Then `F = [[0,1],[c,b]` is diagonalizable, and `F^k = [[\\alpha^k, 0], [0,\\beta^k]]` is scaler
        matrix.  Thus for all values of `j` mod `k`, the `j` mod `k` terms of `u_n` form a geometric
        series.

        If `\\alpha` or `\\beta` is zero, this implies that `c=0`.  This is the case when `F` is
        singular.  In this case, `u_1, u_2, u_3, ...` is geometric.

        EXAMPLES::

            sage: S = BinaryRecurrenceSequence(0,1)
            sage: [S(i) for i in range(10)]
            [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
            sage: S.is_quasigeometric()
            True

            sage: R = BinaryRecurrenceSequence(3,0)
            sage: [R(i) for i in range(10)]
            [0, 1, 3, 9, 27, 81, 243, 729, 2187, 6561]
            sage: R.is_quasigeometric()
            True
        """
        # First test if F is singular... i.e. beta = 0
        if self.c == 0:
            return True

        # Otherwise test if alpha/beta is a root of unity that is not 1
        D = self.b**2 + 4 * self.c
        if D != 0:  # thus alpha/beta != 1
            if D.is_square():
                A = sqrt(D)
            else:
                K = QuadraticField(D, 'x')
                A = K.gen()
            if ((self.b + A) / (self.b - A))**6 == 1:
                return True

        return False
Пример #29
0
    def _derivative_(self, n, m, theta, phi, diff_param):
        r"""
        TESTS::

            sage: n, m, theta, phi = var('n m theta phi')
            sage: spherical_harmonic(n, m, theta, phi).diff(theta)
            m*cot(theta)*spherical_harmonic(n, m, theta, phi)
             + sqrt(-(m + n + 1)*(m - n))*e^(-I*phi)*spherical_harmonic(n, m + 1, theta, phi)
            sage: spherical_harmonic(n, m, theta, phi).diff(phi)
            I*m*spherical_harmonic(n, m, theta, phi)
        """
        if diff_param == 2:
            return (m * cot(theta) * spherical_harmonic(n, m, theta, phi) +
                    sqrt((n - m) * (n + m + 1)) * exp(-I * phi) *
                    spherical_harmonic(n, m + 1, theta, phi))
        if diff_param == 3:
            return I * m * spherical_harmonic(n, m, theta, phi)

        raise ValueError('only derivative with respect to theta or phi'
                         ' supported')
Пример #30
0
    def get_background_graphic(self, **bdry_options):
        r"""
        Return a graphic object that makes the model easier to visualize.
        For the hyperboloid model, the background object is the hyperboloid
        itself.

        EXAMPLES::

            sage: H = HyperbolicPlane().HM().get_background_graphic()
        """
        from sage.plot.plot3d.all import plot3d
        from sage.symbolic.ring import SR
        hyperboloid_opacity = bdry_options.get('hyperboloid_opacity', .1)
        z_height = bdry_options.get('z_height', 7.0)
        x_max = sqrt((z_height**2 - 1) / 2.0)
        x = SR.var('x')
        y = SR.var('y')
        return plot3d((1 + x**2 + y**2).sqrt(), (x, -x_max, x_max),
                      (y, -x_max, x_max),
                      opacity=hyperboloid_opacity,
                      **bdry_options)
Пример #31
0
    def _derivative_(self, x, diff_param=None):
        """
        Derivative of erf function.

        EXAMPLES::

            sage: erf(x).diff(x)
            2*e^(-x^2)/sqrt(pi)

        TESTS:

        Check if :trac:`8568` is fixed::

            sage: var('c,x')
            (c, x)
            sage: derivative(erf(c*x),x)
            2*c*e^(-c^2*x^2)/sqrt(pi)
            sage: erf(c*x).diff(x)._maxima_init_()
            '((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'
        """
        return 2*exp(-x**2)/sqrt(pi)
Пример #32
0
    def __init__(self, n, secret_dist='uniform', m=None):
        """
        Construct LWE instance parameterised by security parameter ``n`` where
        the modulus ``q`` and the ``stddev`` of the noise are chosen as in
        [Reg09]_.

        INPUT:

        - ``n`` - security parameter (integer > 0)
        - ``secret_dist`` - distribution of the secret. See documentation of :class:`LWE`
          for details (default='uniform')
        - ``m`` - number of allowed samples or ``None`` if no such limit exists
          (default: ``None``)

        EXAMPLES::

            sage: from sage.crypto.lwe import Regev
            sage: Regev(n=20)
            LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 1.915069 and c = 401, 'uniform', None)
        """
        q = ZZ(next_prime(n**2))
        s = RR(1 / (RR(n).sqrt() * log(n, 2)**2) * q)
        D = DiscreteGaussianDistributionIntegerSampler(s / sqrt(2 * pi.n()), q)
        LWE.__init__(self, n=n, q=q, D=D, secret_dist=secret_dist, m=m)