SPB Git

Repository Public

Demo.swift 14.0 KB 273 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/FeatureCharts/Sources/charts-preview/Demo.swift10// Module           : charts-preview11// 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 AppKit88import SheetCore89import SheetCharts90import SheetUI91import FeatureCharts9293/// Demo workbook of the charts preview. Every number is synthetic (seeded generator) and the sheets say so.94@MainActor enum Demo {95    static let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]9697    static func session() -> WorkbookSession {98        let wb = Workbook(sheetNames: ["Sales", "Prices", "Lab", "Matrix", "Dashboard"])99        let s = WorkbookSession(workbook: wb, locale: Locale(identifier: "en_US"))100        var rng = SampleRandom(seed: 0x0D1CE)101        let parser = s.parser102        s.perform("Demo") { e in103            func put(_ si: Int, _ r: Int, _ c: Int, _ text: String) { try? e.setInput(sheet: si, row: r, col: c, text, parser: parser) }104            func num(_ si: Int, _ r: Int, _ c: Int, _ v: Double) { e.set(sheet: si, row: r, col: c, .value(.number(v))) }105            let headerFill = RGBA(hex: 0x0891B2)106            func header(_ si: Int, _ a1: String) {107                e.setStyle(sheet: si, range: RangeRef(a1: a1)!) { $0.bold = true; $0.fill = headerFill; $0.textColor = .white; $0.hAlign = .center }108            }109110            // Sales: monthly sales by region, with a growth parameter that drives a forecast column111            for (c, h) in ["Month", "North", "Central", "South", "Forecast"].enumerated() { put(0, 0, c, h) }112            for (i, m) in months.enumerated() {113                put(0, i + 1, 0, m)114                num(0, i + 1, 1, (120 + 9 * Double(i) + 14 * rng.normal()).rounded())115                num(0, i + 1, 2, (96 + 5 * Double(i) + 11 * rng.normal()).rounded())116                num(0, i + 1, 3, (70 + 7.5 * Double(i) + 9 * rng.normal()).rounded())117                put(0, i + 1, 4, "=(B\(i + 2)+C\(i + 2)+D\(i + 2))*(1+$H$2)")118            }119            put(0, 0, 6, "Parameter"); put(0, 0, 7, "Value")120            put(0, 1, 6, "Growth"); num(0, 1, 7, 0.08)121            put(0, 3, 6, "Synthetic sample data")122            header(0, "A1:E1"); header(0, "G1:H1")123            e.setStyle(sheet: 0, range: RangeRef(a1: "H2")!) { $0.numberFormat = "0%" }124            e.setStyle(sheet: 0, range: RangeRef(a1: "G4")!) { $0.italic = true; $0.textColor = RGBA(hex: 0x7A8098) }125            e.setStyle(sheet: 0, range: RangeRef(a1: "B2:E13")!) { $0.numberFormat = "#,##0" }126127            // Prices: a random-walk price series with OHLC128            for (c, h) in ["Date", "Open", "High", "Low", "Close", "Volume"].enumerated() { put(1, 0, c, h) }129            var price = 100.0130            let start = 46_023.0          // serial date, 2026-01-01131            for i in 0..<60 {132                let open = price133                let close = max(20, open + 1.6 * rng.normal() + 0.12)134                let high = max(open, close) + abs(0.9 * rng.normal()), low = min(open, close) - abs(0.9 * rng.normal())135                num(1, i + 1, 0, start + Double(i)); num(1, i + 1, 1, (open * 100).rounded() / 100); num(1, i + 1, 2, (high * 100).rounded() / 100)136                num(1, i + 1, 3, (low * 100).rounded() / 100); num(1, i + 1, 4, (close * 100).rounded() / 100)137                num(1, i + 1, 5, (4000 + 900 * abs(rng.normal())).rounded())138                price = close139            }140            header(1, "A1:F1")141            e.setStyle(sheet: 1, range: RangeRef(a1: "A2:A61")!) { $0.numberFormat = "yyyy-mm-dd" }142            e.setStyle(sheet: 1, range: RangeRef(a1: "B2:E61")!) { $0.numberFormat = "0.00" }143            e.editMeta(sheet: 1) { $0.colWidths[0] = 92 }144            put(1, 0, 7, "Synthetic sample data")145146            // Lab: three measurement groups and a dose / response / weight table147            for (c, h) in ["Group A", "Group B", "Group C"].enumerated() { put(2, 0, c, h) }148            for i in 0..<40 {149                num(2, i + 1, 0, ((50 + 6 * rng.normal()) * 10).rounded() / 10)150                num(2, i + 1, 1, ((57 + 9 * rng.normal()) * 10).rounded() / 10)151                num(2, i + 1, 2, ((46 + 4 * rng.normal()) * 10).rounded() / 10)152            }153            for (c, h) in ["Dose", "Response", "Weight"].enumerated() { put(2, 0, 4 + c, h) }154            for i in 0..<30 {155                let dose = (1 + Double(i) * 0.6 + 0.3 * rng.uniform())156                num(2, i + 1, 4, (dose * 100).rounded() / 100)157                num(2, i + 1, 5, ((8 + 3.1 * dose + 3.4 * rng.normal()) * 10).rounded() / 10)158                num(2, i + 1, 6, ((55 + 18 * rng.uniform()) * 10).rounded() / 10)159            }160            header(2, "A1:C1"); header(2, "E1:G1")161            put(2, 0, 8, "Synthetic sample data")162163            // Matrix: a smooth surface sampled on a 12 × 16 grid164            for r in 0..<12 { for c in 0..<16 {165                let x = Double(c) / 15 * 4 - 2, y = Double(r) / 11 * 3 - 1.5166                num(3, r, c, ((sin(x * 1.4) * cos(y * 1.7) + 0.35 * x * exp(-(x * x + y * y) / 2)) * 1000).rounded() / 1000)167            } }168            e.editMeta(sheet: 3) { $0.defaultColWidth = 56 }169170            // Dashboard: a small financial summary driven by formulas171            let rows: [[String]] = [172                ["Quarterly results (synthetic sample data)", "", "", "", "", ""],173                ["", "Q1", "Q2", "Q3", "Q4", "Year"],174                ["Revenue", "4120", "4480", "4310", "5260", "=SUM(B3:E3)"],175                ["Cost of sales", "-1730", "-1840", "-1790", "-2110", "=SUM(B4:E4)"],176                ["Gross profit", "=B3+B4", "=C3+C4", "=D3+D4", "=E3+E4", "=SUM(B5:E5)"],177                ["Operating costs", "-1310", "-1365", "-1420", "-1480", "=SUM(B6:E6)"],178                ["Operating income", "=B5+B6", "=C5+C6", "=D5+D6", "=E5+E6", "=SUM(B7:E7)"],179                ["Margin", "=B7/B3", "=C7/C3", "=D7/D3", "=E7/E3", "=F7/F3"],180                ["", "", "", "", "", ""],181                ["Bridge", "Amount", "", "Segment", "Revenue", ""],182                ["Revenue", "=F3", "", "Cloud", "7350", ""],183                ["Cost of sales", "=F4", "", "Licences", "5120", ""],184                ["Operating costs", "=F6", "", "Services", "3890", ""],185                ["Operating income", "=F7", "", "Hardware", "1810", ""],186            ]187            for (r, row) in rows.enumerated() { for (c, text) in row.enumerated() where !text.isEmpty { put(4, r, c, text) } }188            e.setStyle(sheet: 4, range: RangeRef(a1: "A1")!) { $0.bold = true; $0.fontSize = 15 }189            header(4, "A2:F2"); header(4, "A10:B10"); header(4, "D10:E10")190            e.setStyle(sheet: 4, range: RangeRef(a1: "B3:F7")!) { $0.numberFormat = "#,##0" }191            e.setStyle(sheet: 4, range: RangeRef(a1: "B11:B14")!) { $0.numberFormat = "#,##0" }192            e.setStyle(sheet: 4, range: RangeRef(a1: "E11:E14")!) { $0.numberFormat = "#,##0" }193            e.setStyle(sheet: 4, range: RangeRef(a1: "B8:F8")!) { $0.numberFormat = "0.0%" }194            e.setStyle(sheet: 4, range: RangeRef(a1: "A7:F7")!) { $0.bold = true; $0.borders.top = BorderEdge(style: .thin, color: headerFill) }195            e.setStyle(sheet: 4, range: RangeRef(a1: "A5:F5")!) { $0.bold = true }196            e.editMeta(sheet: 4) { m in m.colWidths[0] = 132; m.rowHeights[0] = 28 }197        }198        s.engine.clearUndoHistory()199        return s200    }201202    static func detection(_ s: WorkbookSession, _ sheet: Int, _ a1: String) -> SeriesDetection {203        ChartBuilder.detect(AreaRef(sheet: sheet, range: RangeRef(a1: a1)!), in: s.workbook)!204    }205206    /// A chart of `kind` bound to the demo sheet that suits it.207    static func spec(_ kind: ChartKind, _ s: WorkbookSession) -> ChartSpec {208        var spec: ChartSpec209        switch kind {210        case .line, .column, .bar, .area, .radar:211            spec = ChartBuilder.spec(kind, detection(s, 0, "A1:D13"))212            spec.title = "Monthly sales by region"; spec.yAxis.title = "Units"213            if kind == .area { spec.options.stacking = .stacked }214        case .combo:215            spec = ChartBuilder.spec(kind, detection(s, 0, "A1:E13"))216            spec.title = "Sales and forecast"217            for i in spec.series.indices { spec.series[i].kind = i == 3 ? .line : .column; spec.series[i].axis = .primary }218            spec.options.stacking = .stacked219        case .pie, .donut, .treemap:220            spec = ChartBuilder.spec(kind, detection(s, 4, "D10:E14"))221            spec.title = "Revenue by segment"222        case .waterfall:223            spec = ChartBuilder.spec(kind, detection(s, 4, "A10:B14"))224            spec.title = "Income bridge"; spec.options.waterfallTotals = [3]; spec.yAxis.numberFormat = "#,##0"225        case .timeSeries:226            spec = ChartBuilder.spec(kind, detection(s, 1, "A1:E61"))227            spec.series = spec.series.filter { $0.name == "Close" }228            spec.title = "Closing price"; spec.yAxis.numberFormat = "0.00"229        case .candlestick:230            spec = ChartBuilder.spec(kind, detection(s, 1, "A1:E61"))231            spec.title = "Price (OHLC)"232        case .scatter:233            spec = ChartBuilder.spec(kind, detection(s, 2, "E1:F31"))234            spec.title = "Dose and response"235            if !spec.series.isEmpty { spec.series[0].trendline = .linear(showEquation: true, showR2: true) }236        case .bubble:237            spec = ChartBuilder.spec(kind, detection(s, 2, "E1:G31"))238            spec.title = "Dose, response and weight"239        case .histogram, .density, .boxPlot, .violin:240            spec = ChartBuilder.spec(kind, detection(s, 2, "A1:C41"))241            spec.title = "Measurements by group"242        case .heatmap, .contour, .surface3D:243            spec = ChartBuilder.spec(kind, detection(s, 3, "A1:P12"))244            spec.title = "Response surface"245            if kind == .heatmap { spec.options.colorMap = .rdBu }246        }247        spec.subtitle = "Synthetic sample data"248        return spec249    }250251    /// Index of the sheet a demo chart of `kind` reads.252    static func sheet(for kind: ChartKind) -> Int {253        switch kind {254        case .pie, .donut, .treemap, .waterfall: 4255        case .timeSeries, .candlestick: 1256        case .scatter, .bubble, .histogram, .density, .boxPlot, .violin: 2257        case .heatmap, .contour, .surface3D: 3258        default: 0259        }260    }261262    /// Adds a chart object at an explicit frame on the active sheet.263    @discardableResult264    static func place(_ spec: ChartSpec, _ s: WorkbookSession, x: Double, y: Double, w: Double, h: Double) -> SheetObject {265        var spec = spec266        spec.id = UUID()267        let o = SheetObject(id: spec.id, kind: ChartSpec.objectKind, name: ChartPayload.name(for: spec), x: x, y: y, width: w, height: h,268                            payload: ChartPayload.encode(ChartValue(spec: spec))!)269        s.addObject(o)270        return o271    }272}273
Files main
Menu

Theme