-
Notifications
You must be signed in to change notification settings - Fork 367
/
visualizer_rllib.py
457 lines (397 loc) · 16.5 KB
/
visualizer_rllib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
"""Visualizer for rllib experiments.
Attributes
----------
EXAMPLE_USAGE : str
Example call to the function, which is
::
python ./visualizer_rllib.py /tmp/ray/result_dir 1
parser : ArgumentParser
Command-line argument parser
"""
import argparse
import gym
import numpy as np
import os
import sys
import time
import ray
try:
from ray.rllib.agents.agent import get_agent_class
except ImportError:
from ray.rllib.agents.registry import get_agent_class
from ray.tune.registry import register_env
from flow.core.rewards import instantaneous_mpg
from flow.core.util import emission_to_csv
from flow.utils.registry import make_create_env
from flow.utils.rllib import get_flow_params
from flow.utils.rllib import get_rllib_config
from flow.utils.rllib import get_rllib_pkl
from flow.data_pipeline.data_pipeline import write_dict_to_csv, upload_to_s3, get_extra_info, get_configuration
from flow.data_pipeline.leaderboard_utils import network_name_translate
from collections import defaultdict
from datetime import datetime, timezone
import uuid
EXAMPLE_USAGE = """
example usage:
python ./visualizer_rllib.py /ray_results/experiment_dir/result_dir 1
Here the arguments are:
1 - the path to the simulation results
2 - the number of the checkpoint
"""
def visualizer_rllib(args):
"""Visualizer for RLlib experiments.
This function takes args (see function create_parser below for
more detailed information on what information can be fed to this
visualizer), and renders the experiment associated with it.
"""
result_dir = args.result_dir if args.result_dir[-1] != '/' \
else args.result_dir[:-1]
config = get_rllib_config(result_dir)
# check if we have a multiagent environment but in a
# backwards compatible way
if config.get('multiagent', {}).get('policies', None):
multiagent = True
pkl = get_rllib_pkl(result_dir)
config['multiagent'] = pkl['multiagent']
else:
multiagent = False
# Run on only one cpu for rendering purposes
config['num_workers'] = 0
flow_params = get_flow_params(config)
# hack for old pkl files
# TODO(ev) remove eventually
sim_params = flow_params['sim']
setattr(sim_params, 'num_clients', 1)
# for hacks for old pkl files TODO: remove eventually
if not hasattr(sim_params, 'use_ballistic'):
sim_params.use_ballistic = False
# Determine agent and checkpoint
config_run = config['env_config']['run'] if 'run' in config['env_config'] \
else None
if args.run and config_run:
if args.run != config_run:
print('visualizer_rllib.py: error: run argument '
+ '\'{}\' passed in '.format(args.run)
+ 'differs from the one stored in params.json '
+ '\'{}\''.format(config_run))
sys.exit(1)
if args.run:
agent_cls = get_agent_class(args.run)
elif config['env_config']['run'] == "<class 'ray.rllib.agents.trainer_template.CCPPOTrainer'>":
from flow.algorithms.centralized_PPO import CCTrainer, CentralizedCriticModel
from ray.rllib.models import ModelCatalog
agent_cls = CCTrainer
ModelCatalog.register_custom_model("cc_model", CentralizedCriticModel)
elif config['env_config']['run'] == "<class 'ray.rllib.agents.trainer_template.CustomPPOTrainer'>":
from flow.algorithms.custom_ppo import CustomPPOTrainer
agent_cls = CustomPPOTrainer
elif config_run:
agent_cls = get_agent_class(config_run)
else:
print('visualizer_rllib.py: error: could not find flow parameter '
'\'run\' in params.json, '
'add argument --run to provide the algorithm or model used '
'to train the results\n e.g. '
'python ./visualizer_rllib.py /tmp/ray/result_dir 1 --run PPO')
sys.exit(1)
sim_params.restart_instance = True
dir_path = os.path.dirname(os.path.realpath(__file__))
emission_path = '{0}/test_time_rollout/'.format(dir_path)
sim_params.emission_path = emission_path if args.gen_emission else None
# pick your rendering mode
if args.render_mode == 'sumo_web3d':
sim_params.num_clients = 2
sim_params.render = False
elif args.render_mode == 'drgb':
sim_params.render = 'drgb'
sim_params.pxpm = 4
elif args.render_mode == 'sumo_gui':
sim_params.render = False # will be set to True below
elif args.render_mode == 'no_render':
sim_params.render = False
if args.save_render:
if args.render_mode != 'sumo_gui':
sim_params.render = 'drgb'
sim_params.pxpm = 4
sim_params.save_render = True
# Create and register a gym+rllib env
create_env, env_name = make_create_env(params=flow_params, version=0)
register_env(env_name, create_env)
# check if the environment is a single or multiagent environment, and
# get the right address accordingly
# single_agent_envs = [env for env in dir(flow.envs)
# if not env.startswith('__')]
# if flow_params['env_name'] in single_agent_envs:
# env_loc = 'flow.envs'
# else:
# env_loc = 'flow.envs.multiagent'
# Start the environment with the gui turned on and a path for the
# emission file
env_params = flow_params['env']
env_params.restart_instance = False
if args.evaluate:
env_params.evaluate = True
# lower the horizon if testing
if args.horizon:
config['horizon'] = args.horizon
env_params.horizon = args.horizon
# create the agent that will be used to compute the actions
agent = agent_cls(env=env_name, config=config)
checkpoint = result_dir + '/checkpoint_' + args.checkpoint_num
checkpoint = checkpoint + '/checkpoint-' + args.checkpoint_num
agent.restore(checkpoint)
if hasattr(agent, "local_evaluator") and \
os.environ.get("TEST_FLAG") != 'True':
env = agent.local_evaluator.env
else:
env = gym.make(env_name)
# reroute on exit is a training hack, it should be turned off at test time.
if hasattr(env, "reroute_on_exit"):
env.reroute_on_exit = False
if args.render_mode == 'sumo_gui':
env.sim_params.render = True # set to True after initializing agent and env
if multiagent:
rets = {}
# map the agent id to its policy
policy_map_fn = config['multiagent']['policy_mapping_fn']
for key in config['multiagent']['policies'].keys():
rets[key] = []
else:
rets = []
if config['model']['use_lstm']:
use_lstm = True
if multiagent:
state_init = {}
# map the agent id to its policy
policy_map_fn = config['multiagent']['policy_mapping_fn']
size = config['model']['lstm_cell_size']
for key in config['multiagent']['policies'].keys():
state_init[key] = [np.zeros(size, np.float32),
np.zeros(size, np.float32)]
else:
state_init = [
np.zeros(config['model']['lstm_cell_size'], np.float32),
np.zeros(config['model']['lstm_cell_size'], np.float32)
]
else:
use_lstm = False
# if restart_instance, don't restart here because env.reset will restart later
if not sim_params.restart_instance:
env.restart_simulation(sim_params=sim_params, render=sim_params.render)
# data pipeline
extra_info = defaultdict(lambda: [])
source_id = 'flow_{}'.format(uuid.uuid4().hex)
metadata = defaultdict(lambda: [])
# collect current time
cur_datetime = datetime.now(timezone.utc)
cur_date = cur_datetime.date().isoformat()
cur_time = cur_datetime.time().isoformat()
# collecting information for metadata table
metadata['source_id'].append(source_id)
metadata['submission_time'].append(cur_time)
metadata['network'].append(network_name_translate(env.network.name.split('_20')[0]))
metadata['is_baseline'].append(str(args.is_baseline))
if args.to_aws:
name, strategy = get_configuration()
metadata['submitter_name'].append(name)
metadata['strategy'].append(strategy)
# Simulate and collect metrics
final_outflows = []
final_inflows = []
mpg = []
mean_speed = []
std_speed = []
for i in range(args.num_rollouts):
vel = []
run_id = "run_{}".format(i)
env.pipeline_params = (extra_info, source_id, run_id)
state = env.reset()
if multiagent:
ret = {key: [0] for key in rets.keys()}
else:
ret = 0
for _ in range(env_params.horizon):
vehicles = env.unwrapped.k.vehicle
speeds = vehicles.get_speed(vehicles.get_ids())
# only include non-empty speeds
if speeds:
vel.append(np.mean(speeds))
mpg.append(instantaneous_mpg(env.unwrapped, vehicles.get_ids(), gain=1.0))
if multiagent:
action = {}
for agent_id in state.keys():
if use_lstm:
action[agent_id], state_init[agent_id], logits = \
agent.compute_action(
state[agent_id], state=state_init[agent_id],
policy_id=policy_map_fn(agent_id))
else:
action[agent_id] = agent.compute_action(
state[agent_id], policy_id=policy_map_fn(agent_id))
else:
action = agent.compute_action(state)
state, reward, done, _ = env.step(action)
# collect data for data pipeline
get_extra_info(vehicles, extra_info, vehicles.get_ids(), source_id, run_id)
if multiagent:
for actor, rew in reward.items():
ret[policy_map_fn(actor)][0] += rew
else:
ret += reward
if multiagent and done['__all__']:
break
if not multiagent and done:
break
if multiagent:
for key in rets.keys():
rets[key].append(ret[key])
else:
rets.append(ret)
outflow = vehicles.get_outflow_rate(500)
final_outflows.append(outflow)
inflow = vehicles.get_inflow_rate(500)
final_inflows.append(inflow)
if np.all(np.array(final_inflows) > 1e-5):
throughput_efficiency = [x / y for x, y in
zip(final_outflows, final_inflows)]
else:
throughput_efficiency = [0] * len(final_inflows)
mean_speed.append(np.mean(vel))
std_speed.append(np.std(vel))
if multiagent:
for agent_id, rew in rets.items():
print('Round {}, Return: {} for agent {}'.format(
i, ret, agent_id))
else:
print('Round {}, Return: {}'.format(i, ret))
print('==== Summary of results ====')
print("Return:")
print(mean_speed)
if multiagent:
for agent_id, rew in rets.items():
print('For agent', agent_id)
print(rew)
print('Average, std return: {}, {} for agent {}'.format(
np.mean(rew), np.std(rew), agent_id))
else:
print(rets)
print('Average, std: {}, {}'.format(
np.mean(rets), np.std(rets)))
print("\nSpeed, mean (m/s):")
print(mean_speed)
print('Average, std: {}, {}'.format(np.mean(mean_speed), np.std(
mean_speed)))
print('Average, std miles per gallon: {}, {}'.format(np.mean(mpg), np.std(mpg)))
# Compute arrival rate of vehicles in the last 500 sec of the run
print("\nOutflows (veh/hr):")
print(final_outflows)
print('Average, std: {}, {}'.format(np.mean(final_outflows),
np.std(final_outflows)))
# Compute departure rate of vehicles in the last 500 sec of the run
print("Inflows (veh/hr):")
print(final_inflows)
print('Average, std: {}, {}'.format(np.mean(final_inflows),
np.std(final_inflows)))
# Compute throughput efficiency in the last 500 sec of the
print("Throughput efficiency (veh/hr):")
print(throughput_efficiency)
print('Average, std: {}, {}'.format(np.mean(throughput_efficiency),
np.std(throughput_efficiency)))
# terminate the environment
env.unwrapped.terminate()
# if prompted, convert the emission file into a csv file
if args.gen_emission:
time.sleep(0.1)
dir_path = os.path.dirname(os.path.realpath(__file__))
emission_filename = '{0}-emission.xml'.format(env.network.name)
emission_path = \
'{0}/test_time_rollout/{1}'.format(dir_path, emission_filename)
# convert the emission file into a csv file
emission_to_csv(emission_path)
# print the location of the emission csv file
emission_path_csv = emission_path[:-4] + ".csv"
print("\nGenerated emission file at " + emission_path_csv)
# delete the .xml version of the emission file
os.remove(emission_path)
# generate datapipeline output
trajectory_table_path = os.path.join(dir_path, '{}.csv'.format(source_id))
metadata_table_path = os.path.join(dir_path, '{}_METADATA.csv'.format(source_id))
write_dict_to_csv(trajectory_table_path, extra_info, True)
write_dict_to_csv(metadata_table_path, metadata, True)
if args.to_aws:
upload_to_s3('circles.data.pipeline',
'metadata_table/date={0}/partition_name={1}_METADATA/{1}_METADATA.csv'.format(cur_date,
source_id),
metadata_table_path)
upload_to_s3('circles.data.pipeline',
'fact_vehicle_trace/date={0}/partition_name={1}/{1}.csv'.format(cur_date, source_id),
trajectory_table_path,
{'network': metadata['network'][0]})
def create_parser():
"""Create the parser to capture CLI arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='[Flow] Evaluates a reinforcement learning agent '
'given a checkpoint.',
epilog=EXAMPLE_USAGE)
# required input parameters
parser.add_argument(
'result_dir', type=str, help='Directory containing results')
parser.add_argument('checkpoint_num', type=str, help='Checkpoint number.')
# optional input parameters
parser.add_argument(
'--run',
type=str,
help='The algorithm or model to train. This may refer to '
'the name of a built-on algorithm (e.g. RLLib\'s DQN '
'or PPO), or a user-defined trainable function or '
'class registered in the tune registry. '
'Required for results trained with flow-0.2.0 and before.')
parser.add_argument(
'--num_rollouts',
type=int,
default=1,
help='The number of rollouts to visualize.')
parser.add_argument(
'--gen_emission',
action='store_true',
help='Specifies whether to generate an emission file from the '
'simulation')
parser.add_argument(
'--evaluate',
action='store_true',
help='Specifies whether to use the \'evaluate\' reward '
'for the environment.')
parser.add_argument(
'--render_mode',
type=str,
default='sumo_gui',
help='Pick the render mode. Options include sumo_web3d, '
'rgbd and sumo_gui')
parser.add_argument(
'--save_render',
action='store_true',
help='Saves a rendered video to a file. NOTE: Overrides render_mode '
'with pyglet rendering.')
parser.add_argument(
'--horizon',
type=int,
help='Specifies the horizon.')
parser.add_argument(
'--is_baseline',
action='store_true',
help='specifies whether this is a baseline run'
)
parser.add_argument(
'--to_aws',
type=str, nargs='?', default=None, const="default",
help='Specifies the name of the partition to store the output'
'file on S3. Putting not None value for this argument'
'automatically set gen_emission to True.'
)
return parser
if __name__ == '__main__':
parser = create_parser()
args = parser.parse_args()
ray.init(num_cpus=1)
visualizer_rllib(args)