Sources/OrgCore/Compute/TablePlotRadar.swift

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