File size: 13,552 Bytes
b0335cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Augment data from TSV files to change team names and years"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create dictionary for mapping team names and abbreviations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n",
      "30\n",
      "30\n",
      "30\n",
      "0,Atlanta Hawks,0,ATL,0\n",
      "1,Boston Celtics,1,BOS,1\n",
      "2,Cleveland Cavaliers,2,CLE,2\n",
      "3,New Orleans Pelicans,3,NOP,3\n",
      "4,Chicago Bulls,4,CHI,4\n",
      "5,Dallas Mavericks,5,DAL,5\n",
      "6,Denver Nuggets,6,DEN,6\n",
      "7,Golden State Warriors,7,GSW,7\n",
      "8,Houston Rockets,8,HOU,8\n",
      "9,Los Angeles Clippers,9,LAC,9\n",
      "10,Los Angeles Lakers,10,LAL,10\n",
      "11,Miami Heat,11,MIA,11\n",
      "12,Milwaukee Bucks,12,MIL,12\n",
      "13,Minnesota Timberwolves,13,MIN,13\n",
      "14,Brooklyn Nets,14,BKN,14\n",
      "15,New York Knicks,15,NYK,15\n",
      "16,Orlando Magic,16,ORL,16\n",
      "17,Indiana Pacers,17,IND,17\n",
      "18,Philadelphia 76ers,18,PHI,18\n",
      "19,Phoenix Suns,19,PHX,19\n",
      "20,Portland Trail Blazers,20,POR,20\n",
      "21,Sacramento Kings,21,SAC,21\n",
      "22,San Antonio Spurs,22,SAS,22\n",
      "23,Oklahoma City Thunder,23,OKC,23\n",
      "24,Toronto Raptors,24,TOR,24\n",
      "25,Utah Jazz,25,UTA,25\n",
      "26,Memphis Grizzlies,26,MEM,26\n",
      "27,Washington Wizards,27,WAS,27\n",
      "28,Detroit Pistons,28,DET,28\n",
      "29,Charlotte Hornets,29,CHA,29\n"
     ]
    }
   ],
   "source": [
    "# Create team map and team array\n",
    "team_map = {\n",
    "    \"Atlanta Hawks\": 0,\n",
    "    \"Boston Celtics\": 1,\n",
    "    \"Cleveland Cavaliers\": 2,\n",
    "    \"New Orleans Pelicans\": 3,\n",
    "    \"Chicago Bulls\": 4,\n",
    "    \"Dallas Mavericks\": 5,\n",
    "    \"Denver Nuggets\": 6,\n",
    "    \"Golden State Warriors\": 7,\n",
    "    \"Houston Rockets\": 8,\n",
    "    \"Los Angeles Clippers\": 9,\n",
    "    \"Los Angeles Lakers\": 10,\n",
    "    \"Miami Heat\": 11,\n",
    "    \"Milwaukee Bucks\": 12,\n",
    "    \"Minnesota Timberwolves\": 13,\n",
    "    \"Brooklyn Nets\": 14,\n",
    "    \"New York Knicks\": 15,\n",
    "    \"Orlando Magic\": 16,\n",
    "    \"Indiana Pacers\": 17,\n",
    "    \"Philadelphia 76ers\": 18,\n",
    "    \"Phoenix Suns\": 19,\n",
    "    \"Portland Trail Blazers\": 20,\n",
    "    \"Sacramento Kings\": 21,\n",
    "    \"San Antonio Spurs\": 22,\n",
    "    \"Oklahoma City Thunder\": 23,\n",
    "    \"Toronto Raptors\": 24,\n",
    "    \"Utah Jazz\": 25,\n",
    "    \"Memphis Grizzlies\": 26,\n",
    "    \"Washington Wizards\": 27,\n",
    "    \"Detroit Pistons\": 28,\n",
    "    \"Charlotte Hornets\": 29\n",
    "}\n",
    "\n",
    "team_array = [\n",
    "\"Atlanta Hawks\",\n",
    "\"Boston Celtics\",\n",
    "\"Cleveland Cavaliers\",\n",
    "\"New Orleans Pelicans\",\n",
    "\"Chicago Bulls\",\n",
    "\"Dallas Mavericks\",\n",
    "\"Denver Nuggets\",\n",
    "\"Golden State Warriors\",\n",
    "\"Houston Rockets\",\n",
    "\"Los Angeles Clippers\",\n",
    "\"Los Angeles Lakers\",\n",
    "\"Miami Heat\",\n",
    "\"Milwaukee Bucks\",\n",
    "\"Minnesota Timberwolves\",\n",
    "\"Brooklyn Nets\",\n",
    "\"New York Knicks\",\n",
    "\"Orlando Magic\",\n",
    "\"Indiana Pacers\",\n",
    "\"Philadelphia 76ers\",\n",
    "\"Phoenix Suns\",\n",
    "\"Portland Trail Blazers\",\n",
    "\"Sacramento Kings\",\n",
    "\"San Antonio Spurs\",\n",
    "\"Oklahoma City Thunder\",\n",
    "\"Toronto Raptors\",\n",
    "\"Utah Jazz\",\n",
    "\"Memphis Grizzlies\",\n",
    "\"Washington Wizards\",\n",
    "\"Detroit Pistons\",\n",
    "\"Charlotte Hornets\"]\n",
    "\n",
    "# Check that array and dictionary are aligned properly\n",
    "for i in range(len(team_array)):\n",
    "    if i != team_map[team_array[i]]:\n",
    "        print(\"Invalid!\")\n",
    "\n",
    "# Create abbreviation map and array\n",
    "abbreviation_array = [\n",
    "\"ATL\",\n",
    "\"BOS\",\n",
    "\"CLE\",\n",
    "\"NOP\",\n",
    "\"CHI\",\n",
    "\"DAL\",\n",
    "\"DEN\",\n",
    "\"GSW\",\n",
    "\"HOU\",\n",
    "\"LAC\",\n",
    "\"LAL\",\n",
    "\"MIA\",\n",
    "\"MIL\",\n",
    "\"MIN\",\n",
    "\"BKN\",\n",
    "\"NYK\",\n",
    "\"ORL\",\n",
    "\"IND\",\n",
    "\"PHI\",\n",
    "\"PHX\",\n",
    "\"POR\",\n",
    "\"SAC\",\n",
    "\"SAS\",\n",
    "\"OKC\",\n",
    "\"TOR\",\n",
    "\"UTA\",\n",
    "\"MEM\",\n",
    "\"WAS\",\n",
    "\"DET\",\n",
    "\"CHA\"]\n",
    "\n",
    "abbreviation_map = {}\n",
    "for i in range(len(abbreviation_array)):\n",
    "    abbreviation_map[abbreviation_array[i]] = i\n",
    "\n",
    "print(len(team_array))\n",
    "print(len(team_map))\n",
    "print(len(abbreviation_array))\n",
    "print(len(abbreviation_map))\n",
    "\n",
    "# Check that team names, abbreviation and index maps all line up\n",
    "for i in range(len(team_array)):\n",
    "    print(str(i) + \",\" + team_array[i] + \",\" + str(team_map[team_array[i]]) + \",\" + abbreviation_array[i] + \",\" + str(abbreviation_map[abbreviation_array[i]]))\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create function to augment data by updating team names in SQL queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import pandas as pd\n",
    "import sqlite3 as sql\n",
    "\n",
    "# Find team names in the sample\n",
    "def find_teams_in_sample(sample, team_list):\n",
    "    result = []\n",
    "    for i in range(len(team_list)):\n",
    "        if team_list[i] in sample:\n",
    "            result.append(i)\n",
    "    return result\n",
    "\n",
    "# Get random number excluding the one already used\n",
    "def get_random_excluding(floor, ceiling, excluded_number):\n",
    "    number = random.randint(floor, ceiling)\n",
    "    while number == excluded_number:\n",
    "        number = random.randint(floor, ceiling)\n",
    "    return number\n",
    "\n",
    "def augment_dataframe(df, team_list, abbreviation_list, database):\n",
    "    augmented_df = df.copy()\n",
    "    for _, row in df.iterrows():\n",
    "        team_idx = find_teams_in_sample(row[\"natural_query\"], team_list)\n",
    "        # Only do simple update if only one team detected \n",
    "        if len(team_idx) == 1:\n",
    "            team_idx = team_idx[0]\n",
    "\n",
    "            # Check if team name is used in SQL query\n",
    "            if team_list[team_idx] in row[\"sql_query\"]:\n",
    "                # Create updated query with new team \n",
    "                new_team_name = team_list[get_random_excluding(0, 29, team_idx)]\n",
    "                new_natural_query = row[\"natural_query\"].replace(team_list[team_idx], new_team_name)\n",
    "                new_sql_query = row[\"sql_query\"].replace(team_list[team_idx], new_team_name)\n",
    "\n",
    "                # Obtain result of running on sqlite database\n",
    "                try:\n",
    "                    database.execute(new_sql_query)\n",
    "                    rows = database.fetchall()\n",
    "                    if len(rows) == 1:\n",
    "                        if len(rows[0]) == 2 and rows[0][1] == None:\n",
    "                            result = str(rows[0][0])\n",
    "                        else:\n",
    "                            result = \" | \".join(str(x) for x in rows[0]) \n",
    "                    else:\n",
    "                        result = \" | \".join(str(x) for x in rows)\n",
    "                    # Append new row to augmented dataframe if result successful\n",
    "                    new_row = pd.DataFrame([{'natural_query': new_natural_query, 'sql_query': new_sql_query, 'result': result}])\n",
    "                    augmented_df = pd.concat([augmented_df, new_row], ignore_index=True)\n",
    "                except:\n",
    "                    pass\n",
    "\n",
    "            # Check if abbreviation is in SQL query used instead\n",
    "            elif abbreviation_list[team_idx] in row[\"sql_query\"]:\n",
    "                # Create updated query with new team \n",
    "                new_index = get_random_excluding(0, 29, team_idx)\n",
    "                new_team_name = team_list[new_index]\n",
    "                new_team_abbreviation = abbreviation_list[new_index]\n",
    "                new_natural_query = row[\"natural_query\"].replace(team_list[team_idx], new_team_name)\n",
    "                new_sql_query = row[\"sql_query\"].replace(abbreviation_list[team_idx], new_team_abbreviation)\n",
    "\n",
    "                # Obtain result of running on sqlite database\n",
    "                try:\n",
    "                    database.execute(new_sql_query)\n",
    "                    rows = database.fetchall()\n",
    "                    if len(rows) == 1:\n",
    "                        \n",
    "                        if len(rows[0]) == 2 and rows[0][1] == None:\n",
    "                            result = str(rows[0][0])\n",
    "                        else:\n",
    "                            result = \" | \".join(str(x) for x in rows[0]) \n",
    "                    else:\n",
    "                        result = \" | \".join(str(x) for x in rows)\n",
    "                    # Append new row to augmented dataframe if result successful\n",
    "                    new_row = pd.DataFrame([{'natural_query': new_natural_query, 'sql_query': new_sql_query, 'result': result}])\n",
    "                    augmented_df = pd.concat([augmented_df, new_row], ignore_index=True)\n",
    "                except:\n",
    "                    pass\n",
    "    return augmented_df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test functions on small dataframe sample"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total dataset examples: 1044\n",
      "New Dataset Length:\n",
      "6\n",
      "\n",
      "What is the total free throws made by the Indiana Pacers at home?\n",
      "SELECT SUM(ftm_home) as total_ftm  FROM game  WHERE team_name_home = 'Indiana Pacers';\n",
      "39545.0\n",
      "\n",
      "How many total rebounds did the Los Angeles Lakers grab in the 1985 season?\n",
      "SELECT SUM(reb) AS total_rebounds FROM (     SELECT reb_home AS reb FROM game WHERE team_abbreviation_home = 'LAL' AND season_id = '21985'     UNION ALL     SELECT reb_away AS reb FROM game WHERE team_abbreviation_away = 'LAL' AND season_id = '21985' );\n",
      "3655.0\n",
      "\n",
      "How many home games did the Orlando Magic play in the 2013 season?\n",
      "SELECT COUNT(*) FROM game WHERE team_name_home = 'Orlando Magic' AND season_id = '22013';\n",
      "41.0\n",
      "\n",
      "What is the total free throws made by the Denver Nuggets at home?\n",
      "SELECT SUM(ftm_home) as total_ftm  FROM game  WHERE team_name_home = 'Denver Nuggets';\n",
      "43821.0\n",
      "\n",
      "How many total rebounds did the Miami Heat grab in the 1985 season?\n",
      "SELECT SUM(reb) AS total_rebounds FROM (     SELECT reb_home AS reb FROM game WHERE team_abbreviation_home = 'MIA' AND season_id = '21985'     UNION ALL     SELECT reb_away AS reb FROM game WHERE team_abbreviation_away = 'MIA' AND season_id = '21985' );\n",
      "None\n",
      "\n",
      "How many home games did the Atlanta Hawks play in the 2013 season?\n",
      "SELECT COUNT(*) FROM game WHERE team_name_home = 'Atlanta Hawks' AND season_id = '22013';\n",
      "41\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Load dataset\n",
    "train_df = pd.read_csv(\"./train-data/sql_train.tsv\", sep='\\t')\n",
    "\n",
    "# Display dataset info\n",
    "print(f\"Total dataset examples: {len(train_df)}\")\n",
    "#print(train_df.head())\n",
    "\n",
    "# Setup sqlite database connection\n",
    "connection = sql.connect('./nba-data/nba.sqlite')\n",
    "cursor = connection.cursor()\n",
    "\n",
    "# Test augmentation on sample of 3 rows\n",
    "test_df = train_df.sample(n=3)\n",
    "#for _, row in test_df.iterrows():\n",
    "    #print(row)\n",
    "#print()\n",
    "#print()\n",
    "\n",
    "# Run augmentation function and print output\n",
    "augmented_df = augment_dataframe(test_df, team_array, abbreviation_array, cursor)\n",
    "print(\"New Dataset Length:\")\n",
    "print(len(augmented_df))\n",
    "print()\n",
    "for _, row in augmented_df.iterrows():\n",
    "    print(row[\"natural_query\"])\n",
    "    print(row[\"sql_query\"])\n",
    "    print(row[\"result\"])\n",
    "    print()"
   ]
  }
 ],
 "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.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}