示例#1
0
    def add_muscle(self, muscle):
        """Add the muscle model to the system.

        Parameters
        ----------
        muscle: <Muscle>
            Instance of muscle model

        Example:
        --------
        >>> from muscle import Muscle
        >>> from system_parameters import MuscleParameters
        >>> muscle = Muscle(MuscleParameters()) #: Default muscle
        >>> isometric_system = IsometricMuscleSystem()
        >>> isometric_system.add_muscle(muscle)
        """
        if self.muscle is not None:
            pylog.warning(
                'You have already added the muscle model to the system.')
            return
        else:
            if muscle.__class__ is not Muscle:
                pylog.error('Trying to set of type {} to muscle'.format(
                    muscle.__class__))
                raise TypeError()
            else:
                pylog.info('Added new muscle model to the system')
                self.muscle = muscle
def exercise_example(timestep):
    """Exercise example"""
    # Parameters
    parameter_set = [
        SimulationParameters(
            duration=10,  # Simulation duration in [s]
            timestep=timestep,  # Simulation timestep in [s]
            spawn_position=[0, 0, 0.1],  # Robot position in [m]
            spawn_orientation=[0, 0, 0],  # Orientation in Euler angles [rad]
            drive=3,  # An example of parameter part of the grid search
            amplitude_gradient=None,
            #amplitudes=[1, 2, 3],  # Just an example
            phase_lag=2 * np.pi / 10,  # or np.zeros(n_joints) for example
            # Another example
            frequency=1,
            # ...
        ) for drive in np.linspace(1, 2, 2)
        # for amplitudes in ...
        # for ...
    ]

    # Grid search
    for simulation_i, sim_parameters in enumerate(parameter_set):
        filename = './logs/example/simulation_{}.{}'
        sim, data = simulation(
            sim_parameters=sim_parameters,  # Simulation parameters, see above
            arena='water',  # Can also be 'ground' or 'amphibious'
            # fast=True,  # For fast mode (not real-time)
            # headless=True,  # For headless mode (No GUI, could be faster)
            # record=True,  # Record video, see below for saving
            # video_distance=1.5,  # Set distance of camera to robot
            # video_yaw=0,  # Set camera yaw for recording
            # video_pitch=-45,  # Set camera pitch for recording
        )
        # Log robot data
        data.to_file(filename.format(simulation_i, 'h5'), sim.iteration)
        # Log simulation parameters
        with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file:
            pickle.dump(sim_parameters, param_file)
        # Save video
        if sim.options.record:
            if 'ffmpeg' in manimation.writers.avail:
                sim.interface.video.save(
                    filename='salamandra_robotica_simulation.mp4',
                    iteration=sim.iteration,
                    writer='ffmpeg',
                )
            elif 'html' in manimation.writers.avail:
                # FFmpeg might not be installed, use html instead
                sim.interface.video.save(
                    filename='salamandra_robotica_simulation.html',
                    iteration=sim.iteration,
                    writer='html',
                )
            else:
                pylog.error('No known writers, maybe you can use: {}'.format(
                    manimation.writers.avail))
示例#3
0
def exercise_8f(timestep, phase_lag_vector, experience):
    """Exercise 8f"""
    # Parameters
    parameter_set = [
        SimulationParameters(
            duration=10,  # Simulation duration in [s]
            timestep=timestep,  # Simulation timestep in [s]
            spawn_position=[0, 0, 0.1],  # Robot position in [m]
            spawn_orientation=[0, 0, 0],  # Orientation in Euler angles [rad]
            drive_mlr=2,  # drive so the robot can walk
            amplitude_limb=0.5,
            phase_lag=phase_lag,
            phase_limb_body=np.pi / 2,
            exercise_8f=True
            # ...
        ) for phase_lag in phase_lag_vector
    ]

    # Grid search
    for simulation_i, sim_parameters in enumerate(parameter_set):
        filename = './logs/{}/simulation_{}.{}'
        sim, data = simulation(
            sim_parameters=sim_parameters,  # Simulation parameters, see above
            arena='ground',  # Can also be 'ground' or 'amphibious'
            #fast=True,  # For fast mode (not real-time)
            #headless=True,  # For headless mode (No GUI, could be faster)
            # record=True,  # Record video, see below for saving
            # video_distance=1.5,  # Set distance of camera to robot
            # video_yaw=0,  # Set camera yaw for recording
            # video_pitch=-45,  # Set camera pitch for recording
        )
        # Log robot data
        data.to_file(filename.format(experience, simulation_i, 'h5'),
                     sim.iteration)
        # Log simulation parameters
        with open(filename.format(experience, simulation_i, 'pickle'),
                  'wb') as param_file:
            pickle.dump(sim_parameters, param_file)
        # Save video
        if sim.options.record:
            if 'ffmpeg' in manimation.writers.avail:
                sim.interface.video.save(
                    filename='salamandra_robotica_simulation.mp4',
                    iteration=sim.iteration,
                    writer='ffmpeg',
                )
            elif 'html' in manimation.writers.avail:
                # FFmpeg might not be installed, use html instead
                sim.interface.video.save(
                    filename='salamandra_robotica_simulation.html',
                    iteration=sim.iteration,
                    writer='html',
                )
            else:
                pylog.error('No known writers, maybe you can use: {}'.format(
                    manimation.writers.avail))
示例#4
0
def exercise_8g(timestep):
    """Exercise 8g"""
    # Parameters
    parameter_set = [
        SimulationParameters(
            duration=30,
            timestep=timestep,
            spawn_position=[-0.8, 0, 0.1],  # Robot position in [m]
            spawn_orientation=[0, 0,
                               np.pi],  # Orientation in Euler angles [rad]
            amplitude_gradient=True,
            drive=1.5,
            amplitudes=[0.4, 1],
            frequency=1,
            nominal_radius=0.3,
            phase_lag=1.95)
    ]

    # Grid search
    for simulation_i, sim_parameters in enumerate(parameter_set):
        filename = './logs/exercise_8g/simulation_{}.{}'
        sim, data = simulation(
            sim_parameters=sim_parameters,  # Simulation parameters, see above
            arena='amphibious',  # Can also be 'ground' or 'amphibious'
            fast=True,  # For fast mode (not real-time)
            # headless=True,  # For headless mode (No GUI, could be faster)
            # record=True,  # Record video, see below for saving
            # video_distance=1.5,  # Set distance of camera to robot
            # video_yaw=0,  # Set camera yaw for recording
            # video_pitch=-45,  # Set camera pitch for recording
        )
        # Log robot data
        data.to_file(filename.format(simulation_i, 'h5'), sim.iteration)
        # Log simulation parameters
        with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file:
            pickle.dump(sim_parameters, param_file)
        # Save video
        if sim.options.record:
            if 'ffmpeg' in manimation.writers.avail:
                sim.interface.video.save(
                    filename='salamandra_robotica_simulation.mp4',
                    iteration=sim.iteration,
                    writer='ffmpeg',
                )
            elif 'html' in manimation.writers.avail:
                # FFmpeg might not be installed, use html instead
                sim.interface.video.save(
                    filename='salamandra_robotica_simulation.html',
                    iteration=sim.iteration,
                    writer='html',
                )
            else:
                pylog.error('No known writers, maybe you can use: {}'.format(
                    manimation.writers.avail))
 def load_config_file(self):
     """Load the animal configuration file"""
     try:
         stream = open(os.path.realpath(self.muscle_joint_config_path), 'r')
         self.muscle_joint_config = yaml.load(stream)
         biolog.info('Successfully loaded the file : {}'.format(
             os.path.split(self.muscle_joint_config_path)[-1]))
         return
     except ValueError:
         biolog.error('Unable to read the file {}'.format(
             self.muscle_joint_config_path))
         raise ValueError()
示例#6
0
 def val(self, data):
     """
     Set the value of the parameter
     Parameters
     ----------
     data : <float>
         Value of the parameter
     """
     try:
         self._p_list[self.idx] = data
     except IndexError:
         biolog.error('Unable to find index {} in list {}'.format(
             self.idx, self._p_list))
         raise IndexError()
""" Analyse system symbolically (corrections) """

import numpy as np
import farms_pylog as pylog
from ex3_pendulum import PendulumParameters, pendulum_system, pendulum_equation

USE_SYMPY = False
try:
    import sympy as sp
    USE_SYMPY = True
except ImportError as err:
    pylog.error(err)
    USE_SYMPY = False

def exercise_example(timestep):
    """Exercise example"""
    # Parameters
    cv_body = [0.2, 0.3]
    cv_limb = [0.2, 0.]

    cr_body = [0.056, 0.196]
    cr_limb = [0.131, 0.131]

    parameter_set = [
        SimulationParameters(
            freqs=1,
            duration=10,  # Simulation duration in [s]
            timestep=timestep,  # Simulation timestep in [s]
            spawn_position=[-1.3, 0, 0.1],  # Robot position in [m]
            spawn_orientation=[0, 0, 0],  # Orientation in Euler angles [rad]
            drive=4,  # An example of parameter part of the grid search
            amplitudes=[0.3, 0.3],
            turn=0,
            pattern='walk',
            phase_lag=0.2 * np.pi,
            absolute_amplitude=False,
            phase_body_limb=4 * np.pi / 9,
            #transition=['walk','swim'],
            #amplitude=1.,
            # ...
        ) for drive in np.linspace(1, 1, 1)
        # for amplitudes in ...
        # for ...
    ]

    # Grid search
    for simulation_i, sim_parameters in enumerate(parameter_set):
        filename = './logs/example/simulation_{}.{}'
        sim, data = simulation(
            sim_parameters=sim_parameters,  # Simulation parameters, see above
            arena='amphibious',  # Can also be 'ground' or 'amphibious'
            fast=True,  # For fast mode (not real-time)
            # headless=True,  # For headless mode (No GUI, could be faster)
            #record=True,  # Record video, see below for saving
            # video_distance=1.5,  # Set distance of camera to robot
            # video_yaw=0,  # Set camera yaw for recording
            # video_pitch=-45,  # Set camera pitch for recording
        )
        # Log robot data
        data.to_file(filename.format(simulation_i, 'h5'), sim.iteration)
        # Log simulation parameters
        with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file:
            pickle.dump(sim_parameters, param_file)
        # Save video
        if sim.options.record:
            if 'ffmpeg' in manimation.writers.avail:
                sim.interface.video.save(
                    filename='video_transition_from_walking_to_swimming.mp4',
                    iteration=sim.iteration,
                    writer='ffmpeg',
                )
            elif 'html' in manimation.writers.avail:
                # FFmpeg might not be installed, use html instead
                sim.interface.video.save(
                    filename='transition_from_walking_to_swimming.html',
                    iteration=sim.iteration,
                    writer='html',
                )
            else:
                pylog.error('No known writers, maybe you can use: {}'.format(
                    manimation.writers.avail))
pylog.info('Element wise subtraction of numpy arrays b-a :\n{}'.format(b - a))

pylog.info("""Have a look at Array broadcasting to understand how numpy
    compares two arrays for math operations""")

# Create a random numpy array using random method
A = np.ones((2, 3))
pylog.info('Numpy array  A of size (2,3) using ones method :\n{}'.format(A))

# Create a random numpy array using random method
B = np.ones((3, 2))
pylog.info('Numpy array B of size (3,2) using ones method :\n{}'.format(B))

pylog.info('Matrix multiplication A*B using numpy dot method :\n{}'.format(
    np.dot(A, B)))

pylog.info('Matrix multiplication B*A using numpy dot method :\n{}'.format(
    np.dot(B, A)))

try:
    pylog.info("""Matrix multiplication transpose(A)*B using numpy dot method:
        {}""".format(np.dot(A.T, B)))
except ValueError:
    pylog.error(
        'ValueError: shapes (3,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)'
    )

pylog.info('Have a look at numpy matrices method!')
pylog.warning(' Numpy matrices are not very often used!')
示例#10
0
digits = (0, 1, 'two')  # Create a tuple directly
digits = tuple([0, 1, 'two'])  # Create a tuple from list
pylog.warning('A trailing comma is required to indicate its a tuple')
zero = (0, )

# examine a tuple
digits[2]  # returns 'two'
len(digits)  # returns 3
digits.count(0)  # counts the number of instances of that value (1)
digits.index(1)  # returns the index of the first instance of that value (1)

# elements of a tuple cannot be modified
try:
    digits[2] = 2  # throws an error
except BaseException:
    pylog.error('Tuples cannot be edited once initialized')

# concatenate tuples
digits = digits + (3, 4)

# create a single tuple with elements repeated (also works with lists)
(3, 4) * 2  # returns (3, 4, 3, 4)

# sort a list of tuples
tens = [(20, 60), (10, 40), (20, 30)]
sorted(tens)  # sorts by first element in tuple, then second element
#   returns [(10, 40), (20, 30), (20, 60)]

# tuple unpacking
bart = ('male', 10, 'simpson')  # create a tuple
(sex, age, surname) = bart  # assign three values at once