This repository was archived by the owner on Apr 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathupdate_aggregated_data.py
More file actions
384 lines (367 loc) · 13.4 KB
/
update_aggregated_data.py
File metadata and controls
384 lines (367 loc) · 13.4 KB
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
import datetime
import time
from apps.aggregated.models import (
AggregatedTracking,
AggregatedUserGroupStatData,
AggregatedUserStatData,
)
from apps.existing_database.models import MappingSession, Project
from django.core.management.base import BaseCommand
from django.db import connection, models, transaction
from django.utils import timezone
# Factor calculated by @Hagellach37
# For defining the threshold for outliers using `95_percent`
# Used by TASK_GROUP_METADATA_QUERY
# |project_type|median|95_percent|avg|
# |------------|------|----------|---|
# |1|00:00:00.208768|00:00:01.398161|00:00:28.951521|
# |2|00:00:01.330297|00:00:06.076814|00:00:03.481192|
# |3|00:00:02.092967|00:00:11.271081|00:00:06.045881|
UPDATE_PROJECT_GROUP_DATA_USING_PROJECT_ID = f"""
WITH to_calculate_groups AS (
SELECT
project_id,
group_id
FROM groups
WHERE
(project_id, group_id) in (
SELECT
MS.project_id,
MS.group_id
FROM mapping_sessions MS
WHERE
project_id = %(project_id)s
GROUP BY MS.project_id, MS.group_id
) AND
(
total_area is NULL OR time_spent_max_allowed is NULL
)
),
groups_data AS (
SELECT
T.project_id,
T.group_id,
SUM( -- sqkm
ST_Area(T.geom::geography(GEOMETRY,4326)) / 1000000
) as total_task_group_area,
(
CASE
-- Using 95_percent value of existing data for each project_type
WHEN P.project_type = {Project.Type.BUILD_AREA.value} THEN 1.4
WHEN P.project_type = {Project.Type.COMPLETENESS.value} THEN 1.4
WHEN P.project_type = {Project.Type.CHANGE_DETECTION.value} THEN 11.2
-- FOOTPRINT: Not calculated right now
WHEN P.project_type = {Project.Type.FOOTPRINT.value} THEN 6.1
WHEN P.project_type = {Project.Type.STREET.value} THEN 65
ELSE 1
END
) * COUNT(*) as time_spent_max_allowed
FROM tasks T
INNER JOIN to_calculate_groups G USING (project_id, group_id)
INNER JOIN projects P USING (project_id)
GROUP BY project_id, P.project_type, group_id
)
UPDATE groups G
SET
total_area = GD.total_task_group_area,
time_spent_max_allowed = GD.time_spent_max_allowed
FROM groups_data GD
WHERE
G.project_id = GD.project_id AND
G.group_id = GD.group_id;
"""
UPDATE_PROJECT_GROUP_DATA_USING_TIME_RANGE = f"""
WITH to_calculate_groups AS (
SELECT
project_id,
group_id
FROM groups
WHERE
(project_id, group_id) in (
SELECT
MS.project_id,
MS.group_id
FROM mapping_sessions MS
WHERE
MS.start_time >= %(from_date)s
AND MS.start_time < %(until_date)s
GROUP BY MS.project_id, MS.group_id
) AND
(
total_area is NULL OR time_spent_max_allowed is NULL
)
),
groups_data AS (
SELECT
T.project_id,
T.group_id,
SUM( -- sqkm
ST_Area(T.geom::geography(GEOMETRY,4326)) / 1000000
) as total_task_group_area,
(
CASE
-- Using 95_percent value of existing data for each project_type
WHEN P.project_type = {Project.Type.BUILD_AREA.value} THEN 1.4
WHEN P.project_type = {Project.Type.COMPLETENESS.value} THEN 1.4
WHEN P.project_type = {Project.Type.CHANGE_DETECTION.value} THEN 11.2
-- FOOTPRINT: Not calculated right now
WHEN P.project_type = {Project.Type.FOOTPRINT.value} THEN 6.1
WHEN P.project_type = {Project.Type.STREET.value} THEN 65
ELSE 1
END
) * COUNT(*) as time_spent_max_allowed
FROM tasks T
INNER JOIN to_calculate_groups G USING (project_id, group_id)
INNER JOIN projects P USING (project_id)
GROUP BY project_id, P.project_type, group_id
)
UPDATE groups G
SET
total_area = GD.total_task_group_area,
time_spent_max_allowed = GD.time_spent_max_allowed
FROM groups_data GD
WHERE
G.project_id = GD.project_id AND
G.group_id = GD.group_id;
"""
TASK_GROUP_METADATA_QUERY = f"""
SELECT
G.project_id,
G.group_id,
(
CASE
-- Hide area for Footprint
WHEN P.project_type = {Project.Type.FOOTPRINT.value} THEN 0
ELSE G.total_area
END
) as total_task_group_area,
G.time_spent_max_allowed
FROM groups G
INNER JOIN used_task_groups UG USING (project_id, group_id)
INNER JOIN projects P USING (project_id)
GROUP BY G.project_id, P.project_type, G.group_id
"""
UPDATE_USER_DATA_SQL = f"""
INSERT INTO "{AggregatedUserStatData._meta.db_table}" (
project_id,
user_id,
timestamp_date,
total_time,
task_count,
area_swiped,
swipes
)
(
-- Retrieve used task groups
WITH used_task_groups as (
SELECT
MS.project_id,
P.project_type,
MS.group_id
FROM mapping_sessions MS
INNER JOIN projects P USING (project_id)
WHERE
MS.start_time >= %(from_date)s
AND MS.start_time < %(until_date)s
GROUP BY project_id, project_type, group_id -- To get unique
),
-- Calculated area by task_groups
task_group_metadata as ({TASK_GROUP_METADATA_QUERY}),
-- Aggregate data by user
user_data as (
SELECT
MS.project_id,
MS.group_id,
MS.user_id,
MS.start_time::date as timestamp_date,
LEAST(
EXTRACT(EPOCH FROM (MS.end_time - MS.start_time)),
TG.time_spent_max_allowed
) as time_spent_sec,
MS.items_count as task_count,
Coalesce(TG.total_task_group_area, 0) as area_swiped
FROM mapping_sessions MS
LEFT JOIN task_group_metadata TG USING (project_id, group_id)
WHERE
MS.start_time >= %(from_date)s
AND MS.start_time < %(until_date)s
),
-- Additional aggregate by timestamp_date
user_agg_data as (
SELECT
project_id,
user_id,
timestamp_date,
COALESCE(SUM(time_spent_sec), 0) as total_time,
COALESCE(SUM(task_count), 0) as task_count,
COALESCE(SUM(area_swiped), 0) as area_swiped
FROM user_data
GROUP BY project_id, user_id, timestamp_date
)
-- Precalculate additional values here.
SELECT
user_agg_data.*,
CASE
WHEN P.project_type in (1, 4) THEN ROUND(task_count/6)
ELSE task_count
END as swipes
FROM user_agg_data
INNER JOIN projects P USING (project_id)
)
ON CONFLICT (project_id, user_id, timestamp_date)
DO UPDATE SET
total_time = EXCLUDED.total_time,
task_count = EXCLUDED.task_count,
area_swiped = EXCLUDED.area_swiped,
swipes = EXCLUDED.swipes;
"""
UPDATE_USER_GROUP_SQL = f"""
INSERT INTO "{AggregatedUserGroupStatData._meta.db_table}" (
project_id,
user_id,
user_group_id,
timestamp_date,
total_time,
task_count,
area_swiped,
swipes
)
(
-- Retrieve used task groups
WITH used_task_groups as (
SELECT
MS.project_id,
P.project_type,
MS.group_id
FROM mapping_sessions_user_groups MSUR
INNER JOIN mapping_sessions MS USING (mapping_session_id)
INNER JOIN projects P USING (project_id)
WHERE
MS.start_time >= %(from_date)s
AND MS.start_time < %(until_date)s
GROUP BY project_id, project_type, group_id -- To get unique
),
-- Calculated area by task_groups
task_group_metadata as ({TASK_GROUP_METADATA_QUERY}),
-- Aggregate data by user-group
user_group_data as (
SELECT
MS.project_id,
MS.group_id,
MS.user_id,
MSUR.user_group_id,
MS.start_time::date as timestamp_date,
LEAST(
EXTRACT(EPOCH FROM (MS.end_time - MS.start_time)),
TG.time_spent_max_allowed
) as time_spent_sec,
MS.items_count as task_count,
Coalesce(TG.total_task_group_area, 0) as area_swiped
FROM mapping_sessions_user_groups MSUR
INNER JOIN mapping_sessions MS USING (mapping_session_id)
LEFT JOIN task_group_metadata TG USING (project_id, group_id)
WHERE
MS.start_time >= %(from_date)s
AND MS.start_time < %(until_date)s
),
-- Additional aggregate by timestamp_date
user_group_agg_data as (
SELECT
project_id,
user_id,
user_group_id,
timestamp_date,
COALESCE(SUM(time_spent_sec), 0) as total_time,
COALESCE(SUM(task_count), 0) as task_count,
COALESCE(SUM(area_swiped), 0) as area_swiped
FROM user_group_data
GROUP BY project_id, user_id, user_group_id, timestamp_date
)
-- Precalculate additional values here.
SELECT
user_group_agg_data.*,
CASE
WHEN P.project_type in (1, 4) THEN ROUND(task_count/6)
ELSE task_count
END as swipes
FROM user_group_agg_data
INNER JOIN projects P USING (project_id)
)
ON CONFLICT (project_id, user_id, user_group_id, timestamp_date)
DO UPDATE SET
total_time = EXCLUDED.total_time,
task_count = EXCLUDED.task_count,
area_swiped = EXCLUDED.area_swiped,
swipes = EXCLUDED.swipes;
"""
INTERVAL_RANGE_DAYS = 30
class Command(BaseCommand):
def _track(self, tracker_type, label, sql):
tracker, _ = AggregatedTracking.objects.get_or_create(type=tracker_type)
now = timezone.now().date()
# Fallback: For now only update from 1 day before instead of whole data
# which is quite big.
from_date = tracker.value
if tracker.value is not None:
from_date = datetime.datetime.strptime(tracker.value, "%Y-%m-%d").date()
else:
self.stdout.write(f"{label.title()} Last tracker data not found.")
timestamp_min = MappingSession.objects.aggregate(
timestamp_min=models.Min("start_time")
)["timestamp_min"]
if timestamp_min:
self.stdout.write(f"Using min timestamp from database {timestamp_min}")
from_date = timestamp_min.date()
else:
self.stdout.write("Nothing found from database.")
from_date = now
while True:
until_date = min(
now,
from_date + datetime.timedelta(days=INTERVAL_RANGE_DAYS),
)
if from_date >= until_date:
self.stdout.write(f"{label.title()} Nothing to do here.....")
break
params = dict(
from_date=from_date.strftime("%Y-%m-%d"),
until_date=until_date.strftime("%Y-%m-%d"),
)
start_time = time.time()
self.stdout.write(
f"Updating Project Group Data for {label.title()} for date: {params}"
)
with transaction.atomic():
with connection.cursor() as cursor:
cursor.execute(UPDATE_PROJECT_GROUP_DATA_USING_TIME_RANGE, params)
self.stdout.write(
self.style.SUCCESS(
f"Successfull. Runtime: {time.time() - start_time} seconds"
)
)
start_time = time.time()
self.stdout.write(f"Updating {label.title()} Data for date: {params}")
with transaction.atomic():
with connection.cursor() as cursor:
cursor.execute(sql, params)
self.stdout.write(
self.style.SUCCESS(
f"Successfull. Runtime: {time.time() - start_time} seconds"
)
)
tracker.value = from_date = until_date
self.stdout.write(f"Saving date {tracker.value} as last tracker")
tracker.save()
def run(self):
self._track(
AggregatedTracking.Type.AGGREGATED_USER_STAT_DATA_LATEST_DATE,
"user",
UPDATE_USER_DATA_SQL,
)
self._track(
AggregatedTracking.Type.AGGREGATED_USER_GROUP_STAT_DATA_LATEST_DATE,
"user_group",
UPDATE_USER_GROUP_SQL,
)
def handle(self, **_):
self.run()