Sources/OrgApp/PlotChart.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgApp/PlotChart.swift history · blame · raw

301 lines · 15731 bytes

  1import Charts
  2import Foundation
  3import OrgCore
  4import SwiftUI
  5
  6/// A `#+PLOT` table drawn by Swift Charts, as gnuplot would draw it for org-plot: 2d as lines,
  7/// points, bars or impulses per `with:`, grid as a heat map, 3d as a surface (seen from above
  8/// with `map:t`). `still` draws 3d as a wireframe, which an image can hold.
  9public struct PlotChart: View {
 10    let plot: TablePlot.Plot
 11    let still: Bool
 12
 13    public init(_ plot: TablePlot.Plot, still: Bool = false) {
 14        self.plot = plot
 15        self.still = still
 16    }
 17
 18    public var body: some View {
 19        VStack(spacing: 8) {
 20            if let title = plot.options.title { Text(title).font(.headline) }
 21            switch plot.options.type {
 22            case "grid": HeatMap(plot: plot)
 23            case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot)
 24            case "3d" where still: Wireframe(values: TablePlot.matrix(plot).values)
 25            case "3d": Surface(plot: plot)
 26            default: Lines(plot: plot)
 27            }
 28        }
 29        .padding()
 30    }
 31
 32    /// The `ymin`/`ymax` (or `xmin`/`xmax`) range, filling in from `values` what isn't given.
 33    static func domain(_ low: TablePlot.Value?, _ high: TablePlot.Value?, values: [Double]) -> ClosedRange<Double>? {
 34        func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } }
 35        guard number(low) != nil || number(high) != nil else { return nil }
 36        let lower = number(low) ?? values.min() ?? 0
 37        let upper = number(high) ?? values.max() ?? lower + 1
 38        return lower < upper ? lower...upper : nil
 39    }
 40
 41    struct Lines: View {
 42        let plot: TablePlot.Plot
 43
 44        var body: some View {
 45            let series = TablePlot.series(plot)
 46            let o = plot.options
 47            let ys = series.flatMap { $0.points.map(\.y) }
 48            let xs = series.flatMap { $0.points.compactMap { if case .number(let n) = $0.x { n } else { nil } } }
 49            let ticks = o["ticks"].flatMap { if case .number(let n) = $0 { Int(n) } else { nil } }
 50            let numericX = series.allSatisfy { $0.points.allSatisfy { if case .number = $0.x { true } else { false } } }
 51            let bars = ["boxes", "histograms", "hist", "impulses"].contains(o.with)
 52            let chart = Chart {
 53                ForEach(Array(series.enumerated()), id: \.offset) { _, s in
 54                    ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in
 55                        mark(point.x, point.y, series: s.label)
 56                    }
 57                }
 58            }
 59            .chartYAxis { AxisMarks(values: .automatic(desiredCount: ticks ?? 5)) }
 60            .chartLegend(series.count > 1 ? .visible : .hidden)
 61            // As gnuplot autoscales: to the data, from zero for bars.
 62            let y = Group {
 63                if let domain = PlotChart.domain(o["ymin"], o["ymax"], values: ys) {
 64                    chart.chartYScale(domain: domain)
 65                } else {
 66                    chart.chartYScale(domain: .automatic(includesZero: bars))
 67                }
 68            }
 69            if numericX, let domain = PlotChart.domain(o["xmin"], o["xmax"], values: xs) {
 70                y.chartXScale(domain: domain)
 71            } else if numericX {
 72                y.chartXScale(domain: .automatic(includesZero: false))
 73            } else {
 74                y
 75            }
 76        }
 77
 78        @ChartContentBuilder
 79        func mark(_ x: TablePlot.Series.X, _ y: Double, series: String) -> some ChartContent {
 80            switch x {
 81            case .number(let n): marks(.value("x", n), y, series)
 82            case .date(let d): marks(.value("x", d), y, series)
 83            case .label(let l): marks(.value("x", l), y, series)
 84            }
 85        }
 86
 87        @ChartContentBuilder
 88        func marks<X: Plottable>(_ x: PlottableValue<X>, _ y: Double, _ series: String) -> some ChartContent {
 89            switch plot.options.with {
 90            case "points", "dots":
 91                PointMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
 92            case "linespoints":
 93                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).symbol(by: .value("Series", series))
 94            case "impulses":
 95                BarMark(x: x, y: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series))
 96            case "boxes", "histograms", "hist":
 97                BarMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series))
 98            case "steps":
 99                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepEnd)
100            case "fsteps":
101                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepStart)
102            default:
103                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
104            }
105        }
106    }
107
108    struct HeatMap: View {
109        let plot: TablePlot.Plot
110
111        var body: some View {
112            let (values, rowLabels) = TablePlot.matrix(plot)
113            let columnLabels = columnNames(values.first?.count ?? 0)
114            Chart {
115                ForEach(Array(values.enumerated()), id: \.offset) { r, row in
116                    ForEach(Array(row.enumerated()), id: \.offset) { c, value in
117                        RectangleMark(x: .value("Column", columnLabels[c]), y: .value("Row", rowName(r, rowLabels)),
118                                      width: .ratio(1), height: .ratio(1))
119                            .foregroundStyle(by: .value("Value", value))
120                    }
121                }
122            }
123            .chartForegroundStyleScale(range: Gradient(colors: [.indigo, .teal, .yellow]))
124            // The first row at the bottom, as gnuplot draws it.
125            .chartYScale(domain: values.indices.reversed().map { rowName($0, rowLabels) })
126            .chartXScale(domain: columnLabels)
127        }
128
129        func rowName(_ r: Int, _ labels: [String]) -> String { r < labels.count ? labels[r] : "\(r + 1)" }
130
131        /// The header's names for the plotted columns, or their numbers.
132        func columnNames(_ count: Int) -> [String] {
133            let ind = plot.options.ind - 1
134            let header = plot.options.labels ?? []
135            var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array(0..<plot.columns)
136            deps.removeAll { $0 == ind }
137            return (0..<count).map { i in i < deps.count && deps[i] < header.count ? header[deps[i]] : "\(i + 1)" }
138        }
139    }
140
141    struct Surface: View {
142        let plot: TablePlot.Plot
143
144        var body: some View {
145            let values = TablePlot.matrix(plot).values
146            let rows = max(1, values.count), columns = max(1, values.first?.count ?? 1)
147            Chart3D {
148                SurfacePlot(x: "Column", y: "Value", z: "Row") { x, z in Self.interpolate(values, x, z) }
149            }
150            .chartXScale(domain: 1...Double(max(2, columns)))
151            .chartZScale(domain: 1...Double(max(2, rows)))
152        }
153
154        /// The matrix's value at a fractional column and row, from its four neighbours.
155        static func interpolate(_ m: [[Double]], _ x: Double, _ z: Double) -> Double {
156            guard !m.isEmpty, !m[0].isEmpty else { return 0 }
157            let c = min(max(x - 1, 0), Double(m[0].count - 1)), r = min(max(z - 1, 0), Double(m.count - 1))
158            let c0 = Int(c), r0 = Int(r), c1 = min(c0 + 1, m[0].count - 1), r1 = min(r0 + 1, m.count - 1)
159            func at(_ r: Int, _ c: Int) -> Double { c < m[r].count ? m[r][c] : 0 }
160            let fc = c - Double(c0), fr = r - Double(r0)
161            let top = at(r0, c0) * (1 - fc) + at(r0, c1) * fc
162            let bottom = at(r1, c0) * (1 - fc) + at(r1, c1) * fc
163            return top * (1 - fr) + bottom * fr
164        }
165    }
166}
167
168/// A matrix as gnuplot's `splot … matrix with lines` draws it: a wireframe seen from its
169/// default view, rows and columns along the floor and values up.
170struct Wireframe: View {
171    let values: [[Double]]
172
173    var body: some View {
174        Canvas { context, size in
175            let rows = values.count, columns = values.map(\.count).max() ?? 0
176            guard rows > 0, columns > 0 else { return }
177            let all = values.flatMap { $0 }
178            let low = all.min() ?? 0, high = max(all.max() ?? 1, low + 1e-9)
179            // gnuplot's view: 60° from the vertical, 30° around.
180            let rotation = 30.0 * .pi / 180, tilt = 60.0 * .pi / 180
181            func project(_ c: Double, _ r: Double, _ v: Double) -> CGPoint {
182                let x = c / Double(max(1, columns - 1)) - 0.5, y = r / Double(max(1, rows - 1)) - 0.5, z = (v - low) / (high - low) - 0.5
183                let px = x * cos(rotation) - y * sin(rotation)
184                let depth = x * sin(rotation) + y * cos(rotation)
185                let py = z * sin(tilt) - depth * cos(tilt)
186                let scale = min(size.width, size.height) * 0.75
187                return CGPoint(x: size.width / 2 + px * scale, y: size.height / 2 - py * scale)
188            }
189            var path = Path()
190            for r in 0..<rows {
191                for c in 0..<values[r].count {
192                    let p = project(Double(c), Double(r), values[r][c])
193                    if c == 0 { path.move(to: p) } else { path.addLine(to: p) }
194                }
195            }
196            for c in 0..<columns {
197                var started = false
198                for r in 0..<rows where c < values[r].count {
199                    let p = project(Double(c), Double(r), values[r][c])
200                    if started { path.addLine(to: p) } else { path.move(to: p); started = true }
201                }
202            }
203            context.stroke(path, with: .color(.accentColor), lineWidth: 1.5)
204            var floor = Path()
205            for (c, r) in [(0.0, 0.0), (Double(columns - 1), 0), (Double(columns - 1), Double(rows - 1)), (0, Double(rows - 1)), (0, 0)] {
206                let p = project(c, r, low)
207                if c == 0, r == 0, floor.isEmpty { floor.move(to: p) } else { floor.addLine(to: p) }
208            }
209            context.stroke(floor, with: .color(.secondary), lineWidth: 0.5)
210        }
211    }
212}
213
214/// Plots written to files and run through gnuplot.
215@MainActor
216public enum PlotOutput {
217    public struct Failure: Error, CustomStringConvertible {
218        public let description: String
219    }
220
221    /// `file:` relative to the Org file's folder.
222    public static func file(_ plot: TablePlot.Plot, directory: URL?) -> URL? {
223        guard let name = plot.options.file, !name.isEmpty else { return nil }
224        let expanded = (name as NSString).expandingTildeInPath
225        return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: NSHomeDirectory())).appendingPathComponent(expanded)
226    }
227
228    /// The chart as gnuplot's default 640×480, as PNG, JPEG or PDF by the file's extension.
229    public static func write(_ plot: TablePlot.Plot, to url: URL) throws {
230        let renderer = ImageRenderer(content: PlotChart(plot, still: true).frame(width: 640, height: 480).background(Color.white).environment(\.colorScheme, .light))
231        renderer.scale = 2
232        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
233        switch url.pathExtension.lowercased() {
234        case "pdf":
235            var box = CGRect(x: 0, y: 0, width: 640, height: 480)
236            guard let consumer = CGDataConsumer(url: url as CFURL), let context = CGContext(consumer: consumer, mediaBox: &box, nil) else {
237                throw Failure(description: "Can't write \(url.lastPathComponent)")
238            }
239            renderer.render { _, draw in
240                context.beginPDFPage(nil)
241                draw(context)
242                context.endPDFPage()
243                context.closePDF()
244            }
245        case "png", "jpg", "jpeg", "":
246            guard let image = renderer.cgImage else { throw Failure(description: "The plot couldn't be drawn") }
247            let type = ["jpg", "jpeg"].contains(url.pathExtension.lowercased()) ? "public.jpeg" : "public.png"
248            guard let destination = CGImageDestinationCreateWithURL(url as CFURL, type as CFString, 1, nil) else {
249                throw Failure(description: "Can't write \(url.lastPathComponent)")
250            }
251            CGImageDestinationAddImage(destination, image, nil)
252            guard CGImageDestinationFinalize(destination) else { throw Failure(description: "Can't write \(url.lastPathComponent)") }
253        default:
254            throw Failure(description: "Without gnuplot, plots are written as .png, .jpg or .pdf, not .\(url.pathExtension)")
255        }
256    }
257
258    #if os(macOS)
259    /// gnuplot on the `PATH` Babel uses, when installed.
260    public static var gnuplot: URL? {
261        let path = BabelRunner.environment["PATH"] ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
262        return path.split(separator: ":").map { URL(fileURLWithPath: String($0)).appendingPathComponent("gnuplot") }
263            .first { FileManager.default.isExecutableFile(atPath: $0.path) }
264    }
265
266    /// `org-plot/gnuplot` through gnuplot: the data file and script org-plot writes, run with
267    /// the output at `file:`, or a PNG for showing when there's none. Returns the image.
268    public static func runGnuplot(_ plot: TablePlot.Plot, directory: URL?, gnuplot: URL) async throws -> URL {
269        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
270        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
271        let dataFile = folder.appendingPathComponent("data.tsv")
272        var plot = plot
273        let output = file(plot, directory: directory) ?? folder.appendingPathComponent("plot.png")
274        if plot.options.file == nil { plot.options.values["file"] = .string(output.path) }
275        let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), [])
276        try data.write(to: dataFile, atomically: true, encoding: .utf8)
277        var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels)
278        if let custom = plot.options["script"]?.description {
279            let path = (custom as NSString).expandingTildeInPath
280            let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
281            guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") }
282            script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true)
283                + "\n" + text.replacingOccurrences(of: "$datafile", with: dataFile.path)
284        }
285        let scriptFile = folder.appendingPathComponent("plot.gp")
286        try script.write(to: scriptFile, atomically: true, encoding: .utf8)
287        let process = Process()
288        process.executableURL = gnuplot
289        process.arguments = [scriptFile.path]
290        process.currentDirectoryURL = directory
291        let errors = Pipe()
292        process.standardError = errors
293        try process.run()
294        while process.isRunning { try await Task.sleep(for: .milliseconds(50)) }
295        guard process.terminationStatus == 0 else {
296            throw Failure(description: "gnuplot: " + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
297        }
298        return output
299    }
300    #endif
301}