Ejemplo n.º 1
0
def check_conj_q_matrix(M):
    """
    sage: from sage.monoids.j_trivial_monoids import *
    sage: for p in Posets(3):
    ...       check_conj_q_matrix(NDPFMonoidPoset(p))
    ([1], 1, 1)
    (
    [1 0]
    [0 1], 2, 2
    )
    (
    [1 0 0 0]
    [0 1 0 0]
    [0 0 1 0]
    [0 0 0 1], 4, 4
    )
    (
    [1 0 0 0]
    [0 1 q 0]
    [0 0 1 0]
    [0 0 0 1], q + 4, q + 4
    )
    ([1], 1, 1)
    """
    msage = M.cartan_matrix(var('q'))
    rsage = sum(sum(msage))
    mmup = M.cartan_matrix_mupad(var('q'))
    rmup = sum(sum(mmup))
    assert (rmup == rsage), "Conjecture False "
    return msage, rsage, rmup
Ejemplo n.º 2
0
def findz(input, p, q, sig):
    """Function to find individual z variables in terms of x
	   and y.
		Args:
		    input (int): The number of the z variable
			   to be shown in terms of x and y.
		Returns:
		    z term(symb exp): The z variable expressed
				      in terms of x and y.
	"""
    if input == 0:
        return 0
    else:
        if p + q + 1 > input > p:
            final = 0
            alt = itertools.cycle([0, 1]).next
            for l in xrange(1, 2 * (input - p) + 1):
                altvar = alt()
                if altvar == 0:
                    final = final + var("y" + str(l))
                else:
                    final = final - (var("y" + str(l)))
            return z_adder(p) + final

        elif input == p + q + 1:
            return findt(p + q + 1 + sig, p, q) - var("y" + str(2 * q + 2))

        else:
            return z_adder(input)
Ejemplo n.º 3
0
def create_power_list(r, s):
    list_of_powers = []
    for number_of_xs in xrange(1, r + 1):
        list_of_powers.append(var("xpower" + str(number_of_xs)))

    for number_of_ys in xrange(1, s + 1):
        list_of_powers.append(var("ypower" + str(number_of_ys)))

    return list_of_powers
Ejemplo n.º 4
0
    def belfunc(self):
        """
        Returns belonging function of ellipsoid.
        """

        X = Matrix([[var('x')], [var('y')], [var('z')]])
        v = self.pos
        B = self.red_belonging_matrix()
        return (expand((X - v).transpose() * B * (X - v)) - 1)[0, 0]
Ejemplo n.º 5
0
def create_template_monomial(r, s):
    test_monomial = 1
    for number_of_xs in xrange(1, r + 1):
        test_monomial = test_monomial * var("x" + str(number_of_xs))**var(
            "xpower" + str(number_of_xs))
    for number_of_ys in xrange(1, s + 1):
        test_monomial = test_monomial * var("y" + str(number_of_ys))**var(
            "ypower" + str(number_of_ys))
    return test_monomial
Ejemplo n.º 6
0
def _arc(p,q,s,**kwds):
    #rewrite this to use polar_plot and get points to do filled triangles
    from sage.misc.functional import det
    from sage.plot.line import line
    from sage.misc.functional import norm
    from sage.symbolic.all import pi
    from sage.plot.arc import arc

    p,q,s = map( lambda x: vector(x), [p,q,s])

    # to avoid running into division by 0 we set to be colinear vectors that are
    # almost colinear
    if abs(det(matrix([p-s,q-s])))<0.01:
        return line((p,q),**kwds)

    (cx,cy)=var('cx','cy')
    equations=[
            2*cx*(s[0]-p[0])+2*cy*(s[1]-p[1]) == s[0]**2+s[1]**2-p[0]**2-p[1]**2,
            2*cx*(s[0]-q[0])+2*cy*(s[1]-q[1]) == s[0]**2+s[1]**2-q[0]**2-q[1]**2
            ]
    c = vector( [solve( equations, (cx,cy), solution_dict=True )[0][i] for i in [cx,cy]] )
    
    r = norm(p-c)

    a_p, a_q, a_s = map(lambda x: atan2(x[1],x[0]), [p-c,q-c,s-c])
    a_p, a_q = sorted([a_p,a_q])
    if a_s < a_p or a_s > a_q:
        return arc( c, r, angle=a_q, sector=(0,2*pi-a_q+a_p), **kwds)
    return arc( c, r, angle=a_p, sector=(0,a_q-a_p), **kwds)
Ejemplo n.º 7
0
    def __init__(self, Sym, t = 't'):
        r"""
        The family of Hall-Littlewood symmetric function bases
        By default the paramter for these functions is `t` and
        whatever the paramter is, it must be in the base ring.

        INPUT:

        - ``self`` -- a class of Hall-Littlewood symmetric function bases

        EXAMPLES::

            sage: SymmetricFunctions(QQ).hall_littlewood(1)
            Hall-Littlewood polynomials with t=1 over Rational Field
            sage: SymmetricFunctions(QQ['t'].fraction_field()).hall_littlewood()
            Hall-Littlewood polynomials over Fraction Field of Univariate Polynomial Ring in t over Rational Field
        """
        self._sym = Sym
        if not (t in Sym.base_ring() or var(t) in Sym.base_ring()):
            raise ValueError, "parameter t must be in the base ring"
        self.t = Sym.base_ring()(t)
        self._name_suffix = ""
        if str(t) !='t':
            self._name_suffix += " with t=%s"%t
        self._name = "Hall-Littlewood polynomials"+self._name_suffix
Ejemplo n.º 8
0
def _arc(p, q, s, **kwds):
    #rewrite this to use polar_plot and get points to do filled triangles
    from sage.misc.functional import det
    from sage.plot.line import line
    from sage.misc.functional import norm
    from sage.symbolic.all import pi
    from sage.plot.arc import arc

    p, q, s = map(lambda x: vector(x), [p, q, s])

    # to avoid running into division by 0 we set to be colinear vectors that are
    # almost colinear
    if abs(det(matrix([p - s, q - s]))) < 0.01:
        return line((p, q), **kwds)

    (cx, cy) = var('cx', 'cy')
    equations = [
        2 * cx * (s[0] - p[0]) + 2 * cy * (s[1] - p[1]) == s[0]**2 + s[1]**2 -
        p[0]**2 - p[1]**2, 2 * cx * (s[0] - q[0]) + 2 * cy *
        (s[1] - q[1]) == s[0]**2 + s[1]**2 - q[0]**2 - q[1]**2
    ]
    c = vector([
        solve(equations, (cx, cy), solution_dict=True)[0][i] for i in [cx, cy]
    ])

    r = norm(p - c)

    a_p, a_q, a_s = map(lambda x: atan2(x[1], x[0]), [p - c, q - c, s - c])
    a_p, a_q = sorted([a_p, a_q])
    if a_s < a_p or a_s > a_q:
        return arc(c, r, angle=a_q, sector=(0, 2 * pi - a_q + a_p), **kwds)
    return arc(c, r, angle=a_p, sector=(0, a_q - a_p), **kwds)
Ejemplo n.º 9
0
Archivo: grs.py Proyecto: wdv4758h/sage
    def weight_distribution(self):
        r"""
        Returns the list whose `i`'th entry is the number of words of weight `i`
        in ``self``.

        Computing the weight distribution for a GRS code is very fast. Note that
        for random linear codes, it is computationally hard.

        EXAMPLES::

            sage: F = GF(11)
            sage: n, k = 10, 5
            sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)
            sage: C.weight_distribution()
            [1, 0, 0, 0, 0, 0, 2100, 6000, 29250, 61500, 62200]
        """
        d = self.minimum_distance()
        n = self.length()
        q = self.base_ring().order()
        s = var('s')
        wd = [1] + [0] * (d - 1)
        for i in range(d, n + 1):
            tmp = binomial(n, i) * (q - 1)
            wd.append(tmp * symbolic_sum(
                binomial(i - 1, s) * (-1)**s * q**(i - d - s), s, 0, i - d))
        return wd
Ejemplo n.º 10
0
Archivo: grs.py Proyecto: wdv4758h/sage
    def weight_enumerator(self):
        r"""
        Returns the polynomial whose coefficient to `x^i` is the number of codewords of weight `i` in ``self``.

        Computing the weight enumerator for a GRS code is very fast. Note that
        for random linear codes, it is computationally hard.

        EXAMPLES::

            sage: F = GF(11)
            sage: n, k = 10, 5
            sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)
            sage: C.weight_enumerator()
            62200*x^10 + 61500*x^9 + 29250*x^8 + 6000*x^7 + 2100*x^6 + 1
        """
        PolRing = ZZ['x']
        x = PolRing.gen()
        s = var('s')
        wd = self.weight_distribution()
        d = self.minimum_distance()
        n = self.length()
        w_en = PolRing(1)
        for i in range(n + 1 - d):
            w_en += wd[i + d] * x**(i + d)
        return w_en
Ejemplo n.º 11
0
    def weight_distribution(self):
        r"""
        Returns the list whose `i`'th entry is the number of words of weight `i`
        in ``self``.

        Computing the weight distribution for a GRS code is very fast. Note that
        for random linear codes, it is computationally hard.

        EXAMPLES::

            sage: F = GF(11)
            sage: n, k = 10, 5
            sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)
            sage: C.weight_distribution()
            [1, 0, 0, 0, 0, 0, 2100, 6000, 29250, 61500, 62200]
        """
        d = self.minimum_distance()
        n = self.length()
        q = self.base_ring().order()
        s = var('s')
        wd = [1] + [0] * (d - 1)
        for i in range(d, n+1):
            tmp = binomial(n, i) * (q - 1)
            wd.append(tmp * symbolic_sum(binomial(i-1, s) * (-1) ** s * q ** (i - d - s), s, 0, i-d))
        return wd
Ejemplo n.º 12
0
    def weight_enumerator(self):
        r"""
        Returns the polynomial whose coefficient to `x^i` is the number of codewords of weight `i` in ``self``.

        Computing the weight enumerator for a GRS code is very fast. Note that
        for random linear codes, it is computationally hard.

        EXAMPLES::

            sage: F = GF(11)
            sage: n, k = 10, 5
            sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)
            sage: C.weight_enumerator()
            62200*x^10 + 61500*x^9 + 29250*x^8 + 6000*x^7 + 2100*x^6 + 1
        """
        PolRing = ZZ['x']
        x = PolRing.gen()
        s = var('s')
        wd = self.weight_distribution()
        d = self.minimum_distance()
        n = self.length()
        w_en = PolRing(1)
        for i in range(n + 1 - d):
            w_en += wd[i + d] * x ** (i + d)
        return w_en
Ejemplo n.º 13
0
def _step_upper_bound_internal(r, m, q, generating_function):
    r"""
    Common implementation for :func:`step_upper_bound` and :func:`step_upper_bound_specific`
    """
    L = LieAlgebra(QQ, ['X_%d' % k for k in range(r)]).Lyndon()
    dim_fm = L.graded_dimension(m)

    t = var('t')
    pt = symbolic_prod(
        (1 / ((1 - t**k)**L.graded_dimension(k)) for k in range(1, m)),
        (1 - dim_fm * (1 - t**q)) * t**m)

    increment = series_precision()
    i = 0
    coeffsum = ZZ.zero()
    while True:
        # sum the coefficients of the series for t^i...t^(i+increment-1)
        p_series = pt.series(t, i + increment)
        for s in range(i, i + increment):
            coeffsum += ZZ(p_series.coefficient(t, s))
            if coeffsum > 0:
                verbose("upper bound for abnormality: step %d" % s)
                if generating_function:
                    return s, pt
                return s
        # exponential growth to avoid recomputing the series too much
        i += increment
        increment += increment
Ejemplo n.º 14
0
    def show(self, boundary=True, **options):
        r"""
        Plot ``self``.

        EXAMPLES::

            sage: HyperbolicPlane().UHP().get_geodesic(0, 1).show()
            Graphics object consisting of 2 graphics primitives
        """
        opts = {'axes': False, 'aspect_ratio': 1}
        opts.update(self.graphics_options())
        opts.update(options)
        end_1, end_2 = [CC(k.coordinates()) for k in self.endpoints()]
        bd_1, bd_2 = [CC(k.coordinates()) for k in self.ideal_endpoints()]
        if (abs(real(end_1) - real(end_2)) < EPSILON) \
                or CC(infinity) in [end_1, end_2]: #on same vertical line
            # If one of the endpoints is infinity, we replace it with a
            # large finite  point
            if end_1 == CC(infinity):
                end_1 = (real(end_2), (imag(end_2) + 10))
                end_2 = (real(end_2), imag(end_2))
            elif end_2 == CC(infinity):
                end_2 = (real(end_1), (imag(end_1) + 10))
                end_1 = (real(end_1), imag(end_1))
            from sage.plot.line import line
            pic = line((end_1, end_2), **opts)
            if boundary:
                cent = min(bd_1, bd_2)
                bd_dict = {'bd_min': cent - 3, 'bd_max': cent + 3}
                bd_pic = self._model.get_background_graphic(**bd_dict)
                pic = bd_pic + pic
                return pic
        else:
            center = (bd_1 + bd_2)/2 # Circle center
            radius = abs(bd_1 - bd_2)/2
            theta1 = CC(end_1 - center).arg()
            theta2 = CC(end_2 - center).arg()
            if abs(theta1 - theta2) < EPSILON:
                theta2 += pi
            [theta1, theta2] = sorted([theta1, theta2])
            from sage.calculus.var import var
            from sage.plot.plot import parametric_plot
            x = var('x')
            pic = parametric_plot((radius*cos(x) + real(center),
                                   radius*sin(x) + imag(center)),
                                  (x, theta1, theta2), **opts)
            if boundary:
                # We want to draw a segment of the real line.  The
                # computations below compute the projection of the
                # geodesic to the real line, and then draw a little
                # to the left and right of the projection.
                shadow_1, shadow_2 = [real(k) for k in [end_1, end_2]]
                midpoint = (shadow_1 + shadow_2)/2
                length = abs(shadow_1 - shadow_2)
                bd_dict = {'bd_min': midpoint - length, 'bd_max': midpoint +
                           length}
                bd_pic = self._model.get_background_graphic(**bd_dict)
                pic = bd_pic + pic
            return pic
Ejemplo n.º 15
0
    def test_geometric(self):
        G = (1 - x) * y - 1
        S = newton_iteration(G, 9).truncate(x, 10)

        z = var('z')
        series = taylor(1 / (1 - z), z, 0, 9)
        series = R(series.subs({z: x}))
        self.assertEqual(S, series)
Ejemplo n.º 16
0
    def test_geometric(self):
        G = (1-x)*y - 1
        S = newton_iteration(G,9).truncate(x,10)

        z = var('z')
        series = taylor(1/(1-z),z,0,9)
        series = R(series.subs({z:x}))
        self.assertEqual(S,series)
Ejemplo n.º 17
0
    def test_cuberoot(self):
        # recenter cuberoot(x) at x+1
        G = (y+1)**3 - (x+1)
        S = newton_iteration(G,9).truncate(x,10) + 1

        z = var('z')
        series = taylor(z**(QQ(1)/QQ(3)),z,1,9)
        series = R(series.subs({z:x+1}))
        self.assertEqual(S,series)
Ejemplo n.º 18
0
    def test_cuberoot(self):
        # recenter cuberoot(x) at x+1
        G = (y + 1)**3 - (x + 1)
        S = newton_iteration(G, 9).truncate(x, 10) + 1

        z = var('z')
        series = taylor(z**(QQ(1) / QQ(3)), z, 1, 9)
        series = R(series.subs({z: x + 1}))
        self.assertEqual(S, series)
Ejemplo n.º 19
0
    def test_sqrt(self):
        # recenter sqrt(x) at x+1
        G = (y+1)**2 - (x+1)
        S = newton_iteration(G,9).truncate(x,10) + 1

        z = var('z')
        series = taylor(sqrt(z),z,1,9)
        series = R(series.subs({z:x+1}))
        self.assertEqual(S,series)
Ejemplo n.º 20
0
    def test_sqrt(self):
        # recenter sqrt(x) at x+1
        G = (y + 1)**2 - (x + 1)
        S = newton_iteration(G, 9).truncate(x, 10) + 1

        z = var('z')
        series = taylor(sqrt(z), z, 1, 9)
        series = R(series.subs({z: x + 1}))
        self.assertEqual(S, series)
Ejemplo n.º 21
0
def t_adder(input, p):
    """Function similar to z_adder(), but for t variables.
		Args:
		    input(int): The number of the t variable
				to be shown in terms of x and y.
		Returns:
		    t_added(symb exp): Series of x and y variables
				       added together.
	"""
    t_added = 0
    alty = itertools.cycle([0, 1]).next
    for i in xrange(1, 2 * input):
        altyvar = alty()
        if altyvar == 0:
            t_added = t_added + var("y" + str(i))
        else:
            t_added = t_added - (var("y" + str(i)))
    return t_added + z_adder(p)
Ejemplo n.º 22
0
def ring_lists(r, s):
    slist = ''
    for i in xrange(1, r + 1):
        slist = slist + 'x' + str(i) + ', '
    for i in xrange(1, s + 1):
        slist = slist + 'y' + str(i) + ', '
    slist = slist[0:-2]
    vlist = var(slist)
    return [slist, vlist]
Ejemplo n.º 23
0
def tangent_vector(f):
    # https://doc.sagemath.org/html/en/reference/manifolds/sage/manifolds/differentiable/tangent_vector.html?highlight=partial%20differential
    # XXX:  There is TangentVector in Sage but a little bit more complicated. Does it pay to use that one ?
    r"""
    Do a tangent vector

    DEFINITION:

    missing

    INPUT:

    - ``f`` - symbolic expression of type 'function'

    OUTPUT:

    the tangent vector

    .. NOTE::

    none so far

    ..

    EXAMPLES: compute the tangent vector of

    ::
    sage: from delierium.helpers import tangent_vector
    sage: x,y,z = var ("x y z")
    sage: tangent_vector (x**2 - 3*y**4 - z*x*y + z - x)
    [-y*z + 2*x - 1, -12*y^3 - x*z, -x*y + 1]
    sage: tangent_vector (x**2 + 2*y**3 - 3*z**4)
    [2*x, 6*y^2, -12*z^3]
    sage: tangent_vector (x**2)
    [2*x]
    """
    t = var("t")
    newvars = [var("x%s" % i) for i in f.variables()]
    for o, n in zip(f.variables(), newvars):
        f = f.subs({o: o+t*n})
    d = diff(f, t).limit(t=0)
    return [d.coefficient(_) for _ in newvars]
Ejemplo n.º 24
0
 def generating_function(self):
     ''' starts with minimum, subtracts off basis '''
     if using_sage or using_sympy:
         k = len(self)
         dots = self.minimum.count(1)
         dimension = k - dots
         # sets up 'x' as an algebraic variable in both sympy and sage
         var('x')
         fcn = ( x ** sum(self.minimum) ) / ((1 - x) ** dimension)
         basis_size = len(self.basis)
         mult = 1
         for level in range(1, basis_size + 1):
             mult *= -1
             for comb in it.combinations(self.basis, level):
                 # comb is a list of vectors
                 maxvector = [max(t) for t in zip(*comb)]
                 maxvector = [max(t) for t in zip(maxvector, self.minimum)]
                 fcn = fcn + mult * (x ** sum(maxvector)) / ((1-x) ** dimension)
         return fcn
     if function_strings:
         # spits out LONG list of strings that can be input into sage
         # use L = self.generating_function(); print '\n +'.join(L)
         biglist = []
         k = len(self)
         dots = self.minimum.count(1)
         dimension = k - dots
         # sets up 'x' as an algebraic variable in both sympy and sage
         mult = 1
         biglist.append('(%d)*(x ** %d)/(1 - x) ** %d'
                                         % (mult, sum(self.minimum), dimension))
         basis_size = len(self.basis)
         for level in range(1, basis_size + 1):
             mult *= -1
             for comb in it.combinations(self.basis, level):
                 # comb is a list of vectors
                 maxvector = [max(t) for t in zip(*comb)]
                 maxvector = [max(t) for t in zip(maxvector, self.minimum)]
                 biglist.append('(%d)*(x ** %d)/(1 - x) ** %d'
                                                 % (mult, sum(maxvector), dimension))
         return biglist
     else:
         return '''either install sympy or run this script in a sage session for
Ejemplo n.º 25
0
def FrechetD(support, dependVar, independVar, testfunction):
    frechet = []
    var("eps")
    for j in range(len(support)):
        deriv = []
        for i in range(len(support)):

            def r0(*args):
                return dependVar[i](
                    *independVar) + testfunction[i](*independVar) * eps

            #def _r0(*args):
            #    # this version has issues as it always uses w2 ?!? investigate further
            #    # when time and motivation. Online version on asksage works perfectly
            #    return dependVar[i](*independVar)+ testfunction[i](*independVar) * eps
            #r0 = function('r0', eval_func=_r0)
            s = support[j].substitute_function(dependVar[i], r0)
            deriv.append(diff(s, eps).subs({eps: 0}))
        frechet.append(deriv)
    return frechet
Ejemplo n.º 26
0
        def plot_arc(radius, p, q, **opts):
            # TODO: THIS SHOULD USE THE EXISTING PLOT OF ARCS!
            # plot the arc from p to q differently depending on the type of self
            p = ZZ(p)
            q = ZZ(q)
            t = var('t')
            if p - q in [1, -1]:

                def f(t):
                    return (radius * cos(t), radius * sin(t))

                (p, q) = sorted([p, q])
                angle_p = vertex_to_angle(p)
                angle_q = vertex_to_angle(q)
                return parametric_plot(f(t), (t, angle_q, angle_p), **opts)
            if self.type() == 'A':
                angle_p = vertex_to_angle(p)
                angle_q = vertex_to_angle(q)
                if angle_p < angle_q:
                    angle_p += 2 * pi
                internal_angle = angle_p - angle_q
                if internal_angle > pi:
                    (angle_p, angle_q) = (angle_q + 2 * pi, angle_p)
                    internal_angle = angle_p - angle_q
                angle_center = (angle_p + angle_q) / 2
                hypotenuse = radius / cos(internal_angle / 2)
                radius_arc = hypotenuse * sin(internal_angle / 2)
                center = (hypotenuse * cos(angle_center),
                          hypotenuse * sin(angle_center))
                center_angle_p = angle_p + pi / 2
                center_angle_q = angle_q + 3 * pi / 2

                def f(t):
                    return (radius_arc * cos(t) + center[0],
                            radius_arc * sin(t) + center[1])

                return parametric_plot(f(t),
                                       (t, center_angle_p, center_angle_q),
                                       **opts)
            elif self.type() == 'D':
                if p >= q:
                    q += self.r()
                px = -2 * pi * p / self.r() + pi / 2
                qx = -2 * pi * q / self.r() + pi / 2
                arc_radius = (px - qx) / 2
                arc_center = qx + arc_radius

                def f(t):
                    return exp(I * ((cos(t) + I * sin(t)) * arc_radius +
                                    arc_center)) * radius

                return parametric_plot((real_part(f(t)), imag_part(f(t))),
                                       (t, 0, pi), **opts)
Ejemplo n.º 27
0
    def show(self, boundary=True, **options):
        r"""
        Plot ``self``.

        EXAMPLES::

            sage: HyperbolicPlane().PD().get_geodesic(0, 1).show()
            Graphics object consisting of 2 graphics primitives
        """
        opts = dict([('axes', False), ('aspect_ratio', 1)])
        opts.update(self.graphics_options())
        opts.update(options)
        end_1, end_2 = [CC(k.coordinates()) for k in self.endpoints()]
        bd_1, bd_2 = [CC(k.coordinates()) for k in self.ideal_endpoints()]
        # Check to see if it's a line
        if bool(real(bd_1)*imag(bd_2) - real(bd_2)*imag(bd_1))**2 < EPSILON:
            from sage.plot.line import line
            pic = line([(real(bd_1),imag(bd_1)),(real(bd_2),imag(bd_2))],
                       **opts)
        else:
            # If we are here, we know it's not a line
            # So we compute the center and radius of the circle
            center = (1/(real(bd_1)*imag(bd_2) - real(bd_2)*imag(bd_1)) *
                ((imag(bd_2)-imag(bd_1)) + (real(bd_1)-real(bd_2))*I))
            radius = RR(abs(bd_1 - center)) # abs is Euclidean distance
            # Now we calculate the angles for the parametric plot
            theta1 = CC(end_1 - center).arg()
            theta2 = CC(end_2 - center).arg()
            if theta2 < theta1:
                theta1, theta2 = theta2, theta1
            from sage.calculus.var import var
            from sage.plot.plot import parametric_plot
            x = var('x')
            mid = (theta1 + theta2)/2.0
            if (radius*cos(mid) + real(center))**2 + \
               (radius*sin(mid) + imag(center))**2 > 1.0:
                # Swap theta1 and theta2
                tmp = theta1 + 2*pi
                theta1 = theta2
                theta2 = tmp
                pic = parametric_plot((radius*cos(x) + real(center),
                                       radius*sin(x) + imag(center)),
                                      (x, theta1, theta2), **opts)

            else:
                pic = parametric_plot((radius*cos(x) + real(center),
                                   radius*sin(x) + imag(center)),
                                  (x, theta1, theta2), **opts)
        if boundary:
            bd_pic = self._model.get_background_graphic()
            pic = bd_pic + pic
        return pic
Ejemplo n.º 28
0
def z_adder(input):
    """Function for use in building z and t variables.
		Args:
		    input(int): The number of the z variable
			        to be shown in terms of x.
		Returns:
		    z_added(symb exp): Series of x variables
				       added together.
	"""
    z_added = 0
    for i in xrange(1, input + 1):
        z_added = z_added + var("x" + str(i))
    return z_added
Ejemplo n.º 29
0
def EulerD(density, depend, independ):
    r'''
    >>> t = var("t")
    >>> u= function('u')
    >>> v= function('v')
    >>> L=u(t)*v(t) + diff(u(t), t)**2 + diff(v(t), t)**2 - u(t)**2 - v(t)**2
    >>> EulerD(L, (u,v), t)
    [-2*u(t) + v(t) - 2*diff(u(t), t, t), u(t) - 2*v(t) - 2*diff(v(t), t, t)]
    >>> L=u(t)*v(t) + diff(u(t), t)**2 + diff(v(t), t)**2 + 2*diff(u(t), t) * diff(v(t), t)
    >>> EulerD(L, (u,v), t)
    [v(t) - 2*diff(u(t), t, t) - 2*diff(v(t), t, t), u(t) - 2*diff(u(t), t, t) - 2*diff(v(t), t, t)]
    '''
    wtable = [function("w_%s" % i) for i in range(len(depend))]
    y = function('y')
    w = function('w')
    e = var('e')
    result = []
    for j in range(len(depend)):
        loc_result = 0

        def f0(*args):
            return y(independ) + e * w(independ)

        def dep(*args):
            return depend[j](independ)

        fh = density.substitute_function(depend[j], f0)
        fh = fh.substitute_function(y, dep)
        fh = fh.substitute_function(w, wtable[j])
        fh = fh.diff(e)
        fh = fh.subs({e: 0}).expand()
        if fh.operator().__name__ == 'mul_vararg':
            operands = [fh]
        else:
            operands = fh.operands()
        for operand in operands:
            d = None
            coeff = []
            for _ops in operand.operands():
                if is_op_du(_ops, wtable[j](independ)):
                    d = _ops.operands().count(independ)
                elif is_function(_ops) and _ops.operator() == wtable[j]:
                    pass
                else:
                    coeff.append(_ops)
            coeff = functools.reduce(mul, coeff, 1)
            if d is not None:
                coeff = ((-1)**d) * diff(coeff, independ, d)
            loc_result += coeff
        result.append(loc_result)
    return result
Ejemplo n.º 30
0
def FrechetD(support, dependVar, independVar, testfunction):
    """
    >>> t, x = var ("t x")
    >>> v  = function ("v")
    >>> u  = function ("u")
    >>> w1 = function ("w1")
    >>> w2 = function ("w2")
    >>> eqsys = [diff(v(x,t), x) - u(x,t), diff(v(x,t), t) - diff(u(x,t), x)/(u(x,t)**2)]
    >>> m = Matrix(FrechetD (eqsys, [u,v], [x,t], [w1,w2]))
    >>> m[0][0]
    -w1(x, t)
    >>> m[0][1]
    diff(w2(x, t), x)
    >>> m[1][0]
    2*w1(x, t)*diff(u(x, t), x)/u(x, t)^3 - diff(w1(x, t), x)/u(x, t)^2
    >>> m[1][1]
    diff(w2(x, t), t)
    """
    frechet = []
    var("eps")
    for j in range(len(support)):
        deriv = []
        for i in range(len(support)):

            def r0(*args):
                return dependVar[i](
                    *independVar) + testfunction[i](*independVar) * eps

            #def _r0(*args):
            #    # this version has issues as it always uses w2 ?!? investigate further
            #    # when time and motivation. Online version on asksage works perfectly
            #    return dependVar[i](*independVar)+ testfunction[i](*independVar) * eps
            #r0 = function('r0', eval_func=_r0)
            s = support[j].substitute_function(dependVar[i], r0)
            deriv.append(diff(s, eps).subs({eps: 0}))
        frechet.append(deriv)
    return frechet
Ejemplo n.º 31
0
        def plot_arc(radius, p, q, **opts):
            # TODO: THIS SHOULD USE THE EXISTING PLOT OF ARCS!
            # plot the arc from p to q differently depending on the type of self
            p = ZZ(p)
            q = ZZ(q)
            t = var('t')
            if p - q in [1, -1]:
                def f(t):
                    return (radius * cos(t), radius * sin(t))
                (p, q) = sorted([p, q])
                angle_p = vertex_to_angle(p)
                angle_q = vertex_to_angle(q)
                return parametric_plot(f(t), (t, angle_q, angle_p), **opts)
            if self.type() == 'A':
                angle_p = vertex_to_angle(p)
                angle_q = vertex_to_angle(q)
                if angle_p < angle_q:
                    angle_p += 2 * pi
                internal_angle = angle_p - angle_q
                if internal_angle > pi:
                    (angle_p, angle_q) = (angle_q + 2 * pi, angle_p)
                    internal_angle = angle_p - angle_q
                angle_center = (angle_p+angle_q) / 2
                hypotenuse = radius / cos(internal_angle / 2)
                radius_arc = hypotenuse * sin(internal_angle / 2)
                center = (hypotenuse * cos(angle_center),
                          hypotenuse * sin(angle_center))
                center_angle_p = angle_p + pi / 2
                center_angle_q = angle_q + 3 * pi / 2

                def f(t):
                    return (radius_arc * cos(t) + center[0],
                            radius_arc * sin(t) + center[1])
                return parametric_plot(f(t), (t, center_angle_p,
                                              center_angle_q), **opts)
            elif self.type() == 'D':
                if p >= q:
                    q += self.r()
                px = -2 * pi * p / self.r() + pi / 2
                qx = -2 * pi * q / self.r() + pi / 2
                arc_radius = (px - qx) / 2
                arc_center = qx + arc_radius

                def f(t):
                    return exp(I * ((cos(t) + I * sin(t)) *
                                    arc_radius + arc_center)) * radius
                return parametric_plot((real_part(f(t)), imag_part(f(t))),
                                       (t, 0, pi), **opts)
Ejemplo n.º 32
0
def findt(input, p, q):
    """Function to find individual t variables in terms of x
	   and y.
		Args:
		    input(int): The number of the t variable.
		Returns:
		    t term(symb exp): The t variable expressed
				       in terms of x and y.
	"""
    if input > q + 1:
        final = 0
        for l in xrange(p + 1, input - q + p):
            final = final - (var("x" + str(l)))
        return t_adder(q + 1, p) + final
    else:
        return t_adder(input, p)
Ejemplo n.º 33
0
    def _to_expr_on_basis(self, vector, alphabet=None):
        r"""
        Transforms a vector key of a finite basis into a symbolic
        expression factor.

        It uses formal variables with names : basis_repr + i
        (by default, 'x1' to 'xn')

        INPUT :
            - ``vector`` a key element of a finite basis
            ``CominatorialFreeModule``
            - ``alphabet`` an obtional alphabet of formal variables, if let
            to ``None``, it uses basis_repr + i (by default, 'x1' to 'xn')

        OUTPUT:
            - a symbolic expression corresponding to the monomial

        EXAMPLES::

            sage: from multipolynomial_bases import MultivariatePolynomialAlgebra
            sage: A.<x> = MultivariatePolynomialAlgebra(QQ)
            sage: pol = x[2,2,1] + x[3,2]; pol
            x[2, 2, 1] + x[3, 2, 0]
            sage: key = list(pol)[0][0]; key
            [2, 2, 1]
            sage: x._to_expr_on_basis(key)
            x1^2*x2^2*x3
            sage: var('a,b,c')
            (a, b, c)
            sage: alphabet = [a,b,c]
            sage: x._to_expr_on_basis(key, alphabet=alphabet)
            a^2*b^2*c

        """
        from sage.calculus.var import var
        key = list(vector)
        if alphabet is None:
            alphabet = [
                var(self.basis_repr() + str(i))
                for i in range(1,
                               len(key) + 1)
            ]
        expr = 1
        for i in range(len(key)):
            expr *= alphabet[i]**key[i]

        return expr
Ejemplo n.º 34
0
    def __init__(self, Sym, t = 't'):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: HL = SymmetricFunctions(FractionField(QQ['t'])).hall_littlewood()
            sage: TestSuite(HL).run()
        """
        self._sym = Sym
        if not (t in Sym.base_ring() or var(t) in Sym.base_ring()):
            raise ValueError, "parameter t must be in the base ring"
        self.t = Sym.base_ring()(t)
        self._name_suffix = ""
        if str(t) !='t':
            self._name_suffix += " with t=%s"%t
        self._name = "Hall-Littlewood polynomials"+self._name_suffix
Ejemplo n.º 35
0
    def __init__(self, Sym, t='t'):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: HL = SymmetricFunctions(FractionField(QQ['t'])).hall_littlewood()
            sage: TestSuite(HL).run()
        """
        self._sym = Sym
        if not (t in Sym.base_ring() or var(t) in Sym.base_ring()):
            raise ValueError, "parameter t must be in the base ring"
        self.t = Sym.base_ring()(t)
        self._name_suffix = ""
        if str(t) != 't':
            self._name_suffix += " with t=%s" % t
        self._name = "Hall-Littlewood polynomials" + self._name_suffix
Ejemplo n.º 36
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
        [LP11]_.

        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, DiscreteGaussianPolynomialSamplerRejection(8, 2.803372, 53, 4), 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 = 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 [LP11]_
        q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
        # Gaussian parameter as defined in [LP11]_
        s = sqrt(s_t_bound * floor(q / 4))
        # Transform s into stddev
        stddev = s / sqrt(2 * pi.n())
        D = DiscreteGaussianPolynomialSampler(n, stddev)
        RingLWE.__init__(self,
                         N=N,
                         q=q,
                         D=D,
                         poly=None,
                         secret_dist='noise',
                         m=m)
Ejemplo n.º 37
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
        [LP11]_.

        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 [LP11]_ (default: ``None``)

        EXAMPLES::

            sage: from sage.crypto.lwe import LindnerPeikert
            sage: LindnerPeikert(n=20)
            LWE(20, 2053, DiscreteGaussianSamplerRejection(3.600954, 53, 4), '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 = 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 [LP11]_
        q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
        # Gaussian parameter as defined in [LP11]_
        s = sqrt(s_t_bound * floor(q / 4))
        # Transform s into stddev
        stddev = s / sqrt(2 * pi.n())
        D = DiscreteGaussianSampler(stddev)
        LWE.__init__(self, n=n, q=q, D=D, secret_dist='noise', m=m)
Ejemplo n.º 38
0
Archivo: lwe.py Proyecto: Etn40ff/sage
    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
        [LP11]_.

        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 [LP11]_ (default: ``None``)

        EXAMPLES::

            sage: from sage.crypto.lwe import LindnerPeikert
            sage: LindnerPeikert(n=20)
            LWE(20, 2053, DiscreteGaussianSamplerRejection(3.600954, 53, 4), '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 = 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 [LP11]_
        q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
        # Gaussian parameter as defined in [LP11]_
        s = sqrt(s_t_bound*floor(q/4))
        # Transform s into stddev
        stddev = s/sqrt(2*pi.n())
        D   = DiscreteGaussianSampler(stddev)
        LWE.__init__(self, n=n, q=q, D=D, secret_dist='noise', m=m)
Ejemplo n.º 39
0
    def __init__(self, Sym, k, t='t'):
        r"""
        Class of LLT symmetric function bases

        INPUT:

        - ``self`` -- a family of LLT symmetric function bases
        - ``k`` -- a positive integer (the level)
        - ``t`` -- a parameter (default: `t`)

        EXAMPLES::

            sage: L3 = SymmetricFunctions(FractionField(QQ['t'])).llt(3)
            sage: L3 == loads(dumps(L3))
            True
            sage: TestSuite(L3).run(skip=["_test_associativity","_test_distributivity","_test_prod"])

        TESTS::

            sage: L3 != SymmetricFunctions(FractionField(QQ['t'])).llt(2)
            True
            sage: L3p = SymmetricFunctions(FractionField(QQ['t'])).llt(3,t=1)
            sage: L3 != L3p
            True
            sage: L3p != SymmetricFunctions(QQ).llt(3,t=1)
            True
        """
        self._k = k
        self._sym = Sym
        self._name = "level %s LLT polynomials"%self._k
        if not (t in Sym.base_ring() or var(t) in Sym.base_ring()):
            raise ValueError("parameter t must be in the base ring")
        self.t = Sym.base_ring()(t)
        self._name_suffix = ""
        if str(t) !='t':
            self._name_suffix += " with t=%s"%self.t
        self._name += self._name_suffix+" over %s"%self._sym.base_ring()
        self._m = sage.combinat.sf.sf.SymmetricFunctions(QQt).monomial()
Ejemplo n.º 40
0
    def mu(self, epsilon=1e-12):
        """
        Returns rescaling factor associated to the couple with precision epsilon
        in the search of the root of the contact function.
        """

        eta = var('eta')

        Y = (eta * self.ellipsoid2.red_belonging_matrix().inverse() +
             (1 - eta) * self.ellipsoid1.red_belonging_matrix().inverse())

        p = (eta * (1 - eta) *
             ((self.ellipsoid2.pos - self.ellipsoid1.pos).transpose()) *
             (Y.adjugate()) * (self.ellipsoid2.pos - self.ellipsoid1.pos))
        q = Y.determinant()

        h = expand(p.derivative(eta) * q - p * q.derivative(eta))[0, 0]
        F = expand(p / q)[0, 0]

        root, iter = halleyMethod(
            h, eta, self.ellipsoid1.R[0] /
            (self.ellipsoid1.R[0] + self.ellipsoid2.R[0]), epsilon)
        return sqrt(F(eta=root))
Ejemplo n.º 41
0
def map_coefficients_to_variable_index(M, x):
    r"""
    INPUT:

    - ``M`` -- matrix
    - ``x`` -- string, variable

    EXAMPLES::

        sage: from slabbe.matrices import map_coefficients_to_variable_index
        sage: M = matrix(2, range(4))
        sage: map_coefficients_to_variable_index(M, 's')
        [s_0 s_1]
        [s_2 s_3]
        sage: latex(_)
        \left(\begin{array}{rr}
        s_{0} & s_{1} \\
        s_{2} & s_{3}
        \end{array}\right)
    """
    from sage.calculus.var import var
    L = [var('{}_{}'.format(x,a)) for a in M.list()]
    return matrix(M.nrows(), L)
Ejemplo n.º 42
0
    def show(self, show_hyperboloid=True, **graphics_options):
        r"""
        Plot ``self``.

        EXAMPLES::

            sage: from sage.geometry.hyperbolic_space.hyperbolic_geodesic import *
            sage: g = HyperbolicPlane().HM().random_geodesic()
            sage: g.show()
            Graphics3d Object
        """
        from sage.calculus.var import var
        (x,y,z) = var('x,y,z')
        opts = self.graphics_options()
        opts.update(graphics_options)
        v1,u2 = [vector(k.coordinates()) for k in self.endpoints()]
        # Lorentzian Gram Shmidt.  The original vectors will be
        # u1, u2 and the orthogonal ones will be v1, v2.  Except
        # v1 = u1, and I don't want to declare another variable,
        # hence the odd naming convention above.
        # We need the Lorentz dot product of v1 and u2.
        v1_ldot_u2 = u2[0]*v1[0] + u2[1]*v1[1] - u2[2]*v1[2]
        v2 = u2 + v1_ldot_u2*v1
        v2_norm = sqrt(v2[0]**2 + v2[1]**2 - v2[2]**2)
        v2 = v2/v2_norm
        v2_ldot_u2 = u2[0]*v2[0] + u2[1]*v2[1] - u2[2]*v2[2]
        # Now v1 and v2 are Lorentz orthogonal, and |v1| = -1, |v2|=1
        # That is, v1 is unit timelike and v2 is unit spacelike.
        # This means that cosh(x)*v1 + sinh(x)*v2 is unit timelike.
        hyperbola = cosh(x)*v1 + sinh(x)*v2
        endtime = arcsinh(v2_ldot_u2)
        from sage.plot.plot3d.all import parametric_plot3d
        pic = parametric_plot3d(hyperbola,(x,0, endtime), **graphics_options)
        if show_hyperboloid:
            bd_pic = self._model.get_background_graphic()
            pic = bd_pic + pic
        return pic
Ejemplo n.º 43
0
 def __init__(self, base_ring, fibre_names, base_names,
              max_differential_orders):
     self._fibre_names = tuple(fibre_names)
     self._base_names = tuple(base_names)
     self._max_differential_orders = tuple(max_differential_orders)
     base_dim = len(self._base_names)
     fibre_dim = len(self._fibre_names)
     jet_names = []
     idx_to_name = {}
     for fibre_idx in range(fibre_dim):
         u = self._fibre_names[fibre_idx]
         idx_to_name[(fibre_idx, ) + tuple([0] * base_dim)] = u
         for d in range(1, max_differential_orders[fibre_idx] + 1):
             for multi_index in IntegerVectors(d, base_dim):
                 v = '{}_{}'.format(
                     u, ''.join(self._base_names[i] * multi_index[i]
                                for i in range(base_dim)))
                 jet_names.append(v)
                 idx_to_name[(fibre_idx, ) + tuple(multi_index)] = v
     self._polynomial_ring = PolynomialRing(
         base_ring, base_names + fibre_names + tuple(jet_names))
     self._idx_to_var = {
         idx: self._polynomial_ring(idx_to_name[idx])
         for idx in idx_to_name
     }
     self._var_to_idx = {
         jet: idx
         for (idx, jet) in self._idx_to_var.items()
     }
     # for conversion:
     base_vars = [var(b) for b in self._base_names]
     symbolic_functions = [
         function(f)(*base_vars) for f in self._fibre_names
     ]
     self._subs_jet_vars = SubstituteJetVariables(symbolic_functions)
     self._subs_tot_ders = SubstituteTotalDerivatives(symbolic_functions)
Ejemplo n.º 44
0
Archivo: lwe.py Proyecto: Etn40ff/sage
    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
        [LP11]_.

        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, DiscreteGaussianPolynomialSamplerRejection(8, 2.803372, 53, 4), 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 = 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 [LP11]_
        q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
        # Gaussian parameter as defined in [LP11]_
        s = sqrt(s_t_bound*floor(q/4))
        # Transform s into stddev
        stddev = s/sqrt(2*pi.n())
        D = DiscreteGaussianPolynomialSampler(n, stddev)
        RingLWE.__init__(self, N=N, q=q, D=D, poly=None, secret_dist='noise', m=m)
Ejemplo n.º 45
0
def curve(nb_equipes, max_points=100, K=1, R=2, base=2, verbose=False):
    r"""
    INPUT:

    - ``nb_equipes`` -- integer
    - ``max_points`` -- integer
    - ``K`` -- the value at ``p = nb_equipes``
    - ``R`` -- real (default: ``2``), curve parameter
    - ``base`` -- 2
    - ``verbose`` - bool 

    EXEMPLES::

        sage: from slabbe.ranking_scale import curve
        sage: curve(20, 100)
        -99*(p*(log(40) + 1) - p*log(p) - 20*log(40) + 20*log(20) -
        20)/(19*log(40) - 20*log(20) + 19) + 1
        sage: curve(64, 100)
        -33*(p*(7*log(2) + 1) - p*log(p) - 64*log(2) - 64)/(19*log(2) + 21) + 1

    ::

        sage: curve(64, 100)(p=64)
        1
        sage: curve(64, 100)(p=1)
        100
        sage: curve(64, 100)(p=2)
        66*(26*log(2) + 31)/(19*log(2) + 21) + 1
        sage: n(curve(64, 100)(p=2))     # abs tol 1e-10
        95.6871477097753

    ::

        sage: curve(64, 100, verbose=True)
        fn = -(p*(7*log(2) + 1) - p*log(p) - 64*log(2) - 64)/log(2)
        aire = 147.889787576005
        fn normalise = -33*(p*(7*log(2) + 1) - p*log(p) - 64*log(2) - 64)/(19*log(2) + 21) + 1
        -33*(p*(7*log(2) + 1) - p*log(p) - 64*log(2) - 64)/(19*log(2) + 21) + 1

    The base argument seems to be useless (why?)::

        sage: curve(100,100,base=3)
        -99*(p*(log(200) + 1) - p*log(p) - 100*log(200) + 200*log(10) - 
        100)/(99*log(200) - 200*log(10) + 99) + 1
        sage: curve(100,100,base=2)
        -99*(p*(log(200) + 1) - p*log(p) - 100*log(200) + 200*log(10) -
        100)/(99*log(200) - 200*log(10) + 99) + 1
        
    """
    from sage.symbolic.assumptions import forget, assume
    from sage.misc.functional import integrate, n
    from sage.functions.log import log
    from sage.calculus.var import var
    x,p = var('x,p')
    forget()
    assume(p - 1 > 0)
    assume(p-nb_equipes < 0)
    fn = integrate(log(R*nb_equipes, base=base) - log(x, base=base), x, p, nb_equipes)
    if verbose: print("fn = %s" % fn)
    aire = fn(p=1)
    if verbose: print("aire = %s" % n(aire))
    fn_normalise = fn / aire * (max_points - K) + K
    if verbose: print("fn normalise = %s" % fn_normalise)
    return fn_normalise
Ejemplo n.º 46
0
    def cluster_expansion(self, beta):
        if beta == 0:
            return dict()

        coefficients=beta.monomial_coefficients()
        if any ( x < 0 for x in coefficients.values() ):
            alpha = [ -x for x in self.initial_cluster() ]
            negative_part = dict( [(-alpha[x],-coefficients[x]) for x in
                    coefficients if coefficients[x] < 0 ] )
            positive_part = sum( [ coefficients[x]*alpha[x] for x in
                    coefficients if coefficients[x] > 0 ] )
            return dict( negative_part.items() +
                    self.cluster_expansion(positive_part).items() )

        if self.is_affine():
            if self.gamma().associated_coroot().scalar(beta) < 0:
                shifted_expansion = self.cluster_expansion( self.tau_c()(beta) )
                return dict( [ (self.tau_c_inverse()(x),shifted_expansion[x]) for x in
                    shifted_expansion ] )
            elif self.gamma().associated_coroot().scalar(beta) > 0:
                shifted_expansion = self.cluster_expansion( self.tau_c_inverse()(beta) )
                return dict( [ (self.tau_c()(x),shifted_expansion[x]) for x in
                    shifted_expansion ] )
            else:
                ###
                # Assumptions
                #
                # Two cases are possible for vectors in the interior of the cone
                # according to how many tubes there are:
                # 1) If there is only one tube then its extremal rays are linearly
                # independent, therefore a point is in the interior of the cone
                # if and only if it is a linear combination of all the extremal
                # rays with strictly positive coefficients. In this case solve()
                # should produce only one solution.
                # 2) If there are two or three tubes then the extreme rays are
                # linearly dependent. A vector is in the interior of the cone if
                # and only if it can be written as a strictly positive linear
                # combination of all the rays of at least one tube. In this case
                # solve() should return at least two solutions.
                #
                # If a vector is on one face of the cone than it can be written
                # uniquely as linear combination of the rays of that face (they
                # are linearly independent). solve() should return only one
                # solution no matter how many tubes there are.

                rays = flatten([ t[0] for t in self.affine_tubes() ])
                system = matrix( map( vector, rays ) ).transpose()
                x = vector( var ( ['x%d'%i for i in range(len(rays))] ) )
                eqs =  [ (system*x)[i] == vector(beta)[i] for i in
                        range(self._n)]
                ieqs = [ y >= 0 for y in x ]
                solutions = solve( eqs+ieqs, x, solution_dict=True )

                if not solutions:
                    # we are outside the cone
                    shifted_expansion = self.cluster_expansion( self.tau_c()(beta) )
                    return dict( [ (self.tau_c_inverse()(v),shifted_expansion[v]) for v in
                        shifted_expansion ] )

                if len(solutions) > 1 or all( v > 0 for v in solutions[0].values() ):
                    # we are in the interior of the cone
                    raise ValueError("Vectors in the interior of the cone do "
                        "not have a cluster expansion")

                # we are on the boundary of the cone
                solution_dict=dict( [(rays[i],solutions[0][x[i]]) for i in range(len(rays)) ] )
                tube_bases = [ t[0] for t in self.affine_tubes() ]
                connected_components = []
                index = 0
                for t in tube_bases:
                    component = []
                    for a in t:
                        if solution_dict[a] == 0:
                            if component:
                                connected_components.append( component )
                                component = []
                        else:
                            component.append( (a,solution_dict[a]) )
                    if component:
                        if connected_components:
                            connected_components[index] = ( component +
                                    connected_components[index] )
                        else:
                            connected_components.append( component )
                    index = len(connected_components)
                expansion = dict()
                while connected_components:
                    component = connected_components.pop()
                    c = min( [ a[1] for a in component] )
                    expansion[sum( [a[0] for a in component])] = c
                    component = [ (a[0],a[1]-c) for a in component ]
                    new_component = []
                    for a in component:
                        if a[1] == 0:
                            if new_component:
                                connected_components.append( new_component )
                                new_component = []
                        else:
                            new_component.append( a )
                    if new_component:
                        connected_components.append( new_component )
                return expansion

        if self.is_finite():
            shifted_expansion = self.cluster_expansion( self.tau_c()(beta) )
            return dict( [ (self.tau_c_inverse()(x),shifted_expansion[x]) for x
                in shifted_expansion ] )
Ejemplo n.º 47
0
def gghlite_params(n, kappa, target_lambda=_sage_const_80 , xi=None, rerand=False, gddh_hard=False):
    """
    Return GGHLite parameter estimates for a given dimension ‘n‘ and
    multilinearity level ‘κ‘.
    :param n:     lattice dimension, must be power of two
    :param kappa: multilinearity level ‘κ>1‘
    :param target_lambda: target security level
    :param xi:    pick ‘ξ‘ manually
    :param rerand:is the instance supposed to support re-randomisation
                  This should be true for ‘N‘-partite DH key
                  exchange and false for iO and friends.
    :param gddh_hard:should the GDDH problem be hard
    :returns:     parameter choices for a GGHLite-like graded-encoding scheme
    """
    n = ZZ(n)
    kappa = ZZ(kappa)
    RR = RealField(_sage_const_2 *target_lambda)
    sigma= RR(_sage_const_4 *pi*n * sqrt(e*log(_sage_const_8 *n)/pi))
    ell_g = RR(_sage_const_4 *sqrt(pi*e*n)/(sigma))
    sigma_p = RR(_sage_const_7  * n**(_sage_const_2p5 ) * log(n)**(_sage_const_1p5 ) * sigma)
    ell_b = RR(_sage_const_1p0 /(_sage_const_2p0 *sqrt(pi*e*n)) * sigma_p)
    eps = RR(log(target_lambda)/kappa)
    ell = RR(log(_sage_const_8 *n*sigma, _sage_const_2 ))
    m = RR(_sage_const_2 )
    if rerand:
        sigma_s = RR(n**(_sage_const_1p5 ) * sigma_p**_sage_const_2  * sqrt(_sage_const_8 *pi/eps)/ell_b)
        if gddh_hard:
            sigma_s *= _sage_const_2 **target_lambda * sqrt(kappa) * target_lambda / n
    else:
        sigma_s = _sage_const_1 
    normk = sqrt(n)**(kappa-_sage_const_1 ) * ((sigma_p)**_sage_const_2  * n**RR(_sage_const_1p5 ) + _sage_const_2 *sigma_s * sigma_p * n**RR(_sage_const_1p5 ))**kappa
    q_base = RR(n * ell_g * normk)

    if xi is None:
        log_negl = target_lambda
        xivar = var('xivar')
        f = (ell + log_negl) == (_sage_const_2 *xivar/(_sage_const_1 -_sage_const_2 *xivar))*log(q_base, _sage_const_2 )
        xi = RR(f.solve(xivar)[_sage_const_0 ].rhs())
        q = q_base**(ZZ(_sage_const_2 )/(_sage_const_1 -_sage_const_2 *xi))
        t = q**xi * _sage_const_2 **(-ell + _sage_const_2 )
        assert(q > _sage_const_2 *t*n*sigma**(_sage_const_1 /xi))
        assert(abs(xi*log(q, _sage_const_2 ) - log_negl - ell) <= _sage_const_0p1 )
    else:
        q = q_base**(ZZ(_sage_const_2 )/(_sage_const_1 -_sage_const_2 *xi))
        t = q**xi * _sage_const_2 **(-ell + _sage_const_2 )

    params = OrderedDict()
    params[u"κ"] = kappa
    params["n"] = n
    params[u"σ"] = sigma
    params[u"σ’"] = sigma_p
    if rerand:
        params[u"σ^*"] = sigma_s
    params[u"lnorm_κ"] = normk
    params[u"unorm_κ"] = normk# if we had re-rand at higher levels this could be bigger
    params[u"ℓ_g"] = ell_g
    params[u"ℓ_b"] = ell_b
    params[u"ǫ"] = eps
    params[u"m"] = m
    params[u"ξ"] = xi
    params["q"] = q
    params["|enc|"] = RR(log(q, _sage_const_2 ) * n)
    if rerand:
        params["|par|"] = (_sage_const_2  + _sage_const_1  + _sage_const_1 )*RR(log(q, _sage_const_2 ) * n)
    else:
        params["|par|"] = RR(log(q, _sage_const_2 ) * n)
    return params
Ejemplo n.º 48
0
    second_vector=second_point-center
    radius=norm(first_vector)
    if norm(second_vector)!=radius:
        raise ValueError("Ellipse not implemented")
    first_unit_vector=first_vector/radius
    second_unit_vector=second_vector/radius
    normal_vector=second_vector-(second_vector*first_unit_vector)*first_unit_vector
    if norm(normal_vector)==0:
        print (first_point,second_point)
        return 
    normal_unit_vector=normal_vector/norm(normal_vector)
    scalar_product=first_unit_vector*second_unit_vector
    if abs(scalar_product) == 1:
        raise ValueError("The points are alligned")
    angle=arccos(scalar_product)
    var('t')
    return parametric_plot3d(center+first_vector*cos(t)+radius*normal_unit_vector*sin(t),(0,angle),**kwds)


def _arc(p,q,s,**kwds):
    #rewrite this to use polar_plot and get points to do filled triangles
    from sage.misc.functional import det
    from sage.plot.line import line
    from sage.misc.functional import norm
    from sage.symbolic.all import pi
    from sage.plot.arc import arc

    p,q,s = map( lambda x: vector(x), [p,q,s])

    # to avoid running into division by 0 we set to be colinear vectors that are
    # almost colinear