├── src ├── cmd │ ├── __init__.py │ └── api.py ├── server │ ├── __init__.py │ ├── test_federated.py │ └── federated.py ├── env │ └── env.py ├── rand.py ├── noise.py ├── util.py ├── replaybuffer.py ├── reporter.py ├── config.py └── environment.py ├── requirements.txt ├── setup.py ├── .gitignore ├── README.md ├── agent ├── ddpgagent.py └── model.py ├── workers ├── controller.py ├── accumulator.py ├── evaluator.py └── trainer.py ├── run.py └── LICENSE /src/cmd/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/server/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Requirements 2 | tensorflow==2.4.1 3 | graphviz==0.13.2 4 | pydot==1.4.2 5 | pandas 6 | numpy==1.19.5 7 | matplotlib==3.3.2 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup(name='avddpg', 4 | version='0.3', 5 | description='DDPG implentation using tensorflow', 6 | author='Christian Boin', 7 | author_email='', 8 | url='', 9 | packages=[] 10 | ) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Vscode # 3 | .vscode 4 | .ropeproject 5 | # venv 6 | venv 7 | 8 | 9 | .outputs 10 | 11 | # compute canada files 12 | jout_files 13 | launch_configs 14 | 15 | # General 16 | __pycache__ 17 | *.pyc 18 | .DS_STORE 19 | tensorflow/ 20 | test.py 21 | 22 | # Project dirs 23 | res/ 24 | reports/ 25 | -------------------------------------------------------------------------------- /src/env/env.py: -------------------------------------------------------------------------------- 1 | """Environment variables for avddpg. 2 | """ 3 | 4 | # DF columns for storing data 5 | PLATOON_COL = "platoon" 6 | SEED_COL = "seed" 7 | EPISODIC_REWARD_AVGWINDOW_COL = "avg window" 8 | VEHICLE_COL = "Vehicle %s" 9 | TRAINING_EPISODE_COLNAME = "Episode" 10 | FED_WEIGHT_SUM_COL = "Vehicle %s fws" # fed weight sum column 11 | FED_WEIGHT_PCT_COL = "Vehicle %s pct" # fed weight pct column -------------------------------------------------------------------------------- /src/rand.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import os 3 | import numpy as np 4 | import random 5 | 6 | def set_global_seed(seed: int): 7 | os.environ['PYTHONHASHSEED']=str(seed) 8 | random.seed(seed) 9 | tf.random.set_seed(seed) 10 | np.random.seed(seed) 11 | 12 | os.environ['TF_DETERMINISTIC_OPS'] = "1" 13 | os.environ['TF_CUDNN_DETERMINISTIC'] = "1" 14 | tf.config.threading.set_inter_op_parallelism_threads(1) 15 | tf.config.threading.set_intra_op_parallelism_threads(1) -------------------------------------------------------------------------------- /src/noise.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from src import util 3 | class OUActionNoise: 4 | def __init__(self, mean, x_init=None, config=None): 5 | self.config = config 6 | self.theta = self.config.theta 7 | self.mean = mean 8 | 9 | self.std_dev = float(self.config.std_dev)* np.ones(1) 10 | self.dt = self.config.ou_dt 11 | self.x_init = x_init 12 | self.reset() 13 | 14 | def __call__(self): 15 | x = ( 16 | self.x_prev 17 | + self.theta * (self.mean - self.x_prev) * self.dt 18 | + self.std_dev * np.sqrt(self.dt) * util.get_random_val(self.config.normal, std_dev=1.0, config=self.config, size=self.mean.shape) 19 | ) 20 | 21 | self.x_prev = x 22 | 23 | return x 24 | 25 | def reset(self): 26 | if self.x_init is not None: 27 | self.x_prev = self.x_init 28 | else: 29 | self.x_prev = np.zeros_like(self.mean) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Autonomous Vehicle Reinforcement Learning using DDPG Algorithm v1.1.4 2 | A CLI tool for running DRL experiments on a simulated Autonomous vehicle platoon (or many). 3 | 4 | ## Install 5 | To install, create a venv and install the requirements file. 6 | This program is loosely tested on Python 3.6, 3.7 and 3.8 7 | ``` 8 | python3 -m venv venv 9 | source venv/bin/activate 10 | pip install -r requirements.txt 11 | ``` 12 | 13 | Note: For simulations to render, you will need 14 | gym==0.21.0 15 | pyglet==1.5.23 16 | 17 | ***Note that on windows you will perform ```venv/Scripts/Activate``` instead of ```source venv/bin/activate```. 18 | 19 | ## Run the program 20 | To see what the cli can do, enter the following. 21 | ``` 22 | python run.py --help 23 | ``` 24 | 25 | ### Training 26 | ``` 27 | python run.py tr 28 | ``` 29 | To gain insight on configurable parameters, use 30 | ``` 31 | python run.py tr --help 32 | ``` 33 | A training session will create a .outputs folder within the base of the repo. 34 | This folder will contain an experiment folder containing the results. 35 | 36 | ### Reporting 37 | After training, you can generate a latex report in a folder. This can be embedded into an overleaf project as a latex subfile if you like. 38 | ``` 39 | python run.py lmany 40 | ``` 41 | Note that this command only works if the .outputs folder contains an experiment(s). 42 | 43 | ### Figure Generation 44 | If you wish to compare similar experiments, you can use at the [accumulator.py](./workers/accumulator.py) file. 45 | 46 | ``` 47 | python run.py accumr 48 | ``` 49 | This will accumulate experiment results and plot the reward averaged across the seeds in svg files for each platoon. 50 | 51 | ### Re-run simulations 52 | You can re-run simulations on existing experiments, by running the below command and passing the file as an argument 53 | ``` 54 | python run.py esim 55 | ``` 56 | 57 | ## Notes 58 | You can nest --help on any of the above commands if you cant figure out what to do with the cli. 59 | 60 | -------------------------------------------------------------------------------- /agent/ddpgagent.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from agent import model 4 | 5 | 6 | def policy(actor_state, noise_object=None, lbound=None, hbound=None): 7 | """gets the policy from the model 8 | 9 | Args: 10 | noise_object ([type]): the noise from OUA process 11 | actor_state ([type]): the actor models state 12 | lbound ([type]): low bound for the action 13 | hbound ([type]): high bound 14 | 15 | Returns: 16 | list: the policy from the prediction 17 | """ 18 | sampled_actions = tf.squeeze(actor_state) 19 | if noise_object is not None: 20 | noise = noise_object() 21 | # Adding noise to action 22 | sampled_actions = sampled_actions.numpy() + noise 23 | else: 24 | sampled_actions = sampled_actions.numpy() 25 | 26 | # We make sure action is within bounds 27 | legal_action = np.clip(sampled_actions, lbound, hbound) 28 | 29 | return [np.squeeze(legal_action)] 30 | 31 | def update_target(tau, t_critic_weights, critic_weights, t_actor_weights, actor_weights): 32 | """Get the new target critic and target actor weights 33 | 34 | Args: 35 | tau (float): learning rate 36 | t_critic_weights (): weights of target critic network 37 | critic_weights (): weights of critic network 38 | t_actor_weights (): weights of target actor network 39 | actor_weights (): weights of actor network 40 | 41 | Returns: 42 | list tc_new_weights, list ta_new_weights: the new target critic and target actor weights 43 | """ 44 | tc_new_weights = [] 45 | target_variables = t_critic_weights 46 | for i, variable in enumerate(critic_weights): 47 | tc_new_weights.append(variable * tau + target_variables[i] * (1 - tau)) 48 | 49 | 50 | ta_new_weights = [] 51 | target_variables = t_actor_weights 52 | for i, variable in enumerate(actor_weights): 53 | ta_new_weights.append(variable * tau + target_variables[i] * (1 - tau)) 54 | 55 | return tc_new_weights, ta_new_weights -------------------------------------------------------------------------------- /workers/controller.py: -------------------------------------------------------------------------------- 1 | 2 | from src import environment 3 | from src import config 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | import math 7 | def run(): 8 | conf = config.Config() 9 | simulation_time = 20 # sim time in seconds 10 | steps = int(simulation_time/conf.sample_rate) 11 | 12 | env = environment.Vehicle(1, conf) 13 | 14 | print(env) 15 | 16 | high_bound = env.action_high 17 | low_bound = env.action_low 18 | 19 | print(f"Total episodes: {conf.number_of_episodes}\nSteps per episode: {conf.steps_per_episode}") 20 | 21 | controller = PID(4.5, 10, 0) # initialize controller 22 | states = np.zeros((steps, env.num_states)) # states 23 | input_list = [] # input list for plotting 24 | state = env.x # first state 25 | for i in range(steps): 26 | inp = math.sin(i) 27 | input_list.append(inp) 28 | 29 | action = controller.control(conf.sample_rate, inp - state[2]) 30 | state, reward, terminal = env.step([action], 0) 31 | states[i] = state 32 | 33 | plt.plot(states[:, 0], label="ep") 34 | plt.plot(states[:, 1], label="ev") 35 | plt.plot(states[:, 2], label="a") 36 | plt.plot(input_list, label="u") 37 | plt.xlabel(f"{conf.sample_rate}s steps for total time of {simulation_time} s") 38 | plt.legend() 39 | plt.show() 40 | 41 | class PID: 42 | def __init__(self, kp, ki, kd): 43 | """Default constructor for PID 44 | 45 | Args: 46 | kp (float): proportional gain 47 | ki (float): integral gain 48 | kd (float): differential gain 49 | """ 50 | self.cumulative_err = 0 51 | self.delta_err = 0 52 | self.last_err = 0 53 | 54 | self.kp = kp 55 | self.ki = ki 56 | self.kd = kd 57 | 58 | def control(self, dt, error): 59 | """Apply the PID control to the signal error 60 | 61 | Args: 62 | dt (integer): the timestep for the control 63 | error (float): the error 64 | 65 | Returns: 66 | float: the control output 67 | """ 68 | self.cumulative_err += error 69 | self.delta_err = error - self.last_err 70 | 71 | output = self.kp * error \ 72 | + self.ki * dt * self.cumulative_err \ 73 | + (self.kd/dt) * self.delta_err 74 | self.last_err = error 75 | return output 76 | -------------------------------------------------------------------------------- /src/util.py: -------------------------------------------------------------------------------- 1 | import h5py 2 | import json 3 | import tensorflow as tf 4 | from types import SimpleNamespace 5 | import numpy as np 6 | import pandas as pd 7 | import random 8 | import os, sys 9 | import logging 10 | import glob 11 | 12 | log = logging.getLogger(__name__) 13 | 14 | def save_file(fpath, txt): 15 | with open(fpath, 'w') as f: 16 | log.info(f"Saving {txt} to : {fpath}") 17 | f.write(txt) 18 | 19 | def read_csv(fp): 20 | return pd.read_csv(fp) 21 | 22 | def write_csv_from_df(df, fp): 23 | log.info("writing..") 24 | log.info(df.head()) 25 | log.info(f"To - > {fp}") 26 | df.to_csv(fp) 27 | 28 | def config_writer(fpath, obj): 29 | with open(fpath, 'w') as f: 30 | log.info(f"Saving configuration Config.py as json: outfile -> {fpath}.") 31 | json.dump(obj.__dict__, f) 32 | 33 | def config_loader(fpath): 34 | with open(fpath, 'r') as f: 35 | return json.load(f, object_hook=lambda d: SimpleNamespace(**d)) 36 | 37 | def load_json(fpath): 38 | with open(fpath, 'r') as f: 39 | return json.load(f) 40 | 41 | def latexify(s): 42 | return str(s).replace('_', '\_').replace('%', '\%') 43 | 44 | def print_dct(dct): 45 | for k, v in dct.items(): 46 | print(f"{latexify(k)} & {latexify(v)} \\\\") 47 | 48 | def inititialize_dirs(config): 49 | for directory in config.dirs: 50 | dir_path = os.path.join(sys.path[0], directory) 51 | if not os.path.exists(dir_path): 52 | log.info(f"Making dir {dir_path}") 53 | os.mkdir(dir_path) 54 | 55 | def get_random_val(mode, val=None, std_dev=None, config=None, size=None): 56 | """Generates a uniformally distributed random variable, or a gaussian random variable centered at 0 by dafault. 57 | 58 | Args: 59 | mode (str): the random generation type 60 | val (float, optional): the bound for uniform number generation 61 | std_dev (float, optional): the standard devation for guassian function. Defaults to None. 62 | config (config.Config, optional): the configuration class for the training environment . Defaults to None. 63 | 64 | Returns: 65 | [type]: [description] 66 | """ 67 | if mode == config.uniform: 68 | return np.random.uniform(-1*val, val) 69 | elif mode == config.normal: 70 | return np.random.normal(0, std_dev, size=size) 71 | 72 | def load_json_to_df(df): 73 | return pd.read_json(df) 74 | 75 | def find_files(file_name): 76 | paths = glob.glob(file_name) 77 | return paths 78 | 79 | def remove_keys_from_dict(dct, keys): 80 | for key in keys: 81 | try: 82 | del dct[key] 83 | except KeyError: 84 | pass 85 | return dct -------------------------------------------------------------------------------- /src/replaybuffer.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | import random 3 | import numpy as np 4 | import tensorflow as tf 5 | class ReplayBuffer: 6 | def __init__(self, buffer_capacity=100000, batch_size=64, 7 | num_states=None, 8 | num_actions=None, 9 | platoon_size=None, 10 | ): 11 | """Default constructor 12 | 13 | Args: 14 | buffer_capacity (int, optional): Capacity of the buffer. Defaults to 100000. 15 | batch_size (int, optional): random sample batch sizes. Defaults to 64. 16 | num_states (int, optional): state space of env. Defaults to None. 17 | num_actions (int, optional): action space of env. Default to None. 18 | seed_int (int, optional): the seed for the number generator 19 | """ 20 | 21 | # Number of "experiences" to store at max 22 | self.buffer_capacity = buffer_capacity 23 | # Num of tuples to train on. 24 | self.batch_size = batch_size 25 | 26 | # Its tells us num of times record() was called. 27 | self.buffer_counter = 0 28 | 29 | # Instead of list of tuples as the exp.replay concept go 30 | # We use different np.arrays for each tuple element 31 | self.state_buffer = np.zeros((self.buffer_capacity, num_states)) 32 | self.action_buffer = np.zeros((self.buffer_capacity, num_actions)) 33 | self.reward_buffer = np.zeros((self.buffer_capacity, 1)) 34 | self.next_state_buffer = np.zeros((self.buffer_capacity, num_states)) 35 | 36 | # Takes (s,a,r,s') obervation tuple as input 37 | def add(self, obs_tuple): 38 | # Set index to zero if buffer_capacity is exceeded, 39 | # replacing old records 40 | index = self.buffer_counter % self.buffer_capacity 41 | 42 | self.state_buffer[index] = obs_tuple[0] 43 | self.action_buffer[index] = obs_tuple[1] 44 | self.reward_buffer[index] = obs_tuple[2] 45 | self.next_state_buffer[index] = obs_tuple[3] 46 | 47 | self.buffer_counter += 1 48 | 49 | # We compute the loss and update parameters 50 | def sample(self): 51 | # Get sampling range 52 | record_range = min(self.buffer_counter, self.buffer_capacity) 53 | # Randomly sample indices 54 | batch_indices = np.random.choice(record_range, self.batch_size) 55 | 56 | # Convert to tensors 57 | state_batch = tf.convert_to_tensor(self.state_buffer[batch_indices]) 58 | action_batch = tf.convert_to_tensor(self.action_buffer[batch_indices]) 59 | reward_batch = tf.convert_to_tensor(self.reward_buffer[batch_indices]) 60 | reward_batch = tf.cast(reward_batch, dtype=tf.float32) 61 | next_state_batch = tf.convert_to_tensor(self.next_state_buffer[batch_indices]) 62 | 63 | return state_batch, action_batch, reward_batch, next_state_batch 64 | 65 | if __name__=="__main__": 66 | pass -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from workers import trainer, controller, evaluator, accumulator 4 | from src import config, util, reporter, rand 5 | from src.cmd import api 6 | import os 7 | import random 8 | import sys 9 | import logging 10 | import datetime 11 | 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | def setup_global_logging_stream(conf): 16 | console = logging.StreamHandler(sys.stdout) 17 | formatter = logging.Formatter(conf.log_format) 18 | console.setFormatter(formatter) 19 | logging.getLogger('').addHandler(console) 20 | 21 | 22 | def run(args): 23 | conf = config.Config() 24 | args, conf = api.get_cmdl_args(args[1:], "Autonomous Vehicle Platoon with DDPG.", conf) 25 | 26 | # set the seed for everything 27 | rand.set_global_seed(conf.random_seed) 28 | 29 | physical_devices = tf.config.list_physical_devices('GPU') 30 | 31 | if len(physical_devices) > 0: 32 | tf.config.experimental.set_memory_growth(physical_devices[0], True) 33 | 34 | util.inititialize_dirs(conf) 35 | 36 | root_dir = sys.path[0] 37 | timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") 38 | 39 | if args.mode == 'tr': 40 | base_dir = os.path.join(sys.path[0], conf.res_dir, timestamp+f"_{conf.model}_seed{conf.random_seed}_{conf.framework}_{conf.fed_method}") 41 | os.mkdir(base_dir) 42 | 43 | """ Setup logging to file and console """ 44 | logging.basicConfig(level=logging.INFO, 45 | format=conf.log_format, 46 | datefmt=conf.log_date_fmt, 47 | filename=os.path.join(base_dir, "out.log"), 48 | filemode='w') 49 | 50 | setup_global_logging_stream(conf) 51 | tr = trainer.Trainer(base_dir, timestamp, debug_enabled=args.tr_debug, conf=conf) 52 | tr.initialize() 53 | tr.run() 54 | 55 | elif args.mode == 'pid': 56 | controller.run() 57 | 58 | elif args.mode == 'esim': # run eval with that of conf.json 59 | setup_global_logging_stream(conf) 60 | conf_path = os.path.join(args.exp_path, config.Config.param_path) 61 | logger.info(f"Loading configuration instance from {conf_path}") 62 | conf = util.config_loader(conf_path) 63 | 64 | for p in range(conf.num_platoons): 65 | evaluator.run(conf=conf, root_path=args.exp_path, out='save', seed=True, 66 | pl_idx=p+1, debug_enabled=args.sim_debug, 67 | render=args.sim_render, 68 | title_off=args.title_off, 69 | eval_plwidth=args.eval_plwidth) # already seeded above 70 | evaluator.run(conf=conf, root_path=args.exp_path, out='save', seed=True, 71 | pl_idx=p+1, debug_enabled=args.sim_debug, 72 | render=args.sim_render, 73 | title_off=args.title_off, 74 | manual_timestep_override=args.n_timesteps, 75 | eval_plwidth=args.eval_plwidth) # already seeded above 76 | elif args.mode == "accumr": 77 | setup_global_logging_stream(conf) 78 | accumulator.generate_reward_plot(n_vehicles=args.acc_nv, timestamp=timestamp, mode_limit=args.mode_limit) 79 | 80 | 81 | elif args.mode == 'lsim': 82 | setup_global_logging_stream(conf) 83 | util.print_dct(util.load_json(args.config_path)) 84 | 85 | elif args.mode == 'lmany': 86 | setup_global_logging_stream(conf) 87 | report_root = os.path.join(root_dir, conf.report_dir) 88 | res_dir = os.path.join(root_dir, conf.res_dir) 89 | list_of_exp_paths = util.find_files(os.path.join(res_dir, '*')) 90 | 91 | reporter.generate_latex_report(report_root, list_of_exp_paths, conf.param_path, conf.index_col, 92 | conf.drop_keys_in_report, timestamp, 0.5, conf.param_descs) 93 | 94 | 95 | if __name__ == "__main__": 96 | run(sys.argv) 97 | 98 | -------------------------------------------------------------------------------- /agent/model.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from tensorflow.keras import layers 3 | import numpy as np 4 | def get_actor(num_states, num_actions, high_bound, seed_int=None, hidd_mult=1, 5 | layer1_size=400, layer2_size=300): 6 | """Get an actor network 7 | 8 | Args: 9 | num_states (int): number of states from the environment 10 | upper_bound ([type]): used for scaling the actions 11 | seed_int (int): a seed for the random number generator 12 | hidd_mult (float): a value for scaling the hidden layers sizes by a constant value 13 | layer1_size (int): the size of the first layer 14 | layer2_size (int): the size of the second layer 15 | Returns: 16 | model: the tensorflow model 17 | """ 18 | # weight intializers 19 | last_init = tf.random_uniform_initializer(minval=-0.003, maxval=0.003, seed=seed_int) 20 | layer1_init_bound = 1/(np.sqrt(layer1_size)) 21 | layer1_init = tf.random_uniform_initializer(minval=-layer1_init_bound, maxval=layer1_init_bound, seed=seed_int) 22 | 23 | layer2_init_bound = 1/(np.sqrt(layer2_size)) 24 | layer2_init = tf.random_uniform_initializer(minval=-layer2_init_bound, maxval=layer2_init_bound, seed=seed_int) 25 | # Model build 26 | inputs = layers.Input(shape=(num_states)) 27 | out = layers.Dense(int(layer1_size * hidd_mult), activation="relu", kernel_initializer=layer1_init)(inputs) 28 | out = layers.BatchNormalization()(out) 29 | 30 | out = layers.Dense(int(layer2_size * hidd_mult), activation="relu", kernel_initializer=layer2_init)(out) 31 | out = layers.BatchNormalization()(out) 32 | 33 | # Output 34 | outputs = layers.Dense(num_actions, activation="tanh", kernel_initializer=last_init)(out) 35 | 36 | outputs = outputs * high_bound 37 | model = tf.keras.Model(inputs, outputs) 38 | return model 39 | 40 | 41 | def get_critic(num_states, num_actions, hidd_mult=1, seed_int=None, 42 | layer1_size=400, layer2_size=300, action_layer_size=64): 43 | """get the critic network 44 | 45 | Args: 46 | num_states (int): the number of states from the environment 47 | num_actions (int): the number of actions from the environment 48 | hidd_mult (float): a value that scales the hidden layer sizes by a value 49 | layer1_size (int): the size of the first layer 50 | layer2_size (int): the size of the second layer 51 | Returns: 52 | model: the critic model 53 | """ 54 | # weight initializers 55 | last_init = tf.random_uniform_initializer(minval=-0.0003, maxval=0.0003, seed=seed_int) 56 | 57 | layer1_init_bound = 1/(np.sqrt(layer1_size)) 58 | layer1_init = tf.random_uniform_initializer(minval=-layer1_init_bound, maxval=layer1_init_bound, seed=seed_int) 59 | 60 | layer2_init_bound = 1/(np.sqrt(layer2_size)) 61 | layer2_init = tf.random_uniform_initializer(minval=-layer2_init_bound, maxval=layer2_init_bound, seed=seed_int) 62 | 63 | # State as input 64 | state_input = layers.Input(shape=(num_states)) 65 | state_out = layers.Dense(int(layer1_size * hidd_mult), activation="relu", kernel_regularizer='l2', kernel_initializer=layer1_init)(state_input) 66 | state_out = layers.BatchNormalization()(state_out) 67 | 68 | # Action as input 69 | action_input = layers.Input(shape=(num_actions)) 70 | action_out = layers.Dense(int(action_layer_size * hidd_mult), activation="relu", kernel_regularizer='l2', kernel_initializer=layer2_init)(action_input) 71 | action_out = layers.BatchNormalization()(action_out) 72 | 73 | # Both are passed through seperate layer before concatenating 74 | concat = layers.Concatenate(axis=1)([state_out, action_out]) 75 | 76 | out = layers.Dense(int(layer2_size * hidd_mult), activation="relu", kernel_regularizer='l2', kernel_initializer=layer2_init)(concat) 77 | out = layers.BatchNormalization()(out) 78 | 79 | # Output 80 | outputs = layers.Dense(num_actions, kernel_initializer=last_init, kernel_regularizer='l2')(out) 81 | 82 | # Outputs single value for give state-action 83 | model = tf.keras.Model([state_input, action_input], outputs) 84 | 85 | return model 86 | -------------------------------------------------------------------------------- /src/server/test_federated.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | import logging 3 | import tensorflow as tf 4 | import numpy as np 5 | 6 | import logging 7 | import federated 8 | logger = logging.getLogger(__name__) 9 | 10 | if __name__=="__main__": 11 | """ 12 | Quick testing of federated averaging 13 | """ 14 | 15 | log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' 16 | log_date_fmt = "%y-%m-%d %H:%M:%S" 17 | logging.basicConfig(level=logging.INFO, 18 | format=log_format, 19 | datefmt=log_date_fmt) 20 | console = logging.StreamHandler(sys.stdout) 21 | formatter = logging.Formatter(log_format) 22 | console.setFormatter(formatter) 23 | 24 | server = federated.Server("fed", True) 25 | 26 | pl1_model1 = np.array([np.array([1,2,3], dtype=np.float32), np.array([1,2], dtype=np.float32), np.array([3,4], dtype=np.float32)], dtype=object) 27 | pl1_model2 = np.array([np.array([7,8,9], dtype=np.float32), np.array([5,6], dtype=np.float32), np.array([7,8], dtype=np.float32)], dtype=object) 28 | pl2_model1 = np.array([np.array([10,11,12], dtype=np.float32), np.array([9,10], dtype=np.float32), np.array([11,12], dtype=np.float32)], dtype=object) 29 | pl2_model2 = np.array([np.array([13,14,15], dtype=np.float32), np.array([13,14], dtype=np.float32), np.array([15,16], dtype=np.float32)], dtype=object) 30 | 31 | # Parameters for the test 32 | method = "interfrl" 33 | 34 | grads_list = [ 35 | [pl1_model1,pl1_model2 ], 36 | [pl2_model1, pl2_model2] 37 | ] 38 | 39 | weights = [ 40 | [2, 0.5], 41 | [1, 6] 42 | ] 43 | 44 | num_platoons = len(grads_list) 45 | num_models = len(grads_list[0]) 46 | 47 | fed_proc_grads = [] 48 | fed_weights = [] 49 | test_valid = True 50 | if method == "interfrl": 51 | for m in range(num_models): # initialize the gradient collections based on platoon for each model 52 | model_grads = [] 53 | model_weights = [] 54 | for p in range(num_platoons): 55 | model_grads.append([]) 56 | model_weights.append(1) 57 | fed_proc_grads.append(model_grads) 58 | fed_weights.append(model_weights) 59 | 60 | elif method == "intrafrl": 61 | for p in range(num_platoons): # initialize the gradient collections based on model numbers per platoon 62 | pl_grads = [] 63 | pl_weight = [] 64 | for m in range(num_models): 65 | pl_grads.append([]) 66 | pl_weight.append(1) 67 | 68 | fed_proc_grads.append(pl_grads) 69 | fed_weights.append(pl_weight) 70 | 71 | else: 72 | logger.info("invalid test") 73 | test_valid = not test_valid 74 | 75 | if test_valid: 76 | print(f"\n--FEDERATED TEST INIT--\nInitialized \n\tfed_proc_grads:{fed_proc_grads}\n\tfed_weights:{fed_weights}") 77 | for p in range(num_platoons): # simulating collecting the gradients 78 | for m in range(num_models): 79 | grads = grads_list[p][m] 80 | weight = weights[p][m] 81 | if method == "interfrl": 82 | print(weight, grads) 83 | fed_proc_grads[m][p] = weight * grads 84 | fed_weights[m][p] = weight 85 | else: 86 | fed_proc_grads[p][m] = weight * grads 87 | fed_weights[p][m] = weight 88 | 89 | fed_weight_sums = tf.reduce_sum(fed_weights, axis=1) 90 | input_str = "" 91 | input_str += f"\n--FEDERATED TEST INPUTS--\n\t --> grad_list: {grads_list}, shape: {np.shape(grads_list)}" 92 | input_str += f"\n\n\t --> fed_proc_grads: {fed_proc_grads}, shape: {np.shape(fed_proc_grads)}" 93 | input_str += f"\n\n\t --> weights: {weights}, shape: {np.shape(weights)}" 94 | input_str += f"\n\n\t --> fed_weights_sum: {fed_weight_sums}, shape: {np.shape(fed_weight_sums)}" 95 | print(input_str) 96 | fed_avg = server.get_weighted_avg_params(fed_proc_grads, fed_weight_sums) 97 | logger.info(f"--> Input gradients: {fed_proc_grads}") 98 | logger.info(f"--> Output gradients: {fed_avg}") 99 | logger.info(f"--> fed_weights: {fed_weights}") -------------------------------------------------------------------------------- /workers/accumulator.py: -------------------------------------------------------------------------------- 1 | from distutils.command import config 2 | from logging import root 3 | from operator import concat 4 | from this import d 5 | from typing import List, Optional 6 | import pandas as pd 7 | import numpy as np 8 | from src import config, util 9 | from src.env import env 10 | import os, sys, shutil 11 | import glob 12 | import matplotlib.pyplot as plt 13 | 14 | AGG_FNAME = "aggregation.csv" 15 | AVERAGED_DF = "averaged.csv" 16 | 17 | def generate_reward_plot(n_vehicles: int, timestamp: int, mode_limit: int) -> bool: 18 | """Accumulates and plots across multiple seeds, averaging the reward value 19 | across the seed and plotting with a shaded error bar. 20 | 21 | Args: 22 | mode (int): A value of 0 or 1 dictates which csv file to use for aggregation. 23 | 0 = not averaged, 1 = averaged, 2 = fed weightings, 3 = fw percents 24 | """ 25 | accum_path = os.path.join(sys.path[0], config.Config.report_dir, f"ACCUM_{timestamp}") 26 | os.mkdir(accum_path) 27 | # iterate modes 0,1..3 28 | for i in range (mode_limit+1): 29 | df = get_data(i, accum_path) 30 | df = transform(df, n_vehicles,i, accum_path) 31 | plot(df, n_vehicles, i, accum_path) 32 | return True 33 | 34 | 35 | def get_data(mode: int, accum_path: str) -> pd.DataFrame: 36 | """Aggregates all csv's into a single csv file and writes to disk. Returns the object in a pd.DataFrame. 37 | """ 38 | # TODO: Investigate why this function is not importing data correctly and duplicates the first entry! 39 | path_lst = glob.glob(os.path.join(sys.path[0], config.Config.res_dir, "*")) 40 | df = None 41 | for i, root_path in enumerate(path_lst): 42 | conf_path = os.path.join(root_path, config.Config.param_path) 43 | dir_name = os.path.basename(os.path.normpath(root_path)) 44 | if not os.path.exists(os.path.join(accum_path, dir_name)): 45 | os.mkdir(os.path.join(accum_path, dir_name)) 46 | conf = util.config_loader(conf_path) 47 | # heres where you can point to different files. 48 | if mode == 0: 49 | data_path = conf.ep_reward_path % (conf.random_seed) 50 | elif mode == 1: 51 | data_path = conf.avg_ep_reward_path % (conf.random_seed) 52 | elif mode == 2 or mode == 3: 53 | if not hasattr(conf, "frl_weighted_avg_parameters_path"): 54 | raise ValueError(f"Mode {mode} is invalid as attribute frl_weighted_avg_parameters_path does not exist in config!") 55 | data_path = conf.frl_weighted_avg_parameters_path % (conf.random_seed) 56 | 57 | if df is None: 58 | df = pd.read_csv(os.path.join(root_path, data_path)) 59 | 60 | shutil.copy(conf_path, os.path.join(accum_path, dir_name, config.Config.param_path)) 61 | shutil.copy(os.path.join(root_path, data_path), os.path.join(accum_path, dir_name, 62 | data_path)) 63 | 64 | if df is not None and i > 0: 65 | df = df.append(pd.read_csv(os.path.join(root_path, data_path))) 66 | df_out = df.rename(columns={df.columns[0] : env.TRAINING_EPISODE_COLNAME}) 67 | 68 | util.write_csv_from_df(df_out,os.path.join(accum_path, get_mode_tag(mode,AGG_FNAME))) 69 | return df_out 70 | 71 | def transform(df, n_vehicles: int, mode: int, accum_path: str): 72 | """Performs a transformation on the given df, producing the averaged result 73 | 74 | Args: 75 | df (pd.DataFrame): the pandas dataframe 76 | n_vehicles (int): the number of assumed vehicle columns in the data frame. 77 | """ 78 | # Get the number of platoons out of the data set. Will return a single dataframe averaged for vehicles aross the seeds. 79 | df_c = df.copy() 80 | df_c.drop(columns=[env.SEED_COL], inplace=True) 81 | if mode == 1: 82 | df_c.drop(columns=[env.EPISODIC_REWARD_AVGWINDOW_COL], inplace=True) 83 | if mode == 2: 84 | df_c.drop(columns=get_fws_colnames(n_vehicles) + get_fwpct_colnames(n_vehicles), inplace=True) 85 | if mode == 3: 86 | df_c.drop(columns=get_fws_colnames(n_vehicles) + get_vehicle_colnames(n_vehicles), inplace=True) 87 | 88 | grouped_df = df_c.groupby([env.TRAINING_EPISODE_COLNAME, env.PLATOON_COL]) 89 | avg_df = grouped_df.agg([np.mean, np.std]) 90 | util.write_csv_from_df(avg_df,os.path.join(accum_path, get_mode_tag(mode,AVERAGED_DF))) 91 | return avg_df 92 | 93 | def plot(df, n_vehicles: int, mode: int, accum_path: str): 94 | n_platoons = len(set(df.index.get_level_values(1))) 95 | 96 | for p_idx in range(n_platoons): 97 | fig, ax = plt.subplots() 98 | sub_df = df.xs(p_idx+1, level=env.PLATOON_COL) # Select out data pertinent to the platoon idx, p_id 99 | if mode == 0 or mode == 1: 100 | col_to_plot = "Vehicle" 101 | elif mode == 2: 102 | col_to_plot = "Vehicle Weighting" 103 | elif mode == 3: 104 | col_to_plot = "Vehicle Weighting in Percent" 105 | 106 | sub_df.columns.names = [col_to_plot, None] 107 | sub_df = sub_df.stack(col_to_plot).reset_index().sort_values(env.TRAINING_EPISODE_COLNAME).reset_index(drop=True) 108 | for i, v in sub_df.groupby(col_to_plot): 109 | ax.plot(v[env.TRAINING_EPISODE_COLNAME], v['mean'], linewidth=get_plot_weight(mode), label=v[col_to_plot].unique()[0]) 110 | ax.fill_between(v[env.TRAINING_EPISODE_COLNAME], 111 | v['mean'] - v['std'], 112 | v['mean'] + v['std'], alpha=0.35) 113 | ax.set_xlabel("Training episode") 114 | ax.set_ylabel(get_y_axis_title(mode)) 115 | ax.legend() 116 | plt.rcParams.update({'font.size': 14}) 117 | plt.tight_layout() 118 | plt.savefig(os.path.join(accum_path, get_mode_tag(mode,f"pl{p_idx+1}.svg")), dpi=150) 119 | 120 | def get_vehicle_colnames(n_vehicles: int): 121 | return [env.VEHICLE_COL % (v_idx) for v_idx in range(1, n_vehicles+1)] 122 | 123 | def get_fws_colnames(n_vehicles: int): 124 | return [env.FED_WEIGHT_SUM_COL % (v_idx) for v_idx in range(1, n_vehicles+1)] 125 | 126 | def get_fwpct_colnames(n_vehicles: int): 127 | return [env.FED_WEIGHT_PCT_COL % (v_idx) for v_idx in range(1, n_vehicles+1)] 128 | 129 | 130 | def get_mode_tag(mode, s) -> str: 131 | if mode == 0: 132 | return "ep_reward_" + s 133 | elif mode == 1: 134 | return "avgep_reward_" + s 135 | elif mode == 2: 136 | return "fw_" + s 137 | elif mode == 3: 138 | return "fws_" + s 139 | else: 140 | raise ValueError(f"No such mode exists {mode}") 141 | def get_y_axis_title(mode) -> str: 142 | if mode == 0: 143 | return "Average episodic reward" 144 | elif mode == 1: 145 | return "Cumulative average episodic reward" 146 | elif mode == 2: 147 | return "Federated Weighting" 148 | elif mode == 3: 149 | return "Federated Weighting Percent" 150 | else: 151 | raise ValueError(f"No such mode exists {mode}") 152 | def get_plot_weight(mode) -> int: 153 | if mode == 0: 154 | return 0.35 155 | elif mode == 1: 156 | return 0.5 157 | elif mode == 2: 158 | return 0.5 159 | elif mode == 3: 160 | return 0.5 161 | else: 162 | raise ValueError(f"No such mode exists {mode}") 163 | -------------------------------------------------------------------------------- /src/cmd/api.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from secrets import choice 3 | from src import config 4 | 5 | def set_args_to_config(args, config: config.Config): 6 | """Set method for writing command line arguments to the configuration class 7 | """ 8 | if hasattr(args, "seed") and args.seed is not None: # redundnat statement keeps 3.6 compatibile with 3.7.8 9 | config.random_seed = args.seed 10 | if hasattr(args, "method") and args.method is not None: 11 | config.method = args.method 12 | if hasattr(args, "rand_states") and args.rand_states is not None: 13 | config.rand_states = args.rand_states 14 | if hasattr(args, "total_time_steps") and args.total_time_steps is not None: 15 | config.total_time_steps = args.total_time_steps 16 | config.number_of_episodes = int(args.total_time_steps/config.steps_per_episode) 17 | if hasattr(args, "render") and args.render is not None: 18 | config.show_env = args.render 19 | if hasattr(args, "pl_num") and args.pl_num is not None: 20 | config.num_platoons = args.pl_num 21 | if hasattr(args, "pl_size") and args.pl_size is not None: 22 | config.pl_size = args.pl_size 23 | if hasattr(args, "buffer_size") and args.buffer_size is not None: 24 | config.buffer_size = args.buffer_size 25 | if hasattr(args, "actor_lr") and args.actor_lr is not None: 26 | config.actor_lr = args.actor_lr 27 | if hasattr(args, "critic_lr") and args.critic_lr is not None: 28 | config.critic_lr = args.critic_lr 29 | if hasattr(args, "fed_method") and args.fed_method is not None: 30 | config.fed_method = args.fed_method 31 | if hasattr(args, "fed_update_count") and args.fed_update_count is not None: 32 | config.fed_update_count = args.fed_update_count 33 | if hasattr(args, "fed_cutoff_ratio") and args.fed_cutoff_ratio is not None: 34 | config.fed_cutoff_ratio = args.fed_cutoff_ratio 35 | config.fed_cutoff_episode = int(config.fed_cutoff_ratio * config.number_of_episodes) 36 | if hasattr(args, "intra_directional_averaging") and args.intra_directional_averaging is not None: 37 | config.intra_directional_averaging = args.intra_directional_averaging 38 | 39 | if hasattr(args, "fed_update_delay") and args.fed_update_delay is not None: 40 | config.fed_update_delay = args.fed_update_delay 41 | config.fed_update_delay_steps = int(config.fed_update_delay/config.sample_rate) 42 | 43 | if hasattr(args, "fed_weight_enabled") and args.fed_weight_enabled is not None: 44 | config.weighted_average_enabled = args.fed_weight_enabled 45 | 46 | if hasattr(args, "fed_weight_window") and args.fed_weight_window is not None: 47 | config.weighted_window = args.fed_weight_window 48 | if hasattr(args, "fed_agg_method") and args.fed_agg_method is not None: 49 | config.aggregation_method = args.fed_agg_method 50 | return config 51 | def get_cmdl_args(args: list, description: str, config: config.Config): 52 | """Simple command line parser 53 | 54 | Args: 55 | args (list): the input arguments from command prompt 56 | return (list) : the list of parsed arguments 57 | """ 58 | parser = argparse.ArgumentParser(description=description) 59 | subparsers = parser.add_subparsers(dest="mode") 60 | add_tr = subparsers.add_parser('tr', help="run in training mode") 61 | add_tr.add_argument("--seed", type=int, default=config.random_seed, 62 | help="the seed globally set across the experiment. If not set, will take whatever is in src/config.py") 63 | add_tr.add_argument("--method", choices=[config.exact, config.euler], help="Discretization method.") 64 | add_tr.add_argument("--rand_states", type=bool, help='whether to initialize the vehicle environments with random states or what is in config.py. Pass "" to turn false!') 65 | add_tr.add_argument("--total_time_steps", type=int, help='The number of training time steps. Usually 1000000 leads to good results') 66 | add_tr.add_argument("--render", type=bool, help='Whether to output the environment states to console. Pass "" to turn false!') 67 | add_tr.add_argument("--tr_debug", type=bool, help='Whether to enable debug mode for the trainer. Pass "" to turn false!') 68 | add_tr.add_argument("--pl_num", type=int, help="How many platoons to simulate with.") 69 | add_tr.add_argument("--pl_size", type=int, help="How many vehicles in each platoon.") 70 | add_tr.add_argument("--buffer_size", type=int, help="The number of samples to include in the replay buffer!") 71 | add_tr.add_argument("--actor_lr", type=float, help="The learning rate of the actor!") 72 | add_tr.add_argument("--critic_lr", type=float, help="The learning rate of the critic!") 73 | 74 | add_tr.add_argument("--fed_method", choices=[config.interfrl, config.intrafrl, config.normal]) 75 | add_tr.add_argument("--fed_update_count", type=int, help="number of episodes between federated averaging updates") 76 | add_tr.add_argument("--fed_cutoff_ratio", type=float, help="the ratio to toral number of episodes at which FRL is cutoff") 77 | add_tr.add_argument("--fed_update_delay", type=float, help="the time in second between updates during a training episode for FRL.") 78 | add_tr.add_argument("--fed_weight_enabled", type=bool, default=False, help='whether to use weighted averaging FRL. Pass "" to turn false!') 79 | add_tr.add_argument("--fed_weight_window", type=int, help="how many cumulative episodes to average for calculating the weights.") 80 | add_tr.add_argument("--fed_agg_method", type=str, choices=["gradients", "weights"], help="which method to use for federated aggregation") 81 | add_tr.add_argument("--intra_directional_averaging", type=bool, default=True, help="whether to average the leaders parameters during intrafrl. default: true") 82 | 83 | add_esim = subparsers.add_parser('esim', help="run in evaluation/simulator mode. ") 84 | add_esim.add_argument("exp_path", type=str, help="path to experiment directory") 85 | add_esim.add_argument("--sim_debug", type=bool, default=False, help="whether to launch the simulator step by step or not.") 86 | add_esim.add_argument("--sim_render", type=bool, help="Whether to output the environment states to console.") 87 | add_esim.add_argument("--title_off", type=bool, default=False, help="Whether to include a title in the plot.") 88 | add_esim.add_argument("--n_timesteps", type=int, default=100, help= 89 | "specify a number of timesteps to plot the simulation for. This setting used in the manual override pass of the evaluator, with a default value of 100.") 90 | add_esim.add_argument("--eval_plwidth", type=float, default=0.85, help="Default plot width for evaluator.") 91 | 92 | add_accumr = subparsers.add_parser('accumr', help="run in accumulator mode for reward plotting.") 93 | add_accumr.add_argument("--acc_debug", type=bool, default=False, help="whether to launch the reward accumulator step by step or not.") 94 | add_accumr.add_argument("--acc_nv", type=int, default=1, help="Number of vehicles in the episodic reward table (should be >0).") 95 | add_accumr.add_argument("--mode_limit", type=int, default=3, choices=[0,1,2,3], help= 96 | "Number of modes for plotting. If specified, you can limit the range of modes. 0 = ep reward, 1 = avg ep reward, 2 = fed weightings, 3 = fed weighting pct") 97 | 98 | add_accums = subparsers.add_parser('accums', help="run in accumulator mode for simulation plotting.") 99 | add_accums.add_argument("--sim_render", type=bool, help="Whether to output the environment states to console.") 100 | add_accums.add_argument("--acc_debug", type=bool, default=False, help="whether to launch the reward accumulator step by step or not.") 101 | 102 | add_lsim = subparsers.add_parser('lsim', help="run a latex table generator for a single config file") 103 | add_lsim.add_argument("config_path", type=str, help="path to trained configuration json file") 104 | 105 | add_lmany = subparsers.add_parser('lmany', help="run a latex table generator for all config files") 106 | 107 | args = parser.parse_args(args) 108 | config = set_args_to_config(args, config) 109 | 110 | return args, config 111 | -------------------------------------------------------------------------------- /src/reporter.py: -------------------------------------------------------------------------------- 1 | from src import util 2 | import pandas as pd 3 | import os 4 | import shutil 5 | 6 | def aggregate_json_to_df(output_root, list_of_exp_paths, conf_fname, report_timestamp, drop_cols=None, index_col=None, save_latex_out=True): 7 | """[summary] 8 | Args: 9 | output_root (str): The string of the rroto reporting folder 10 | list_of_exp_paths (list): List of experiments (directories) to scrape info from 11 | conf_name (str): Name of json with hyperparameters 12 | report_timestamp (str): timestampe for the report folder 13 | """ 14 | report_dir = os.path.join(output_root, report_timestamp) 15 | if not os.path.exists(report_dir): 16 | os.mkdir(report_dir) 17 | for i, dname in enumerate(list_of_exp_paths): 18 | conf_fpath = os.path.join(dname, conf_fname) 19 | conf_dct = util.load_json(conf_fpath) 20 | conf_dct = util.remove_keys_from_dict(conf_dct, drop_cols) 21 | if i == 0: 22 | aggregate_df = pd.DataFrame([conf_dct]) 23 | else: 24 | aggregate_df = aggregate_df.append(pd.DataFrame([conf_dct])) 25 | 26 | if index_col is not None: 27 | aggregate_df = aggregate_df.set_index(index_col) 28 | util.write_csv_from_df(aggregate_df, os.path.join(report_dir, report_timestamp + ".csv")) 29 | if save_latex_out: 30 | util.save_file(os.path.join(report_dir, report_timestamp + ".txt"), aggregate_df.to_latex()) 31 | else: 32 | return aggregate_df 33 | 34 | def get_figure_str(fig_width, fig_path, fig_label, fig_caption): 35 | figure = """ 36 | \\begin{figure} 37 | \caption{%s} 38 | \centering 39 | \includegraphics[width=%s\linewidth]{%s} 40 | \label{%s} 41 | \end{figure} 42 | """ % (fig_caption, fig_width, fig_path, fig_label) 43 | return figure 44 | 45 | def get_svg_str(fig_width, fig_path, fig_label, fig_caption): 46 | figure = """ 47 | \\begin{figure} 48 | \caption{%s} 49 | \centering 50 | \includesvg[width=%s\linewidth]{%s} 51 | \label{%s} 52 | \end{figure} 53 | """ % (fig_caption, fig_width, fig_path, fig_label) 54 | return figure 55 | 56 | def generate_fig_params(experiment_dir, conf_fname): 57 | conf = util.config_loader(os.path.join(experiment_dir, conf_fname)) 58 | fig_params = [{"name" : conf.actor_picname % (1, 1), 59 | "width" : 0.5, 60 | "caption" : "Actor network model for experiment %s"}, 61 | {"name" : conf.critic_picname % (1, 1), 62 | "width" : 0.6, 63 | "caption" : "Critic network model for experiment %s"} 64 | ] 65 | 66 | for p in range(conf.num_platoons): 67 | fig_params.append( {"name" : conf.fig_path % (p+1), 68 | "width" : 0.6, 69 | "caption" : f"Platoon {p+1} reward curve for experiment %s"} 70 | ) 71 | fig_params.append({"name" : f"res_guassian{conf.pl_tag}.svg" % (p+1), 72 | "width" : 0.4, 73 | "caption" : f"Platoon {p+1} simulation for experiment %s including state space variables."}) 74 | fig_params.append({"name" : f"rew_guassian{conf.pl_tag}.svg" % (p+1), 75 | "width" : 0.4, 76 | "caption" : f"Platoon {p+1} simulation for experiment %s including reward equation variables."}) 77 | 78 | return fig_params 79 | 80 | def generate_latex_report(output_root, list_of_exp_paths, conf_fname, conf_index_col, conf_drop_cols, report_timestamp, fig_width, param_dct): 81 | """Generates a latex report body 82 | 83 | Args: 84 | output_root (str): The string of the rroto reporting folder 85 | list_of_exp_paths (str): List of experiments (directories) to scrape info from 86 | conf_fname (str): Name of json with hyperparameters 87 | conf_index_col (str) : the config files key for setting index of dataframe 88 | conf_drop_cols (str) : any columns to drop from the dataframe 89 | report_timestamp (str): timestampe for the report folder 90 | fig_names (list): file names of any figures to include in the report 91 | fig_width (float): width of the figures 92 | json_names (str): json for hyperparameter descriptions 93 | """ 94 | report_dir = os.path.join(output_root, report_timestamp) 95 | if not os.path.exists(report_dir): 96 | os.mkdir(report_dir) 97 | report_txt_fname = 'latex_results.tex' 98 | with open(os.path.join(report_dir, report_txt_fname), 'a') as f: 99 | f.write('\section{Parameter Descriptions}\n') 100 | f.write(pd.DataFrame({'Hyperparameter' : param_dct.keys(), "Description" : param_dct.values()}).to_latex(caption="Hyperparameter Legend", label="tab:hyplegend")) 101 | 102 | f.write('\section{Summary of Results}') 103 | all_confs_df = aggregate_json_to_df(output_root, 104 | list_of_exp_paths, 105 | conf_fname, 106 | report_timestamp, 107 | drop_cols=conf_drop_cols, 108 | index_col=conf_index_col, 109 | save_latex_out=False) 110 | f.write(all_confs_df.to_latex(caption=f"Results Across All Experiments with Hyperparameters", label=f"tab:all_hyps")) 111 | 112 | # get columns that are constant from the dataframe, to make a summary table of the constant params with their values 113 | constant_value_cols = [c for c in all_confs_df.columns if len(set(all_confs_df[c])) == 1] 114 | all_confs_df_constants = all_confs_df[constant_value_cols][:1].T.reset_index() 115 | all_confs_df_constants.columns = ['Hyperparameters', 'Value'] 116 | util.write_csv_from_df(all_confs_df_constants, os.path.join(report_dir, "constants.csv")) 117 | f.write(all_confs_df_constants.to_latex(caption=f"Hyperparameters Unchanged Across All Experiments", label=f"tab:const_hyps")) 118 | 119 | # make a table of those that changed 120 | all_confs_df_changed = all_confs_df.drop(columns=constant_value_cols) 121 | util.write_csv_from_df(all_confs_df_changed, os.path.join(report_dir, "changed.csv")) 122 | f.write(all_confs_df_changed.to_latex(caption=f"Hyperparameters That Changed Across All Experiments", label=f"tab:changed_hyps")) 123 | 124 | for dir_ in list_of_exp_paths: 125 | dir_name = os.path.basename(os.path.normpath(dir_)) 126 | latexify_dir_name = util.latexify(dir_name) 127 | f.write('\section{Experiment %s}\n' % (latexify_dir_name)) 128 | report_exp_dir = os.path.join(report_dir, dir_name) 129 | os.mkdir(report_exp_dir) 130 | 131 | fig_params = generate_fig_params(dir_, conf_fname) 132 | 133 | for fig_map in fig_params: 134 | fig_name = fig_map['name'] 135 | fig_src = os.path.join(dir_, fig_name) 136 | fig_dest = os.path.join(report_exp_dir, fig_name) 137 | fig_relative_path = dir_name + "/" + fig_name 138 | shutil.copy(fig_src, fig_dest) 139 | if '.png' in fig_name: 140 | f.write(get_figure_str(fig_map['width'], fig_relative_path, f"fig:{fig_relative_path}", fig_map["caption"] % (latexify_dir_name))) 141 | elif '.svg' in fig_name: 142 | f.write(get_svg_str(fig_map['width'], fig_relative_path, f"fig:{fig_relative_path}", fig_map["caption"] % (latexify_dir_name))) 143 | else: 144 | raise ValueError(f"Cannot load image. Consider converting image {fig_src} to one of '.png' or '.svg' and try running again.") 145 | 146 | conf_fpath = os.path.join(dir_, conf_fname) 147 | conf_dct = util.load_json(conf_fpath) 148 | conf_dct = util.remove_keys_from_dict(conf_dct, conf_drop_cols) 149 | 150 | conf_df = pd.DataFrame({'Hyperparameter' : conf_dct.keys(), "Values" : conf_dct.values()}) 151 | f.write(conf_df.to_latex(caption=f"Hyperparameter's for Experiment {latexify_dir_name}", label=f"tab:hyp_exp{dir_name}")) 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | -------------------------------------------------------------------------------- /src/server/federated.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | import logging 3 | from numpy.core.shape_base import stack 4 | import tensorflow as tf 5 | import numpy as np 6 | 7 | import logging 8 | from typing import Optional, List 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | class Server: 13 | def __init__(self, name, debug_enabled): 14 | logger.info(f"Launching FRL Server: {name}") 15 | self.name = name 16 | self.debug = debug_enabled 17 | 18 | def get_avg_params(self, system_params : list): 19 | """ 20 | Computes the average params of a system of models.. by averaging horizontally across system environments 21 | Args: system 1 model 1 system X model 1 22 | system_params (list) : expecting list of shape [[[tf.tensor1...tf.tensorN], ... [tf.tensor1...tf.tensorN]], 23 | . . 24 | . . 25 | . . 26 | system 1 model M system X model M 27 | [tf.tensor1...tf.tensorN]] ... [tf.tensor1...tf.tensorN]]] 28 | where -- 29 | N is the number of layers in each model 30 | M is the number of models in each system 31 | X is the number of systems 32 | weight_sums (list) : a list of scalar float values for scaling each system average. If weighted tensors are added, providing weight_sums for each weighted system will compute the weighted average 33 | Returns: 34 | model 1 35 | (list) : averaged horizontally model-wise s.t. [[tf.tensor1...tf.tensorN], 36 | . 37 | . 38 | . 39 | model M 40 | [tf.tensor1...tf.tensorN]] 41 | 42 | """ 43 | system_avg_params = [] 44 | if self.debug: 45 | logger.info(f"System params: {system_params}") 46 | 47 | for p in range(len(system_params)): 48 | multi_model_params_stacked = np.stack(np.array(system_params[p], dtype=object), axis=1) # stacks the params along the first axis.. 49 | #s.t. each model layer's params are now adjacent 50 | if self.debug: 51 | logger.info(f"") 52 | logger.info(f"System params after stacking layers:\n{multi_model_params_stacked}") 53 | averaged_params = [] 54 | 55 | for i in range(len(multi_model_params_stacked)): 56 | stacked_layer_tensors = tf.stack(multi_model_params_stacked[i], axis=0) # stack all the layers for the models into single tensor 57 | 58 | if self.debug: 59 | logger.info(f"All layer [{i}] params:\n{stacked_layer_tensors}") 60 | logger.info(f"Layer [{i}] means: {tf.reduce_mean(stacked_layer_tensors, axis=0)}\n") 61 | 62 | averaged_params.append(tf.reduce_mean(stacked_layer_tensors, axis=0)) # compute the mean across model params per layer 63 | system_avg_params.append(averaged_params) 64 | 65 | if self.debug: 66 | logger.info(f"System params after averaging: {system_avg_params}") 67 | return system_avg_params 68 | 69 | def get_weighted_avg_params(self, system_params : list, weight_sums: List[float]): 70 | """ 71 | Computes the average params of a system of models.. by summing weighted params, and diving each system set by the sum of weights 72 | Expects the system params passed in to already be multiplied by weights. 73 | Args: system 1 model 1 system X model 1 74 | system_params (list) : expecting list of shape [[[tf.tensor1...tf.tensorN], ... [tf.tensor1...tf.tensorN]], 75 | . . 76 | . . 77 | . . 78 | system 1 model M system X model M 79 | [tf.tensor1...tf.tensorN]] ... [tf.tensor1...tf.tensorN]]] 80 | where -- 81 | N is the number of layers in each model 82 | M is the number of models in each system 83 | X is the number of systems 84 | weight_sums (list) : a list of scalar float values for scaling each system average. If weighted tensors are added, providing weight_sums for each weighted system will compute the weighted average 85 | Returns: 86 | model 1 87 | (list) : averaged horizontally model-wise s.t. [[tf.tensor1...tf.tensorN], 88 | . 89 | . 90 | . 91 | model M 92 | [tf.tensor1...tf.tensorN]] 93 | 94 | """ 95 | system_avg_params = [] 96 | if self.debug: 97 | logger.info(f"System params: {system_params}") 98 | 99 | for p in range(len(system_params)): 100 | multi_model_params_stacked = np.stack(np.array(system_params[p], dtype=object), axis=1) # stacks the params along the first axis.. 101 | #s.t. each model layer's params are now adjacent 102 | system_weight_sum = weight_sums[p] 103 | if self.debug: 104 | logger.info(f"------------System [{p}]-------------") 105 | logger.info(f"System weighted params after stacking layers:\n{multi_model_params_stacked}") 106 | averaged_params = [] 107 | 108 | for i in range(len(multi_model_params_stacked)): 109 | stacked_layer_tensors = tf.stack(multi_model_params_stacked[i], axis=0) # stack all the layers for the models into single tensor 110 | weighted_layer_avg = tf.math.scalar_mul(tf.cast(1 / system_weight_sum, tf.float32), tf.reduce_sum(stacked_layer_tensors, axis=0)) 111 | if self.debug: 112 | logger.info(f"\t------Layer [{i}]------") 113 | logger.info(f"\t\tweighted params:\n{stacked_layer_tensors}") 114 | logger.info(f"\t\tsum of weights: {system_weight_sum}") 115 | logger.info(f"\t\tweighted means: {weighted_layer_avg}\n") 116 | 117 | averaged_params.append(weighted_layer_avg) # compute the mean across model params per layer 118 | system_avg_params.append(averaged_params) 119 | 120 | if self.debug: 121 | logger.info(f"System params after averaging: {system_avg_params}") 122 | return system_avg_params 123 | if __name__=="__main__": 124 | logger.info("hi there") -------------------------------------------------------------------------------- /workers/evaluator.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from src import config, noise, replaybuffer, environment, util, rand 4 | from agent import model, ddpgagent 5 | import matplotlib.pyplot as plt 6 | import h5py 7 | import math 8 | from src.config import Config 9 | import os 10 | import random 11 | import logging 12 | from typing import Optional 13 | import warnings 14 | 15 | log = logging.getLogger(__name__) 16 | def run(conf=None, actors=None, 17 | path_timestamp=None, 18 | out=None, 19 | root_path=None, 20 | seed=True, 21 | pl_idx=None, 22 | debug_enabled=False, 23 | render=False, 24 | title_off=False, 25 | manual_timestep_override=None, 26 | eval_plwidth=0.5): 27 | log.info(f"====__--- Launching Evaluator for Platoon {pl_idx}! ---__====") 28 | plot_lwidth = eval_plwidth 29 | legend_fontsize = 8 30 | if conf is None: 31 | conf_path = os.path.join(root_path, config.Config.param_path) 32 | log.info(f"Loading configuration instance from {conf_path}") 33 | conf = util.config_loader(conf_path) 34 | 35 | if path_timestamp is None: 36 | model_parent_dir = root_path 37 | else: 38 | model_parent_dir = path_timestamp 39 | 40 | if seed: 41 | evaluation_seed = conf.evaluation_seed 42 | rand.set_global_seed(conf.evaluation_seed) 43 | 44 | else: 45 | evaluation_seed = None 46 | 47 | env = environment.Platoon(conf.pl_size, conf, pl_idx, evaluator_states_enabled=True) # do not use random states here, for consistency across evaluation sessions 48 | num_models = env.num_models 49 | episode_simulation_timesteps = get_number_of_timesteps_for_plot(conf, manual_timestep_override) 50 | if actors is None: 51 | actors = [] 52 | for m in range(num_models): 53 | actors.append(tf.keras.models.load_model(os.path.join(root_path, conf.actor_fname % (pl_idx, m+1)), compile=False)) 54 | 55 | input_opts = {conf.guasfig_name : [util.get_random_val(conf.rand_gen, conf.reset_max_u, std_dev=conf.reset_max_u, config=conf) 56 | for _ in range(episode_simulation_timesteps)]} 57 | 58 | actions = np.zeros((num_models, env.num_actions)) 59 | pl_states = np.zeros((episode_simulation_timesteps, conf.pl_size, env.def_num_states)) 60 | pl_inputs = np.zeros((episode_simulation_timesteps, conf.pl_size, env.def_num_actions)) 61 | pl_jerks = np.zeros((episode_simulation_timesteps, conf.pl_size, 1)) 62 | 63 | num_rows = env.def_num_states + 1 64 | num_cols = 1 65 | 66 | number_of_reward_components = env.number_of_reward_components 67 | episodic_reward_counters = np.array([0]*num_models, dtype=np.float32) 68 | number_of_sim_plot_components = 5 69 | 70 | for typ, input_list in input_opts.items(): # allows for a variety of input responses for simulation. 71 | states_fig, states_axs = plt.subplots(num_rows,num_cols, figsize = (4,12)) 72 | reward_fig, reward_axs = plt.subplots(number_of_reward_components, num_cols, figsize=(4,12)) 73 | sim_fig, sim_axs = plt.subplots(number_of_sim_plot_components, num_cols, figsize = (4,12)) 74 | 75 | states = env.reset() 76 | # generate the simulated data for plotting 77 | for i in range(episode_simulation_timesteps): 78 | if conf.show_env == True or render: 79 | env.render() 80 | 81 | for m in range(num_models): 82 | state = tf.expand_dims(tf.convert_to_tensor(states[m]), 0) 83 | actions[m] = ddpgagent.policy(actors[m](state), lbound=conf.action_low, hbound=conf.action_high)[0] # do not use noise in the simulation 84 | states, rewards, terminal = env.step(actions.flatten(), input_list[i], debug_enabled) 85 | jerks = env.get_jerk() 86 | if debug_enabled: 87 | user_input = input("Advance to the next timestep 'q' quits: ") 88 | if user_input == 'q': 89 | return 90 | 91 | for m in range(num_models): 92 | episodic_reward_counters[m] += rewards[m] 93 | pl_states[i] = np.reshape(states, (conf.pl_size, env.def_num_states)) # reshapes to standard format, regardless of cent or decent 94 | pl_inputs[i] = np.reshape(actions, (conf.pl_size, env.def_num_actions)) 95 | pl_jerks[i] = np.reshape(jerks, (conf.pl_size, 1)) 96 | # generate the plots 97 | for i in range(conf.pl_size): # for each follower's states in the platoon states 98 | for j in range(env.def_num_states): # state plots 99 | states_axs[j].plot(pl_states[:,i][:,j], label=f"Vehicle {i+1}", linewidth=plot_lwidth) 100 | states_axs[j].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 101 | states_axs[j].yaxis.set_label_text(f"{env.state_lbs[j]}") 102 | states_axs[j].legend(prop={"size":legend_fontsize}) 103 | 104 | if j < 2: # first two states are used in the reward eqn 105 | reward_axs[j].plot(pl_states[:,i][:,j], label=f"Vehicle {i+1}", linewidth=plot_lwidth) 106 | reward_axs[j].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 107 | reward_axs[j].yaxis.set_label_text(f"{env.state_lbs[j]}") 108 | reward_axs[j].legend(prop={"size":legend_fontsize}) 109 | 110 | if j in [0,1,2]: # these states exclude acceleration of leader. 111 | sim_axs[j].plot(pl_states[:,i][:,j], label=f"Vehicle {i+1}", linewidth=plot_lwidth) 112 | sim_axs[j].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 113 | sim_axs[j].yaxis.set_label_text(f"{env.state_lbs[j]}") 114 | sim_axs[j].legend(prop={"size":legend_fontsize}) 115 | 116 | states_axs[num_rows-1].plot(pl_inputs[:, i], label=f"Vehicle {i+1}") # input plots 117 | 118 | reward_axs[number_of_reward_components-2].plot(pl_inputs[:, i], label=f"Vehicle {i+1}", linewidth=plot_lwidth) # input plot 119 | reward_axs[number_of_reward_components-1].plot(pl_jerks[:, i], label=f"Vehicle {i+1}", linewidth=plot_lwidth) # jerk plots 120 | reward_axs[number_of_reward_components-1].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 121 | reward_axs[number_of_reward_components-1].yaxis.set_label_text(env.jerk_lb) 122 | reward_axs[number_of_reward_components-1].legend(prop={"size":legend_fontsize}) 123 | 124 | sim_axs[number_of_sim_plot_components-2].plot(pl_inputs[:, i], label=f"Vehicle {i+1}", linewidth=plot_lwidth) # input plot 125 | sim_axs[number_of_sim_plot_components-1].plot(pl_jerks[:, i], label=f"Vehicle {i+1}", linewidth=plot_lwidth) # jerk plots 126 | sim_axs[number_of_sim_plot_components-1].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 127 | sim_axs[number_of_sim_plot_components-1].yaxis.set_label_text(env.jerk_lb) 128 | sim_axs[number_of_sim_plot_components-1].legend(loc="upper right", prop={"size": legend_fontsize}) 129 | 130 | states_axs[num_rows-1].plot(input_list, label=f"Platoon leader", zorder=0) # overlay platoon leaders transmitted data 131 | states_axs[num_rows-1].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 132 | states_axs[num_rows-1].yaxis.set_label_text(env.exog_lbl) 133 | states_axs[num_rows-1].legend(prop={"size":legend_fontsize}) 134 | 135 | reward_axs[number_of_reward_components-2].plot(input_list, label=f"Platoon leader", zorder=0) # overlay platoon leaders transmitted data 136 | reward_axs[number_of_reward_components-2].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 137 | reward_axs[number_of_reward_components-2].yaxis.set_label_text(env.exog_lbl) 138 | reward_axs[number_of_reward_components-2].legend(prop={"size":legend_fontsize}) 139 | 140 | sim_axs[num_rows-2].plot(input_list, label=f"Platoon leader", zorder=0, linewidth=plot_lwidth) # overlay platoon leaders transmitted data 141 | sim_axs[num_rows-2].xaxis.set_label_text(f"{conf.sample_rate}s steps (total time of {episode_simulation_timesteps*conf.sample_rate} s)") 142 | sim_axs[num_rows-2].yaxis.set_label_text(env.exog_lbl) 143 | sim_axs[num_rows-2].legend(prop={"size": legend_fontsize}) 144 | 145 | pl_rew = round(np.average(episodic_reward_counters), 3) 146 | 147 | sim_plot_title = f"Platoon {pl_idx} {conf.model} {typ} input response\n with cumulative platoon reward of %.3f\n and random seed %s" % (pl_rew, evaluation_seed) 148 | if manual_timestep_override is not None: 149 | fig_tag = "_manual" 150 | save_fig(states_fig, conf, sim_plot_title, out, "res"+fig_tag, title_off, episodic_reward_counters, model_parent_dir, typ, pl_idx) 151 | save_fig(reward_fig, conf, sim_plot_title, out, "rew"+fig_tag, title_off, episodic_reward_counters, model_parent_dir, typ, pl_idx) 152 | save_fig(sim_fig, conf, sim_plot_title, out, "sim"+fig_tag, title_off, episodic_reward_counters, model_parent_dir, typ, pl_idx) 153 | else: 154 | save_fig(states_fig, conf, sim_plot_title, out, "res", title_off, episodic_reward_counters, model_parent_dir, typ, pl_idx) 155 | save_fig(reward_fig, conf, sim_plot_title, out, "rew", title_off, episodic_reward_counters, model_parent_dir, typ, pl_idx) 156 | save_fig(sim_fig, conf, sim_plot_title, out, "sim", title_off, episodic_reward_counters, model_parent_dir, typ, pl_idx) 157 | env.close_render() 158 | return pl_rew 159 | 160 | def save_fig(fig, conf: config.Config, title: str, out: str, fig_type: str, title_off: bool, episodic_reward_counters: np.array, model_parent_dir: str, typ: str, pl_idx: int): 161 | """Save a fig object 162 | 163 | Args: 164 | title (str): the title for the fig 165 | out (str): 'save' writes fig to disc, otherwise the fig is shown using fig.show() 166 | fpath (str): the file path 167 | title_off (bool): whether to plot with a title. 168 | episodic_reward_counters (np.array): the cumulative episodic rewards across the platoon 169 | model_parent_dir (str): the directory to the model 170 | typ (str): the type of simulation 171 | """ 172 | if not title_off: 173 | if len(episodic_reward_counters) == 1: 174 | fig.suptitle(title) 175 | else: 176 | fig.suptitle(title + f" and cumulative vehicle\nrewards {np.round(episodic_reward_counters, 2)}") 177 | fig.tight_layout() 178 | 179 | if out == 'save': 180 | out_file = os.path.join(model_parent_dir, f"{fig_type}_{typ}{conf.pl_tag % (pl_idx)}.svg") 181 | log.info(f"Generated {typ} simulation plot to -> {out_file}") 182 | fig.savefig(out_file, dpi=150) 183 | else: 184 | fig.show() 185 | 186 | def get_number_of_timesteps_for_plot(conf: config.Config, manual_timestep_override: Optional[int]): 187 | """Defines the number of timesteps for the plot 188 | 189 | Args: 190 | conf (config.Config): the configuration class 191 | manual_timestep_override (Optional[int]): a manual option. If provided, this value will be used 192 | 193 | Returns: 194 | int : the number of timesteps in the simulation 195 | """ 196 | if manual_timestep_override is None: 197 | return conf.steps_per_episode 198 | else: 199 | return manual_timestep_override -------------------------------------------------------------------------------- /src/config.py: -------------------------------------------------------------------------------- 1 | import enum 2 | import os, sys 3 | import random 4 | class Config(): 5 | modelA = 'ModelA' 6 | modelB = 'ModelB' 7 | model = modelB 8 | weights = "weights" 9 | gradients = "gradients" 10 | report_dir = "reports" 11 | res_dir = os.path.join('.outputs') 12 | param_path = "conf.json" 13 | 14 | def __init__(self): 15 | """Vars that we want to access statically, but also through a simple name space need redundant declaration""" 16 | self.modelA = self.modelA 17 | self.modelB = self.modelB 18 | self.model = self.model 19 | self.dcntrl = "decentralized" 20 | self.cntrl = "centralized" 21 | """ Federated Learning""" 22 | self.interfrl = "interfrl" # averages across the same environments from multiple platoons 23 | self.intrafrl = "intrafrl" # averages all envirnoments within a platoon, no sharing across platoons 24 | self.nofrl = "normal" 25 | self.fed_method = self.nofrl 26 | self.framework = self.dcntrl 27 | self.fed_enabled = (self.fed_method == self.interfrl or self.fed_method == self.intrafrl) and (self.framework == self.dcntrl) 28 | self.weighted_average_enabled = True 29 | self.weighted_window = 10 # window for calculating the average cumulative reward weight (looks backwards for the given amount of episodes) 30 | self.fed_update_count = 1 # number of episodes between federated averaging updates 31 | self.fed_cutoff_ratio = 1.0 # the ratio to toral number of episodes at which FRL is cutoff 32 | self.fed_update_delay = 0.1 # the time in second between updates during a training episode for FRL. 33 | self.res_dir = self.res_dir 34 | self.report_dir = "reports" 35 | self.param_path = self.param_path 36 | self.aggregation_method = self.gradients 37 | self.intra_directional_averaging=False 38 | """Environment""" 39 | self.num_platoons = 1 # the number of platoons for training and simulation 40 | self.pl_size = 2 # the number of following vehicles in the platoon. 41 | self.pl_leader_reset_a = 0 # max initial acceleration of the platoon leader (used in the calculation for \dot{a_{i-1}}) (bound for uniform, std_dev for normal) 42 | self.reset_max_u = 0.100 # max initial control input of the platoon leader (used in the calculation for \dot{a_{i-1}}, (bound for uniform, std_dev for normal) 43 | 44 | self.pl_leader_tau = 0.1 45 | self.exact = 'exact' 46 | self.euler = 'euler' 47 | self.method = self.euler 48 | 49 | self.timegap = 1.0 50 | self.dyn_coeff = 0.1 51 | 52 | self.reward_ep_coeff = 0.4 53 | self.reward_ev_coeff = 0.2 54 | self.reward_u_coeff = 0.2 55 | self.reward_jerk_coeff = 0.2 56 | 57 | self.max_ep = 20 58 | self.max_ev = 20 59 | 60 | self.reset_ep_max = 1.5 # max position error upon environment reset 61 | self.reset_max_ev = 1.5 # max velocity error upon environment reset 62 | self.reset_max_a = 0.05 # max accel of a vehicle upon reset 63 | 64 | self.reset_ep_eval_max = 1 # the position error upon initialization of the evaluator 65 | self.reset_ev_eval_max = 1 # the position error upon initialization of the evaluator 66 | self.reset_a_eval_max = 0.03 # the position error upon initialization of the evaluator 67 | 68 | self.action_high =2.5 69 | self.action_low = -2.5 70 | 71 | self.re_scalar = 1 # reward scale 72 | self.terminal_reward = 0.5 73 | 74 | """Trainer""" 75 | self.can_terminate = True 76 | self.random_seed = 1 77 | self.evaluation_seed = 6 78 | 79 | self.normal = 'normal' 80 | self.uniform = 'uniform' 81 | self.rand_gen = self.normal # which type of random numbers to use. 82 | self.rand_states = True # whether or not to use random initial states for each environment reset. 83 | 84 | self.total_time_steps = 1000000 85 | 86 | self.sample_rate = 0.1 87 | self.episode_sim_time = 60 # simulation time for a training episode 88 | self.steps_per_episode = int(self.episode_sim_time/self.sample_rate) 89 | self.fed_update_delay_steps = int(self.fed_update_delay/self.sample_rate) 90 | 91 | self.number_of_episodes = int(self.total_time_steps/self.steps_per_episode) 92 | 93 | self.gamma = 0.99 # Discount factor for future rewards 94 | self.fed_cutoff_episode = int(self.fed_cutoff_ratio * self.number_of_episodes) 95 | self.centrl_hidd_mult = 1.2 96 | 97 | self.reward_averaging_window = 40 98 | # Learning rate for actor-critic models 99 | self.critic_lr = 0.0005 100 | self.actor_lr = 0.00005 101 | self.std_dev = 0.02 # orhnstein gaussian noise standard dev 102 | self.theta = 0.15 # orhstein theta 103 | self.ou_dt = 1e-2 # ornstein dt 104 | self.tau = 0.001 # target network update coeff 105 | 106 | self.batch_size=64 107 | self.buffer_size=100000 108 | self.show_env=False 109 | """Evaluator""" 110 | self.manual_timestep_override = 100 111 | """Models""" 112 | self.actor_layer1_size=256 113 | self.actor_layer2_size=128 114 | 115 | self.critic_layer1_size=256 116 | self.critic_act_layer_size = 48 117 | self.critic_layer2_size=128 118 | """Directories""" 119 | self.img_tag = "%s_%s" 120 | self.actor_fname = f'actor{self.img_tag}.h5' 121 | self.actor_picname = f'actor{self.img_tag}.svg' 122 | self.actor_weights = f'actor_weights{self.img_tag}.h5' 123 | self.critic_fname = f'critic{self.img_tag}.h5' 124 | self.critic_picname = f'critic{self.img_tag}.svg' 125 | self.critic_weights = f'critic_weights{self.img_tag}.h5' 126 | self.t_actor_fname = f'target_actor{self.img_tag}.h5' 127 | self.t_actor_picname = f'target_actor{self.img_tag}.svg' 128 | self.t_actor_weights = f'target_actor_weights{self.img_tag}.h5' 129 | self.t_critic_fname = f'target_critic{self.img_tag}.h5' 130 | self.t_critic_picname = f'target_critic{self.img_tag}.svg' 131 | self.t_critic_weights = f'target_critic_weights{self.img_tag}.h5' 132 | 133 | self.pl_tag = "_p%s" 134 | self.seed_tag = "_seed%s" 135 | self.fig_path = f"reward_curve{self.pl_tag}.svg" 136 | self.avg_ep_reward_path = f"avg_ep_reward_{self.seed_tag}.csv" 137 | self.ep_reward_path = f"ep_reward_{self.seed_tag}.csv" 138 | self.frl_weighted_avg_parameters_path = f"frl_weightings_{self.seed_tag}.csv" 139 | self.zerofig_name = "zero" 140 | self.guasfig_name = "guassian" 141 | self.stepfig_name = "step" 142 | self.rampfig_name = "ramp" 143 | 144 | self.dirs = [self.res_dir, self.report_dir] 145 | 146 | """Logging""" 147 | self.log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' 148 | self.log_date_fmt = "%y-%m-%d %H:%M:%S" 149 | 150 | """Reporting""" 151 | self.pl_rew_for_simulation = 0 152 | self.pl_rews_for_simulations = [] 153 | self.index_col = "timestamp" 154 | self.timestamp = None 155 | self.drop_keys_in_report = ["fed_enabled", "modelA", "modelB", "dcntrl", "cntrl", "interfrl", "intrafrl", "hfrl", "vfrl", "nofrl", "res_dir", "report_dir", "param_path", "euler", 156 | "exact", "normal", "uniform", "show_env", "actor_fname", "actor_picname", "actor_weights", "critic_fname", "critic_picname", 157 | "critic_weights", "t_actor_fname", "t_actor_picname", "t_actor_weights", "t_critic_fname", "t_critic_picname", 158 | "t_critic_weights", "fig_path", "zerofig_name", "guasfig_name", "stepfig_name", "rampfig_name", "dirs", 159 | "log_format", "log_date_fmt", "drop_keys_in_report", "index_col", "param_descs", "img_tag", "pl_rews_for_simulations", "pl_tag"] 160 | 161 | self.param_descs = {"timestamp" : "The time at which the experiment was run", 162 | "model" : "Whether a 3 (ModelA) of 4 (ModelB) state model", 163 | "fed_method" : "Type of federated learning used", 164 | "framework" : "Decentralized or centralized", 165 | "weighted_window" : "number of episodes to consider for calculating the weight for averaging", 166 | "fed_update_count" : "The number of episodes between a federated averaging update", 167 | "fed_update_delay" : "the time in second between updates during a training episode for FRL", 168 | "fed_cutoff_ratio" : "The percent of all episodes before ending federated updates", 169 | "num_platoons" : "The number of platoons", 170 | "pl_size" : "The size of the platoon", 171 | "pl_leader_reset_a" : "The mean value of the platoon leader acceleration upon environment reset", 172 | "reset_max_u" : "The mean value of the platoon leader control input upon environment reset", 173 | "pl_leader_tau" : "Vehicle dynamics coefficient", 174 | "method" : "Exact or euler discretization", 175 | "timegap" : "Constant time headway CACC time gap", 176 | "dyn_coeff" : "Dynamic coefficients for the following vehicles", 177 | "reward_ev_coeff" : "Coefficient of velocity difference in reward equation", 178 | "reward_u_coeff" : "Coefficient of control input in reward equation", 179 | "max_ep" : "Maximum position error in followers before episode termination", 180 | "max_ev" : "Maximum position error in followers before episode termination", 181 | "reset_ep_max" : "Maximum position error in followers upon environment reset", 182 | "reset_max_ev" : "Maximum velocity error in followers upon environment reset", 183 | "reset_max_a" : "Maximum acceleration upon environment reset", 184 | "reset_ep_eval_max" : "Position error upon initialization of the evaluator", 185 | "reset_ev_eval_max" : "Velocity error upon initialization of the evaluator", 186 | "reset_a_eval_max" : "Accel error upon initialization of the evaluator", 187 | "action_high" : "Upper bound on action space for the environment", 188 | "action_low" : "Lower bound on action space for the environment", 189 | "re_scalar" : "Reward scaling coefficient", 190 | "terminal_reward" : "Reward assigned upon early termination", 191 | "can_terminate" : "Whether the environment is allowed to terminate early", 192 | "random_seed" : "Seed for the experiment across all python libraries", 193 | "evaluation_seed" : "Seed used during final simulation", 194 | "rand_gen" : "Either uniform or normal for random number generation", 195 | "rand_states" : "whether or not to use random initial states for each environment reset", 196 | "total_time_steps" : "The number of timesteps to train on", 197 | "sample_rate" : "The sample rate of the system", 198 | "episode_sim_time" : "The time in seconds to run simulations for", 199 | "steps_per_episode" : "The number of steps per episode", 200 | "fed_update_delay_steps" : "The number of steps in an episode between a FRL update", 201 | "number_of_episodes" : "The total number of episodes for training", 202 | "gamma" : "The discounted reward coefficient", 203 | "fed_cutoff_episode" : "The episode at which federated learning terminates", 204 | "centrl_hidd_mult" : "Multiplier for number of nodes across hidden layers", 205 | "critic_lr" : "Learning rate for critic network", 206 | "actor_lr" : "Learning rate for actor network", 207 | "std_dev" : "Standard deviation used in OU noise", 208 | "theta" : "Theta value for OU noise", 209 | "ou_dt" : "Sample rate for OU noise", 210 | "tau" : "Target network update parameter", 211 | "batch_size" : "Batch size for sampling replay buffer", 212 | "buffer_size" : "Size of the replay buffer", 213 | "pl_rews_for_simulations" : "Stores all platoon's rewards after the final simulation", 214 | "pl_rew_for_simulation" : "The average of the platoon rewards after the final simulation", 215 | "actor_layer1_size" : "Number of nodes in actor's first hidden layer", 216 | "actor_layer2_size" : "Number of nodes in actor's second hidden layer", 217 | "critic_layer1_size" : "Number of nodes in critic's first hidden layer", 218 | "critic_act_layer_size" : "Number of nodes in the critic's action layer", 219 | "critic_layer2_size" : "Number of nodes in critics's second hidden layer"} 220 | 221 | if __name__=="__main__": 222 | import util 223 | conf = Config() 224 | 225 | util.config_writer("conf.json", conf) 226 | 227 | -------------------------------------------------------------------------------- /src/environment.py: -------------------------------------------------------------------------------- 1 | import random 2 | import numpy as np 3 | from src import config, util 4 | import logging 5 | 6 | log = logging.getLogger(__name__) 7 | 8 | class Platoon: 9 | def __init__(self, length, config: config.Config, pl_idx, rand_states=True, evaluator_states_enabled=False): 10 | """Initialize the platoon 11 | 12 | Args: 13 | length (int): the length of the platoon. Note that the leader parameters 14 | such as tau and a_i are passed into the first vehicle 'FOLLOWER' 15 | config (Config): the global configuration class 16 | rand_states (Boolean) : whether the platoon will use random states, or the max values from the config on reset. 17 | """ 18 | self.pl_idx = pl_idx 19 | log.info(f"=== INITIALIZING PLATOON {self.pl_idx} ===") 20 | self.config = config 21 | 22 | self.length = length 23 | self.followers = [] 24 | self.front_accel = util.get_random_val(self.config.rand_gen, self.config.pl_leader_reset_a, std_dev=self.config.pl_leader_reset_a, config=self.config) 25 | 26 | self.rand_states = rand_states 27 | self.evaluator_states_enabled = evaluator_states_enabled 28 | 29 | self.state_lbs = {0: "$e_{pi,k}$", 1 : "$e_{vi,k}$", 2 : "$a_{i,k}$", 3 : "$a_{i-1,k}$"} 30 | self.jerk_lb = "jerk" 31 | self.exog_lbl = '$u_{i,k}$' 32 | self.front_u = util.get_random_val(self.config.rand_gen, self.config.reset_max_u, std_dev=self.config.reset_max_u, config=self.config) 33 | self.pl_leader_tau = self.config.pl_leader_tau 34 | 35 | if self.config.framework == self.config.cntrl: 36 | self.multiplier = self.length 37 | self.hidden_multiplier = self.config.centrl_hidd_mult 38 | self.num_models = 1 39 | else: 40 | self.multiplier = 1 41 | self.hidden_multiplier = 1 42 | self.num_models = self.length 43 | 44 | self.def_num_actions = 1 # useful for plotting 45 | self.num_actions = self.def_num_actions * self.multiplier 46 | 47 | if self.config.model == self.config.modelA: 48 | self.def_num_states = 3 # useful for tracking the states numbers in the followers 49 | self.num_states = self.def_num_states * self.multiplier 50 | else: 51 | self.def_num_states = 4 52 | self.num_states = self.def_num_states * self.multiplier 53 | 54 | self.number_of_reward_components = Vehicle.number_of_reward_components 55 | for i in range(0, length): 56 | if i == 0: 57 | self.followers.append(Vehicle(i, self.config, self.pl_leader_tau, self.front_accel, 58 | num_states=self.num_states, 59 | num_actions=self.num_actions, rand_states=self.rand_states, evaluator_states_enabled=self.evaluator_states_enabled)) 60 | else: 61 | self.followers.append(Vehicle(i, self.config, self.followers[i-1].tau, self.followers[i-1].x[2], 62 | num_states=self.num_states, num_actions=self.num_actions, rand_states=self.rand_states, 63 | evaluator_states_enabled=self.evaluator_states_enabled)) # chain tau and accel in state 64 | 65 | # Rendering attr 66 | self.viewer = None 67 | self.screen_width = 600 * self.num_models 68 | self.screen_height = 550 69 | self.max_position = 1.2*self.config.max_ep*self.num_models 70 | self.min_position = -self.max_position 71 | self.world_width = self.max_position - self.min_position 72 | self.scale = self.screen_width / self.world_width 73 | self.floor = 0 74 | self.followers_trans_lst = [] 75 | self.goal_trans_lst = [] 76 | self.colors = [[0,0,0], # black 77 | [255, 0, 0], # red 78 | [0,255,0], # green 79 | [0,0,255], # blue 80 | [255,0,255], # magenta 81 | [0,255,255] # cyan 82 | ] 83 | 84 | if self.length > len(self.colors): 85 | raise ValueError(f"Platoon of length {self.length}, but only have {len(self.colors)}! Add more colors in environment to work with larger platoons in rendering!") 86 | 87 | def render(self, mode="human"): 88 | output = "" 89 | if self.viewer is None: 90 | self._initialize_render() 91 | 92 | cumulative_desired_headway = 0 93 | cumulative_headway = 0 94 | for f, f_trans, g_trans in zip(self.followers, self.followers_trans_lst, self.goal_trans_lst): 95 | output += f"{f.render(str_form=True)} <~ \t\t" 96 | cumulative_desired_headway -= f.desired_headway 97 | cumulative_headway -= f.headway 98 | self.update_rendering(f, f_trans, g_trans, cumulative_desired_headway, cumulative_headway, mode=mode) 99 | 100 | print(output, end="\r", flush=True) 101 | 102 | def _initialize_render(self): 103 | from gym.envs.classic_control import rendering 104 | self.viewer = rendering.Viewer(self.screen_width, self.screen_height) 105 | 106 | # make track 107 | res = 100 108 | xs = np.linspace(self.min_position, self.max_position, res) 109 | ys = np.linspace(self.floor, self.floor, res) 110 | xys = list(zip((xs - self.min_position) * self.scale, ys * self.scale)) 111 | track_height = 0.25 * self.scale 112 | self.track = rendering.make_polyline(xys) 113 | self.track.set_linewidth(track_height) 114 | self.viewer.add_geom(self.track) 115 | 116 | clearance = track_height 117 | 118 | # add hashmarks 119 | for mtr in range(0, int(self.world_width)): 120 | hash_width = mtr * self.scale 121 | hash_height = track_height * 1.2 122 | distance_hash = rendering.Line((hash_width, self.floor), (hash_width, hash_height)) 123 | self.viewer.add_geom(distance_hash) 124 | 125 | for i, follower in enumerate(self.followers): 126 | # add a car 127 | color_r = self.colors[i][0] 128 | color_g = self.colors[i][1] 129 | color_b = self.colors[i][2] 130 | wheel_size = (follower.height / 3)*self.scale 131 | car_clearance = track_height + wheel_size 132 | 133 | l, r, t, b = -(follower.length / 2) * self.scale, (follower.length / 2) * self.scale, follower.height * self.scale, 0 * self.scale 134 | car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) 135 | car.add_attr(rendering.Transform(translation=(0, car_clearance))) 136 | car.set_color(color_r, color_g, color_b) 137 | follower_trans = rendering.Transform() 138 | car.add_attr(follower_trans) 139 | self.viewer.add_geom(car) 140 | frontwheel = rendering.make_circle(wheel_size) 141 | frontwheel.set_color(0.5, 0.5, 0.5) 142 | frontwheel.add_attr( 143 | rendering.Transform(translation=((follower.length / 4)*self.scale, car_clearance)) 144 | ) 145 | frontwheel.add_attr(follower_trans) 146 | self.viewer.add_geom(frontwheel) 147 | backwheel = rendering.make_circle(wheel_size) 148 | backwheel.add_attr( 149 | rendering.Transform(translation=(-(follower.length / 4) * self.scale, car_clearance)) 150 | ) 151 | backwheel.add_attr(follower_trans) 152 | backwheel.set_color(0.5, 0.5, 0.5) 153 | self.viewer.add_geom(backwheel) 154 | 155 | self.followers_trans_lst.append(follower_trans) 156 | 157 | # add a flag to represent the desired headway 158 | flagpole_height = follower.height*2.0 * self.scale 159 | flagx = 0 * self.scale 160 | flagy1 = self.floor * self.scale 161 | flagy2 = flagy1 + flagpole_height 162 | flagpole = rendering.Line((flagx, flagy1), (flagx, flagy2)) 163 | flagpole.add_attr(rendering.Transform(translation=(0, clearance))) 164 | flagpole_trans = rendering.Transform() 165 | flagpole.add_attr(flagpole_trans) 166 | self.viewer.add_geom(flagpole) 167 | 168 | flag_banner_top = 0.4 * self.scale 169 | flag_banner_bottom = 0.3 * self.scale 170 | flag_banner_width = 0.8 * self.scale 171 | flag = rendering.FilledPolygon( 172 | [(flagx, flagy2), (flagx, flagy2 - flag_banner_top), (flagx + flag_banner_width, flagy2 - flag_banner_bottom)] 173 | ) 174 | flag.set_color(color_r, color_g, color_b) 175 | flag.add_attr( 176 | rendering.Transform(translation=(0, clearance)) 177 | ) 178 | flag.add_attr(flagpole_trans) 179 | self.viewer.add_geom(flag) 180 | self.goal_trans_lst.append(flagpole_trans) 181 | 182 | def update_rendering(self, f, f_trans, g_trans, desired_headway, headway, mode): 183 | """Update the translational offset for a following vehicle 184 | 185 | Args: 186 | f (environment.Vehicle): the vehicle 187 | f_trans (rendering.Transform): the transform object for the following car 188 | g_trans (rendering.Transfrom): the transform object for the following car goal 189 | mode (str): the type to render based on openAI gym rendering types of human or rgb_array 190 | 191 | Returns: 192 | bool, None: see viewer.render 193 | """ 194 | f_trans.set_translation( 195 | (headway - self.min_position) * self.scale, self.floor * self.scale 196 | ) 197 | 198 | g_trans.set_translation( 199 | (desired_headway - self.min_position) * self.scale, self.floor * self.scale 200 | ) 201 | 202 | return self.viewer.render(return_rgb_array= mode == "rgb_array") 203 | 204 | def close_render(self): 205 | if self.viewer is not None: 206 | self.viewer.close() 207 | self.viewer = None 208 | 209 | def step(self, actions, leader_exog=None, debug_mode=False): 210 | """Advances the environment one step 211 | 212 | Args: 213 | actions (list): list of actions from the DNN model 214 | leader_exog (float): the exogenous value for the platoon leader 215 | debug_mode (bool): whether to run debug mode 216 | 217 | Returns: 218 | list, float : a list of states calculated for the platoon, 219 | the platoon reward 220 | """ 221 | states = [] 222 | rewards = [] 223 | terminals = [] 224 | for i, action in enumerate(actions): 225 | follower = self.followers[i] 226 | 227 | exog = self.get_exogenous_info(i, leader_exog) 228 | 229 | f_state, f_reward, f_terminal = follower.step(action, exog, debug_mode) 230 | states.append(f_state) 231 | rewards.append(f_reward) 232 | terminals.append(f_terminal) 233 | 234 | if self.config.framework == self.config.cntrl: 235 | states = [list(np.concatenate(states).flat)] 236 | rewards = [self.get_reward(states, rewards)] 237 | 238 | platoon_done = True if True in terminals else False 239 | if platoon_done: 240 | log.info(f"Platoon [{self.pl_idx}] is terminating as a vehicle reached terminal state!") 241 | return states, rewards, platoon_done 242 | 243 | def get_jerk(self): 244 | """ 245 | Get the jerk vector of the platoon from vehicle [0.. 1 .. n] 246 | """ 247 | jerks = [] 248 | for i in range(self.length): 249 | jerks.append([self.followers[i].jerk]) 250 | 251 | return jerks 252 | 253 | def get_exogenous_info(self, idx, leader_exog): 254 | """ 255 | Get the 'exogenous' information for the system. For 256 | 'Model A' this would be the leading vehicle acceleration. For 'Model B' .. use leader control input 'u'""" 257 | if self.config.model == self.config.modelB: 258 | if idx == 0: 259 | exog = self.front_u if leader_exog == None else leader_exog 260 | else: 261 | exog = self.followers[idx-1].u # model B uses the control input, u as exogenous 262 | 263 | elif self.config.model == self.config.modelA: 264 | if idx == 0: 265 | exog = self.front_accel if leader_exog == None else leader_exog 266 | else: 267 | exog = self.followers[idx-1].x[2] # for model A use the accel of the leading vehicle as exogenous 268 | 269 | return exog 270 | 271 | def get_reward(self, states, rewards): 272 | """Calculates the platoons reward 273 | 274 | Args: 275 | states (list): the list of the states for all followers in platoon 276 | rewards (list): the list of rewards for all followers in platoon 277 | 278 | Returns: 279 | float : the reward of the platoon 280 | """ 281 | reward = (1/self.length)*sum(rewards) 282 | return reward 283 | 284 | def reset(self): 285 | states = [] 286 | self.front_accel = util.get_random_val(self.config.rand_gen, self.config.pl_leader_reset_a, std_dev=self.config.pl_leader_reset_a, config=self.config) 287 | 288 | for i in range(len(self.followers)): 289 | self.front_u = util.get_random_val(self.config.rand_gen, self.config.reset_max_u, std_dev=self.config.reset_max_u, config=self.config) 290 | 291 | if i == 0: 292 | follower_st = self.followers[i].reset(self.front_accel) 293 | else: 294 | follower_st = self.followers[i].reset(self.followers[i-1].x[2]) 295 | 296 | states.append(follower_st) 297 | 298 | if self.config.framework == self.config.cntrl: 299 | states = [list(np.concatenate(states).flat)] 300 | 301 | return states 302 | 303 | 304 | class Vehicle: 305 | """Vehicle class based on constant time headway modeling 306 | Model A and B are functionally the same, just the number of states is only 3 for model A. This means any model implementing this environment should have an input dimension equal to the self.num_states attribute 307 | Attributes: 308 | h (float) : the desired time gap (s) 309 | idx (int) : the integer id of the vehicle 310 | T (float) : sample rate 311 | tau (float) : vehicle accel dynamics coefficient 312 | tau_lead (float) : leading vehicle accell dynamics coeff 313 | num_states (int) : number of states in the model 314 | num_actions (int) : number of actions in the model 315 | a (float) : epi stability constant 316 | b (float) : evi stability constant 317 | x (np.array) : the state of the system (control error ep, 318 | control error ev, vehicle acceleration a) 319 | A (np.array) : system matrix 320 | B (np.array) : system matrix 321 | C (np.array) : system matrix 322 | config (Config) : configuration class 323 | """ 324 | # indicate the number of variables in the reward for plotting 325 | number_of_reward_components = 4 326 | def __init__(self, idx, config: config.Config, tau_lead=None, a_lead = None, num_states = None, num_actions = None, rand_states=True, 327 | evaluator_states_enabled=True): 328 | """constructor - r, h, L and tau referenced from 329 | https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7146426/ 330 | b,c taken from https://www.merl.com/publications/docs/TR2019-142.pdf 331 | Arguments: 332 | idx (integer) : the vehicle's index in the platoon 333 | config (config.Config) : the configuration class 334 | tau_lead (float, optional) : the vehicle dynamics coefficent of the leading vehicle in the platoon 335 | a_lead (float, optional) : the acceleration of the leading vehicle in the platoon 336 | """ 337 | log.info(f"=== Inititializing Vehicle {idx}===") 338 | self.config = config 339 | self.step_count = 0 340 | 341 | self.idx = idx 342 | self.h = self.config.timegap 343 | self.stand_still = 8 # standstill distance (r) 344 | self.height = 1.5 # height of the vehicle 345 | self.length = 2.5 # length of the vehicle 346 | self.T = self.config.sample_rate 347 | self.tau = self.config.dyn_coeff 348 | self.tau_lead = tau_lead 349 | 350 | self.a = self.config.reward_ep_coeff 351 | self.b = self.config.reward_ev_coeff 352 | self.c = self.config.reward_u_coeff 353 | self.d = self.config.reward_jerk_coeff 354 | 355 | self.max_ep = self.config.max_ep # max ep error before environment returns terminate = True 356 | self.max_ev = self.config.max_ev # max ev error before environment returns terminate = True 357 | self.max_a = self.config.action_high # map a is limited by the action as the action is the acceleration. 358 | 359 | self.reset_ep_max = self.config.reset_ep_max # used as the max +/- value when generating new ep on reset 360 | self.reset_max_ev = self.config.reset_max_ev # max +/- value when generating new ev on reset 361 | self.reset_max_a = self.config.reset_max_a # max +/- value for accel on reset 362 | 363 | self.evaluator_states_enabled = evaluator_states_enabled 364 | self.reset_ep_eval_max = self.config.reset_ep_eval_max 365 | self.reset_ev_eval_max = self.config.reset_ev_eval_max 366 | self.reset_a_eval_max = self.config.reset_a_eval_max 367 | 368 | self.reward = 0 369 | self.u = 0 # the input to the system 370 | self.exog = 0 371 | 372 | self.action_high = self.config.action_high 373 | self.action_low = self.config.action_low 374 | 375 | self.num_states = num_states 376 | self.num_actions = num_actions 377 | 378 | self.rand_states = rand_states 379 | 380 | self.num_actions = 1 381 | self.cumulative_accel = 0 382 | self.velocity = 0 383 | self.desired_headway = 0 384 | self.headway = 0 385 | self.reset(a_lead) # initializes the states 386 | 387 | """ Defining the system matrices """ 388 | self.set_system_matrices(self.config.method) 389 | 390 | def set_system_matrices(self, method): 391 | e = np.exp(-self.T/self.tau) 392 | e_lead = np.exp(-self.T/self.tau_lead) 393 | if method == self.config.euler: 394 | print("Using Euler Discretization.") 395 | self.A = np.array( [ [1, self.T, -self.h*self.T, 0], 396 | [0, 1, -self.T, self.T], 397 | [0, 0, 1 -(self.T/self.tau), 0], 398 | [0, 0, 0 , 1 -(self.T/self.tau_lead)]]) 399 | 400 | self.B = np.array( [0, 401 | 0, 402 | self.T/self.tau, 403 | 0]) 404 | 405 | self.C = np.array( [0, 406 | 0, 407 | 0, 408 | self.T/self.tau_lead]) 409 | 410 | elif method == self.config.exact: 411 | log.info("Using Exact Discretization.") 412 | A_13 = - self.h * self.tau + self.h * self.tau * e \ 413 | - self.tau * self.T + self.tau**2 - (self.tau ** 2) * e 414 | 415 | A_14 = self.tau_lead * self.T - self.tau_lead ** 2 \ 416 | + (self.tau_lead ** 2) * e_lead 417 | 418 | A_23 = - self.tau + self.tau * e 419 | 420 | A_24 = self.tau_lead - self.tau_lead * e_lead 421 | 422 | self.A = np.array( [ [1, self.T, A_13, A_14], 423 | [0, 1 , A_23, A_24], 424 | [0, 0 , e , 0 ], 425 | [0, 0 , 0 , e_lead]]) 426 | 427 | B_11 = - self.h * self.T + self.h * self.tau * e \ 428 | - self.h * self.tau - (self.T ** 2) / 2 + self.tau * self.T \ 429 | + (self.tau ** 2) * e - self.tau ** 2 430 | 431 | B_21 = - self.T - self.tau * e + self.tau 432 | 433 | self.B = np.array([B_11, 434 | B_21, 435 | -e + 1, 436 | 0]) 437 | 438 | C_11 = (self.T ** 2)/2 - self.tau_lead * self.T \ 439 | - (self.tau_lead ** 2) * e_lead + self.tau_lead ** 2 440 | C_21 = self.T + self.tau_lead * e_lead - self.tau_lead 441 | 442 | self.C = np.array([C_11, 443 | C_21, 444 | 0, 445 | -e_lead + 1]) 446 | 447 | log.info(" --- Vehicle %s Initialized System Matrices --- " % (self.idx)) 448 | log.info("A Matrix: %s" % (self.A)) 449 | log.info("B Matrix: %s" % (self.B)) 450 | log.info("C Matrix: %s" % (self.C)) 451 | self.print_hyps(output="log") 452 | 453 | def render(self, str_form=False): 454 | output = f"| v[{self.idx}] -- x: {np.round(self.x, 2)}, r: {round(self.reward, 2)}, u: {round(self.u, 2)}, exog: {round(self.exog, 2)}, vel: {round(self.velocity, 2)} -- |" 455 | if str_form == True: 456 | return output 457 | else: 458 | print(output, end='\r', flush=True) 459 | 460 | def step(self, u, exog_info, debug_mode=False): 461 | """advances the vehicle model by one timestep 462 | 463 | Args: 464 | u (float): the action to take 465 | exog_info (float): the exogenous information given to the vehicle 466 | prev_a (float) : the previous acceleration for the vehicle 467 | """ 468 | self.step_count +=1 469 | terminal = False 470 | self.u = u 471 | self.exog = exog_info 472 | 473 | norm_ep = abs(self.x[0]) / self.max_ep 474 | norm_ev = abs(self.x[1]) / self.max_ev 475 | norm_u = abs(self.u) / abs(self.action_high) 476 | n_jerk = abs(self.x[2] - self.prev_x[2]) / (2 * self.max_a) 477 | self.jerk = (self.x[2] - self.prev_x[2]) / (self.T) 478 | 479 | if debug_mode: 480 | print("====__ Vehicle %s __====" % (self.idx)) 481 | self.print_hyps(output="print") 482 | print("--- Evolution Equation Timestep %s ---" % (self.step_count)) 483 | print("\tA Matrix: ", self.A) 484 | print("\tB Matrix: ", self.B) 485 | print("\tC Matrix: ", self.C) 486 | print("\tx before evolution: ", self.x) 487 | print("\tprev_x : ", self.prev_x) 488 | print("--- Reward Equation ---") 489 | print("\ta: ", self.a) 490 | print("\tx[0]=epi: ", self.x[0]) 491 | print("\tb: ", self.b) 492 | print("\tx[1]=evi: ", self.x[1]) 493 | print("\tc: ", self.c) 494 | print("\tu: ", self.u) 495 | print("\td: ", self.d) 496 | print("\tn_jerk: ", n_jerk) 497 | print("\tjerk: ", self.jerk) 498 | print("\texog: ", self.exog) 499 | 500 | self.cumulative_accel += self.x[2] 501 | self.velocity = self.cumulative_accel * self.T # updates the velocity of the car. 502 | self.desired_headway = (self.stand_still + self.h * self.velocity) # updates the desired headway of the car 503 | self.headway = self.x[0] + self.desired_headway # updates the headway of the car. 504 | 505 | if (abs(self.x[0]) > self.config.max_ep or abs(self.x[1]) > self.config.max_ev) and self.config.can_terminate: 506 | terminal=True 507 | self.reward = self.config.terminal_reward * self.config.re_scalar 508 | log.info(f"Vehicle [{self.idx}] : Terminal state detected at (val, allowed) for ep = ({self.x[0]}, {self.config.max_ep}), ev = ({self.x[1]}, {self.config.max_ev}). Returning reward: {self.reward}") 509 | else: 510 | self.reward = (self.a*(norm_ep) + self.b*(norm_ev) + self.c*(norm_u) + self.d*(n_jerk)) * self.config.re_scalar 511 | 512 | self.prev_x = self.x 513 | self.x = self.A.dot(self.x) + self.B.dot(self.u) + self.C.dot(exog_info) # state update 514 | 515 | if debug_mode: 516 | print("\tx after evolution: ", self.x) 517 | 518 | return self.x[0:self.num_states], -self.reward, terminal # return only the elements that correspond to the state size. 519 | 520 | def reset(self, a_lead=None): 521 | """reset the vehicle environment 522 | 523 | Args: 524 | a_lead (float, optional): used in models where acceleration is chained throughout the vehicle state. Defaults to None. 525 | """ 526 | self.u = 0 527 | self.exog_info = 0 528 | self.step_count = 0 529 | self.cumulative_accel = 0 530 | self.desired_headway = 0 531 | self.headway = 0 532 | self.jerk = 0 533 | 534 | if self.evaluator_states_enabled: 535 | if self.rand_states: 536 | self.x = np.array([self.reset_ep_eval_max, # intial gap error (m) 537 | self.reset_ev_eval_max, # initial velocity error 538 | self.reset_a_eval_max, # initial accel of this vehicle 539 | a_lead]) # initial accel of leading vehicle 540 | else: 541 | self.x = np.array([self.reset_ep_max, # intial gap error (m) 542 | self.reset_max_ev, # initial velocity error 543 | self.reset_max_a, # initial accel of this vehicle 544 | a_lead]) # initial accel of leading vehicle 545 | else: 546 | if self.rand_states == True: 547 | self.x = np.array([util.get_random_val(self.config.rand_gen, self.reset_ep_max, std_dev=self.reset_ep_max, config=self.config), # intial gap error (m) 548 | util.get_random_val(self.config.rand_gen, self.reset_max_ev, std_dev=self.reset_max_ev, config=self.config), # initial velocity error 549 | util.get_random_val(self.config.rand_gen, self.reset_max_a, std_dev=self.reset_max_a, config=self.config), # initial accel of this vehicle 550 | a_lead]) # initial accel of leading vehicle 551 | else: 552 | self.x = np.array([self.reset_ep_max, # intial gap error (m) 553 | self.reset_max_ev, # initial velocity error 554 | self.reset_max_a, # initial accel of this vehicle 555 | a_lead]) # initial accel of leading vehicle 556 | 557 | self.prev_x = self.x 558 | 559 | return (self.x[0:self.num_states]) 560 | 561 | def set_state(self, state): 562 | self.x = state 563 | 564 | def print_hyps(self, output: str): 565 | """ 566 | Method for printing attributes for the class 567 | """ 568 | valid_output_opts = ["log", "print"] 569 | if output not in valid_output_opts: 570 | raise ValueError(f"Invalid parameter for 'output'. Choices are: {valid_output_opts}") 571 | 572 | hyp = " | ".join(( 573 | f"\tself.idx = {self.idx}", 574 | f"self.h = {self.h}", 575 | f"self.T = {self.T}", 576 | f"self.tau = {self.tau}", 577 | f"self.tau_lead = {self.tau_lead}\n\t", 578 | f"self.a = {self.a}", 579 | f"self.b = {self.b}", 580 | f"self.max_ep = {self.max_ep}", # max ep error before environment returns terminate = True 581 | f"self.max_ev = {self.max_ev}", # max ev error before environment returns terminate = True 582 | f"self.reset_ep_max = {self.reset_ep_max}\n\t", # used as the max +/- value when generating new ep on reset 583 | f"self.reset_max_ev = {self.reset_max_ev}", # max +/- value when generating new ev on reset 584 | f"self.reset_max_a = {self.reset_max_a}" # max +/- value for accel on reset 585 | )) 586 | if output == "log": 587 | log.info(f"---== Hyperparameters for vehicle {self.idx} ==---") 588 | log.info(hyp) 589 | elif output == "print": 590 | print(hyp) 591 | 592 | if __name__ == "__main__": 593 | pass 594 | # print("hello") 595 | # conf = config.Config() 596 | # pl = Platoon(2, conf) 597 | # # v = Vehicle(1, conf) 598 | # pl.render() 599 | # print("\npre reset") 600 | # print(pl.step([[2.5], [-1.5]])) 601 | # pl.render() 602 | # print("\npost") 603 | # print(pl.reset()) 604 | 605 | 606 | 607 | 608 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright © 2007 Free Software Foundation, Inc. 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 11 | 12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 15 | 16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 21 | 22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 23 | 24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 25 | 26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | TERMS AND CONDITIONS 30 | 0. Definitions. 31 | 32 | “This License” refers to version 3 of the GNU General Public License. 33 | 34 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 35 | 36 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 37 | 38 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 39 | 40 | A “covered work” means either the unmodified Program or a work based on the Program. 41 | 42 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 43 | 44 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 45 | 46 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 47 | 1. Source Code. 48 | 49 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 50 | 51 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 52 | 53 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 54 | 55 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 56 | 57 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 58 | 59 | The Corresponding Source for a work in source code form is that same work. 60 | 2. Basic Permissions. 61 | 62 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 63 | 64 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 65 | 66 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 67 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 68 | 69 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 70 | 71 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 72 | 4. Conveying Verbatim Copies. 73 | 74 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 75 | 76 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 77 | 5. Conveying Modified Source Versions. 78 | 79 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 80 | 81 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 82 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 83 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 84 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 85 | 86 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 87 | 6. Conveying Non-Source Forms. 88 | 89 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 90 | 91 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 92 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 93 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 94 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 95 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 96 | 97 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 98 | 99 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 100 | 101 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 102 | 103 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 104 | 105 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 106 | 107 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 108 | 7. Additional Terms. 109 | 110 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 111 | 112 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 113 | 114 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 115 | 116 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 117 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 118 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 119 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 120 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 121 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 122 | 123 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 124 | 125 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 126 | 127 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 128 | 8. Termination. 129 | 130 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 131 | 132 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 133 | 134 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 135 | 136 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 137 | 9. Acceptance Not Required for Having Copies. 138 | 139 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 140 | 10. Automatic Licensing of Downstream Recipients. 141 | 142 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 143 | 144 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 145 | 146 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 147 | 11. Patents. 148 | 149 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 150 | 151 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 152 | 153 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 154 | 155 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 156 | 157 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 158 | 159 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 160 | 161 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 162 | 163 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 164 | 12. No Surrender of Others' Freedom. 165 | 166 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 167 | 13. Use with the GNU Affero General Public License. 168 | 169 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 170 | 14. Revised Versions of this License. 171 | 172 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 173 | 174 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 175 | 176 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 177 | 178 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 179 | 15. Disclaimer of Warranty. 180 | 181 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 182 | 16. Limitation of Liability. 183 | 184 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 185 | 17. Interpretation of Sections 15 and 16. 186 | 187 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 188 | 189 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /workers/trainer.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | import pandas as pd 4 | from tensorflow.python.keras.backend import dtype, gradients 5 | from src import config, noise, replaybuffer, environment, util 6 | from agent import model, ddpgagent 7 | from workers import evaluator 8 | from src.server import federated 9 | from src.env import env 10 | 11 | import matplotlib.pyplot as plt 12 | import datetime 13 | import sys, os 14 | import logging 15 | 16 | log = logging.getLogger(__name__) 17 | 18 | class Trainer: 19 | def __init__(self, base_dir: str, timestamp: str, debug_enabled: bool, conf: config.Config) -> None: 20 | self.base_dir = base_dir 21 | self.timestamp = timestamp 22 | self.debug_enabled = debug_enabled 23 | self.conf = conf 24 | 25 | self.all_envs = [] 26 | self.all_ou_objects = [] 27 | self.all_actors = [] 28 | self.all_critics = [] 29 | self.all_target_actors = [] 30 | self.all_target_critics = [] 31 | self.all_actor_optimizers = [] 32 | self.all_critic_optimizers = [] 33 | self.all_ep_reward_lists = [] 34 | self.all_avg_reward_lists = [] 35 | self.all_rbuffers = [] 36 | 37 | self.all_rbuffers_filled = [] 38 | 39 | self.high_bound = self.conf.action_high 40 | self.low_bound = self.conf.action_low 41 | 42 | self.all_num_states = [] 43 | self.all_num_actions = [] 44 | 45 | self.num_models = self.conf.pl_size 46 | self.num_platoons = self.conf.num_platoons 47 | 48 | self.all_actor_grad_list = [] 49 | self.all_actor_weight_list = [] 50 | 51 | self.all_critic_grad_list = [] 52 | self.all_critic_weight_list = [] 53 | 54 | self.fed_weights = [] 55 | self.fed_weight_sums = [] 56 | self.all_fed_weights = [] 57 | self.all_fed_weight_sums = [] 58 | 59 | self.all_episodic_reward_counters = [] 60 | 61 | def initialize(self): 62 | log.info("=== Initializing Trainer ===") 63 | self.conf.timestamp = str(self.timestamp) 64 | self.conf.fed_enabled = is_fed_enabled(self.conf) 65 | 66 | if self.conf.fed_enabled: 67 | self.fed_server = federated.Server('AVDDPG', self.debug_enabled) 68 | 69 | log.info(f"Total episodes: {self.conf.number_of_episodes}\nSteps per episode: {self.conf.steps_per_episode}") 70 | 71 | for p in range(self.num_platoons): 72 | log.info(f"--- Platoon {p+1} summary ---") 73 | env = environment.Platoon(self.conf.pl_size, self.conf, p, rand_states=self.conf.rand_states) 74 | self.all_envs.append(env) 75 | 76 | self.all_num_states.append(env.num_states) 77 | self.all_num_actions.append(env.num_actions) 78 | 79 | log.info(f"Number of models : {self.num_models}") 80 | log.info("Size of Model input -> {}".format(env.num_states)) 81 | log.info("Size of Model output -> {}".format(env.num_actions)) 82 | 83 | log.info("Max Value of Action -> {}".format(self.high_bound)) 84 | log.info("Min Value of Action -> {}".format(self.low_bound)) 85 | 86 | ou_objects = [] 87 | actors = [] 88 | critics = [] 89 | target_actors = [] 90 | target_critics = [] 91 | actor_optimizers = [] 92 | critic_optimizers = [] 93 | ep_reward_lists = [] 94 | avg_reward_lists = [] 95 | rbuffers = [] 96 | 97 | rbuffers_filled = [] 98 | fed_weight_lists = [] 99 | fed_weight_sum_lists = [] 100 | for i in range(self.num_models): 101 | ou_objects.append(noise.OUActionNoise(mean=np.zeros(1), config=self.conf)) 102 | actor = model.get_actor(env.num_states, env.num_actions, self.high_bound, seed_int=self.conf.random_seed, 103 | hidd_mult=env.hidden_multiplier, layer1_size=self.conf.actor_layer1_size, 104 | layer2_size=self.conf.actor_layer2_size) 105 | critic = model.get_critic(env.num_states, env.num_actions, hidd_mult=env.hidden_multiplier, 106 | layer1_size=self.conf.critic_layer1_size, 107 | layer2_size=self.conf.critic_layer2_size, 108 | action_layer_size=self.conf.critic_act_layer_size) 109 | 110 | target_actor = model.get_actor(env.num_states, env.num_actions, self.high_bound, seed_int=self.conf.random_seed, 111 | hidd_mult=env.hidden_multiplier, 112 | layer1_size=self.conf.actor_layer1_size, 113 | layer2_size=self.conf.actor_layer2_size) 114 | target_critic = model.get_critic(env.num_states, env.num_actions, hidd_mult=env.hidden_multiplier, 115 | layer1_size=self.conf.critic_layer1_size, 116 | layer2_size=self.conf.critic_layer2_size, 117 | action_layer_size=self.conf.critic_act_layer_size) 118 | 119 | 120 | # Making the weights equal initially 121 | if i == 0 and p == 0: 122 | log.info("Getting the initial weights to be used across all models in each platoon!") 123 | initial_actor_weights = actor.get_weights() 124 | initial_critic_weights = critic.get_weights() 125 | else: 126 | log.info(f"Initializing platoon idx [{p}] model [{i}] with the same weights as platoon [0] model [0]!") 127 | actor.set_weights(initial_actor_weights) 128 | critic.set_weights(initial_critic_weights) 129 | 130 | target_actor.set_weights(actor.get_weights()) 131 | target_critic.set_weights(critic.get_weights()) 132 | 133 | actors.append(actor) 134 | critics.append(critic) 135 | target_actors.append(target_actor) 136 | target_critics.append(target_critic) 137 | 138 | critic_optimizers.append(tf.keras.optimizers.Adam(self.conf.critic_lr)) 139 | actor_optimizers.append(tf.keras.optimizers.Adam(self.conf.actor_lr)) 140 | 141 | ep_reward_lists.append([]) 142 | avg_reward_lists.append([]) 143 | 144 | rbuffers.append(replaybuffer.ReplayBuffer(self.conf.buffer_size, 145 | self.conf.batch_size, 146 | env.num_states, 147 | env.num_actions, 148 | self.conf.pl_size, 149 | )) 150 | 151 | 152 | rbuffers_filled.append(False) 153 | fed_weight_lists.append([]) 154 | fed_weight_sum_lists.append([]) 155 | 156 | self.all_ou_objects.append(ou_objects) 157 | self.all_actors.append(actors) 158 | self.all_critics.append(critics) 159 | self.all_target_actors.append(target_actors) 160 | self.all_target_critics.append(target_critics) 161 | self.all_actor_optimizers.append(actor_optimizers) 162 | self.all_critic_optimizers.append(critic_optimizers) 163 | self.all_ep_reward_lists.append(ep_reward_lists) 164 | self.all_avg_reward_lists.append(avg_reward_lists) 165 | self.all_rbuffers.append(rbuffers) 166 | 167 | self.all_rbuffers_filled.append(rbuffers_filled) 168 | # note these are initialized normally, despite being frl specific. We want to store the data in a standard way for plotting 169 | # later. 170 | self.all_fed_weights.append(fed_weight_lists) 171 | self.all_fed_weight_sums.append(fed_weight_sum_lists) 172 | self.initialize_lists_for_federation() 173 | 174 | assert len(set(self.all_num_actions)) == 1 # make sure the action and state spaces are identical across the platoons 175 | assert len(set(self.all_num_states)) == 1 176 | 177 | self.num_actions = self.all_num_actions[0] 178 | self.num_states = self.all_num_states[0] 179 | self.actions = np.zeros((self.num_platoons, self.num_models, self.num_actions)) 180 | 181 | def initialize_lists_for_federation(self): 182 | """ Initialization for FRL methods 183 | Note that we iterate models, then platoons for HFRL. This is to save having to reshape the data later, as we wish to avg 184 | Gradients across the common vehicles in each platoon .. AVERAGE(platoon1_vehicle1:platoonN_vehicle1)""" 185 | 186 | if self.conf.fed_method == self.conf.interfrl: 187 | self.build_lists_for_federation(self.num_models, self.num_platoons) 188 | 189 | if self.conf.fed_method == self.conf.intrafrl: 190 | self.build_lists_for_federation(self.num_platoons, self.num_models) 191 | 192 | def build_lists_for_federation(self, range1, range2): 193 | """Build up the empty lists to use for federated learning 194 | 195 | Args: 196 | range1 (int): the number of first axis items for the system: for interfrl use the model 197 | range2 (int): the number of second axis items for the system: for intrafrl use the platoon 198 | """ 199 | log.info(f"{self.conf.fed_method} enabled (weighted = {self.conf.weighted_average_enabled}@{self.conf.weighted_window}), disabling at episode {self.conf.fed_cutoff_episode} with updates every {self.conf.fed_update_count} episodes!") 200 | for _ in range(range1): 201 | actor_grad_list = [] 202 | actor_weight_list = [] 203 | critic_grad_list = [] 204 | critic_weight_list = [] 205 | 206 | 207 | weight_factors = [] 208 | for _ in range(range2): 209 | actor_grad_list.append([]) 210 | actor_weight_list.append([]) 211 | critic_grad_list.append([]) 212 | critic_weight_list.append([]) 213 | weight_factors.append(0) 214 | 215 | 216 | self.all_actor_grad_list.append(actor_grad_list) 217 | self.all_actor_weight_list.append(actor_weight_list) 218 | self.all_critic_grad_list.append(critic_grad_list) 219 | self.all_critic_weight_list.append(critic_weight_list) 220 | self.fed_weights.append(weight_factors) 221 | 222 | 223 | def run(self): 224 | """ 225 | Run the trainer. 226 | Arguments: 227 | base_dir : the root folder for the DL experiment 228 | timestamp : the timestamp for the experiment 229 | tr_debug : whether to train in debug mode or not 230 | conf : the configuration class config.Config() 231 | """ 232 | for ep in range(self.conf.number_of_episodes): 233 | if is_valid_update_episode(self.conf, ep) and is_fed_enabled(self.conf): 234 | log.info(f"Applying federated averaging (weighted = {self.conf.weighted_average_enabled}@{self.conf.weighted_window}," 235 | + f"agg_method = {self.conf.aggregation_method}) at episode {ep} w/ delay {self.conf.fed_update_delay}s " 236 | + f"(every {self.conf.fed_update_delay_steps} steps).") 237 | 238 | if is_fed_enabled(self.conf) and ep == self.conf.fed_cutoff_episode + 1: 239 | log.info(f"Turned off federated learning as cutoff ratio [{self.conf.fed_cutoff_ratio}] ({self.conf.fed_cutoff_episode} episodes) passed at ep [{ep}]") 240 | 241 | if self.conf.fed_method == self.conf.intrafrl: 242 | log.info(f"Intrafrl directional averaging enabled={self.conf.intra_directional_averaging}") 243 | 244 | self.all_episodic_reward_counters = [] 245 | all_prev_states = [] 246 | for p in range(self.num_platoons): # reset environments and episodic reward counters 247 | states_on_reset = self.all_envs[p].reset() 248 | all_prev_states.append(states_on_reset) 249 | self.all_episodic_reward_counters.append(np.array([0]*self.num_models, dtype=np.float32)) 250 | 251 | for i in range(self.conf.steps_per_episode): 252 | all_states = [] 253 | all_rewards = [] 254 | all_terminals = [] 255 | for p in range(self.num_platoons): 256 | states, rewards, terminal = self.advance_environment(p, all_prev_states) 257 | 258 | all_states.append(states) 259 | all_rewards.append(rewards) 260 | all_terminals.append(terminal) 261 | 262 | self.train_all_models(all_rewards, all_states, all_prev_states, ep, i) 263 | if is_valid_step_for_federated_training_with_gradients(self.conf, ep, i): 264 | self.train_all_models_federated_gradients(i, ep) 265 | if is_valid_step_for_federated_training_with_weights(self.conf, ep, i): 266 | self.train_all_models_federated_weights(i, ep) 267 | 268 | if True in all_terminals: # break if any of the platoons have failed 269 | break 270 | 271 | all_prev_states = all_states 272 | 273 | self.update_reward_list(ep) 274 | 275 | self.close_renderings() 276 | self.generate_csvs() 277 | self.run_simulations() 278 | 279 | self.conf.pl_rew_for_simulation = np.average(self.conf.pl_rews_for_simulations) 280 | util.config_writer(os.path.join(self.base_dir, self.conf.param_path), self.conf) 281 | 282 | def advance_environment(self, p, all_prev_states): 283 | if self.conf.show_env: 284 | self.all_envs[p].render() 285 | 286 | for m in range(self.num_models): # iterate the list of actors here... passing in single state or concatanated for centrlz 287 | tf_prev_state = tf.expand_dims(tf.convert_to_tensor(all_prev_states[p][m]), 0) 288 | 289 | self.actions[p][m] = ddpgagent.policy(self.all_actors[p][m](tf_prev_state), self.all_ou_objects[p][m], self.low_bound, self.high_bound)[0] 290 | 291 | states, rewards, terminal = self.all_envs[p].step(self.actions[p].flatten(), 292 | util.get_random_val(self.conf.rand_gen, 293 | self.conf.reset_max_u, 294 | std_dev=self.conf.reset_max_u, 295 | config=self.conf), 296 | debug_mode=self.debug_enabled) 297 | if self.debug_enabled: 298 | user_input = input("Advance to the next timestep 'q' quits: ") 299 | if user_input == 'q': 300 | return 301 | 302 | return states, rewards, terminal 303 | 304 | def train_all_models(self, all_rewards, all_states, all_prev_states, training_episode, training_step): 305 | """Main method responsible for advancing the environment one timestep, aggregating parameters for FRL, 306 | and lastly performing local training steps 307 | Args: 308 | all_rewards (): [description] 309 | all_states ([type]): [description] 310 | all_prev_states ([type]): [description] 311 | training_episode ([type]): [description] 312 | training_step ([type]): [description] 313 | """ 314 | for p in range(self.num_platoons): 315 | for m in range(self.num_models): 316 | self.all_rbuffers[p][m].add((all_prev_states[p][m], 317 | self.actions[p][m], 318 | all_rewards[p][m], 319 | all_states[p][m])) 320 | 321 | self.all_episodic_reward_counters[p][m] += all_rewards[p][m] 322 | if self.all_rbuffers[p][m].buffer_counter > self.conf.batch_size: # first fill the buffer to the batch size 323 | self.all_rbuffers_filled[p][m] = True 324 | # train and update the actor critics 325 | critic_grad, actor_grad = self.learn(self.all_rbuffers[p][m], self.all_actors[p][m], self.all_critics[p][m], 326 | self.all_target_actors[p][m], self.all_target_critics[p][m]) 327 | actor_weights = self.all_actors[p][m].weights 328 | critic_weights = self.all_critics[p][m].weights 329 | # append gradients for avg'ing if federated enabled 330 | # compute weighted averaging factor 331 | if is_weighted_fed_enabled(self.conf, training_episode): 332 | frl_weighting_factor = self.get_weight(p, m) # calculate the metric for weighting. 333 | else: 334 | if self.debug_enabled: 335 | log.info(f"Waiting before applying weighted FRL, since averaging window is set to {self.conf.weighted_window} and thus episode must be >= {self.conf.weighted_window} prior to applying weighted averaging!") 336 | frl_weighting_factor = None 337 | 338 | if self.conf.fed_method == self.conf.interfrl: 339 | self.aggregate_params(m, p, frl_weighting_factor, training_episode, actor_grad, critic_grad, actor_weights, critic_weights) 340 | 341 | elif self.conf.fed_method == self.conf.intrafrl: 342 | self.aggregate_params(p, m, frl_weighting_factor, training_episode, actor_grad, critic_grad, actor_weights, critic_weights) 343 | 344 | # local updates should only occur when global updates do not occur 345 | if not is_fed_enabled(self.conf) or not is_valid_update_step(self.conf, training_step): 346 | if self.debug_enabled: 347 | log.info(f"Applying local training at episode [{training_episode}] step [{training_step}]!") 348 | self.all_critic_optimizers[p][m].apply_gradients(zip(critic_grad, self.all_critics[p][m].trainable_variables)) 349 | self.all_actor_optimizers[p][m].apply_gradients(zip(actor_grad, self.all_actors[p][m].trainable_variables)) 350 | 351 | # update the target networks 352 | tc_new_weights, ta_new_weights = ddpgagent.update_target(self.conf.tau, self.all_target_critics[p][m].weights, 353 | self.all_critics[p][m].weights, self.all_target_actors[p][m].weights, 354 | self.all_actors[p][m].weights) 355 | self.all_target_actors[p][m].set_weights(ta_new_weights) 356 | self.all_target_critics[p][m].set_weights(tc_new_weights) 357 | 358 | if is_weighted_fed_enabled(self.conf, training_episode): 359 | self.fed_weight_sums = tf.reduce_sum(self.fed_weights, axis=1) 360 | 361 | def aggregate_params(self, idx1: int, idx2: int, frl_weighting_factor, training_episode: str, actor_grad, critic_grad, actor_weights, critic_weights) -> None: 362 | """Aggregate the parameters using the appropriate federation method. 363 | 364 | Args: 365 | idx1 (int): the idx to use for the system. for interfrl, the idx of the model is passed in 366 | idx2 (int): the idx to use for the system. for interfrl, the idx of the system is passed in 367 | training_episode (str): the current training episode 368 | actor_grad (list): the gradients of the actor 369 | critic_grad (list): the gradients of the critic 370 | """ 371 | if is_weighted_fed_enabled(self.conf, training_episode): 372 | self.all_actor_grad_list[idx1][idx2] = self.compute_weighted_params(actor_grad, frl_weighting_factor) # get weighted actor params 373 | self.all_actor_weight_list[idx1][idx2] = self.compute_weighted_params(actor_weights, frl_weighting_factor) 374 | 375 | self.all_critic_grad_list[idx1][idx2] = self.compute_weighted_params(critic_grad, frl_weighting_factor) # get weighted critic params 376 | self.all_critic_weight_list[idx1][idx2] = self.compute_weighted_params(critic_weights, frl_weighting_factor) 377 | self.fed_weights[idx1][idx2] = frl_weighting_factor 378 | else: 379 | self.all_actor_grad_list[idx1][idx2] = actor_grad 380 | self.all_actor_weight_list[idx1][idx2] = actor_weights 381 | 382 | self.all_critic_grad_list[idx1][idx2] = critic_grad 383 | self.all_critic_weight_list[idx1][idx2] = critic_weights 384 | 385 | def get_weight(self, idx1, idx2): 386 | """The weight criteria for a single model's weight 387 | 388 | Args: 389 | idx1 (int): the first idx to use for the system, for interfrl the idx of the model is passed in 390 | idx2 (int): the second idx to use for the system, for interfrl the idx of the system is passed in 391 | 392 | Returns: 393 | float: the weight to use for performing weighted averaging 394 | """ 395 | return abs(1/np.mean(self.all_ep_reward_lists[idx1][idx2][-self.conf.weighted_window:]))# calculate the metric for weighting 396 | 397 | def compute_weighted_params(self, params, weight): 398 | return np.multiply(np.array(params, dtype=object), weight) 399 | 400 | def train_all_models_federated_gradients(self, i, training_episode): 401 | # apply FL aggregation method, and reapply gradients to models 402 | if self.are_all_rbuffers_filled(): 403 | if self.debug_enabled: 404 | log.info(f"Applying {self.conf.fed_method} using {self.conf.aggregation_method} at step {i}") 405 | if is_weighted_fed_enabled(self.conf, training_episode): 406 | log.info(f"using weighted sums {[self.fed_weight_sums]}") 407 | 408 | if is_weighted_fed_enabled(self.conf, training_episode): 409 | actor_avg_grads = self.fed_server.get_weighted_avg_params(self.all_actor_grad_list, self.fed_weight_sums) 410 | critic_avg_grads = self.fed_server.get_weighted_avg_params(self.all_critic_grad_list, self.fed_weight_sums) 411 | else: 412 | actor_avg_grads = self.fed_server.get_avg_params(self.all_actor_grad_list) 413 | critic_avg_grads = self.fed_server.get_avg_params(self.all_critic_grad_list) 414 | 415 | for p in range(self.num_platoons): 416 | for m in range(self.num_models): 417 | if self.conf.fed_method == self.conf.intrafrl and m == 0 and self.conf.intra_directional_averaging: 418 | continue # we dont bother averaging the first vehicle in intra as it is king. 419 | if self.conf.fed_method == self.conf.interfrl: 420 | self.all_actor_optimizers[p][m].apply_gradients(zip(actor_avg_grads[m], self.all_actors[p][m].trainable_variables)) 421 | self.all_critic_optimizers[p][m].apply_gradients(zip(critic_avg_grads[m], self.all_critics[p][m].trainable_variables)) 422 | 423 | elif self.conf.fed_method == self.conf.intrafrl: 424 | self.all_actor_optimizers[p][m].apply_gradients(zip(actor_avg_grads[p], self.all_actors[p][m].trainable_variables)) 425 | self.all_critic_optimizers[p][m].apply_gradients(zip(critic_avg_grads[p], self.all_critics[p][m].trainable_variables)) 426 | 427 | # update the target networks 428 | tc_new_weights, ta_new_weights = ddpgagent.update_target(self.conf.tau, self.all_target_critics[p][m].weights, self.all_critics[p][m].weights, 429 | self.all_target_actors[p][m].weights, self.all_actors[p][m].weights) 430 | self.all_target_actors[p][m].set_weights(ta_new_weights) 431 | self.all_target_critics[p][m].set_weights(tc_new_weights) 432 | 433 | def train_all_models_federated_weights(self, training_step, training_episode): 434 | # apply FL aggregation method, and reapply gradients to models 435 | if self.are_all_rbuffers_filled(): 436 | if self.debug_enabled: 437 | log.info(f"Applying {self.conf.fed_method} using {self.conf.aggregation_method} at step {training_step}!") 438 | if is_weighted_fed_enabled(self.conf, training_episode): 439 | log.info(f"Using weights {self.fed_weights} and weighted sums {self.fed_weight_sums}") 440 | 441 | if is_weighted_fed_enabled(self.conf, training_episode): 442 | actor_avg_weights = self.fed_server.get_weighted_avg_params(self.all_actor_weight_list, self.fed_weight_sums)[0] 443 | critic_avg_weights = self.fed_server.get_weighted_avg_params(self.all_critic_weight_list, self.fed_weight_sums)[0] 444 | else: 445 | actor_avg_weights = self.fed_server.get_avg_params(self.all_actor_weight_list)[0] 446 | critic_avg_weights = self.fed_server.get_avg_params(self.all_critic_weight_list)[0] 447 | 448 | for p in range(self.num_platoons): 449 | for m in range(self.num_models): 450 | if self.conf.fed_method == self.conf.intrafrl and m == 0 and self.conf.intra_directional_averaging: 451 | continue # we dont bother averaging the first vehicle in intra as it is king. 452 | self.all_actors[p][m].set_weights(actor_avg_weights) 453 | self.all_critics[p][m].set_weights(critic_avg_weights) 454 | 455 | self.all_target_actors[p][m].set_weights(actor_avg_weights) 456 | self.all_target_critics[p][m].set_weights(critic_avg_weights) 457 | 458 | def are_all_rbuffers_filled(self) -> bool: 459 | """Check if all the replay buffers are filled in the system 460 | 461 | Returns: 462 | bool: true if the replay buffers are filled 463 | """ 464 | for p in range(self.num_platoons): 465 | all_rbuffers_are_filled = True 466 | if False in self.all_rbuffers_filled[p]: # ensure rbuffers have filled for ALL the platoons 467 | all_rbuffers_are_filled = False 468 | break 469 | 470 | return all_rbuffers_are_filled 471 | 472 | def learn(self, rbuffer, actor_model, critic_model, 473 | target_actor, target_critic): 474 | """Trains and updates the actor critic network 475 | 476 | Args: 477 | config (Config): the config for the program 478 | rbuffer : the replay buffer object 479 | actor_model : the actor model network 480 | critic_model : the critic model network 481 | target_actor : the target actor network 482 | target_critic : the target critic network 483 | state_idx : used to locate the platoon data in the buffer 484 | 485 | Returns: 486 | : the updated gradients for the actor critic network 487 | """ 488 | # Sample replay buffer 489 | state_batch, action_batch, reward_batch, next_state_batch = rbuffer.sample() 490 | 491 | # Update and train the actor critic networks 492 | with tf.GradientTape() as tape: 493 | target_actions = target_actor(next_state_batch) 494 | y = reward_batch + self.conf.gamma * target_critic([next_state_batch, target_actions]) 495 | critic_value = critic_model([state_batch, action_batch]) 496 | critic_loss = tf.math.reduce_mean(tf.math.square(y - critic_value)) 497 | 498 | critic_grad = tape.gradient(critic_loss, critic_model.trainable_variables) 499 | 500 | 501 | with tf.GradientTape() as tape: 502 | actions = actor_model(state_batch) 503 | critic_value = critic_model([state_batch, actions]) 504 | actor_loss = -tf.math.reduce_mean(critic_value) 505 | 506 | actor_grad = tape.gradient(actor_loss, actor_model.trainable_variables) 507 | 508 | return critic_grad, actor_grad 509 | 510 | def update_reward_list(self, ep): 511 | print("") 512 | for p in range(self.num_platoons): 513 | for m in range(self.num_models): 514 | self.all_ep_reward_lists[p][m].append(self.all_episodic_reward_counters[p][m]) 515 | avg_reward = np.mean(self.all_ep_reward_lists[p][m][-self.conf.reward_averaging_window:]) 516 | self.all_avg_reward_lists[p][m].append(avg_reward) 517 | log.info(f"Platoon {p+1} Model {m+1} : Episode * {ep} of {self.conf.number_of_episodes} * Avg Reward over {self.conf.reward_averaging_window} eps is ==> {avg_reward}, Cum. Episodic Reward is ==> {self.all_ep_reward_lists[p][m][-1]}") 518 | if is_weighted_fed_enabled(self.conf, ep): 519 | # recall that I store vars in memory along different axes of the list in inter or intra frl. I need to access the right values for printing 520 | if self.conf.fed_method == self.conf.interfrl: 521 | self.all_fed_weights[p][m].append(self.fed_weights[m][p]) # we store using idx p,m as we want to standardize storage for plotting 522 | self.all_fed_weight_sums[p][m].append(self.fed_weight_sums[m].numpy()) 523 | log.info(f"\t .. federated weighting: {self.fed_weights[m][p]}, weight sum: {self.fed_weight_sums[m]}, weighted pct (weighting/weight_sum).: {self.fed_weights[m][p]/self.fed_weight_sums[m]}") 524 | elif self.conf.fed_method == self.conf.intrafrl: 525 | self.all_fed_weights[p][m].append(self.fed_weights[p][m]) 526 | self.all_fed_weight_sums[p][m].append(self.fed_weight_sums[p].numpy()) 527 | log.info(f"\t .. federated weighting: {self.fed_weights[p][m]}, weight sum: {self.fed_weight_sums[p]}, weighted pct (weighting/weight_sum).: {self.fed_weights[p][m]/self.fed_weight_sums[p]}") 528 | else: 529 | raise ValueError(f"Invalid configured method {self.conf.method} for applying FRL!") 530 | 531 | print("") 532 | 533 | def close_renderings(self): 534 | for env in self.all_envs: 535 | env.close_render() 536 | 537 | def run_simulations(self): 538 | for p in range(self.num_platoons): 539 | plt.figure() 540 | for m in range(self.num_models): 541 | self.save_training_results(p, m, self.all_actors[p][m], self.all_critics[p][m], self.all_target_actors[p][m], 542 | self.all_target_critics[p][m], self.all_avg_reward_lists[p][m]) 543 | 544 | plt.xlabel("Episode") 545 | plt.ylabel("Average Epsiodic Reward") 546 | plt.legend() 547 | plt.tight_layout() 548 | plt.savefig(os.path.join(self.base_dir, self.conf.fig_path % (p+1))) 549 | self.conf.pl_rews_for_simulations.append(evaluator.run(conf=self.conf, actors=self.all_actors[p], path_timestamp=self.base_dir, out='save', pl_idx=p+1) / self.conf.re_scalar) 550 | evaluator.run(conf=self.conf, actors=self.all_actors[p], path_timestamp=self.base_dir, out='save', pl_idx=p+1, manual_timestep_override=self.conf.manual_timestep_override) / self.conf.re_scalar 551 | 552 | def generate_csvs(self): 553 | """Responsible for generating csv files from data stores in the class. 554 | """ 555 | full_avg_rew_df = None 556 | full_rew_df = None 557 | for p in range(self.num_platoons): 558 | # Generate the dataframes for rewards 559 | avg_rew_df, rew_df = self.generate_reward_data(p, self.all_avg_reward_lists[p], self.all_ep_reward_lists[p]) 560 | if (full_avg_rew_df is None and full_rew_df is None): 561 | full_avg_rew_df = avg_rew_df 562 | full_rew_df = rew_df 563 | else: 564 | full_avg_rew_df = full_avg_rew_df.append(avg_rew_df) 565 | full_rew_df = full_rew_df.append(rew_df) 566 | 567 | full_avg_rew_df.to_csv(os.path.join(self.base_dir, self.conf.avg_ep_reward_path % (self.conf.random_seed))) 568 | full_rew_df.to_csv(os.path.join(self.base_dir, self.conf.ep_reward_path % (self.conf.random_seed))) 569 | 570 | if self.conf.weighted_average_enabled: 571 | full_weights_df = None 572 | for p in range(self.num_platoons): 573 | # Generate the dataframes for frl weighting factors 574 | weights_df = self.generate_frl_weight_data(p) 575 | if (full_weights_df is None): 576 | full_weights_df = weights_df 577 | else: 578 | full_weights_df = full_weights_df.append(weights_df) 579 | full_weights_df.to_csv(os.path.join(self.base_dir, self.conf.frl_weighted_avg_parameters_path % (self.conf.random_seed))) 580 | 581 | def save_training_results(self, p, m, actor, critic, target_actor, target_critic, avg_ep_reward_list): 582 | tag = (p+1, m+1) 583 | 584 | actor.save(os.path.join(self.base_dir, self.conf.actor_fname % tag)) 585 | tf.keras.utils.plot_model(actor, to_file=os.path.join(self.base_dir, self.conf.actor_picname % tag), show_shapes=True) 586 | 587 | critic.save(os.path.join(self.base_dir, self.conf.critic_fname % tag)) 588 | tf.keras.utils.plot_model(critic, to_file=os.path.join(self.base_dir, self.conf.critic_picname % tag), show_shapes=True) 589 | 590 | target_actor.save(os.path.join(self.base_dir, self.conf.t_actor_fname % tag)) 591 | tf.keras.utils.plot_model(target_actor, to_file=os.path.join(self.base_dir, self.conf.t_actor_picname % tag), show_shapes=True) 592 | 593 | target_critic.save(os.path.join(self.base_dir, self.conf.t_critic_fname % tag)) 594 | tf.keras.utils.plot_model(target_critic, to_file=os.path.join(self.base_dir, self.conf.t_critic_picname % tag), show_shapes=True) 595 | 596 | plt.plot(avg_ep_reward_list, label=f"Platoon {p+1} Vehicle {m+1}") 597 | 598 | def generate_reward_data(self, pl_idx, pl_avg_ep_reward_list, pl_ep_reward_list): 599 | tag = (pl_idx+1) 600 | column_labels = [env.VEHICLE_COL % (m+1) for m in range(self.num_models)] 601 | 602 | stacked_pl_avg_ep_reward = np.stack(np.array(pl_avg_ep_reward_list, dtype=object), axis=1) 603 | stacked_pl_ep_reward = np.stack(np.array(pl_ep_reward_list, dtype=object), axis=1) 604 | avg_ep_df = pd.DataFrame(data=stacked_pl_avg_ep_reward, columns=column_labels) 605 | avg_ep_df[env.SEED_COL] = self.conf.random_seed 606 | avg_ep_df[env.PLATOON_COL] = tag 607 | avg_ep_df[env.EPISODIC_REWARD_AVGWINDOW_COL] = self.conf.reward_averaging_window 608 | ep_df = pd.DataFrame(data=stacked_pl_ep_reward, columns=column_labels) 609 | ep_df[env.SEED_COL] = self.conf.random_seed 610 | ep_df[env.PLATOON_COL] = tag 611 | return avg_ep_df, ep_df 612 | 613 | def generate_frl_weight_data(self, idx): 614 | tag = (idx + 1) 615 | stacked_pl_fed_weights = np.stack(np.array(self.all_fed_weights[idx], dtype=object), axis=1) 616 | vehicle_cols = [env.VEHICLE_COL % (m+1) for m in range(self.num_models)] 617 | df = pd.DataFrame(data=stacked_pl_fed_weights, columns=vehicle_cols) 618 | df[env.SEED_COL] = self.conf.random_seed 619 | df[env.PLATOON_COL] = tag 620 | stacked_pl_weight_sums = np.stack(np.array(self.all_fed_weight_sums[idx], dtype=object), axis=1) 621 | fed_weight_sum_cols = [env.FED_WEIGHT_SUM_COL % (m+1) for m in range(self.num_models)] 622 | df2 = pd.DataFrame(data=stacked_pl_weight_sums, columns=fed_weight_sum_cols) 623 | df = df.join(df2[fed_weight_sum_cols]) 624 | # compute the percents as well for human readability. 625 | for i in range(self.num_models): 626 | df[env.FED_WEIGHT_PCT_COL % (i+1)] = df[vehicle_cols[i]] / df[fed_weight_sum_cols[i]] 627 | # account for the episodes missed using while waiting for weighted window 628 | df.index += self.conf.weighted_window 629 | return df 630 | 631 | def is_fed_enabled(conf: config.Config) -> bool: 632 | return (conf.fed_method == conf.interfrl or conf.fed_method == conf.intrafrl) and (conf.framework == conf.dcntrl) 633 | 634 | def is_gradient_updates_enabled(conf: config.Config) -> bool: 635 | return conf.aggregation_method == conf.gradients 636 | 637 | def is_model_weight_updates_enabled(conf: config.Config) -> bool: 638 | return conf.aggregation_method == conf.weights 639 | 640 | def is_weighted_fed_enabled(conf: config.Config, training_episode: int) -> bool: 641 | return (conf.weighted_average_enabled and training_episode >= conf.weighted_window) 642 | 643 | def is_valid_update_episode(conf: config.Config, training_episode: int) -> bool: 644 | """Check if the current episode is valid for a federated update 645 | 646 | Args: 647 | training_episode (int): the current episode 648 | 649 | Returns: 650 | bool: true if the episode is valid 651 | """ 652 | return conf.fed_enabled and (training_episode % conf.fed_update_count) == 0 and training_episode <= conf.fed_cutoff_episode 653 | 654 | def is_valid_update_step(conf: config.Config, training_step: int) -> bool: 655 | """Check if the current training step is valid for a federated update 656 | 657 | Args: 658 | conf (config.Config): the configuration class 659 | training_step (int): the current step 660 | 661 | Returns: 662 | bool: true if the current step is valid 663 | """ 664 | return (training_step % conf.fed_update_delay_steps) == 0 665 | 666 | def is_valid_step_for_federated_training_with_gradients(conf, training_episode, training_step): 667 | """ 668 | Args: 669 | conf (config.Config): the configuration class 670 | training_episode (int): the current training episode 671 | training_step (int): the current training step 672 | 673 | Returns: 674 | bool : true if:\n 675 | 1. FRL is enabled\n 676 | 2. the current episode is a valid FRL episode\n 677 | 3. the current step in the episode is a valid FRL step\n 678 | 4. gradient updates are enabled 679 | """ 680 | return is_fed_enabled(conf) and is_valid_update_episode(conf, training_episode) and is_valid_update_step(conf, training_step) and is_gradient_updates_enabled(conf) 681 | 682 | def is_valid_step_for_federated_training_with_weights(conf, training_episode, training_step): 683 | """ 684 | Args: 685 | conf (config.Config): the configuration class 686 | training_episode (int): the current training episode 687 | training_step (int): the current training step 688 | 689 | Returns: 690 | bool : true if:\n 691 | 1. FRL is enabled\n 692 | 2. the current episode is a valid FRL episode\n 693 | 3. the current step in the episode is a valid FRL step\n 694 | 4. model weights updates are enabled 695 | """ 696 | return is_fed_enabled(conf) and is_valid_update_episode(conf, training_episode) and is_valid_update_step(conf, training_step) and is_model_weight_updates_enabled(conf) --------------------------------------------------------------------------------