SPB Git

Repository Public MIT

GlassChartModel.swift 10.8 KB 243 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassData/Data/GlassChartModel.swift8// Module           : SPGlassData9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassCore4344/// The mark used to draw a ``GlassChart``.45public enum GlassChartKind: String, CaseIterable, Sendable {46    case line, bar, area47}4849/// Horizontal position of a chart point: a category or a date.50public enum GlassChartX: Hashable, Sendable {51    /// A named category ("Q1", "Montréal").52    case category(String)53    /// A point in time, placed on a continuous time axis.54    case date(Date)5556    /// The position as text, for accessibility and summaries. Dates use an abbreviated date without time.57    public func label(locale: Locale = .current, timeZone: TimeZone = .current) -> String {58        switch self {59        case .category(let name):60            return name61        case .date(let date):62            var style = Date.FormatStyle(date: .abbreviated, time: .omitted, locale: locale)63            style.timeZone = timeZone64            return date.formatted(style)65        }66    }67}6869/// One typed value of a ``GlassChart``.70public struct GlassChartPoint: Identifiable, Hashable, Sendable {71    /// Stable identifier, unique in the chart.72    public let id: String73    public let x: GlassChartX74    public let value: Double75    /// Name of the series the point belongs to, or `nil` for a single-series chart.76    public let series: String?7778    /// Creates a point on a category axis.79    public init(id: String? = nil, label: String, value: Double, series: String? = nil) {80        self.init(id: id, x: .category(label), value: value, series: series)81    }8283    /// Creates a point on a time axis.84    public init(id: String? = nil, date: Date, value: Double, series: String? = nil) {85        self.init(id: id, x: .date(date), value: value, series: series)86    }8788    /// Creates a point. Without an explicit `id` the identifier is derived from the series and the position,89    /// which is unique as long as a series has one value per position.90    public init(id: String? = nil, x: GlassChartX, value: Double, series: String? = nil) {91        self.x = x92        self.value = value93        self.series = series94        if let id {95            self.id = id96        } else {97            let position: String98            switch x {99            case .category(let name): position = "c:\(name)"100            case .date(let date): position = "d:\(date.timeIntervalSinceReferenceDate)"101            }102            self.id = "\(series ?? "")|\(position)"103        }104    }105}106107/// What a chart series says, in numbers: the basis of the textual description read by assistive technologies.108public struct GlassChartSummary: Equatable, Sendable {109    /// The series described, or `nil` for points without a series.110    public let series: String?111    /// Number of finite values.112    public let count: Int113    /// First and last positions, in the order of the points.114    public let first: GlassChartPoint115    public let last: GlassChartPoint116    /// Points holding the smallest and the largest value (the earliest one when several are equal).117    public let minimum: GlassChartPoint118    public let maximum: GlassChartPoint119    /// Direction from the first value to the last one.120    public let trend: GlassTrend121}122123/// What the header of a chart reads out: one position and the value of each series there.124public struct GlassChartReadout: Equatable, Sendable {125    public let x: GlassChartX126    /// The points at `x`, one per series, in order of first appearance.127    public let values: [GlassChartPoint]128}129130/// Pure functions that prepare and describe chart data.131public enum GlassChartLogic {132    /// The values to read out at `x`. Without a position, or with one no point holds, the read-out is the133    /// last position of the data. `nil` when there are no finite values.134    public static func readout(of points: [GlassChartPoint], at x: GlassChartX?) -> GlassChartReadout? {135        let finite = plottable(points)136        guard let last = finite.last else { return nil }137        let position = x.flatMap { wanted in finite.contains { $0.x == wanted } ? wanted : nil } ?? last.x138        var seen = Set<String?>()139        let values = finite.filter { $0.x == position && seen.insert($0.series).inserted }140        return GlassChartReadout(x: position, values: values)141    }142143    /// The dated position nearest to `date`, or `nil` when no point is dated.144    public static func nearestPosition(to date: Date, in points: [GlassChartPoint]) -> GlassChartX? {145        var best: (distance: TimeInterval, x: GlassChartX)?146        for point in plottable(points) {147            guard case .date(let candidate) = point.x else { continue }148            let distance = abs(candidate.timeIntervalSince(date))149            if best == nil || distance < (best?.distance ?? .infinity) { best = (distance, point.x) }150        }151        return best?.x152    }153154    /// Share of the value range under which the difference between the first and the last value counts as flat.155    public static let flatTolerance = 0.01156157    /// The points a chart can draw: those with a finite value, in their original order.158    public static func plottable(_ points: [GlassChartPoint]) -> [GlassChartPoint] {159        points.filter { $0.value.isFinite }160    }161162    /// Whether every point is dated, in which case the chart uses a time axis.163    public static func usesTimeAxis(_ points: [GlassChartPoint]) -> Bool {164        !points.isEmpty && points.allSatisfy { if case .date = $0.x { true } else { false } }165    }166167    /// Series names in order of first appearance. Points without a series are not listed.168    public static func seriesNames(_ points: [GlassChartPoint]) -> [String] {169        var seen = Set<String>()170        return points.compactMap(\.series).filter { seen.insert($0).inserted }171    }172173    /// One summary per series (in order of first appearance; points without a series form their own group).174    /// Values that are not finite are ignored; a series without any finite value has no summary.175    ///176    /// The trend compares the last value with the first one and is flat when they differ by no more than177    /// ``flatTolerance`` of the larger of the series' range and its largest magnitude.178    public static func summaries(_ points: [GlassChartPoint]) -> [GlassChartSummary] {179        var order: [String?] = []180        var groups: [String?: [GlassChartPoint]] = [:]181        for point in plottable(points) {182            if groups[point.series] == nil { order.append(point.series) }183            groups[point.series, default: []].append(point)184        }185        return order.compactMap { series in186            guard let group = groups[series], let first = group.first, let last = group.last else { return nil }187            var minimum = first, maximum = first188            for point in group.dropFirst() {189                if point.value < minimum.value { minimum = point }190                if point.value > maximum.value { maximum = point }191            }192            let scale = max(maximum.value - minimum.value, abs(maximum.value), abs(minimum.value))193            let trend = GlassTrend.of(change: last.value - first.value, tolerance: scale * flatTolerance)194            return GlassChartSummary(series: series, count: group.count, first: first, last: last, minimum: minimum, maximum: maximum, trend: trend)195        }196    }197198    /// A value as text with at most two fraction digits, followed by its unit when there is one.199    public static func valueText(_ value: Double, unit: String? = nil, locale: Locale = .current) -> String {200        let number = value.formatted(.number.precision(.fractionLength(0...2)).locale(locale))201        guard let unit, !unit.isEmpty else { return number }202        return "\(number)\u{00A0}\(unit)"203    }204205    /// The sentence describing one series: count, extent, minimum, maximum and trend.206    ///207    /// - Parameter localization: language of GlassKit's own words (`"en"`, `"fr"`); `nil` follows the application.208    public static func description(209        of summary: GlassChartSummary,210        unit: String? = nil,211        locale: Locale = .current,212        timeZone: TimeZone = .current,213        localization: String? = nil214    ) -> String {215        let format = localization.map { GlassL10n.string(.chartSummary, localization: $0) } ?? GlassL10n.string(.chartSummary)216        let trend = localization.map { summary.trend.label(localization: $0) } ?? summary.trend.label217        let arguments: [any CVarArg] = [218            summary.count,219            summary.first.x.label(locale: locale, timeZone: timeZone),220            summary.last.x.label(locale: locale, timeZone: timeZone),221            valueText(summary.minimum.value, unit: unit, locale: locale),222            valueText(summary.maximum.value, unit: unit, locale: locale),223            trend,224        ]225        let sentence = String(format: format, locale: locale, arguments: arguments)226        guard let series = summary.series else { return sentence }227        return "\(series): \(sentence)"228    }229230    /// The description of a whole chart: one sentence per series, or an empty string without finite values.231    public static func description(232        of points: [GlassChartPoint],233        unit: String? = nil,234        locale: Locale = .current,235        timeZone: TimeZone = .current,236        localization: String? = nil237    ) -> String {238        summaries(points)239            .map { description(of: $0, unit: unit, locale: locale, timeZone: timeZone, localization: localization) }240            .joined(separator: " ")241    }242}243
Files main
Menu

Theme