Sources/OrgApp/PlotChart.swift

525225e4f44b53a1ea7559b03462473575dfa523
orgstar/Sources/OrgApp/PlotChart.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form