Sources/OrgApp/PlotChart.swift

430 lines · 22145 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`), radar as a web. `still` draws 3d as a wireframe, which an image can hold.
  9/// The `set` commands in `TablePlot.settings` are followed; the rest are left out.
 10public struct PlotChart: View {
 11    let plot: TablePlot.Plot
 12    let still: Bool
 13
 14    public init(_ plot: TablePlot.Plot, still: Bool = false) {
 15        self.plot = plot
 16        self.still = still
 17    }
 18
 19    public var body: some View {
 20        let settings = TablePlot.settings(plot)
 21        VStack(spacing: 8) {
 22            if let title = settings.title { Text(title).font(.headline) }
 23            switch plot.options.type {
 24            case "grid": HeatMap(plot: plot, settings: settings)
 25            case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot, settings: settings)
 26            case "3d" where still: Wireframe(values: TablePlot.matrix(plot).values)
 27            case "3d": Surface(plot: plot)
 28            case "radar": if let radar = try? TablePlot.radar(plot) { Radar(radar: radar) }
 29            default: Lines(plot: plot, settings: settings)
 30            }
 31        }
 32        .padding()
 33    }
 34
 35    /// The range given by `set` or the options, filling in from `values` what isn't given.
 36    static func domain(_ low: Double?, _ high: Double?, values: [Double]) -> ClosedRange<Double>? {
 37        guard low != nil || high != nil else { return nil }
 38        let lower = low ?? values.min() ?? 0
 39        let upper = high ?? values.max() ?? lower + 1
 40        return lower < upper ? lower...upper : nil
 41    }
 42
 43    static func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } }
 44
 45    struct Lines: View {
 46        let plot: TablePlot.Plot
 47        let settings: TablePlot.Settings
 48
 49        var body: some View {
 50            let s = settings
 51            // Log axes leave out what they can't place.
 52            let series = TablePlot.series(plot).map { series in
 53                var series = series
 54                series.points.removeAll { point in
 55                    if s.logY, !TablePlot.logRange.contains(point.y) { return true }
 56                    if s.logX, case .number(let n) = point.x, !TablePlot.logRange.contains(n) { return true }
 57                    return false
 58                }
 59                return series
 60            }
 61            let o = plot.options
 62            let ys = series.flatMap { $0.points.map(\.y) }
 63            let xs = series.flatMap { $0.points.compactMap { if case .number(let n) = $0.x { n } else { nil } } }
 64            let ticks = o["ticks"].flatMap { if case .number(let n) = $0 { Int(n) } else { nil } }
 65            let numericX = series.allSatisfy { $0.points.allSatisfy { if case .number = $0.x { true } else { false } } }
 66            let bars = ["boxes", "histograms", "hist", "impulses"].contains(o.with)
 67            let yGiven = (low: s.yrange?.low ?? PlotChart.number(o["ymin"]), high: s.yrange?.high ?? PlotChart.number(o["ymax"]))
 68            // A log axis has no 0, so bars stand on its foot, the range the SVG gives it.
 69            let logBars = bars && s.logY ? try? TablePlot.Axis(values: ys, given: yGiven.low == nil && yGiven.high == nil ? nil : .init(low: yGiven.low, high: yGiven.high), log: true, step: nil, zero: false) : nil
 70            let chart = Chart {
 71                ForEach(Array(series.enumerated()), id: \.offset) { _, s in
 72                    ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in
 73                        mark(point.x, point.y, base: logBars?.low, series: s.label)
 74                    }
 75                }
 76            }
 77            .chartXAxis {
 78                AxisMarks(values: s.xtics.map { AxisMarkValues.stride(by: $0) } ?? .automatic) { _ in
 79                    if s.grid { AxisGridLine() }
 80                    AxisTick()
 81                    AxisValueLabel()
 82                }
 83            }
 84            .chartYAxis {
 85                AxisMarks(values: s.ytics.map { AxisMarkValues.stride(by: $0) } ?? .automatic(desiredCount: ticks ?? 5)) { _ in
 86                    if s.grid { AxisGridLine() }
 87                    AxisTick()
 88                    AxisValueLabel()
 89                }
 90            }
 91            .chartXAxisLabel { if let label = s.xlabel { Text(label) } }
 92            .chartYAxisLabel { if let label = s.ylabel { Text(label) } }
 93            .key(s.key, shown: series.count > 1)
 94            // As gnuplot autoscales: to the data, from zero for bars.
 95            let yType: ScaleType? = s.logY ? .log : nil, xType: ScaleType? = s.logX ? .log : nil
 96            let y = Group {
 97                if let logBars {
 98                    chart.chartYScale(domain: logBars.low...logBars.high, type: yType)
 99                } else if let domain = PlotChart.domain(yGiven.low, yGiven.high, values: ys) {
100                    chart.chartYScale(domain: domain, type: yType)
101                } else {
102                    chart.chartYScale(domain: .automatic(includesZero: bars && !s.logY), type: yType)
103                }
104            }
105            if numericX, let domain = PlotChart.domain(s.xrange?.low ?? PlotChart.number(o["xmin"]), s.xrange?.high ?? PlotChart.number(o["xmax"]), values: xs) {
106                y.chartXScale(domain: domain, type: xType)
107            } else if numericX {
108                y.chartXScale(domain: .automatic(includesZero: false), type: xType)
109            } else {
110                y
111            }
112        }
113
114        @ChartContentBuilder
115        func mark(_ x: TablePlot.Series.X, _ y: Double, base: Double?, series: String) -> some ChartContent {
116            switch x {
117            case .number(let n): marks(.value("x", n), y, base, series)
118            case .date(let d): marks(.value("x", d), y, base, series)
119            case .label(let l): marks(.value("x", l), y, base, series)
120            }
121        }
122
123        @ChartContentBuilder
124        func marks<X: Plottable>(_ x: PlottableValue<X>, _ y: Double, _ base: Double?, _ series: String) -> some ChartContent {
125            switch plot.options.with {
126            case "points", "dots":
127                PointMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
128            case "linespoints":
129                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).symbol(by: .value("Series", series))
130            case "impulses":
131                if let base {
132                    BarMark(x: x, yStart: .value("y", base), yEnd: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series))
133                } else {
134                    BarMark(x: x, y: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series))
135                }
136            case "boxes", "histograms", "hist":
137                if let base {
138                    BarMark(x: x, yStart: .value("y", base), yEnd: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series))
139                } else {
140                    BarMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series))
141                }
142            case "steps":
143                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepEnd)
144            case "fsteps":
145                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepStart)
146            default:
147                LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
148            }
149        }
150    }
151
152    struct HeatMap: View {
153        let plot: TablePlot.Plot
154        let settings: TablePlot.Settings
155
156        var body: some View {
157            let (values, rowLabels) = TablePlot.matrix(plot)
158            let columnLabels = columnNames(values.first?.count ?? 0)
159            Chart {
160                ForEach(Array(values.enumerated()), id: \.offset) { r, row in
161                    ForEach(Array(row.enumerated()), id: \.offset) { c, value in
162                        RectangleMark(x: .value("Column", columnLabels[c]), y: .value("Row", rowName(r, rowLabels)),
163                                      width: .ratio(1), height: .ratio(1))
164                            .foregroundStyle(by: .value("Value", value))
165                    }
166                }
167            }
168            .chartForegroundStyleScale(range: Gradient(colors: [.indigo, .teal, .yellow]))
169            // The first row at the bottom, as gnuplot draws it.
170            .chartYScale(domain: values.indices.reversed().map { rowName($0, rowLabels) })
171            .chartXScale(domain: columnLabels)
172            .chartXAxisLabel { if let label = settings.xlabel { Text(label) } }
173            .chartYAxisLabel { if let label = settings.ylabel { Text(label) } }
174            .key(settings.key, shown: true)
175        }
176
177        func rowName(_ r: Int, _ labels: [String]) -> String { r < labels.count ? labels[r] : "\(r + 1)" }
178
179        /// The header's names for the plotted columns, or their numbers.
180        func columnNames(_ count: Int) -> [String] {
181            let ind = plot.options.ind - 1
182            let header = plot.options.labels ?? []
183            var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array(0..<plot.columns)
184            deps.removeAll { $0 == ind }
185            return (0..<count).map { i in i < deps.count && deps[i] < header.count ? header[deps[i]] : "\(i + 1)" }
186        }
187    }
188
189    struct Surface: View {
190        let plot: TablePlot.Plot
191
192        var body: some View {
193            let values = TablePlot.matrix(plot).values
194            let rows = max(1, values.count), columns = max(1, values.first?.count ?? 1)
195            Chart3D {
196                SurfacePlot(x: "Column", y: "Value", z: "Row") { x, z in Self.interpolate(values, x, z) }
197            }
198            .chartXScale(domain: 1...Double(max(2, columns)))
199            .chartZScale(domain: 1...Double(max(2, rows)))
200        }
201
202        /// The matrix's value at a fractional column and row, from its four neighbours.
203        nonisolated static func interpolate(_ m: [[Double]], _ x: Double, _ z: Double) -> Double {
204            guard !m.isEmpty, !m[0].isEmpty else { return 0 }
205            let c = min(max(x - 1, 0), Double(m[0].count - 1)), r = min(max(z - 1, 0), Double(m.count - 1))
206            let c0 = Int(c), r0 = Int(r), c1 = min(c0 + 1, m[0].count - 1), r1 = min(r0 + 1, m.count - 1)
207            func at(_ r: Int, _ c: Int) -> Double { c < m[r].count ? m[r][c] : 0 }
208            let fc = c - Double(c0), fr = r - Double(r0)
209            let top = at(r0, c0) * (1 - fc) + at(r0, c1) * fc
210            let bottom = at(r1, c0) * (1 - fc) + at(r1, c1) * fc
211            return top * (1 - fr) + bottom * fr
212        }
213    }
214}
215
216extension View {
217    /// The legend as `set key` places it, else shown or not.
218    func key(_ key: TablePlot.Settings.Key?, shown: Bool) -> some View {
219        let visible = key.map { $0 != .off } ?? shown
220        return chartLegend(visible ? .visible : .hidden).chartLegend(position: PlotChart.keyPosition(key))
221    }
222}
223
224extension PlotChart {
225    /// Where `set key` puts the legend; gnuplot keeps a direction not given at its default, right top.
226    static func keyPosition(_ key: TablePlot.Settings.Key?) -> AnnotationPosition {
227        guard case .at(let vertical, let horizontal) = key else { return .automatic }
228        switch (vertical ?? "top", horizontal ?? "right") {
229        case ("top", "left"): return .topLeading
230        case ("top", "right"): return .topTrailing
231        case ("bottom", "left"): return .bottomLeading
232        case ("bottom", "right"): return .bottomTrailing
233        default: return .automatic
234        }
235    }
236}
237
238/// A radar plot as org-plot's gnuplot script draws it: an axis per row, clockwise from the
239/// top, each scaled from its low to its high value; a web at each tick; each series filled.
240struct Radar: View {
241    let radar: TablePlot.Radar
242
243    var body: some View {
244        VStack(spacing: 8) {
245            Canvas { context, size in
246                let n = radar.axes.count
247                guard n > 0 else { return }
248                let center = CGPoint(x: size.width / 2, y: size.height / 2)
249                // gnuplot's range is 1.4 times the axes' length each way.
250                let unit = min(size.width, size.height) / 2 / 1.4
251                func point(_ axis: Int, _ r: Double, offset: Double = 0) -> CGPoint {
252                    let angle = (90 - Double(axis) * 360 / Double(n)) * .pi / 180
253                    return CGPoint(x: center.x + (r * cos(angle) + offset * sin(angle)) * unit,
254                                   y: center.y - (r * sin(angle) - offset * cos(angle)) * unit)
255                }
256                let count = radar.ticks == 0 ? 2 : radar.ticks
257                if radar.ticks != 0 {
258                    for i in 1...count {
259                        let r = Double(i) / Double(count)
260                        var web = Path()
261                        web.move(to: point(0, r))
262                        for axis in 1...n { web.addLine(to: point(axis % n, r)) }
263                        context.stroke(web, with: .color(.secondary), style: StrokeStyle(lineWidth: 0.5, dash: [3, 3]))
264                        for axis in 0..<n {
265                            let scale = radar.axes[radar.sharedTicks ? 0 : axis]
266                            let value = Double(i) * (scale.high - scale.low) / Double(count) + scale.low
267                            context.draw(Text(String(format: "%g", value)).font(.system(size: 8)).foregroundStyle(.secondary), at: point(axis, r, offset: 0.1))
268                        }
269                    }
270                }
271                for axis in 0..<n {
272                    var line = Path()
273                    line.move(to: center)
274                    line.addLine(to: point(axis, 1.1))
275                    context.stroke(line, with: .color(.primary), lineWidth: 1)
276                    context.draw(Text(radar.axes[axis].label), at: point(axis, 1.2))
277                }
278                for s in radar.series.indices {
279                    var shape = Path()
280                    for (axis, a) in radar.axes.enumerated() where s < a.values.count && a.high != a.low {
281                        let p = point(axis, (a.values[s] - a.low) / (a.high - a.low))
282                        if shape.isEmpty { shape.move(to: p) } else { shape.addLine(to: p) }
283                    }
284                    shape.closeSubpath()
285                    context.fill(shape, with: .color(Radar.color(s).opacity(0.2)))
286                    context.stroke(shape, with: .color(Radar.color(s)), lineWidth: 1.5)
287                }
288            }
289            .aspectRatio(1, contentMode: .fit)
290            HStack(spacing: 16) {
291                ForEach(Array(radar.series.enumerated()), id: \.offset) { s, name in
292                    HStack(spacing: 4) {
293                        Rectangle().fill(Radar.color(s).opacity(0.4)).frame(width: 16, height: 10)
294                        Text(name).font(.caption)
295                    }
296                }
297            }
298        }
299    }
300
301    /// gnuplot's colour for series `i`.
302    static func color(_ i: Int) -> Color {
303        let v = Int(TablePlot.colors[i % TablePlot.colors.count].dropFirst(), radix: 16) ?? 0
304        return Color(red: Double(v >> 16 & 255) / 255, green: Double(v >> 8 & 255) / 255, blue: Double(v & 255) / 255)
305    }
306}
307
308/// A matrix as gnuplot's `splot … matrix with lines` draws it: a wireframe seen from its
309/// default view, rows and columns along the floor and values up.
310struct Wireframe: View {
311    let values: [[Double]]
312
313    var body: some View {
314        Canvas { context, size in
315            let rows = values.count, columns = values.map(\.count).max() ?? 0
316            guard rows > 0, columns > 0 else { return }
317            let all = values.flatMap { $0 }
318            let low = all.min() ?? 0, high = max(all.max() ?? 1, low + 1e-9)
319            // gnuplot's view: 60° from the vertical, 30° around.
320            let rotation = 30.0 * .pi / 180, tilt = 60.0 * .pi / 180
321            func project(_ c: Double, _ r: Double, _ v: Double) -> CGPoint {
322                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
323                let px = x * cos(rotation) - y * sin(rotation)
324                let depth = x * sin(rotation) + y * cos(rotation)
325                let py = z * sin(tilt) - depth * cos(tilt)
326                let scale = min(size.width, size.height) * 0.75
327                return CGPoint(x: size.width / 2 + px * scale, y: size.height / 2 - py * scale)
328            }
329            var path = Path()
330            for r in 0..<rows {
331                for c in 0..<values[r].count {
332                    let p = project(Double(c), Double(r), values[r][c])
333                    if c == 0 { path.move(to: p) } else { path.addLine(to: p) }
334                }
335            }
336            for c in 0..<columns {
337                var started = false
338                for r in 0..<rows where c < values[r].count {
339                    let p = project(Double(c), Double(r), values[r][c])
340                    if started { path.addLine(to: p) } else { path.move(to: p); started = true }
341                }
342            }
343            context.stroke(path, with: .color(.accentColor), lineWidth: 1.5)
344            var floor = Path()
345            for (c, r) in [(0.0, 0.0), (Double(columns - 1), 0), (Double(columns - 1), Double(rows - 1)), (0, Double(rows - 1)), (0, 0)] {
346                let p = project(c, r, low)
347                if c == 0, r == 0, floor.isEmpty { floor.move(to: p) } else { floor.addLine(to: p) }
348            }
349            context.stroke(floor, with: .color(.secondary), lineWidth: 0.5)
350        }
351    }
352}
353
354/// Plots written to files and run through gnuplot.
355@MainActor
356public enum PlotOutput {
357    public struct Failure: Error, CustomStringConvertible {
358        public let description: String
359
360        public init(description: String) { self.description = description }
361    }
362
363    /// `file:` relative to the Org file's folder.
364    public static func file(_ plot: TablePlot.Plot, directory: URL?) -> URL? {
365        guard let name = plot.options.file, !name.isEmpty else { return nil }
366        let expanded = OrgPaths.expandingTilde(name)
367        return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: OrgPaths.home)).appendingPathComponent(expanded)
368    }
369
370    /// The options a chart drawn here leaves out, for the result message.
371    public static func note(_ plot: TablePlot.Plot) -> String? {
372        let unfollowed = TablePlot.settings(plot).unfollowed
373        return unfollowed.isEmpty ? nil : "Not followed without gnuplot: " + unfollowed.joined(separator: ", ")
374    }
375
376    /// Refuses what the chart can't draw: a radar plot `TablePlot.radar` refuses, which
377    /// `TablePlot.plot` leaves to gnuplot when there's a `script:`, or one with more than 1000
378    /// rings, and a log axis the SVG refuses, which Swift Charts traps on.
379    public static func check(_ plot: TablePlot.Plot) throws {
380        switch plot.options.type {
381        case "radar":
382            let radar: TablePlot.Radar
383            do { radar = try TablePlot.radar(plot) } catch { throw Failure(description: "\(error)") }
384            guard radar.ticks <= 1000 else { throw Failure(description: "Without gnuplot, ticks: takes 0 to 1000") }
385        case "2d":
386            let s = TablePlot.settings(plot)
387            guard s.logX || s.logY else { return }
388            do { _ = try TablePlot.svg(plot) } catch { throw Failure(description: "\(error)") }
389        default:
390            return
391        }
392    }
393
394    /// The chart as gnuplot's default 640×480, as PNG, JPEG, PDF or SVG by the file's extension.
395    public static func write(_ plot: TablePlot.Plot, to url: URL) throws {
396        try check(plot)
397        if url.pathExtension.lowercased() == "svg" {
398            let svg: String
399            do { svg = try TablePlot.svg(plot) } catch { throw Failure(description: "\(error)") }
400            try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
401            return try svg.write(to: url, atomically: true, encoding: .utf8)
402        }
403        let renderer = ImageRenderer(content: PlotChart(plot, still: true).frame(width: 640, height: 480).background(Color.white).environment(\.colorScheme, .light))
404        renderer.scale = 2
405        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
406        switch url.pathExtension.lowercased() {
407        case "pdf":
408            var box = CGRect(x: 0, y: 0, width: 640, height: 480)
409            guard let consumer = CGDataConsumer(url: url as CFURL), let context = CGContext(consumer: consumer, mediaBox: &box, nil) else {
410                throw Failure(description: "Can't write \(url.lastPathComponent)")
411            }
412            renderer.render { _, draw in
413                context.beginPDFPage(nil)
414                draw(context)
415                context.endPDFPage()
416                context.closePDF()
417            }
418        case "png", "jpg", "jpeg", "":
419            guard let image = renderer.cgImage else { throw Failure(description: "The plot couldn't be drawn") }
420            let type = ["jpg", "jpeg"].contains(url.pathExtension.lowercased()) ? "public.jpeg" : "public.png"
421            guard let destination = CGImageDestinationCreateWithURL(url as CFURL, type as CFString, 1, nil) else {
422                throw Failure(description: "Can't write \(url.lastPathComponent)")
423            }
424            CGImageDestinationAddImage(destination, image, nil)
425            guard CGImageDestinationFinalize(destination) else { throw Failure(description: "Can't write \(url.lastPathComponent)") }
426        default:
427            throw Failure(description: "Without gnuplot, plots are written as .png, .jpg, .pdf or .svg, not .\(url.pathExtension)")
428        }
429    }
430}