-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathditzy.go
More file actions
335 lines (297 loc) · 9.98 KB
/
ditzy.go
File metadata and controls
335 lines (297 loc) · 9.98 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
// Package ditzy detects timezone offsets from activity patterns.
//
// It analyzes timestamped events or pre-aggregated activity buckets to identify
// likely UTC offsets based on sleep patterns, lunch breaks, and activity distribution.
//
// Basic usage:
//
// result := ditzy.FromEvents(events)
// fmt.Printf("Most likely timezone: %s\n", result.Candidates[0].Timezone)
//
// For legacy code with pre-aggregated bucket data:
//
// result := ditzy.FromBuckets(halfHourCounts,
// ditzy.WithClaimedTimezone("America/New_York"))
package ditzy
import (
"log/slog"
"time"
)
// Event represents a timestamped activity.
type Event struct {
Time time.Time
Type string // "commit", "push", "pr", "issue", "review", "comment", etc.
}
// hasPreservedTZ returns true if the event has non-Zulu timezone info.
func (e Event) hasPreservedTZ() bool {
name, _ := e.Time.Zone()
return name != "UTC"
}
// Candidate represents a detected timezone with full analysis data.
type Candidate struct {
Timezone string `json:"timezone"`
ScoringDetails []string `json:"-"` // Debug only, not exported to JSON
SleepBucketsUTC []float64 `json:"sleep_buckets_utc,omitempty"`
SleepMidUTC float64 `json:"sleep_mid_utc"`
PeakStartUTC float64 `json:"peak_start_utc,omitempty"`
Offset float64 `json:"offset"`
LunchConfidence float64 `json:"lunch_confidence"`
LunchEndUTC float64 `json:"lunch_end_utc"`
WorkStartUTC float64 `json:"work_start_utc"`
WorkEndUTC float64 `json:"work_end_utc"`
LunchStartUTC float64 `json:"lunch_start_utc"`
LunchDipStrength float64 `json:"lunch_dip_strength"`
Confidence float64 `json:"confidence"`
PeakEndUTC float64 `json:"peak_end_utc,omitempty"`
EveningActivity int `json:"evening_activity"`
PeakCount int `json:"peak_count,omitempty"`
PeakTimeReasonable bool `json:"peak_time_reasonable"`
SleepReasonable bool `json:"sleep_reasonable"`
WorkHoursReasonable bool `json:"work_hours_reasonable"`
LunchReasonable bool `json:"lunch_reasonable"`
IsProfile bool `json:"is_profile"`
}
// Hours returns the offset in hours (e.g., -8 for PST).
func (c Candidate) Hours() float64 {
return c.Offset
}
// OffsetDuration returns the offset as a time.Duration.
func (c Candidate) OffsetDuration() time.Duration {
return time.Duration(c.Offset) * time.Hour
}
// Analysis contains global detection results (not per-candidate).
type Analysis struct {
HalfHourCounts map[float64]int // raw bucket data for callers who need it
SleepBuckets []float64 // half-hour buckets (UTC) identified as sleep
PeakStartUTC float64 // global peak productivity start
PeakEndUTC float64 // global peak productivity end
PeakCount int // activity count during peak
LunchStartUTC float64 // best global lunch pattern start
LunchEndUTC float64 // best global lunch pattern end
LunchConfidence float64 // confidence in lunch detection
TotalEvents int
PreservedTZCount int // events with preserved timezone info
SleepConfidence float64 // confidence in sleep detection
}
// Result contains timezone detection output.
type Result struct {
Candidates []Candidate // ranked by confidence, highest first
Analysis Analysis // global patterns for the activity data
}
// GlobalLunchPattern represents the best lunch pattern found globally in UTC.
type GlobalLunchPattern struct {
StartUTC float64
EndUTC float64
Confidence float64
DropPercent float64
}
// config holds options for detection.
type config struct {
newestActivity time.Time
logger *slog.Logger
claimedTimezone string
username string
bestGlobalLunch GlobalLunchPattern
}
// Option configures detection behavior.
type Option func(*config)
// WithLogger sets a custom logger.
func WithLogger(l *slog.Logger) Option {
return func(c *config) { c.logger = l }
}
// WithClaimedTimezone provides a timezone claimed by the user's profile.
func WithClaimedTimezone(tz string) Option {
return func(c *config) { c.claimedTimezone = tz }
}
// WithUsername provides the username for logging/debugging.
func WithUsername(u string) Option {
return func(c *config) { c.username = u }
}
// WithNewestActivity provides the most recent activity timestamp.
func WithNewestActivity(t time.Time) Option {
return func(c *config) { c.newestActivity = t }
}
// WithGlobalLunch provides a pre-computed global lunch pattern.
func WithGlobalLunch(g GlobalLunchPattern) Option {
return func(c *config) { c.bestGlobalLunch = g }
}
// FromEvents analyzes timestamped events and returns timezone candidates.
// This is the preferred API for new code.
func FromEvents(events []Event, opts ...Option) *Result {
if len(events) == 0 {
return &Result{}
}
cfg := &config{}
for _, opt := range opts {
opt(cfg)
}
if cfg.logger == nil {
cfg.logger = slog.Default()
}
// Aggregate events into half-hourly and hourly buckets
halfHourly := make(map[float64]int)
hourly := make(map[int]int)
preservedCount := 0
for _, e := range events {
hour := float64(e.Time.Hour())
if e.Time.Minute() >= 30 {
hour += 0.5
}
halfHourly[hour]++
hourly[e.Time.Hour()]++
if e.hasPreservedTZ() {
preservedCount++
}
}
cfg.logger.Debug("aggregated activity",
"total_events", len(events),
"preserved_tz_count", preservedCount,
"buckets", len(halfHourly))
result := fromBucketsInternal(halfHourly, hourly, cfg)
result.Analysis.TotalEvents = len(events)
result.Analysis.PreservedTZCount = preservedCount
return result
}
// FromBuckets analyzes pre-aggregated half-hour activity buckets.
// This is provided for legacy code that already has bucket data.
// Keys are hours (0-23) with .5 for second half (e.g., 14.5 = 2:30-2:59 PM UTC).
func FromBuckets(halfHourCounts map[float64]int, opts ...Option) *Result {
if len(halfHourCounts) == 0 {
return &Result{}
}
cfg := &config{}
for _, opt := range opts {
opt(cfg)
}
if cfg.logger == nil {
cfg.logger = slog.Default()
}
// Convert half-hour buckets to hourly for compatibility
hourly := make(map[int]int)
total := 0
for bucket, count := range halfHourCounts {
hourly[int(bucket)] += count
total += count
}
result := fromBucketsInternal(halfHourCounts, hourly, cfg)
result.Analysis.TotalEvents = total
return result
}
// fromBucketsInternal is the shared implementation for both entry points.
func fromBucketsInternal(halfHourly map[float64]int, hourly map[int]int, cfg *config) *Result {
// Find quiet hours and active start
quietHours := findQuietHours(hourly)
activeStart := findActiveStart(halfHourly)
midQuiet := 0.0
if len(quietHours) > 0 {
sum := 0
for _, h := range quietHours {
sum += h
}
midQuiet = float64(sum) / float64(len(quietHours))
}
// Detect global patterns
sleepBuckets := detectSleepBuckets(halfHourly, 0)
peakStart, peakEnd, peakCount := detectPeakProductivity(halfHourly)
// Use provided global lunch or detect it
globalLunch := cfg.bestGlobalLunch
if globalLunch.Confidence == 0 {
detected := findBestGlobalLunchPattern(halfHourly)
globalLunch = GlobalLunchPattern{
StartUTC: detected.startUTC,
EndUTC: detected.endUTC,
Confidence: detected.confidence,
DropPercent: detected.dropPercent,
}
}
// Run evaluation
evalInput := evaluationInput{
username: cfg.username,
hourCounts: hourly,
halfHourCounts: halfHourly,
profileTimezone: cfg.claimedTimezone,
quietHours: quietHours,
midQuiet: midQuiet,
activeStart: activeStart,
newestActivity: cfg.newestActivity,
bestGlobalLunch: globalLunchPattern{
startUTC: globalLunch.StartUTC,
endUTC: globalLunch.EndUTC,
confidence: globalLunch.Confidence,
dropPercent: globalLunch.DropPercent,
},
}
// Count total activity
for _, count := range halfHourly {
evalInput.totalActivity += count
}
evalCandidates := evaluate(evalInput)
// Convert to public Candidate type
candidates := make([]Candidate, 0, len(evalCandidates))
for i := range evalCandidates {
ec := &evalCandidates[i]
candidates = append(candidates, Candidate{
Timezone: ec.timezone,
ScoringDetails: ec.scoringDetails,
SleepBucketsUTC: ec.sleepBucketsUTC,
SleepMidUTC: ec.sleepMidUTC,
PeakStartUTC: ec.peakStartUTC,
Offset: ec.offset,
LunchConfidence: ec.lunchConfidence,
LunchEndUTC: ec.lunchEndUTC,
WorkStartUTC: ec.workStartUTC,
WorkEndUTC: ec.workEndUTC,
LunchStartUTC: ec.lunchStartUTC,
LunchDipStrength: ec.lunchDipStrength,
Confidence: ec.confidence,
PeakEndUTC: ec.peakEndUTC,
EveningActivity: ec.eveningActivity,
PeakCount: ec.peakCount,
PeakTimeReasonable: ec.peakTimeReasonable,
SleepReasonable: ec.sleepReasonable,
WorkHoursReasonable: ec.workHoursReasonable,
LunchReasonable: ec.lunchReasonable,
IsProfile: ec.isProfile,
})
}
// Build analysis with global patterns
sleepConfidence := 0.0
if len(sleepBuckets) >= 8 {
sleepConfidence = 0.8
} else if len(sleepBuckets) >= 4 {
sleepConfidence = 0.5
}
return &Result{
Candidates: candidates,
Analysis: Analysis{
HalfHourCounts: halfHourly,
SleepBuckets: sleepBuckets,
SleepConfidence: sleepConfidence,
PeakStartUTC: peakStart,
PeakEndUTC: peakEnd,
PeakCount: peakCount,
LunchStartUTC: globalLunch.StartUTC,
LunchEndUTC: globalLunch.EndUTC,
LunchConfidence: globalLunch.Confidence,
},
}
}
// findQuietHours finds hours with zero activity.
func findQuietHours(hourly map[int]int) []int {
var quiet []int
for hour := range 24 {
if hourly[hour] == 0 {
quiet = append(quiet, hour)
}
}
return quiet
}
// findActiveStart finds the first half-hour bucket with activity.
func findActiveStart(halfHourly map[float64]int) float64 {
for hour := 0.0; hour < 24.0; hour += 0.5 {
if halfHourly[hour] > 0 {
return hour
}
}
return 0
}