Tests/OrgAppTests/PlotChartTests.swift
198 lines · 15466 bytes
13 symbols in this file
1import Charts
2import Foundation
3import OrgCore
4@testable import OrgApp
5import Testing
6
7@MainActor
8struct PlotChartTests {
9 @Test func writesImagesAndPDF() throws {
10 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plotchart-\(UUID().uuidString)")
11 defer { try? FileManager.default.removeItem(at: folder) }
12 let texts = [
13 "#+PLOT: title:\"Lines\" ind:1 file:\"a.png\"\n| x | a | b |\n|---+---+---|\n| 1 | 2 | 3 |\n| 2 | 4 | 1 |\n| 3 | 3 | 5 |\n",
14 "#+PLOT: ind:1 with:histograms file:\"b.jpg\"\n| name | n |\n|------+---|\n| a | 3 |\n| b | 5 |\n",
15 "#+PLOT: type:grid ind:1 file:\"c.pdf\"\n| r | a | b |\n|---+---+---|\n| x | 1 | 2 |\n| y | 3 | 4 |\n",
16 "#+PLOT: type:3d file:\"d.png\"\n| 1 | 2 | 3 |\n| 2 | 4 | 6 |\n| 3 | 6 | 9 |\n",
17 "#+PLOT: ind:1 with:linespoints file:\"h.png\" set:\"grid\" set:\"xlabel 'x'\" set:\"ylabel 'y'\" set:\"key left top\" set:\"logscale y\"\n| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 500 |\n",
18 "#+PLOT: ind:1 with:linespoints file:\"h.svg\" set:\"grid\" set:\"xlabel 'x'\" set:\"ylabel 'y'\" set:\"key left top\" set:\"logscale y\"\n| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 500 |\n",
19 "#+PLOT: type:radar file:\"r.png\"\n| skill | Anna | Ben |\n|---+---+---|\n| Swift | 7 | 4 |\n| Lisp | 3 | 8 |\n| SQL | 6 | 2 |\n| Ops | 8 | 1 |\n",
20 ]
21 for text in texts {
22 let plot = try TablePlot.plot(text, at: (text as NSString).range(of: "|").location)
23 let url = try #require(PlotOutput.file(plot, directory: folder))
24 try PlotOutput.write(plot, to: url)
25 let size = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0
26 #expect(size > 1000, "\(url.lastPathComponent) is \(size) bytes")
27 if let copy = ProcessInfo.processInfo.environment["ORGSTAR_PLOT_DUMP"] {
28 try? FileManager.default.removeItem(atPath: copy + "/" + url.lastPathComponent)
29 try FileManager.default.copyItem(atPath: url.path, toPath: copy + "/" + url.lastPathComponent)
30 }
31 }
32 let svg = try TablePlot.plot("#+PLOT: file:\"e.svg\"\n| 1 | 2 |\n", at: 25)
33 try PlotOutput.write(svg, to: PlotOutput.file(svg, directory: folder)!)
34 #expect(try String(contentsOf: folder.appendingPathComponent("e.svg"), encoding: .utf8).hasPrefix("<svg"))
35 let grid = try TablePlot.plot("#+PLOT: type:grid file:\"f.svg\"\n| 1 | 2 |\n| 3 | 4 |\n", at: 35)
36 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(grid, to: PlotOutput.file(grid, directory: folder)!) }
37 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(grid, to: folder.appendingPathComponent("g.eps")) }
38 }
39
40 static func plot(_ text: String) throws -> TablePlot.Plot {
41 try TablePlot.plot(text, at: (text as NSString).range(of: "\n|").location + 1)
42 }
43
44 static let table = "| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 50 |\n"
45
46 @Test func followsTheSetSubset() throws {
47 let sets = ["title 'Set'", "xlabel 'Day'", "ylabel 'Count'", "xrange [0:10]", "yrange [*:60]",
48 "grid", "key left top", "xtics 2", "ytics 0.5"]
49 let plot = try Self.plot("#+PLOT: title:\"Given\" ind:1 " + sets.map { "set:\"\($0)\"" }.joined(separator: " ") + "\n" + Self.table)
50 let s = TablePlot.settings(plot)
51 #expect(s.title == "Set" && s.xlabel == "Day" && s.ylabel == "Count")
52 #expect(s.xrange?.low == 0 && s.xrange?.high == 10 && s.yrange?.low == nil && s.yrange?.high == 60)
53 #expect(!s.logY && !s.logX && s.grid && s.xtics == 2 && s.ytics == 0.5)
54 #expect(s.key == .at(vertical: "top", horizontal: "left"))
55 #expect(s.unfollowed.isEmpty && PlotOutput.note(plot) == nil)
56
57 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"logscale\"\n" + Self.table)).logX)
58 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"logscale y\"\n" + Self.table)).logY)
59 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"key off\"\n" + Self.table)).key == .off)
60 #expect(TablePlot.settings(try Self.plot("#+PLOT: line:\"set key bottom\"\n" + Self.table)).key == .at(vertical: "bottom", horizontal: nil))
61 // gnuplot reads title:, then line:, then set:, so a set: wins.
62 #expect(TablePlot.settings(try Self.plot("#+PLOT: line:\"set title 'L'\" set:\"title 'S'\"\n" + Self.table)).title == "S")
63 }
64
65 @Test func reportsWhatItDoesntFollow() throws {
66 let plot = try Self.plot("#+PLOT: ind:1 script:\"plot.gp\" line:\"plot sin(x)\" set:\"style fill solid\" set:\"xrange [a:b]\" set:\"grid\"\n" + Self.table)
67 #expect(TablePlot.settings(plot).unfollowed == ["line:\"plot sin(x)\"", "set:\"style fill solid\"", "set:\"xrange [a:b]\"", "script:\"plot.gp\""])
68 #expect(PlotOutput.note(plot) == "Not followed without gnuplot: line:\"plot sin(x)\", set:\"style fill solid\", set:\"xrange [a:b]\", script:\"plot.gp\"")
69 // Text on the x axis has no range or steps; a heat map has no log scale; a radar plot sets its own key.
70 let text = try Self.plot("#+PLOT: ind:1 set:\"xtics 2\" set:\"ytics 2\"\n| n | v |\n|---+---|\n| a | 1 |\n| b | 2 |\n")
71 #expect(TablePlot.settings(text).unfollowed == ["set:\"xtics 2\""])
72 let grid = try Self.plot("#+PLOT: type:grid set:\"logscale\" set:\"xlabel 'C'\"\n| 1 | 2 |\n| 3 | 4 |\n")
73 #expect(TablePlot.settings(grid).unfollowed == ["set:\"logscale\""] && TablePlot.settings(grid).xlabel == "C")
74 // gnuplot's key leaves a heat map's colour scale alone.
75 let heat = try Self.plot("#+PLOT: type:grid set:\"key off\"\n| 1 | 2 |\n| 3 | 4 |\n")
76 #expect(TablePlot.settings(heat).unfollowed == ["set:\"key off\""] && TablePlot.settings(heat).key == nil)
77 let map = try Self.plot("#+PLOT: type:3d map:t set:\"key left\"\n| 1 | 2 |\n| 3 | 4 |\n")
78 #expect(TablePlot.settings(map).unfollowed == ["set:\"key left\""])
79 // On a log axis gnuplot's step is a factor, whichever comes first.
80 let logTics = try Self.plot("#+PLOT: ind:1 set:\"ytics 2\" set:\"logscale y\" set:\"xtics 1\"\n" + Self.table)
81 #expect(TablePlot.settings(logTics).unfollowed == ["set:\"ytics 2\""] && TablePlot.settings(logTics).ytics == nil && TablePlot.settings(logTics).xtics == 1)
82 let logX = try Self.plot("#+PLOT: ind:1 line:\"set xtics 2\" set:\"logscale x\"\n" + Self.table)
83 #expect(TablePlot.settings(logX).unfollowed == ["line:\"set xtics 2\""])
84 // gnuplot reverses an axis whose range runs high to low.
85 let reversed = try Self.plot("#+PLOT: ind:1 set:\"xrange [10:0]\" set:\"yrange [5:0]\" set:\"yrange [0:5]\"\n" + Self.table)
86 #expect(TablePlot.settings(reversed).unfollowed == ["set:\"xrange [10:0]\"", "set:\"yrange [5:0]\""] && TablePlot.settings(reversed).xrange == nil)
87 let radar = try Self.plot("#+PLOT: type:radar ticks:2 set:\"key off\" set:\"title 'R'\"\n| n | a |\n|---+---|\n| x | 1 |\n| y | 2 |\n| z | 3 |\n")
88 #expect(TablePlot.settings(radar).unfollowed == ["set:\"key off\""] && TablePlot.settings(radar).title == "R")
89 }
90
91 @Test func drawsRadarPlots() throws {
92 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-radar-\(UUID().uuidString)")
93 defer { try? FileManager.default.removeItem(at: folder) }
94 let plot = try Self.plot("#+PLOT: type:radar title:\"Skills\"\n| skill | Anna | Ben |\n|---+---+---|\n| Swift | 7 | 4 |\n| Lisp | 3 | 8 |\n| SQL | 6 | 2 |\n| Ops | 8 | 1 |\n")
95 for name in ["radar.png", "radar.pdf"] {
96 try PlotOutput.write(plot, to: folder.appendingPathComponent(name))
97 let size = (try FileManager.default.attributesOfItem(atPath: folder.appendingPathComponent(name).path)[.size] as? Int) ?? 0
98 #expect(size > 1000, "\(name) is \(size) bytes")
99 }
100 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(plot, to: folder.appendingPathComponent("radar.svg")) }
101 // With script:, TablePlot.plot leaves the radar to gnuplot; drawn here, it's refused.
102 let scripted = try Self.plot("#+PLOT: type:radar script:\"r.gp\"\n| n | a | b |\n|---+---+---|\n| x | 1 | 1 |\n| y | 2 | 3 |\n")
103 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.check(scripted) }
104 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(scripted, to: folder.appendingPathComponent("scripted.png")) }
105 #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("scripted.png").path))
106 try PlotOutput.check(plot)
107 }
108
109 @Test func refusesLogRangesAndDrawsLogBars() throws {
110 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-log-\(UUID().uuidString)")
111 defer { try? FileManager.default.removeItem(at: folder) }
112 let data = "| 1 | 3 |\n| 2 | 4 |\n"
113 for options in ["set:\"logscale y\" set:\"yrange [0:100]\"", "set:\"logscale x\" set:\"xrange [0:10]\"",
114 "set:\"logscale y\" set:\"yrange [-1:100]\"", "set:\"logscale y\" ymin:0", "set:\"logscale x\" xmin:-1"] {
115 let plot = try Self.plot("#+PLOT: ind:1 \(options)\n" + data)
116 #expect(throws: PlotOutput.Failure.self, "\(options)") { try PlotOutput.check(plot) }
117 for name in ["o.png", "o.pdf"] {
118 #expect(throws: PlotOutput.Failure.self, "\(options)") { try PlotOutput.write(plot, to: folder.appendingPathComponent(name)) }
119 }
120 }
121 for options in ["with:boxes set:\"logscale y\"", "with:impulses set:\"logscale y\"", "with:histograms set:\"logscale y\"",
122 "with:boxes set:\"logscale y\" set:\"yrange [0.5:10]\"", "with:impulses set:\"logscale y\" set:\"yrange [2:10]\"", "with:boxes set:\"logscale xy\"", "with:lines set:\"logscale y\""] {
123 let plot = try Self.plot("#+PLOT: ind:1 \(options)\n| 1 | 1 |\n| 2 | 5 |\n")
124 for name in ["b.png", "b.pdf"] {
125 let url = folder.appendingPathComponent(name)
126 try PlotOutput.write(plot, to: url)
127 let size = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0
128 #expect(size > 1000, "\(options) \(name) is \(size) bytes")
129 }
130 }
131 }
132
133 @Test func skipsLogPointsPastADouble() throws {
134 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-log-\(UUID().uuidString)")
135 defer { try? FileManager.default.removeItem(at: folder) }
136 for axis in ["x", "y"] {
137 for field in ["1e400", "3e-324", "1e-320", "1.5e308", "1.0e+INF"] {
138 let row = axis == "x" ? "| \(field) | 5 |" : "| 2 | \(field) |"
139 let plot = try Self.plot("#+PLOT: ind:1 set:\"logscale \(axis)\"\n| x | y |\n|---+---|\n| 1 | 10 |\n\(row)\n| 3 | 20 |\n")
140 try PlotOutput.check(plot)
141 let svg = try TablePlot.svg(plot)
142 #expect(!svg.contains("inf") && !svg.contains("nan"), "\(axis) \(field)")
143 try PlotOutput.write(plot, to: folder.appendingPathComponent("l.png"))
144 }
145 }
146 for range in ["[1:1e400]", "[1e-320:10]"] {
147 let plot = try Self.plot("#+PLOT: ind:1 set:\"logscale y\" set:\"yrange \(range)\"\n| 1 | 10 |\n| 2 | 20 |\n")
148 #expect(throws: PlotOutput.Failure.self, "\(range)") { try PlotOutput.check(plot) }
149 }
150 }
151
152 @Test func placesALoneKeyDirectionAsGnuplot() throws {
153 func position(_ set: String) throws -> String {
154 String(describing: PlotChart.keyPosition(TablePlot.settings(try Self.plot("#+PLOT: set:\"\(set)\"\n" + Self.table)).key))
155 }
156 #expect(try position("key top") == String(describing: AnnotationPosition.topTrailing))
157 #expect(try position("key left") == String(describing: AnnotationPosition.topLeading))
158 #expect(try position("key bottom") == String(describing: AnnotationPosition.bottomTrailing))
159 #expect(try position("key right") == String(describing: AnnotationPosition.topTrailing))
160 #expect(try position("key bottom left") == String(describing: AnnotationPosition.bottomLeading))
161 }
162
163 @Test func capsRadarRingsWithoutGnuplot() throws {
164 let plot = try Self.plot("#+PLOT: type:radar ticks:2000\n| n | a | b |\n|---+---+---|\n| x | 1 | 5 |\n| y | 2 | 3 |\n")
165 #expect(try TablePlot.radarSetup(plot).hasSuffix(" 2000\nEOD\n"))
166 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.check(plot) }
167 try PlotOutput.check(Self.plot("#+PLOT: type:radar ticks:1000\n| n | a | b |\n|---+---+---|\n| x | 1 | 5 |\n| y | 2 | 3 |\n"))
168 }
169
170 @Test func writesSVG() throws {
171 let lines = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"title 'T&C'\" set:\"xlabel 'Day'\" set:\"grid\"\n" + Self.table))
172 #expect(lines.hasPrefix("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"480\""))
173 #expect(lines.components(separatedBy: "<polyline").count - 1 == 2)
174 #expect(lines.contains(">T&C</text>") && lines.contains(">Day</text>") && lines.contains("stroke-dasharray"))
175 #expect(lines.contains(">a</text>") && lines.contains(">b</text>"))
176 let bars = try TablePlot.svg(Self.plot("#+PLOT: ind:1 with:histograms set:\"key off\"\n| n | v |\n|---+---|\n| a | 3 |\n| b | 5 |\n"))
177 #expect(bars.components(separatedBy: "<rect x=").count - 1 == 2 + 2)
178 #expect(bars.contains(">a</text>") && !bars.contains(">v</text>") && !bars.contains("stroke-dasharray"))
179 let log = try TablePlot.svg(Self.plot("#+PLOT: ind:1 with:points set:\"logscale y\"\n| x | v |\n|---+---|\n| 1 | 5 |\n| 2 | 500 |\n| 3 | 0 |\n"))
180 #expect(log.contains(">1</text>") && log.contains(">1000</text>") && log.components(separatedBy: "<circle").count - 1 == 2)
181 // A log range with no power of ten in it is labelled at its ends.
182 let narrow = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale y\" set:\"yrange [2:5]\"\n| 1 | 3 |\n| 2 | 4 |\n"))
183 #expect(narrow.contains(">2</text>") && narrow.contains(">5</text>"))
184 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale y\"\n| 1 | 0 |\n| 2 | -4 |\n")) }
185 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale y\" set:\"yrange [0:100]\"\n| 1 | 3 |\n| 2 | 4 |\n")) }
186 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale x\" set:\"xrange [*:10]\"\n| 0 | 3 |\n| -1 | 4 |\n")) }
187 let ranged = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"xrange [0:10]\" set:\"ytics 25\"\n" + Self.table))
188 #expect(ranged.contains(">10</text>") && ranged.contains(">25</text>") && ranged.contains(">50</text>"))
189 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: type:3d\n| 1 | 2 |\n| 3 | 4 |\n")) }
190 }
191
192 @Test func interpolatesTheMatrix() {
193 let m: [[Double]] = [[1, 2], [3, 4]]
194 #expect(PlotChart.Surface.interpolate(m, 1, 1) == 1)
195 #expect(PlotChart.Surface.interpolate(m, 2, 2) == 4)
196 #expect(PlotChart.Surface.interpolate(m, 1.5, 1.5) == 2.5)
197 }
198}