TrajectoryMetric.ipynb 33.9 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
11
12
13
    "import json\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import math\n",
14
    "import matplotlib as mpl\n",
15
16
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.lines import Line2D\n",
17
18
    "import seaborn as sns\n",
    "sns.set(style=\"ticks\")\n",
19
    "\n",
20
21
22
23
24
25
26
27
    "from IPython.core.display import display, HTML\n",
    "display(HTML('<style>.container { width:100% !important; }</style>'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
28
    "# Convert Vadere trajectories into a DataFrame"
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
   ]
  },
  {
   "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",
49
50
    "    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",
51
52
53
54
55
56
57
58
59
60
    "    return dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "file = \"./data/TrajectoryMetric/trajectories_simulation.txt\"\n",
61
62
63
    "f = open(file, \"r\")\n",
    "header = f.readline();\n",
    "trajectories = dict({});\n",
64
    "\n",
65
66
67
68
69
    "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",
70
71
72
73
74
    "\n",
    "ptrajectories = trajectories_to_dataframe(trajectories)\n",
    "ptrajectories.head()"
   ]
  },
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
  {
   "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",
98
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
    "    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",
125
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
    "    \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)"
   ]
  },
198
199
200
201
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
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
    "# 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",
    "trajectoriesReal[\"timeDelta\"] = trajectoriesReal[\"endTime\"] - trajectoriesReal[\"startTime\"]\n",
    "evacuation_time = trajectoriesReal.groupby([\"pedestrianId\"])[\"timeDelta\"].sum()\n",
    "\n",
229
230
231
232
233
234
235
    "# 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",
236
237
238
239
    "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",
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    "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"
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
   ]
  },
  {
   "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"
277
278
279
280
281
282
283
284
285
286
287
288
289
   ]
  },
  {
   "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",
290
291
292
    "def get_trajectories(t, trajectories):\n",
    "    return trajectories[np.logical_and(trajectories.startTime <= t, trajectories.endTime >= t)]\n",
    "\n",
293
294
    "def get_pedestrianIds(trajectories):\n",
    "    return trajectories['pedestrianId'].unique()\n",
295
    "\n",
296
297
298
    "#def get_velocity(trajectories, t, dt):\n",
    "#    trajectories[np.logical_and(trajectory.endX >= xmax, trajectory.startX < xmax)]\n",
    "\n",
299
    "def get_footstep(trajectory, i):\n",
300
301
    "    \"\"\"returns the i-ths footstep.\"\"\"\n",
    "    return trajectory.iloc[i];\n",
302
    "\n",
303
304
305
306
307
308
    "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",
309
    "\n",
310
311
312
    "def start_time(trajectory):\n",
    "    \"\"\"returns the time of the first footstep of the trajectory.\"\"\"\n",
    "    return get_footstep(trajectory, 0)['startTime'];\n",
313
314
    "\n",
    "def end_time(trajectory):\n",
315
316
317
318
319
320
    "    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",
321
322
    "\n",
    "def min_end_time(trajectories):\n",
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    "    \"\"\"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",
339
340
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
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
419
420
421
422
423
424
425
426
427
428
    "    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",
    "    i1 = trajectory[trajectory.endX >= xmax].index.max()\n",
    "    i2 = trajectory[trajectory.endX <= xmin].index.max()\n",
    "    #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",
    "        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_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",
    "#cuttail_by(trajectoriesReal, 13, 22).head()\n",
    "#cuthead_by(trajectoriesReal, 0, 4).tail()\n",
    "#traj.loc[100]\n",
    "#trajectoriesReal.tail()"
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
   ]
  },
  {
   "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",
450
451
452
453
    "    dx = x1-x2;\n",
    "    dy = y1-y2;\n",
    "    return np.sqrt(dx*dx + dy*dy);\n",
    "\n",
454
455
456
    "def mean_velocity_at(t, trajectories):\n",
    "    return get_trajectories(t, trajectories)['velocity'].mean()\n",
    "\n",
457
    "def trajectory_length(trajectory):\n",
458
459
460
461
462
463
464
465
466
467
468
    "    \"\"\"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",
469
470
    "    return np.array([x2-x1, y2-y1]);\n",
    "\n",
471
472
    "def footstep_duration(fs):\n",
    "    \"\"\"Duration of a footstep.\"\"\"\n",
473
474
475
476
    "    startTime = fs['startTime'];\n",
    "    endTime = fs['endTime'];\n",
    "    return endTime-startTime;\n",
    "\n",
477
478
479
    "def trajectory_duration(trajectory):\n",
    "    \"\"\"Euclidean length of a trajectory.\"\"\"\n",
    "    return (trajectory['endTime'] - trajectory['startTime']).sum();\n",
480
    "\n",
481
482
483
    "def footstep_speed(fs):\n",
    "    \"\"\"Speed of the footstep.\"\"\"\n",
    "    return footstep_length(fs) / footstep_duration(fs);\n",
484
    "\n",
485
486
487
    "def trajectory_speed(fs):\n",
    "    \"\"\"Speed of the trajectory.\"\"\"\n",
    "    return trajectory_length(fs) / trajectory_duration(fs);\n",
488
    "\n",
489
490
491
492
493
494
495
496
497
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
    "#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",
587
588
589
590
591
592
593
594
595
    "    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": [
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    "#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",
611
612
613
614
615
    "#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()"
616
617
618
619
620
621
622
623
624
625
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "code_folding": []
   },
   "outputs": [],
   "source": [
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
    "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",
646
    "    return match"
647
648
649
   ]
  },
  {
650
   "cell_type": "markdown",
651
652
   "metadata": {},
   "source": [
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
    "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."
673
674
675
676
677
678
679
680
681
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def to_line(trajectory, xleft):\n",
682
    "    \"\"\"Transforms a trajectory into a Line2D.\"\"\"\n",
683
    "    current_palette = sns.color_palette()\n",
684
685
    "    x = trajectory['endX'].values\n",
    "    y = trajectory['endY'].values\n",
686
687
688
689
    "    if x[0] < xleft:\n",
    "        c = current_palette[2]\n",
    "    else:\n",
    "        c = current_palette[0]\n",
690
    "    return x, y, Line2D(x, y, color=c, linewidth=0.3)\n",
691
    "\n",
692
693
694
695
696
697
698
699
700
701
702
703
704
    "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": [
705
706
    "x_vcenter = 17.5\n",
    "y_vcenter = 5.2\n",
707
    "\n",
708
709
710
711
712
713
    "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",
714
    "\n",
715
716
717
718
719
720
    "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",
721
722
723
724
725
    "\n",
    "plt.show()"
   ]
  },
  {
726
   "cell_type": "markdown",
727
728
   "metadata": {},
   "source": [
729
730
731
    "# 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. "
732
733
734
735
736
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
737
738
739
   "metadata": {
    "scrolled": true
   },
740
741
   "outputs": [],
   "source": [
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    "times = np.arange(0, 70, 0.2)\n",
    "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"
773
774
775
   ]
  },
  {
776
   "cell_type": "markdown",
777
778
   "metadata": {},
   "source": [
779
780
781
    "# 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."
782
783
784
785
786
787
788
789
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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
    "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",
    "    traj.loc[:,'x'] = traj['startX'] + (traj['endX'] - traj['startX']) * (t - traj['startTime']) / (traj['endTime'] - traj['startTime'])\n",
    "    traj.loc[:,'y'] = traj['startY'] + (traj['endY'] - traj['startY']) * (t - traj['startTime']) / (traj['endTime'] - traj['startTime'])\n",
    "    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",
    "    if number_of_peds == 0:\n",
    "        return 0\n",
    "    else:\n",
    "        return number_of_peds / area\n",
    "    \n",
    "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",
    "\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"
838
839
840
841
842
843
844
845
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
846
847
848
849
850
851
852
853
854
    "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()"
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
   ]
  }
 ],
 "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",
874
   "version": "3.6.8"
875
876
877
878
879
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}