TrajectoryMetric.ipynb 34.7 KB
Newer Older
1
2
{
 "cells": [
3
4
5
6
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
7
8
   "outputs": [],
   "source": [
9
    "# expand the cell of the notebook\n",
10
    "import json\n",
11
    "import gc\n",
12
13
14
    "import numpy as np\n",
    "import pandas as pd\n",
    "import math\n",
15
    "import matplotlib as mpl\n",
16
17
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.lines import Line2D\n",
18
19
    "import seaborn as sns\n",
    "sns.set(style=\"ticks\")\n",
20
    "\n",
21
22
23
24
25
26
27
28
    "from IPython.core.display import display, HTML\n",
    "display(HTML('<style>.container { width:100% !important; }</style>'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
29
    "# Convert Vadere trajectories into a DataFrame"
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
   ]
  },
  {
   "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",
50
51
    "    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",
52
53
54
55
56
57
58
59
60
61
    "    return dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "file = \"./data/TrajectoryMetric/trajectories_simulation.txt\"\n",
62
63
64
    "f = open(file, \"r\")\n",
    "header = f.readline();\n",
    "trajectories = dict({});\n",
65
    "\n",
66
67
68
69
70
    "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",
71
72
73
74
75
    "\n",
    "ptrajectories = trajectories_to_dataframe(trajectories)\n",
    "ptrajectories.head()"
   ]
  },
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  {
   "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",
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    "    rows = []\n",
    "    #print(trajectories)\n",
    "    last_ped_id = None\n",
    "    lastX = None\n",
    "    lastY = None\n",
    "    for row in data.itertuples():\n",
    "        endX = row.x / 100 + 18.7\n",
    "        endY = row.y / 100 + 4.2\n",
    "        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",
    "            startX = lastX / 100 + 18.7\n",
    "            startY = lastY / 100 + 4.2\n",
    "            distance = np.sqrt(np.square(endX - startX) + np.square(endY - startY))\n",
    "            velocity = distance / (endTime - startTime)\n",
    "        last_ped_id = row.pedestrianId\n",
    "        lastX = row.x\n",
    "        lastY = row.y\n",
    "            \n",
    "        rows.append([row.pedestrianId, startX, startY, endX, endY, startTime, endTime, distance, velocity])\n",
    "    dataframe = pd.DataFrame(rows, columns=['pedestrianId', 'startX', 'startY', 'endX', 'endY','startTime','endTime','distance','velocity'])\n",
    "    return dataframe\n",
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    "    \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)"
   ]
  },
199
200
201
202
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    "# Calculate evacution time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Evacuation time = endTime - startTime"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Real data"
   ]
  },
  {
   "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",
227
228
229
    "copy = trajectoriesReal.copy(deep=True)\n",
    "copy[\"timeDelta\"] = copy[\"endTime\"] - copy[\"startTime\"]\n",
    "evacuation_time = copy.groupby([\"pedestrianId\"])[\"timeDelta\"].sum()\n",
230
    "\n",
231
232
233
234
235
236
237
    "# trajectories starting from left\n",
    "cut_minX = trajectoriesReal[trajectoriesReal[\"endX\"] < 15].groupby([\"pedestrianId\"])[\"endX\"].min().max()\n",
    "\n",
    "# trajectories starting from right\n",
    "cut_maxX = trajectoriesReal[trajectoriesReal[\"endX\"] > 21].groupby([\"pedestrianId\"])[\"endX\"].max().min()\n",
    "cut_maxY = trajectoriesReal.groupby([\"pedestrianId\"])[\"endY\"].max().min()\n",
    "\n",
238
239
240
241
    "print(\"Evacuation time (real data)\")\n",
    "print(\"- mean: {:.2f} [s]\".format(evacuation_time.mean()))\n",
    "print(\"- std: {:.2f} [s]\".format(evacuation_time.std()))\n",
    "print(\"- min: {:.2f} [s]\".format(evacuation_time.min()))\n",
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    "print(\"- max: {:.2f} [s]\".format(evacuation_time.max()))\n",
    "print(\"- minX: {:.2f} [m]\".format(cut_minX))\n",
    "print(\"- maxX: {:.2f} [m]\".format(cut_maxX))\n",
    "print(\"- maxY: {:.2f} [m]\".format(cut_maxY))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rightX = trajectoriesReal[trajectoriesReal.endX < 16].groupby([\"pedestrianId\"])[\"endX\"].min().max()\n",
    "leftX = trajectoriesReal[trajectoriesReal.endX > 16].groupby([\"pedestrianId\"])[\"endX\"].max().min()\n",
    "topY = trajectoriesReal.groupby([\"pedestrianId\"])[\"endY\"].max().min()\n",
    "topY"
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
   ]
  },
  {
   "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"
279
280
281
282
283
284
285
286
287
288
289
290
291
   ]
  },
  {
   "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",
292
293
294
    "def get_trajectories(t, trajectories):\n",
    "    return trajectories[np.logical_and(trajectories.startTime <= t, trajectories.endTime >= t)]\n",
    "\n",
295
296
    "def get_pedestrianIds(trajectories):\n",
    "    return trajectories['pedestrianId'].unique()\n",
297
    "\n",
298
299
300
    "#def get_velocity(trajectories, t, dt):\n",
    "#    trajectories[np.logical_and(trajectory.endX >= xmax, trajectory.startX < xmax)]\n",
    "\n",
301
    "def get_footstep(trajectory, i):\n",
302
303
    "    \"\"\"returns the i-ths footstep.\"\"\"\n",
    "    return trajectory.iloc[i];\n",
304
    "\n",
305
306
307
308
309
310
    "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",
311
    "\n",
312
313
314
    "def start_time(trajectory):\n",
    "    \"\"\"returns the time of the first footstep of the trajectory.\"\"\"\n",
    "    return get_footstep(trajectory, 0)['startTime'];\n",
315
316
    "\n",
    "def end_time(trajectory):\n",
317
318
319
320
321
322
    "    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",
323
324
    "\n",
    "def min_end_time(trajectories):\n",
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
    "    \"\"\"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",
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    "    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",
    "    #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",
375
376
    "    i1 = trajectory[np.logical_or(trajectory.endX >= xmax, trajectory.startX is np.nan)].index.max()\n",
    "    i2 = trajectory[np.logical_or(trajectory.endX <= xmin, trajectory.startX is np.nan)].index.max()\n",
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    "    #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",
    "    i = i+1\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",
    "    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",
    "        r = (x - fs[\"startX\"]) / (fs[\"endX\"] - fs[\"startX\"])\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",
396
397
398
399
400
401
402
    "        if abs(endTime - startTime) < 0.00001:\n",
    "            if distance < 0.00001:\n",
    "                velocity = 0\n",
    "            else:\n",
    "                raise exception\n",
    "        else:\n",
    "            velocity = distance / (endTime - startTime)\n",
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    "        \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_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",
    "def cut(trajectories):\n",
    "    df = cuttail_by(trajectories, cut_minX, cut_maxX)\n",
    "    df = cuthead_by(df, -1000, cut_maxY)\n",
    "    return df\n",
    "\n",
    "traj = get_trajectory(2, trajectoriesReal)\n",
    "ts = traj[traj.endX > 22].index.max()\n",
    "ts\n",
    "#cut(trajectoriesReal)\n",
433
    "cuttail_by(trajectoriesReal, cut_minX, cut_maxX).head()\n",
434
435
    "#cuthead_by(trajectoriesReal, 0, 4).tail()\n",
    "#traj.loc[100]\n",
436
437
    "#trajectoriesReal.tail()\n",
    "trajectoriesReal.head()"
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
   ]
  },
  {
   "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",
459
460
461
462
    "    dx = x1-x2;\n",
    "    dy = y1-y2;\n",
    "    return np.sqrt(dx*dx + dy*dy);\n",
    "\n",
463
464
465
    "def mean_velocity_at(t, trajectories):\n",
    "    return get_trajectories(t, trajectories)['velocity'].mean()\n",
    "\n",
466
    "def trajectory_length(trajectory):\n",
467
468
469
470
471
472
473
474
475
476
477
    "    \"\"\"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",
478
479
    "    return np.array([x2-x1, y2-y1]);\n",
    "\n",
480
481
    "def footstep_duration(fs):\n",
    "    \"\"\"Duration of a footstep.\"\"\"\n",
482
483
484
485
    "    startTime = fs['startTime'];\n",
    "    endTime = fs['endTime'];\n",
    "    return endTime-startTime;\n",
    "\n",
486
487
488
    "def trajectory_duration(trajectory):\n",
    "    \"\"\"Euclidean length of a trajectory.\"\"\"\n",
    "    return (trajectory['endTime'] - trajectory['startTime']).sum();\n",
489
    "\n",
490
491
492
    "def footstep_speed(fs):\n",
    "    \"\"\"Speed of the footstep.\"\"\"\n",
    "    return footstep_length(fs) / footstep_duration(fs);\n",
493
    "\n",
494
495
496
    "def trajectory_speed(fs):\n",
    "    \"\"\"Speed of the trajectory.\"\"\"\n",
    "    return trajectory_length(fs) / trajectory_duration(fs);\n",
497
    "\n",
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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
    "#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",
596
597
598
599
600
601
602
603
604
    "    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": [
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    "#start_time(get_trajectory(1, ptrajectories))\n",
    "#max_start_time(ptrajectories)\n",
    "#end_time(get_trajectory(1, ptrajectories))\n",
    "#foot_step_length(get_footstep(get_trajectory(1, ptrajectories), 0))\n",
    "#trajectory_length(get_trajectory(1, ptrajectories))\n",
    "#trajectory_speed(get_trajectory(1, ptrajectories))\n",
    "#cutTraj.mask(cutTraj['startTime'] <= 4 and 4 > cutTraj['endTime'])\n",
    "#start_time(get_trajectory(1, ptrajectories))\n",
    "#trajectories_position(ptrajectories, [1,2,3,4]).head()\n",
    "trajPos1 = trajectories_position(get_trajectory(2, ptrajectories), [1,2,3,4,5,6,8,9,10,11,12,13])\n",
    "trajPos2 = trajectories_position(get_trajectory(7, ptrajectories), [1,2,3,4,5,6,8,9,10,11,12,13])\n",
    "trajPos1 = trajPos1[~np.isnan(trajPos1.x)]\n",
    "trajPos2 = trajPos2[~np.isnan(trajPos2.x)]\n",
    "euclid_path_length(trajPos1, trajPos2)\n",
    "euclid_len(ptrajectories,0,10000)\n",
620
621
622
623
624
    "#print(total_inter_agent(ptrajectories, ptrajectories, [1,2]))\n",
    "t = 0.5\n",
    "ttraj = ptrajectories[np.logical_and(ptrajectories.startTime <= t, ptrajectories.endTime >= t)]\n",
    "#ptrajectories[\"velocity\"] = numpy.linalg.norm(\n",
    "get_trajectories(0.5, ptrajectories).head()"
625
626
627
628
629
630
631
632
633
634
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "code_folding": []
   },
   "outputs": [],
   "source": [
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    "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",
655
    "    return match"
656
657
658
   ]
  },
  {
659
   "cell_type": "markdown",
660
661
   "metadata": {},
   "source": [
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    "Here we cut all trajectory data such each left trajectory starts at the same $x$-coordinate and each right trajectory starts at the same $x$-coordinate. In addition each trajectory ends a the same $y$-coordinate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c_real_trajectories = cut(trajectoriesReal)\n",
    "c_sim_trajecotories = cut(ptrajectories)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot trajectories\n",
    "\n",
    "Now we plot the cut trajectories."
682
683
684
685
686
687
688
689
690
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def to_line(trajectory, xleft):\n",
691
    "    \"\"\"Transforms a trajectory into a Line2D.\"\"\"\n",
692
    "    current_palette = sns.color_palette()\n",
693
694
    "    x = trajectory['endX'].values\n",
    "    y = trajectory['endY'].values\n",
695
696
697
698
    "    if x[0] < xleft:\n",
    "        c = current_palette[2]\n",
    "    else:\n",
    "        c = current_palette[0]\n",
699
    "    return x, y, Line2D(x, y, color=c, linewidth=0.3)\n",
700
    "\n",
701
702
703
704
705
706
707
708
709
710
711
712
713
    "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": [
714
715
    "x_vcenter = 17.5\n",
    "y_vcenter = 5.2\n",
716
    "\n",
717
718
719
720
721
722
    "fig_trajectories = plt.figure(figsize=(10,10))\n",
    "ax1_trajectories = fig_trajectories.add_subplot(121)\n",
    "add_lines(c_real_trajectories, 16, ax1_trajectories)\n",
    "ax1_trajectories.set_xlim(x_vcenter-5, x_vcenter+6)\n",
    "ax1_trajectories.set_ylim(y_vcenter-4, y_vcenter+4)\n",
    "ax1_trajectories.set_aspect(1)\n",
723
    "\n",
724
725
726
727
728
729
    "ax2_trajectories = fig_trajectories.add_subplot(122, sharey=ax1)\n",
    "add_lines(c_sim_trajecotories, 16, ax2_trajectories)\n",
    "plt.setp(ax2_trajectories.get_yticklabels(), visible=False)\n",
    "ax2_trajectories.set_xlim(x_vcenter-5, x_vcenter+6)\n",
    "ax2_trajectories.set_ylim(y_vcenter-4, y_vcenter+4)\n",
    "ax2_trajectories.set_aspect(1)\n",
730
731
732
733
734
    "\n",
    "plt.show()"
   ]
  },
  {
735
   "cell_type": "markdown",
736
737
   "metadata": {},
   "source": [
738
739
740
    "# 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. "
741
742
743
744
745
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
746
747
748
   "metadata": {
    "scrolled": true
   },
749
750
   "outputs": [],
   "source": [
751
    "times = np.arange(0, 70, 5)\n",
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
    "velocity1 = list(map(lambda t: mean_velocity_at(t, c_real_trajectories), times))\n",
    "std1 = list(map(lambda t: get_trajectories(t, c_real_trajectories)['velocity'].std(),times))\n",
    "\n",
    "velocity2 = list(map(lambda t: mean_velocity_at(t, c_sim_trajecotories), times))\n",
    "std2 = list(map(lambda t: get_trajectories(t, c_sim_trajecotories)['velocity'].std(),times))\n",
    "\n",
    "#df1 = pd.DataFrame({'velocity':vel1, 'time':times})\n",
    "#df2 = pd.DataFrame({'velocity':vel2, 'time':times})\n",
    "\n",
    "fig_velocities = plt.figure(figsize=(10,5))\n",
    "ax1_velocities = fig_velocities.add_subplot(121)\n",
    "ax1_velocities.set_xlim(min(times),max(times))\n",
    "ax1_velocities.set_ylim(0,2)\n",
    "ax1_velocities.set_xlabel(\"time\")\n",
    "ax1_velocities.set_ylabel(\"velocity\")\n",
    "plt.errorbar(times, velocity1, std1, ecolor=sns.color_palette()[2])\n",
    "ax2_velocities = fig_velocities.add_subplot(122)\n",
    "ax2_velocities.set_xlim(min(times),max(times))\n",
    "ax2_velocities.set_ylim(0,2)\n",
    "ax2_velocities.set_xlabel(\"time\")\n",
    "ax2_velocities.set_ylabel(\"velocity\")\n",
    "plt.errorbar(times, velocity2, std2, ecolor=sns.color_palette()[2])\n",
    "plt.show()\n",
    "#ax6 = fig2.add_subplot(212)\n",
    "#sns.relplot(x=\"startTime\", y=\"velocity\", kind=\"line\", ci=\"sd\", data=c_real_trajectories, ax=ax) #linewidth=0.5\n",
    "#sns.relplot(x=\"startTime\", y=\"velocity\", kind=\"line\", ci=\"sd\", data=c_sim_trajecotories, ax=ax6)\n",
    "#fmri = sns.load_dataset(\"fmri\")\n",
    "#fmri\n",
    "#c_real_trajectories[c_real_trajectories.endTime == 5.0]\n",
    "#c_real_trajectories"
782
783
784
   ]
  },
  {
785
   "cell_type": "markdown",
786
787
   "metadata": {},
   "source": [
788
789
790
    "# Plot densities\n",
    "\n",
    "The following code plots the density inside the measurement area at $t = 0, 0.5, \\ldots 70$ and the corresponding standard deviation."
791
792
793
794
795
796
797
798
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
799
800
801
802
    "%%prun\n",
    "#gc.disable()\n",
    "print(len(times))\n",
    "gc.disable()\n",
803
804
805
806
807
808
809
810
    "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",
811
812
    "    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",
813
814
815
816
817
818
819
    "    traj = traj[traj.apply(lambda x: contains(x['x'], x['y'],rect), axis=1)]\n",
    "    return traj\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",
820
821
    "    traj = None\n",
    "    #gc.collect()\n",
822
823
824
825
    "    if number_of_peds == 0:\n",
    "        return 0\n",
    "    else:\n",
    "        return number_of_peds / area\n",
826
    "\n",
827
828
829
    "measurementArea = mpl.patches.Rectangle((16.3,6.0), 2.4, 2.0)\n",
    "density1 = list(map(lambda t: density(t, measurementArea, c_real_trajectories), times))\n",
    "density2 = list(map(lambda t: density(t, measurementArea, c_sim_trajecotories), times))\n",
830
    "#gc.enable()\n",
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
    "\n",
    "fig_density = plt.figure(figsize=(10,5))\n",
    "ax1_density = fig_density.add_subplot(121)\n",
    "ax1_density.set_xlim(min(times),max(times))\n",
    "ax1_density.set_ylim(0,6)\n",
    "ax1_density.set_xlabel(\"time\")\n",
    "ax1_density.set_ylabel(\"density\")\n",
    "plt.plot(times, density1)\n",
    "\n",
    "ax2_density = fig_density.add_subplot(122)\n",
    "ax2_density.set_xlim(min(times),max(times))\n",
    "ax2_density.set_xlabel(\"time\")\n",
    "ax2_density.set_ylabel(\"density\")\n",
    "ax2_density.set_ylim(0,6)\n",
    "plt.plot(times, density2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot of fundamental diagrams using method c"
854
855
856
857
858
859
860
861
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
862
863
864
865
866
867
868
869
870
    "fig_fundamental = plt.figure(figsize=(10,5))\n",
    "ax1_fundamental = fig_fundamental.add_subplot(111)\n",
    "#ax1_fundamental.set_xlim(min(times),max(times))\n",
    "ax1_fundamental.set_ylim(0,6)\n",
    "ax1_fundamental.set_xlabel(\"velocity\")\n",
    "ax1_fundamental.set_ylabel(\"density\")\n",
    "plt.plot(velocity1, density1, '*')\n",
    "plt.plot(velocity2, density2, '*')\n",
    "plt.show()"
871
   ]
872
873
874
875
876
877
878
879
880
881
882
883
884
885
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
  }
 ],
 "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",
904
   "version": "3.6.8"
905
906
907
908
909
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}