Exemplo n.º 1
0
def main():
    conn = Eu.connection(data_work)
    try:

        inspect_continuous_var(varName='age', conn=conn)
        inspect_continuous_var(
            varName='duration',
            conn=conn)  #duration in sec of last contact in current campaign

        #Exercise : Find other continous variables (Use Data Dictionary on Synopsis Page).
        #Exercise : Call inspection on those variables.

        inspect_continuous_var(
            varName='pdays',
            conn=conn)  #days since last contacted in this campaign
        inspect_continuous_var(varName='previous', conn=conn)  # no of contacts
        #inspect_continuous_var(varName='cons_conf_idx',conn=conn)#confidence index
        #inspect_continuous_var(varName='cons_price_idx',conn=conn)#consumer price
        #inspect_continuous_var(varName='emp_var_rate',conn=conn)# employment variation rate
        #inspect_continuous_var(varName='nr_employed',conn=conn) # no of employees

    except Exception as err:
        Eu.print_error(err)
    finally:
        conn.close()
Exemplo n.º 2
0
	def q2e(self):
		euler = Euler((0, 0, 0))
		sinx = 2.0*(self.w*self.x + self.y*self.z)
		cosx = 1.0 - 2.0*(self.x*self.x + self.y*self.y)
		euler.x = np.arctan2(sinx, cosx)

		siny = 2.0*(self.w*self.y - self.z*self.x)
		euler.y = np.arcsin(siny)

		sinz = 2.0*(self.w*self.z + self.x*self.y)
		cosz = 1.0 - 2.0*(self.y*self.y + self.z*self.z)
		euler.z = np.arctan2(sinz, cosz)

		return euler
Exemplo n.º 3
0
def main():
    conn = Eu.connection(data_work)
    try:

        sql = '''
        SELECT sql FROM sqlite_master
        WHERE tbl_name = 'bank' AND type = 'table'
        '''
        #Eu.run(sql,conn)

        ##A look at the 'age'
        sql = '''
        select age*1. from bank limit 10
        '''
        #Eu.run(sql,conn)

        ###Average age in sample
        sql = '''
        select avg(1.*age) mean_age  from bank
        '''
        #Eu.run(sql,conn)

        ####Min, Max, Mean
        sql = '''
        select min(age*1.) min_age, 
        round(avg(age*1.),0) mean_age, 
        max(age*1.) max_age
        from  bank
        '''
        #Eu.run(sql,conn)

        #####Min, Max, Mean by class type
        sql = '''
        select y,count(*) n_people, 
        min(age*1.) min_age, 
        round(avg(age*1.),0) mean_age, 
        max(age*1.) max_age
        from  bank
        group by y
        '''
        Eu.run(sql, conn)

        # Exercise: Fix the function
        inspect_continuous_var(varName='duration', conn=conn)
        inspect_continuous_var(varName='age', conn=conn)

    except Exception as err:
        Eu.print_error(err)
    finally:
        conn.close()
Exemplo n.º 4
0
def data_ingestion():
    '''
    This function reads CSV file
    and loads it into a SQLITE 
    database in Table form.
    '''
    try:
        csvfile = data_folder + 'bank_dataset.csv'
        pcsv = Eu.pycsv_reader(csvfile)
        #Dump into the database. Specify the tablename,sqlite filename etc
        pcsv.to_database(tabName='bank', database=data_work, verbose=False)

    except Exception as err:
        Eu.print_error(err)
    finally:
        pcsv.close()
Exemplo n.º 5
0
 def Initialze(self, acceleration, magneticField, position):
     """ calculates attitutde and heading
         sets position to given position vector 
     """
     self.quaternion = Quaternion(Euler(acceleration, magneticField).values)
     self.position.values = position
     self.isInitialized = True
Exemplo n.º 6
0
 def test_init(self):
     acc = toVector(1., 2., -10.)
     mag = toVector(50., 100., 120.)
     b = Euler(acc, mag)
     self.assertAlmostEqual(-0.197, b.values[0], delta=0.01)
     self.assertAlmostEqual(0.102, b.values[1], delta=0.01)
     self.assertAlmostEqual(1.047, b.values[2], delta=0.01)
Exemplo n.º 7
0
def inspect_categorical_var(varName, conn):
    '''
    Informal Inspection of Variables
    Parameters:
     varName : Variable to be inspected.
     conn    : Connection to sqlite database.
    '''
    try:
        sql = '''
        select ?varN?, count(*) n_people from bank
        group by ?varN?
        '''
        sql = sql.replace('?varN?', varName)
        print(sql)
        Eu.run(sql, conn)
    except Exception as err:
        Eu.print_error(err)
def plot_Euler_approx(dfdx, y_a, delta_x, a, b):
    """
    Plots the Euler approximation of y(x) given function dfdx and
    the initial point y_a from a to b with stepsize delta_x
    """
    xList = np.arange(a, b, delta_x)
    yList = Euler(dfdx, y_a, delta_x, a, b)
    plt.plot(xList, yList)
    plt.show()
Exemplo n.º 9
0
def main():
    conn = Eu.connection(data_work)
    try:
        sql = '''
        SELECT sql 
        FROM sqlite_master
        WHERE tbl_name = 'bank' AND type = 'table'
        '''
        Eu.run(sql, conn)

        #Calling inspect marital function
        inspect_marital(conn)

        #Exercise: Following function needs fixing
        inspect_job(conn)

    except Exception as err:
        Eu.print_error(err)
    finally:
        conn.close()
def plot_approx_and_exact(exact, resolution, dfdx, y_a, delta_x, a, b):
    """
    Plots the Euler approximation y(x) in red alongside its 
    given exact value in green from a to b
    """
    xList_a = np.arange(a, b, delta_x)
    yList_a = Euler(dfdx, y_a, delta_x, a, b)
    xList_e = np.linspace(a, b, resolution)
    yList_e = np.vectorize(exact)(xList_e)
    plt.plot(xList_a, yList_a, 'r')
    plt.plot(xList_e, yList_e, 'g')
    plt.show()
Exemplo n.º 11
0
def main():
    conn = Eu.connection(data_work)
    try:
        sql = '''
        SELECT sql FROM sqlite_master
        WHERE tbl_name = 'bank' AND type = 'table'
        '''
        Eu.run(sql, conn)

        #Calling inspect marital function
        inspect_marital(conn)
        #Calling inspect marital function
        inspect_job(conn)

        #Calling inspect categorical function
        inspect_categorical_var(varName='job', conn=conn)

    except Exception as err:
        Eu.print_error(err)
    finally:
        conn.close()
Exemplo n.º 12
0
def fs(mesh, prmt, u, AB, nmode, time):
    # set flow field boundary by structure
    A = AB[0]
    B = AB[1]
    [mesh.w_bot, mesh.wx_bot,
     mesh.wt_bot] = get_dydx_v_bot(A, B, nmode, mesh, prmt)
    # solve flow field
    [p, temp] = get_p_H(u)
    dudt = Euler(mesh, u, prmt, time)
    # solve structure
    dABdt = plate(AB, nmode, mesh, prmt, p)
    return dudt, dABdt
Exemplo n.º 13
0
def inspect_continuous_var(varName, conn):
    try:
        #Min, Max, Mean
        sql = '''
        select min(?var?*1.) min_?var?, 
        round(avg(?var?*1.),0) mean_?var?, 
        max(?var?*1.) max_?var?
        from  bank
        '''.replace('?var?', varName)
        print('Statistics for: ' + varName)
        Eu.run(sql, conn)

        #Min, Max, Mean by class type
        sql = '''
        select y,count(*) n_people, 
        min(?var?*1.) min_?var?, 
        round(avg(?var?*1.),0) mean_?var?, 
        max(?var?*1.) max_?var?
        from  bank
        group by y
        '''.replace('?var?', varName)
        print('Statistics for: ' + varName + ', grouped by y')
        Eu.run(sql, conn)

    except Exception as err:
        Eu.print_error(err)
Exemplo n.º 14
0
def inspect_continuous_var(varName, conn):
    '''
    Exercise: Fix this function so that
    it fetches information for 'varName'
    instead of 'age'.
    '''
    try:
        #Min, Max, Mean
        sql = '''
        select min(?varN?*1.) min_?varN?, 
        round(avg(?varN?*1.),0) mean_?varN?, 
        max(?varN?*1.) max_?varN?
        from  bank
        '''
        sql = sql.replace('?varN?', varName)
        print('Statistics for: ' + varName)
        Eu.run(sql, conn)

        #Min, Max, Mean by class type
        sql = '''
        select y,count(*) n_people, 
        min(?varN?*1.) min_?varN?, 
        round(avg(?varN?*1.),0) mean_?varN?, 
        max(?varN?*1.) max_?varN?
        from  bank
        group by y
        '''
        sql = sql.replace('?varN?', varName)
        print('Statistics for: ' + varName + ', grouped by y')
        Eu.run(sql, conn)

    except Exception as err:
        Eu.print_error(err)
Exemplo n.º 15
0
    def Solve(self):

        if self.method is 'Euler':
            from Euler import Euler
            [self.t, self.y] = Euler([self.minv, self.maxv], self.f0,
                                     self.funct, self.N)
        elif self.method is 'Heun':
            from Heun import Heun
            [self.t, self.y] = Heun([self.minv, self.maxv], self.f0,
                                    self.funct, self.N)
        elif self.method is 'RungeKutta4':
            from RungeKutta4 import RungeKutta4
            [self.t, self.y] = RungeKutta4([self.minv, self.maxv], self.f0,
                                           self.funct, self.N)
Exemplo n.º 16
0
def inspect_job(conn):
    try:
        #A look at the 'marital'
        sql = '''
        select distinct job from bank
        '''
        Eu.run(sql, conn)

        #Order the results by descending order of people
        sql = '''
        select job,count(*) n_people from bank
        group by job order by n_people desc
        '''
        Eu.run(sql, conn)
    except Exception as err:
        Eu.print_error(err)
Exemplo n.º 17
0
def AB2(sim):
    if sim.nfluxes < 1:
        sim.nfluxes = 1

    if len(sim.fluxes.u) == 0:

        Euler(sim)

    elif len(sim.fluxes.u) == 1:

        # Compute the fluxes
        sim.flux()

        if sim.adaptive:
            # The AB2 weights for adaptive delta(t)
            w1 = sim.dt * (1. + 0.5 * sim.dt / sim.dts[0])
            w2 = -0.5 * sim.dt**2 / sim.dts[0]
        else:
            # The AB2 weights for fixed delta(t)
            w1 = 3. / 2. * sim.dt
            w2 = -1. / 2. * sim.dt

        # Evolve the system
        sim.soln.u += w1 * sim.curr_flux.u + w2 * sim.fluxes.u[0]
        sim.soln.v += w1 * sim.curr_flux.v + w2 * sim.fluxes.v[0]
        sim.soln.h += w1 * sim.curr_flux.h + w2 * sim.fluxes.h[0]

        # Store the appropriate history
        if sim.nfluxes == 1:
            sim.fluxes.u = [sim.curr_flux.u.copy()]
            sim.fluxes.v = [sim.curr_flux.v.copy()]
            sim.fluxes.h = [sim.curr_flux.h.copy()]
            sim.dts = [sim.dt]
        else:
            sim.fluxes.u = [sim.curr_flux.u.copy()] + sim.fluxes.u
            sim.fluxes.v = [sim.curr_flux.v.copy()] + sim.fluxes.v
            sim.fluxes.h = [sim.curr_flux.h.copy()] + sim.fluxes.h
            sim.dts = [sim.dt] + sim.dts
Exemplo n.º 18
0
def inspect_marital(conn):
    '''
    This function examines the variable 'marital'
    '''
    try:
        #A look at the 'marital'
        sql = '''
        select distinct marital 
        from bank
        '''
        Eu.run(sql, conn)

        #Order the results by descending order of people
        sql = '''
        select marital, 
        count(*) n_people 
        from bank
        group by marital 
        order by n_people desc
        '''
        Eu.run(sql, conn)
    except Exception as err:
        Eu.print_error(err)
# -*- coding: utf-8 -*-
"""
Created on Wed May 22 22:17:31 2019

@author: Yorlin García
"""

from Euler import Euler
from scipy import linspace
from matplotlib import pyplot as plt
import numpy as np

fun = '2*a*b'

h = 0.05
xo = 1
yo = 1
Xmin = 1
Xmax = 1.5

Eu = Euler()
[t, y] = Eu.normal(xo, yo, Xmin, Xmax, h, fun)
plt.plot(t, y)
[x, Y] = Eu.mejorado(xo, yo, Xmin, Xmax, h, fun)
plt.plot(x, Y)
z1 = linspace(Xmin, Xmax, int((Xmax - Xmin) / h))
z2 = np.exp(z1**2 - 1)
plt.plot(z1, z2)
Exemplo n.º 20
0
def main():
    """ demo function for measurements saved as CSV file
    """
    s = Strapdown()
    K = KalmanPVO()
    #     kml = simplekml.Kml()

    rot_mean = toVector(0.018461137, -0.01460140625,
                        0.002765854)  # approximate values for gyro bias
    accelBias = toVector(0., 0., 0.)
    acc_mean = toVector(0., 0., 0.)
    mag_mean = toVector(0., 0., 0.)
    pos_mean = s.getPosition()
    dt_mean = 0.01

    # import IMU
    filePath = "data\\adafruit10DOF\\linie_dach_imu.csv"
    dIMU = CSVImporter(filePath,
                       columns=range(0, 13),
                       skip_header=7,
                       hasTime=True)
    accelArray, rotationArray, magneticArray = convArray2IMU(dIMU.values)
    tIMU, deltaArray = convArray2time(dIMU.values)

    # import GPS
    dGPS = CSVImporter("data\\UltimateGPS\\linie_dach_gps.csv",
                       skip_header=1,
                       columns=range(7))
    posArray, velArray = convArray2PV(dGPS.values)
    tGPS, _ = convArray2time(dGPS.values)
    #     PDOP = convArray2err(dGPS.values)

    j = 1  # index for GPS measurements
    for i in range(100, 58164):  # index for IMU measurements
        dt_mean = runningAverage(dt_mean, deltaArray[i], 1)

        # Initialzation
        if not s.isInitialized:
            rot_mean = runningAverage(rot_mean, rotationArray[:, i],
                                      1 / (i + 1))
            acc_mean = runningAverage(acc_mean, accelArray[:, i], 1 / i)
            mag_mean = runningAverage(mag_mean, magneticArray[:, i], 1 / i)
            if tIMU[i] >= tGPS[j]:
                pos_mean = runningAverage(pos_mean, posArray[:, j], 1 / j)
                j += 1
            if i >= 48133:  # for 10 - 15 minutes
                s.Initialze(acc_mean, mag_mean, pos_mean)
                gyroBias = rot_mean

                print(
                    'STRAPDOWN INITIALIZED with %i samples and %i position measurements\n'
                    % (i, j))
                e = Euler()
                e.values = s.getOrientation()
                print('Initial orientation\n', e)
                print('Initial velocity\n', s.velocity)
                print('Initial position\n', s.position)
                e.values = gyroBias
                print('Initial gyro bias\n', e)

        else:
            ###################################### plot area
            if i % 10 == 0:
                plt.figure(1)
                #                 lat, lon, h = s.getPosition()
                #                 plt.plot(i, h, 'ro')
                #                 plt.plot(lon,lat, 'go')
                #                 plotVector(i,s.getVelocity())
                plotVector(i, rad2deg(rad2deg(s.getOrientation())))
#                 kml.newpoint(name=str(i), coords=[(rad2deg(lon), rad2deg(lat), h)])
######################################

            acceleration = accelArray[:, i] - accelBias
            rotationRate = rotationArray[:, i] - gyroBias
            magneticField = magneticArray[:, i]

            s.quaternion.update(rotationRate, dt_mean)
            s.velocity.update(acceleration, s.quaternion, dt_mean)
            s.position.update(s.velocity, dt_mean)

            K.timeUpdate(acceleration, s.quaternion, dt_mean)
            try:
                gpsAvailable = tIMU[i] >= tGPS[j]
            except:  # end of GPS file reached
                gpsAvailable = False

#             if 55450 <= i <= 56450: # simulated GPS outage
#                 gpsAvailable = False
#
            if gpsAvailable or i % 10 == 0:  # doing either complete update or gyro error and bias update
                if gpsAvailable:
                    pos = posArray[:, j]
                    vel = velArray[:, j]
                    j += 1
                else:
                    pos = toVector(0., 0., 0.)
                    vel = toVector(0., 0., 0.)
                K.measurementUpdate(s.quaternion, s.position, s.velocity, pos,
                                    vel, acceleration, magneticField,
                                    gpsAvailable)
                errorQuat = Quaternion(K.oriError)
                s.quaternion = errorQuat * s.quaternion
                s.position.correct(K.posError)
                s.velocity.correct(K.velError)
                gyroBias = gyroBias + K.gyrError
                accelBias = accelBias - K.accError
                K.resetState()

    e.values = s.getOrientation()
    print('\nFinal orientation\n', e)
    print('Final position\n', s.position)

    print("Average sampling rate: {:3.1f}".format(1. / dt_mean))
    #         kml.save("export\\linie_dach.kml")
    plt.show()
Exemplo n.º 21
0
# print(-1 * pow(np.e, -0.5*0.1) - 1.5 * pow(np.e, -1.5*0.1))


if __name__ == '__main__':
    # email example (first order)
    # y' = (y-x-1)^2 + 2, y0 = 1, h = 0.1

    # input 형식(f, xn, yn, h)
    def f(x, y):  # y' = f(x, y)
        return pow(y - x - 1, 2) + 2
    x0 = 0
    y0 = 1
    h = 0.1

    # 사용법
    y1_Euler = Euler.eulerMethod(f, x0, y0, h)
    y1_improvedEuler = Euler.improvedEulerMethod(f, x0, y0, h)
    y1_RKClassic = RK.RKClassic(f, x0, y0, h)
    y1_4th = RK.RKFourth(f, x0, y0, h)  # 4-th order
    y1_5th = RK.RKFifth(f, x0, y0, h)  # 5-th order

    error = y1_5th - y1_4th  # email pdf에 나와있는 에러

    # 결과 출력법
    # Utils.printResult(f, x0, y0, h, exact_y=1.20033467209)  # pdf에 있는 실제 y값 사용했음
    # Utils.printResult(f, x0, y0, h)  # exact_y를 주지 않았을 때의 출력


    # -----------------------------------------------------------------------------------------
    # pdf system example
    # y'' + 2y' + 0.75y = 0, y0 = 3, y'0 = -2.5, h = 0.2
Exemplo n.º 22
0
 def Initialze(self, acceleration, magneticField):
     self.quaternion = Quaternion(Euler(acceleration, magneticField).values)
     self.isInitialized = True
Exemplo n.º 23
0
faces = np.arange(-N_cells // 2, N_cells // 2 + 1, delta_x)

#Grid generation
grid = Grid(faces)

#Specific heat ratio
gamma = 1.4

#Initial condition
U_initial = [
    State("Left", gamma, 1, 0, 2) if grid.cell_position[i] <= 0 else State(
        "Right", gamma, 1, 0, 1) for i in range(N_cells)
]

#Time parameters
t0 = 0
t_final = 25

#Exact solution
Riemann_problem = Riemann(1., 0., 2., 1., 0., 1., 1.4)

Courant_number = 0.7

solution = Euler(U_initial, grid, Courant_number, t0, t_final,
                 "Steger_Warming")

plot(Riemann_problem, solution, grid, t_final, Courant_number)

#Plot Figures
plt.show()
Exemplo n.º 24
0
from Euler import Euler

import matplotlib.pyplot as plt
import numpy as np
from numpy import cos

eq = Euler(0, 1, lambda x, y: y * (0.5 - y))

eq.plot("forward euler", [0, 3], 6)


def analytic(x):
    return -1 / (np.exp(-x / 2) - 2)


x = np.linspace(0, 3, 101)
y = np.vectorize(analytic)

plt.plot(x, y(x), label="analytic")
plt.legend()
plt.savefig("images/task_2b.png")

eq.plot("midpoint euler", [0, 3], 6)

plt.legend()
plt.savefig("images/task_2c.png")
plt.show()
Exemplo n.º 25
0
def main():
    conn = Eu.connection(data_work)
    try:
        #Call data_ingestion to create a working database.
        data_ingestion()
        #Check the column names
        sql = '''
        SELECT sql FROM sqlite_master
        WHERE tbl_name = 'bank' AND type = 'table'
        '''
        Eu.run(sql, conn)

        #A look at the column: 'marital'
        sql = '''
        select distinct marital 
        from bank
        '''
        Eu.run(sql, conn)

        #Count how many entries for each value of marital
        sql = '''
        SELECT marital, 
        COUNT(*) n_people 
        FROM bank
        GROUP by marital
        '''
        Eu.run(sql, conn)

        #Order the results by descending order of people
        sql = '''
        SELECT marital,
        COUNT(*) n_people 
        FROM bank
        GROUP by marital 
        ORDER by n_people desc
        '''
        Eu.run(sql, conn)

    except Exception as err:
        Eu.print_error(err)
    finally:
        conn.close()
Exemplo n.º 26
0
def AB3(sim):
    if sim.nfluxes < 2:
        sim.nfluxes = 2

    if len(sim.fluxes.u) == 0:

        Euler(sim)

    elif len(sim.fluxes.u) == 1:

        AB2(sim)

    elif len(sim.fluxes.u) == 2:

        # Compute the fluxes
        sim.flux()

        if sim.adaptive:
            # Compute the weights for the adaptive delta(t)
            # Adams-Bashforth 3 scheme
            tp = sim.time + sim.dt
            tn = sim.time

            gam1 = 3 * tn**2 + 3 * tn * sim.dt + sim.dt**2  # (tp**3 - tn**3)/dt
            gam2 = 2 * sim.time + sim.dt  # (tp**2 - tn**2)/dt
            gam3 = 1.  # (tp - tn)/dt

            a = sim.time - sim.dts[0]
            b = sim.time - sim.dts[0] - sim.dts[1]

            w0 = sim.dt * (
                (1. / 3) * gam1 - 0.5 * gam2 *
                (a + b) + a * b * gam3) / (sim.dts[0] *
                                           (sim.dts[0] + sim.dts[1]))

            a = sim.time
            b = sim.time - sim.dts[0] - sim.dts[1]

            w1 = sim.dt * ((1. / 3) * gam1 - 0.5 * gam2 *
                           (a + b) + a * b * gam3) / (-sim.dts[0] * sim.dts[1])

            a = sim.time
            b = sim.time - sim.dts[0]

            w2 = sim.dt * ((1. / 3) * gam1 - 0.5 * gam2 *
                           (a + b) + a * b * gam3) / (
                               (sim.dts[0] + sim.dts[1]) * sim.dts[1])
        else:
            # Compute the weights for the fixed delta(t)
            # Adams-Bashforth 3 scheme
            w0 = 23. / 12. * sim.dt
            w1 = -16. / 12. * sim.dt
            w2 = 5. / 12. * sim.dt

        # Evolve the system
        sim.soln.u += w0 * sim.curr_flux.u + w1 * sim.fluxes.u[
            0] + w2 * sim.fluxes.u[1]
        sim.soln.v += w0 * sim.curr_flux.v + w1 * sim.fluxes.v[
            0] + w2 * sim.fluxes.v[1]
        sim.soln.h += w0 * sim.curr_flux.h + w1 * sim.fluxes.h[
            0] + w2 * sim.fluxes.h[1]

        # Store the appropriate histories.
        if sim.nfluxes == 2:
            sim.fluxes.u = [sim.curr_flux.u.copy(), sim.fluxes.u[0].copy()]
            sim.fluxes.v = [sim.curr_flux.v.copy(), sim.fluxes.v[0].copy()]
            sim.fluxes.h = [sim.curr_flux.h.copy(), sim.fluxes.h[0].copy()]
            sim.dts = [sim.dt, sim.dts[0]]
        else:
            sim.fluxes.u = [sim.curr_flux.u.copy()] + sim.fluxes.u
            sim.fluxes.v = [sim.curr_flux.v.copy()] + sim.fluxes.v
            sim.fluxes.h = [sim.curr_flux.h.copy()] + sim.fluxes.h
            sim.dts = [sim.dt] + sim.dts
Copyright (c) 2016 Michael Seaman
License: MIT
Description: Runnable module that creates
graphs of the functions given by ODE solvers
along with their analyitical solutions
"""

from Euler import Euler
from Heun import Heun
from Runge_Kutta2 import Runge_Kutta2
from Runge_Kutta4 import Runge_Kutta4
from math import sin, cos



e = Euler(u0 = 1, v0 = 0, n = 8)
e.generate_graph_with_exact(sin, cos)

e = Euler(u0 = 1, v0 = 0, n = 100)
e.generate_graph_with_exact(sin, cos)

e = Euler(u0 = 1, v0 = 0, n = 1000)
e.generate_graph_with_exact(sin, cos)

e = Heun(u0 = 1, v0 = 0, n = 8)
e.generate_graph_with_exact(sin, cos)

e = Heun(u0 = 1, v0 = 0, n = 25)
e.generate_graph_with_exact(sin, cos)

e = Heun(u0 = 1, v0 = 0, n = 100)
Exemplo n.º 28
0
            nodeCount = sys.argv[nodeIndex + 1]

            edgeIndex = sys.argv.index("-e")
            edgeCount = sys.argv[edgeIndex + 1]

            t = timeit.Timer("Generator().generate_half_euler_graph("+nodeCount+","+edgeCount+")",
                            "from Generator import Generator")
            times = t.repeat(5,10)
            print avg(times)

        elif s == "-i":
            dFile = sys.argv.index("-i")
            fileTemp = sys.argv[dFile+1]
            graphFile = GraphFile(fileTemp)
            (G, pos, nodesNumber, edgesNumber) = graphFile.load()
            euler = Euler()
            (info,odds) = euler.checkGraph(G)
            print info
            print "Edges: "+str(nodesNumber)
            print "Nodes: "+str(edgesNumber)

        elif s == "-e":
            dFile = sys.argv.index("-e")
            fileTemp = sys.argv[dFile+1]
            graphFile = GraphFile(fileTemp)
            (G, pos, nodesNumber, edgesNumber) = graphFile.load()
            euler = Euler()
            path = euler.start(G)
            print path

        elif s == "-et":
Exemplo n.º 29
0
class GraphGui(QWidget):
    def __init__(self, G=None, pos=None, parent=None):
        QWidget.__init__(self, parent)
        self.scene = GraphGraphicsScene(G, pos, self)
        self.view = QGraphicsView(self.scene, self)
        self.button = QPushButton("Quit", self)
        self.nodeButton = QPushButton("Node", self)
        self.edgeButton = QPushButton("Edge", self)
        self.addButton = QPushButton("Add", self)
        self.deleteButton = QPushButton("Delete", self)
        self.printButton = QPushButton("Print", self)
        self.eulerButton = QPushButton("Euler", self)
        self.generateFullButton = QPushButton("Full", self)
        self.generateHalfButton = QPushButton("Half", self)
        self.infoButton = QPushButton("Info", self)
        # self.testButton = QPushButton('Test', self)
        self.nodesInputLabel = QLabel("Nodes", self)
        self.edgesInputLabel = QLabel("Edges", self)
        self.saveButton = QPushButton("Save", self)
        self.loadButton = QPushButton("Load", self)
        self.saveAsButton = QPushButton("SaveAs", self)
        self.bridgeButton = QPushButton("Bridge", self)
        self.stepSlider = QSlider(self)
        self.cursorLabelX = QLabel("X:", self)
        self.cursorLabelY = QLabel("Y:", self)
        self.nodeNumberLabel = QLabel("Nr:", self)
        self.fileLabel = QLabel("File:", self)
        self.nodeInfo = QLabel("N:", self)
        self.edgeInfo = QLabel("E:", self)
        self.eulerInfo = QLabel("None", self)
        # self.fileInput = QLineEdit(self)
        self.fileInput = QLabel("", self)
        self.euler = Euler()
        self.eulerStep = 0
        self.eulerPath = []

        validator = QIntValidator(0, 10000)

        self.nodesNumberInput = QLineEdit(self)
        self.nodesNumberInput.setValidator(validator)
        self.edgesNumberInput = QLineEdit(self)
        self.edgesNumberInput.setValidator(validator)

        self.cursorLabelX.setMinimumSize(150, 25)
        self.cursorLabelY.setMinimumSize(150, 25)
        self.nodeNumberLabel.setMinimumSize(150, 25)

        self.labelsGroup = QVBoxLayout()
        self.labelsGroup.addWidget(self.cursorLabelX)
        self.labelsGroup.addWidget(self.cursorLabelY)
        self.labelsGroup.addWidget(self.nodeNumberLabel)

        HEIGHT = 50
        WIDTH = 50

        self.nodeButton.setFixedSize(HEIGHT, WIDTH)
        self.edgeButton.setFixedSize(HEIGHT, WIDTH)
        self.addButton.setFixedSize(HEIGHT, WIDTH)
        self.button.setFixedSize(HEIGHT, WIDTH)
        self.deleteButton.setFixedSize(HEIGHT, WIDTH)
        self.printButton.setFixedSize(HEIGHT, WIDTH)
        self.eulerButton.setFixedSize(HEIGHT, WIDTH)
        self.generateFullButton.setFixedSize(HEIGHT, WIDTH)
        self.generateHalfButton.setFixedSize(HEIGHT, WIDTH)
        self.saveButton.setFixedSize(HEIGHT, WIDTH)
        self.loadButton.setFixedSize(HEIGHT, WIDTH)
        self.saveAsButton.setFixedSize(HEIGHT, WIDTH)
        self.infoButton.setFixedSize(HEIGHT, WIDTH)
        self.bridgeButton.setFixedSize(HEIGHT, WIDTH)
        self.nodesNumberInput.setFixedSize(HEIGHT * 2, 28)
        self.edgesNumberInput.setFixedSize(HEIGHT * 2, 28)
        self.stepSlider.setFixedSize(HEIGHT * 2, 28)
        # self.testButton.setFixedSize(HEIGHT, WIDTH)

        self.disableSlider()
        self.stepSlider.setOrientation(Qt.Horizontal)
        horizontal_expanding_spacer1 = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.fileGroup = QHBoxLayout()
        self.fileGroup.addWidget(self.fileLabel)
        self.fileGroup.addWidget(self.fileInput)
        self.fileGroup.addItem(horizontal_expanding_spacer1)

        self.actionsButtonGroup = QHBoxLayout()
        self.actionsButtonGroup.addWidget(self.addButton)
        self.actionsButtonGroup.addWidget(self.deleteButton)
        self.actionsButtonGroup.addWidget(self.printButton)
        self.actionsButtonGroup.addWidget(self.eulerButton)
        self.actionsButtonGroup.addWidget(self.generateFullButton)
        self.actionsButtonGroup.addWidget(self.generateHalfButton)
        self.actionsButtonGroup.addWidget(self.saveButton)
        self.actionsButtonGroup.addWidget(self.loadButton)
        self.actionsButtonGroup.addWidget(self.saveAsButton)
        self.actionsButtonGroup.addWidget(self.infoButton)
        self.actionsButtonGroup.addWidget(self.bridgeButton)
        # self.actionsButtonGroup.addWidget(self.testButton)
        self.actionsButtonGroup.addWidget(self.button)

        self.topGroup = QVBoxLayout()
        self.topGroup.addItem(self.fileGroup)
        self.topGroup.addItem(self.actionsButtonGroup)

        horizontal_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.actionsButtonGroup.addItem(horizontal_expanding_spacer)
        self.actionsButtonGroup.addItem(self.labelsGroup)

        self.modeButtonGroup = QVBoxLayout()
        self.modeButtonGroup.addWidget(self.nodeButton)
        self.modeButtonGroup.addWidget(self.edgeButton)
        self.modeButtonGroup.addWidget(self.nodesInputLabel)
        self.modeButtonGroup.addWidget(self.nodesNumberInput)
        self.modeButtonGroup.addWidget(self.edgesInputLabel)
        self.modeButtonGroup.addWidget(self.edgesNumberInput)
        self.modeButtonGroup.addWidget(self.stepSlider)

        vertical_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)

        self.modeButtonGroup.addItem(vertical_expanding_spacer)

        self.infoGroup = QVBoxLayout()
        self.infoGroup.addWidget(self.edgeInfo)
        self.infoGroup.addWidget(self.nodeInfo)
        self.infoGroup.addWidget(self.eulerInfo)

        self.modeButtonGroup.addItem(self.infoGroup)

        self.button.clicked.connect(QCoreApplication.instance().quit)
        self.addButton.clicked.connect(self.add)
        self.deleteButton.clicked.connect(self.delete)
        self.nodeButton.clicked.connect(self.nodeButtonEvent)
        self.edgeButton.clicked.connect(self.edgeButtonEvent)
        self.printButton.clicked.connect(self.printButtonEvent)
        self.eulerButton.clicked.connect(self.findEulerPath)
        self.generateFullButton.clicked.connect(self.generateFull)
        self.generateHalfButton.clicked.connect(self.generateHalf)
        # self.testButton.clicked.connect(self.scene.changeColor)
        self.saveAsButton.clicked.connect(self.saveAsFile)
        self.saveButton.clicked.connect(self.saveFile)
        self.loadButton.clicked.connect(self.loadFile)
        self.scene.cursorPositionSignal.connect(self.setLabels)
        self.scene.nodeNumberSignal.connect(self.setLabelNumber)
        self.stepSlider.sliderMoved.connect(self.setEulerStep)
        self.bridgeButton.clicked.connect(self.findBridges)
        self.infoButton.clicked.connect(self.setInfo)

        self.view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        layoutH = QHBoxLayout()
        layoutH.addWidget(self.view)
        layoutH.addItem(self.modeButtonGroup)

        layoutV = QVBoxLayout()
        layoutV.addItem(self.topGroup)
        layoutV.addItem(layoutH)

        self.setLayout(layoutV)

        self.setWindowTitle("Example")

        self.scene.setSceneRect(0, 0, 1, 1)

        self.view.setMouseTracking(True)

        self.showMaximized()
        self.graphFile = GraphFile("file.txt")

    def findBridges(self):
        bridges = self.euler.find_bridges(self.scene.G)
        print bridges

    def generate(self, h_or_f):
        generator = Generator()
        nodesNumberStr = self.nodesNumberInput.text()
        edgesNumberStr = self.edgesNumberInput.text()

        if nodesNumberStr == "" or edgesNumberStr == "":
            return

        nodeNumber = int(nodesNumberStr)
        edgesNumber = int(edgesNumberStr)

        G = None
        if h_or_f == "FULL":
            G = generator.generate_full_euler_graph(nodeNumber, edgesNumber)
        elif h_or_f == "HALF":
            G = generator.generate_half_euler_graph(nodeNumber, edgesNumber)

        if G is not None:
            self.scene.clear()

            self.scene.drawGraph(G)

        self.setInfo()

    def setInfo(self):
        self.edgeInfo.setText("E: " + str(len(self.scene.G.edges())))
        self.nodeInfo.setText("N: " + str(len(self.scene.G.nodes())))

        info, odds = self.euler.checkGraph(self.scene.G)
        self.eulerInfo.setText(info)

    def generateHalf(self):
        self.generate("HALF")

    def generateFull(self):
        self.generate("FULL")

    def add(self):
        self.scene.add()
        self.setInfo()

    def delete(self):
        self.scene.delete()
        self.setInfo()

    def findEulerPath(self):
        eulerPath = self.euler.start(self.scene.getGraph())
        print eulerPath

        if eulerPath is not None and len(eulerPath) > 0:
            self.enableSlider(len(eulerPath))
            self.eulerPath = eulerPath

    def setEulerStep(self, stepNum):

        self.scene.setColorForAllEdges(QColor.fromRgb(0, 0, 0))
        if stepNum > 0:
            for i in range(stepNum):
                node1 = self.eulerPath[i]
                node2 = self.eulerPath[i + 1]
                self.scene.setColorForEdge(node1, node2, QColor.fromRgb(0, 255, 0))

    def resizeEvent(self, event):
        w = self.view.width() - 10
        h = self.view.height() - 10

        transform = QTransform.fromScale(w, h)

        self.view.setTransform(transform)
        QWidget.resizeEvent(self, event)

    def enableSlider(self, maximum):
        self.stepSlider.setEnabled(True)
        self.stepSlider.setMinimum(0)
        self.stepSlider.setMaximum(maximum - 1)

    def disableSlider(self):
        self.stepSlider.setDisabled(False)

    def setLabels(self, x, y):
        self.cursorLabelX.setText("X:" + str(x))
        self.cursorLabelY.setText("Y:" + str(y))

    def setLabelNumber(self, number):
        self.nodeNumberLabel.setText("Nr:" + str(number))

    def nodeButtonEvent(self):
        if self.scene.getMode() == "None":
            self.scene.changeMode("Node")
            self.nodeButton.setFlat(True)
        elif self.scene.getMode() == "Node":
            self.nodeButton.setFlat(False)
            self.scene.changeMode("None")
        elif self.scene.getMode() == "Edge":
            self.edgeButton.setFlat(False)
            self.scene.changeMode("Node")
            self.nodeButton.setFlat(True)

    def edgeButtonEvent(self):
        if self.scene.getMode() == "None":
            self.scene.changeMode("Edge")
            self.edgeButton.setFlat(True)
        elif self.scene.getMode() == "Edge":
            self.scene.changeMode("None")
            self.edgeButton.setFlat(False)
        elif self.scene.getMode() == "Node":
            self.scene.changeMode("Edge")
            self.nodeButton.setFlat(False)
            self.edgeButton.setFlat(True)

    def printButtonEvent(self):
        print self.scene.G.nodes()
        print self.scene.G.edges()

    def saveFile(self):
        if self.graphFile.path != "":
            self.graphFile.save(self.scene.G, self.scene.getPos())
        else:
            self.saveAsFile()

    def saveAsFile(self):
        path = QFileDialog.getSaveFileName(self, "Open Graph", ".", "Text files (*.txt)")
        self.setFilePath(path)
        self.graphFile.save(self.scene.G, self.scene.getPos())

    def loadFile(self):
        path = QFileDialog.getOpenFileName(self, "Open Graph", ".", "Text files (*.txt)")
        self.setFilePath(path)
        (G, pos, n, n) = self.graphFile.load()
        self.scene.clear()

        self.scene.drawGraph(G, pos)

        self.setInfo()

    def setFilePath(self, path):
        self.graphFile.path = path
        self.fileInput.setText(path)
from Euler import Euler
import matplotlib.pyplot as plt
import numpy as np

# équation y'=2ty-2t**2+1 avec y(0)=0
f = lambda y, t: 2 * t * y - 2 * t**2 + 1

# solution approchée
T = np.linspace(0, 2, 10)
Y = Euler(f, 0, T)
plt.plot(T, Y, 'r-', label=u"approchée")

# solution exacte
phi = lambda t: t
plt.plot(T, phi(np.array(T)), 'bo', label="exacte")

plt.title("$y'=3y+2t-3t^2 \qquad y(0)=0$")

# trace les axes
xx, XX = -.25, 2.25
yy, YY = -1, 2
plt.plot([0, 0], [yy, YY], 'k-', [xx, XX], [0, 0], 'k-')
plt.xlabel(u"Avec la méthode d'Euler", fontsize=20)
plt.axes().set_aspect('equal')

# trace le champ de vecteurs
dx, dy = .3, .3
L = .05
x, y = xx + dx, yy
while y < YY:
    u = L / np.sqrt(1 + f(y, x)**2)
Exemplo n.º 31
0
    def __init__(self, G=None, pos=None, parent=None):
        QWidget.__init__(self, parent)
        self.scene = GraphGraphicsScene(G, pos, self)
        self.view = QGraphicsView(self.scene, self)
        self.button = QPushButton("Quit", self)
        self.nodeButton = QPushButton("Node", self)
        self.edgeButton = QPushButton("Edge", self)
        self.addButton = QPushButton("Add", self)
        self.deleteButton = QPushButton("Delete", self)
        self.printButton = QPushButton("Print", self)
        self.eulerButton = QPushButton("Euler", self)
        self.generateFullButton = QPushButton("Full", self)
        self.generateHalfButton = QPushButton("Half", self)
        self.infoButton = QPushButton("Info", self)
        # self.testButton = QPushButton('Test', self)
        self.nodesInputLabel = QLabel("Nodes", self)
        self.edgesInputLabel = QLabel("Edges", self)
        self.saveButton = QPushButton("Save", self)
        self.loadButton = QPushButton("Load", self)
        self.saveAsButton = QPushButton("SaveAs", self)
        self.bridgeButton = QPushButton("Bridge", self)
        self.stepSlider = QSlider(self)
        self.cursorLabelX = QLabel("X:", self)
        self.cursorLabelY = QLabel("Y:", self)
        self.nodeNumberLabel = QLabel("Nr:", self)
        self.fileLabel = QLabel("File:", self)
        self.nodeInfo = QLabel("N:", self)
        self.edgeInfo = QLabel("E:", self)
        self.eulerInfo = QLabel("None", self)
        # self.fileInput = QLineEdit(self)
        self.fileInput = QLabel("", self)
        self.euler = Euler()
        self.eulerStep = 0
        self.eulerPath = []

        validator = QIntValidator(0, 10000)

        self.nodesNumberInput = QLineEdit(self)
        self.nodesNumberInput.setValidator(validator)
        self.edgesNumberInput = QLineEdit(self)
        self.edgesNumberInput.setValidator(validator)

        self.cursorLabelX.setMinimumSize(150, 25)
        self.cursorLabelY.setMinimumSize(150, 25)
        self.nodeNumberLabel.setMinimumSize(150, 25)

        self.labelsGroup = QVBoxLayout()
        self.labelsGroup.addWidget(self.cursorLabelX)
        self.labelsGroup.addWidget(self.cursorLabelY)
        self.labelsGroup.addWidget(self.nodeNumberLabel)

        HEIGHT = 50
        WIDTH = 50

        self.nodeButton.setFixedSize(HEIGHT, WIDTH)
        self.edgeButton.setFixedSize(HEIGHT, WIDTH)
        self.addButton.setFixedSize(HEIGHT, WIDTH)
        self.button.setFixedSize(HEIGHT, WIDTH)
        self.deleteButton.setFixedSize(HEIGHT, WIDTH)
        self.printButton.setFixedSize(HEIGHT, WIDTH)
        self.eulerButton.setFixedSize(HEIGHT, WIDTH)
        self.generateFullButton.setFixedSize(HEIGHT, WIDTH)
        self.generateHalfButton.setFixedSize(HEIGHT, WIDTH)
        self.saveButton.setFixedSize(HEIGHT, WIDTH)
        self.loadButton.setFixedSize(HEIGHT, WIDTH)
        self.saveAsButton.setFixedSize(HEIGHT, WIDTH)
        self.infoButton.setFixedSize(HEIGHT, WIDTH)
        self.bridgeButton.setFixedSize(HEIGHT, WIDTH)
        self.nodesNumberInput.setFixedSize(HEIGHT * 2, 28)
        self.edgesNumberInput.setFixedSize(HEIGHT * 2, 28)
        self.stepSlider.setFixedSize(HEIGHT * 2, 28)
        # self.testButton.setFixedSize(HEIGHT, WIDTH)

        self.disableSlider()
        self.stepSlider.setOrientation(Qt.Horizontal)
        horizontal_expanding_spacer1 = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.fileGroup = QHBoxLayout()
        self.fileGroup.addWidget(self.fileLabel)
        self.fileGroup.addWidget(self.fileInput)
        self.fileGroup.addItem(horizontal_expanding_spacer1)

        self.actionsButtonGroup = QHBoxLayout()
        self.actionsButtonGroup.addWidget(self.addButton)
        self.actionsButtonGroup.addWidget(self.deleteButton)
        self.actionsButtonGroup.addWidget(self.printButton)
        self.actionsButtonGroup.addWidget(self.eulerButton)
        self.actionsButtonGroup.addWidget(self.generateFullButton)
        self.actionsButtonGroup.addWidget(self.generateHalfButton)
        self.actionsButtonGroup.addWidget(self.saveButton)
        self.actionsButtonGroup.addWidget(self.loadButton)
        self.actionsButtonGroup.addWidget(self.saveAsButton)
        self.actionsButtonGroup.addWidget(self.infoButton)
        self.actionsButtonGroup.addWidget(self.bridgeButton)
        # self.actionsButtonGroup.addWidget(self.testButton)
        self.actionsButtonGroup.addWidget(self.button)

        self.topGroup = QVBoxLayout()
        self.topGroup.addItem(self.fileGroup)
        self.topGroup.addItem(self.actionsButtonGroup)

        horizontal_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.actionsButtonGroup.addItem(horizontal_expanding_spacer)
        self.actionsButtonGroup.addItem(self.labelsGroup)

        self.modeButtonGroup = QVBoxLayout()
        self.modeButtonGroup.addWidget(self.nodeButton)
        self.modeButtonGroup.addWidget(self.edgeButton)
        self.modeButtonGroup.addWidget(self.nodesInputLabel)
        self.modeButtonGroup.addWidget(self.nodesNumberInput)
        self.modeButtonGroup.addWidget(self.edgesInputLabel)
        self.modeButtonGroup.addWidget(self.edgesNumberInput)
        self.modeButtonGroup.addWidget(self.stepSlider)

        vertical_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)

        self.modeButtonGroup.addItem(vertical_expanding_spacer)

        self.infoGroup = QVBoxLayout()
        self.infoGroup.addWidget(self.edgeInfo)
        self.infoGroup.addWidget(self.nodeInfo)
        self.infoGroup.addWidget(self.eulerInfo)

        self.modeButtonGroup.addItem(self.infoGroup)

        self.button.clicked.connect(QCoreApplication.instance().quit)
        self.addButton.clicked.connect(self.add)
        self.deleteButton.clicked.connect(self.delete)
        self.nodeButton.clicked.connect(self.nodeButtonEvent)
        self.edgeButton.clicked.connect(self.edgeButtonEvent)
        self.printButton.clicked.connect(self.printButtonEvent)
        self.eulerButton.clicked.connect(self.findEulerPath)
        self.generateFullButton.clicked.connect(self.generateFull)
        self.generateHalfButton.clicked.connect(self.generateHalf)
        # self.testButton.clicked.connect(self.scene.changeColor)
        self.saveAsButton.clicked.connect(self.saveAsFile)
        self.saveButton.clicked.connect(self.saveFile)
        self.loadButton.clicked.connect(self.loadFile)
        self.scene.cursorPositionSignal.connect(self.setLabels)
        self.scene.nodeNumberSignal.connect(self.setLabelNumber)
        self.stepSlider.sliderMoved.connect(self.setEulerStep)
        self.bridgeButton.clicked.connect(self.findBridges)
        self.infoButton.clicked.connect(self.setInfo)

        self.view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        layoutH = QHBoxLayout()
        layoutH.addWidget(self.view)
        layoutH.addItem(self.modeButtonGroup)

        layoutV = QVBoxLayout()
        layoutV.addItem(self.topGroup)
        layoutV.addItem(layoutH)

        self.setLayout(layoutV)

        self.setWindowTitle("Example")

        self.scene.setSceneRect(0, 0, 1, 1)

        self.view.setMouseTracking(True)

        self.showMaximized()
        self.graphFile = GraphFile("file.txt")
Exemplo n.º 32
0
def main():
    #out = open('out_put.txt', 'a')
    #out.close()

    with open('input.txt') as arquivo:
        for line in arquivo:
            in_put = line
            in_put = in_put.split()

            if (in_put[0] == "euler"):
                metodo = Euler(in_put)
                print("\n")

            if (in_put[0] == "euler_inverso"):
                metodo = Euler_Inverso(in_put)
                print("\n")

            if (in_put[0] == "euler_aprimorado"):
                metodo = Euler_Aprimorado(in_put)
                print("\n")

            if (in_put[0] == "runge_kutta"):
                metodo = Runge_Kutta(in_put)
                print("\n")

            if (in_put[0] == "adam_bashforth"):
                metodo = Bashforth(in_put)
                print("\n")

            if (in_put[0] == "adam_bashforth_by_euler"):
                metodo = Bashforth_Euler(in_put)
                print("\n")

            if (in_put[0] == "adam_bashforth_by_euler_inverso"):
                metodo = Bashforth_Euler_Inverso(in_put)
                print("\n")

            if (in_put[0] == "adam_bashforth_by_euler_aprimorado"):
                metodo = Bashforth_Euler_Aprimorado(in_put)
                print("\n")

            if (in_put[0] == "adam_bashforth_by_runge_kutta"):
                metodo = Bashforth_RungeKutta(in_put)
                print("\n")

            if (in_put[0] == "adam_multon"):
                metodo = Multon(in_put)
                print("\n")

            if (in_put[0] == "adam_multon_by_euler"):
                metodo = Multon_Euler(in_put)
                print("\n")

            if (in_put[0] == "adam_multon_by_euler_inverso"):
                metodo = Multon_Euler_Inverso(in_put)
                print("\n")

            if (in_put[0] == "adam_multon_by_euler_aprimorado"):
                metodo = Multon_Euler_Aprimorado(in_put)
                print("\n")

            if (in_put[0] == "adam_multon_by_runge_kutta"):
                metodo = Multon_RungeKutta(in_put)
                print("\n")

            metodo.method()
    arquivo.close()
Exemplo n.º 33
0
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as spig
from Euler import Euler

#f=lambda y,t: t+np.sin(y)**2
f = lambda y, t: 3 * y + 2 * t - 3 * t**2

T = np.linspace(0, 2, 20)
y0 = 0

#par la méthode d'Euler
Y = Euler(f, y0, T)
plt.plot(T, Y, 'r-', label=u"par Euler")

# par la fonction odeint
Z = spig.odeint(f, y0, T)
plt.plot(T, Z, 'g-', label=u"par odeint")

# solutino exacte
phi = lambda t: t**2
plt.plot(T, phi(np.array(T)), 'bo', label="exacte")

# trace les axes
xx, XX = -.25, 2.25
yy, YY = -.25, 4
plt.plot([0, 0], [yy, YY], 'k-', [xx, XX], [0, 0], 'k-')
plt.axes().set_aspect('equal')
Exemplo n.º 34
0
# coding:utf-8
from Euler import Euler
edu = Euler()

ts0 = edu.time()

from math import sqrt
import time
def divi(number):
    sumnum=1
    for x in range(2,int(sqrt(number))+1):
        if number%x==0:
            sumnum+=(x+number/x)
            if x==number/x:
                sumnum-=x
    return sumnum

start=time.time()
list=[]

for x in range(1,10001):
    a=divi(x)
    b=divi(a)
    if b==x and a!=b:
        list.append(x)

count=0
for x in list:
    count+=x

print list
Exemplo n.º 35
0
# coding:utf-8
import sys
from Euler import Euler
edu = Euler()

ts0 = edu.time()

def p009():
    for x in range(1,998):
        for y in range(1,998):
            z=1000-x-y
            if z<0:
                break
            if x**2+y**2==z**2:
                return '%d %d %d' % (x,y,z)
            
print p009()

            
print edu.time()-ts0