SPB Git

Repository Public

ModelTests.swift 25.9 KB 380 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/ModelTests.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("Model, data resolution, suggestions, figures")94struct ModelTests {95    @Test func specsRoundTripThroughJSON() throws {96        for spec in ChartSamples.all() + ChartSamples.extras().map(\.spec) {97            let data = try spec.encoded()98            let back = try ChartSpec.decoded(from: data)99            // NaN ≠ NaN, so compare the canonical encodings100            #expect(try back.encoded() == data, "\(spec.kind)")101            #expect(back.id == spec.id && back.schema == ChartSpec.currentSchema)102        }103        var s = ChartSamples.sample(.line)104        s.series[0].values = .range(sheet: "Data", range: RangeRef(a1: "B2:B13")!)105        s.series[0].nameRef = .range(sheet: "Data", range: RangeRef(a1: "B1")!)106        let obj = try s.sheetObject(x: 10, y: 20, width: 480, height: 300)107        #expect(obj.kind == "chart" && obj.name == "Monthly active users" && obj.id == s.id)108        #expect(ChartSpec(sheetObject: obj) == s)109        // sheet rename + a row inserted above the data110        var moved = s111        moved.mapRanges { sheet, range in sheet == "Data" ? ("Renamed", range.offset(rows: 1, cols: 0)) : nil }112        #expect(moved.series[0].values == .range(sheet: "Renamed", range: RangeRef(a1: "B3:B14")!) && moved.series[0].nameRef == .range(sheet: "Renamed", range: RangeRef(a1: "B2")!))113        #expect(s.referencedRanges.count == 2 && s.referencedRanges[0].sheet == "Data")114        #expect(ChartSpec(sheetObject: SheetObject(kind: "image", name: "", x: 0, y: 0, width: 1, height: 1, payload: obj.payload)) == nil)115        #expect(ChartSpec(sheetObject: SheetObject(kind: "chart", name: "", x: 0, y: 0, width: 1, height: 1, payload: Data("nope".utf8))) == nil)116    }117118    @Test func decodingToleratesMissingKeys() throws {119        // a minimal, hand-written payload (as an older schema or another tool might produce)120        let json = """121        {"kind":"scatter","title":"Hand written","series":[{"name":"A","values":{"literal":{"_0":[1,2,3]}},"trendline":{"kind":"power"},122          "style":{"dash":"dot"}},{"errorBars":{"kind":"percent","value":5}}],123         "y2Axis":{"title":"Right"},"options":{"binRule":"scott"},"annotations":[{"kind":"referenceLine","value":2}],"theme":{"name":"Custom","isDark":true}}124        """125        let spec = try ChartSpec.decoded(from: Data(json.utf8))126        #expect(spec.kind == .scatter && spec.title == "Hand written" && spec.series.count == 2)127        #expect(spec.series[0].values == .literal([1, 2, 3]) && spec.series[0].trendline?.kind == .power && spec.series[0].trendline?.order == 2)128        #expect(spec.series[0].style.dash == .dot && spec.series[0].style.marker == .automatic && spec.series[0].axis == .primary)129        #expect(spec.series[1].errorBars?.kind == .percent && spec.series[1].errorBars?.capWidth == 5)130        #expect(spec.series[0].id != spec.series[1].id)131        #expect(spec.y2Axis?.title == "Right" && spec.y2Axis?.gridlines == true)132        #expect(spec.options.binRule == .scott && spec.options.quartileMethod == .inclusive)133        #expect(spec.annotations[0].kind == .referenceLine && spec.annotations[0].dash == .dash)134        #expect(spec.theme.name == "Custom" && spec.theme.isDark && spec.theme.palette == ChartTheme.light.palette)135        #expect(spec.legend.position == .automatic && spec.xAxis.scale == .linear)136        #expect(throws: (any Error).self) { try ChartSpec.decoded(from: Data("{\"kind\":\"hologram\"}".utf8)) }137        // and it renders138        #expect(SVGProbe.parse(ChartRenderer.svgString(spec, source: LiteralDataSource(), size: CGSize(width: 400, height: 300))) != nil)139    }140141    @Test func themesAndPalettes() {142        #expect(ChartTheme.presets.count == 10 && Set(ChartTheme.presets.map(\.name)).count == 10)143        #expect(ChartTheme.named("okabe–ito")?.palette == ChartPalette.okabeIto)144        #expect(ChartPalette.okabeIto.count == 8 && ChartPalette.okabeIto.contains(RGBA(hex: 0xE69F00)))145        let dark = ChartTheme.light.variant(dark: true)146        #expect(dark.isDark && dark.background == ChartTheme.dark.background && dark.palette == ChartPalette.orixDark && dark.name == "Dark")147        #expect(dark.variant(dark: false) == ChartTheme.light)148        #expect(ChartTheme.okabeIto.variant(dark: true).palette == ChartPalette.okabeItoDark)149        for t in ChartTheme.presets {150            // text is legible on the background (WCAG contrast ≥ 4.5), marks are visible (≥ 1.5)151            func contrast(_ a: RGBA, _ b: RGBA) -> Double { (Swift.max(a.luminance, b.luminance) + 0.05) / (Swift.min(a.luminance, b.luminance) + 0.05) }152            #expect(contrast(t.textColor, t.background) >= 7, "\(t.name)")153            #expect(contrast(t.secondaryTextColor, t.background) >= 4.5, "\(t.name)")154            for c in t.palette.prefix(6) { #expect(contrast(c, t.background) >= 1.5, "\(t.name) \(c.hexString)") }155        }156        let typo = ChartTypography().scaled(to: 19)157        #expect(typo.tickLabel == 19 && abs(typo.title / typo.tickLabel - 15 / 9.5) < 1e-12)158        #expect(LineDash.solid.pattern(lineWidth: 2).isEmpty && LineDash.dash.pattern(lineWidth: 2) == [8, 5])159    }160161    @Test func missingValueRuleAndWorkbookSource() {162        let wb = Workbook(sheetNames: ["Data", "Other"])163        let sheet = wb.sheets[0]164        let cells: [Value] = [.text("Sales"), .number(10), .blank, .text("12"), .error(.na), .bool(true), .number(.infinity), .number(-3.5), .number(0)]165        for (i, v) in cells.enumerated() where !v.isBlank { sheet.cells[i, 1] = Cell(value: v) }166        for i in 1..<cells.count { sheet.cells[i, 0] = Cell(value: i == 3 ? .number(2024) : .text("r\(i)")) }167        var locks = 0168        let source = WorkbookDataSource(workbook: wb, lock: { locks += 1 }, unlock: { locks -= 1 })169        var spec = ChartSpec(kind: .column)170        spec.categories = .range(sheet: "data", range: RangeRef(a1: "A2:A9")!)          // sheet names are case-insensitive171        spec.series = [SeriesSpec(nameRef: .range(sheet: "Data", range: RangeRef(a1: "B1")!), values: .range(sheet: "Data", range: RangeRef(a1: "B2:B9")!)),172                       SeriesSpec(values: .range(sheet: "Missing", range: RangeRef(a1: "A1:A3")!)),173                       SeriesSpec(name: "Whole column", values: .range(sheet: "Data", range: RangeRef(a1: "B:B")!))]174        let data = ChartData.resolve(spec, source: source)175        #expect(locks == 0)176        #expect(data.series[0].name == "Sales" && data.series[1].name == "Series 2")177        // only finite numbers are data: blank, numeric-looking text, errors, booleans and ∞ are missing178        #expect(data.series[0].values == [10, nil, nil, nil, nil, nil, -3.5, 0])179        #expect(data.skippedCells >= 4)180        #expect(data.series[1].values == [nil, nil, nil])181        #expect(data.series[2].values == [nil, 10, nil, nil, nil, nil, nil, -3.5, 0])    // clipped to the used rows182        #expect(data.categories == ["r1", "r2", "2024", "r4", "r5", "r6", "r7", "r8"])183        #expect(data.categoryValues[2] == 2024 && data.categoryValues[0] == nil)184        let layout = ChartRenderer.layout(spec, data: data, size: CGSize(width: 500, height: 300), measure: CoreTextMeasurer())185        #expect(layout.hitItems.filter { $0.seriesIndex == 0 }.map(\.pointIndex) == [0, 6, 7])186        #expect(source.shape(.range(sheet: "Data", range: RangeRef(a1: "A:B")!)).rows == 9)187        #expect(LiteralDataSource().values(.literal([1, .nan])) == [.number(1), .blank])188189        // error bars and matrices190        var eb = ChartSpec(kind: .line, series: [SeriesSpec(values: .literal([2, 4, 6, 8]), errorBars: ErrorBarSpec(kind: .stddev, value: 2))])191        var d = ChartData.resolve(eb, source: LiteralDataSource())192        #expect(abs(d.series[0].errorPlus[0]! - 2 * 2.581988897471611) < 1e-12)193        eb.series[0].errorBars = ErrorBarSpec(kind: .stderr); d = ChartData.resolve(eb, source: LiteralDataSource())194        #expect(abs(d.series[0].errorPlus[0]! - 2.581988897471611 / 2) < 1e-12)195        eb.series[0].errorBars = ErrorBarSpec(kind: .percent, value: 10, direction: .plus); d = ChartData.resolve(eb, source: LiteralDataSource())196        #expect(zip(d.series[0].errorPlus, [0.2, 0.4, 0.6, 0.8]).allSatisfy { abs($0! - $1) < 1e-12 } && d.series[0].errorMinus == [nil, nil, nil, nil])197        eb.series[0].errorBars = ErrorBarSpec(kind: .custom, plus: .literal([1, 2, 3, 4]), minus: .literal([0.5, .nan, 0.5, 0.5])); d = ChartData.resolve(eb, source: LiteralDataSource())198        #expect(d.series[0].errorPlus == [1, 2, 3, 4] && d.series[0].errorMinus == [0.5, nil, 0.5, 0.5])199        for r in 0..<3 { for c in 0..<4 { wb.sheets[1].cells[r, c] = Cell(value: .number(Double(r * 4 + c))) } }200        let m = ChartData.resolve(ChartSpec(kind: .heatmap, series: [SeriesSpec(values: .range(sheet: "Other", range: RangeRef(a1: "A1:D3")!))]), source: source)201        #expect(m.matrix == [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])202    }203204    @Test func axisFormatter() {205        #expect(AxisFormatter.automatic(0) == "0")206        #expect(AxisFormatter.automatic(1500, step: 500, maxAbs: 3000) == "1500")207        #expect(AxisFormatter.automatic(25000, step: 5000, maxAbs: 30000) == "25,000")208        #expect(AxisFormatter.automatic(-0.25, step: 0.05, maxAbs: 0.3) == "−0.25")209        #expect(AxisFormatter.automatic(2.5, step: 2.5, maxAbs: 10) == "2.5")210        #expect(AxisFormatter.automatic(0.30000000000000004, step: 0.1, maxAbs: 1) == "0.3")211        #expect(AxisFormatter.automatic(2e11, step: 2e11, maxAbs: 1e12) == "2×10¹¹")212        #expect(AxisFormatter.automatic(1e12, step: 2e11, maxAbs: 1e12) == "10¹²")213        #expect(AxisFormatter.automatic(-4e-13, step: 2e-13, maxAbs: 1e-12) == "−4×10⁻¹³")214        #expect(AxisFormatter.automatic(-0.0000001, step: 1, maxAbs: 10) == "0")215        #expect(AxisFormatter.logLabel(1e-6, base: 10) == "10⁻⁶" && AxisFormatter.logLabel(100, base: 10) == "100" && AxisFormatter.logLabel(0.01, base: 10) == "0.01")216        #expect(AxisFormatter.apply(code: "0.00", to: 3.14159) == "3.14")217        #expect(AxisFormatter.apply(code: "#,##0", to: 1234567.8) == "1,234,568")218        #expect(AxisFormatter.apply(code: "0.0%", to: 0.1234) == "12.3%")219        #expect(AxisFormatter.apply(code: "$#,##0.00", to: -1234.5) == "−$1,234.50")220        #expect(AxisFormatter.apply(code: "0.00E+00", to: 123456) == "1.23E+05")221        #expect(AxisFormatter.apply(code: "0 \"kg\"", to: 12) == "12 kg")222        #expect(AxisFormatter.apply(code: "General", to: 1) == nil && AxisFormatter.apply(code: "", to: 1) == nil)223        let d = DateSerial.serial(year: 2024, month: 2, day: 29) + 0.5625224        #expect(AxisFormatter.apply(code: "yyyy-mm-dd", to: d) == "2024-02-29")225        #expect(AxisFormatter.apply(code: "d mmm yy", to: d) == "29 Feb 24")226        #expect(AxisFormatter.apply(code: "mmmm yyyy", to: d) == "February 2024")227        #expect(AxisFormatter.apply(code: "hh:mm:ss", to: d) == "13:30:00")228        #expect(AxisFormatter.apply(code: "dd/mm/yyyy hh:mm", to: d) == "29/02/2024 13:30")229        // an app-supplied formatter wins over the built-in one230        var spec = ChartSamples.sample(.column)231        spec.yAxis.numberFormat = "custom"232        let data = ChartData.resolve(spec, source: LiteralDataSource())233        let scene = ChartRenderer.scene(spec, data: data, size: CGSize(width: 500, height: 300), measure: CoreTextMeasurer(), formatter: { v, code in "<\(Int(v))|\(code)>" })234        #expect(scene.layout.yAxis!.ticks.contains { $0.label == "<10|custom>" })235    }236237    func table(_ rows: [[Value]], formats: [Int: String] = [:]) -> (Workbook, AreaRef) {238        let wb = Workbook(sheetNames: ["Sheet1"])239        for (r, row) in rows.enumerated() { for (c, v) in row.enumerated() where !v.isBlank {240            var cell = Cell(value: v)241            if let f = formats[c], v.isNumber { var st = CellStyle(); st.numberFormat = f; cell.style = wb.styles.intern(st) }242            wb.sheets[0].cells[r + 1, c + 1] = cell243        } }244        return (wb, AreaRef(sheet: 0, range: RangeRef(r0: 0, c0: 0, r1: 200, c1: 30)))245    }246247    @Test func suggestionsFollowTheShapeOfTheSelection() {248        // text categories + one measure249        var (wb, area) = table([[.text("Region"), .text("Sales")], [.text("North"), .number(10)], [.text("South"), .number(14)], [.text("East"), .number(7)]])250        var a = ChartSuggest.analyze(area, in: wb)!251        #expect(a.range.a1 == "B2:C5" && a.hasHeaderRow && a.hasCategoryColumn && !a.categoryIsDate && a.dataRows == 3)252        var s = ChartSuggest.suggest(for: area, in: wb)253        #expect(s.map(\.kind) == [.column, .bar, .pie, .donut, .line])254        #expect(s[0].categories == .range(sheet: "Sheet1", range: RangeRef(a1: "B3:B5")!) && s[0].series[0].values == .range(sheet: "Sheet1", range: RangeRef(a1: "C3:C5")!))255        #expect(s[0].title == "Sales" && s[0].xAxis.title == "Region")256        let data = ChartData.resolve(s[0], source: WorkbookDataSource(workbook: wb))257        #expect(data.series[0].name == "Sales" && data.series[0].values == [10, 14, 7] && data.categories == ["North", "South", "East"])258259        // several measures, one negative: no stacked / pie suggestion260        (wb, area) = table([[.text("Q"), .text("A"), .text("B"), .text("C")]] + (1...4).map { [.text("Q\($0)"), .number(Double($0)), .number(-2), .number(3)] })261        s = ChartSuggest.suggest(for: area, in: wb)262        #expect(s.map(\.kind) == [.column, .line, .bar, .radar, .heatmap] && s[0].series.count == 3)263        #expect(s.allSatisfy { $0.options.stacking == .grouped })264265        // dates → time series266        let d0 = DateSerial.serial(year: 2025, month: 1, day: 1)267        (wb, area) = table([[.text("Date"), .text("Price")]] + (0..<60).map { [.number(d0 + Double($0)), .number(100 + Double($0 % 7))] }, formats: [0: "yyyy-mm-dd"])268        a = ChartSuggest.analyze(area, in: wb)!269        #expect(a.categoryIsDate && a.columnTypes == [.date, .numeric])270        s = ChartSuggest.suggest(for: area, in: wb)271        #expect(s.first?.kind == .timeSeries && s.count == 2)272        #expect(Charts.isPNG(ChartRenderer.pngData(s[0], source: WorkbookDataSource(workbook: wb), size: CGSize(width: 400, height: 260), scale: 1)))273274        // OHLC275        (wb, area) = table([[.text("Date"), .text("Open"), .text("High"), .text("Low"), .text("Close")]]276                           + (0..<10).map { [.number(d0 + Double($0)), .number(10), .number(12), .number(9), .number(11)] }, formats: [0: "d-mmm"])277        #expect(ChartSuggest.suggest(for: area, in: wb).first?.kind == .candlestick)278279        // years as categories280        (wb, area) = table([[.text("Year"), .text("GDP")]] + (0..<8).map { [.number(Double(2015 + $0)), .number(Double(100 + $0 * 3))] })281        #expect(ChartSuggest.analyze(area, in: wb)!.hasCategoryColumn)282        #expect(ChartSuggest.suggest(for: area, in: wb).map(\.kind) == [.line, .column])283284        // one numeric column, many rows → distribution charts285        (wb, area) = table((0..<40).map { [.number(sin(Double($0)) * 10)] })286        a = ChartSuggest.analyze(area, in: wb)!287        #expect(!a.hasHeaderRow && !a.hasCategoryColumn)288        #expect(ChartSuggest.suggest(for: area, in: wb).map(\.kind) == [.histogram, .boxPlot, .density, .line, .column])289290        // two / three numeric columns → scatter, bubble291        (wb, area) = table([[.text("Height"), .text("Weight")]] + (0..<12).map { [.number(150 + Double($0) * 2.5), .number(50 + Double($0 * $0) * 0.3)] })292        s = ChartSuggest.suggest(for: area, in: wb)293        #expect(s.map(\.kind) == [.scatter, .line] && s[0].xAxis.title == "Height" && s[0].yAxis.title == "Weight" && s[0].series[0].x != nil)294        (wb, area) = table([[.text("x"), .text("y"), .text("size")]] + (0..<12).map { [.number(Double($0) * 1.7), .number(Double(12 - $0)), .number(Double($0 + 1))] })295        #expect(ChartSuggest.suggest(for: area, in: wb).map(\.kind) == [.scatter, .bubble, .line])296297        // bare numeric matrix298        (wb, area) = table((0..<6).map { r in (0..<5).map { c in .number(Double(r * c) + 0.5) } })299        s = ChartSuggest.suggest(for: area, in: wb)300        #expect(Array(s.map(\.kind).prefix(3)) == [.heatmap, .contour, .surface3D])301        #expect(ChartData.resolve(s[0], source: WorkbookDataSource(workbook: wb)).matrix.count == 6)302303        // wide table: series in rows304        (wb, area) = table([[.text("Product"), .text("Jan"), .text("Feb"), .text("Mar"), .text("Apr")], [.text("A"), .number(1), .number(2), .number(3), .number(4)],305                            [.text("B"), .number(4), .number(3), .number(2), .number(1)]])306        s = ChartSuggest.suggest(for: area, in: wb)307        #expect(ChartSuggest.analyze(area, in: wb)!.seriesInRows && s[0].series.count == 2)308        let rows = ChartData.resolve(s[0], source: WorkbookDataSource(workbook: wb))309        #expect(rows.series.map(\.name) == ["A", "B"] && rows.categories == ["Jan", "Feb", "Mar", "Apr"] && rows.series[1].values == [4, 3, 2, 1])310311        // nothing chartable312        (wb, area) = table([[.text("a"), .text("b")], [.text("c"), .text("d")]])313        #expect(ChartSuggest.suggest(for: area, in: wb).isEmpty)314        #expect(ChartSuggest.suggest(for: AreaRef(sheet: 0, range: RangeRef(a1: "Z90:Z99")!), in: wb).isEmpty)315        #expect(ChartSuggest.suggest(for: AreaRef(sheet: 7, range: RangeRef(a1: "A1")!), in: wb).isEmpty)316        // every suggestion of every case renders317        for spec in s { #expect(SVGProbe.parse(ChartRenderer.svgString(spec, source: WorkbookDataSource(workbook: wb), size: CGSize(width: 400, height: 260))) != nil) }318    }319320    @Test func figuresLayOutShareAxesAndExport() throws {321        #expect(FigureTemplates.all.count == 6 && Set(FigureTemplates.all.map(\.id)).count == 6)322        #expect(abs(FigureTemplates.academicSingleColumn.figure.widthMM - 89) < 1e-9 && abs(FigureTemplates.academicDoubleColumn.figure.widthMM - 183) < 1e-9)323        #expect(FigureTemplates.businessPresentation.figure.width / FigureTemplates.businessPresentation.figure.height == 16.0 / 9.0)324        #expect(PanelLabelStyle.parenLower.label(0) == "(a)" && PanelLabelStyle.upper.label(27) == "AB" && PanelLabelStyle.none.label(3) == "")325        let source = LiteralDataSource()326        for (name, figure) in ChartSamples.figures() {327            let svg = FigureRenderer.svgString(figure, source: source)328            let probe = SVGProbe.parse(svg)329            #expect(probe != nil, "\(name)")330            #expect(probe?.elements.filter { $0.name == "g" && ($0.attributes["class"] ?? "").hasPrefix("panel-") }.count == figure.panels.count)331            let pdf = FigureRenderer.pdfData(figure, source: source)332            #expect(Charts.isPDF(pdf) && Charts.containsFont(pdf!) && !Charts.containsImage(pdf!))333            #expect(Charts.isPNG(FigureRenderer.pngData(figure, source: source, scale: 1)))334            #expect(Charts.isPDF(FigureRenderer.exportData(figure, source: source)) || Charts.isPNG(FigureRenderer.exportData(figure, source: source)))335            // one typography everywhere: a single family and the template's size ladder336            let families = Set(probe!.elements.filter { $0.name == "text" }.compactMap { $0.attributes["font-family"] })337            #expect(families.count == 1, "\(name): \(families)")338            let layout = FigureRenderer.scene(figure, source: source, measure: CoreTextMeasurer()).layout339            #expect(layout.panels.count == figure.panels.count)340            let bounds = CGRect(origin: .zero, size: figure.size)341            for (i, p) in layout.panels.enumerated() {342                #expect(bounds.insetBy(dx: -0.5, dy: -0.5).contains(p.frame))343                for (j, q) in layout.panels.enumerated() where j > i { #expect(!p.frame.intersects(q.frame.insetBy(dx: 1, dy: 1))) }344                for f in p.chart.textFrames {345                    #expect(CGRect(origin: .zero, size: p.chartFrame.size).insetBy(dx: -1, dy: -1).contains(f.frame), "\(name) panel \(i): “\(f.text)” is clipped")346                }347            }348            let back = try FigureSpec.decoded(from: figure.encoded())349            #expect(try back.encoded() == figure.encoded())350            #expect(FigureSpec(sheetObject: try figure.sheetObject(x: 0, y: 0))?.id == figure.id)351        }352        // shared axes353        var a = ChartSpec(kind: .scatter, title: "A", series: [SeriesSpec(name: "a", values: .literal([1, 2, 3]), x: .literal([0, 5, 10]))])354        a.xAxis.title = "x"; a.yAxis.title = "y"355        var b = a; b.title = "B"; b.series = [SeriesSpec(name: "b", values: .literal([40, 55, 90]), x: .literal([100, 150, 180]))]356        var fig = FigureSpec(rows: 1, cols: 2, width: 600, height: 260, shareY: true)357        fig.setPanels([a, b])358        var layout = FigureRenderer.scene(fig, source: source, measure: CoreTextMeasurer()).layout359        #expect(layout.panels[0].chart.yAxis!.scale.domainMin == layout.panels[1].chart.yAxis!.scale.domainMin)360        #expect(layout.panels[0].chart.yAxis!.scale.domainMax == layout.panels[1].chart.yAxis!.scale.domainMax && layout.panels[0].chart.yAxis!.scale.domainMax >= 90)361        #expect(layout.panels[0].chart.yAxis!.title == "y" && layout.panels[1].chart.yAxis!.title == "")362        #expect(layout.panels[0].chart.xAxis!.scale.domainMax != layout.panels[1].chart.xAxis!.scale.domainMax)363        #expect(layout.panels.map(\.label) == ["(a)", "(b)"])364        fig = FigureSpec(rows: 2, cols: 1, width: 400, height: 500, shareX: true); fig.setPanels([a, b])365        layout = FigureRenderer.scene(fig, source: source, measure: CoreTextMeasurer()).layout366        #expect(layout.panels[0].chart.xAxis!.scale.domainMax == layout.panels[1].chart.xAxis!.scale.domainMax)367        #expect(layout.panels[0].chart.xAxis!.title == "" && layout.panels[1].chart.xAxis!.title == "x")368        // hit testing through the figure369        let hit = layout.panel(at: CGPoint(x: layout.panels[1].chartFrame.midX, y: layout.panels[1].chartFrame.midY))370        #expect(hit?.panel.label == "(b)")371        // spans and degenerate figures372        fig = FigureSpec(rows: 2, cols: 2, width: 500, height: 400)373        fig.panels = [FigurePanel(chart: a, row: 0, col: 0, colSpan: 2), FigurePanel(chart: b, row: 1, col: 1, label: "Z"), FigurePanel(chart: b, row: 9, col: 9, rowSpan: 5)]374        layout = FigureRenderer.scene(fig, source: source, measure: CoreTextMeasurer()).layout375        #expect(layout.panels[0].frame.width > layout.panels[1].frame.width * 1.9 && layout.panels[1].label == "Z" && layout.panels[2].label == "(b)")376        #expect(SVGProbe.parse(FigureRenderer.svgString(FigureSpec(width: 0, height: 0), source: source)) != nil)377        #expect(SVGProbe.parse(FigureRenderer.svgString(FigureSpec(rows: 0, cols: 0, width: 300, height: 200), source: source)) != nil)378    }379}380
Files main
Menu

Theme