Reportage/Services/Charts/ContextSummary.swift (11458B)
1import CoreData
2import Foundation
3
4
5struct ContextRecord: Sendable {
6 var date: Date
7 var timeZone: TimeZone
8
9 var steps: Int?
10
11 var temperature: Double?
12}
13
14
15struct StepsSummary: Equatable, Sendable {
16
17 var mean: Double
18
19 var days: Int
20
21 var trend: [TrendPoint]
22}
23
24
25struct TemperatureSummary: Equatable, Sendable {
26 var mean: Double
27 var lowest: Double
28 var highest: Double
29
30 var reports: Int
31
32 var trend: [TrendPoint]
33}
34
35
36struct MapPlace: Identifiable, Equatable, Sendable {
37
38 var id: String
39 var name: String
40 var coordinate: Coordinate
41 var count: Int
42}
43
44
45struct PlacesSummary: Equatable, Sendable {
46
47 var places: [MapPlace]
48
49 var unplaced: Int
50
51
52
53
54
55 static func summarise(
56 _ rows: [AnswerRecord], lookup: SummaryLookup, tokenCoordinates: [String: Coordinate]
57 ) -> PlacesSummary? {
58 var counts: [String: Int] = [:]
59 var sums: [String: (latitude: Double, longitude: Double, count: Int)] = [:]
60 for row in rows {
61 guard case .place(let answer) = row.value else { continue }
62 let id = lookup.mergedIDs[answer.tokenID] ?? answer.tokenID
63 counts[id, default: 0] += 1
64 if let coordinate = answer.coordinate {
65 let sum = sums[id] ?? (0, 0, 0)
66 sums[id] = (sum.latitude + coordinate.latitude, sum.longitude + coordinate.longitude, sum.count + 1)
67 }
68 }
69 guard !counts.isEmpty else { return nil }
70 var places: [MapPlace] = []
71 var unplaced = 0
72 for (id, count) in counts {
73 let centre = sums[id].map {
74 Coordinate(latitude: $0.latitude / Double($0.count), longitude: $0.longitude / Double($0.count))
75 }
76 guard let name = lookup.tokenTexts[id], let coordinate = tokenCoordinates[id] ?? centre else {
77 unplaced += 1
78 continue
79 }
80 places.append(MapPlace(id: id, name: name, coordinate: coordinate, count: count))
81 }
82 places.sort { lhs, rhs in
83 lhs.count != rhs.count
84 ? lhs.count > rhs.count
85 : lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending
86 }
87 return PlacesSummary(places: places, unplaced: unplaced)
88 }
89}
90
91
92struct CalendarSummary: Equatable, Sendable {
93
94
95 var counts: [Date: Int]
96
97 var first: Date
98 var last: Date
99 var reports: Int
100
101 var days: Int
102
103
104
105
106
107 static func summarise(
108 _ dates: [Date], from first: Date, through now: Date, calendar: Calendar = .current
109 ) -> CalendarSummary? {
110 let first = calendar.startOfDay(for: first)
111 let last = calendar.startOfDay(for: now)
112 guard first <= last else { return nil }
113 var counts: [Date: Int] = [:]
114 for date in dates {
115 let day = calendar.startOfDay(for: date)
116 guard day >= first, day <= last else { continue }
117 counts[day, default: 0] += 1
118 }
119 guard !counts.isEmpty else { return nil }
120 let days = (calendar.dateComponents([.day], from: first, to: last).day ?? 0) + 1
121 return CalendarSummary(
122 counts: counts, first: first, last: last, reports: counts.values.reduce(0, +), days: days)
123 }
124
125
126 var daysWithReports: Int { counts.count }
127
128
129
130
131 static func level(of count: Int) -> Int {
132 switch count {
133 case ...0: 0
134 case 1: 1
135 case 2...3: 2
136 case 4...5: 3
137 default: 4
138 }
139 }
140}
141
142struct ContextSummary: Equatable, Sendable {
143 var calendar: CalendarSummary?
144 var steps: StepsSummary?
145 var temperature: TemperatureSummary?
146 var places: PlacesSummary?
147
148 var isEmpty: Bool { calendar == nil && steps == nil && temperature == nil && places == nil }
149
150
151
152
153 static func summarise(
154 _ records: [ContextRecord], bucket: Calendar.Component = .day, calendar: Calendar = .current
155 ) -> ContextSummary {
156 var summary = ContextSummary()
157
158 var daily: [Date: Int] = [:]
159 for record in records {
160 guard let steps = record.steps, steps > 0 else { continue }
161 var zoned = calendar
162 zoned.timeZone = record.timeZone
163
164 let components = zoned.dateComponents([.year, .month, .day], from: record.date)
165 guard let day = calendar.date(from: components) else { continue }
166 daily[day] = max(daily[day] ?? 0, steps)
167 }
168 if !daily.isEmpty {
169 let bySpan = Dictionary(grouping: daily, by: { calendar.start(of: bucket, for: $0.key) })
170 summary.steps = StepsSummary(
171 mean: Double(daily.values.reduce(0, +)) / Double(daily.count),
172 days: daily.count,
173 trend: bySpan.map { span, days in
174 TrendPoint(date: span, value: Double(days.map(\.value).reduce(0, +)) / Double(days.count))
175 }
176 .sorted { $0.date < $1.date })
177 }
178
179 let temperatures = records.compactMap { record in record.temperature.map { (record.date, $0) } }
180 if let lowest = temperatures.map(\.1).min(), let highest = temperatures.map(\.1).max() {
181 let bySpan = Dictionary(grouping: temperatures, by: { calendar.start(of: bucket, for: $0.0) })
182 summary.temperature = TemperatureSummary(
183 mean: temperatures.map(\.1).reduce(0, +) / Double(temperatures.count),
184 lowest: lowest, highest: highest, reports: temperatures.count,
185 trend: bySpan.map { span, values in
186 let values = values.map(\.1)
187 return TrendPoint(
188 date: span, value: values.reduce(0, +) / Double(values.count),
189 low: values.min(), high: values.max())
190 }
191 .sorted { $0.date < $1.date })
192 }
193 return summary
194 }
195}
196
197
198struct ChartData: Equatable, Sendable {
199 var period: ChartPeriod
200 var summaries: [QuestionSummary] = []
201 var context = ContextSummary()
202
203
204 var domain: ClosedRange<Date>?
205}
206
207extension ReportStore {
208
209
210 func contexts(since start: Date?) async throws -> [ContextRecord] {
211 let context = persistence.newBackgroundContext()
212 return try await context.perform {
213 let request = ReportEntity.fetchRequest()
214 if let start {
215 request.predicate = NSPredicate(format: "date >= %@", start as NSDate)
216 }
217 request.relationshipKeyPathsForPrefetching = ["health"]
218 return try context.fetch(request).compactMap { entity in
219 guard let date = entity.date else { return nil }
220 let captured = try entity.context.map { try ModelCoding.decode(Context.self, from: $0) }
221 let health = try entity.health?.record().health
222 return ContextRecord(
223 date: date,
224 timeZone: entity.timeZone.flatMap(TimeZone.init(identifier:)) ?? .current,
225 steps: health?.activity?.steps ?? captured?.motion?.steps,
226 temperature: captured?.weather?.temperature)
227 }
228 }
229 }
230
231
232
233 func chartData(for period: ChartPeriod, now: Date = Date(), calendar: Calendar = .current) async throws
234 -> ChartData
235 {
236 let start = period.start(endingAt: now, calendar: calendar)
237 async let lookupResult = summaryLookup()
238 async let questionsResult = allQuestions()
239 async let rowsResult = answers(since: start)
240 async let recordsResult = contexts(since: start)
241 let (lookup, questions, answerRows, contextRecords) = try await (
242 lookupResult, questionsResult, rowsResult, recordsResult
243 )
244
245 var data = ChartData(period: period)
246 data.summaries = AnswerSummary.summarise(
247 answerRows, questions: questions, lookup: lookup, bucket: period.bucket, calendar: calendar)
248 data.context = ContextSummary.summarise(contextRecords, bucket: period.bucket, calendar: calendar)
249 let placeIDs = Set(
250 answerRows.compactMap { row -> String? in
251 guard case .place(let answer) = row.value else { return nil }
252 return lookup.mergedIDs[answer.tokenID] ?? answer.tokenID
253 })
254 let coordinates = try await tokenEntries(ids: Array(placeIDs)).compactMapValues(\.coordinate)
255 data.context.places = PlacesSummary.summarise(answerRows, lookup: lookup, tokenCoordinates: coordinates)
256
257
258 let firstDay = start.flatMap { calendar.date(byAdding: .day, value: 1, to: $0) }
259 if let first = firstDay ?? contextRecords.map(\.date).min() {
260 data.context.calendar = CalendarSummary.summarise(
261 contextRecords.map(\.date), from: first, through: now, calendar: calendar)
262 }
263 if let first = start ?? contextRecords.map(\.date).min(), first <= now {
264 data.domain = calendar.start(of: period.bucket, for: first)...now
265 }
266 return data
267 }
268}