SPB Git

Repository Public

VQLabChartData.swift 10.6 KB 206 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Lab/VQLabChartData.swift3// Description: The pure part of chart rendering — reading axis values, dropping holes, downsampling large series,4//              quantising matrices — kept out of the UI so it is unit-tested and shared by every renderer.5import Foundation67/// One x position of a chart, typed by the axis.8public enum VQChartX: Sendable, Hashable {9    case time(Date)10    case number(Double)11    case category(String)1213    /// Position on a continuous scale (seconds for time; nil for categories).14    public var scalar: Double? {15        switch self {16        case .time(let d): return d.timeIntervalSince197017        case .number(let n): return n18        case .category: return nil19        }20    }21    public var label: String {22        switch self {23        case .time(let d): return VQFormat.dateISO(d, timeZone: TimeZone(identifier: "UTC")!)24        case .number(let n): return VQJSON.number(n).text()25        case .category(let s): return s26        }27    }28}2930public struct VQChartPoint: Sendable, Hashable {31    public var x: VQChartX32    public var y: Double33    public var lower: Double?34    public var upper: Double?35    /// Index in the original series (before holes were dropped and before downsampling).36    public var index: Int37    public init(x: VQChartX, y: Double, lower: Double? = nil, upper: Double? = nil, index: Int) {38        self.x = x; self.y = y; self.lower = lower; self.upper = upper; self.index = index39    }40}4142public enum VQLabChartData {43    /// The axis type to use: the declared one, corrected when the values say otherwise (numbers declared as44    /// categories stay categories; strings that are not dates on a time axis become categories).45    public static func effectiveAxis(_ chart: VQLabResult.Chart) -> VQLabResult.Chart.AxisType {46        let declared = chart.x.type.known ?? .number47        let sample = chart.series.flatMap { $0.x.prefix(3) } + (chart.matrix?.x.prefix(3) ?? [])48        switch declared {49        case .time: return sample.allSatisfy { $0.stringValue.flatMap(VQISODate.parse) != nil } ? .time : .category50        case .number: return sample.allSatisfy { $0.doubleValue != nil } ? .number : .category51        case .category: return .category52        }53    }5455    public static func x(_ value: VQJSON, axis: VQLabResult.Chart.AxisType) -> VQChartX? {56        switch axis {57        case .time: return value.stringValue.flatMap(VQISODate.parse).map(VQChartX.time)58        case .number: return value.doubleValue.map(VQChartX.number)59        case .category: return value.displayString.map(VQChartX.category)60        }61    }6263    /// The drawable points of a series: positions the axis cannot read and null `y` values are dropped (a hole in a64    /// line is a break, never a zero).65    public static func points(_ series: VQLabResult.Chart.Series, axis: VQLabResult.Chart.AxisType) -> [VQChartPoint] {66        var out: [VQChartPoint] = []67        out.reserveCapacity(series.x.count)68        for i in 0..<min(series.x.count, series.y.count) {69            guard let x = x(series.x[i], axis: axis), let y = series.y[i], y.isFinite else { continue }70            let lo = series.lower.flatMap { $0.indices.contains(i) ? $0[i] : nil }71            let hi = series.upper.flatMap { $0.indices.contains(i) ? $0[i] : nil }72            out.append(VQChartPoint(x: x, y: y, lower: lo, upper: hi, index: i))73        }74        return out75    }7677    /// Runs of consecutive indices: a null in the data splits a line into segments.78    public static func segments(_ points: [VQChartPoint]) -> [[VQChartPoint]] {79        var out: [[VQChartPoint]] = []80        for p in points {81            if let last = out.last?.last, last.index + 1 == p.index { out[out.count - 1].append(p) } else { out.append([p]) }82        }83        return out84    }8586    /// Reduces a long series to at most `limit` points while keeping its shape: each bucket keeps its minimum and its87    /// maximum (so spikes survive), first and last points are always kept. Series at or under the limit are returned88    /// as they are. Categories are never downsampled.89    public static func downsample(_ points: [VQChartPoint], limit: Int) -> [VQChartPoint] {90        guard limit >= 4, points.count > limit, points.first?.x.scalar != nil else { return points }91        let buckets = max(1, (limit - 2) / 2)92        let inner = points.count - 293        var out: [VQChartPoint] = [points[0]]94        out.reserveCapacity(limit)95        for b in 0..<buckets {96            let start = 1 + b * inner / buckets97            let end = 1 + (b + 1) * inner / buckets98            guard start < end else { continue }99            var lo = start, hi = start100            for i in start..<end {101                if points[i].y < points[lo].y { lo = i }102                if points[i].y > points[hi].y { hi = i }103            }104            if lo == hi { out.append(points[lo]) }105            else { out.append(points[min(lo, hi)]); out.append(points[max(lo, hi)]) }106        }107        out.append(points[points.count - 1])108        return out109    }110111    /// The smallest positive gap between consecutive x positions (bar and bin width on a continuous axis).112    public static func minimumSpacing(_ scalars: [Double]) -> Double? {113        let sorted = Array(Set(scalars)).sorted()114        guard sorted.count > 1 else { return nil }115        var best = Double.greatestFiniteMagnitude116        for i in 1..<sorted.count { best = min(best, sorted[i] - sorted[i - 1]) }117        return best > 0 && best.isFinite ? best : nil118    }119120    /// The index of the point nearest to a position on a continuous axis (value inspection).121    public static func nearestIndex(_ points: [VQChartPoint], to scalar: Double) -> Int? {122        guard !points.isEmpty else { return nil }123        var lo = 0, hi = points.count - 1124        guard let first = points[lo].x.scalar, let last = points[hi].x.scalar else { return nil }125        if first <= last {                                    // ascending (the usual case): binary search126            while hi - lo > 1 {127                let mid = (lo + hi) / 2128                if (points[mid].x.scalar ?? 0) <= scalar { lo = mid } else { hi = mid }129            }130            return abs((points[lo].x.scalar ?? 0) - scalar) <= abs((points[hi].x.scalar ?? 0) - scalar) ? lo : hi131        }132        return points.indices.min { abs((points[$0].x.scalar ?? 0) - scalar) < abs((points[$1].x.scalar ?? 0) - scalar) }133    }134135    // MARK: matrices (heatmap, surface)136137    public struct ColorScale: Sendable, Equatable {138        public var minimum: Double139        public var maximum: Double140        /// The range crosses zero: use the diverging ramp centred on zero.141        public var diverging: Bool142        public init(minimum: Double, maximum: Double, diverging: Bool) { self.minimum = minimum; self.maximum = maximum; self.diverging = diverging }143        /// Position of a value on the ramp, 0…1 (0.5 = zero on a diverging scale).144        public func position(_ value: Double) -> Double {145            if diverging {146                let extent = max(abs(minimum), abs(maximum))147                return extent > 0 ? min(1, max(0, 0.5 + value / (2 * extent))) : 0.5148            }149            return maximum > minimum ? min(1, max(0, (value - minimum) / (maximum - minimum))) : 0.5150        }151        /// The ramp step (0-based, of `steps`) of a value: the filled-contour band it falls in.152        public func band(_ value: Double, steps: Int) -> Int { min(steps - 1, max(0, Int(position(value) * Double(steps)))) }153        /// Boundaries of the bands, `steps + 1` values from the low end to the high end.154        public func levels(steps: Int) -> [Double] {155            let lo = diverging ? -max(abs(minimum), abs(maximum)) : minimum156            let hi = diverging ? max(abs(minimum), abs(maximum)) : maximum157            return (0...steps).map { lo + (hi - lo) * Double($0) / Double(steps) }158        }159    }160161    public static func colorScale(_ matrix: VQLabResult.Chart.Matrix) -> ColorScale? {162        guard let r = matrix.range else { return nil }163        return ColorScale(minimum: r.lowerBound, maximum: r.upperBound, diverging: r.lowerBound < 0 && r.upperBound > 0)164    }165166    // MARK: descriptions (accessibility)167168    /// One sentence describing a chart for VoiceOver: what it shows, its range, where it ends.169    public static func summary(of chart: VQLabResult.Chart, locale: VQNumberLocale = .frCA, language: VQLanguage = .preferred) -> String {170        if let m = chart.matrix, let r = m.range {171            let lo = VQFormat.byUnit(r.lowerBound, chart.y.unit, locale: locale), hi = VQFormat.byUnit(r.upperBound, chart.y.unit, locale: locale)172            return VQL10n.string("Matrix of %1$@ rows by %2$@ columns, values from %3$@ to %4$@.", language, "\(m.y.count)", "\(m.x.count)", "\(lo)", "\(hi)")173        }174        let axis = effectiveAxis(chart)175        var parts: [String] = []176        for s in chart.series.prefix(6) {177            let pts = points(s, axis: axis)178            guard let first = pts.first, let last = pts.last, let lo = pts.map(\.y).min(), let hi = pts.map(\.y).max() else { continue }179            let f = { (v: Double) in VQFormat.byUnit(v, chart.y.unit, locale: locale) }180            parts.append(VQL10n.string("%1$@: %2$@ points, from %3$@ to %4$@, minimum %5$@, maximum %6$@, last value %7$@", language,181                                       s.name, "\(pts.count)", first.x.label, last.x.label, f(lo), f(hi), f(last.y)))182        }183        if chart.series.count > 6 { parts.append(VQL10n.string("and %lld more series", language, chart.series.count - 6)) }184        return parts.joined(separator: ". ") + (parts.isEmpty ? "" : ".")185    }186187    /// The chart as rows for a table view or a CSV export: one row per x position, one column per series.188    public static func table(of chart: VQLabResult.Chart) -> (header: [String], rows: [[String]]) {189        if let m = chart.matrix {190            let header = [chart.y.label] + m.x.map { $0.displayString ?? "" }191            let rows = m.y.enumerated().map { i, y in [y.displayString ?? ""] + (m.z.indices.contains(i) ? m.z[i].map { $0.map { VQJSON.number($0).text() } ?? "" } : []) }192            return (header, rows)193        }194        var order: [String] = [], byX: [String: [String: String]] = [:]195        for s in chart.series {196            for i in 0..<min(s.x.count, s.y.count) {197                let key = s.x[i].displayString ?? ""198                if byX[key] == nil { order.append(key) }199                byX[key, default: [:]][s.name] = s.y[i].map { VQJSON.number($0).text() } ?? ""200            }201        }202        let names = chart.series.map(\.name)203        return ([chart.x.label] + names, order.map { key in [key] + names.map { byX[key]?[$0] ?? "" } })204    }205}206
Files main
Menu

Theme