Repository Public
1import Foundation2import SheetCore3import SheetCharts4import Statistics5import AnalysisKit67/// Principal component analysis.8enum PCATool {9 static let descriptor: ToolDescriptor = {10 var t = ToolDescriptor(11 id: "multivariate.pca", title: L("Principal Component Analysis"), group: L("Multivariate"), systemImage: "arrow.up.left.and.arrow.down.right",12 summary: L("Finds the orthogonal directions of largest variance: eigenvalues, explained variance, loadings and scores."),13 fields: [14 .range("data", L("Data range")),15 .columns("vars", L("Variables")),16 .toggle("standardize", L("Standardize the variables (correlation matrix)"), true,17 help: L("Recommended when the variables have different units.")),18 .integer("components", L("Components to keep"), 0, min: 0, max: 100, help: L("0 = all components.")),19 ],20 info: [21 L("Computed by singular value decomposition; eigenvalues use the divisor n − 1 (matches scikit-learn PCA to 1e-9)."),22 L("Sign convention: in each component the entry of largest absolute value is positive."),23 L("Loadings are eigenvectors × √eigenvalue; for a correlation PCA they are the correlations between variables and components."),24 ],25 run: run)26 t.demo = { _, v in v.set("data", range: "Prices!A1:F253"); v.set("vars", columns: [1, 2, 3, 4, 5]) }27 return t28 }()2930 static func run(_ input: ToolInput) throws -> ToolResult {31 let m = try Sup.matrix(input, atLeast: 2, standardize: false)32 let standardize = input.values.bool("standardize")33 let requested = input.values.int("components")34 let k = requested > 0 ? min(requested, min(m.names.count, m.rows.count - 1)) : nil35 let r = try PCA.fit(m.data, standardize: standardize, components: k, names: m.names)36 let loc = input.locale37 let count = r.explainedVariance.count38 let labels = (1...count).map { L("PC%d", $0) }39 let cumulative = r.cumulativeVarianceRatio40 var rows: [[Value]] = [[.text(L("Component")), .text(L("Eigenvalue")), .text(L("Share of variance")), .text(L("Cumulative share"))]]41 for i in 0..<count { rows.append([.text(labels[i]), .finite(r.explainedVariance[i]), .finite(r.explainedVarianceRatio[i]), .finite(cumulative[i])]) }42 let variance = ReportTable(title: L("Explained variance"), rows: rows, columnFormats: [1: .fixed(4), 2: .percent(2), 3: .percent(2)])43 let load = r.loadings44 let loadings = ReportTable(title: L("Loadings"), rows: [[.text(L("Variable"))] + labels.map { .text($0) }]45 + r.variableNames.enumerated().map { i, n in [.text(n)] + (0..<count).map { .finite(load[i, $0]) } },46 columnFormats: Dictionary(uniqueKeysWithValues: (1...count).map { ($0, CellFormat.fixed(4)) }))47 let vectors = ReportTable(title: L("Eigenvectors (principal axes)"), rows: [[.text(L("Variable"))] + labels.map { .text($0) }]48 + r.variableNames.enumerated().map { i, n in [.text(n)] + (0..<count).map { .finite(r.components[$0, i]) } },49 columnFormats: Dictionary(uniqueKeysWithValues: (1...count).map { ($0, CellFormat.fixed(4)) }))50 // scree plot: eigenvalue share as columns, cumulative share as a line on the same axis51 var scree = ChartSpec(kind: .combo)52 scree.categories = .labels(labels)53 scree.series = [SeriesSpec(name: L("Share of variance"), values: .literal(r.explainedVarianceRatio), kind: .column),54 SeriesSpec(name: L("Cumulative share"), values: .literal(cumulative), style: SeriesStyle(marker: .circle), kind: .line)]55 scree.xAxis.title = L("Component"); scree.yAxis.title = L("Share of variance"); scree.yAxis.numberFormat = "0%"56 scree.xAxis.gridlines = false57 scree.legend = LegendSpec(position: .top)58 let actionNames = labels.map { L("Score %@", $0) }59 let scoreColumns = (0..<count).map { c in m.frame.expand(r.scores.column(c), rows: m.rows) }60 let blocks: [ResultBlock] = [61 .metrics([Metric(L("Observations"), Double(r.n), .integer), Metric(L("Variables"), Double(r.variableNames.count), .integer),62 Metric(L("PC1 share of variance"), r.explainedVarianceRatio.first ?? .nan, .percent(1)),63 Metric(L("First two components"), cumulative.count > 1 ? cumulative[1] : (cumulative.first ?? .nan), .percent(1))]),64 .chart(ChartBlock(title: L("Scree plot"), spec: scree,65 summary: L("Scree plot of %d components: the first explains %@ of the variance, the first two %@.", count,66 Fmt.percent(r.explainedVarianceRatio.first ?? .nan, 1, locale: loc),67 Fmt.percent(cumulative.count > 1 ? cumulative[1] : (cumulative.first ?? .nan), 1, locale: loc)), height: 240)),68 .table(variance), .table(loadings), .table(vectors),69 .note([Sup.listwiseNote(used: m.rows.count, of: m.frame.rowCount),70 standardize ? L("Variables were centred and divided by their sample standard deviations (correlation PCA).")71 : L("Variables were centred only (covariance PCA): variables with large variances dominate.")]),72 ]73 let action = Sup.writeColumns(id: "write-scores", title: L("Write Scores to Sheet"), label: L("Write PCA Scores"), frame: m.frame, names: actionNames, columns: scoreColumns)74 return ToolResult(title: L("Principal Component Analysis"), subtitle: L("%@ — %d variables", m.frame.label, m.names.count), blocks: blocks, actions: [action], sheetName: "PCA")75 }76}77