-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsleep.go
More file actions
264 lines (226 loc) · 6.18 KB
/
sleep.go
File metadata and controls
264 lines (226 loc) · 6.18 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
package ditzy
import "sort"
// detectSleepBuckets finds sleep periods for a given timezone offset (hours).
// Returns the half-hour buckets (UTC) that represent sleep time.
// A rest period is defined as 4+ hours of continuous low activity (0-2 events)
// that preferably occurs at nighttime (21:00-09:00 local time).
func detectSleepBuckets(halfHourly map[float64]int, offsetHours float64) []float64 {
// Calculate total activity for sparse data detection
total := 0
for _, count := range halfHourly {
total += count
}
sparseData := total < 50
// Find UTC hour for 21:00 (9pm) local time
utcNightStart := 21.0 - offsetHours
utcNightStart = normHour(utcNightStart)
// Build search order: night hours first (21:00-09:00 local), then day
searchOrder := make([]float64, 0, 48)
for i := range 48 {
h := normHour(utcNightStart + float64(i)*0.5)
searchOrder = append(searchOrder, h)
}
// Find all candidate rest periods
type period struct {
buckets []float64
score float64
}
var candidates []period
startThreshold := 1
if sparseData {
startThreshold = 0
}
for _, start := range searchOrder {
// Skip buckets that don't exist in the data (missing != quiet)
count, exists := halfHourly[start]
if !exists || count > startThreshold {
continue
}
buckets := findRestPeriod(halfHourly, start, offsetHours, total)
if len(buckets) < 8 { // Need at least 4 hours
continue
}
score := nighttimeScore(buckets, offsetHours)
if sparseData && score == 0 {
continue // Skip daytime periods for sparse data
}
candidates = append(candidates, period{buckets: buckets, score: score})
}
if len(candidates) == 0 {
return nil
}
// Sort by nighttime score, then length
sort.Slice(candidates, func(i, j int) bool {
if candidates[i].score != candidates[j].score {
return candidates[i].score > candidates[j].score
}
return len(candidates[i].buckets) > len(candidates[j].buckets)
})
best := candidates[0].buckets
best = trimActiveEnd(best, halfHourly)
best = trimActiveStart(best, halfHourly)
sort.Float64s(best)
return findLongestContinuous(best)
}
// findRestPeriod builds a continuous quiet period starting from startBucket.
func findRestPeriod(counts map[float64]int, start, offsetHours float64, total int) []float64 {
var buckets []float64
bucket := start
prevCount := -1
consecutiveLow := 0
for len(buckets) < 24 { // Max 12 hours
count, exists := counts[bucket]
if !exists {
break // Stop at missing data
}
localHour := normHour(bucket + offsetHours)
// Work hours (9-17 local) with activity means wake up
isWorkHours := localHour >= 9 && localHour < 17
if isWorkHours && count >= 3 && len(buckets) >= 8 {
break
}
// High activity breaks the period
//nolint:nestif // sleep detection requires handling multiple edge cases
if count > 5 {
if len(buckets) >= 8 {
break
}
buckets = nil
prevCount = -1
consecutiveLow = 0
} else {
// Track sustained low activity (2+ events)
if count >= 2 {
consecutiveLow++
} else {
if consecutiveLow >= 4 {
trim := min(consecutiveLow, len(buckets))
buckets = buckets[:len(buckets)-trim]
}
consecutiveLow = 0
}
// 4+ consecutive buckets with 2+ events = real work
if consecutiveLow >= 4 && count >= 2 {
trim := min(consecutiveLow-1, len(buckets))
buckets = buckets[:len(buckets)-trim]
break
}
// Check halting conditions
if total < 50 {
if count > 0 && prevCount >= 0 {
break
}
} else {
if (prevCount >= 2 && count >= 3) || (prevCount >= 3 && count >= 2) {
if len(buckets) > 0 && prevCount >= 2 {
buckets = buckets[:len(buckets)-1]
}
break
}
}
buckets = append(buckets, bucket)
prevCount = count
}
bucket = normHour(bucket + 0.5)
if bucket == start {
break
}
}
return buckets
}
// nighttimeScore returns 0-1 indicating overlap with night hours (21:00-09:00 local).
func nighttimeScore(buckets []float64, offsetHours float64) float64 {
nightCount, workCount := 0, 0
for _, b := range buckets {
localHour := normHour(b + offsetHours)
if localHour >= 21 || localHour < 9 {
nightCount++
}
if localHour >= 9 && localHour < 17 {
workCount++
}
}
// More than 30% during work hours = not sleep
if float64(workCount)/float64(len(buckets)) > 0.3 {
return 0
}
return float64(nightCount) / float64(len(buckets))
}
// trimActiveEnd removes buckets from the end that have 3+ events.
func trimActiveEnd(buckets []float64, counts map[float64]int) []float64 {
for len(buckets) > 0 {
last := buckets[len(buckets)-1]
if counts[last] < 3 {
break
}
buckets = buckets[:len(buckets)-1]
}
return buckets
}
// trimActiveStart removes buckets from the start until we find 2 consecutive quiet ones.
func trimActiveStart(buckets []float64, counts map[float64]int) []float64 {
for len(buckets) > 1 {
if counts[buckets[0]] <= 2 && counts[buckets[1]] <= 2 {
break
}
buckets = buckets[1:]
}
return buckets
}
// findLongestContinuous extracts the longest continuous period from sorted buckets.
func findLongestContinuous(buckets []float64) []float64 {
if len(buckets) == 0 {
return nil
}
// Check for wraparound sleep (spans midnight)
hasEvening := false
hasMorning := false
for _, b := range buckets {
if b >= 22 {
hasEvening = true
}
if b < 8 {
hasMorning = true
}
}
isWraparound := hasEvening && hasMorning
var periods [][]float64
current := []float64{buckets[0]}
for i := 1; i < len(buckets); i++ {
diff := buckets[i] - buckets[i-1]
consecutive := diff <= 0.5
// For wraparound, large gap (>12h) means we're at the midnight boundary
if !consecutive && isWraparound && diff > 12 {
consecutive = true
}
if consecutive {
current = append(current, buckets[i])
} else {
if len(current) >= 7 {
periods = append(periods, current)
}
current = []float64{buckets[i]}
}
}
if len(current) >= 7 {
periods = append(periods, current)
}
// Return the longest period
var longest []float64
for _, p := range periods {
if len(p) > len(longest) {
longest = p
}
}
return longest
}
// normHour normalizes an hour value to the 0-24 range.
func normHour(h float64) float64 {
for h < 0 {
h += 24
}
for h >= 24 {
h -= 24
}
return h
}