Ejemplo n.º 1
0
def symbolic_sis(n, alpha, q, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon>0)
        assume(epsilon<ZZ(1)/2)
    delta_0 = var("delta_0")
    assume(delta_0>=1.0)

    e = alpha*q/sqrt(2*pi)

    if m is None:
        m = sqrt(n*log(q)/log(delta_0))

    v = e * delta_0**m * q**(n/m)  # norm of the vector

    # epsilon = exp(-pi*(|v|^2/q^2))
    f = log(1/epsilon)/pi == (v/q)**2

    # solve
    f = 2* q**2 * m * f * pi
    f = f.simplify_full()
    f = f.solve(delta_0**(2*m))[0]
    f = f.log().canonicalize_radical()
    f = f.solve(log(delta_0))[0]
    f = f.simplify_log()
    return f
Ejemplo n.º 2
0
def test_issue924():
    sage.var("a x")
    log = sage.log
    i = sympy.integrate(log(x)/a, (x, a, a+1))
    i2 = sympy.simplify(i)
    s = sage.SR(i2)
    assert s == (a*log(1+a) - a*log(a) + log(1+a) - 1)/a
Ejemplo n.º 3
0
  def nice_matrix(self):
      Mnice = Matrix(SR, self.M.nrows(), self.M.ncols())
      for edge in range(1, self.num_edges()+1):
          Mnice[0,edge] = self.M[0,edge]
      for v in range(1, self.num_vertices()+1):
          kappas = 1
          for expon, coef in self.M[v,0].dict().items():
              if expon[0]==0:
                  Mnice[v,0] += coef
              else:
                  kappas *= var("ka{0}".format(expon[0]))**coef
          if kappas != 1:
              Mnice[v,0] += kappas

          for edge in range(1, self.num_edges()+1):
              psis = 1
              for expon, coef in self.M[v,edge].dict().items():
                  if expon[0]==0:
                      Mnice[v,edge] += coef
                  elif expon[0]==1:
                      psis *= var(StrataGraph.ps_name)**coef
                  elif expon[0]==2:
                      psis *= var(StrataGraph.ps2_name)**coef
              if psis != 1:
                  Mnice[v,edge] += psis
      return Mnice
Ejemplo n.º 4
0
def check_expression(expr, var_symbols):
    """Does eval(expr) both in Sage and SymPy and does other checks."""

    # evaluate the expression in the context of Sage:
    sage.var(var_symbols)
    a = globals().copy()
    # safety checks...
    assert not "sin" in a
    a.update(sage.__dict__)
    assert "sin" in a
    e_sage = eval(expr, a)
    assert not isinstance(e_sage, sympy.Basic)

    # evaluate the expression in the context of SymPy:
    sympy.var(var_symbols)
    b = globals().copy()
    assert not "sin" in b
    b.update(sympy.__dict__)
    assert "sin" in b
    b.update(sympy.__dict__)
    e_sympy = eval(expr, b)
    assert isinstance(e_sympy, sympy.Basic)

    # Do the actual checks:
    assert sympy.S(e_sage) == e_sympy
    assert e_sage == sage.SR(e_sympy)
Ejemplo n.º 5
0
def symbolic_modulus_switching(n, alpha, q, h, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon>0)
        assume(epsilon<ZZ(1)/2)

    delta_0 = var("delta_0")
    assume(delta_0>=1.0)

    if m is None:
        m = sqrt(n*log(q)/log(delta_0))

    e = alpha*q/sqrt(2*pi)

    c = e * sqrt(m-n)/sqrt(h)

    v = delta_0**m * (q/c)**(n/m)  # norm of the vector
    v_ = v**2/m  # variance of each component

    v_r = (m-n) * e**2 *v_   # noise contribution
    v_l = h * v_ * c**2  # nose contribution of rounding noise

    # epsilon = exp(-pi*(|v|^2/q^2))

    f = log(1/epsilon)/pi == (v_l + v_r)/q**2

    # solve
    f = 2* q**2 * m * f * pi
    f = f.simplify_full()
    f = f.solve(delta_0**(2*m))[0]
    f = f.log().canonicalize_radical()
    f = f.solve(log(delta_0))[0]
    f = f.simplify_log()
    return f
Ejemplo n.º 6
0
 def q_expansion(self,n=20):
     r"""
     Give the q-expansion of the quotient.
     """
     var('q')
     et = qexp_eta(ZZ[['q']],n)
     etA= et.subs(q=q**self._arg_num).power_series(ZZ[['q']])
     etB= et.subs(q=q**self._arg_den).power_series(ZZ[['q']])
     res = etA**(self._exp_num)/etB**(self._exp_den)
     return res
Ejemplo n.º 7
0
def eqn_list_to_curve_plot(L,rat_pts):
    xpoly_rng = PolynomialRing(QQ,'x')
    poly_tup = [xpoly_rng(tup) for tup in L]
    f = poly_tup[0]
    h = poly_tup[1]
    g = f+h**2/4
    if len(g.real_roots())==0 and g(0)<0:
        return text("$X(\mathbb{R})=\emptyset$",(1,1),fontsize=50)
    X0 = [real(z[0]) for z in g.base_extend(CC).roots()]+[real(z[0]) for z in g.derivative().base_extend(CC).roots()]
    a,b = inflate_interval(min(X0),max(X0),1.5)
    groots = [a]+g.real_roots()+[b]
    if b-a<1e-7:
        a=-3
        b=3
        groots=[a,b]
    ngints = len(groots)-1
    plotzones = []
    npts = 100
    for j in range(ngints):
        c = groots[j]
        d = groots[j+1]
        if g((c+d)/2)<0:
            continue
        (c,d) = inflate_interval(c,d,1.1)
        s = (d-c)/npts
        u = c
        yvals = []
        for i in range(npts+1):
            v = g(u)
            if v>0:
                v = sqrt(v)
                w = -h(u)/2
                yvals.append(w+v)
                yvals.append(w-v)
            u += s
        (m,M) = inflate_interval(min(yvals),max(yvals),1.2)
        plotzones.append((c,d,m,M))
    x = var('x')
    y = var('y')
    plot=sum(implicit_plot(y**2 + y*h(x) - f(x), (x,R[0],R[1]),(y,R[2],R[3]), aspect_ratio='automatic', plot_points=500, zorder=1) for R in plotzones)
    xmin=min([R[0] for R in plotzones])
    xmax=max([R[1] for R in plotzones])
    ymin=min([R[2] for R in plotzones])
    ymax=max([R[3] for R in plotzones])
    for P in rat_pts:
    	(x,y,z)=eval(P.replace(':',','))
        z=ZZ(z)
     	if z: # Do not attempt to plot points at infinity
      		x=ZZ(x)/z
      		y=ZZ(y)/z**3
      		if x >= xmin and x <= xmax and y >= ymin and y <= ymax:
       			plot += point((x,y),color='red',size=40,zorder=2)
    return plot
Ejemplo n.º 8
0
def main2():
    t, n = var('t, n')
    G = symbolic_expression(t**n * (t - Integer(1))**n /
                            factorial(n) * e**t).function(t)
    T = symbolic_expression(G.integral(t, Integer(0), Integer(1))).function(n)
    print([T(j) for j in range(Integer(10))])
    print([T(j).n() for j in range(Integer(10))])
Ejemplo n.º 9
0
    def test_wt_20_eigen(self):
        N20 = KlingenEisensteinAndCuspForms(20)
        pl = N20.hecke_charpoly(2)
        x = pl.parent().gens()[0]
        pl1 = ((x + Integer(840960)) *
               (x ** Integer(2) - Integer(1378464) * x + Integer(328189501440)))
        self.assertTrue(pl == (x - Integer(119538120)) * pl1)

        x = var("x")

        f20_1 = N20.eigenform_with_eigenvalue_t2(alpha20_1)
        f20_2 = N20.eigenform_with_eigenvalue_t2(alpha20_2)
        f20_3 = N20.eigenform_with_eigenvalue_t2(alpha20_3)

        l = [f20_1, f20_2, f20_3]

        l = [f.normalize(f[(1, 1, 1)]) for f in l]

        cons20[-1] = coerce_pol(cons20[-1], alpha20_3.parent())
        self.assertTrue(cons20 == [f._construction for f in l])
        self.assertTrue(all(polynomial_to_form(c, 4) == f
                            for c, f in zip(cons20, l)))

        dcts = [f20_1_dct, f20_2_dct, f20_3_dct]

        self.assertTrue(all(coerce_dict(d, f.base_ring) == f.fc_dct for d, f in zip(dcts, l)))
Ejemplo n.º 10
0
def cohendiv():
    dig = DIG('../invgen/Traces/NLA/cohendiv.tcs')
    rs = dig.getInvs(inv_typ='eqt', seed=0, vs=dig.vs, deg=2)

    q,y,rvu,x,a,b = var('q,y,rvu,x,a,b')
    expected_rs = [-q*y - rvu + x == 0, -a*y + b == 0, -q*y - 2*b + x >= 0, -2*a*y + rvu >= 0]
    assert set(expected_rs) == set([r.inv for r in rs]), rs
Ejemplo n.º 11
0
 def test_web_latex_split_on(self):
     r"""
     Checking utility: web_latex_split_on
     """
     x = var('x')
     self.assertEqual(web_latex_split_on("test string"), "test string")
     self.assertEqual(web_latex_split_on(x**2 + 1),
                      '\\( x^{2} \\) + \\(  1 \\)')
Ejemplo n.º 12
0
 def test_web_latex_split_on_re(self):
     r"""
     Checking utility: web_latex_split_on_re
     """
     x = var('x')
     f = x**2 + 1
     expected = '\\(x^{2} \\) \\(\\mathstrut+  1 \\)'
     self.assertEqual(web_latex_split_on_re(f), expected)
Ejemplo n.º 13
0
 def test_web_latex(self):
     r"""
     Checking utility: web_latex
     """
     x = var('x')
     self.assertEqual(web_latex("test string"), "test string")
     self.assertEqual(web_latex(x**23 + 2*x + 1),
                      '\\( x^{23} + 2 \\, x + 1 \\)')
Ejemplo n.º 14
0
def root_of_unities():
    x = var("x")
    dct = {"i": x ** 2 + 1,
           "rho": x ** 2 + x + 1,
           "omega": x ** 4 + x ** 3 + x ** 2 + x + 1,
           "sigma": x ** 4 - x ** 2 + 1}
    dctnm = {k: NumberField(v, names=k) for k, v in dct.iteritems()}
    return {k: v.gens()[0] for k, v in dctnm.iteritems()}
Ejemplo n.º 15
0
 def test_Heckemethods(self):
     from sage.all import NumberField, var
     x = var('x')
     k = NumberField(x**3-x**2+x+1,'a')
     modlabel, numlabel = '82.-5a0+1a2', '5.3.3'
     mod = WebHecke.label2ideal(k, modlabel)
     assert WebHecke.ideal2label(mod) == modlabel
     num = WebHecke.label2number(numlabel)
     assert WebHecke.number2label(num) == numlabel
Ejemplo n.º 16
0
def plotit(k):
    k = int(k[0])
    # FIXME there could be a filename collission
    fn = tempfile.mktemp(suffix=".png")
    x = var('x')
    p = plot(sin(k * x))
    p.save(filename=fn)
    data = file(fn).read()
    os.remove(fn)
    return data
Ejemplo n.º 17
0
    def test_Heckemethods(self):
        from sage.all import NumberField, var

        x = var("x")
        k = NumberField(x ** 3 - x ** 2 + x + 1, "a")
        modlabel, numlabel = "82.-5a0+1a2", "5.3.3"
        mod = WebHecke.label2ideal(k, modlabel)
        assert WebHecke.ideal2label(mod) == modlabel
        num = WebHecke.label2number(numlabel)
        assert WebHecke.number2label(num) == numlabel
Ejemplo n.º 18
0
def eqn_list_to_curve_plot(L):
    xpoly_rng = PolynomialRing(QQ,'x')
    poly_tup = [xpoly_rng(tup) for tup in L]
    f = poly_tup[0]
    h = poly_tup[1]
    g = f+h**2/4
    if len(g.real_roots())==0 and g(0)<0:
        return text("$X(\mathbb{R})=\emptyset$",(1,1),fontsize=50)
    X0 = [real(z[0]) for z in g.base_extend(CC).roots()]+[real(z[0]) for z in g.derivative().base_extend(CC).roots()]
    a,b = inflate_interval(min(X0),max(X0),1.5)
    groots = [a]+g.real_roots()+[b]
    if b-a<1e-7:
        a=-3
        b=3
        groots=[a,b]
    ngints = len(groots)-1
    plotzones = []
    npts = 100
    for j in range(ngints):
        c = groots[j]
        d = groots[j+1]
        if g((c+d)/2)<0:
            continue
        (c,d) = inflate_interval(c,d,1.1)
        s = (d-c)/npts
        u = c
        yvals = []
        for i in range(npts+1):
            v = g(u)
            if v>0:
                v = sqrt(v)
                w = -h(u)/2
                yvals.append(w+v)
                yvals.append(w-v)
            u += s
        (m,M) = inflate_interval(min(yvals),max(yvals),1.2)
        plotzones.append((c,d,m,M))
    x = var('x')
    y = var('y')
    return sum(implicit_plot(y**2 + y*h(x) - f(x), (x,R[0],R[1]),
        (y,R[2],R[3]), aspect_ratio='automatic', plot_points=500) for R in
        plotzones)
Ejemplo n.º 19
0
 def test_web_latex_ideal_fact(self):
     r"""
     Checking utility: web_latex_ideal_fact
     """
     from sage.all import NumberField
     x = var('x')
     K = NumberField(x**2 - 5, 'a')
     a = K.gen()
     I = K.ideal(2/(5+a)).factor()
     self.assertEqual(web_latex_ideal_fact(I),
                      '\\( \\left(-a\\right)^{-1} \\)')
Ejemplo n.º 20
0
 def test_pol_to_html(self):
     r"""
     Checking utility: pol_to_html
     """
     x = var('x')
     f1 = x**2 + 2*x + 1
     self.assertEqual(pol_to_html(f1),
                      '<i>x</i><sup>2</sup> + 2<i>x</i> + 1')
     f2 = 'x^3 + 1'
     self.assertEqual(pol_to_html(f2),
                      '<i>x</i><sup>3</sup> + 1')
Ejemplo n.º 21
0
def EC_R_plot(ainvs, xmin, xmax, ymin, ymax, colour, legend):
    x = var("x")
    y = var("y")
    c = (xmin + xmax) / 2
    d = xmax - xmin
    return implicit_plot(
        y ** 2 + ainvs[0] * x * y + ainvs[2] * y - x ** 3 - ainvs[1] * x ** 2 - ainvs[3] * x - ainvs[4],
        (x, xmin, xmax),
        (y, ymin, ymax),
        plot_points=1000,
        aspect_ratio="automatic",
        color=colour,
    ) + plot(
        0,
        xmin=c - 1e-5 * d,
        xmax=c + 1e-5 * d,
        ymin=ymin,
        ymax=ymax,
        aspect_ratio="automatic",
        color=colour,
        legend_label=legend,
    )  # Add an extra plot outside the visible frame because implicit plots are buggy: their legend does not show (http://trac.sagemath.org/ticket/15903)
Ejemplo n.º 22
0
def _circ_arc(t0, t1, c, r, num_pts=500):
    r""" Circular arc
    INPUTS:
    - ''t0'' -- starting parameter
    - ''t1'' -- ending parameter
    - ''c''  -- center point of the circle
    - ''r''  -- radius of circle
    - ''num_pts''  -- (default 100) number of points on polygon
    OUTPUT:
    - ''ca'' -- a polygonal approximation of a circular arc centered
    at c and radius r, starting at t0 and ending at t1


    EXAMPLES::

        sage: ca=_circ_arc(0.1,0.2,0.0,1.0,100)

    """
    from sage.plot.plot import parametric_plot
    from sage.functions.trig import cos, sin
    from sage.all import var

    t00 = t0
    t11 = t1
    ## To make sure the line is correct we reduce all arguments to the same branch,
    ## e.g. [0,2pi]
    pi = RR.pi()
    while t00 < 0.0:
        t00 = t00 + RR(2.0 * pi)
    while t11 < 0:
        t11 = t11 + RR(2.0 * pi)
    while t00 > 2 * pi:
        t00 = t00 - RR(2.0 * pi)
    while t11 > 2 * pi:
        t11 = t11 - RR(2.0 * pi)

    xc = CC(c).real()
    yc = CC(c).imag()
    # L0 =
    # [[RR(r*cos(t00+i*(t11-t00)/num_pts))+xc,RR(r*sin(t00+i*(t11-t00)/num_pts))+yc]
    # for i in range(0 ,num_pts)]
    t = var("t")
    if t11 > t00:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t00, t11))
    else:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t11, t00))
    return ca
Ejemplo n.º 23
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.all import var
        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, y) = var('x,y')
        return plot3d((1 + x ** 2 + y ** 2).sqrt(),
                      (x, -x_max, x_max), (y,-x_max, x_max),
                      opacity=hyperboloid_opacity, **bdry_options)
Ejemplo n.º 24
0
    def get_constraints(m, result_as_dict=False):
        """
        Input a model m, returns its set of constraints in either
        1) sage dict {x:7,y:10}
        1) z3 expr [x==7,y==0]


        sage: S = z3.Solver()
        sage: S.add(z3.Int('x') + z3.Int('y') == z3.IntVal('7'))
        sage: S.check()
        sat
        sage: M = S.model()
        sage: d = SMT_Z3.get_constraints(M, result_as_dict=True)
        sage: sorted(d.items(), key=lambda(k,_): str(k))
        [(x, 7), (y, 0)]
        sage: SMT_Z3.get_constraints(M)
        [y == 0, x == 7]
        sage: S.reset()

        """

        assert m is not None, m

        if result_as_dict:  #sage format
            rs = [(var(str(v())),sage_eval(str(m[v]))) for v in m]
            rs = dict(rs)

            if __debug__:
                assert all(is_sage_expr(x) for x in rs.keys())
                assert all(is_sage_real(x) or is_sage_int(x) for x in rs.values())


        else:  #z3 format
            rs = [v()==m[v] for v in m]
            if __debug__:
                assert all(z3.is_expr(x) for x in rs)

        return rs
Ejemplo n.º 25
0
def _a47():
    x = var("x")
    K = NumberField(
        x ** 3 - x ** 2 - ZZ(524706) * x + ZZ(103406706), names="a47")
    return K.gens()[0]
Ejemplo n.º 26
0
def _alpha20_3():
    x = var("x")
    K = NumberField(x ** 2 - ZZ(1378464) * x + ZZ(328189501440), "alpha20_3")
    return K.gens()[0]
Ejemplo n.º 27
0
 def test_coeff_to_poly(self):
     r"""
     Checking utility: coeff_to_poly
     """
     x = var('x')
     self.assertEqual(coeff_to_poly("1 - 3x + x^2"), x**2 - 3*x + 1)
Ejemplo n.º 28
0
def Metodo_Newton(tolerancia, limite, nombre, opcion):
    """Funcion que llevara a cabo el Metodo de Newton"""
    # Primero llena un vector columna con las funciones contenidas en el documento de texto
    vectFun = Llenar_Vector_Funciones(nombre)
    # Despues crea un vector de flotantes que contendra los valores de las variables dados por el usuario   
    vectSol = np.array([1.5,3.5], dtype = 'f')
    vectSol = np.reshape(vectSol, (vectSol.shape[0], 1))
    # Declara las variables para poder calcular el jacobiano
    x,y = var('x','y')

    # Crea la matriz que contendra el jacobiano de las funciones
    matJac = np.empty(0, dtype = type(SR()))
    # Bucle que recorre todo el vector de funciones para calcular la matriz jacobiana y almacenarla en matJac
    for funcion in vectFun:
        # Ira calculando el jacobiano de cada fila
        filaJac = jacobian(funcion[0], (x,y))
        # Se selecciona 'funcion[0]' porque 'funcion' es una lista
        # Bucle que ira agregando las funciones una por una para separarlas
        for derPar in filaJac[0]:
            matJac = np.append(matJac, derPar)

    # Se usa para considerar una presicion de 6
    np.set_printoptions(precision = 6, suppress = True)

    matJac = np.reshape(matJac, ((vectFun.shape[0]), (vectFun.shape[0])))

    # Crea la matriz que se mandara como parametro para la funcion que va a calcular 'y' (aplicando el Metodo de Jacobi)
    mtrzY = np.empty((matJac.shape[0], (matJac.shape[0] + 1)), dtype = 'f')

    # Calcula la norma de 'vectSol'
    normaX1 = np.linalg.norm(vectSol)

    # Crea la matriz que contendra los valores obtenidos en cada iteracion para poder imprimirlos
    matIter = np.copy(vectSol)
    matIter = np.append(matIter, 0)

    contIt = 0
    # Bucle que se repetira hasta que el error sea menor o igual al permitido
    while True:
        # Bucle anidado que evaluara cada una de las funciones que hay en la matriz jacobiana y cada una que hay
        # en el vector columna que tiene las funciones y los resultados los ira almacenando en la matriz 'mtrzY'
        for cont1 in range(matJac.shape[0]):
            for cont2 in range(matJac.shape[0] + 1):
                # Cuando se cumple la condicion quiere decir que ahora hay que considerar la funcion del vector de funciones
                if cont2 == matJac.shape[0]:
                    # Se cambiara de signo cuando se evaluen las funciones
                    mtrzY[cont1, cont2] = (-1) * (vectFun[cont1][0].subs(x = vectSol[0, 0],y = vectSol[1, 0]))
                    continue
                mtrzY[cont1, cont2] = matJac[cont1, cont2].subs(x = vectSol[0, 0],y = vectSol[1, 0])

        if opcion == 1:
            # Manda a llamar a la funcion "Jacobi" para resolver el sistema de ecuaciones
            vectY = Met_Jacobi.Jacobi(mtrzY)
        else:
            # Calula la inversa del jacobiano y lo multiplica por el vector que contiene como valores las funciones evaluadas con signo negativo
            vectY = np.matmul(np.linalg.inv(mtrzY[:, :(matJac.shape[0])]), np.reshape(mtrzY[:, (matJac.shape[0]):], (matJac.shape[0], 1)))

        vectSol += vectY

        contIt += 1

        # Ingresa el vector 'vectSol' en una nueva columna de la matriz 'matIter'
        matIter = np.append(matIter, vectSol)

        # Calcula la norma de 'vectSol'
        normaX2 = np.linalg.norm(vectSol)

        # Calcula el error aproximado porcentual y almacena el resultado en la variable 'errorAproxPorcen'
        errorAproxPorcen = ((normaX2 - normaX1) / normaX2) * 100

        matIter = np.append(matIter, abs(errorAproxPorcen))

        if abs(errorAproxPorcen) < tolerancia:
            break

        if contIt == limite:
            matIter = np.reshape(matIter, ((contIt + 1), (vectSol.shape[0] + 1)))
            print("-" * (15 * vectSol.shape[0]))
            # Se imprimen los resultados por cada iteracion
            print(matIter)
            print("-" * (15 * vectSol.shape[0]))
            # En caso que se hayan hecho 'x' iteraciones, entonces suponemos que
            # no se ha determinado el resultado y se detiene la ejecucion del programa
            print("\n\nSe ha llegado al limite de iteraciones y no se ha encontrado un posible resultado")
            print("Pruebe con otro vector inicial\n\n")
            sys.exit(1)

        # Se copia el valor de 'normaX2' en la variable 'normaX1' para que en la siguiente iteracion se considere la norma que se acaba de calcular
        normaX1 = normaX2

    print('-' * (15 * vectSol.shape[0]))
    print((' ' * 5) + 'x' + (' ' * 4), sep = '', end = '')
    print((' ' * 5) + 'y' + (' ' * 4), sep = '', end = '')
    print((' ' * 6) + 'error')

    matIter = np.reshape(matIter, ((contIt + 1), (vectSol.shape[0] + 1)))

    print("-" * (15 * vectSol.shape[0]))
    # Se imprimen los resultados por cada iteracion
    print(matIter)
    print("-" * (15 * vectSol.shape[0]))
    print("\nSe contaron ", contIt, "iteraciones\n")

    # Regresa la solucion aproximada
    return vectSol
Ejemplo n.º 29
0
def SurfaceBetweenFunctions(f1, f2, mx=None, Mx=None):
    r"""
    Represents a surface between two functions.

    INPUT:

    - ``f1,f2`` - functions (sage or phyFunction). ``f1`` is considered
    to be the upper function while ``f2`` is the lower function.

    - ``mx,Mx`` - (optional) initial and end values of x.
    If these are not given, we suppose that `f1` and `f2` are graphs.
        If `f1` is a graph while `mx` is given, t
        he value of `f1.mx` is forgotten and the given `mx`
        is taken into account.

    EXAMPLES:

    If you want the surface to be blue ::

        sage: from yanntricks import *
        sage: surf=SurfaceBetweenFunctions(sin(x)+3,cos(x),0,2*pi)
        sage: surf.parameters.color="blue"

    If you want the function ``f1`` to be red without changing
    the color of the surface, you have to change the color AND the style::

        sage: surf.f1.parameters.color="red"

    You can also try to control the option linestyle (use add_option).

    .. literalinclude:: yanntricksexSurfaceBetweenFunction.py

    .. image:: Picture_FIGLabelFigexSurfaceBetweenFunctionPICTexSurfaceBetweenFunction-for_eps.png

    """
    mx1 = mx
    mx2 = mx
    Mx1 = Mx
    Mx2 = Mx
    if "mx" in dir(f1) and mx is None:
        mx1 = f1.mx
        Mx1 = f1.Mx
    if "mx" in dir(f2) and mx is None:
        mx2 = f2.mx
        Mx2 = f2.Mx
    # The following is a precaution because it can happen that
    # f1 has a "mx" attribute which is set to None while
    # a mx is given here.
    if mx1 is None:
        mx1 = mx
    if Mx1 is None:
        Mx1 = Mx
    if mx2 is None:
        mx2 = mx
    if Mx2 is None:
        Mx2 = Mx
    x = var('x')
    curve1 = ParametricCurve(x, f1, (mx1, Mx1))
    curve2 = ParametricCurve(x, f2, (mx2, Mx2))
    return SurfaceBetweenParametricCurves(curve1, curve2, (mx1, Mx1),
                                          (mx, Mx2))
Ejemplo n.º 30
0
    def __init__(self, base, g, markings=(), make_vars=True):
        r"""
        A ring representing the Strata algebra.

        :param Ring base: The ring of coefficients you want to work over, usually ``QQ``.
        :param int g: The genus.
        :param tuple markings: The markings should be positive integers. Repeats are allowed. Defaults to no markings.
        :param bool make_vars: Defaults to True. If True, creates variables ``ps``, ``ps_``, ``ka1``, ... , ``ka{d}`` (where d is the dimension of the moduli space) that can be used to create basis elements. Remark: in the update to Sage 9, it seems like this option does nothing now.
            
        First import the module: ::
        
            sage: from strataalgebra import *

        Construct a :class:`StrataAlgebra`: ::
            
            sage: SA = StrataAlgebra(QQ,1,(1,2)); SA
            Strata algebra with genus 1 and markings (1, 2) over Rational Field

        Print the basis elements in a certain codimension, with their (arbitrary) index: ::

            sage: SA.print_strata(2)
            **** i: 0
            [0 1 2 0 0]
            [0 0 0 2 1]
            [0 1 1 0 1]
            <BLANKLINE>
            **** i: 1
            [0 1 2 0 0]
            [0 0 1 1 1]
            [0 1 0 1 1]
            <BLANKLINE>
            **** i: 2
            [  0   1   2   0]
            [ka1   1   1   2]
            <BLANKLINE>
            **** i: 3
            [     0      1      2      0]
            [     0      1      1 ps + 2]
            <BLANKLINE>
            **** i: 4
            [     0      1      2      0]
            [     0 ps + 1      1      2]
            <BLANKLINE>
            **** i: 5
            [     0      1      2      0]
            [     0      1 ps + 1      2]
            <BLANKLINE>
            **** i: 6
            [      0       1       2       0]
            [      0       1       1       1]
            [ka1 + 1       0       0       1]
            <BLANKLINE>
            **** i: 7
            [     0      1      2      0]
            [     0      1      1      1]
            [     1      0      0 ps + 1]
            <BLANKLINE>
            **** i: 8
            ka2
            <BLANKLINE>
            **** i: 9
            ka1^2
            <BLANKLINE>
            **** i: 10
            ka1*ps1
            <BLANKLINE>
            **** i: 11
            ka1*ps2
            <BLANKLINE>
            **** i: 12
            ps1^2
            <BLANKLINE>
            **** i: 13
            ps1*ps2
            <BLANKLINE>
            **** i: 14
            ps2^2
            <BLANKLINE>


        Classes that are monomials in :math:`\psi` and :math:`\kappa` have self-explanatory names.

        More complicated classes are displayed in a matrix as follows:

        Each row after the first corresponds to a vertex of the graph.
        The constant term in the entry in the first column is the genus.
        The kappa classes also appear in the first column.
        Each column beyond the first corresponds to an edge or a half edge.
        The entry in the first row gives the label of the half edge, or ``0`` for a full edge.
        The constant term of the entry in location (v,e) gives the number of times (0, 1, or 2) that edge e touches vertex v.
        A ``ps`` in entry (v,e) means a :math:`\psi`-class associated to the half edge coming out of v.
        A ``ps_`` may occur when there is a loop at the vertex.
        The entry in the top left is just padding.

        To create classes, you can use their codimension and index.
        Boundary strata and psi-kappa monomials are represented by their special names,
        and the rest are represented by ``s_{codim},{index}`` ::

            sage: a = SA(2, 1); a
            s_2,1
            sage: b = SA(2, 7); b
            s_2,7
            sage: c = SA(2, 11); c
            ka1*ps2
            sage: d = SA(1,1); d
            Dg1

        Vector space arithmetic is supported. ::

            sage: 3*b
            3*s_2,7
            sage: a*72 - b/17
            72*s_2,1 - 1/17*s_2,7

        Use :meth:`~strataalgebra.StrataAlgebra.get_stratum` if you need to know what an unamed basis element means. ::

            sage: SA.get_stratum(2,7)
            [     0      1      2      0]
            [     0      1      1      1]
            [     1      0      0 ps + 1]

        You can construct :math:`\psi,\;\kappa` monomials and boundary divisors with the methods :meth:`~strataalgebra.StrataAlgebra.kappa`, :meth:`~strataalgebra.StrataAlgebra.psi`,
        :meth:`~strataalgebra.StrataAlgebra.boundary`, and :meth:`~strataalgebra.StrataAlgebra.irr`.

        You can construct an element using the matrix notation. Just pass a list of lists into your :class:`StrataAlgebra`. ::
        
            sage: ps = SA.ps #For convenience in the examples.
            sage: SA([[0,1,2,0],[1,0,0,ps+1],[0,1,1,1]])
            s_2,7

        Here is an example of the ``ps_``: ::

            sage: s = StrataAlgebra(QQ,2,())
            sage: s.get_stratum(3,9)
            [       0        0]
            [       1 ps^2 + 2]
            sage: s.get_stratum(3,10)
            [         0          0]
            [         1 ps*ps_ + 2]
            sage: ps_ = s.ps_
            sage: s([[0,0],[1,ps_*ps+2]])
            s_3,10

        One of the main features is the computation of the product. ::

            sage: a*b
            0

        Of course, the codimension was too big. Lets do some less trivial ones. ::

            sage: SA = StrataAlgebra(QQ,1,(1,2,3)); SA
            Strata algebra with genus 1 and markings (1, 2, 3) over Rational Field
            sage: SA.psi(1) * SA.psi(2)
            ps1*ps2
            sage: SA.get_stratum(2,7) #just so you can see what it is
            [0 1 2 3 0 0]
            [0 0 1 1 1 0]
            [0 1 0 0 1 1]
            [1 0 0 0 0 1]
            sage: SA(2,7)*SA.psi(1)
            0
            sage: SA(2,7)*SA.kappa(1)
            s_3,36
            sage: SA.get_stratum(3,36)
            [      0       1       2       3       0       0]
            [      0       0       1       1       1       0]
            [      0       1       0       0       1       1]
            [ka1 + 1       0       0       0       0       1]
            sage: SA.irr()^3
            6*s_3,4 - 3*s_3,15 - 3*s_3,23 - 3*s_3,35 + s_3,48 + s_3,49

        Everything should work with distributive laws, etc. ::

            sage: SA.kappa(2)*(3*SA.psi(3)-SA(1,3)) == -SA(1,3) *SA.kappa(2) + SA.psi(3)*SA.kappa(2)*3
            True

        It should work over any ring. ::

            sage: R.<t> = PolynomialRing(ZZ)
            sage: SA = StrataAlgebra(R, 2); SA
            Strata algebra with genus 2 and markings () over Univariate Polynomial Ring in t over Integer Ring
            sage: (3+t)*SA.kappa(1) + t^2 + t*SA.kappa(1)
            t^2*one + (2*t+3)*ka1
            sage: _^2
            t^4*one + (4*t^3+6*t^2)*ka1 + (4*t^2+12*t+9)*ka1^2


        There may be problems over a non-divisible ring. ::

            sage: SA.irr()
            Traceback (most recent call last):
            ...
            TypeError: unsupported operand parent(s) for *: 'Rational Field' and 'Strata algebra with genus 2 and markings () over Univariate Polynomial Ring in t over Integer Ring'

        Also, repeated names of the markings are allowed. The following corresponds to :math:`\overline{\mathcal M}_{1,2}/S_2`.
        Compare the codimension 2 strata to our earlier example. ::

            sage: SA = StrataAlgebra(QQ,1,(1,1)); SA
            Strata algebra with genus 1 and markings (1, 1) over Rational Field
            sage: SA.print_strata(2)
            **** i: 0
            [0 1 1 0 0]
            [0 0 0 2 1]
            [0 1 1 0 1]
            <BLANKLINE>
            **** i: 1
            [0 1 1 0 0]
            [0 0 1 1 1]
            [0 1 0 1 1]
            <BLANKLINE>
            **** i: 2
            [  0   1   1   0]
            [ka1   1   1   2]
            <BLANKLINE>
            **** i: 3
            [     0      1      1      0]
            [     0      1      1 ps + 2]
            <BLANKLINE>
            **** i: 4
            [     0      1      1      0]
            [     0 ps + 1      1      2]
            <BLANKLINE>
            **** i: 5
            [      0       1       1       0]
            [      0       1       1       1]
            [ka1 + 1       0       0       1]
            <BLANKLINE>
            **** i: 6
            [     0      1      1      0]
            [     0      1      1      1]
            [     1      0      0 ps + 1]
            <BLANKLINE>
            **** i: 7
            ka2
            <BLANKLINE>
            **** i: 8
            ka1^2
            <BLANKLINE>
            **** i: 9
            ka1*ps1
            <BLANKLINE>
            **** i: 10
            ps1^2
            <BLANKLINE>
            **** i: 11
            ps1*ps1
            <BLANKLINE>
        """

        if base not in CommutativeRings():
            raise ValueError("%s is no CommutativeRing" % base)

        self.g = g
        self.markings = markings

        self.moduli_dim = 3 * g - 3 + len(markings)

        self.strataP = StrataPyramid(g, markings)

        self._prod_dict = dict()

        self.get_stratum = self.strataP.get_stratum
        self.FZ_matrix = self.strataP.FZ_matrix
        self.print_strata = self.strataP.print_strata
        self.FZ_matrix_pushforward_basis = self.strataP.FZ_matrix_pushforward_basis

        CommutativeAlgebra.__init__(self, base)

        ### This no longer seems to do anything. Perhaps it should be removed?
        if make_vars:
            if self.moduli_dim == 1:
                var("ka1")
            elif self.moduli_dim > 1:
                var(["ka{0}".format(a) for a in range(1, self.moduli_dim + 1)])
            var(StrataGraph.ps_name, StrataGraph.ps2_name)
        ###

        ### Lets do this instead:
        self.__dict__[StrataGraph.ps_name] = var(StrataGraph.ps_name)
        self.__dict__[StrataGraph.ps2_name] = var(StrataGraph.ps2_name)
Ejemplo n.º 31
0
 def add_motor(self,position,link,longaxis):
   im = len(self.motors)+1
   Imz = var( 'I_M'+str(im), latex_name=r'I_{M'+str(im)+'}', domain=RR )
   self.Imzi.append( Imz )
   self.motors.append( (Imz,position,link,longaxis) )
Ejemplo n.º 32
0
 def transform(expr):
     if self._par_type == 'symbolic':
         return str(transform_rec(expr).subs([self._parameter==var('T')]))
     elif self._par_type == 'rational':
         h = self._field.hom(var('T'))
         return str(transform_rec(h(expr)))
Ejemplo n.º 33
0
    def collisions(self):
        r"""
        Return vertex-edge collisions.

        OUTPUT:

        A dictionary where key ``v`` is a vertex and the corresponding value
        is a list of edges ``e`` such that ``v`` collides with ``e`` for some parameter value.

        EXAMPLES::

            sage: from flexrilog import GraphMotion
            sage: GraphMotion.Deltoid().collisions()
            {0: [(1, 2), (2, 3)], 1: [(0, 3), (2, 3)], 3: [(0, 1), (1, 2)]}

        ::

            sage: from flexrilog import FlexRiGraph
            sage: t = var('t')
            sage: edges = [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 5), (3, 6), (3, 4)]
            sage: M = GraphMotion.ParametricMotion(FlexRiGraph(edges),
            ....:     {1: vector([sin(t),0]), 2: vector([sqrt(1+sin(t)^2),0]), 3: vector([-sqrt(2+sin(t)^2),0]),
            ....:     4: vector([0,cos(t)]), 5: vector([0,sqrt(1+cos(t)*cos(t))]), 6: vector([0,-sqrt(2+cos(t)^2)])},
            ....:     'symbolic')
            sage: M.collisions()
            {1: [(3, 4), (2, 4)], 4: [(1, 5), (1, 6)]}


        WARNING:

        It is not guaranteed that all collisions are found,
        since it depends on numerical root finding of complicated expressions.
        """
        def find_all_roots(eq, a, b):
            r = find_root(eq, a, b)
            res = [r]
            margin = 0.01
            r_l = r - margin
            r_r = r + margin
            try:
                if a<r_l:
                    res += find_all_roots(eq, a, r_l)
            except RuntimeError:
                pass
            try:
                if r_r<b:
                    res += find_all_roots(eq, r_r, b)
            except RuntimeError:
                pass
            return res
        res = {}
        for u in self._graph:
            res[u] = []
            for v,w in self._graph.edges(labels=False):
                if u in [v, w]:
                    continue
                z = self._parametrization[u] - self._parametrization[v]
                a = z.inner_product(z)
                z = self._parametrization[u] - self._parametrization[w]
                b = z.inner_product(z)
                z = self._parametrization[w] - self._parametrization[v]
                c = z.inner_product(z)
                if self._par_type == 'symbolic':
                    eq = sqrt(a) + sqrt(b) - sqrt(c)
                elif self._par_type == 'rational':
                    h = self._field.hom(var('T'))
                    eq = sqrt(h(a)) + sqrt(h(b)) - sqrt(h(c))
                try:
                    r = find_root(eq, self._interval[0], self._interval[1])
                    res[u].append((v,w))
                except RuntimeError:
                    pass
        for u in self._graph:
            for v,w in self._graph.edges(labels=False):
                if u in [v, w]:
                    continue
                x = self._parametrization[w] - self._parametrization[u]
                y = self._parametrization[v] - self._parametrization[u]
                eq = x[0]*y[1] - y[0]*x[1]
                if self._par_type == 'rational':
                    h = self._field.hom(var('T'))
                    eq = h(eq)
                try:
                    for r in find_all_roots(eq, self._interval[0], self._interval[1]):
                        if self._par_type == 'symbolic':
                            if x[0].subs({self._parameter:RR(r)})!=0:
                                ratio = y[0]/x[0]
                            elif x[1].subs({self._parameter:RR(r)})!=0:
                                ratio = y[1]/x[1]
                            else:
                                res[u].append((v,w))
                                continue
                            if (ratio).subs({self._parameter:RR(r)}) <= 0:
                                res[u].append((v,w))
                        elif self._par_type == 'rational':
                            if h(x[0])!=0:
                                ratio = y[0]/x[0]
                            elif h(x[1])!=0:
                                ratio = y[1]/x[1]
                            else:
                                res[u].append((v,w))
                                continue
                            h = self._field.hom(RR(r))
                            if h(ratio) <= 0:
                                res[u].append((v,w))
                        else:
                            raise NotImplementedError()
                except RuntimeError:
                    pass
        return {v: Set(res[v]).list() for v in res if res[v]}
Ejemplo n.º 34
0
def list_to_factored_poly_otherorder(s, galois=False, vari='T'):
    """ Either return the polynomial in a nice factored form,
        or return a pair, with first entry the factored polynomial
        and the second entry a list describing the Galois groups
        of the factors.
        vari allows to choose the variable of the polynomial to be returned.
    """
    gal_list = []
    if len(s) == 1:
        if galois:
            return [str(s[0]), [[0, 0]]]
        return str(s[0])
    sfacts = factor(PolynomialRing(ZZ, 'T')(s))
    sfacts_fc = [[v[0], v[1]] for v in sfacts]
    if sfacts.unit() == -1:
        sfacts_fc[0][0] *= -1
    outstr = ''
    x = var('x')
    for v in sfacts_fc:
        this_poly = v[0]
        # if the factor is -1+T^2, replace it by 1-T^2
        # this should happen an even number of times, mod powers
        if this_poly.substitute(T=0) == -1:
            this_poly = -1 * this_poly
            v[0] = this_poly
        if galois:
            this_degree = this_poly.degree()
            # hack because currently sage only handles monic polynomials:
            this_poly = expand(x**this_degree * this_poly.substitute(T=1 / x))
            this_number_field = NumberField(this_poly, "a")
            this_gal = this_number_field.galois_group(type='pari')
            this_t_number = this_gal.group()._pari_()[2].sage()
            gal_list.append([this_degree, this_t_number])
        vcf = v[0].list()
        started = False
        if len(sfacts) > 1 or v[1] > 1:
            outstr += '('
        for i in range(len(vcf)):
            if vcf[i] != 0:
                if started and vcf[i] > 0:
                    outstr += '+'
                started = True
                if i == 0:
                    outstr += str(vcf[i])
                else:
                    if abs(vcf[i]) != 1:
                        outstr += str(vcf[i])
                    elif vcf[i] == -1:
                        outstr += '-'
                    if i == 1:
                        outstr += vari  #instead of putting in T for the variable, put in a variable of your choice
                    elif i > 1:
                        outstr += vari + '^{' + str(i) + '}'
        if len(sfacts) > 1 or v[1] > 1:
            outstr += ')'
        if v[1] > 1:
            outstr += '^{' + str(v[1]) + '}'
    if galois:
        if galois and len(sfacts_fc) == 2:
            if sfacts[0][0].degree() == 2 and sfacts[1][0].degree() == 2:
                troubletest = sfacts[0][0].disc() * sfacts[1][0].disc()
                if troubletest.is_square():
                    gal_list = [[2, 1]]
        return [outstr, gal_list]
    return outstr
Ejemplo n.º 35
0
 def _createBandwidthFunctions(self):
     """Create piecewise bandwidth functions after computing position functions (SLOW!)."""
     t, px, py, pz, dSq = var('t, px, py, pz, dSq')
     self.dSquared = (self.px - px)**2 + (self.py - py)**2 + (self.pz -
                                                              pz)**2
     self.R = self.B * log(1 + self.gamma / dSq, 2)
Ejemplo n.º 36
0
 def render(self, **kwargs):
     """Render based on position functions."""
     t = var('t')
     return parametric_plot([self.px, self.py, self.pz],
                            (t, 0, self.cycleTime - 0.00001), **kwargs)
Ejemplo n.º 37
0
print "import..."
from timeit import default_timer as clock
from sage.all import var
var("x")
e = 1
print "constructing expression..."
for i in range(1, 351):
    e *= (i + x)**3
print "running benchmark..."
t1 = clock()
f = e.expand()
t2 = clock()
print "Total time:", t2 - t1, "s"
Ejemplo n.º 38
0
from sage.all import var, pi, assume, sqrt, log, ZZ, assume

n, alpha, q, h, m = var("n, alpha, q, h, m")
assume(n > 1)
assume(n, "integer")
assume(q > 2)
assume(q, "integer")
assume(alpha > 0)
assume(alpha < 1)
assume(h, "integer")
assume(h > 0)
assume(h <= n)


def symbolic_modulus_switching(n, alpha, q, h, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon > 0)
        assume(epsilon < ZZ(1) / 2)

    delta_0 = var("delta_0")
    assume(delta_0 >= 1.0)

    if m is None:
        m = sqrt(n * log(q) / log(delta_0))

    e = alpha * q / sqrt(2 * pi)

    c = e * sqrt(m - n) / sqrt(h)

    v = delta_0**m * (q / c)**(n / m)  # norm of the vector
Ejemplo n.º 39
0
  def _gensymbols(self, usefricdyn=True) :
    
    self.t = var('t',domain=RR)

    self.q = matrix(SR,self.dof,1 )
    self.dq = matrix(SR,self.dof,1 )
    self.ddq = matrix(SR,self.dof,1 )
    for i in range(1 ,self.dof+1 ):
      self.q[i-1 ] = var('q'+str(i),domain=RR)
      self.dq[i-1 ] = var('dq'+str(i),latex_name=r'\dot{q}_'+str(i),domain=RR)
      self.ddq[i-1 ] = var('ddq'+str(i),latex_name=r'\ddot{q}_'+str(i),domain=RR)

    self.qt = matrix(SR,self.dof,1 )
    for i in range(1 ,self.dof+1 ):
      self.qt[i-1 ,0 ] = function('q'+str(i)+'t',t,latex_name=r'q_'+str(i))
      
      self.LoP_trig_f2v = []
      for i in range(1 ,self.dof+1 ):
          self.LoP_trig_f2v.append( ( cos(self.q[i-1 ,0 ]) , var('c'+str(i),domain=RR) ) )
          self.LoP_trig_f2v.append( ( sin(self.q[i-1 ,0 ]) , var('s'+str(i),domain=RR) ) )
      self.LoP_trig_v2f = zip(zip(*self.LoP_trig_f2v)[1],zip(*self.LoP_trig_f2v)[0])
    
    self.D_q_v2f={} ; self.D_q_f2v={}
    for i in range(0 ,self.dof):
      self.D_q_v2f.update( { self.q[i,0 ]:self.qt[i,0 ], self.dq[i,0 ]:self.qt[i,0 ].derivative(t), self.ddq[i,0 ]:self.qt[i,0 ].derivative(t,2 ) } )
      self.D_q_f2v.update( { self.qt[i,0 ]:self.q[i,0 ], self.qt[i,0 ].derivative(t):self.dq[i,0 ], self.qt[i,0 ].derivative(t,2 ):self.ddq[i,0 ] } )
    
    
    self.mi = range(0 ,self.dof+1 )
    self.li = range(0 ,self.dof+1 )
    self.fvi = range(0 ,self.dof+1 )
    self.fci = range(0 ,self.dof+1 )
    self.Ici = range(0 ,self.dof+1 )
    self.Ifi = range(0 ,self.dof+1 )
    self.Ici_from_Ifi = range(0 ,self.dof+1 )
    self.Ifi_from_Ici = range(0 ,self.dof+1 )
    self.LoP_Ii_c2f = []
    self.LoP_Ii_f2c = []
    self.mli = range(0 ,self.dof+1 )
    self.mli_e = range(0 ,self.dof+1 )
    self.LoP_mli_v2e = []
    self.D_mli_v2e = {}

    for i in range(1 ,self.dof+1 ):

      self.mi[i] = var('m'+str(i),domain=RR)

      self.fvi[i] = var('fv'+str(i),latex_name=r'{fv}_{'+str(i)+'}',domain=RR)
      self.fci[i] = var('fc'+str(i),latex_name=r'{fc}_{'+str(i)+'}',domain=RR)
      
      aux1 = var('l_'+str(i)+'x',latex_name=r'l_{'+str(i)+',x}',domain=RR)
      aux2 = var('l_'+str(i)+'y',latex_name=r'l_{'+str(i)+',y}',domain=RR)
      aux3 = var('l_'+str(i)+'z',latex_name=r'l_{'+str(i)+',z}',domain=RR)
      self.li[i] = matrix([[aux1],[aux2],[aux3]])
      
      aux1 = var('ml_'+str(i)+'x',latex_name=r'\widehat{m_'+str(i)+'l_{'+str(i)+',x}}',domain=RR)
      aux2 = var('ml_'+str(i)+'y',latex_name=r'\widehat{m_'+str(i)+'l_{'+str(i)+',y}}',domain=RR)
      aux3 = var('ml_'+str(i)+'z',latex_name=r'\widehat{m_'+str(i)+'l_{'+str(i)+',z}}',domain=RR)
      self.mli[i] = matrix([[aux1],[aux2],[aux3]])
      self.mli_e[i] = self.mi[i] * self.li[i]
      self.LoP_mli_v2e.append( ( self.mli[i][0 ,0 ] , self.mli_e[i][0 ,0 ] ) )
      self.LoP_mli_v2e.append( ( self.mli[i][1 ,0 ] , self.mli_e[i][1 ,0 ] ) )
      self.LoP_mli_v2e.append( ( self.mli[i][2 ,0 ] , self.mli_e[i][2 ,0 ] ) )
    
      auxIcxx = var('I_'+str(i)+'xx',latex_name=r'I_{'+str(i)+',xx}',domain=RR)
      auxIcyy = var('I_'+str(i)+'yy',latex_name=r'I_{'+str(i)+',yy}',domain=RR)
      auxIczz = var('I_'+str(i)+'zz',latex_name=r'I_{'+str(i)+',zz}',domain=RR)
      auxIcxy = var('I_'+str(i)+'xy',latex_name=r'I_{'+str(i)+',xy}',domain=RR)
      auxIcxz = var('I_'+str(i)+'xz',latex_name=r'I_{'+str(i)+',xz}',domain=RR)
      auxIcyz = var('I_'+str(i)+'yz',latex_name=r'I_{'+str(i)+',yz}',domain=RR)
      self.Ici[i] = matrix([[auxIcxx,auxIcxy,auxIcxz],[auxIcxy,auxIcyy,auxIcyz],[auxIcxz,auxIcyz,auxIczz]])
      
      auxIfxx = var('If_'+str(i)+'xx',latex_name=r'\hat{I}_{'+str(i)+',xx}',domain=RR)
      auxIfyy = var('If_'+str(i)+'yy',latex_name=r'\hat{I}_{'+str(i)+',yy}',domain=RR)
      auxIfzz = var('If_'+str(i)+'zz',latex_name=r'\hat{I}_{'+str(i)+',zz}',domain=RR)
      auxIfxy = var('If_'+str(i)+'xy',latex_name=r'\hat{I}_{'+str(i)+',xy}',domain=RR)
      auxIfxz = var('If_'+str(i)+'xz',latex_name=r'\hat{I}_{'+str(i)+',xz}',domain=RR)
      auxIfyz = var('If_'+str(i)+'yz',latex_name=r'\hat{I}_{'+str(i)+',yz}',domain=RR)
      self.Ifi[i] = matrix([[auxIfxx,auxIfxy,auxIfxz],[auxIfxy,auxIfyy,auxIfyz],[auxIfxz,auxIfyz,auxIfzz]])
      
      self.Ifi_from_Ici[i] = self.Ici[i] + self.mi[i] * utils.skew(self.li[i]).transpose() * utils.skew(self.li[i])
      self.Ici_from_Ifi[i] = self.Ifi[i] - self.mi[i] * utils.skew(self.li[i]).transpose() * utils.skew(self.li[i])
      for e in [(a,b) for a in range(3) for b in range (3)]:
          self.LoP_Ii_f2c.append( ( self.Ifi[i][e] , self.Ifi_from_Ici[i][e] ) )
          self.LoP_Ii_c2f.append( ( self.Ici[i][e] , self.Ici_from_Ifi[i][e] ) )
    
    self.D_mli_v2e = utils.LoP_to_D( self.LoP_mli_v2e )
    self.D_Ii_f2c = utils.LoP_to_D( self.LoP_Ii_f2c )
    self.D_Ii_c2f = utils.LoP_to_D( self.LoP_Ii_c2f )
    self.D_parm_lin2elem =  utils.LoP_to_D( self.LoP_mli_v2e + self.LoP_Ii_f2c )
    
    Pi = [ matrix([ self.mi[i], self.mli[i][0,0], self.mli[i][1,0], self.mli[i][2,0], self.Ifi[i][0,0], self.Ifi[i][0,1], self.Ifi[i][0,2], self.Ifi[i][1,1], self.Ifi[i][1,2], self.Ifi[i][2,2] ] ).transpose() for i in range(1,self.dof+1) ]

    return self
Ejemplo n.º 40
0
def EC_R_plot(ainvs, xmin, xmax, ymin, ymax, colour, legend):
    x = var('x')
    y = var('y')
    c = (xmin + xmax) / 2
    d = (xmax - xmin)
    return implicit_plot(y ** 2 + ainvs[0] * x * y + ainvs[2] * y - x ** 3 - ainvs[1] * x ** 2 - ainvs[3] * x - ainvs[4], (x, xmin, xmax), (y, ymin, ymax), plot_points=500, aspect_ratio="automatic", color=colour) + plot(0, xmin=c - 1e-5 * d, xmax=c + 1e-5 * d, ymin=ymin, ymax=ymax, aspect_ratio="automatic", color=colour, legend_label=legend)  # Add an extra plot outside the visible frame because implicit plots are buggy: their legend does not show (http://trac.sagemath.org/ticket/15903)
Ejemplo n.º 41
0
def list_to_factored_poly_otherorder(s, galois=False, vari = 'T'):
    """ Either return the polynomial in a nice factored form,
        or return a pair, with first entry the factored polynomial
        and the second entry a list describing the Galois groups
        of the factors.
        vari allows to choose the variable of the polynomial to be returned.
    """
    gal_list=[]
    if len(s) == 1:
        if galois:
            return [str(s[0]), [[0,0]]]
        return str(s[0])
    sfacts = factor(PolynomialRing(ZZ, 'T')(s))
    sfacts_fc = [[v[0],v[1]] for v in sfacts]
    if sfacts.unit() == -1:
        sfacts_fc[0][0] *= -1
    outstr = ''
    x = var('x')
    for v in sfacts_fc:
        this_poly = v[0]
        # if the factor is -1+T^2, replace it by 1-T^2
        # this should happen an even number of times, mod powers
        if this_poly.substitute(T=0) == -1:
            this_poly = -1*this_poly
            v[0] = this_poly
        if galois:
            this_degree = this_poly.degree()
                # hack because currently sage only handles monic polynomials:
            this_poly = expand(x**this_degree*this_poly.substitute(T=1/x))
            this_number_field = NumberField(this_poly, "a")
            this_gal = this_number_field.galois_group(type='pari')
            this_t_number = this_gal.group().__pari__()[2].sage()
            gal_list.append([this_degree, this_t_number])
        vcf = v[0].list()
        started = False
        if len(sfacts) > 1 or v[1] > 1:
            outstr += '('
        for i in range(len(vcf)):
            if vcf[i] != 0:
                if started and vcf[i] > 0:
                    outstr += '+'
                started = True
                if i == 0:
                    outstr += str(vcf[i])
                else:
                    if abs(vcf[i]) != 1:
                        outstr += str(vcf[i])
                    elif vcf[i] == -1:
                        outstr += '-'
                    if i == 1:
                        outstr += vari #instead of putting in T for the variable, put in a variable of your choice
                    elif i > 1:
                        outstr += vari + '^{' + str(i) + '}'
        if len(sfacts) > 1 or v[1] > 1:
            outstr += ')'
        if v[1] > 1:
            outstr += '^{' + str(v[1]) + '}'
    if galois:
        if galois and len(sfacts_fc)==2:
            if sfacts[0][0].degree()==2 and sfacts[1][0].degree()==2:
                troubletest = sfacts[0][0].disc()*sfacts[1][0].disc()
                if troubletest.is_square():
                    gal_list=[[2,1]]
        return [outstr, gal_list]
    return outstr
Ejemplo n.º 42
0
from timeit import default_timer as clock
from sage.all import var
var("x y z")
e = (x + y + z + 1)**15
f = e * (e + 1)
print f
t1 = clock()
g = f.expand()
t2 = clock()
print "Total time:", t2 - t1, "s"
Ejemplo n.º 43
0
 def test_coeff_to_poly(self):
     r"""
     Checking utility: coeff_to_poly
     """
     x = var('x')
     self.assertEqual(coeff_to_poly("1 - 3x + x^2"), x**2 - 3 * x + 1)
Ejemplo n.º 44
0
from timeit import default_timer as clock
from sage.all import var
var("x y z w")
e = (x+y+z+w)**15
f = e*(e+w)
print f
t1 = clock()
g = f.expand()
t2 = clock()
print("Total time:", t2-t1, "s")
Ejemplo n.º 45
0
from timeit import default_timer as clock
from sage.all import var
var("x y z w")
e = (x+y+z+w)**15
f = e*(e+w)
print f
t1 = clock()
g = f.expand()
t2 = clock()
print "Total time:", t2-t1, "s"
Ejemplo n.º 46
0
 def _sage_(self):
     import sage.all as sage
     return sage.var(self.name)
Ejemplo n.º 47
0
 def _sage_(self):
     import sage.all as sage
     return sage.var(self.name)
Ejemplo n.º 48
0
def Intersection(f, g, a=None, b=None, numerical=False):
    """
    Return the list of intersection point between `f` and `g`.

    When f and g are objects with an attribute equation, return
    the list of points of intersections.

  - The list of point is sorted by order of `x` coordinates.
  - Return only real solutions.

    Only numerical approximations are returned as there are some errors
    otherwise. As an example the following #solving return points that
    are not even near from the circle \f$ x^2+y^2=9 \f$ :
    ``` #pylint:disable=line-too-long
    solve( [ -1/3*sqrt(3)*y + 1/3*sqrt(3)*(-0.19245008972987399*sqrt(3) - 3) + x == 0,x^2 + y^2 - 9 == 0 ],[x,y] )
    ```

     Examples
    ```
    sage: from yanntricks import *
    sage: fun=phyFunction(x**2-5*x+6)
    sage: droite=phyFunction(2)
    sage: pts = Intersection(fun,droite)
    sage: for P in pts:print P
    <Point(1,2)>
    <Point(4,2)>
    ```

   ```
    sage: f=phyFunction(sin(x))
    sage: g=phyFunction(cos(x))
    sage: pts=Intersection(f,g,-2*pi,2*pi,numerical=True)
    sage: for P in pts:print P
    <Point(-5.497787143782138,0.707106781186548)>
    <Point(-2.3561944901923466,-0.707106781186546)>
    <Point(0.7853981633974484,0.707106781186548)>
    <Point(3.926990816987241,-0.707106781186547)>
    ```

    If 'numerical' is True, it searchs for the intersection points
    of the functions 'f' and 'g' (it only work with functions).
    In this case an interval is required.
    """
    from yanntricks.src.affine_vector import AffineVector
    from yanntricks.src.SmallComputations import find_roots_recursive
    from yanntricks.src.point import Point

    if isinstance(f, AffineVector):
        f = f.segment
    if isinstance(g, AffineVector):
        g = g.segment

    if numerical and "sage" in dir(f):
        k = f - g
        xx = find_roots_recursive(k.sage, a, b)
        pts = [Point(x, f(x)) for x in xx]
        return pts

    x, y = var('x,y')
    pts = []
    if numerical:
        soluce = solve(
            [f.equation(numerical=True),
             g.equation(numerical=True)], [x, y])
    else:
        soluce = solve([f.equation(), g.equation()], [x, y])
    for s in soluce:
        a = s[0].rhs()
        b = s[1].rhs()
        ok1, a = test_imaginary_part(a)
        ok2, b = test_imaginary_part(b)
        if ok1 and ok2:
            pts.append(Point(a, b))
    return pts