OpenAI Gym: CartPole-v1

This notebook demonstrates how grammar-guided genetic programming (G3P) can be used to solve the CartPole-v1 problem from OpenAI Gym. This is achieved by searching for a small program that defines an agent, who uses an algebraic expression of the observed variables to decide which action to take in each moment.

References

In [1]:
import time
import warnings

import alogos as al
import gym
import unified_map as um
In [2]:
warnings.filterwarnings('ignore')

Preparation

1) Environment

CartPole-v1: The aim is to move a cart (black) such that it balances a pendulum (brown) without moving too far from the center. The agent observes current position and velocity of the cart, as well as angle and velocity of the pole. It can act by pushing the cart to the left (value 0) or to the right (value 1).

In [3]:
env = gym.make('CartPole-v1')

2) Functions to run single or multiple simulations

It allows an agent to act in an environment and collect rewards until the environment signals it is done.

In [4]:
def simulate_single_run(env, agent, render=False):
    observation = env.reset()
    episode_reward = 0.0
    while True:
        action = agent.decide(observation)
        observation, reward, done, info = env.step(action)
        episode_reward += reward
        if render:
            time.sleep(0.03)
            env.render()
        if done:
            break
    env.close()
    return episode_reward
In [5]:
def simulate_multiple_runs(env, agent, n):
    total_reward = sum(simulate_single_run(env, agent) for _ in range(n))
    mean_reward = total_reward / n
    return mean_reward

Example solutions

In [6]:
num_sim = 200

1) By Zhiqing Xiao

In [7]:
class Agent:
    def decide(self, observation):
        position, velocity, angle, angle_velocity = observation
        action = int(3. * angle + angle_velocity > 0.)
        return action

agent = Agent()
simulate_multiple_runs(env, agent, num_sim)
Out[7]:
500.0

2) By previous runs of evolutionary optimization

In [8]:
class Agent:
    def decide(self, observation):
        position, velocity, angle, angle_velocity = observation
        output = (((1.00+angle)+velocity)+angle_velocity)
        action = int(output)
        return action

agent = Agent()
simulate_multiple_runs(env, agent, num_sim)
Out[8]:
500.0
In [9]:
class Agent:
    def decide(self, observation):
        position, velocity, angle, angle_velocity = observation
        output = ((1.00+(1.92*angle))+(1.12*angle_velocity))
        action = int(output)
        return action

agent = Agent()
simulate_multiple_runs(env, agent, num_sim)
Out[9]:
500.0
In [10]:
class Agent:
    def decide(self, observation):
        position, velocity, angle, angle_velocity = observation
        output = ((1.25**angle_velocity)+angle)
        action = int(output)
        return action

agent = Agent()
simulate_multiple_runs(env, agent, num_sim)
Out[10]:
500.0

Definition of search space and goal

1) Grammar

This grammar defines the search space: a Python program that creates an Agent who uses an algebraic expression of the observed variables to decide how to act in each situation.

In [11]:
ebnf_text = """
PROGRAM = L0 NL L1 NL L2 NL L3 NL L4 NL L5

L0 = "class Agent:"
L1 = "    def decide(self, observation):"
L2 = "        position, velocity, angle, angle_velocity = observation"
L3 = "        output = " EXPR
L4 = "        action = 0 if output < 0.0 else 1"
L5 = "        return action"

NL = "\n"

EXPR = VAR | CONST | "(" EXPR OP EXPR ")"
VAR = "position" | "velocity" | "angle" | "angle_velocity"
CONST = DIGIT "." DIGIT DIGIT
OP = "+" | "-" | "*" | "/" | "**"
DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
"""

grammar = al.Grammar(ebnf_text=ebnf_text)

2) Objective function

The objective function gets a candidate solution (=a string of the grammar's language) and returns a fitness value for it. This is done by 1) executing the string as a Python program, so that it creates an agent object, and then 2) using the agent in multiple simulations to see how good it can handle different situations: the higher the total reward, the better is the candidate.

In [12]:
def string_to_agent(string):
    local_vars = dict()
    exec(string, None, local_vars)
    Agent = local_vars['Agent']
    return Agent()


def objective_function(string):
    agent = string_to_agent(string)
    avg_reward = simulate_multiple_runs(env, agent, 30)
    return avg_reward

Generation of a random solution

Check if grammar and objective function work as intended.

In [13]:
random_string = grammar.generate_string()
print(random_string)
class Agent:
    def decide(self, observation):
        position, velocity, angle, angle_velocity = observation
        output = (2.74*((5.07/(2.34*(angle_velocity**7.44)))/(angle**angle)))
        action = 0 if output < 0.0 else 1
        return action
In [14]:
objective_function(random_string)
Out[14]:
9.4

Search for an optimal solution

Evolutionary optimization with random variation and non-random selection is used to find increasingly better candidate solutions.

1) Parameterization

In [15]:
ea = al.EvolutionaryAlgorithm(
    grammar, objective_function, 'max', max_or_min_fitness=500,
    population_size=50, offspring_size=50, evaluator=um.univariate.parallel.futures, verbose=True)

2) Run

In [16]:
best_ind = ea.run()
Progress         Generations      Evaluations      Runtime (sec)    Best fitness    
..... .....      10               496              3.8              64.53333333333333
..... .....      20               848              6.4              205.8
..... .....      30               923              7.3              205.8
..... .....      40               995              8.2              205.8
..... .....      50               1056             8.9              205.8
..... .....      60               1124             9.8              205.8
..... .....      70               1183             10.6             205.8
..... .....      80               1245             11.3             205.8
..... .....      90               1317             12.4             473.4
..... 

Finished         95               1365             13.1             500.0           

3) Result

In [17]:
string = best_ind.phenotype
print(string)
class Agent:
    def decide(self, observation):
        position, velocity, angle, angle_velocity = observation
        output = ((angle_velocity+angle)+angle)
        action = 0 if output < 0.0 else 1
        return action
In [18]:
agent = string_to_agent(string)
simulate_multiple_runs(env, agent, 100)
Out[18]:
500.0
In [19]:
simulate_single_run(env, agent, render=True)
Out[19]:
500.0