Sources/OrgCore/Compute/TablePlotRadar.swift

525225e4f44b53a1ea7559b03462473575dfa523
orgstar/Sources/OrgCore/Compute/TablePlotRadar.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form