Tests/OrgCoreTests/TablePlotTests.swift
238 lines · 12665 bytes
7 symbols in this file
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct TablePlotTests {
6 static let cases: [String] = [
7 """
8 #+PLOT: title:"Sales" ind:1 deps:(2 3) type:2d with:lines set:"grid" set:"xrange [0:10]" line:"set key left"
9 | x | a | b | c |
10 |---+---+---+---|
11 | 1 | 2 | 3 | 4 |
12 | 2 | 4 | 5 | 6 |
13 """,
14 """
15 #+PLOT: with:points
16 | 1 | 10 |
17 | 2 | 20 |
18 | 3 | 15 |
19 """,
20 """
21 #+PLOT: ind:1 with:histograms title:"By name"
22 | name | count |
23 |-------+-------|
24 | apple | 3 |
25 | "pear | 5 |
26 """,
27 """
28 #+NAME: series
29 #+PLOT: ind:1 deps:(2) with:linespoints
30 | day | value |
31 |------------------+-------|
32 | <2026-01-05 Mon> | 1.5 |
33 | [2026-01-06 Tue 10:30] | 2 |
34 """,
35 """
36 #+PLOT: type:3d map:t with:lines
37 | 1 | 2 | 3 |
38 | 4 | 5 | 6 |
39 | 7 | 8 | 9 |
40 """,
41 """
42 #+PLOT: type:grid ind:1 title:"Heat"
43 | row | a | b |
44 |-----+---+---|
45 | r1 | 1 | 2 |
46 | r2 | 3 | 4 |
47 """,
48 """
49 #+PLOT: transpose:yes ind:1
50 | x | 1 | 2 | 3 |
51 |---+---+---+---|
52 | y | 4 | 5 | 6 |
53 """,
54 """
55 #+PLOT: labels:("first" "second") ind:1 file:"/tmp/orgstar-plot-test.png"
56 #+PLOT: set:"title 'Upper'"
57 | 1 | 2 |
58 | 3 | 4 |
59 """,
60 """
61 #+PLOT: type:radar title:"Skills"
62 | skill | Anna | Ben | Cleo |
63 |--------+------+-----+------|
64 | Swift | 7 | 4 | 9 |
65 | Lisp | 3 | 8 | 5 |
66 | SQL | 6 | 6 | 2 |
67 | Design | 2.5 | 9 | 4 |
68 | Ops | 8 | 1 | 7 |
69 """,
70 """
71 #+PLOT: type:radar ymin:0 ymax:8
72 | axis | a | b |
73 |------+----+----|
74 | x | 1 | 9 |
75 | y | 4 | 4 |
76 | z | 8 | 3 |
77 """,
78 """
79 #+PLOT: type:radar ticks:0
80 | axis | a | b |
81 |------+-----+-----|
82 | p | 120 | 340 |
83 | q | 0.5 | 0.2 |
84 | r | 15 | 90 |
85 """,
86 """
87 #+PLOT: type:radar ticks:4 file:"/tmp/orgstar-radar.png"
88 | axis | a |
89 |------+----|
90 | one | 3 |
91 | two | 12 |
92 | three | 7 |
93 """,
94 """
95 #+PLOT: type:radar
96 | axis | a | b | c | d |
97 |------+------+------+-----+-----|
98 | u | 1 | 2 | 3 | 4 |
99 | v | 10 | 40 | 25 | 33 |
100 | w | 0.01 | 0.05 | 0.2 | 0.3 |
101 | x | 100 | 700 | 350 | 250 |
102 """,
103 ]
104
105 static func lisp(_ s: String) -> String {
106 "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
107 }
108
109 /// The script and the data file `org-plot/gnuplot` writes, gnuplot itself left out.
110 static func emacs(_ text: String, data: String, setup: String = "") throws -> (script: String, data: String, setup: String) {
111 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
112 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
113 defer { try? FileManager.default.removeItem(at: folder) }
114 let output = folder.appendingPathComponent("script.txt").path
115 let form = """
116 (progn
117 (require 'org) (require 'org-plot)
118 (defun gnuplot-mode ())
119 (defun gnuplot-send-buffer-to-gnuplot ())
120 (provide 'gnuplot)
121 (let ((captured nil))
122 (cl-letf (((symbol-function 'gnuplot-send-buffer-to-gnuplot) (lambda () (setq captured (buffer-string))))
123 ((symbol-function 'org-babel-temp-stable-file) (lambda (&rest _) \(lisp(data))))
124 ((symbol-function 'make-temp-file) (lambda (&rest _) \(lisp(setup)))))
125 (with-temp-buffer
126 (insert \(lisp(text)))
127 (org-mode)
128 (goto-char (point-min))
129 (re-search-forward "^|")
130 (org-plot/gnuplot)))
131 (with-temp-file \(lisp(output)) (insert captured))))
132 """
133 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
134 guard let script = try? String(contentsOfFile: output, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) }
135 return (script, (try? String(contentsOfFile: data, encoding: .utf8)) ?? "", (try? String(contentsOfFile: setup, encoding: .utf8)) ?? "")
136 }
137
138 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: cases.indices)
139 func scriptsAndDataMatchEmacs(index: Int) throws {
140 let text = Self.cases[index]
141 let dataFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-data-\(UUID().uuidString)").path
142 let setupFile = dataFile + "-setup"
143 defer { try? FileManager.default.removeItem(atPath: dataFile); try? FileManager.default.removeItem(atPath: setupFile) }
144 let expected = try Self.emacs(text, data: dataFile, setup: setupFile)
145 let offset = (text as NSString).range(of: "|").location
146 let plot = try TablePlot.plot(text, at: offset)
147 var utc = Calendar(identifier: .gregorian)
148 utc.timeZone = TimeZone(identifier: "UTC")!
149 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot, calendar: utc), [])
150 let script = TablePlot.script(plot, dataFile: dataFile, output: plot.options.file, yLabels: labels, setupFile: setupFile)
151 if plot.options.type == "radar" {
152 let setup = try TablePlot.radarSetup(plot)
153 #expect(setup == expected.setup, "case \(index)\nours:\n\(setup)\nemacs:\n\(expected.setup)")
154 }
155 #expect(script == expected.script, "case \(index)\nours:\n\(script)\nemacs:\n\(expected.script)")
156 #expect(data == expected.data, "case \(index)\nours:\n\(data.debugDescription)\nemacs:\n\(expected.data.debugDescription)")
157 }
158
159 /// `org--plot/sensible-tick-num` over tables of varied ranges; "error" where Emacs signals one.
160 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
161 func radarTicksMatchEmacs() throws {
162 var seed: UInt64 = 7
163 func next(_ n: Int) -> Int { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return Int(seed >> 33) % n }
164 let scales = [1.0, 10, 100, 0.1, 1000, 3]
165 var tables: [[[String]]] = []
166 for _ in 0..<60 {
167 let scale = scales[next(scales.count)]
168 let rows = (0..<(2 + next(4))).map { r in
169 // Distinct values, so no axis is flat (Emacs never returns on one).
170 ["r\(r)"] + (0..<(2 + next(3))).map { c in TablePlot.printed((Double(next(50) * 10 + c) * scale / 10, scale >= 10)) }
171 }
172 tables.append(rows)
173 }
174 let forms = tables.map { t in
175 "(condition-case nil (format \"%S\" (org--plot/sensible-tick-num '(" + t.map { "(" + $0.map { Self.lisp($0) }.joined(separator: " ") + ")" }.joined(separator: " ") + "))) (error \"error\"))"
176 }
177 let expected = try EmacsOracle.evaluate("", "(progn (require 'org-plot) (list " + forms.joined(separator: " ") + "))")
178 #expect(Set(expected).count > 4 && expected.count == tables.count)
179 for (t, want) in zip(tables, expected) {
180 let ours = TablePlot.sensibleTicks(t, hardMin: nil, hardMax: nil).map(String.init) ?? "error"
181 #expect(ours == want, "\(t)")
182 }
183 let rows = [["a", "1", "5"], ["b", "3", "4"]]
184 let bounds: [(Double?, Double?, String)] = [(100, nil, "100 nil"), (nil, 0, "nil 0"), (0, 10, "0 10"), (-5, nil, "-5 nil")]
185 let hard = try EmacsOracle.evaluate("", "(progn (require 'org-plot) (list " + bounds.map {
186 "(condition-case nil (format \"%S\" (org--plot/sensible-tick-num '((\"a\" \"1\" \"5\") (\"b\" \"3\" \"4\")) \($0.2))) (error \"error\"))"
187 }.joined(separator: " ") + "))")
188 for (b, want) in zip(bounds, hard) {
189 #expect((TablePlot.sensibleTicks(rows, hardMin: b.0, hardMax: b.1).map(String.init) ?? "error") == want, "\(b.2)")
190 }
191 }
192
193 @Test func seriesAndMatrices() throws {
194 let plot = try TablePlot.plot(Self.cases[0], at: 100)
195 let series = TablePlot.series(plot)
196 #expect(series.map(\.label) == ["a", "b"])
197 #expect(series[0].points.map(\.y) == [2, 4] && series[0].points.first?.x == .number(1))
198 let text = try TablePlot.plot(Self.cases[2], at: 60)
199 #expect(text.textInd && TablePlot.series(text)[0].points.first?.x == .label("apple"))
200 let dated = try TablePlot.plot(Self.cases[3], at: 80)
201 #expect(dated.timeInd)
202 if case .date = TablePlot.series(dated)[0].points[0].x {} else { Issue.record("not a date") }
203 let grid = try TablePlot.plot(Self.cases[5], at: 60)
204 let m = TablePlot.matrix(grid)
205 #expect(m.values == [[1, 2], [3, 4]] && m.rowLabels == ["r1", "r2"])
206 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| 1 |\n", at: 0) }
207 // Emacs never returns choosing ticks for an axis whose values are all the same.
208 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| a | 1 | 1 |\n| b | 2 | 3 |\n", at: 0) }
209 // Emacs signals an error where the ranges leave nothing to pick ticks from.
210 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ymin:0 ymax:10\n| a | 1 | 9 |\n| b | 2 | 3 |\n", at: 0) }
211 _ = try TablePlot.plot("#+PLOT: type:radar ticks:3\n| a | 1 | 1 |\n| b | 2 | 3 |\n", at: 0)
212 // A ymin above a row's values, or a ymax below them: Emacs signals overflow-error.
213 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ymin:100\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
214 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ymax:0\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
215 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ticks:-1\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
216 // string-to-number reads the reader's infinities and NaNs; Emacs then signals overflow-error.
217 #expect(TablePlot.lispNumber("-2.0e+INF").value == -.infinity && TablePlot.lispNumber("1e+NaN").value.isNaN)
218 #expect(TablePlot.lispNumber("1.0e-INF").value == 1 && TablePlot.lispNumber("1.0e+inf").value == 1 && TablePlot.stringToNumber(".5e+INFx") == .infinity)
219 for field in ["1.0e+INF", "1.0e+NaN"] {
220 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ticks:4\n| a | 1 | \(field) |\n| b | 2 | 5 |\n", at: 0) }
221 }
222 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ticks:99999999999999999999\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
223 // gnuplot draws as many rings as it's given.
224 _ = try TablePlot.plot("#+PLOT: type:radar ticks:2000\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0)
225 // Emacs scales every row with or without ticks:, and signals overflow-error past a double.
226 for row in ["| x | 1e400 | 5 |", "| x | 1e400 | 1e400 |", "| x | -1e400 | 5 |", "| x | 1e308 | -1e308 |"] {
227 #expect(throws: TablePlot.Failure.self, "\(row)") { try TablePlot.plot("#+PLOT: type:radar ticks:3\n\(row)\n| y | 2 | 3 |\n", at: 0) }
228 #expect(throws: TablePlot.Failure.self, "\(row)") { try TablePlot.plot("#+PLOT: type:radar ticks:3 ymin:0 ymax:10\n\(row)\n| y | 2 | 3 |\n", at: 0) }
229 }
230 // Emacs prints a bignum as it is.
231 let big = try TablePlot.radarSetup(TablePlot.plot("#+PLOT: type:radar ticks:3\n| x | 100000000000000000000 | 100000000000000000000 |\n| y | -007 | -007 |\n", at: 0))
232 #expect(big.contains("\"x\" 100000000000000000000 100000000000000000000 3\n\"y\" -7 -7 3\n"), "\(big)")
233 let radar = try TablePlot.radar(TablePlot.plot(Self.cases[9], at: 40))
234 #expect(radar.series == ["a", "b"] && radar.axes.map(\.label) == ["x", "y", "z"] && radar.sharedTicks)
235 #expect(radar.axes[2].values == [8, 3] && radar.axes[0].low == 0 && radar.axes[0].high == 8)
236 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("no table\n", at: 0) }
237 }
238}