SPB Git

Repository Public

StructureTests.swift 22.8 KB 401 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetCharts/Tests/SheetChartsTests/StructureTests.swift10// Module           : SheetChartsTests11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreGraphics88import Foundation89import SheetCore90import Testing91@testable import SheetCharts9293@Suite("Geometry is faithful to the data")94struct StructureTests {95    static let size = CGSize(width: 640, height: 400)96    let source = LiteralDataSource()9798    func column(_ values: [[Double]], stacking: StackMode = .grouped, kind: ChartKind = .column) -> ChartSpec {99        var spec = ChartSpec(kind: kind, title: "t")100        spec.categories = .labels((0..<values[0].count).map { "c\($0)" })101        spec.series = values.enumerated().map { SeriesSpec(name: "s\($0.offset)", values: .literal($0.element)) }102        spec.options.stacking = stacking103        spec.options.barCornerRadius = 0104        return spec105    }106107    @Test func columnBarsCorrespondToValues() {108        let values: [[Double]] = [[3, -2, 5.5, .nan, 1], [1, 4, -6, 2, 0]]109        let spec = column(values)110        let layout = Charts.scene(spec).layout111        let ys = layout.yAxis!.scale, xs = layout.xAxis!.scale112        // one mark per present value (NaN is missing; zero is a value)113        #expect(layout.hitItems.count == 9)114        #expect(layout.item(series: 0, point: 3) == nil)115        let zero = ys.position(0)116        for item in layout.hitItems {117            guard case .rect(let r) = item.shape, let y = item.y else { Issue.record("not a rect"); continue }118            #expect(y == values[item.seriesIndex][item.pointIndex])119            let top = ys.position(y)120            #expect(abs((y >= 0 ? r.minY : r.maxY) - top) < 0.5)121            #expect(abs((y >= 0 ? r.maxY : r.minY) - zero) < 0.5)122            // inside its category band123            let c = xs.position(Double(item.pointIndex))124            #expect(abs(r.midX - c) < xs.unitLength / 2 && r.width < xs.unitLength)125            #expect(layout.plotRect.insetBy(dx: -0.5, dy: -0.5).contains(r))126        }127        // SVG: exactly one <path> per bar inside the series group128        let probe = SVGProbe.parse(ChartRenderer.svgString(spec, source: source, size: Self.size))!129        #expect(probe.elements("path", inGroup: "series-0").count == 4)130        #expect(probe.elements("path", inGroup: "series-1").count == 4)   // the zero-height bar draws nothing131        #expect(probe.texts.contains("c0") && probe.texts.contains("s1") && probe.texts.contains("t"))132        // horizontal bars: same geometry with the axes swapped133        let flipped = Charts.scene(column(values, kind: .bar)).layout134        #expect(flipped.isFlipped && flipped.xAxis!.edge == .left && flipped.yAxis!.edge == .bottom)135        for item in flipped.hitItems {136            guard case .rect(let r) = item.shape, let y = item.y else { continue }137            let end = flipped.yAxis!.scale.position(y)138            #expect(abs((y >= 0 ? r.maxX : r.minX) - end) < 0.5)139        }140    }141142    @Test func stackedColumnsSumAndPercentNormalises() {143        let values: [[Double]] = [[3, 2, 5], [1, 4, 6], [2, 2, 1]]144        let layout = Charts.scene(column(values, stacking: .stacked)).layout145        let ys = layout.yAxis!.scale146        for c in 0..<3 {147            let rects = (0..<3).compactMap { s -> CGRect? in if case .rect(let r)? = layout.item(series: s, point: c)?.shape { return r } else { return nil } }148            #expect(rects.count == 3)149            let total = values.reduce(0) { $0 + $1[c] }150            #expect(abs(rects.map(\.minY).min()! - ys.position(total)) < 0.5)151            #expect(abs(rects.map(\.maxY).max()! - ys.position(0)) < 0.5)152            // segments abut153            #expect(abs(rects[0].minY - rects[1].maxY) < 0.01 && abs(rects[1].minY - rects[2].maxY) < 0.01)154        }155        let pct = Charts.scene(column(values, stacking: .percent)).layout156        let ps = pct.yAxis!.scale157        #expect(ps.domainMin == 0 && ps.domainMax == 100)158        #expect(pct.yAxis!.ticks.last?.label == "100%")159        for c in 0..<3 {160            if case .rect(let r)? = pct.item(series: 2, point: c)?.shape { #expect(abs(r.minY - ps.position(100)) < 0.5) } else { Issue.record("missing") }161        }162    }163164    @Test func linePointsCorrespondToValuesAndGapsBreakTheLine() {165        var spec = ChartSpec(kind: .line)166        spec.categories = .labels(["a", "b", "c", "d", "e", "f"])167        spec.series = [SeriesSpec(name: "s", values: .literal([2, 4, .nan, 8, 3, 5]))]168        let scene = Charts.scene(spec)169        let layout = scene.layout170        #expect(layout.hitItems.map(\.pointIndex) == [0, 1, 3, 4, 5])171        for item in layout.hitItems {172            let p = layout.position(x: Double(item.pointIndex), y: item.y!)!173            #expect(abs(p.x - item.anchor.x) < 0.01 && abs(p.y - item.anchor.y) < 0.01)174            let back = layout.dataPoint(at: item.anchor)!175            #expect(abs(back.x - Double(item.pointIndex)) < 1e-9 && abs(back.y - item.y!) < 1e-9)176        }177        // two sub-paths: the missing value is a gap, not a zero178        let probe = SVGProbe.parse(ChartRenderer.svgString(spec, source: source, size: Self.size))!179        let strokes = probe.elements.filter { $0.name == "path" && $0.groups.contains("series-0") && $0.attributes["stroke"] != nil }180        #expect(strokes.first?.attributes["d"]?.filter { $0 == "M" }.count == 2)181        var joined = spec; joined.options.connectGaps = true182        let probe2 = SVGProbe.parse(ChartRenderer.svgString(joined, source: source, size: Self.size))!183        #expect(probe2.elements.first { $0.name == "path" && $0.groups.contains("series-0") && $0.attributes["stroke"] != nil }?.attributes["d"]?.filter { $0 == "M" }.count == 1)184        // the value axis does not start at zero for a line, and does for an area185        #expect(layout.yAxis!.scale.domainMin == 2)186        var area = spec; area.kind = .area187        #expect(Charts.scene(area).layout.yAxis!.scale.domainMin == 0)188    }189190    @Test func scatterPositionsOnLinearAndLogAxes() {191        let xs = [0.02, 0.5, 3, 40, 900, 12000.0], ys = [5, 80, 2, 4000, 60, 0.7]192        for (sx, sy) in [(AxisScale.linear, AxisScale.linear), (.log10, .log10), (.log2, .linear), (.linear, .log10)] {193            var spec = ChartSpec(kind: .scatter, series: [SeriesSpec(name: "p", values: .literal(ys), x: .literal(xs))])194            spec.xAxis.scale = sx; spec.yAxis.scale = sy195            let layout = Charts.scene(spec).layout196            #expect(layout.hitItems.count == 6)197            let ax = layout.xAxis!.scale, ay = layout.yAxis!.scale198            for item in layout.hitItems {199                func t(_ v: Double, _ s: AxisScale) -> Double { s == .log10 ? log10(v) : (s == .log2 ? log2(v) : v) }200                let fx = (t(item.x!, sx) - t(ax.domainMin, sx)) / (t(ax.domainMax, sx) - t(ax.domainMin, sx))201                let fy = (t(item.y!, sy) - t(ay.domainMin, sy)) / (t(ay.domainMax, sy) - t(ay.domainMin, sy))202                #expect(abs(item.anchor.x - (layout.plotRect.minX + CGFloat(fx) * layout.plotRect.width)) < 0.5)203                #expect(abs(item.anchor.y - (layout.plotRect.maxY - CGFloat(fy) * layout.plotRect.height)) < 0.5)204            }205            if sx == .log10 { #expect(layout.xAxis!.ticks.map(\.label) == ["0.01", "0.1", "1", "10", "100", "1000", "10000", "10⁵"]) }206        }207        // values that a log axis cannot show are skipped, never moved208        var bad = ChartSpec(kind: .scatter, series: [SeriesSpec(name: "p", values: .literal([1, -5, 0, 100]), x: .literal([1, 2, 3, 4]))])209        bad.yAxis.scale = .log10210        #expect(Charts.scene(bad).layout.hitItems.map(\.pointIndex) == [0, 3])211    }212213    @Test func bubbleAreaIsProportionalToSize() {214        var spec = ChartSpec(kind: .bubble)215        spec.series = [SeriesSpec(name: "b", values: .literal([1, 2, 3, 4]), x: .literal([1, 2, 3, 4]), size: .literal([100, 25, 400, -3]))]216        spec.options.bubbleMinDiameter = 0217        let layout = Charts.scene(spec).layout218        #expect(layout.hitItems.count == 3)      // non-positive sizes are not drawn219        func radius(_ i: Int) -> CGFloat { if case .point(_, let r)? = layout.item(series: 0, point: i)?.shape { return r } else { return 0 } }220        #expect(abs(radius(0) * radius(0) / (radius(2) * radius(2)) - 0.25) < 1e-6)221        #expect(abs(radius(1) * radius(1) / (radius(2) * radius(2)) - 0.0625) < 1e-6)222        #expect(abs(radius(2) * 2 - CGFloat(spec.options.bubbleMaxDiameter)) < 1e-9)223    }224225    @Test func histogramBarsMatchBins() {226        let x = Reference.shared.datasets["normal500"]!227        var spec = ChartSpec(kind: .histogram, series: [SeriesSpec(name: "x", values: .literal(x))])228        spec.options.binRule = .sturges229        let bins = Binning.histogram(x, rule: .sturges)230        let layout = Charts.scene(spec).layout231        #expect(layout.hitItems.count == bins.binCount)232        let xs = layout.xAxis!.scale, ys = layout.yAxis!.scale233        #expect(xs.domainMin == bins.edges.first! && xs.domainMax == bins.edges.last!)234        for item in layout.hitItems {235            guard case .rect(let r) = item.shape else { continue }236            #expect(abs(r.minX - xs.position(bins.edges[item.pointIndex])) < 0.5 && abs(r.maxX - xs.position(bins.edges[item.pointIndex + 1])) < 0.5)237            #expect(abs(r.minY - ys.position(Double(bins.counts[item.pointIndex]))) < 0.5)238            #expect(item.y == Double(bins.counts[item.pointIndex]))239        }240        #expect(layout.hitItems.reduce(0) { $0 + ($1.y ?? 0) } == 500)241    }242243    @Test func pieAnglesAreProportional() {244        let values: [Double] = [50, 25, 12.5, 12.5, 0, -4, .nan]245        var spec = ChartSpec(kind: .pie, series: [SeriesSpec(name: "v", values: .literal(values))])246        spec.categories = .labels(["a", "b", "c", "d", "e", "f", "g"])247        let layout = Charts.scene(spec).layout248        #expect(layout.hitItems.map(\.pointIndex) == [0, 1, 2, 3])249        #expect(layout.notes.contains { $0.contains("negative") })250        var sum: CGFloat = 0251        for item in layout.hitItems {252            guard case .wedge(_, let ri, let ro, let a0, let a1) = item.shape else { Issue.record("not a wedge"); continue }253            #expect(abs(Double(a1 - a0) / (2 * .pi) - item.y! / 100) < 1e-9)254            #expect(ri == 0 && ro > 50)255            sum += a1 - a0256            #expect(layout.hitTest(item.anchor)?.pointIndex == item.pointIndex)257        }258        #expect(abs(sum - 2 * .pi) < 1e-9)259        // first slice starts at 12 o'clock260        if case .wedge(_, _, _, let a0, _) = layout.hitItems[0].shape { #expect(abs(a0 + .pi / 2) < 1e-9) }261        var donut = spec; donut.kind = .donut262        if case .wedge(_, let ri, let ro, _, _) = Charts.scene(donut).layout.hitItems[0].shape { #expect(abs(ri / ro - 0.58) < 1e-9) }263        let texts = SVGProbe.parse(ChartRenderer.svgString(spec, source: source, size: Self.size))!.texts264        #expect(texts.contains("a  50.0%") && texts.contains("c  12.5%"))265    }266267    @Test func heatmapCandlestickWaterfallBoxGeometry() {268        // heatmap: one cell per number, missing cells absent269        var heat = ChartSpec(kind: .heatmap)270        heat.series = [[1, 2, 3], [4, .nan, 6]].map { SeriesSpec(values: .literal($0)) }271        heat.options.colorMin = 0; heat.options.colorMax = 6272        let hl = Charts.scene(heat).layout273        #expect(hl.hitItems.map(\.pointIndex) == [0, 1, 2, 3, 5])274        #expect(hl.colorBarFrame != nil)275        let probe = SVGProbe.parse(ChartRenderer.svgString(heat, source: source, size: Self.size))!276        let fills = probe.elements("path", inGroup: "series-0").compactMap { $0.attributes["fill"] }277        #expect(fills.count == 5)278        #expect(fills.last == "#" + ColorMap(.viridis).color(1).hexString.lowercased())279280        // candlestick: body spans open–close, wick spans low–high; incomplete rows are skipped281        var candle = ChartSpec(kind: .candlestick)282        candle.series = [SeriesSpec(name: "p", open: .literal([10, 12, 11]), high: .literal([13, 14, .nan]), low: .literal([9, 10, 8]), close: .literal([12, 11, 12]))]283        let cl = Charts.scene(candle).layout284        #expect(cl.hitItems.map(\.pointIndex) == [0, 1])285        let cy = cl.yAxis!.scale286        if case .rect(let r) = cl.hitItems[0].shape { #expect(abs(r.minY - cy.position(13)) < 0.5 && abs(r.maxY - cy.position(9)) < 0.5) }287288        // waterfall289        let steps = SceneBuilder.waterfallSteps([100, -30, nil, 20, 0, 5, 999], totals: [0, 4, 6])290        #expect(steps.map(\.to) == [100, 70, 90, 90, 95, 95] && steps.map(\.from) == [0, 100, 70, 0, 90, 0] && steps.map(\.index) == [0, 1, 3, 4, 5, 6])291        let wl = Charts.scene(ChartSamples.sample(.waterfall)).layout292        let wy = wl.yAxis!.scale293        if case .rect(let r)? = wl.item(series: 0, point: 7)?.shape { #expect(abs(r.minY - wy.position(38)) < 0.5 && abs(r.maxY - wy.position(0)) < 0.5) } else { Issue.record("no total") }294        if case .rect(let r)? = wl.item(series: 0, point: 1)?.shape { #expect(abs(r.minY - wy.position(184)) < 0.5 && abs(r.maxY - wy.position(113)) < 0.5) } else { Issue.record("no step") }295296        // box plot: box spans the quartiles297        let x = Reference.shared.datasets["lognormal200"]!298        let bl = Charts.scene(ChartSpec(kind: .boxPlot, series: [SeriesSpec(name: "x", values: .literal(x))])).layout299        let st = BoxStats(x)!300        if case .rect(let r) = bl.hitItems[0].shape { #expect(abs(r.minY - bl.yAxis!.scale.position(st.q3)) < 0.5 && abs(r.maxY - bl.yAxis!.scale.position(st.q1)) < 0.5) }301        #expect(bl.hitItems.count == 1 + st.outliers.count)302        // treemap: mark areas proportional to values303        let tl = Charts.scene(ChartSamples.sample(.treemap)).layout304        let areas = tl.hitItems.map { $0.bounds.width * $0.bounds.height }305        let total = tl.hitItems.reduce(0) { $0 + $1.y! }306        for (item, a) in zip(tl.hitItems, areas) { #expect(abs(Double(a / areas.reduce(0, +)) - item.y! / total) < 1e-9) }307        // radar: radius proportional to value308        let rl = Charts.scene(ChartSamples.sample(.radar)).layout309        let c = CGPoint(x: rl.plotRect.midX, y: rl.plotRect.midY)310        for item in rl.hitItems { #expect(abs(Double(hypot(item.anchor.x - c.x, item.anchor.y - c.y) / (rl.plotRect.width / 2)) - item.y! / 10) < 1e-6) }311    }312313    @Test func axisTicksAreNiceAndInsideThePlot() {314        for kind in ChartKind.allCases where !kind.isAxisFree {315            let layout = Charts.scene(ChartSamples.sample(kind)).layout316            for axis in [layout.xAxis, layout.yAxis, layout.y2Axis].compactMap({ $0 }) {317                #expect(axis.ticks.count >= 2, "\(kind) \(axis.edge)")318                let horizontal = axis.edge == .bottom || axis.edge == .top319                for t in axis.ticks {320                    #expect(abs(axis.scale.position(t.value) - t.position) < 1e-6)321                    let lo = horizontal ? layout.plotRect.minX : layout.plotRect.minY, hi = horizontal ? layout.plotRect.maxX : layout.plotRect.maxY322                    #expect(t.position >= lo - 0.6 && t.position <= hi + 0.6, "\(kind) tick outside plot")323                }324            }325        }326        let ts = Charts.scene(ChartSamples.sample(.timeSeries)).layout.xAxis!327        #expect(ts.dateUnit == .month)328        #expect(ts.ticks.first?.label == "Jan 2030" && ts.ticks.contains { $0.label == "Jan 2031" })329    }330331    @Test func noTextIsClippedOrOverlapping() {332        var specs = ChartSamples.all() + ChartSamples.all(theme: .presentation) + ChartSamples.extras().map(\.spec)333        specs += ChartSamples.all().map { var s = $0; s.legend.position = .right; return s }334        for spec in specs {335            for size in [CGSize(width: 640, height: 400), CGSize(width: 420, height: 300), CGSize(width: 900, height: 420)] {336                let layout = Charts.scene(spec, size: size).layout337                let canvas = CGRect(origin: .zero, size: size).insetBy(dx: -0.75, dy: -0.75)338                let frames = layout.textFrames339                for f in frames { #expect(canvas.contains(f.frame), "\(spec.kind) \(size): “\(f.text)” leaves the canvas \(f.frame)") }340                // rotated tick labels have overlapping bounding boxes by construction: compare the others341                var rotated: [CGRect] = []342                for axis in [layout.xAxis, layout.yAxis, layout.y2Axis].compactMap({ $0 }) where axis.labelRotation != 0 { rotated += axis.ticks.compactMap(\.labelFrame) }343                let checked = frames.filter { f in !(f.role == .tickLabel && rotated.contains(f.frame)) }344                for i in checked.indices { for j in checked.indices where j > i {345                    let x = checked[i].frame.intersection(checked[j].frame)346                    if !x.isNull && x.width > 1.5 && x.height > 2.5 {347                        Issue.record("\(spec.kind) “\(spec.title)” \(size): “\(checked[i].text)” (\(checked[i].role)) overlaps “\(checked[j].text)” (\(checked[j].role))")348                    }349                } }350            }351        }352    }353354    @Test func hitTestingFindsMarksAndAlignedItems() {355        let layout = Charts.scene(ChartSamples.sample(.column)).layout356        for item in layout.hitItems where item.bounds.height > 2 {357            let p = CGPoint(x: item.bounds.midX, y: item.bounds.midY)358            let hit = layout.hitTest(p)359            #expect(hit?.seriesIndex == item.seriesIndex && hit?.pointIndex == item.pointIndex)360        }361        #expect(layout.hitTest(CGPoint(x: 2, y: 2), maxDistance: 5) == nil)362        let line = Charts.scene(ChartSamples.sample(.line)).layout363        let target = line.item(series: 1, point: 4)!364        #expect(line.hitTest(CGPoint(x: target.anchor.x + 3, y: target.anchor.y - 2))?.pointIndex == 4)365        let aligned = line.items(alignedWith: CGPoint(x: target.anchor.x + 2, y: 100))366        #expect(aligned.count == 3 && Set(aligned.map(\.pointIndex)) == [4])367        #expect(line.legend.map(\.label) == ["North", "Central", "South"])368        #expect(line.legendFrame != nil && line.titleFrame != nil && line.subtitleFrame != nil)369    }370371    @Test func combinationChartUsesBothAxes() {372        let layout = Charts.scene(ChartSamples.sample(.combo)).layout373        let y2 = layout.y2Axis!374        #expect(y2.edge == .right && y2.scale.domainMin == 0)375        let margin = layout.item(series: 2, point: 6)!376        #expect(abs(margin.anchor.y - y2.scale.position(18.4)) < 0.5)377        if case .rect(let r)? = layout.item(series: 0, point: 6)?.shape { #expect(abs(r.minY - layout.yAxis!.scale.position(243)) < 0.5) } else { Issue.record("no bar") }378        #expect(layout.position(x: 6, y: 18.4, axis: .secondary)!.y == margin.anchor.y)379    }380381    @Test func largeSeriesStayFastAndDecimated() {382        let spec = ChartSamples.largeSeries(.line, count: 100_000)383        let data = ChartData.resolve(spec, source: source)384        let start = Date()385        let scene = ChartRenderer.scene(spec, data: data, size: Self.size, measure: CoreTextMeasurer())386        let svg = SVGChartCanvas(size: Self.size)387        scene.draw(in: svg)388        let elapsed = Date().timeIntervalSince(start)389        #expect(elapsed < 3, "100k-point line took \(elapsed) s (debug build)")390        // every point remains addressable, while the drawn path is bounded by the pixel width391        #expect(scene.layout.hitItems.count == 100_000)392        let probe = SVGProbe.parse(svg.svgString())!393        let d = probe.elements.first { $0.name == "path" && $0.groups.contains("series-0") && $0.attributes["stroke"] != nil }!.attributes["d"]!394        let segments = d.filter { $0 == "L" }.count395        #expect(segments < 4 * Int(Self.size.width / 0.5) && segments > 500)396        var raw = spec; raw.options.decimation = false397        let rawScene = ChartRenderer.scene(raw, data: data, size: Self.size, measure: CoreTextMeasurer())398        #expect(rawScene.layout.plotRect == scene.layout.plotRect)399    }400}401
Files main
Menu

Theme