2.12.2021, 9:00 - 11:00: Due to updates GitLab may be unavailable for some minutes between 09:00 and 11:00.

TrajectoryMetric.ipynb 69.3 KB
Newer Older
1
2
{
 "cells": [
3
4
5
6
7
8
9
10
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Note\n",
    "You can find the required data on the Nextcloud data/Paperdaten/2019/TGF2019-vadere"
   ]
  },
11
12
13
14
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
15
16
   "outputs": [],
   "source": [
17
    "# expand the cell of the notebook\n",
18
    "import json\n",
19
    "import gc\n",
20
21
22
    "import numpy as np\n",
    "import pandas as pd\n",
    "import math\n",
23
    "import matplotlib as mpl\n",
24
25
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.lines import Line2D\n",
26
    "import seaborn as sns\n",
27
28
29
30
31
    "import functools\n",
    "import operator\n",
    "sns.set_context(\"poster\")\n",
    "sns.set(style=\"whitegrid\", font_scale=1.8)\n",
    "\n",
32
    "\n",
33
34
35
36
37
38
39
40
    "from IPython.core.display import display, HTML\n",
    "display(HTML('<style>.container { width:100% !important; }</style>'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
41
    "# Convert Vadere trajectories into a DataFrame"
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fs_append(pedestrianId, fs, llist):\n",
    "    llist.append([pedestrianId, fs['start']['x'], fs['start']['y'], fs['startTime'], fs['end']['x'], fs['end']['y'], fs['endTime']])\n",
    "   \n",
    "def trajectory_append(pedestrianId, trajectory, llist):\n",
    "    for fs in trajectory:\n",
    "        fs_append(pedestrianId, fs, llist)\n",
    "\n",
    "def trajectories_to_dataframe(trajectories):\n",
    "    llist = []\n",
    "    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",
62
63
    "    dataframe[\"distance\"] = np.sqrt(np.square(dataframe[\"endX\"] - dataframe[\"startX\"]) + np.square(dataframe[\"endY\"] - dataframe[\"startY\"]))\n",
    "    dataframe[\"velocity\"] = dataframe[\"distance\"] / (dataframe[\"endTime\"] - dataframe[\"startTime\"])\n",
64
65
66
67
68
69
70
71
72
    "    return dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
73
74
75
76
77
78
79
80
81
82
    "def load_simulation_data(file):\n",
    "    f = open(file, \"r\")\n",
    "    header = f.readline();\n",
    "    trajectories = dict({});\n",
    "    for row in f:\n",
    "        s = row.split(\" \");\n",
    "        pedId = int(s[0]);\n",
    "        footsteps = json.loads(s[1]);\n",
    "        trajectories[pedId] = footsteps[0]['footSteps'];   \n",
    "    return trajectories_to_dataframe(trajectories)"
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
  {
   "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",
    "    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",
108
109
110
111
112
113
    "    rows = []\n",
    "    #print(trajectories)\n",
    "    last_ped_id = None\n",
    "    lastX = None\n",
    "    lastY = None\n",
    "    for row in data.itertuples():\n",
114
115
    "        endX = row.x / 100.0 + 18.7\n",
    "        endY = row.y / 100.0 + 4.2\n",
116
117
118
119
120
121
122
123
    "        startTime = row.timeStep / fps - 1/fps\n",
    "        endTime = row.timeStep / fps\n",
    "        if last_ped_id is None or last_ped_id != row.pedestrianId:\n",
    "            startX = np.nan\n",
    "            startY = np.nan\n",
    "            distance = np.nan\n",
    "            velocity = np.nan\n",
    "        else:\n",
124
125
    "            startX = lastX / 100.0 + 18.7\n",
    "            startY = lastY / 100.0 + 4.2\n",
126
127
    "            distance = np.sqrt(np.square(endX - startX) + np.square(endY - startY))\n",
    "            velocity = distance / (endTime - startTime)\n",
128
    "            rows.append([row.pedestrianId, startX, startY, endX, endY, startTime, endTime, distance, velocity])\n",
129
130
131
132
133
134
    "        last_ped_id = row.pedestrianId\n",
    "        lastX = row.x\n",
    "        lastY = row.y\n",
    "            \n",
    "    dataframe = pd.DataFrame(rows, columns=['pedestrianId', 'startX', 'startY', 'endX', 'endY','startTime','endTime','distance','velocity'])\n",
    "    return dataframe\n",
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
    "    \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": "markdown",
   "metadata": {},
   "source": [
162
163
164
    "# Load all data\n",
    "\n",
    "The following code loads the experiment data as well as the simulated data and transforms everything into the same format (data frame). The simulated trajectories are cut with respect to the camera bounds of the experiment."
165
166
167
168
169
170
171
172
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
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
    "#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",
    "trajectories240o050o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-050-240/ko-240-050-240_combined_MB.txt\")\n",
    "trajectories240o060o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-060-240/ko-240-060-240_combined_MB.txt\")\n",
    "trajectories240o080o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-080-240/ko-240-080-240_combined_MB.txt\")\n",
    "trajectories240o100o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-100-240/ko-240-100-240_combined_MB.txt\")\n",
    "trajectories240o120o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-120-240/ko-240-120-240_combined_MB.txt\")\n",
    "trajectories240o150o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-150-240/ko-240-150-240_combined_MB.txt\")\n",
    "trajectories240o240o240 = load_experiment(\"./T-junction-experiment-trajectories-files/KO/ko-240-240-240/ko-240-240-240_combined_MB.txt\")\n",
    "\n",
    "trajectoriesReal = pd.concat([trajectories240o050o240, trajectories240o060o240, trajectories240o080o240, \n",
    "                              trajectories240o100o240, trajectories240o120o240, trajectories240o150o240, \n",
    "                              trajectories240o240o240], ignore_index=True)\n",
    "\n",
    "# trajectories starting from left\n",
    "cut_minX = trajectoriesReal[trajectoriesReal[\"endX\"] < 15].groupby([\"pedestrianId\"])[\"startX\"].min().max() + 0.12\n",
    "\n",
    "# trajectories starting from right\n",
    "cut_maxX = trajectoriesReal[trajectoriesReal[\"endX\"] > 21].groupby([\"pedestrianId\"])[\"startX\"].max().min() - 0.2\n",
    "\n",
    "# trajectories ending at top\n",
    "cut_maxY = trajectoriesReal.groupby([\"pedestrianId\"])[\"endY\"].max().min() - 0.168\n",
    "\n",
    "trajectories240o050o240 = cut(trajectories240o050o240, cut_minX, cut_maxX, cut_maxY)\n",
    "trajectories240o060o240 = cut(trajectories240o060o240, cut_minX, cut_maxX, cut_maxY)\n",
    "trajectories240o080o240 = cut(trajectories240o080o240, cut_minX, cut_maxX, cut_maxY)\n",
    "trajectories240o100o240 = cut(trajectories240o100o240, cut_minX, cut_maxX, cut_maxY)\n",
    "trajectories240o120o240 = cut(trajectories240o120o240, cut_minX, cut_maxX, cut_maxY)\n",
    "trajectories240o150o240 = cut(trajectories240o150o240, cut_minX, cut_maxX, cut_maxY)\n",
    "trajectories240o240o240 = cut(trajectories240o240o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o050o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-050-240.txt\")\n",
    "osm_trajectories240o050o240 = cut(osm_trajectories240o050o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o060o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-060-240.txt\")\n",
    "osm_trajectories240o060o240 = cut(osm_trajectories240o060o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o080o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-080-240.txt\")\n",
    "osm_trajectories240o080o240 = cut(osm_trajectories240o080o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o100o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-100-240.txt\")\n",
    "osm_trajectories240o100o240 = cut(osm_trajectories240o100o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o120o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-120-240.txt\")\n",
    "osm_trajectories240o120o240 = cut(osm_trajectories240o120o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o150o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-150-240.txt\")\n",
    "osm_trajectories240o150o240 = cut(osm_trajectories240o150o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "osm_trajectories240o240o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-OSM-240-240-240.txt\")\n",
    "osm_trajectories240o240o240 = cut(osm_trajectories240o240o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "trajectoriesOSM = pd.concat([osm_trajectories240o050o240, osm_trajectories240o060o240, osm_trajectories240o080o240, osm_trajectories240o100o240, osm_trajectories240o120o240, osm_trajectories240o150o240, osm_trajectories240o240o240], ignore_index=True)\n",
    "\n",
    "bhm_trajectories240o050o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-050-240.txt\")\n",
    "bhm_trajectories240o050o240 = cut(bhm_trajectories240o050o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "bhm_trajectories240o060o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-060-240.txt\")\n",
    "bhm_trajectories240o060o240 = cut(bhm_trajectories240o060o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "bhm_trajectories240o080o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-080-240.txt\")\n",
    "bhm_trajectories240o080o240 = cut(bhm_trajectories240o080o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "bhm_trajectories240o100o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-100-240.txt\")\n",
    "bhm_trajectories240o100o240 = cut(bhm_trajectories240o100o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "bhm_trajectories240o120o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-120-240.txt\")\n",
    "bhm_trajectories240o120o240 = cut(bhm_trajectories240o120o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "bhm_trajectories240o150o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-150-240.txt\")\n",
    "bhm_trajectories240o150o240 = cut(bhm_trajectories240o150o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "bhm_trajectories240o240o240 = load_simulation_data(\"./T-junction-sim-trajectory-files/trajectories-BHM-240-240-240.txt\")\n",
    "bhm_trajectories240o240o240 = cut(bhm_trajectories240o240o240, cut_minX, cut_maxX, cut_maxY)\n",
    "\n",
    "trajectoriesBHM = pd.concat([bhm_trajectories240o050o240, bhm_trajectories240o060o240, bhm_trajectories240o080o240, \n",
    "                             bhm_trajectories240o100o240, bhm_trajectories240o120o240, bhm_trajectories240o150o240, \n",
    "                             bhm_trajectories240o240o240], ignore_index=True)"
253
254
255
256
257
258
259
260
261
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sum up all measured time deltas of a pedestrian to get the final evacuation time\n",
262
263
    "copy = trajectoriesReal.copy(deep=True)\n",
    "copy[\"timeDelta\"] = copy[\"endTime\"] - copy[\"startTime\"]\n",
264
    "et = copy.groupby([\"pedestrianId\"])[\"timeDelta\"].sum()\n",
265
    "print(\"Evacuation time (real data)\")\n",
266
267
268
269
    "print(\"- mean: {:.2f} [s]\".format(et.mean()))\n",
    "print(\"- std: {:.2f} [s]\".format(et.std()))\n",
    "print(\"- min: {:.2f} [s]\".format(et.min()))\n",
    "print(\"- max: {:.2f} [s]\".format(et.max()))\n",
270
271
272
273
274
    "print(\"- minX: {:.2f} [m]\".format(cut_minX))\n",
    "print(\"- maxX: {:.2f} [m]\".format(cut_maxX))\n",
    "print(\"- maxY: {:.2f} [m]\".format(cut_maxY))"
   ]
  },
275
276
277
278
279
280
281
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convert DataFrame to postvis DataFrame"
   ]
  },
282
283
284
285
286
287
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
288
289
290
291
292
293
294
295
296
    "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"
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "TODO: Use `PedestrianEvacuationTimeProcessor` to log evacuation time during simulation and analyze it here."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Helper method to access parts of the trajectory"
318
319
320
321
322
323
324
325
326
327
328
329
330
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_trajectory(pedId, trajectories):\n",
    "    \"\"\"returns a data frame containing the trajectory of one specific agent.\"\"\"\n",
    "    query = 'pedestrianId == ' + str(pedId)\n",
    "    return trajectories.query(query)\n",
    "\n",
331
    "def get_trajectories(t, trajectories):\n",
332
    "    return trajectories[np.logical_and(trajectories.startTime <= t, trajectories.endTime > t)]\n",
333
    "\n",
334
335
    "def get_pedestrianIds(trajectories):\n",
    "    return trajectories['pedestrianId'].unique()\n",
336
    "\n",
337
338
339
    "#def get_velocity(trajectories, t, dt):\n",
    "#    trajectories[np.logical_and(trajectory.endX >= xmax, trajectory.startX < xmax)]\n",
    "\n",
340
    "def get_footstep(trajectory, i):\n",
341
342
    "    \"\"\"returns the i-ths footstep.\"\"\"\n",
    "    return trajectory.iloc[i];\n",
343
    "\n",
344
345
346
347
348
349
    "def get_footstep_by_time(trajectory, time):\n",
    "    \"\"\"returns the footstep which happens at time or nothing (None).\"\"\"\n",
    "    query = 'startTime <= ' + str(time) + ' and ' + str(time) + ' < endTime'\n",
    "    fs = trajectories.query(query)\n",
    "    assert len(fs) >= 1\n",
    "    return fs\n",
350
    "\n",
351
352
353
    "def start_time(trajectory):\n",
    "    \"\"\"returns the time of the first footstep of the trajectory.\"\"\"\n",
    "    return get_footstep(trajectory, 0)['startTime'];\n",
354
355
    "\n",
    "def end_time(trajectory):\n",
356
357
358
359
360
361
    "    return get_footstep(trajectory, len(trajectory)-1)['endTime'];\n",
    "\n",
    "def max_start_time(trajectories):\n",
    "    \"\"\"returns the time of the first footstep of the trajectory which starts last.\"\"\"\n",
    "    pedestrianIds = get_pedestrianIds(trajectories)\n",
    "    return max(map(lambda pedId: start_time(get_trajectory(pedId, trajectories)), pedestrianIds))\n",
362
363
    "\n",
    "def min_end_time(trajectories):\n",
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    "    \"\"\"returns the time of the last footstep of the trajectory which ends first.\"\"\"\n",
    "    pedestrianIds = get_pedestrianIds(trajectories)\n",
    "    return min(map(lambda pedId: end_time(get_trajectory(pedId, trajectories)), pedestrianIds))\n",
    "\n",
    "def footstep_is_between(fs, time):\n",
    "    \"\"\"true if the foostep and the intersection with time is not empty.\"\"\"\n",
    "    startTime = fs['startTime'];\n",
    "    endTime = fs['endTime'];\n",
    "    return startTime <= time and time < endTime;\n",
    "\n",
    "def cut(trajectory, sTime, eTime):\n",
    "    query = 'startTime >= ' + str(sTime) + ' and endTime < ' + str(eTime)\n",
    "    return trajectory.query(query)\n",
    "\n",
    "def cut_soft(trajectory, sTime, eTime):\n",
    "    query = 'endTime > ' + str(sTime) + ' and startTime < ' + str(eTime)\n",
380
381
382
383
384
385
386
387
    "    return trajectory.query(query)\n",
    "\n",
    "def cuthead_trajectory_by(trajectory, ymin, ymax):\n",
    "    i1 = trajectory[trajectory.endY >= ymax].index.min()\n",
    "    i2 = trajectory[trajectory.endY <= ymin].index.min()\n",
    "    #assert (i1 is np.nan and i2 is not np.nan) or (i1 is not np.nan and i2 is np.nan)\n",
    "    y = ymax if i2 is np.nan or (i1 is not np.nan and i1 < i2) else ymin\n",
    "    i = i1 if y == ymax else i2\n",
388
389
390
391
392
    "    if i is np.nan:\n",
    "        print(\"i1:\"+str(i1))\n",
    "        print(\"i2:\"+str(i2))\n",
    "        \n",
    "    assert i is not np.nan\n",
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
    "    #print(i)\n",
    "    # cut the footstep at the tail to exactly fit xmin or xmax\n",
    "    fs = trajectory.loc[i]\n",
    "    start = np.array([fs[\"startX\"], fs[\"startY\"]])\n",
    "    end = np.array([fs[\"endX\"], fs[\"endY\"]])\n",
    "    endTime = fs[\"endTime\"]\n",
    "    startTime = fs[\"startTime\"]\n",
    "    distance = fs[\"distance\"]\n",
    "    velocity = fs[\"velocity\"]\n",
    "    d = end - start\n",
    "    if abs(fs[\"endY\"] - fs[\"startY\"]) > 0.00001:\n",
    "        r = (y - fs[\"startY\"]) / (fs[\"endY\"] - fs[\"startY\"])\n",
    "        end = start + (d * r)\n",
    "        time = fs[\"endTime\"] - fs[\"startTime\"]\n",
    "        endTime = fs[\"startTime\"] + (time * r)\n",
    "        distance = np.linalg.norm(end - start)\n",
    "        velocity = distance / (endTime - startTime)\n",
    "        \n",
    "    df = trajectory.loc[:i-1]\n",
    "    llist = [[fs[\"pedestrianId\"],fs[\"startX\"],fs[\"startY\"],fs[\"startTime\"],end[0],end[1],endTime,distance,velocity]]\n",
    "    df_head = pd.DataFrame(llist, columns=['pedestrianId','startX','startY','startTime','endX','endY','endTime','distance','velocity'])\n",
    "    df = df.append(df_head, ignore_index=True)\n",
    "    return df\n",
    "\n",
    "def cuttail_trajectory_by(trajectory, xmin, xmax):\n",
    "    #i1 = trajectory[np.logical_and(trajectory.endX >= xmax, trajectory.startX < xmax)].index.max()\n",
419
420
    "    i1 = trajectory[trajectory.startX >= xmax].index.max()\n",
    "    i2 = trajectory[trajectory.startX <= xmin].index.max()\n",
421
422
423
    "    #assert (i1 is np.nan and i2 is not np.nan) or (i1 is not np.nan and i2 is np.nan)\n",
    "    x = xmax if i2 is np.nan or (i1 is not np.nan and i1 > i2) else xmin\n",
    "    i = i1 if x == xmax else i2\n",
424
    "    assert i is not np.nan\n",
425
426
427
428
429
430
431
432
433
434
    "    # cut the footstep at the tail to exactly fit xmin or xmax\n",
    "    fs = trajectory.loc[i]\n",
    "    start = np.array([fs[\"startX\"], fs[\"startY\"]])\n",
    "    end = np.array([fs[\"endX\"], fs[\"endY\"]])\n",
    "    startTime = fs[\"startTime\"]\n",
    "    endTime = fs[\"endTime\"]\n",
    "    distance = fs[\"distance\"]\n",
    "    velocity = fs[\"velocity\"]\n",
    "    d = end - start\n",
    "    if abs(fs[\"endX\"] - fs[\"startX\"]) > 0.00001:\n",
435
436
    "        r = (fs[\"endX\"] - x) / (fs[\"endX\"] - fs[\"startX\"])\n",
    "        start = end - (d * r)\n",
437
    "        time = fs[\"endTime\"] - fs[\"startTime\"]\n",
438
    "        startTime = fs[\"endTime\"] - (time * r)\n",
439
    "        distance = np.linalg.norm(end - start)\n",
440
441
    "        velocity = distance / (endTime - startTime)\n",
    "        assert startTime <= endTime\n",
442
443
    "        \n",
    "    df = trajectory.loc[i+1:]\n",
444
    "    llist = [[fs[\"pedestrianId\"],start[0],start[1],startTime,fs[\"endX\"],fs[\"endY\"],fs[\"endTime\"],distance,velocity]]\n",
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
    "    df_tail = pd.DataFrame(llist, columns=['pedestrianId','startX','startY','startTime','endX','endY','endTime','distance','velocity'])\n",
    "    df_tail = df_tail.append(df, ignore_index=True)\n",
    "    return df_tail\n",
    "\n",
    "def cuthead_by(trajectories, ymin, ymax):\n",
    "    df = pd.DataFrame([], columns=['pedestrianId','startX','startY','startTime','endX','endY','endTime'])\n",
    "    pedIds = get_pedestrianIds(trajectories)\n",
    "    for pedId in pedIds:\n",
    "        df = df.append(cuthead_trajectory_by(get_trajectory(pedId, trajectories), ymin, ymax), ignore_index=True)\n",
    "    return df\n",
    "\n",
    "def cuttail_by(trajectories, xmin, xmax):\n",
    "    df = pd.DataFrame([], columns=['pedestrianId','startX','startY','startTime','endX','endY','endTime'])\n",
    "    pedIds = get_pedestrianIds(trajectories)\n",
    "    for pedId in pedIds:\n",
    "        df = df.append(cuttail_trajectory_by(get_trajectory(pedId, trajectories), xmin, xmax), ignore_index=True)\n",
    "    return df\n",
    "\n",
463
    "def cut(trajectories, cut_minX, cut_maxX, cut_maxY):\n",
464
465
    "    df = cuttail_by(trajectories, cut_minX, cut_maxX)\n",
    "    df = cuthead_by(df, -1000, cut_maxY)\n",
466
    "    return df"
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Helper methods to compute different metrices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def footstep_length(fs):\n",
    "    \"\"\"Euclidean length of a footstep.\"\"\"\n",
    "    x1 = fs['startX'];\n",
    "    y1 = fs['startY'];\n",
    "    x2 = fs['endX'];\n",
    "    y2 = fs['endY'];\n",
488
489
490
491
    "    dx = x1-x2;\n",
    "    dy = y1-y2;\n",
    "    return np.sqrt(dx*dx + dy*dy);\n",
    "\n",
492
493
494
    "def mean_velocity_at(t, trajectories):\n",
    "    return get_trajectories(t, trajectories)['velocity'].mean()\n",
    "\n",
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    "def evacuation_times(trajectories):\n",
    "    pedIds = get_pedestrianIds(trajectories)\n",
    "    rows = []\n",
    "    for pedId in pedIds:\n",
    "        evacTime = evacuation_time(pedId, trajectories)\n",
    "        rows.append([pedId, evacTime])\n",
    "    return pd.DataFrame(rows, columns=['pedestrianId', 'evacuationTime'])\n",
    "    \n",
    "def evacuation_time(pedId, trajectories):\n",
    "    traj = get_trajectory(pedId, trajectories)\n",
    "    start = traj.iloc[0]['endTime']\n",
    "    end = traj.iloc[len(traj)-1]['endTime']\n",
    "    return end - start\n",
    "\n",
509
    "def trajectory_length(trajectory):\n",
510
511
512
513
514
515
516
517
518
519
520
    "    \"\"\"Euclidean length of a trajectory.\"\"\"\n",
    "    dx = trajectory['startX']-trajectory['endX']\n",
    "    dy = trajectory['startY']-trajectory['endY']\n",
    "    return np.sqrt(dx*dx + dy*dy).sum();\n",
    "\n",
    "def footstep_direction(fs):\n",
    "    \"\"\"Vector from start to end position.\"\"\"\n",
    "    x1 = fs['startX'];\n",
    "    y1 = fs['startY'];\n",
    "    x2 = fs['endX'];\n",
    "    y2 = fs['endY'];\n",
521
522
    "    return np.array([x2-x1, y2-y1]);\n",
    "\n",
523
524
    "def footstep_duration(fs):\n",
    "    \"\"\"Duration of a footstep.\"\"\"\n",
525
526
527
528
    "    startTime = fs['startTime'];\n",
    "    endTime = fs['endTime'];\n",
    "    return endTime-startTime;\n",
    "\n",
529
530
531
    "def trajectory_duration(trajectory):\n",
    "    \"\"\"Euclidean length of a trajectory.\"\"\"\n",
    "    return (trajectory['endTime'] - trajectory['startTime']).sum();\n",
532
    "\n",
533
534
535
    "def footstep_speed(fs):\n",
    "    \"\"\"Speed of the footstep.\"\"\"\n",
    "    return footstep_length(fs) / footstep_duration(fs);\n",
536
    "\n",
537
538
539
    "def trajectory_speed(fs):\n",
    "    \"\"\"Speed of the trajectory.\"\"\"\n",
    "    return trajectory_length(fs) / trajectory_duration(fs);\n",
540
    "\n",
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
    "#def trajectory_positions(trajectory, times):\n",
    "#    mask = trajectory[['startTime', 'endTime']].mask(lambda x: x**2)\n",
    "#    (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')\n",
    "#    duration = trajectory['endTime'] - trajectory['startTime']\n",
    "#    dx = trajectory['endX'] - trajectory['startX']\n",
    "#    dy = trajectory['endY'] - trajectory['startY']\n",
    "#    direction = \n",
    "    \n",
    "def filter_trajectories(trajectories, times):\n",
    "    \"\"\"Filters trajectory by times.\"\"\"\n",
    "    rows = []\n",
    "    for row in trajectories.itertuples():\n",
    "        if len(list(filter(lambda b: b, map(lambda t: row.startTime <= t and t < row.endTime, times)))) > 0:\n",
    "            rows.append(row)\n",
    "    return pd.DataFrame(rows)\n",
    "\n",
    "def trajectories_position(trajectories, times):\n",
    "    \"\"\"Transforms trajectories into positions at each time in times such that each position is computed by linear interpolation.\"\"\"\n",
    "    rows = []\n",
    "    #print(trajectories)\n",
    "    for row in trajectories.itertuples():\n",
    "        llist = list(filter(lambda t: row.startTime <= t and t < row.endTime, times))\n",
    "        assert len(llist) == 1 or len(llist) == 0\n",
    "        if len(llist) > 0:\n",
    "            time = llist[0]\n",
    "            dur = row.endTime - row.startTime\n",
    "            partial_dur = time - row.startTime\n",
    "            ratio = partial_dur / dur\n",
    "            direction = np.array([row.endX - row.startX, row.endY - row.startY])\n",
    "            l = np.linalg.norm(direction)\n",
    "            if l > 0:\n",
    "                partial_l = l * ratio;\n",
    "                v = direction / l * partial_l;\n",
    "                pos = np.array([row.startX, row.startY]) + v;\n",
    "                rows.append([row.pedestrianId, pos[0], pos[1], time])\n",
    "            else:\n",
    "                rows.append([row.pedestrianId, np.nan, np.nan, time])\n",
    "    dataframe = pd.DataFrame(rows, columns=['pedestrianId','x','y','time'])\n",
    "    return dataframe\n",
    "    \n",
    "def euclid_d(trajPos1, trajPos2):\n",
    "    \"\"\"Computes the total (Euclidean) distance between two trajectories.\n",
    "       Assumption: trajectories are both cut acccordingly!   \n",
    "    \"\"\"\n",
    "    assert len(trajPos1) == len(trajPos2)\n",
    "    dx = trajPos1['x'] - trajPos2['x']\n",
    "    dy = trajPos1['y'] - trajPos2['y']\n",
    "    norm = np.sqrt(dx**2 + dy**2)\n",
    "    return norm.sum() / len(dx)\n",
    "\n",
    "def euclid_path_length(trajPos1, trajPos2):\n",
    "    \"\"\"Computes the total (Euclidean) path length difference between two trajectories.\n",
    "       Assumption: trajectories are both cut acccordingly!\n",
    "    \"\"\"\n",
    "    count = len(trajPos1)\n",
    "    pad = pd.DataFrame([[np.nan, np.nan, np.nan, np.nan]], columns=['pedestrianId','x','y','time'])\n",
    "    trajPos1Pad = pd.concat([pad, trajPos1], ignore_index=True)\n",
    "    trajPos2Pad = pd.concat([pad, trajPos1], ignore_index=True)\n",
    "    dx1 = trajPos1['x'] - trajPos1Pad['x']\n",
    "    dy1 = trajPos1['y'] - trajPos1Pad['y']\n",
    "    dx2 = trajPos2['x'] - trajPos2Pad['x']\n",
    "    dy2 = trajPos2['y'] - trajPos2Pad['y']\n",
    "    dx = dx1 - dx2\n",
    "    dy = dy1 - dy2\n",
    "    diff = np.sqrt(dx**2 + dy**2)\n",
    "    return diff.sum()\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 inter_agent_d(trajPos):\n",
    "    \"\"\"Computes the inter agent (Euclidean) distance between all pairs of agents.\n",
    "       Assumption: the trajectory is cut accordingly, ie the time is equal for\n",
    "       each position.\n",
    "    \"\"\"\n",
    "    s = 0\n",
    "    min_index = min(trajectories.keys())\n",
    "    c = 0\n",
    "    llen = len(trajPos)\n",
    "    for index1, row1 in trajPos.iterrows():\n",
    "        for index2, row2 in trajPos.tail(llen-1-index1).iterrows():\n",
    "            x1 = row1['x']\n",
    "            y1 = row1['y']\n",
    "            x2 = row2['x']\n",
    "            y2 = row2['y']\n",
    "            dx = x1 - x2\n",
    "            dy = y1 - y2\n",
    "            s = s + np.sqrt(dx**2 + dy**2)\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",
    "    \"\"\"too expensive! TODO!\"\"\"\n",
639
640
641
642
643
644
645
646
647
    "    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": [
648
649
    "trajPos1 = trajectories_position(get_trajectory(2, osm_trajectories240o120o240), [1,2,3,4,5,6,8,9,10,11,12,13])\n",
    "trajPos2 = trajectories_position(get_trajectory(7, osm_trajectories240o120o240), [1,2,3,4,5,6,8,9,10,11,12,13])\n",
650
651
652
    "trajPos1 = trajPos1[~np.isnan(trajPos1.x)]\n",
    "trajPos2 = trajPos2[~np.isnan(trajPos2.x)]\n",
    "euclid_path_length(trajPos1, trajPos2)\n",
653
    "euclid_len(osm_trajectories240o120o240,0,10000)\n",
654
    "t = 0.5\n",
655
656
657
    "ttraj = osm_trajectories240o120o240[np.logical_and(osm_trajectories240o120o240.startTime <= t, osm_trajectories240o120o240.endTime >= t)]\n",
    "get_trajectories(0.5, osm_trajectories240o120o240).head()\n",
    "#osm_trajectories240o120o240"
658
659
660
661
662
663
664
665
666
667
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "code_folding": []
   },
   "outputs": [],
   "source": [
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    "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",
    "    min_index1 = min(trajectories1.keys())\n",
    "    min_index2 = min(trajectories2.keys())\n",
    "    match = {}\n",
    "    indexSet = set(range(min_index2, len(trajectories2)))\n",
    "    for i in range(min_index1, len(trajectories1)):\n",
    "        traj1 = trajectories1[i]\n",
    "        minVal = None\n",
    "        minIndex = None\n",
    "        for j in indexSet:\n",
    "            traj2 = trajectories2[j]\n",
    "            if overlap(traj1, traj2, 0.4):\n",
    "                val = f(traj1, traj2, times)\n",
    "                if(minVal == None or val < minVal):\n",
    "                    minIndex = j\n",
    "                    minVal = val\n",
    "        match[i] = minIndex\n",
    "        indexSet.remove(minIndex)\n",
688
    "    return match"
689
690
   ]
  },
691
692
693
694
695
696
697
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot trajectories\n",
    "\n",
    "Now we plot the cut trajectories."
698
699
700
701
702
703
704
705
706
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def to_line(trajectory, xleft):\n",
707
    "    \"\"\"Transforms a trajectory into a Line2D.\"\"\"\n",
708
    "    current_palette = sns.color_palette()\n",
709
710
    "    x = trajectory['endX'].values\n",
    "    y = trajectory['endY'].values\n",
711
712
713
714
    "    if x[0] < xleft:\n",
    "        c = current_palette[2]\n",
    "    else:\n",
    "        c = current_palette[0]\n",
715
    "    return x, y, Line2D(x, y, color=c, linewidth=0.4)\n",
716
    "\n",
717
718
719
720
    "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",
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
    "        ax.add_line(line)\n",
    "        \n",
    "def contains(x,y,rect):\n",
    "    #ma = mpl.patches.Rectangle((16.3,6.0), 2.4, 2.0)\n",
    "    return x >= rect.get_x() and y >= rect.get_y() and x <= rect.get_x() + rect.get_width() and y <= rect.get_y() + rect.get_height()\n",
    "\n",
    "def filter_by_time_and_place(t, rect, trajectories):\n",
    "    \"\"\"returns a subset of trajectories i.e. at most one footstep for each pedestrian / agent such that the footstep the position (x,y) is the position of the\n",
    "    agent at the time t contained in the rectanlge rect. Two new colums will be added for x and y.\"\"\"\n",
    "    traj = get_trajectories(t, trajectories)\n",
    "    #TODO: this is very very memory expensive!\n",
    "    traj.loc[:,'x'] = traj.loc[:,'startX'] + (traj.loc[:,'endX'] - traj.loc[:,'startX']) * (t - traj.loc[:,'startTime']) / (traj.loc[:,'endTime'] - traj.loc[:,'startTime'])\n",
    "    traj.loc[:,'y'] = traj.loc[:,'startY'] + (traj.loc[:,'endY'] - traj.loc[:,'startY']) * (t - traj.loc[:,'startTime']) / (traj.loc[:,'endTime'] - traj.loc[:,'startTime'])\n",
    "    #traj.loc[:,'x'] = traj.loc[:,'startX']\n",
    "    #traj.loc[:,'y'] = traj.loc[:,'startY']\n",
    "    traj = traj[traj.apply(lambda x: contains(x['x'], x['y'],rect), axis=1)]\n",
    "    return traj\n",
    "\n",
    "def density_velocity(t, rect, trajectories):\n",
    "    area = rect.get_width() * rect.get_height()\n",
    "    traj = filter_by_time_and_place(t, rect, trajectories)\n",
    "    meanVelocity = traj.loc[:,'velocity'].mean();\n",
    "    number_of_peds = len(traj)\n",
    "    traj = None\n",
    "    #gc.collect()\n",
    "    if number_of_peds == 0:\n",
    "        return np.nan, np.nan\n",
    "    else:\n",
    "        return number_of_peds / area, meanVelocity\n",
    "\n",
    "def density(t, rect, trajectories):\n",
    "    area = rect.get_width() * rect.get_height()\n",
    "    traj = filter_by_time_and_place(t, rect, trajectories)\n",
    "    number_of_peds = len(traj)\n",
    "    traj = None\n",
    "    #gc.collect()\n",
    "    if number_of_peds == 0:\n",
    "        return np.nan\n",
    "    else:\n",
    "        return number_of_peds / area"
761
762
763
764
765
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
766
767
768
   "metadata": {
    "scrolled": false
   },
769
770
   "outputs": [],
   "source": [
771
772
    "x_vcenter = 17.5\n",
    "y_vcenter = 5.2\n",
773
    "\n",
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
    "xmin = x_vcenter-4\n",
    "xmax = x_vcenter+5\n",
    "ymin = y_vcenter-3.2\n",
    "ymax = y_vcenter+3\n",
    "\n",
    "alp = 0.549020\n",
    "measurementArea_front = mpl.patches.Rectangle((16.3,6.0), 2.4, 2.0, color='r', alpha = alp)\n",
    "measurementArea_left = mpl.patches.Rectangle((14.2,1.8), 2.0, 2.4, color='r', alpha = alp)\n",
    "measurementArea_right = mpl.patches.Rectangle((19.7,1.8), 2.0, 2.4, color='r', alpha = alp)\n",
    "\n",
    "fig_trajectories = plt.figure(figsize=(20,20))\n",
    "ax1_trajectories = fig_trajectories.add_subplot(131)\n",
    "ax1_trajectories.add_patch(measurementArea_left)\n",
    "ax1_trajectories.add_patch(measurementArea_right)\n",
    "ax1_trajectories.add_patch(measurementArea_front)\n",
    "add_lines(trajectories240o150o240, 16, ax1_trajectories)\n",
    "ax1_trajectories.set_title(\"Experiment\")\n",
    "ax1_trajectories.set_xlim(xmin, xmax)\n",
    "ax1_trajectories.set_ylim(ymin, ymax)\n",
793
    "ax1_trajectories.set_aspect(1)\n",
794
    "\n",
795
796
797
798
799
    "ax2_trajectories = fig_trajectories.add_subplot(132, sharey=ax1_trajectories)\n",
    "ax2_trajectories.add_patch(mpl.patches.Rectangle((16.3,6.0), 2.4, 2.0, color='r', alpha = alp))\n",
    "ax2_trajectories.add_patch(mpl.patches.Rectangle((14.2,1.8), 2.0, 2.4, color='r', alpha = alp))\n",
    "ax2_trajectories.add_patch(mpl.patches.Rectangle((19.7,1.8), 2.0, 2.4, color='r', alpha = alp))\n",
    "add_lines(osm_trajectories240o150o240, 16, ax2_trajectories)\n",
800
    "plt.setp(ax2_trajectories.get_yticklabels(), visible=False)\n",
801
802
803
    "ax2_trajectories.set_title(\"OSM\")\n",
    "ax2_trajectories.set_xlim(xmin, xmax)\n",
    "ax2_trajectories.set_ylim(ymin, ymax)\n",
804
    "ax2_trajectories.set_aspect(1)\n",
805
    "\n",
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
    "ax3_trajectories = fig_trajectories.add_subplot(133, sharey=ax2_trajectories)\n",
    "ax3_trajectories.add_patch(mpl.patches.Rectangle((16.3,6.0), 2.4, 2.0, color='r', alpha = alp))\n",
    "ax3_trajectories.add_patch(mpl.patches.Rectangle((14.2,1.8), 2.0, 2.4, color='r', alpha = alp))\n",
    "ax3_trajectories.add_patch(mpl.patches.Rectangle((19.7,1.8), 2.0, 2.4, color='r', alpha = alp))\n",
    "add_lines(bhm_trajectories240o150o240, 16, ax3_trajectories)\n",
    "plt.setp(ax3_trajectories.get_yticklabels(), visible=False)\n",
    "ax3_trajectories.set_title(\"BHM\")\n",
    "ax3_trajectories.set_xlim(xmin, xmax)\n",
    "ax3_trajectories.set_ylim(ymin, ymax)\n",
    "ax3_trajectories.set_aspect(1)\n",
    "plt.savefig('./trajectories.pdf', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Computation of evacuation times"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#240-050-240\n",
    "evacTime240o050o240 = evacuation_times(trajectories240o050o240)\n",
    "evacTime240o050o240['scenario'] = '$b_{in} = 50$'\n",
    "evacTime240o050o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o050o240 = evacuation_times(osm_trajectories240o050o240)\n",
    "osm_evacTime240o050o240['scenario'] = '$b_{in} = 50$'\n",
    "osm_evacTime240o050o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o050o240 = evacuation_times(bhm_trajectories240o050o240)\n",
    "bhm_evacTime240o050o240['scenario'] = '$b_{in} = 50$'\n",
    "bhm_evacTime240o050o240['model'] = 'BHM'\n",
    "\n",
    "#240-060-240\n",
    "evacTime240o060o240 = evacuation_times(trajectories240o060o240)\n",
    "evacTime240o060o240['scenario'] = '$b_{in} = 60$'\n",
    "evacTime240o060o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o060o240 = evacuation_times(osm_trajectories240o060o240)\n",
    "osm_evacTime240o060o240['scenario'] = '$b_{in} = 60$'\n",
    "osm_evacTime240o060o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o060o240 = evacuation_times(bhm_trajectories240o060o240)\n",
    "bhm_evacTime240o060o240['scenario'] = '$b_{in} = 60$'\n",
    "bhm_evacTime240o060o240['model'] = 'BHM'\n",
    "\n",
    "#240-080-240\n",
    "evacTime240o080o240 = evacuation_times(trajectories240o080o240)\n",
    "evacTime240o080o240['scenario'] = '$b_{in} = 80$'\n",
    "evacTime240o080o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o080o240 = evacuation_times(osm_trajectories240o080o240)\n",
    "osm_evacTime240o080o240['scenario'] = '$b_{in} = 80$'\n",
    "osm_evacTime240o080o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o080o240 = evacuation_times(bhm_trajectories240o080o240)\n",
    "bhm_evacTime240o080o240['scenario'] = '$b_{in} = 80$'\n",
    "bhm_evacTime240o080o240['model'] = 'BHM'\n",
    "\n",
    "#240-100-240\n",
    "evacTime240o100o240 = evacuation_times(trajectories240o100o240)\n",
    "evacTime240o100o240['scenario'] = '$b_{in} = 100$'\n",
    "evacTime240o100o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o100o240 = evacuation_times(osm_trajectories240o100o240)\n",
    "osm_evacTime240o100o240['scenario'] = '$b_{in} = 100$'\n",
    "osm_evacTime240o100o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o100o240 = evacuation_times(bhm_trajectories240o100o240)\n",
    "bhm_evacTime240o100o240['scenario'] = '$b_{in} = 100$'\n",
    "bhm_evacTime240o100o240['model'] = 'BHM'\n",
    "\n",
    "#240-120-240\n",
    "evacTime240o120o240 = evacuation_times(trajectories240o120o240)\n",
    "evacTime240o120o240['scenario'] = '$b_{in} = 120$'\n",
    "evacTime240o120o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o120o240 = evacuation_times(osm_trajectories240o120o240)\n",
    "osm_evacTime240o120o240['scenario'] = '$b_{in} = 120$'\n",
    "osm_evacTime240o120o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o120o240 = evacuation_times(bhm_trajectories240o120o240)\n",
    "bhm_evacTime240o120o240['scenario'] = '$b_{in} = 120$'\n",
    "bhm_evacTime240o120o240['model'] = 'BHM'\n",
    "\n",
    "#240-150-240\n",
    "evacTime240o150o240 = evacuation_times(trajectories240o150o240)\n",
    "evacTime240o150o240['scenario'] = '$b_{in} = 150$'\n",
    "evacTime240o150o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o150o240 = evacuation_times(osm_trajectories240o150o240)\n",
    "osm_evacTime240o150o240['scenario'] = '$b_{in} = 150$'\n",
    "osm_evacTime240o150o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o150o240 = evacuation_times(bhm_trajectories240o150o240)\n",
    "bhm_evacTime240o150o240['scenario'] = '$b_{in} = 150$'\n",
    "bhm_evacTime240o150o240['model'] = 'BHM'\n",
    "\n",
    "#240-240-240\n",
    "evacTime240o240o240 = evacuation_times(trajectories240o240o240)\n",
    "evacTime240o240o240['scenario'] = '$b_{in} = 240$'\n",
    "evacTime240o240o240['model'] = 'Experiment'\n",
    "\n",
    "osm_evacTime240o240o240 = evacuation_times(osm_trajectories240o240o240)\n",
    "osm_evacTime240o240o240['scenario'] = '$b_{in} = 240$'\n",
    "osm_evacTime240o240o240['model'] = 'OSM'\n",
    "\n",
    "bhm_evacTime240o240o240 = evacuation_times(bhm_trajectories240o240o240)\n",
    "bhm_evacTime240o240o240['scenario'] = '$b_{in} = 240$'\n",
    "bhm_evacTime240o240o240['model'] = 'BHM'\n",
    "\n",
    "# merge all together\n",
    "experiments_evacuation_times = pd.concat([evacTime240o240o240, evacTime240o150o240, evacTime240o120o240, evacTime240o100o240, evacTime240o080o240, evacTime240o060o240, evacTime240o050o240], ignore_index=True)\n",
    "osm_evacuation_times = pd.concat([osm_evacTime240o240o240, osm_evacTime240o150o240, osm_evacTime240o120o240, osm_evacTime240o100o240, osm_evacTime240o080o240, osm_evacTime240o060o240, osm_evacTime240o050o240], ignore_index=True)\n",
    "bhm_evacuation_times = pd.concat([bhm_evacTime240o240o240, bhm_evacTime240o150o240, bhm_evacTime240o120o240, bhm_evacTime240o100o240, bhm_evacTime240o080o240, bhm_evacTime240o060o240, bhm_evacTime240o050o240], ignore_index=True)\n",
    "all_evacuation_times = pd.concat([experiments_evacuation_times, osm_evacuation_times, bhm_evacuation_times], ignore_index=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Compute densities, velocities and evacuation times"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_overall_velocity(times, trajectories):\n",
    "    velocity_all = list(map(lambda t: mean_velocity_at(t, trajectories), times))\n",
    "    veloicty_std_all = list(map(lambda t: get_trajectories(t, trajectories)['velocity'].std(),times))\n",
    "    return velocity_all, veloicty_std_all\n",
    "\n",
    "def compute_fundamentals(times, measurementAreas, trajectories):\n",
    "    fundamentals_all = []\n",
    "    for measurementArea in measurementAreas:\n",
    "        densities_velocities = *map(lambda t: density_velocity(t, measurementArea, trajectories), times),\n",
    "        density = list(map(lambda e: e[0], densities_velocities))\n",
    "        velocity = list(map(lambda e: e[1], densities_velocities))\n",
    "        fundamentals_all.append([density, velocity])\n",
    "    return fundamentals_all"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Front\n",
    "Computation of the density and velocity at the front measurement area."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gc.disable()\n",
    "times = np.arange(0, 110, 2)\n",
    "measurementArea_front = mpl.patches.Rectangle((16.3,6.0), 2.4, 2.0)\n",
    "measurementArea_left = mpl.patches.Rectangle((14.2,1.8), 2.0, 2.4)\n",
    "measurementArea_right = mpl.patches.Rectangle((19.7,1.8), 2.0, 2.4)\n",
    "measurementAreas = [measurementArea_front, measurementArea_left, measurementArea_right]\n",
    "\n",
    "#240-050-240\n",
    "fundamentals240o050o240_all = compute_fundamentals(times, measurementAreas, trajectories240o050o240)\n",
    "velocities240o050o240 = compute_overall_velocity(times, trajectories240o050o240)\n",
    "\n",
    "osm_fundamentals240o050o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o050o240)\n",
    "osm_velocities240o050o240 = compute_overall_velocity(times, osm_trajectories240o050o240)\n",
    "\n",
    "bhm_fundamentals240o050o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o050o240)\n",
    "bhm_velocities240o050o240 = compute_overall_velocity(times, bhm_trajectories240o050o240)\n",
    "\n",
    "gc.collect()\n",
    "\n",
    "#240-060-240\n",
    "fundamentals240o060o240_all = compute_fundamentals(times, measurementAreas, trajectories240o060o240)\n",
    "velocities240o060o240 = compute_overall_velocity(times, trajectories240o060o240)\n",
    "\n",
    "osm_fundamentals240o060o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o060o240)\n",
    "osm_velocities240o060o240 = compute_overall_velocity(times, osm_trajectories240o060o240)\n",
    "\n",
    "bhm_fundamentals240o060o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o060o240)\n",
    "bhm_velocities240o060o240 = compute_overall_velocity(times, bhm_trajectories240o060o240)\n",
    "\n",
    "gc.collect()\n",
    "\n",
    "#240-080-240\n",
    "fundamentals240o080o240_all = compute_fundamentals(times, measurementAreas, trajectories240o080o240)\n",
    "velocities240o080o240 = compute_overall_velocity(times, trajectories240o080o240)\n",
    "\n",
    "osm_fundamentals240o080o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o080o240)\n",
    "osm_velocities240o080o240 = compute_overall_velocity(times, osm_trajectories240o080o240)\n",
    "\n",
    "bhm_fundamentals240o080o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o080o240)\n",
    "bhm_velocities240o080o240 = compute_overall_velocity(times, bhm_trajectories240o080o240)\n",
    "\n",
    "gc.collect()\n",
    "\n",
    "#240-100-240\n",
    "fundamentals240o100o240_all = compute_fundamentals(times, measurementAreas, trajectories240o100o240)\n",
    "velocities240o100o240 = compute_overall_velocity(times, trajectories240o100o240)\n",
    "\n",
    "osm_fundamentals240o100o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o100o240)\n",
    "osm_velocities240o100o240 = compute_overall_velocity(times, osm_trajectories240o100o240)\n",
    "\n",
    "bhm_fundamentals240o100o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o100o240)\n",
    "bhm_velocities240o100o240 = compute_overall_velocity(times, bhm_trajectories240o100o240)\n",
    "\n",
    "gc.collect()\n",
    "\n",
    "#240-120-240\n",
    "fundamentals240o120o240_all = compute_fundamentals(times, measurementAreas, trajectories240o120o240)\n",
    "velocities240o120o240 = compute_overall_velocity(times, trajectories240o120o240)\n",
    "\n",
    "osm_fundamentals240o120o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o120o240)\n",
    "osm_velocities240o120o240 = compute_overall_velocity(times, osm_trajectories240o120o240)\n",
    "\n",
    "bhm_fundamentals240o120o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o120o240)\n",
    "bhm_velocities240o120o240 = compute_overall_velocity(times, bhm_trajectories240o120o240)\n",
    "\n",
    "gc.collect()\n",
    "\n",
    "#240-150-240\n",
    "fundamentals240o150o240_all = compute_fundamentals(times, measurementAreas, trajectories240o150o240)\n",
    "velocities240o150o240 = compute_overall_velocity(times, trajectories240o150o240)\n",
    "\n",
    "osm_fundamentals240o150o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o150o240)\n",
    "osm_velocities240o150o240 = compute_overall_velocity(times, osm_trajectories240o150o240)\n",
    "\n",
    "bhm_fundamentals240o150o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o150o240)\n",
    "bhm_velocities240o150o240 = compute_overall_velocity(times, bhm_trajectories240o150o240)\n",
    "\n",
    "gc.collect()\n",
    "\n",
    "#240-240-240\n",
    "fundamentals240o240o240_all = compute_fundamentals(times, measurementAreas, trajectories240o240o240)\n",
    "velocities240o240o240 = compute_overall_velocity(times, trajectories240o240o240)\n",
    "\n",
    "osm_fundamentals240o240o240_all = compute_fundamentals(times, measurementAreas, osm_trajectories240o240o240)\n",
    "osm_velocities240o240o240 = compute_overall_velocity(times, osm_trajectories240o240o240)\n",
    "\n",
    "bhm_fundamentals240o240o240_all = compute_fundamentals(times, measurementAreas, bhm_trajectories240o240o240)\n",
    "bhm_velocities240o240o240 = compute_overall_velocity(times, bhm_trajectories240o240o240)\n",
    "\n",
    "gc.enable()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def flatten(mylist):\n",
    "    return functools.reduce(operator.iconcat, mylist, [])\n",
    "\n",
    "all_fundamentals = [fundamentals240o050o240_all, fundamentals240o060o240_all, fundamentals240o080o240_all, fundamentals240o100o240_all, fundamentals240o120o240_all, fundamentals240o150o240_all, fundamentals240o240o240_all]\n",
    "osm_all_fundamentals = [osm_fundamentals240o050o240_all, osm_fundamentals240o060o240_all, osm_fundamentals240o080o240_all, osm_fundamentals240o100o240_all, osm_fundamentals240o120o240_all, osm_fundamentals240o150o240_all, osm_fundamentals240o240o240_all]\n",
    "bhm_all_fundamentals = [bhm_fundamentals240o050o240_all, bhm_fundamentals240o060o240_all, bhm_fundamentals240o080o240_all, bhm_fundamentals240o100o240_all, bhm_fundamentals240o120o240_all, bhm_fundamentals240o150o240_all, bhm_fundamentals240o240o240_all]\n",
    "\n",
    "fundamentals_all_front = [flatten([e[0][0] for e in all_fundamentals]), flatten([e[0][1] for e in all_fundamentals])]\n",
    "fundamentals_all_left = [flatten([e[1][0] for e in all_fundamentals]), flatten([e[1][1] for e in all_fundamentals])]\n",
    "fundamentals_all_right = [flatten([e[2][0] for e in all_fundamentals]), flatten([e[2][1] for e in all_fundamentals])]\n",
    "\n",
    "osm_fundamentals_all_front = [flatten([e[0][0] for e in osm_all_fundamentals]), flatten([e[0][1] for e in osm_all_fundamentals])]\n",
    "osm_fundamentals_all_left = [flatten([e[1][0] for e in osm_all_fundamentals]), flatten([e[1][1] for e in osm_all_fundamentals])]\n",
    "osm_fundamentals_all_right = [flatten([e[2][0] for e in osm_all_fundamentals]), flatten([e[2][1] for e in osm_all_fundamentals])]\n",
    "\n",
    "bhm_fundamentals_all_front = [flatten([e[0][0] for e in bhm_all_fundamentals]), flatten([e[0][1] for e in bhm_all_fundamentals])]\n",
    "bhm_fundamentals_all_left = [flatten([e[1][0] for e in bhm_all_fundamentals]), flatten([e[1][1] for e in bhm_all_fundamentals])]\n",
    "bhm_fundamentals_all_right = [flatten([e[2][0] for e in bhm_all_fundamentals]), flatten([e[2][1] for e in bhm_all_fundamentals])]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot evacuation times\n",
    "\n",
    "The following plots show the evacuation times for different sceanrios."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.catplot(x=\"scenario\", y=\"evacuationTime\", kind=\"box\", hue=\"model\", data=all_evacuation_times, height=8, legend_out=False)\n",
    "g.set_xticklabels(rotation=20).set_axis_labels(\"\", \"Walking times [s]\").set(ylim=(0, 40))\n",
    "handles, labels = g.axes[0][0].get_legend_handles_labels()\n",
    "g.axes[0][0].legend(handles=handles[0:], labels=labels[0:])\n",
    "g.savefig('./evacuation_times.pdf', bbox_inches='tight')"
1110
1111
1112
   ]
  },
  {
1113
   "cell_type": "markdown",
1114
1115
   "metadata": {},
   "source": [
1116
1117
1118
    "# Plot velocities\n",
    "\n",
    "The following code plots the mean (over all agents / pedestrians) velocity at $t = 0, 0.5, \\ldots 70$ and the corresponding standard deviation. "
1119
1120
1121
1122
1123
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
1124
   "metadata": {
1125
    "scrolled": false
1126
   },
1127
1128
   "outputs": [],
   "source": [
1129
    "fig_velocities = plt.figure(figsize=(15,10))\n",
1130
    "\n",
1131
1132
    "ax1_velocities = fig_velocities.add_subplot(211)\n",
    "ax1_velocities.set_xlim(min(times),105)\n",
1133
    "ax1_velocities.set_ylim(0,2)\n",
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
    "#ax1_velocities.set_xlabel(\"Time [s]\")\n",
    "ax1_velocities.set_ylabel(\"Mean velocity [m/s]\")\n",
    "ax1_velocities.yaxis.set_label_coords(-0.1, 0.)\n",
    "ax1_velocities.set_aspect(30)\n",
    "plt.setp(ax1_velocities.get_xticklabels(), visible=False)\n",
    "plt.errorbar(times, osm_velocities240o120o240[0], osm_velocities240o120o240[1], label = 'OSM', c = sns.color_palette()[1])\n",
    "plt.errorbar(times, velocities240o120o240[0], velocities240o120o240[1], label = 'Experiment', c = sns.color_palette()[0])\n",
    "plt.legend(loc='upper left', bbox_to_anchor=(0.55,1))\n",
    "\n",
    "ax2_velocities = fig_velocities.add_subplot(212)\n",
    "ax2_velocities.set_xlim(min(times),105)\n",
1145
    "ax2_velocities.set_ylim(0,2)\n",
1146
1147
1148
1149
1150
1151
1152
    "ax2_velocities.set_xlabel(\"Time [s]\")\n",
    "#ax2_velocities.set_ylabel(\"Mean velocity [m/s]\")\n",
    "ax2_velocities.set_aspect(30)\n",
    "plt.errorbar(times, bhm_velocities240o120o240[0], bhm_velocities240o120o240[1], label = 'BHM', c = sns.color_palette()[2])\n",
    "plt.errorbar(times, velocities240o120o240[0], velocities240o120o240[1], label = 'Experiment', c = sns.color_palette()[0])\n",
    "plt.legend(loc='upper left', bbox_to_anchor=(0.55,1))\n",
    "plt.savefig('./mean_velocities.pdf', bbox_inches='tight')"
1153
1154
1155
   ]
  },
  {
1156
   "cell_type": "markdown",
1157
1158
   "metadata": {},
   "source": [
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
    "# Plot the velocity of a single agent / pedestrian"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "#c_sim_trajecotories\n",
    "#trajectories240o100o240\n",
    "traj = get_trajectory(2, trajectories240o050o240)\n",
    "fig_velocity = plt.figure(figsize=(20,5))\n",
    "plt.plot(traj['endTime'], traj['velocity'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot densities inside measurement areas\n",
    "\n",
    "The following code plots the density inside the measurement area at different times $t$ and the corresponding standard deviation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "lw = 2\n",
    "ymin = -0.1\n",
    "ymax = 2.4\n",
    "xmin = min(times)\n",
    "xmax = max(times)\n",
    "labelx = \"Time [s]\"\n",
    "\n",
    "a_ratio = 30\n",
    "height = 7\n",
    "width = 3*7\n",
    "\n",
    "fig_density = plt.figure(figsize=(width,height))\n",
    "ax1__exp_density = fig_density.add_subplot(131)\n",
    "ax1__exp_density.set_xlim(xmin, xmax)\n",
    "ax1__exp_density.set_ylim(ymin,ymax)\n",
    "ax1__exp_density.set_aspect(a_ratio)\n",
    "ax1__exp_density.set_xlabel(labelx)\n",
    "ax1__exp_density.set_ylabel(\"Density [m$^{-2}$]\")\n",
    "ax1__exp_density.set_title(\"Experiment\")\n",
    "plt.plot(times, fundamentals240o050o240_all[0][0], linewidth=lw)\n",
    "plt.plot(times, fundamentals240o100o240_all[0][0], linewidth=lw)\n",
    "plt.plot(times, fundamentals240o240o240_all[0][0], linewidth=lw)\n",
1216
    "\n",
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
    "ax1__osm_density = fig_density.add_subplot(132, sharey=ax1__exp_density)\n",
    "plt.setp(ax1__osm_density.get_yticklabels(), visible=False)\n",
    "ax1__osm_density.set_xlim(xmin,xmax)\n",
    "ax1__osm_density.set_ylim(ymin,ymax)\n",
    "ax1__osm_density.set_aspect(a_ratio)\n",
    "ax1__osm_density.set_xlabel(labelx)\n",
    "ax1__osm_density.set_title(\"OSM\")\n",
    "plt.plot(times, osm_fundamentals240o050o240_all[0][0], linewidth=lw)\n",
    "plt.plot(times, osm_fundamentals240o100o240_all[0][0], linewidth=lw)\n",
    "plt.plot(times, osm_fundamentals240o240o240_all[0][0], linewidth=lw)\n",
    "\n",
    "ax1__bhm_density = fig_density.add_subplot(133, sharey=ax1__osm_density)\n",
    "plt.setp(ax1__bhm_density.get_yticklabels(), visible=False)\n",
    "ax1__bhm_density.set_xlim(xmin,xmax)\n",
    "ax1__bhm_density.set_ylim(ymin,ymax)\n",
    "ax1__bhm_density.set_aspect(a_ratio)\n",
    "ax1__bhm_density.set_xlabel(labelx)\n",
    "ax1__bhm_density.set_title(\"BHM\")\n",
    "plt.plot(times, bhm_fundamentals240o050o240_all[0][0], linewidth=lw, label=\"$b_{in}$ = 50\")\n",
    "plt.plot(times, bhm_fundamentals240o100o240_all[0][0], linewidth=lw, label=\"$b_{in}$ = 100\")\n",
    "plt.plot(times, bhm_fundamentals240o240o240_all[0][0], linewidth=lw, label=\"$b_{in}$ = 240\")\n",
    "plt.legend(loc='upper left', bbox_to_anchor=(0.55,1))\n",
    "plt.savefig('./densities.pdf', bbox_inches='tight')"
1240
1241
1242
1243
1244
1245
1246
1247
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
1248
1249
1250
1251
1252
1253
    "lw = 2\n",
    "ymin = -0.1\n",
    "ymax = 2.4\n",
    "xmin = 5\n",
    "xmax = 100\n",
    "labelx = \"time [s]\"\n",
1254
    "\n",
1255
1256
1257
    "a_ratio = 30\n",
    "height = 7\n",
    "width = 2*7\n",
1258
    "\n",
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
    "\n",
    "fig = plt.figure(figsize=(width,height))\n",
    "ax1__density = fig.add_subplot(121)\n",
    "ax1__density.set_xlim(xmin, xmax)\n",
    "ax1__density.set_ylim(ymin,ymax)\n",
    "ax1__density.set_aspect(a_ratio)\n",
    "ax1__density.set_xlabel(labelx)\n",
    "ax1__density.set_ylabel(\"density [m$^{-2}$]\")\n",
    "#ax1__density.set_title(\"Experiment\")\n",
    "plt.plot(times, fundamentals240o150o240_all[0][0], linewidth=lw, label='Experiment')\n",
    "plt.plot(times, osm_fundamentals240o150o240_all[0][0], linewidth=lw,label='OSM')\n",
    "plt.plot(times, bhm_fundamentals240o150o240_all[0][0], linewidth=lw, label='BHM')\n",
    "\n",
    "ax1_velocity = fig.add_subplot(122)\n",
    "ax1_velocity.set_xlim(xmin, xmax)\n",
    "ax1_velocity.set_ylim(ymin,ymax)\n",
    "ax1_velocity.set_aspect(a_ratio)\n",
    "ax1_velocity.set_xlabel(labelx)\n",
    "ax1_velocity.set_ylabel(\"velocity [m/s]\")\n",
    "#ax1_velocity.set_title(\"Experiment\")\n",
    "plt.plot(times, fundamentals240o150o240_all[0][1], linewidth=lw, label='Experiment')\n",
    "plt.plot(times, osm_fundamentals240o150o240_all[0][1], linewidth=lw, label='OSM')\n",
    "plt.plot(times, bhm_fundamentals240o150o240_all[0][1], linewidth=lw, label='BHM')\n",
    "plt.legend(loc='upper left', bbox_to_anchor=(0.55,1))\n",
    "plt.savefig('./densities_velocities.pdf', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot velocities inside measurement areas\n",
    "\n",
    "The following code plots the velocity inside the measurement area at different times $t$ and the corresponding standard deviation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lw = 2\n",
    "ymin = -0.1\n",
    "ymax = 2.0\n",
    "xmin = min(times)\n",
    "xmax = max(times)\n",
    "labelx = \"Time [s]\"\n",
    "\n",
    "a_ratio = 50\n",
    "height = 7\n",
    "width = 3*7\n",
    "\n",
    "fig_density = plt.figure(figsize=(width,height))\n",
    "ax1__exp_density = fig_density.add_subplot(131)\n",
    "ax1__exp_density.set_xlim(xmin, xmax)\n",
    "ax1__exp_density.set_ylim(ymin,ymax)\n",
    "ax1__exp_density.set_aspect(a_ratio)\n",
    "ax1__exp_density.set_xlabel(labelx)\n",
    "ax1__exp_density.set_ylabel(\"Velocity [m/s]\")\n",
    "ax1__exp_density.set_title(\"Experiment\")\n",
    "plt.plot(times, fundamentals240o050o240_all[0][1], linewidth=lw)\n",
    "plt.plot(times, fundamentals240o100o240_all[0][1], linewidth=lw)\n",
    "plt.plot(times, fundamentals240o240o240_all[0][1], linewidth=lw)\n",
    "\n",
    "ax1__osm_density = fig_density.add_subplot(132, sharey=ax1__exp_density)\n",
    "plt.setp(ax1__osm_density.get_yticklabels(), visible=False)\n",
    "ax1__osm_density.set_xlim(xmin,xmax)\n",
    "ax1__osm_density.set_ylim(ymin,ymax)\n",
    "ax1__osm_density.set_aspect(a_ratio)\n",
    "ax1__osm_density.set_xlabel(labelx)\n",
    "ax1__osm_density.set_title(\"OSM\")\n",
    "plt.plot(times, osm_fundamentals240o050o240_all[0][1], linewidth=lw)\n",
    "plt.plot(times, osm_fundamentals240o100o240_all[0][1], linewidth=lw)\n",
    "plt.plot(times, osm_fundamentals240o240o240_all[0][1], linewidth=lw)\n",
    "\n",
    "ax1__bhm_density = fig_density.add_subplot(133, sharey=ax1__osm_density)\n",
    "plt.setp(ax1__bhm_density.get_yticklabels(), visible=False)\n",
    "ax1__bhm_density.set_xlim(xmin,xmax)\n",
    "ax1__bhm_density.set_ylim(ymin,ymax)\n",
    "ax1__bhm_density.set_aspect(a_ratio)\n",
    "ax1__bhm_density.set_xlabel(labelx)\n",
    "ax1__bhm_density.set_title(\"BHM\")\n",
    "plt.plot(times, bhm_fundamentals240o050o240_all[0][1], linewidth=lw, label=\"$b_{in}$ = 50\")\n",
    "plt.plot(times, bhm_fundamentals240o100o240_all[0][1], linewidth=lw, label=\"$b_{in}$ = 100\")\n",
    "plt.plot(times, bhm_fundamentals240o240o240_all[0][1], linewidth=lw, label=\"$b_{in}$ = 240\")\n",
    "plt.legend(loc='upper left', bbox_to_anchor=(0.55,1))\n",
    "plt.savefig('./velocities.pdf', bbox_inches='tight')"
1347
1348
1349
1350
1351
1352
1353
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot of fundamental diagrams using method c"
1354
1355
   ]
  },
1356
1357
1358
1359
1360
1361
1362
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Front"
   ]
  },
1363
1364
1365
1366
1367
1368
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
    "ymin = -0.1\n",
    "ymax = 2.1\n",
    "xmin = -0.2\n",
    "xmax = 2.5\n",
    "ms = 7\n",
    "labelx = \"Density [m$^{-2}$]\"\n",
    "a_ratio = 2\n",
    "height = 7\n",
    "width = 3*7\n",
    "\n",
1379
    "fig_fundamental = plt.figure(figsize=(10,5))\n",
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
    "ax_exp_trajectories = fig_fundamental.add_subplot(131)\n",
    "ax_exp_trajectories.set_ylim(ymin,ymax)\n",
    "ax_exp_trajectories.set_xlim(xmin,xmax)\n",
    "ax_exp_trajectories.set_aspect(a_ratio)\n",
    "ax_exp_trajectories.set_xlabel(labelx)\n",
    "ax_exp_trajectories.set_ylabel(\"Velocity [m/s]\")\n",
    "ax_exp_trajectories.set_title(\"Experiment\")\n",
    "\n",
    "plt.plot(fundamentals240o050o240_all[0][0], fundamentals240o050o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(fundamentals240o060o240_all[0][0], fundamentals240o060o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(fundamentals240o080o240_all[0][0], fundamentals240o080o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(fundamentals240o100o240_all[0][0], fundamentals240o100o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(fundamentals240o120o240_all[0][0], fundamentals240o120o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(fundamentals240o150o240_all[0][0], fundamentals240o150o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(fundamentals240o240o240_all[0][0], fundamentals240o240o240_all[0][1] ,'.',markersize=ms)\n",
    "\n",
    "ax_osm_trajectories = fig_fundamental.add_subplot(132)\n",
    "plt.setp(ax_osm_trajectories.get_yticklabels(), visible=False)\n",
    "ax_osm_trajectories.set_ylim(ymin,ymax)\n",
    "ax_osm_trajectories.set_xlim(xmin,xmax)\n",
    "ax_osm_trajectories.set_aspect(a_ratio)\n",
    "ax_osm_trajectories.set_xlabel(labelx)\n",
    "ax_osm_trajectories.set_title(\"OSM\")\n",
    "#ax_osm_trajectories.set_ylabel(\"velocity\")\n",
    "\n",
    "plt.plot(osm_fundamentals240o050o240_all[0][0], osm_fundamentals240o050o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(osm_fundamentals240o060o240_all[0][0], osm_fundamentals240o060o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(osm_fundamentals240o080o240_all[0][0], osm_fundamentals240o080o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(osm_fundamentals240o100o240_all[0][0], osm_fundamentals240o100o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(osm_fundamentals240o120o240_all[0][0], osm_fundamentals240o120o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(osm_fundamentals240o150o240_all[0][0], osm_fundamentals240o150o240_all[0][1] ,'.',markersize=ms)\n",
    "plt.plot(osm_fundamentals240o240o240_all[0][0], osm_fundamentals240o240o240_all[0][1] ,'.',markersize=ms)\n",
    "\n",
    "ax_bhm_trajectories = fig_fundamental.add_subplot(133)\n",
    "plt.setp(ax_bhm_trajectories.get_yticklabels(), visible=False)\n",
    "ax_bhm_trajectories.set_ylim(ymin,ymax)\n",
    "ax_bhm_trajectories.set_xlim(xmin,xmax)\n",
    "ax_bhm_trajectories.set_aspect(a_ratio)\n",
    "ax_bhm_trajectories.set_xlabel(labelx)\n",
    "ax_bhm_trajectories.set_title('BHM')\n",
    "\n",
    "plt.plot(bhm_fundamentals240o050o240_all[0][0], bhm_fundamentals240o050o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 50\")\n",
    "plt.plot(bhm_fundamentals240o060o240_all[0][0], bhm_fundamentals240o060o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 60\")\n",
    "plt.plot(bhm_fundamentals240o080o240_all[0][0], bhm_fundamentals240o080o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 80\")\n",
    "plt.plot(bhm_fundamentals240o100o240_all[0][0], bhm_fundamentals240o100o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 100\")\n",
    "plt.plot(bhm_fundamentals240o120o240_all[0][0], bhm_fundamentals240o120o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 120\")\n",
    "plt.plot(bhm_fundamentals240o150o240_all[0][0], bhm_fundamentals240o150o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 150\")\n",
    "plt.plot(bhm_fundamentals240o240o240_all[0][0], bhm_fundamentals240o240o240_all[0][1] ,'.',markersize=ms, label=\"$b_{in}$ = 240\")\n",
    "\n",
    "plt.legend(loc=2, bbox_to_anchor=(1.05, 1), borderaxespad=0.)\n",
    "\n",
    "plt.savefig('./fundamental_front.pdf', bbox_inches='tight')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Combined"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ymin = -0.1\n",
    "ymax = 2.1\n",
    "xmin = -0.2\n",
    "xmax = 4\n",
    "ms = 5\n",
    "labelx = \"Density [#peds / m$^{2}$]\"\n",
    "a_ratio = 2\n",
    "height = 7\n",
    "width = 3*7\n",
    "palette=sns.color_palette()\n",
    "\n",
    "fig_fundamental = plt.figure(figsize=(width,height))\n",
    "ax_exp_trajectories = fig_fundamental.add_subplot(131)\n",
    "ax_exp_trajectories.set_ylim(ymin,ymax)\n",
    "ax_exp_trajectories.set_xlim(xmin,xmax)\n",
    "ax_exp_trajectories.set_aspect(a_ratio)\n",
    "#ax_exp_trajectories.set_xlabel(labelx)\n",
    "#ax_exp_trajectories.xaxis.set_label_coords(1.5, -0.1)\n",
    "ax_exp_trajectories.set_ylabel(\"Velocity [m/s]\")\n",
    "ax_exp_trajectories.set_title(\"Experiment\")\n",
    "\n",
    "plt.plot(fundamentals_all_right[0], fundamentals_all_right[1], '^', label=\"T-right\", markersize=ms, c=palette[4])\n",
    "plt.plot(fundamentals_all_left[0], fundamentals_all_left[1], 'd', label=\"T-left\", markersize=ms, c=palette[8])\n",
    "plt.plot(fundamentals_all_front[0], fundamentals_all_front[1] ,'o', label=\"T-top\", markersize=ms, c=palette[9])\n",
    "\n",
    "\n",
    "ax_osm_trajectories = fig_fundamental.add_subplot(132)\n",
    "ax_osm_trajectories.set_ylim(ymin,ymax)\n",
    "ax_osm_trajectories.set_xlim(xmin,xmax)\n",
    "ax_osm_trajectories.set_aspect(a_ratio)\n",
    "ax_osm_trajectories.set_xlabel(labelx)\n",
    "#ax_osm_trajectories.set_ylabel(\"velocity\")\n",
    "ax_osm_trajectories.set_title(\"OSM\")\n",
    "\n",
    "plt.setp(ax_osm_trajectories.get_yticklabels(), visible=False)\n",
    "plt.plot(osm_fundamentals_all_right[0], osm_fundamentals_all_right[1], '^', label=\"R-right\", markersize=ms, c=palette[4])\n",
    "plt.plot(osm_fundamentals_all_left[0], osm_fundamentals_all_left[1], 'd', label=\"T-left\",markersize=ms, c=palette[8])\n",
    "plt.plot(osm_fundamentals_all_front[0], osm_fundamentals_all_front[1] ,'o', label=\"T-top\",markersize=ms, c=palette[9])\n",
    "\n",
    "ax_bhm_trajectories = fig_fundamental.add_subplot(133)\n",
    "ax_bhm_trajectories.set_ylim(ymin,ymax)\n",
    "ax_bhm_trajectories.set_xlim(xmin,xmax)\n",
    "ax_bhm_trajectories.set_aspect(a_ratio)\n",
    "#ax_bhm_trajectories.set_xlabel(labelx)\n",
    "#ax_bhm_trajectories.set_ylabel(\"velocity\")\n",
    "ax_bhm_trajectories.set_title(\"BHM\")\n",
    "\n",
    "plt.setp(ax_bhm_trajectories.get_yticklabels(), visible=False)\n",
    "plt.plot(bhm_fundamentals_all_right[0], bhm_fundamentals_all_right[1], '^', label=\"right\", markersize=ms, c=palette[4])\n",
    "plt.plot(bhm_fundamentals_all_left[0], bhm_fundamentals_all_left[1], 'd', label=\"left\", markersize=ms, c=palette[8])\n",
    "plt.plot(bhm_fundamentals_all_front[0], bhm_fundamentals_all_front[1] ,'o', label=\"top\", markersize=ms, c=palette[9])\n",
    "\n",
    "plt.legend(loc='upper left', bbox_to_anchor=(0.6,1))\n",
    "plt.savefig('./fundamental_all.pdf', bbox_inches='tight')\n",
1502
    "plt.show()"
1503
   ]
1504
1505
1506
1507
1508
1509
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
1510
1511
1512
   "source": [
    "palette[8]"
   ]
1513
1514
1515
1516
1517
1518
1519
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
1538
   "version": "3.6.8"
1539
1540
1541
1542
1543
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}