Ejemplo n.º 1
0
def quality_function(x):
    # Defining a quadratic cost function. The optimum is this case is trivial: [1.0, 2.0, 3.0].
    return -((x[0] - 1.0)**2.0 + (x[1] - 2.0)**2.0 + (x[2] - 3.0)**2.0)


# Defining hyperparameters for the algorithm
hyperparams = Params()
hyperparams.num_particles = 40
hyperparams.inertia_weight = 0.7
hyperparams.cognitive_parameter = 0.6
hyperparams.social_parameter = 0.8
# Defining the lower and upper bounds
lower_bound = np.array([0.0, 0.0, 0.0])
upper_bound = np.array([3.0, 3.0, 3.0])
pso = ParticleSwarmOptimization(hyperparams, lower_bound, upper_bound)
position_history = []
quality_history = []
# Number of function evaluations will be 1000 times the number of particles,
# i.e. PSO will be executed by 1000 generations
num_evaluations = 1000 * hyperparams.num_particles
for i in range(num_evaluations):
    position = pso.get_position_to_evaluate()
    value = quality_function(position)
    pso.notify_evaluation(value)
    position_history.append(position)
    quality_history.append(value)
# Finally, print the best position found by the algorithm and its value
print('Best position:', pso.get_best_position())
print('Best value:', pso.get_best_value())
sensor_params = Params()
sensor_params.sensor_range = 0.015
sensor_params.num_sensors = 7
sensor_params.array_width = 0.06
line_follower = LineFollower(Pose(0.5, 0.5, 45.0 * pi / 180.0),
                             controller_params, robot_params, sensor_params)

# Defining PSO hyperparameters
hyperparams = Params()
hyperparams.num_particles = 40
hyperparams.inertia_weight = 0.5
hyperparams.cognitive_parameter = 0.6
hyperparams.social_parameter = 0.8
lower_bound = np.array([0.0, 10.0, 0.0, 0.0])
upper_bound = np.array([0.9, 200.0, 1300.0, 30.0])
pso = ParticleSwarmOptimization(hyperparams, lower_bound, upper_bound)

# Creating track
# Switch to simple track if you are having trouble to make the robot learn in the complex track
track = create_complex_track()  # create_simple_track()

# Creating the simulation
simulation = Simulation(line_follower, track)

# Initializing pygame
pygame.init()
window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Lab 4 - Line Follower Optimization")
clock = pygame.time.Clock()
font = pygame.font.SysFont('Arial', 20, True)
 def test_hello(self):
     particleSwarmOptimization = ParticleSwarmOptimization()
     particleSwarmOptimization.run_pso_demo()