async def graph(client, message): args = message.command try: if "arg" not in args: return # nothing to plot await client.send_chat_action(message.chat.id, "upload_document") expr = args["arg"] logger.info(f"Plotting \'{expr}\'") eq = [] for a in expr.split(", "): eq.append(parse_expr(a).simplify()) if "-3d" in args["flags"]: plot3d(*eq, show=False).save("graph.png") else: plot(*eq, show=False).save("graph.png") await client.send_photo(message.chat.id, "graph.png", reply_to_message_id=message.message_id, caption=f"` → {eq} `") except Exception as e: traceback.print_exc() await edit_or_reply(message, "`[!] → ` " + str(e)) await client.send_chat_action(message.chat.id, "cancel") await client.set_offline()
def da_solver(DA_type): import sympy #Currently LDA is definitely broken. #A bug was introduced when I was refactoring if (DA_type == 'LDA'): lhs_inv_cov = invcovall lhs_det = sympy.Matrix([0]) rhs_inv_cov = invcovall rhs_det = sympy.Matrix([0]) if (DA_type == 'QDA'): lhs_inv_cov = invcov1 lhs_det = sympy.Matrix([np.log(np.sqrt(1 / detcov1))]) rhs_inv_cov = invcov2 rhs_det = sympy.Matrix([np.log(np.sqrt(1 / detcov2))]) sympy.var('y0') sympy.var('x0') cept_mat = sympy.Matrix([x0 - x1_mean, y0 - y1_mean]) lhs_inv_cov = sympy.Matrix(lhs_inv_cov) LHS = ((cept_mat.T).multiply(lhs_inv_cov)).multiply(cept_mat) cept_mat = sympy.Matrix([x0 - x2_mean, y0 - y2_mean]) rhs_inv_cov = sympy.Matrix(rhs_inv_cov) RHS = ((cept_mat.T).multiply(rhs_inv_cov)).multiply(cept_mat) equation = (LHS - RHS) if (DA_type == 'QDA'): s1p = sympy.plot_implicit((equation[0]) > 0) if (DA_type == 'LDA'): solution = sympy.solve(equation[0], y0) sympy.plot(solution[0][y0]) return equation
def animate(ti): p = sym.plot(x.subs(t, tau), (tau, taud[0], taud[-1]), show=False) line_x.set_segments(p[0].get_segments()) p = sym.plot(h.subs(t, t - tau).subs(t, ti), (tau, taud[0], taud[-1]), show=False) line_h.set_segments(p[0].get_segments()) p = sym.plot(y, (t, taud[0], taud[-1]), show=False) line_y.set_segments(p[0].get_segments()) p = sym.plot(x.subs(t, tau) * h.subs(t, ti - tau), (tau, -5, 5), show=False) # see https://github.com/sympy/sympy/issues/21392 #points = np.array(p[0].get_points()) # alternative via lambdify func = sym.lambdify(tau, x.subs(t, tau) * h.subs(t, ti - tau), modules=['numpy', {'Heaviside':my_heaviside}]) tt = np.linspace(-5,5,100) points = np.vstack((tt, np.asarray(func(tt)))) verts = [[(xi[0], xi[1]) for xi in points.T]] fill.set_verts(verts) dot.set_data(ti, y.subs(t, ti))
def metoda_najmniejszych_kwadratow(polynomial_degree, *points): y_matrix = Matrix([[]]) x_matrix = Matrix([[]]) for point in points: y_matrix = y_matrix.col_join(Matrix([[point[1]]])) auxiliary = Matrix([[]]) for i in range(polynomial_degree + 1): auxiliary = auxiliary.row_join(Matrix([[point[0]**i]])) x_matrix = x_matrix.col_join(auxiliary) x_transposed = x_matrix.T x_transposed_times_x = x_transposed * x_matrix if x_transposed_times_x.det() == 0: print( "Macierz X^T * X ma wyznacznik równy 0, nie jest więc odwracalna.") return b_matrix = x_transposed_times_x**-1 * x_transposed * y_matrix x, y = symbols("x, y") polynomial_formula_matrix = Matrix([[]]) for i in range(polynomial_degree + 1): polynomial_formula_matrix = polynomial_formula_matrix.row_join( Matrix([[x**i]])) polynomial_formula_matrix = polynomial_formula_matrix * b_matrix print("y = " + str(simplify(polynomial_formula_matrix[0, 0])) + "\n") # for plotting to work the Python interpreter must have matplotlib available for use # otherwise SymPy will use TextBackend library for plotting which does not work whatsoever if matplotlib_is_available: plot(polynomial_formula_matrix[0, 0])
def serie_potencias_graficar(fn, a, ns, f0): # funcion, variable, suma f, x, g = sp.symbols('f,x,g') f = fn L = sp.plot(f, (x, -1, 1), ylim=(0.5, -6), show=False, legend=True) L.label = '$f$' for n in ns: g = sp.diff(f, x, 0).subs(x, a) / sp.factorial(0) * ((x - a) ** 0) conTerminos = 0 i = 1 # sumatoria en for dependiendo del número de terminos # Se itera en base al número de términos que sean VALIDOS while conTerminos <= n - 1: termino_nuevo = sp.diff(f, x, i).subs(x, a) / sp.factorial(i) * ((x - a) ** i) termino_nuevo_ev = termino_nuevo.evalf(subs={x: f0}) # print(termino_nuevo_ev) if (termino_nuevo_ev != 0): conTerminos += 1 g += termino_nuevo i += 1 M = sp.plot(g, (x, -1, 1), ylim=(0.5, -6), show=False, legend=True) M[0].label = 'n={}'.format(n) ##color random r = lambda: random.randint(0, 255) color = '#%02X%02X%02X' % (r(), r(), r()) M[0].line_color = color L.append(M[0]) L.show()
def falsi(): x = symbols('x') f = x ** 3 + x - 1 func = lambdify(x, f) a = -1 b = 1 tol = 0.000001 xc = (b * func(a) - a * func(b)) / (func(a) - func(b)) while b - a > tol: f_xc = func(xc) if f_xc == 0: break else: f_a = func(a) f_b = func(b) if (f_a * f_xc) < 0: b = xc else: a = xc xc = (b * f_a - a * f_b) / (f_a - f_b) # 输出结果并打印函数图像 print("方程[ %s = 0 ]在误差范围为(%f)的近似解为x = %f" % (f, tol, xc)) plot(f, (x, -1, 1))
async def graph_cmd(client, message): """plot provided function This command will run sympy `plot` and return result as image. You can add the `-3d` argument to plot in 3d (pass functions with 3 variables!) """ if len(message.command) < 1: return await edit_or_reply(message, "`[!] → ` No input") prog = ProgressChatAction(client, message.chat.id, action="upload_document") expr = message.command.text eq = [] for a in expr.split(", "): eq.append(parse_expr(a).simplify()) if message.command["-3d"]: plot3d(*eq, show=False).save("graph.png") else: plot(*eq, show=False).save("graph.png") await client.send_photo(message.chat.id, "graph.png", reply_to_message_id=message.message_id, caption=f"` → {eq} `", progress=prog.tick)
def DrawFourier(a0, an, bn, wo, t, n, armonicos): Ft = an * sym.cos(n * w0 * t) + bn * sym.sin(n * w0 * t) j = a0 for i in range(1, armonicos): j += Ft.subs(n, i) sym.plot(j)
def serie_potencias_calcular_estimar(fn, a, n, f0): #funcion, variable, suma f, x, g = sp.symbols('f,x,g') f = fn L = sp.plot(sp.integrate(f), (x, -1, 1), show=False, legend=True) L.label = '$f$' error = 10000 while abs(error) > (10**(-4)): g = (sp.diff(f, x, 0).subs(x, a) / sp.factorial(0)) * ((x - a)**0) conTerminos = 0 i = 1 #sumatoria en for dependiendo del número de terminos #Se itera en base al número de términos que sean VALIDOS while (conTerminos <= n - 1): termino_nuevo = sp.diff(f, x, i).subs(x, a) / sp.factorial(i) * ( (x - a)**i) termino_nuevo_ev = termino_nuevo.evalf(subs={x: f0}) if (termino_nuevo_ev != 0): conTerminos += 1 g += termino_nuevo i += 1 g_next_diff = sp.diff(f, x, n + 1) M = sp.plot(sp.integrate(g), (x, -1, 1), show=False, legend=True) M[0].label = 'n={}'.format(n) ##color random r = lambda: random.randint(0, 255) color = '#%02X%02X%02X' % (r(), r(), r()) M[0].line_color = color L.append(M[0]) g = sp.integrate(g) #obtenemos M m = get_m(g_next_diff, f0, a) #print(m) #Calculamos el error absoluto error = np.float(((np.float(m)) * ((np.abs(f0 - a))**(n + 1))) / np.math.factorial(n + 1)) #print(g) val_estimado = g.evalf(subs={x: 1.0}) print( f'El valor estimado da igual por la serie para x=pi/60 es igual = {val_estimado:.8}' ) print( f'The absolute error for function {f}, Maclaurin Serie around a={a}, evaluating x={f0:.5}, with {n} terms is {np.float(error):.8}' ) print('\n') n += 1 L.show()
def basic_plot(): p1=plot(g1, rnge, show=False, line_color='b', ylim=(0., 1.)) p2=plot(g2, rnge, show=False, line_color='g') p3=plot(g3, rnge, show=False, line_color='y') p4=plot(g4, rnge, show=False, line_color='r') p1.extend(p2) p1.extend(p3) p1.extend(p4) return p1
def basic_plot(): p1 = plot(g1, rnge, show=False, line_color='b', ylim=(0., 1.)) p2 = plot(g2, rnge, show=False, line_color='g') p3 = plot(g3, rnge, show=False, line_color='y') p4 = plot(g4, rnge, show=False, line_color='r') p1.extend(p2) p1.extend(p3) p1.extend(p4) return p1
def bisection(eq, x: sym.Symbol, error_bound, graph=False): sym.plot(eq) low, high = change_x('Enter X bounds that bracket the root: ') y_low = eq.subs({x: low}) y_high = eq.subs({x: high}) # bounds are symmetric about the x axis, then add a small amount to avoid divide by zero error if low * -1 == high: low -= 0.0000001 ''' True means positive and False is negative. This will be used to determine where is the function crosses the x axis and changes from positive to negative ''' low_sign = get_sign(y_low) high_sign = get_sign(y_high) mid = (high + low) / 2 end = False i = 0 if not low_sign ^ high_sign: print("Not a simple root/ Unable to center about a single root") end = True # stops looping if the root is found or floating point precision becomes significant while not end: i += 1 mid = (high + low) / 2 y_mid = eq.subs({x: mid}) mid_sign = get_sign(y_mid) # if mid and low are on other sides of the x axis if mid_sign ^ low_sign: high = mid error_approx = 100 * (low - mid) / mid elif mid_sign ^ high_sign: low = mid error_approx = 100 * (high - mid) / mid else: end = True error_approx = 0.0 # 1 x 10^-15 to max out floating point precision if abs(error_approx) < error_bound: end = True if graph: sym.plot(eq, xlim=[low, high]) # print(f"high {high}, low {low}") print(f'iteration reached {i} loops. Approximate Error is {error_approx}%') return mid
def graph(z): e = get_integer(MIN, MAX, '> Lower limit') f = get_integer(MIN, MAX, '> Upper limit') if not e: e = 0 if not f: f = 100 try: sp.plot(z, (x, e, f)) except: input('Invalid data.\n<enter>')
def test_surplus_tax(self): """Practice problem 2.3 """ sp.var('x p W') benefit = et.benefit_from_demand(x, p, 100 - p) sp.plot(benefit, (x, 0, 100)) cons = Consumer(x, p, benefit) cons_sub = Consumer(x, p, benefit, other=W - x*p/2) self.assertEqual(cons_sub.surplus().subs(p, 50) - cons.surplus().subs(p, 50), 1562.5)
def DrawFourierDeriv(a0, an, bn, wo, t, n, armonicos): anp = bn * n * wo bnp = -1 * an * n * wo fpt = anp * sym.cos(n * wo * t) + bnp * sym.sin(n * wo * t) j = 0 for i in range(1, armonicos): j += fpt.subs(n, i) sym.plot(j)
def plotPolyNet(self, ylimits=(-100, 100), xlimits=(x, -10, 10), samplePoints=None): if samplePoints == None: sp.plot(self.constructedPolynomial, xlimits, ylim=ylimits) else: sp.plot(self.constructedPolynomial, xlimits, ylim=ylimits, adaptive=False, nb_of_points=samplePoints)
def calc(): X0, X1 = 1, 1 / s W = parse_expr(e1.get()) Y0 = X0 * W Y1 = X1 * W y0 = inverse_laplace_transform(Y0, s, t) y1 = inverse_laplace_transform(Y1, s, t) l2['text'] = y0 l3['text'] = y1 p = sp.plot(y0, (t, T_min, T_max), line_color='r', show=False) p.extend(sp.plot(y1, (t, T_min, T_max), line_color='g', show=False)) p.show()
def graph(expr): """ Try to find good plotting range and plot the graph """ var = fa.get_variables(expr) try: [xran, yran] = fpl.find_plot_range(expr) sp.plot(expr, (var[0], xran[0], xran[1]), axis_center=(0, 0), ylim=(yran[0], yran[1])) except: sp.plot(expr)
def test_surplus_tax(self): """Practice problem 2.3 """ sp.var('x p W') benefit = et.benefit_from_demand(x, p, 100 - p) sp.plot(benefit, (x, 0, 100)) cons = Consumer(x, p, benefit) cons_sub = Consumer(x, p, benefit, other=W - x * p / 2) self.assertEqual( cons_sub.surplus().subs(p, 50) - cons.surplus().subs(p, 50), 1562.5)
def newtons_method(u): error = 1E-12 xpoints = linspace(-0.99, 0.99, 100) ypoints = [] x = xpoints[0] x1 = xpoints[1] accuracy = abs(x1 - x) while accuracy > error: x1 = x - f(x, u)/derivative(x) x1 = x ypoints.append(x1) plot(xpoints, ypoints)
def false_pos(eq, z, error_bound): # x_temp = x(i+1) , x_new = x(i), x_old = x(i-1) sym.plot(eq) x_old, x_new = change_x('Enter 2 X bounds that bracket to the root: ') y_old = eq.subs({z: x_old}) y_new = eq.subs({z: x_new}) end = False i = 0 while not end: i += 1 old_sign = get_sign(y_old) new_sign = get_sign(y_new) if not (old_sign ^ new_sign): print(f"Bounds {x_old} and {x_new} don't bracket the root") sys.exit() x_temp = x_new - (y_new * (x_old - x_new)) / (y_old - y_new) y_temp = eq.subs({z: x_temp}) temp_sign = get_sign(y_temp) # the only difference between secant and false position method is that # if temp and old are on other sides of the x axis, the Old stays the same and temp becomes new if old_sign ^ temp_sign: error_approx = 100 * (x_temp - x_new) / x_temp x_new, y_new = x_temp, y_temp # if new and temp are on opposite side of the x axis, new become the old, and temp becomes new elif new_sign ^ temp_sign: error_approx = 100 * (x_temp - x_old) / x_temp x_old, y_old = x_new, y_new x_new, y_new = x_temp, y_temp # bounds don't bracket the root else: end = True print("Not a simple root/ Unable to center about a single root") error_approx = 0.0 # print(f"x_i = {x_new}, and x_i-1 = {x_old}, iterations = {i}") # ending at the user specified percent error if abs(error_approx) < error_bound: end = True print(f"approximate error is {abs(error_approx)} % \n iterations = {i}") return x_new
def get_simulated_imu_data(t_max, dt, plot=False): t_W_B, v_W_B, a_W_B = simulate_pos_vel_acc(0.7, 1.0, .5, 2.0, 1.0, 2.0, 0.7, 1.0, 1.0) R_W_B = simulate_rotation_matrix(0.5, 0.05, 0.2, 1.0, 2.0, 1.0, 0.0, 1.0, 4.0) B_w_W_B = rotation_rate_from_rotation_matrix(R_W_B) if plot: # Plot symbolic sy.plot(B_w_W_B[0], B_w_W_B[1], B_w_W_B[2], (t, 0, 2.0)) sy.plotting.plot3d_parametric_line(t_W_B[0], t_W_B[1], t_W_B[2], (t, 0, 2.0)) sy.plot(t_W_B[0], v_W_B[0], a_W_B[0], (t, 0, 2.0)) sy.plot(t_W_B[1], v_W_B[1], a_W_B[1], (t, 0, 2.0)) sy.plot(t_W_B[2], v_W_B[2], a_W_B[2], (t, 0, 2.0)) # Evaluate symbolic trajectory for specific time instances t_W_B_val, v_W_B_val, a_W_B_val, R_W_B_val, B_w_W_B_val = \ evaluate_symbolic_trajectory(t_W_B, v_W_B, a_W_B, R_W_B, B_w_W_B, 0.0, t_max, dt) # Transform IMU Measurements to body frame, where they are measured. n = np.shape(t_W_B_val)[0] B_a_W_B = np.zeros((n, 3), dtype=np.float32) for i in range(n): R_B_W = np.transpose(np.reshape(R_W_B_val[i, :], (3, 3))) B_a_W_B[i, :] = np.dot(R_B_W, a_W_B_val[i, :]) return t_W_B_val, v_W_B_val, R_W_B_val, B_a_W_B, B_w_W_B_val
def save_plots(t1,t2,f,yt,yder,yder2): Pf = plot((f,(t,0,t2+1)),title=r"$f(t)$",xlabel="",ylabel="",show=False) # vypis formulacie Py = plot((yt,(t,0,t2+1)),depth=12,title=r"$y(t)$",xlabel="",ylabel="",show=False) Pdy = plot((yder,(t,0,t2+1)),title=r"$y'(t)$",xlabel="",ylabel="",show=False) Pddy = plot((yder2,(t,0,t2+1)),sings=[t1,t2],title=r"$y''(t)$",xlabel="",ylabel="",show=False) ffn = mkstemp(suffix=".pdf",dir=".")[1] yfn = mkstemp(suffix=".pdf",dir=".")[1] dyfn = mkstemp(suffix=".pdf",dir=".")[1] ddyfn = mkstemp(suffix=".pdf",dir=".")[1] Pf.save(ffn) Py.save(yfn) Pdy.save(dyfn) Pddy.save(ddyfn) return ffn, yfn, dyfn, ddyfn
def plotSymbolicEq(): b1, b2, x = symbols('b1 b2 x') def calculateRoots(): roots = solve([ Eq(90 * 0.05 + 90 * exp(b1 - (b2 * 90)) - 90, 0.0), Eq(99 * 0.95 + 99 * exp(b1 - (b2 * 99)) - 99, 0.0) ], [b1, b2]) return roots roots = calculateRoots() f = x / (x + exp(b1 - b2 * x)) res = {b1: roots.get(b1), b2: roots.get(b2)} plot(f.subs(res), (x, 0, 100))
def retaTangentePonto(self, funcao, coord_x=0.0, coord_y=0.0, show_tangente=False, legenda="f(x)=", plot_eixo_x_limites=(-10, 10), plot_eixo_y_limites=(-10, 10)): """Mostra o grafico de uma função, suporta mostrar a reta tangente num ponto (x, y) dadas as coordenadas Args: funcao (string): Função a mostrar em formato grafico coord_x (float, optional): Ponto x da reta tangente. Defaults to 0.0. coord_y (float, optional): Ponto y da reta tangente. Defaults to 0.0. show_tangente (bool, optional): Mostrar reta tangente da função, True para mostrar, False para omitir. Defaults to False. legenda (str, optional): Identificador do tipo de função, exemplos; f(x), f'(x), f''(x), etc. Defaults to "f(x)=". """ m, x, y = s.symbols('m x y') funcao_pretty = self.handler.pretty_ready(funcao) funcao_plot = s.plot(funcao, show=False) funcao_plot.legend = True funcao_plot[0].label = legenda + funcao_pretty funcao_plot.xlim = plot_eixo_x_limites funcao_plot.ylim = plot_eixo_y_limites #Reta tangente no ponto (x,y) if show_tangente == True: m = self.DecliveValor(funcao, coord_x) y = s.sympify(m * (x - coord_x) + coord_y) rt = s.plot(y, show=False) rt.xlim = plot_eixo_x_limites rt.ylim = plot_eixo_y_limites funcao_plot.append(rt[0]) reta_tangente_pretty = "Reta tangente no ponto (" + str( coord_x) + ", " + str( coord_y) + ") de f(x)=" + self.handler.pretty_ready(funcao) funcao_plot[1].label = reta_tangente_pretty funcao_plot[1].line_color = 'firebrick' funcao_latex = self.sympyLatexify(funcao) funcao_plot.title = f"${funcao_latex}$" funcao_plot.show()
def test_solve_plane(f, x0, y0): """ Проверяем решение векторных уравнений """ # get iterations tol = 1e-9 xs, ys, zs = solve_plane(f, x0, y0, tol) f_eval = f.subs({x: xs[-1], y: ys[-1]}) assert np.linalg.norm([float(f_eval[0]), float(f_eval[1])]) < tol # plot f() lines # p = sp.plot(show=False, backend=sp.plotting.plot_backends['matplotlib']) p = sp.plot(show=False) p.extend(sp.plot_implicit(f[0], depth=1, line_color='k', show=False)) p.extend(sp.plot_implicit(f[1], depth=1, line_color='k', show=False)) # plot iterations traj = List2DSeries(xs, ys) traj.line_color = 'm' p.append(traj) p.title = f'{f[0]}\n{f[1]}' p.xlabel = 'x' p.ylabel = 'y' p.show() # plot accuracy plt.figure() plt.plot(-np.log10(np.abs(zs)), 'b.:') plt.suptitle(p.title) plt.xlabel('N step') plt.ylabel('Accuracy') plt.show()
def bisection(funcion, xi, xs, nIter, iter): results = {} if nIter > 0: x = sm.symbols('x') fxi = sm.sympify(funcion).subs(x, xi) fxs = sm.sympify(funcion).subs(x, xs) sm.plot(funcion) if (fxi == 0): print(fxi) elif (fxs == 0): print(fxs) elif (fxs * fxi < 0): xm = (xi + xs) / 2 fxm = sm.sympify(funcion).subs(x, xm) count = 1 error = iter + 1 results[count] = [ float(xi), float(xm), float(xs), float(fxm), float(error) ] while ((error > iter) and (count < nIter)): if (fxi * fxm < 0): xs = xm else: xi = xm xaux = xm xm = (xi + xs) / 2 fxm = sm.sympify(funcion).subs(x, xm) error = abs(xm - xaux) count += 1 results[count] = [ float(xi), float(xm), float(xs), float(fxm), float(error) ] print(results) return results else: results['message'] = 'Error' print('el intervalo no sirve') return results
async def plot(ctx, *, exp): exp = syp.sympify(exp) img_path = path.join(log_dir, 'figure.png') img = syp.plot(exp, show=False) img.save(img_path) return await bot.upload(img_path)
def animate(ti): p = sym.plot(x.subs(t, tau), (tau, taud[0], taud[-1]), show=False) line_x.set_segments(p[0].get_segments()) p = sym.plot(h.subs(t, t - tau).subs(t, ti), (tau, taud[0], taud[-1]), show=False) line_h.set_segments(p[0].get_segments()) p = sym.plot(y, (t, taud[0], taud[-1]), show=False) line_y.set_segments(p[0].get_segments()) p = sym.plot(x.subs(t, tau) * h.subs(t, ti - tau), (tau, -5, 5), show=False) points = p[0].get_points() verts = [[(xi[0], xi[1]) for xi in np.transpose(np.array(points))]] fill.set_verts(verts) dot.set_data(ti, y.subs(t, ti))
def plot_function_overlay(empirical_distribution_function, empirical_arg, gamma_distribution_function, gamma_arg, bound): """ :param empirical_distribution_function: империческая функция распределения - символьная функция :param empirical_arg: аргумент символьной функции империческая функция распределениz :param gamma_distribution_function: функция гамма распределения - символьная функция :param gamma_arg: аргумент символьной гамма функции распределения :param bound: кортеж - границы построения графика :return: обьект графика """ p1 = plot(gamma_distribution_function, (gamma_arg, bound[0], bound[1]), show=False) p2 = plot(empirical_distribution_function, (empirical_arg, bound[0], bound[1]), show=False) p2[0].line_color = 'red' p1.append(p2[0]) return p1
def lagrange(f, vectorX, vectorY): f = sy.sympify(f) indice = 0 n = len(vectorX) resultado = 0 x = symbols('x') while indice != n: resultado += vectorY[indice] * multiplicacionL(vectorX, indice, n) indice += 1 print(resultado) resultado = sy.sympify(resultado) p1 = plot(resultado, (x, vectorX[0], vectorX[n - 1]), show=False, line_color='r') p2 = plot(f, (x, vectorX[0], vectorX[n - 1]), show=False) p1.append(p2[0]) p1.show() return resultado
def plot_graphic(self, file_name): file = '{}.png'.format(file_name) graph = plot(self.f, (x, Float( self.interval.split()[0]), Float(self.interval.split()[1])), show=False, line_color='r') # graph.append(List2DSeries(x1, y1)) graph.save(file)
def plot_sympy(*args, ax=None, **kwargs): """Plot a SymPy expression into a Matplotlib plot.""" from matplotlib.collections import LineCollection if ax is None: ax = _plt.gca() for line in _sp.plot(*args, show=False, **kwargs): x, y = line.get_points() # if the function is constant, SymPy only emits one value: x, y = _np.broadcast_arrays(x, y) ax.plot(x, y) ax.autoscale()
def normal_form(): #x=sy.Function('f') (r, x) = sy.symbols('r x') #eq=sy.Eq(sy.Derivative(x(t),t),x(t)**3-3*x(t)**2+(r+2)*x(t)-r) eq = [ sy.Eq(x**3 - 3 * x**2 + (r + 2) * x - r, 0), sy.Eq(3 * x**2 - 6 * x + (r + 2), 0) ] solution = sy.solve(eq)[0] (y, t) = sy.symbols('y t') newEq = [ sy.expand(eq[0].subs([(x, y + solution[x]), (r, t + solution[r])])), sy.expand(eq[0].subs([(x, y + solution[x]), (r, t + solution[r])])) ] expression = x**3 - 3 * x**2 + (r + 2) * x - r newExp = expression.subs([(x, y + solution[x]), (r, t + solution[r])]) print(sy.expand(newExp)) sy.plot(newExp.subs(t, 0))
import modsolve from sympy import plot # feature-positive discrimination m = modsolve.model() m.train( {'A':0, 'AB':1} ) VB1 = m.V( 'B', 1 ) VB1rem = m.bind( VB1, 'rem' ) VB1p87 = m.bind( VB1, 'p87' ) VB1p94 = m.bind( VB1, 'p94' ) (r, c) = (m.symbols['r'], m.symbols['c']) plot( (VB1rem, (r,0,1)), (VB1p87, (c,0,1)), (VB1p94, (c,0,1)) ) # external inhibition m = modsolve.model() m.train( {'A':1} ) VAB1 = m.V( 'AB', 1 ) VAB1rem = m.bind( VAB1, 'rem' ) VAB1p87 = m.bind( VAB1, 'p87' ) VAB1p94 = m.bind( VAB1, 'p94' ) (r, c) = (m.symbols['r'], m.symbols['c']) plot( (VAB1rem, (r,0,1)), (VAB1p87, (c,0,1)), (VAB1p94, (c,0,1)) ) # summation m = modsolve.model() m.train( {'A':1, 'B':1} ) VAB1 = m.V( 'AB', 1 ) VAB1rem = m.bind( VAB1, 'rem' ) VAB1p87 = m.bind( VAB1, 'p87' ) VAB1p94 = m.bind( VAB1, 'p94' ) (r, c) = (m.symbols['r'], m.symbols['c'])
rw = np.matrix([sx, sy, 1]) #%% x = np.linspace(-200, 200, num=100) y = np.linspace(-200, 200, num=100) X, Y = np.meshgrid(x, y) matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' #%% Q = np.matrix(np.random.uniform(low=-1., high=1., size=(3, 3))) Q /= np.linalg.norm(Q) #Q = np.matrix(np.random.normal(size=(2, 2))) #P = np.matrix(np.random.normal(size=(1, 2))) eq = rw * (Q * rw.T) #+ P*rw.T eqsy = sympy.solve(eq[0,0], sy) sympy.plot(*[(teq, (sx, -1, 1)) for teq in eqsy]) #%% Z = np.zeros(X.shape) for y in range(Z.shape[0]): for x in range(Z.shape[1]): posvec = np.matrix([Y[y, x], X[y, x], 1.]) Z[y, x] = posvec*(Q * posvec.T) #+ P*posvec.T plt.figure() CS = plt.contour(X, Y, Z) plt.clabel(CS, inline=1, fontsize=10) plt.title('Quadric contours')
# -*- coding: utf-8 -*- """ Created on Sat Apr 05 14:04:50 2014 @author: lassnech """ from sympy import plot, log, re, Abs from sympy.abc import x sh_entropy = re(-x*log(x)/log(2)-(1-x)*log(1-x)/log(2)) ind_p_1 = 1-Abs(0.5-x)**1 * 2 ind_p_2 = 1-Abs(0.5-x)**2 * 4 ind_p_3 = 1-Abs(0.5-x)**3 * 8 ind_p_4 = 1-Abs(0.5-x)**4 * 16 rnge = (x, 0, 1) p1 = plot(sh_entropy, rnge, show=False, line_color='b') p2 = plot(ind_p_2, rnge, show=False, line_color='g') p3 = plot(ind_p_3, rnge, show=False, line_color='y') p4 = plot(ind_p_4, rnge, show=False, line_color='r') p5 = plot(ind_p_1, rnge, show=False, line_color='purple') p1.extend(p2) p1.extend(p3) p1.extend(p4) p1.extend(p5) p1.title = 'entropies' p1.save('impurities.png') p1.show()
# Check the plot docstring from sympy import Symbol, plot, exp, sin, cos 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 #a = plot(lx, ly, show=False) # list plot b = plot(expr, (x, 2, 4), show=False) # cartesian plot #c = plot((lx, ly), (expr, (x, 2, 4)), ('x*cos(x)', 'x*sin(x)', (x, 0, 15)), show=False) # list, cartesian and parametric plot #d = plot(1/(x**2+y**2+1), (x, -10, 10), (y, -10, 10), 'contour') # contour plot e = plot(exp(-x),(x, 0, 4), show=False) # cartesian plot (and coloring, see below) f = plot(sin(x), cos(x), x, (x,0,10), show=False) # 3d parametric line plot g = plot(sin(x)*cos(y), (x, -5, 5), (y, -10, 10), show=False) # 3d surface cartesian plot h = plot(cos(u)*v,sin(u)*v,u,(u,0,10),(v,-2,2), show=False) # 3d parametric surface plot # Some global options #c.title = 'Big nice title' #c.xlabel = 'my argument' #c.ylabel = 'my function' #c.legend = True # Some aesthetics e[0].line_color = lambda x : x/4 f[0].line_color = lambda x, y, z : z/10
p3=plot(g3, rnge, show=False, line_color='y') p4=plot(g4, rnge, show=False, line_color='r') p1.extend(p2) p1.extend(p3) p1.extend(p4) return p1 p1 = basic_plot() p1.title = 'sample result distributions' p1.save('dist_basic.png') p1.show() means = 1./4.*(g1+g2+g3+g4) p1.title = 'averaging' p1.extend(plot(means, rnge, show=False, line_color='black')) p1.save('dist_means.png') p1.show() p1 = basic_plot() p1.title = 'multiplication' mult = g1*g2*g3*g4 # Find pseudo max of mult. multf = lambdify(x, mult) xv = np.linspace(0, 12, 1000) sumv = 0. maxv = 0. for val in xv: v = multf(val) sumv += v
def plot_riesenie(t1,yt,yder,yder2): Py = plot((yt,(t,0,t1)),depth=12,title=r"$y(t)$",xlabel="",ylabel="") Pdy = plot((yder,(t,0,t1)),title=r"$y'(t)$",xlabel="",ylabel="") Pddy = plot((yder2,(t,0,t1)),sings=[t1,t2],title=r"$y''(t)$",xlabel="",ylabel="")
print(x2) #final answer printed out ############################################################ #part b points = [] y = []; def new_f(x,c): return (1 - math.exp(-c*x) - x) def new_df(x, c): return c*math.exp(-c*x) - 1 for c in linspace(0,3,3): x1 = 1 x2 = 1 target = 1e-6 points.append(c) while True: x1=x2 x2=x1-new_f(x1, c)/new_df(x1, c) if abs(x2-x1) < target: if x2 is not None: y.append(x2) else: y.append(0) break plot(points, y) show()
# from sympy.plotting import plot # from sympy import Symbol # x = Symbol('x') # plot(2*x+3) from sympy import plot, Symbol x = Symbol('x') plot(2*x + 3, (x, -5, 5), title='A Line', xlabel='x', ylabel='2x+3')
def plot_and_save(name): x = Symbol("x") y = Symbol("y") z = Symbol("z") ### # Examples from the 'introduction' notebook ### p = plot(x, show=False) p = plot(x * sin(x), x * cos(x), show=False) 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, show=False)) p.append(plot((x + 3,), (x ** 2,), show=False)[1]) p.save(tmp_file("%s_plot_extend_append.png" % name)) p[2] = x ** 2, (x, -2, 3) p.save(tmp_file("%s_plot_setitem.png" % name)) p = plot(sin(x), (x, -2 * pi, 4 * pi), show=False) p.save(tmp_file("%s_line_explicit.png" % name)) p = plot(sin(x), (-2 * pi, 4 * pi), show=False) p.save(tmp_file("%s_line_implicit_var.png" % name)) p = plot(sin(x), show=False) p.save(tmp_file("%s_line_default_range.png" % name)) p = plot((x,), (x * sin(x), x * cos(x)), show=False) p.save(tmp_file("%s_two_curves.png" % name)) p = plot(sin(x), cos(x), x, show=False) p.save(tmp_file("%s_3d_line.png" % name)) p = plot(x * y, show=False) p.save(tmp_file("%s_surface.png" % name)) p = plot(x * sin(z), x * cos(z), z, show=False) p.save(tmp_file("%s_parametric_surface.png" % name)) ### # Examples from the 'colors' notebook ### p = plot(sin(x), show=False) 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), (0, 10), show=False) 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 = plot( sin(x) + 0.1 * sin(x) * cos(7 * x), cos(x) + 0.1 * cos(x) * cos(7 * x), 0.1 * sin(7 * x), (0, 2 * pi), show=False, ) 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 = plot(sin(x) * y, (0, 6 * pi), show=False) 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 = plot(x * cos(4 * y), x * sin(4 * y), y, (-1, 1), (-1, 1), show=False) 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, (1, 5), show=False) p.save(tmp_file("%s_advanced_integral.png" % name)) s = summation(1 / x ** y, (x, 1, oo)) p = plot(s, (2, 10), show=False) p.save(tmp_file("%s_advanced_inf_sum.png" % name)) p = plot(summation(1 / x, (x, 1, 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. ### # with warnings.catch_warnings(record=True) as w: # warnings.simplefilter("always") # plot(sqrt(sqrt(-x)), show=False).save(tmp_file()) # assert len(w) == 1 # assert "Complex values as arguments to numpy functions encountered." == str(w[-1].message) # with warnings.catch_warnings(record=True) as w: # warnings.simplefilter("always") # plot(LambertW(x), show=False).save(tmp_file()) # assert len(w) > 10 #TODO trace where do the other warnings come from # assert "Complex values as arguments to python math functions encountered." == str(w[-1].message) # with warnings.catch_warnings(record=True) as w: # warnings.simplefilter("always") # plot(sqrt(LambertW(x)), show=False).save(tmp_file()) # assert len(w) == 1 # assert "Complex values as arguments to python math functions encountered." == str(w[-1].message) # TODO these test do not work properly. plot(sin(x) + I * cos(x)).save(tmp_file()) plot(sqrt(sqrt(-x)), show=False).save(tmp_file()) plot(LambertW(x), show=False).save(tmp_file()) plot(sqrt(LambertW(x)), show=False).save(tmp_file()) ### # Test all valid input args for plot() ### # 2D line with all possible inputs plot(x).save(tmp_file()) plot(x, (x,)).save(tmp_file()) plot(x, (-10, 10)).save(tmp_file()) plot(x, (x, -10, 10)).save(tmp_file()) # two 2D lines plot((x,), (x + 1, (x, -10, 10))).save(tmp_file()) plot((x, (x,)), (x + 1, (x, -10, 10))).save(tmp_file()) plot((x, (-10, 10)), (x + 1, (x, -10, 10))).save(tmp_file()) plot((x, (x, -10, 10)), (x + 1, (x, -10, 10))).save(tmp_file()) plot([x, x + 1]).save(tmp_file()) plot([x, x + 1], (x,)).save(tmp_file()) plot([x, x + 1], (-10, 10)).save(tmp_file()) plot([x, x + 1], (x, -10, 10)).save(tmp_file()) # 2D and 3D parametric lines plot(x, 2 * x).save(tmp_file()) plot(x, 2 * x, sin(x)).save(tmp_file()) # surface and parametric surface plot(x * y).save(tmp_file()) plot(x * y, 1 / x, 1 / y).save(tmp_file()) # some bizarre combinatrions ## two 3d parametric lines and a surface plot(([x, -x], x ** 2, sin(x)), (x * y,)).save(tmp_file())
def plot_and_save(name): x = Symbol('x') y = Symbol('y') z = Symbol('z') ### # Examples from the 'introduction' notebook ### p = plot(x, show=False) p = plot(x*sin(x),x*cos(x), show=False) 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, show=False)) p.append(plot((x+3,),(x**2,), show=False)[1]) p.save(tmp_file('%s_plot_extend_append.png' % name)) p[2] = x**2, (x, -2, 3) p.save(tmp_file('%s_plot_setitem.png' % name)) p = plot(sin(x),(x,-2*pi,4*pi), show=False) p.save(tmp_file('%s_line_explicit.png' % name)) p = plot(sin(x),(-2*pi,4*pi), show=False) p.save(tmp_file('%s_line_implicit_var.png' % name)) p = plot(sin(x), show=False) p.save(tmp_file('%s_line_default_range.png' % name)) p = plot((x,), (x*sin(x), x*cos(x)), show=False) p.save(tmp_file('%s_two_curves.png' % name)) p = plot(sin(x),cos(x),x, show=False) p.save(tmp_file('%s_3d_line.png' % name)) p = plot(x*y, show=False) p.save(tmp_file('%s_surface.png' % name)) p = plot(x*sin(z),x*cos(z),z, show=False) p.save(tmp_file('%s_parametric_surface.png' % name)) ### # Examples from the 'colors' notebook ### p = plot(sin(x), show=False) 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), (0,10), show=False) 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 = plot(sin(x)+0.1*sin(x)*cos(7*x), cos(x)+0.1*cos(x)*cos(7*x), 0.1*sin(7*x), (0, 2*pi), show=False) 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 = plot(sin(x)*y, (0,6*pi), show=False) 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 = plot(x*cos(4*y), x*sin(4*y), y, (-1, 1), (-1, 1), show=False) 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,(1,5), show=False) p.save(tmp_file('%s_advanced_integral.png' % name)) s = summation(1/x**y,(x,1,oo)) p = plot(s, (2,10), show=False) p.save(tmp_file('%s_advanced_inf_sum.png' % name)) p = plot(summation(1/x,(x,1,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), show=False).save(tmp_file()) plot(sqrt(sqrt(-x)), show=False).save(tmp_file()) plot(LambertW(x), show=False).save(tmp_file()) plot(sqrt(LambertW(x)), show=False).save(tmp_file()) ### # Test all valid input args for plot() ### # 2D line with all possible inputs plot(x , show=False).save(tmp_file()) plot(x, (x, ), show=False).save(tmp_file()) plot(x, ( -10, 10), show=False).save(tmp_file()) plot(x, (x, -10, 10), show=False).save(tmp_file()) # two 2D lines plot((x, ), (x+1, (x, -10, 10)), show=False).save(tmp_file()) plot((x, (x, )), (x+1, (x, -10, 10)), show=False).save(tmp_file()) plot((x, ( -10, 10)), (x+1, (x, -10, 10)), show=False).save(tmp_file()) plot((x, (x, -10, 10)), (x+1, (x, -10, 10)), show=False).save(tmp_file()) plot([x, x+1], show=False).save(tmp_file()) plot([x, x+1], (x, ), show=False).save(tmp_file()) plot([x, x+1], ( -10, 10), show=False).save(tmp_file()) plot([x, x+1], (x, -10, 10), show=False).save(tmp_file()) # 2D and 3D parametric lines plot(x, 2*x, show=False).save(tmp_file()) plot(x, 2*x, sin(x), show=False).save(tmp_file()) # surface and parametric surface plot(x*y, show=False).save(tmp_file()) plot(x*y, 1/x, 1/y,show=False).save(tmp_file()) # some bizarre combinatrions ## two 3d parametric lines and a surface plot(([x, -x], x**2, sin(x)), (x*y,), show=False).save(tmp_file())
def plotexprt(ft,sings=[],depth=10,xlabel='t',ylabel='y(t)'): P=plot(ft,singularities=sings,depth=depth,xlabel=xlabel,ylabel=ylabel)
def plotnp(ft,t1,t2, xlab=r'$t$',ylab=r'$y(t)$',npts=200): tn = linspace(t1,t2,npts) yn = array([ft(ta) for ta in tn],dtype='float') plot(tn,yn) xlabel(xlab); ylabel(ylab)