-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlunch.go
More file actions
385 lines (330 loc) · 9.89 KB
/
lunch.go
File metadata and controls
385 lines (330 loc) · 9.89 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
385
package ditzy
import "math"
// detectLunchBreak finds lunch break patterns for a given timezone offset.
// Returns start (UTC), end (UTC), and confidence (0-1).
// Lunch is expected between 11:00-14:30 local time with durations of 30, 60, or 90 minutes.
//
//nolint:gocognit,revive,maintidx // lunch detection requires analyzing multiple duration patterns and edge cases
func detectLunchBreak(halfHourly map[float64]int, offsetHours float64) (start, end, confidence float64) {
// Check if we have any data in the lunch window
hasData := false
for localHour := 11.0; localHour <= 14.5; localHour += 0.5 {
utcHour := normHour(localHour - offsetHours)
if _, ok := halfHourly[utcHour]; ok {
hasData = true
break
}
}
if !hasData {
return -1, -1, 0
}
// Calculate total events for threshold adjustment
total := 0
for _, count := range halfHourly {
total += count
}
var bestStart, bestDuration, bestScore, bestDrop float64
bestStart = -1
// Try durations: 30, 60, 90 minutes
for duration := 0.5; duration <= 1.5; duration += 0.5 {
// Check each start time in the 11:00-14:30 window
for startLocal := 11.0; startLocal <= 14.5-duration; startLocal += 0.5 {
// Skip unreasonable lunch times (1:30pm or later start)
if startLocal >= 13.5 {
continue
}
startUTC := normHour(startLocal - offsetHours)
beforeUTC := normHour(startUTC - 0.5)
beforeCount := halfHourly[beforeUTC]
// Check pre-lunch activity
preLunchActivity := 0
for t := 1.0; t <= 2.0; t += 0.5 {
checkUTC := normHour(startUTC - t)
preLunchActivity += halfHourly[checkUTC]
}
// Adjust threshold based on data sparsity
minPreActivity := 20
switch {
case total < 50:
minPreActivity = 3
// Check broader window for sparse data
for t := 2.5; t <= 4.0 && preLunchActivity < minPreActivity; t += 0.5 {
checkUTC := normHour(startUTC - t)
preLunchActivity += halfHourly[checkUTC]
}
case total < 200:
minPreActivity = 10
case total < 500:
minPreActivity = 15
}
// Special case: near-noon lunches can have lighter mornings
if startLocal >= 11.5 && startLocal <= 12.5 && preLunchActivity > 0 {
minPreActivity = 1
}
// Check for obvious lunch signal (empty bucket + strong recovery)
hasEmpty := false
for t := 0.0; t < duration; t += 0.5 {
bucket := normHour(startUTC + t)
if count, ok := halfHourly[bucket]; !ok || count == 0 {
hasEmpty = true
break
}
}
afterUTC := normHour(startUTC + duration)
afterCount := halfHourly[afterUTC]
avgLunch := avgActivity(halfHourly, startUTC, duration)
strongRecovery := afterCount >= 5 && (avgLunch == 0 || float64(afterCount) >= avgLunch*3)
obviousSignal := hasEmpty && strongRecovery && startLocal >= 11 && startLocal < 14
if !obviousSignal && preLunchActivity < minPreActivity {
continue
}
// Calculate drop ratio
if beforeCount == 0 {
continue
}
drop := (float64(beforeCount) - avgLunch) / float64(beforeCount)
// Calculate distance from standard lunch times
midpoint := startLocal + duration/2
distNoon := math.Abs(midpoint - 12.0)
dist1130 := math.Abs(midpoint - 11.5)
dist1230 := math.Abs(midpoint - 12.5)
effectiveDist := math.Min(distNoon, math.Min(dist1130, dist1230))
// Score this candidate
minThreshold := 0.01 + effectiveDist*0.02
recoveryToPreLunch := float64(afterCount) / float64(beforeCount)
isQuickLunch := recoveryToPreLunch > 0.4 && drop > 0.5 && effectiveDist < 1.0
if isQuickLunch && effectiveDist < 0.5 {
minThreshold *= 0.5
}
if drop <= minThreshold {
continue
}
score := drop
// Boost for pre-lunch activity
if preLunchActivity > 40 {
score *= 1.5
} else if preLunchActivity > 30 {
score *= 1.2
}
// Massive boost for 100% drops
if drop >= 1.0 && effectiveDist <= 1.0 {
score *= 10.0
}
// Check if lunch continues beyond duration
actualDuration := duration
if duration < 1.5 {
nextBucket := normHour(startUTC + duration)
nextCount := halfHourly[nextBucket]
lunchLow := nextCount == 0 || (beforeCount > 0 && float64(nextCount)/float64(beforeCount) < 0.3)
lowerThanLunch := avgLunch > 0 && float64(nextCount) < avgLunch*0.95
if lunchLow || lowerThanLunch {
switch duration {
case 0.5:
actualDuration = 1.0
case 1.0:
actualDuration = 1.5
}
}
}
// Duration-based adjustments
hasStrongRecovery := recoveryToPreLunch > 0.6 && drop > 0.6
switch {
case duration == 0.5 && hasStrongRecovery && actualDuration == duration:
score *= 2.0
case duration == 0.5 && isQuickLunch && actualDuration == duration:
score *= 1.3
case duration == 0.5 && actualDuration > duration:
score *= 0.5
case duration == 1.0 && !hasStrongRecovery:
score *= 1.2
case duration == 1.0 && hasStrongRecovery:
score *= 0.8
case duration == 0.5:
score *= 0.95
default:
score *= 0.9
}
// Big boost for 100% drops
if drop >= 1.0 {
score *= 5.0
}
// Time-based preferences
switch {
case distNoon <= 0.25:
switch {
case drop > 0.8:
score *= 3.0
case drop > 0.6:
score *= 2.5
default:
score *= 2.0
}
if isQuickLunch {
score *= 1.3
}
case dist1230 <= 0.25:
score *= 2.2
case dist1130 <= 0.25:
score *= 1.5
case effectiveDist < 0.5:
score *= 1.5
if isQuickLunch {
score *= 1.2
}
case effectiveDist < 1.0:
score *= 1.2
case effectiveDist > 2.0:
score *= 0.5
case effectiveDist > 1.5:
score *= 0.7
}
// European timezone constraint
if offsetHours >= -1 && offsetHours <= 3 && midpoint < 11.5 {
score *= 0.3
}
if score > bestScore {
bestScore = score
bestStart = startLocal
bestDuration = actualDuration
bestDrop = drop
}
}
}
if bestStart < 0 {
return -1, -1, 0
}
// Find actual minimum point in the lunch window
startUTC := normHour(bestStart - offsetHours)
minActivity := math.MaxInt32
minBucket := startUTC
for t := 0.0; t < bestDuration; t += 0.5 {
bucket := normHour(startUTC + t)
count := halfHourly[bucket]
if count < minActivity {
minActivity = count
minBucket = bucket
}
}
// If minimum is not at start, adjust to center on minimum
if minBucket != startUTC && bestDuration <= 1.0 {
startUTC = minBucket
bestDuration = 0.5
}
endUTC := normHour(startUTC + bestDuration)
// Calculate confidence
conf := 0.3
if bestDrop > 0.2 {
conf += 0.3
}
if bestStart >= 11.5 && bestStart <= 13.0 {
conf += 0.2
}
if conf > 1.0 {
conf = 1.0
}
return startUTC, endUTC, conf
}
// avgActivity calculates average activity during a period.
func avgActivity(counts map[float64]int, start, duration float64) float64 {
sum, n := 0, 0
for t := 0.0; t < duration; t += 0.5 {
bucket := normHour(start + t)
sum += counts[bucket]
n++
}
if n == 0 {
return 0
}
return float64(sum) / float64(n)
}
// findBestGlobalLunchPattern finds the best lunch pattern globally in UTC time.
// This is timezone-independent and looks for the strongest activity drop + recovery pattern.
func findBestGlobalLunchPattern(halfHourCounts map[float64]int) globalLunchPattern {
// Calculate average activity as baseline
totalActivity := 0
totalBuckets := 0
for _, count := range halfHourCounts {
totalActivity += count
totalBuckets++
}
if totalBuckets == 0 {
return globalLunchPattern{startUTC: -1, confidence: 0}
}
avgActivity := float64(totalActivity) / float64(totalBuckets)
if avgActivity < 1 {
return globalLunchPattern{startUTC: -1, confidence: 0}
}
var bestPattern globalLunchPattern
bestPattern.startUTC = -1
bestScore := 0.0
// Look for lunch breaks of 30, 60, or 90 minutes (1, 2, or 3 buckets)
durations := []int{1, 2, 3}
for _, duration := range durations {
// Restrict search to reasonable global lunch window (15:00-21:00 UTC)
// This covers 11am-2pm across US timezones (-4 to -8), Europe (+1 to +3), and Asia (+8 to +9)
for startBucket := 15.0; startBucket < 21.0; startBucket += 0.5 {
endBucket := startBucket + float64(duration)*0.5
// Get surrounding buckets for comparison
prevBucket := normHour(startBucket - 0.5)
nextBucket := normHour(endBucket)
prevCount := halfHourCounts[prevBucket]
startCount := halfHourCounts[startBucket]
afterCount := halfHourCounts[nextBucket]
// Skip if no data for comparison
if prevCount == 0 {
continue
}
dropPercent := (float64(prevCount) - float64(startCount)) / float64(prevCount)
// Calculate recovery factor
recoveryFactor := 1.0
if startCount > 0 && afterCount > startCount {
recoveryFactor = float64(afterCount) / float64(startCount)
}
// Calculate average lunch activity
lunchTotal := 0
lunchBuckets := 0
for b := startBucket; b < endBucket; b += 0.5 {
bucket := normHour(b)
lunchTotal += halfHourCounts[bucket]
lunchBuckets++
}
if lunchBuckets == 0 {
continue
}
avgLunchActivity := float64(lunchTotal) / float64(lunchBuckets)
// Check if this qualifies as a lunch pattern
minDropThreshold := 0.25 // 25% minimum drop
if recoveryFactor >= 2.0 {
minDropThreshold = 0.15 // Allow smaller drops with strong recovery
}
if dropPercent > minDropThreshold && avgLunchActivity <= avgActivity*0.8 {
// Score this pattern
score := 0.0
// Prefer stronger drops
score += dropPercent * 100
// Prefer lower lunch activity
quietness := 1.0 - (avgLunchActivity / avgActivity)
score += quietness * 50
// Boost for strong recovery
if recoveryFactor >= 1.5 {
score += (recoveryFactor - 1.0) * 30
}
// Prefer 60-minute lunches
if duration == 2 {
score += 20
}
// Track the best pattern
if score > bestScore {
bestScore = score
bestPattern = globalLunchPattern{
startUTC: startBucket,
endUTC: endBucket,
confidence: math.Min(1.0, score/100.0),
dropPercent: dropPercent,
}
}
}
}
}
return bestPattern
}