integrating orbital trajectories 2 - python-2.7

The original second order ODEs are
x'' - 2 * omega * y' - omega ** 2 * x = - mue * (x + pi2 * r12) / np.sqrt((x + pi2 * r12) ** 2 + y ** 2) ** 3 - mum * (x - pi1 * r12) / np.sqrt((x - pi1 * r12) ** 2 + y ** 2)
y'' + 2 * omega * x' - omega **2 * y = - mue * y / np.sqrt((x + pi2 * r12) ** 2 + y ** 2) ** 3 - mum * y / np.sqrt((x - pi1 * r12) ** 2 + y ** 2)
z'' = 0
So here is the code I used to solve the ODE but first I broke it up into 2 first orders.
I am receiving the error that the module on line 61 is not callable.
Line 61 is u = odeint(deriv, u0, dt)
#!/usr/bin/env python
import numpy as np
import scipy.integrate as 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 = 0.0 # flight path angle
x = 327156.0 # x location where the moon's SOI effects the spacecraft
y = 33050.0 # y location
vbo = 10.85 # velocity at burnout
gamma = -141.868 * np.pi / 180 # angle in radians of true anomaly
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(gamma)
# spacecraft x location relative to the earth
yrel = (re + 300.0) * np.sin(gamma)
# 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, 250000.0, .1)
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()

Assuming you mean this error:
~/coding$ python orbit1.py
Traceback (most recent call last):
File "orbit1.py", line 61, in <module>
u = odeint(deriv, u0, dt)
TypeError: 'module' object is not callable
This is because you want the function named odeint in scipy.integrate. Your line
import scipy.integrate as odeint
imports the entire module and gives it the name odeint. Try
from scipy.integrate import odeint
instead, or
import scipy.integrate
[...]
u = scipy.integrate.odeint(deriv, u0, dt)
which should give you

Related

Sum of increasing alternate terms in python

I need to evaluate the finite sum of numbers which are increasing in absolute value, but are alternate. Problem is: the abolute values grow too fast and it starts accumulating numerical errors. These the functions definitions, one (Gj_full) straight to it and the other (Gj) recursively. fact_quo is a simple factorial function.
def fact_quo(n, m=1):
if (type(n) != int) or (type(m) != int):
raise TypeError("Arguments must be integers.")
if (n < 0) or (m < 0):
raise ValueError("n=" + str(n) + "\t m=" + str(m))
if (n == 0) or (n == 1) or (n == m):
return 1
if (n < m):
raise ValueError("n=" + str(n) + "\t m=" + str(m))
f = n
while n > (m+1):
n -= 1
f *= n
return f
def Gj_full(X, Y, Xl, Yl, j=0, coef=1):
if (X - Y + Xl + Yl) % 2 or X < Y or Y < j:
raise ValueError
u = (X - Y + Xl + Yl) // 2
v = coef * (2 ** (X - Y) * fact_quo(X, Y-j) * fact_quo(u+j, j) *
4 ** j * (-1) ** j)
w = 3 ** (u+j) * fact_quo(X-Y+j)
den2 = fact_quo(X) * fact_quo(Xl) * fact_quo(Yl)
z = (np.sqrt(fact_quo(X)) * np.sqrt(fact_quo(Y))
* np.sqrt(fact_quo(Xl)) * np.sqrt(fact_quo(Yl)))
return (v / (den2 * w)) * z
def Gj(X, Y, Xl, Yl, j=0, coef=1):
if (X - Y + Xl + Yl) % 2 or X < Y or Y < j:
raise ValueError
kX, kY, kXl, kYl, kj = X % 2, Y % 2, Xl % 2, Yl % 2, 0
g = coef * Gj_full(kX, kY, kXl, kYl, kj)
while kX < X:
u = (kX - kY + kXl + kYl) // 2
v = 4 * (u + kj + 1)
w = 3 * (kX + 2 - kY + kj) * (kX + 1 - kY + kj)
g *= (v / w) * np.sqrt(kX + 2) * np.sqrt(kX + 1)
kX += 2
while kXl < Xl:
u = (kX - kY + kXl + kYl) // 2
v = u + kj + 1
w = 3 * (kXl + 2) * (kXl + 1)
g *= (v / w) * np.sqrt(kXl + 2) * np.sqrt(kXl + 1)
kXl += 2
while kYl < Yl:
u = (kX - kY + kXl + kYl) // 2
v = u + kj + 1
w = 3 * (kYl + 2) * (kYl + 1)
g *= (v / w) * np.sqrt(kYl + 2) * np.sqrt(kYl + 1)
kYl += 2
while kY < Y:
u = (kX - kY + kXl + kYl) // 2
v = 3 * (kX - kY + kj) * (kX - kY - 1 + kj)
w = 4 * (kY + 2 - kj) * (kY + 1 - kj) * (u + kj)
g *= (v / w) * np.sqrt(kY + 2) * np.sqrt(kY + 1)
kY += 2
while kj < j:
u = (kX - kY + kXl + kYl) // 2
v = -4 * (kY - kj) * (u + kj + 1)
w = 3 * (kX - kY + kj + 1) * (kj + 1)
g *= (v / w)
kj += 1
return g
The (4/3) ** j and the factorials quicly increase the absolute value of the summing terms. The sum, however, are supposed to be smaller than 1. In fact, for X = Y and Xl = Yl = 0, the sum equals to (-1/3) ** X.
The precision for infinitely large numbers for floats are not available yet without using a lib. Therefore you should look into the decimal lib, you can even set the precision. Eg.
import decimal
decimal.getcontext().prec = 100
def pi():
pi = decimal.Decimal(0)
for k in range(350):
pi += (decimal.Decimal(4)/(decimal.Decimal(8)*decimal.Decimal(k+1))...)
If you manage to force all the numbers to be integers, you don't need to worry about it

How to Solve Rendering Artifact in Blinn/Loop's Resolution Independent Curve Rendering?

In implementing Blinn/Loop's algorithm on curve rendering, I realize there is a special case on Loop Curve Type. As described in their paper (subsection 4.4, page 6-7), they said the curve should be divided into two but I'm really confused how to obtain the intersection point.
Here's my rendering result:
As stated in the paper, this artifact occurs when either td/sd or te/se lie in between value [0, 1].
My source code:
...
case CURVE_TYPE_LOOP:
td = d2 + sqrt(4.0 * d1 * d3 - 3.0 * d2 *d2);
sd = 2.0 * d1;
te = d2 - sqrt(4.0 * d1 * d3 - 3.0 * d2 * d2);
se = 2.0 * d1;
if((td / sd > 0.0 && td/ sd < 1.0) || (te / se > 0.0 && te/ se < 1.0))
std::cout << "error\n";
// F matrix will be multiplied with inverse M3 to obtain tex coords (I use Eigen library btw...)
F << td * te, td * td * te, td * te * te, 1,
(-se * td) - (se * te), (-se * td * td) - (2.0 * sd * te * td), (-sd * te * te) - (2.0 * se * td * te), 0,
sd * se, te * sd * sd + 2.0 * se * td* sd, td * se * se + 2 * sd * te * se, 0,
0, -sd * sd * se, -sd * se * se, 0;
break;
...
Solved it,
I should get the splitting value t,
here's my code:
// get t
double splitLoop = -1.0;
switch (curve_type)
{
case CURVE_TYPE_UNKNOWN:
break;
case CURVE_TYPE_SERPENTINE:
tl = d2 + ((1.0 / sqrt(3.0)) * sqrt(3.0 * d2 * d2 - 4.0 * d1 * d3));
sl = 2.0 * d1;
tm = d2 - ((1.0 / sqrt(3.0)) * sqrt(3.0 * d2 * d2 - 4.0 * d1 * d3));
sm = 2.0 * d1;
F << tl * tm, tl * tl * tl, tm * tm * tm, 1,
-(sm * tl) -(sl * tm), -(3.0 * sl * tl * tl), -(3.0 * sm * tm * tm), 0,
sl * sm, 3.0 * sl * sl * tl, 3.0 * sm * sm * tm, 0,
0, -(sl * sl * sl), -(sm * sm * sm), 0;
break;
case CURVE_TYPE_LOOP:
td = d2 + sqrt(4.0 * d1 * d3 - 3.0 * d2 *d2);
sd = 2.0 * d1;
te = d2 - sqrt(4.0 * d1 * d3 - 3.0 * d2 * d2);
se = 2.0 * d1;
// Get splitting t
if((td / sd) > 0.0 && (td / sd) < 1.0)
{
splitLoop = td / sd;
}
else if((te / se) > 0.0 && (te/ se) < 1.0)
{
splitLoop = te / se;
}
F << td * te, td * td * te, td * te * te, 1,
(-se * td) - (se * te), (-se * td * td) - (2.0 * sd * te * td), (-sd * te * te) - (2.0 * se * td * te), 0,
sd * se, te * sd * sd + 2.0 * se * td* sd, td * se * se + 2 * sd * te * se, 0,
0, -sd * sd * se, -sd * se * se, 0;
break;
case CURVE_TYPE_QUADRATIC:
break;
case CURVE_TYPE_LINE:
break;
}
if(splitLoop > 0.0 && splitLoop < 1.0)
{
// SPLIT
double x01 = (x1 - x0) * splitLoop + x0;
double y01 = (y1 - y0) * splitLoop + y0;
double x12 = (x2 - x1) * splitLoop + x1;
double y12 = (y2 - y1) * splitLoop + y1;
double x23 = (x3 - x2) * splitLoop + x2;
double y23 = (y3 - y2) * splitLoop + y2;
double x012 = (x12 - x01) * splitLoop + x01;
double y012 = (y12 - y01) * splitLoop + y01;
double x123 = (x23 - x12) * splitLoop + x12;
double y123 = (y23 - y12) * splitLoop + y12;
double x0123 = (x123 - x012) * splitLoop + x012;
double y0123 = (y123 - y012) * splitLoop + y012;
// CURVE A (recursive)
DrawCubic(x0, y0, x01, y01, x012, y012, x0123, y0123);
// CURVE B (recursive)
DrawCubic(x0123, y0123, x123, y123, x23, y23, x3, y3);
}
else
{
// Draw as usual...
}
== EDIT ==
After i experimented again for a while, There's a numerical error on my program when the values of td/sd or te/se on subcurves lie again in between [0, 1], since my program use recursive by calling DrawCubic(), it causes recursive heap error.
In the meantime, I use 'hack' solution where I will not call DrawCurve() inside the recursive call (making sure the recursive is called only once). So far the result is quite satisfying and I don't see any artifact.
Any feedback is really welcomed since I'm not really good in numerical calculation :)

how can i change the b-spline curves from 4 point to 6?

I have a code on C++ it's b-spline curve that has 4 points if I want to change it to 6 point what shall I change in the code?
You can check the code:
#include "graphics.h"
#include <math.h>
int main(void) {
int gd, gm, page = 0;
gd = VGA;
gm = VGAMED;
initgraph(&gd, &gm, "");
point2d pontok[4] = { 100, 100, 150, 200, 170, 130, 240, 270 }; //pontok means points
int ap;
for (;;) {
setactivepage(page);
cleardevice();
for (int i = 0; i < 4; i++)
circle(integer(pontok[i].x), integer(pontok[i].y), 3);
double t = 0;
moveto((1.0 / 6) * (pontok[0].x * pow(1 - t, 3) +
pontok[1].x * (3 * t * t * t - 6 * t * t + 4) +
pontok[2].x * (-3 * t * t * t + 3 * t * t + 3 * t + 1) +
pontok[3].x * t * t * t),
(1.0 / 6) * (pontok[0].y * pow(1 - t, 3) +
pontok[1].y * (3 * t * t * t - 6 * t * t + 4) +
pontok[2].y * (-3 * t * t * t + 3 * t * t + 3 * t + 1) +
pontok[3].y * t * t * t));
for (t = 0; t <= 1; t += 0.01)
lineto(
(1.0 / 6) * (pontok[0].x * pow(1 - t, 3) +
pontok[1].x * (3 * t * t * t - 6 * t * t + 4) +
pontok[2].x * (-3 * t * t * t + 3 * t * t + 3 * t + 1) +
pontok[3].x * t * t * t),
(1.0 / 6) * (pontok[0].y * pow(1 - t, 3) +
pontok[1].y * (3 * t * t * t - 6 * t * t + 4) +
pontok[2].y * (-3 * t * t * t + 3 * t * t + 3 * t + 1) +
pontok[3].y * t * t * t));
/* Egerkezeles */ //Egerkezeles means mouse event handling
if (!balgomb)
ap = getactivepoint((point2d *)pontok, 4, 5);
if (ap >= 0 && balgomb) { //balgomb means left mouse button
pontok[ap].x = egerx; //eger means mouse
pontok[ap].y = egery;
}
/* Egerkezeles vege */
setvisualpage(page);
page = 1 - page;
if (kbhit())
break;
}
getch();
closegraph();
return 0;
}
From your formula, it looks like you are trying to draw a cubic Bezier curve. But the formula does not seem entirely correct. You can google "cubic Bezier curve" to find the correct formula. The Wikipedia page contains the formula for any degree of Bezier curve. You can find the "6-points" formula from there by using degree = 5.

Working code but getting a "confusing" plot with labels

I was trying to put labes on the streamlines around a body whose symmetric profile is generated by a vortex and a uniform flow, so far I must get something like this (with labels)
which I get it with the next code:
import numpy as np
import matplotlib.pyplot as plt
vortex_height = 18.0
h = vortex_height
vortex_intensity = 55.0
cv = vortex_intensity
permanent_speed = 10.0
U1 = permanent_speed
Y, X = np.mgrid[-25:25:100j, -25:25:100j]
U = 5.0 + 37.0857 * (Y - 18.326581) / (X ** 2 + (Y - 18.326581) ** 2) +- 37.0857 * (Y + 18.326581) / (X ** 2 + (Y + 18.326581) ** 2)
V = - 37.0857 * (X) / (X ** 2 + (Y - 18.326581) ** 2) + 37.0857 * (X) / (X ** 2 + (Y + 18.326581) ** 2)
speed = np.sqrt(U*U + V*V)
plt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
plt.colorbar()
#CS = plt.contour(U, v, speed)
#plt.clabel(CS, inline=1, fontsize=10)
#f, (ax1, ax2) = plt.subplots(ncols=2)
#ax1.streamplot(X, Y, U, V, density=[0.5, 1])
#lw = 5*speed/speed.max()
#ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)
plt.savefig("stream_plot5.png")
plt.show()
So I was changing the next example code (which use pylab):
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
# the function that I'm going to plot
def z_func(x,y):
return (1-(x**2+y**3))*exp(-(x**2+y**2)/2)
x = arange(-3.0,3.0,0.1)
y = arange(-3.0,3.0,0.1)
X,Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
im = imshow(Z,cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z,arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=10)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('$z=(1-x^2+y^3) e^{-(x^2+y^2)/2}$')
show()
with this plot:
And finally I get it like this:
import numpy as np
from numpy import exp,arange,log
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
# PSI = streamline
def streamLine(x, y, U = 5, hv = 18.326581, cv = 37.0857):
x2 = x ** 2
y2plus = (y + hv) ** 2
y2minus = (y - hv) ** 2
PSI_1 = U * y
PSI_2 = 0.5 * cv * log(x2 + y2minus)
PSI_3 = - 0.5 * cv * log(x2 + y2plus)
psi = PSI_1 + PSI_2 + PSI_3
return psi
"""
def streamLine(x, y):
return 0.5 * 37.0857 * log(x ** 2 + (y - 18.326581) ** 2)
# (5.0 * y + 0.5 * 37.0857 * math.log(x ** 2 + (y - 18.326581) ** 2) - 0.5 * 37.0857 * math.log(x ** 2 + (y + 18.326581) ** 2))
"""
x = arange(-20.0,20.0,0.1)
y = arange(-20.0,20.0,0.1)
X,Y = meshgrid(x, y) # grid of point
#Z = z_func(X, Y) # evaluation of the function on the grid
Z= streamLine(X, Y)
im = imshow(Z,cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z,arange(-5,6.5,0.2),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=9)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('$phi= 5.0 y + (1/2)* 37.0857 log(x^2 + (y - 18.326581)^2)-(1/2)* 37.085...$')
show()
#print type(Z)
#print len(Z)
But then I get the next plot:
which is something that keeps me wondering what's wrong because the axis are not where they should be.
contour() draws contour lines of a scalar field, and streamplot() is draw of vector field,
Vector fields can be constructed out of scalar fields using the gradient operator.
Here is an example:
import numpy as np
from numpy import exp,arange,log
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show,streamplot
# PSI = streamline
def f(x, y, U = 5, hv = 18.326581, cv = 37.0857):
x2 = x ** 2
y2plus = (y + hv) ** 2
y2minus = (y - hv) ** 2
PSI_1 = U * y
PSI_2 = 0.5 * cv * log(x2 + y2minus)
PSI_3 = - 0.5 * cv * log(x2 + y2plus)
psi = PSI_1 + PSI_2 + PSI_3
return psi
x = arange(-20.0,20.0,0.1)
y = arange(-20.0,20.0,0.1)
X,Y = meshgrid(x, y) # grid of point
#Z = z_func(X, Y) # evaluation of the function on the grid
Z= f(X, Y)
dx, dy = 1e-6, 1e-6
U = (f(X+dx, Y) - f(X, Y))/dx
V = (f(X, Y+dy) - f(X, Y))/dy
streamplot(X, Y, U, V, linewidth=1, color=(0, 0, 1, 0.3))
cset = contour(X, Y, Z,arange(-20,20,2.0),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=9)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('$phi= 5.0 y + (1/2)* 37.0857 log(x^2 + (y - 18.326581)^2)-(1/2)* 37.085...$')
show()
output:

2d rotation opengl

Here is the code I am using.
#define ANGLETORADIANS 0.017453292519943295769236907684886f // PI / 180
#define RADIANSTOANGLE 57.295779513082320876798154814105f // 180 / PI
rotation = rotation *ANGLETORADIANS;
cosRotation = cos(rotation);
sinRotation = sin(rotation);
for(int i = 0; i < 3; i++)
{
px[i] = (vec[i].x + centerX) * (cosRotation - (vec[i].y + centerY)) * sinRotation;
py[i] = (vec[i].x + centerX) * (sinRotation + (vec[i].y + centerY)) * cosRotation;
printf("num: %i, px: %f, py: %f\n", i, px[i], py[i]);
}
so far it seams my Y value is being fliped.. say I enter the value of X = 1 and Y = 1 with a 45 rotation you should see about x = 0 and y = 1.25 ish but I get x = 0 y = -1.25.
Also my 90 degree rotation always return x = 0 and y = 0.
p.s I know I'm only centering my values and not putting them back where they came from. It's not needed to put them back as all I need to know is the value I'm getting now.
Your bracket placement doesn't look right to me. I would expect:
px[i] = (vec[i].x + centerX) * cosRotation - (vec[i].y + centerY) * sinRotation;
py[i] = (vec[i].x + centerX) * sinRotation + (vec[i].y + centerY) * cosRotation;
Your brackets are wrong. It should be
px[i] = ((vec[i].x + centerX) * cosRotation) - ((vec[i].y + centerY) * sinRotation);
py[i] = ((vec[i].x + centerX) * sinRotation) + ((vec[i].y + centerY) * cosRotation);
instead