Exemplo n.º 1
0
    def solve(self, span, P0, err=1e-6):
        ''' 
            solve back wheel track according to front wheel track and 
            initial position of the bicycle.

            Arguments:
                span: solving range of parameter t
                P0  : initial position of back wheel (x, y)
        '''

        t0, t1 = span

        # initial point of back wheel
        P0 = np.array(P0)

        # initial point of front wheel is defined by parametric equations
        Q0 = np.array([self.front_track_x(t0), self.front_track_y(t0)])

        # frame length is defined by P0 and Q0
        self.L = np.sum((P0 - Q0)**2)**0.5

        # solving
        res = ode(self.governing_equation, span, P0, err=err)

        # solved back track
        XY = [P[1] for P in res]
        X, Y = zip(*XY)
        self.X, self.Y = np.array(X), np.array(Y)

        # front wheel track
        self.t = np.array([P[0] for P in res])
        self.FX, self.FY = self.front_track_x(self.t), self.front_track_y(
            self.t)
def calculate(v,theta):
    vx_0 = v * math.cos(theta*math.pi/180)
    vy_0 = v * math.sin(theta*math.pi/180)
    A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
    A.set_fx(['v_x','-0.00004*700*v_x*(1-(0.0065*y)/280)**2.5','v_y','-9.8-0.00004*700*v_y*(1-(0.0065*y)/280)**2.5'],['t','x','v_x','y','v_y'])
    record = A.euler()[:]
    return correct([record[1][0],record[1][2]],0)
Exemplo n.º 3
0
def play(E2=2.0, L=0.75, r0=1.0, M=0.1, t0=0.0, signal_drds=-1.0, phi0=0.0):
    h = 0.005
    part = sch.particle(E2, L, t0, r0, phi0, signal_drds)
    if (E2 - part.V([t0, r0, phi0]) >= 0.0):
        f = [part.dtds, part.drds, part.dphids]  #Rightside function
        bh = sch.blackhole(M)
        ODE = ode.ode(f, h, r0, t0, 1.0)
        orbit = orb.orbit(part, bh, ODE)
        ani = anim.orbit_animation(orbit, 10)
        ani.show_orbit()
    else:
        print('Error! Values violate the energy equation!')
    return
def scan3(theta,delta,ran):
    theta = theta - ran
    theta_record = []
    x = []
    theta_record.append(theta)
    for i in range(int(ran*2/delta)):
        vx_0 = v * math.cos(theta*math.pi/180)
        vy_0 = v * math.sin(theta*math.pi/180)
        A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
        A.set_fx(['v_x','-0.00004*math.sqrt(v_x**2+v_y**2)*v_x','v_y','-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y'],['t','x','v_x','y','v_y'])
        x.append(correct(A.euler()[:])[1][0][-1])
        theta = theta + delta
        theta_record.append(theta)
    for j in range(len(x)):
        if ( x[0] < x[j]):
            x[0] = x[j]
            theta_record[0] = theta_record[j]
    return theta_record[0]
def scan3(theta,delta,ran):
    theta = theta - ran
    theta_record = []
    x = []
    theta_record.append(theta)
    for i in range(int(ran*2/delta)):
        vx_0 = v * math.cos(theta*math.pi/180)
        vy_0 = v * math.sin(theta*math.pi/180)
        A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
        A.set_fx(['v_x','-0.00004*math.sqrt(v_x**2+v_y**2)*v_x','v_y','-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y'],['t','x','v_x','y','v_y'])
        x.append(correct(A.euler()[:])[1][0][-1])
        theta = theta + delta
        theta_record.append(theta)
    for j in range(len(x)):
        if ( x[0] < x[j]):
            x[0] = x[j]
            theta_record[0] = theta_record[j]
    return theta_record[0]
Exemplo n.º 6
0
        self.x = []
        self.t = []
        self.t.append(self.a)
        self.w.append(0)
        self.x.append(self.x_0)
        for i in range(1,self.N):
            self.w.append(self.w[i - 1] - self.x[i - 1]**3*self.dt)
            self.x.append(self.x[i - 1] + self.w[i] * self.dt)
            self.t.append(self.t[i - 1] + self.dt)
        return self.t, self.x
        

plt.figure(figsize = (10,6))
### --------------- forth-order Runge-Kutta ----------
#start=time.clock()
A = solving_ode.ode(0.1,0,40,(0,1.2))  
A.set_fx(('-x**5','w'),['t','w','x'])
rgkt_3_record = A.rgkt_4()[:]
#end = time.clock()
#print "read: %f s" % (end - start)
### -------------- second-order Runge-Kutta ----------
#rgkt_2_record = A.rgkt_2()[:]
### -----------------------------------------------
#start=time.clock()
B = harmonic_alpha3(0.04,0,40,1.2)
euler_c_record = B.calculate()
#B.find_period()
#end = time.clock()
#print "read: %f s" % (end - start)
### ------------- alpha = 3 ----------------------
'''amplitude = 0.8
            theta_record[0] = theta_record[j]
    return theta_record[0]
         

##---------------- Isothermal ---------------------------------
#theta = 45
#theta = scan1(scan1(scan1(scan1(45,5,20),2,10),0.5,2),0.01,0.3)
theta = scan2(scan2(scan2(scan2(45,5,20),2,10),0.5,2),0.01,0.3)
plt.figure(figsize = (8,6))
#plt.subplot(131)
vx_0 = v * math.cos(theta*math.pi/180)
vy_0 = v * math.sin(theta*math.pi/180)
plt.title('Trajectory of cannon shell (Isothermal Correction)')
plt.xlabel('x(m)')
plt.ylabel('y(m)')
A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
#A.set_fx(['v_x','-0.00004*v_x*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)','v_y','-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y*math.e**(-y/10000)'],['t','x','v_x','y','v_y'])
A.set_fx(['v_x','-0.00004*math.sqrt(v_x**2+v_y**2)*v_x*(1-(0.0065*y)/280)**2.5','v_y','-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y*(1-(0.0065*y)/280)**2.5'],['t','x','v_x','y','v_y'])
cannon_record = correct(A.euler()[:])
x_max = cannon_record[1][0][-1]
print x_max
print theta
plt.plot(cannon_record[1][0],cannon_record[1][2],linewidth = 3, label=str(theta))
#for i in range(6):
#    vx_0 = v * math.cos(theta*math.pi/180)
#    vy_0 = v * math.sin(theta*math.pi/180)
#    A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
#    A.set_fx(['v_x','-0.00004*v_x*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)','v_y','-9.8-0.00004*v_y*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)'],['t','x','v_x','y','v_y'])
#    cannon_record = correct(A.rgkt_3()[:])
#    plt.plot(cannon_record[1][0],cannon_record[1][2],linewidth = 3, label=str(theta))
#    theta = theta +5
Exemplo n.º 8
0
import numpy as np
from ode import ode_solver as ode

def f(x, y) :
	return np.array([y[1],-y[0]])

a = 0
b = 4*np.pi
eps = 1e-6
acc = 1e-6
h = 1e-6
x = [a]
y = [np.array([0, 1])]
ode = ode(f, x, y, eps = eps, acc = acc, step = h, printinfo = False)
ode.driver(b)

for i in range(len(ode.x)):
    print(ode.x[i]/np.pi, ' ', ode.y[i][0], ' ',ode.y[i][1])
Exemplo n.º 9
0
def one_step_evolution(p_density, s_density, police, xx, yy,
                       p_kernel, cut_off_pirates,
                       cut_off_ships, cut_off_police,
                       dx, dy, dt, kappa, a,
                       velocity, nu_x, nu_y, controls, time):
    """
    This function performs a one time step evolution for the whole system

    :param p_density: numpy 2d array describing the density of pirates at time t
    :param s_density: numpy 2d array describing the density of ships at time t
    :param police: list containing the position of police
    :param xx: numpy 2d array describing the x-mesh. Same shape as p_density
               and s_density
    :param yy: numpy 2d array describing the y-mesh. Same shape as p_density
               and s_density
    :param p_kernel: numpy 2d array describing the kernel in the equation for
                     pirates. Same shape as p_density
    :param cut_off_pirates: cut_off function for pirates.
    :param cut_off_ships: cut_off function for ships.
    :param cut_off_police: cut_off function for police.
    :param dx: float. The size of the x-mesh
    :param dy: float. The size of the y-mesh
    :param dt: float. The time step. It should satisfy a stability condition
    :param kappa: function. It takes a numpy array and returns an arry of the same shape. It is the normalized function in the equation for pirates
    :param a: array of floats. Coefficients a for the source term f in the equation for pirates.
    :param velocity: function describing the speed of the ship.
    :param nu_x: x-direction of the geometric component of nu
    :param nu_y: x-direction of the geometric component of nu
    :param controls: function giving the controls for police vessels
    :param time: float. initial time

    The output is a tuple (p_new, s_new, police_new) of three elements.
    :output p_new: numpy 2d array of the same shape as p_density
                   describing the density of pirates at time t + dt
    :output s_new: numpy 2d array of the same shape as s_density
                   describing the density of ships at time t + dt
    :output police_new: list of final position of police vessels
    """
    # some checks
    shape_p_density = numpy.shape(p_density)
    assert (shape_p_density == numpy.shape(s_density))
    assert (shape_p_density == numpy.shape(xx))
    assert (shape_p_density == numpy.shape(yy))
    assert (shape_p_density == numpy.shape(yy))

    # Calculus of common terms ?
    police_sum_x = sum(i[0] for i in police)
    police_sum_y = sum(i[1] for i in police)
    M = len(police)
    
    ################################
    # Evolution of pirate density
    ################################

    # 2d convolution on a fixed mesh
    # h * k [n, m] = dx * dy * convolve2d(h, k)
    p_convolution = dx * dy * scipy.signal.convolve2d(s_density, p_kernel, mode='same')
    # gradient of the convolution
    grad_py, grad_px = numpy.gradient(p_convolution, dy, dx)
    # norm of the gradient
    norm_grad_p_convolution = numpy.sqrt(grad_px**2 + grad_py**2)
    flux_x = kappa(norm_grad_p_convolution) * grad_px * p_density
    flux_y = kappa(norm_grad_p_convolution) * grad_py * p_density
    # divergence
    trash, div1 = numpy.gradient(flux_x, dy, dx)
    div2, trash = numpy.gradient(flux_y, dy, dx)
    div = - div1 - div2
    
    # term depending on the police
    f = numpy.zeros_like(xx)
    for i in xrange(len(police)):
        f += a[i] * cut_off_pirates(xx - police[i][0], yy - police[i][1])

    p_new = pde.one_step_parabolic(p_density, xx, yy, div, -f, dx, dy, dt)



    ################################
    # Evolution of ship density
    ################################

    # 2d convolution on a fixed mesh
    # h * k [n, m] = dx * dy * convolve2d(h, k)
    cal_I1_x = - dx * dy * scipy.signal.convolve2d(p_density, xx * cut_off_ships(xx, yy), mode='same')
    cal_I1_y = - dx * dy * scipy.signal.convolve2d(p_density, yy * cut_off_ships(xx, yy), mode='same')

    cal_I2_x = numpy.zeros_like(xx)
    cal_I2_y = numpy.zeros_like(xx)
    for i in xrange(len(police)):
        cal_I2_x += cut_off_ships(xx - police[i][0], yy - police[i][1]) * (police[i][0] - xx)
        cal_I2_y += cut_off_ships(xx - police[i][0], yy - police[i][1]) * (police[i][1] - yy)

    cal_I_x = cal_I1_x + cal_I2_x
    cal_I_y = cal_I1_y + cal_I2_y
    vel_x = cal_I_x + nu_x
    vel_y = cal_I_y + nu_y

    # (vel_x, vel_y) should be at most of norm 1!!!
    vel_pseudo_norm = numpy.maximum(numpy.sqrt(vel_x**2 + vel_y**2), 1.)
    vel_x = vel_x / vel_pseudo_norm
    vel_y = vel_y / vel_pseudo_norm
        
    s_new = pde.one_step_hyperbolic_godunov(s_density, velocity, vel_x, vel_y, dx, dy, dt)

    s_new = numpy.minimum(numpy.maximum(s_new, 0.), 1.)


    
    ################################
    # Evolution of police position
    ################################

    police_new = []
    for i in xrange(len(police)):
        temp = cut_off_police(police[i][0] - xx, police[i][1] - yy) * p_density * s_density
        F1_x = dx * dy * numpy.sum(temp * (xx - police[i][0]))
        F1_y = dx * dy * numpy.sum(temp * (yy - police[i][1]))

        F2_x = police_sum_x - M * police[i][0]
        F2_y = police_sum_y - M * police[i][1]

        F3_x = controls(time)[i][0]   #control_x
        F3_y = controls(time)[i][1]   #control_y

        police_new.append(ode.ode(F1_x + F2_x + F3_x, F1_y + F2_y + F3_y, police[i], dt))



    return (p_new, s_new, police_new)
Exemplo n.º 10
0
            theta_record[0] = theta_record[j]
    return theta_record[0]


##---------------- Isothermal ---------------------------------
#theta = 45
#theta = scan1(scan1(scan1(scan1(45,5,20),2,10),0.5,2),0.01,0.3)
theta = scan2(scan2(scan2(scan2(45, 5, 20), 2, 10), 0.5, 2), 0.01, 0.3)
plt.figure(figsize=(8, 6))
#plt.subplot(131)
vx_0 = v * math.cos(theta * math.pi / 180)
vy_0 = v * math.sin(theta * math.pi / 180)
plt.title('Trajectory of cannon shell (Isothermal Correction)')
plt.xlabel('x(m)')
plt.ylabel('y(m)')
A = solving_ode.ode(0.1, 0, 200, (0, vx_0, 0, vy_0))
#A.set_fx(['v_x','-0.00004*v_x*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)','v_y','-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y*math.e**(-y/10000)'],['t','x','v_x','y','v_y'])
A.set_fx([
    'v_x', '-0.00004*math.sqrt(v_x**2+v_y**2)*v_x*(1-(0.0065*y)/280)**2.5',
    'v_y', '-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y*(1-(0.0065*y)/280)**2.5'
], ['t', 'x', 'v_x', 'y', 'v_y'])
cannon_record = correct(A.euler()[:])
x_max = cannon_record[1][0][-1]
print x_max
print theta
plt.plot(cannon_record[1][0],
         cannon_record[1][2],
         linewidth=3,
         label=str(theta))
#for i in range(6):
#    vx_0 = v * math.cos(theta*math.pi/180)
Exemplo n.º 11
0
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 24 19:09:36 2016

@author: AF
"""

import ode as solving_ode
import matplotlib.pyplot as plt
import math

A = solving_ode.ode(0.005, 3.8, 4, (2, 8))
A.set_fx(('y1', '-x*y+y1*math.e**x+3*math.sin(2*x)'), ['x', 'y', 'y1'])
rgkt_3_record = A.rgkt_3()
B = solving_ode.ode(0.005, 3.8, 4, (2, 8))
B.set_fx(('y1', '-x*y+y1*math.e**x+3*math.sin(2*x)'), ['x', 'y', 'y1'])
euler_record = B.euler()
plt.figure(figsize=(10, 6))
plt.plot(euler_record[0], euler_record[1][0], label='simple euler method')
plt.plot(rgkt_3_record[0], rgkt_3_record[1][0], label='3rd Runge-Kutta method')
plt.legend(loc='left upper')
plt.savefig('example2.png', dpi=144)
plt.show()
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 24 19:09:36 2016

@author: AF
"""

import ode as solving_ode
import matplotlib.pyplot as plt

A = solving_ode.ode(0.1,0,2,5)  ##### setting the initial population N(0) = 10
A.set_fx('N',['t','N'])
rgkt_3_record = A.rgkt_3()
plt.figure(figsize = (10,6))
plt.plot(rgkt_3_record[0],rgkt_3_record[1][0],label = '3rd Runge-Kutta method')
plt.legend()
plt.savefig('chapter1_1.6.png',dpi = 144)
plt.show()
##---------------- Isothermal ---------------------------------
theta = 45

theta = scan1(scan1(scan1(scan1(45,5,20),2,10),0.5,2),0.01,0.3)

plt.figure(figsize = (8,6))

plt.subplot(131)

vx_0 = v * math.cos(theta*math.pi/180)
vy_0 = v * math.sin(theta*math.pi/180)
plt.title('Trajectory of cannon shell (Isothermal Correction)')
plt.xlabel('x(m)')
plt.ylabel('y(m)')
A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
A.set_fx(['v_x','-0.00004*v_x*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)','v_y','-9.8-0.00004*math.sqrt(v_x**2+v_y**2)*v_y*math.e**(-y/10000)'],['t','x','v_x','y','v_y'])

cannon_record = correct(A.euler()[:])
x_max = cannon_record[1][0][-1]
print x_max
print theta
plt.plot(cannon_record[1][0],cannon_record[1][2],linewidth = 3, label=str(theta))

theta = 30
for i in range(6):
    vx_0 = v * math.cos(theta*math.pi/180)
    vy_0 = v * math.sin(theta*math.pi/180)
    A = solving_ode.ode(0.1,0,200,(0,vx_0,0,vy_0))
    A.set_fx(['v_x','-0.00004*v_x*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)','v_y','-9.8-0.00004*v_y*math.sqrt(v_x**2+v_y**2)*math.e**(-y/10000)'],['t','x','v_x','y','v_y'])
    cannon_record = correct(A.euler()[:])
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 09:08:06 2016

@author: AF
"""

import ode as solving_ode
import matplotlib.pyplot as plt
import math

A = solving_ode.ode(0.01, 0, 0.5, 100)
A.set_fx('10*y', ['x', 'y'])
rgkt_3_record1 = A.rgkt_3()[:]
euler_record = A.euler()[:]
A.set_fx('10*y - 0.01*y**2', ['x', 'y'])
rgkt_3_record2 = A.rgkt_3()[:]
A.set_fx('10*y - 0.04*y**2', ['x', 'y'])
rgkt_3_record3 = A.rgkt_3()[:]
A.set_fx('10*y - 0.07*y**2', ['x', 'y'])
rgkt_3_record4 = A.rgkt_3()[:]
A.set_fx('10*y - 0.12*y**2', ['x', 'y'])
rgkt_3_record5 = A.rgkt_3()[:]
A.set_fx('10*y - 0.16*y**2', ['x', 'y'])
rgkt_3_record6 = A.rgkt_3()[:]
b = 0
y = [100]
euler_2nd = [100]
for i in range(1, len(rgkt_3_record1[0])):
    y.append((10 * 100 * math.e**(10 * rgkt_3_record1[0][i])) /
             (10 - b * 100 + b * 100 * math.e**(10 * rgkt_3_record1[0][i])))
@author: AF
"""

import numpy as np
import matplotlib.pyplot as plt
import ode as solving_ode
#from visual import *

###  -------- circular orbit -----------------
e = 0.99
r_min = 0.314
r_0 = r_min * (1 + e) / (1 - e)
a = r_min / (1 - e)
v_0 = np.sqrt(4 * np.pi**2 * (1 - e)**2 / (r_min * (1 + e)))
A = solving_ode.ode(0.001, 0, 50, (r_0, 0, 0, v_0))
A.set_fx([
    'vx',
    '-4*np.pi**2*x/(np.sqrt(x**2+y**2))**3*(1+0.001/(np.sqrt(x**2+y**2))**2)',
    'vy',
    '-4*np.pi**2*y/(np.sqrt(x**2+y**2))**3*(1+0.001/(np.sqrt(x**2+y**2))**2)'
], ['t', 'x', 'vx', 'y', 'vy'])
data_record = A.rgkt_4()
theta_record = []
time_record = []
for i in range(len(data_record[1][0]) - 1):
    if (data_record[1][0][i]**2 + data_record[1][2][i]**2 >
            data_record[1][0][i - 1]**2 + data_record[1][2][i - 1]**2
            and data_record[1][0][i]**2 + data_record[1][2][i]**2 >
            data_record[1][0][i + 1]**2 + data_record[1][2][i + 1]**2):
        time_record.append(data_record[0][i])
        self.x = []
        self.t = []
        self.t.append(self.a)
        self.w.append(0)
        self.x.append(self.x_0)
        for i in range(1,self.N):
            self.w.append(self.w[i - 1] - self.x[i - 1]**3*self.dt)
            self.x.append(self.x[i - 1] + self.w[i] * self.dt)
            self.t.append(self.t[i - 1] + self.dt)
        return self.t, self.x
        

plt.figure(figsize = (10,6))
### --------------- forth-order Runge-Kutta ----------
#start=time.clock()
A = solving_ode.ode(0.1,0,40,(0,1.2))  
A.set_fx(('-x**5','w'),['t','w','x'])
rgkt_3_record = A.rgkt_4()[:]
#end = time.clock()
#print "read: %f s" % (end - start)
### -------------- second-order Runge-Kutta ----------
#rgkt_2_record = A.rgkt_2()[:]
### -----------------------------------------------
#start=time.clock()
B = harmonic_alpha3(0.04,0,40,1.2)
euler_c_record = B.calculate()
#B.find_period()
#end = time.clock()
#print "read: %f s" % (end - start)
### ------------- alpha = 3 ----------------------
'''amplitude = 0.8
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 24 19:09:36 2016

@author: AF
"""

import ode as solving_ode
import matplotlib.pyplot as plt
import math

A = solving_ode.ode(0.005,3.8,4,(2,8))  
A.set_fx(('y1','-x*y+y1*math.e**x+3*math.sin(2*x)'),['x','y','y1'])
rgkt_3_record = A.rgkt_3()
B = solving_ode.ode(0.005,3.8,4,(2,8))
B.set_fx(('y1','-x*y+y1*math.e**x+3*math.sin(2*x)'),['x','y','y1'])
euler_record = B.euler()
plt.figure(figsize = (10,6))
plt.plot(euler_record[0],euler_record[1][0],label = 'simple euler method')
plt.plot(rgkt_3_record[0],rgkt_3_record[1][0],label = '3rd Runge-Kutta method')
plt.legend(loc = 'left upper')
plt.savefig('example2.png',dpi = 144)
plt.show()
Exemplo n.º 18
0
def one_step_evolution(p_density, s_density, police, xx, yy, p_kernel,
                       cut_off_pirates, cut_off_ships, cut_off_police, dx, dy,
                       dt, kappa, a, velocity, nu_x, nu_y, controls, time):
    """
    This function performs a one time step evolution for the whole system

    :param p_density: numpy 2d array describing the density of pirates at time t
    :param s_density: numpy 2d array describing the density of ships at time t
    :param police: list containing the position of police
    :param xx: numpy 2d array describing the x-mesh. Same shape as p_density
               and s_density
    :param yy: numpy 2d array describing the y-mesh. Same shape as p_density
               and s_density
    :param p_kernel: numpy 2d array describing the kernel in the equation for
                     pirates. Same shape as p_density
    :param cut_off_pirates: cut_off function for pirates.
    :param cut_off_ships: cut_off function for ships.
    :param cut_off_police: cut_off function for police.
    :param dx: float. The size of the x-mesh
    :param dy: float. The size of the y-mesh
    :param dt: float. The time step. It should satisfy a stability condition
    :param kappa: function. It takes a numpy array and returns an arry of the same shape. It is the normalized function in the equation for pirates
    :param a: array of floats. Coefficients a for the source term f in the equation for pirates.
    :param velocity: function describing the speed of the ship.
    :param nu_x: x-direction of the geometric component of nu
    :param nu_y: x-direction of the geometric component of nu
    :param controls: function giving the controls for police vessels
    :param time: float. initial time

    The output is a tuple (p_new, s_new, police_new) of three elements.
    :output p_new: numpy 2d array of the same shape as p_density
                   describing the density of pirates at time t + dt
    :output s_new: numpy 2d array of the same shape as s_density
                   describing the density of ships at time t + dt
    :output police_new: list of final position of police vessels
    """
    # some checks
    shape_p_density = numpy.shape(p_density)
    assert (shape_p_density == numpy.shape(s_density))
    assert (shape_p_density == numpy.shape(xx))
    assert (shape_p_density == numpy.shape(yy))
    assert (shape_p_density == numpy.shape(yy))

    # Calculus of common terms ?
    police_sum_x = sum(i[0] for i in police)
    police_sum_y = sum(i[1] for i in police)
    M = len(police)

    ################################
    # Evolution of pirate density
    ################################

    # 2d convolution on a fixed mesh
    # h * k [n, m] = dx * dy * convolve2d(h, k)
    p_convolution = dx * dy * scipy.signal.convolve2d(
        s_density, p_kernel, mode='same')
    # gradient of the convolution
    grad_py, grad_px = numpy.gradient(p_convolution, dy, dx)
    # norm of the gradient
    norm_grad_p_convolution = numpy.sqrt(grad_px**2 + grad_py**2)
    flux_x = kappa(norm_grad_p_convolution) * grad_px * p_density
    flux_y = kappa(norm_grad_p_convolution) * grad_py * p_density
    # divergence
    trash, div1 = numpy.gradient(flux_x, dy, dx)
    div2, trash = numpy.gradient(flux_y, dy, dx)
    div = -div1 - div2

    # term depending on the police
    f = numpy.zeros_like(xx)
    for i in xrange(len(police)):
        f += a[i] * cut_off_pirates(xx - police[i][0], yy - police[i][1])

    p_new = pde.one_step_parabolic(p_density, xx, yy, div, -f, dx, dy, dt)

    ################################
    # Evolution of ship density
    ################################

    # 2d convolution on a fixed mesh
    # h * k [n, m] = dx * dy * convolve2d(h, k)
    cal_I1_x = -dx * dy * scipy.signal.convolve2d(
        p_density, xx * cut_off_ships(xx, yy), mode='same')
    cal_I1_y = -dx * dy * scipy.signal.convolve2d(
        p_density, yy * cut_off_ships(xx, yy), mode='same')

    cal_I2_x = numpy.zeros_like(xx)
    cal_I2_y = numpy.zeros_like(xx)
    for i in xrange(len(police)):
        cal_I2_x += cut_off_ships(xx - police[i][0],
                                  yy - police[i][1]) * (police[i][0] - xx)
        cal_I2_y += cut_off_ships(xx - police[i][0],
                                  yy - police[i][1]) * (police[i][1] - yy)

    cal_I_x = cal_I1_x + cal_I2_x
    cal_I_y = cal_I1_y + cal_I2_y
    vel_x = cal_I_x + nu_x
    vel_y = cal_I_y + nu_y

    # (vel_x, vel_y) should be at most of norm 1!!!
    vel_pseudo_norm = numpy.maximum(numpy.sqrt(vel_x**2 + vel_y**2), 1.)
    vel_x = vel_x / vel_pseudo_norm
    vel_y = vel_y / vel_pseudo_norm

    s_new = pde.one_step_hyperbolic_godunov(s_density, velocity, vel_x, vel_y,
                                            dx, dy, dt)

    s_new = numpy.minimum(numpy.maximum(s_new, 0.), 1.)

    ################################
    # Evolution of police position
    ################################

    police_new = []
    for i in xrange(len(police)):
        temp = cut_off_police(police[i][0] - xx,
                              police[i][1] - yy) * p_density * s_density
        F1_x = dx * dy * numpy.sum(temp * (xx - police[i][0]))
        F1_y = dx * dy * numpy.sum(temp * (yy - police[i][1]))

        F2_x = police_sum_x - M * police[i][0]
        F2_y = police_sum_y - M * police[i][1]

        F3_x = controls(time)[i][0]  #control_x
        F3_y = controls(time)[i][1]  #control_y

        police_new.append(
            ode.ode(F1_x + F2_x + F3_x, F1_y + F2_y + F3_y, police[i], dt))

    return (p_new, s_new, police_new)
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 09:08:06 2016

@author: AF
"""

import ode as solving_ode
import matplotlib.pyplot as plt
import math


A = solving_ode.ode(0.01,0,0.5,100)
A.set_fx('10*y',['x','y'])
rgkt_3_record1 = A.rgkt_3()[:]
euler_record = A.euler()[:]
A.set_fx('10*y - 0.01*y**2',['x','y'])
rgkt_3_record2 = A.rgkt_3()[:]
A.set_fx('10*y - 0.04*y**2',['x','y'])
rgkt_3_record3 = A.rgkt_3()[:]
A.set_fx('10*y - 0.07*y**2',['x','y'])
rgkt_3_record4 = A.rgkt_3()[:]
A.set_fx('10*y - 0.12*y**2',['x','y'])
rgkt_3_record5 = A.rgkt_3()[:]
A.set_fx('10*y - 0.16*y**2',['x','y'])
rgkt_3_record6 = A.rgkt_3()[:]
b = 0
y = [100]
euler_2nd = [100]
for i in range(1,len(rgkt_3_record1[0])):
    y.append((10*100*math.e**(10*rgkt_3_record1[0][i]))/(10 - b*100 + b*100*math.e**(10*rgkt_3_record1[0][i])))
@author: AF
"""

import numpy as np
import matplotlib.pyplot as plt
import ode as solving_ode
#from visual import *

###  -------- circular orbit -----------------
e = 0.99
r_min = 0.314
r_0 = r_min*(1 + e)/(1 - e)
a = r_min/(1 - e)
v_0 = np.sqrt(4*np.pi**2*(1 - e)**2/(r_min*(1 + e))) 
A = solving_ode.ode(0.001,0,50,(r_0,0,0,v_0))
A.set_fx(['vx','-4*np.pi**2*x/(np.sqrt(x**2+y**2))**3*(1+0.001/(np.sqrt(x**2+y**2))**2)','vy','-4*np.pi**2*y/(np.sqrt(x**2+y**2))**3*(1+0.001/(np.sqrt(x**2+y**2))**2)'],['t','x','vx','y','vy'])
data_record = A.rgkt_4()
theta_record = []
time_record = []
for i in range(len(data_record[1][0]) - 1):
    if ( data_record[1][0][i]**2+data_record[1][2][i]**2 > data_record[1][0][i - 1]**2+data_record[1][2][i - 1]**2 and data_record[1][0][i]**2+data_record[1][2][i]**2> data_record[1][0][i + 1]**2+data_record[1][2][i + 1]**2):
        time_record.append(data_record[0][i])
        theta_record.append(np.arctan(data_record[1][2][i]/data_record[1][0][i])*180/np.pi)
print time_record
print theta_record

###  ------ vpython -------------------------
'''sun = sphere(pos = (0,0,0),radius = 0.22,color = color.yellow)
lamp = local_light(pos=(0,0,0), color=color.yellow)
deltat = 0.0001