File size: 6,721 Bytes
10927b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "eb4d98e6",
   "metadata": {},
   "source": [
    "### In this notebook we will use Valhalla to snap the latitude/longitude points from VED to roads using OpenStreetMap data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d99459b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import requests\n",
    "import json\n",
    "from tqdm.notebook import tqdm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b3e0b1f",
   "metadata": {},
   "source": [
    "Create the headers and the meili request body."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "20178448",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_meili_request_body(df_trip):\n",
    "    \"\"\"Returns the body for meili for its request.\n",
    "    \"\"\"\n",
    "    coordinates = df_trip.to_json(orient='records')\n",
    "    head = '{\"shape\":'\n",
    "    tail = \"\"\",\"search_radius\": 5, \"shape_match\":\"map_snap\", \"costing\":\"auto\", \"format\":\"osrm\"}\"\"\"\n",
    "    body = head + coordinates + tail\n",
    "    return body"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "357a90c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "headers = {'Content-type': 'application/json'}\n",
    "trace_url = \"http://localhost:8002/trace_attributes\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "154c0f88",
   "metadata": {},
   "source": [
    "Read all the file names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f1097900",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "da818fc0e91c42fcb09ca4b0fadd0d45",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/54 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "data_path = \"../data/ved/dynamic/\"\n",
    "files = [os.path.join(data_path, file) for file in tqdm(os.listdir(data_path)) if file.endswith(\".csv\")]\n",
    "files.sort()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f9b0acf",
   "metadata": {},
   "source": [
    "The functions that send the requests to the meili\n",
    "Match types: {'matched': 0, 'interpolated': 1, 'unmatched': 2}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "91bffff4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_matched_response(matched_points, group_df):\n",
    "    \"\"\" Returns a list of dictionaries for the matched coordinates.\n",
    "        Dictionary keys: matched_lat, matched_lon, and match_type. \n",
    "        If a points was not matched, returns the original coordinates. \"\"\"\n",
    "    \n",
    "    processed_matches = []\n",
    "    for (i, matched_point) in enumerate(matched_points):\n",
    "        match_type = {'matched': 0, 'interpolated': 1, 'unmatched': 2}\n",
    "        \n",
    "        matched_dict = {'matched_lat': group_df.iloc[i, 1] \n",
    "                        if matched_point['type'] == 'unmatched' \n",
    "                        else matched_point['lat'], \n",
    "                        'matched_lon': group_df.iloc[i, 0] \n",
    "                        if matched_point['type'] == 'unmatched' \n",
    "                        else matched_point['lon'], \n",
    "                        'match_type': match_type[matched_point['type']]}\n",
    "\n",
    "        processed_matches.append(matched_dict)\n",
    "    \n",
    "    return processed_matches\n",
    "      "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fb36bca3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def map_match(file):\n",
    "    \"\"\" Takes a csv file and sends requests to Valhalla Meili service to snap the coordinates\n",
    "    in the file to roads. \"\"\"\n",
    "    signal_df = pd.read_csv(file)\n",
    "    dataframes = []\n",
    "    \n",
    "    # Group the dataframe by the columns VehId and Trip\n",
    "    for _, group_df in signal_df.groupby(['VehId', 'Trip']):\n",
    "        group = group_df.rename(columns={'Longitude[deg]':'lon','Latitude[deg]':'lat'})[['lon', 'lat']]\n",
    "        meili_request_body = create_meili_request_body(group)\n",
    "        r = requests.post(trace_url, data=str(meili_request_body), headers=headers)\n",
    "        \n",
    "        if r.status_code == 200:\n",
    "            res = r.json()\n",
    "            matched_dicts = process_matched_response(res['matched_points'], group)\n",
    "            matched_df = pd.DataFrame.from_dict(matched_dicts)\n",
    "            dataframes.append(matched_df.set_index(group_df.index.copy()))\n",
    "            \n",
    "        else:\n",
    "            print('Error', r.status_code)\n",
    "\n",
    "    conc_dfs = pd.concat(dataframes)\n",
    "    signal_df = pd.merge(signal_df, conc_dfs, left_index=True, right_index=True)\n",
    "    return signal_df"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d6be11d",
   "metadata": {},
   "source": [
    "Process all files and save the results to another directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d1466e8d",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "18f1e3506e9d40eeb9f8966359fd6065",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/54 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def get_save_path(filename):\n",
    "    return f\"../data/ved-valhalla/{filename[len(data_path)-1:]}\"\n",
    "\n",
    "for file in tqdm(files):\n",
    "    matched_df = map_match(file)\n",
    "    matched_df.to_csv(get_save_path(file), na_rep=np.nan, index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7865645b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}