Solving and Plot Equation in Python - equations

I am kind of new to python. All I am trying to do is to solve for y and plot the function,
In other words, plug values for x and generate y.
y^10+y = x.
Please forgive my ignorance.

from numpy import *
from matplotlib.pyplot import plot, show
y = arange(-10, 10, 0.01) #get values between -10 and 10 with 0.01 step and set to y
x = y**10 + y #get x values from y
plot(x, y)
show()
Using the matplotlib and numpy library: http://scipy.org/
If you want to solve things, use sympy: https://github.com/sympy/sympy/wiki/Quick-examples

Related

Remove noise and smoothen the ecg signal

I am processing Long term afib dataset - https://physionet.org/content/ltafdb/1.0.0/
When I test the 30s strips of this data, my model is not correcting predicting the signals. So I am trying to deal with noise in this dataset. Here how it looks
Here is the code to plot -
def plot_filter_graphs(data,xmin,xmax,order):
from numpy import sin, cos, pi, linspace
from numpy.random import randn
from scipy import signal
from scipy.signal import lfilter, lfilter_zi, filtfilt, butter
from matplotlib.pyplot import plot, legend, show, grid, figure, savefig,xlim
lowcut=1
highcut=35
nyq = 0.5 * 300
low = lowcut / nyq
high = highcut / nyq
b, a = signal.butter(order, [low, high], btype='band')
# Apply the filter to xn. Use lfilter_zi to choose the initial condition
# of the filter.
z = lfilter(b, a,data)
# Use filtfilt to apply the filter.
y = filtfilt(b, a, data)
y = np.flipud(y)
y = signal.lfilter(b, a, y)
y = np.flipud(y)
# Make the plot.
figure(figsize=(16,5))
plot(data,'b',linewidth=1.75)
plot(z, 'r--', linewidth=1.75)
plot( y, 'k', linewidth=1.75)
xlim(xmin,xmax)
legend(('actual',
'lfilter',
'filtfilt'),
loc='best')
grid(True)
show()
I am using butter band pass filter to filter the noise. I also checked with filtfilt and lfilt but that is also not giving good result.
Any suggestion, how noise can be removed so that signal accuracy is good and hense it can be used for model prediction

Using numerical methods to plot solution to first-order nonlinear differential equation in Matlab

I have a question about plotting x(t), the solution to the following differential equation knowing that dx/dt equals the expression below. The value of x is 0 at t = 0.
syms x
dxdt = -(1.0*(6.84e+45*x^2 + 5.24e+32*x - 2.49e+42))/(2.47e+39*x + 7.12e+37)
I want to plot the solution of this first-order nonlinear differential equation. The analytical solution involves complex numbers so that's not relevant because this equation models a real-life process, but Matlab can solve the equation using numerical methods and plot it. Can someone please suggest how to do this?
in matlab try this
tspan = [0 10];
x0 = 0;
[t,x] = ode45(#(t,x) -(1.0*(6.84e+45*x^2 + 5.24e+32*x - 2.49e+42))/(2.47e+39*x + 7.12e+37), tspan, x0);
plot(t,x,'b')
i try it and i got this
hope that help you.
I have written an example for how to use Python with SymPy and matplotlib. SymPy can be used to calculate both definite and indefinite integrals. By calculating the indefinite integral and adding a constant to set it to evaluate to 0 at t = 0. Now you have the integral, so just a matter of plotting. I would define an array from a starting point to an endpoint with 1000 points between (could likely be less). You can then calculate the value of the integral with the constant at each time point, which can then be plotted with matplotlib. There are plenty of other questions on how to customize plots with matplotlib.
This displays a basic plot of the indefinite integral of the function dxdt with assumption of x(t) = 0. Variation of the tuple when running Plotting() will set what range of x values to plot. This is set to plot 1000 data points between the minimum and maximum values set when calling the function.
For more information on customizing the plot, I recommend matplotlib documentation. Documentation on the integral can be found in SymPy documentation.
import pandas as pd
from sympy import *
from sympy.abc import x
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def Plotting(xValues, dxdt):
# Calculate integral
xt = integrate(dxdt,x)
# Convert to function
f = lambdify(x, xt)
C = -f(0)
# Define x values, last number in linspace corresponding to number of points to plot
xValues = np.linspace(xValues[0],xValues[1],500)
yValues = [f(x)+C for x in xValues]
# Initialize figure
fig = plt.figure(figsize = (4,3))
ax = fig.add_axes([0, 0, 1, 1])
# Plot Data
ax.plot(xValues, yValues)
plt.show()
plt.close("all")
# Define Function
dxdt = -(1.0*(6.84e45*x**2 + 5.24e32*x - 2.49e42))/(2.47e39*x + 7.12e37)
# Run Plotting function, with left and right most points defined as tuple, and function as second argument
Plotting((-0.025, 0.05),dxdt)

How to calculate the cosine similarity of two vectors in PySpark?

I am about to compute the cosine similarity of two vectors in PySpark, like
1 - spatial.distance.cosine(xvec, yvec)
but scipy seems to not support the pyspark.ml.linalg.Vector type.
You can use dot and norm methods to calculate this pretty easily:
from pyspark.ml.linalg import Vectors
x = Vectors.dense([1,2,3])
y = Vectors.dense([2,3,5])
1 - x.dot(y)/(x.norm(2)*y.norm(2))
# 0.0028235350472619603
With scipy:
from scipy.spatial.distance import cosine
​
x = np.array([1,2,3])
y = np.array([2,3,5])
cosine(x, y)
# 0.0028235350472619603

How to obtain 3D colored surface via Python?

How to obtain the following surface via Matplotlib?
It is easy in matlab via:
mesh(peaks)
It seems matplotlib does not have an exact counterpart of mesh in matlab.
the Wireframe plots does not have any colormap option
While answering another question I found that you can easily do this using plot_surface to produce a color mapped surface, and then exchanging face and edge colors:
surf = ax.plot_surface(X, Y, Z, rstride=2, cstride=2, shade=False, cmap="jet", linewidth=1)
draw()
surf.set_edgecolors(surf.to_rgba(surf._A))
surf.set_facecolors("white")
show()
produces
The disadvantage this solution has over the other one is that the edges do not have smooth, per-pixel colouring, but one single color each.
It seems to be possible with matplotlib even if it is a bit of a hack:
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d import art3d
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
wire = ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
# Retrive data from internal storage of plot_wireframe, then delete it
nx, ny, _ = np.shape(wire._segments3d)
wire_x = np.array(wire._segments3d)[:, :, 0].ravel()
wire_y = np.array(wire._segments3d)[:, :, 1].ravel()
wire_z = np.array(wire._segments3d)[:, :, 2].ravel()
wire.remove()
# create data for a LineCollection
wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)])
wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)])
wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)])
to_delete = np.arange(0, nx*ny, ny)
wire_x1 = np.delete(wire_x1, to_delete, axis=1)
wire_y1 = np.delete(wire_y1, to_delete, axis=1)
wire_z1 = np.delete(wire_z1, to_delete, axis=1)
scalars = np.delete(wire_z, to_delete)
segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \
zip(wire_x1.T, wire_y1.T, wire_z1.T)]
# Plots the wireframe by a a line3DCollection
my_wire = art3d.Line3DCollection(segs, cmap="hsv")
my_wire.set_array(scalars)
ax.add_collection(my_wire)
plt.colorbar(my_wire)
plt.show()
An official feature request is underway:
https://github.com/matplotlib/matplotlib/issues/3562
The accepted solution doesn't work when X and Y arrays are not the same size.
It seems the current matplotlib 1.3.1 does not handle such mesh plot or further PDF export. gnuplot.pygnuplot.py 1.8 might be a choice before there is further updates in matplotlib.
Here is an example created via gnuplot:
MayaVI2 does not support PDF exports but might be another good choice.

Plotting complex functions

How to plot complex functions in Matlab? For example:
Y[e^jx] = 1 / (1 - cosx + j4)
I tried some code, but I think the right way is by plotting real and imaginary part separately.
x = linspace(-pi, pi, 1e3);
y = 1./(1 - cos(x) + i*4);
% Plot absolute value and phase
figure;
subplot(2,1,1); plot(x, abs(y));
subplot(2,1,2); plot(x, angle(y));
% Plot real and imaginary parts
figure;
subplot(2,1,1); plot(x, real(y));
subplot(2,1,2); plot(x, imag(y));
There are some MATLAB functions that are specific to plotting complex maps:
z = cplxgrid(60);
cplxmap(z, 1./(1 - cos(z) + 4*i));
See also Functions of Complex Variables in MATLAB's documentation.
Maybe not for you, but for other people looking to draw complex functions.
We set up a website where you can render them quickly and download them (reflex4you.com, reflex = representation of complex function)
I can display complex functions in 2D in a colorful way. Your function can be
visible here and below:
Note that the black is zero, the white infinite, and it covers the complex plane with colors associated to complex numbers, such as red = 1, cyan = -1, i = greenish, -i = purplish.
plot(re(Y),im(Y))
but remember there is a domain associated with a complex function in which it is valid, in your case: cos(x)-4j < 1
By default, plot(X) will plot real vs imaginary, so it's equal to plot(real(X), imag(X))
For example, try:
>> r = sort(rand(10, 1)) + 1i * rand(10, 1);
>> figure, plot(r)
If you need them both on y-axis, use:
plot([real(X), imag(X)])
You can use one of the following:
plot(real(Y))
plot(imag(Y))
plot(real(Y),imag(Y))
plot(abs(Y))
As an alternative for Python, you can use a tool I wrote: cplot. It uses domain coloring for complex plotting, i.e., it associated the absolute value of f(z) with the brightness and the hue with the complex angle.
Your function:
import cplot
import numpy as np
plt = cplot.plot(lambda z: 1 / (1 - np.cos(z) + 4j), (-10, +10, 400), (-10, +10, 400))
plt.show()