Commit ec049e49 authored by Benedikt Zoennchen's avatar Benedikt Zoennchen
Browse files

update metric notebook, add data for the notebook such that one can experiment with it.

parent 819e9600
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# expand the cell of the notebook
import json
import numpy as np
import pandas as pd
import math
......@@ -19,11 +13,11 @@
display(HTML('<style>.container { width:100% !important; }</style>'))
```
%% Cell type:markdown id: tags:
# Methods to convert Vadere trajectories into a DataFrame
# Convert Vadere trajectories into a DataFrame
%% Cell type:code id: tags:
``` python
def fs_append(pedestrianId, fs, llist):
......@@ -37,12 +31,16 @@
llist = []
for pedId in trajectories:
trajectory_append(pedId, trajectories[pedId], llist)
dataframe = pd.DataFrame(llist, columns=['pedestrianId','startX','startY','startTime','endX','endY','endTime'])
return dataframe
```
file = "./data/trajectories_distance.txt"
%% Cell type:code id: tags:
``` python
file = "./data/TrajectoryMetric/trajectories_simulation.txt"
f = open(file, "r")
header = f.readline();
trajectories = dict({});
for row in f:
......@@ -55,10 +53,99 @@
ptrajectories.head()
```
%% Cell type:markdown id: tags:
# Convert experiment data into a DataFrame
%% Cell type:code id: tags:
``` python
def load_experiment(file):
fps = 16
pad = pd.DataFrame([[np.nan, np.nan, np.nan, np.nan, np.nan]], columns=['pedestrianId', 'timeStep', 'x', 'y', 'e'])
data = pd.read_csv(
file,
sep=' ',
names=['pedestrianId', 'timeStep', 'x', 'y', 'e'],
index_col=False,
header=None,
skiprows=0)
cc = pd.concat([pad, data], ignore_index=True)
data['endX'] = data['x'] / 100 + 18.7
data['endY'] = data['y'] / 100 + 4.2
data['startX'] = cc['x'] / 100 + 18.7
data['startY'] = cc['y'] / 100 + 4.2
data['startTime'] = data['timeStep'] / fps - 1/fps
data['endTime'] = data['timeStep'] / fps
data = data.drop(columns=['timeStep','x','y','e'])
return data
def to_trajectories(data):
trajectories = dict({})
trajectory = []
for i in range(len(data)-1):
pedId = data['pedestrianId'][i]
if pedId == data['pedestrianId'][i+1]:
pedId = data['pedestrianId'][i]
x1 = data['x'][i]
y1 = data['y'][i]
x2 = data['x'][i+1]
y2 = data['y'][i+1]
startTime = data['timeStep'][i]
endTime = data['timeStep'][i+1]
fs = {'startTime':startTime, 'endTime': endTime, 'start':{'x':x1, 'y':y1}, 'end':{'x':x2, 'y':y2}}
trajectory.append(fs)
else:
trajectories[pedId] = trajectory
trajectory = []
pedId = data['pedestrianId'][i]
return trajectories
```
%% Cell type:code id: tags:
``` python
#times = np.linspace(4,10,10)
#euclid_d(get_trajectory(1), get_trajectory(1), times)
#to_trajectories(load_experiment(real_file))[1]
real_file = "./data/TrajectoryMetric/KO/ko-240-120-240/ko-240-120-240_combined_MB.txt"
trajectoriesReal = load_experiment(real_file)
#trajectoriesReal = to_trajectories(data)
trajectoriesReal.query('pedestrianId == 1').head()
```
%% Cell type:markdown id: tags:
# Convert DataFrame to postvis DataFrame
%% Cell type:code id: tags:
``` python
def to_postVis(df):
simTimeStep = 0.4
fps = 16
df['timeStep'] = np.ceil(df['endTime'] / (1/fps)).astype(np.int)
df['x'] = df['endX']
df['y'] = df['endY']
df['simTime'] = df['endTime']
df = df.drop(columns=['startX','startY','endX','endY','startTime', 'endTime'])
return df
```
%% Cell type:code id: tags:
``` python
to_postVis(trajectoriesReal).to_csv('expteriment_2.trajectories',index=False,sep=' ')
to_postVis(trajectoriesReal).head(10)
```
%% Cell type:markdown id: tags:
# Helpler method to access parts of the trajectory
%% Cell type:code id: tags:
``` python
......@@ -259,11 +346,16 @@
return s / c
def total_inter_agent(trajectories1, trajectories2, times):
"""too expensive! TODO!"""
return sum(map(lambda t: inter_agent_d(trajectories_position(trajectories1, [t])) - inter_agent_d(trajectories_position(trajectories2, [t])), times)) / len(times)
```
%% Cell type:code id: tags:
``` python
#start_time(get_trajectory(1, ptrajectories))
#max_start_time(ptrajectories)
#end_time(get_trajectory(1, ptrajectories))
#foot_step_length(get_footstep(get_trajectory(1, ptrajectories), 0))
#trajectory_length(get_trajectory(1, ptrajectories))
......@@ -282,91 +374,10 @@
```
%% Cell type:code id: tags:
``` python
trajPos2
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
def position(trajectory, time):
fs = footstep(trajectory, time);
if fs != None:
startTime = fs['startTime'];
endTime = fs['endTime'];
dur = duration(fs);
partial_dur = time - startTime;
ratio = partial_dur / dur;
start = fs['start'];
x1 = start['x'];
y1 = start['y'];
l = length(fs);
if l == 0.0:
return np.array([x1, y1])
else:
partial_l = l * ratio;
v = direction(fs) / l * partial_l;
return np.array([x1, y1]) + v;
def euclid_d(traj1, traj2, times):
"""Computes the total (Euclidean) distance between two trajectories at certain times."""
return 0
sT = max([start_time(traj1), start_time(traj2)])
eT = min([end_time(traj1), end_time(traj2)])
filtered_times = list(filter(lambda t: t >= sT and t <= eT, times))
overlaps = len(filtered_times)
if overlaps == 0:
return 0
return sum(map(lambda t: np.linalg.norm(position(traj1, t)- position(traj2, t)), filtered_times)) / overlaps
def euclid_path_length(traj1, traj2, times):
sT = max([start_time(traj1), start_time(traj2)]);
eT = min([end_time(traj1), end_time(traj2)]);
filtered_times = list(filter(lambda t: t >= sT and t <= eT, times));
s = np.array([0, 0])
for i in range(len(filtered_times)-1):
t1 = filtered_times[i]
t2 = filtered_times[i+1]
d1 = position(traj1, t1) - position(traj1, t2)
d2 = position(traj2, t1) - position(traj2, t2)
diff = d1 - d2
s = s + diff
return s;
def inter_agent_d(trajectories, t):
s = 0
min_index = min(trajectories.keys())
c = 0
for i in range(len(trajectories)):
pos1 = position(trajectories[i+min_index], t)
for j in range(i+1, len(trajectories)):
pos2 = position(trajectories[j+min_index], t)
if pos1 is not None and pos2 is not None:
s = s + np.linalg.norm(pos1 - pos2)
c = c + 1
if c == 0:
return 0
else:
return s / c
def total_inter_agent(trajectories1, trajectories2, times):
return sum(map(lambda t: inter_agent_d(trajectories1, t) - inter_agent_d(trajectories2, t), times)) / len(times)
def euclid_len(trajectory, sTime, eTime):
"""Computes the total (Euclidean) length of the trajectory in between [sTime;eTime]."""
cut_traj = cut_soft(trajectory, sTime, eTime);
return trajectory_length(cut_traj)
def greedy_match(trajectories1, trajectories2, times, f):
"""Computes a match of trajectories by using a greedy algorithm."""
assert len(trajectories1) == len(trajectories2)
min_index1 = min(trajectories1.keys())
min_index2 = min(trajectories2.keys())
......@@ -384,125 +395,57 @@
minIndex = j
minVal = val
match[i] = minIndex
indexSet.remove(minIndex)
return match
def overlap(traj1, traj2, dt):
return True
def load_experiment(file):
fps = 16
pad = pd.DataFrame([[np.nan, np.nan, np.nan, np.nan, np.nan]], columns=['pedestrianId', 'timeStep', 'x', 'y', 'e'])
data = pd.read_csv(
file,
sep=' ',
names=['pedestrianId', 'timeStep', 'x', 'y', 'e'],
index_col=False,
header=None,
skiprows=0)
cc = pd.concat([pad, data], ignore_index=True)
data['endX'] = data['x'] / 100 + 18.7
data['endY'] = data['y'] / 100 + 4.2
data['startX'] = cc['x'] / 100 + 18.7
data['startY'] = cc['y'] / 100 + 4.2
data['startTime'] = data['timeStep'] / fps - 1/fps
data['endTime'] = data['timeStep'] / fps
data = data.drop(columns=['timeStep','x','y','e'])
return data
def to_trajectories(data):
trajectories = dict({})
trajectory = []
for i in range(len(data)-1):
pedId = data['pedestrianId'][i]
if pedId == data['pedestrianId'][i+1]:
pedId = data['pedestrianId'][i]
x1 = data['x'][i]
y1 = data['y'][i]
x2 = data['x'][i+1]
y2 = data['y'][i+1]
startTime = data['timeStep'][i]
endTime = data['timeStep'][i+1]
fs = {'startTime':startTime, 'endTime': endTime, 'start':{'x':x1, 'y':y1}, 'end':{'x':x2, 'y':y2}}
trajectory.append(fs)
else:
trajectories[pedId] = trajectory
trajectory = []
pedId = data['pedestrianId'][i]
return trajectories
```
def to_postVis(df):
simTimeStep = 0.4
fps = 16
df['timeStep'] = np.ceil(df['endTime'] / (1/fps)).astype(np.int)
df['x'] = df['endX']
df['y'] = df['endY']
df['simTime'] = df['endTime']
df = df.drop(columns=['startX','startY','endX','endY','startTime', 'endTime'])
return df
#times = np.linspace(4,10,10)
#euclid_d(get_trajectory(1), get_trajectory(1), times)
#to_trajectories(load_experiment(real_file))[1]
%% Cell type:markdown id: tags:
file = "./data/trajectories_distance.txt"
real_file = "./data/KO/ko-240-120-240/ko-240-120-240_combined_MB.txt"
```
# Plot trajectories
%% Cell type:code id: tags:
``` python
data = load_experiment(real_file)
#trajectoriesReal = to_trajectories(data)
data.query('pedestrianId == 1').head()
to_postVis(data).to_csv('expteriment_2.trajectories',index=False,sep=' ')
to_postVis(data).head(10)
def to_line(trajectory, xleft):
"""Transforms a trajectory into a Line2D."""
x = trajectory['endX'].values
y = trajectory['endY'].values
if x[0] < xleft:
c = current_palette[2]
else:
c = current_palette[0]
return x, y, Line2D(x, y, color=c, linewidth=0.2)
def add_lines(trajectories, xleft, ax):
grouped = trajectories.groupby(['pedestrianId'])
for name, group in grouped:
x, y, line = to_line(group, xleft)
ax.add_line(line)
```
%% Cell type:code id: tags:
``` python
import seaborn as sns
sns.set(style="ticks")
current_palette = sns.color_palette()
def to_line(trajectory, xleft):
x = []
y = []
for fs in trajectory:
x.append(fs['start']['x'])
y.append(fs['start']['y'])
if x[0] < xleft:
c = current_palette[2]
else:
c = current_palette[0]
return x, y, Line2D(x, y, color=c, linewidth=0.2)
x_vcenter = 17.5
y_vcenter = 5.2
fig1 = plt.figure(figsize=(10,10))
ax1 = fig1.add_subplot(111)
x_vcenter = 17.5
y_vcenter = 5.2
for i in range(len(trajectoriesReal)):
x, y, line = to_line(trajectoriesReal[i+1], 14)
ax1.add_line(line)
add_lines(trajectoriesReal, 14, ax1)
ax1.set_xlim(x_vcenter-5, x_vcenter+5)
ax1.set_ylim(y_vcenter-4, y_vcenter+4)
ax1.set_aspect(1)
fig2 = plt.figure(figsize=(10,10))
ax2 = fig2.add_subplot(111)
for i in range(len(trajectories)):
x, y, line = to_line(trajectories[i+1], 14)
ax2.add_line(line)
add_lines(ptrajectories, 14, ax2)
ax2.set_xlim(x_vcenter-5, x_vcenter+5)
ax2.set_ylim(y_vcenter-4, y_vcenter+4)
ax2.set_aspect(1)
plt.show()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment