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