I want to "animate" a circle rolling over the sin graph, I made a code where the circle moves rapidly down a straight line, now I want the same but the acceleration will be changing.
My previous code:
import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0, np.pi * 2, (0.01 * np.pi))
x = np.arange(-50, 1, 1)
y = x - 7
plt.figure()
for t in np.arange(0, 4, 0.1):
plt.plot(x, y)
xc = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.cos(theta))
yc = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.sin(theta))
plt.plot(xc, yc, 'r')
xp = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.cos(np.pi * t))
yp = ((-9.81 * t**2 * np.sin(np.pi / 2)) / 3) + (5 * np.sin(np.pi * t))
plt.plot(xp, yp, 'bo')
plt.pause(0.01)
plt.cla()
plt.show()
You can do this by numerically integrating:
dt = 0.01
lst_x = []
lst_y = []
t = 0
while t < 10: #for instance
t += dt
a = get_acceleration(function, x)
x += v * dt + 0.5 * a * dt * dt
v += a * dt
y = get_position(fuction, x)
lst_x.append(x)
lst_y.append(y)
This is assuming the ball never leaves your slope! If it does, you'll also have to integrate in y in a similar way as done in x!!
Where your acceleration is going to be equal to g * cos(slope).
Related
I solve the motion in gravitational field around the sun with scipy and mathplotlib and have a problem. My solution is not correct. It is not like in example. Formulas that I used.
from scipy.integrate import odeint
import scipy.constants as constants
import numpy as np
import matplotlib.pyplot as plt
M = 1.989 * (10 ** 30)
G = constants.G
alpha = 30
alpha0 = (alpha / 180) * np.pi
v00 = 0.7
v0 = v00 * 1000
def dqdt(q, t):
x = q[0]
y = q[2]
ax = - G * M * (x / ((x ** 2 + y ** 2) ** 1.5))
ay = - G * M * (y / ((x ** 2 + y ** 2) ** 1.5))
return [q[1], ax, q[3], ay]
vx0 = v0 * np.cos(alpha0)
vy0 = v0 * np.sin(alpha0)
x0 = -150 * (10 ** 11)
y0 = 0 * (10 ** 11)
q0 = [x0, vx0, y0, vy0]
N = 1000000
t = np.linspace(0.0, 100000000000.0, N)
pos = odeint(dqdt, q0, t)
x1 = pos[:, 0]
y1 = pos[:, 2]
plt.plot(x1, y1, 0, 0, 'ro')
plt.ylabel('y')
plt.xlabel('x')
plt.grid(True)
plt.show()
How can I fix this?
Maybe you can tell me solution with another method for example with Euler's formula or with using other library.
I will be very greatful if you help me.
Below is my code, I'm supposed to use the electric field equation and the given variables to create a density plot and surface plot of the equation. I'm getting "invalid dimensions for image data" probably because the function E takes multiple variables and is trying to display them all as multiple dimensions. I know the issue is that I have to turn E into an array so that the density plot can be displayed, but I cannot figure out how to do so. Please help.
import numpy as np
from numpy import array,empty,linspace,exp,cos,sqrt,pi
import matplotlib.pyplot as plt
lam = 500 #Nanometers
x = linspace(-10*lam,10*lam,10)
z = linspace(-20*lam,20*lam,10)
w0 = lam
E0 = 5
def E(E0,w0,x,z,lam):
E = np.zeros((len(x),len(z)))
for i in z:
for j in x:
E = ((E0 * w0) / w(z,w0,zR(w0,lam)))
E = E * exp((-r(x)**2) / (w(z,w0,zR(w0,lam)))**2)
E = E * cos((2 * pi / lam) * (z + (r(x)**2 / (2 * Rz(z,zR,lam)))))
return E
def r(x):
r = sqrt(x**2)
return r
def w(z,w0,lam):
w = w0 * sqrt(1 + (z / zR(w0,lam))**2)
return w
def Rz(z,w0,lam):
Rz = z * (1 + (zR(w0,lam) / z)**2)
return Rz
def zR(w0,lam):
zR = pi * lam
return zR
p = E(E0,w0,x,z,lam)
plt.imshow(p)
It took me way too much time and thinking but I finally figured it out after searching for similar examples of codes for similar problems. The correct code looks like:
import numpy as np
from numpy import array,empty,linspace,exp,cos,sqrt,pi
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
lam = 500*10**-9 #Nanometers
x1 = linspace(-10*lam,10*lam,100)
z1 = linspace(-20*lam,20*lam,100)
[x,y] = np.meshgrid(x1,z1)
w0 = lam
E0 = 5
r = sqrt(x**2)
zR = pi * lam
w = w0 * sqrt(1 + (y / zR)**2)
Rz = y * (1 + (zR / y)**2)
E = (E0 * w0) / w
E = E * exp((-r**2 / w**2))
E = E * cos((2 * pi / lam) * (y + (r**2 / (2 * Rz))))
def field(x,y):
lam = 500*10**-9
k = (5 * lam) / lam * sqrt(1 + (y / (pi*lam))**2)
k *= exp(((-sqrt(x**2)**2 / (lam * sqrt(1 + (y / pi * lam)**2))**2)))
k *= cos((2 / lam) * (y + ((sqrt(x**2)**2 / (2 * y * (1 + (pi * lam / y)**2))))))
return k
#Density Plot
f = field(x,y)
plt.imshow(f)
plt.show()
#Surface Plot
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x,y,E,rstride=1,cstride=1)
plt.show
I have no idea about how to plot fourier series graph from equation like this
I try to use matplotlib to plot this but there are so many values. Here are code that I used. Not sure about algorithm.
import numpy as np
import matplotlib.pyplot as plt
x_ = np.linspace(0, 30, 10000)
a0 = 3/5
##an = 1/n * np.pi * (np.sin(0.4 * n * np.pi) + np.sin(0.8 * n * np.pi))
##bn = 1/n * np.pi * (2 - np.cos(0.4 * n * np.pi) - np.cos(0.8 * n * np.pi))
f0 = 5
def a(n):
return 1/n * np.pi * (np.sin(0.4 * n * np.pi) + np.sin(0.8 * n * np.pi))
def b(n):
return 1/n * np.pi * (2 - np.cos(0.4 * n * np.pi) - np.cos(0.8 * n * np.pi))
def s(t, n):
temp = 0
for i in range (1, n + 1):
temp = temp + (a(i) * np.cos(2 * np.pi * i * f0 * t) \
+ b(i) * np.sin(2 * np.pi * n * f0 * t))
temp += a0
return temp
st = []
for i in range (1, 6):
st.append(s(1, 6))
plt.title("Test")
plt.plot(x_, st, color="red")
plt.show()
Tried this then got this error
ValueError: x and y must have same first dimension, but have shapes (10000,) and (5,)
thanks for any help
I have an image read in with python and I wish to add some different sine stripes on this image as a noise. I wish the frequency and the rotation degree of a sine is totally random. I tried numpy module but it might not be the model I need here.
Can anyone tell me any python module has such function to add random sine curve to a image?
The result should somewhat similar to this image below:
Finally I find I can finish all of this using Numpy module:
def sineimg(img, color='black', linewidth=1.5, linestyle="-"):
'''
frequency = X / random.uniform(10.0, 20.0)
amplitude = randint(35, 50)
phase = random.uniform(1.0, 16.0)
rotation = random.uniform(-pi / 2, pi / 2)
'''
#Random rotation angle
rot = random.randint(-90, 90)
x_ = img.shape[0] / np.cos(np.pi * rot / 180)
X = np.linspace(-1 * x_, x_, 512)
axes = plt.subplot(111)
np.cos(np.pi * rot / 180)
#Random amplitude
amp1 = random.randint(35, 50)
amp2 = random.randint(35, 50)
#Random frequency
frequency1 = X / random.uniform(10.0, 20.0)
frequency2 = X / random.uniform(10.0, 20.0)
#Random offset phase
phase1 = np.pi / random.uniform(1.0, 16.0) + np.pi / 2
phase2 = np.pi / random.uniform(1.0, 16.0) + np.pi / 3
#random distance between line cluster
distance = random.randint(90, 115)
#I need roughly 8 times of them
for i in range(8):
Y1 = amp1 * np.sin(frequency1 + phase1) - 450 + i * distance
Y2 = amp2 * np.sin(frequency2 + phase2) - 420 + i * distance
x1_trans = X * np.cos(np.pi * rot / 180) - Y1* np.sin(np.pi * rot / 180)
y1_trans = X * np.sin(np.pi * rot / 180) + Y1* np.cos(np.pi * rot / 180)
x2_trans = X * np.cos(np.pi * rot / 180) - Y2* np.sin(np.pi * rot / 180)
y2_trans = X * np.sin(np.pi * rot / 180) + Y2* np.cos(np.pi * rot / 180)
#Remove label
axes.set_xticks([])
axes.set_yticks([])
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_color('none')
axes.spines['left'].set_color('none')
axes.plot(x1_trans, y1_trans, color = color, linewidth=linewidth, linestyle=linestyle)
axes.plot(x2_trans, y2_trans, color = color, linewidth=linewidth, linestyle=linestyle)
plt.imshow(img, zorder=0, extent=[148, -148, -225, 225])
Them:
img=mpimg.imread('me.jpg')
sineimg(img)
I get images like:
How can I find the closet distance between my trajectory and (384400,0,0)?
Also, how can I the distance from (384400,0,0) to the path at time t = 197465?
I understand that the arrays have the data but is there a way to have it check the distance of all the points (x,y,z) and return what I am looking for?
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
me = 5.974 * 10 ** (24) # mass of the earth
mm = 7.348 * 10 ** (22) # mass of the moon
G = 6.67259 * 10 ** (-20) # gravitational parameter
re = 6378.0 # radius of the earth in km
rm = 1737.0 # radius of the moon in km
r12 = 384400.0 # distance between the CoM of the earth and moon
M = me + mm
pi1 = me / M
pi2 = mm / M
mue = 398600.0 # gravitational parameter of earth km^3/sec^2
mum = G * mm # grav param of the moon
mu = mue + mum
omega = np.sqrt(mu / r12 ** 3)
nu = -129.21 * np.pi / 180 # true anomaly angle in radian
x = 327156.0 - 4671
# x location where the moon's SOI effects the spacecraft with the offset of the
# Earth not being at (0,0) in the Earth-Moon system
y = 33050.0 # y location
vbo = 10.85 # velocity at burnout
gamma = 0 * np.pi / 180 # angle in radians of the flight path
vx = vbo * (np.sin(gamma) * np.cos(nu) - np.cos(gamma) * np.sin(nu))
# velocity of the bo in the x direction
vy = vbo * (np.sin(gamma) * np.sin(nu) + np.cos(gamma) * np.cos(nu))
# velocity of the bo in the y direction
xrel = (re + 300.0) * np.cos(nu) - pi2 * r12
# spacecraft x location relative to the earth
yrel = (re + 300.0) * np.sin(nu)
# r0 = [xrel, yrel, 0]
# v0 = [vx, vy, 0]
u0 = [xrel, yrel, 0, vx, vy, 0]
def deriv(u, dt):
n1 = -((mue * (u[0] + pi2 * r12) / np.sqrt((u[0] + pi2 * r12) ** 2
+ u[1] ** 2) ** 3)
- (mum * (u[0] - pi1 * r12) / np.sqrt((u[0] - pi1 * r12) ** 2
+ u[1] ** 2) ** 3))
n2 = -((mue * u[1] / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3)
- (mum * u[1] / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3))
return [u[3], # dotu[0] = u[3]
u[4], # dotu[1] = u[4]
u[5], # dotu[2] = u[5]
2 * omega * u[5] + omega ** 2 * u[0] + n1, # dotu[3] = that
omega ** 2 * u[1] - 2 * omega * u[4] + n2, # dotu[4] = that
0] # dotu[5] = 0
dt = np.arange(0.0, 320000.0, 1) # 200000 secs to run the simulation
u = odeint(deriv, u0, dt)
x, y, z, x2, y2, z2 = u.T
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z)
plt.show()
To find the distance along each point in the trajectory:
my_x, my_y, my_z = (384400,0,0)
delta_x = x - my_x
delta_y = y - my_y
delta_z = z - my_z
distance = np.sqrt(np.power(delta_x, 2) +
np.power(delta_y, 2) +
np.power(delta_z, 2))
And then to find the min and that specific distance:
i = np.argmin(distance)
t_min = i / UNITS_SCALE # I can't tell how many units to a second. Is it 1.6?
d_197465 = distance[int(197465 * UNITS_SCALE)]
PS, I'm no rocket scientist, and thus haven't actually checked the stuff above x, y, z, x2, y2, z2 = u.T. I'm assuming that those are your trajectory's position and velocity?