mcts.py 9.45 KB
Newer Older
Aravind Bk's avatar
Aravind Bk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
from env.simple_intersection import SimpleIntersectionEnv
from env.simple_intersection.constants import *
from options.options_loader import OptionsGraph
from backends import DDPGLearner, DQNLearner, MCTSLearner
import pickle
import tqdm
import numpy as np
import tqdm

import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("logfile.log", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)  
        self.log.flush()

    def flush(self):
        #this flush method is needed for python 3 compatibility.
        #this handles the flush command by doing nothing.
        #you might want to specify some extra behavior here.
        pass    

sys.stdout = Logger()

# TODO: make a separate file for this function.
def mcts_training(nb_traversals, save_every=20, visualize=False):
    """
    Do RL of the low-level policy of the given maneuver and test it.
    Args:
     nb_traversals: number of MCTS traversals
     save_every: save at every these many traversals
     visualize: visualization / rendering
    """

    # initialize the numpy random number generator
    np.random.seed()

    # load options graph
    options = OptionsGraph("mcts_config.json", SimpleIntersectionEnv)
    options.load_trained_low_level_policies()

    agent = DQNLearner(input_shape=(50,), nb_actions=options.get_number_of_nodes(),
                       low_level_policies=options.maneuvers)

    agent.load_model("backends/trained_policies/highlevel/highlevel_weights.h5f")
    options.set_controller_args(predictor = agent.get_softq_value_using_option_alias)
    options.controller.max_depth = 20
    #options.controller.load_model('backends/trained_policies/mcts/mcts.pickle')

    total_epochs = nb_traversals//save_every
    trav_num = 1
    print('Total number of epochs = %d' % total_epochs)
    for num_epoch in range(total_epochs):
        last_rewards = []
        beg_trav_num = trav_num
        for num_traversal in tqdm.tqdm(range(save_every)):
            options.controller.curr_node_num = 0
            init_obs = options.reset()
            v, all_ep_R = options.controller.traverse(init_obs, visualize=visualize)
            # print('Traversal %d: V = %f' % (num_traversal, v))
            # print('Overall Reward: %f\n' % all_ep_R)
            last_rewards += [all_ep_R]
            trav_num += 1
        options.controller.save_model('mcts_%d.pickle' % (num_epoch))
        success = lambda x: x > 50
        success_rate = np.sum(list(map(success, last_rewards)))/(len(last_rewards)*1.0)
        print('success rate: %f' % success_rate)
        print('Average Reward (%d-%d): %f\n' % (beg_trav_num, trav_num-1, np.mean(last_rewards)))

def mcts_evaluation(nb_traversals, num_trials=5, visualize=False):
    """
    Do RL of the low-level policy of the given maneuver and test it.
    Args:
     nb_traversals: number of MCTS traversals
     save_every: save at every these many traversals
     visualize: visualization / rendering
    """

    # initialize the numpy random number generator
    np.random.seed()

    # load options graph
    options = OptionsGraph("mcts_config.json", SimpleIntersectionEnv)
    options.load_trained_low_level_policies()

    agent = DQNLearner(input_shape=(50,), nb_actions=options.get_number_of_nodes(),
                       low_level_policies=options.maneuvers)

    agent.load_model("backends/trained_policies/highlevel/highlevel_weights.h5f")
    options.set_controller_args(predictor=agent.get_softq_value_using_option_alias)
    options.controller.max_depth = 20

    success_list = []
    print('Total number of trials = %d' % num_trials)
    for trial in range(num_trials):
        num_successes = 0
        options.controller.load_model('backends/trained_policies/mcts/mcts.pickle')
        for num_traversal in tqdm.tqdm(range(nb_traversals)):
            options.controller.curr_node_num = 0
            init_obs = options.reset()
            v, all_ep_R = options.controller.traverse(init_obs, visualize=visualize)
            if all_ep_R > 50:
                num_successes += 1
        print("\nTrial {}: success: {}".format(trial + 1, num_successes))
        success_list.append(num_successes)

    print("\nSuccess: Avg: {}, Std: {}".format(np.mean(success_list), np.std(success_list)))


def online_mcts(nb_episodes = 10):
    # MCTS visualization is off

    # initialize the numpy random number generator
    np.random.seed()

    # load options graph
    options = OptionsGraph("mcts_config.json", SimpleIntersectionEnv)
    options.load_trained_low_level_policies()

    agent = DQNLearner(input_shape=(50,), nb_actions=options.get_number_of_nodes(),
                       low_level_policies=options.maneuvers)

    agent.load_model("backends/trained_policies/highlevel/highlevel_weights_772.h5f")
    options.set_controller_args(predictor = agent.get_softq_value_using_option_alias)
    
    # Loop
    num_successes = 0
    for num_ep in range(nb_episodes):
        init_obs = options.reset()
        episode_reward = 0
        first_time = True
        while not options.env.is_terminal():
            if first_time:
                first_time = False
            else:
                print('Stepping through ...')
                features, R, terminal, info = options.controller.step_current_node(visualize_low_level_steps=True)
                episode_reward += R
                print('Intermediate Reward: %f (ego x = %f)' % (R, options.env.vehs[0].x))
                print('')
            if options.controller.can_transition():
                options.controller.do_transition()
        print('')
        print('EPISODE %d: Reward = %f' % (num_ep, episode_reward))
        print('')
        print('')
        if episode_reward > 50: num_successes += 1

    print ("Policy succeeded {} times!".format(num_successes))


def evaluate_online_mcts(nb_episodes=20, nb_trials=5):
    # MCTS visualization is off

    # initialize the numpy random number generator
    np.random.seed()

    # load options graph
    options = OptionsGraph("mcts_config.json", SimpleIntersectionEnv)
    options.load_trained_low_level_policies()

    agent = DQNLearner(input_shape=(50,), nb_actions=options.get_number_of_nodes(),
                       low_level_policies=options.maneuvers)

    agent.load_model("backends/trained_policies/highlevel/highlevel_weights_772.h5f")
    options.set_controller_args(predictor=agent.get_softq_value_using_option_alias)

    print ("\nConducting {} trials of {} episodes each".format(nb_trials,nb_episodes))
    success_list = []
    termination_reason_list = {}
    for trial in range(nb_trials):
        # Loop
        num_successes = 0
        termination_reason_counter = {}
        for num_ep in range(nb_episodes):
            init_obs = options.reset()
            episode_reward = 0
            first_time = True
            while not options.env.is_terminal():
                if first_time:
                    first_time = False
                else:
                    print('Stepping through ...')
                    features, R, terminal, info = options.controller.step_current_node(visualize_low_level_steps=True)
                    episode_reward += R
                    print('Intermediate Reward: %f (ego x = %f)' % (R, options.env.vehs[0].x))
                    print('')
                    if terminal:
                        if 'episode_termination_reason' in info:
                            termination_reason = info['episode_termination_reason']
                            if termination_reason in termination_reason_counter:
                                termination_reason_counter[termination_reason] += 1
                            else:
                                termination_reason_counter[termination_reason] = 1
                if options.controller.can_transition():
                    options.controller.do_transition()
            print('')
            print('EPISODE %d: Reward = %f' % (num_ep, episode_reward))
            print('')
            print('')
            if episode_reward > 50: num_successes += 1

        print("\nTrial {}: success: {}".format(trial+1, num_successes))
        success_list.append(num_successes)
        for reason, count in termination_reason_counter.items():
            if reason in termination_reason_list:
                termination_reason_list[reason].append(count)
            else:
                termination_reason_list[reason] = [count]

    success_list = np.array(success_list)
    print ("\nSuccess: Avg: {}, Std: {}".format(np.mean(success_list), np.std(success_list)))
    print ("Termination reason(s):")
    for reason, count_list in termination_reason_list.items():
        count_list = np.array(count_list)
        print("{}: Avg: {}, Std: {}".format(reason,
                                            np.mean(count_list),
                                            np.std(count_list)))

def mcts_visualize(file_name):
    with open(file_name, 'rb') as handle:
        to_restore = pickle.load(handle)
    # TR = to_restore['TR']
    # M = to_restore['M']
    # for key, val in TR.items():
    #    print('%s: %f, count = %d' % (key, val/M[key], M[key]))
    print(len(to_restore['nodes']))

if __name__ == "__main__":

    mcts_training(nb_traversals=10000, save_every=1000, visualize=False)
    # mcts_evaluation(nb_traversals=100, num_trials=10, visualize=False)
    # for num in range(100): mcts_visualize('timeout_inf_save100/mcts_%d.pickle' % num)
    # mcts_visualize('mcts.pickle')
    #online_mcts(10)
    # evaluate_online_mcts(nb_episodes=20,nb_trials=5)