Ejemplo n.º 1
0
def adams_method(f, h, n, vec0, r, sigma=10, b=8 / 3):
    ans = []
    for i in range(len(vec0)):
        ans.append([])
    lib.transpose_and_add(ans, vec0)
    vec_0 = vec0
    f0 = f(vec_0, sigma, b, r)
    vec_1_ = runge_kutta.runge_kutta(f, h, 1, vec_0, r, sigma, b)
    vec_1 = [vec_1_[0][0], vec_1_[1][0], vec_1_[2][0]]
    lib.transpose_and_add(ans, vec_1)
    f1 = f(vec_1, sigma, b, r)
    vec_2_ = runge_kutta.runge_kutta(f, h, 1, vec_1, r, sigma, b)
    vec_2 = [vec_2_[0][0], vec_2_[1][0], vec_2_[2][0]]
    lib.transpose_and_add(ans, vec_2)
    f2 = f(vec_2, sigma, b, r)
    vec_3_ = runge_kutta.runge_kutta(f, h, 1, vec_2, r, sigma, b)
    vec_3 = [vec_3_[0][0], vec_3_[1][0], vec_3_[2][0]]
    lib.transpose_and_add(ans, vec_3)
    f3 = f(vec_3, sigma, b, r)
    for i in range(n):
        vec_4_0 = lib.sum_vectors(vec_3,
                                lib.num_to_vector(h / 24,
                                                  lib.sum_vectors(lib.num_to_vector(55, f3),
                                                                  lib.sum_vectors(lib.num_to_vector(-59, f2),
                                                                                  lib.sum_vectors(lib.num_to_vector(37, f1),
                                                                                                  lib.num_to_vector(-9, f0)
                                                                                                  )
                                                                                  )
                                                                  )
                                                  )
                                )
        f_4_0 = f(vec_4_0, sigma, b, r)

        vec_4 = lib.sum_vectors(vec_3,
                                lib.num_to_vector(h / 24,
                                                  lib.sum_vectors(lib.num_to_vector(9, f_4_0),
                                                                  lib.sum_vectors(lib.num_to_vector(19, f3),
                                                                                  lib.sum_vectors(lib.num_to_vector(-5, f2),
                                                                                                  f1
                                                                                                  )
                                                                                  )
                                                                  )
                                                  )
                                 )
        f4 = f(vec_4, sigma, b, r)
        vec_0 = vec_1
        vec_1 = vec_2
        vec_2 = vec_3
        vec_3 = vec_4
        f0 = f1
        f1 = f2
        f2 = f3
        f3 = f4
        lib.transpose_and_add(ans, vec_4)

    return ans
Ejemplo n.º 2
0
    def test_should_approximate_t_squared(self):
        y_0 = 0.0
        t_0 = 0.0
        steps = 100
        h = 1.0 / float(steps)
        function_2_t = lambda t_n, y_n: 2.0 * t_n
        ylist = [0.0 for i in range(steps)]
        runge_kutta(function_2_t, y_0, t_0, h, ylist)

        for i in range(0, steps - 1):
            t = float(i) * h
            self.assertEquals(ylist[i], t * t, 0.000000000000001, t)

        return
Ejemplo n.º 3
0
def runge_kutta_theoretical_error(h, left, right, result):
    new_result = runge_kutta(0.5 * h, left, right)[0]
    new_result = new_result[::2]
    result = scipy.array(result)
    new_result = scipy.array(new_result)
    error = abs(result - new_result) / 15.0
    return max(error)
def plot_simulation(state, title, export_file, t0, tf, dt, u, r0):
    #Variáveis para o plot no gráfico
    S = np.array([])
    I = np.array([])
    R = np.array([])
    x = np.array([])

    # Simulação usando o método de Runge Kutta
    for t in range(t0, t0 + tf, dt):
        u = runge_kutta(t0 + t, dt, u, r0)
        S = np.append(S, u[0])
        I = np.append(I, u[1])
        R = np.append(R, u[2])
        x = np.append(x, t0 + t)
        #if u[1] <= 1: break

    fig, ax1 = plt.subplots()  # Cria a figura e o axis para S e R

    color = 'tab:blue'
    ax1.set_xlabel('tempo (dias)')  # Configura o nome do axis x
    ax1.set_ylabel('não-infectados')  # Configura o nome do axis y para S e R
    ax1.plot(x, S, label='S', color=color)  # Plota S como linha simples
    ax1.plot(x, R, '--', label='R',
             color=color)  # Plota R como linha pontilhada
    ax1.tick_params(
        axis='y',
        labelcolor=color)  # Configura a cor e escala do axis y para I

    ax2 = ax1.twinx()  # Cria um novo axis para I

    color = 'tab:red'  # Cor para I
    ax2.set_ylabel('infectados')  #Configura o nome do axis y para I
    ax2.plot(x, I, label='I', color=color)  # Plota I como linha simples
    ax2.tick_params(
        axis='y',
        labelcolor=color)  # Configura a cor e escala do axis y para I

    ax1.set_title(title)  # Adiciona um título ao gráfico
    #ax1.set_title(title + ' - ' + state)  # Adiciona um título ao gráfico
    ax1.legend()  # Adiciona legenda para os plots em ax1
    #ax2.legend()  # Adiciona legenda para os plots em ax2

    #plt.show() # Mostra o plot em uma janela externa
    export_file = 'simulacoes/' + export_file + '.svg'
    plt.savefig(export_file,
                bbox_inches="tight")  # Salva o arquivo do plot como .svg

    plt.close()
Ejemplo n.º 5
0
def path_tracker(h, x_ball_init, front, up, W_of_backboard, H_of_backboard,
                 T_of_backboard, r_of_ball, center_hoop, backboard):
    import runge_kutta
    import Physical_Variables as p
    does_it_go_through = False
    t_new = 0
    x_new = x_ball_init
    while (t_new < 2):
        print(x_new)
        t_new, x_new = runge_kutta.runge_kutta(h, t_new, x_new)
        location, does_it_collide = did_it_collide(backboard, x_new[0:3],
                                                   front, up, W_of_backboard,
                                                   H_of_backboard,
                                                   T_of_backboard, r_of_ball)
        velocity_at_time = x_new[3:6]
        if does_it_collide:
            does_it_collide = True
            break
    return does_it_collide, location, velocity_at_time
Ejemplo n.º 6
0
from matrix import Matrix
from runge_kutta import runge_kutta
from trapez import trapez

if __name__ == '__main__':
    A = Matrix([[0, 1], [-200, -102]])
    B = Matrix([[0], [0]])
    T = 0.1
    t_max = 0.5

    x = Matrix([[1], [-2]])

    trapez(A=A, B=[], T=T, t_max=t_max, x0=x)
    print()
    runge_kutta(A=A, B=B, T=T, t_max=t_max, x0=x,)

 def _start_runge_kutta(self):
     self.points = [[],[]]
     self.points_i = [[],[]]
     # Inputs: endtime, starttime, matrix with start voltage and start currency, timesteps, figure to plot
     runge_kutta(300., 0, np.matrix('0;0'), 0.1, self)
Ejemplo n.º 8
0
import matplotlib.pyplot as plt
import numpy as np
import math

from function import f
from runge_kutta import runge_kutta
from adams_bashford import adams_bashford
from error import runge_kutta_theoretical_error, error

if __name__ == '__main__':
    h = 0.1
    left = 0
    right = 3
    x, runge_kutta_result = runge_kutta(h, left, right)
    x_adams_bashford, adams_bashford_result = adams_bashford(h, left, right)
    y = []
    for element in x:
        y.append(math.exp(element))
    plt.xlabel('x')
    plt.ylabel('y')
    plt.plot(x, y, 'g--', label='True solution')
    plt.plot(x, runge_kutta_result, 'r--', label='Runge-Kutta method')
    plt.plot(x_adams_bashford,
             adams_bashford_result,
             'b--',
             label='Adams-Bashford method')
    plt.legend()
    plt.grid(True)
    plt.show()

    theoretical_error = runge_kutta_theoretical_error(h, left, right,
Ejemplo n.º 9
0
from runge_kutta import runge_kutta
from matrix import Matrix
import math

if __name__ == '__main__':
    A = Matrix([[0, 1], [-1, 0]])
    B = Matrix([[0], [0]])
    T = math.pi * 2 / 50
    # T = 0.001
    t_max = 2

    x = Matrix([[1], [1]])

    runge_kutta(A=A, B=B, t_max=t_max, T=T, x0=x, real_value_flag=True)
Ejemplo n.º 10
0
x0 = x = 1
y0 = fex(1)
step = 20
exact = []

for i in range(step + 1):
    exact.append(fex(x))
    x = round(x + h, 1)

f = open("methods.csv", "w")

try:
    f.write("x, y(euler), y(exact), %error \n")
    for i in formatter(euler.euler(dydx, (x0, y0), 20, h, 1), exact, 2):
        f.write(f"{i[0]},{i[1]},{i[2]},{i[3]}\n")

    f.write("\n")

    f.write("x, y(e_cauchy), y(exact), %error \n")
    for i in formatter(eulercauchy.euler_cauchy(dydx, (x0, y0), 20, h, 1),
                       exact, 2):
        f.write(f"{i[0]},{i[1]},{i[2]},{i[3]}\n")

    f.write("\n")

    f.write("x, y(r_kutta), y(exact), %error \n")
    for i in formatter(runge_kutta.runge_kutta(dydx, (x0, y0), 20, h, 1),
                       exact, 5):
        f.write(f"{i[0]},{i[1]},{i[2]},{i[3]}\n")
finally:
    f.close()