SPB Git

Repository Public

Generator.swift 8.0 KB 192 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetData/Sources/orix-data-bench/Generator.swift10// Module           : orix-data-bench11// 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 Foundation8889/// Streams clearly synthetic rows to a CSV file: nothing but a 4 MiB byte buffer is held in memory.90struct SyntheticGenerator {91    static let categories = (0..<20).map { String(format: "cat_%02d", $0) }92    static let regions = ["north", "south", "east", "west", "central", "overseas", "online", "partner"]93    static let statuses = ["new", "paid", "shipped", "returned", "cancelled"]94    static let segments = ["retail", "wholesale", "enterprise", "public"]95    static let customerCount = 100_0009697    /// SplitMix64: deterministic, fast, good enough for benchmark data.98    struct RNG {99        var state: UInt64100        mutating func next() -> UInt64 {101            state &+= 0x9E37_79B9_7F4A_7C15102            var z = state103            z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9104            z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB105            return z ^ (z >> 31)106        }107        mutating func below(_ n: UInt64) -> Int { Int(next() % n) }108    }109110    final class Writer {111        private let handle: FileHandle112        private var buffer = [UInt8]()113        private(set) var bytes = 0114        init(_ url: URL) throws {115            FileManager.default.createFile(atPath: url.path, contents: nil)116            handle = try FileHandle(forWritingTo: url)117            buffer.reserveCapacity(4 << 20)118        }119        @inline(__always) func put(_ s: [UInt8]) { buffer.append(contentsOf: s) }120        @inline(__always) func byte(_ b: UInt8) { buffer.append(b) }121        func put(_ value: Int) {122            if value == 0 { buffer.append(48); return }123            var v = value, digits = [UInt8](repeating: 0, count: 20), n = 0124            while v > 0 { digits[n] = UInt8(48 + v % 10); v /= 10; n += 1 }125            while n > 0 { n -= 1; buffer.append(digits[n]) }126        }127        /// Cents as "123.45".128        func put(cents: Int) {129            put(cents / 100)130            buffer.append(46)131            buffer.append(UInt8(48 + (cents % 100) / 10))132            buffer.append(UInt8(48 + cents % 10))133        }134        func flushIfNeeded() throws {135            if buffer.count >= (4 << 20) - 256 { try flush() }136        }137        func flush() throws {138            try handle.write(contentsOf: buffer)139            bytes += buffer.count140            buffer.removeAll(keepingCapacity: true)141        }142        func close() throws { try flush(); try handle.close() }143    }144145    /// orders: id, category, region, order_date, amount, quantity, customer_id, status146    static func writeOrders(to url: URL, rows: Int, seed: UInt64 = 42) throws -> Int {147        let w = try Writer(url)148        var rng = RNG(state: seed)149        let cats = categories.map { Array($0.utf8) }, regs = regions.map { Array($0.utf8) }, stats = statuses.map { Array($0.utf8) }150        // 2020-01-01 … 2024-12-31151        var dates = [[UInt8]]()152        var calendar = Calendar(identifier: .gregorian)153        calendar.timeZone = TimeZone(identifier: "UTC")!154        let start = calendar.date(from: DateComponents(year: 2020, month: 1, day: 1))!155        for d in 0..<1827 {156            let c = calendar.dateComponents([.year, .month, .day], from: calendar.date(byAdding: .day, value: d, to: start)!)157            dates.append(Array(String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!).utf8))158        }159        w.put(Array("id,category,region,order_date,amount,quantity,customer_id,status\n".utf8))160        for id in 1...max(rows, 1) where rows > 0 {161            let r = rng.next()162            w.put(id); w.byte(44)163            w.put(cats[Int(r % 20)]); w.byte(44)164            w.put(regs[Int((r >> 8) % 8)]); w.byte(44)165            w.put(dates[Int((r >> 16) % 1827)]); w.byte(44)166            w.put(cents: Int((r >> 28) % 200_000) + 100); w.byte(44)167            w.put(Int((r >> 46) % 50) + 1); w.byte(44)168            w.put(rng.below(UInt64(customerCount)) + 1); w.byte(44)169            w.put(stats[Int((r >> 54) % 5)]); w.byte(10)170            try w.flushIfNeeded()171        }172        try w.close()173        return w.bytes174    }175176    /// customers: customer_id, segment, credit_limit177    static func writeCustomers(to url: URL, seed: UInt64 = 7) throws -> Int {178        let w = try Writer(url)179        var rng = RNG(state: seed)180        let segs = segments.map { Array($0.utf8) }181        w.put(Array("customer_id,segment,credit_limit\n".utf8))182        for id in 1...customerCount {183            w.put(id); w.byte(44)184            w.put(segs[rng.below(4)]); w.byte(44)185            w.put((rng.below(50) + 1) * 1000); w.byte(10)186            try w.flushIfNeeded()187        }188        try w.close()189        return w.bytes190    }191}192
Files main
Menu

Theme