forked from sovaa/submission-criteria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase_manager.py
409 lines (332 loc) · 12.7 KB
/
database_manager.py
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
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
# System
"""MongoDB Data Access Object."""
import os
import datetime
import logging
import math
# Third Party
import pymongo as pymongo
from bson.objectid import ObjectId
import pandas as pd
from sklearn.metrics import log_loss
import numpy as np
# First Party
from concordance import get_submission_pieces
MONGO_URL = os.environ.get("MONGO_URL", "mongodb://localhost:27017/numerai-dev")
MONGO_DB_NAME = os.environ.get("MONGO_DB_NAME", "numerai-dev")
def connect_db(local_db = True):
"""Make a connection to either the production or local database. The defintions
of local and production can be changed with environment variables.
"""
url = MONGO_URL
db_name = MONGO_DB_NAME
client = pymongo.MongoClient(url)
return client[db_name]
class DatabaseManager(object):
def __init__(self, local_db = True):
self.db = connect_db(local_db)
def __hash__(self):
"""
We want to implement the hash function so we can use this with a lru_cache
but we don't actually care about hashing it.
"""
return 314159
def update_leaderboard(self, submission_id, filemanager):
"""Update the leaderboard with a submission
Parameters:
----------
submission_id : string
ID of the submission
filemanager : FileManager
S3 Bucket data access object for querying competition datasets
"""
submission = self.db.submissions.find_one({"_id":ObjectId(submission_id)})
submission_id = submission["_id"]
competition_id = submission["competition_id"]
# Get the tournament data
extract_dir = filemanager.download_dataset(competition_id)
tournament_data = pd.read_csv(os.path.join(extract_dir, "numerai_tournament_data.csv"))
# Get the user submission
s3_file = self.get_filename(submission_id)
local_file = filemanager.download([s3_file])[0]
submission_data = pd.read_csv(local_file)
validation_data = tournament_data[tournament_data.data_type == "validation"]
validation_submission_data = submission_data[submission_data.id.isin(validation_data.id.values)]
validation_eras = np.unique(validation_data.era.values)
num_eras = len(validation_eras)
# Calculate era loglosses
better_than_random_era_count = 0
for era in validation_eras:
era_data = validation_data[validation_data.era == era]
submission_era_data = validation_submission_data[validation_submission_data.id.isin(era_data.id.values)]
era_data = era_data.sort_values(["id"])
submission_era_data = submission_era_data.sort_values(["id"])
logloss = log_loss(era_data.target.values, submission_era_data.probability.values)
if logloss < -math.log(0.5):
better_than_random_era_count += 1
consistency = better_than_random_era_count / num_eras * 100
print("Consistency: {}".format(consistency))
self.db.submissions.update_one(
{"_id": submission_id},
{
"$set": {
"consistency": consistency,
"concordant": {
"pending": True
},
"original": {
"pending": True
}
}
}
)
competition_id = submission["competition_id"]
# TODO remove list comprehension, change to find_one, and change checks/loops
lb_position = [a for a in self.db.competitions.find({"_id": int(competition_id)}, {"leaderboard": {"$elemMatch": {"username": submission["username"]}}})]
is_in_leaderboard = False
for lb in lb_position:
try:
lb["leaderboard"]
is_in_leaderboard = True
except:
pass
if is_in_leaderboard:
self.db.competitions.update_one(
{
"_id": int(competition_id),
"leaderboard": {
"$elemMatch": {
"username": submission["username"]
}
}
},
{
"$set": {
"leaderboard.$.submission_id": ObjectId(submission_id),
"leaderboard.$.logloss.validation": submission["validationLogloss"],
"leaderboard.$.logloss.consistency": consistency,
"leaderboard.$.concordant": {
"pending": True
},
"leaderboard.$.original": {
"pending": True
}
}
},
upsert=False
)
else:
user = self.db.users.find_one({"username":submission["username"]})
self.db.competitions.update(
{"_id": int(competition_id)},
{
"$push": {
"leaderboard": {
"username": submission["username"],
"submission_id": ObjectId(submission_id),
"earnings": {
"career": {
"usd": user["earnings"]["career"]["usd"],
"nmr": user["earnings"]["career"]["nmr"]
},
"competition": {
"usd": 0,
"nmr": 0
}
},
"logloss": {
"validation": submission["validationLogloss"],
"consistency": consistency
},
"concordant": {
"pending": True
},
"original": {
"pending": True
}
}
}
}
)
def write_concordance(self, submission_id, competition_id, concordance):
"""Write to both the submission and leaderboard
Parameters:
-----------
submission_id : string
ID of the submission
competition_id : int
The numerical ID of the competition round
concordance : bool
The calculated concordance for a submission
"""
concordance = bool(concordance)
logging.getLogger().info("Writing out submission_id {} concordance {}".format(submission_id, concordance))
self.db.submissions.update_one(
{"_id": ObjectId(submission_id)},
{
"$set": {
"concordant": {
"pending": False,
"value": concordance
}
}
},
upsert=False
)
lb_position = [a for a in self.db.competitions.find({"_id": int(competition_id)}, {"leaderboard": {"$elemMatch": {"submission_id": ObjectId(submission_id)}}})]
if len(lb_position)>0:
self.db.competitions.update_one(
{
"_id": int(competition_id),
"leaderboard": {
"$elemMatch": {
"submission_id": ObjectId(submission_id)
}
}
},
{
"$set": {
"leaderboard.$.concordant": {
"pending": False,
"value": concordance
}
}
},
upsert=False
)
def write_originality(self, submission_id, competition_id, is_original):
""" Write to both the submission and leaderboard
Parameters:
-----------
submission_id : string
The ID of the submission
competition_id : int
The numerical ID of the competition round
is_original : bool
Originality value for the submission
"""
#TODO: change to reference submission data directly in leaderboard (instead of duplicating data manually)
logging.getLogger().info("Writing out submission_id {} originality {}".format(submission_id, is_original))
self.db.submissions.update_one(
{"_id": ObjectId(submission_id)},
{
"$set": {
"original": {
"pending": False,
"value": is_original
}
}
},
upsert=False
)
lb_position = [a for a in self.db.competitions.find({"_id": int(competition_id)}, {"leaderboard": {"$elemMatch": {"submission_id": ObjectId(submission_id)}}})]
if len(lb_position)>0:
self.db.competitions.update_one(
{
"_id": int(competition_id),
"leaderboard": {
"$elemMatch": {
"submission_id": ObjectId(submission_id)
}
}
},
{
"$set": {
"leaderboard.$.original": {
"pending": False,
"value": is_original
}
}
},
upsert=False
)
def get_originality(self, submission_id):
"""Get the originality for a submission_id
Parameters:
-----------
submission_id : string
The ID of the submission
Returns:
--------
bool
Whether the submission was deemed original
"""
submission = self.db.submissions.find_one({"_id":ObjectId(submission_id)})
if "original" in submission:
return submission["original"]
return True
def get_everyone_elses_recent_submssions(self, competition_id, username, end_time = None):
""" Get all the submissions, excluding those by username, up to time end_time.
Parameters:
-----------
competition_id : int
The numerical ID of the competition round
username : string
The username belonging to the submission
endtime : time, optional, default: None
Lookback window for querying recent submissions
Returns:
--------
submissions : list
List of all recent submissions for the competition round less than end_time
"""
if end_time is None:
end_time = datetime.datetime.utcnow()
pipeline = [{
"$match": {
"competition_id": int(competition_id),
"created": {
"$lt": end_time
}
}
},
{
"$sort": {
"created": -1
}
},
{
"$group": {
"_id": "$username",
"username": {
"$first": "$username"
},
"filename": {
"$first": "$filename"
},
"submission_id": {
"$first": "$_id"
},
"created": {
"$first": "$created"
}
}
}]
submissions = []
for submission in self.db.submissions.aggregate(pipeline):
if submission["username"] == username:
continue
submissions.append(submission)
return submissions
def get_filename(self, submission_id):
"""Get the filename that is used by S3 based on submission_id
Paramters:
----------
submission_id:
The ID of the submission_id
Returns:
--------
string
The filename belonging to the submission id, if not found return None
"""
submission = self.db.submissions.find_one({"_id": ObjectId(submission_id)})
fname = submission.get("filename", None)
user = submission.get("username", None)
if fname and user:
return "{}/{}".format(user, fname)
else:
return None
def get_date_created(self, submission_id):
"""Get the date create for a submission"""
submission = self.db.submissions.find_one({"_id":ObjectId(submission_id)})
return submission["created"]