示例#1
0
文件: test_plot.py 项目: bjodah/sympy
def plotgrid_and_save(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    p1 = plot(x)
    p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False)
    p3 = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500, show=False)
    p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False)
    # symmetric grid
    p = PlotGrid(2, 2, p1, p2, p3, p4)
    p.save(tmp_file('%s_grid1' % name))
    p._backend.close()

    # grid size greater than the number of subplots
    p = PlotGrid(3, 4, p1, p2, p3, p4)
    p.save(tmp_file('%s_grid2' % name))
    p._backend.close()

    p5 = plot(cos(x),(x, -pi, pi), show=False)
    p5[0].line_color = lambda a: a
    p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False)
    p7 = plot_contour((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False)
    # unsymmetric grid (subplots in one line)
    p = PlotGrid(1, 3, p5, p6, p7)
    p.save(tmp_file('%s_grid3' % name))
    p._backend.close()
示例#2
0
def main():
    '''
    legendre_polynomial.py : ルジャンドルの多項式
    '''
    x = symbols("x")
    psi = [1,x,x**2,x**3,x**100]
    phy = schmidt(psi)
    plot(phy[0],phy[1],phy[2],phy[3],phy[4],(x, -1.5, 1.5),ylim=(-1.5,1.5),ylabel='',xlabel='')
示例#3
0
def solve_plot_equations(eq1, eq2, x, y):
    # Solve
    solution = solve((eq1, eq2), dict=True)
    if solution:
        print('x: {0} y: {1}'.format(solution[0][x], solution[0][y]))
    else:
        print('No solution found')
    # Plot
    eq1_y = solve(eq1,'y')[0]
    eq2_y = solve(eq2, 'y')[0]
    plot(eq1_y, eq2_y, legend=True)
示例#4
0
def plot():
    e = Symbol('e')
    y = Symbol('y')
    n = Symbol('n')
    generalized_vc_bounds = (original_vc_bound, rademacher_penalty_bound)
    growth_function_bound = generate_growth_function_bound(50)
    p1 = plot(original_vc_bound(n, 0.05, growth_function_bound), (n,100, 15000), show=False, line_color = 'black')
    p2 = plot(rademacher_penalty_bound(n, 0.05, growth_function_bound), (n,100, 15000), show=False, line_color = 'blue')
    plot_implicit(Eq(e, parrondo_van_den_broek_right(e, n, 0.05, growth_function_bound)), (n,100, 15000), (e,0,5))
    # plot_implicit(Eq(e, devroye(e, n, 0.05, growth_function_bound)), (n,100, 1000), (e,0,5))
    p1.extend(p2)
    p1.show()
示例#5
0
文件: test_plot.py 项目: Lenqth/sympy
def test_issue_15265():
    from sympy.core.sympify import sympify
    from sympy.core.singleton import S

    matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    eqn = sin(x)

    p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1))
    p._backend.close()

    p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi))
    p._backend.close()

    p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14')))
    p._backend.close()

    p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1))
    p._backend.close()

    raises(ValueError,
        lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-S.Infinity, 1), ylim=(-1, 1)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
示例#6
0
def test_append_issue_7140():
    x = Symbol('x')
    p1 = plot(x)
    p2 = plot(x**2)
    p3 = plot(x + 2)

    # append a series
    p2.append(p1[0])
    assert len(p2._series) == 2

    with raises(TypeError):
        p1.append(p2)

    with raises(TypeError):
        p1.append(p2._series)
示例#7
0
文件: test_plot.py 项目: Lenqth/sympy
def plot_and_save_4(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Examples from the 'advanced' notebook
    ###

    # XXX: This raises the warning "The evaluation of the expression is
    # problematic. We are trying a failback method that may still work. Please
    # report this as a bug." It has to use the fallback because using evalf()
    # is the only way to evaluate the integral. We should perhaps just remove
    # that warning.

    with warnings.catch_warnings(record=True) as w:
        i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
        p = plot(i, (y, 1, 5))
        p.save(tmp_file('%s_advanced_integral' % name))
        p._backend.close()
        # Make sure no other warnings were raised
        for i in w:
            assert issubclass(i.category, UserWarning)
            assert "The evaluation of the expression is problematic" in str(i.message)
示例#8
0
文件: test_plot.py 项目: Lenqth/sympy
def plot_and_save_5(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    s = Sum(1/x**y, (x, 1, oo))
    p = plot(s, (y, 2, 10))
    p.save(tmp_file('%s_advanced_inf_sum' % name))
    p._backend.close()

    p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False)
    p[0].only_integers = True
    p[0].steps = True
    p.save(tmp_file('%s_advanced_fin_sum' % name))
    p._backend.close()
示例#9
0
def plot_all_Ant_fits( AntEqtbl_split ):
    """
    plot_all_Ant_fits = plot_all_Ant_fits( AntEqtbl_split )

    EXAMPLES of USAGE:
    propane_dat = cleaned_Phase_data("propane")
    propane_plts = plot_all_Ant_fits( propane_dat.AntEqParams )
    """
    fits = []
    for row in AntEqtbl_split:
        fit = AntoineEqn.subs(dict(zip([A,B,C], [float(no) for no in row[2:5]])))
        fits.append( fit )
    to_plot = []
    for fit, row in zip(fits, AntEqtbl_split):
        range = (T, float(row[0]), float(row[1]))
        to_plot.append( (fit.rhs, range ) )
    plot( *to_plot )
    return to_plot
示例#10
0
def main():
    x = symbols("x")
    rho = (1 - x**2)**(-1/2)
    color = ["b","r","g","k","c","m","y"]

    T = rodrigues_formula(rho)
    p = []


    for i in range(7):
        t = simplify(T[i])
        print ("T(",i,") = ", t)
        if i > 0 :
            p.append( plot(T[i],(x,-1.1,1.1),ylim=(-1.1,1.1),show=False,line_color=color[i]) )
            p[0].extend(p[i])
        else:
            p.append( plot((T[i],(x,-1.1,1.1)),ylim=(-1.1,1.1),show=False,line_color=color[i]) )
    p[0].show()
示例#11
0
def test_append_issue_7140():
    matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    p1 = plot(x)
    p2 = plot(x**2)
    p3 = plot(x + 2)

    # append a series
    p2.append(p1[0])
    assert len(p2._series) == 2

    with raises(TypeError):
        p1.append(p2)

    with raises(TypeError):
        p1.append(p2._series)
示例#12
0
文件: test_plot.py 项目: Lenqth/sympy
def plot_and_save_6(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Test expressions that can not be translated to np and generate complex
    # results.
    ###
    plot(sin(x) + I*cos(x)).save(tmp_file())
    plot(sqrt(sqrt(-x))).save(tmp_file())
    plot(LambertW(x)).save(tmp_file())
    plot(sqrt(LambertW(x))).save(tmp_file())

    #Characteristic function of a StudentT distribution with nu=10
    plot((meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(-I*pi)/2)
            + meijerg(((1/2,), ()), ((5, 0, 1/2), ()),
                5*x**2 * exp_polar(I*pi)/2)) / (48 * pi), (x, 1e-6, 1e-2)).save(tmp_file())
示例#13
0
def tanteo():
    """
    Compara los signos de valores adyacentes de Y. Si son distintos, guarda los
    valores en xo y x1 respectivamente para informar el intervalo.
    :return: Intervalo donde la función cambia de signo.
    """
    x0 = 0
    x1 = 0
    for i in range(len(y) - 1):
        if np.sign(y[i]) != np.sign(y[i + 1]):
            x0 = x[i]
            x1 = x[i + 1]
            print('Hay raíz en el intervalo [' + str(x0) + ', ' + str(x1) +
                  ']')
            plot(f, (h, a, b),
                 title='Método de Tanteos\n',
                 line_color='orange')

    if x0 == 0 and x1 == 0:
        print('No se hallaron raíces en el intervalo con el incremento ΔX = ' +
              str(inc))
示例#14
0
def main():
    x = symbols("x")

    m = Rational(1,3) #1/3
    k = 2 #Rational(1,2)
    rho = (1 - (k**2) * (x**2) )**(-m)
    color = ["b","r","g","k","c","m","y"]

    T = rodrigues_formula(rho,m,k)
    p = []


    for i in range(7):
        t = simplify(T[i])
        print ("T(",i,") = ", t)
        if i > 0 :
            p.append( plot(T[i],(x,-0.52,0.52),ylim=(-1.1,1.1),show=False,line_color=color[i]) )
            p[0].extend(p[i])
        else:
            p.append( plot((T[i],(x,-0.52,0.52)),ylim=(-1.1,1.1),show=False,line_color=color[i]) )
    p[0].show()
示例#15
0
文件: test_plot.py 项目: zalois/sympy
def test_append_issue_7140():
    matplotlib = import_module('matplotlib',
                               min_module_version='1.1.0',
                               catch=(RuntimeError, ))
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    p1 = plot(x)
    p2 = plot(x**2)
    p3 = plot(x + 2)

    # append a series
    p2.append(p1[0])
    assert len(p2._series) == 2

    with raises(TypeError):
        p1.append(p2)

    with raises(TypeError):
        p1.append(p2._series)
示例#16
0
def process(params: Params):
    """ Process the method """
    if not params:
        logging.error('No params provided!')
        return

    proc_hist = calc(params)

    if not proc_hist:
        messagebox.showerror('Error!', 'Unable to process')
        return

    # last middle in the processing history:
    result = round(proc_hist[-1][2], 5)

    process_window = Toplevel()
    process_window.title('Process half-division method')
    main_frame = ttk.Frame(process_window, padding='10 10 10 10')
    main_frame.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))

    p = plot(params.expression, (x, params.left_edge, params.right_edge),
             show=False,
             title=str(params.expression))
    # p.append(plot(result, 0, (x, result, result+ACCURACY),
    #               line_color='red', linestyle='-', show=False)[0])

    show_plot_btn = ttk.Button(main_frame,
                               text='Show plot',
                               command=lambda: p.show()).grid(column=1, row=0)

    save_excel_btn = ttk.Button(main_frame,
                                text='Save to CSV',
                                command=lambda: save_csv(proc_hist)).grid(
                                    column=1, row=1)

    ttk.Label(main_frame, text='Result: {}'.format(result)).grid(column=0,
                                                                 row=0)
    ttk.Label(main_frame, text='Accuracy: {}'.format(ACCURACY)).grid(column=0,
                                                                     row=1)

    # to_show = reduce(lambda full_list, ind: full_list +
    #                  [list(ind.values()), ], proc_hist, [])

    table = Table(main_frame,
                  headings=('left', 'left_va;', 'middle', 'middle_val',
                            'right', 'right_val'),
                  rows=tuple(proc_hist))

    table.grid(column=0, row=2, rowspan=12, sticky=tk.S)

    for child in main_frame.winfo_children():
        child.grid_configure(padx=5, pady=5)
示例#17
0
def double_plot_expression(expr1, expr2):
    x = Symbol('x')
    y = Symbol('y')
    expr = solve((expr1, expr2), dict=True)
    solution1 = solve(expr1, y)
    solution2 = solve(expr2, y)
    expression1 = solution1[0]
    expression2 = solution2[0]
    p = plot(expression1, expression2, legend=True, show=False)
    p[0].line_color = 'b'
    p[1].line_color = 'r'
    p.show()
    print("交点の値は" + str(expr[0]))
示例#18
0
def plot_and_save_6(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')

    ###
    # Test expressions that can not be translated to np and generate complex
    # results.
    ###
    plot(sin(x) + I * cos(x)).save(tmp_file())
    plot(sqrt(sqrt(-x))).save(tmp_file())
    plot(LambertW(x)).save(tmp_file())
    plot(sqrt(LambertW(x))).save(tmp_file())

    #Characteristic function of a StudentT distribution with nu=10
    plot((meijerg(
        ((1 / 2, ), ()),
        ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(-I * pi) / 2) + meijerg(
            ((1 / 2, ), ()),
            ((5, 0, 1 / 2),
             ()), 5 * x**2 * exp_polar(I * pi) / 2)) / (48 * pi),
         (x, 1e-6, 1e-2)).save(tmp_file())
示例#19
0
 def __init__(self):
     self.plotters = {
         "plot":
         lambda args, params: plot(*args, **params),
         "plot_parametric":
         lambda args, params: plot_parametric(*args, **params),
         "plot3d":
         lambda args, params: plot3d(*args, **params),
         "plot3d_parametric_line":
         lambda args, params: plot3d_parametric_line(*args, **params),
         "plot3d_parametric_surface":
         lambda args, params: plot3d_parametric_surface(*args, **params),
     }
示例#20
0
def test_logplot_PR_16796():
    matplotlib = import_module('matplotlib',
                               min_module_version='1.1.0',
                               catch=(RuntimeError, ))
    if not matplotlib:
        skip("Matplotlib not the default backend")
    x = Symbol('x')
    p = plot(x, (x, .001, 100), xscale='log', show=False)
    # Random number of segments, probably more than 100, but we want to see
    # that there are segments generated, as opposed to when the bug was present
    assert len(p[0].get_segments()) >= 30
    assert p[0].end == 100.0
    assert p[0].start == .001
示例#21
0
 def RenderGraf(self):
     if self.OpcoesDeVariaveis.value != "Nenhuma":
         var = eval(ParseInput(self.OpcoesDeVariaveis.value))
         for i in range(0, len(self.ListaLinhas)):
             if self.ListaLinhas[i].ExpOpt.value != "Nenhuma":
                 tempfun = eval(ParseInput(
                     self.ListaLinhas[i].ExpOpt.value))
                 Color = []
                 Color.append(
                     float.fromhex(self.ListaLinhas[i].CorOpt.value[2:3]))
                 Color.append(
                     float.fromhex(self.ListaLinhas[i].CorOpt.value[2:3]))
                 Color.append(
                     float.fromhex(self.ListaLinhas[i].CorOpt.value[4:5]))
                 if i == 0:
                     Grafico = plot(tempfun,
                                    (var, self.LimiteEsquerdo.value,
                                     self.LimiteDireito.value),
                                    show=False)
                 else:
                     Linha = plot(tempfun, (var, self.LimiteEsquerdo.value,
                                            self.LimiteDireito.value),
                                  show=False)
                     Linha.color = var, (Color[0])
                     Grafico.extend(Linha)
         backend = Grafico.backend(Grafico)
         backend.process_series()
         backend.fig.savefig("Recursos\\" + self.NomeGrafico,
                             dpi=int(self.DPI.value))
         if self.GraficoEmSi != 0:
             self.GraficoEmSi.destroy()
             self.GraficoEmSi = 0
         self.GraficoEmSi = Picture(self.AreaGrafico,
                                    "Recursos\\" + self.NomeGrafico)
     else:
         if self.GraficoEmSi != 0:
             self.GraficoEmSi.destroy()
             self.GraficoEmSi = 0
示例#22
0
def graph(expression):
    x = symbols(expression)
    image = plot(expression, show=False)
    image.save("graph.png")
    image = matplotlib.pyplot
    image.close()
    upload = vk_api.VkUpload(vk)
    photo = upload.photo_messages("graph.png")
    owner_id = photo[0]['owner_id']
    photo_id = photo[0]['id']
    access_key = photo[0]['access_key']
    attachment = f'photo{owner_id}_{photo_id}_{access_key}'
    del x, image, upload, photo
    return attachment
示例#23
0
def draw_two_graph(expr1, expr2):
    y = Symbol('y')
    print(expr1)
    print(expr2)

    solutions1 = solve(expr1, y)
    solutions2 = solve(expr2, y)
    expr_y1 = solutions1[0]
    expr_y2 = solutions2[0]

    p = plot(expr_y1, expr_y2, legend=True, show=False)
    p[0].line_color = 'b'
    p[1].line_color = 'r'
    print(f'answer = {solve((expr1, expr2), dict=True)}')
    p.show()
示例#24
0
def psolve_expressions(expr_1, expr_2):
    '''Plot the graph of input expressions and find solution that satisfies both equations'''
    solution_1y = solve(expr_1, "y")[0]
    solution_2y = solve(expr_2, "y")[0]

    p = plot(solution_1y, solution_2y, ylim=[-10, 10], legend=True, show=False)
    p[0].line_color = "r"
    p[1].line_color = "b"

    p.show()

    com_solution = solve((expr_1, expr_2), dict=True)
    sol_xy = com_solution[0]

    return sol_xy
示例#25
0
文件: test_plot.py 项目: msgoff/sympy
def plotgrid_and_save(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol("x")
    y = Symbol("y")

    p1 = plot(x)
    p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False)
    p3 = plot_parametric(cos(x),
                         sin(x),
                         adaptive=False,
                         nb_of_points=500,
                         show=False)
    p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False)
    # symmetric grid
    p = PlotGrid(2, 2, p1, p2, p3, p4)
    p.save(tmp_file("%s_grid1" % name))
    p._backend.close()

    # grid size greater than the number of subplots
    p = PlotGrid(3, 4, p1, p2, p3, p4)
    p.save(tmp_file("%s_grid2" % name))
    p._backend.close()

    p5 = plot(cos(x), (x, -pi, pi), show=False)
    p5[0].line_color = lambda a: a
    p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False)
    p7 = plot_contour(
        (x**2 + y**2, (x, -5, 5), (y, -5, 5)),
        (x**3 + y**3, (x, -3, 3), (y, -3, 3)),
        show=False,
    )
    # unsymmetric grid (subplots in one line)
    p = PlotGrid(1, 3, p5, p6, p7)
    p.save(tmp_file("%s_grid3" % name))
    p._backend.close()
示例#26
0
def test_issue_11865():
    matplotlib = import_module('matplotlib',
                               min_module_version='1.1.0',
                               catch=(RuntimeError, ))
    if not matplotlib:
        skip("Matplotlib not the default backend")
    k = Symbol('k', integer=True)
    f = Piecewise(
        (-I * exp(I * pi * k) / k + I * exp(-I * pi * k) / k, Ne(k, 0)),
        (2 * pi, True))
    p = plot(f, show=False)
    # Random number of segments, probably more than 100, but we want to see
    # that there are segments generated, as opposed to when the bug was present
    # and that there are no exceptions.
    assert len(p[0].get_segments()) >= 30
示例#27
0
def main():
    # prepare data
    numPoints = 100
    trainingSet = np.array([[0, 0, 1], [0, 1.0, 1], [5.0, 5.0, -1]])
    testSet = []
    #generatePoints(testSet,numPoints)
    print("Training Set :")
    print(trainingSet)

    var = raw_input("Select problem : (a,b, or c)")
    if var == "a":
        for i in range(len(trainingSet)):
            neighbors = getNeighbors(trainingSet[i], trainingSet)
            print("Closest Neighbors for :")
            print(trainingSet[i])
            print(neighbors)
            decisionRegions(trainingSet)
        plot(trainingSet)

    if var == "b":
        whitened = whiten(trainingSet)
        print("Whitened :")
        print(whitened)
        for i in range(len(trainingSet)):
            neighbors = getNeighbors(whitened[i], whitened)
            print("Closest Neighbors for :")
            print(whitened[i])
            print(neighbors)
            decisionRegions(whitened)
        plot(whitened)

    if var == "c":
        trainingSet = np.array([[0, 0], [0, 1.0], [5.0, 5.0]])
        pca = matplotlib.mlab.PCA(trainingSet)
        p = np.array(pca.Y)
        p = np.hstack((p, np.atleast_2d([1, 1, -1]).T))
        print("Principal Component Analysis :")
        print(p)
        for i in range(len(p)):
            neighbors = getNeighbors(p[i], p)
            print("Closest Neighbors for :")
            print(p[i])
            print(neighbors)
            decisionRegions(p)
        plot(p)

    plt.grid(True)
    plt.axhline(y=0, color='k')
    plt.axvline(x=0, color='k')
    plt.xlim(-2, 5.5)
    plt.ylim(-2, 5.5)
    plt.show()
示例#28
0
文件: mly.py 项目: alex2060/dubble
def make_eqation_F(number_of_floors, egonval, convec, y):
    row = 0
    for x in range(number_of_floors):

        if egonval[0][x] >= 0:
            add = convec[2 * x + 0] * sinh(
                math.sqrt(abs(egonval[0][x])) *
                (time)) + convec[0][2 * x + 0] * cosh(
                    math.sqrt(abs(egonval[0][x])) * (time))
        else:
            #print(convec[0])
            add = convec[2 * x + 0] * sin(
                math.sqrt(abs(egonval[0][x])) * time) + convec[
                    2 * x + 1] * cos(math.sqrt(abs(egonval[0][x])) * (time))
        row = row + add * egonval[1][y][x]
    row += f_2_l_taylor[y]

    print(row)
    print(row.subs(time, 0))
    here = latex(plot(row, (time, 0, 50)))
    return here
示例#29
0
def plot_and_save_4(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')

    ###
    # Examples from the 'advanced' notebook
    ###

    # XXX: This raises the warning "The evaluation of the expression is
    # problematic. We are trying a failback method that may still work. Please
    # report this as a bug." It has to use the fallback because using evalf()
    # is the only way to evaluate the integral. We should perhaps just remove
    # that warning.

    with warns(UserWarning, match="The evaluation of the expression is problematic"):
        i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
        p = plot(i, (y, 1, 5))
        p.save(tmp_file('%s_advanced_integral' % name))
        p._backend.close()
示例#30
0
文件: test_plot.py 项目: bjodah/sympy
def plot_and_save_4(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Examples from the 'advanced' notebook
    ###

    # XXX: This raises the warning "The evaluation of the expression is
    # problematic. We are trying a failback method that may still work. Please
    # report this as a bug." It has to use the fallback because using evalf()
    # is the only way to evaluate the integral. We should perhaps just remove
    # that warning.

    with warns(UserWarning, match="The evaluation of the expression is problematic"):
        i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
        p = plot(i, (y, 1, 5))
        p.save(tmp_file('%s_advanced_integral' % name))
        p._backend.close()
示例#31
0
    async def plot(self,
                   ctx,
                   from_: Optional[float] = -10,
                   to_: Optional[float] = 10,
                   *,
                   inp: str):
        """
            !plot from_range to_range equation1; equation2; equation3; ...

            example:
                !plot -10 10 x^2; x^3; x^4
        """
        try:
            x, y = symbols('x y')
            equations = inp.split(";")
            fx = plot(*[simplify(eq) for eq in equations], (x, from_, to_),
                      show=False)

            fx.save("assets/plot.png")
            await ctx.send(file=discord.File("assets/plot.png"))
            os.remove("assets/plot.png")

        except Exception as e:
            await ctx.send(f"{e}")
示例#32
0
def create_plot(expr, s, color='b'):
    """
    Create a plot based on whether it's 1-variable or 2-variable
    Raise Index error if we don't have any variables, or more than 2
    """
    if len(expr.free_symbols) == 1:
        var1 = list(expr.free_symbols)[0]
        p = plot(expr, (var1, s["xmin"], s["xmax"]),
                 xlim=(s["xmin"], s["xmax"]),
                 ylim=(s["ymin"], s["ymax"]),
                 legend=True,
                 show=False,
                 line_color=color)
    elif len(expr.free_symbols) == 2:
        var1, var2 = list(expr.free_symbols)
        p = plot3d(expr, (var1, s["xmin"], s["xmax"]),
                   (var2, s["ymin"], s["ymax"]),
                   xlim=(s["xmin"], s["xmax"]),
                   ylim=(s["ymin"], s["ymax"]),
                   title=str(expr),
                   show=False)
    else:
        raise IndexError("Too many or too little variables")
    return p
示例#33
0
 def plotExpression(self):
     plot(self.expression )
示例#34
0
from sympy import Symbol, pprint
import sympy as sym
import sympy.plotting as syp
import matplotlib.pyplot as plt

a = Symbol('a')
lam = Symbol('lambda')

deger1 = ((lam**a) * sym.exp(-lam))
deger2 = sym.factorial(a)

ols = deger1 / deger2
pprint(ols)

syp.plot(ols.subs({lam: 5}), (a, 0, 10), title="Poisson Distribution")
plt.show()

a_degeri = []
b_degeri = []
for deger in range(12):
    y = ols.subs({lam: 5, a: deger}).evalf()
    b_deger.append(b)
    a_deger.append(deger)
plt.plot(a_deger, b_deger)
plt.show()
"""
Ad Soyad : Halil İbrahim Türkmenoğlu
Numara : 180401006
180401006 % 4 Değerinin Sonucu = 2
GİTHUB: github.com/halillibo
示例#35
0
#    else:
#        return mydict[key]


# rationalize input
def rat(val, rational):
    if rational is False:
        return float(val)
    else:
        return Rational(val)


if __name__ == '__main__':
    from sympy.plotting import plot

    plot(eta(1, oo, x), (x, -1, 5))


# load serialized formulas
# stat from enums
def load_formulas(gname, phiname, stat, folder='./.formulas/'):
    path = folder + gname + '_' + phiname + '_' + str(stat) + '.sav'
    dill.load(open(path, 'rb'))
    try:
        return dill.load(open(path, 'rb'))
    except:
        return None


# get largets components
def get_largest_component(g, save=True):
示例#36
0
# %%
def non_unitary_psi(_t, _gamma=GAMMA):
    return B(_gamma)(_t) * Matrix([1, 0])


# %%
def unitary_psi(_t):
    return U()(_t) * Matrix([1, 0])


# %%
non_unitary_psi(t, gamma)

# %%
plot(re(non_unitary_psi(t)[0]), (t, 0, 100), line_color='r')

# %%
plot(im(non_unitary_psi(t)[1]), (t, 0, 100), line_color='b')


# %%
def lossy_norm(_t, _gamma=GAMMA):
    psi = B(_gamma)(_t) * Matrix([1, 0])
    return abs(psi[0])**2 + abs(psi[1])**2


# %%
lossy_norm(t, gamma)

# %%
示例#37
0
# from sympy.plotting import plot
# from sympy import Symbol
# x = Symbol('x')
# plot(2*x+3, 3*x+1)

from sympy.plotting import plot
from sympy import Symbol
x = Symbol('x')
p = plot(2*x+3, 3*x+1, legend=True, show=False)
p[0].line_color = 'b'
p[1].line_color = 'r'
p.show()
示例#38
0
from sympy.plotting import plot
from sympy import Symbol
x = Symbol('x')
plot(2*x+3)
示例#39
0
from sympy import symbols
from sympy.plotting import plot
import sys
x = symbols('x')
func = sys.argv[1]
p1 = plot(func,(x,0,5))
'''while (True):
	x = raw_input("Do you want another plot(y/n) : ")
	if x == 'y':
		func = raw_input("type in the function : ")
		p2 = plot(func)
		p1.extend(p2)
	elif x == 'n' :
		break
	else :
		print('Please input y or n')
p1'''

		

示例#40
0
pprint(sym.sqrt(2 * sym.pi * sigma**2))

#

part_1 = 1 / (sym.sqrt(2 * sym.pi * sigma**2))
part_2 = sy.exp((-1 * (x - mu)**2) / (2 * sigma**2))

my_gauss_function = part_1 * part_2

pprint(my_gauss_function)

#1/√2  √2/2 seklinde yazdi.

grafik = syp.plot(my_gauss_function.subs({
    mu: 1,
    sigma: 3
}), (x, -10, 10),
                  title='gauss distribution')
#(fonksion_adi.subs({mu:deger,sigma:deger}),(x,baslangic_degeri,bitis_degeri),title='grafik basligi')
print(grafik)

#

for value in range(-5, 5):
    y = my_gauss_function.subs({mu: 10, sigma: 30, x: value}).evalf()

    print("Value: ", value, "Y: ", y)

#

x_values = []
示例#41
0
from sympy import Symbol, exp, sin, cos
from sympy.plotting import (plot, plot_parametric,
                            plot3d_parametric_surface, plot3d_parametric_line,
                            plot3d)

lx = range(5)
ly = [i**2 for i in lx]

x = Symbol('x')
y = Symbol('y')
u = Symbol('u')
v = Symbol('v')
expr = x**2 - 1

b = plot(expr, (x, 2, 4), show=False)  # cartesian plot
e = plot(exp(-x), (x, 0, 4), show=False)  # cartesian plot (and coloring, see below)
f = plot3d_parametric_line(sin(x), cos(x), x, (x, 0, 10), show=False)  # 3d parametric line plot
g = plot3d(sin(x)*cos(y), (x, -5, 5), (y, -10, 10), show=False)  # 3d surface cartesian plot
h = plot3d_parametric_surface(cos(u)*v, sin(u)*v, u, (u, 0, 10), (v, -2, 2), show=False)  # 3d parametric surface plot

# Some aesthetics
e[0].line_color = lambda x: x / 4
f[0].line_color = lambda x, y, z: z / 10
g[0].surface_color = lambda x, y: sin(x)

# Some more stuff on aesthetics - coloring wrt coordinates or parameters
param_line_2d = plot_parametric((x*cos(x), x*sin(x), (x, 0, 15)), (1.1*x*cos(x), 1.1*x*sin(x), (x, 0, 15)), show=False)
param_line_2d[0].line_color = lambda u: sin(u)  # parametric
param_line_2d[1].line_color = lambda u, v: u**2 + v**2  # coordinates
param_line_2d.title = 'The inner one is colored by parameter and the outher one by coordinates'
示例#42
0
from sympy import symbols, sin, cos, pi
from sympy.plotting import plot
from sympy.functions.special.delta_functions import DiracDelta
from matplotlib import style
style.use('ggplot')

x0 = 5
x = symbols('x')
y = 5 + sin(x) + 10 * sin(x + pi / 2) + 6 * cos(pi * x)
p = plot(y)
示例#43
0
import sympy as sym
from sympy.plotting import plot
sym.init_printing(use_unicode=True) %matplotlib inline

expr = x**2-12*x+8

plot(expr, (x, -20, 20))
示例#44
0
文件: bubbles.py 项目: MiroK/fem-dofs
        # Compute the bubble
        bubble, bubble_dof = get_bubble(deg)
        # The whole hierarchy
        basis_coefs = np.zeros((len(bubble), len(bubble)))
        basis_coefs[-1] = bubble
        basis_coefs[:deg, :deg], dofs = bubble_basis(deg-1)
        dofs.append(bubble_dof)

        return basis_coefs, dofs

deg = 2
alpha, dofs = bubble_basis(deg)
poly_basis = leg.basis_functions(len(alpha))
basis = [sum(c*f for c, f in zip(row, poly_basis)) for row in alpha]

ps = plot(basis[0], (x, -1, 1), show=False)
[ps.append(plot(f, (x, -1, 1), show=False)[0]) for f in basis[1:]]
# ps.show()

# Plot is nice, but let's make sure that this is really a basis of polynomials
# Any polynomial must be expreesible in it or equivantyl Ax = 0 -> x = 0
pts = chebyshev_points(deg)
A = np.zeros((len(pts), len(basis))) 
for col, f in enumerate(basis):
    A[:, col] = lambdify(x, f, 'numpy')(pts)

print np.linalg.solve(A, np.zeros(len(pts)))
print dofs

# Do we really have a basis such that eval f_i @ dof_j is identity
dofs = np.array(dofs)
示例#45
0
 def plotExpressioFromTo(self, fromm, to):
     plot(self.expression, (self.x,fromm,to) )
示例#46
0
def plot_and_save(name):
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Examples from the 'introduction' notebook
    ###

    p = plot(x)
    p = plot(x*sin(x),x*cos(x))
    p.extend(p)
    p[0].line_color = lambda a : a
    p[1].line_color='b'
    p.title = 'Big title'
    p.xlabel = 'the x axis'
    p[1].label = 'straight line'
    p.legend = True
    p.aspect_ratio = (1,1)
    p.xlim = (-15,20)
    p.save(tmp_file('%s_basic_options_and_colors.png' % name))

    p.extend(plot(x+1))
    p.append(plot(x+3,x**2)[1])
    p.save(tmp_file('%s_plot_extend_append.png' % name))

    p[2] = plot(x**2, (x, -2, 3))
    p.save(tmp_file('%s_plot_setitem.png' % name))

    p = plot(sin(x),(x,-2*pi,4*pi))
    p.save(tmp_file('%s_line_explicit.png' % name))

    p = plot(sin(x))
    p.save(tmp_file('%s_line_default_range.png' % name))

    p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3)))
    p.save(tmp_file('%s_line_multiple_range.png' % name))


    #parametric 2d plots.
    #Single plot with default range.
    plot_parametric(sin(x), cos(x)).save(tmp_file())

    #Single plot with range.
    p = plot_parametric(sin(x), cos(x), (x, -5, 5))
    p.save(tmp_file('%s_parametric_range.png' % name))

    #Multiple plots with same range.
    p = plot_parametric((sin(x), cos(x)), (x, sin(x)))
    p.save(tmp_file('%s_parametric_multiple.png' % name))

    #Multiple plots with different ranges.
    p = plot_parametric((sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5)))
    p.save(tmp_file('%s_parametric_multiple_ranges.png' % name))

    #depth of recursion specified.
    p = plot_parametric(x, sin(x), depth=13)
    p.save(tmp_file('%s_recursion_depth' % name))

    #No adaptive sampling.
    p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500)
    p.save(tmp_file('%s_adaptive' % name))

    #3d parametric plots
    p = plot3d_parametric_line(sin(x),cos(x),x)
    p.save(tmp_file('%s_3d_line.png' % name))

    p = plot3d_parametric_line((sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3)))
    p.save(tmp_file('%s_3d_line_multiple' % name))

    p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30)
    p.save(tmp_file('%s_3d_line_points' % name))

    # 3d surface single plot.
    p = plot3d(x * y)
    p.save(tmp_file('%s_surface.png' % name))

    # Multiple 3D plots with same range.
    p = plot3d(-x * y, x * y, (x, -5, 5))
    p.save(tmp_file('%s_surface_multiple' % name))

    # Multiple 3D plots with different ranges.
    p = plot3d((x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3)))
    p.save(tmp_file('%s_surface_multiple_ranges' % name))

    # Single Parametric 3D plot
    p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y)
    p.save(tmp_file('%s_parametric_surface' % name))

    # Multiple Parametric 3D plots.
    p = plot3d_parametric_surface((x*sin(z),x*cos(z),z, (x, -5, 5), (z, -5, 5)),
                (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5)))
    p.save(tmp_file('%s_parametric_surface.png' % name))

    ###
    # Examples from the 'colors' notebook
    ###

    p = plot(sin(x))
    p[0].line_color = lambda a : a
    p.save(tmp_file('%s_colors_line_arity1.png' % name))

    p[0].line_color = lambda a, b : b
    p.save(tmp_file('%s_colors_line_arity2.png' % name))

    p = plot(x*sin(x), x*cos(x), (x, 0, 10))
    p[0].line_color = lambda a : a
    p.save(tmp_file('%s_colors_param_line_arity1.png' % name))

    p[0].line_color = lambda a, b : a
    p.save(tmp_file('%s_colors_param_line_arity2a.png' % name))

    p[0].line_color = lambda a, b : b
    p.save(tmp_file('%s_colors_param_line_arity2b.png' % name))

    p = plot3d_parametric_line(sin(x)+0.1*sin(x)*cos(7*x),
             cos(x)+0.1*cos(x)*cos(7*x),
             0.1*sin(7*x),
             (x, 0 , 2*pi))
    p[0].line_color = lambda a : sin(4*a)
    p.save(tmp_file('%s_colors_3d_line_arity1.png' % name))
    p[0].line_color = lambda a, b : b
    p.save(tmp_file('%s_colors_3d_line_arity2.png' % name))
    p[0].line_color = lambda a, b, c : c
    p.save(tmp_file('%s_colors_3d_line_arity3.png' % name))

    p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5))
    p[0].surface_color = lambda a : a
    p.save(tmp_file('%s_colors_surface_arity1.png' % name))
    p[0].surface_color = lambda a, b : b
    p.save(tmp_file('%s_colors_surface_arity2.png' % name))
    p[0].surface_color = lambda a, b, c : c
    p.save(tmp_file('%s_colors_surface_arity3a.png' % name))
    p[0].surface_color = lambda a, b, c : sqrt((a-3*pi)**2+b**2)
    p.save(tmp_file('%s_colors_surface_arity3b.png' % name))

    p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y,
             (x, -1, 1), (y, -1, 1))
    p[0].surface_color = lambda a : a
    p.save(tmp_file('%s_colors_param_surf_arity1.png' % name))
    p[0].surface_color = lambda a, b : a*b
    p.save(tmp_file('%s_colors_param_surf_arity2.png' % name))
    p[0].surface_color = lambda a, b, c : sqrt(a**2+b**2+c**2)
    p.save(tmp_file('%s_colors_param_surf_arity3.png' % name))

    ###
    # Examples from the 'advanced' notebook
    ###

    i = Integral(log((sin(x)**2+1)*sqrt(x**2+1)),(x,0,y))
    p = plot(i,(y, 1, 5))
    p.save(tmp_file('%s_advanced_integral.png' % name))

    s = summation(1/x**y,(x, 1, oo))
    p = plot(s, (y, 2, 10))
    p.save(tmp_file('%s_advanced_inf_sum.png' % name))

    p = plot(summation(1/x,(x,1,y)), (y, 2,10), show=False)
    p[0].only_integers = True
    p[0].steps = True
    p.save(tmp_file('%s_advanced_fin_sum.png' % name))


    ###
    # Test expressions that can not be translated to np and generate complex
    # results.
    ###


    plot(sin(x)+I*cos(x)).save(tmp_file())
    plot(sqrt(sqrt(-x))).save(tmp_file())
    plot(LambertW(x)).save(tmp_file())
    plot(sqrt(LambertW(x))).save(tmp_file())
示例#47
0
 def plotIndependetExpression(self, expression, fromm, to):
     x = symbols('x')
     exp = sympify(expression)
     plot(exp, (x,fromm,to), title=expression)
示例#48
0
from sympy import *
from sympy.plotting import plot
import sys

exprstr = raw_input('Enter an expression in terms of x and y: ')

x = Symbol('x')
try:
	expr1 = sympify(exprstr)
except SympifyError:
	print ('Invalid input(s)')
	sys.exit("Exiting")

p = plot(expr1, legend = true, show = false)
p.show()
示例#49
0
def ploteq(*args, **kwargs):
    """軸のアスペクト比を均等にプロットするための関数である。broken。以下の方法で均等なプロットを見ることはできるが、Plot._backend を生成するためには plot(..., show=False) とはできないようである。なので均等ではないプロットと均等なプロットとが両方表示されてしまう。しかし何にせよ、均等なプロットを見ることはできている。それらが両方表示されるのは好ましいと考えることもできる。"""
    p = plot(*args, **kwargs)
    p._backend.ax.set_aspect("equal")
    return p._backend.fig
示例#50
0
文件: test_plot.py 项目: Lenqth/sympy
def plot_and_save_3(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Examples from the 'colors' notebook
    ###

    p = plot(sin(x))
    p[0].line_color = lambda a: a
    p.save(tmp_file('%s_colors_line_arity1' % name))

    p[0].line_color = lambda a, b: b
    p.save(tmp_file('%s_colors_line_arity2' % name))
    p._backend.close()

    p = plot(x*sin(x), x*cos(x), (x, 0, 10))
    p[0].line_color = lambda a: a
    p.save(tmp_file('%s_colors_param_line_arity1' % name))

    p[0].line_color = lambda a, b: a
    p.save(tmp_file('%s_colors_param_line_arity2a' % name))

    p[0].line_color = lambda a, b: b
    p.save(tmp_file('%s_colors_param_line_arity2b' % name))
    p._backend.close()

    p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x),
             cos(x) + 0.1*cos(x)*cos(7*x),
        0.1*sin(7*x),
        (x, 0, 2*pi))
    p[0].line_color = lambdify_(x, sin(4*x))
    p.save(tmp_file('%s_colors_3d_line_arity1' % name))
    p[0].line_color = lambda a, b: b
    p.save(tmp_file('%s_colors_3d_line_arity2' % name))
    p[0].line_color = lambda a, b, c: c
    p.save(tmp_file('%s_colors_3d_line_arity3' % name))
    p._backend.close()

    p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5))
    p[0].surface_color = lambda a: a
    p.save(tmp_file('%s_colors_surface_arity1' % name))
    p[0].surface_color = lambda a, b: b
    p.save(tmp_file('%s_colors_surface_arity2' % name))
    p[0].surface_color = lambda a, b, c: c
    p.save(tmp_file('%s_colors_surface_arity3a' % name))
    p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2))
    p.save(tmp_file('%s_colors_surface_arity3b' % name))
    p._backend.close()

    p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y,
             (x, -1, 1), (y, -1, 1))
    p[0].surface_color = lambda a: a
    p.save(tmp_file('%s_colors_param_surf_arity1' % name))
    p[0].surface_color = lambda a, b: a*b
    p.save(tmp_file('%s_colors_param_surf_arity2' % name))
    p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2))
    p.save(tmp_file('%s_colors_param_surf_arity3' % name))
    p._backend.close()
from sympy.abc import x
from sympy import *
from sympy.plotting import plot

n = 1
T = n * pi
f = sin(x)**2
g = integrate(f, (x, 0, T))

print(g)
plot(f, g, (x, 0, 4 * T))
print(r)

################################################################################
import sympy as sym
from sympy import Symbol
from sympy import pprint
%matplotlib notebook
import sympy.plotting as syp
sigma = Symbol('sigma') # Gauss hesaplaması için sigma,x ve mu değerleri tanımlanıyor
x = Symbol('x')
mu = Symbol('mu')
part_1 = 1/(sym.sqrt(2*sym.pi*sigma**2)) # Gauss ifadesinin ilk kısmı hesaplanıyor
part_2 = sym.exp(-1*((x-mu)**2)/(2*sigma**2)) # İkinci kısmı hesaplanıyor
my_gauss_function = part_1*part_2 # Hesaplanan kısımlar çarpılarak gauss ifadesi elde ediliyor
pprint(my_gauss_function) # Matematiksel gösterimde gauss fonksiyonu gösteriliyor
# Subs komutu ile mu,sigma, x ifadelerine değerler atanarak plot ile grafik çizdiriliyor. Title ile grafiğe isimlendirme yapılıyor
syp.plot(my_gauss_function.subs({mu:10,sigma:30}), (x, -1000, 1000), title='gauss distribution')

# Yukarı da yapılan grafik for döngüsü ile farklı bir biçimde çizdiriliyor
x_values = []
y_values = []
for value in range(-50,50):
    y = my_gauss_function.subs({mu:0,sigma:10,x:value}).evalf() # Evalf ile ifade matematiksel hale getiriliyor
    y_values.append(y)
    x_values.append(value)
    print(value,y)

%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(x_values,y_values) # Değerler aktarılarak grafik çizdiriliyor
plt.show() # Grafik gösteriliyor
示例#53
0
    CH4dat = cleaned_Phase_data("methane")
    CH4DeltaH = float(CH4dat.DeltaH_vap[0][2][0])*1000*1000 # kJ/mol -> J/mol -> J/kmol
    CH4T_boil = CH4dat.T_boil['Value']
    CH4CCEqn = fit_ClausClapEqn(CH4T_boil, CH4DeltaH)
    CH4fits = []
    for row in CH4dat.AntEqParams:
        fit = AntoineEqn.subs(dict(zip([A,B,C],[float(no) for no in row[2:5]])))
        CH4fits.append(fit)
    return CH4dat, CH4CCEqn, CH4fits

if __name__ == "__main__":
    print "The functions to use are \n \t cleaned_Phase_data \n \t fit_ClausClapEqn \n \t plot_all_Ant_fits \n"
    
    CH4dat, CH4CCEqn, CH4fits = comparing_AntEq_vs_ClausClap()
    
    CH4Antplts = plot_all_Ant_fits(CH4dat.AntEqParams)

    plot( *CH4Antplts,title="Methane phase p vs. T", ylabel="p (bar)", xlabel="T (K)", legend=True)
    plot( CH4CCEqn.rhs,(T,95,180),title="Clausius-Clapeyron equation for Methane, p vs. T",ylabel="p (Pa)",xlabel="T(K)")

    plot(*(CH4Antplts+[(CH4CCEqn.rhs/100000,(T,95,180)),]),title="Compare Clausius-Clapeyron equation and Antoine Equation for Methane, p vs. T",ylabel="p (bar)",xlabel="T(K)")




    




示例#54
0
文件: test_plot.py 项目: Lenqth/sympy
def plot_and_save_1(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Examples from the 'introduction' notebook
    ###

    p = plot(x)
    p = plot(x*sin(x), x*cos(x))
    p.extend(p)
    p[0].line_color = lambda a: a
    p[1].line_color = 'b'
    p.title = 'Big title'
    p.xlabel = 'the x axis'
    p[1].label = 'straight line'
    p.legend = True
    p.aspect_ratio = (1, 1)
    p.xlim = (-15, 20)
    p.save(tmp_file('%s_basic_options_and_colors' % name))
    p._backend.close()

    p.extend(plot(x + 1))
    p.append(plot(x + 3, x**2)[1])
    p.save(tmp_file('%s_plot_extend_append' % name))

    p[2] = plot(x**2, (x, -2, 3))
    p.save(tmp_file('%s_plot_setitem' % name))
    p._backend.close()

    p = plot(sin(x), (x, -2*pi, 4*pi))
    p.save(tmp_file('%s_line_explicit' % name))
    p._backend.close()

    p = plot(sin(x))
    p.save(tmp_file('%s_line_default_range' % name))
    p._backend.close()

    p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3)))
    p.save(tmp_file('%s_line_multiple_range' % name))
    p._backend.close()

    raises(ValueError, lambda: plot(x, y))

    #Piecewise plots
    p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1))
    p.save(tmp_file('%s_plot_piecewise' % name))
    p._backend.close()

    p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3))
    p.save(tmp_file('%s_plot_piecewise_2' % name))
    p._backend.close()

    # test issue 7471
    p1 = plot(x)
    p2 = plot(3)
    p1.extend(p2)
    p.save(tmp_file('%s_horizontal_line' % name))
    p._backend.close()

    # test issue 10925
    f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \
        (x**2, And(0 <= x, x < 1)), (x**3, x >= 1))
    p = plot(f, (x, -3, 3))
    p.save(tmp_file('%s_plot_piecewise_3' % name))
    p._backend.close()
示例#55
0
k = Symbol('k')                     # k'nın sembolizasyonu & olay sayısı


part1 = lmbda**k                    # Lambda^k işleminin yapıldığı kısım.
part2 = sym.exp(-lmbda)             # e^(-Lambda) işleminin yapıldığı kısım.
part3 = sym.factorial(k)            # k! işleminin yapıldığı kısım.


poisson_distribution_func1 = part1*part2            # (Lambda^k)*(e^(-Lambda)) (bölümün üzerinde kalan kısmın işlemleri ve tanımlanması.)
poisson_distribution_func2 = part3                  # k! (bölümün altında kalan kısmın işlemleri ve tanımlanması.)

poisson_distribution_func_total = poisson_distribution_func1/poisson_distribution_func2             # Fonkisyonun tüm partlarının bir ara getirilmesi.

pprint(poisson_distribution_func_total)         # Fonksiyonun günlük yaşamda kullandığımız şekilde yazımı.

syp.plot(poisson_distribution_func_total.subs({lmbda:7}),(k,0,10),title="Poisson Distribution")     # sympy.plotting kütüphanesi ile grafiğin çizdirilmesi.
plt.show()

x_values = []
y_values = []

for value in range(20):                # for in range döngüsü ile grafiğin hangi aralıkta fonksiyonun kullanılacağının belirlenmesi.

    y = poisson_distribution_func_total.subs({lmbda: 7, k: value}).evalf()
    y_values.append(y)          # Listeye ekleme kısmı.
    x_values.append(value)

    print(value, y)

plt.plot(x_values, y_values)
plt.show()                      #Matplotlib kütüphanesiyle yazdırılan grafik.
示例#56
0
from sympy import fourier_series, pi, Piecewise
from sympy.abc import t
from sympy.plotting import plot

f = Piecewise((0, t < -pi), (-1, t < -pi / 2), (1, t < pi / 2), (-1, t < pi),
              (0, True))
T = 2 * pi

s = fourier_series(f, (t, -T / 2, T / 2))
F = s.truncate(5)
print(F)

n = [10, 50, 200]
p = plot(s.truncate(n[0]), (t, -10, 10),
         title="For 10 terms",
         line_color='firebrick',
         show=False)
p.xlabel = '$t$'
p.ylabel = '$F(t)$'
p.show()
p = plot(s.truncate(n[1]), (t, -10, 10),
         title="For 50 terms",
         line_color='darkblue',
         show=False)
p.xlabel = '$t$'
p.ylabel = '$F(t)$'
p.show()
p = plot(s.truncate(n[2]), (t, -10, 10),
         title="For 200 terms",
         line_color='green',
         show=False)
示例#57
0
from sympy.functions import exp, log


x = symbols('x')
 
f0 = -1/exp(x**2)

f1 = diff(f0, x)


# plot(f0, f1)

f = f0
F = f0
k = 1


for i in range(1, 5):
    f = diff(f)
    f = diff(f)
    k = k*i
    F = F + f

# print(F)
plot(F, (x, -10, 10))





示例#58
0
def plot_and_save(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')

    ###
    # Examples from the 'introduction' notebook
    ###

    p = plot(x)
    p = plot(x*sin(x), x*cos(x))
    p.extend(p)
    p[0].line_color = lambda a: a
    p[1].line_color = 'b'
    p.title = 'Big title'
    p.xlabel = 'the x axis'
    p[1].label = 'straight line'
    p.legend = True
    p.aspect_ratio = (1, 1)
    p.xlim = (-15, 20)
    p.save(tmp_file('%s_basic_options_and_colors' % name))
    p._backend.close()

    p.extend(plot(x + 1))
    p.append(plot(x + 3, x**2)[1])
    p.save(tmp_file('%s_plot_extend_append' % name))

    p[2] = plot(x**2, (x, -2, 3))
    p.save(tmp_file('%s_plot_setitem' % name))
    p._backend.close()

    p = plot(sin(x), (x, -2*pi, 4*pi))
    p.save(tmp_file('%s_line_explicit' % name))
    p._backend.close()

    p = plot(sin(x))
    p.save(tmp_file('%s_line_default_range' % name))
    p._backend.close()

    p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3)))
    p.save(tmp_file('%s_line_multiple_range' % name))
    p._backend.close()

    raises(ValueError, lambda: plot(x, y))

    #Piecewise plots
    p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1))
    p.save(tmp_file('%s_plot_piecewise' % name))
    p._backend.close()

    p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3))
    p.save(tmp_file('%s_plot_piecewise_2' % name))
    p._backend.close()

    # test issue 7471
    p1 = plot(x)
    p2 = plot(3)
    p1.extend(p2)
    p.save(tmp_file('%s_horizontal_line' % name))
    p._backend.close()

    # test issue 10925
    f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \
        (x**2, And(0 <= x, x < 1)), (x**3, x >= 1))
    p = plot(f, (x, -3, 3))
    p.save(tmp_file('%s_plot_piecewise_3' % name))
    p._backend.close()

    #parametric 2d plots.
    #Single plot with default range.
    plot_parametric(sin(x), cos(x)).save(tmp_file())

    #Single plot with range.
    p = plot_parametric(sin(x), cos(x), (x, -5, 5))
    p.save(tmp_file('%s_parametric_range' % name))
    p._backend.close()

    #Multiple plots with same range.
    p = plot_parametric((sin(x), cos(x)), (x, sin(x)))
    p.save(tmp_file('%s_parametric_multiple' % name))
    p._backend.close()

    #Multiple plots with different ranges.
    p = plot_parametric((sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5)))
    p.save(tmp_file('%s_parametric_multiple_ranges' % name))
    p._backend.close()

    #depth of recursion specified.
    p = plot_parametric(x, sin(x), depth=13)
    p.save(tmp_file('%s_recursion_depth' % name))
    p._backend.close()

    #No adaptive sampling.
    p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500)
    p.save(tmp_file('%s_adaptive' % name))
    p._backend.close()

    #3d parametric plots
    p = plot3d_parametric_line(sin(x), cos(x), x)
    p.save(tmp_file('%s_3d_line' % name))
    p._backend.close()

    p = plot3d_parametric_line(
        (sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3)))
    p.save(tmp_file('%s_3d_line_multiple' % name))
    p._backend.close()

    p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30)
    p.save(tmp_file('%s_3d_line_points' % name))
    p._backend.close()

    # 3d surface single plot.
    p = plot3d(x * y)
    p.save(tmp_file('%s_surface' % name))
    p._backend.close()

    # Multiple 3D plots with same range.
    p = plot3d(-x * y, x * y, (x, -5, 5))
    p.save(tmp_file('%s_surface_multiple' % name))
    p._backend.close()

    # Multiple 3D plots with different ranges.
    p = plot3d(
        (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3)))
    p.save(tmp_file('%s_surface_multiple_ranges' % name))
    p._backend.close()

    # Single Parametric 3D plot
    p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y)
    p.save(tmp_file('%s_parametric_surface' % name))
    p._backend.close()

    # Multiple Parametric 3D plots.
    p = plot3d_parametric_surface(
        (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)),
        (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5)))
    p.save(tmp_file('%s_parametric_surface' % name))
    p._backend.close()

    ###
    # Examples from the 'colors' notebook
    ###

    p = plot(sin(x))
    p[0].line_color = lambda a: a
    p.save(tmp_file('%s_colors_line_arity1' % name))

    p[0].line_color = lambda a, b: b
    p.save(tmp_file('%s_colors_line_arity2' % name))
    p._backend.close()

    p = plot(x*sin(x), x*cos(x), (x, 0, 10))
    p[0].line_color = lambda a: a
    p.save(tmp_file('%s_colors_param_line_arity1' % name))

    p[0].line_color = lambda a, b: a
    p.save(tmp_file('%s_colors_param_line_arity2a' % name))

    p[0].line_color = lambda a, b: b
    p.save(tmp_file('%s_colors_param_line_arity2b' % name))
    p._backend.close()

    p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x),
             cos(x) + 0.1*cos(x)*cos(7*x),
        0.1*sin(7*x),
        (x, 0, 2*pi))
    p[0].line_color = lambdify_(x, sin(4*x))
    p.save(tmp_file('%s_colors_3d_line_arity1' % name))
    p[0].line_color = lambda a, b: b
    p.save(tmp_file('%s_colors_3d_line_arity2' % name))
    p[0].line_color = lambda a, b, c: c
    p.save(tmp_file('%s_colors_3d_line_arity3' % name))
    p._backend.close()

    p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5))
    p[0].surface_color = lambda a: a
    p.save(tmp_file('%s_colors_surface_arity1' % name))
    p[0].surface_color = lambda a, b: b
    p.save(tmp_file('%s_colors_surface_arity2' % name))
    p[0].surface_color = lambda a, b, c: c
    p.save(tmp_file('%s_colors_surface_arity3a' % name))
    p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2))
    p.save(tmp_file('%s_colors_surface_arity3b' % name))
    p._backend.close()

    p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y,
             (x, -1, 1), (y, -1, 1))
    p[0].surface_color = lambda a: a
    p.save(tmp_file('%s_colors_param_surf_arity1' % name))
    p[0].surface_color = lambda a, b: a*b
    p.save(tmp_file('%s_colors_param_surf_arity2' % name))
    p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2))
    p.save(tmp_file('%s_colors_param_surf_arity3' % name))
    p._backend.close()

    ###
    # Examples from the 'advanced' notebook
    ###

    # XXX: This raises the warning "The evaluation of the expression is
    # problematic. We are trying a failback method that may still work. Please
    # report this as a bug." It has to use the fallback because using evalf()
    # is the only way to evaluate the integral. We should perhaps just remove
    # that warning.

    with warnings.catch_warnings(record=True) as w:
        i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
        p = plot(i, (y, 1, 5))
        p.save(tmp_file('%s_advanced_integral' % name))
        p._backend.close()
        # Make sure no other warnings were raised
        for i in w:
            assert issubclass(i.category, UserWarning)
            assert "The evaluation of the expression is problematic" in str(i.message)

    s = Sum(1/x**y, (x, 1, oo))
    p = plot(s, (y, 2, 10))
    p.save(tmp_file('%s_advanced_inf_sum' % name))
    p._backend.close()

    p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False)
    p[0].only_integers = True
    p[0].steps = True
    p.save(tmp_file('%s_advanced_fin_sum' % name))
    p._backend.close()

    ###
    # Test expressions that can not be translated to np and generate complex
    # results.
    ###
    plot(sin(x) + I*cos(x)).save(tmp_file())
    plot(sqrt(sqrt(-x))).save(tmp_file())
    plot(LambertW(x)).save(tmp_file())
    plot(sqrt(LambertW(x))).save(tmp_file())

    #Characteristic function of a StudentT distribution with nu=10
    plot((meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(-I*pi)/2)
            + meijerg(((1/2,), ()), ((5, 0, 1/2), ()),
                5*x**2 * exp_polar(I*pi)/2)) / (48 * pi), (x, 1e-6, 1e-2)).save(tmp_file())
def plot(*args):
    # plot requires 3 arguments: the expression and the min/max range
    # plot parses the expression and plots it within the specified range
    expr, min_range, max_range = args
    x = symbols('x')
    return plotting.plot(parse_expr(expr),(x,min_range,max_range))