I'm trying to graph this function. x domain is (1,3) a_1 domain is (0,1) and b domain is (0,0.8)
function
My code is this so far:
import numpy as np
def t2(x,a,b):
if (x <= 1.5 - (a/2)).any():
imagent2=0
elif np.logical_and((1.5) - (a/2) < x, x <=(1.5) + (a/2)).all():
imagent2=(x-(1.5)+(a/2))/a
elif np.logical_and((1.5)+(a/2) < x ,x <= (2.6)-(b/2)).all():
imagent2=1
elif np.logical_and((2.6)-(b/2) < x, x <= 2.6+(b/2)).all():
imagent2=((2.6)+(b/2)-x)/b
elif (((2.6)+(b/2)) < x).any():
imagent2=0
return imagent2
n=5
q = np.linspace(1.01, 2.99,n)
w = np.linspace(0.01,0.99,n)
e = np.linspace(0.01,0.79,n)
X, A, B= np.meshgrid(q, w, e, indexing='ij')
assert np.all(X[:,0,0] == q)
assert np.all(A[0,:,0] == w)
assert np.all(B[0,0,:] == e)
print(t2(X,A,B))
I put the .all() and .any() cause i was getting errors without them. I will like to have an array with the values of the function on the specific domain. With that i would graph using f(x) as z, x as x, a as y and b should be represented as a colour. Don't really know how to do that last part also.
In the end i did something like this. Not quite what i wanted but i guess is enough.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
def t2(x,a,b):
return np.piecewise(x, [np.logical_and(x>1,x<=1.5-(a/2)),np.logical_and((1.5)-(a/2)<x,x<=(1.5)+(a/2)),np.logical_and((1.5)+(a/2)<x,x<=(2.6)-(b/2)),np.logical_and((2.6)-(b/2)<x,x<=2.6+(b/2)),np.logical_and(x<3,((2.6)+(b/2))<x)], [lambda x: 0, lambda x: (x-(1.5)+(a/2))/a,lambda x: 1, lambda x: ((2.6)+(b/2)-x)/b, lambda x: 0])
n=100
x = np.linspace(1.01, 2.99,n)
y = np.linspace(0.01,0.99,n)
X,Y = np.meshgrid(x,y)
b_vals = [ 0.01,0.4, 0.79 ]
num_subplots = len(b_vals)
fig = plt.figure(figsize=(10, 4))
for i,b in enumerate(b_vals):
ax = fig.add_subplot(1 , num_subplots , i+1, projection='3d')
ax.plot_surface(X, Y, np.vectorize(t2)(X,Y,b), cmap=cm.gnuplot)
ax.set_title('b = %.2f'%b, fontsize=10)
plt.xlabel("x")
plt.ylabel("a")
ax.set_zlabel('T1(x,a,a_2)')
fig.savefig('contours.png', facecolor='grey', edgecolor='none')
Related
I have to do a second degree interpolation using an already existing code and changing the values for mine, but for some reason when i go ahead and gragth the interpolation, the fuction suddently stops (it is not continuous). Can someone help me figuring out whats wrong? I believe it has something to do with line 43 (evaluation on new data points), but I am not sure.
Source code:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-poster')
%matplotlib inline
def divided_diff(x, y):
'''
function to calculate the divided
differences table
'''
n = len(y)
coef = np.zeros([n, n])
# the first column is y
coef[:,0] = y
for j in range(1,n):
for i in range(n-j):
coef[i][j] = \
(coef[i+1][j-1] - coef[i][j-1]) / (x[i+j]-x[i])
return coef
def newton_poly(coef, x_data, x):
'''
evaluate the newton polynomial
at x
'''
n = len(x_data) - 1
p = coef[n]
for k in range(1,n+1):
p = coef[n-k] + (x -x_data[n-k])*p
return p
x = np.array([-5, -1, 0, 2])
y = np.array([-2, 6, 1, 3])
# get the divided difference coef
a_s = divided_diff(x, y)[0, :]
# evaluate on new data points
x_new = np.arange(-5, 2.1, .1)
y_new = newton_poly(a_s, x, x_new)
plt.figure(figsize = (12, 8))
plt.plot(x, y, 'bo')
plt.plot(x_new, y_new)
My code (adjusted for data points (0,0);(6.4,1.9);(10.6,4.3)):
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-poster')
%matplotlib inline
def divided_diff(x, y):
'''
function to calculate the divided
differences table
'''
n = len(y)
coef = np.zeros([n, n])
# the first column is y
coef[:,0] = y
for j in range(1,n):
for i in range(n-j):
coef[i][j] = \
(coef[i+1][j-1] - coef[i][j-1]) / (x[i+j]-x[i])
return coef
def newton_poly(coef, x_data, x):
'''
evaluate the newton polynomial
at x
'''
n = len(x_data) - 1
p = coef[n]
for k in range(1,n+1):
p = coef[n-k] + (x -x_data[n-k])*p
return p
x = np.array([0, 6.4, 10.6])
y = np.array([0, 1.9, 4.3])
# get the divided difference coef
a_s = divided_diff(x, y)[0, :]
# evaluate on new data points
x_new = np.arange(-5, 2.1, .1)
y_new = newton_poly(a_s, x, x_new)
plt.figure(figsize = (12, 8))
plt.plot(x, y, 'bo')
plt.plot(x_new, y_new)
I want to plot a graph in python by substituting piecewise function.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#set up constants
d0=0.2
d1=0.2
L0=0.2
L=5
delta1=0.02
Dp=1
def fun(x):
out = np.zeros_like(x)
out[(x >= 0) & (x <= d1)] = d0
mask = (x >= d1) & (x <= d1 + L0)
out[mask] = d0-0.5*delta1*(1+np.cos(2*np.pi/L0)*(x[mask]-d1-0.5*L0))
out[(x >= d1 + L0) & (x <= L)] = L0
return out
# Define 100 points between 0 to 5 evenly spaced
y = np.linspace(0, 5, 100) # Change
g = Dp*(y*y-(fun(y))**2) # Change
plt.plot(y, g) # Change
plt.show() # Change
dear fun(y)is not a function of y its a function of x. i am attaching the sample graph
I just have place holders for the initial conditions. But it seems the u function is the main issue. In removing it and replacing it as a constant I get a float int error. I feel like I'm almost there and am just making a small mistake.
enter image description here
code:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif', size=16)
from scipy.integrate import solve_ivp
%matplotlib inline
def EulerSys(F, y0, ti, tf, h):
t = np.arange(ti, tf+h, h)
n = len(t)
neq = len(y0)
x = np.zeros((neq, n))
x[:,0] = y0
for i in range(t.size - 1):
# [new value] = [old value] + [slope x step size]
x[:,i+1] = x[:,i] + h*F( t[i], x[:,i] )
return x
m1=55
m2=400
m3=100
k1=230000
k2=30000
k3=50000
k4=0
b2=1500
b3=4000
b4=700
L0=5
v=15
A=0.03
h = .05
ti =0
tf =3.2
t = np.arange(ti, tf+h, h)
# the initial conditions:
x0 = np.array([ 2.0, 0.0 , 1, 1,1,1])
n = len(t)
neq = len(x0)
# initialize the vector to store the solutions:
# the rows are the solutions, the columns are the time instances:
x = np.zeros((neq, n))
# store the initial conditions:
x[:,0] = x0
print(x)
def myFun(t,x):
u = lambda t: (A/2)*(1-np.cos(2*(3.14*(v*t/L0)))
n = len(x)
dx = np.zeros((n))
dx[0] = x[1]
dx[1] = (-(b2 + b4)*x[1]+b2*x[3]+b4*x[5]-[k1+k2+k4]*x[0]+k2*x[2]+k4*x[4]+k1*u)/m1
dx[2] = x[3]
dx[3] = (b2*x[1]-(b2+b3)*x[3]+b3*x[5]+k2*x[0]-(k2+k3)*x[2]+k3*x[4])/m2
dx[4] = x[5]
dx[5] = (b4*x[1]+b3*x[3]-(b3+b4)*x[5]+k4*x[0]+k3*x[2]-(k3+k4)*x(4))/m3
return dx
xsol= EulerSys(myFun, x0, ti, tf, h)
you are simply missing one bracket at the end.
u = lambda t: (A/2)*(1-np.cos(2*(3.14*(v*t/L0)))
should be:
u = lambda t: (A/2)*(1-np.cos(2*(3.14*(v*t/L0)))) # one more bracket
here is the test code that is stripped from the original question:
import numpy as np
# define variables needed
A = 1
v = 1
L0 = 1
u = lambda t: (A/2)*(1-np.cos(2*(3.14*(v*t/L0))))
print(u(1))
the result (with test numbers) is this:
2.536543312392503e-06
I have a set of data and I have fit a normal distribution to the data using numpy and scipy. But when I try to plot the pdf, I get the following error:
I have tried to change the dtype of Z, but that did not work. Any suggestions will help. Thanks.
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import numpy as np
import random
from sympy.matrices import Matrix
from sympy import symbols, pprint, N
from scipy.stats import multivariate_normal
from target import true_target_trajectory, target_posiion
def plot_gaussian(X, Y, Z):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
plt.show()
def covariance(x, y):
sigma1 = np.std(x, dtype=np.float64)
sigma2 = np.std(y, dtype=np.float64)
cov = np.matrix([[sigma1, sigma1*sigma2], [sigma1*sigma2, sigma2]])
min_eig = np.min(np.real(np.linalg.eigvals(cov)))
if min_eig < 0:
cov -= 10*min_eig * np.eye(*cov.shape)
return cov
def gaussian(x, mu, cov):
rv = multivariate_normal(mu, cov)
return rv.pdf(x)
#plot_gaussian()
vin = 300
qin = 9
x = []
y = []
time = np.linspace(0, 2*np.pi, 100)
for t in (time):
cc = target_posiion(vin, qin, t)
x.append(cc.T[0])
y.append(cc.T[1])
mu = np.array([np.mean(x), np.mean(y)])
cov = covariance(x, y)
X, Y = np.meshgrid(x, y)
pos = np.dstack((X, Y))
Z = gaussian(pos, mu, cov)
plot_gaussian(X, Y, Z)
I tried to reproduce the issue with x = np.linspace(-1, 3, 100) and y = np.linspace(0, 4, 100). But that did not give any error and i got the bell curve as expected.
So i am attaching the code for target position.
The code for target_position:
import random
import numpy as np
from sympy.vector.coordsysrect import CoordSys3D
from sympy.physics.mechanics import dynamicsymbols
from sympy import symbols, sin, pprint, Derivative, Identity, N
from sympy.matrices import Matrix, BlockMatrix, block_collapse
C = CoordSys3D('C')
i, j, k = C.base_vectors()
def evaluate_matrix(m, v_in, q_in, tk):
w, t = symbols('w t')
v0, q = symbols('v0 q')
params = {v0:v_in, q:q_in, t:tk}
return Matrix([[N(m[0].subs(params)), N(m[1].subs(params))]]).T
def true_target_trajectory(v_in, q_in, tk):
w, t = symbols('w t')
v0, q, A = symbols('v0 q A')
r, v, a, x, y = dynamicsymbols('r v a x y')
A = (v0**2)/q
w = q/(2*v0)
x = A*sin(w*t)*i
y = A*sin(2*w*t)*j
r = x + y
r_m = Matrix(r.to_matrix(C)[:2])
v = Derivative(r, t).doit()
v_m = Matrix(v.to_matrix(C)[:2])
a = Derivative(v, t).doit()
a_m = Matrix(a.to_matrix(C)[:2])
x_k = BlockMatrix([[r_m.T, v_m.T, a_m.T]]).T
I = Identity(2)
H = BlockMatrix([[I, I, I]])
z = evaluate_matrix(block_collapse(H*x_k), v_in, q_in, tk)
return z
def target_posiion(v_in, q_in, tk):
sigma = 50
u_k = Matrix([[random.gauss(0,1), random.gauss(0,1)]]).T
z = true_target_trajectory(v_in, q_in, tk)
z_c_k = z + sigma*u_k
return z_c_k
The problem
The problem is that your x and y are lists of type sympy.core.numbers.Float, not regular Python float. Numpy doesn't know how to convert Sympy numeric types, so meshgrid ends up returning X and Y arrays of dtype=object. Down the line, this ends up screwing up the call to ax.plot_surface.
The fix
Just convert x and y to standard Numpy arrays of np.float64 before you pass them into meshgrid:
X, Y = np.meshgrid(np.array(x).astype(float), np.array(y).astype(float))
Once you do that, everything should be fine. Here's the output:
I am trying to calculate the error rate of the training data I'm using.
I believe I'm calculating the error incorrectly. The formula is as shown:
y is calculated as shown:
I am calculating this in the function fitPoly(M) at line 49. I believe I am incorrectly calculating y(x(n)), but I don't know what else to do.
Below is the Minimal, Complete, and Verifiable example.
import numpy as np
import matplotlib.pyplot as plt
dataTrain = [[2.362761180904257019e-01, -4.108125266714775847e+00],
[4.324296163702689988e-01, -9.869308732049049127e+00],
[6.023323504115264404e-01, -6.684279243433971729e+00],
[3.305079685397107614e-01, -7.897042003779912278e+00],
[9.952423271981121200e-01, 3.710086310489402628e+00],
[8.308127402955634011e-02, 1.828266768673480147e+00],
[1.855495407116576345e-01, 1.039713135916495501e+00],
[7.088332047815845138e-01, -9.783208407540947560e-01],
[9.475723071629885697e-01, 1.137746192425550085e+01],
[2.343475721257285427e-01, 3.098019704040922750e+00],
[9.338350584099475160e-02, 2.316408265530458976e+00],
[2.107903139601833287e-01, -1.550451474833406396e+00],
[9.509966727520677843e-01, 9.295029459100994984e+00],
[7.164931165416982273e-01, 1.041025972594300075e+00],
[2.965557300301902011e-03, -1.060607693351102121e+01]]
def strip(L, xt):
ret = []
for i in L:
ret.append(i[xt])
return ret
x1 = strip(dataTrain, 0)
y1 = strip(dataTrain, 1)
# HELP HERE
def getY(m, w, D):
y = w[0]
y += np.sum(w[1:] * D[:m])
return y
# HELP ABOVE
def dataMatrix(X, M):
Z = []
for x in range(len(X)):
row = []
for m in range(M + 1):
row.append(X[x][0] ** m)
Z.append(row)
return Z
def fitPoly(M):
t = []
for i in dataTrain:
t.append(i[1])
w, _, _, _ = np.linalg.lstsq(dataMatrix(dataTrain, M), t)
w = w[::-1]
errTrain = np.sum(np.subtract(t, getY(M, w, x1)) ** 2)/len(x1)
print('errTrain: %s' % (errTrain))
return([w, errTrain])
#fitPoly(8)
def plotPoly(w):
plt.ylim(-15, 15)
x, y = zip(*dataTrain)
plt.plot(x, y, 'bo')
xw = np.arange(0, 1, .001)
yw = np.polyval(w, xw)
plt.plot(xw, yw, 'r')
#plotPoly(fitPoly(3)[0])
def bestPoly():
m = 0
plt.figure(1)
plt.xlim(0, 16)
plt.ylim(0, 250)
plt.xlabel('M')
plt.ylabel('Error')
plt.suptitle('Question 3: training and Test error')
while m < 16:
plt.figure(0)
plt.subplot(4, 4, m + 1)
plotPoly(fitPoly(m)[0])
plt.figure(1)
plt.plot(fitPoly(m)[1])
#plt.plot(fitPoly(m)[2])
m+= 1
plt.figure(3)
plt.xlabel('t')
plt.ylabel('x')
plt.suptitle('Question 3: best-fitting polynomial (degree = 8)')
plotPoly(fitPoly(8)[0])
print('Best M: %d\nBest w: %s\nTraining error: %s' % (8, fitPoly(8)[0], fitPoly(8)[1], ))
bestPoly()
Updated: This solution uses numpy's np.interp which will connect the points as a kind of "best fit". We then use your error function to find the difference between this interpolated line and the predicted y values for the degree of each polynomial.
import numpy as np
import matplotlib.pyplot as plt
import itertools
dataTrain = [
[2.362761180904257019e-01, -4.108125266714775847e+00],
[4.324296163702689988e-01, -9.869308732049049127e+00],
[6.023323504115264404e-01, -6.684279243433971729e+00],
[3.305079685397107614e-01, -7.897042003779912278e+00],
[9.952423271981121200e-01, 3.710086310489402628e+00],
[8.308127402955634011e-02, 1.828266768673480147e+00],
[1.855495407116576345e-01, 1.039713135916495501e+00],
[7.088332047815845138e-01, -9.783208407540947560e-01],
[9.475723071629885697e-01, 1.137746192425550085e+01],
[2.343475721257285427e-01, 3.098019704040922750e+00],
[9.338350584099475160e-02, 2.316408265530458976e+00],
[2.107903139601833287e-01, -1.550451474833406396e+00],
[9.509966727520677843e-01, 9.295029459100994984e+00],
[7.164931165416982273e-01, 1.041025972594300075e+00],
[2.965557300301902011e-03, -1.060607693351102121e+01]
]
data = np.array(dataTrain)
data = data[data[:, 0].argsort()]
X,y = data[:, 0], data[:, 1]
fig,ax = plt.subplots(4, 4)
indices = list(itertools.product([0,1,2,3], repeat=2))
for i,loc in enumerate(indices, start=1):
xx = np.linspace(X.min(), X.max(), 1000)
yy = np.interp(xx, X, y)
w = np.polyfit(X, y, i)
y_pred = np.polyval(w, xx)
ax[loc].scatter(X, y)
ax[loc].plot(xx, y_pred)
ax[loc].plot(xx, yy, 'r--')
error = np.square(yy - y_pred).sum() / X.shape[0]
print(error)
plt.show()
This prints out:
2092.19807848
1043.9400277
1166.94550318
252.238810889
225.798905379
155.785478366
125.662973726
143.787869281
6553.66570273
10805.6609259
15577.8686283
13536.1755299
108074.871771
213513916823.0
472673224393.0
1.01198058355e+12
Visually, it plots out this:
From here, it's just a matter of saving those errors to a list and finding the minimum.
I may contribute :
def pol_y(x, w):
y = 0; power = 0;
for i in w:
y += i*(x**power);
power += 1;
return y
The M is included implicitly because it is the final index of w. So if w = [0, 0, 1], then pol_y(x, w) is as same as f(x) = x^2.
If you want to map the 1st column of the dataTrain :
get_Y = [pol_y(i, w) for i in x1 ]
The error may be calculated by
vec_error = [(y1[i] - getY[i])**2 for i in range(0, len(y1)];
train_error = np.sum(vec_error)/len(y1);
Hope this helps.