SPB Git

Repository Public

README.md 16.8 KB 225 lines markdown

1# SheetCharts23Charting engine of ORIX Sheet: a pure model + drawing package (Swift 6, macOS 14+). It depends on `SheetCore`,4CoreGraphics, CoreText, ImageIO and UniformTypeIdentifiers — no SwiftUI/AppKit, no third-party code — so it runs5headless and is fully testable.67Design rule: **every mark derives from data**. Nothing decorative is drawn; a value that cannot be represented8(missing, non-positive on a log axis, negative in a pie) is left out and never replaced by zero.910```swift11var spec = ChartSpec(kind: .column, title: "Sales")12spec.categories = .range(sheet: "Data", range: RangeRef(a1: "A2:A13")!)13spec.series = [SeriesSpec(nameRef: .range(sheet: "Data", range: RangeRef(a1: "B1")!),14                          values: .range(sheet: "Data", range: RangeRef(a1: "B2:B13")!))]15let source = WorkbookDataSource(workbook: workbook)16let pdf = ChartRenderer.pdfData(spec, source: source, size: CGSize(width: 480, height: 300))17sheet.meta.objects.append(try spec.sheetObject(x: 40, y: 40, width: 480, height: 300))   // kind "chart"18```1920## Layout of the package2122| Directory | Content |23|---|---|24| `Model/` | `ChartSpec`, `SeriesSpec`, `AxisSpec`, `LegendSpec`, `Annotation`, `ChartOptions`, `ChartTheme`, JSON coding |25| `Data/` | `ChartDataSource`, `WorkbookDataSource`, `LiteralDataSource`, `ChartData` (resolved numbers) |26| `Stats/` | quantiles, box statistics, binning, KDE, stacking, regression, marching squares, treemap, decimation, colour maps |27| `Scales/` | tick generation (linear, log, calendar), `AxisScaleMap`, built-in axis formatter |28| `Canvas/` | `ChartCanvas` protocol, `CGChartCanvas`, `SVGChartCanvas`, CoreText measurement |29| `Render/` | scene builder, frame (title / legend), Cartesian layout and axes, `ChartLayout`, `ChartRenderer` |30| `Marks/` | one file per family of marks (XY, bars, distributions, grids, pie, radar/treemap, surface, decorations) |31| `Figure/` | ORIX Figure Studio: `FigureSpec`, `FigureTemplates`, `FigureRenderer` |32| `Suggest/` | `ChartSuggest` (default charts for a selection) |33| `Samples/` | deterministic synthetic sample charts (gallery, previews, tests) |3435`chart-gallery <dir>` (executable target) writes a PNG (2x), SVG and PDF per chart kind, dark PNGs, option36variants and multi-panel figures, and prints timings.3738## Spec model3940`ChartSpec` is `Codable`, `Sendable`, `Hashable`, versioned (`schema`, currently 1). `encoded()` /41`ChartSpec.decoded(from:)` give the `SheetObject` payload. Decoding is **tolerant**: the stored JSON is overlaid on42the defaults of the current model, so payloads that lack keys (older schema, hand-written JSON) still load.43`FigureSpec` works the same way (`SheetObject.kind == "figure"`).4445* `kind` — 21 kinds: line, bar (horizontal), column, area, scatter, bubble, histogram, boxPlot, violin, heatmap,46  waterfall, candlestick, pie, donut, radar, treemap, surface3D, contour, density, timeSeries, combo.47* `series[]` — `name` / `nameRef`, and the references used by the kind: `values`, `x`, `size`, `open/high/low/close`,48  `lower/upper` (confidence band), per-series `categories`; `style` (colour, line width, dash, marker, fill49  opacity); `axis` (primary / secondary); `kind` (mark override in a combo chart: line, column, area, scatter);50  `trendline`; `errorBars`; `showDataLabels`.51* `DataRef` — `.range(sheet:range:)` (sheet addressed by **name**), `.literal([Double])`, `.labels([String])`.52* `categories`, `rowLabels` — band labels, pie / treemap labels, radar spokes, matrix column / row coordinates.53* `xAxis`, `yAxis`, `y2Axis` — title, unit, min / max, major step, minor ticks, scale (linear, log10, log2, date),54  number-format code, gridlines, reversed, label rotation, `includeZero`. `xAxis` is always the independent axis:55  for horizontal bars it is the one drawn on the left.56* `legend`, `annotations` (text, arrow, reference line, band — in data coordinates), `theme`, `options`.5758What each kind reads:5960| Kind | Data |61|---|---|62| line, area, column, bar, combo, radar | `categories` + `series[].values` |63| scatter, timeSeries | `series[].x` + `values` (x falls back to numeric categories, then 1, 2, 3…) |64| bubble | `x`, `values`, `size` |65| histogram, density, boxPlot, violin | each series' `values` is one sample |66| pie, donut, treemap, waterfall | first series + `categories` |67| candlestick | first series' `open/high/low/close` + `categories`; further series with `values` are line overlays |68| heatmap, contour, surface3D | one series whose `values` is a 2-D range, or one series per matrix row; `categories` / `rowLabels` are the column / row labels (numeric, strictly monotonic labels become coordinates for contour and surface) |6970A line or area chart uses a category axis unless a series has `x` or `xAxis.scale` is log / date.7172## Data resolution and the missing-value rule7374`ChartData.resolve(spec, source:)` turns references into numbers through a `ChartDataSource`.75`WorkbookDataSource(workbook:)` reads **computed** values, clips open-ended references (`A:A`) to the stored76extent, and takes an optional `synchronize` closure (or a `lock` / `unlock` pair) because `Workbook` is not77thread-safe.7879> **Only numeric cells holding a finite number are data.** Blank cells, text (including text that looks like a80> number), booleans, error values and NaN / ±∞ are *missing*. Missing values are never plotted as zero:81> line-type marks break (unless `options.connectGaps`), bar-type marks leave the slot empty, stacks do not move,82> statistics exclude the value. `ChartData.skippedCells` counts the non-blank cells that were skipped.8384Further rules: values ≤ 0 are skipped on log axes; pie / donut / treemap draw strictly positive values only85(`ChartLayout.notes` reports dropped negatives); a candle needs all four prices; bubbles need a size > 0. When a86chart has nothing to draw it shows a short note ("No numeric data") instead of an empty frame.8788## Statistical conventions8990| Topic | Convention | Reference used in tests |91|---|---|---|92| Linear ticks | steps 1-2-5 × 10^k, at least two ticks inside the range, automatic ends extended to the enclosing ticks (a bound passing a tick by < 15 % of a step does not add an interval) | `matplotlib.ticker.MaxNLocator(steps=[1,2,5,10])` |93| Log ticks | integer powers of the base, regular stride when crowded, 2…9 minors; 1-2-5 multiples under one decade | numpy |94| Calendar ticks | seconds → years from serial dates through `DateSerial` (1900 and 1904 systems); months and years on the first day, weeks on Mondays | Python `datetime` |95| Histogram bins | `auto`, `freedmanDiaconis`, `sturges`, `scott`, `fixedCount`, `fixedWidth`; bins are `[a, b)` with the last one closed; `auto` = min(max(FD, range / 2√n), Sturges); at most 2000 bins | `numpy.histogram_bin_edges` / `numpy.histogram` (2.4) |96| Normalisation | count, density (count / (n · width)), probability | numpy `density=True` |97| Quartiles | Hyndman–Fan type 7 `inclusive` (default; Excel `QUARTILE.INC`), type 6 `exclusive`, type 2 `averaged`, type 8 `medianUnbiased` | `numpy.quantile` methods linear, weibull, averaged_inverted_cdf, median_unbiased |98| Box plot | box Q1–Q3, median line, whiskers to the most extreme observation within 1.5 · IQR (Tukey) or to min / max, the rest are outliers; optional mean | `matplotlib.cbook.boxplot_stats` |99| KDE (violin, density) | Gaussian kernel; bandwidth `silverman` = 0.9 · min(s, IQR / 1.34) · n^(−1/5) (default), `scott` = s · n^(−1/5), or fixed; s is the sample standard deviation. No estimate (nothing drawn) for n < 2 or zero spread. Density curves extend 3 bandwidths beyond the data; violins are trimmed to the data range and all scaled to the same maximum width | `scipy.stats.gaussian_kde` |100| Stacking | positive values stack upward from zero, negative values downward; 100 % mode divides by the sum of absolute values of the category | numpy cumulative sums |101| Trendlines | least squares: linear, polynomial (degree ≤ 8, solved by Householder QR on centred / scaled x), exponential (ln y on x, y > 0), logarithmic (y on ln x, x > 0), power (ln y on ln x), trailing moving average. R² is computed in the space of the fit (Excel's convention). On category axes x = 1, 2, 3… | `numpy.polyfit` |102| Error bars | fixed, percent of the value, k · sample standard deviation of the series, k · standard error (s / √n), custom ranges | closed forms |103| Contours | marching squares on grid nodes (inside = value ≥ level, saddles resolved by the cell mean), segments joined into polylines; filled bands are exact polygon clips of the same piecewise-linear surface | matplotlib / contourpy iso-line lengths, analytic circle |104| Treemap | squarified (Bruls, Huizing & van Wijk); areas exactly proportional to values | property tests |105| Bubbles | **area** proportional to size (diameter ∝ √size) | closed form |106| Waterfall | values are deltas; indices in `waterfallTotals` show the running sum from zero (index 0 as a total is the opening balance) | closed form |107| Colour maps | viridis, magma, plasma, inferno, cividis, RdBu, coolwarm, BrBG, Blues, Greys — 65 anchors each, linearly interpolated; diverging maps are centred on zero unless bounds are given | matplotlib (within 4 / 255) |108| 3D surface | **static orthographic projection** (azimuth, elevation), quads painted far-to-near by mean depth; no perspective, lighting or interaction | — |109110Reference numbers are generated by `Tests/SheetChartsTests/Generators/gen_fixtures.py` and `gen_colormaps.py`111(`/opt/homebrew/bin/python3`, numpy 2.4.4, scipy 1.17.1, matplotlib) into `Tests/SheetChartsTests/Fixtures/`.112113## Decimation114115* **Lines** longer than 2000 points are reduced per horizontal bucket of 0.5 pt to at most four points — first,116  lowest, highest, last, in order (`Decimation.minMaxIndices`). Every bucket keeps its exact vertical extent, so the117  drawn envelope is unchanged while the path is bounded by the plot width. Disable with118  `options.decimation = false`; smoothed and area series are not decimated.119* **Scatter** series above 20 000 opaque markers skip a marker that falls on an already occupied 0.5 pt cell120  (identical markers on top of each other are indistinguishable). Markers are emitted in chunks of 64 per path.121* Hit-test data always contains every point.122123Measured on this machine (release build, 640 × 400 pt, best of three; resolve + layout + draw + encode):124125| 100 000 points | PNG 2x | PDF | SVG |126|---|---|---|---|127| line (decimated) | 40–45 ms | 8–9 ms | 5–6 ms |128| line, decimation off | 1.4–1.7 s | — | — |129| scatter | 0.26–0.57 s | 0.29–0.85 s | 0.10–0.18 s |130131(Two runs; the machine was shared with other builds, hence the ranges.)132133## Drawing, layout and interaction134135`ChartRenderer.scene(spec, data:size:measure:viewport:formatter:)` builds a `ChartScene`: a `ChartLayout` plus a136display list. `scene.draw(in:)` replays it into any `ChartCanvas`; `ChartRenderer.draw / pngData / pdfData /137svgString` are conveniences. Cache the scene and replay it for redraws.138139`ChartLayout` exposes the plot rectangle, axis scales and ticks (with label frames), legend entries, colour-bar140frame, every text frame, and hit-test data:141142* `hitTest(point)` → the mark under the point, else the nearest anchor within a distance;143  `items(alignedWith:)` → all series at the nearest x (shared tooltip); `item(series:point:)`;144* `dataPoint(at:)` and `position(x:y:axis:)` convert between canvas and data coordinates;145* `viewport` + `ChartViewport.zoomed(by:aroundX:y:)` / `panned(dx:dy:)` → pass the result back as `viewport:` to146  zoom and pan (category axes use the category index as coordinate).147148Number formatting: axes and labels use a small built-in formatter (automatic decimals from the tick step,149thousands separators from 10 000, `×10ⁿ` beyond 10⁹ / below 10⁻⁴, and a subset of format codes: `0.00`, `#,##0`,150`0%`, `0.00E+00`, literal prefix / suffix, date-time tokens). Pass a `ChartValueFormatter` closure151(`(value, formatCode) -> String?`) to delegate format codes to SheetFormat.152153Themes: `ChartTheme.presets` — Light, Dark, Okabe–Ito (colour-blind-safe) and its dark variant, Publication,154Minimal, Financial, Presentation (light / dark), Monochrome. `theme.variant(dark:)` switches surfaces and palette.155`ChartPalette` also carries Tol "bright" and Tableau 10.156157Concurrency: scenes can be built on any thread. Font matching goes through a process-wide, locked cache158(`FontCache`), because concurrent first-time font lookups from many threads can stall in the system font159service.160161## Export formats162163| Format | API | Notes |164|---|---|---|165| PNG | `pngData(…scale:)` | sRGB, `scale` pixels per point, DPI metadata |166| PDF | `pdfData` | single page, vector; text is text. Only heatmaps above 4096 cells embed a raster (one pixel per cell) |167| SVG | `svgString` | standalone SVG 1.1, real `<text>` elements, groups named `series-N`, `grid`, `axes`, `legend`… Fonts are referenced by family name, not embedded |168169Coordinates are points with the origin at the top-left. `CGChartCanvas(context:height:flipped:)` draws into any170`CGContext` (views, printing).171172## Figure Studio173174`FigureSpec` places `FigurePanel`s (a `ChartSpec` + row / column / spans + label) on a `rows × cols` grid of a175figure sized in points (`widthMM` / `heightMM` convert). One `FigureTypography` (family + base size, from which176the whole size ladder derives) and one `ChartTheme` are applied to every panel; panel titles move to a header line177next to the panel label ("(a)", "A"…). `shareX` / `shareY` unify the automatic domains of continuous axes per178column / row and keep the axis title on the outer panels only. `FigureRenderer` offers `scene`, `draw`, `pngData`,179`pdfData`, `svgString`, `exportData` (format of the `exportPreset`).180181`FigureTemplates.all`: Academic paper single column (89 mm) and double column (183 mm), Scientific publication182(174 mm, serif), Financial report (170 mm), Business presentation (16:9), Dashboard. **Templates are size, grid and183typography presets only. They do not claim compliance with the requirements of any journal or publisher.**184185## Suggestions186187`ChartSuggest.suggest(for:in:)` trims the selection to its content, detects a header row (text over numbers) and a188category column (text, date-formatted numbers, years or 1, 2, 3…), then proposes charts best-first: time series for189dates, column / bar / pie for one measure, grouped and stacked columns for several, histogram / box plot / density190for a single long numeric column, scatter / bubble for two / three numeric columns, heatmap / contour / surface for191a bare numeric matrix, candlestick for Open / High / Low / Close headers, series-in-rows for wide tables.192`ChartSuggest.analyze` returns what was detected.193194## Known limitations195196* The 3D surface is a static projection; the painter's algorithm can mis-order quads on steep, self-occluding197  surfaces, and its hit test returns the smallest containing quad.198* Contour charts have no in-line level labels (levels are read on the colour bar). Heatmap / contour colour bars199  have no title.200* A legend for bubble sizes is not drawn. One legend per chart; long legends are truncated to the available space.201* Markers of one series are filled as compound paths: with `fillOpacity < 1` overlapping markers of the same202  series do not darken each other.203* Automatic tick labels are English / invariant ("Jan", "," grouping, "." decimals). Localised output needs the204  `ChartValueFormatter` and explicit format codes.205* Text is single-line, left-to-right; long labels are truncated with an ellipsis. No rich text or line wrapping.206* SVG and PDF reference fonts by family; a viewer without the font substitutes it.207* Ranges are addressed by sheet **name** and are not adjusted automatically by structural edits: after a sheet208  rename or an insertion / deletion of rows or columns the owner of the `SheetObject` must call209  `ChartSpec.mapRanges` (and `FigureSpec.mapRanges`). `referencedRanges` lists the dependencies.210* Histograms of several series share the bin edges of the pooled data and are overlaid, not dodged or stacked.211* Stacking applies to columns, bars, areas and category-axis lines; not to continuous-x series.212* Error-bar kind `stddev` draws ± k·s around each point (not around the series mean as Excel does).213* `shareX` / `shareY` unify domains only; panels keep their own tick labels.214215## Tests216217`swift test` — 43 test functions (three of them parameterised over the 21 kinds):218numeric algorithms against the Python references; every kind × {normal, empty, single point, all blank, negative,2191e-12…1e12, dirty (errors / text / NaN / booleans)} rendered to SVG (parsed with `XMLParser`), PDF and PNG; every220kind in every theme and at extreme sizes; scales × stacking × decorations on difficult data; structural checks221(marks per datum, positions through the axis scale within 0.5 pt, stack sums, bin geometry, wedge angles, bubble222areas); no clipped or overlapping text on the gallery charts at three sizes; vector-PDF heuristics (fonts present,223no image XObject except dense heatmaps); JSON round trips and tolerant decoding; data-source rules; suggestions;224figures.225
Files main
Menu

Theme