← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Charts/ContextSummary.swift (11458B)

1import CoreData
2import Foundation
3
4/// The context of one report the charts use.
5struct ContextRecord: Sendable {
6    var date: Date
7    var timeZone: TimeZone
8    /// Steps so far that day, from Health or else the motion sensors.
9    var steps: Int?
10    /// °C.
11    var temperature: Double?
12}
13
14/// Steps a day over a period.
15struct StepsSummary: Equatable, Sendable {
16    /// The average of each day's steps.
17    var mean: Double
18    /// How many days had a count.
19    var days: Int
20    /// Each span's average daily steps.
21    var trend: [TrendPoint]
22}
23
24/// The temperatures reports captured over a period, in °C.
25struct TemperatureSummary: Equatable, Sendable {
26    var mean: Double
27    var lowest: Double
28    var highest: Double
29    /// How many reports captured one.
30    var reports: Int
31    /// Each span's average, with its lowest and highest.
32    var trend: [TrendPoint]
33}
34
35/// A place given as a location answer, with how many reports chose it.
36struct MapPlace: Identifiable, Equatable, Sendable {
37    /// The token's ID, after merges.
38    var id: String
39    var name: String
40    var coordinate: Coordinate
41    var count: Int
42}
43
44/// The places location answers chose over a period.
45struct PlacesSummary: Equatable, Sendable {
46    /// Most chosen first.
47    var places: [MapPlace]
48    /// How many places chosen have no coordinate to show them at.
49    var unplaced: Int
50
51    /// The places chosen in `rows`, from any location question. A place
52    /// merged into another counts as that place. Each is shown at its own
53    /// coordinate, from `tokenCoordinates`, or else at the centre of where
54    /// its answers were given.
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/// How many reports were filed on each day of a period.
92struct CalendarSummary: Equatable, Sendable {
93    /// Each day's count, by the start of the day. Days without a report
94    /// are left out.
95    var counts: [Date: Int]
96    /// The start of the first day the period covers in full, and of today.
97    var first: Date
98    var last: Date
99    var reports: Int
100    /// How many days the period covers, today included.
101    var days: Int
102
103    /// The reports in `dates` from `first`'s day through `now`'s, by their
104    /// day in `calendar`, which, as in the timeline, is the device's rather
105    /// than each report's own, so a day here shows the same reports as
106    /// that day there.
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    /// How many days had a report.
126    var daysWithReports: Int { counts.count }
127
128    /// How dark a day with `count` reports is shaded, from 0 for none to 4
129    /// for six or more: a day of prompts with a wake and bedtime report
130    /// reaches the darkest.
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    /// Trends are split into spans of `bucket` in `calendar`. A day's steps
151    /// are the highest count its reports captured, since each is the count
152    /// so far that day, and its day is the one in the report's time zone.
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            // The report's day, as that day in `calendar`.
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/// Everything the Charts tab shows for a period.
198struct ChartData: Equatable, Sendable {
199    var period: ChartPeriod
200    var summaries: [QuestionSummary] = []
201    var context = ContextSummary()
202    /// The span trends cover: from the start of the period, or of the
203    /// earliest report for all time, to now.
204    var domain: ClosedRange<Date>?
205}
206
207extension ReportStore {
208    /// The context of every report made since `start`, or ever when it's
209    /// `nil`.
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    /// The question summaries and context trends for `period`. See
232    /// `AnswerSummary` and `ContextSummary`.
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        // The calendar starts with the first whole day: the day the period
257        // starts on is only partly in it.
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}