Sources/OrgCore/Compute/PlotSVG.swift
189 lines · 11994 bytes
1import Foundation
2
3/// A 2d plot as an SVG file, 640×480 as gnuplot's default: lines, points or bars by `with:`,
4/// with the `set` commands `settings` follows.
5extension TablePlot {
6 /// gnuplot's default line colours.
7 public static let colors = ["#9400d3", "#009e73", "#56b4e9", "#e69f00", "#f0e442", "#0072b2", "#e51e10", "#000000"]
8
9 /// 1, 2 or 5 times a power of ten, near a fifth of `span`.
10 static func niceStep(_ span: Double) -> Double {
11 let raw = span / 5, power = pow(10, (log10(raw)).rounded(.down)), f = raw / power
12 return power * (f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10)
13 }
14
15 /// What a log axis places; gnuplot skips undefined points, and Swift Charts traps past these.
16 public static let logRange = 1e-307...1e308
17
18 /// An axis: its ends, widened to whole steps where they're not given, and its ticks.
19 public struct Axis {
20 public var low: Double
21 public var high: Double
22 var log: Bool
23 var ticks: [Double] = []
24
25 public init(values: [Double], given: Settings.Range?, log: Bool, step: Double?, zero: Bool) throws {
26 var data = values.filter { !log || TablePlot.logRange.contains($0) }
27 // gnuplot refuses these too.
28 if log, data.isEmpty, given?.low == nil || given?.high == nil { throw Failure(description: "A log axis needs values above 0") }
29 if log, [given?.low, given?.high].contains(where: { ($0 ?? 1) <= 0 }) { throw Failure(description: "A log axis's range must be above 0") }
30 if log, [given?.low, given?.high].contains(where: { !TablePlot.logRange.contains($0 ?? 1) }) { throw Failure(description: "A log axis's range must be within 1e-307 to 1e308") }
31 if zero, !log { data.append(0) }
32 var low = given?.low ?? data.min() ?? 0, high = given?.high ?? data.max() ?? 1
33 if low == high { (low, high) = log ? (low / 10, high * 10) : (low - 1, high + 1) }
34 if low > high { swap(&low, &high) }
35 self.log = log
36 if log {
37 if given?.low == nil { low = pow(10, log10(low).rounded(.down)) }
38 if given?.high == nil { high = pow(10, log10(high).rounded(.up)) }
39 guard TablePlot.logRange.contains(low), TablePlot.logRange.contains(high) else { throw Failure(description: "A log axis's range must be within 1e-307 to 1e308") }
40 let first = log10(low).rounded(.up), last = log10(high).rounded(.down)
41 // A range with no power of ten in it is labelled at its ends.
42 ticks = first <= last ? Array(Int(first)...Int(last)).map { pow(10, Double($0)) } : [low, high]
43 } else {
44 let step = step ?? TablePlot.niceStep(high - low)
45 if given?.low == nil { low = (low / step).rounded(.down) * step }
46 if given?.high == nil { high = (high / step).rounded(.up) * step }
47 var t = (low / step).rounded(.up) * step
48 while t <= high + step * 1e-9, ticks.count < 200 { ticks.append(abs(t) < step * 1e-9 ? 0 : t); t += step }
49 }
50 self.low = low
51 self.high = high
52 }
53
54 func fraction(_ v: Double) -> Double {
55 log ? (log10(v) - log10(low)) / (log10(high) - log10(low)) : (v - low) / (high - low)
56 }
57 }
58
59 static func escaped(_ s: String) -> String {
60 s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
61 .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
62 }
63
64 static func number(_ v: Double) -> String { String(format: "%.2f", v) }
65
66 public static func svg(_ plot: Plot, calendar: Calendar = .current) throws -> String {
67 guard plot.options.type == "2d" else {
68 throw Failure(description: "Without gnuplot, only 2d plots are written as .svg; use .png, .jpg or .pdf")
69 }
70 let s = settings(plot), with = plot.options.with
71 let series = series(plot, calendar: calendar)
72 let bars = ["boxes", "histograms", "hist"].contains(with)
73 var categories: [String] = []
74 for p in series.flatMap(\.points) { if case .label(let l) = p.x, !categories.contains(l) { categories.append(l) } }
75 let dates = series.contains { $0.points.contains { if case .date = $0.x { true } else { false } } }
76 func xValue(_ x: Series.X) -> Double {
77 switch x {
78 case .number(let n): n
79 case .date(let d): d.timeIntervalSince1970
80 case .label(let l): Double(categories.firstIndex(of: l)!)
81 }
82 }
83 func bound(_ key: String) -> Double? { if case .number(let n)? = plot.options[key] { n } else { nil } }
84 func given(_ set: Settings.Range?, _ low: String, _ high: String) -> Settings.Range? {
85 let r = Settings.Range(low: set?.low ?? bound(low), high: set?.high ?? bound(high))
86 return r.low == nil && r.high == nil ? nil : r
87 }
88 let ys = series.flatMap { $0.points.map(\.y) }
89 let y = try Axis(values: ys, given: given(s.yrange, "ymin", "ymax"), log: s.logY, step: s.ytics, zero: bars || with == "impulses")
90 var x: Axis
91 if !categories.isEmpty {
92 x = try Axis(values: [], given: .init(low: -0.5, high: Double(categories.count) - 0.5), log: false, step: 1, zero: false)
93 x.ticks = categories.indices.map(Double.init)
94 } else {
95 x = try Axis(values: series.flatMap { $0.points.map { xValue($0.x) } }, given: given(s.xrange, "xmin", "xmax"), log: s.logX, step: s.xtics, zero: false)
96 }
97
98 let width = 640.0, height = 480.0
99 let left = 60.0 + (s.ylabel == nil ? 0 : 20), right = 620.0
100 let top = 20.0 + (s.title == nil ? 0 : 20), bottom = height - 40 - (s.xlabel == nil ? 0 : 20)
101 func px(_ v: Double) -> Double { left + x.fraction(v) * (right - left) }
102 func py(_ v: Double) -> Double { bottom - y.fraction(v) * (bottom - top) }
103 func xLabel(_ t: Double) -> String {
104 if !categories.isEmpty { return categories[Int(t)] }
105 if dates {
106 let c = calendar.dateComponents([.year, .month, .day], from: Date(timeIntervalSince1970: t))
107 return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
108 }
109 return String(format: "%g", t)
110 }
111
112 var out = """
113 <svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480" font-family="Helvetica, Arial, sans-serif" font-size="12">
114 <rect width="\(Int(width))" height="\(Int(height))" fill="white"/>
115 <clipPath id="plot"><rect x="\(number(left))" y="\(number(top))" width="\(number(right - left))" height="\(number(bottom - top))"/></clipPath>
116
117 """
118 func add(_ line: String) { out += line + "\n" }
119 for t in x.ticks where t >= x.low && t <= x.high {
120 if s.grid { add("<line x1=\"\(number(px(t)))\" y1=\"\(number(top))\" x2=\"\(number(px(t)))\" y2=\"\(number(bottom))\" stroke=\"#a0a0a0\" stroke-dasharray=\"2,3\"/>") }
121 add("<line x1=\"\(number(px(t)))\" y1=\"\(number(bottom))\" x2=\"\(number(px(t)))\" y2=\"\(number(bottom - 6))\" stroke=\"black\"/>")
122 add("<text x=\"\(number(px(t)))\" y=\"\(number(bottom + 16))\" text-anchor=\"middle\">\(escaped(xLabel(t)))</text>")
123 }
124 for t in y.ticks where t >= y.low && t <= y.high {
125 if s.grid { add("<line x1=\"\(number(left))\" y1=\"\(number(py(t)))\" x2=\"\(number(right))\" y2=\"\(number(py(t)))\" stroke=\"#a0a0a0\" stroke-dasharray=\"2,3\"/>") }
126 add("<line x1=\"\(number(left))\" y1=\"\(number(py(t)))\" x2=\"\(number(left + 6))\" y2=\"\(number(py(t)))\" stroke=\"black\"/>")
127 add("<text x=\"\(number(left - 6))\" y=\"\(number(py(t) + 4))\" text-anchor=\"end\">\(escaped(String(format: "%g", t)))</text>")
128 }
129 add("<rect x=\"\(number(left))\" y=\"\(number(top))\" width=\"\(number(right - left))\" height=\"\(number(bottom - top))\" fill=\"none\" stroke=\"black\"/>")
130 if let title = s.title { add("<text x=\"320\" y=\"24\" text-anchor=\"middle\" font-size=\"14\">\(escaped(title))</text>") }
131 if let label = s.xlabel { add("<text x=\"\(number((left + right) / 2))\" y=\"\(number(height - 12))\" text-anchor=\"middle\">\(escaped(label))</text>") }
132 if let label = s.ylabel { add("<text transform=\"translate(16 \(number((top + bottom) / 2))) rotate(-90)\" text-anchor=\"middle\">\(escaped(label))</text>") }
133
134 add("<g clip-path=\"url(#plot)\">")
135 let xs = series.flatMap { $0.points.map { xValue($0.x) } }.sorted()
136 let spacing = categories.isEmpty ? zip(xs, xs.dropFirst()).map { $1 - $0 }.filter { $0 > 0 }.min().map { abs(px(xs[0] + $0) - px(xs[0])) } ?? 40 : (px(1) - px(0))
137 let base = py(y.log ? y.low : min(max(0, y.low), y.high))
138 for (i, s) in series.enumerated() {
139 let color = colors[i % colors.count]
140 let points = s.points.filter { (!y.log || logRange.contains($0.y)) && (!x.log || logRange.contains(xValue($0.x))) }.map { (px(xValue($0.x)), py($0.y)) }
141 guard !points.isEmpty else { continue }
142 func polyline(_ p: [(Double, Double)]) {
143 add("<polyline fill=\"none\" stroke=\"\(color)\" stroke-width=\"1.5\" points=\"" + p.map { "\(number($0.0)),\(number($0.1))" }.joined(separator: " ") + "\"/>")
144 }
145 switch with {
146 case "points", "dots", "linespoints":
147 if with == "linespoints" { polyline(points) }
148 for (px, py) in points { add("<circle cx=\"\(number(px))\" cy=\"\(number(py))\" r=\"\(with == "dots" ? 1 : 3)\" fill=\"none\" stroke=\"\(color)\"/>") }
149 case "impulses":
150 for (px, py) in points { add("<line x1=\"\(number(px))\" y1=\"\(number(base))\" x2=\"\(number(px))\" y2=\"\(number(py))\" stroke=\"\(color)\" stroke-width=\"1.5\"/>") }
151 case "boxes", "histograms", "hist":
152 let group = spacing * 0.8, bar = group / Double(series.count)
153 for (px, py) in points {
154 let x0 = px - group / 2 + bar * Double(i)
155 add("<rect x=\"\(number(x0))\" y=\"\(number(min(py, base)))\" width=\"\(number(bar))\" height=\"\(number(abs(base - py)))\" fill=\"\(color)\" fill-opacity=\"0.8\" stroke=\"\(color)\"/>")
156 }
157 case "steps", "fsteps":
158 var stepped = [points[0]]
159 for p in points.dropFirst() {
160 stepped.append(with == "steps" ? (p.0, stepped.last!.1) : (stepped.last!.0, p.1))
161 stepped.append(p)
162 }
163 polyline(stepped)
164 default:
165 polyline(points)
166 }
167 }
168 add("</g>")
169
170 var showKey = true, vertical = "top", horizontal = "right"
171 switch s.key {
172 case .off: showKey = false
173 case .at(let v, let h): vertical = v ?? vertical; horizontal = h ?? horizontal
174 case nil: break
175 }
176 if showKey {
177 for (i, s) in series.enumerated() {
178 let color = colors[i % colors.count]
179 let row = vertical == "top" ? top + 16 + Double(i) * 16 : bottom - 10 - Double(series.count - 1 - i) * 16
180 let sample = horizontal == "right" ? right - 50 : left + 10
181 let text = horizontal == "right" ? "<text x=\"\(number(sample - 6))\" y=\"\(number(row + 4))\" text-anchor=\"end\">"
182 : "<text x=\"\(number(sample + 46))\" y=\"\(number(row + 4))\">"
183 add(text + escaped(s.label) + "</text>")
184 add("<line x1=\"\(number(sample))\" y1=\"\(number(row))\" x2=\"\(number(sample + 40))\" y2=\"\(number(row))\" stroke=\"\(color)\" stroke-width=\"\(bars ? 8 : 1.5)\"/>")
185 }
186 }
187 return out + "</svg>\n"
188 }
189}