Skip to content
GitLab
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in
Toggle navigation
Menu
9.2.2023: Due to updates GitLab will be unavailable for some minutes between 9:00 and 11:00.
Open sidebar
vadere
vadere
Commits
ec049e49
Commit
ec049e49
authored
May 22, 2019
by
Benedikt Zoennchen
Browse files
update metric notebook, add data for the notebook such that one can experiment with it.
parent
819e9600
Changes
3
Expand all
Hide whitespace changes
Inline
Side-by-side
Tools/Notebooks/TrajectoryMetric.ipynb
View file @
ec049e49
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
...
...
@@ -29,7 +22,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"#
Methods to c
onvert Vadere trajectories into a DataFrame"
"#
C
onvert Vadere trajectories into a DataFrame"
]
},
{
...
...
@@ -50,9 +43,16 @@
" for pedId in trajectories:\n",
" trajectory_append(pedId, trajectories[pedId], llist)\n",
" dataframe = pd.DataFrame(llist, columns=['pedestrianId','startX','startY','startTime','endX','endY','endTime'])\n",
" return dataframe\n",
"\n",
"file = \"./data/trajectories_distance.txt\"\n",
" return dataframe"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"file = \"./data/TrajectoryMetric/trajectories_simulation.txt\"\n",
"f = open(file, \"r\")\n",
"header = f.readline();\n",
"trajectories = dict({});\n",
...
...
@@ -67,6 +67,113 @@
"ptrajectories.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Convert experiment data into a DataFrame"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def load_experiment(file):\n",
" fps = 16\n",
" pad = pd.DataFrame([[np.nan, np.nan, np.nan, np.nan, np.nan]], columns=['pedestrianId', 'timeStep', 'x', 'y', 'e'])\n",
" data = pd.read_csv(\n",
" file, \n",
" sep=' ', \n",
" names=['pedestrianId', 'timeStep', 'x', 'y', 'e'], \n",
" index_col=False, \n",
" header=None, \n",
" skiprows=0)\n",
" \n",
" cc = pd.concat([pad, data], ignore_index=True)\n",
" \n",
" data['endX'] = data['x'] / 100 + 18.7\n",
" data['endY'] = data['y'] / 100 + 4.2\n",
" data['startX'] = cc['x'] / 100 + 18.7\n",
" data['startY'] = cc['y'] / 100 + 4.2\n",
" data['startTime'] = data['timeStep'] / fps - 1/fps\n",
" data['endTime'] = data['timeStep'] / fps\n",
" data = data.drop(columns=['timeStep','x','y','e'])\n",
" return data\n",
" \n",
"def to_trajectories(data):\n",
" trajectories = dict({})\n",
" trajectory = []\n",
" for i in range(len(data)-1):\n",
" pedId = data['pedestrianId'][i]\n",
" if pedId == data['pedestrianId'][i+1]:\n",
" pedId = data['pedestrianId'][i]\n",
" x1 = data['x'][i]\n",
" y1 = data['y'][i]\n",
" x2 = data['x'][i+1]\n",
" y2 = data['y'][i+1]\n",
" startTime = data['timeStep'][i] \n",
" endTime = data['timeStep'][i+1]\n",
" fs = {'startTime':startTime, 'endTime': endTime, 'start':{'x':x1, 'y':y1}, 'end':{'x':x2, 'y':y2}}\n",
" trajectory.append(fs)\n",
" else:\n",
" trajectories[pedId] = trajectory\n",
" trajectory = []\n",
" pedId = data['pedestrianId'][i]\n",
" return trajectories"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#times = np.linspace(4,10,10)\n",
"#euclid_d(get_trajectory(1), get_trajectory(1), times)\n",
"#to_trajectories(load_experiment(real_file))[1]\n",
"\n",
"real_file = \"./data/TrajectoryMetric/KO/ko-240-120-240/ko-240-120-240_combined_MB.txt\"\n",
"trajectoriesReal = load_experiment(real_file)\n",
"#trajectoriesReal = to_trajectories(data)\n",
"trajectoriesReal.query('pedestrianId == 1').head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Convert DataFrame to postvis DataFrame"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def to_postVis(df):\n",
" simTimeStep = 0.4\n",
" fps = 16\n",
" df['timeStep'] = np.ceil(df['endTime'] / (1/fps)).astype(np.int)\n",
" df['x'] = df['endX']\n",
" df['y'] = df['endY']\n",
" df['simTime'] = df['endTime']\n",
" df = df.drop(columns=['startX','startY','endX','endY','startTime', 'endTime']) \n",
" return df"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"to_postVis(trajectoriesReal).to_csv('expteriment_2.trajectories',index=False,sep=' ')\n",
"to_postVis(trajectoriesReal).head(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
...
...
@@ -284,8 +391,15 @@
" \n",
"def total_inter_agent(trajectories1, trajectories2, times):\n",
" \"\"\"too expensive! TODO!\"\"\"\n",
" return sum(map(lambda t: inter_agent_d(trajectories_position(trajectories1, [t])) - inter_agent_d(trajectories_position(trajectories2, [t])), times)) / len(times)\n",
" \n",
" return sum(map(lambda t: inter_agent_d(trajectories_position(trajectories1, [t])) - inter_agent_d(trajectories_position(trajectories2, [t])), times)) / len(times)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#start_time(get_trajectory(1, ptrajectories))\n",
"#max_start_time(ptrajectories)\n",
"#end_time(get_trajectory(1, ptrajectories))\n",
...
...
@@ -305,22 +419,6 @@
"#print(total_inter_agent(ptrajectories, ptrajectories, [1,2]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trajPos2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
...
...
@@ -329,75 +427,6 @@
},
"outputs": [],
"source": [
"def position(trajectory, time):\n",
" fs = footstep(trajectory, time);\n",
" if fs != None:\n",
" startTime = fs['startTime'];\n",
" endTime = fs['endTime'];\n",
" dur = duration(fs);\n",
" partial_dur = time - startTime;\n",
" ratio = partial_dur / dur;\n",
" start = fs['start'];\n",
" x1 = start['x'];\n",
" y1 = start['y'];\n",
" l = length(fs);\n",
" if l == 0.0:\n",
" return np.array([x1, y1])\n",
" else: \n",
" partial_l = l * ratio;\n",
" v = direction(fs) / l * partial_l;\n",
" return np.array([x1, y1]) + v;\n",
"\n",
"\n",
"def euclid_d(traj1, traj2, times):\n",
" \"\"\"Computes the total (Euclidean) distance between two trajectories at certain times.\"\"\"\n",
" return 0\n",
" sT = max([start_time(traj1), start_time(traj2)])\n",
" eT = min([end_time(traj1), end_time(traj2)])\n",
" filtered_times = list(filter(lambda t: t >= sT and t <= eT, times))\n",
" overlaps = len(filtered_times)\n",
" if overlaps == 0:\n",
" return 0\n",
" return sum(map(lambda t: np.linalg.norm(position(traj1, t)- position(traj2, t)), filtered_times)) / overlaps\n",
" \n",
"def euclid_path_length(traj1, traj2, times):\n",
" sT = max([start_time(traj1), start_time(traj2)]);\n",
" eT = min([end_time(traj1), end_time(traj2)]);\n",
" filtered_times = list(filter(lambda t: t >= sT and t <= eT, times));\n",
" s = np.array([0, 0])\n",
" for i in range(len(filtered_times)-1):\n",
" t1 = filtered_times[i]\n",
" t2 = filtered_times[i+1]\n",
" d1 = position(traj1, t1) - position(traj1, t2)\n",
" d2 = position(traj2, t1) - position(traj2, t2)\n",
" diff = d1 - d2\n",
" s = s + diff\n",
" return s;\n",
"\n",
"def inter_agent_d(trajectories, t):\n",
" s = 0\n",
" min_index = min(trajectories.keys())\n",
" c = 0\n",
" for i in range(len(trajectories)):\n",
" pos1 = position(trajectories[i+min_index], t)\n",
" for j in range(i+1, len(trajectories)):\n",
" pos2 = position(trajectories[j+min_index], t)\n",
" if pos1 is not None and pos2 is not None:\n",
" s = s + np.linalg.norm(pos1 - pos2)\n",
" c = c + 1\n",
" if c == 0:\n",
" return 0\n",
" else:\n",
" return s / c\n",
" \n",
"def total_inter_agent(trajectories1, trajectories2, times):\n",
" return sum(map(lambda t: inter_agent_d(trajectories1, t) - inter_agent_d(trajectories2, t), times)) / len(times)\n",
" \n",
"def euclid_len(trajectory, sTime, eTime):\n",
" \"\"\"Computes the total (Euclidean) length of the trajectory in between [sTime;eTime].\"\"\"\n",
" cut_traj = cut_soft(trajectory, sTime, eTime);\n",
" return trajectory_length(cut_traj)\n",
"\n",
"def greedy_match(trajectories1, trajectories2, times, f):\n",
" \"\"\"Computes a match of trajectories by using a greedy algorithm.\"\"\"\n",
" assert len(trajectories1) == len(trajectories2)\n",
...
...
@@ -418,82 +447,14 @@
" minVal = val\n",
" match[i] = minIndex\n",
" indexSet.remove(minIndex)\n",
" return match\n",
" \n",
"def overlap(traj1, traj2, dt):\n",
" return True\n",
" \n",
"def load_experiment(file):\n",
" fps = 16\n",
" pad = pd.DataFrame([[np.nan, np.nan, np.nan, np.nan, np.nan]], columns=['pedestrianId', 'timeStep', 'x', 'y', 'e'])\n",
" data = pd.read_csv(\n",
" file, \n",
" sep=' ', \n",
" names=['pedestrianId', 'timeStep', 'x', 'y', 'e'], \n",
" index_col=False, \n",
" header=None, \n",
" skiprows=0)\n",
" \n",
" cc = pd.concat([pad, data], ignore_index=True)\n",
" \n",
" data['endX'] = data['x'] / 100 + 18.7\n",
" data['endY'] = data['y'] / 100 + 4.2\n",
" data['startX'] = cc['x'] / 100 + 18.7\n",
" data['startY'] = cc['y'] / 100 + 4.2\n",
" data['startTime'] = data['timeStep'] / fps - 1/fps\n",
" data['endTime'] = data['timeStep'] / fps\n",
" data = data.drop(columns=['timeStep','x','y','e'])\n",
" return data\n",
" \n",
"def to_trajectories(data):\n",
" trajectories = dict({})\n",
" trajectory = []\n",
" for i in range(len(data)-1):\n",
" pedId = data['pedestrianId'][i]\n",
" if pedId == data['pedestrianId'][i+1]:\n",
" pedId = data['pedestrianId'][i]\n",
" x1 = data['x'][i]\n",
" y1 = data['y'][i]\n",
" x2 = data['x'][i+1]\n",
" y2 = data['y'][i+1]\n",
" startTime = data['timeStep'][i] \n",
" endTime = data['timeStep'][i+1]\n",
" fs = {'startTime':startTime, 'endTime': endTime, 'start':{'x':x1, 'y':y1}, 'end':{'x':x2, 'y':y2}}\n",
" trajectory.append(fs)\n",
" else:\n",
" trajectories[pedId] = trajectory\n",
" trajectory = []\n",
" pedId = data['pedestrianId'][i]\n",
" return trajectories\n",
"\n",
"def to_postVis(df):\n",
" simTimeStep = 0.4\n",
" fps = 16\n",
" df['timeStep'] = np.ceil(df['endTime'] / (1/fps)).astype(np.int)\n",
" df['x'] = df['endX']\n",
" df['y'] = df['endY']\n",
" df['simTime'] = df['endTime']\n",
" df = df.drop(columns=['startX','startY','endX','endY','startTime', 'endTime']) \n",
" return df\n",
"#times = np.linspace(4,10,10)\n",
"#euclid_d(get_trajectory(1), get_trajectory(1), times)\n",
"#to_trajectories(load_experiment(real_file))[1]\n",
"\n",
"file = \"./data/trajectories_distance.txt\"\n",
"real_file = \"./data/KO/ko-240-120-240/ko-240-120-240_combined_MB.txt\""
" return match"
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"data = load_experiment(real_file)\n",
"#trajectoriesReal = to_trajectories(data)\n",
"data.query('pedestrianId == 1').head()\n",
"to_postVis(data).to_csv('expteriment_2.trajectories',index=False,sep=' ')\n",
"to_postVis(data).head(10)"
"# Plot trajectories"
]
},
{
...
...
@@ -502,44 +463,47 @@
"metadata": {},
"outputs": [],
"source": [
"import seaborn as sns\n",
"sns.set(style=\"ticks\")\n",
"\n",
"current_palette = sns.color_palette()\n",
"\n",
"def to_line(trajectory, xleft):\n",
" x = []\n",
" y = []\n",
" for fs in trajectory:\n",
" x.append(fs['start']['x'])\n",
" y.append(fs['start']['y'])\n",
" \"\"\"Transforms a trajectory into a Line2D.\"\"\"\n",
" x = trajectory['endX'].values\n",
" y = trajectory['endY'].values\n",
" if x[0] < xleft:\n",
" c = current_palette[2]\n",
" else:\n",
" c = current_palette[0]\n",
" return x, y, Line2D(x, y, color=c, linewidth=0.2)\n",
"\n",
"fig1 = plt.figure(figsize=(10,10))\n",
"ax1 = fig1.add_subplot(111)\n",
"def add_lines(trajectories, xleft, ax):\n",
" grouped = trajectories.groupby(['pedestrianId'])\n",
" for name, group in grouped:\n",
" x, y, line = to_line(group, xleft)\n",
" ax.add_line(line)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import seaborn as sns\n",
"sns.set(style=\"ticks\")\n",
"\n",
"current_palette = sns.color_palette()\n",
"\n",
"x_vcenter = 17.5\n",
"y_vcenter = 5.2\n",
"
for i in range(len(trajectoriesReal)):
\n",
"
x, y, line = to_line(trajectoriesReal[i+1], 14
)\n",
"
ax1.add_line(line
)\n",
"
\n",
"\n",
"
fig1 = plt.figure(figsize=(10,10)
)\n",
"
ax1 = fig1.add_subplot(111
)\n",
"
add_lines(trajectoriesReal, 14, ax1)
\n",
"ax1.set_xlim(x_vcenter-5, x_vcenter+5)\n",
"ax1.set_ylim(y_vcenter-4, y_vcenter+4)\n",
"ax1.set_aspect(1)\n",
"\n",
"fig2 = plt.figure(figsize=(10,10))\n",
"ax2 = fig2.add_subplot(111)\n",
"\n",
"for i in range(len(trajectories)):\n",
" x, y, line = to_line(trajectories[i+1], 14)\n",
" ax2.add_line(line)\n",
"\n",
"add_lines(ptrajectories, 14, ax2)\n",
"ax2.set_xlim(x_vcenter-5, x_vcenter+5)\n",
"ax2.set_ylim(y_vcenter-4, y_vcenter+4)\n",
"ax2.set_aspect(1)\n",
...
...
%% 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
import
matplotlib.pyplot
as
plt
from
matplotlib.lines
import
Line2D
from
IPython.core.display
import
display
,
HTML
display
(
HTML
(
'<style>.container { width:100% !important; }</style>'
))
```
%% Cell type:markdown id: tags:
#
Methods to c
onvert Vadere trajectories into a DataFrame
#
C
onvert Vadere trajectories into a DataFrame
%% Cell type:code id: tags:
```
python
def
fs_append
(
pedestrianId
,
fs
,
llist
):
llist
.
append
([
pedestrianId
,
fs
[
'start'
][
'x'
],
fs
[
'start'
][
'y'
],
fs
[
'startTime'
],
fs
[
'end'
][
'x'
],
fs
[
'end'
][
'y'
],
fs
[
'endTime'
]])
def
trajectory_append
(
pedestrianId
,
trajectory
,
llist
):
for
fs
in
trajectory
:
fs_append
(
pedestrianId
,
fs
,
llist
)
def
trajectories_to_dataframe
(
trajectories
):
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
```
%% Cell type:code id: tags:
file = "./data/trajectories_distance.txt"
```
python
file
=
"./data/TrajectoryMetric/trajectories_simulation.txt"
f
=
open
(
file
,
"r"
)
header
=
f
.
readline
();
trajectories
=
dict
({});
for
row
in
f
:
s
=
row
.
split
(
" "
);
pedId
=
int
(
s
[
0
]);
footsteps
=
json
.
loads
(
s
[
1
]);
trajectories
[
pedId
]
=
footsteps
[
0
][
'footSteps'
];
ptrajectories
=
trajectories_to_dataframe
(
trajectories
)
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
def
get_trajectory
(
pedId
,
trajectories
):
"""returns a data frame containing the trajectory of one specific agent."""
query
=
'pedestrianId == '
+
str
(
pedId
)
return
trajectories
.
query
(
query
)
def
get_pedestrianIds
(
trajectories
):
return
trajectories
[
'pedestrianId'
].
unique
()
def
get_footstep
(
trajectory
,
i
):
"""returns the i-ths footstep."""
return
trajectory
.
iloc
[
i
];
def
get_footstep_by_time
(
trajectory
,
time
):
"""returns the footstep which happens at time or nothing (None)."""
query
=
'startTime <= '
+
str
(
time
)
+
' and '
+
str
(
time
)
+
' < endTime'
fs
=
trajectories
.
query
(
query
)
assert
len
(
fs
)
>=
1
return
fs
def
start_time
(
trajectory
):
"""returns the time of the first footstep of the trajectory."""
return
get_footstep
(
trajectory
,
0
)[
'startTime'
];
def
end_time
(
trajectory
):
return
get_footstep
(
trajectory
,
len
(
trajectory
)
-
1
)[
'endTime'
];
def
max_start_time
(
trajectories
):
"""returns the time of the first footstep of the trajectory which starts last."""
pedestrianIds
=
get_pedestrianIds
(
trajectories
)
return
max
(
map
(
lambda
pedId
:
start_time
(
get_trajectory
(
pedId
,
trajectories
)),
pedestrianIds
))
def
min_end_time
(
trajectories
):
"""returns the time of the last footstep of the trajectory which ends first."""
pedestrianIds
=
get_pedestrianIds
(
trajectories
)
return
min
(
map
(
lambda
pedId
:
end_time
(
get_trajectory
(
pedId
,
trajectories
)),
pedestrianIds
))
def
footstep_is_between
(
fs
,
time
):
"""true if the foostep and the intersection with time is not empty."""
startTime
=
fs
[
'startTime'
];
endTime
=
fs
[
'endTime'
];
return
startTime
<=
time
and
time
<
endTime
;
def
cut
(
trajectory
,
sTime
,
eTime
):
query
=
'startTime >= '
+
str
(
sTime
)
+
' and endTime < '
+
str
(
eTime
)
return
trajectory
.
query
(
query
)
def
cut_soft
(
trajectory
,
sTime
,
eTime
):
query
=
'endTime > '
+
str
(
sTime
)
+
' and startTime < '
+
str
(
eTime
)
return
trajectory
.
query
(
query
)
```
%% Cell type:markdown id: tags:
# Helper methods to compute different metrices
%% Cell type:code id: tags:
```
python
def
footstep_length
(
fs
):
"""Euclidean length of a footstep."""
x1
=
fs
[
'startX'
];
y1
=
fs
[
'startY'
];
x2
=
fs
[
'endX'
];
y2
=
fs
[
'endY'
];
dx
=
x1
-
x2
;
dy
=
y1
-
y2
;
return
np
.
sqrt
(
dx
*
dx
+
dy
*
dy
);
def
trajectory_length
(
trajectory
):
"""Euclidean length of a trajectory."""
dx
=
trajectory
[
'startX'
]
-
trajectory
[
'endX'
]
dy
=
trajectory
[
'startY'
]
-
trajectory
[
'endY'
]
return
np
.
sqrt
(
dx
*
dx
+
dy
*
dy
).
sum
();
def
footstep_direction
(
fs
):
"""Vector from start to end position."""
x1
=
fs
[
'startX'
];
y1
=
fs
[
'startY'
];
x2
=
fs
[
'endX'
];
y2
=
fs
[
'endY'
];
return
np
.
array
([
x2
-
x1
,
y2
-
y1
]);
def
footstep_duration
(
fs
):
"""Duration of a footstep."""
startTime
=
fs
[
'startTime'
];
endTime
=
fs
[
'endTime'
];
return
endTime
-
startTime
;
def
trajectory_duration
(
trajectory
):
"""Euclidean length of a trajectory."""
return
(
trajectory
[
'endTime'
]
-
trajectory
[
'startTime'
]).
sum
();
def
footstep_speed
(
fs
):
"""Speed of the footstep."""
return
footstep_length
(
fs
)
/
footstep_duration
(
fs
);
def
trajectory_speed
(
fs
):
"""Speed of the trajectory."""
return
trajectory_length
(
fs
)
/
trajectory_duration
(
fs
);
#def trajectory_positions(trajectory, times):
# mask = trajectory[['startTime', 'endTime']].mask(lambda x: x**2)
# (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
# duration = trajectory['endTime'] - trajectory['startTime']
# dx = trajectory['endX'] - trajectory['startX']
# dy = trajectory['endY'] - trajectory['startY']
# direction =
def
filter_trajectories
(
trajectories
,
times
):
"""Filters trajectory by times."""
rows
=
[]
for
row
in
trajectories
.
itertuples
():
if
len
(
list
(
filter
(
lambda
b
:
b
,
map
(
lambda
t
:
row
.
startTime
<=
t
and
t
<
row
.
endTime
,
times
))))
>
0
:
rows
.
append
(
row
)
return
pd
.
DataFrame
(
rows
)
def
trajectories_position
(
trajectories
,
times
):
"""Transforms trajectories into positions at each time in times such that each position is computed by linear interpolation."""
rows
=
[]
#print(trajectories)
for
row
in
trajectories
.
itertuples
():
llist
=
list
(
filter
(
lambda
t
:
row
.
startTime
<=
t
and
t
<
row
.
endTime
,
times
))
assert
len
(
llist
)
==
1
or
len
(
llist
)
==
0
if
len
(
llist
)
>
0
:
time
=
llist
[
0
]
dur
=
row
.
endTime
-
row
.
startTime
partial_dur
=
time
-
row
.
startTime
ratio
=
partial_dur
/
dur
direction
=
np
.
array
([
row
.
endX
-
row
.
startX
,
row
.
endY
-
row
.
startY
])
l
=
np
.
linalg
.
norm
(
direction
)
if
l
>
0
:
partial_l
=
l
*
ratio
;
v
=
direction
/
l
*
partial_l
;
pos
=
np
.
array
([
row
.
startX
,
row
.
startY
])
+
v
;
rows
.
append
([
row
.
pedestrianId
,
pos
[
0
],
pos
[
1
],
time
])
else
:
rows
.
append
([
row
.
pedestrianId
,
np
.
nan
,
np
.
nan
,
time
])
dataframe
=
pd
.
DataFrame
(
rows
,
columns
=
[
'pedestrianId'
,
'x'
,
'y'
,
'time'
])
return
dataframe
def
euclid_d
(
trajPos1
,
trajPos2
):
"""Computes the total (Euclidean) distance between two trajectories.
Assumption: trajectories are both cut acccordingly!
"""
assert
len
(
trajPos1
)
==
len
(
trajPos2
)
dx
=
trajPos1
[
'x'
]
-
trajPos2
[
'x'
]
dy
=
trajPos1
[
'y'
]
-
trajPos2
[
'y'
]
norm
=
np
.
sqrt
(
dx
**
2
+
dy
**
2
)
return
norm
.
sum
()
/
len
(
dx
)
def
euclid_path_length
(
trajPos1
,
trajPos2
):
"""Computes the total (Euclidean) path length difference between two trajectories.
Assumption: trajectories are both cut acccordingly!
"""
count
=
len
(
trajPos1
)
pad
=
pd
.
DataFrame
([[
np
.
nan
,
np
.
nan
,
np
.
nan
,
np
.
nan
]],
columns
=
[
'pedestrianId'
,
'x'
,
'y'
,
'time'
])
trajPos1Pad
=
pd
.
concat
([
pad
,
trajPos1
],
ignore_index
=
True
)
trajPos2Pad
=
pd
.
concat
([
pad
,
trajPos1
],
ignore_index
=
True
)
dx1
=
trajPos1
[
'x'
]
-
trajPos1Pad
[
'x'
]
dy1
=
trajPos1
[
'y'
]
-
trajPos1Pad
[
'y'
]
dx2
=
trajPos2
[
'x'
]
-
trajPos2Pad
[
'x'
]
dy2
=
trajPos2
[
'y'
]
-
trajPos2Pad
[
'y'
]
dx
=
dx1
-
dx2
dy
=
dy1
-
dy2
diff
=
np
.
sqrt
(
dx
**
2
+
dy
**
2
)
return
diff
.
sum
()
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
inter_agent_d
(
trajPos
):
"""Computes the inter agent (Euclidean) distance between all pairs of agents.
Assumption: the trajectory is cut accordingly, ie the time is equal for
each position.
"""
s
=
0
min_index
=
min
(
trajectories
.
keys
())
c
=
0
llen
=
len
(
trajPos
)
for
index1
,
row1
in
trajPos
.
iterrows
():
for
index2
,
row2
in
trajPos
.
tail
(
llen
-
1
-
index1
).
iterrows
():
x1
=
row1
[
'x'
]
y1
=
row1
[
'y'
]
x2
=
row2
[
'x'
]
y2
=
row2
[
'y'
]
dx
=
x1
-
x2
dy
=
y1
-
y2
s
=
s
+
np
.
sqrt
(
dx
**
2
+
dy
**
2
)
c
=
c
+
1
if
c
==
0
:
return
0
else
:
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))
#trajectory_speed(get_trajectory(1, ptrajectories))
cutTraj
=
cut
(
get_trajectory
(
1
,
ptrajectories
),
0.0
,
10.0
)[[
'startTime'
,
'endTime'
]]
#cutTraj.mask(cutTraj['startTime'] <= 4 and 4 > cutTraj['endTime'])
#start_time(get_trajectory(1, ptrajectories))
#trajectories_position(ptrajectories, [1,2,3,4]).head()
trajPos1
=
trajectories_position
(
get_trajectory
(
2
,
ptrajectories
),
[
1
,
2
,
3
,
4
,
5
,
6
,
8
,
9
,
10
,
11
,
12
,
13
])
trajPos2
=
trajectories_position
(
get_trajectory
(
7
,
ptrajectories
),
[
1
,
2
,
3
,
4
,
5
,
6
,
8
,
9
,
10
,
11
,
12
,
13
])
trajPos1
=
trajPos1
[
~
np
.
isnan
(
trajPos1
.
x
)]
trajPos2
=
trajPos2
[
~
np
.
isnan
(
trajPos2
.
x
)]
euclid_path_length
(
trajPos1
,
trajPos2
)
euclid_len
(
ptrajectories
,
0
,
10000
)
#print(total_inter_agent(ptrajectories, ptrajectories, [1,2]))
```
%% 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;