Example #1
0
 def __init__(self, parent):
     position = list(parent.position())
     velocity = list(parent.velocity)
     position[0] += sin(parent.direction) * parent.radius() * 3
     position[1] += cos(parent.direction) * parent.radius() * 3
     velocity[0] += sin(parent.direction) * parent.bullet_velocity
     velocity[1] += cos(parent.direction) * parent.bullet_velocity
     Mass.__init__(self, tuple(position), parent.bullet_mass, tuple(velocity), MAX_DENSITY, parent.arena)
     Agent.__init__(self)
     self.age = 0
Example #2
0
 def __init__(self, position, mass, steer_power, thrust_power, arena):
     Mass.__init__(self, position, mass, [0, 0], 1, arena)
     Agent.__init__(self)
     self.direction = 0
     self.omega = 0
     self.decelerating, self.accelerating = False, False
     self.steer_power = steer_power
     self.thrust_power = thrust_power
     self.bullet_velocity = 50
     self.bullet_mass = 10
     self.health = 1
Example #3
0
def isotonic_experiment(muscle_stimulation, loads,
                        time_param=TimeParameters()):

    # Muscle
    muscle_parameters = MuscleParameters()
    muscle = Muscle(muscle_parameters)

    # Initial conditions
    x0 = [0] * StatesIsotonic.NB_STATES.value
    x0[StatesIsotonic.STIMULATION.value] = 0.
    x0[StatesIsotonic.L_CE.value] = muscle.L_OPT
    x0[StatesIsotonic.LOAD_POS.value] = muscle.L_OPT + muscle.L_SLACK
    x0[StatesIsotonic.LOAD_SPEED.value] = 0.

    # Containers
    v_ce = []
    tendon_force = []

    # Integration
    pylog.info("Running the experiments (this might take a while)...")
    for load in loads:

        # New load definition
        mass_parameters = MassParameters()
        mass_parameters.mass = load
        mass = Mass(mass_parameters)

        # System definition
        sys = IsotonicMuscleSystem()
        sys.add_muscle(muscle)
        sys.add_mass(mass)

        result = sys.integrate(x0=x0,
                               time=time_param.times,
                               time_step=time_param.t_step,
                               time_stabilize=time_param.t_stabilize,
                               stimulation=muscle_stimulation,
                               load=load)

        # Result processing
        if result.l_mtc[-1] > x0[StatesIsotonic.LOAD_POS.value]:
            # Extension
            index = result.v_ce.argmax()
            v_ce.append(result.v_ce.max())
            tendon_force.append(result.tendon_force[index])
        else:
            # Contraction
            index = result.v_ce.argmin()
            v_ce.append(result.v_ce.min())
            tendon_force.append(result.tendon_force[index])

    return v_ce, tendon_force
Example #4
0
    def initalizeBodies(self,config):
        level=config.levels[0]
        for i in range(1,len(config.colors)):
            surfFeat=config.featureDict[config.featureTypes[i]]

            self.inactiveMassList.append(
                Mass(i,level["pos"][i],level["radii"][i],config.colors[i],config.secondColors[i],surfFeat,level["vels"][i])
            )
        plrSurfFeat=config.featureDict[config.featureTypes[0]]
        plr=Player(config,0,level["pos"][0],level["radii"][0],config.colors[0],config.secondColors[0],plrSurfFeat,level["vels"][0])
        self.inactiveMassList.append(plr)
        self.totalMasses=len(self.inactiveMassList)
        self.plr=plr
Example #5
0
    def handle_shoot(self):
        # You can only shoot if you are a single cell
        if len(self.cells) > 1:
            return

        if self.get_mass() < conf.MIN_MASS_TO_SHOOT:
            return

        # Must be moving in a direction in order to shoot
        if self.angle is None:
            return

        cell = self.cells[0]
        cell.mass = cell.mass - conf.MASS_MASS

        (mass_x, mass_y) = cell.get_pos()
        mass = Mass(mass_x, mass_y, self.color, self.angle, cell.radius)
        self.game.add_mass(mass)
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evaluate for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 1.25
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    # Set max_vce
    max_vce = []

    # ---------------------------------------------
    # Small load experiment
    # ---------------------------------------------
    load_table_small = [5, 10, 20, 50, 100]

    # Begin plotting
    plt.figure('Isotonic muscle experiment - load [10, 200] [N]')
    max_vce_small = ex1d_for(sys, x0, time, time_step, time_stabilize,
                             muscle_stimulation, load_table_small, False)

    plt.title('Isotonic muscle experiment - load [5, 140] [N]')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractile velocity [m/s]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # Big load experiment
    # ---------------------------------------------
    load_table_big = [150, 200, 220, 250, 500, 1000, 1500]

    # Begin plotting
    plt.figure('Isotonic muscle experiment - load [150, 1500] [N]')
    max_vce += ex1d_for(sys, x0, time, time_step, time_stabilize,
                        muscle_stimulation, load_table_big, True)

    plt.title('Isotonic muscle experiment - load [150, 1500] [N]')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractile velocity [m/s]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # Plot velocity - tension relation
    # ---------------------------------------------
    load = np.arange(5, 2500, 200)
    (max_vce, active_force) = ex1d_for(sys, x0, time, time_step,
                                       time_stabilize, muscle_stimulation,
                                       load, False)

    fig = plt.figure('Velocity - Tension')
    ax = fig.add_subplot(111)

    # Plot comments and line at 0 value
    min_val = 0.0
    if min(map(abs, max_vce)) not in max_vce:
        min_val = -min(map(abs, max_vce))
    else:
        min_val = min(map(abs, max_vce))

    xy = (load[max_vce.index(min_val)], min_val)
    xytext = (load[max_vce.index(min_val)] + 50, min_val)
    ax.annotate('load = {:0.1f}'.format(152.2), xy=xy, xytext=xytext)

    plt.title('Velocity [m/s] - Tension [N]')
    plt.xlabel('Tension [N]')
    plt.ylabel('Velocity [m/s]')
    plt.grid()

    plt.plot(load, max_vce)
    plt.plot(load[max_vce.index(min_val)], min_val, 'o')
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.l_opt # To get the muscle optimal length

    # Evalute for a single load
    load = 250 / 9.81

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.0

    # Set the initial condition
    x0 = [0.0, sys.muscle.l_opt, sys.muscle.l_opt + sys.muscle.l_slack, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.4
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    # Run the integration
    result = sys.integrate(x0=x0,
                           time=time,
                           time_step=time_step,
                           time_stabilize=time_stabilize,
                           stimulation=muscle_stimulation,
                           load=load)

    # Plotting
    plt.figure('Isotonic muscle experiment')
    plt.plot(result.time, result.v_ce)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contracticle velocity [lopts/s]')
    plt.grid()

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1d
    pylog.info(
        "1d. relationship between muscle contractile velocity and external load"
    )

    load_start = 1
    load_stop = 501
    load_step = 10
    load_range = np.arange(load_start, load_stop, load_step)

    muscle_stimulation = 1.0

    vels = []
    tendon_forces = []
    active_forces = []
    passive_forces = []
    total_forces = []

    for temp_load in load_range:
        temp_result = sys.integrate(x0=x0,
                                    time=time,
                                    time_step=time_step,
                                    time_stabilize=time_stabilize,
                                    stimulation=muscle_stimulation,
                                    load=temp_load)

        temp_tendon_force = temp_result.tendon_force[-1]
        temp_active_force = temp_result.active_force[-1]
        temp_passive_force = temp_result.passive_force[-1]
        temp_total_force = temp_active_force + temp_passive_force

        tendon_forces = tendon_forces + [temp_tendon_force]
        active_forces = active_forces + [temp_active_force]
        passive_forces = passive_forces + [temp_passive_force]
        total_forces = total_forces + [temp_total_force]

        temp_l_mtu = temp_result.l_mtu[-1]

        if temp_l_mtu < sys.muscle.l_opt + sys.muscle.l_slack:
            vels = vels + [np.min(temp_result.v_ce)]
        else:
            vels = vels + [np.max(temp_result.v_ce)]

    plt.figure(
        '1d. Isotonic muscle experiment for tension and contractile velocities'
    )
    plt.plot(vels, tendon_forces)
    plt.plot(vels, load_range)
    plt.plot(vels, active_forces)
    plt.plot(vels, passive_forces)
    plt.plot(vels, total_forces)
    plt.title(
        'Isotonic muscle experiment for tension and contractile velocities')
    plt.xlabel('Muscle contracticle velocity [lopts/s]')
    plt.ylabel('Tension [N]')
    plt.legend(("Tendon Force", "Load", "Active Force", "Passive Force",
                "Total force"))
    plt.grid()
    plt.show()

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1f

    pylog.info(
        "1f. relationship between muscle contractile velocity and external load with different stimulations"
    )

    muscle_stimulations = np.arange(0, muscle_stimulation + 0.1, 0.1)

    load_start = 1
    load_stop = 501
    load_step = 10
    load_range = np.arange(load_start, load_stop, load_step)

    all_vels = []
    all_tendon_forces = []

    for temp_muscle_stimulation in muscle_stimulations:

        temp_vels = []
        temp_tendon_forces = []

        for temp_load in load_range:
            temp_result = sys.integrate(x0=x0,
                                        time=time,
                                        time_step=time_step,
                                        time_stabilize=time_stabilize,
                                        stimulation=temp_muscle_stimulation,
                                        load=temp_load)

            temp_tendon_force = temp_result.tendon_force[-1]
            temp_tendon_forces = temp_tendon_forces + [temp_tendon_force]

            temp_l_mtu = temp_result.l_mtu[-1]

            if temp_l_mtu < sys.muscle.l_opt + sys.muscle.l_slack:
                temp_vels = temp_vels + [np.min(temp_result.v_ce)]
            else:
                temp_vels = temp_vels + [np.max(temp_result.v_ce)]

        all_vels = all_vels + [temp_vels]
        all_tendon_forces = all_tendon_forces + [temp_tendon_forces]

    plt.figure(
        '1f. Isotonic muscle experiment for loads and contractile velocities with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_vels[i], load_range)
    plt.title(
        'Isotonic muscle experiment for loads and contractile velocities with different stimulations'
    )
    plt.xlabel('Muscle contracticle velocity [lopts/s]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure(
        '1f. Isotonic muscle experiment for tendon forces and contractile velocities with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_vels[i], all_tendon_forces[i])
    plt.title(
        'Isotonic muscle experiment for tendon forces and contractile velocities with different stimulations'
    )
    plt.xlabel('Muscle contracticle velocity [lopts/s]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()
Example #8
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single load
    load = 100.

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]

    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.5
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    loads = np.arange(20, 351, 10)

    velocities = []

    for index, load in enumerate(loads):

        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=muscle_stimulation,
                               load=load)

        if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK):
            velocities.append(np.max(result.v_ce))
            print('max')
        else:
            velocities.append(np.min(result.v_ce))
            print('min')

    #Muscle contracile Velocity - Tension (load) relationship

    plt.figure('Isotonic muscle experiment')
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Muscle Contractile Velocity [m/s]')
    plt.ylabel('Tension (load) [N]')
    plt.plot(velocities, loads)
    plt.grid()

    #For different stimulations 1.f

    muscle_stimulation = np.arange(0, 1.1, 0.2)
    plt.figure('Isotonic muscle exp with different stimulations')
    plt.title('Isotonic muscle experiment with different stimulations')

    for stim in muscle_stimulation:
        velocities = []
        for index, load in enumerate(loads):
            #    Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   time_stabilize=time_stabilize,
                                   stimulation=stim,
                                   load=load)

            if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK):
                velocities.append(np.max(result.v_ce))
            else:
                velocities.append(np.min(result.v_ce))
        plt.xlabel('Muscle Contractile Velocity [m/s]')
        plt.ylabel('Tension (load) [N]')
        plt.plot(velocities, loads)

    plt.legend(('0', '0.2', '0.4', '0.6', '0.8', '1.0'))
    plt.grid()
Example #9
0
def mass_convert():
	mass = Mass()

	while True:
		title()
		option = str(input('''
			[1] Kg a G
			[2] G a Kg
			[3] Kg a Lb
			[4] Lb a Kg
			[5] G a Onz
			[6] Onz a G
			[7] Kg a Tn

			[s]alir
			''')).lower()

		if option == '1':
			mass.kgAG()
		elif option == '2':
			mass.GaKg()
		elif option == '3':
			mass.KgaLb()
		elif option == '4':
			mass.LbaKg()
		elif option == '5':
			mass.GaOnz()
		elif option == '6':
			mass.OnaAG()
		elif option == '7':
			mass.kgATn()

		elif option == 's':
			break
		else:
			print('Ingreso un dato invalido')
from mass import Mass


def elastic_collision(A, B):
    Vaf = A.velocity - 2 * B.mass / (A.mass + B.mass) * (A.velocity -
                                                         B.velocity)
    Vbf = B.velocity - 2 * A.mass / (A.mass + B.mass) * (B.velocity -
                                                         A.velocity)
    A.velocity = Vaf
    B.velocity = Vbf


# Adjust masses here!
A = Mass(1, 5)
B = Mass(2, -3)
Pi = A.momentum() + B.momentum()
Ki = A.kinetic_energy() + B.kinetic_energy()

print "---[Before collision]---"
print "[Object A] %s" % A
print "[Object B] %s" % B
print "[Total] p=%f, K=%f" % (Pi, Ki)

elastic_collision(A, B)
Pf = A.momentum() + B.momentum()
Kf = A.kinetic_energy() + B.kinetic_energy()

print "---[After collision]---"
print "[Object A] %s" % A
print "[Object B] %s" % B
print "[Total] p=%f, K=%f" % (Pf, Kf)
Example #11
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single load
    #load = 15.

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.35
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    ####custom code#####

    load_range = np.arange(1, 361, 5)
    my_velocity = []
    plt.figure('Isotonic muscle experiment')
    for load in load_range:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=muscle_stimulation,
                               load=load)

        my_velocity.append(max(abs(result.v_ce)))

        i, = np.where(result.v_ce == my_velocity[-1])
        if i.shape == (0, ):  #checks for negative velocity
            my_velocity[-1] *= -1

        plt.plot(result.time, result.v_ce, label='Load: %s' % load)

    # Plotting

    #plt.plot(result.time, result.v_ce)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractilve velocity')
    plt.grid()

    plt.figure('Isotonic Experiment')
    plt.plot(load_range, my_velocity)
    plt.xlabel('Load[Kg]')
    plt.ylabel('Maximal Muscle Contractile Velocity[m/s]')
    plt.grid()
Example #12
0
white = 255, 255, 255

screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

masses = []

preset = "lagrange"

if preset == "gas":
    XPAD = 200
    YPAD = 200
    MINMAX = 200
    for x in range(0, int(width / XPAD)):
        for y in range(0, int(height / YPAD)):
            masses.append(Mass(np.array([XPAD / 2 + x * XPAD, YPAD / 2 + y * YPAD]),\
                np.array([r.uniform(-MINMAX, MINMAX), r.uniform(-MINMAX, MINMAX)]), 10))

elif preset == "three":
    masses.append(Mass(np.array([500.0, 300.0]), np.array([0.0, 0.0]), 20))
    masses.append(Mass(np.array([630.0, 300.0]), np.array([0.0, 0.0]), 20))
    masses.append(Mass(np.array([600.0, 400.0]), np.array([0.0, 0.0]), 20))
elif preset == "lagrange":
    masses.append(Mass(np.array([367.0, 456.0]), np.array([39.5, -148.3]), 1))
    masses.append(Mass(np.array([500.0, 350.0]), np.array([150.0, 0.0]), 10))
    masses.append(Mass(np.array([500.0, 500.0]), np.array([0.0, 0.0]), 50))
elif preset == "quad":
    SPEED = 122
    masses.append(Mass(np.array([500.0, 300.0]), np.array([-SPEED, 0.0]), 50))
    masses.append(Mass(np.array([300.0, 500.0]), np.array([0.0, SPEED]), 50))
    masses.append(Mass(np.array([500.0, 700.0]), np.array([SPEED, 0.0]), 50))
    masses.append(Mass(np.array([700.0, 500.0]), np.array([0.0, -SPEED]), 50))
Example #13
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    #sys.muscle.L_OPT=0.05

    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.25
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal

    # Create a V_ce vector
    V_ce_1d = np.zeros(100)
    PF_ce_1d = np.zeros(100)
    AF_ce_1d = np.zeros(100)
    # Create load vector
    Load = np.linspace(1, 600, num=100)
    """1.d) velocity-tension analysis """

    for i in range(0, len(Load)):
        # Set the initial condition
        x0 = [
            muscle_stimulation, sys.muscle.L_OPT,
            sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0
        ]

        # Evalute for a single load
        load = Load[i]

        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=muscle_stimulation,
                               load=load)
        #print(sys.muscle.L_OPT+sys.muscle.L_SLACK)
        #print(result.l_mtc[-1]-(sys.muscle.L_OPT+sys.muscle.L_SLACK))

        if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK):
            V_ce_1d[i] = min(result.v_ce)

        else:

            V_ce_1d[i] = max(result.v_ce)

        PF_ce_1d[i] = result.passive_force[-1]
        AF_ce_1d[i] = result.active_force[-1]

        # Plotting
        plt.figure('Isotonic muscle experiment')
        plt.plot(result.time, result.v_ce)
        plt.title('Isotonic muscle experiment')
        plt.xlabel('Time [s]')
        plt.ylabel('Contractile element velocity')
        plt.grid()

    # Plot velocity versus tension
    plt.figure()
    plt.plot(V_ce_1d, Load)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Contractile element velocity')
    plt.ylabel('Load')
    plt.grid()
    plt.axvline(0, color='r', linestyle='--')

    # Plot velocity versus tension
    plt.figure()
    plt.plot(V_ce_1d, PF_ce_1d + AF_ce_1d)
    #plt.plot(V_ce_1d, PF_ce_1d)
    #plt.plot(V_ce_1d, AF_ce_1d, '--')
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Contractile element velocity')
    plt.ylabel('Total Force')
    plt.grid()
    #plt.legend(['total','passive', 'active'])
    plt.axvline(0, color='r', linestyle='--')
    """ 1.f) velocity-tension as a function of muscle activation """
    # Create solution vector
    #R_glob=np.zeros((5,50))
    # Create muscle activation vector
    dS = np.linspace(0.1, 1, num=5)
    # Create a V_ce vector
    V_ce = np.zeros((5, 100))

    PF_ce = np.zeros((5, 100))
    AF_ce = np.zeros((5, 100))
    for i in range(0, len(Load)):
        for j in range(0, len(dS)):

            # Evalute for a single load
            load = Load[i]

            # Evalute for a single muscle stimulation
            muscle_stimulation = dS[j]

            # Set the initial condition
            x0 = [
                muscle_stimulation, sys.muscle.L_OPT,
                sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0
            ]

            # Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   time_stabilize=time_stabilize,
                                   stimulation=muscle_stimulation,
                                   load=load)
            #R_glob[j,i]=result.tendon_force[len(result.tendon_force)-1]
            #print(sys.muscle.L_OPT+sys.muscle.L_SLACK)
            #print(result.l_mtc[-1]-(sys.muscle.L_OPT+sys.muscle.L_SLACK))

            if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK):
                V_ce[j, i] = min(result.v_ce)

            else:

                V_ce[j, i] = max(result.v_ce)

            PF_ce[j, i] = result.passive_force[-1]
            AF_ce[j, i] = result.active_force[-1]

            # # Plotting
            # plt.figure('Isotonic muscle experiment')
            # plt.plot(result.time, result.v_ce)
            # plt.title('Isotonic muscle experiment')
            # plt.xlabel('Time [s]')
            # plt.ylabel('Contractile element velocity')
            # plt.grid()

    # Plot velocity versus tension
    plt.figure()
    for i in range(0, 5):
        plt.plot(V_ce[i, :], PF_ce[i, :] + AF_ce[i, :])
        plt.title('Isotonic muscle experiment')
        plt.xlabel('Contractile element velocity')
        plt.ylabel('Force')
        plt.grid()
    plt.legend([
        'Stimulation = 0.1', 'Stimulation = 0.28', 'Stimulation = 0.46',
        'Stimulation = 0.64', 'Stimulation = 0.82', 'Stimulation = 1'
    ])
Example #14
0
class RocketSimulator(object):
    def __init__(self):
        self.T = 150
        self.dt = 0.01
        self.time = np.arange(0.0, self.T, self.dt)
        self.N = len(self.time)

    def initialize(self, design, launch_condition):
        """ 初期化 """
        self.name = design['name']
        self.m_af = design['m_af']
        self.I_af = design['I_af']
        self.CP = design['CP']
        self.CG_a = design['CG_a']
        self.d = design['d']
        self.area = np.pi * (self.d**2) / 4.0
        self.len_a = design['len_a']
        self.inertia_z0 = design['inertia_z0']
        self.inertia_zT = design['inertia_zT']
        self.engine = design['engine']
        self.me_total = design['me_total']
        self.me_prop = design['me_prop']
        self.len_e = design['len_e']
        self.d_e = design['d_e']

        self.p0 = np.array([0., 0., 0.])  # position(x, y, z)
        self.condition_name = launch_condition['name']
        self.theta0 = launch_condition['AngleOfFire']
        self.phi0 = launch_condition['azimuthal']
        self.launch_rod = launch_condition['launch_rod']
        self.v0 = np.array([0., 0., 0.])  # velocity(vx, vy, vz)
        self.ome0 = np.array([0., 0., 0.])
        self.density = launch_condition['density']
        self.wind_R = launch_condition['StandardWind']
        self.z_R = launch_condition['StandardHeight']
        self.beta = launch_condition['WindDirection']  # wind direction
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])
        self.qua_theta0 = np.array(
            [np.cos(0.5 * self.theta0),
             np.sin(0.5 * self.theta0), 0., 0.])  # x軸theta[rad]回転, 射角
        self.qua_phi0 = np.array(
            [np.cos(0.5 * self.phi0), 0., 0.,
             np.sin(0.5 * self.phi0)])  # z軸phi[rad]回転, 方位角
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])

        self.engine_data = np.loadtxt(self.engine)

        self.force = Force(self.area, self.engine_data, self.T, self.density)
        self.thrust = self.force.thrust()

        self.mass = Mass(self.m_af, self.I_af, self.CG_a, self.len_a,
                         self.inertia_z0, self.inertia_zT, self.me_total,
                         self.me_prop, self.len_e, self.d_e,
                         self.force.burn_time, self.T)
        self.M = self.mass.mass()
        self.Me = self.mass.me_t()
        self.Me_dot = self.mass.me_dot()
        self.CG = self.mass.CG()
        self.CG_dot = self.mass.CG_dot()
        self.Ie = self.mass.iexg()
        self.Inertia = self.mass.inertia()
        self.Inertia_z = self.mass.inertia_z()
        self.Inertia_dot = self.mass.inertia_dot()
        self.Inertia_z_dot = self.mass.inertia_z_dot()

        self.wind = Wind(self.z_R, self.wind_R)

    def deriv_mc(self, pi, vi, quai, omei, t, nw, nb):
        """ 運動方程式 """
        qt = Quaternion()
        # 機軸座標系の推力方向ベクトル
        r_Ta = np.array([0., 0., 1.0])
        # 慣性座標系重力加速度
        gra = np.array([0., 0., -g])
        # 機軸座標系の空力中心位置
        r = np.array([0., 0., self.CG(t) - self.CP])
        # 慣性座標系の推力方向ベクトル
        r_T = qt.rotation(r_Ta, qt.coquat(quai))
        r_T /= np.linalg.norm(r_T)
        # 慣性テンソル
        I = np.diag([self.Inertia(t), self.Inertia(t), self.Inertia_z(t)])
        # 慣性テンソルの時間微分
        I_dot = np.diag(
            [self.Inertia_dot(t),
             self.Inertia_dot(t),
             self.Inertia_z_dot(t)])
        # 慣性座標系対気速度
        beta = self.beta + nb
        v_air = (1 + nw) * self.wind.wind(pi[2]) * np.array(
            [np.cos(beta), np.sin(beta), 0.0]) - vi
        # 迎角
        alpha = aoa.aoa(qt.rotation(v_air, quai))
        # ランチロッド垂直抗力
        N = 0
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod and r_T[2] >= 0:
            Mg_ = self.M(t) * gra - np.dot(self.M(t) * gra, r_T) * r_T
            D_ = self.force.drag(alpha, v_air) - np.dot(
                self.force.drag(alpha, v_air), r_T) * r_T
            N = -Mg_ - D_
        # 慣性座標系加速度
        v_dot = gra + (self.thrust(t) * r_T + self.force.drag(alpha, v_air) +
                       N) / self.M(t)
        # クォータニオンの導関数
        qua_dot = qt.qua_dot(omei, quai)
        # 機軸座標系角加速度
        ome_dot = np.linalg.solve(
            I, -np.cross(r, qt.rotation(self.force.drag(alpha, v_air), quai)) -
            np.dot(I_dot, omei) - np.cross(omei, np.dot(I, omei)))
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod:
            # ランチロッド進行中は姿勢が一定なので角加速度0とする
            ome_dot = np.array([0., 0., 0.])

        return vi, v_dot, qua_dot, ome_dot

    def simulate_mc(self, sd_w=0.1, sd_b=0.1):
        noise_w = np.random.randn(self.N) * sd_w
        noise_b = np.random.randn(self.N) * sd_b
        """ 数値計算 """
        qt = Quaternion()
        p = np.empty((self.N + 1, 3))
        v = np.empty((self.N + 1, 3))
        qua = np.empty((self.N + 1, 4))
        ome = np.empty((self.N + 1, 3))
        p[0] = self.p0
        v[0] = self.v0
        qua[0] = qt.product(self.qua_phi0, self.qua_theta0)
        ome[0] = self.ome0
        count = 0

        for (i, t) in enumerate(self.time):
            # Euler method
            p_dot, v_dot, qua_dot, ome_dot = self.deriv_mc(
                p[i], v[i], qua[i], ome[i], t, noise_w[i], noise_b[i])

            # if np.isnan(qua_dot).any() or np.isinf(qua_dot).any() or np.isnan(ome_dot).any() or np.isinf(ome_dot).any():
            #     count = i
            #     break

            p[i + 1] = p[i] + p_dot * self.dt
            v[i + 1] = v[i] + v_dot * self.dt
            qua[i + 1] = qua[i] + qua_dot * self.dt
            ome[i + 1] = ome[i] + ome_dot * self.dt

            # vz<0かつz<0のとき計算を中断
            if v[i + 1][2] < 0 and p[i + 1][2] < 0:
                count = i + 1
                break

            qua[i + 1] /= np.linalg.norm(qua[i + 1])

            if t <= self.force.burn_time:
                p[i + 1][2] = max(0., p[i + 1][2])

            # vz<0かつz<0のとき計算を中断
            if v[i + 1][2] < 0 and p[i + 1][2] < 0:
                count = i + 1
                break

        self.p = p[:count + 1]
        self.v = v[:count + 1]
        self.qua = qua[:count + 1]
        self.ome = ome[:count + 1]

    def falling_range(self, n=1000, sd_w=0.1, sd_b=0.1):
        falling_area = []
        max_alttitude = []
        self.paths = []
        for i in range(n):
            self.simulate_mc(sd_w, sd_b)
            falling_area.append(self.p[-1])
            max_alttitude.append(self.p[:, 2].max())
            self.paths.append(self.p)
            if (i + 1) % 10 == 0:
                print(str((i + 1) / n * 100) + '%')
        self.paths = np.array(self.paths)
        return np.array(falling_area), np.array(max_alttitude)

    def output_kml(self, place):
        # 原点からの距離
        def dis2d(x, y):
            return pow(pow(x, 2) + pow(y, 2), 0.5)

        # y軸とベクトル(x, y)のなす角
        def ang2d(x, y):
            # y軸上
            if x == 0:
                if y >= 0:
                    return 0.0
                else:
                    return 180.0
            # x軸上
            if y == 0:
                if x >= 0:
                    return 90.0
                else:
                    return 270.0
            # 第1象限
            if x > 0 and y > 0:
                return np.arctan(x / y) * 180 / np.pi
            # 第2象限
            if x > 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第3象限
            if x < 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第4象限
            if x < 0 and y > 0:
                return 360.0 + np.arctan(x / y) * 180 / np.pi

        distance = [
            dis2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))
        ]

        angle = [ang2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))]

        coordinate0 = place[1]
        latitude = coordinate0[0]
        longitude = coordinate0[1]
        geod = pyproj.Geod(ellps='WGS84')
        newLong = []
        newLat = []
        invAngle = []
        for i in range(len(self.p)):
            nlon, nlat, nang = geod.fwd(longitude, latitude, angle[i],
                                        distance[i])
            newLong.append(nlon)
            newLat.append(nlat)
            invAngle.append(nang)

        kml = simplekml.Kml(open=1)
        cood = []
        for i in range(len(self.p)):
            cood.append((newLong[i], newLat[i], self.p[i, 2]))
        ls = kml.newlinestring(name=self.name + "'s Path")
        ls.coords = cood
        ls.style.linestyle.width = 3
        ls.style.linestyle.color = simplekml.Color.blue
        ls.altitudemode = simplekml.AltitudeMode.relativetoground
        ls.extrude = 0
        kml.save(self.name + "_" + place[0] + '_' + self.condition_name +
                 "_path.kml")
        print("Kml file for Google Earth was created.")
Example #15
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.l_opt # To get the muscle optimal length

    # Evalute for a single load
    load = 250/9.81

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.0

    # Set the initial condition
    x0 = [0.0, sys.muscle.l_opt,
          sys.muscle.l_opt + sys.muscle.l_slack, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.4
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)
    
    load = np.linspace(100/9.81,1700/9.81,50)
    Stimu = np.linspace(0,1,6)
    Vce = np.zeros((len(load),len(Stimu)))
    plt.figure('Isotonix Globale')
    for j in range(len(Stimu)):
        
   #     Vce = np.empty(len(load))
    #    Vcemax = np.empty(len(load))
    #    Vcemin = np.empty(len(load))
    
        for i in range(len(load)):

    # Run the integration
            result = sys.integrate(x0=x0,
                           time=time,
                           time_step=time_step,
                           time_stabilize=time_stabilize,
                           stimulation=Stimu[j],
                           load=load[i]
                           )
            print(result.l_mtu[-1])
            print(sys.muscle.l_opt + sys.muscle.l_slack)
            if (result.l_mtu[-1] > sys.muscle.l_opt + sys.muscle.l_slack):
                Vce[i,j]=(max(result.v_ce))
            else: Vce[i,j] = min(result.v_ce)
        
        Vce[:,j]
        plt.plot(Vce[:,j],load, label ="MS %s" %round(Stimu[j],1))
        plt.legend(loc = "upper left")
        plt.xlabel('Vitesse max [m/s]')
        plt.ylabel('Load [kg]')






    # Plotting
    plt.figure('Isotonic muscle experiment')
    #plt.plot(result.time,
    #         result.v_ce)
    plt.plot(Vce,load)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Vitesse max [m/s]')
    plt.ylabel('Load [kg]')
    #plt.xlabel('Time [s]')
    #plt.ylabel('Muscle contracticle velocity [lopts/s]')
    plt.grid()

#MUSCLE-Force Velocity relationship : 
    plt.figure('Muscle Force-Velocity')
    plt.plot(result.v_ce,result.active_force, label ="Active Force")
    plt.plot(result.v_ce,result.active_force+result.passive_force, label = "Passive + Active")
    plt.plot(result.v_ce,result.passive_force, label = "Passive Force")
    plt.legend(loc = "upper left")
    plt.xlabel('Vitesse m')
    plt.ylabel('Force')
Example #16
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single load
    load = 100.

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT,
          sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.3
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    # Run the integration
    result = sys.integrate(x0=x0,
                           time=time,
                           time_step=time_step,
                           time_stabilize=time_stabilize,
                           stimulation=muscle_stimulation,
                           load=load)

    # Plotting
    plt.figure('Isotonic muscle experiment')
    plt.plot(result.time, result.v_ce)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractilve velocity')
    plt.grid()
    
    # Run 1.d
    load = np.arange(0,1000,20)
    plotVceLoad(load,[0.1,0.5,1])
Example #17
0
def exercise1d():
    """ Exercise 1d
    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Velocity-tension curve

    # Evalute for various loads
    load_min = 1
    load_max = 301
    N_load = 50
    load_list = np.arange(load_min, load_max, (load_max - load_min) / N_load)

    # Evalute for Stimulation = 1.0
    stimulation = 1.0

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.3
    time_step = 0.001
    time_stabilize = 0.2
    time = np.arange(t_start, t_stop, time_step)

    max_velocity = np.zeros(N_load)
    tendonF = np.zeros(N_load)
    for ind_load, load in enumerate(load_list):
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=stimulation,
                               load=load)
        if (result.l_mtc[-1] < (sys.muscle.L_OPT + sys.muscle.L_SLACK)):
            max_velocity[ind_load] = np.max(-result.v_ce)
        else:
            max_velocity[ind_load] = np.min(-result.v_ce)
        tendonF[ind_load] = result.tendon_force[-1]

    # Plotting
    plt.figure('Isotonic Muscle Experiment 1d')
    v_min = np.amin(max_velocity)
    v_max = np.amax(max_velocity)
    plt.plot(max_velocity * 100 / -muscle.V_MAX, tendonF * 100 / muscle.F_MAX)
    plt.axvline(linestyle='--', color='r', linewidth=2)
    plt.text(v_min * 100 / -muscle.V_MAX, 20, r'lengthening', fontsize=14)
    plt.text(v_max * 100 / -muscle.V_MAX * 1 / 3,
             20,
             r'shortening',
             fontsize=14)
    plt.xlabel('Maximal velocity [% of $V_{max}$]')
    plt.ylabel('Tendon Force [% of $F_{max}$]')
    plt.title(
        'Velocity-tension curve for isotonic muscle experiment (Stimulation = 1.0)'
    )
    plt.grid()
Example #18
0
 def createMass(self, mass, charge, parent_mass, x, y, z):
     """
     inserts new Masses into the masses list
     """
     self.masses.insert(0, Mass(mass, charge, parent_mass, x, y, z))
Example #19
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)


    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single load
    load = 100.

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT,
          sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.3
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    # Run the integration
    load_array=np.arange(0.1,3000/sys.mass.parameters.g,5)
    vel_ce=[]
    act_force_int=[]

    stimulation=[0.,0.2,0.4,0.6,0.8,1.]
    colors=['r','g','b','c','m','y']
    for loadx in load_array:
        
        result = sys.integrate(x0=x0,
                           time=time,
                           time_step=time_step,
                           time_stabilize=time_stabilize,
                           stimulation=muscle_stimulation,
                           load=loadx)
        if (loadx==150.1 or loadx==155.1):
            plt.figure("Single Exp")
            plt.title("Result for a single experiment")
            plt.plot(result.time,result.v_ce*(-1))
            plt.xlabel("Time [s]")
            plt.ylabel("Velocity [m/s]")
            plt.legend(('Shortening','Lengthening'))
            pylog.info(result.l_mtc[-1])
            plt.grid()
            plt.show()
            
        if result.l_mtc[-1] < ( muscle_parameters.l_opt + muscle_parameters.l_slack):
            #pylog.info("min condition")
            vel_ce.append(min(result.v_ce[:])*(-1))
            act_force_int.append(max(result.active_force))
        else: 
            vel_ce.append(max(result.v_ce[:])*(-1))
            act_force_int.append(max(result.active_force))
           # pylog.info("max condition")
                
    
    plt.figure('Isotonic muscle experiment')
    plt.plot(vel_ce,load_array*mass_parameters.g)
    plt.plot(vel_ce,act_force_int)
    plt.title('Isotonic Muscle Experiment')
    plt.xlabel('Contractile Element Velocity [m/s]')
    plt.ylabel('Force[N]')
    plt.legend(("External Load","Internal Active Force"))
    plt.grid()
    plt.show()
    plt.figure('Varying Stimulation')
    leg=[] 
    for i,stim in enumerate(stimulation):
        pylog.info("Stim is {}".format(stim))
        vel_ce=[]
        act_force_int=[]
        for loadx in load_array:
            
            result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=stim,
                               load=loadx)
                
            if result.l_mtc[-1] < ( muscle_parameters.l_opt + muscle_parameters.l_slack):
                #pylog.info("min condition")
                vel_ce.append(min(result.v_ce[:])*(-1))
                act_force_int.append(max(result.active_force))
            else: 
                vel_ce.append(max(result.v_ce[:])*(-1))
                act_force_int.append(max(result.active_force))
        plt.plot(vel_ce,load_array*mass_parameters.g,colors[i],label='Stimulation={}'.format(stim))
        plt.plot(vel_ce,act_force_int,colors[i],linestyle=":",label='Stimulation={}'.format(stim))
        leg.append(("Load-velocity  plot with simulation={}".format(stim))) 
        leg.append(("Force-velocity with simulation={}".format(stim))) 

    plt.title('Varying Stimulation')
    plt.legend(leg)
    plt.xlabel('Contractile Element Velocity [m/s]')
    plt.ylabel('Force[N]')
    
    #("Stimulation = 0","Stimulation = 0.2","Stimulation = 0.4","Stimulation = 0.6","Stimulation = 0.8","Stimulation = 1")
    plt.grid()
def exercise1f():
    """ Exercise 1f

    What happens to the force-velocity relationship when the stimulation is varied
    between [0 - 1]?"""
    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    # Instantiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evaluate for a single load
    load = 100.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 1.25
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)

    # ---------------------------------------------
    # maximum force over stimulation
    # ---------------------------------------------

    # Evaluate for different muscle stimulation
    muscle_stimulation = np.arange(0, 1.1, 0.1)
    max_active_force = []
    max_passive_force = []
    max_sum_force = []

    # Begin plotting
    for s in muscle_stimulation:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=s,
                               load=load)

        if abs(min(result.active_force)) > max(result.active_force):
            max_active_force.append(min(result.active_force))
        else:
            max_active_force.append(max(result.active_force))

        if abs(min(result.passive_force)) > max(result.passive_force):
            max_passive_force.append(min(result.passive_force))
        else:
            max_passive_force.append(max(result.passive_force))

        max_sum_force.append(max_active_force[-1] + max_passive_force[-1])

    plt.figure('Isotonic muscle active force - stimulation [0, 1]')

    plt.plot(muscle_stimulation,
             max_active_force,
             label='maximum active force')
    plt.plot(muscle_stimulation,
             max_passive_force,
             label='maximum passive force')
    plt.plot(muscle_stimulation, max_sum_force, label='maximum sum force')

    plt.xlabel('Stimulation [-]')
    plt.ylabel('Muscle sum forces [N]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # force - velocity over stimulation
    # ---------------------------------------------
    muscle_stimulation = np.arange(0, 1.1, 0.1)

    # Begin plotting
    for s in muscle_stimulation:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=s,
                               load=load)

        plt.figure('Isotonic muscle active force - velocity')
        plt.plot(result.v_ce[200:-1],
                 result.active_force[200:-1],
                 label='stimulation {:0.1f}'.format(s))

        plt.figure('Isotonic muscle passive force - velocity')
        plt.plot(result.v_ce[200:-1],
                 result.passive_force[200:-1],
                 label='stimulation {:0.1f}'.format(s))

        plt.figure('Isotonic muscle sum forces - velocity')
        plt.plot(result.v_ce[200:-1],
                 result.active_force[200:-1] + result.passive_force[200:-1],
                 label='stimulation {:0.1f}'.format(s))

    plt.figure('Isotonic muscle active force - velocity')
    plt.xlabel('Velocity contractile element [m/s]')
    plt.ylabel('Active force [N]')
    plt.legend(loc='upper right')
    plt.grid()

    plt.figure('Isotonic muscle passive force - velocity')
    plt.xlabel('Velocity contractile element [m/s]')
    plt.ylabel('Passive force [N]')
    plt.legend(loc='upper right')
    plt.grid()

    plt.figure('Isotonic muscle sum forces - velocity')
    plt.xlabel('Velocity contractile element [m/s]')
    plt.ylabel('Sum forces [N]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # Plot velocity - tension relation
    # ---------------------------------------------
    muscle_stimulation = np.arange(0, 1.1, 0.25)
    load = np.arange(5, 1500, 20)
    plt.figure('Velocity - Tension')

    # Begin plotting
    for s in muscle_stimulation:
        (max_vce, active_force) = ex1d_for(sys, x0, time, time_step,
                                           time_stabilize, s, load, False)
        plt.plot(load, max_vce, label="stimulation {:0.1f}".format(s))

    plt.title('Velocity [m/s] - Load [N]')
    plt.xlabel('Load [N]')
    plt.ylabel('Velocity [m/s]')
    plt.legend(loc='lower right')
    plt.grid()
Example #21
0
    def initialize(self, design, launch_condition):
        """ 初期化 """
        self.name = design['name']
        self.m_af = design['m_af']
        self.I_af = design['I_af']
        self.CP = design['CP']
        self.CG_a = design['CG_a']
        self.d = design['d']
        self.area = np.pi * (self.d**2) / 4.0
        self.len_a = design['len_a']
        self.inertia_z0 = design['inertia_z0']
        self.inertia_zT = design['inertia_zT']
        self.engine = design['engine']
        self.me_total = design['me_total']
        self.me_prop = design['me_prop']
        self.len_e = design['len_e']
        self.d_e = design['d_e']

        self.p0 = np.array([0., 0., 0.])  # position(x, y, z)
        self.condition_name = launch_condition['name']
        self.theta0 = launch_condition['AngleOfFire']
        self.phi0 = launch_condition['azimuthal']
        self.launch_rod = launch_condition['launch_rod']
        self.v0 = np.array([0., 0., 0.])  # velocity(vx, vy, vz)
        self.ome0 = np.array([0., 0., 0.])
        self.density = launch_condition['density']
        self.wind_R = launch_condition['StandardWind']
        self.z_R = launch_condition['StandardHeight']
        self.beta = launch_condition['WindDirection']  # wind direction
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])
        self.qua_theta0 = np.array(
            [np.cos(0.5 * self.theta0),
             np.sin(0.5 * self.theta0), 0., 0.])  # x軸theta[rad]回転, 射角
        self.qua_phi0 = np.array(
            [np.cos(0.5 * self.phi0), 0., 0.,
             np.sin(0.5 * self.phi0)])  # z軸phi[rad]回転, 方位角
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])

        self.engine_data = np.loadtxt(self.engine)

        self.force = Force(self.area, self.engine_data, self.T, self.density)
        self.thrust = self.force.thrust()

        self.mass = Mass(self.m_af, self.I_af, self.CG_a, self.len_a,
                         self.inertia_z0, self.inertia_zT, self.me_total,
                         self.me_prop, self.len_e, self.d_e,
                         self.force.burn_time, self.T)
        self.M = self.mass.mass()
        self.Me = self.mass.me_t()
        self.Me_dot = self.mass.me_dot()
        self.CG = self.mass.CG()
        self.CG_dot = self.mass.CG_dot()
        self.Ie = self.mass.iexg()
        self.Inertia = self.mass.inertia()
        self.Inertia_z = self.mass.inertia_z()
        self.Inertia_dot = self.mass.inertia_dot()
        self.Inertia_z_dot = self.mass.inertia_z_dot()

        self.wind = Wind(self.z_R, self.wind_R)
Example #22
0
 def __init__(self, position, mass, velocity, density, arena):
     Mass.__init__(self, position, mass, velocity, density, arena)
     Agent.__init__(self)
     self.shape = [random() for i in xrange(24)]
     self.direction = 0
     self.omega = (random() - 0.5) * (pi/50)
Example #23
0
def exercise1f():
    """ Exercise 1f """

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # Add the mass to the system
    sys.add_mass(mass)

    # Velocity-tension curve

    # Evalute for various loads
    load_min = 1
    load_max = 501
    N_load = 50
    load_list = np.arange(load_min, load_max, (load_max - load_min) / N_load)

    # Evalute for various muscle stimulation
    N_stim = 4
    muscle_stimulation = np.round(np.arange(N_stim) / (N_stim - 1), 2)

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.3
    time_step = 0.001
    time_stabilize = 0.2
    time = np.arange(t_start, t_stop, time_step)

    max_velocity = np.zeros((N_stim, N_load))
    tendonF = np.zeros((N_stim, N_load))

    for i, stim in enumerate(muscle_stimulation):

        for ind_load, load in enumerate(load_list):
            # Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   time_stabilize=time_stabilize,
                                   stimulation=stim,
                                   load=load)
            if (result.l_mtc[-1] < (sys.muscle.L_OPT + sys.muscle.L_SLACK)):
                max_velocity[i, ind_load] = np.max(-result.v_ce)
            else:
                max_velocity[i, ind_load] = np.min(-result.v_ce)
            tendonF[i, ind_load] = result.tendon_force[-1]

    # Plotting
    plt.figure('Isotonic Muscle Experiment 1f')
    v_min = np.amin(max_velocity)
    v_max = np.amax(max_velocity)

    for i, stim in enumerate(muscle_stimulation):
        plt.plot(max_velocity[i, :] * 100 / -muscle.V_MAX,
                 tendonF[i, :] * 100 / muscle.F_MAX,
                 label='Tendon Force - Stimulation = {}'.format(stim))
        plt.xlim(v_min * 100 / -muscle.V_MAX, v_max * 100 / -muscle.V_MAX)
        plt.ylim(0, 200)

    plt.axvline(linestyle='--', color='r', linewidth=2)
    plt.text(v_min * 100 / -muscle.V_MAX * 2 / 3,
             170,
             r'lengthening',
             fontsize=16)
    plt.text(v_max * 100 / -muscle.V_MAX * 1 / 8,
             170,
             r'shortening',
             fontsize=16)
    plt.xlabel('Maximal velocity [% of $V_{max}$]')
    plt.ylabel('Tendon Force [% of $F_{max}$]')
    plt.title(
        'Velocity-tension curves for isotonic muscle experiment with various muscle stimulations'
    )
    plt.legend()
    plt.grid()
Example #24
0
def plotVceLoad(load,ms=[1.]):
    # Defination of muscles
    muscle_parameters = MuscleParameters()
    mass_parameters = MassParameters()
    # Create muscle object
    muscle = Muscle(muscle_parameters)
    # Create mass object
    mass = Mass(mass_parameters)
    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()
    # Add the muscle to the system
    sys.add_muscle(muscle)
    # Add the mass to the system
    sys.add_mass(mass)
    
    # Evalute for a single load
    #load = 100.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT,
          sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.3
    time_step = 0.001
    time_stabilize = 0.2

    time = np.arange(t_start, t_stop, time_step)
    
    plt.figure('Max Velocity-Tension curve')
    for s in ms:
        muscle_stimulation = s
        v = []
        for l in load:
            # Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   time_stabilize=time_stabilize,
                                   stimulation=muscle_stimulation,
                                   load=l)
            # Find the max or min speed achieved
            i = np.argmax(np.abs(result.v_ce))
            v.append(-result.v_ce[i])
            #if result[i].l_mtc < sys.muscle.L_OPT + sys.muscle.L_SLACK:
        
        for i in range(len(v)):
            if i >= 1 and v[i]*v[i-1] <=0:
                plt.plot(load[i],v[i],color='green', marker='x', linestyle='dashed',
                         linewidth=2, markersize=12)
        plt.plot(load, v,label='maximal speed\nMuscle stimulation: {}'.format(s))
        plt.legend()
        plt.title('Isotonic muscle experiment\nMax Velocity-Tension curve')
        plt.xlabel('load [kg]')
        plt.ylabel('CE speed [m/s]') 
        #axes = plt.gca()
        #axes.set_xlim([0.05,0.2])
        #axes.set_ylim([0,1700])
    plt.grid()
Example #25
0
class RocketSimulator(object):
    def __init__(self):
        self.T = 150
        self.dt = 0.01
        self.time = np.arange(0.0, self.T, self.dt)
        self.N = len(self.time)

    def initialize(self, design, launch_condition):
        """ 初期化 """
        self.name = design['name']
        self.m_af = design['m_af']
        self.I_af = design['I_af']
        self.CP = design['CP']
        self.CG_a = design['CG_a']
        self.d = design['d']
        self.area = np.pi * (self.d**2) / 4.0
        self.len_a = design['len_a']
        self.inertia_z0 = design['inertia_z0']
        self.inertia_zT = design['inertia_zT']
        self.engine = design['engine']
        self.me_total = design['me_total']
        self.me_prop = design['me_prop']
        self.len_e = design['len_e']
        self.d_e = design['d_e']

        self.p0 = np.array([0., 0., 0.])  # position(x, y, z)
        self.condition_name = launch_condition['name']
        self.theta0 = launch_condition['AngleOfFire']
        self.phi0 = launch_condition['azimuthal']
        self.launch_rod = launch_condition['launch_rod']
        self.v0 = np.array([0., 0., 0.])  # velocity(vx, vy, vz)
        self.ome0 = np.array([0., 0., 0.])
        self.density = launch_condition['density']
        self.wind_R = launch_condition['StandardWind']
        self.z_R = launch_condition['StandardHeight']
        self.beta = launch_condition['WindDirection']  # wind direction
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])
        self.qua_theta0 = np.array(
            [np.cos(0.5 * self.theta0),
             np.sin(0.5 * self.theta0), 0., 0.])  # x軸theta[rad]回転, 射角
        self.qua_phi0 = np.array(
            [np.cos(0.5 * self.phi0), 0., 0.,
             np.sin(0.5 * self.phi0)])  # z軸phi[rad]回転, 方位角
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])

        self.engine_data = np.loadtxt(self.engine)

        self.force = Force(self.area, self.engine_data, self.T, self.density)
        self.thrust = self.force.thrust()

        self.mass = Mass(self.m_af, self.I_af, self.CG_a, self.len_a,
                         self.inertia_z0, self.inertia_zT, self.me_total,
                         self.me_prop, self.len_e, self.d_e,
                         self.force.burn_time, self.T)
        self.M = self.mass.mass()
        self.Me = self.mass.me_t()
        self.Me_dot = self.mass.me_dot()
        self.CG = self.mass.CG()
        self.CG_dot = self.mass.CG_dot()
        self.Ie = self.mass.iexg()
        self.Inertia = self.mass.inertia()
        self.Inertia_z = self.mass.inertia_z()
        self.Inertia_dot = self.mass.inertia_dot()
        self.Inertia_z_dot = self.mass.inertia_z_dot()

        self.wind = Wind(self.z_R, self.wind_R)

    def deriv(self, pi, vi, quai, omei, t):
        """ 運動方程式 """
        qt = Quaternion()
        # 機軸座標系の推力方向ベクトル
        r_Ta = np.array([0., 0., 1.0])
        # 慣性座標系重力加速度
        gra = np.array([0., 0., -g])
        # 機軸座標系の空力中心位置
        r = np.array([0., 0., self.CG(t) - self.CP])
        # 慣性座標系の推力方向ベクトル
        r_T = qt.rotation(r_Ta, qt.coquat(quai))
        r_T /= np.linalg.norm(r_T)
        # 慣性テンソル
        I = np.diag([self.Inertia(t), self.Inertia(t), self.Inertia_z(t)])
        # 慣性テンソルの時間微分
        I_dot = np.diag(
            [self.Inertia_dot(t),
             self.Inertia_dot(t),
             self.Inertia_z_dot(t)])
        # 慣性座標系対気速度
        v_air = self.wind.wind(pi[2]) * self.wind_direction - vi
        # 迎角
        alpha = aoa.aoa(qt.rotation(v_air, quai))
        # ランチロッド垂直抗力
        N = 0
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod and r_T[2] >= 0:
            Mg_ = self.M(t) * gra - np.dot(self.M(t) * gra, r_T) * r_T
            D_ = self.force.drag(alpha, v_air) - np.dot(
                self.force.drag(alpha, v_air), r_T) * r_T
            N = -Mg_ - D_
        # 慣性座標系加速度
        v_dot = gra + (self.thrust(t) * r_T + self.force.drag(alpha, v_air) +
                       N) / self.M(t)
        # クォータニオンの導関数
        qua_dot = qt.qua_dot(omei, quai)
        # 機軸座標系角加速度
        ome_dot = np.linalg.solve(
            I, -np.cross(r, qt.rotation(self.force.drag(alpha, v_air), quai)) -
            np.dot(I_dot, omei) - np.cross(omei, np.dot(I, omei)))
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod:
            # ランチロッド進行中は姿勢が一定なので角加速度0とする
            ome_dot = np.array([0., 0., 0.])

        return vi, v_dot, qua_dot, ome_dot

    def simulate(self, method='RungeKutta', log=False):
        """ 数値計算 """
        qt = Quaternion()
        p = np.empty((self.N + 1, 3))
        v = np.empty((self.N + 1, 3))
        qua = np.empty((self.N + 1, 4))
        ome = np.empty((self.N + 1, 3))
        p[0] = self.p0
        v[0] = self.v0
        qua[0] = qt.product(self.qua_phi0, self.qua_theta0)
        ome[0] = self.ome0
        count = 0

        for (i, t) in enumerate(self.time):
            if method == 'RungeKutta':
                # Runge-Kutta method
                pk1, vk1, quak1, omek1 = self.deriv(p[i], v[i], qua[i], ome[i],
                                                    t)
                pk2, vk2, quak2, omek2 = self.deriv(
                    p[i] + pk1 * self.dt * 0.5, v[i] + vk1 * self.dt * 0.5,
                    qua[i] + quak1 * self.dt * 0.5,
                    ome[i] + omek1 * self.dt * 0.5, t + self.dt * 0.5)
                pk3, vk3, quak3, omek3 = self.deriv(
                    p[i] + pk2 * self.dt * 0.5, v[i] + vk2 * self.dt * 0.5,
                    qua[i] + quak2 * self.dt * 0.5,
                    ome[i] + omek2 * self.dt * 0.5, t + self.dt * 0.5)
                pk4, vk4, quak4, omek4 = self.deriv(p[i] + pk3 * self.dt,
                                                    v[i] + vk3 * self.dt,
                                                    qua[i] + quak3 * self.dt,
                                                    ome[i] + omek3 * self.dt,
                                                    t + self.dt)
                p[i + 1] = p[i] + (pk1 + 2 * pk2 + 2 * pk3 + pk4) * self.dt / 6
                v[i + 1] = v[i] + (vk1 + 2 * vk2 + 2 * vk3 + vk4) * self.dt / 6
                qua[i + 1] = qua[i] + (quak1 + 2 * quak2 + 2 * quak3 +
                                       quak4) * self.dt / 6
                ome[i + 1] = ome[i] + (omek1 + 2 * omek2 + 2 * omek3 +
                                       omek4) * self.dt / 6

            elif method == 'Euler':
                # Euler method
                p_dot, v_dot, qua_dot, ome_dot = self.deriv(
                    p[i], v[i], qua[i], ome[i], t)
                p[i + 1] = p[i] + p_dot * self.dt
                v[i + 1] = v[i] + v_dot * self.dt
                qua[i + 1] = qua[i] + qua_dot * self.dt
                ome[i + 1] = ome[i] + ome_dot * self.dt

            if t <= self.force.burn_time:
                p[i + 1][2] = max(0., p[i + 1][2])

            # vz<0かつz<0のとき計算を中断
            if v[i + 1][2] < 0 and p[i + 1][2] < 0:
                count = i + 1
                print("Calculation was successfully completed.")
                break

        self.p = p[:count + 1]
        self.v = v[:count + 1]
        self.qua = qua[:count + 1]
        self.ome = ome[:count + 1]
        if log:
            np.savetxt(self.name + "_" + self.condition_name + "_position.csv",
                       p,
                       delimiter=",")
            print("Position file was created.")

        print("Altitude is " + str(max(p[:, 2])) + "[m].")

    def output_kml(self, place):
        # 原点からの距離
        def dis2d(x, y):
            return pow(pow(x, 2) + pow(y, 2), 0.5)

        # y軸とベクトル(x, y)のなす角
        def ang2d(x, y):
            # y軸上
            if x == 0:
                if y >= 0:
                    return 0.0
                else:
                    return 180.0
            # x軸上
            if y == 0:
                if x >= 0:
                    return 90.0
                else:
                    return 270.0
            # 第1象限
            if x > 0 and y > 0:
                return np.arctan(x / y) * 180 / np.pi
            # 第2象限
            if x > 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第3象限
            if x < 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第4象限
            if x < 0 and y > 0:
                return 360.0 + np.arctan(x / y) * 180 / np.pi

        distance = [
            dis2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))
        ]

        angle = [ang2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))]

        coordinate0 = place[1]
        latitude = coordinate0[0]
        longitude = coordinate0[1]
        geod = pyproj.Geod(ellps='WGS84')
        newLong = []
        newLat = []
        invAngle = []
        for i in range(len(self.p)):
            nlon, nlat, nang = geod.fwd(longitude, latitude, angle[i],
                                        distance[i])
            newLong.append(nlon)
            newLat.append(nlat)
            invAngle.append(nang)

        kml = simplekml.Kml(open=1)
        cood = []
        for i in range(len(self.p)):
            cood.append((newLong[i], newLat[i], self.p[i, 2]))
        ls = kml.newlinestring(name=self.name + "'s Path")
        ls.coords = cood
        ls.style.linestyle.width = 3
        ls.style.linestyle.color = simplekml.Color.blue
        ls.altitudemode = simplekml.AltitudeMode.relativetoground
        ls.extrude = 0
        kml.save(self.name + "_" + place[0] + '_' + self.condition_name +
                 "_path.kml")
        print("Kml file for Google Earth was created.")