Sources/OrgCore/Compute/TablePlotRadar.swift
228 lines · 11647 bytes
1import Foundation
2
3/// `type:radar` (`org--plot/radar`, Org 9.8.7): each row is an axis with its own scale, each
4/// column after the first a series.
5extension TablePlot {
6 public struct Radar: Sendable, Equatable {
7 public struct Axis: Sendable, Equatable {
8 public var label: String
9 public var fields: [String]
10 public var values: [Double]
11 public var low: Double
12 public var high: Double
13 /// `low` and `high` as `format "%s"` prints them.
14 var lowText: String
15 var highText: String
16 }
17 public var axes: [Axis]
18 /// The header's names after the first, one per series.
19 public var series: [String]
20 /// The web's rings; 0 draws none.
21 public var ticks: Int
22 /// With both `ymin` and `ymax`, every axis is labelled with the first axis's values.
23 public var sharedTicks: Bool
24 }
25
26 /// A number as `string-to-number` reads it, and whether it's an integer.
27 static func lispNumber(_ s: String) -> (value: Double, integer: Bool) {
28 let trimmed = s.drop { $0 == " " || $0 == "\t" }
29 guard let m = trimmed.firstMatch(of: /^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?/) else { return (0, true) }
30 let text = String(m.0)
31 return (Double(text) ?? 0, text.firstMatch(of: /\.[0-9]|[eE]/) == nil)
32 }
33
34 static func printed(_ n: (value: Double, integer: Bool)) -> String {
35 n.integer ? String(Int(n.value)) : Elisp.floatText(n.value)
36 }
37
38 /// `org--plot/values-stats`.
39 static func stats(_ nums: [(value: Double, integer: Bool)], hardMin: Double? = nil, hardMax: Double? = nil)
40 -> (factor: Double, niceMin: (value: Double, integer: Bool), niceMax: (value: Double, integer: Bool)) {
41 let low = hardMin ?? nums.map(\.value).min()!, high = hardMax ?? nums.map(\.value).max()!
42 let range = high - low
43 guard range != 0 else { return (1, nums[0], nums[0]) }
44 let order = (1 - log10(range)).rounded(.up)
45 let factor = pow(10, order)
46 return (factor, ((low * factor).rounded(.down) / factor, false), ((high * factor).rounded(.up) / factor, false))
47 }
48
49 /// `org--plot/sensible-tick-num`, or nil where Emacs signals an error or never returns.
50 static func sensibleTicks(_ rows: [[String]], hardMin: Double?, hardMax: Double?) -> Int? {
51 var decompositions: [[(Int, Double)]] = []
52 for row in rows {
53 let s = stats(row.dropFirst().map(lispNumber), hardMin: hardMin, hardMax: hardMax)
54 var value = Int((s.factor * (s.niceMax.value - s.niceMin.value)).rounded(.toNearestOrEven))
55 if value % 10 == 0 { value /= 10 }
56 // `org--plot/prime-factors` loops forever on 0.
57 guard value > 0 else { return nil }
58 var factors: [Int] = [], i = 1
59 while value != 1 {
60 i += 1
61 if value % i == 0 { factors.insert(i, at: 0); value /= i; i -= 1 }
62 }
63 // `org--plot/item-frequencies`, keys in `seq-group-by`'s order.
64 var groups: [(Int, Int)] = []
65 for f in factors.reversed() {
66 if let at = groups.firstIndex(where: { $0.0 == f }) { groups[at].1 += 1 } else { groups.insert((f, 1), at: 0) }
67 }
68 decompositions.append(groups.map { ($0.0, Double($0.1) / Double(factors.count)) })
69 }
70 // `org--plot/merge-alists` needs two lists.
71 func merge(_ lists: ArraySlice<[(Int, Double)]>) -> [(Int, Double)] {
72 let a1 = lists.first!
73 let a2 = lists.count > 2 ? merge(lists.dropFirst()) : lists[lists.startIndex + 1]
74 // `cl-union` with :test: the longer list, the shorter's new keys pushed on its front.
75 var (keys, other) = (a1.map(\.0), a2.map(\.0))
76 if !keys.isEmpty, !other.isEmpty {
77 if keys.count < other.count { swap(&keys, &other) }
78 for k in other where !keys.contains(k) { keys.insert(k, at: 0) }
79 } else if keys.isEmpty {
80 keys = other
81 }
82 func lookup(_ k: Int, _ list: [(Int, Double)]) -> Double { list.first { $0.0 == k }?.1 ?? 0 }
83 return keys.map { ($0, lookup($0, a1) + lookup($0, a2)) }
84 }
85 guard decompositions.count >= 2 else { return nil }
86 let weighted = merge(decompositions[...]).enumerated().sorted { $0.element.1 != $1.element.1 ? $0.element.1 > $1.element.1 : $0.offset < $1.offset }.map(\.element)
87 // `org--plot/nice-frequency-pick`.
88 var pick: [Int]
89 switch weighted.count {
90 case 0: return nil
91 case 1: pick = [weighted[0].0]
92 case 2: pick = 3 <= weighted[0].1 / weighted[1].1 ? [weighted[0].0, weighted[0].0] : [weighted[0].0, weighted[1].0]
93 default:
94 let total = weighted.map(\.1).reduce(0, +)
95 let n = weighted.map { ($0.0, $0.1 / total) }
96 pick = [n[0].0]
97 let r12 = n[0].1 / n[1].1, r23 = n[1].1 / n[2].1, r13 = r12 * r23
98 if r12 > 4 { pick.insert(n[0].0, at: 0) }
99 if r12 < Double(n[1].0), pick.reduce(1, *) * n[1].0 < 30 { pick.insert(n[1].0, at: 0) }
100 if r13 < Double(n[2].0), pick.reduce(1, *) * n[2].0 < 30 { pick.insert(n[2].0, at: 0) }
101 }
102 return pick.reduce(1, *)
103 }
104
105 /// The radar plot's axes, series and ticks, as `org--plot/radar` works them out.
106 public static func radar(_ plot: Plot) throws -> Radar {
107 let rows = plot.rows.compactMap { $0 }
108 guard !rows.isEmpty, rows.allSatisfy({ $0.count > 1 }) else {
109 throw Failure(description: "A radar plot needs a name and a value in each row")
110 }
111 func number(_ key: String) throws -> Double? {
112 guard let v = plot.options[key] else { return nil }
113 guard case .number(let n) = v else { throw Failure(description: "\(key): must be a number") }
114 return n
115 }
116 let ymin = try number("ymin"), ymax = try number("ymax")
117 let ticks: Int
118 if let given = try number("ticks") {
119 ticks = Int(given)
120 } else if let sensible = sensibleTicks(rows, hardMin: ymin, hardMax: ymax) {
121 ticks = sensible
122 } else {
123 throw Failure(description: "Org can't choose this radar plot's ticks; give ticks:")
124 }
125 let axes = rows.map { row -> Radar.Axis in
126 let nums = row.dropFirst().map(lispNumber)
127 let s = stats(nums)
128 return Radar.Axis(label: row[0], fields: Array(row.dropFirst()), values: nums.map(\.value),
129 low: ymin ?? s.niceMin.value, high: ymax ?? s.niceMax.value,
130 lowText: plot.options["ymin"]?.description ?? printed(s.niceMin),
131 highText: plot.options["ymax"]?.description ?? printed(s.niceMax))
132 }
133 return Radar(axes: axes, series: Array((plot.options.labels ?? []).dropFirst()), ticks: ticks, sharedTicks: ymin != nil && ymax != nil)
134 }
135
136 /// The setup file `org--plot/radar` writes: the data and each axis's scale.
137 public static func radarSetup(_ plot: Plot) throws -> String {
138 let radar = try radar(plot)
139 let axes = radar.axes + radar.axes.prefix(1)
140 let data = "\"" + (plot.options.labels ?? []).joined(separator: "\" \"") + "\"\n"
141 + axes.map { "\"\($0.label)\" " + $0.fields.joined(separator: " ") }.joined(separator: "\n")
142 let settings = axes.map { "\"\($0.label)\" \($0.lowText) \($0.highText) \(radar.ticks == 0 ? 2 : radar.ticks)" }.joined(separator: "\n")
143 return "# Data\n$Data <<HEREHAVESOMEDATA\n\(data)\nHEREHAVESOMEDATA\nHeaderLines = 1\n\n"
144 + "# Settings for scale and offset adjustments\n# axis min max tics axisLabelXoff axisLabelYoff\n$Settings <<EOD\n\(settings)\nEOD\n"
145 }
146
147 /// `org--plot/radar-template` filled in.
148 static func radarScript(_ radar: Radar, setupFile: String) -> String {
149 let axis = radar.sharedTicks ? "1" : "$1"
150 let ticks = radar.ticks == 0 ? "" : """
151 '++' u (PosX($1,$2/TicCount)):(PosY($1,$2/TicCount)): \\
152 \t(PosX($1+1,$2/TicCount)-PosX($1,$2/TicCount)): \\
153 \t(PosY($1+1,$2/TicCount)-PosY($1,$2/TicCount)) w vec as 2 not, \\
154 '++' u (TicLabelPosX(\(axis),$2)):(TicLabelPosY(\(axis),$2)): \\
155 \t(sprintf('%g',TicValue(\(axis),$2))) w labels font ',8' @fgat not
156 """
157 return """
158 ### spider plot/chart with gnuplot
159 # also known as: radar chart, web chart, star chart, cobweb chart,
160 # radar plot, web plot, star plot, cobweb plot, etc. ...
161 set datafile separator ' '
162 set size square
163 unset tics
164 set angles degree
165 set key bmargin center horizontal
166 unset border
167
168 # Load data and setup
169 load "\(setupFile)"
170
171 # General settings
172 DataColCount = words($Data[1])-1
173 AxesCount = |$Data|-HeaderLines-1
174 AngleOffset = 90
175 Max = 1
176 d=0.1*Max
177 Direction = -1 # counterclockwise=1, clockwise = -1
178
179 # Tic settings
180 TicCount = \(radar.ticks == 0 ? 2 : radar.ticks)
181 TicOffset = 0.1
182 TicValue(axis,i) = real(i)*(word($Settings[axis],3)-word($Settings[axis],2)) \\
183 \t / word($Settings[axis],4)+word($Settings[axis],2)
184 TicLabelPosX(axis,i) = PosX(axis,i/TicCount) + PosY(axis, TicOffset)
185 TicLabelPosY(axis,i) = PosY(axis,i/TicCount) - PosX(axis, TicOffset)
186 TicLen = 0.03
187 TicdX(axis,i) = 0.5*TicLen*cos(alpha(axis)-90)
188 TicdY(axis,i) = 0.5*TicLen*sin(alpha(axis)-90)
189
190 # Label
191 LabOffset = 0.10
192 LabX(axis) = PosX(axis+1,Max+2*d) + PosY(axis, LabOffset)
193 LabY(axis) = PosY($0+1,Max+2*d)
194
195 # Functions
196 alpha(axis) = (axis-1)*Direction*360.0/AxesCount+AngleOffset
197 PosX(axis,R) = R*cos(alpha(axis))
198 PosY(axis,R) = R*sin(alpha(axis))
199 Scale(axis,value) = real(value-word($Settings[axis],2))/(word($Settings[axis],3)-word($Settings[axis],2))
200
201 # Spider settings
202 set style arrow 1 dt 1 lw 1.0 @fgal head filled size 0.06,25 # style for axes
203 set style arrow 2 dt 2 lw 0.5 @fgal nohead # style for weblines
204 set style arrow 3 dt 1 lw 1 @fgal nohead # style for axis tics
205 set samples AxesCount
206 set isosamples TicCount
207 set urange[1:AxesCount]
208 set vrange[1:TicCount]
209 set style fill transparent solid 0.2
210
211 set xrange[-Max-4*d:Max+4*d]
212 set yrange[-Max-4*d:Max+4*d]
213 plot \\
214 '+' u (0):(0):(PosX($0,Max+d)):(PosY($0,Max+d)) w vec as 1 not, \\
215 $Data u (LabX($0)): \\
216 \t(LabY($0)):1 every ::HeaderLines w labels center enhanced @fgt not, \\
217 for [i=1:DataColCount] $Data u (PosX($0+1,Scale($0+1,column(i+1)))): \\
218 \t(PosY($0+1,Scale($0+1,column(i+1)))) every ::HeaderLines w filledcurves lt i title word($Data[1],i+1), \\
219 \(ticks)
220 # '++' u (PosX($1,$2/TicCount)-TicdX($1,$2/TicCount)): \\
221 # (PosY($1,$2/TicCount)-TicdY($1,$2/TicCount)): \\
222 # (2*TicdX($1,$2/TicCount)):(2*TicdY($1,$2/TicCount)) \\
223 # w vec as 3 not, \\
224 ### end of code
225
226 """
227 }
228}