Sources/OrgCore/Compute/TablePlot.swift
353 lines · 17490 bytes
1import Foundation
2
3/// `#+PLOT` (org-plot.el, Org 9.8.7): the options above a table, the table as org-plot reads
4/// it, the data file and the gnuplot script `org-plot/gnuplot` writes, and the values a chart
5/// of its own draws.
6public enum TablePlot {
7 /// A value as `read-from-string` reads an option.
8 public enum Value: Sendable, Equatable, CustomStringConvertible {
9 case number(Double)
10 case symbol(String)
11 case string(String)
12 case list([Value])
13
14 public var description: String {
15 switch self {
16 case .number(let n): n == n.rounded() && abs(n) < 1e15 ? String(Int(n)) : String(n)
17 case .symbol(let s), .string(let s): s
18 case .list(let l): "(" + l.map(\.description).joined(separator: " ") + ")"
19 }
20 }
21
22 var int: Int? { if case .number(let n) = self { Int(n) } else { nil } }
23 public var truthy: Bool { if case .symbol(let s) = self { s != "nil" } else { true } }
24 }
25
26 /// The plist org-plot builds, by key without the colon.
27 public struct Options: Sendable, Equatable {
28 public var values: [String: Value] = [:]
29 /// `:set` and `:line`, latest first, as `cons` leaves them.
30 public var sets: [String] = []
31 public var lines: [String] = []
32
33 public subscript(key: String) -> Value? { values[key] }
34 public var type: String { values["plot-type"]?.description ?? "2d" }
35 public var with: String { values["with"]?.description ?? "lines" }
36 public var ind: Int { values["ind"]?.int ?? 0 }
37 public var deps: [Int]? {
38 guard case .list(let l)? = values["deps"] else { return nil }
39 return l.compactMap(\.int)
40 }
41 public var labels: [String]? {
42 guard case .list(let l)? = values["labels"] else { return nil }
43 return l.map(\.description)
44 }
45 public var file: String? { values["file"]?.description }
46 public var title: String? { values["title"]?.description }
47 }
48
49 static let keys: [(name: String, key: String)] = [
50 ("type", "plot-type"), ("script", "script"), ("line", "line"), ("set", "set"), ("title", "title"), ("ind", "ind"),
51 ("deps", "deps"), ("with", "with"), ("file", "file"), ("labels", "labels"), ("map", "map"), ("timeind", "timeind"),
52 ("timefmt", "timefmt"), ("min", "ymin"), ("ymin", "ymin"), ("max", "ymax"), ("ymax", "ymax"), ("xmin", "xmin"),
53 ("xmax", "xmax"), ("ticks", "ticks"), ("trans", "transpose"), ("transpose", "transpose"),
54 ]
55
56 /// `org-plot/add-options-to-plist`, with its quirks: a key also matches inside a longer
57 /// word (`timeind:` sets `ind`), and an unquoted value ends at `.`, `,` or `;`.
58 static func add(_ text: String, to options: inout Options) {
59 let value = #":("[^"]+?"|\([^)]+?\)|[^ \t\n\r;,.]*)"#
60 var start = text.startIndex
61 for (name, key) in keys {
62 let pattern = try! NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: name) + value)
63 if name == "set" || name == "line" {
64 while let m = pattern.firstMatch(in: text, range: NSRange(start..<text.endIndex, in: text)) {
65 start = Range(m.range, in: text)!.upperBound
66 let read = Self.read(String(text[Range(m.range(at: 1), in: text)!]))
67 if name == "set" { options.sets.insert(read.description, at: 0) } else { options.lines.insert(read.description, at: 0) }
68 }
69 } else if let m = pattern.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) {
70 options.values[key] = Self.read(String(text[Range(m.range(at: 1), in: text)!]))
71 }
72 }
73 }
74
75 /// `read-from-string` of an option's value.
76 static func read(_ s: String) -> Value {
77 if s.hasPrefix("\""), s.hasSuffix("\""), s.count >= 2 { return .string(String(s.dropFirst().dropLast())) }
78 if s.hasPrefix("("), s.hasSuffix(")") {
79 let inner = s.dropFirst().dropLast()
80 var items: [Value] = []
81 for m in inner.matches(of: /"[^"]*"|[^\s"]+/) { items.append(read(String(m.0))) }
82 return .list(items)
83 }
84 if let n = Double(s), s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)(e[-+]?[0-9]+)?$", options: .regularExpression) != nil { return .number(n) }
85 return .symbol(s)
86 }
87
88 // MARK: - The table
89
90 /// What `org-plot/gnuplot` reads: the options, the header row as labels, and the rows.
91 public struct Plot: Sendable, Equatable {
92 public var options: Options
93 /// Rows of fields; nil for a rule left in the table.
94 public var rows: [[String]?]
95 public var columns: Int
96 /// The ind column holds timestamps (`:timeind`) or text (`:textind`).
97 public var timeInd = false
98 public var textInd = false
99 }
100
101 public struct Failure: Error, Equatable, CustomStringConvertible {
102 public let description: String
103 }
104
105 /// The plot for the table at `offset`, or the first table after it, with the `#+PLOT`
106 /// lines above it.
107 public static func plot(_ text: String, at offset: Int) throws -> Plot {
108 let buffer = EmacsBuffer(text, point: offset)
109 // `org-plot/goto-nearest-table`.
110 buffer.point = buffer.lineStart(buffer.point)
111 while !buffer.atTable, buffer.forwardLine(1) == 0 {}
112 guard buffer.atTable else { throw Failure(description: "No table at point") }
113 let begin = buffer.tableBegin()
114 var options = Options()
115 options.values = ["plot-type": .symbol("2d"), "with": .symbol("lines"), "ind": .number(0)]
116 func collect() {
117 buffer.point = begin
118 while buffer.forwardLine(-1) == 0, buffer.looking("[ \\t]*#\\+", caseInsensitive: false, setsMatch: false) != nil {
119 let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
120 if let m = line.firstMatch(of: /#\+PLOT: +(.*)$/) { add(String(m.1), to: &options) }
121 }
122 }
123 collect()
124 buffer.point = begin
125 var table = buffer.tableToLisp()
126 if let t = options["transpose"]?.description, ["y", "yes", "t"].contains(t) {
127 let rows = table.compactMap { $0 }
128 let width = rows.map(\.count).min() ?? 0
129 var transposed: [[String]?] = (0..<width).map { c in rows.map { $0[c] } }
130 if table.contains(where: { $0 == nil }), !transposed.isEmpty { transposed.insert(nil, at: 1) }
131 table = transposed
132 }
133 let first = table.first.flatMap { $0 } ?? (table.count > 1 ? table[1] : nil)
134 let columns = first?.count ?? 0
135 guard ["2d", "3d", "grid", "radar"].contains(options.type) else {
136 throw Failure(description: "Org-plot type `\(options.type)' is undefined")
137 }
138 if table.count > 1, table[1] == nil, let header = table[0] {
139 options.values["labels"] = .list(header.map { .string($0) })
140 table = table.dropFirst().filter { $0 != nil }
141 }
142 collect()
143 var plot = Plot(options: options, rows: table, columns: columns)
144 if options.type == "2d" {
145 let ind = options.ind - 1
146 if ind >= 0 {
147 let column = table.compactMap { $0 }.map { ind < $0.count ? $0[ind] : "" }
148 if column.allSatisfy({ $0.range(of: EmacsBuffer.timestampPattern, options: .regularExpression) != nil }) {
149 plot.timeInd = true
150 } else if options.with == "hist" || !column.allSatisfy(isNumber) {
151 plot.textInd = true
152 }
153 }
154 }
155 if options.type == "radar", options["script"] == nil { _ = try radar(plot) }
156 return plot
157 }
158
159 /// `org-table-number-regexp`.
160 static let numberPattern = "^([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$"
161 static func isNumber(_ s: String) -> Bool { s.range(of: numberPattern, options: .regularExpression) != nil }
162
163 // MARK: - gnuplot
164
165 /// `org-plot/gnuplot-to-data`: tab-separated fields, numbers as they are, timestamps in
166 /// `timefmt`, other text quoted.
167 public static func data(_ plot: Plot, calendar: Calendar = .current) -> String {
168 let format = plot.options["timefmt"]?.description ?? "%Y-%m-%d-%H:%M:%S"
169 return plot.rows.compactMap { $0 }.map { row in
170 row.map { field -> String in
171 if isNumber(field) { return field }
172 if let m = field.firstMatch(of: try! Regex(EmacsBuffer.timestampPattern)),
173 let stamp = Timestamp.parse(String(field[m.range])) {
174 return strftime(format, stamp.start, calendar: calendar)
175 }
176 return "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\""
177 }.joined(separator: "\t")
178 }.joined(separator: "\n")
179 }
180
181 /// `format-time-string` for the escapes timestamps use.
182 static func strftime(_ format: String, _ p: Timestamp.Point, calendar: Calendar) -> String {
183 var out = ""
184 var chars = Array(format)
185 var i = 0
186 chars.append(" ")
187 while i < chars.count - 1 {
188 if chars[i] == "%" {
189 switch chars[i + 1] {
190 case "Y": out += String(format: "%04d", p.year)
191 case "m": out += String(format: "%02d", p.month)
192 case "d": out += String(format: "%02d", p.day)
193 case "H": out += String(format: "%02d", p.hour ?? 0)
194 case "M": out += String(format: "%02d", p.minute ?? 0)
195 case "S": out += "00"
196 case "%": out += "%"
197 default: out += "%" + String(chars[i + 1])
198 }
199 i += 2
200 } else {
201 out.append(chars[i])
202 i += 1
203 }
204 }
205 return out
206 }
207
208 /// `org-plot/gnuplot-to-grid-data`: each cell as the four corners gnuplot's `pm3d`
209 /// draws, and the ind column's values as y labels.
210 public static func gridData(_ plot: Plot) -> (data: String, yLabels: [(Int, String)]) {
211 let ind = plot.options.ind - 1
212 var rows = plot.rows.compactMap { $0 }
213 var labels: [(Int, String)] = []
214 if ind >= 0 { labels = rows.enumerated().map { ($0.offset + 1, ind < $0.element.count ? $0.element[ind] : "") } }
215 var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array((0..<(rows.first?.count ?? 0)).reversed())
216 if ind >= 0 || !deps.isEmpty {
217 deps.removeAll { $0 == ind }
218 rows = rows.map { row in row.indices.filter(deps.contains).map { row[$0] } }
219 }
220 var out = ""
221 let columns = rows.first?.count ?? 0
222 func corners(_ col: Int, _ row: Int, _ value: Double) -> String {
223 String(format: "%f %f %f\n%f %f %f\n", Double(col + 1), Double(row + 1) - 0.5, value, Double(col + 1), Double(row + 1) + 0.5, value)
224 }
225 for col in 0..<columns {
226 var back = "", front = ""
227 for (r, row) in rows.enumerated() {
228 let value = col < row.count ? stringToNumber(row[col]) : 0
229 back += corners(col - 1, r, value)
230 front += corners(col, r, value)
231 }
232 out += back + "\n" + front + "\n"
233 }
234 return (out, labels)
235 }
236
237 /// `string-to-number`: the leading number, else 0.
238 static func stringToNumber(_ s: String) -> Double {
239 lispNumber(s).value
240 }
241
242 /// `org-plot/gnuplot-script`, with `org-plot/gnuplot-term-extra` and the preamble empty.
243 /// `output` is where `file:` goes, expanded. A `preface` leaves out the plot command, for
244 /// a `script:` file to follow.
245 /// `setupFile` is where a radar plot's `radarSetup` goes.
246 public static func script(_ plot: Plot, dataFile: String, output: String?, yLabels: [(Int, String)] = [], preface: Bool = false, setupFile: String = "") -> String {
247 let o = plot.options
248 var script = "reset"
249 func add(_ line: String?) { if let line { script += "\n" + line } }
250 add("set term \(o.file.map { ($0 as NSString).pathExtension } ?? "GNUTERM") ")
251 if let output { add("set output '\(output)'") }
252 switch o.type {
253 case "3d": if o["map"]?.truthy == true { add("set map") }
254 case "grid": add(o["map"]?.truthy == true ? "set pm3d map" : "set map")
255 default: break
256 }
257 add("")
258 if let title = o.title { add("set title '\(title)'") }
259 for line in o.lines { add(line) }
260 for set in o.sets { add("set \(set)") }
261 if script.range(of: "(?m)^set datafile separator", options: .regularExpression) == nil { add("set datafile separator \"\\t\"") }
262 if !yLabels.isEmpty { add("set ytics (" + yLabels.map { "\"\($0.1)\" \($0.0)" }.joined(separator: ", ") + ")") }
263 if o["timeind"]?.truthy == true || plot.timeInd {
264 add("set xdata time")
265 add("set timefmt \"" + (o["timefmt"]?.description ?? "%Y-%m-%d-%H:%M:%S") + "\"")
266 }
267 if preface { return script }
268 var plotLines: [String] = []
269 let with = o.type == "grid" ? "pm3d" : o.with
270 switch o.type {
271 case "2d":
272 let ind = o.ind
273 let textInd = plot.textInd || o.with == "histograms"
274 for col in 0..<plot.columns {
275 if ind == col + 1 || (o.deps.map { !$0.contains(col + 1) } ?? false) { continue }
276 let using = ind > 0 && !textInd ? "\(ind):" : ""
277 let tic = textInd ? ":xticlabel(\(ind))" : ""
278 let label = o.labels.flatMap { col < $0.count ? $0[col] : nil } ?? "\(col + 1)"
279 plotLines.append("'\(dataFile)' using \(using)\(col + 1)\(tic) with \(with) title '\(label)'")
280 }
281 add("plot " + plotLines.joined(separator: ",\\\n "))
282 case "3d":
283 add("splot '\(dataFile)' matrix with \(with) title ''")
284 case "radar":
285 if let radar = try? radar(plot) { add(radarScript(radar, setupFile: setupFile)) }
286 default:
287 add("splot '\(dataFile)' with \(with) title ''")
288 }
289 return script
290 }
291
292 // MARK: - Values for a chart
293
294 /// A dependent column's points: x as a number, a date or a label, and y.
295 public struct Series: Sendable, Equatable {
296 public enum X: Sendable, Equatable {
297 case number(Double)
298 case date(Date)
299 case label(String)
300 }
301 public var label: String
302 public var points: [(x: X, y: Double)]
303 public static func == (a: Series, b: Series) -> Bool {
304 a.label == b.label && a.points.count == b.points.count && zip(a.points, b.points).allSatisfy { $0.x == $1.x && $0.y == $1.y }
305 }
306 }
307
308 /// The 2d plot's series, as the script plots them: one per column but the ind column (or
309 /// the deps), against the ind column or the row number.
310 public static func series(_ plot: Plot, calendar: Calendar = .current) -> [Series] {
311 let o = plot.options
312 let rows = plot.rows.compactMap { $0 }
313 let ind = o.ind
314 var out: [Series] = []
315 for col in 0..<plot.columns {
316 if ind == col + 1 || (o.deps.map { !$0.contains(col + 1) } ?? false) { continue }
317 let label = o.labels.flatMap { col < $0.count ? $0[col] : nil } ?? "\(col + 1)"
318 var points: [(Series.X, Double)] = []
319 for (r, row) in rows.enumerated() {
320 guard col < row.count, isNumber(row[col]), let y = Double(row[col].filter { "0123456789.-+eE".contains($0) }) else { continue }
321 let x: Series.X
322 if ind > 0, ind - 1 < row.count {
323 let field = row[ind - 1]
324 if plot.timeInd, let m = field.firstMatch(of: try! Regex(EmacsBuffer.timestampPattern)), let stamp = Timestamp.parse(String(field[m.range])) {
325 let p = stamp.start
326 x = .date(calendar.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour ?? 0, minute: p.minute ?? 0)) ?? Date())
327 } else if plot.textInd || o.with == "histograms" {
328 x = .label(field)
329 } else {
330 x = .number(stringToNumber(field))
331 }
332 } else {
333 x = .number(Double(r + 1))
334 }
335 points.append((x, y))
336 }
337 out.append(Series(label: label, points: points))
338 }
339 return out
340 }
341
342 /// The 3d and grid plots' matrix: rows of numbers, without the ind column, and the
343 /// ind column's values for the rows.
344 public static func matrix(_ plot: Plot) -> (values: [[Double]], rowLabels: [String]) {
345 let rows = plot.rows.compactMap { $0 }
346 if plot.options.type == "3d" { return (rows.map { $0.map(stringToNumber) }, []) }
347 let ind = plot.options.ind - 1
348 var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array(0..<(rows.first?.count ?? 0))
349 deps.removeAll { $0 == ind }
350 let values = rows.map { row in row.indices.filter(deps.contains).map { stringToNumber(row[$0]) } }
351 return (values, ind >= 0 ? rows.map { ind < $0.count ? $0[ind] : "" } : [])
352 }
353}