Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

timespace diagram merge bug fix #974

Merged
merged 2 commits into from
Jun 19, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion flow/utils/rllib.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ def get_flow_params(config):
if type(config) == dict:
flow_params = json.loads(config['env_config']['flow_params'])
else:
flow_params = json.load(open(config, 'r'))
config = json.load(open(config, 'r'))
flow_params = json.loads(config['env_config']['flow_params'])

# reinitialize the vehicles class from stored data
veh = VehicleParams()
Expand Down
122 changes: 7 additions & 115 deletions flow/visualize/time_space_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,31 +169,7 @@ def _merge(data):

return segs, data

# compute the absolute position
for veh_id in data.keys():
data[veh_id]['abs_pos'] = _get_abs_pos(data[veh_id]['edge'],
data[veh_id]['pos'], edgestarts)

# prepare the speed and absolute position in a way that is compatible with
# the space-time diagram, and compute the number of vehicles at each step
pos = np.zeros((all_time.shape[0], len(data.keys())))
speed = np.zeros((all_time.shape[0], len(data.keys())))
for i, veh_id in enumerate(sorted(data.keys())):
for spd, abs_pos, ti, edge in zip(data[veh_id]['vel'],
data[veh_id]['abs_pos'],
data[veh_id]['time'],
data[veh_id]['edge']):
# avoid vehicles outside the main highway
if edge in ['inflow_merge', 'bottom', ':bottom_0']:
continue
ind = np.where(ti == all_time)[0]
pos[ind, i] = abs_pos
speed[ind, i] = spd

return pos, speed, all_time


def _highway(data, params, all_time):
def _highway(data):
r"""Generate position and speed data for the highway subnetwork.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update docstring


Parameters
Expand All @@ -220,61 +196,11 @@ def _highway(data, params, all_time):
time step. Set to zero if the vehicle is not present in the network at
that time step.
"""
junction_length = 0.1
length = params['net'].additional_params["length"]
num_edges = params['net'].additional_params.get("num_edges", 1)
edge_starts = {}
# Add the main edges.
edge_starts.update({
"highway_{}".format(i): i * (length / num_edges + junction_length)
for i in range(num_edges)
})

if params['net'].additional_params["use_ghost_edge"]:
edge_starts.update({"highway_end": length + num_edges * junction_length})

edge_starts.update({
":edge_{}".format(i + 1): (i + 1) * length / num_edges + i * junction_length
for i in range(num_edges - 1)
})

if params['net'].additional_params["use_ghost_edge"]:
edge_starts.update({
":edge_{}".format(num_edges): length + (num_edges - 1) * junction_length
})

# compute the absolute position
for veh_id in data.keys():
data[veh_id]['abs_pos'] = _get_abs_pos_1_edge(data[veh_id]['edge'],
data[veh_id]['pos'],
edge_starts)

# track only vehicles that were around during this time period
# create the output variables
pos = np.zeros((all_time.shape[0], len(data.keys())))
speed = np.zeros((all_time.shape[0], len(data.keys())))
observed_row_list = []
for i, veh_id in enumerate(sorted(data.keys())):
for spd, abs_pos, ti, edge, lane in zip(data[veh_id]['vel'],
data[veh_id]['abs_pos'],
data[veh_id]['time'],
data[veh_id]['edge'],
data[veh_id]['lane']):
# avoid vehicles not on the relevant edges. Also only check the
# second to last lane
if edge not in edge_starts.keys() or ti not in all_time:
continue
else:
if i not in observed_row_list:
observed_row_list.append(i)
ind = np.where(ti == all_time)[0]
pos[ind, i] = abs_pos
speed[ind, i] = spd

pos = pos[:, observed_row_list]
speed = speed[:, observed_row_list]

return pos, speed, all_time
data.loc[:, :] = data[(data['distance'] > 500)]
data.loc[:, :] = data[(data['distance'] < 2300)]
segs = data[['time_step', 'distance', 'next_time', 'next_pos']].values.reshape((len(data), 2, 2))

return segs, data


def _ring_road(data, params, all_time):
Expand Down Expand Up @@ -566,6 +492,7 @@ def plot_tsd(ax, df, segs, args, lane=None):

for lane, df in traj_df.groupby('lane_id'):
ax = plt.subplot(nlanes, 1, lane+1)

plot_tsd(ax, df, segs[lane], args, lane)
else:
# perform plotting operation
Expand All @@ -574,41 +501,6 @@ def plot_tsd(ax, df, segs, args, lane=None):

plot_tsd(ax, traj_df, segs, args)

for indx_car in range(pos.shape[1]):
unique_car_pos = pos[:, indx_car]

if flow_params['network'] == I210SubNetwork or flow_params['network'] == HighwayNetwork:
indices = np.where(pos[:, indx_car] != 0)[0]
unique_car_speed = speed[indices, indx_car]
points = np.array([time[indices], pos[indices, indx_car]]).T.reshape(-1, 1, 2)
else:

# discontinuity from wraparound
disc = np.where(np.abs(np.diff(unique_car_pos)) >= 10)[0] + 1
unique_car_time = np.insert(time, disc, np.nan)
unique_car_pos = np.insert(unique_car_pos, disc, np.nan)
unique_car_speed = np.insert(speed[:, indx_car], disc, np.nan)
#
points = np.array(
[unique_car_time, unique_car_pos]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=my_cmap, norm=norm)

# Set the values used for color mapping
lc.set_array(unique_car_speed)
lc.set_linewidth(1.75)
cols.append(lc)

plt.title(args.title, fontsize=25)
plt.ylabel('Position (m)', fontsize=20)
plt.xlabel('Time (s)', fontsize=20)

for col in cols:
line = ax.add_collection(col)
cbar = plt.colorbar(line, ax=ax, norm=norm)
cbar.set_label('Velocity (m/s)', fontsize=20)
cbar.ax.tick_params(labelsize=18)

###########################################################################
# Note: For MergeNetwork only #
if flow_params['network'] == 'MergeNetwork': #
Expand Down